diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index e6e7860..490b523 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -81,6 +81,16 @@ 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, + /// Keep the card's clocks up meanwhile (VICTORY_CARD_AWAKE=1). + #[arg(long)] + awake: bool, + /// 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 +265,14 @@ pub(crate) fn run(r: Replay) -> Result<()> { merge: !r.no_merge, wait_all: r.wait_all, wait_lists: r.wait_lists, + pace: r.pace, + awake: r.awake, 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 7197f01..8b3fab9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -872,6 +872,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 a90fb22..304ecdb 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3227,10 +3227,13 @@ fn late_line(frames: f64) { } } +pub(crate) mod awake; mod card_steps; pub(crate) mod indirects; mod place; mod send; +#[cfg(feature = "diagnostics")] +pub(crate) mod spans; mod torn; pub(crate) mod upcheck; @@ -5090,11 +5093,17 @@ 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); self.queue.Signal(&self.fence, *submitted) }; + awake::sent(&self.device); self.card_sent(); if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); @@ -7434,6 +7443,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); @@ -8027,6 +8038,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/awake.rs b/crates/victory-gpu/src/host/awake.rs new file mode 100644 index 0000000..8837d15 --- /dev/null +++ b/crates/victory-gpu/src/host/awake.rs @@ -0,0 +1,251 @@ +//! Keeps the card's clocks up between submissions (`VICTORY_CARD_AWAKE=1`; off +//! by default). The card stands idle half of every frame, some thirty times for +//! a millisecond or two each, while the CPU prepares the next submission. The +//! driver takes that for a light load and lowers the clocks, and what comes +//! next starts slow: a captured frame whose lists take 30 ms sent in one go +//! takes 38-40 ms with waits of 1.2-2.4 ms between its submissions +//! (`victory replay --pace`). +//! +//! One group of 64 threads counts on a compute queue, over and +//! over: it takes one or two of the card's few thousand wave slots, and the +//! card is never idle. Nothing is sent once no submission has gone out for a +//! while (a menu at 30 fps, a minimized window). + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; + +use windows::Win32::Foundation::CloseHandle; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +/// About 2 ms at full clocks: 500 sends a second. +const COUNT: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer sum : register(u0); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint x = id.x; + [loop] for (uint i = 0; i < 400000u; i++) x = x * 1664525u + 1013904223u; + sum.Store(id.x * 4u, x); +} +"#; + +/// Quiet this long after the last submission. +const QUIET_MS: u64 = 250; + +fn now_ms() -> u64 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// When a submission was last sent ([`now_ms`] plus one; 0: never). +static LAST: AtomicU64 = AtomicU64::new(0); + +fn wanted() -> bool { + let (last, now) = (LAST.load(Ordering::Relaxed), now_ms()); + last != 0 && now + 1 < last + QUIET_MS && (mode() != Mode::ByTurns || now / TURN_MS % 2 == 1) +} + +/// With `VICTORY_CARD_AWAKE=turns`: this long on, this long off. +const TURN_MS: u64 = 20_000; + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Off, + On, + /// On and off by turns, to compare the two in one run (the log says when). + ByTurns, +} + +fn mode() -> Mode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_AWAKE").as_deref() { + Ok("1") => Mode::On, + Ok("turns") => Mode::ByTurns, + _ => Mode::Off, + }) +} + +/// A submission of the title's goes to `device`'s drawing queue. +pub(super) fn sent(device: &ID3D12Device) { + if mode() == Mode::Off { + return; + } + let now = now_ms(); + let before = LAST.swap(now + 1, Ordering::Relaxed); + if mode() == Mode::ByTurns && before.saturating_sub(1) / TURN_MS != now / TURN_MS { + tracing::info!(on = now / TURN_MS % 2 == 1, "the card is kept awake, by turns"); + } + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + // Runs as long as the process does. + std::mem::forget(start(device, wanted)); + }); +} + +/// The thread that keeps the card busy; it ends when this is dropped. +pub(crate) struct Awake { + stop: std::sync::Arc, + thread: Option>, +} + +impl Drop for Awake { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// Keeps the card of `device` busy while `wanted`. +pub(crate) fn start(device: &ID3D12Device, wanted: impl Fn() -> bool + Send + 'static) -> Option { + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let (device, ended) = (device.clone(), stop.clone()); + let thread = std::thread::Builder::new() + .name("victory-card-awake".into()) + .spawn(move || { + if let Err(e) = run(&device, &wanted, &ended) { + tracing::warn!(error = %e, "the card is not kept awake"); + } + }) + .ok()?; + Some(Awake { + stop, + thread: Some(thread), + }) +} + +fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> windows::core::Result<()> { + let code = super::compile(COUNT, windows::core::s!("main"), windows::core::s!("cs_5_1"))?; + // SAFETY: plain object creation; the code lives through the calls, the + // root signature is inside it. Two closed lists, sent in turn, whose + // objects live until what was sent last has run. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?; + let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + })?; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0, + ..Default::default() + })?; + let mut sum: Option = None; + device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut sum, + )?; + let sum = sum.ok_or_else(windows::core::Error::empty)?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE)?; + let mut lists = Vec::new(); + for _ in 0..2 { + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &allocator, &pso)?; + list.SetComputeRootSignature(&root); + list.SetComputeRootUnorderedAccessView(0, sum.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.Close()?; + lists.push(Some(list.cast::()?)); + } + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let mut value = 0u64; + let mut result = Ok(()); + while !stop.load(Ordering::Relaxed) && result.is_ok() { + if !wanted() { + std::thread::sleep(Duration::from_millis(2)); + continue; + } + // Never more than two on the way. + if value >= 2 && fence.GetCompletedValue() + 2 <= value { + result = fence.SetEventOnCompletion(value - 1, event); + if result.is_ok() { + WaitForSingleObject(event, 1000); + result = device.GetDeviceRemovedReason(); + } + continue; + } + queue.ExecuteCommandLists(&lists[(value % 2) as usize..][..1]); + value += 1; + result = queue.Signal(&fence, value); + } + if result.is_ok() && fence.GetCompletedValue() < value && fence.SetEventOnCompletion(value, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + let _ = CloseHandle(event); + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Card memory the CPU maps holds what the CPU wrote, with the card kept + /// awake meanwhile; the thread ends when it is let go. + #[test] + fn mapped_card_memory_is_written_by_the_cpu_and_read_by_the_card() { + let Some(host) = crate::host::host() else { + return; + }; + let awake = start(&host.device, || true); + assert!(awake.is_some()); + let Some((buffer, data)) = host.mapped_card_buffer(4096, true) else { + return; + }; + let (seen, back) = host.shared_buffer(4096).unwrap(); + // SAFETY: mappings of 4096 bytes; a list, a queue and a fence of the + // test's own, and nothing is read before the copy has run. + let read = unsafe { + for i in 0..4096 { + data.add(i).write((i * 7 + i / 251) as u8); + } + let device = &host.device; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + list.CopyBufferRegion(&seen, 0, &buffer, 0, 4096); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + // No event: returns when the fence is there. + fence.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + std::slice::from_raw_parts(back, 4096).to_vec() + }; + assert!(read.iter().enumerate().all(|(i, &b)| b == (i * 7 + i / 251) as u8)); + drop(awake); + } +} diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 9227399..ff836de 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -88,8 +88,22 @@ 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), and take 0.4 this way; but filling it takes the +/// submitting thread 8-9 ms a frame instead of 3 (73-93 MB, run card-3 against +/// card-1), so it is a loss while the card waits for that thread: off by +/// default. +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 +114,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 +132,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/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs index 21af58a..e6da6a1 100644 --- a/crates/victory-gpu/src/indirect/batch.rs +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -96,6 +96,8 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { } else { if (record[0] > 65535u) { record[0] = 0; + record[1] = 0; + record[2] = 0; } asked = record[0]; record[1] = min(record[1], 1u); diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 069a431..826eb00 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)] { @@ -1084,6 +1112,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..b823576 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -84,6 +84,11 @@ 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, + /// The card kept awake meanwhile (`crate::host::awake`). + pub awake: bool, /// 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 +100,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 +124,14 @@ impl Default for Options { merge: true, wait_all: false, wait_lists: false, + pace: 0.0, + awake: false, only: None, until: None, skip_shaders: Vec::new(), compare: false, debug: false, + breadcrumbs: false, } } } @@ -150,6 +161,7 @@ impl Options { one_submit: false, wait_all: false, wait_lists: false, + awake: false, only: None, skip_shaders: Vec::new(), ..self.clone() @@ -488,6 +500,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 +519,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 = @@ -570,7 +586,7 @@ impl Player { step("descriptors", &mut at); player.load_contents()?; step("contents", &mut at); - player.make_masters(options.buffers)?; + player.make_masters(options.buffers, options.restore)?; step("copies to restore from", &mut at); let steps: Vec = steps .iter() @@ -1554,7 +1570,7 @@ impl Player { } /// Copies of what the frame changes; and the states it leaves. - fn make_masters(&mut self, buffers: Buffers) -> Result<()> { + fn make_masters(&mut self, buffers: Buffers, wanted: bool) -> Result<()> { let mut states = States::default(); for r in &self.frame.resources { if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { @@ -1687,6 +1703,11 @@ impl Player { }) .collect(); ids.sort_unstable(); + // Without restoring they are of no use, and their room may be what + // the frame itself lacks. + if !wanted { + ids.clear(); + } let mut total = 0u64; let mut in_pc = 0u64; for id in ids { @@ -2413,9 +2434,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 +2453,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 +2944,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 { @@ -2907,6 +2971,7 @@ impl Player { /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { let mut made = self.prepare(o)?; + let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None }; let mut stamps = Vec::new(); for _ in 0..o.loops.max(1) { stamps = self.once(o, &mut made)?; @@ -3014,7 +3079,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 +3303,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 +3321,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..8426552 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,51 @@ 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. In a +/// captured frame the lists take 26 ms of the card instead of 29, the frame 32 +/// instead of 36; filling them costs the CPU what it did. +/// +/// 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 +2296,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 +2683,7 @@ impl Shadow { }, card: None, window: false, + mapped: false, place: None, } } @@ -4602,6 +4655,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 | +| `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) | +| `--pace ` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one | +| `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) | +| `--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