From bd68f5e175e01551f5e65dab7d484fe690af346b Mon Sep 17 00:00:00 2001 From: local Date: Wed, 25 Nov 2026 03:35:03 -0600 Subject: [PATCH] Card memory the CPU maps: windows, sends and scratch (VICTORY_WINDOWS_BAR_MB, VICTORY_SEND_BAR, VICTORY_SCRATCH_BAR); the card's own stamps (VICTORY_CARD_SPANS) GPU_UPLOAD heaps, all off by default. Replayed yard frame (capture play-1125-0127): 36.3 ms; windows in the card's memory 31.9, sends 32.7. Replay: --pace, --breadcrumbs, copies counted by the memory they cross. VICTORY_GPU_LOAD_MS: what the title's GPU timestamps show. Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 9 + crates/victory-gpu/src/draw.rs | 4 + crates/victory-gpu/src/host.rs | 105 +++++++++++- crates/victory-gpu/src/host/send.rs | 23 ++- crates/victory-gpu/src/host/spans.rs | 232 ++++++++++++++++++++++++++ crates/victory-gpu/src/queue.rs | 38 ++++- crates/victory-gpu/src/replay/play.rs | 82 ++++++++- crates/victory-gpu/src/shadow.rs | 66 +++++++- docs/replay.md | 2 + 9 files changed, 549 insertions(+), 12 deletions(-) create mode 100644 crates/victory-gpu/src/host/spans.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index e6e7860..db2f9d6 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -81,6 +81,13 @@ pub(crate) struct Replay { /// Each list sent on its own, and waited for. #[arg(long)] wait_lists: bool, + /// Milliseconds to wait after sending each submission: the card stands + /// idle between them, as it does while the title prepares the next. + #[arg(long, default_value_t = 0.0)] + pace: f64, + /// The system's breadcrumbs after every command (VICTORY_D3D12_DRED=light). + #[arg(long)] + breadcrumbs: bool, /// Run only these lists, by their place in the frame (`3..7`, or `5`); /// of the others only barriers. #[arg(long)] @@ -255,11 +262,13 @@ pub(crate) fn run(r: Replay) -> Result<()> { merge: !r.no_merge, wait_all: r.wait_all, wait_lists: r.wait_lists, + pace: r.pace, only, until, skip_shaders: r.skip_shader, compare: r.compare, debug: r.debug_layer, + breadcrumbs: r.breadcrumbs, }; if let Some(text) = &r.slots { let (list, command) = text diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2b6f8a0..8454580 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -833,6 +833,10 @@ impl State { /// Viewports, scissors, the blend factor and the stencil reference: set /// on the host list at once, and kept for [`State::replay`]. pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + #[cfg(feature = "diagnostics")] + if let Some(v) = viewports.first() { + crate::host::spans::viewport(v.Width as u32, v.Height as u32); + } self.viewports.clear(); self.viewports.extend_from_slice(viewports); crate::draw::viewports(list, viewports); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e24be3b..0c77c85 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1579,6 +1579,15 @@ impl Spare { /// Scratch chunks no list holds. static SPARE: Mutex> = Mutex::new(Spare::new()); +/// Whether lists' scratch memory (constants and tables, which shaders read) +/// lies in the card's memory, written by the CPU through the bus +/// (`VICTORY_SCRATCH_BAR=1`; the default is upload memory, which the card +/// reads through it). +fn scratch_on_card() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SCRATCH_BAR").is_some_and(|v| v == "1")) +} + /// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. fn take_chunk(host: &Host, size: u64) -> Option { if scratch_pool() @@ -1589,7 +1598,11 @@ fn take_chunk(host: &Host, size: u64) -> Option { ALIVE[5].fetch_add(1, Ordering::Relaxed); return Some(chunk); } - let (buffer, data) = host.upload_buffer(size)?; + let mapped = if scratch_on_card() { host.mapped_card_buffer(size, false) } else { None }; + let (buffer, data) = match mapped { + Some(made) => made, + None => host.upload_buffer(size)?, + }; name(&buffer, || "list scratch".into()); ALIVE[1].fetch_add(1, Ordering::Relaxed); ALIVE[2].fetch_add(size, Ordering::Relaxed); @@ -3157,6 +3170,8 @@ fn late_line(frames: f64) { mod card_steps; mod place; mod send; +#[cfg(feature = "diagnostics")] +pub(crate) mod spans; mod torn; pub(crate) mod upcheck; @@ -5005,6 +5020,11 @@ impl Host { let prepared = std::time::Instant::now(); if late { *submitted += 1; + #[cfg(feature = "diagnostics")] + if let Some([front, behind]) = self.span_lists() { + lists.insert(0, Some(front)); + lists.push(Some(behind)); + } // SAFETY: closed lists; the fence is ours. let signalled = unsafe { self.queue.ExecuteCommandLists(&lists); @@ -7318,6 +7338,8 @@ impl Meter { crate::descriptor::sync_line(frames); late_line(frames); card_clock_line(frames, ms); + #[cfg(feature = "diagnostics")] + spans::line(frames); crate::shadow::back_line(frames); #[cfg(feature = "diagnostics")] split_line(frames); @@ -7891,6 +7913,87 @@ impl Host { } } + /// Whether buffers can lie in the card's memory and be mapped by the CPU + /// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver + /// that offer it); logged once. + pub(crate) fn mapped_card_memory(&self) -> bool { + static THERE: OnceLock = OnceLock::new(); + *THERE.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + // SAFETY: writes `options` of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS16, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let supported = ok && options.GPUUploadHeapSupported.as_bool(); + tracing::info!(supported, "card memory the CPU maps"); + supported + }) + } + + /// A buffer in the card's own memory that the CPU maps, shaders read and + /// (with `written`) may write. The CPU should only write it: a read of the + /// mapping crosses the bus a few bytes at a time. + pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> { + if !self.mapped_card_memory() { + return None; + } + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_GPU_UPLOAD, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if written { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + } else { + D3D12_RESOURCE_FLAG_NONE + }, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps"); + None + } + } + } + /// A device-local buffer shaders may write (unordered access) and indirect /// execution may read, starting in the common state. pub(crate) fn uav_buffer(&self, size: u64) -> Option { diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 9227399..669c965 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -88,8 +88,19 @@ unsafe impl Send for Memory {} /// What submissions that have run gave back. static SPARE: Mutex> = Mutex::new(Vec::new()); -/// At most this much is kept. -const KEPT: u64 = 768 << 20; +/// At most this much is kept (of the card's memory, with [`on_card`]). +fn kept() -> u64 { + if on_card() { 256 << 20 } else { 768 << 20 } +} + +/// Whether the memory lies in the card's memory, written by the CPU through +/// the bus (`VICTORY_SEND_BAR=1`): the copies on the card's drawing queue, which +/// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of +/// the card's 30 (342 copies). +fn on_card() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_BAR").is_some_and(|v| v == "1")) +} fn memory(host: &Host, size: u64) -> Option { { @@ -100,7 +111,11 @@ fn memory(host: &Host, size: u64) -> Option { } } let size = size.next_multiple_of(8 << 20); - let (buffer, data) = host.upload_buffer(size)?; + let mapped = if on_card() { host.mapped_card_buffer(size, false) } else { None }; + let (buffer, data) = match mapped { + Some(made) => made, + None => host.upload_buffer(size)?, + }; name(&buffer, || "bytes a submission sends up".into()); Some(Memory { buffer, @@ -114,7 +129,7 @@ pub(super) fn give_back(memory: Memory) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); spare.push(memory); spare.sort_by_key(|m| std::cmp::Reverse(m.size)); - while spare.iter().map(|m| m.size).sum::() > KEPT { + while spare.iter().map(|m| m.size).sum::() > kept() { spare.remove(0); } } diff --git a/crates/victory-gpu/src/host/spans.rs b/crates/victory-gpu/src/host/spans.rs new file mode 100644 index 0000000..e8bd804 --- /dev/null +++ b/crates/victory-gpu/src/host/spans.rs @@ -0,0 +1,232 @@ +//! Diagnostics: how long the card itself works on our submissions, by its own +//! timestamps (`VICTORY_CARD_SPANS=1`). The clock of the frame line +//! (`card_clock_line`) counts from the call that sends a submission to the +//! moment a thread of ours wakes behind its last signal: the time the system +//! takes to hand a submission to the card and to report it done is in it, 40 +//! times a frame. Here two lists made once, of nothing but a timestamp, stand +//! around each submission. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +use super::Host; + +/// Submissions stamped before the first stamps are read and used again. +const SPANS: usize = 512; + +/// The stamps of one queue's submissions. +pub(super) struct Spans { + _allocator: ID3D12CommandAllocator, + _heap: ID3D12QueryHeap, + _back: ID3D12Resource, + /// The mapped results, two a submission. + data: usize, + lists: Vec, + ticks_per_ms: f64, + next: usize, + sums: Sums, +} + +// SAFETY: free-threaded objects and a mapping only read behind a lock. +unsafe impl Send for Spans {} + +/// What the stamps read so far add up to. +#[derive(Debug, Default, Clone, Copy, PartialEq)] +struct Sums { + /// Submissions, ticks the card worked on them, ticks between them. + count: u64, + busy: u64, + between: u64, + /// Ticks of the longest one, and the last one's end. + longest: u64, + last: u64, +} + +impl Sums { + /// A submission that ran from `start` to `end` (card ticks), after those + /// before it. The start's stamp may be of before the last one's end: the + /// part before that end is the last one's. + fn add(&mut self, start: u64, end: u64) { + if start == 0 || end < start { + return; + } + let start = start.max(self.last); + let took = end.saturating_sub(start); + if self.last != 0 { + self.between += start - self.last; + } + self.count += 1; + self.busy += took; + self.longest = self.longest.max(took); + self.last = end.max(self.last); + } +} + +fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CARD_SPANS").is_some_and(|v| v == "1")) +} + +static SPANS_MADE: Mutex>> = Mutex::new(None); + +impl Host { + /// The lists that go in front of and behind a submission about to be + /// sent to the drawing queue, if stamps are asked for. + pub(super) fn span_lists(&self) -> Option<[ID3D12CommandList; 2]> { + if !on() { + return None; + } + let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner()); + let spans = made + .get_or_insert_with(|| { + self.make_spans() + .inspect_err(|e| tracing::warn!(error = %e, "no stamps around submissions")) + .ok() + }) + .as_mut()?; + let i = spans.next; + spans.next = (i + 1) % SPANS; + // The stamps of the submission that had these lists, that many + // submissions ago: long done. + // SAFETY: inside the mapping; written by the card at whole words. + let (start, end) = unsafe { + let at = (spans.data as *mut u64).add(2 * i); + let read = (at.read_volatile(), at.add(1).read_volatile()); + at.write_volatile(0); + at.add(1).write_volatile(0); + read + }; + spans.sums.add(start, end); + Some([spans.lists[2 * i].clone(), spans.lists[2 * i + 1].clone()]) + } + + fn make_spans(&self) -> windows::core::Result { + let device = &self.device; + // SAFETY: plain object creation; lists of one allocator recorded one + // after the other. + unsafe { + let mut heap: Option = None; + device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2 * SPANS as u32, + NodeMask: 0, + }, + &mut heap, + )?; + let heap = heap.ok_or_else(windows::core::Error::empty)?; + let back = self.read_back_buffer(16 * SPANS as u64).ok_or_else(windows::core::Error::empty)?; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data))?; + std::ptr::write_bytes(data.cast::(), 0, 16 * SPANS); + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let mut lists = Vec::with_capacity(2 * SPANS); + for i in 0..2 * SPANS as u32 { + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i); + list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, &back, u64::from(i) * 8); + list.Close()?; + lists.push(list.cast()?); + } + Ok(Spans { + _allocator: allocator, + _heap: heap, + _back: back, + data: data as usize, + lists, + ticks_per_ms: self.queue.GetTimestampFrequency()? as f64 / 1000.0, + next: 0, + sums: Sums::default(), + }) + } + } +} + +/// The GPU timestamps the title was given since the last frame-rate line: +/// how many, how often a later one was 1 ms or more after the one before +/// (written with another submission), and where the first few lie. +static STAMPED: Mutex<(u64, u64, u64, Vec)> = Mutex::new((0, 0, 0, Vec::new())); + +/// The title's GPU timestamp at `at` was given the value `now` (ticks of 10 +/// ns). +pub(crate) fn stamped(at: usize, now: u64) { + if !on() { + return; + } + let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner()); + s.0 += 1; + s.1 += u64::from(now.saturating_sub(s.2) > 100_000); + s.2 = now; + if s.3.len() < 64 && !s.3.contains(&at) { + s.3.push(at); + tracing::info!(address = format_args!("{at:#x}"), now, "a GPU timestamp of the title"); + } +} + +/// The viewports' sizes seen (each said once): whether the title draws its +/// scene at sizes of its choice. +pub(crate) fn viewport(width: u32, height: u32) { + if !on() || width < 1024 || height < 576 { + return; + } + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < 200 && !seen.contains(&(width, height)) { + seen.push((width, height)); + tracing::info!(width, height, "a viewport of the title"); + } +} + +/// For the frame-rate line: what the stamps read since the last one say, per +/// frame (they are of some [`SPANS`] submissions ago). +pub(super) fn line(frames: f64) { + { + let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner()); + if s.0 > 0 { + tracing::info!( + "GPU timestamps the title asked for per frame: {:.1}, in {:.1} groups written at one time", + s.0 as f64 / frames, + s.1 as f64 / frames + ); + } + (s.0, s.1) = (0, 0); + } + let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(spans)) = made.as_mut() else { + return; + }; + let last = spans.sums.last; + let s = std::mem::replace(&mut spans.sums, Sums { last, ..Sums::default() }); + let ms = |ticks: u64| ticks as f64 / spans.ticks_per_ms / frames; + tracing::info!( + "the card's own stamps per frame: {:.1} submissions, working {:.1} ms, idle between them {:.1} ms, the longest {:.1} ms", + s.count as f64 / frames, + ms(s.busy), + ms(s.between), + s.longest as f64 / spans.ticks_per_ms + ); +} + +#[cfg(test)] +mod tests { + use super::Sums; + + #[test] + fn submissions_add_up_without_counting_anything_twice() { + let mut s = Sums::default(); + s.add(100, 150); + s.add(140, 200); // began before the last one ended + s.add(260, 270); + assert_eq!((s.count, s.busy, s.between, s.longest, s.last), (3, 110, 60, 50, 270)); + // Never written, or nonsense: nothing. + s.add(0, 0); + s.add(300, 290); + assert_eq!(s.count, 3); + // Whole inside the last one. + s.add(265, 268); + assert_eq!((s.count, s.busy, s.between), (4, 110, 60)); + } +} diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 11d3a8c..884fbf0 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -715,7 +715,10 @@ impl Written { Written::GpuTimestamp => { static START: std::sync::OnceLock = std::sync::OnceLock::new(); let elapsed = START.get_or_init(std::time::Instant::now).elapsed(); - (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 + let now = (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64; + #[cfg(all(windows, feature = "diagnostics"))] + crate::host::spans::stamped(at as usize, now); + as_loaded(now, at as usize, gpu_load()) } Written::SystemTimestamp => system_timestamp(), }; @@ -730,6 +733,31 @@ impl Written { } } +/// What the title's GPU time is made to look like, in ticks +/// (`VICTORY_GPU_LOAD_MS`; unset: as it is). +/// +/// The title asks for four GPU timestamps a frame, in pairs of 16 bytes, the +/// start in the second eight and the end in the first. All of them are written +/// when the frame's last submissions land, within microseconds, so every pair +/// says the card did nothing. +fn gpu_load() -> u64 { + static LOAD: std::sync::OnceLock = std::sync::OnceLock::new(); + *LOAD.get_or_init(|| { + let ms = std::env::var("VICTORY_GPU_LOAD_MS").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + ms * (TIMESTAMP_FREQUENCY / 1000) + }) +} + +/// The timestamp written at `at` when the clock says `now`, if a pair's start +/// is to lie `load` ticks before its end. +fn as_loaded(now: u64, at: usize, load: u64) -> u64 { + if at & 8 != 0 { + now.saturating_sub(load).max(1) + } else { + now + } +} + fn system_timestamp() -> u64 { #[cfg(windows)] { @@ -1072,6 +1100,14 @@ mod tests { assert_eq!(new[35], execute_x as *const ()); // 0x118 } + #[test] + fn a_pair_of_timestamps_shows_the_load_it_is_given() { + let (start, end) = (0xd0419_6698, 0xd0419_6690); + assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000); + assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000); + assert_eq!(as_loaded(5, start, 100), 1); + } + #[test] fn timestamps_and_values_are_written() { let mut at = [0u64; 2]; diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index b56f6e2..e28c20c 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -84,6 +84,9 @@ pub struct Options { pub wait_all: bool, /// Each list sent on its own, and waited for. pub wait_lists: bool, + /// Milliseconds the sender waits after each submission, as a title does + /// that prepares the next one meanwhile: the card stands idle. + pub pace: f64, /// Run only these lists (by their place in the frame). pub only: Option<(u32, u32)>, /// The last command that runs (list, command); after it only barriers. @@ -95,6 +98,9 @@ pub struct Options { pub compare: bool, /// The debug layer, if it is installed. pub debug: bool, + /// The system's breadcrumbs after every command, as + /// `VICTORY_D3D12_DRED=light` has them. + pub breadcrumbs: bool, } impl Default for Options { @@ -116,11 +122,13 @@ impl Default for Options { merge: true, wait_all: false, wait_lists: false, + pace: 0.0, only: None, until: None, skip_shaders: Vec::new(), compare: false, debug: false, + breadcrumbs: false, } } } @@ -488,6 +496,10 @@ pub struct Player { /// What a command of a list is timed as. type Stamp = (usize, &'static str, u32); +/// With a stamp of a copy to a texture: this bit and the texture's number +/// stand for the pipeline's. +const COPY_TO: u32 = 1 << 31; + /// A list made from commands, with what its timestamps are of. struct Built { _allocator: ID3D12CommandAllocator, @@ -503,7 +515,7 @@ impl Player { let folder = find(folder)?; let began = Instant::now(); let frame = Frame::read(&folder.join("frame.bin"))?; - let (device, info) = make_device(&frame, options.debug)?; + let (device, info) = make_device(&frame, options.debug, options.breadcrumbs)?; // SAFETY: plain creation and queries. let (queue, frequency) = unsafe { let queue: ID3D12CommandQueue = @@ -2413,9 +2425,18 @@ impl Player { "clears" } Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves", - _ => "copies", + _ => self.copy_kind(c), + }; + let runs = match c { + c if c.runs_shaders() => bound, + // Copies to textures by what they go to. + Cmd::CopyResource { dst, .. } + | Cmd::CopyTexture { + dst: Loc::Sub { res: dst, .. }, + .. + } => COPY_TO | dst, + _ => NONE, }; - let runs = if c.runs_shaders() { bound } else { NONE }; stamps.push((**next as usize, category, runs)); **next += 1; } @@ -2423,6 +2444,34 @@ impl Player { stamps } + /// Which copies a copy is counted with: by the memory it crosses. + fn copy_kind(&self, c: &Cmd) -> &'static str { + let pc = |id: u32| { + self.objects.get(&id).is_some_and(|o| { + matches!(&self.frame.resources[o.index].place, + Place::Committed { props, .. } if gpu::seen(props) != Seen::No) + }) + }; + let res = |l: &Loc| match l { + Loc::Sub { res, .. } | Loc::Placed { res, .. } => *res, + }; + match c { + Cmd::CopyBuffer { dst, src, .. } => match (pc(*dst), pc(*src)) { + (false, true) => "copies of buffers, PC to card", + (true, false) => "copies of buffers, card to PC", + (true, true) => "copies of buffers, PC to PC", + (false, false) => "copies of buffers, card to card", + }, + Cmd::CopyTexture { dst, src, .. } => match (pc(res(dst)), pc(res(src))) { + (false, true) => "copies of textures, PC to card", + (true, _) => "copies of textures, to the PC", + (false, false) => "copies of textures, card to card", + }, + Cmd::CopyResource { .. } => "copies of whole resources", + _ => "copies", + } + } + unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) { let res = |id: u32| self.resource(id); let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default(); @@ -2886,6 +2935,12 @@ impl Player { for all in &submissions { if !o.wait_lists { self.worker.queue.ExecuteCommandLists(all); + if o.pace > 0.0 { + let until = Instant::now() + std::time::Duration::from_secs_f64(o.pace / 1e3); + while Instant::now() < until { + std::thread::yield_now(); + } + } continue; } for l in all { @@ -3014,7 +3069,16 @@ impl Player { all.truncate(o.top); report.shaders = all .into_iter() - .map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso))) + .map(|(ms, n, pso)| { + let name = match self.objects.get(&(pso & !COPY_TO)).filter(|_| pso & COPY_TO != 0) { + Some(o) => { + let r = &self.frame.resources[o.index]; + format!("copies to #{} {}", pso & !COPY_TO, r.name) + } + None => self.pipeline_name(pso), + }; + (ms, n, name) + }) .collect(); } @@ -3229,7 +3293,7 @@ fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> { Ok(()) } -fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option)> { +fn make_device(frame: &Frame, debug: bool, breadcrumbs: bool) -> Result<(ID3D12Device, Option)> { // SAFETY: plain creation and queries. unsafe { if debug { @@ -3247,6 +3311,14 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option tracing::warn!("no debug layer: {e}"), } } + if breadcrumbs { + let mut dred: Option = None; + D3D12GetDebugInterface(&mut dred)?; + if let Some(dred) = dred { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + } let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; let mut adapter = None; for i in 0.. { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 8b127df..b2d9155 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -83,6 +83,8 @@ pub(crate) struct Shadow { card: Option, /// A window of title memory outside buffers, not a title buffer's copy. window: bool, + /// A window in card memory the CPU maps ([`window_mapped_for`]). + mapped: bool, /// With `crate::inplace`: not a copy at all. `buffer` is placed in a /// heap opened on the title memory itself, so shaders read and write /// the title's own bytes and nothing is copied either way. The heap, @@ -299,7 +301,9 @@ pub(crate) fn card_stats() -> [u64; 10] { out[i] = stat.swap(0, Ordering::Relaxed); } out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; - out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); + out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed); out[9] = CARD_BYTES[1].load(Ordering::Relaxed); out } @@ -447,6 +451,49 @@ fn window_card_for(size: u64) -> Option { Some(buffer) } +/// The most bytes of windows outside buffers that lie in the card's memory +/// and are filled by the CPU through the bus (`VICTORY_WINDOWS_BAR_MB`; 0, the +/// default, none): one buffer (`D3D12_HEAP_TYPE_GPU_UPLOAD`), no CPU's side, no +/// copy to send and no list of changes, unlike [`window_card_most`]. The CPU +/// only writes them, as no shader is declared to write a window; if one were, +/// its snapshot and compare would read through the bus, right but slow. +/// +/// Windows go there while a fifth of the card's budget is free, as with +/// [`window_room_for`], which this comes before. +fn window_mapped_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("VICTORY_WINDOWS_BAR_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of windows in card memory the CPU maps. +static WINDOW_MAPPED_BYTES: AtomicU64 = AtomicU64::new(0); + +/// A buffer for a window of `size` bytes in card memory the CPU maps, if it is +/// to be there ([`window_mapped_most`]). +fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let most = window_mapped_most(); + if most == 0 { + return None; + } + let host = host()?; + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if WINDOW_MAPPED_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let made = host.mapped_card_buffer(size, true); + if made.is_none() { + WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed); + } + made +} + /// Whether windows outside buffers have two sides too, so that submissions /// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`; /// off by default: it takes the windows' bytes again, 3.3 GB in capture @@ -2247,6 +2294,9 @@ impl Drop for Shadow { KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); } let window = self.window; + if self.mapped { + WINDOW_MAPPED_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } if let Some(card) = &mut self.card { if window { WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); @@ -2631,6 +2681,7 @@ impl Shadow { }, card: None, window: false, + mapped: false, place: None, } } @@ -4602,6 +4653,19 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | | `--no-restore` | leaves what a loop changed | +| `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | +| `--breadcrumbs` | the system's breadcrumbs (`VICTORY_D3D12_DRED=light`) | | `--debug-layer` | D3D12's debug layer; its errors in the report | Use the median of several loops; the first is slower. An experiment that