diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index cba972b..858802a 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -30,7 +30,7 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/ab.rs b/crates/victory-gpu/src/ab.rs new file mode 100644 index 0000000..56922e4 --- /dev/null +++ b/crates/victory-gpu/src/ab.rs @@ -0,0 +1,131 @@ +//! Diagnostics: switches that change while the title runs, so that one run +//! measures both sides in the same scene. `VICTORY_AB=,[,..]`: +//! every so many seconds, at a present, the next phase begins; switch number +//! n is on in the phases whose number has bit n, so that all combinations +//! come one after another, again and again. Each phase's frame times are +//! logged at its end (the frames of its first second left out). A switch +//! named here does not go by its own variable any more. + +use std::sync::atomic::{AtomicU32, Ordering::Relaxed}; +use std::sync::{Mutex, OnceLock}; + +struct Asked { + seconds: f64, + switches: Vec, +} + +fn parse(text: &str) -> Option { + let mut parts = text.split(',').map(str::trim); + let seconds = parts.next()?.parse::().ok().filter(|s| *s > 1.0)?; + let switches: Vec = parts.filter(|s| !s.is_empty()).map(str::to_string).collect(); + (!switches.is_empty() && switches.len() <= 8).then_some(Asked { seconds, switches }) +} + +fn asked() -> Option<&'static Asked> { + static ASKED: OnceLock> = OnceLock::new(); + ASKED.get_or_init(|| parse(&std::env::var("VICTORY_AB").ok()?)).as_ref() +} + +/// The switches that are on now, a bit each. +static BITS: AtomicU32 = AtomicU32::new(0); + +/// Whether `switch` is on now, if it is one of those that change. +pub(crate) fn pick(switch: &str) -> Option { + bit(switch).map(on) +} + +/// The number of `switch` among those that change. +pub(crate) fn bit(switch: &str) -> Option { + Some(asked()?.switches.iter().position(|s| s == switch)? as u32) +} + +/// Whether the switch of that number is on now. +pub(crate) fn on(bit: u32) -> bool { + BITS.load(Relaxed) >> bit & 1 != 0 +} + +/// What the run has seen of the phase under way. +struct Phase { + started: std::time::Instant, + number: u64, + began: std::time::Instant, + last: std::time::Instant, + drawn: u64, + frames: Vec, + draws: u64, +} + +/// The frames' mean, median and nine tenths. +fn summary(frames: &mut [f32]) -> (f32, f32, f32) { + if frames.is_empty() { + return (0.0, 0.0, 0.0); + } + let mean = frames.iter().sum::() / frames.len() as f32; + frames.sort_by(f32::total_cmp); + (mean, frames[frames.len() / 2], frames[frames.len() * 9 / 10]) +} + +/// The title's present ends on this thread. `change`: called when another +/// phase begins, before any switch changes, with what `switch` is and what it +/// will be. +pub(crate) fn presented(change: impl Fn(&str, bool, bool)) { + let Some(asked) = asked() else { + return; + }; + static PHASE: Mutex> = Mutex::new(None); + let now = std::time::Instant::now(); + let drawn = crate::draw::drawn(); + let mut phase = PHASE.lock().unwrap_or_else(|e| e.into_inner()); + let p = phase.get_or_insert_with(|| Phase { + started: now, + number: 0, + began: now, + last: now, + drawn, + frames: Vec::new(), + draws: 0, + }); + if (now - p.began).as_secs_f64() > 1.0 { + p.frames.push((now - p.last).as_secs_f32() * 1000.0); + p.draws += drawn.saturating_sub(p.drawn); + } + (p.last, p.drawn) = (now, drawn); + let number = ((now - p.started).as_secs_f64() / asked.seconds) as u64; + if number == p.number { + return; + } + let bits = |number: u64| (number % (1 << asked.switches.len())) as u32; + let (was, will) = (bits(p.number), bits(number)); + let (mean, median, most) = summary(&mut p.frames); + let on: Vec<&str> = asked.switches.iter().enumerate().filter(|(n, _)| was >> n & 1 != 0).map(|(_, s)| s.as_str()).collect(); + tracing::info!( + "A/B phase {} bits {was} on [{}]: {} frames, mean {mean:.1} ms, median {median:.1}, p90 {most:.1}, {:.0} draws a frame", + p.number, + on.join(" "), + p.frames.len(), + p.draws as f64 / p.frames.len().max(1) as f64 + ); + for (n, switch) in asked.switches.iter().enumerate() { + change(switch, was >> n & 1 != 0, will >> n & 1 != 0); + } + BITS.store(will, Relaxed); + (p.number, p.began, p.draws) = (number, now, 0); + p.frames.clear(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn switches_and_seconds_are_read_and_frames_summed_up() { + let a = parse("10, VICTORY_A,VICTORY_B").unwrap(); + assert_eq!((a.seconds, a.switches), (10.0, vec!["VICTORY_A".to_string(), "VICTORY_B".to_string()])); + assert!(parse("10").is_none()); + assert!(parse("x,VICTORY_A").is_none()); + assert!(parse("0,VICTORY_A").is_none()); + assert_eq!(summary(&mut [30.0, 10.0, 20.0]), (20.0, 20.0, 30.0)); + assert_eq!(summary(&mut []), (0.0, 0.0, 0.0)); + assert_eq!(pick("VICTORY_NONE_SUCH"), None); + } +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index c43d1af..484c90a 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -131,10 +131,39 @@ pub(crate) enum C { IndirectBounded, } const COUNTERS: usize = 80; -static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; +/// One of some sets of counters, each in lines of the processor's memory of +/// its own: a set for all threads had them wait for each other's lines at +/// every list call (what counts here is summed up for the log alone). +#[repr(align(64))] +struct Bank([AtomicU64; N]); + +/// The sets. +const BANKS: usize = 32; + +static COUNT: [Bank; BANKS] = [const { Bank([const { AtomicU64::new(0) }; COUNTERS]) }; BANKS]; + +/// This thread's set. +#[inline] +fn bank() -> usize { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + thread_local!(static MINE: std::cell::Cell = const { std::cell::Cell::new(usize::MAX) }); + // (Asked by the allocator too: nothing here allocates.) + MINE.try_with(|mine| { + if mine.get() == usize::MAX { + mine.set(NEXT.fetch_add(1, Relaxed) % BANKS); + } + mine.get() + }) + .unwrap_or(0) +} pub(crate) fn add(c: C, n: u64) { - COUNT[c as usize].fetch_add(n, Relaxed); + COUNT[bank()].0[c as usize].fetch_add(n, Relaxed); +} + +/// Counter `i`, all sets together, from now on 0. +fn taken(i: usize) -> u64 { + COUNT.iter().map(|b| b.0[i].swap(0, Relaxed)).sum() } /// How copies run: 0 guarded (as always), 1 plain, 2 not at all. @@ -277,7 +306,13 @@ pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { /// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by /// some 2 MB a frame, and nothing said whose): this says which part is /// ours. Bigger blocks are allocations of their own in the map. -static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +static OWN: [Bank<8>; BANKS] = [const { Bank([const { AtomicU64::new(0) }; 8]) }; BANKS]; + +/// Count `i` of [`OWN`], all sets together (a block made by one thread and +/// released by another leaves one set below zero: the sum is right). +fn owned(i: usize) -> u64 { + OWN.iter().fold(0u64, |sum, b| sum.wrapping_add(b.0[i].load(Relaxed))) +} /// The class of [`OWN`] a block of `size` bytes counts in. fn block_class(size: usize) -> usize { @@ -291,12 +326,13 @@ fn block_class(size: usize) -> usize { fn own(size: usize, made: bool) { let class = block_class(size); + let own = &OWN[bank()].0; if made { - OWN[class].fetch_add(size as u64, Relaxed); - OWN[4 + class].fetch_add(1, Relaxed); + own[class].fetch_add(size as u64, Relaxed); + own[4 + class].fetch_add(1, Relaxed); } else { - OWN[class].fetch_sub(size as u64, Relaxed); - OWN[4 + class].fetch_sub(1, Relaxed); + own[class].fetch_sub(size as u64, Relaxed); + own[4 + class].fetch_sub(1, Relaxed); } } @@ -408,7 +444,7 @@ mod command_tests { #[cfg(test)] mod own_tests { - use super::{OWN, block_class}; + use super::{block_class, owned}; use std::sync::atomic::Ordering::Relaxed; #[test] @@ -446,10 +482,10 @@ mod own_tests { #[test] fn a_block_is_counted_while_it_lives() { let block = vec![1u8; 8 << 20]; - assert!(OWN[3].load(Relaxed) >= 8 << 20); - assert!(OWN[7].load(Relaxed) >= 1); + assert!(owned(3) >= 8 << 20); + assert!(owned(7) >= 1); drop(block); - assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero"); + assert!(owned(7) < u64::MAX / 2, "no count below zero"); } } @@ -815,7 +851,7 @@ fn log_memory() { let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); let window = crate::shadow::window_use(); let views = crate::descriptor::views_kept(); - let own: Vec = OWN.iter().map(|o| o.load(Relaxed)).collect(); + let own: Vec = (0..8).map(owned).collect(); tracing::info!( "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", alive[0], @@ -981,7 +1017,9 @@ fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { /// A list call on this thread that began at `started` has returned. pub(crate) fn recorded(started: std::time::Instant) { - let ns = started.elapsed().as_nanos() as u64; + let took = started.elapsed(); + let ns = took.as_nanos() as u64; + crate::timeline::called(took); add(C::RecordCalls, 1); add(C::RecordNs, ns); if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { @@ -1093,15 +1131,12 @@ fn page_faults() -> u64 { /// second or more: a 4 s frame after an unlogged 4 s frame showed two /// frames' counts as one's). pub(crate) fn log(frames: f64) { - let counted = COUNT[C::Frames as usize].swap(0, Relaxed); + let counted = taken(C::Frames as usize); let frames = if counted > 0 { counted as f64 } else { frames }; static FAULTS: AtomicU64 = AtomicU64::new(0); let faults = page_faults(); let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); - let c: Vec = COUNT - .iter() - .map(|a| a.swap(0, Relaxed) as f64 / frames) - .collect(); + let c: Vec = (0..COUNTERS).map(|i| taken(i) as f64 / frames).collect(); let mb = |v: f64| v / 1e6; let ms = |v: f64| v / 1e3; tracing::info!( diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 91f9f68..6585bfa 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -249,6 +249,8 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps { last = std::time::Instant::now(); Over }); + let _round = + crate::timeline::span(if asked { "the heaps' records, for a submission" } else { "the heaps' records, early" }); let _ = std::panic::catch_unwind(sync_heaps); } }); @@ -1124,6 +1126,16 @@ fn view_at(i: u32, generation: u32) -> Option { } } +/// The words of the record at `handle`, if they are a view's. +pub(crate) fn record_at(handle: u64) -> Option<[u32; 3]> { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let words = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + (words[0] == VIEW_TAG).then_some(words) +} + /// 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 2597d45..5869757 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -52,7 +52,11 @@ pub(crate) struct HostHeap { /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource /// read there is a GPU page fault (the console reads stale memory). - kept: Mutex>>, + /// + /// A lock for each slot: one for the heap was what the recording threads + /// waited for most (5.6 % of their time, profile waits-1: each descriptor + /// made for a draw takes it, and lets go of what the slot held under it). + kept: Box<[Mutex>]>, /// Where the search for free dynamic slots starts, and which are taken /// (by lists not yet reset). next: Mutex<(u32, Vec)>, @@ -982,7 +986,7 @@ pub(crate) fn slot_story(slot: u32) -> String { if let Some(at) = host.written.get(slot as usize) { text.push_str(&format!(", written last at {:.1} s", f64::from(at.load(Relaxed)) / 1e3)); } - let kept = host.kept.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize).cloned().flatten(); + let kept = host.kept_in(index); match kept { None => text.push_str(", holds nothing"), Some(resource) => { @@ -1249,7 +1253,7 @@ impl HostHeap { copied: Mutex::new(Vec::new()), waiting: Mutex::default(), away: Mutex::default(), - kept: Mutex::new(vec![None; (count + extra) as usize]), + kept: (0..count + extra).map(|_| Mutex::new(None)).collect(), next: Mutex::new((0, vec![false; extra as usize])), free: std::sync::atomic::AtomicU32::new(extra), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), @@ -1644,12 +1648,7 @@ impl HostHeap { // as `mirror` takes them. let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); made.get(index as usize).is_some_and(|&made| made != 0 && made == key) - && self - .kept - .lock() - .unwrap_or_else(|e| e.into_inner()) - .get(index as usize) - .is_some_and(Option::is_some) + && self.kept_in(index).is_some() } /// Levels on demand (`crate::tiles`): makes again the host slots of the @@ -2130,6 +2129,68 @@ impl HostHeap { self.keep(index, kept.flatten()); } + /// Makes slot `index` (a dynamic one) the view the record `words` names, + /// from this thread's descriptor of it if the recording `recording` has + /// made one, else as [`HostHeap::make_at`] does, and keeps that + /// ([`ListViews`]). What is known of the record in this recording; + /// `None` (the slot is not made): not a view kept so. + pub(crate) fn make_listed(&self, recording: u64, words: [u32; 3], index: u32) -> Option { + if self.sampler { + return None; + } + LIST_VIEWS.with(|views| { + let mut views = views.borrow_mut(); + if views.is_none() { + *views = Some(ListViews::new()?); + } + let views = views.as_mut()?; + if views.recording != recording { + views.recording = recording; + views.made.clear(); + } + let twins = self.twins.get(index as usize).is_some(); + if !views.made.contains_key(&words) { + let view = super::view_at(words[1], words[2])?; + let at = 2 * views.made.len() as u32; + // (A constant buffer's bytes are copied for each draw.) + if at >= ListViews::SLOTS || matches!(view, View::Constant(..)) { + return None; + } + let twin = twinned(&view); + let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; + let listed = Listed { + kind: crate::draw::view_kind(&view), + texture: is_texture_view(&view), + ready: (0, 0, false), + tabled: None, + }; + views.made.insert(words, ListView { view, at, twin, kept, listed }); + } + let made = &views.made[&words]; + self.copy_from(index, views.slot(made.at)); + if made.twin && twins { + self.copy_from(self.raw + index, views.slot(made.at + 1)); + self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed); + } else { + self.clear_twin(index); + } + self.keep(index, made.kept.clone()); + Some(made.listed) + }) + } + + /// As [`HostHeap::copy_to`], from the slot `from`, which the card does not + /// see. + fn copy_from(&self, to: u32, from: D3D12_CPU_DESCRIPTOR_HANDLE) { + #[cfg(feature = "diagnostics")] + if let Some(written) = self.written.get(to as usize) { + written.store(crate::host::coarse_ms() as u32, std::sync::atomic::Ordering::Relaxed); + } + let Some(host) = host() else { return }; + // SAFETY: a slot of our heap, and one of this thread's heap. + unsafe { host.device.CopyDescriptorsSimple(1, self.cpu(to), from, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) }; + } + /// Makes slot `index` read nothing: a null view, or a plain sampler. pub(crate) fn make_null(&self, index: u32) { if self.sampler { @@ -2171,21 +2232,30 @@ impl HostHeap { /// Slot `index` now views `resource` (or nothing of the host's). fn keep(&self, index: u32, resource: Option) { - let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(slot) = kept.get_mut(index as usize) { + let Some(slot) = self.kept.get(index as usize) else { + return; + }; + let old = { use windows::core::Interface; + let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); // The same again: nothing to retire. if slot.as_ref().map(Interface::as_raw) == resource.as_ref().map(Interface::as_raw) { return; } - // A running submission may still read the old resource through - // this slot. - if let Some(old) = std::mem::replace(slot, resource) { - crate::host::retire(old); - } + std::mem::replace(&mut *slot, resource) + }; + // A running submission may still read the old resource through + // this slot. + if let Some(old) = old { + crate::host::retire_resource(old); } } + /// What slot `index` views. + fn kept_in(&self, index: u32) -> Option { + self.kept.get(index as usize)?.lock().unwrap_or_else(|e| e.into_inner()).clone() + } + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a /// size, whose reads past it return zeros instead of reaching whatever @@ -2371,7 +2441,7 @@ impl HostHeap { fn copy_to(&self, to: u32, which: u32) { #[cfg(feature = "diagnostics")] if let Some(written) = self.written.get(to as usize) { - written.store(crate::host::now_ms() as u32, std::sync::atomic::Ordering::Relaxed); + written.store(crate::host::coarse_ms() as u32, std::sync::atomic::Ordering::Relaxed); } let (Some(from), Some(host)) = (staged(self.sampler, which), host()) else { return; // made in place @@ -2593,9 +2663,8 @@ impl HostHeap { /// that is brought up to date for it). #[cfg(feature = "diagnostics")] pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { - let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); - let shown = kept.get(index as usize)?.as_ref()?; - Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) + let shown = self.kept_in(index)?; + Some(windows::core::Interface::as_raw(&shown) == windows::core::Interface::as_raw(buffer)) } /// What the queue of textures picked by index knows of title slot @@ -3060,8 +3129,7 @@ fn buffer_srv( } let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - // SAFETY: a live buffer. - let width = unsafe { shadow.buffer.GetDesc() }.Width; + let width = shadow.width(); if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); once!( @@ -4658,3 +4726,100 @@ mod tests { assert_eq!(heap.dynamic(2), None); } } + +/// What is known of a record a list's tables hold, in that recording of the +/// list ([`HostHeap::make_listed`]). +#[derive(Clone, Copy)] +pub(crate) struct Listed { + pub(crate) kind: Option, + pub(crate) texture: bool, + /// Read at this epoch of the list ([`crate::host::HostList::epoch`]) with + /// this depth target tested: up to date; and whether it is that target's. + pub(crate) ready: (u64, usize, bool), + /// The title's slot last noted for it, and whether the draw read it. + pub(crate) tabled: Option<(u32, bool)>, +} + +struct ListView { + view: View, + /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. + at: u32, + twin: bool, + kept: Kept, + listed: Listed, +} + +/// The descriptors a thread made for one recording of a list, by the record +/// they were made from, in a heap the card does not see. +/// +/// The title's culling and lighting dispatches each bind a table of their own +/// that differs in one constant buffer, and the same thirty views beside it: +/// each was found, checked, made and brought up to date anew for every +/// dispatch, some 2,500 indirect dispatches in the one recording job the +/// frame waits for last (timeline waits-2: 24 of 65 ms). Here a list makes a +/// view once, as it makes a table once (`crate::draw::State::tables`), and +/// copies its descriptor. +struct ListViews { + recording: u64, + heap: ID3D12DescriptorHeap, + step: usize, + start: usize, + made: std::collections::HashMap<[u32; 3], ListView, std::hash::BuildHasherDefault>, +} + +impl ListViews { + const SLOTS: u32 = 8192; + + fn new() -> Option { + let host = host()?; + // SAFETY: plain object creation. + unsafe { + let heap: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: Self::SLOTS, + ..Default::default() + }) + .ok()?; + let step = host.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let start = heap.GetCPUDescriptorHandleForHeapStart().ptr; + Some(ListViews { recording: 0, heap, step, start, made: Default::default() }) + } + } + + fn slot(&self, i: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + debug_assert!(i < Self::SLOTS && !windows::core::Interface::as_raw(&self.heap).is_null()); + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: self.start + i as usize * self.step } + } +} + +thread_local! { + static LIST_VIEWS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The view the record `words` names, as this thread made it for `recording`. +pub(crate) fn listed_view(recording: u64, words: [u32; 3]) -> Option { + LIST_VIEWS.with(|views| { + let views = views.borrow(); + let views = views.as_ref().filter(|v| v.recording == recording)?; + views.made.get(&words).map(|m| m.view.clone()) + }) +} + +/// Notes what is known of the record `words` in `recording`. +pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) { + LIST_VIEWS.with(|views| { + if let Some(views) = views.borrow_mut().as_mut().filter(|v| v.recording == recording) + && let Some(made) = views.made.get_mut(&words) + { + made.listed = listed; + } + }); +} + +/// Whether a list makes a view its tables hold once (`VICTORY_LIST_VIEWS=0`: +/// for every table). +pub(crate) fn list_views() -> bool { + crate::toggled!("VICTORY_LIST_VIEWS") +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 28b9a32..1850b78 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -328,7 +328,7 @@ pub(crate) struct State { host_heaps: [usize; 2], /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. - fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>, + fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault>, /// The dynamic slots the list holds: title heap, first, count; given /// back when the list has run, is reset or released. dynamic: Vec<(usize, u32, u32)>, @@ -341,6 +341,9 @@ pub(crate) struct State { root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, /// The list ran and its dynamic slots were given back. tables_gone: bool, + /// This recording, for [`crate::descriptor::host::HostHeap::make_listed`] + /// (0: it has none yet). + recording: u64, } impl Drop for State { @@ -371,6 +374,7 @@ impl State { crate::descriptor::release_dynamic(heap, first, n); } self.fresh_tables.clear(); + self.recording = 0; self.root_srv_slots.clear(); self.root_uav_slots.clear(); self.tables_gone = true; @@ -1463,7 +1467,16 @@ impl State { None }; if let Some((param, dwords)) = stage.user_data { - let mut values = vec![0u32; dwords as usize]; + // (A root signature holds 64 dwords.) + let mut room = [0u32; 64]; + let mut more = Vec::new(); + let values: &mut [u32] = match room.get_mut(..dwords as usize) { + Some(values) => values, + None => { + more.resize(dwords as usize, 0); + &mut more + } + }; for u in &t.host.user_data { if let RootType::Other(kind) = u.root { values[u.index as usize] = @@ -1481,7 +1494,7 @@ impl State { #[cfg(feature = "diagnostics")] { self.user.clear(); - self.user.extend_from_slice(&values); + self.user.extend_from_slice(values); } // SAFETY: an open list; `values` covers the parameter. unsafe { @@ -1846,6 +1859,7 @@ impl State { return Some(gpu); } let started = std::time::Instant::now(); + let mut stage = crate::timeline::span("the heap pass: begun, or done here"); if crate::host::aside::on() { let at = std::ptr::from_ref(heap) as usize; list.refreshes_coming(move || { @@ -1860,7 +1874,9 @@ impl State { } #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); + stage.next("the heap pass: textures"); self.heap_textures(list, heap, host); + stage.end(); #[cfg(feature = "diagnostics")] HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); @@ -2931,14 +2947,14 @@ impl State { used: &[UsedResource], indexed: &[RootIndexedView], compute: bool, - ) -> Vec<(u8, u32)> { + ) -> Few<(u8, u32), 16> { let tables = |u: &&UsedResource| u.root == RootType::Table; - let mut fresh: Vec = used - .iter() - .filter(tables) - .filter(|u| u.kind == ResourceType::Cbv) - .map(|u| u.slot) - .collect(); + let mut fresh: Few = Few::default(); + for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) { + if !fresh.contains(&u.slot) { + fresh.push(u.slot); + } + } // Tables reaching past a host heap smaller than the title's (the // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the // title's slots there have no host slot of their own. @@ -2961,22 +2977,22 @@ impl State { } } fresh.sort_unstable(); - fresh.dedup(); for u in used.iter().filter(tables) { if !fresh.contains(&u.slot) { self.table_entry(list, u, compute); } } - let mut made = Vec::new(); - for slot in fresh { + let mut made = Few::default(); + for &slot in fresh.iter() { let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { continue; }; - let entries: Vec<&UsedResource> = used - .iter() - .filter(tables) - .filter(|u| u.slot == slot) - .collect(); + // (Their places among `used`.) + let mut places: Few = Few::default(); + for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) { + places.push(i as u16); + } + let entries = || places.iter().map(|&i| &used[usize::from(i)]); let Some(heap) = self.heap_of(table) else { continue; }; @@ -3002,8 +3018,7 @@ impl State { .collect(); selected.sort_unstable(); selected.dedup(); - let n = entries - .iter() + let n = entries() .map(|u| u.table_offset_dwords / 8) .chain(selected.last().copied()) .max() @@ -3018,24 +3033,41 @@ impl State { } // The table and what its entries hold (record words). let key = { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); + let mut h = RecordHash::default(); for k in 0..n { let at = table + u64::from(k) * 32; // SAFETY: a descriptor slot in title memory. - unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); + h.add(unsafe { (at as *const [u32; 3]).read_unaligned() }); } - (table, n, h.finish()) + (table, n, h.0) }; - if let Some(&first) = self.fresh_tables.get(&key) { - for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { + // Who reads of it, and as what, as far as [`readable`] goes by it. + let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0); + if let Some(known) = self.fresh_tables.get_mut(&key) { + let first = known.first; + // This reader had it brought up to date, and nothing in the + // list changed since: nothing to do again. + let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav); + if once + && known.epoch == list.epoch() + && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader) + { + if *depth { + TESTED_DEPTH.set((reader.3, true)); + } + made.push((slot, first * 32)); + continue; + } + let depth_before = TESTED_DEPTH.get(); + TESTED_DEPTH.set((depth_before.0, false)); + for u in entries().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { readable(list, u.kind, &view); } } for k in selected { - if entries.iter().any(|u| u.table_offset_dwords / 8 == k) { + if entries().any(|u| u.table_offset_dwords / 8 == k) { continue; } let handle = table + u64::from(k) * 32; @@ -3045,6 +3077,20 @@ impl State { readable(list, kind, &view); } } + let depth = TESTED_DEPTH.get().1; + TESTED_DEPTH.set((depth_before.0, depth_before.1 || depth)); + if once && let Some(known) = self.fresh_tables.get_mut(&key) { + // (The epoch as it is now: what this changed itself it + // need not do again.) + let epoch = list.epoch(); + if known.epoch != epoch { + known.epoch = epoch; + known.ready.clear(); + } + if known.ready.len() < 16 { + known.ready.push((reader, depth)); + } + } made.push((slot, first * 32)); continue; } @@ -3054,7 +3100,7 @@ impl State { made.push((slot, u32::MAX)); continue; }; - self.fresh_tables.insert(key, first); + self.fresh_tables.insert(key, FreshTable { first, epoch: 0, ready: Vec::new() }); self.dynamic .push((std::ptr::from_ref(heap) as usize, first, n)); // The title's own slots of this table: what the draw reads of @@ -3064,15 +3110,63 @@ impl State { // which may lie over slots shaders pick by index, only the ones // the shader names.) if let Some(title) = title_first { - for k in (0..n).filter(|&k| n <= 64 || entries.iter().any(|u| u.table_offset_dwords / 8 == k)) { + for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) { host.slot_tabled(title + k); } } + let list_views = crate::descriptor::host::list_views(); + if self.recording == 0 { + static NEXT: AtomicU64 = AtomicU64::new(1); + self.recording = NEXT.fetch_add(1, Ordering::Relaxed); + } + let recording = self.recording; // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { let index = first + k; - let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); + // A view this list has made before: its descriptor copied, + // and nothing more if nothing changed in the list since. + if list_views + && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) + && let Some(mut listed) = host.make_listed(recording, words, index) + { + let kind = entries() + .find(|u| u.table_offset_dwords / 8 == k) + .map(|u| u.kind) + .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); + let was = (listed.ready, listed.tabled); + if let Some(kind) = kind { + let tested = TESTED_DEPTH.get(); + if kind == ResourceType::Srv && listed.ready.0 == list.epoch() && listed.ready.1 == tested.0 { + if listed.ready.2 { + TESTED_DEPTH.set((tested.0, true)); + } + } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { + TESTED_DEPTH.set((tested.0, false)); + readable(list, kind, &view); + let depth = TESTED_DEPTH.get().1; + TESTED_DEPTH.set((tested.0, tested.1 || depth)); + if kind == ResourceType::Srv { + listed.ready = (list.epoch(), tested.0, depth); + } + } + } + if let Some(title) = title_first + && listed.texture + && listed.tabled != Some((title + k, kind.is_some())) + { + listed.tabled = Some((title + k, kind.is_some())); + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); + } + } + if was != (listed.ready, listed.tabled) { + crate::descriptor::host::note_listed(recording, words, listed); + } + continue; + } + let used = entries().find(|u| u.table_offset_dwords / 8 == k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { @@ -3669,7 +3763,7 @@ fn host_signature(kind: u32, stride: u32) -> Option { /// Gets what a shader reads or writes through a view ready: buffer data /// copied, textures moved to the state they need. -fn view_kind(view: &View) -> Option { +pub(crate) fn view_kind(view: &View) -> Option { match view { View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv), View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav), @@ -3705,6 +3799,83 @@ fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_ } } +/// A few things, up to `N` of them without memory of the heap: what a draw's +/// tables are gone through with, some six lists a stage. +struct Few { + few: [T; N], + len: usize, + /// All of them, if they are more. + many: Vec, +} + +impl Default for Few { + fn default() -> Self { + Few { few: [T::default(); N], len: 0, many: Vec::new() } + } +} + +impl Few { + fn push(&mut self, what: T) { + if self.many.is_empty() && self.len < N { + self.few[self.len] = what; + self.len += 1; + } else { + if self.many.is_empty() { + self.many.extend_from_slice(&self.few); + } + self.many.push(what); + } + } +} + +impl std::ops::Deref for Few { + type Target = [T]; + fn deref(&self) -> &[T] { + if self.many.is_empty() { &self.few[..self.len] } else { &self.many } + } +} + +impl std::ops::DerefMut for Few { + fn deref_mut(&mut self) -> &mut [T] { + if self.many.is_empty() { &mut self.few[..self.len] } else { &mut self.many } + } +} + +/// A table made afresh in dynamic slots, in a list ([`State::tables`]). +struct FreshTable { + first: u32, + /// The list's epoch ([`HostList::epoch`]) at which all its entries that + /// these readers (a stage's list of what it reads, whether it stores, the + /// tested depth target) read were brought up to date, and whether that read the + /// tested depth target. + epoch: u64, + ready: Vec<((usize, usize, bool, usize), bool)>, +} + +/// Whether a table a list reads again, with nothing changed in the list +/// since, is left as it is (`VICTORY_READY_ONCE=0`: every entry is gone +/// through again at every draw). +fn ready_once() -> bool { + crate::toggled!("VICTORY_READY_ONCE") +} + +/// A hash of records' words: 64 bits, two multiplications a record. (The +/// standard library's took 3 % of the recording threads' time.) +#[derive(Default)] +struct RecordHash(u64); + +impl RecordHash { + fn add(&mut self, [a, b, c]: [u32; 3]) { + let fold = |x: u64, y: u64| { + let p = u128::from(x) * u128::from(y); + p as u64 ^ (p >> 64) as u64 + }; + let words = u64::from(a) << 32 | u64::from(b); + let first = fold(self.0 ^ words ^ 0x2d35_8dcc_aa6c_78a5, 0x8bb8_4b93_962e_acc9 ^ u64::from(c)); + self.0 = fold(first ^ 0x4b33_a62e_d433_d4a3, 0x4d5a_2da5_1de1_aa47 ^ self.0.rotate_left(23)) ^ first; + } +} + fn readable(list: &HostList, kind: ResourceType, view: &View) { const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); @@ -3737,9 +3908,11 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { let aliased = crate::resource::alias_of(*resource as This) .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); if !aliased - && let Some(t) = crate::resource::host_resource(*resource as This) - && crate::texture::title_written(t) + && let Some(t) = crate::resource::host_copy(*resource as This) + && t.flags() & 0x7 == 0 { + // (A texture the title writes: no target, depth or unordered + // access, `crate::texture::title_written`.) // Of a texture the title placed, the levels the view shows. let first = match (&placed, view) { (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc), @@ -3760,7 +3933,9 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { }; crate::list::ensure_state(list, *resource as This, state); #[cfg(feature = "diagnostics")] - if let Some(t) = crate::resource::host_resource(*resource as This) { + if tracing::enabled!(tracing::Level::DEBUG) + && let Some(t) = crate::resource::host_resource(*resource as This) + { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; if d.Flags.0 & 7 == 0 { @@ -4009,3 +4184,43 @@ mod tests { assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB); } } + +#[cfg(test)] +mod record_hash_tests { + use super::{Few, RecordHash}; + + #[test] + fn a_few_things_are_kept_in_order_however_many() { + for n in 0..10u32 { + let mut few: Few = Few::default(); + (0..n).for_each(|i| few.push(n - i)); + assert_eq!(few.to_vec(), (0..n).map(|i| n - i).collect::>()); + few.sort_unstable(); + assert_eq!(few.to_vec(), (1..=n).collect::>()); + } + } + + #[test] + fn records_that_differ_hash_apart() { + let of = |records: &[[u32; 3]]| { + let mut h = RecordHash::default(); + records.iter().for_each(|r| h.add(*r)); + h.0 + }; + let mut seen = std::collections::HashSet::new(); + // One record, one word or two of it different; runs of zeros; order. + for a in 0..64u32 { + for b in 0..64u32 { + for c in [0, 1, 0x8000_0000, u32::MAX] { + assert!(seen.insert(of(&[[a, b, c]]))); + assert!(seen.insert(of(&[[1, 2, 3], [a, b, c]]))); + assert!(seen.insert(of(&[[a, b, c], [1, 2, 3], [0, 0, 0]]))); + } + } + } + assert!(seen.insert(of(&[]))); + // (One record of zeros is among the above.) + let zeros: Vec = (2..100).map(|n| of(&vec![[0; 3]; n])).collect(); + assert!(zeros.iter().all(|h| seen.insert(*h))); + } +} diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index d3103b0..10a9e93 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -85,6 +85,13 @@ extern "system" fn release(this: This) -> u32 { pub(crate) extern "system" fn completed(this: This) -> u64 { fence(this).value.load(Ordering::Acquire) } +/// The title's `GetCompletedValue`. +extern "system" fn completed_called(this: This) -> u64 { + let value = completed(this); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::polled(this as usize, value); + value +} extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); @@ -94,6 +101,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c } return S_OK; } + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::told("an event asked for", this as usize, value); if event.is_null() { // With submissions sent to the card and not waited for // (`crate::host::late`) the signal may be behind them: they are @@ -120,6 +129,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c /// Moves the fence to `value` and sets the events that waited for it. pub(crate) fn set(this: This, value: u64) { let fence = fence(this); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::told("a fence set", this as usize, value); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); waiters.retain(|&(wanted, event)| { @@ -131,6 +142,7 @@ pub(crate) fn set(this: This, value: u64) { }); } pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + let _called = crate::timeline::span("a fence set"); set(this, value); // A queue may have waited for it: what it held runs now. #[cfg(windows)] @@ -153,7 +165,7 @@ static FUNCTIONS: Table<24> = { f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 - f[8] = completed as *const (); // 0x40 + f[8] = completed_called as *const (); // 0x40 f[9] = set_event_on_completion as *const (); // 0x48 f[10] = signal as *const (); // 0x50 f[11] = creation_flags as *const (); // 0x58 diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index e9da52c..8bf432f 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -148,6 +148,7 @@ pub(crate) extern "system" fn wait( tick -= 1; wait = Duration::ZERO; } + let _called = crate::timeline::span("the title's frame wait"); let hr = if wait > limit { std::thread::sleep(limit); TIMEOUT diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index bfd49f0..507a79d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -77,7 +77,12 @@ static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// A retired object, dropped on whatever thread finishes the submission. -struct Retired(#[allow(dead_code)] Box); +#[allow(dead_code)] +enum Retired { + Any(Box), + /// What a descriptor slot showed: 20,000 a frame, without a box each. + Resource(ID3D12Resource), +} // SAFETY: what is retired is D3D12 objects (free-threaded) and the // reference-counted wrappers holding them, dropped once. unsafe impl Send for Retired {} @@ -88,12 +93,24 @@ pub(crate) fn now_ms() -> u64 { EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 } +/// [`now_ms`] to the system's tick (16 ms): a few nanoseconds, where the +/// performance counter's are 25. For what is noted tens of thousands of +/// times a frame and read in tenths of a second. +pub(crate) fn coarse_ms() -> u64 { + use windows_sys::Win32::System::SystemInformation::GetTickCount64; + // The same beginning as `now_ms`. + static BEGAN: OnceLock = OnceLock::new(); + // SAFETY: a plain query. + let now = unsafe { GetTickCount64() }; + now.saturating_sub(*BEGAN.get_or_init(|| now.saturating_sub(now_ms()))) +} + /// This moment, for telling later how long ago it was ([`long_ago`]): the /// frames begun so far (high half, `crate::frame::current`) and tenths of a /// second since the start. Host copies of title memory, staging buffers and /// host textures note when they were last used with it. pub(crate) fn moment() -> u64 { - (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff) + (crate::frame::current() << 32) | ((coarse_ms() / 100) & 0xffff_ffff) } /// Whether `moment` lies at least `ms` milliseconds and `frames` frames @@ -443,7 +460,20 @@ pub(crate) fn retire(object: T) { RETIRED .lock() .unwrap_or_else(|e| e.into_inner()) - .push_back((started, Retired(Box::new(object)))); + .push_back((started, Retired::Any(Box::new(object)))); +} + +/// [`retire`] for a resource. +pub(crate) fn retire_resource(object: ID3D12Resource) { + let queued = crate::queue::queued(); + let started = STARTED.load(Ordering::Acquire) + queued; + if bury_lag() == 0 && started <= FINISHED.load(Ordering::Acquire) { + RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); + drop(object); + return; + } + RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); + RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push_back((started, Retired::Resource(object))); } /// How many submissions later than it could (the last one that may use it @@ -1136,6 +1166,10 @@ pub(crate) struct HostList { /// Refreshes of host copies that a thread of ours is still finding, and /// where among the list's steps they belong ([`aside`]). coming: Mutex)>>, + /// Another number each time something changes that what a draw reads + /// depends on ([`HostList::changed_something`]); no two lists have the + /// same. + epoch: std::sync::atomic::AtomicU64, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -2137,7 +2171,7 @@ struct Deferred { kept: Vec, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. - refreshed: std::collections::HashSet<(usize, usize, usize)>, + refreshed: std::collections::HashSet<(usize, usize, usize), std::hash::BuildHasherDefault>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, @@ -3038,7 +3072,9 @@ fn late_helper() { } }; let Some(target) = target else { + let mut helping = crate::timeline::span("helper: landed lists reset and given back"); land(); + helping.next("helper: looking at what queues hold"); crate::queue::release_held(false); continue; }; @@ -3047,6 +3083,8 @@ fn late_helper() { // SAFETY: our fence and event. unsafe { if host.fence.SetEventOnCompletion(target, event).is_ok() { + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(target)); WaitForSingleObject(event, INFINITE); } } @@ -3104,6 +3142,15 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { LATE_STATS[why].fetch_add(1, Ordering::Relaxed); let was_working = working(false); let waiting = std::time::Instant::now(); + let _waiting = crate::timeline::span(match why { + WHY_SYNC => "waiting for landings: everything (a present, the sweep)", + WHY_VALUE => "waiting for landings: a memory value", + WHY_STALE => "waiting for landings: title memory changed under shader writes", + WHY_READ => "waiting for landings: title memory read", + WHY_MOST => "waiting for landings: lists in the air", + WHY_FENCE => "waiting for landings: a blocking fence wait", + _ => "waiting for landings: another reason", + }); while !done(&line) { line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); } @@ -3195,6 +3242,8 @@ fn relay_worker() { Ok(items) => host.relay_land(items, &mut fetch), Err(target) => { let waiting = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(target)); // SAFETY: the host's fence and this thread's event. let waited = unsafe { host.fence.SetEventOnCompletion(target, event).map(|()| { @@ -3425,6 +3474,10 @@ pub(crate) use send::{goes_as_words, words_under}; pub(crate) mod spans; mod torn; pub(crate) mod upcheck; +#[cfg(feature = "diagnostics")] +mod stamps; +#[cfg(feature = "diagnostics")] +pub(crate) use stamps::{timeline_ready, timeline_restart, timeline_stamps}; #[cfg(test)] mod late_tests { @@ -3823,6 +3876,7 @@ impl Host { indirect_args: Mutex::default(), batch_args: Mutex::default(), coming: Mutex::default(), + epoch: std::sync::atomic::AtomicU64::new(next_epoch()), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -4444,11 +4498,14 @@ impl Host { } list.Close()?; let lists = [Some(list.cast::()?)]; + let _fetching = crate::timeline::span("landing: fetching pieces"); if let Some(queue) = ©_queue { queue.ExecuteCommandLists(&lists); queue.Signal(&fence, sent)?; meanwhile(); fence.SetEventOnCompletion(sent, event)?; + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(None); WaitForSingleObject(event, INFINITE); return Ok(behind); } @@ -4462,6 +4519,8 @@ impl Host { self.queue.Signal(&fence, sent)?; meanwhile(); fence.SetEventOnCompletion(sent, event)?; + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(None); WaitForSingleObject(event, INFINITE); Ok(after) })() @@ -4480,6 +4539,7 @@ impl Host { CARD_STATS[6].fetch_add(us, Ordering::Relaxed); } let merging = std::time::Instant::now(); + let _merging = crate::timeline::span("landing: merging fetched pieces"); let mut written = 0; if land::on() { let titles: Vec<(usize, usize)> = @@ -4548,6 +4608,7 @@ impl Host { /// is complete before the title is told anything. fn relay_land(&self, items: Vec, fetch: &mut Option) { let landing = std::time::Instant::now(); + let mut stage = crate::timeline::span("landing: what is to be looked through"); { let flights: Vec<&Flight> = items .iter() @@ -4580,12 +4641,16 @@ impl Host { } } let mut hand_back = relay_hand_back(&back); + stage.next("landing: copies in the card's memory"); self.relay_card_back(&plans, fetch, &mut || { if crate::land::on() { + let _looking = crate::timeline::span("landing: looking through copies, beside the fetch"); hand_back.look(crate::land::stat::SCAN_BESIDE); } }); + stage.next("landing: copies in the PC's memory"); hand_back.merge(); + stage.next("landing: ranges done with"); let finishing = std::time::Instant::now(); // Only now, and flight by flight: a range another flight // in the air declared too stays closed to refreshes. @@ -4601,6 +4666,7 @@ impl Host { } } // In the order given: what tells the title the card is done. + stage.next("landing: read-backs, telling the title"); let mut last = 0; let mut landed = Vec::new(); let mut telling = std::time::Instant::now(); @@ -4634,6 +4700,7 @@ impl Host { FINISHED.store(last, Ordering::Release); bury(last); } + stage.next("landing: the rest"); self.log_messages(); crate::land::spent(crate::land::stat::REST, telling); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -4870,6 +4937,7 @@ impl Host { LINE_MOVED.notify_one(); } drop(submitted); + let _landing = crate::timeline::span("landed lists reset and given back"); land(); } @@ -4935,6 +5003,7 @@ impl Host { return; } let was_working = working(true); + let _settling = crate::timeline::span("settling flights"); let mut counted = false; loop { let items = { @@ -4964,6 +5033,8 @@ impl Host { match self.fence.SetEventOnCompletion(*submitted, self.event) { Ok(()) => { working(false); + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(*submitted)); WaitForSingleObject(self.event, INFINITE); stood(waiting); working(true); @@ -5106,6 +5177,7 @@ impl Host { crate::copystat::submission_begins(); // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. + let mut stage = crate::timeline::span("submit: the submission lock"); let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let was_working = working(true); submitting(1, runs.len()); @@ -5113,6 +5185,7 @@ impl Host { let ahead = Split::begin(); #[cfg(feature = "diagnostics")] SPLIT[11].fetch_add(called.elapsed().as_nanos() as u64, Ordering::Relaxed); + stage.next("submit: steps given to the card"); // Flights in the air ([`late`]): a submission that is waited for // settles them first, one sent ahead only if preparing it reads // what they write. @@ -5120,6 +5193,7 @@ impl Host { let own = if late { self.card_steps(runs) } else { None }; #[cfg(feature = "diagnostics")] ahead.part(12); + stage.next("submit: waiting for flights it reads from"); if !late { self.settle(&mut submitted, WHY_SYNC); } else if own.is_none() @@ -5149,6 +5223,7 @@ impl Host { } None => runs, }; + stage.next("submit: the sweep"); let behind = late && flying(); // Before this submission counts as started: what the sweep lets go // of is named by no list, and nothing runs now (behind flights the @@ -5172,6 +5247,7 @@ impl Host { SWEPT.store(now_ms(), Ordering::Relaxed); } let behind = late && flying(); + stage.next("submit: gathering what to ask about"); let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; // The ranges shaders write are counted for it (with the relay). crate::shadow::preparing(this_submission); @@ -5211,9 +5287,11 @@ impl Host { let ranges: Vec<(usize, usize)> = spans.into_values().collect(); #[cfg(feature = "diagnostics")] SPLIT[8].fetch_add(split.so_far(), Ordering::Relaxed); + stage.next("submit: asking the write watch"); crate::watch::ask_once(&ranges); #[cfg(feature = "diagnostics")] split.part(0); + stage.next("submit: title bytes under flights' writes"); // Behind flights: the title wrote memory that a flight's shaders // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote @@ -5239,9 +5317,11 @@ impl Host { split.part(1); // What flights in the air may write. let air = line().written.clone(); + stage.next("submit: refreshes ahead of writes"); if ahead_of_writes() { batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i))); } + stage.next("submit: the lists' steps"); for list in runs { list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); @@ -5251,10 +5331,12 @@ impl Host { lists.push(list.list.cast().ok()); } batch.fill(); + stage.next("submit: the last refreshes"); batch.flush(); crate::watch::ask_once_end(); #[cfg(feature = "diagnostics")] split.part(2); + stage.next("submit: snapshots"); // The snapshots of the ranges shaders may write, if they were left // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. @@ -5267,6 +5349,7 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(3); + stage.next("submit: copies in the card's memory"); // Copies in the card's memory: what changed on their CPU side goes // up ahead of the lists, and a compare of what the shaders may // write follows them in the same submission. @@ -5293,6 +5376,7 @@ impl Host { } #[cfg(feature = "diagnostics")] split.part(4); + stage.next("submit: waiting for the heaps' records"); drop(heaps_synced); // The slots that waited for a texture's host copy, before the // lists that may read them run. @@ -5300,6 +5384,18 @@ impl Host { #[cfg(feature = "diagnostics")] split.part(15); let prepared = std::time::Instant::now(); + stage.next("submit: sending"); + // When it runs on the card, for the timeline. + #[cfg(feature = "diagnostics")] + let stamp = stamps::take(); + #[cfg(feature = "diagnostics")] + if let Some((ahead, behind)) = stamp.and_then(stamps::lists) { + lists.insert(0, Some(ahead)); + lists.push(Some(behind)); + firsts.iter_mut().for_each(|first| *first += 1); + } + #[cfg(feature = "diagnostics")] + let sending = crate::timeline::ticks(); if late { *submitted += 1; #[cfg(feature = "diagnostics")] @@ -5313,7 +5409,10 @@ impl Host { self.queue.Signal(&self.fence, *submitted) }; awake::sent(&self.device); + #[cfg(feature = "diagnostics")] + crate::timeline::sent(sending, *submitted, stamp); self.card_sent(); + stage.next("submit: noting what is in the air"); if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } @@ -5360,9 +5459,13 @@ impl Host { .queue .Signal(&self.fence, *submitted) .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + #[cfg(feature = "diagnostics")] + crate::timeline::sent(sending, *submitted, stamp); match waited { Ok(()) => { working(false); + #[cfg(feature = "diagnostics")] + let _card = crate::timeline::card_wait(Some(*submitted)); WaitForSingleObject(self.event, INFINITE); stood(started); working(true); @@ -5429,6 +5532,7 @@ impl Host { )); } submitting(3, runs.len()); + stage.next("submit: copying back"); // What shaders wrote goes back before the bottom-of-pipe writes, // which tell the title the GPU is done; each range once per // submission, however many dispatches declared it (the world's @@ -5777,6 +5881,7 @@ impl HostList { } pub(crate) fn close(&self) { + let _closing = crate::timeline::span("closing a host list"); self.twins_to_depth(); let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); if let Some((scratch, _)) = scratch { @@ -5827,8 +5932,10 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { + self.changed_something(); #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); + let _resetting = crate::timeline::span("resetting a host list"); self._alive.used(); *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None; *self.deferred() = Deferred::default(); @@ -5861,6 +5968,18 @@ impl HostList { crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); } + /// Something changed in this list that bringing a draw's textures and + /// buffers up to date depends on: a texture's state, a twin, what was + /// refreshed. + pub(crate) fn changed_something(&self) { + self.epoch.store(next_epoch(), Ordering::Relaxed); + } + + /// See [`HostList::changed_something`]. + pub(crate) fn epoch(&self) -> u64 { + self.epoch.load(Ordering::Relaxed) + } + /// Moves a title texture's host copy to `wanted` (a host state) in this /// list: the host texture and the state it leaves, if that is a change. /// The list's first use of a texture records nothing: its prelude brings @@ -5874,15 +5993,19 @@ impl HostList { // SAFETY: as in `crate::resource::host_resource`; the list's states // hold the copy from here on. let texture: &'static ID3D12Resource = unsafe { &*std::ptr::from_ref(©.texture) }; - let wanted = legal_state(texture, wanted); + let wanted = legal_for(copy.flags(), wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); match states.entry(std::sync::Arc::as_ptr(©) as usize) { std::collections::hash_map::Entry::Vacant(v) => { v.insert((wanted, wanted, copy)); + self.changed_something(); None } std::collections::hash_map::Entry::Occupied(mut o) => { let before = std::mem::replace(&mut o.get_mut().1, wanted); + if before != wanted { + self.changed_something(); + } (before != wanted).then_some((texture, before)) } } @@ -5893,7 +6016,8 @@ impl HostList { /// records the barrier: for textures that are not a title resource's /// host copy (colour twins) and for the copies between the two. fn settle(&self, copy: &std::sync::Arc, wanted: u32) { - let wanted = legal_state(©.texture, wanted); + let wanted = legal_for(copy.flags(), wanted); + self.changed_something(); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { std::collections::hash_map::Entry::Vacant(v) => { @@ -5957,6 +6081,7 @@ impl HostList { writing: false, late: false, }); + let was = (u.needs, u.behind, u.writing); let copy = match u.behind[side] { Some(behind) => behind, None => { @@ -5973,6 +6098,9 @@ impl HostList { (true, false) => u.behind[1] = Some(true), (false, _) => {} } + if was != (u.needs, u.behind, u.writing) || copy || colour { + self.changed_something(); + } // shortcut: the depth plane's twin is not drawn into the plane // here: the pass sets a pipeline and a target of ours, which a list // still recording the title's commands cannot take. This use sees @@ -6078,6 +6206,7 @@ impl HostList { for u in twins.values_mut().filter(|u| u.writing) { u.writing = false; u.behind[0] = Some(true); + self.changed_something(); } } @@ -6287,6 +6416,7 @@ impl HostList { .copies .push(Step::Copy(dst as usize, src as usize, len)); deferred.refreshed.clear(); + self.changed_something(); } /// Copies `len` bytes of title memory at `src` into the list's upload @@ -6669,6 +6799,7 @@ impl HostList { pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Run(Box::new(work))); self.deferred().refreshed.clear(); + self.changed_something(); } /// As [`HostList::defer`], for work that writes only host memory. @@ -6766,6 +6897,7 @@ impl HostList { if matches!(step, Step::Run(_)) { batch.title_written(); } + let _step = crate::timeline::span("a step of ours"); work(); // It wrote title memory, where is not known here: the // submission's one asking ends, later refreshes ask anew. @@ -6822,6 +6954,12 @@ impl HostList { } } +/// The numbers of [`HostList::epoch`]. +fn next_epoch() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + /// A table by a copy's address. pub(crate) type ByCopy = std::collections::HashMap>; @@ -6844,6 +6982,12 @@ impl std::hash::Hasher for AddressHash { let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); self.0 = h ^ (h >> 32); } + fn write_u64(&mut self, n: u64) { + self.write_usize(n as usize); + } + fn write_u32(&mut self, n: u32) { + self.write_usize(n as usize); + } } /// Since the last frame-rate line, nanoseconds of the submitting thread's @@ -7196,6 +7340,7 @@ impl Batch { /// Brings `[from, to)` of a copy up to date, timed. fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { let started = std::time::Instant::now(); + let _one = crate::timeline::span("a copy's refresh"); let copied = shadow.update(from, to - from); let us = started.elapsed().as_micros() as u64; #[cfg(feature = "diagnostics")] @@ -7299,6 +7444,7 @@ impl Batch { self.due.drain(..).for_each(|staging| staging.refresh()); return; } + let _textures = crate::timeline::span("textures brought up to date"); // The time counted is the time it took, not the threads' sum. let started = std::time::Instant::now(); let before = PREPARING[2].load(Ordering::Relaxed); @@ -7316,6 +7462,7 @@ impl Batch { } #[cfg(feature = "diagnostics")] let (began, all) = (std::time::Instant::now(), self.refreshes.len()); + let _flush = crate::timeline::span("refreshes of copies"); self.flush_all(); #[cfg(feature = "diagnostics")] { @@ -8240,8 +8387,11 @@ impl Host { } #[cfg(feature = "diagnostics")] crate::replay::record::present(texture, state); + let mut showing = crate::timeline::span("the host's Present"); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + showing.next("the frame meter"); p.meter.frame(p.hwnd); + showing.end(); #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); #[cfg(not(feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/host/aside.rs b/crates/victory-gpu/src/host/aside.rs index e466613..b46cf61 100644 --- a/crates/victory-gpu/src/host/aside.rs +++ b/crates/victory-gpu/src/host/aside.rs @@ -25,6 +25,7 @@ impl Coming { /// What was found. pub(crate) fn wait(&self) -> Vec { let began = std::time::Instant::now(); + let _waiting = crate::timeline::span("a list's close waits for the heap's views"); let mut found = self.0.lock().unwrap_or_else(|e| e.into_inner()); loop { if let Some(found) = found.take() { @@ -56,6 +57,7 @@ pub(crate) fn begin(work: impl FnOnce() -> Vec + Send + 'static) -> std let told = coming.clone(); let job: Job = Box::new(move || { // (However it ends, the list that waits goes on.) + let _aside = crate::timeline::span("beside: the heap's views"); let found = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)).unwrap_or_default(); told.found(found); }); diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 7d494e0..cde0149 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -256,6 +256,7 @@ impl HostList { from: scratch.map(|s| s.2 as usize), })); deferred.refreshed.clear(); + self.changed_something(); true } diff --git a/crates/victory-gpu/src/host/stamps.rs b/crates/victory-gpu/src/host/stamps.rs new file mode 100644 index 0000000..6abbcfb --- /dev/null +++ b/crates/victory-gpu/src/host/stamps.rs @@ -0,0 +1,187 @@ +//! Diagnostics: when each submission began and ended on the card, for the +//! timeline (`crate::timeline`). Lists made ahead, each a timestamp and its +//! way into memory the PC reads, go ahead of and behind every submission +//! while the timeline records. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use windows::core::Interface; + +use super::*; + +/// Submissions stamped (three frames have some hundred and twenty). +const MOST: usize = 1024; + +struct Stamps { + /// The first half the lists that go ahead, then those that go behind. + lists: Vec, + /// The mapping of what they write, a tick count each. + back: usize, + /// Keeps it all. + _kept: (ID3D12CommandAllocator, ID3D12QueryHeap, ID3D12Resource), + /// The card's ticks and the PC's counter at one moment. + calibrated: (u64, u64), +} + +// SAFETY: free-threaded objects, and a mapping only read. +unsafe impl Send for Stamps {} +// SAFETY: as above. +unsafe impl Sync for Stamps {} + +static STAMPS: OnceLock> = OnceLock::new(); +static NEXT: AtomicUsize = AtomicUsize::new(0); + +/// Makes the lists, before the recording begins. +pub(crate) fn timeline_ready() { + let Some(host) = host() else { + return; + }; + STAMPS.get_or_init(|| match host.make_stamps() { + Ok(stamps) => Some(stamps), + Err(e) => { + tracing::warn!(error = %e, "the timeline is without the card's times"); + None + } + }); +} + +/// The place of the next submission's stamps, if the timeline records. +pub(super) fn take() -> Option { + if !crate::timeline::on() || STAMPS.get()?.is_none() { + return None; + } + let at = NEXT.fetch_add(1, Ordering::Relaxed); + (at < MOST).then_some(at) +} + +/// The list that goes ahead of the submission at `at`, and the one behind. +pub(super) fn lists(at: usize) -> Option<(ID3D12CommandList, ID3D12CommandList)> { + let stamps = STAMPS.get()?.as_ref()?; + Some((stamps.lists[at].clone(), stamps.lists[MOST + at].clone())) +} + +/// By place, from when to when a submission ran on the card, in ticks of +/// the PC's counter. Once the card has run them. +pub(crate) fn timeline_stamps() -> Vec<(u64, u64)> { + times(NEXT.load(Ordering::Relaxed).min(MOST)) +} + +/// The stamps are used from the first again, for the next timeline. +pub(crate) fn timeline_restart() { + if let Some(Some(stamps)) = STAMPS.get() { + // SAFETY: the mapping holds twice `MOST` tick counts; the card wrote + // them some frames ago. + unsafe { std::ptr::write_bytes(stamps.back as *mut u8, 0, 16 * MOST) }; + } + NEXT.store(0, Ordering::Relaxed); +} + +/// The first `taken` of them. +fn times(taken: usize) -> Vec<(u64, u64)> { + let (Some(Some(stamps)), Some(host)) = (STAMPS.get(), host()) else { + return Vec::new(); + }; + let (mut card, mut pc) = (0, 0); + // SAFETY: plain queries; the mapping holds twice `MOST` tick counts. + let (frequency, back) = unsafe { + if host.queue.GetClockCalibration(&mut card, &mut pc).is_err() { + return Vec::new(); + } + let frequency = host.queue.GetTimestampFrequency().unwrap_or(0); + (frequency, std::slice::from_raw_parts(stamps.back as *const u64, 2 * MOST)) + }; + if frequency == 0 { + return Vec::new(); + } + // By the two calibrations, the card's clock as it ran between them. + let (card0, pc0) = stamps.calibrated; + let rate = match card.saturating_sub(card0) { + 0 => 1e7 / frequency as f64, + passed => pc.saturating_sub(pc0) as f64 / passed as f64, + }; + let place = |ticks: u64| (pc0 as f64 + (ticks as f64 - card0 as f64) * rate) as u64; + (0..taken) + .map(|at| match (back[at], back[MOST + at]) { + (0, _) | (_, 0) => (0, 0), + (from, to) => (place(from), place(to)), + }) + .collect() +} + +impl Host { + fn make_stamps(&self) -> windows::core::Result { + let Some((buffer, back)) = self.shared_buffer(16 * MOST as u64) else { + return Err(windows::core::Error::from(windows::Win32::Foundation::E_OUTOFMEMORY)); + }; + // SAFETY: plain object creation; a fresh mapping of that size. + unsafe { + std::ptr::write_bytes(back, 0, 16 * MOST); + let mut heap: Option = None; + self.device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2 * MOST as u32, + NodeMask: 0, + }, + &mut heap, + )?; + let heap = heap.ok_or_else(windows::core::Error::empty)?; + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let mut lists = Vec::with_capacity(2 * MOST); + for at in 0..2 * MOST as u32 { + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, at); + list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, at, 1, &buffer, u64::from(at) * 8); + list.Close()?; + lists.push(list.cast()?); + } + let (mut card, mut pc) = (0, 0); + self.queue.GetClockCalibration(&mut card, &mut pc)?; + Ok(Stamps { + lists, + back: back as usize, + _kept: (allocator, heap, buffer), + calibrated: (card, pc), + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What goes ahead of and behind a submission says when it ran, by the + /// PC's own counter. + #[test] + fn a_submissions_times_are_the_pcs() { + let Some(host) = host() else { + return; + }; + timeline_ready(); + let Some((ahead, behind)) = lists(5) else { + return; + }; + let sent = crate::timeline::ticks(); + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + *submitted += 1; + // SAFETY: closed lists; the fence and event are the host's, under + // its lock. + unsafe { + host.queue.ExecuteCommandLists(&[Some(ahead), Some(behind)]); + host.queue.Signal(&host.fence, *submitted).unwrap(); + host.fence.SetEventOnCompletion(*submitted, host.event).unwrap(); + WaitForSingleObject(host.event, INFINITE); + } + } + let done = crate::timeline::ticks(); + let times = times(6); + assert_eq!(times[4], (0, 0), "not run"); + let (from, to) = times[5]; + // (The two clocks agree to some tens of microseconds.) + let near = 2_000; + assert!(from <= to && from + near >= sent && to <= done + near, "{sent} {from} {to} {done}"); + } +} diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs index 4d207f4..0bc5d5f 100644 --- a/crates/victory-gpu/src/land.rs +++ b/crates/victory-gpu/src/land.rs @@ -254,8 +254,10 @@ impl Pool { }; state.running += 1; drop(state); + let working = crate::timeline::span("a landing's job"); // SAFETY: counted in `running`, so `each` has not returned. let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) })); + working.end(); state = self.state(); state.running -= 1; state.panicked |= ran.is_err(); @@ -272,6 +274,7 @@ impl Pool { (0..count).for_each(f); return; } + let _spread = crate::timeline::span("landing: spread over threads"); let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: the lifetime is left out only until this call returns, and // it does not before no helper is inside `f` and none can enter. diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 045e5d6..29947a7 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -68,10 +68,13 @@ mod shadow; mod tiles; pub mod signature; mod switch; +#[cfg(all(windows, feature = "diagnostics"))] +mod ab; #[cfg(windows)] mod tdr; #[cfg(windows)] mod texture; +pub mod timeline; #[cfg(windows)] mod upload; #[cfg(windows)] @@ -80,6 +83,13 @@ mod watch; #[cfg(windows)] pub use host::on_failure; +/// Whether `switch` is on now, if it is one of those `VICTORY_AB` turns on and +/// off while the title runs (`ab`). +#[cfg(all(windows, feature = "diagnostics"))] +pub fn switched(switch: &str) -> Option { + ab::pick(switch) +} + /// What the frame is at (`copystat::phase`), for the sampling profiler. #[cfg(all(windows, feature = "diagnostics"))] pub fn frame_phase() -> u32 { diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 4c5fa52..52c49b0 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -621,6 +621,7 @@ extern "system" fn list_type(this: This) -> u32 { unsafe { (*this.cast::()).kind } } extern "system" fn close(this: This) -> HRESULT { + let _called = crate::timeline::span("the title's Close"); #[cfg(windows)] if let Some(host) = host_list(this) { host.close(); @@ -631,6 +632,7 @@ extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT if allocator.is_null() { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's list Reset"); // A wait recorded and never submitted goes with the recording. VALUE_WAITS .lock() diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index bd80ec5..90ec3d8 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -320,6 +320,7 @@ pub(crate) fn release_held(all: bool) { if lock(&WAITING).is_empty() { return; } + let _looking = crate::timeline::span("looking at what queues hold"); let _one = lock(&RELEASING); loop { let queues = lock(&WAITING).clone(); @@ -549,6 +550,9 @@ extern "system" fn execute(this: This, count: u32, lists: *const This) { if lists.is_null() { return; } + let _called = crate::timeline::span("the title's ExecuteCommandLists"); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::title_thread(); #[cfg(windows)] if let Some(host) = crate::host::host() { // SAFETY: the title passes `count` lists. @@ -650,6 +654,7 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's queue Signal"); #[cfg(windows)] if behind::on() && !this.is_null() { behind::signal(this, fence, value); @@ -680,6 +685,7 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's queue Wait"); #[cfg(windows)] if !this.is_null() { let now = crate::fence::completed(fence); @@ -767,6 +773,8 @@ impl Written { } Written::SystemTimestamp => system_timestamp(), }; + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::told("written when its list had run", at as usize, value); // SAFETY: the title names writable GPU memory (unified with ours). unsafe { if bytes == 4 { @@ -837,6 +845,9 @@ extern "system" fn present( let _ = this; #[cfg(all(windows, feature = "diagnostics"))] crate::copystat::present_begins(); + let called = crate::timeline::span("the title's Present"); + #[cfg(all(windows, feature = "diagnostics"))] + crate::timeline::title_thread(); // Submissions sent to the card and not waited for are settled first, // and what that frees runs in its own order, before anything is forced. #[cfg(windows)] @@ -917,6 +928,9 @@ extern "system" fn present( }; let resource = texture.as_ref().map_or(0, |t| t.0); behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource }); + called.end(); + #[cfg(feature = "diagnostics")] + frame_ends(); return S_OK; } #[cfg(windows)] @@ -939,8 +953,23 @@ extern "system" fn present( } #[cfg(not(windows))] let _ = (planes, plane_parameters); + called.end(); + #[cfg(all(windows, feature = "diagnostics"))] + frame_ends(); S_OK } + +/// Diagnostics: the title's present is over. +#[cfg(all(windows, feature = "diagnostics"))] +fn frame_ends() { + crate::timeline::presented(); + crate::ab::presented(|switch, was, will| { + if switch == "VICTORY_ASYNC_SUBMIT" && was && !will { + behind::leave(); + } + }); +} + /// The frame a present shows, and the title's resource it shows. #[cfg(windows)] #[derive(Clone, Copy)] @@ -1037,6 +1066,7 @@ extern "system" fn copy_page_mappings( if batches.is_null() && count > 0 { return E_INVALIDARG; } + let _called = crate::timeline::span("the title's CopyPageMappings"); 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/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index 69dbdd9..b2f3de7 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -340,6 +340,12 @@ impl Work for Job { fn go(self, forced: bool) { let began = Instant::now(); + let _doing = crate::timeline::span(match self { + Job::Run(..) => "the line: a submission", + Job::Present(..) => "the line: a present", + Job::Signal(..) => "the line: a signal", + _ => "the line: a wait that is met", + }); if forced { STATS[FORCED].fetch_add(1, Relaxed); #[cfg(feature = "diagnostics")] @@ -426,11 +432,27 @@ thread_local! { /// (`VICTORY_ASYNC_SUBMIT=1`; needs flights with the present sent ahead, as /// the relay has them, and lists cut at their waits). pub(super) fn on() -> bool { + // Diagnostics: on and off while the title runs (`crate::ab`). + #[cfg(feature = "diagnostics")] + if let Some(on) = crate::ab::pick("VICTORY_ASYNC_SUBMIT") { + return on && started(); + } + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") && started()) +} + +/// The line is about to be left for the way without it: everything in it is +/// done first. (At a present, by the title's thread that submits.) +#[cfg(feature = "diagnostics")] +pub(super) fn leave() { + LANE.wait_presents(0); + LANE.drain(); +} + +/// Starts the thread, once: whether there is one. +fn started() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| { - if !std::env::var_os("VICTORY_ASYNC_SUBMIT").is_some_and(|v| v == "1") { - return false; - } if !crate::host::late_free_present() || !super::cuts() { tracing::warn!("VICTORY_ASYNC_SUBMIT=1 needs the relay and lists cut at their waits: submissions are prepared by the thread that makes them"); return false; @@ -528,6 +550,7 @@ pub(super) fn submit(this: This, lists: &[This]) { LANE.push(queue, jobs); if before + runs > runs_most() as u64 { let began = Instant::now(); + let _waiting = crate::timeline::span("a submission waits for room in the line"); LANE.wait_runs(runs_most()); STATS[ROOM].fetch_add(began.elapsed().as_micros() as u64, Relaxed); } @@ -558,6 +581,7 @@ pub(super) fn present(this: This, texture: Option<(std::sync::Arc, + /// The texture's flags (asked once: the runtime takes 100 ns to say, and + /// every texture of every draw is asked about). + flags: u32, } /// What a host copy was filled with last: the first level of it and the @@ -1627,7 +1630,10 @@ fn hosted(this: This, make: bool) -> Option { // are made before the next submission runs. crate::descriptor::texture_made(this as usize); } - r.host.used.store(crate::host::moment(), Relaxed); + let now = crate::host::moment(); + if r.host.used.load(Relaxed) != now { + r.host.used.store(now, Relaxed); + } made.clone() } @@ -2268,9 +2274,15 @@ fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> #[cfg(windows)] impl HostTexture { + pub(crate) fn flags(&self) -> u32 { + self.flags + } + fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { use std::sync::atomic::Ordering::Relaxed; let bytes = host_bytes(&texture); + // SAFETY: a live texture. + let flags = unsafe { texture.GetDesc() }.Flags.0 as u32; HOST_TEXTURES[0].fetch_add(1, Relaxed); HOST_TEXTURES[1].fetch_add(bytes, Relaxed); HostTexture { @@ -2283,6 +2295,7 @@ impl HostTexture { serial: SERIAL.fetch_add(1, Relaxed) + 1, grown: Default::default(), holds: Default::default(), + flags, } } @@ -2294,6 +2307,8 @@ impl HostTexture { tiled: crate::tiles::Tiled, ) -> HostTexture { HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // SAFETY: a live texture. + let flags = unsafe { texture.GetDesc() }.Flags.0 as u32; HostTexture { texture, state: std::sync::atomic::AtomicU32::new(state), @@ -2304,6 +2319,7 @@ impl HostTexture { serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1, grown: Default::default(), holds: Default::default(), + flags, } } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index abc75c1..671d6d8 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -26,6 +26,8 @@ use crate::watch::PAGE; /// A title buffer's host copy. pub(crate) struct Shadow { + /// The bytes of `buffer`, once asked. + width: std::sync::OnceLock, pub(crate) buffer: ID3D12Resource, data: *mut u8, gpu: u64, @@ -1465,6 +1467,7 @@ fn workers() -> &'static Workers { jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); } }; + let _working = crate::timeline::span("a job for another thread"); job(); } }); @@ -1483,6 +1486,7 @@ fn wide(jobs: Vec) { return; } let workers = workers(); + let _wide = crate::timeline::span("work spread over threads"); let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); { let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); @@ -2739,11 +2743,18 @@ impl Shadow { list.defer_refresh(self, address as usize, len as usize); } + /// The bytes of the host buffer. + pub(crate) fn width(&self) -> u64 { + // SAFETY: a live buffer. + *self.width.get_or_init(|| unsafe { self.buffer.GetDesc() }.Width) + } + fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; LIVE[0].fetch_add(1, Ordering::Relaxed); LIVE[1].fetch_add(len, Ordering::Relaxed); Shadow { + width: Default::default(), buffer, data, gpu, @@ -4376,7 +4387,63 @@ struct Entry { 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()) + let map = BUFFERS.write().unwrap_or_else(|e| e.into_inner()); + // What threads remember of it ([`FOUND`]) is of before. + BUFFERS_CHANGED.fetch_add(1, Ordering::SeqCst); + map +} + +/// How often [`BUFFERS`] was taken to be changed. +static BUFFERS_CHANGED: AtomicU64 = AtomicU64::new(1); + +/// Answers a thread remembers. +const FOUND_MOST: usize = 1024; + +/// An ask (address, bytes), the count of changes it was answered at, and the +/// answer. +type Found = (u64, u64, u64, std::sync::Weak); + +thread_local! { + /// The last answers of [`lookup`] out of [`BUFFERS`], by a hash of the + /// ask: the same buffers are asked about draw after draw, from five + /// threads, each time through the map's lock and a dozen of its nodes + /// (7 % of the recording threads' time, profile waits-1). + static FOUND: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Whether [`FOUND`] is kept (`VICTORY_QUICK_FIND=0`: not). +fn quick_find() -> bool { + crate::toggled!("VICTORY_QUICK_FIND") +} + +fn found_at(address: u64, len: u64) -> usize { + let h = (address ^ len.rotate_left(32)).wrapping_mul(0x9E37_79B9_7F4A_7C15); + (h >> 54) as usize % FOUND_MOST +} + +/// What this thread remembers of an ask, if nothing changed since. +fn found(address: u64, len: u64) -> Option> { + let changed = BUFFERS_CHANGED.load(Ordering::SeqCst); + let shadow = FOUND.with(|f| { + let f = f.borrow(); + let (a, n, at, shadow) = f.get(found_at(address, len))?; + ((*a, *n, *at) == (address, len, changed)).then(|| shadow.upgrade()).flatten() + })?; + // Whoever takes the map to let a copy go that nobody holds finds it held + // now, or had counted before: then it is not handed out. + std::sync::atomic::fence(Ordering::SeqCst); + (BUFFERS_CHANGED.load(Ordering::SeqCst) == changed).then_some(shadow) +} + +/// Remembers an answer given while `changed` was the count. +fn remember(address: u64, len: u64, changed: u64, shadow: &Arc) { + FOUND.with(|f| { + let mut f = f.borrow_mut(); + if f.is_empty() { + f.resize_with(FOUND_MOST, || (0, 0, 0, std::sync::Weak::new())); + } + f[found_at(address, len)] = (address, len, changed, Arc::downgrade(shadow)); + }); } fn buffers_read() -> std::sync::RwLockReadGuard<'static, BTreeMap<(u64, usize), Entry>> { @@ -4492,12 +4559,22 @@ pub(crate) fn peek(address: u64, len: u64) -> Option> { } fn lookup(address: u64, len: u64, any: bool) -> Option> { + let quick = quick_find(); + if quick && let Some(shadow) = found(address, len) { + return Some(shadow); + } let end = address.checked_add(len.max(1))?; { let map = buffers_read(); match map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end) { // The copy is made already (nearly always). - Some((_, Entry { shadow: Some(shadow), .. })) => return Some(shadow.clone()), + Some((_, Entry { shadow: Some(shadow), .. })) => { + if quick { + // (Nobody changes the map while this lock is held.) + remember(address, len, BUFFERS_CHANGED.load(Ordering::SeqCst), shadow); + } + return Some(shadow.clone()); + } Some(_) => {} None => { drop(map); @@ -4792,9 +4869,17 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option address { + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + } + if shadow.asked[1].load(Ordering::Relaxed) < end { + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + } if unsized_ask { shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); } diff --git a/crates/victory-gpu/src/switch.rs b/crates/victory-gpu/src/switch.rs index f3ea9b9..b5ef277 100644 --- a/crates/victory-gpu/src/switch.rs +++ b/crates/victory-gpu/src/switch.rs @@ -15,6 +15,33 @@ pub(crate) fn on(name: &str) -> bool { value_is_on(std::env::var_os(name).as_deref()) } +/// A switch that is on unless its variable is `0`, read once; with +/// `VICTORY_AB` naming it (diagnostics builds, `crate::ab`), on and off while +/// the title runs. +#[cfg(windows)] +#[macro_export] +#[doc(hidden)] +macro_rules! toggled { + ($name:literal) => {{ + #[cfg(feature = "diagnostics")] + { + static BIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + match BIT.get_or_init(|| match $crate::ab::bit($name) { + Some(bit) => Err(bit), + None => Ok(std::env::var_os($name).is_none_or(|v| v != "0")), + }) { + Ok(on) => *on, + Err(bit) => $crate::ab::on(*bit), + } + } + #[cfg(not(feature = "diagnostics"))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os($name).is_none_or(|v| v != "0")) + } + }}; +} + #[cfg(test)] mod tests { use super::value_is_on; diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index dc7bad1..365d024 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -1155,6 +1155,7 @@ impl Staging { pub(crate) fn refresh(&self) { use std::sync::atomic::Ordering::Relaxed; let started = std::time::Instant::now(); + let _texture = crate::timeline::span("a texture's refresh"); let read = self.refresh_now(); let preparing = &crate::host::PREPARING; preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); diff --git a/crates/victory-gpu/src/timeline.rs b/crates/victory-gpu/src/timeline.rs new file mode 100644 index 0000000..3bdbcf7 --- /dev/null +++ b/crates/victory-gpu/src/timeline.rs @@ -0,0 +1,57 @@ +//! Diagnostics: a timeline of a few frames. `VICTORY_TIMELINE=` writes +//! one, from the first present after `VICTORY_TIMELINE_AT` seconds (60) on +//! and for `VICTORY_TIMELINE_FRAMES` frames (3); +//! `VICTORY_TIMELINE=[+..],,` one for each of +//! the times (each in a file of its own, the second in its name): a Chrome trace (JSON, for +//! `chrome://tracing` or Perfetto) and beside it a text summary (`.txt`) +//! with the chain of work and waits each frame's present came out of. +//! +//! What is recorded while it runs, by every thread: +//! - spans of ours ([`span`]): the title's calls, the submitting thread's +//! stages, the relay's, the pools' jobs, texture and streaming work; +//! - waits and the wake-ups that end them ([`hooks`]): the functions the +//! title's threads wait with (its imports are bound to wrappers) and those +//! our own code does (the entries of our own import table: every contended +//! lock, condition and park of the standard library is a `WaitOnAddress`), +//! each with the thread that woke it and where it waited; +//! - kernel calls on the address space that took long; +//! - the card: when each submission began and ended on it (timestamps). +//! +//! Without the variable nothing is wrapped and a span is one load of a +//! flag; a build without `diagnostics` has nothing of it. + +#[cfg(all(windows, feature = "diagnostics"))] +mod hooks; +#[cfg(all(windows, feature = "diagnostics"))] +mod record; +#[cfg(all(windows, feature = "diagnostics"))] +mod report; + +#[cfg(all(windows, feature = "diagnostics"))] +pub use hooks::import; +#[cfg(all(windows, feature = "diagnostics"))] +pub use record::{Span, span}; +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) use record::{called, card_wait, on, polled, presented, sent, ticks, title_thread, told}; + +/// A span of ours: from where it is made until it is dropped. +#[cfg(not(all(windows, feature = "diagnostics")))] +pub struct Span; + +#[cfg(not(all(windows, feature = "diagnostics")))] +impl Span { + /// The span ends here and another begins. + #[inline(always)] + pub fn next(&mut self, _name: &'static str) {} + + /// The span ends here. + #[inline(always)] + pub fn end(self) {} +} + +/// A span named `name`. +#[cfg(not(all(windows, feature = "diagnostics")))] +#[inline(always)] +pub fn span(_name: &'static str) -> Span { + Span +} diff --git a/crates/victory-gpu/src/timeline/hooks.rs b/crates/victory-gpu/src/timeline/hooks.rs new file mode 100644 index 0000000..83afa26 --- /dev/null +++ b/crates/victory-gpu/src/timeline/hooks.rs @@ -0,0 +1,322 @@ +//! The wrappers around what threads wait and wake each other with. The +//! title's imports are bound to them ([`import`]), and the entries of our +//! own import table point at them, if a timeline was asked for; else nothing +//! is wrapped. While nothing is recorded a wrapper is a load and a jump. + +use std::ffi::{CStr, c_void}; +use std::sync::Once; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::record::{kernel, on, standing, stood_at, ticks, waited, woken}; + +type Handle = *mut c_void; + +macro_rules! wrapped { + ($($index:literal $name:ident ($($arg:ident: $type:ty),*) $(-> $result:ty)? => $body:expr;)*) => { + /// The functions wrapped, by name: their own addresses, ours. + static TABLE: [(&str, AtomicUsize, usize); [$($index),*].len()] = [ + $((stringify!($name), AtomicUsize::new(0), $index)),* + ]; + + fn wrapper(index: usize) -> usize { + match index { + $($index => wrappers::$name as *const () as usize,)* + _ => 0, + } + } + + #[allow(non_snake_case)] + mod wrappers { + use super::*; + $( + pub(super) unsafe extern "system" fn $name($($arg: $type),*) $(-> $result)? { + // SAFETY: the function of that name, as the system has it + // (or the module the title imports it from). + let real: unsafe extern "system" fn($($type),*) $(-> $result)? = + unsafe { std::mem::transmute(TABLE[$index].1.load(Ordering::Relaxed)) }; + if !on() { + // SAFETY: the caller's own call. + return unsafe { real($($arg),*) }; + } + ($body)(real) + } + )* + } + }; +} + +/// Runs `call`, a wait on `object` that may be long; what the caller may +/// ask [`GetLastError`] about stays. +/// +/// [`GetLastError`]: windows_sys::Win32::Foundation::GetLastError +fn wait(name: &'static str, object: u64, call: impl FnOnce() -> T) -> T { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + let t0 = ticks(); + let result = { + let _standing = standing(object); + call() + }; + // SAFETY: plain queries of this thread's own. + unsafe { + let error = GetLastError(); + waited(name, object, t0); + SetLastError(error); + } + result +} + +/// Runs `call`, a call of the kernel's on `bytes`. +fn measured(name: &'static str, bytes: usize, call: impl FnOnce() -> T) -> T { + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + let t0 = ticks(); + let result = call(); + // SAFETY: plain queries of this thread's own. + unsafe { + let error = GetLastError(); + kernel(name, bytes as u64, t0); + SetLastError(error); + } + result +} + +/// The function `name` of the table, as the system has it. +fn real(name: &str) -> usize { + TABLE.iter().find(|t| t.0 == name).map_or(0, |t| t.1.load(Ordering::Relaxed)) +} + +/// `take(lock)`, a try that does not wait, then `wait`. +fn lock_of(name: &'static str, lock: Handle, take: &str, call: impl FnOnce()) { + let take = real(take); + if take != 0 { + // SAFETY: `TryEnterCriticalSection` or a `TryAcquireSRWLock` call: + // one pointer, a truth value (one byte of it for the latter). + let taken = unsafe { std::mem::transmute:: u8>(take)(lock) }; + if taken != 0 { + return; + } + } + wait(name, lock as u64, call); +} + +fn released(name: &'static str, object: Handle) { + if stood_at(object as u64) { + woken(name, object as u64); + } +} + +wrapped! { + 0 WaitForSingleObject(object: Handle, ms: u32) -> u32 => |real: unsafe extern "system" fn(Handle, u32) -> u32| { + // SAFETY: the caller's own call (so below). + wait("WaitForSingleObject", object as u64, || unsafe { real(object, ms) }) + }; + 1 WaitForSingleObjectEx(object: Handle, ms: u32, alertable: i32) -> u32 => |real: unsafe extern "system" fn(Handle, u32, i32) -> u32| { + wait("WaitForSingleObjectEx", object as u64, || unsafe { real(object, ms, alertable) }) + }; + 2 Sleep(ms: u32) => |real: unsafe extern "system" fn(u32)| { + wait("Sleep", 0, || unsafe { real(ms) }) + }; + 3 SleepEx(ms: u32, alertable: i32) -> u32 => |real: unsafe extern "system" fn(u32, i32) -> u32| { + wait("SleepEx", 0, || unsafe { real(ms, alertable) }) + }; + 4 SetEvent(object: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + woken("SetEvent", object as u64); + unsafe { real(object) } + }; + 5 ReleaseSemaphore(object: Handle, count: i32, before: *mut i32) -> i32 => |real: unsafe extern "system" fn(Handle, i32, *mut i32) -> i32| { + woken("ReleaseSemaphore", object as u64); + unsafe { real(object, count, before) } + }; + 6 ReleaseMutex(object: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + woken("ReleaseMutex", object as u64); + unsafe { real(object) } + }; + 7 EnterCriticalSection(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + lock_of("EnterCriticalSection", lock, "TryEnterCriticalSection", || unsafe { real(lock) }) + }; + 8 LeaveCriticalSection(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("LeaveCriticalSection", lock); + unsafe { real(lock) } + }; + 9 AcquireSRWLockExclusive(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + lock_of("AcquireSRWLockExclusive", lock, "TryAcquireSRWLockExclusive", || unsafe { real(lock) }) + }; + 10 ReleaseSRWLockExclusive(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("ReleaseSRWLockExclusive", lock); + unsafe { real(lock) } + }; + 11 AcquireSRWLockShared(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + lock_of("AcquireSRWLockShared", lock, "TryAcquireSRWLockShared", || unsafe { real(lock) }) + }; + 12 ReleaseSRWLockShared(lock: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("ReleaseSRWLockShared", lock); + unsafe { real(lock) } + }; + 13 WaitOnAddress(at: Handle, compare: Handle, size: usize, ms: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, usize, u32) -> i32| { + wait("WaitOnAddress", at as u64, || unsafe { real(at, compare, size, ms) }) + }; + 14 WakeByAddressSingle(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeByAddressSingle", at); + unsafe { real(at) } + }; + 15 WakeByAddressAll(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeByAddressAll", at); + unsafe { real(at) } + }; + 16 SleepConditionVariableSRW(at: Handle, lock: Handle, ms: u32, flags: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, u32, u32) -> i32| { + wait("SleepConditionVariableSRW", at as u64, || unsafe { real(at, lock, ms, flags) }) + }; + 17 SleepConditionVariableCS(at: Handle, lock: Handle, ms: u32) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, u32) -> i32| { + wait("SleepConditionVariableCS", at as u64, || unsafe { real(at, lock, ms) }) + }; + 18 WakeConditionVariable(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeConditionVariable", at); + unsafe { real(at) } + }; + 19 WakeAllConditionVariable(at: Handle) => |real: unsafe extern "system" fn(Handle)| { + released("WakeAllConditionVariable", at); + unsafe { real(at) } + }; + 20 WaitForMultipleObjects(count: u32, objects: *const Handle, all: i32, ms: u32) -> u32 => |real: unsafe extern "system" fn(u32, *const Handle, i32, u32) -> u32| { + // (Named by the first of them.) + // SAFETY: the caller passes `count` handles. + let first = if count > 0 && !objects.is_null() { (unsafe { *objects }) as u64 } else { 0 }; + wait("WaitForMultipleObjects", first, || unsafe { real(count, objects, all, ms) }) + }; + 21 GetWriteWatch(flags: u32, at: Handle, size: usize, found: Handle, count: Handle, granularity: Handle) -> u32 => |real: unsafe extern "system" fn(u32, Handle, usize, Handle, Handle, Handle) -> u32| { + measured("GetWriteWatch", size, || unsafe { real(flags, at, size, found, count, granularity) }) + }; + 22 VirtualProtect(at: Handle, size: usize, new: u32, old: Handle) -> i32 => |real: unsafe extern "system" fn(Handle, usize, u32, Handle) -> i32| { + measured("VirtualProtect", size, || unsafe { real(at, size, new, old) }) + }; + 23 ReadProcessMemory(process: Handle, at: Handle, to: Handle, size: usize, done: Handle) -> i32 => |real: unsafe extern "system" fn(Handle, Handle, Handle, usize, Handle) -> i32| { + measured("ReadProcessMemory", size, || unsafe { real(process, at, to, size, done) }) + }; + 24 VirtualQuery(at: Handle, info: Handle, size: usize) -> usize => |real: unsafe extern "system" fn(Handle, Handle, usize) -> usize| { + measured("VirtualQuery", 0, || unsafe { real(at, info, size) }) + }; + 25 VirtualAlloc(at: Handle, size: usize, kind: u32, protect: u32) -> Handle => |real: unsafe extern "system" fn(Handle, usize, u32, u32) -> Handle| { + measured("VirtualAlloc", size, || unsafe { real(at, size, kind, protect) }) + }; + 26 VirtualFree(at: Handle, size: usize, kind: u32) -> i32 => |real: unsafe extern "system" fn(Handle, usize, u32) -> i32| { + measured("VirtualFree", size, || unsafe { real(at, size, kind) }) + }; + 27 _Mtx_lock(lock: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + wait("_Mtx_lock", lock as u64, || unsafe { real(lock) }) + }; + 28 _Mtx_unlock(lock: Handle) -> i32 => |real: unsafe extern "system" fn(Handle) -> i32| { + released("_Mtx_unlock", lock); + unsafe { real(lock) } + }; + 29 TryEnterCriticalSection(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) }; + 30 TryAcquireSRWLockExclusive(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) }; + 31 TryAcquireSRWLockShared(lock: Handle) -> u8 => |real: unsafe extern "system" fn(Handle) -> u8| unsafe { real(lock) }; +} + +/// The wrappers from here on are there for their real functions only. +const ONLY_REAL: usize = 29; + +/// Asks the system for the real functions, and points our own import table +/// at the wrappers: once, if a timeline is wanted. +fn arm() -> bool { + static ONCE: Once = Once::new(); + if !super::record::wanted() { + return false; + } + ONCE.call_once(wrap_own); + true +} + +/// See [`arm`]. +pub(super) fn wrap_own() { + find_real(); + // SAFETY: our own module's mapped image. + let changed = unsafe { wrap_imports() }; + tracing::info!(changed, "the timeline's wrappers are in (VICTORY_TIMELINE)"); +} + +fn find_real() { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + for dll in [c"kernelbase.dll", c"kernel32.dll", c"ntdll.dll"] { + // SAFETY: NUL-terminated names of modules every process has. + let module = unsafe { GetModuleHandleA(dll.as_ptr().cast()) }; + for (name, at, _) in &TABLE { + if at.load(Ordering::Relaxed) == 0 && !module.is_null() { + let text = std::ffi::CString::new(*name).expect("a plain name"); + // SAFETY: as above. + if let Some(f) = unsafe { GetProcAddress(module, text.as_ptr().cast()) } { + at.store(f as *const () as usize, Ordering::Relaxed); + } + } + } + } +} + +/// What the title's import `name`, found at `address`, is bound to: the +/// address itself, or our wrapper of it. +pub fn import(name: &str, address: usize) -> usize { + if !arm() { + return address; + } + let Some((i, (_, at, _))) = TABLE.iter().enumerate().find(|(i, t)| *i < ONLY_REAL && t.0 == name) else { + return address; + }; + if at.load(Ordering::Relaxed) == 0 { + at.store(address, Ordering::Relaxed); + } + wrapper(i) +} + +/// Points the entries of our own import table that are in [`TABLE`] at the +/// wrappers: how many. +/// +/// # Safety +/// The process's module is mapped as the loader left it. +unsafe fn wrap_imports() -> usize { + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + // SAFETY: a plain query. + let base = unsafe { GetModuleHandleW(std::ptr::null()) } as usize; + let mut changed = 0; + // SAFETY: the headers, the import directory and the tables it names lie + // in the mapped image, as the loader read them; an entry is eight bytes, + // aligned, and made writable for the store. + unsafe { + let at = |rva: u32| base + rva as usize; + let read = |at: usize| (at as *const u32).read_unaligned(); + let headers = at(read(base + 0x3c)); + // The second data directory of the 64-bit optional header: imports. + let mut descriptor = at(read(headers + 0x18 + 0x70 + 8)); + loop { + let (names, first) = (read(descriptor), read(descriptor + 16)); + if first == 0 { + break; + } + let names = if names != 0 { names } else { first }; + for i in 0.. { + let entry = (at(names) as *const u64).add(i).read_unaligned(); + if entry == 0 { + break; + } + if entry >> 63 != 0 { + continue; // by number + } + let name = CStr::from_ptr((at(entry as u32) + 2) as *const _); + let Some(index) = TABLE[..ONLY_REAL].iter().position(|t| t.0.as_bytes() == name.to_bytes()) else { + continue; + }; + if TABLE[index].1.load(Ordering::Relaxed) == 0 { + continue; + } + let slot = (at(first) as *mut usize).add(i); + let (mut old, mut ignored) = (0, 0); + if VirtualProtect(slot.cast(), 8, PAGE_READWRITE, &mut old) != 0 { + (*slot.cast::()).store(wrapper(index), Ordering::SeqCst); + VirtualProtect(slot.cast(), 8, old, &mut ignored); + changed += 1; + } + } + descriptor += 20; + } + } + changed +} diff --git a/crates/victory-gpu/src/timeline/record.rs b/crates/victory-gpu/src/timeline/record.rs new file mode 100644 index 0000000..fb3b517 --- /dev/null +++ b/crates/victory-gpu/src/timeline/record.rs @@ -0,0 +1,678 @@ +//! What is recorded, and when. Every event goes into one buffer made ahead: +//! a write takes a place in it (one atomic addition) and nothing else, so it +//! can be done anywhere, the handler of write faults included. + +use std::cell::Cell; +use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +/// What an event is. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Kind { + /// A span of ours. + Span, + /// A run of list calls: `a` calls, `b` ticks inside them. + Calls, + /// A wait on the object `a` (an address, or a handle's value); `b`: the + /// value of the host's fence it stands for (0: none, [`COPY_QUEUE`]). + Wait, + /// The object `a` is signalled or released. + Wake, + /// A call of the kernel's that took long; `a` its bytes. + Kernel, + /// Lists went to the card: `a` the value signalled behind them, `b` the + /// place of their timestamps plus one. + Sent, + /// A present came back: a frame ends. + Frame, + /// The title is told something: `b` is stored at `a` (a fence, or what + /// a list writes when it has run). + Told, + /// The title asked a fence (`a`) for its value and got `b`, again and + /// again from the beginning to the end. + Poll, + /// Where a thread of the title's was: `a` the instruction, the stack + /// what on its stack may be return addresses. + Sample, +} + +/// The `b` of a wait for the card's copy queue. +pub(super) const COPY_QUEUE: u64 = u64::MAX; + +#[derive(Clone, Copy, Debug)] +pub(super) struct Event { + pub(super) t0: u64, + pub(super) t1: u64, + pub(super) a: u64, + pub(super) b: u64, + pub(super) name: &'static str, + pub(super) thread: u32, + /// Its place among the stacks, plus one (0: none). + pub(super) stack: u32, + pub(super) cpu: u16, + pub(super) kind: Kind, +} + +struct Slot { + event: std::cell::UnsafeCell>, + written: AtomicBool, +} + +/// Events kept, and stacks. +const EVENTS: usize = 1 << 20; +const STACKS: usize = 1 << 16; +/// Return addresses of a stack. +pub(super) const DEPTH: usize = 14; + +static ON: AtomicBool = AtomicBool::new(false); +static SLOTS: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); +static NEXT: AtomicUsize = AtomicUsize::new(0); +static STACK: AtomicPtr<[usize; DEPTH]> = AtomicPtr::new(std::ptr::null_mut()); +static NEXT_STACK: AtomicUsize = AtomicUsize::new(0); + +/// [`ticks`] per second. +pub(super) fn frequency() -> u64 { + static TICKS: OnceLock = OnceLock::new(); + *TICKS.get_or_init(|| { + let mut ticks = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut ticks) }; + ticks.max(1) as u64 + }) +} + +/// The performance counter: the clock the card's is calibrated against. +pub(crate) fn ticks() -> u64 { + let mut ticks = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut ticks) }; + ticks as u64 +} + +pub(super) fn micros(ticks: u64) -> u64 { + ticks.saturating_mul(1_000_000) / frequency() +} + +/// Whether events are recorded now. +#[inline(always)] +pub(crate) fn on() -> bool { + ON.load(Ordering::Relaxed) +} + +pub(super) fn thread() -> u32 { + thread_local!(static ID: Cell = const { Cell::new(0) }); + ID.with(|id| { + if id.get() == 0 { + // SAFETY: a plain query. + id.set(unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }); + } + id.get() + }) +} + +/// Records an event of this thread. +pub(super) fn put(kind: Kind, name: &'static str, t: (u64, u64), a: u64, b: u64, stack: u32) { + put_of(thread(), kind, name, t, a, b, stack); +} + +/// Records an event of `thread`. +fn put_of(thread: u32, kind: Kind, name: &'static str, (t0, t1): (u64, u64), a: u64, b: u64, stack: u32) { + let slots = SLOTS.load(Ordering::Acquire); + if slots.is_null() { + return; + } + let at = NEXT.fetch_add(1, Ordering::Relaxed); + if at >= EVENTS { + return; + } + // SAFETY: a plain query. + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u16; + let event = Event { t0, t1, a, b, name, thread, stack, cpu, kind }; + // SAFETY: within the buffer, and this place was given to this call alone. + unsafe { + let slot = &*slots.add(at); + (*slot.event.get()).write(event); + slot.written.store(true, Ordering::Release); + } +} + +/// The caller's stack: its place, plus one. +fn stack() -> u32 { + let stacks = STACK.load(Ordering::Acquire); + if stacks.is_null() { + return 0; + } + let at = NEXT_STACK.fetch_add(1, Ordering::Relaxed); + if at >= STACKS { + return 0; + } + let mut frames = [0usize; DEPTH]; + // SAFETY: room for `DEPTH` return addresses; the place was given to this + // call alone. + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace( + 1, + DEPTH as u32, + frames.as_mut_ptr().cast(), + std::ptr::null_mut(), + ); + stacks.add(at).write(frames); + } + at as u32 + 1 +} + +/// Shorter spans of ours are not kept (microseconds). +const SHORTEST: u64 = 5; +/// The stack of a wait or a list call this long is kept (microseconds). +const DEEP: u64 = 50; + +/// A span of ours: from where it is made until it is dropped. +pub struct Span { + name: &'static str, + /// When it began (0: nothing is recorded). + began: u64, +} + +/// A span named `name`. +#[inline(always)] +pub fn span(name: &'static str) -> Span { + Span { + name, + began: if on() { ticks() } else { 0 }, + } +} + +impl Span { + /// The span ends here and another begins. + #[inline(always)] + pub fn next(&mut self, name: &'static str) { + self.close(); + (self.name, self.began) = (name, if on() { ticks() } else { 0 }); + } + + /// The span ends here. + #[inline(always)] + pub fn end(self) {} + + fn close(&mut self) { + let began = std::mem::take(&mut self.began); + if began != 0 { + let now = ticks(); + if micros(now - began) >= SHORTEST { + put(Kind::Span, self.name, (began, now), 0, 0, 0); + } + } + } +} + +impl Drop for Span { + #[inline(always)] + fn drop(&mut self) { + if self.began != 0 { + self.close(); + } + } +} + +/// List calls closer than this (microseconds) are one event. +const RUN_GAP: u64 = 10; + +/// A list call of the title's that took `took` has returned. +pub(crate) fn called(took: std::time::Duration) { + if !on() { + return; + } + let inside = (took.as_nanos() as u64).saturating_mul(frequency()) / 1_000_000_000; + let t1 = ticks(); + let t0 = t1 - inside; + thread_local! { + /// The run under way: from, to, calls, ticks inside them. + static RUN: Cell<(u64, u64, u64, u64)> = const { Cell::new((0, 0, 0, 0)) }; + } + RUN.with(|run| { + let (from, to, calls, sum) = run.get(); + if calls > 0 && micros(t0.saturating_sub(to)) < RUN_GAP { + run.set((from, t1, calls + 1, sum + inside)); + return; + } + if calls > 0 { + put(Kind::Calls, "list calls", (from, to), calls, sum, 0); + } + run.set((t0, t1, 1, inside)); + }); + if micros(inside) >= DEEP { + put(Kind::Span, "a long list call", (t0, t1), 0, 0, stack()); + } +} + +thread_local! { + /// What the wait this thread makes now stands for ([`card_wait`]). + static CARD: Cell = const { Cell::new(0) }; +} + +/// While it lives, this thread's waits are for the card. +pub(crate) struct CardWait(()); + +/// This thread's waits are for the card to reach `fence` (`None`: for its +/// copy queue) until what comes back is dropped. +pub(crate) fn card_wait(fence: Option) -> CardWait { + CARD.with(|c| c.set(fence.unwrap_or(COPY_QUEUE))); + CardWait(()) +} + +impl Drop for CardWait { + fn drop(&mut self) { + CARD.with(|c| c.set(0)); + } +} + +/// This thread waited on `object` with `name` since `t0`. +pub(super) fn waited(name: &'static str, object: u64, t0: u64) { + let t1 = ticks(); + let us = micros(t1 - t0); + if us >= 2 { + let stack = if us >= DEEP { stack() } else { 0 }; + put(Kind::Wait, name, (t0, t1), object, CARD.with(Cell::get), stack); + } +} + +/// `object` is about to be signalled. +pub(super) fn woken(name: &'static str, object: u64) { + let t = ticks(); + put(Kind::Wake, name, (t, t), object, 0, 0); +} + +/// A call of the kernel's on `bytes` began at `t0`. +pub(super) fn kernel(name: &'static str, bytes: u64, t0: u64) { + let t1 = ticks(); + if micros(t1 - t0) >= 20 { + put(Kind::Kernel, name, (t0, t1), bytes, 0, 0); + } +} + +/// Lists went to the card between `t0` ([`ticks`]) and now, the value +/// `fence` signalled behind them, with the timestamps at `stamp`. +pub(crate) fn sent(t0: u64, fence: u64, stamp: Option) { + if on() { + put(Kind::Sent, "ExecuteCommandLists", (t0, ticks()), fence, stamp.map_or(0, |s| s as u64 + 1), 0); + } +} + +/// `value` is being stored at `at`, where the title looks for it. +#[inline(always)] +pub(crate) fn told(name: &'static str, at: usize, value: u64) { + if on() { + let t = ticks(); + put(Kind::Told, name, (t, t), at as u64, value, 0); + } +} + +/// The title asked the fence at `at` for its value, which is `value`. +#[inline(always)] +pub(crate) fn polled(at: usize, value: u64) { + if !on() { + return; + } + thread_local! { + /// The same answer, again and again: fence, value, from, to. + static SAME: Cell<(usize, u64, u64, u64)> = const { Cell::new((0, 0, 0, 0)) }; + } + let t = ticks(); + SAME.with(|same| { + let (fence, was, from, to) = same.get(); + if (fence, was) == (at, value) && micros(t.saturating_sub(to)) < 1000 { + same.set((at, value, from, t)); + return; + } + if fence != 0 && micros(to.saturating_sub(from)) >= 100 { + put(Kind::Poll, "asks a fence", (from, to), fence as u64, was, 0); + } + same.set((at, value, t, t)); + }); +} + +/// Threads of the title's that submit or present. +static TITLES: [AtomicU32; 4] = [const { AtomicU32::new(0) }; 4]; + +/// This thread is one of the title's that submit: what it does is sampled. +#[inline(always)] +pub(crate) fn title_thread() { + if !on() { + return; + } + let id = thread(); + for place in &TITLES { + match place.load(Ordering::Relaxed) { + there if there == id => return, + 0 if place.compare_exchange(0, id, Ordering::Relaxed, Ordering::Relaxed).is_ok() => return, + _ => {} + } + } +} + +/// Looks every quarter of a millisecond where the title's submitting threads +/// are, while the recording goes on: what they do outside our calls (a loop +/// on a value in memory has no event of its own). +fn sample() { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, CONTEXT_CONTROL_AMD64, GetThreadContext}; + use windows_sys::Win32::System::Threading::{ + OpenThread, ResumeThread, SuspendThread, THREAD_GET_CONTEXT, THREAD_SUSPEND_RESUME, + }; + /// `GetThreadContext` wants a 16-byte aligned context. + #[repr(C, align(16))] + struct Aligned(CONTEXT); + let mut open: Vec<(u32, *mut std::ffi::c_void)> = Vec::new(); + while on() { + for place in &TITLES { + let id = place.load(Ordering::Relaxed); + if id == 0 { + continue; + } + let thread = match open.iter().find(|o| o.0 == id) { + Some(o) => o.1, + None => { + // SAFETY: a thread of our own process. + let handle = unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT, 0, id) }; + open.push((id, handle)); + handle + } + }; + if thread.is_null() { + continue; + } + let mut words = [0usize; 64]; + // SAFETY: zeroed is a valid CONTEXT; the thread is another one of + // this process and runs on before anything here allocates or + // locks; its stack is read from its pointer to the end of that + // page alone. + let at = unsafe { + let mut context = Aligned(std::mem::zeroed()); + context.0.ContextFlags = CONTEXT_CONTROL_AMD64; + if SuspendThread(thread) == u32::MAX { + continue; + } + let known = GetThreadContext(thread, &mut context.0) != 0; + if known { + let sp = context.0.Rsp as usize & !7; + let n = ((sp | 0xfff) + 1 - sp) / 8; + for (i, word) in words.iter_mut().enumerate().take(n) { + *word = (sp as *const usize).add(i).read_volatile(); + } + } + ResumeThread(thread); + if known { context.0.Rip as usize } else { 0 } + }; + let t = ticks(); + // What lies near the instruction may be a return address; where + // the instruction is the system's, all of it may tell something. + let mut frames = [0usize; DEPTH]; + let near = words.iter().copied().filter(|w| *w != 0 && (at >> 40 == 0x7f || w.abs_diff(at) < 0x1000_0000)); + for (frame, word) in frames.iter_mut().zip(near) { + *frame = word; + } + put_of(id, Kind::Sample, "a sample", (t, t), at as u64, 0, keep(frames)); + } + let until = ticks() + frequency() / 4000; + while ticks() < until { + std::hint::spin_loop(); + } + } + for (_, handle) in open { + // SAFETY: opened above. + unsafe { CloseHandle(handle) }; + } +} + +/// `frames` among the stacks: its place, plus one. +fn keep(frames: [usize; DEPTH]) -> u32 { + let stacks = STACK.load(Ordering::Acquire); + let at = NEXT_STACK.fetch_add(1, Ordering::Relaxed); + if stacks.is_null() || at >= STACKS { + return 0; + } + // SAFETY: the place was given to this call alone. + unsafe { stacks.add(at).write(frames) }; + at as u32 + 1 +} + +/// What was asked for. +struct Asked { + file: std::path::PathBuf, + /// Seconds after which a recording begins, for each. + after: Vec, + frames: u64, + started: std::time::Instant, +} + +/// `[+..],,`, or a file alone. +fn parse(text: &str) -> (Option<(Vec, u64)>, &str) { + let mut parts = text.splitn(3, ','); + let three = (parts.next(), parts.next(), parts.next()); + if let (Some(from), Some(frames), Some(file)) = three + && let Ok(from) = from.split('+').map(|f| f.trim().parse::()).collect::, _>>() + && let Ok(frames) = frames.trim().parse::() + { + return (Some((from, frames)), file); + } + (None, text) +} + +/// The variables, read once (before the title runs: its imports are bound +/// by them). +fn asked() -> Option<&'static Asked> { + static ASKED: OnceLock> = OnceLock::new(); + ASKED + .get_or_init(|| { + let file = std::env::var_os("VICTORY_TIMELINE").filter(|v| !v.is_empty())?; + let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); + let text = file.to_string_lossy(); + let (when, file) = parse(&text); + let (after, frames) = when.unwrap_or_else(|| { + ( + vec![number("VICTORY_TIMELINE_AT").unwrap_or(60.0)], + number("VICTORY_TIMELINE_FRAMES").map_or(3, |n| n as u64), + ) + }); + Some(Asked { + file: file.into(), + after, + frames: frames.clamp(1, 60), + started: std::time::Instant::now(), + }) + }) + .as_ref() +} + +/// Whether a timeline was asked for. +pub(super) fn wanted() -> bool { + asked().is_some() +} + +/// Where the recording is. +struct Stage { + ready: bool, + began: bool, + frames: u64, + /// Recordings made, and whether one is being written. + made: usize, + writing: bool, + before: Option, +} + +/// The title's present came back. +pub(crate) fn presented() { + let Some(asked) = asked() else { + return; + }; + static STAGE: Mutex = Mutex::new(Stage { + ready: false, + began: false, + frames: 0, + made: 0, + writing: false, + before: None, + }); + let mut stage = STAGE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(&after) = asked.after.get(stage.made) else { + return; + }; + if stage.writing || asked.started.elapsed().as_secs_f64() < after { + return; + } + if !stage.ready { + // The buffers, the card's lists and the threads' clocks take a + // while: the recording begins two frames later. + stage.ready = true; + make_room(); + crate::host::timeline_ready(); + return; + } + if !stage.began { + stage.began = true; + stage.before = Some(super::report::Threads::now()); + tracing::info!(file = %asked.file.display(), frames = asked.frames, "the timeline begins (VICTORY_TIMELINE)"); + begin(); + if std::thread::Builder::new().name("victory-sample".into()).spawn(sample).is_err() { + tracing::warn!("the timeline is without samples of the title's threads"); + } + frame(); + return; + } + frame(); + stage.frames += 1; + if stage.frames < asked.frames { + return; + } + stage.writing = true; + let before = stage.before.take().unwrap_or_default(); + // Several recordings: a file each. + let file = match asked.after.len() { + 1 => asked.file.clone(), + _ => { + let end = asked.file.extension().map_or("json".into(), |e| e.to_string_lossy().into_owned()); + asked.file.with_extension(format!("{after:.0}.{end}")) + } + }; + drop(stage); + let write = move || { + let after = super::report::Threads::now(); + // The spans under way at the last present end first. + std::thread::sleep(std::time::Duration::from_millis(250)); + let data = end(); + super::report::write(&file, data, &before, &after, crate::host::timeline_stamps()); + crate::host::timeline_restart(); + let mut stage = STAGE.lock().unwrap_or_else(|e| e.into_inner()); + (stage.began, stage.frames, stage.writing) = (false, 0, false); + stage.made += 1; + }; + if std::thread::Builder::new().name("victory-timeline".into()).spawn(write).is_err() { + tracing::warn!("no thread to write the timeline"); + } +} + +/// A frame ends now. +pub(super) fn frame() { + let t = ticks(); + put(Kind::Frame, "present", (t, t), 0, 0, 0); +} + +/// Makes the buffers (kept for good: a thread may be about to write). +pub(super) fn make_room() { + if !SLOTS.load(Ordering::Acquire).is_null() { + return; + } + fn zeroed(n: usize) -> *mut T { + let layout = std::alloc::Layout::array::(n).expect("a small number"); + // SAFETY: not of no size. + unsafe { std::alloc::alloc_zeroed(layout) }.cast() + } + STACK.store(zeroed(STACKS), Ordering::Release); + SLOTS.store(zeroed(EVENTS), Ordering::Release); +} + +/// Recording starts. +pub(super) fn begin() { + ON.store(true, Ordering::SeqCst); +} + +/// What was recorded, in no order. +pub(super) struct Data { + pub(super) events: Vec, + pub(super) stacks: Vec<[usize; DEPTH]>, + /// Events there was no room for. + pub(super) lost: usize, +} + +/// Recording ends. +pub(super) fn end() -> Data { + ON.store(false, Ordering::SeqCst); + // Those about to write do. + std::thread::sleep(std::time::Duration::from_millis(20)); + let taken = NEXT.load(Ordering::SeqCst); + TITLES.iter().for_each(|t| t.store(0, Ordering::SeqCst)); + let slots = SLOTS.load(Ordering::Acquire); + let mut events = Vec::with_capacity(taken.min(EVENTS)); + for at in 0..taken.min(EVENTS) { + // SAFETY: within the buffer; a written place is never written again. + unsafe { + let slot = &*slots.add(at); + if slot.written.load(Ordering::Acquire) { + events.push((*slot.event.get()).assume_init()); + slot.written.store(false, Ordering::Release); + } + } + } + NEXT.store(0, Ordering::SeqCst); + let count = NEXT_STACK.swap(0, Ordering::SeqCst).min(STACKS); + // SAFETY: that many were given out; each was written before the event + // that names it. + let stacks = unsafe { std::slice::from_raw_parts(STACK.load(Ordering::Acquire), count) }.to_vec(); + Data { + events, + stacks, + lost: taken.saturating_sub(EVENTS), + } +} + +/// Objects threads stand at now, by a hash of theirs: releases of a lock +/// nobody waits for are not recorded. +static STOOD_AT: [AtomicU32; 4096] = [const { AtomicU32::new(0) }; 4096]; + +fn place(object: u64) -> &'static AtomicU32 { + &STOOD_AT[(object.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 52) as usize] +} + +/// This thread is about to wait for `object`, until what comes back is +/// dropped. +pub(super) fn standing(object: u64) -> Standing { + place(object).fetch_add(1, Ordering::SeqCst); + Standing(object) +} + +/// See [`standing`]. +pub(super) struct Standing(u64); + +impl Drop for Standing { + fn drop(&mut self) { + place(self.0).fetch_sub(1, Ordering::SeqCst); + } +} + +/// Whether a thread may wait for `object`. +pub(super) fn stood_at(object: u64) -> bool { + place(object).load(Ordering::SeqCst) != 0 +} + +#[cfg(test)] +mod tests { + use super::parse; + + #[test] + fn a_timeline_is_asked_for_by_seconds_frames_and_a_file() { + assert_eq!(parse("120,20,D:/a.json"), (Some((vec![120.0], 20)), "D:/a.json")); + assert_eq!(parse("120+130.5,20,D:/a,b.json"), (Some((vec![120.0, 130.5], 20)), "D:/a,b.json")); + assert_eq!(parse("D:/a,1,2.json"), (None, "D:/a,1,2.json")); + assert_eq!(parse("D:/a.json"), (None, "D:/a.json")); + } +} diff --git a/crates/victory-gpu/src/timeline/report.rs b/crates/victory-gpu/src/timeline/report.rs new file mode 100644 index 0000000..d07a5e8 --- /dev/null +++ b/crates/victory-gpu/src/timeline/report.rs @@ -0,0 +1,957 @@ +//! What was recorded, put in order: the Chrome trace, and the text summary +//! with the chain each present came out of. + +use std::collections::{BTreeMap, HashMap}; +use std::fmt::Write as _; + +use super::record::{COPY_QUEUE, DEPTH, Data, Event, Kind, frequency}; + +/// The process's threads at a moment. +#[derive(Default)] +pub(super) struct Threads { + /// By number: its processor cycles so far, its name, where it started. + all: HashMap, + /// The processor's clock and the performance counter then. + cycles: u64, + ticks: u64, +} + +#[link(name = "kernel32")] +unsafe extern "system" { + fn QueryThreadCycleTime(thread: *mut std::ffi::c_void, cycles: *mut u64) -> i32; +} + +#[link(name = "ntdll")] +unsafe extern "system" { + fn NtQueryInformationThread( + thread: *mut std::ffi::c_void, + class: i32, + out: *mut std::ffi::c_void, + len: u32, + returned: *mut u32, + ) -> i32; +} + +impl Threads { + pub(super) fn now() -> Threads { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE, LocalFree}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetThreadDescription, OpenThread, THREAD_QUERY_INFORMATION, + }; + /// `ThreadQuerySetWin32StartAddress`. + const START: i32 = 9; + let mut threads = Threads::default(); + // SAFETY: a snapshot of our own, walked with a sized entry; handles + // opened here are closed; the name is the system's, freed as asked. + unsafe { + let own = GetCurrentProcessId(); + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + return threads; + } + let mut entry = THREADENTRY32 { + dwSize: size_of::() as u32, + ..Default::default() + }; + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == own { + let thread = OpenThread(THREAD_QUERY_INFORMATION, 0, entry.th32ThreadID); + if !thread.is_null() { + let (mut cycles, mut start, mut name) = (0, 0usize, std::ptr::null_mut()); + QueryThreadCycleTime(thread, &mut cycles); + NtQueryInformationThread(thread, START, (&raw mut start).cast(), 8, std::ptr::null_mut()); + let mut text = String::new(); + if GetThreadDescription(thread, &mut name) >= 0 && !name.is_null() { + let len = (0..).take_while(|&i| *name.add(i) != 0).count(); + text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len)); + LocalFree(name.cast()); + } + CloseHandle(thread); + threads.all.insert(entry.th32ThreadID, (cycles, text, start)); + } + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + threads.cycles = std::arch::x86_64::_rdtsc(); + } + threads.ticks = super::record::ticks(); + threads + } +} + +/// Names of addresses. +pub(super) struct Names { + known: HashMap, + symbols: Option, +} + +/// The system's symbol library (asked for when a timeline is written, not +/// at start). +struct Symbols { + from_address: unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32, + process: *mut std::ffi::c_void, +} + +impl Symbols { + fn load() -> Option { + use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + type Initialize = unsafe extern "system" fn(*mut std::ffi::c_void, *const u16, i32) -> i32; + type Options = unsafe extern "system" fn(u32) -> u32; + // SAFETY: the system's own library and functions, by their names and + // signatures. + unsafe { + let module = LoadLibraryExA(c"dbghelp.dll".as_ptr().cast(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); + if module.is_null() { + return None; + } + let options: Options = std::mem::transmute(GetProcAddress(module, c"SymSetOptions".as_ptr().cast())?); + let initialize: Initialize = std::mem::transmute(GetProcAddress(module, c"SymInitializeW".as_ptr().cast())?); + let from_address = std::mem::transmute::< + unsafe extern "system" fn() -> isize, + unsafe extern "system" fn(*mut std::ffi::c_void, u64, *mut u64, *mut u8) -> i32, + >(GetProcAddress(module, c"SymFromAddr".as_ptr().cast())?); + let process = GetCurrentProcess(); + // Undecorated names, loaded when asked for, no dialogs. + options(0x2 | 0x4 | 0x200); + // Our symbols lie beside the program, which names them by their + // file alone. (It fails if a backtrace was asked for before: + // then it is there, and looks beside every module.) + let beside = std::env::current_exe().ok().and_then(|p| Some(p.parent()?.to_path_buf())).unwrap_or_default(); + let beside: Vec = std::os::windows::ffi::OsStrExt::encode_wide(beside.as_os_str()).chain([0]).collect(); + initialize(process, beside.as_ptr(), 1); + Some(Symbols { from_address, process }) + } + } + + fn name(&self, address: usize) -> Option { + // `SYMBOL_INFO`: 88 bytes with the name's first character at 84. + const NAME: usize = 84; + const ROOM: usize = 512; + let mut info = [0u64; (NAME + ROOM) / 8 + 1]; + let at = info.as_mut_ptr().cast::(); + let mut off = 0u64; + // SAFETY: a buffer of the structure's size and the name's, its size + // fields set as asked. + unsafe { + at.cast::().write(88); + at.add(80).cast::().write(ROOM as u32); + if (self.from_address)(self.process, address as u64 - 1, &mut off, at) == 0 { + return None; + } + let name = std::ffi::CStr::from_ptr(at.add(NAME).cast()); + Some(name.to_string_lossy().into_owned()) + } + } +} + +impl Names { + pub(super) fn new() -> Names { + Names { + known: HashMap::new(), + symbols: Symbols::load(), + } + } + + /// The module `address` lies in, and where in it; whether it is ours. + fn module(address: usize) -> (String, usize, bool) { + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, + GetModuleHandleExW, GetModuleHandleW, + }; + let mut module = std::ptr::null_mut(); + let mut path = [0u16; 260]; + // SAFETY: an address, no name; plain queries. + unsafe { + let flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; + if GetModuleHandleExW(flags, address as *const u16, &mut module) == 0 { + return ("?".into(), address, false); + } + let len = GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) as usize; + let path = String::from_utf16_lossy(&path[..len]); + let file = path.rsplit('\\').next().unwrap_or("?").to_string(); + (file, address - module as usize, module == GetModuleHandleW(std::ptr::null())) + } + } + + /// A name for `address`: our own functions by their names, others by + /// their module and place in it. + fn of(&mut self, address: usize) -> String { + if let Some(name) = self.known.get(&address) { + return name.clone(); + } + let (file, at, ours) = Self::module(address); + let name = match self.symbols.as_ref().filter(|_| ours).and_then(|s| s.name(address)) { + Some(name) => name, + None => format!("{}+{at:#x}", file.strip_suffix(".dll").unwrap_or(&file)), + }; + self.known.insert(address, name.clone()); + name + } + + /// Where a stack says the thread was: the innermost functions that are + /// not the standard library's or this module's. + fn site(&mut self, stack: &[usize; DEPTH]) -> String { + let mut parts: Vec = Vec::new(); + for &address in stack.iter().take_while(|a| **a != 0) { + let name = self.of(address); + let plain = name.trim_start_matches('<').trim_start_matches("impl$").trim_start_matches(|c: char| c.is_ascii_digit()); + let skipped = ["std::", "core::", "alloc::", "windows_core::", "windows::"].iter().any(|p| plain.starts_with(p)) + || ["timeline::hooks::", "timeline::record::"].iter().any(|p| name.contains(p)) + || ["KERNEL", "ntdll", "kernel"].iter().any(|p| name.starts_with(p)); + if !skipped { + parts.push(name.replace("victory_gpu::", "").replace("victory_hle::", "hle::")); + } + if parts.len() == 3 { + break; + } + } + parts.join(" < ") + } +} + +/// A part of a chain: what was done, or waited for, from when to when. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Part { + pub(super) from: u64, + pub(super) to: u64, + /// The thread (0: the card). + pub(super) thread: u32, + pub(super) cause: String, +} + +/// A wait that ended, as the chains see it. +#[derive(Clone, Copy, Debug)] +struct Wait { + t0: u64, + t1: u64, + object: u64, + fence: u64, + event: usize, +} + +/// A submission: when it went to the card, from which thread, and from when +/// to when it ran there. +#[derive(Clone, Copy, Debug)] +pub(super) struct Run { + pub(super) fence: u64, + pub(super) t0: u64, + pub(super) t1: u64, + pub(super) thread: u32, + pub(super) on: (u64, u64), +} + +/// What was recorded, by thread and in order. +pub(super) struct Trace { + pub(super) events: Vec, + /// The spans of a thread (places among the events), by their beginning. + spans: HashMap>, + /// The waits of a thread, by their end. + waits: HashMap>, + /// Who signalled an object when. + wakes: HashMap>, + /// The submissions, by the fence's value. + pub(super) runs: Vec, + pub(super) frames: Vec<(u64, u32)>, +} + +impl Trace { + /// `stamps`: the card's times of a submission by its place, as ticks. + pub(super) fn new(mut events: Vec, stamps: &[(u64, u64)]) -> Trace { + events.sort_by_key(|e| (e.t0, std::cmp::Reverse(e.t1))); + let mut trace = Trace { + events: Vec::new(), + spans: HashMap::new(), + waits: HashMap::new(), + wakes: HashMap::new(), + runs: Vec::new(), + frames: Vec::new(), + }; + for (i, e) in events.iter().enumerate() { + match e.kind { + Kind::Span | Kind::Calls | Kind::Kernel => trace.spans.entry(e.thread).or_default().push(i), + Kind::Wait => trace.waits.entry(e.thread).or_default().push(Wait { + t0: e.t0, + t1: e.t1, + object: e.a, + fence: e.b, + event: i, + }), + Kind::Wake => trace.wakes.entry(e.a).or_default().push((e.t0, e.thread)), + Kind::Sent => { + let on = (e.b as usize).checked_sub(1).and_then(|at| stamps.get(at)).copied().unwrap_or((0, 0)); + trace.runs.push(Run { + fence: e.a, + t0: e.t0, + t1: e.t1, + thread: e.thread, + on, + }); + trace.spans.entry(e.thread).or_default().push(i); + } + Kind::Frame => trace.frames.push((e.t1, e.thread)), + Kind::Told | Kind::Poll | Kind::Sample => {} + } + } + for waits in trace.waits.values_mut() { + waits.sort_by_key(|w| w.t1); + } + trace.runs.sort_by_key(|r| r.fence); + trace.events = events; + trace + } + + /// Who ended the wait `w` of `thread`, and when. + fn waker(&self, thread: u32, w: &Wait) -> Option<(u32, u64)> { + let wakes = self.wakes.get(&w.object)?; + let end = wakes.partition_point(|k| k.0 <= w.t1); + wakes[..end].iter().rev().take_while(|k| k.0 >= w.t0).find(|k| k.1 != thread).map(|k| (k.1, k.0)) + } + + /// What `thread` was doing in `[from, to)`, the innermost span counting; + /// the newest part first. + fn doing(&self, thread: u32, from: u64, to: u64, out: &mut Vec) { + if from >= to { + return; + } + let none = Vec::new(); + let spans = self.spans.get(&thread).unwrap_or(&none); + // The spans that touch it (a span is at most some frames long). + let end = spans.partition_point(|&i| self.events[i].t0 < to); + let touching: Vec<&Event> = + spans[..end].iter().map(|&i| &self.events[i]).filter(|e| e.t1 > from).collect(); + let mut edges: Vec = vec![from, to]; + for e in &touching { + edges.extend([e.t0, e.t1].iter().filter(|t| **t > from && **t < to)); + } + edges.sort_unstable(); + edges.dedup(); + let mut parts: Vec = Vec::new(); + for pair in edges.windows(2) { + let (a, b) = (pair[0], pair[1]); + let inner = touching.iter().filter(|e| e.t0 <= a && e.t1 >= b).max_by_key(|e| (e.t0, std::cmp::Reverse(e.t1))); + let cause = match inner { + Some(e) if e.kind == Kind::Calls => { + // Of a run of list calls, the part that was ours. + let ours = (b - a) * e.b.min(e.t1 - e.t0) / (e.t1 - e.t0).max(1); + parts.push(Part { + from: a, + to: a + ours, + thread, + cause: "recording: inside our list calls".into(), + }); + parts.push(Part { + from: a + ours, + to: b, + thread, + cause: "recording: between list calls (the caller's code)".into(), + }); + continue; + } + Some(e) if e.kind == Kind::Kernel => format!("kernel: {}", e.name), + Some(e) => e.name.to_string(), + None => OUTSIDE.into(), + }; + match parts.last_mut() { + Some(last) if last.cause == cause => last.to = b, + _ => parts.push(Part { from: a, to: b, thread, cause }), + } + } + out.extend(parts.into_iter().rev().filter(|p| p.from < p.to)); + } + + /// The chain that ended at `t` on `thread`, back to `until`: what that + /// thread did since its last wait ended, then what the thread that ended + /// the wait had done, or the card, and so on. Newest first, end to end. + pub(super) fn chain(&self, mut thread: u32, mut t: u64, until: u64) -> Vec { + let mut out = Vec::new(); + for _ in 0..200_000 { + if t <= until { + break; + } + let waits = self.waits.get(&thread).map_or(&[][..], |w| w); + let last = waits[..waits.partition_point(|w| w.t1 <= t)].last().filter(|w| w.t1 > until).copied(); + let Some(w) = last else { + self.doing(thread, until, t, &mut out); + break; + }; + self.doing(thread, w.t1, t, &mut out); + let name = self.events[w.event].name; + if w.fence != 0 && w.fence != COPY_QUEUE { + match self.card(w.fence, w.t1, until, &mut out) { + Some((sender, at)) if at < t => { + (thread, t) = (sender, at); + continue; + } + Some(_) => {} + None => break, + } + } + match self.waker(thread, &w) { + Some((other, at)) if at < t && w.fence == 0 => { + out.push(Part { + from: at.max(until), + to: w.t1, + thread, + cause: "woken, not running yet".into(), + }); + (thread, t) = (other, at); + } + _ => { + let cause = match w.fence { + 0 => format!("a wait nobody seen here ended ({name})"), + COPY_QUEUE => "the card's copy queue".into(), + _ => "the card (no times of it)".into(), + }; + out.push(Part { + from: w.t0.max(until), + to: w.t1, + thread, + cause, + }); + t = w.t0; + } + } + } + out.retain(|p| p.from < p.to); + out + } + + /// The card's part of a chain: it reached `fence` by `t`. Back through + /// the submissions that stood in its queue, to the sending of one that + /// found it idle: by whom, and when; `None` if that goes back before + /// `until`, or (nothing put in) if the card's times are not known. + fn card(&self, fence: u64, t: u64, until: u64, out: &mut Vec) -> Option<(u32, u64)> { + let mut i = self.runs.partition_point(|r| r.fence < fence); + let first = self.runs.get(i)?; + if first.on == (0, 0) || first.t0 >= t { + return Some((0, u64::MAX)); + } + let part = |from: u64, to: u64, cause: &str| Part { + from: from.max(until), + to: to.max(until), + thread: 0, + cause: cause.into(), + }; + let mut end = first.on.1.min(t); + out.push(part(end, t, "the card was done, the wait not over yet")); + loop { + let run = self.runs[i]; + let begun = run.on.0.clamp(run.t0.min(end), end); + out.push(part(begun, end, "the card running submissions")); + if begun <= until { + return None; + } + match i.checked_sub(1).map(|before| self.runs[before]) { + Some(before) if before.on != (0, 0) && before.on.1 >= run.t0 => { + let to = before.on.1.min(begun); + out.push(part(to, begun, "the card between submissions")); + end = to; + i -= 1; + if end <= until { + return None; + } + } + _ => { + let sent = run.t1.min(begun); + out.push(part(sent, begun, "sent, the card not started yet")); + return Some((run.thread, sent)); + } + } + } + } +} + +/// The cause of what a thread did outside every span. +const OUTSIDE: &str = "outside our spans"; + +fn ms(ticks: u64) -> f64 { + ticks as f64 * 1e3 / frequency() as f64 +} + +/// `parts` by cause, the largest first. +fn by_cause(parts: &[Part], label: &dyn Fn(u32) -> String) -> Vec<(String, u64)> { + let mut sums: BTreeMap = BTreeMap::new(); + for p in parts { + let cause = if p.cause == OUTSIDE { format!("{} on {}", p.cause, label(p.thread)) } else { p.cause.clone() }; + *sums.entry(cause).or_default() += p.to - p.from; + } + let mut sums: Vec<(String, u64)> = sums.into_iter().collect(); + sums.sort_by_key(|s| std::cmp::Reverse(s.1)); + sums +} + +/// The summary. +pub(super) fn summary(trace: &Trace, names: &mut Names, stacks: &[[usize; DEPTH]], before: &Threads, after: &Threads) -> String { + let mut text = String::new(); + let Some((&(start, _), &(stop, _))) = trace.frames.first().zip(trace.frames.last()) else { + return "no frames\n".into(); + }; + let frames = (trace.frames.len() - 1).max(1) as f64; + let mut labels: HashMap = HashMap::new(); + for (&id, (_, name, begun)) in after.all.iter().chain(before.all.iter()) { + labels.entry(id).or_insert_with(|| match name.is_empty() { + true => format!("{id} ({})", names.of(*begun + 1)), + false => format!("{id} \"{name}\""), + }); + } + let label = |id: u32| match id { + 0 => "the card".to_string(), + id => labels.get(&id).cloned().unwrap_or_else(|| id.to_string()), + }; + let _ = writeln!(text, "{} frames in {:.1} ms ({:.1} ms a frame); {} events", frames, ms(stop - start), ms(stop - start) / frames, trace.events.len()); + + // The chains. + let mut all: Vec = Vec::new(); + for pair in trace.frames.windows(2) { + let chain = trace.chain(pair[1].1, pair[1].0, pair[0].0); + let _ = writeln!(text, "\nframe of {:.1} ms, present on {}: the chain it came out of, by cause", ms(pair[1].0 - pair[0].0), label(pair[1].1)); + for (cause, sum) in by_cause(&chain, &label).into_iter().take(24) { + let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum)); + } + all.extend(chain); + } + let whole = trace.chain(trace.frames.last().map_or(0, |f| f.1), stop, start); + let _ = writeln!(text, "\nthe chain back through all frames, per frame, by cause"); + for (cause, sum) in by_cause(&whole, &label).into_iter().take(40) { + let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum) / frames); + } + let _ = writeln!(text, "\nby thread, per frame"); + let mut by_thread: BTreeMap = BTreeMap::new(); + for p in &whole { + *by_thread.entry(p.thread).or_default() += p.to - p.from; + } + let mut by_thread: Vec<(u32, u64)> = by_thread.into_iter().collect(); + by_thread.sort_by_key(|t| std::cmp::Reverse(t.1)); + for (thread, sum) in by_thread { + let _ = writeln!(text, " {:7.2} ms {}", ms(sum) / frames, label(thread)); + } + let _ = writeln!(text, "\nthat chain, oldest first (parts under 0.15 ms left out; ms since the first present)"); + for p in whole.iter().rev().filter(|p| ms(p.to - p.from) >= 0.15) { + let _ = writeln!(text, " {:8.2} +{:6.2} {:32} {}", ms(p.from - start), ms(p.to - p.from), label(p.thread), p.cause); + } + + // The card. + let runs: Vec<&Run> = trace.runs.iter().filter(|r| r.on != (0, 0) && r.on.1 > start && r.on.0 < stop).collect(); + let (mut busy, mut reach) = (0, start); + let mut idle: BTreeMap = BTreeMap::new(); + let mut idle_all = 0; + for r in &runs { + let (a, b) = (r.on.0.clamp(start, stop), r.on.1.clamp(start, stop)); + if a > reach { + idle_all += a - reach; + if r.t1 > reach { + for p in trace.chain(r.thread, r.t1.min(a), reach) { + let cause = if p.cause == OUTSIDE { format!("{} on {}", p.cause, label(p.thread)) } else { p.cause }; + *idle.entry(cause).or_default() += p.to - p.from; + } + } + } + busy += b.saturating_sub(a.max(reach)); + reach = reach.max(b); + } + let _ = writeln!( + text, + "\nthe card, per frame: {:.2} ms running {:.1} submissions, {:.2} ms idle between them; of the idle time, by what the chain to the \ + next submission was", + ms(busy) / frames, + runs.len() as f64 / frames, + ms(idle_all) / frames + ); + let mut idle: Vec<(String, u64)> = idle.into_iter().collect(); + idle.sort_by_key(|i| std::cmp::Reverse(i.1)); + for (cause, sum) in idle.into_iter().take(30) { + let _ = writeln!(text, " {:7.2} ms {cause}", ms(sum) / frames); + } + + // Threads. + let rate = (after.cycles.saturating_sub(before.cycles)) as f64 / ms(after.ticks.saturating_sub(before.ticks)).max(1e-9); + let mut threads: Vec<(u32, f64, u64)> = after + .all + .iter() + .map(|(&id, t)| { + let ran = t.0.saturating_sub(before.all.get(&id).map_or(0, |b| b.0)) as f64 / rate.max(1e-9); + let waits = trace.waits.get(&id).map_or(&[][..], |w| w); + let waited = waits.iter().map(|w| w.t1.min(stop).saturating_sub(w.t0.max(start))).sum(); + (id, ran, waited) + }) + .collect(); + threads.sort_by(|a, b| b.1.total_cmp(&a.1)); + let _ = writeln!(text, "\nthreads, per frame: running, waiting in what is wrapped, outermost spans of ours"); + for (id, ran, waited) in threads.into_iter().filter(|t| t.1 / frames >= 0.2).take(60) { + let mut sums: BTreeMap<&str, u64> = BTreeMap::new(); + let mut reach = 0; + for &i in trace.spans.get(&id).map_or(&[][..], |s| s) { + let e = &trace.events[i]; + if e.t1 > reach { + *sums.entry(e.name).or_default() += e.t1.min(stop).saturating_sub(e.t0.max(reach).max(start)); + reach = e.t1; + } + } + let mut sums: Vec<(&str, u64)> = sums.into_iter().collect(); + sums.sort_by_key(|s| std::cmp::Reverse(s.1)); + let spans: Vec = sums.iter().take(5).map(|(name, sum)| format!("{name} {:.1}", ms(*sum) / frames)).collect(); + let _ = writeln!(text, " {:6.1} ran {:6.1} waited {:36} {}", ran / frames, ms(waited) / frames, label(id), spans.join(", ")); + } + + // Spans, all threads, each by name with what lies in it. + let mut sums: BTreeMap<&str, (u64, u64, u64)> = BTreeMap::new(); + for e in trace.events.iter().filter(|e| matches!(e.kind, Kind::Span | Kind::Kernel | Kind::Sent) && e.t1 > start && e.t0 < stop) { + let s = sums.entry(e.name).or_default(); + let took = e.t1.min(stop) - e.t0.max(start); + *s = (s.0 + took, s.1 + 1, s.2.max(took)); + } + let mut sums: Vec<_> = sums.into_iter().collect(); + sums.sort_by_key(|s| std::cmp::Reverse(s.1.0)); + let _ = writeln!(text, "\nspans and kernel calls, all threads, per frame (a span counts what lies in it)"); + for (name, (sum, n, most)) in sums.into_iter().take(80) { + let _ = writeln!(text, " {:8.2} ms in {:8.1}, longest {:6.2} {name}", ms(sum) / frames, n as f64 / frames, ms(most)); + } + + // Waits: who, where, for whom. + let mut groups: HashMap<(u32, String, String), (u64, u64, u64)> = HashMap::new(); + for (&thread, waits) in &trace.waits { + for w in waits.iter().filter(|w| w.t1 > start && w.t0 < stop && ms(w.t1 - w.t0) >= 0.05) { + let e = &trace.events[w.event]; + let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s)); + let by = match (w.fence, self_waker(trace, thread, w)) { + (COPY_QUEUE, _) => "the card's copy queue".to_string(), + (0, Some((other, _))) => label(other), + (0, None) => "nobody seen".into(), + _ => "the card".into(), + }; + let g = groups.entry((thread, format!("{} at {site}", e.name), by)).or_default(); + let took = w.t1.min(stop) - w.t0.max(start); + *g = (g.0 + took, g.1 + 1, g.2.max(took)); + } + } + let mut groups: Vec<_> = groups.into_iter().collect(); + groups.sort_by_key(|g| std::cmp::Reverse(g.1.0)); + let _ = writeln!(text, "\nwaits of 50 us or more, per frame: who, what and where, who ended them"); + for ((thread, what, by), (sum, n, most)) in groups.into_iter().take(150) { + let _ = writeln!( + text, + " {:7.2} ms in {:7.1}, longest {:6.2} {} | {what} | ended by {by}", + ms(sum) / frames, + n as f64 / frames, + ms(most), + label(thread) + ); + } + + // Long list calls. + let mut calls: HashMap = HashMap::new(); + for e in trace.events.iter().filter(|e| e.name == "a long list call" && e.t1 > start && e.t0 < stop) { + let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s)); + let c = calls.entry(site).or_default(); + *c = (c.0 + (e.t1 - e.t0), c.1 + 1); + } + let mut calls: Vec<_> = calls.into_iter().collect(); + calls.sort_by_key(|c| std::cmp::Reverse(c.1.0)); + let _ = writeln!(text, "\nlist calls of 50 us or more, per frame"); + for (site, (sum, n)) in calls.into_iter().take(25) { + let _ = writeln!(text, " {:7.2} ms in {:7.1} {site}", ms(sum) / frames, n as f64 / frames); + } + text +} + +fn self_waker(trace: &Trace, thread: u32, w: &Wait) -> Option<(u32, u64)> { + trace.waker(thread, w) +} + +fn escaped(text: &str) -> String { + text.chars() + .flat_map(|c| match c { + '"' => vec!['\\', '"'], + '\\' => vec!['\\', '\\'], + c if (c as u32) < 32 => vec![' '], + c => vec![c], + }) + .collect() +} + +/// The Chrome trace. +pub(super) fn chrome( + trace: &Trace, + names: &mut Names, + stacks: &[[usize; DEPTH]], + threads: &Threads, + out: &mut impl std::io::Write, +) -> std::io::Result<()> { + let start = trace.events.first().map_or(0, |e| e.t0); + let us = |t: u64| t.saturating_sub(start) as f64 * 1e6 / frequency() as f64; + write!(out, "{{\"traceEvents\":[\n{{\"ph\":\"M\",\"pid\":1,\"tid\":0,\"name\":\"thread_name\",\"args\":{{\"name\":\"the card\"}}}}")?; + for (id, (_, name, begun)) in &threads.all { + let name = if name.is_empty() { names.of(*begun + 1) } else { name.clone() }; + write!( + out, + ",\n{{\"ph\":\"M\",\"pid\":1,\"tid\":{id},\"name\":\"thread_name\",\"args\":{{\"name\":\"{}\"}}}}", + escaped(&name) + )?; + } + for e in &trace.events { + let (ts, dur) = (us(e.t0), us(e.t1) - us(e.t0)); + let (pid, tid, cpu) = (1, e.thread, e.cpu); + match e.kind { + Kind::Wake => {} + Kind::Told => write!( + out, + ",\n{{\"ph\":\"i\",\"s\":\"t\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"cat\":\"told\",\"name\":\"{}\",\"args\":{{\"at\":\"{:#x}\",\"value\":\"{:#x}\"}}}}", + escaped(e.name), + e.a, + e.b + )?, + Kind::Sample => { + let stack = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(&[][..], |s| &s[..]); + let stack: Vec = stack.iter().take_while(|a| **a != 0).map(|a| format!("{a:#x}")).collect(); + write!( + out, + ",\n{{\"ph\":\"i\",\"s\":\"t\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"cat\":\"sample\",\"name\":\"{}\",\"args\":{{\"at\":\"{:#x}\",\"stack\":\"{}\"}}}}", + escaped(&names.of(e.a as usize)), + e.a, + stack.join(" ") + )?; + } + Kind::Frame => write!(out, ",\n{{\"ph\":\"i\",\"s\":\"g\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"name\":\"a frame ends\"}}")?, + Kind::Wait => { + let site = (e.stack as usize).checked_sub(1).and_then(|s| stacks.get(s)).map_or(String::new(), |s| names.site(s)); + write!( + out, + ",\n{{\"ph\":\"X\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"dur\":{dur:.1},\"cat\":\"wait\",\"cname\":\"grey\",\ + \"name\":\"wait\",\"args\":{{\"what\":\"{}\",\"object\":\"{:#x}\",\"fence\":\"{}\",\"at\":\"{}\"}}}}", + e.name, + e.a, + e.b, + escaped(&site) + )?; + } + _ => write!( + out, + ",\n{{\"ph\":\"X\",\"pid\":{pid},\"tid\":{tid},\"ts\":{ts:.1},\"dur\":{dur:.1},\"cat\":\"{:?}\",\"name\":\"{}\",\ + \"args\":{{\"a\":{},\"b\":{},\"cpu\":{cpu}}}}}", + e.kind, + escaped(e.name), + e.a, + e.b + )?, + } + } + for r in trace.runs.iter().filter(|r| r.on != (0, 0)) { + write!( + out, + ",\n{{\"ph\":\"X\",\"pid\":1,\"tid\":0,\"ts\":{:.1},\"dur\":{:.1},\"name\":\"submission {}\",\"args\":{{\"sent by\":{}}}}}", + us(r.on.0), + us(r.on.1) - us(r.on.0), + r.fence, + r.thread + )?; + } + // Who woke whom. + let mut id = 0u64; + for (&thread, waits) in &trace.waits { + for w in waits.iter().filter(|w| ms(w.t1 - w.t0) >= 0.1) { + if let Some((other, at)) = trace.waker(thread, w) { + id += 1; + write!( + out, + ",\n{{\"ph\":\"s\",\"pid\":1,\"tid\":{other},\"ts\":{:.1},\"id\":{id},\"cat\":\"wake\",\"name\":\"woke\"}},\ + \n{{\"ph\":\"f\",\"bp\":\"e\",\"pid\":1,\"tid\":{thread},\"ts\":{:.1},\"id\":{id},\"cat\":\"wake\",\"name\":\"woke\"}}", + us(at), + us(w.t1) + )?; + } + } + } + writeln!(out, "\n]}}") +} + +/// Writes both files. +pub(super) fn write(file: &std::path::Path, data: Data, before: &Threads, after: &Threads, stamps: Vec<(u64, u64)>) { + let mut names = Names::new(); + let (events, lost) = (data.events.len(), data.lost); + let trace = Trace::new(data.events, &stamps); + let mut text = summary(&trace, &mut names, &data.stacks, before, after); + if lost > 0 { + let _ = writeln!(text, "\n{lost} events were lost: the buffer was full"); + } + let beside = file.with_extension("txt"); + let written = std::fs::write(&beside, text).and_then(|()| { + let mut out = std::io::BufWriter::new(std::fs::File::create(file)?); + chrome(&trace, &mut names, &data.stacks, after, &mut out)?; + std::io::Write::flush(&mut out) + }); + match written { + Ok(()) => tracing::info!(file = %file.display(), summary = %beside.display(), events, lost, "the timeline is written"), + Err(e) => tracing::warn!(error = %e, file = %file.display(), "the timeline could not be written"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn event(kind: Kind, name: &'static str, thread: u32, t: (u64, u64), a: u64, b: u64) -> Event { + Event { + t0: t.0, + t1: t.1, + a, + b, + name, + thread, + stack: 0, + cpu: 0, + kind, + } + } + + fn causes(parts: &[Part]) -> Vec<(u32, u64, u64, &str)> { + parts.iter().map(|p| (p.thread, p.from, p.to, p.cause.as_str())).collect() + } + + /// The present's thread waited for the title's, which waited for the + /// relay, which waited for the card, whose submission a third thread + /// sent: the chain goes back through all of them, end to end. + #[test] + fn a_chain_goes_back_through_who_woke_whom_and_the_card() { + let events = vec![ + event(Kind::Frame, "present", 1, (1000, 1000), 0, 0), + event(Kind::Frame, "present", 1, (2000, 2000), 0, 0), + // Thread 1 presents after waiting for object 7. + event(Kind::Span, "present", 1, (1900, 2000), 0, 0), + event(Kind::Wait, "WaitForSingleObject", 1, (1100, 1850), 7, 0), + event(Kind::Wake, "SetEvent", 2, (1840, 1840), 7, 0), + // (An earlier wake of the same object, before the wait.) + event(Kind::Wake, "SetEvent", 9, (1050, 1050), 7, 0), + // Thread 2 landed flights after the card reached 12. + event(Kind::Span, "landing", 2, (1700, 1845), 0, 0), + event(Kind::Span, "merging", 2, (1750, 1800), 0, 0), + event(Kind::Wait, "WaitForSingleObject", 2, (1200, 1690), 99, 12), + // The card ran 11 and 12, both sent by thread 3; 11 found it idle. + event(Kind::Sent, "ExecuteCommandLists", 3, (1290, 1300), 11, 1), + event(Kind::Sent, "ExecuteCommandLists", 3, (1390, 1400), 12, 2), + event(Kind::Span, "steps", 3, (1100, 1290), 0, 0), + ]; + let trace = Trace::new(events, &[(1310, 1500), (1500, 1680)]); + let chain = trace.chain(1, 2000, 1000); + assert_eq!( + causes(&chain), + [ + (1, 1900, 2000, "present"), + (1, 1850, 1900, OUTSIDE), + (1, 1840, 1850, "woken, not running yet"), + (2, 1800, 1840, "landing"), + (2, 1750, 1800, "merging"), + (2, 1700, 1750, "landing"), + (2, 1690, 1700, OUTSIDE), + (0, 1680, 1690, "the card was done, the wait not over yet"), + (0, 1500, 1680, "the card running submissions"), + (0, 1310, 1500, "the card running submissions"), + (0, 1300, 1310, "sent, the card not started yet"), + (3, 1290, 1300, "ExecuteCommandLists"), + (3, 1100, 1290, "steps"), + (3, 1000, 1100, OUTSIDE), + ] + ); + // End to end: no part of the frame is missing or counted twice. + assert!(chain.windows(2).all(|p| p[0].from == p[1].to)); + } + + /// A wait nobody was seen to end (a timer) is a cause of its own, and + /// the chain goes on with the thread before it. + #[test] + fn a_wait_without_a_waker_stays_with_its_thread() { + let events = vec![ + event(Kind::Wait, "Sleep", 1, (120, 180), 0, 0), + event(Kind::Wait, "WaitOnAddress", 1, (20, 60), 5, 0), + event(Kind::Wake, "WakeByAddressSingle", 1, (50, 50), 5, 0), + ]; + let trace = Trace::new(events, &[]); + assert_eq!( + causes(&trace.chain(1, 200, 0)), + [ + (1, 180, 200, OUTSIDE), + (1, 120, 180, "a wait nobody seen here ended (Sleep)"), + (1, 60, 120, OUTSIDE), + (1, 20, 60, "a wait nobody seen here ended (WaitOnAddress)"), + (1, 0, 20, OUTSIDE), + ] + ); + } + + /// Real threads, real waits: what the wrappers record names who ended + /// them, and the chain leads to the thread that worked. + #[test] + fn real_waits_are_recorded_with_who_ended_them() { + use super::super::{hooks, record, span}; + use std::sync::{Arc, Condvar, Mutex}; + hooks::wrap_own(); + record::make_room(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let lock = Arc::new(Mutex::new(())); + record::begin(); + record::frame(); + let first = super::super::record::ticks(); + let worker = { + let (gate, lock) = (gate.clone(), lock.clone()); + std::thread::spawn(move || { + let held = lock.lock().unwrap(); + let working = span("the work of a test"); + std::thread::sleep(std::time::Duration::from_millis(5)); + let spun = std::time::Instant::now(); + while spun.elapsed().as_millis() < 30 { + std::hint::spin_loop(); + } + working.end(); + drop(held); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + record::thread() + }) + }; + { + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + } + let last = super::super::record::ticks(); + let me = record::thread(); + let other = worker.join().unwrap(); + // A contended lock. + let held = lock.lock().unwrap(); + let second = { + let lock = lock.clone(); + std::thread::spawn(move || { + drop(lock.lock().unwrap()); + record::thread() + }) + }; + std::thread::sleep(std::time::Duration::from_millis(20)); + drop(held); + let second = second.join().unwrap(); + let data = record::end(); + assert_eq!(data.lost, 0); + let trace = Trace::new(data.events, &[]); + let chain = trace.chain(me, last, first); + let work: u64 = chain.iter().filter(|p| p.thread == other && p.cause == "the work of a test").map(|p| p.to - p.from).sum(); + assert!(ms(work) >= 20.0, "{chain:?}"); + let contended = trace.waits[&second] + .iter() + .filter(|w| ms(w.t1 - w.t0) >= 10.0) + .find_map(|w| trace.waker(second, w)); + assert_eq!(contended.map(|c| c.0), Some(me)); + let mut names = Names::new(); + let sites: Vec = data.stacks.iter().map(|s| names.site(s)).collect(); + assert!(sites.iter().any(|s| s.contains("real_waits_are_recorded")), "{sites:?}"); + let mut json = Vec::new(); + chrome(&trace, &mut names, &data.stacks, &Threads::now(), &mut json).unwrap(); + assert!(json.starts_with(b"{\"traceEvents\"")); + let text = summary(&trace, &mut names, &data.stacks, &Threads::now(), &Threads::now()); + assert!(text.contains("frames in")); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 94684f5..92c69e5 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -2123,6 +2123,7 @@ pub(crate) fn install() { EXCEPTION_POINTERS, }; unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { + let _fault = crate::timeline::span("a fault looked at"); // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; const READ: usize = 0; diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 7300687..3c217d8 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -78,7 +78,13 @@ impl HostPolicy { if !self.allows(dll) { return None; } - imp::resolve(dll, symbol) + let address = imp::resolve(dll, symbol)?; + // With a timeline asked for, what threads wait with is wrapped. + #[cfg(all(windows, feature = "diagnostics"))] + if let ImportSymbol::Name { name, .. } = symbol { + return Some(victory_gpu::timeline::import(name, address)); + } + Some(address) } } diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index 5d0a5f2..a44d599 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -774,7 +774,9 @@ fn work(scheduler: &'static Scheduler) { drop(lanes); let started = std::time::Instant::now(); let traced = Traced::start(&job); + let reading = victory_gpu::timeline::span("streaming: a request"); let result = execute(&job.request); + reading.end(); walls_request(&job.request, &result, started); stream_log::request(&job, started, &result); if let Some(traced) = traced { @@ -1341,6 +1343,7 @@ fn queue(this: QueueRef, command: Command) { /// the pages are mapped just before, also those under addresses without a /// list (memory only the CPU sees). extern "system" fn submit(this: QueueRef) { + let _called = victory_gpu::timeline::span("the title's DirectStorage Submit"); // SAFETY: as above. let id = unsafe { &*this }.state.id; let Some(scheduler) = scheduler() else { diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 4181edb..ad0cdb1 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1065,6 +1065,7 @@ pub extern "system" fn XMemMapPhysicalPages( // SAFETY: the title passes `n` page numbers, or null. let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec()); let mut costed = Costed::begin(Some(n)); + let _called = victory_gpu::timeline::span("the title's XMemMapPhysicalPages"); let mut physical = physical(); if let Some(costed) = &mut costed { costed.waited = costed.started.elapsed().as_nanos() as u64; @@ -1263,6 +1264,11 @@ const GROUP: usize = 64; /// queue once at a time. In a bench (60,000 views, five threads changing /// protections) one thread mapped 1,500 pages a second, eight 30,000. fn side_by_side() -> usize { + // Diagnostics: 1 and 8 by turns. + #[cfg(all(windows, feature = "diagnostics"))] + if let Some(on) = victory_gpu::switched("VICTORY_MAP_THREADS") { + return if on { 8 } else { 1 }; + } static THREADS: LazyLock = LazyLock::new(|| { std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32) });