From 8d3ce0190f4885f69a779180ff4cfe626e543469 Mon Sep 17 00:00:00 2001 From: fxceless <36782933+fxceless@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:19:10 -0500 Subject: [PATCH 1/5] Packed textures stay in the upload queue; a texture on the card is refreshed when the card is full Two fixes for textures that shaders pick by index, both proven with a slot listing before they were made: - The title keeps only a texture's small levels and places the next texture in the address range of the absent large ones. Described at full size every neighbour overlapped, and each view written took the textures beside it out of the upload queue and made their host slots null (tens of thousands of slots a run). A newer view now makes an older one stale only when it starts within that one's first 4 KiB. VICTORY_STALE_TEXTURES=overlap: the old rule; =0: never. Unit tests on the span table alone. The first room is lit with its walls and the characters' textures in the first launch with it. - With the card at its limit, a texture that already has its host copy is uploaded again when the title changed its memory (it took no new card memory, and was refused all the same). VICTORY_REUPLOAD_WHEN_FULL=0: as before. Logging only, off unless asked for: both video memory groups and budget moves; card accounting (VICTORY_CARD_ACCOUNTING=1); the slots a listed draw's shaders read, with their state (VICTORY_LIST_SLOTS=); a trace for the missing first-room walls (VICTORY_WALLS_TRACE=1 or 2). A card test of what a bare command costs (ignored by default): cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture Known: about 3 to 5 frames a second; more than half of the texture memory on the card is held for levels the title has not loaded yet (next). Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/copystat.rs | 5 + crates/victory-gpu/src/descriptor/host.rs | 286 +++++++++- crates/victory-gpu/src/draw.rs | 463 +++++++++++++++- crates/victory-gpu/src/host.rs | 114 +++- crates/victory-gpu/src/indirect.rs | 601 +++++++++++++++++++++ crates/victory-gpu/src/resource.rs | 217 ++++++++ crates/victory-gpu/src/shadow.rs | 94 ++++ crates/victory-gpu/src/texture.rs | 10 + crates/victory-hle/src/modules/dstorage.rs | 49 ++ 9 files changed, 1807 insertions(+), 32 deletions(-) diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 4a2b785..204b6c4 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -690,6 +690,11 @@ fn log_memory() { let card = crate::host::host() .and_then(|h| h.video_memory()) .unwrap_or_default(); + // Everything the system says of the two memory groups, beside the + // budget and use the lines below print. + if let Some(h) = crate::host::host() { + h.log_video_memory("with the memory line"); + } // What else holds memory: the map, on a thread of its own, with every // sixth line; and what the shader table and the pipeline library keep. static LINES: AtomicU64 = AtomicU64::new(0); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b2c27c5..7b18b45 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -89,16 +89,25 @@ pub(crate) struct HostHeap { } /// Title memory by the placed texture views that describe it: per span of -/// memory (its start, its end) the title slots holding a view of a -/// texture that takes exactly that span. Spans never overlap: a console -/// title need not clear a descriptor when it streams a texture out, so a -/// view written over memory that older views describe otherwise (another -/// start or another length: another texture) is all that says the older -/// ones are stale. Views of one span with different descriptions (the -/// formats of one family, say) are one texture's. +/// memory (its start, its end at full size) the title slots holding a +/// view of a texture that takes exactly that span. A console title need +/// not clear a descriptor when it streams a texture out, so a newer view +/// that cannot be there together with an older one is all that says the +/// older one is stale ([`Rule`] says when that is). Views of one span with +/// different descriptions (the formats of one family, say) are one +/// texture's. +/// +/// Spans may overlap: a texture's smallest levels lie at the start of its +/// memory, and a title that holds only those puts the next texture where +/// the larger ones would be (the title: three 512x256 textures +/// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all +/// three read by the same frame's draws, run 188). What is there of a +/// texture ends where the next one starts. /// No host heap is needed, so it is tested without one. #[derive(Default)] pub(crate) struct Spans { + /// When a newer view makes an older one stale. + rule: Rule, by_start: std::collections::BTreeMap)>, by_slot: std::collections::HashMap, /// The bytes a placed texture takes, by resource description: worked @@ -107,6 +116,32 @@ pub(crate) struct Spans { sizes: std::collections::HashMap<[u32; 14], Option>, } +/// When a view the title writes makes an older view of other memory stale. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Rule { + /// When it starts where the older one starts: at the same address + /// with another length, or within the older one's first [`HEAD`] + /// bytes (or the older within its own). No two textures share the + /// block of their smallest levels. A view that only reaches into the + /// address range of an older texture's larger levels says nothing. + #[default] + Start, + /// Whenever their spans at full size overlap (the rule until run + /// 188, where it made null the slots of textures packed as above: + /// each view written took its neighbours out of the queue and off the + /// card, for good). `VICTORY_STALE_TEXTURES=overlap`. + Overlap, + /// Never; a view that would be stale under [`Rule::Overlap`] is left + /// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before. + Never, +} + +/// The first bytes of a placed texture that are its own under +/// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129 +/// pairs of overlapping neighbours in the listings of runs 188 and 189, +/// none starts closer than 0x2000 to the one before it.) +const HEAD: u64 = 4096; + impl Spans { /// The bytes of title memory a placed texture with the resource /// description `desc` takes (`crate::resource::placed_bytes`). @@ -119,7 +154,10 @@ impl Spans { bytes } - /// The starts of the spans that overlap `[start, end)`. + /// The starts of the spans that overlap `[start, end)`, each taken to + /// end where the next one starts: the last span that starts before + /// `start`, if it reaches past it at full size, and every span that + /// starts inside. fn overlapping(&self, start: u64, end: u64) -> Vec { let before = self .by_start @@ -131,10 +169,10 @@ impl Spans { } /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: - /// the title wrote it now, so the slots whose views describe that - /// memory otherwise are stale: they are returned, and forgotten. - /// Otherwise (a draw made the slot from what it held) a view that - /// overlaps other spans is left out. + /// the title wrote it now, so the slots whose views cannot be there + /// with it ([`Rule`]) are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held), and under + /// [`Rule::Never`], a view that clashes with other spans is left out. fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { @@ -144,15 +182,40 @@ impl Spans { if end <= start { return Vec::new(); } + let rule = self.rule; + // The spans the view cannot be there with. + let clashing: Vec = match rule { + Rule::Start => self + .by_start + .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD)) + .map(|(at, _)| *at) + .collect(), + Rule::Overlap | Rule::Never => self.overlapping(start, end), + }; let mut stale = Vec::new(); - for at in self.overlapping(start, end) { + for at in clashing { if at == start && same(self.by_start.get(&at)) { continue; } - if !newer { + if !newer || rule == Rule::Never { return stale; } - if let Some((_, slots)) = self.by_start.remove(&at) { + if let Some((old_end, slots)) = self.by_start.remove(&at) { + // The first of them are said with both spans, to tell a + // replacement from a neighbour in one launch's log. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 { + tracing::info!( + slot = index, + start = format_args!("{start:#x}"), + end = format_args!("{end:#x}"), + stale_start = format_args!("{at:#x}"), + stale_end = format_args!("{old_end:#x}"), + stale_slots = slots.len(), + rule = ?rule, + "a placed texture view makes older views of other memory stale" + ); + } for slot in slots { self.by_slot.remove(&slot); stale.push(slot); @@ -206,11 +269,18 @@ static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; -/// Whether a view written over memory that older views describe otherwise -/// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are. -fn stale_out() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0")) +/// When a view the title writes makes older views of other memory stale +/// ([`Rule`]): where it starts in the block of their smallest levels, by +/// default; `VICTORY_STALE_TEXTURES=0`: never, as before; +/// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule +/// until run 188. +fn stale_rule() -> Rule { + static RULE: std::sync::OnceLock = std::sync::OnceLock::new(); + *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() { + Ok("0") => Rule::Never, + Ok("overlap") => Rule::Overlap, + _ => Rule::Start, + }) } /// The runtime mapped or unmapped title memory `[at, at + len)`, or is @@ -856,6 +926,20 @@ impl HostHeap { (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) } + /// Every title slot of the queue that is due at `frame`, and whether + /// it was uploaded before (in part, or whole and waiting for another + /// look): for the card accounting line + /// (`crate::resource::card_accounting`). + pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures + .slots + .iter() + .filter(|(_, w)| w.due <= frame) + .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0)) + .collect() + } + /// The texture view of title slot `index` (as handed out with `write`) /// was brought up to date: due again from frame `again` (uploaded with /// that many bytes of its memory there, not all), or not until the @@ -934,6 +1018,36 @@ impl HostHeap { slots.len() } + /// Whether host slot `index` is made from the very record the title + /// has at `handle` now. Its host texture then exists (a slot keeps what + /// it views), so bringing that texture up to date takes no memory of + /// the card. + pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool { + if index >= self.count { + return false; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let key = u64::from(generation) << 32 | u64::from(i); + if tag != VIEW_TAG { + return false; + } + // And the slot holds a host resource: a slot is also noted as made + // from a view the host could not make (`make` gave nothing, the + // slot is null and keeps nothing). The host copy of such a + // texture is held by no slot, may have been let go, and would be + // made anew here, with the card full. `made` first, then `kept`, + // 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) + } + /// The memory of the texture title slot `index` views is not mapped /// (any more): a host slot made from it becomes null again, so that /// the host copy can be let go (`crate::resource::let_go_idle`; a slot @@ -1103,7 +1217,8 @@ impl HostHeap { Some((start, end)) => { SPANNED[0].fetch_min(start, Relaxed); SPANNED[1].fetch_max(end, Relaxed); - placed.note(index, start, end, !seen && stale_out()) + placed.rule = stale_rule(); + placed.note(index, start, end, !seen) } None => { placed.forget(index); @@ -1412,6 +1527,24 @@ impl HostHeap { 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 + /// `index` at `frame`, in a few words (diagnostics). + #[cfg(feature = "diagnostics")] + pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match textures.slots.get(&index) { + None => "not queued".into(), + Some(w) => format!( + "queued due={} written@{} looks={} part_mapped={} recheck={}", + if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, + w.written, + w.looks, + w.mapped, + w.checked.2 != 0 + ), + } + } + /// The view host slot `index` was made from, in a few words, with the /// title and host addresses of a buffer view (diagnostics). "null" for /// a slot never made or left null. @@ -2433,11 +2566,116 @@ mod tests { assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); } - /// A view written over memory that older views describe otherwise - /// makes those stale; views of the same span are one texture's. + /// Textures of which only the smallest levels are held, packed into + /// one another's address range (the three of run 188: 0x2c000 bytes + /// each at full size, their starts 0x2000 and 0x4000 apart): writing + /// any of them, in any order and again, leaves the others. + #[test] + fn packed_neighbours_stay() { + let mut spans = Spans::default(); + assert_eq!(spans.rule, Rule::Start); + let at = 0xb_86bf_8000u64; + let (a, b, c) = (at, at + 0x2000, at + 0x6000); + assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty()); + // The first written again (as a title does when levels arrive), + // from another slot too: its span reaches over the other two. + assert!(spans.note(7, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + let mut all = spans.slots_in(0, u64::MAX); + all.sort_unstable(); + assert_eq!(all, [7, 105_998, 106_004, 108_521]); + // A draw makes a slot of the second texture: it is one of them. + assert!(spans.note(9, b, b + 0x2c000, false).is_empty()); + assert_eq!(spans.by_slot.get(&9), Some(&b)); + } + + /// A texture written where another starts replaces it: at the same + /// address with another length, or inside the block of its smallest + /// levels. The packed neighbours of the one replaced stay. + #[test] + fn a_texture_written_at_the_start_of_another_replaces_it() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + // Another length from the same start: slot 1 is stale, slot 2 not. + assert_eq!(spans.note(3, at, at + 0xb000, true), [1]); + // A start inside the first 4 KiB of slot 3's texture: stale too. + assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]); + // And the other way: a texture that starts just before one. + assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]); + let mut left = spans.slots_in(0, u64::MAX); + left.sort_unstable(); + assert_eq!(left, [4, 5]); + // Exactly 4 KiB apart: both there. + assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty()); + // A draw's view that clashes is left out, and nothing is stale. + assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty()); + assert_eq!(spans.by_slot.get(&8), None); + assert_eq!(spans.by_slot.len(), 3); + } + + /// A slot written with another texture leaves its old span; the same + /// view written again changes nothing. + #[test] + fn a_slot_rewritten_moves_to_its_new_span() { + let mut spans = Spans::default(); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty()); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [1]); + // Slot 1 now views a texture far away. + assert!(spans.note(1, 0x90000, 0x91000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x12000, 0x12001), [2]); + assert_eq!(spans.slots_in(0x90000, 0x90001), [1]); + spans.forget(1); + spans.forget(2); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps, unmaps or writes names the textures that + /// are there: among packed neighbours the one whose held levels the + /// range lies in (it ends where the next one starts), and the ones + /// that start inside the range. + #[test] + fn memory_changed_under_packed_neighbours_names_the_ones_there() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // Inside the first one's held levels. + assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]); + // Inside the second's: not the first, which ends where it starts. + assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]); + // Past the last start: the last one. + assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]); + // A range over all of them. + assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]); + // Past the end of all: none. + assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); + } + + /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that + /// overlaps others is left out of the spans, as before. + #[test] + fn never_stale_leaves_overlapping_views_out() { + let mut spans = Spans { rule: Rule::Never, ..Default::default() }; + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x2000, 0x4000, true).is_empty()); + assert!(spans.note(3, 0x1000, 0x2000, true).is_empty()); + assert_eq!(spans.slots_in(0, u64::MAX), [1]); + } + + /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view + /// written over memory that older views describe otherwise makes + /// those stale; views of the same span are one texture's. #[test] fn a_newer_view_of_other_memory_makes_the_older_stale() { - let mut spans = Spans::default(); + let mut spans = Spans { rule: Rule::Overlap, ..Default::default() }; // Three textures side by side, the first in two slots. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c018811..29f34cf 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -381,6 +381,18 @@ const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; /// was, and that found it changed (uploaded again), since the start. pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// Uploads of textures already on the card made while it had no room for +/// new ones, since the start. +pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); + +/// Whether a texture that has its host copy is still brought up to date +/// while the card has no room for new ones (`VICTORY_REUPLOAD_WHEN_FULL=0`: +/// no). +fn reupload_when_full() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0")) +} + /// Whether textures picked by index are looked at again after their upload /// (`VICTORY_HEAP_RECHECK=0`: no). fn heap_recheck() -> bool { @@ -913,6 +925,9 @@ impl State { let l = &list.list; // Textures picked by index, before anything asks for them. self.early_textures(list, p, compute); + if crate::host::walls_trace() { + self.walls_census(p, compute); + } // Heaps first: a root signature with directly indexed heaps must be // set after them. if self.host_heaps != self.heaps { @@ -1550,6 +1565,77 @@ impl State { } } + /// The queue's side of the card accounting line + /// (`crate::resource::card_accounting`, which says what the line + /// holds): the slots that are due, by what their texture has on the + /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass + /// that finds the card without room, and every five seconds after it. + /// Nothing is made, uploaded or counted as used here. For 18,000 due + /// slots: 18,000 looks at a title slot and at the texture it views, a + /// lock each, some milliseconds of the thread that records the frame. + fn card_accounting( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + room: bool, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) { + return; + } + // When the next line is due (0: none yet, the card has had room). + static NEXT: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let next = NEXT.load(Ordering::Relaxed); + let due_now = if next == 0 { !room } else { now >= next }; + if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + // Due slots; of them uploaded before; of them viewing nothing the + // title fills; and the textures (each once) whose host copy is + // alive, with their bytes on the card. + let mut due = [0u64; 5]; + // Textures (each once) that never had a host copy, and ones whose + // host copy was let go: where their memory is, and its bytes. + let (mut never, mut gone) = (Vec::new(), Vec::new()); + let mut seen = std::collections::BTreeSet::new(); + for (index, uploaded) in host.texture_slots_all_due(frame) { + due[0] += 1; + due[1] += u64::from(uploaded); + let state = match heap.handle(index).and_then(crate::descriptor::view) { + Some(View::Placed(false, resource, desc)) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + match crate::resource::placed_known(address, &resource) { + Some(texture) => crate::resource::copy_state(texture), + // No title texture was made for it: the pass never + // got as far as making one. + None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)), + } + } + Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => { + crate::resource::copy_state(object as This) + } + _ => None, + }; + let Some((state, bytes, memory)) = state else { + due[2] += 1; + continue; + }; + if !seen.insert(memory) { + continue; + } + match state { + 2 => { + due[3] += 1; + due[4] += bytes; + } + 1 => gone.push((memory, bytes)), + _ => never.push((memory, bytes)), + } + } + crate::resource::card_accounting(room, due, never, gone); + } + /// The texture side of [`State::heap_buffers`]: textures the title fills /// itself (streamed pages, layout-library copies) whose views sit in the /// view heap are created (placed textures have no host texture until @@ -1609,6 +1695,10 @@ impl State { for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { count.store(now, Ordering::Relaxed); } + // Where the card's memory is, and what the due slots would need + // (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no + // room, and every five seconds after it). + Self::card_accounting(heap, host, frame, room); // The frames in about four seconds, between 16 and 256: how long a // slot with nothing to upload waits at most for its next look. In // frames alone it was 120: four minutes at the opening cutscene's @@ -1738,12 +1828,35 @@ impl State { } // From here on a host texture is made: not without room. The // slot stays due. + // Not so a slot already made from this very view: its host + // texture exists, and uploading it again takes none of the + // card's memory. It was refused all the same, so a texture the + // title filled after its first upload kept its empty host copy + // from the moment the card reached the line, which is the first + // world frame in eight launches of nine: the same slots were + // found changed again at every pass and never uploaded (run + // 179: 33,000 such findings), and the main character's face + // had its colour only in the launches that entered the world + // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as + // before. if !room { - refused += 1; - if refused > 256 { - break; + let has_its_texture = reupload_when_full() + && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + if !has_its_texture { + refused += 1; + if refused > 256 { + break; + } + continue; + } + let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(500) { + tracing::info!( + so_far = n, + slot = index, + "a texture already on the card is brought up to date although the card has no room for new ones" + ); } - continue; } let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); @@ -1976,9 +2089,180 @@ impl State { } } let _ = write!(text, " tables {:?}", self.reads(compute)); + if !compute && !list_slots().is_empty() { + text.push_str(&self.slots_text()); + } text } + /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS` + /// names: the heap slots it will pick textures from by index, and what + /// the title and the host hold there (one `~slot` line each), with the + /// words they were read from (`~raw` lines, to decode offline what is + /// not decoded here). + /// + /// Where the slots are, for the title's character shaders + /// (`PS_DeferredPedTexturedNC`, from their native code): in the small + /// buffers and constants of the draw's own table (every word of those + /// that names a texture view gets a line); in the material record, at + /// the byte offset the draw's constants (table 1, dword 56) hold at + /// 0x1c, of the buffer at table 0, dword 160; and in the record at the + /// byte offset the second root constant holds of the buffer at table 0, + /// dword 688. A word that is a small number by chance and names a + /// texture gets a line too. + #[cfg(feature = "diagnostics")] + fn slots_text(&self) -> String { + use std::fmt::Write; + const MATERIALS: u32 = 160; + const GLOBAL: u32 = 688; + const DRAW_CONSTANTS: u32 = 56; + let wanted = list_slots(); + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return String::new(); + }; + let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) + else { + return String::new(); + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return String::new(); + }; + let t = stage.translated(); + let mut text = String::new(); + let entry = |slot: u8, dwords: u32| -> Option { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::view(table + u64::from(dwords) * 4) + }; + let mut material = None; + for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) { + let label = format!("s{}+{}", u.slot, u.table_offset_dwords); + let Some(view) = entry(u.slot, u.table_offset_dwords) else { + let _ = write!(text, "\n ~table {label} no view"); + continue; + }; + let range = match &view { + View::Constant(address, size) => Some((*address, u64::from(*size))), + other => crate::descriptor::host::buffer_range(other), + }; + match range { + // A small buffer or constants: its words. + Some((address, len)) if len <= 2048 => { + Self::slot_words(&mut text, heap, &label, address, len as usize); + if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 { + let mut word = [0u8; 4]; + if crate::host::read_into((address + 0x1c) as *const u8, &mut word) { + material = Some(u32::from_le_bytes(word)); + } + } + } + Some(_) => {} + // A texture read through the table: the title slot it sits in. + None => { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else { + continue; + }; + match heap.index(table + u64::from(u.table_offset_dwords) * 4) { + Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)), + None => { + let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view))); + } + } + } + } + } + let uses = |slot: u8, dwords: u32| { + t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords) + }; + if let Some(at) = material + && uses(0, MATERIALS) + && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "M", base + at, 64); + } + if at + 1936 + 512 <= len { + Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512); + } + } + if uses(0, GLOBAL) + && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot) + && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot)) + && let Some(&at) = words.get(1) + && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "G", base + at, 64); + } + } + text + } + + /// Up to 512 bytes of title memory at `address` as hex words (a `~raw` + /// line), and a `~slot` line for every word of them that names a + /// texture view in `heap`. + #[cfg(feature = "diagnostics")] + fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) { + use std::fmt::Write; + let mut bytes = vec![0u8; len.min(512) & !3]; + if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) { + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable"); + return; + } + let words: Vec = + bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect(); + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:"); + for w in &words { + let _ = write!(text, " {w:08x}"); + } + for (i, &index) in words.iter().enumerate() { + let names = index != 0 + && heap + .handle(index) + .and_then(crate::descriptor::view) + .as_ref() + .is_some_and(crate::descriptor::host::is_texture_view); + if names { + text.push_str(&Self::slot_line(heap, label, i * 4, index)); + } + } + } + + /// One `~slot` line: where the slot number was read (`from`, byte + /// `at`), what the title's heap holds in slot `index` with the state + /// of that texture ([`view_state`]), what the host slot was made from, + /// and what the queue of textures picked by index knows of it. + #[cfg(feature = "diagnostics")] + fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String { + let title = heap.handle(index).and_then(crate::descriptor::view); + let host: String = heap + .host() + .and_then(|h| h.describe_slot(index)) + .unwrap_or_else(|| "none".into()) + .chars() + .take(90) + .collect(); + let queue = match heap.host() { + Some(h) => h.texture_slot_state(index, crate::frame::current()), + None => "no host heap".into(), + }; + format!( + "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]", + view_state(title.as_ref()) + ) + } + /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel: /// the scissors before it (`on`), the title's after it. fn mesh_scissor(&self, list: &HostList, on: bool) { @@ -2022,6 +2306,74 @@ impl State { } } + /// The walls trace (`crate::host::walls_trace`): one log line per + /// frame with the draws of its main pass (four or more colour targets) + /// by scissor rectangle, and how often each of the title's culling + /// programs was dispatched. The title clips what it draws + /// through a window or door to that opening's rectangle while it holds + /// the camera to be in a room (run 182, frame 1529: 1,386 draws under + /// `531 0 1789 1337`); in a launch without the room's walls the same + /// shot has no such rectangle (run 187, frame 1414). The line shows + /// the frame in which that changes. + fn walls_census(&self, p: &HostPipeline, compute: bool) { + const CULL: [(&str, &str); 9] = [ + ("55679a0547649d0b", "tree"), + ("89d08e561897d4e5", "tree_imposter"), + ("9209777e8face9dd", "grass"), + ("17af15c4015cb4b6", "prop"), + ("fdd56d97a806bcca", "prop_nocull"), + ("42f717f1b4d18e94", "simple"), + ("1c4b3c0547e3e6fa", "slod"), + ("9146291b38ea9ce1", "meshlet_args"), + ("42683eebec081520", "depth_pyramid_cpu_occlusion"), + ]; + type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]); + static CENSUS: std::sync::Mutex = + std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9])); + let frame = crate::frame::current(); + let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + if census.0 != frame { + let draws: u32 = census.1.values().sum(); + if draws > 0 { + let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); + rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + let scissors: Vec = rects + .iter() + .take(5) + .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3])) + .collect(); + let counts = census.2; + let culling: Vec = CULL + .iter() + .zip(counts) + .filter(|(_, n)| *n > 0) + .map(|(c, n)| format!("{}={n}", c.1)) + .collect(); + tracing::info!( + frame = census.0, + main_pass_draws = draws, + rectangles = rects.len(), + scissors = ?scissors, + culling = ?culling, + "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches" + ); + } + census.0 = frame; + census.1.clear(); + census.2 = [0; 9]; + } + if compute { + for (i, c) in CULL.iter().enumerate() { + if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) { + census.2[i] += 1; + } + } + } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 { + let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]); + *census.1.entry(r).or_insert(0) += 1; + } + } + fn roots_ref(&self, compute: bool) -> &Vec { if compute { &self.compute @@ -2816,6 +3168,109 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { } } +/// The pixel shaders whose draws get their slots listed +/// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated +/// by commas. None by default. +#[cfg(feature = "diagnostics")] +fn list_slots() -> &'static [String] { + static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); + LIST.get_or_init(|| { + std::env::var("VICTORY_LIST_SLOTS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| !s.is_empty()) + .collect() + }) +} + +/// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of +/// 4 KiB of zeros it is always the same value, which `slots.py` knows), or +/// "unreadable". +#[cfg(feature = "diagnostics")] +fn print_4k(at: u64) -> String { + let mut bytes = [0u8; 4096]; + if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) { + return "unreadable".into(); + } + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for b in bytes { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{hash:016x}") +} + +/// The `bytes` of title memory at `at`: how many are mapped, and the +/// fingerprints of the first and the last 4 KiB (a texture's smallest +/// levels lie first, its largest last). +#[cfg(feature = "diagnostics")] +fn memory_state(at: u64, bytes: u64) -> String { + let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize); + let last = at + bytes.saturating_sub(4096); + format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last)) +} + +/// Title texture `this` for the frame listing: its size, whether it has a +/// host copy (not made here), its staging buffer's state, whether the host +/// copied into it, and its memory ([`memory_state`]). +#[cfg(feature = "diagnostics")] +fn texture_state(this: This) -> String { + let Some((at, desc)) = crate::resource::texture_memory(this) else { + return "not a texture".into(); + }; + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + let staged = match crate::texture::staged_state(this) { + Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"), + None => "staged=no".into(), + }; + format!( + "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}", + u64::from(words[4]) | u64::from(words[5]) << 32, + words[6], + words[8], + words[7] >> 16, + crate::resource::host_made(this).is_some(), + crate::texture::host_wrote(this as usize), + crate::resource::title_fills(this), + memory_state(at as u64, bytes) + ) +} + +/// A view of the title's heap for the frame listing: a texture with its +/// state ([`texture_state`]; a placed one that has no resource yet with +/// its memory alone), anything else in a few words. +#[cfg(feature = "diagnostics")] +fn view_state(view: Option<&View>) -> String { + match view { + None => "no view".into(), + Some(View::Placed(false, r, d)) if r[0] != 1 => { + let address = u64::from(d[10]) | u64::from(d[11]) << 32; + let state = match crate::resource::texture_at_made(address, r) { + Some(this) => texture_state(this), + None => format!( + "{}x{} f{} levels={} resource=none {}", + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[7] >> 16, + memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) + ), + }; + format!("placed texture view_format={} {state}", d[0]) + } + Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { + format!( + "texture object {r:#x} view_format={} {}", + d.as_ref().map_or(0, |d| d[0]), + texture_state(*r as This) + ) + } + Some(v) => format!("{v:?}").chars().take(80).collect(), + } +} + /// A view in a few words (diagnostics builds). #[cfg(feature = "diagnostics")] fn describe(view: Option<&View>) -> String { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b384328..492ae72 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2692,6 +2692,19 @@ fn declared_writes(runs: &[&HostList]) -> Vec { back } +/// The walls trace (`VICTORY_WALLS_TRACE=1` or `2`; off by default): log +/// lines that say what the title's CPU was given while it decided whether +/// the camera is in a room. The values of the small read-backs +/// ([`read_backs`]), the frame's main pass by scissor rectangle with its +/// culling dispatches (`draw.rs`, `walls_census`), the shader-written +/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host +/// copies found stale after their refresh (`shadow.rs`), and, in the +/// runtime, the read requests that fail (with 2: every request). +pub(crate) fn walls_trace() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2")) +} + /// After `list` has run: the texels its read-backs copied into host /// buffers of ours go to the title's memory (`HostList::defer_read_back`). /// @@ -2711,6 +2724,19 @@ fn read_backs(list: &HostList) { for line in 0..*rows { std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row); } + // The walls trace: what the title is handed (one row of at + // most 24 values: its 5x1 and 1x1 float targets). + if walls_trace() && *rows == 1 && *row <= 96 { + let mut values = [0f32; 24]; + std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::(), *row & !3); + tracing::info!( + frame = crate::frame::current(), + to = format_args!("{:#x}", *at), + bytes = *row, + values = ?&values[..*row / 4], + "walls trace: a read-back lands in title memory" + ); + } buffer.Unmap(0, None); } } @@ -3424,7 +3450,9 @@ impl Host { // SAFETY: the mapping of the fetched bytes, `total` of them; // the copy into it has run. let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; - written += shadow.card_merge_relay(*lo, gpu, after, &mut title); + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged; } COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); // Sends up to `after` are of no use to any later merge. @@ -3653,7 +3681,9 @@ impl Host { // the copy into it has run, and the caller // waits for this job. let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) }; - counts[i].fetch_add(shadow.card_merge(lo, gpu, &mut title), Ordering::Relaxed); + let merged = shadow.card_merge(lo, gpu, &mut title); + shadow.walls_merged(gpu.len(), merged); + counts[i].fetch_add(merged, Ordering::Relaxed); } }) as Box }) @@ -3668,7 +3698,9 @@ impl Host { // SAFETY: the mapping of the fetched bytes, `total` of // them; the copy into it has run. let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; - written[i] += plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + plan.ranges[i].shadow.walls_merged(gpu.len(), merged); + written[i] += merged; } } } @@ -5978,7 +6010,17 @@ impl Host { .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) }; match resized { - Ok(()) => (p.width, p.height, p.format) = (width, height, format), + Ok(()) => { + (p.width, p.height, p.format) = (width, height, format); + tracing::info!( + width, + height, + format = format.0, + frame, + "the swap chain's buffers were made again for another size or format" + ); + self.log_video_memory("right after the swap chain's buffers were made again"); + } Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); return None; @@ -6072,6 +6114,7 @@ impl Host { Some(hwnd) => hwnd, None => window(width, height)?, }; + self.log_video_memory("right before the swap chain is made"); // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; @@ -6094,6 +6137,7 @@ impl Host { let copy = self.new_list()?; copy.close(); tracing::info!(width, height, format = format.0, "presenting to a window"); + self.log_video_memory("right after the swap chain is made"); Ok(Presenter { swap_chain, width, @@ -6173,9 +6217,71 @@ impl Host { .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) .ok()?; } + // The card's budget moved by 256 MB or more since the last look: + // said at once, with what was in use at the last look, so the log + // has the moment. (It fell from 11,242 MB to some 10,300 MB with + // the first world frame in runs 179 to 185, and the memory line, + // seconds later, was the first to show it. We reserve nothing + // and make the swap chain once, at the start.) + static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; + let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); + if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { + tracing::info!( + "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", + last[0] >> 20, + own.Budget >> 20, + crate::frame::current(), + last[1] >> 20, + last[2] >> 20 + ); + self.log_video_memory("right after that change"); + } Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) } + /// Both of the system's memory groups for this process, in bytes: for + /// the card's own memory and then for the PC's memory shared with the + /// card, the budget, the use, what could still be reserved and what + /// is reserved (the layer reserves none). + pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { + [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] + }; + Some([all(&own), all(&shared)]) + } + + /// Logs [`Self::video_memory_groups`], with `when` it is said. + pub(crate) fn log_video_memory(&self, when: &str) { + let Some([own, shared]) = self.video_memory_groups() else { + return; + }; + tracing::info!( + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", + when, + own[0] >> 20, + own[1] >> 20, + own[2] >> 20, + own[3] >> 20, + shared[0] >> 20, + shared[1] >> 20, + shared[2] >> 20, + shared[3] >> 20 + ); + } + /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index bff1577..321cc63 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -1214,3 +1214,604 @@ void main() { list.reset(); } } + +/// What one small draw costs this card, bare and with one thing changed +/// between every two draws: a measurement, not a check (it asserts only +/// that the card answered). The timing run of the lit scene (run 187) has +/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no +/// log says whether that is what we put around a command or what the card +/// takes for one. Each variant here is 10,000 one-triangle draws into a +/// 2560x1440 target, timed on the card by one pair of timestamps around +/// the whole batch (not one per command, which would time the stamps). +/// +/// Run by name, no game needed: +/// `cargo test -p victory-gpu --release -- --ignored bare_command_cost --nocapture` +#[cfg(test)] +mod bare_cost { + use windows::Win32::Foundation::{HANDLE, RECT}; + use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use crate::host::{compile, transition}; + + /// Draws in a batch. + const DRAWS: u32 = 10_000; + const WIDTH: u32 = 2560; + const HEIGHT: u32 = 1440; + + /// One small triangle in the middle of the target (about 180 pixels), + /// and two pixel programs that read one texel of a texture through a + /// table, so that the view heap set is in use. + const DRAW: &str = r#" +#define RS "DescriptorTable(SRV(t0))" +Texture2D image : register(t0); +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 0.02 - 0.01, 0.5, 1.0); +} +[RootSignature(RS)] +float4 first(float4 at : SV_Position) : SV_Target { + return image.Load(int3(0, 0, 0)); +} +[RootSignature(RS)] +float4 second(float4 at : SV_Position) : SV_Target { + return 1.0 - image.Load(int3(0, 0, 0)); +} +"#; + + /// A compute pass of next to nothing, as our clamp of an indirect + /// record is: one group of one thread that writes one word. + const WORK: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void work() { + words.Store(0, words.Load(0) + 1); +} +"#; + + /// What changes between every two draws of a batch. + #[derive(Clone, Copy, PartialEq)] + enum Between { + /// Nothing. + Nothing, + /// The pipeline: two alternate. + Pipeline, + /// A second texture goes from target to shader read and back. + BarrierPair, + /// The depth texture bound for testing goes from write to read or + /// back. + DepthMove, + /// The pair of descriptor heaps: two pairs alternate. + Heaps, + /// The colour target: two alternate. + Targets, + /// A compute pass of ours of one group, and the pipeline back. + Compute, + /// The same between two waits for every earlier shader write, as + /// the clamp records them. + ComputeWithWaits, + } + + struct Rig { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + root: ID3D12RootSignature, + pipelines: [ID3D12PipelineState; 2], + work_root: ID3D12RootSignature, + work: ID3D12PipelineState, + words: ID3D12Resource, + other: ID3D12Resource, + depth: ID3D12Resource, + /// Kept alive: the views below name them. + _kept: Vec, + _target_heaps: [ID3D12DescriptorHeap; 2], + heap_pairs: [[Option; 2]; 2], + tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], + targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, + depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + card: String, + } + + fn texture( + device: &ID3D12Device, + (width, height): (u32, u32), + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain texture creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn buffer( + device: &ID3D12Device, + size: u64, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + let flags = if visible { + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + } else { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE + }; + // SAFETY: plain heap creation. + unsafe { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + } + } + + fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + // SAFETY: the description points at live data and never releases + // its pointer to the root signature. + unsafe { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + VS: code(vs), + PS: code(ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Depth is tested and never written, so the texture may be + // in the write state or in the read state under one view. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + device.CreateGraphicsPipelineState(&desc).unwrap() + } + } + + impl Rig { + /// The default adapter, as the layer takes it; `None` without one + /// or on a software adapter. + fn new() -> Option { + let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; + let ps = [ + compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, + compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, + ]; + let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; + // SAFETY: plain object creation on a device of our own; the + // views are made in heaps that live as long as the rig. + unsafe { + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok()? + .cast::() + .ok()? + .GetDesc1() + .ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let card = String::from_utf16_lossy(&desc.Description) + .trim_end_matches('\0') + .to_owned(); + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; + let pipelines = [ + pipeline(&device, &root, &vs, &ps[0]), + pipeline(&device, &root, &vs, &ps[1]), + ]; + let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; + let work: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&work_root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + + let size = (WIDTH, HEIGHT); + let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let target = [ + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + ]; + let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); + let depth = texture( + &device, + size, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let image = texture( + &device, + (4, 4), + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + ); + let words = buffer( + &device, + 64 << 10, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + let back = buffer( + &device, + 16, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut stamps: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut stamps, + ) + .ok()?; + let stamps = stamps?; + + // Target and depth views. + let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); + let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; + targets[1].ptr += rtv_step; + device.CreateRenderTargetView(&target[0], None, targets[0]); + device.CreateRenderTargetView(&target[1], None, targets[1]); + let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); + let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); + let mut depth_tested = depth_written; + depth_tested.ptr += dsv_step; + device.CreateDepthStencilView(&depth, None, depth_written); + let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); + + // Two pairs of shader-visible heaps: views (one view of the + // small texture each) and samplers (none used). + let view_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + ]; + let sampler_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + ]; + for views in &view_heaps { + device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + } + let tables = [ + view_heaps[0].GetGPUDescriptorHandleForHeapStart(), + view_heaps[1].GetGPUDescriptorHandleForHeapStart(), + ]; + let heap_pairs = [ + [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], + [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], + ]; + + // The first list: both targets and the depth texture cleared. + list.ClearRenderTargetView(targets[0], &[0.0; 4], None); + list.ClearRenderTargetView(targets[1], &[0.0; 4], None); + list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + let [first_target, second_target] = target; + let mut rig = Rig { + queue, + allocator, + list, + fence, + submitted: 0, + event, + root, + pipelines, + work_root, + work, + words, + other, + depth, + _kept: vec![first_target, second_target, image], + _target_heaps: [rtvs, dsvs], + heap_pairs, + tables, + targets, + depth_written, + depth_tested, + stamps, + back, + card, + }; + rig.finish(); + Some(rig) + } + } + + /// Closes the open list, runs it, waits for the card and opens the + /// list again. + fn finish(&mut self) { + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + /// What every list starts with: a new list has nothing set. + fn begin(&self) { + let l = &self.list; + // SAFETY: an open list and live objects and views. + unsafe { + l.SetDescriptorHeaps(&self.heap_pairs[0]); + l.SetGraphicsRootSignature(&self.root); + l.SetPipelineState(&self.pipelines[0]); + l.SetGraphicsRootDescriptorTable(0, self.tables[0]); + l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + // A triangle list. + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + } + } + + /// One batch of [`DRAWS`] draws in `lists` lists run one by one, + /// with `between` recorded before every draw: the microseconds a + /// draw took on the card, and the milliseconds recording took. + fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { + let (target, read, written, tested) = ( + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + let started = std::time::Instant::now(); + let mut drawn = 0u32; + for part in 0..lists { + let l = &self.list; + // SAFETY: an open list; our query heap; live objects. + unsafe { + if part == 0 { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + } + } + self.begin(); + // SAFETY: an open list with everything set; live objects. + // Every state moved is moved back within the batch (the + // draws of a list are an even number). + unsafe { + for _ in 0..DRAWS / lists { + let odd = (drawn % 2) as usize; + match between { + Between::Nothing => {} + Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), + Between::BarrierPair => { + l.ResourceBarrier(&[transition(&self.other, target, read)]); + l.ResourceBarrier(&[transition(&self.other, read, target)]); + } + Between::DepthMove => { + let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + l.ResourceBarrier(&[transition(&self.depth, from, to)]); + } + Between::Heaps => { + l.SetDescriptorHeaps(&self.heap_pairs[odd]); + l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); + } + Between::Targets => { + l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + } + Between::Compute | Between::ComputeWithWaits => { + let waits = between == Between::ComputeWithWaits; + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetComputeRootSignature(&self.work_root); + l.SetPipelineState(&self.work); + l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetPipelineState(&self.pipelines[0]); + } + } + l.DrawInstanced(3, 1, 0, 0); + drawn += 1; + } + if part + 1 < lists { + // The next list of the batch: this one is sent on + // its own and the list is opened again at once + // (the allocator is not reset before the card is + // done with all of them). + l.Close().unwrap(); + let run: ID3D12CommandList = l.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + l.Reset(&self.allocator, None).unwrap(); + } else { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + } + } + } + let recording = started.elapsed().as_secs_f64() * 1e3; + self.finish(); + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + // SAFETY: a read-back buffer the finished list resolved two + // timestamps into. + let ticks = unsafe { + self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let stamps = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + self.back.Unmap(0, None); + stamps[1].saturating_sub(stamps[0]) + }; + // SAFETY: a plain query of our queue. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); + (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + } + } + + #[test] + #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] + fn bare_command_cost() { + let Some(mut rig) = Rig::new() else { + eprintln!("no hardware adapter, or our shaders did not compile; skipped"); + return; + }; + eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + // The first batch pays for whatever the driver does at first use. + rig.batch(Between::Nothing, 1); + let variants = [ + ("(a) nothing changes between draws", Between::Nothing, 1), + ("(b) another pipeline every draw", Between::Pipeline, 1), + ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), + ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), + ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ("(f) another colour target every draw", Between::Targets, 1), + ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), + ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), + ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ]; + let mut least = Vec::new(); + for (name, between, lists) in variants { + let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!( + "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", + runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 + ); + least.push(runs[0].0); + } + assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index bb6a00a..e4fee24 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1402,6 +1402,210 @@ fn room_percent() -> u64 { }) } +/// For the card accounting line ([`card_accounting`]): the title texture +/// made for a view of memory at `address` with the resource description +/// `desc`, if there is one ([`texture_at`] makes it; this does not). +#[cfg(windows)] +pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option { + // Without the filler words and with them: whichever `texture_at` keeps. + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) +} + +/// For the card accounting line: whether title texture `this` has a host +/// copy now (2), had one that was let go and not made again (1), or never +/// had one (0); the bytes (its host copy's on the card, or without one +/// what its console layout takes in title memory); and where its title +/// memory is. `None` for buffers. Not a use of the texture. +#[cfg(windows)] +pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let memory = r.data() as u64; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + Some(match made.as_ref() { + Some((host, _)) => (2, host.bytes, memory), + None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), + }) +} + +/// One line of where the card's memory is and what the queue of textures +/// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs` +/// `card_accounting` says when, and hands over the queue's side: `room` +/// as the pass found it, `due` its counts, `never` and `gone` the memory +/// of the due textures without a host copy). The line holds +/// - the host copies of textures the title fills that are alive: how +/// many, their bytes, and the bytes of the levels whose title memory is +/// not mapped (a host copy is made with every level of the description; +/// a texture streaming in has its small levels only). A copy's bytes +/// are shared out to its levels by their texels, so that part is an +/// estimate; +/// - the due slots: how many, and their textures by what they have on +/// the card (a host copy alive: no card memory needed; never one; one +/// that was let go), with the bytes the last two would need and how +/// much of their memory is mapped now; +/// - the host copies let go, made again and made since the line before. +/// +/// The textures are noted under the table's lock (their memory, their +/// description, their copy's bytes: about a millisecond for 18,000) and +/// the kernel is asked about their memory on a thread of its own, after +/// the lock is given back: one question for a texture that is all there +/// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million +/// pages, some 20,000 questions), one per level and array slice more for +/// one that is not. Not measured: a tenth to half a second is expected, +/// and the line says what it took. No line is begun while one is walking. +#[cfg(windows)] +pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) { + use std::sync::atomic::Ordering::Relaxed; + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // Host copies let go and their bytes, made again and their bytes, and + // made in all, at the line before. + static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + if WALKING.swap(true, Relaxed) { + return; + } + let began = std::time::Instant::now(); + let mut copies: Vec<(usize, ResourceDesc, u64)> = Vec::new(); + // Textures the title fills without a host copy: never one, one let go. + let mut without = [0u64; 2]; + { + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) { + continue; + } + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, _)) => copies.push((r.data() as usize, r.desc, host.bytes)), + None => without[usize::from(r.host.gone.load(Relaxed))] += 1, + } + } + } + let kinds = KINDS.each_ref().map(|k| k.load(Relaxed)); + let mut since = [0u64; 5]; + for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) { + *slot = now.saturating_sub(before.swap(now, Relaxed)); + } + let video = crate::host::host().and_then(|h| h.video_memory()); + let noted_us = began.elapsed().as_micros() as u64; + let walk = move || { + fn texels(m: &texture::Mip) -> u64 { + u64::from(m.width) * u64::from(m.height) * u64::from(m.depth) + } + let began = std::time::Instant::now(); + // Copies; their bytes; the bytes of levels not mapped; copies with + // a level not mapped; with the largest level not mapped; with no + // level mapped; copies without a console layout (not asked). + let mut c = [0u64; 7]; + for &(memory, desc, bytes) in &copies { + c[0] += 1; + c[1] += bytes; + let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { + c[6] += 1; + continue; + }; + if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) { + continue; + } + c[3] += 1; + // Every slice holds the whole chain: the levels of the tail in + // its first block, the others after it from the smallest up + // (`victory_formats::texture::Layout`). + let mips = &layout.mips; + let tail = (layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + (0..u64::from(layout.slices)).all(|slice| { + let at = memory as u64 + slice * layout.slice_size + from; + crate::texture::committed(at as *const u8, (to - from) as usize) + }) + }; + let all: u64 = mips.iter().map(texels).sum::().max(1); + let (mut missing, mut any) = (0u64, false); + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset }; + if end <= m.offset { + continue; + } + if there(m.offset, end) { + any = true; + } else { + missing += texels(m); + c[4] += u64::from(level == 0); + } + } + if tail < mips.len() { + if there(0, layout.alignment.min(layout.slice_size).max(1)) { + any = true; + } else { + missing += mips[tail..].iter().map(texels).sum::(); + } + } + c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64; + c[5] += u64::from(!any); + } + // Of the due textures without a host copy: how many; the bytes of + // their memory; with all of it mapped, and those bytes; with part + // of it mapped, and the bytes that are; with none of it mapped. + let mapped = |list: &[(u64, u64)]| { + let mut n = [0u64; 7]; + for &(at, len) in list { + n[0] += 1; + n[1] += len; + let there = crate::texture::mapped_bytes(at as *const u8, len as usize); + if len > 0 && there >= len { + n[2] += 1; + n[3] += len; + } else if there > 0 { + n[4] += 1; + n[5] += there; + } else { + n[6] += 1; + } + } + n + }; + let (never, gone) = (mapped(&never), mapped(&gone)); + let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]); + let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] = + [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; + let [without_never, without_gone] = without; + let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20]; + let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] = + [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]]; + let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] = + [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; + let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; + let walk_ms = began.elapsed().as_millis() as u64; + tracing::info!( + "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ + fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ + with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \ + asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \ + {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \ + copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \ + all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ + copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ + {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own" + ); + WALKING.store(false, Relaxed); + }; + if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() { + WALKING.store(false, Relaxed); + } +} + /// Lets go of the host copies of textures the title fills that nothing /// names any more: placed textures were never released (one host texture /// per address and description ever viewed: 18,639 of them, 2.5 GB, after @@ -2067,6 +2271,19 @@ pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option { footprint(&d).map(|f| f.size) } +/// The resource [`texture_at`] made for a texture placed at `address` with +/// the description `desc`, if it has made one: never made here (for the +/// frame listing, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; + Some(*found as This) +} + /// The resource for a texture placed at `address` with the resource /// description `desc` (as words), made on first use. #[cfg(windows)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index da412f8..133e871 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2403,6 +2403,7 @@ impl Shadow { if let Some((now, written)) = crate::watch::writes(from, to, true) { self.watched.store(1, Ordering::Relaxed); let copied = self.copy_stale(from, to, now, &written); + self.refresh_check(from, to); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -2423,6 +2424,63 @@ impl Shadow { to - from } + /// Diagnostic (`VICTORY_REFRESH_CHECK=1`; off by default): after a + /// refresh of `[from, to)` that trusted the write watch or the guards, + /// the first 256 bytes of every 64 KiB block of it are read from title + /// memory and compared with the copy. A block that differs on three + /// refreshes in a row was changed with nothing to tell of it (a write + /// through another view of its pages, as DirectStorage's page + /// destinations make) and the card reads old bytes there: said with + /// the copy and the address. One that differs once is a write of the + /// title's that arrived between the refresh and the look. + fn refresh_check(&self, from: usize, to: usize) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1") || crate::host::walls_trace()) { + return; + } + const SAMPLE: usize = 256; + // Blocks found differing: how many refreshes in a row. + static DIFFERING: Mutex>> = Mutex::new(None); + static SAID: AtomicU64 = AtomicU64::new(0); + let start = self.start as usize; + let mut title = [0u8; SAMPLE]; + let mut at = from; + while at < to { + let n = SAMPLE.min(to - at); + if crate::host::read_into(at as *const u8, &mut title[..n]) { + // SAFETY: `[from, to)` lies inside the buffer (`update`), + // so these bytes are inside the copy's mapping. + let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(Default::default); + if copy == &title[..n] { + map.remove(&at); + } else { + let times = map.entry(at).or_insert(0); + *times += 1; + if *times == 3 { + let said = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if said <= 64 || said.is_power_of_two() { + tracing::warn!( + said, + copy = self.id, + copy_start = format_args!("{start:#x}"), + copy_bytes = self.len, + address = format_args!("{at:#x}"), + refreshed = format_args!("{from:#x}..{to:#x}"), + on_the_card = self.card.is_some(), + window = self.window, + "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (VICTORY_REFRESH_CHECK=1)" + ); + } + } + } + } + // The first bytes of the next 64 KiB block. + at = (at / PAGE + 1) * PAGE; + } + } + /// Copies the pages of `[from, to)` written after their last copy /// (`written`: last writes by page, in page order; `now`: this /// asking), whole pages within the buffer. @@ -2542,6 +2600,42 @@ impl Shadow { card_piece_of(self.start as usize, self.len as usize, span, i) } + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` + /// bytes of this copy came back from the card and `written` of them + /// went into title memory. Summed per buffer and logged once a frame: + /// which shader-written buffers the title's CPU could see fresh in + /// that frame, and how much of each changed. + pub(crate) fn walls_merged(&self, fetched: usize, written: usize) { + if !crate::host::walls_trace() { + return; + } + static SEEN: Mutex<(u64, BTreeMap)> = Mutex::new((0, BTreeMap::new())); + let frame = crate::frame::current(); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.0 != frame { + let buffers: Vec = seen + .1 + .iter() + .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3)) + .take(32) + .collect(); + if !buffers.is_empty() { + tracing::info!( + frame = seen.0, + count = seen.1.len(), + buffers = ?buffers, + "walls trace: shader-written card buffers merged into title memory in this frame" + ); + } + seen.1.clear(); + seen.0 = frame; + } + let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0)); + entry.1 += 1; + entry.2 += fetched as u64; + entry.3 += written as u64; + } + /// After a submission, for a copy in the card's memory: `gpu` is what /// the card's side holds at offset `at` on, in a piece the compare /// found differing. The bytes shaders wrote (those that differ from the diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 41d6f1e..34e7d51 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -915,6 +915,16 @@ pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { /// Whether a title texture has a staging buffer: a list recorded its /// upload, and the lists that sample it check it at submission. +/// For the frame listing: whether a list has uploaded `resource`'s staging +/// buffer, and whether it was detiled since. None: it has none. +#[cfg(feature = "diagnostics")] +pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { + use std::sync::atomic::Ordering::Relaxed; + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let staging = map.as_ref()?.get(&(resource as usize))?; + Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) +} + pub(crate) fn is_staged(resource: This) -> bool { let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index c066419..4c17b8e 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -141,10 +141,12 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out tracing::warn!(path = name, %error, "dstorage: opening a file failed"); return from_win32(&error); } + let kept = name.clone(); tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); put(out, file) } @@ -440,6 +442,52 @@ impl Scheduler { } } +/// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for +/// every read request that fails, with its file; 2: for every request (the +/// list of a launch's reads, by file and offset, is what a launch with the +/// first room's walls and one without are compared by). +fn walls_trace() -> u8 { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) + }) +} + +/// The files opened, by the address of our file object, with their paths +/// (for the walls trace: a request names its file by that address). +static WALLS_FILES: Mutex> = Mutex::new(Vec::new()); + +/// The walls trace's line for a request that is done. +fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) { + let level = walls_trace(); + if level == 0 || (level == 1 && result.is_ok()) { + return; + } + let file = if request.options & MEMORY_SOURCE != 0 { + "memory".to_string() + } else { + let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); + let source = request.source as usize; + files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) + }; + let hr = match result { + Ok(()) => 0, + Err(hr) => *hr as u32, + }; + tracing::info!( + file, + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + to_pages = request.options & PAGE_DESTINATION != 0, + options = format_args!("{:#x}", request.options), + ms = started.elapsed().as_millis() as u64, + ok = result.is_ok(), + hr = format_args!("{hr:#010x}"), + "walls trace: a read request is done" + ); +} + /// A worker: runs the next read of the most deserving queue. fn work(scheduler: &'static Scheduler) { let mut lanes = scheduler.lock(); @@ -451,6 +499,7 @@ fn work(scheduler: &'static Scheduler) { drop(lanes); let started = std::time::Instant::now(); let result = execute(&job.request); + walls_request(&job.request, &result, started); lanes = scheduler.lock(); lanes.finish(&job, result); lanes.count(&job, started); From bac2b33de2ce22354fc8c53987d3e97672c1ab88 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:29:09 -0600 Subject: [PATCH 2/5] Frame replay: where identical runs diverge; resources dying as a capture starts Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 101 ++ crates/victory-gpu/src/replay/play.rs | 140 ++- crates/victory-gpu/src/replay/play/diverge.rs | 1046 +++++++++++++++++ crates/victory-gpu/src/replay/record.rs | 13 +- crates/victory-gpu/src/replay/snap.rs | 37 +- 5 files changed, 1315 insertions(+), 22 deletions(-) create mode 100644 crates/victory-gpu/src/replay/play/diverge.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index cad167a..714009f 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -62,6 +62,12 @@ pub(crate) struct Replay { /// One ExecuteCommandLists for the whole frame. #[arg(long)] one_submit: bool, + /// A full wait after every draw, dispatch, copy and clear. + #[arg(long)] + wait_all: bool, + /// Each list sent on its own, and waited for. + #[arg(long)] + wait_lists: bool, /// Run only these lists, by their place in the frame (`3..7`, or `5`); /// of the others only barriers. #[arg(long)] @@ -70,6 +76,45 @@ pub(crate) struct Replay { /// (may be given several times). #[arg(long = "skip-shader")] skip_shader: Vec, + /// Find the commands that make identical runs differ: each list is run + /// this often from the same memory. + #[arg(long, num_args = 0..=1, default_missing_value = "3")] + diverge: Option, + /// Find where the picture's variants are decided: from each list on, the + /// rest of the frame is run this often from the same memory. + #[arg(long, num_args = 0..=1, default_missing_value = "5")] + diverge_picture: Option, + /// Run each draw of one list (--lists) whose pipeline's name has this in + /// it alone, --diverge times: how many outcomes it has. + #[arg(long)] + draws: Option, + /// Say which lists (with --lists: commands) change words of buffers: + /// `::` (hexadecimal; repeatable). + #[arg(long)] + watch: Vec, + /// With --diverge-picture and one list in --lists: its commands (`0..900`) + /// and how many are stepped over at a time. + #[arg(long)] + commands: Option, + #[arg(long, default_value_t = 1)] + step: usize, + /// With --diverge and --diverge-picture: only these lists (`3..7`). + #[arg(long)] + lists: Option, + /// With --diverge: the most commands named of one list. + #[arg(long, default_value_t = 4)] + roots: u32, + /// Name resources the frame changes that the replay does not put back. + #[arg(long)] + check_written: bool, + /// Name what the heap slots hold that a command's constants name: + /// `:`. + #[arg(long)] + slots: Option, + /// Only write the DXIL of pipelines with this in their name to the + /// capture's `shaders` folder. + #[arg(long)] + dump: Option, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -84,6 +129,12 @@ fn range(text: &str) -> Option<(u32, u32)> { } pub(crate) fn run(r: Replay) -> Result<()> { + if let Some(text) = &r.dump { + for line in play::dump(&r.folder, text)? { + println!("{line}"); + } + return Ok(()); + } let only = match &r.only { Some(text) => Some( range(text) @@ -107,11 +158,61 @@ pub(crate) fn run(r: Replay) -> Result<()> { skip_clamps: r.skip_clamps, skip_hash_passes: r.skip_hash_passes, one_submit: r.one_submit, + wait_all: r.wait_all, + wait_lists: r.wait_lists, only, skip_shaders: r.skip_shader, compare: r.compare, debug: r.debug_layer, }; + if let Some(text) = &r.slots { + let (list, command) = text + .split_once(':') + .and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?))) + .with_context(|| format!("--slots {text}: not :"))?; + let player = play::Player::load(&r.folder, &options)?; + return player.slots(list, command, &mut |line| println!("{line}")); + } + if r.check_written { + let mut player = play::Player::load(&r.folder, &options)?; + return player.check_written(&mut |line| println!("{line}")); + } + let mut watched = Vec::new(); + for text in &r.watch { + let mut n = text.split(':').map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16)); + let mut next = || n.next().and_then(Result::ok).with_context(|| format!("--watch {text}")); + let id = text.split(':').next().and_then(|p| p.parse().ok()).with_context(|| format!("--watch {text}"))?; + let _ = next(); + watched.push((id, next()?, next()?)); + } + if let Some(runs) = r.diverge.or(r.diverge_picture).or((!watched.is_empty()).then_some(2)) { + let lists = match &r.lists { + Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?), + None => None, + }; + let search = play::diverge::Search { + runs: runs.max(2), + lists, + roots: r.roots, + wait_all: options.wait_all, + options: options.clone(), + }; + let mut player = play::Player::load(&r.folder, &options)?; + if !watched.is_empty() { + return player.watch(&search, &watched, &mut |line| println!("{line}")); + } + if let Some(text) = &r.draws { + return player.diverge_draws(&search, text, &mut |line| println!("{line}")); + } + if r.diverge_picture.is_some() { + let commands = match &r.commands { + Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?), + None => None, + }; + return player.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}")); + } + return player.diverge(&search, &mut |line| println!("{line}")); + } let reports = play::replay(&r.folder, &options)?; for (what, report) in &reports { println!("{}", report.text(what)); diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 8543f6a..ba1543a 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -29,6 +29,8 @@ use super::wire::{ self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, }; +pub mod diverge; + /// The name of the argument clamp's pipeline, by which its passes are /// recognised. pub const CLAMP: &str = "victory: argument clamp"; @@ -67,6 +69,10 @@ pub struct Options { pub skip_clamps: bool, pub skip_hash_passes: bool, pub one_submit: bool, + /// A full wait after every command that works. + pub wait_all: bool, + /// Each list sent on its own, and waited for. + pub wait_lists: bool, /// Run only these lists (by their place in the frame). pub only: Option<(u32, u32)>, /// Skip what runs a pipeline whose name or shader hash has one of @@ -92,6 +98,8 @@ impl Default for Options { skip_clamps: false, skip_hash_passes: false, one_submit: false, + wait_all: false, + wait_lists: false, only: None, skip_shaders: Vec::new(), compare: false, @@ -107,6 +115,8 @@ impl Options { || self.skip_clamps || self.skip_hash_passes || self.one_submit + || self.wait_all + || self.wait_lists || self.only.is_some() || !self.skip_shaders.is_empty() } @@ -119,6 +129,8 @@ impl Options { skip_clamps: false, skip_hash_passes: false, one_submit: false, + wait_all: false, + wait_lists: false, only: None, skip_shaders: Vec::new(), ..self.clone() @@ -144,6 +156,8 @@ pub struct Report { /// Against the presented picture: dB (infinite: the same), and whether /// its bytes are the same. pub picture: Option<(f64, bool)>, + /// Of each loop's picture: dB against the presented one, and its hash. + pub pictures: Vec<(f64, String)>, /// Things to know: from the capture and the replay. pub notes: Vec, } @@ -205,6 +219,20 @@ impl Report { } None => {} } + if self.pictures.len() > 1 { + let all: Vec = self + .pictures + .iter() + .map(|(db, hash)| format!("{db:.1} dB {}", &hash[..8])) + .collect(); + let kinds: HashSet<&String> = self.pictures.iter().map(|p| &p.1).collect(); + let _ = writeln!( + t, + " pictures of the loops: {} different: {}", + kinds.len(), + all.join(", ") + ); + } for n in &self.notes { let _ = writeln!(t, " note: {n}"); } @@ -241,6 +269,43 @@ pub fn find(folder: &Path) -> Result { .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display())) } +/// Writes the DXIL of the pipelines whose name has `text` in it to `shaders` +/// in the capture, and the pipelines' descriptions; what was written. +pub fn dump(folder: &Path, text: &str) -> Result> { + let folder = find(folder)?; + let frame = Frame::read(&folder.join("frame.bin"))?; + let file = File::open(folder.join("shaders.bin"))?; + let to = folder.join("shaders"); + std::fs::create_dir_all(&to)?; + let mut out = Vec::new(); + for p in frame.pipelines.iter().filter(|p| p.name.contains(text)) { + let mut line = format!("pipeline {} {}:", p.id, p.name); + for part in &p.parts { + match part { + wire::Part::Code { kind, blob } => { + let c = &frame.codes[*blob as usize]; + let mut bytes = vec![0; c.len as usize]; + read_at(&file, &mut bytes, c.at)?; + let name: String = c.hash[..8].iter().map(|b| format!("{b:02x}")).collect(); + std::fs::write(to.join(format!("{name}.dxil")), bytes)?; + let _ = write!(line, " {kind}={name}.dxil"); + } + wire::Part::Root { root } => { + if let Some((_, blob)) = frame.roots.iter().find(|r| r.0 == *root) { + std::fs::write(to.join(format!("root-{root}.bin")), &blob.0)?; + } + let _ = write!(line, " root-{root}.bin"); + } + other => { + let _ = write!(line, " {other:?}"); + } + } + } + out.push(line); + } + Ok(out) +} + /// Loads a capture and runs it: the whole of `victory replay`. The reports, /// with what each is of. pub fn replay(folder: &Path, options: &Options) -> Result> { @@ -312,6 +377,8 @@ pub struct Player { commands: Vec>, /// Resources in the states of the start (not those of the end). fresh: bool, + /// States as the last run left them (`diverge`). + at: States, notes: Vec, } @@ -373,6 +440,7 @@ impl Player { results: None, commands, fresh: true, + at: States::default(), notes: frame .notes .iter() @@ -1769,7 +1837,7 @@ impl Player { ); let built = self.build(&submits, &Options::default())?; self.restore(true)?; - self.send(&built, false)?; + self.send(&built, &Options::default())?; self.fresh = false; Ok(clamps) } @@ -1838,8 +1906,13 @@ impl Player { let mut built = Vec::new(); for cmds in lists { let open = self.open(&heap, &mut next)?; - let stamps = - self.translate(&open.1, cmds, i, o.detailed.then_some((&heap, &mut next))); + let stamps = self.translate( + &open.1, + cmds, + i, + o.detailed.then_some((&heap, &mut next)), + o.wait_all, + ); built.push(self.close(open, &heap, &mut next, stamps)?); } steps.push((delta, built)); @@ -1979,6 +2052,7 @@ impl Player { cmds: &[Cmd], submit: usize, mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>, + wait: bool, ) -> Vec { let version = self.version_of.get(submit).copied().unwrap_or(0); let clamps = self.pipelines_named(CLAMP); @@ -2010,6 +2084,10 @@ impl Player { // SAFETY: an open list; the objects are the frame's, alive with // the player; commands the host recorded the same way. unsafe { self.command(list, c, version) }; + if wait && c.works() { + // SAFETY: an open list. + unsafe { self.wait_for_all(list) }; + } let timed = c.works() || matches!(c, Cmd::Barriers { .. }); if timed && let Some((heap, next)) = &mut stamp { // SAFETY: as above. @@ -2474,7 +2552,7 @@ impl Player { } /// Sends the frame, waits for it, and reads the timestamps. - fn send(&mut self, s: &Sends, one: bool) -> Result> { + fn send(&mut self, s: &Sends, o: &Options) -> Result> { let cast = |l: &ID3D12GraphicsCommandList| l.cast::().map(Some); let mut submissions: Vec>> = Vec::new(); for (delta, lists) in &s.steps { @@ -2489,7 +2567,7 @@ impl Player { submissions.push(all); } } - if one { + if o.one_submit { let mut all = Vec::new(); for (i, lists) in submissions.into_iter().enumerate() { if i > 0 @@ -2504,7 +2582,14 @@ impl Player { // SAFETY: closed lists whose last run has finished. unsafe { for all in &submissions { - self.worker.queue.ExecuteCommandLists(all); + if !o.wait_lists { + self.worker.queue.ExecuteCommandLists(all); + continue; + } + for l in all { + self.worker.queue.ExecuteCommandLists(&[l.clone()]); + self.worker.idle()?; + } } self.worker .queue @@ -2534,7 +2619,10 @@ impl Player { for _ in 0..o.loops.max(1) { self.restore(o.restore)?; self.fresh = false; - stamps = self.send(&built, o.one_submit)?; + stamps = self.send(&built, o)?; + if let Some((db, _, hash, _)) = self.picture_now()? { + report.pictures.push((db, hash)); + } let ms = |a: u32, b: u32| { stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency }; @@ -2607,6 +2695,34 @@ impl Player { .collect(); } + /// The presented picture as it is now: dB against the recorded one, + /// whether its bytes are the same, its hash, and its pixels. + fn picture_now(&mut self) -> Result)>> { + let Some(p) = self.frame.presents.last().cloned() else { + return Ok(None); + }; + let Some(bytes) = self.contents(p.res)? else { + return Ok(None); + }; + let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else { + return Ok(None); + }; + let mut recorded = vec![0; bytes.len()]; + read_at( + &File::open(self.folder.join("present.bin"))?, + &mut recorded, + p.file, + )?; + let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default(); + let hash = blake3::hash(&rgb).to_hex().to_string(); + Ok(Some(( + gpu::psnr(&rgb, &was), + rows_equal(&p, &bytes, &recorded), + hash, + rgb, + ))) + } + /// Saves the presented picture and compares it with the recorded one. fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> { let Some(p) = self.frame.presents.last().cloned() else { @@ -2796,7 +2912,15 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option = None; match D3D12GetDebugInterface(&mut layer) { - Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Ok(()) => layer.iter().for_each(|l| { + l.EnableDebugLayer(); + // Every shader access checked on the card: very slow. + if std::env::var_os("VICTORY_REPLAY_GBV").is_some() + && let Ok(l) = l.cast::() + { + l.SetEnableGPUBasedValidation(true); + } + }), Err(e) => tracing::warn!("no debug layer: {e}"), } } diff --git a/crates/victory-gpu/src/replay/play/diverge.rs b/crates/victory-gpu/src/replay/play/diverge.rs new file mode 100644 index 0000000..7a6ace0 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/diverge.rs @@ -0,0 +1,1046 @@ +//! Where identical runs of a frame part: every list is run several times +//! from the very same memory (what the frame writes is put back before each, +//! and everything before it was run once), so what differs after it was made +//! different by it; then the first command of the list that does so, by +//! halving the list. The state after the last run is what the rest goes on +//! from, so each finding is a root, not a consequence. + +use super::*; + +/// A part of memory compared as one. +const PIECE: usize = 64 << 10; + +/// Where a run's contents come down: for each resource (and subresource) the +/// frame writes, its place in read-back memory. +struct Reader { + blocks: Vec<(ID3D12Resource, usize)>, + parts: Vec, +} + +#[derive(Clone)] +struct Part { + id: u32, + /// `None` for a buffer. + sub: Option<(u32, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)>, + block: usize, + at: u64, + len: u64, +} + +/// One way to run commands `from..to` of a list. +struct Unit<'a> { + submit: usize, + cmds: &'a [Cmd], + from: usize, + to: usize, + /// With the copies of what the CPU wrote before the submission. + delta: bool, +} + +/// What differed between runs: part and piece. +type Pieces = Vec<(usize, usize)>; + +/// What to look at. +#[derive(Clone, Debug)] +pub struct Search { + /// Runs of each list. + pub runs: u32, + /// Only these lists (the others are run once). + pub lists: Option<(u32, u32)>, + /// Roots looked for in one list. + pub roots: u32, + /// A full wait after each command. + pub wait_all: bool, + /// Experiments on the frame. + pub options: Options, +} + +impl Player { + /// Looks for what makes identical runs differ; `say` gets the findings + /// as they are made. + pub fn diverge(&mut self, s: &Search, say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + let clamps = if s.options.skip_clamps { + self.clamp_results(&mut report)? + } else { + Vec::new() + }; + let submits = self.edited(&s.options, &mut report, &clamps); + self.restore(true)?; + self.fresh = false; + let ids: Vec = self.masters.iter().map(|m| m.0).collect(); + let reader = self.reader(&ids)?; + let mb: u64 = reader.parts.iter().map(|p| p.len).sum::() >> 20; + say(format!( + "{} resources the frame writes ({mb} MB in {} parts) compared after each list, {} runs of each", + self.masters.len(), + reader.parts.len(), + s.runs + )); + let mut states = self.start_states(); + let mut global = 0u32; + for (i, lists) in submits.iter().enumerate() { + for (j, cmds) in lists.iter().enumerate() { + let here = global; + global += 1; + let delta = j == 0; + let wanted = s.lists.is_none_or(|(a, b)| (a..=b).contains(&here)); + let mut from = 0; + let mut roots = 0; + loop { + let unit = Unit { + submit: i, + cmds, + from, + to: cmds.len(), + delta: delta && from == 0, + }; + let looks = wanted && cmds[from..].iter().any(Cmd::works); + let runs = if looks { s.runs } else { 1 }; + let pieces = self.trials(&reader, &unit, &states, runs, s.wait_all)?; + if pieces.is_empty() || roots >= s.roots { + self.commit(&unit, &mut states)?; + break; + } + roots += 1; + // The shortest start of the rest that differs. + let works: Vec = (from..cmds.len()).filter(|&c| cmds[c].works()).collect(); + let (mut lo, mut hi) = (0, works.len() - 1); + while lo < hi { + let mid = (lo + hi) / 2; + let cut = Unit { to: works[mid] + 1, ..unit }; + self.put_back(&states)?; + if self.trials(&reader, &cut, &states, s.runs, s.wait_all)?.is_empty() { + lo = mid + 1; + } else { + hi = mid; + } + } + let at = works[lo]; + let cut = Unit { to: at + 1, ..unit }; + self.put_back(&states)?; + let pieces = self.trials(&reader, &cut, &states, s.runs.max(6), s.wait_all)?; + say(format!( + "list {here} (submission {i}, its list {j}), command {at} of {}: {}", + cmds.len(), + self.describe(cmds, at) + )); + self.put_back(&states)?; + for line in self.compare(&reader, &cut, &states, &pieces, s.wait_all)? { + say(format!(" {line}")); + } + self.commit(&cut, &mut states)?; + from = at + 1; + if from >= cmds.len() { + break; + } + } + } + states.decay(); + if s.lists.is_some_and(|(_, b)| global > b) { + break; + } + if i % 5 == 4 { + say(format!("submission {i} done")); + } + } + self.restore_all()?; + Ok(()) + } + + /// Looks for where the picture's variants are decided: at each list (or, + /// of one list, each `step` commands in `commands`) the rest of the frame + /// is run several times from the same memory. Where the runs' pictures + /// agree from a point on but not from the one before, what lies between + /// decides. + pub fn diverge_picture( + &mut self, + s: &Search, + commands: Option<(u32, u32)>, + step: usize, + say: &mut dyn FnMut(String), + ) -> Result<()> { + let mut report = Report::default(); + let submits = self.edited(&s.options, &mut report, &[]); + let flat: Vec<(usize, usize, &Vec)> = submits + .iter() + .enumerate() + .flat_map(|(i, lists)| lists.iter().enumerate().map(move |(j, c)| (i, j, c))) + .collect(); + self.restore(true)?; + self.fresh = false; + let mut states = self.start_states(); + for (here, &(i, j, cmds)) in flat.iter().enumerate() { + let inside = s.lists.is_some_and(|(a, b)| a == b && a as usize == here); + let looks = s.lists.is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here)); + let works: Vec = (0..cmds.len()).filter(|&c| cmds[c].works()).collect(); + // Where the list is cut. + let mut cuts: Vec = vec![0]; + if inside { + let (a, b) = commands.unwrap_or((0, u32::MAX)); + let some = works.iter().map(|&c| c + 1).filter(|c| (a as usize..=b as usize).contains(c)); + cuts.extend(some.step_by(step.max(1))); + } + for (k, &from) in cuts.iter().enumerate() { + if looks && !works.is_empty() { + let mut pictures: Vec<(f64, String, Vec)> = Vec::new(); + for run in 0..s.runs { + if run > 0 { + self.put_back(&states)?; + } + let mut now = states.clone(); + let first = Unit { submit: i, cmds, from, to: cmds.len(), delta: j == 0 && from == 0 }; + self.go(&first, s.wait_all)?; + now = self.after(&first, &now); + for (n, &(i, j, cmds)) in flat.iter().enumerate().skip(here + 1) { + if flat[n - 1].0 != i { + now.decay(); + } + let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + self.go(&unit, s.wait_all)?; + now = self.after(&unit, &now); + } + self.at = now; + if let Some((db, _, hash, rgb)) = self.picture_now()? { + pictures.push((db, hash, rgb)); + } + } + self.put_back(&states)?; + let least = pictures + .iter() + .enumerate() + .flat_map(|(a, x)| pictures[a + 1..].iter().map(|y| gpu::psnr(&x.2, &y.2))) + .fold(f64::INFINITY, f64::min); + let kinds: HashSet<&String> = pictures.iter().map(|p| &p.1).collect(); + let db: Vec = pictures.iter().map(|p| format!("{:.1}", p.0)).collect(); + say(format!( + "from list {here} (submission {i}, its list {j}), command {from}: {} pictures of {}, the least alike {least:.1} dB; against the recorded: {}", + kinds.len(), + pictures.len(), + db.join(" ") + )); + } + // On to the next cut. + let to = cuts.get(k + 1).copied().unwrap_or(cmds.len()); + let unit = Unit { submit: i, cmds, from, to, delta: j == 0 && from == 0 }; + self.go(&unit, s.wait_all)?; + self.commit(&unit, &mut states)?; + self.at = states.clone(); + if inside && looks { + let last = (from..to).rev().find(|&c| cmds[c].works()); + if let Some(c) = last { + say(format!(" command {c}: {}", self.describe(cmds, c))); + } + } + } + if flat.get(here + 1).is_none_or(|n| n.0 != i) { + states.decay(); + self.at = states.clone(); + } + if s.lists.is_some_and(|(_, b)| here >= b as usize) { + break; + } + } + Ok(()) + } + + /// The states of textures at the frame's start. + fn start_states(&self) -> States { + let mut states = States::default(); + for (id, all) in &self.start { + let Some(o) = self.objects.get(id) else { continue }; + let flags = self.frame.resources[o.index].desc.flags; + let decays = flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; + states.add(*id, o.subs, all[0], decays); + for (i, s) in all.iter().enumerate().filter(|_| all.len() > 1) { + states.change(&states::Change { + res: *id, + sub: i as u32, + after: *s, + promoted: false, + alias: false, + }); + } + } + states + } + + fn after(&self, unit: &Unit, states: &States) -> States { + let mut after = states.clone(); + let mut all = Vec::new(); + for c in &unit.cmds[unit.from..unit.to] { + states::changes(c, &mut all); + } + all.iter().for_each(|c| after.change(c)); + after + } + + /// Says which resources that are not put back before a run are changed + /// by one all the same. + pub fn check_written(&mut self, say: &mut dyn FnMut(String)) -> Result<()> { + // What is put back, is as it was. + { + let ids: Vec = self.masters.iter().map(|m| m.0).collect(); + let reader = self.reader(&ids)?; + let start = self.start_states(); + let before = self.hashes_now(&reader, &start)?; + let mut again = self.hashes_now(&reader, &start)?; + say(format!("read twice, {} parts differ", before.iter().zip(&again).filter(|(a, b)| a != b).count())); + for i in 0..3 { + self.run(&Options { loops: 1, ..Options::default() })?; + let ran = { + let end: Vec<(u32, Vec)> = self.end.iter().map(|(k, v)| (*k, v.clone())).collect(); + let mut s = start.clone(); + for (id, v) in end { + for (sub, st) in v.iter().enumerate() { + let sub = if v.len() == 1 { ALL } else { sub as u32 }; + s.change(&states::Change { res: id, sub, after: *st, promoted: false, alias: false }); + } + } + self.hashes_now(&reader, &s)? + }; + self.restore(true)?; + again = self.hashes_now(&reader, &start)?; + let differ: Vec = (0..before.len()).filter(|&i| before[i] != again[i]).collect(); + let changed = (0..before.len()).filter(|&i| before[i] != ran[i]).count(); + say(format!("run {i}: {changed} parts changed by the frame, {} not put back as they were", differ.len())); + for &d in differ.iter().take(20) { + let pieces = before[d].iter().zip(&again[d]).filter(|(a, b)| a != b).count(); + say(format!(" {} {:?}: {pieces} of {} pieces", self.called(reader.parts[d].id), reader.parts[d].sub.map(|s| s.0), before[d].len())); + } + } + } + let put_back: HashSet = self.masters.iter().map(|m| m.0).collect(); + let others: Vec = self.objects.keys().copied().filter(|id| !put_back.contains(id)).collect(); + let reader = self.reader(&others)?; + self.restore(true)?; + let start = self.start_states(); + let before = self.hashes_now(&reader, &start)?; + let o = Options { loops: 1, ..Options::default() }; + self.run(&o)?; + self.restore(true)?; + let after = self.hashes_now(&reader, &start)?; + let mut n = 0; + for (i, (a, b)) in before.iter().zip(&after).enumerate() { + let pieces = a.iter().zip(b).filter(|(a, b)| a != b).count(); + if pieces > 0 { + n += 1; + let p = &reader.parts[i]; + let r = &self.frame.resources[self.objects[&p.id].index]; + say(format!( + "not put back, but changed: {} {:?} idle {} late {}: {pieces} pieces of {}", + self.called(p.id), + r.place, + r.idle, + r.late, + a.len() + )); + } + } + say(format!("{} parts of {} resources looked at, {n} changed", reader.parts.len(), others.len())); + Ok(()) + } + + fn reader(&self, ids: &[u32]) -> Result { + const BLOCK: u64 = 512 << 20; + let mut parts = Vec::new(); + let mut sizes: Vec = vec![0]; + for id in ids { + let o = &self.objects[id]; + let r = &self.frame.resources[o.index]; + let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack); + if r.desc.samples[0] > 1 || back { + continue; + } + let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let desc = gpu::to_desc(&r.desc); + for sub in 0..o.subs { + let (sub, len) = if is_buffer { + (None, r.desc.width) + } else { + let (f, total) = gpu::footprints(&self.device, &desc, sub, 1); + (Some((sub, f[0])), total) + }; + let last = sizes.len() - 1; + let at = sizes[last].next_multiple_of(512); + let (block, at) = if at + len > BLOCK && at > 0 { + sizes.push(0); + (last + 1, 0) + } else { + (last, at) + }; + sizes[block] = at + len; + parts.push(Part { + id: *id, + sub, + block, + at, + len, + }); + } + } + let mut blocks = Vec::new(); + for size in sizes { + let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, size, D3D12_RESOURCE_FLAG_NONE)?; + blocks.push((b, data as usize)); + } + Ok(Reader { blocks, parts }) + } + + /// Runs the unit once; resources are as at its start. + fn go(&mut self, unit: &Unit, wait: bool) -> Result<()> { + let mut lists = Vec::new(); + if unit.delta + && let Some(parts) = self.delta_parts.get(unit.submit).filter(|p| !p.is_empty()) + && let Some(from) = &self.deltas + { + let l = self.plain_list()?; + for (d, at) in parts { + if let Some(o) = self.objects.get(&d.res) { + // SAFETY: an open list; live buffers. + unsafe { l.1.CopyBufferRegion(&o.res, d.at, from, *at, d.len) }; + } + } + // SAFETY: as above. + unsafe { l.1.Close()? }; + lists.push(l); + } + let l = self.plain_list()?; + // What the commands before have set, without what they do. + let before: Vec = unit.cmds[..unit.from] + .iter() + .filter(|c| { + !c.works() && !matches!(c, Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) + }) + .cloned() + .collect(); + self.translate(&l.1, &before, unit.submit, None, false); + self.translate(&l.1, &unit.cmds[unit.from..unit.to], unit.submit, None, wait); + // SAFETY: an open list. + unsafe { l.1.Close()? }; + lists.push(l); + for l in &lists { + // SAFETY: a closed list; waited for before it goes. + unsafe { self.worker.queue.ExecuteCommandLists(&[Some(l.1.cast()?)]) }; + self.worker.idle().context("the card was lost")?; + } + Ok(()) + } + + /// Hashes of all parts' pieces, as memory is now (in `states`). + fn hashes_now(&mut self, reader: &Reader, states: &States) -> Result>> { + let objects = &self.objects; + for block in 0..reader.blocks.len() { + let parts: Vec<&Part> = reader.parts.iter().filter(|p| p.block == block).collect(); + let (mut before, mut after) = (Vec::new(), Vec::new()); + let mut seen = HashSet::new(); + for p in parts.iter().filter(|p| p.sub.is_some()) { + if seen.insert(p.id) { + let state = states.get(p.id).unwrap_or(vec![COMMON]); + let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + gpu::moves(&objects[&p.id].res, &state, &to, &mut before); + gpu::moves(&objects[&p.id].res, &to, &state, &mut after); + } + } + let to = &reader.blocks[block].0; + self.worker.run(|list| { + // SAFETY: an open list; live resources. + unsafe { + barriers(list, &before); + for p in &parts { + let res = &objects[&p.id].res; + match p.sub { + None => list.CopyBufferRegion(to, p.at, res, 0, p.len), + Some((sub, mut f)) => { + f.Offset = p.at; + list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(res, sub), None); + } + } + } + barriers(list, &after); + } + })?; + } + let next = AtomicUsize::new(0); + let out: std::sync::Mutex>> = std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]); + std::thread::scope(|scope| { + for _ in 0..16 { + scope.spawn(|| { + while let Some((i, p)) = { + let i = next.fetch_add(1, Ordering::Relaxed); + reader.parts.get(i).map(|p| (i, p)) + } { + let all: Vec = reader + .bytes(p) + .chunks(PIECE) + .map(|c| { + let h = blake3::hash(c); + u64::from_le_bytes(h.as_bytes()[..8].try_into().unwrap_or_default()) + }) + .collect(); + out.lock().unwrap_or_else(|e| e.into_inner())[i] = all; + } + }); + } + }); + Ok(out.into_inner().unwrap_or_else(|e| e.into_inner())) + } + + /// Runs the unit `runs` times (memory is as at its start, and is put + /// back between runs) and compares. Memory is as the last run left it. + fn trials(&mut self, reader: &Reader, unit: &Unit, states: &States, runs: u32, wait: bool) -> Result { + let after = self.after(unit, states); + let mut first: Option>> = None; + let mut pieces = std::collections::BTreeSet::new(); + for run in 0..runs { + if run > 0 { + self.put_back_from(&after, states)?; + } + self.go(unit, wait)?; + if runs == 1 { + break; + } + let now = self.hashes_now(reader, &after)?; + match &first { + None => first = Some(now), + Some(first) => { + for (p, (a, b)) in first.iter().zip(&now).enumerate() { + pieces.extend(a.iter().zip(b).enumerate().filter(|(_, (a, b))| a != b).map(|(i, _)| (p, i))); + } + } + } + } + self.at = after; + Ok(pieces.into_iter().collect()) + } + + /// Puts memory back to the start of a unit in `states`, from where the + /// last run left it. + fn put_back(&mut self, states: &States) -> Result<()> { + let from = self.at.clone(); + self.put_back_from(&from, states) + } + + fn put_back_from(&mut self, from: &States, to: &States) -> Result<()> { + self.copy_masters(from, to, false)?; + self.at = to.clone(); + Ok(()) + } + + /// What memory holds after the last run is the start of what follows. + fn commit(&mut self, unit: &Unit, states: &mut States) -> Result<()> { + *states = self.after(unit, states); + self.copy_masters(&states.clone(), states, true)?; + Ok(()) + } + + /// Copies the masters over the resources (which are in `from` and go to + /// `to`), or the resources into the masters. + fn copy_masters(&mut self, from: &States, to: &States, save: bool) -> Result<()> { + let known: HashMap = self.masters.iter().map(|(id, m)| (*id, m)).collect(); + let (mut before, mut after, mut plain) = (Vec::new(), Vec::new(), Vec::new()); + let here = if save { COPY_SOURCE } else { COPY_DEST }; + for id in self.start.keys() { + let Some(o) = self.objects.get(id) else { continue }; + let (a, b) = (from.get(*id).unwrap_or(vec![COMMON]), to.get(*id).unwrap_or(vec![COMMON])); + let Some(m) = known.get(id) else { + gpu::moves(&o.res, &a, &b, &mut plain); + continue; + }; + gpu::moves(&o.res, &a, &[here], &mut before); + gpu::moves(&o.res, &[here], &b, &mut after); + if save { + before.push(gpu::transition(m, ALL, COPY_SOURCE, COPY_DEST)); + after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE)); + } + } + let objects = &self.objects; + self.worker.run(|list| { + // SAFETY: an open list; live resources of one description. + unsafe { + barriers(list, &plain); + barriers(list, &before); + for (id, m) in &known { + if save { + list.CopyResource(*m, &objects[id].res); + } else { + list.CopyResource(&objects[id].res, *m); + } + } + barriers(list, &after); + } + })?; + Ok(()) + } + + /// The masters hold another state than the frame's start now. + fn restore_all(&mut self) -> Result<()> { + self.note("the player's copies are no longer of the frame's start: load it again".into()); + Ok(()) + } + + /// A command in words: its pipeline, what its list bound for it, and the + /// barriers since the last command that worked. + fn describe(&self, cmds: &[Cmd], at: usize) -> String { + let mut pso = NONE; + let mut binds: BTreeMap<(bool, u32), String> = BTreeMap::new(); + let mut since: Vec = Vec::new(); + let mut targets = String::new(); + for c in &cmds[..at] { + match c { + Cmd::Pipeline { pso: p } => pso = *p, + Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics), + Cmd::RootView { graphics, kind, param, va } => { + let kind = ["", "cbv", "srv", "uav"].get(*kind as usize).copied().unwrap_or(""); + let text = match va { + Va::At { res, offset } => format!("{kind} {} +{offset:#x}", self.called(*res)), + _ => format!("{kind} null"), + }; + binds.insert((*graphics, *param), text); + } + Cmd::Table { graphics, param, heap, slot } => { + binds.insert((*graphics, *param), format!("table heap {heap} slot {slot}")); + } + Cmd::Constants { graphics, param, offset, values } => { + let text = format!("constants +{offset} {values:x?}"); + binds.entry((*graphics, *param)).and_modify(|t| *t = format!("{t}, {text}")).or_insert(text); + } + Cmd::Targets { colors, depth } => { + let all: Vec = colors.iter().chain(depth).map(|s| self.called(s.res)).collect(); + targets = all.join(", "); + } + Cmd::Barriers { all } => since.extend(all.iter().map(|b| match b { + Barrier::Transition { res, before, after, .. } => format!("{} {before:#x}->{after:#x}", self.called(*res)), + Barrier::Uav { res: 0, .. } => "all uav".into(), + Barrier::Uav { res, .. } => format!("uav {}", self.called(*res)), + Barrier::Alias { .. } => "alias".into(), + })), + _ => {} + } + if c.works() { + since.clear(); + } + } + let graphics = !matches!(cmds[at], Cmd::Dispatch { .. }); + let binds: Vec = binds.iter().filter(|(k, _)| k.0 == graphics).map(|(k, t)| format!("[{}] {t}", k.1)).collect(); + let mut text = format!("{:?}", cmds[at]); + if cmds[at].runs_shaders() { + text += &format!(" of {}", self.pipeline_name(pso)); + text += &format!("\n bound: {}", binds.join("; ")); + if graphics && !targets.is_empty() { + text += &format!("\n targets: {targets}"); + } + } + text + &format!("\n barriers since the command before: {}", since.join("; ")) + } + + /// Says which lists (of the list in `s.lists`: which commands) change + /// words of a buffer, and to what. + pub fn watch(&mut self, s: &Search, parts: &[(u32, u64, u64)], say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + let submits = self.edited(&s.options, &mut report, &[]); + self.restore(true)?; + self.fresh = false; + let words = |p: &mut Player| -> Result>> { + parts + .iter() + .map(|&(id, at, len)| { + let bytes = p.slice(id, at, len)?; + Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + }) + .collect() + }; + let mut was = words(self)?; + say(format!("at the start: {was:x?}")); + let mut global = 0u32; + for (i, lists) in submits.iter().enumerate() { + for (j, cmds) in lists.iter().enumerate() { + let here = global; + global += 1; + let inside = s.lists.is_some_and(|(a, b)| (a..=b).contains(&here)); + let mut cuts: Vec = vec![0]; + if inside { + cuts.extend((0..cmds.len()).filter(|&c| cmds[c].works()).map(|c| c + 1)); + } + if *cuts.last().unwrap_or(&0) != cmds.len() { + cuts.push(cmds.len()); + } + for k in 0..cuts.len() - 1 { + let unit = Unit { submit: i, cmds, from: cuts[k], to: cuts[k + 1], delta: j == 0 && k == 0 }; + self.go(&unit, s.wait_all)?; + let now = words(self)?; + if now != was { + if inside { + let last = (unit.from..unit.to).rev().find(|&c| cmds[c].works()).unwrap_or(unit.to - 1); + say(format!("list {here} (submission {i}, its list {j}) command {last}: {}", self.describe(cmds, last))); + } else { + say(format!("list {here} (submission {i}, its list {j})")); + } + for (n, (a, b)) in was.iter().zip(&now).enumerate() { + let changed: Vec = a + .iter() + .zip(b) + .enumerate() + .filter(|(_, (a, b))| a != b) + .take(40) + .map(|(w, (a, b))| format!("+{:#x}: {a:x} -> {b:x}", w * 4)) + .collect(); + if !changed.is_empty() { + say(format!(" part {n}: {}", changed.join(", "))); + } + } + was = now; + } + } + if s.options.only.is_some_and(|(_, b)| here >= b) { + return Ok(()); + } + } + } + Ok(()) + } + + /// Each draw of one list whose pipeline's name has `text` in it, run + /// alone (with what prepares its arguments) from the memory at the list's + /// start, `runs` times: how many different contents its targets get. + pub fn diverge_draws(&mut self, s: &Search, text: &str, say: &mut dyn FnMut(String)) -> Result<()> { + let mut report = Report::default(); + let submits = self.edited(&s.options, &mut report, &[]); + let flat: Vec<(usize, usize, &Vec)> = submits + .iter() + .enumerate() + .flat_map(|(i, lists)| lists.iter().enumerate().map(move |(j, c)| (i, j, c))) + .collect(); + let wanted = s.lists.map_or(0, |l| l.0 as usize); + self.restore(true)?; + self.fresh = false; + let mut states = self.start_states(); + for (here, &(i, j, cmds)) in flat.iter().enumerate() { + if here < wanted { + let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + self.go(&unit, s.wait_all)?; + self.commit(&unit, &mut states)?; + if flat.get(here + 1).is_none_or(|n| n.0 != i) { + states.decay(); + } + self.at = states.clone(); + continue; + } + let mut last = 0; + let mut pso = NONE; + let mut targets: Vec = Vec::new(); + for (c, cmd) in cmds.iter().enumerate() { + match cmd { + Cmd::Pipeline { pso: p } => pso = *p, + Cmd::Targets { colors, depth } => targets = colors.iter().chain(depth).map(|s| s.res).filter(|r| *r != NONE).collect(), + _ => {} + } + if !matches!(cmd, Cmd::Indirect { .. } | Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. }) { + continue; + } + let from = std::mem::replace(&mut last, c + 1); + if !self.pipeline_name(pso).contains(text) { + continue; + } + targets.sort_unstable(); + targets.dedup(); + let reader = self.reader(&targets)?; + let unit = Unit { submit: i, cmds, from, to: c + 1, delta: false }; + // Barriers before it in the list are made up for: textures + // are in the states the list has them in here. + let mut before = states.clone(); + let mut all = Vec::new(); + cmds[..from].iter().for_each(|c| states::changes(c, &mut all)); + all.iter().for_each(|c| before.change(c)); + let after = self.after(&unit, &before); + let mut kinds: HashMap>, u32> = HashMap::new(); + for _ in 0..s.runs { + let at = self.at.clone(); + self.copy_masters(&at, &before, false)?; + self.at = before.clone(); + self.go(&unit, s.wait_all)?; + self.at = after.clone(); + *kinds.entry(self.hashes_now(&reader, &after)?).or_default() += 1; + } + let at = self.at.clone(); + self.copy_masters(&at, &before, false)?; + self.at = before.clone(); + if kinds.len() > 1 || std::env::var_os("VICTORY_REPLAY_PEEK").is_some() { + self.peek(cmds, c, i, say)?; + } + let mut counts: Vec = kinds.values().copied().collect(); + counts.sort_unstable(); + say(format!("command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}", cmd, self.pipeline_name(pso), counts.len())); + } + break; + } + Ok(()) + } + + /// `len` bytes of a buffer from `at`. + fn slice(&mut self, id: u32, at: u64, len: u64) -> Result> { + let Some(o) = self.objects.get(&id) else { return Ok(Vec::new()) }; + let len = len.min(self.frame.resources[o.index].desc.width.saturating_sub(at)); + if len == 0 { + return Ok(Vec::new()); + } + let res = o.res.clone(); + let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + self.worker.run(|list| { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&back, 0, &res, at, len) }; + })?; + // SAFETY: the mapping; the copy into it has run. + Ok(unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec()) + } + + /// The words of a buffer view (raw or typed, of words). + fn view_words(&mut self, s: &Slot, first: u64, n: u64) -> Result> { + let at = u64::from_le_bytes([s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22], s.desc[23]]); + let count = u64::from(u32::from_le_bytes([s.desc[24], s.desc[25], s.desc[26], s.desc[27]])); + let n = n.min(count.saturating_sub(first)); + let bytes = self.slice(s.res, (at + first) * 4, n * 4)?; + Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + } + + /// What a mesh draw of the title's (with its usual constants) reads. + fn peek(&mut self, cmds: &[Cmd], at: usize, submit: usize, say: &mut dyn FnMut(String)) -> Result<()> { + let mut v = [0u32; 16]; + let mut heap = NONE; + for c in &cmds[..at] { + match c { + Cmd::Constants { graphics: true, param: 0, offset, values } => { + for (k, x) in values.iter().enumerate() { + if let Some(at) = v.get_mut(*offset as usize + k) { + *at = *x; + } + } + } + Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE), + _ => {} + } + } + say(format!(" constants {v:x?}")); + let slot = |p: &Player, byte: u32| p.slot_at(heap, byte >> 5, submit); + for (name, byte, n) in [ + ("y+0", v[9], 64u64), + ("y+32 (matrices)", v[9] + 32, 64), + ("y+64", v[9] + 64, 32), + ("y+96 (instances)", v[9] + 96, 64), + ("y+128 (meshlets)", v[9] + 128, 64), + ("y+192 (visible)", v[9] + 192, 64), + ("x+1600", v[8] + 1600, 0), + ("x+2752", v[8] + 2752, 0), + ("x+2848", v[8] + 2848, 0), + ] { + let s = slot(self, byte); + let words = if s.kind == slot::SRV { self.view_words(&s, 0, n)? } else { Vec::new() }; + say(format!(" {name}: slot {} {}: {words:x?}", byte >> 5, self.slot_text(&s))); + } + // The list of visible meshlets, as the mesh shader finds it. + let lists = slot(self, v[8] + 2752); + let word = self.view_words(&lists, u64::from((v[13] & 0x07ff_ffff) & 0x07ff_ffff), 4)?; + let typed = slot(self, v[8] + 1600); + let index = self.view_words(&typed, 510, 1)?; + say(format!(" list words {word:x?} (count {}, first {}), typed view slot {index:x?}", word.first().map_or(0, |w| w >> 15), word.first().map_or(0, |w| w & 0x7fff))); + if let (Some(w), Some(i)) = (word.first(), index.first()) { + let s = self.slot_at(heap, i & 0x07ff_ffff, submit); + say(format!(" typed view: {}", self.slot_text(&s))); + if s.kind == slot::SRV && s.res != NONE { + let list = self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?; + say(format!(" visible meshlets: {list:x?}")); + } + } + Ok(()) + } + + /// What the heap slots hold that a draw's constants name, as the title's + /// shaders find them: byte offsets in the view heap among its first + /// constants, a descriptor of 32 bytes each. + pub fn slots(&self, list: u32, command: usize, say: &mut dyn FnMut(String)) -> Result<()> { + let mut here = 0; + for (i, s) in self.frame.submits.iter().enumerate() { + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + if here == list { + let cmds = &self.commands[l as usize]; + say(self.describe(cmds, command)); + let mut values = [[0u32; 16]; 3]; + let mut heap = NONE; + for c in &cmds[..command] { + match c { + Cmd::Constants { param, offset, values: v, .. } => { + for (k, x) in v.iter().enumerate() { + if let Some(all) = values.get_mut(*param as usize) + && let Some(at) = all.get_mut(*offset as usize + k) + { + *at = *x; + } + } + } + Cmd::Heaps { heaps } => heap = heaps.first().copied().unwrap_or(NONE), + _ => {} + } + } + say(format!("heap {heap}, constants {values:x?}")); + let mut bases: Vec = values.iter().flatten().map(|v| v >> 5).filter(|v| *v > 64).collect(); + bases.dedup(); + for base in bases { + for k in 0..12 { + let s = self.slot_at(heap, base + k, i); + if s.kind != slot::EMPTY { + say(format!(" slot {base}+{k}: {}", self.slot_text(&s))); + } else { + say(format!(" slot {base}+{k}: never written")); + } + } + } + } + here += 1; + } + } + Ok(()) + } + + /// A heap slot as it was for a submission. + fn slot_at(&self, heap: u32, at: u32, submit: usize) -> Slot { + let late = self.frame.submits[..=submit].iter().rev().find_map(|s| { + s.views.iter().rev().find(|(h, i, _)| *h == heap && *i == at).map(|v| v.2) + }); + late.unwrap_or_else(|| { + let runs = self.frame.descriptor_heaps.iter().find(|h| h.id == heap).map(|h| &h.runs); + runs.and_then(|runs| { + let k = runs.partition_point(|r| r.0 <= at).checked_sub(1)?; + let (first, n, s) = &runs[k]; + (at - first < *n).then_some(*s) + }) + .unwrap_or(Slot::EMPTY) + }) + } + + fn slot_text(&self, s: &Slot) -> String { + let word = |i: usize| u32::from_le_bytes([s.desc[i * 4], s.desc[i * 4 + 1], s.desc[i * 4 + 2], s.desc[i * 4 + 3]]); + let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"].get(s.kind as usize).copied().unwrap_or("?"); + let res = if s.res == NONE { "null".into() } else { self.called(s.res) }; + match s.kind { + slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(2)), + _ => format!( + "{kind} format {} dimension {} first {} count {} stride {} flags {}: {res}", + word(0), + word(1), + word(if s.kind == slot::SRV { 4 } else { 2 }), + word(if s.kind == slot::SRV { 6 } else { 4 }), + word(if s.kind == slot::SRV { 7 } else { 5 }), + word(if s.kind == slot::SRV { 8 } else { 8 }), + ), + } + } + + fn called(&self, id: u32) -> String { + let Some(o) = self.objects.get(&id) else { + return format!("resource {id} (not there)"); + }; + let r = &self.frame.resources[o.index]; + let d = &r.desc; + if d.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + let kind = match &r.place { + Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)), + _ => "placed".into(), + }; + format!("#{id} '{}' buffer {:#x} {kind}", r.name, d.width) + } else { + format!("#{id} '{}' {}x{}x{} m{} f{}", r.name, d.width, d.height, d.depth, d.mips, d.format) + } + } + + /// Runs the unit until two runs differ, and says how. + fn compare(&mut self, reader: &Reader, unit: &Unit, states: &States, pieces: &Pieces, wait: bool) -> Result> { + let after = self.after(unit, states); + let parts: std::collections::BTreeSet = pieces.iter().map(|p| p.0).collect(); + let mut seen: Vec<(Vec>, Vec>)> = Vec::new(); + for run in 0..8 { + if run > 0 { + self.put_back_from(&after, states)?; + } + self.go(unit, wait)?; + let hashes = self.hashes_now(reader, &after)?; + if seen.iter().any(|(h, _)| *h == hashes) { + continue; + } + let data = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + seen.push((hashes, data)); + if seen.len() == 2 { + break; + } + } + let mut out = Vec::new(); + // The arguments it ran with. + if let Some(Cmd::Indirect { args, at, .. }) = unit.cmds.get(unit.to - 1) + && let Some((p, part)) = reader.parts.iter().enumerate().find(|(_, p)| p.id == *args) + { + let bytes = &reader.bytes(part)[*at as usize..]; + let words: Vec = bytes.chunks_exact(4).take(8).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let each: HashSet<&Vec> = seen.iter().map(|s| &s.0[p]).collect(); + out.push(format!("arguments {words:x?} (the same in all runs: {})", each.len() == 1)); + } + self.at = after; + let [(_, a), (_, b)] = &seen[..] else { + out.push("it did not differ when looked at again".into()); + return Ok(out); + }; + // And without the command. + let before = Unit { to: unit.to - 1, ..*unit }; + self.put_back(states)?; + self.go(&before, wait)?; + self.at = self.after(&before, states); + let now = self.at.clone(); + self.hashes_now(reader, &now)?; + let without: Vec> = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + let to = self.folder.join("diverge"); + let _ = std::fs::create_dir_all(&to); + for (k, &p) in parts.iter().enumerate().take(12) { + let part = &reader.parts[p]; + // Both contents, to look at. + let sub = part.sub.map_or(0, |s| s.0); + let _ = std::fs::write(to.join(format!("{}-{sub}-0.bin", part.id)), &without[k]); + let changed = |v: &[u8]| v.chunks_exact(4).zip(without[k].chunks_exact(4)).filter(|(x, y)| x != y).count(); + out.push(format!("it changes {} dwords in one run, {} in another", changed(&a[k]), changed(&b[k]))); + let _ = std::fs::write(to.join(format!("{}-{sub}-a.bin", part.id)), &a[k]); + let _ = std::fs::write(to.join(format!("{}-{sub}-b.bin", part.id)), &b[k]); + let words = |v: &[u8]| -> Vec { v.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect() }; + let (x, y) = (words(&a[k]), words(&b[k])); + let differ: Vec = (0..x.len().min(y.len())).filter(|&i| x[i] != y[i]).collect(); + if differ.is_empty() { + continue; + } + // The same words in another order: an order, not a value. + let sorted = |v: &[u32]| { + let mut s: Vec = differ.iter().map(|&i| v[i]).collect(); + s.sort_unstable(); + s + }; + let order = if sorted(&x) == sorted(&y) { " (the same values in another order)" } else { "" }; + let sub = part.sub.map_or(String::new(), |(s, f)| format!(" subresource {s} pitch {}", f.Footprint.RowPitch)); + let sample: Vec = differ.iter().take(8).map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i])).collect(); + out.push(format!( + "writes {}{sub}: {} of {} dwords differ, {:#x}..{:#x}{order}: {}", + self.called(part.id), + differ.len(), + x.len(), + differ[0] * 4, + differ[differ.len() - 1] * 4 + 4, + sample.join(", ") + )); + } + if parts.len() > 12 { + out.push(format!("and {} more parts", parts.len() - 12)); + } + Ok(out) + } +} + +impl Reader { + fn bytes(&self, p: &Part) -> &[u8] { + // SAFETY: a part of a mapped block; copies into it have run. + unsafe { std::slice::from_raw_parts((self.blocks[p.block].1 + p.at as usize) as *const u8, p.len as usize) } + } +} diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index c839d60..67a77e3 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -351,7 +351,10 @@ pub(super) struct Recorder { /// made are kept alive. pub(super) watching: AtomicBool, pub(super) writes: Mutex>, - pub(super) held: Mutex>, + /// Resources kept alive for a capture, by id. One that dies all the same + /// (its last reference was going when ours was taken) is taken out: see + /// `Recorder::gone`. + pub(super) held: Mutex>, /// What could not be recorded, with how often. problems: Mutex>, /// Submissions and presents, one at a time. @@ -586,7 +589,7 @@ impl Recorder { write(&self.resources).insert(id, res); self.ids.set(p as usize, id); if late { - lock(&self.held).push(ID3D12Resource::clone(&object)); + lock(&self.held).insert(id, ID3D12Resource::clone(&object)); } self.tell_gone( &*object, @@ -602,6 +605,12 @@ impl Recorder { fn gone(&self, what: &Gone) { match *what { Gone::Resource { id, ptr, va } => { + // The memory goes whatever we hold: letting go of it later + // would be a call into what is there then. + if let Some(dead) = lock(&self.held).remove(&id) { + std::mem::forget(dead); + self.problem("a resource died as the frame started: its contents may be missing"); + } self.ids.remove(ptr, id); write(&self.resources).remove(&id); if va != 0 { diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index d9832d2..07acb47 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -279,7 +279,8 @@ impl Reads { /// A buffer the CPU sees. struct CpuBuffer { id: u32, - res: ID3D12Resource, + /// Held by the recorder, not by this. + res: std::mem::ManuallyDrop, /// Where it is read: its mapping, or the read-back copy of it. live: *const u8, /// The read-back buffer and the offset in it, for one that is slow to @@ -298,8 +299,6 @@ unsafe impl Sync for CpuBuffer {} struct Capture { worker: Worker, others: Vec, - /// Resources the frame can use, kept alive. - held: Vec, started: bool, frame: u32, states: States, @@ -341,7 +340,6 @@ impl Capture { Ok(Capture { worker: Worker::new(&device, &direct.0)?, others, - held: Vec::new(), started: false, frame: 0, states: States::default(), @@ -388,7 +386,8 @@ impl Capture { let mut all: Vec> = Vec::new(); { let live = read(&r.resources); - for res in live.values() { + let mut held = lock(&r.held); + for res in live.values().filter(|res| !res.late) { let object = res.object(); // SAFETY: a live resource, or one whose end waits for the // lock held here (`Recorder::gone`): the count tells which. @@ -405,9 +404,11 @@ impl Capture { // giving it back would end it a second time. continue; } - // SAFETY: the reference just taken. - self.held - .push(unsafe { ID3D12Resource::from_raw(object.as_raw()) }); + // SAFETY: the reference just taken. (The count does not tell + // all that are dying: `Recorder::gone` takes those out.) + held.insert(res.id, unsafe { + ID3D12Resource::from_raw(object.as_raw()) + }); all.push(res.clone()); } } @@ -594,7 +595,11 @@ impl Capture { } // Moved in: the writers end when it goes. let todo = todo; - for pieces in batches { + for mut pieces in batches { + { + let held = lock(&r.held); + pieces.retain(|p| held.contains_key(&p.res.id)); + } if pieces.is_empty() { continue; } @@ -629,8 +634,12 @@ impl Capture { r.problem("contents of textures in memory the CPU sees are not in the capture"); continue; } - // Those alive at the start are held, those made since too. - let object = ID3D12Resource::clone(&res.object()); + // Those alive at the start are held, those made since too; what + // is not is dying. + if !lock(&r.held).contains_key(&res.id) { + continue; + } + let object = res.object(); let size = res.desc.width as usize; let (live, through) = if res.seen == Seen::Cached { let mut data = std::ptr::null_mut(); @@ -675,6 +684,10 @@ impl Capture { /// zero). fn changed(&mut self, r: &Recorder, reads: &Reads) -> Result, Fault> { self.new_buffers(r)?; + { + let held = lock(&r.held); + self.buffers.retain(|b| held.contains_key(&b.id)); + } let parts: Vec<(usize, usize, usize)> = self .buffers .iter() @@ -697,7 +710,7 @@ impl Capture { list.CopyBufferRegion( &blocks[block].0, at + from as u64, - &b.res, + &*b.res, from as u64, (to - from) as u64, ) From b01486de0275bbc30176c7bde84e54d7074cae8f Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:37:32 -0600 Subject: [PATCH 3/5] Frame replay: the CPU's copies leave what the card wrote; buffers in the card's memory fit Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/replay.rs | 30 +- crates/victory-gpu/src/replay/play.rs | 128 ++++- crates/victory-gpu/src/replay/play/diverge.rs | 516 +++++++++++++++--- crates/victory-gpu/src/replay/play/merge.rs | 291 ++++++++++ crates/victory-gpu/src/replay/record.rs | 4 +- crates/victory-gpu/src/replay/snap.rs | 4 +- docs/replay.md | 24 + 7 files changed, 893 insertions(+), 104 deletions(-) create mode 100644 crates/victory-gpu/src/replay/play/merge.rs diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index 714009f..f73ea08 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -62,6 +62,10 @@ pub(crate) struct Replay { /// One ExecuteCommandLists for the whole frame. #[arg(long)] one_submit: bool, + /// Let copies of what the CPU wrote also overwrite what the card wrote in + /// the replay (as the recorded commands say). + #[arg(long)] + no_merge: bool, /// A full wait after every draw, dispatch, copy and clear. #[arg(long)] wait_all: bool, @@ -158,6 +162,7 @@ pub(crate) fn run(r: Replay) -> Result<()> { skip_clamps: r.skip_clamps, skip_hash_passes: r.skip_hash_passes, one_submit: r.one_submit, + merge: !r.no_merge, wait_all: r.wait_all, wait_lists: r.wait_lists, only, @@ -179,13 +184,27 @@ pub(crate) fn run(r: Replay) -> Result<()> { } let mut watched = Vec::new(); for text in &r.watch { - let mut n = text.split(':').map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16)); - let mut next = || n.next().and_then(Result::ok).with_context(|| format!("--watch {text}")); - let id = text.split(':').next().and_then(|p| p.parse().ok()).with_context(|| format!("--watch {text}"))?; + let mut n = text + .split(':') + .map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16)); + let mut next = || { + n.next() + .and_then(Result::ok) + .with_context(|| format!("--watch {text}")) + }; + let id = text + .split(':') + .next() + .and_then(|p| p.parse().ok()) + .with_context(|| format!("--watch {text}"))?; let _ = next(); watched.push((id, next()?, next()?)); } - if let Some(runs) = r.diverge.or(r.diverge_picture).or((!watched.is_empty()).then_some(2)) { + if let Some(runs) = r + .diverge + .or(r.diverge_picture) + .or((!watched.is_empty()).then_some(2)) + { let lists = match &r.lists { Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?), None => None, @@ -209,7 +228,8 @@ pub(crate) fn run(r: Replay) -> Result<()> { Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?), None => None, }; - return player.diverge_picture(&search, commands, r.step, &mut |line| println!("{line}")); + return player + .diverge_picture(&search, commands, r.step, &mut |line| println!("{line}")); } return player.diverge(&search, &mut |line| println!("{line}")); } diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index ba1543a..5ad96c5 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -30,6 +30,7 @@ use super::wire::{ }; pub mod diverge; +mod merge; /// The name of the argument clamp's pipeline, by which its passes are /// recognised. @@ -69,6 +70,9 @@ pub struct Options { pub skip_clamps: bool, pub skip_hash_passes: bool, pub one_submit: bool, + /// Copies of what the CPU wrote leave alone what the card wrote in this + /// run (`merge`). + pub merge: bool, /// A full wait after every command that works. pub wait_all: bool, /// Each list sent on its own, and waited for. @@ -98,6 +102,7 @@ impl Default for Options { skip_clamps: false, skip_hash_passes: false, one_submit: false, + merge: true, wait_all: false, wait_lists: false, only: None, @@ -372,6 +377,11 @@ pub struct Player { /// States at the start of the frame and after it. start: HashMap>, end: HashMap>, + /// For `Options::merge`. + merger: Option, + merging: bool, + /// Resources the card may write in the frame. + card_writes: HashSet, /// The results of clamp passes ([`RESULTS`]). results: Option, commands: Vec>, @@ -437,6 +447,9 @@ impl Player { delta_parts: Vec::new(), start: HashMap::new(), end: HashMap::new(), + merger: None, + merging: false, + card_writes: HashSet::new(), results: None, commands, fresh: true, @@ -463,12 +476,22 @@ impl Player { step("descriptors", &mut at); player.load_contents()?; step("contents", &mut at); - player.make_masters()?; + player.make_masters(options.buffers)?; step("copies to restore from", &mut at); let steps: Vec = steps .iter() .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64())) .collect(); + if let Some([budget, used, pc]) = player.memory() { + let over = if used + 256 > budget { + ": over the budget, so the system moves memory to the PC's and the times are not the card's" + } else { + "" + }; + player.notes.push(format!( + "{used} MB of the card's memory used, budget {budget} MB; {pc} MB of the PC's{over}" + )); + } player.notes.push(format!( "loaded in {:.1} s: {}", began.elapsed().as_secs_f64(), @@ -1422,7 +1445,7 @@ impl Player { } /// Copies of what the frame changes; and the states it leaves. - fn make_masters(&mut self) -> Result<()> { + fn make_masters(&mut self, buffers: Buffers) -> Result<()> { let mut states = States::default(); for r in &self.frame.resources { if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { @@ -1454,6 +1477,7 @@ impl Player { .filter(|r| r.state.iter().any(|s| s & WRITE != 0)) .map(|r| r.id) .collect(); + let mut by_cpu: HashSet = HashSet::new(); for (i, s) in self.frame.submits.iter().enumerate() { for &l in s.lists.iter().filter(|&&l| l != MISSING) { for c in &self.commands[l as usize] { @@ -1504,7 +1528,7 @@ impl Player { } states.decay(); if i > 0 { - written.extend(self.delta_parts[i].iter().map(|(d, _)| d.res)); + by_cpu.extend(self.delta_parts[i].iter().map(|(d, _)| d.res)); } } // Buffers any unordered-access view names. @@ -1537,6 +1561,8 @@ impl Player { } } } + self.card_writes = written.clone(); + written.extend(by_cpu); for id in self.start.keys() { self.end .insert(*id, states.get(*id).unwrap_or(vec![COMMON])); @@ -1568,7 +1594,10 @@ impl Player { let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes; let room = self.room(); let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; - let pc = buffer && room.is_some_and(|room| room < size + (1 << 30)); + // With all buffers in the card's memory there is no room for + // their copies as well. + let pc = buffer + && (buffers == Buffers::Card || room.is_some_and(|room| room < size + (1 << 30))); let props = if pc { D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, @@ -1642,6 +1671,31 @@ impl Player { Ok(()) } + /// The card's memory budget and use, and the use of the PC's memory, in + /// MB. + fn memory(&self) -> Option<[u64; 3]> { + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut pc = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter3 = factory + .EnumAdapterByLuid(self.device.GetAdapterLuid()) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut pc) + .ok()?; + } + Some([ + own.Budget >> 20, + own.CurrentUsage >> 20, + pc.CurrentUsage >> 20, + ]) + } + /// What is free of the card's memory budget. fn room(&self) -> Option { let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); @@ -1696,6 +1750,13 @@ impl Player { for (id, m) in &restored { list.CopyResource(&objects[id].res, *m); } + if let Some(merger) = &self.merger { + for (id, base) in &merger.bases { + if let Some((_, m)) = self.masters.iter().find(|m| m.0 == *id) { + list.CopyResource(base, m); + } + } + } barriers(list, &back); } })?; @@ -1886,10 +1947,15 @@ impl Player { unsafe { let mut seen = HashSet::new(); let mut after = Vec::new(); + let mut merges = Vec::new(); for (d, at) in parts { let Some(ob) = self.objects.get(&d.res) else { continue; }; + if self.merging && self.card_writes.contains(&d.res) { + merges.push((d.res, d.at, *at, d.len)); + continue; + } open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len); if seen.insert(d.res) { // Back to the common state by itself, for @@ -1898,6 +1964,11 @@ impl Player { } } barriers(&open.1, &after); + if !merges.is_empty() { + self.wait_for_all(&open.1); + self.merge_all(&open.1, from.GetGPUVirtualAddress(), &merges); + self.wait_for_all(&open.1); + } } Some(self.close(open, &heap, &mut next, Vec::new())?) } @@ -2077,13 +2148,51 @@ impl Player { .collect(); let mut stamps = Vec::new(); let mut bound = NONE; + // What the compute side has bound. + let mut compute: Vec = Vec::new(); for c in cmds { if let Cmd::Pipeline { pso } = c { bound = *pso; } - // SAFETY: an open list; the objects are the frame's, alive with - // the player; commands the host recorded the same way. - unsafe { self.command(list, c, version) }; + let merged = self.merged_copy(c); + if let Some((from, what)) = merged { + // SAFETY: an open list; live buffers; what the compute side + // of it had bound is bound again. + unsafe { + self.wait_for_all(list); + self.merge_all(list, from, &[what]); + self.wait_for_all(list); + for c in &compute { + self.command(list, c, version); + } + } + } else { + // SAFETY: an open list; the objects are the frame's, alive + // with the player; commands the host recorded the same way. + unsafe { self.command(list, c, version) }; + } + match c { + Cmd::RootSignature { + graphics: false, .. + } => { + compute.retain(|c| matches!(c, Cmd::Pipeline { .. })); + compute.push(c.clone()); + } + Cmd::Pipeline { .. } => { + compute.retain(|c| !matches!(c, Cmd::Pipeline { .. })); + compute.push(c.clone()); + } + Cmd::Table { + graphics: false, .. + } + | Cmd::Constants { + graphics: false, .. + } + | Cmd::RootView { + graphics: false, .. + } => compute.push(c.clone()), + _ => {} + } if wait && c.works() { // SAFETY: an open list. unsafe { self.wait_for_all(list) }; @@ -2608,6 +2717,7 @@ impl Player { notes: self.notes.clone(), ..Default::default() }; + self.set_merging(o.merge)?; let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { @@ -2654,6 +2764,10 @@ impl Player { if o.detailed { self.detail(&built, &stamps, o, &mut report); } + if self.merging { + let notes = self.merge_notes(o.loops)?; + report.notes.extend(notes); + } self.picture(o, &mut report)?; if let Some(q) = &self.info { report.notes.extend(debug_messages(q)); diff --git a/crates/victory-gpu/src/replay/play/diverge.rs b/crates/victory-gpu/src/replay/play/diverge.rs index 7a6ace0..a297040 100644 --- a/crates/victory-gpu/src/replay/play/diverge.rs +++ b/crates/victory-gpu/src/replay/play/diverge.rs @@ -104,13 +104,20 @@ impl Player { } roots += 1; // The shortest start of the rest that differs. - let works: Vec = (from..cmds.len()).filter(|&c| cmds[c].works()).collect(); + let works: Vec = + (from..cmds.len()).filter(|&c| cmds[c].works()).collect(); let (mut lo, mut hi) = (0, works.len() - 1); while lo < hi { let mid = (lo + hi) / 2; - let cut = Unit { to: works[mid] + 1, ..unit }; + let cut = Unit { + to: works[mid] + 1, + ..unit + }; self.put_back(&states)?; - if self.trials(&reader, &cut, &states, s.runs, s.wait_all)?.is_empty() { + if self + .trials(&reader, &cut, &states, s.runs, s.wait_all)? + .is_empty() + { lo = mid + 1; } else { hi = mid; @@ -172,13 +179,18 @@ impl Player { let mut states = self.start_states(); for (here, &(i, j, cmds)) in flat.iter().enumerate() { let inside = s.lists.is_some_and(|(a, b)| a == b && a as usize == here); - let looks = s.lists.is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here)); + let looks = s + .lists + .is_none_or(|(a, b)| (a as usize..=b as usize).contains(&here)); let works: Vec = (0..cmds.len()).filter(|&c| cmds[c].works()).collect(); // Where the list is cut. let mut cuts: Vec = vec![0]; if inside { let (a, b) = commands.unwrap_or((0, u32::MAX)); - let some = works.iter().map(|&c| c + 1).filter(|c| (a as usize..=b as usize).contains(c)); + let some = works + .iter() + .map(|&c| c + 1) + .filter(|c| (a as usize..=b as usize).contains(c)); cuts.extend(some.step_by(step.max(1))); } for (k, &from) in cuts.iter().enumerate() { @@ -189,14 +201,26 @@ impl Player { self.put_back(&states)?; } let mut now = states.clone(); - let first = Unit { submit: i, cmds, from, to: cmds.len(), delta: j == 0 && from == 0 }; + let first = Unit { + submit: i, + cmds, + from, + to: cmds.len(), + delta: j == 0 && from == 0, + }; self.go(&first, s.wait_all)?; now = self.after(&first, &now); for (n, &(i, j, cmds)) in flat.iter().enumerate().skip(here + 1) { if flat[n - 1].0 != i { now.decay(); } - let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + let unit = Unit { + submit: i, + cmds, + from: 0, + to: cmds.len(), + delta: j == 0, + }; self.go(&unit, s.wait_all)?; now = self.after(&unit, &now); } @@ -222,7 +246,13 @@ impl Player { } // On to the next cut. let to = cuts.get(k + 1).copied().unwrap_or(cmds.len()); - let unit = Unit { submit: i, cmds, from, to, delta: j == 0 && from == 0 }; + let unit = Unit { + submit: i, + cmds, + from, + to, + delta: j == 0 && from == 0, + }; self.go(&unit, s.wait_all)?; self.commit(&unit, &mut states)?; self.at = states.clone(); @@ -248,7 +278,9 @@ impl Player { fn start_states(&self) -> States { let mut states = States::default(); for (id, all) in &self.start { - let Some(o) = self.objects.get(id) else { continue }; + let Some(o) = self.objects.get(id) else { + continue; + }; let flags = self.frame.resources[o.index].desc.flags; let decays = flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0; states.add(*id, o.subs, all[0], decays); @@ -285,38 +317,73 @@ impl Player { let start = self.start_states(); let before = self.hashes_now(&reader, &start)?; let mut again = self.hashes_now(&reader, &start)?; - say(format!("read twice, {} parts differ", before.iter().zip(&again).filter(|(a, b)| a != b).count())); + say(format!( + "read twice, {} parts differ", + before.iter().zip(&again).filter(|(a, b)| a != b).count() + )); for i in 0..3 { - self.run(&Options { loops: 1, ..Options::default() })?; + self.run(&Options { + loops: 1, + ..Options::default() + })?; let ran = { - let end: Vec<(u32, Vec)> = self.end.iter().map(|(k, v)| (*k, v.clone())).collect(); + let end: Vec<(u32, Vec)> = + self.end.iter().map(|(k, v)| (*k, v.clone())).collect(); let mut s = start.clone(); for (id, v) in end { for (sub, st) in v.iter().enumerate() { let sub = if v.len() == 1 { ALL } else { sub as u32 }; - s.change(&states::Change { res: id, sub, after: *st, promoted: false, alias: false }); + s.change(&states::Change { + res: id, + sub, + after: *st, + promoted: false, + alias: false, + }); } } self.hashes_now(&reader, &s)? }; self.restore(true)?; again = self.hashes_now(&reader, &start)?; - let differ: Vec = (0..before.len()).filter(|&i| before[i] != again[i]).collect(); + let differ: Vec = (0..before.len()) + .filter(|&i| before[i] != again[i]) + .collect(); let changed = (0..before.len()).filter(|&i| before[i] != ran[i]).count(); - say(format!("run {i}: {changed} parts changed by the frame, {} not put back as they were", differ.len())); + say(format!( + "run {i}: {changed} parts changed by the frame, {} not put back as they were", + differ.len() + )); for &d in differ.iter().take(20) { - let pieces = before[d].iter().zip(&again[d]).filter(|(a, b)| a != b).count(); - say(format!(" {} {:?}: {pieces} of {} pieces", self.called(reader.parts[d].id), reader.parts[d].sub.map(|s| s.0), before[d].len())); + let pieces = before[d] + .iter() + .zip(&again[d]) + .filter(|(a, b)| a != b) + .count(); + say(format!( + " {} {:?}: {pieces} of {} pieces", + self.called(reader.parts[d].id), + reader.parts[d].sub.map(|s| s.0), + before[d].len() + )); } } } let put_back: HashSet = self.masters.iter().map(|m| m.0).collect(); - let others: Vec = self.objects.keys().copied().filter(|id| !put_back.contains(id)).collect(); + let others: Vec = self + .objects + .keys() + .copied() + .filter(|id| !put_back.contains(id)) + .collect(); let reader = self.reader(&others)?; self.restore(true)?; let start = self.start_states(); let before = self.hashes_now(&reader, &start)?; - let o = Options { loops: 1, ..Options::default() }; + let o = Options { + loops: 1, + ..Options::default() + }; self.run(&o)?; self.restore(true)?; let after = self.hashes_now(&reader, &start)?; @@ -337,7 +404,11 @@ impl Player { )); } } - say(format!("{} parts of {} resources looked at, {n} changed", reader.parts.len(), others.len())); + say(format!( + "{} parts of {} resources looked at, {n} changed", + reader.parts.len(), + others.len() + )); Ok(()) } @@ -381,7 +452,12 @@ impl Player { } let mut blocks = Vec::new(); for size in sizes { - let (b, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, size, D3D12_RESOURCE_FLAG_NONE)?; + let (b, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + size, + D3D12_RESOURCE_FLAG_NONE, + )?; blocks.push((b, data as usize)); } Ok(Reader { blocks, parts }) @@ -410,12 +486,22 @@ impl Player { let before: Vec = unit.cmds[..unit.from] .iter() .filter(|c| { - !c.works() && !matches!(c, Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. }) + !c.works() + && !matches!( + c, + Cmd::Barriers { .. } | Cmd::BeginQuery { .. } | Cmd::EndQuery { .. } + ) }) .cloned() .collect(); self.translate(&l.1, &before, unit.submit, None, false); - self.translate(&l.1, &unit.cmds[unit.from..unit.to], unit.submit, None, wait); + self.translate( + &l.1, + &unit.cmds[unit.from..unit.to], + unit.submit, + None, + wait, + ); // SAFETY: an open list. unsafe { l.1.Close()? }; lists.push(l); @@ -437,7 +523,10 @@ impl Player { for p in parts.iter().filter(|p| p.sub.is_some()) { if seen.insert(p.id) { let state = states.get(p.id).unwrap_or(vec![COMMON]); - let to: Vec = state.iter().map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }).collect(); + let to: Vec = state + .iter() + .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE }) + .collect(); gpu::moves(&objects[&p.id].res, &state, &to, &mut before); gpu::moves(&objects[&p.id].res, &to, &state, &mut after); } @@ -453,7 +542,14 @@ impl Player { None => list.CopyBufferRegion(to, p.at, res, 0, p.len), Some((sub, mut f)) => { f.Offset = p.at; - list.CopyTextureRegion(&gpu::placed_location(to, f), 0, 0, 0, &gpu::sub_location(res, sub), None); + list.CopyTextureRegion( + &gpu::placed_location(to, f), + 0, + 0, + 0, + &gpu::sub_location(res, sub), + None, + ); } } } @@ -462,7 +558,8 @@ impl Player { })?; } let next = AtomicUsize::new(0); - let out: std::sync::Mutex>> = std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]); + let out: std::sync::Mutex>> = + std::sync::Mutex::new(vec![Vec::new(); reader.parts.len()]); std::thread::scope(|scope| { for _ in 0..16 { scope.spawn(|| { @@ -488,7 +585,14 @@ impl Player { /// Runs the unit `runs` times (memory is as at its start, and is put /// back between runs) and compares. Memory is as the last run left it. - fn trials(&mut self, reader: &Reader, unit: &Unit, states: &States, runs: u32, wait: bool) -> Result { + fn trials( + &mut self, + reader: &Reader, + unit: &Unit, + states: &States, + runs: u32, + wait: bool, + ) -> Result { let after = self.after(unit, states); let mut first: Option>> = None; let mut pieces = std::collections::BTreeSet::new(); @@ -505,7 +609,13 @@ impl Player { None => first = Some(now), Some(first) => { for (p, (a, b)) in first.iter().zip(&now).enumerate() { - pieces.extend(a.iter().zip(b).enumerate().filter(|(_, (a, b))| a != b).map(|(i, _)| (p, i))); + pieces.extend( + a.iter() + .zip(b) + .enumerate() + .filter(|(_, (a, b))| a != b) + .map(|(i, _)| (p, i)), + ); } } } @@ -537,12 +647,18 @@ impl Player { /// Copies the masters over the resources (which are in `from` and go to /// `to`), or the resources into the masters. fn copy_masters(&mut self, from: &States, to: &States, save: bool) -> Result<()> { - let known: HashMap = self.masters.iter().map(|(id, m)| (*id, m)).collect(); + let known: HashMap = + self.masters.iter().map(|(id, m)| (*id, m)).collect(); let (mut before, mut after, mut plain) = (Vec::new(), Vec::new(), Vec::new()); let here = if save { COPY_SOURCE } else { COPY_DEST }; for id in self.start.keys() { - let Some(o) = self.objects.get(id) else { continue }; - let (a, b) = (from.get(*id).unwrap_or(vec![COMMON]), to.get(*id).unwrap_or(vec![COMMON])); + let Some(o) = self.objects.get(id) else { + continue; + }; + let (a, b) = ( + from.get(*id).unwrap_or(vec![COMMON]), + to.get(*id).unwrap_or(vec![COMMON]), + ); let Some(m) = known.get(id) else { gpu::moves(&o.res, &a, &b, &mut plain); continue; @@ -590,27 +706,59 @@ impl Player { match c { Cmd::Pipeline { pso: p } => pso = *p, Cmd::RootSignature { graphics, .. } => binds.retain(|k, _| k.0 != *graphics), - Cmd::RootView { graphics, kind, param, va } => { - let kind = ["", "cbv", "srv", "uav"].get(*kind as usize).copied().unwrap_or(""); + Cmd::RootView { + graphics, + kind, + param, + va, + } => { + let kind = ["", "cbv", "srv", "uav"] + .get(*kind as usize) + .copied() + .unwrap_or(""); let text = match va { - Va::At { res, offset } => format!("{kind} {} +{offset:#x}", self.called(*res)), + Va::At { res, offset } => { + format!("{kind} {} +{offset:#x}", self.called(*res)) + } _ => format!("{kind} null"), }; binds.insert((*graphics, *param), text); } - Cmd::Table { graphics, param, heap, slot } => { - binds.insert((*graphics, *param), format!("table heap {heap} slot {slot}")); + Cmd::Table { + graphics, + param, + heap, + slot, + } => { + binds.insert( + (*graphics, *param), + format!("table heap {heap} slot {slot}"), + ); } - Cmd::Constants { graphics, param, offset, values } => { + Cmd::Constants { + graphics, + param, + offset, + values, + } => { let text = format!("constants +{offset} {values:x?}"); - binds.entry((*graphics, *param)).and_modify(|t| *t = format!("{t}, {text}")).or_insert(text); + binds + .entry((*graphics, *param)) + .and_modify(|t| *t = format!("{t}, {text}")) + .or_insert(text); } Cmd::Targets { colors, depth } => { - let all: Vec = colors.iter().chain(depth).map(|s| self.called(s.res)).collect(); + let all: Vec = colors + .iter() + .chain(depth) + .map(|s| self.called(s.res)) + .collect(); targets = all.join(", "); } Cmd::Barriers { all } => since.extend(all.iter().map(|b| match b { - Barrier::Transition { res, before, after, .. } => format!("{} {before:#x}->{after:#x}", self.called(*res)), + Barrier::Transition { + res, before, after, .. + } => format!("{} {before:#x}->{after:#x}", self.called(*res)), Barrier::Uav { res: 0, .. } => "all uav".into(), Barrier::Uav { res, .. } => format!("uav {}", self.called(*res)), Barrier::Alias { .. } => "alias".into(), @@ -622,7 +770,11 @@ impl Player { } } let graphics = !matches!(cmds[at], Cmd::Dispatch { .. }); - let binds: Vec = binds.iter().filter(|(k, _)| k.0 == graphics).map(|(k, t)| format!("[{}] {t}", k.1)).collect(); + let binds: Vec = binds + .iter() + .filter(|(k, _)| k.0 == graphics) + .map(|(k, t)| format!("[{}] {t}", k.1)) + .collect(); let mut text = format!("{:?}", cmds[at]); if cmds[at].runs_shaders() { text += &format!(" of {}", self.pipeline_name(pso)); @@ -631,12 +783,20 @@ impl Player { text += &format!("\n targets: {targets}"); } } - text + &format!("\n barriers since the command before: {}", since.join("; ")) + text + &format!( + "\n barriers since the command before: {}", + since.join("; ") + ) } /// Says which lists (of the list in `s.lists`: which commands) change /// words of a buffer, and to what. - pub fn watch(&mut self, s: &Search, parts: &[(u32, u64, u64)], say: &mut dyn FnMut(String)) -> Result<()> { + pub fn watch( + &mut self, + s: &Search, + parts: &[(u32, u64, u64)], + say: &mut dyn FnMut(String), + ) -> Result<()> { let mut report = Report::default(); let submits = self.edited(&s.options, &mut report, &[]); self.restore(true)?; @@ -646,7 +806,10 @@ impl Player { .iter() .map(|&(id, at, len)| { let bytes = p.slice(id, at, len)?; - Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + Ok(bytes + .chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect()) }) .collect() }; @@ -666,13 +829,25 @@ impl Player { cuts.push(cmds.len()); } for k in 0..cuts.len() - 1 { - let unit = Unit { submit: i, cmds, from: cuts[k], to: cuts[k + 1], delta: j == 0 && k == 0 }; + let unit = Unit { + submit: i, + cmds, + from: cuts[k], + to: cuts[k + 1], + delta: j == 0 && k == 0, + }; self.go(&unit, s.wait_all)?; let now = words(self)?; if now != was { if inside { - let last = (unit.from..unit.to).rev().find(|&c| cmds[c].works()).unwrap_or(unit.to - 1); - say(format!("list {here} (submission {i}, its list {j}) command {last}: {}", self.describe(cmds, last))); + let last = (unit.from..unit.to) + .rev() + .find(|&c| cmds[c].works()) + .unwrap_or(unit.to - 1); + say(format!( + "list {here} (submission {i}, its list {j}) command {last}: {}", + self.describe(cmds, last) + )); } else { say(format!("list {here} (submission {i}, its list {j})")); } @@ -703,7 +878,12 @@ impl Player { /// Each draw of one list whose pipeline's name has `text` in it, run /// alone (with what prepares its arguments) from the memory at the list's /// start, `runs` times: how many different contents its targets get. - pub fn diverge_draws(&mut self, s: &Search, text: &str, say: &mut dyn FnMut(String)) -> Result<()> { + pub fn diverge_draws( + &mut self, + s: &Search, + text: &str, + say: &mut dyn FnMut(String), + ) -> Result<()> { let mut report = Report::default(); let submits = self.edited(&s.options, &mut report, &[]); let flat: Vec<(usize, usize, &Vec)> = submits @@ -717,7 +897,13 @@ impl Player { let mut states = self.start_states(); for (here, &(i, j, cmds)) in flat.iter().enumerate() { if here < wanted { - let unit = Unit { submit: i, cmds, from: 0, to: cmds.len(), delta: j == 0 }; + let unit = Unit { + submit: i, + cmds, + from: 0, + to: cmds.len(), + delta: j == 0, + }; self.go(&unit, s.wait_all)?; self.commit(&unit, &mut states)?; if flat.get(here + 1).is_none_or(|n| n.0 != i) { @@ -732,10 +918,23 @@ impl Player { for (c, cmd) in cmds.iter().enumerate() { match cmd { Cmd::Pipeline { pso: p } => pso = *p, - Cmd::Targets { colors, depth } => targets = colors.iter().chain(depth).map(|s| s.res).filter(|r| *r != NONE).collect(), + Cmd::Targets { colors, depth } => { + targets = colors + .iter() + .chain(depth) + .map(|s| s.res) + .filter(|r| *r != NONE) + .collect() + } _ => {} } - if !matches!(cmd, Cmd::Indirect { .. } | Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. }) { + if !matches!( + cmd, + Cmd::Indirect { .. } + | Cmd::Draw { .. } + | Cmd::DrawIndexed { .. } + | Cmd::DispatchMesh { .. } + ) { continue; } let from = std::mem::replace(&mut last, c + 1); @@ -745,12 +944,20 @@ impl Player { targets.sort_unstable(); targets.dedup(); let reader = self.reader(&targets)?; - let unit = Unit { submit: i, cmds, from, to: c + 1, delta: false }; + let unit = Unit { + submit: i, + cmds, + from, + to: c + 1, + delta: false, + }; // Barriers before it in the list are made up for: textures // are in the states the list has them in here. let mut before = states.clone(); let mut all = Vec::new(); - cmds[..from].iter().for_each(|c| states::changes(c, &mut all)); + cmds[..from] + .iter() + .for_each(|c| states::changes(c, &mut all)); all.iter().for_each(|c| before.change(c)); let after = self.after(&unit, &before); let mut kinds: HashMap>, u32> = HashMap::new(); @@ -770,7 +977,12 @@ impl Player { } let mut counts: Vec = kinds.values().copied().collect(); counts.sort_unstable(); - say(format!("command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}", cmd, self.pipeline_name(pso), counts.len())); + say(format!( + "command {c} (from {from}) {:?} of {}: {} outcomes {counts:?}", + cmd, + self.pipeline_name(pso), + counts.len() + )); } break; } @@ -779,13 +991,20 @@ impl Player { /// `len` bytes of a buffer from `at`. fn slice(&mut self, id: u32, at: u64, len: u64) -> Result> { - let Some(o) = self.objects.get(&id) else { return Ok(Vec::new()) }; + let Some(o) = self.objects.get(&id) else { + return Ok(Vec::new()); + }; let len = len.min(self.frame.resources[o.index].desc.width.saturating_sub(at)); if len == 0 { return Ok(Vec::new()); } let res = o.res.clone(); - let (back, data) = gpu::buffer(&self.device, D3D12_HEAP_TYPE_READBACK, len, D3D12_RESOURCE_FLAG_NONE)?; + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + len, + D3D12_RESOURCE_FLAG_NONE, + )?; self.worker.run(|list| { // SAFETY: an open list; live buffers. unsafe { list.CopyBufferRegion(&back, 0, &res, at, len) }; @@ -796,20 +1015,39 @@ impl Player { /// The words of a buffer view (raw or typed, of words). fn view_words(&mut self, s: &Slot, first: u64, n: u64) -> Result> { - let at = u64::from_le_bytes([s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22], s.desc[23]]); - let count = u64::from(u32::from_le_bytes([s.desc[24], s.desc[25], s.desc[26], s.desc[27]])); + let at = u64::from_le_bytes([ + s.desc[16], s.desc[17], s.desc[18], s.desc[19], s.desc[20], s.desc[21], s.desc[22], + s.desc[23], + ]); + let count = u64::from(u32::from_le_bytes([ + s.desc[24], s.desc[25], s.desc[26], s.desc[27], + ])); let n = n.min(count.saturating_sub(first)); let bytes = self.slice(s.res, (at + first) * 4, n * 4)?; - Ok(bytes.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect()) + Ok(bytes + .chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect()) } /// What a mesh draw of the title's (with its usual constants) reads. - fn peek(&mut self, cmds: &[Cmd], at: usize, submit: usize, say: &mut dyn FnMut(String)) -> Result<()> { + fn peek( + &mut self, + cmds: &[Cmd], + at: usize, + submit: usize, + say: &mut dyn FnMut(String), + ) -> Result<()> { let mut v = [0u32; 16]; let mut heap = NONE; for c in &cmds[..at] { match c { - Cmd::Constants { graphics: true, param: 0, offset, values } => { + Cmd::Constants { + graphics: true, + param: 0, + offset, + values, + } => { for (k, x) in values.iter().enumerate() { if let Some(at) = v.get_mut(*offset as usize + k) { *at = *x; @@ -834,20 +1072,33 @@ impl Player { ("x+2848", v[8] + 2848, 0), ] { let s = slot(self, byte); - let words = if s.kind == slot::SRV { self.view_words(&s, 0, n)? } else { Vec::new() }; - say(format!(" {name}: slot {} {}: {words:x?}", byte >> 5, self.slot_text(&s))); + let words = if s.kind == slot::SRV { + self.view_words(&s, 0, n)? + } else { + Vec::new() + }; + say(format!( + " {name}: slot {} {}: {words:x?}", + byte >> 5, + self.slot_text(&s) + )); } // The list of visible meshlets, as the mesh shader finds it. let lists = slot(self, v[8] + 2752); let word = self.view_words(&lists, u64::from((v[13] & 0x07ff_ffff) & 0x07ff_ffff), 4)?; let typed = slot(self, v[8] + 1600); let index = self.view_words(&typed, 510, 1)?; - say(format!(" list words {word:x?} (count {}, first {}), typed view slot {index:x?}", word.first().map_or(0, |w| w >> 15), word.first().map_or(0, |w| w & 0x7fff))); + say(format!( + " list words {word:x?} (count {}, first {}), typed view slot {index:x?}", + word.first().map_or(0, |w| w >> 15), + word.first().map_or(0, |w| w & 0x7fff) + )); if let (Some(w), Some(i)) = (word.first(), index.first()) { let s = self.slot_at(heap, i & 0x07ff_ffff, submit); say(format!(" typed view: {}", self.slot_text(&s))); if s.kind == slot::SRV && s.res != NONE { - let list = self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?; + let list = + self.view_words(&s, u64::from(w & 0x7fff) * 16, u64::from(w >> 15) + 16)?; say(format!(" visible meshlets: {list:x?}")); } } @@ -868,7 +1119,12 @@ impl Player { let mut heap = NONE; for c in &cmds[..command] { match c { - Cmd::Constants { param, offset, values: v, .. } => { + Cmd::Constants { + param, + offset, + values: v, + .. + } => { for (k, x) in v.iter().enumerate() { if let Some(all) = values.get_mut(*param as usize) && let Some(at) = all.get_mut(*offset as usize + k) @@ -882,7 +1138,12 @@ impl Player { } } say(format!("heap {heap}, constants {values:x?}")); - let mut bases: Vec = values.iter().flatten().map(|v| v >> 5).filter(|v| *v > 64).collect(); + let mut bases: Vec = values + .iter() + .flatten() + .map(|v| v >> 5) + .filter(|v| *v > 64) + .collect(); bases.dedup(); for base in bases { for k in 0..12 { @@ -904,10 +1165,19 @@ impl Player { /// A heap slot as it was for a submission. fn slot_at(&self, heap: u32, at: u32, submit: usize) -> Slot { let late = self.frame.submits[..=submit].iter().rev().find_map(|s| { - s.views.iter().rev().find(|(h, i, _)| *h == heap && *i == at).map(|v| v.2) + s.views + .iter() + .rev() + .find(|(h, i, _)| *h == heap && *i == at) + .map(|v| v.2) }); late.unwrap_or_else(|| { - let runs = self.frame.descriptor_heaps.iter().find(|h| h.id == heap).map(|h| &h.runs); + let runs = self + .frame + .descriptor_heaps + .iter() + .find(|h| h.id == heap) + .map(|h| &h.runs); runs.and_then(|runs| { let k = runs.partition_point(|r| r.0 <= at).checked_sub(1)?; let (first, n, s) = &runs[k]; @@ -918,9 +1188,23 @@ impl Player { } fn slot_text(&self, s: &Slot) -> String { - let word = |i: usize| u32::from_le_bytes([s.desc[i * 4], s.desc[i * 4 + 1], s.desc[i * 4 + 2], s.desc[i * 4 + 3]]); - let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"].get(s.kind as usize).copied().unwrap_or("?"); - let res = if s.res == NONE { "null".into() } else { self.called(s.res) }; + let word = |i: usize| { + u32::from_le_bytes([ + s.desc[i * 4], + s.desc[i * 4 + 1], + s.desc[i * 4 + 2], + s.desc[i * 4 + 3], + ]) + }; + let kind = ["empty", "cbv", "srv", "uav", "sampler", "rtv", "dsv"] + .get(s.kind as usize) + .copied() + .unwrap_or("?"); + let res = if s.res == NONE { + "null".into() + } else { + self.called(s.res) + }; match s.kind { slot::CBV => format!("cbv {res} +{:#x} size {:#x}", s.address(), word(2)), _ => format!( @@ -935,7 +1219,7 @@ impl Player { } } - fn called(&self, id: u32) -> String { + pub(super) fn called(&self, id: u32) -> String { let Some(o) = self.objects.get(&id) else { return format!("resource {id} (not there)"); }; @@ -948,12 +1232,22 @@ impl Player { }; format!("#{id} '{}' buffer {:#x} {kind}", r.name, d.width) } else { - format!("#{id} '{}' {}x{}x{} m{} f{}", r.name, d.width, d.height, d.depth, d.mips, d.format) + format!( + "#{id} '{}' {}x{}x{} m{} f{}", + r.name, d.width, d.height, d.depth, d.mips, d.format + ) } } /// Runs the unit until two runs differ, and says how. - fn compare(&mut self, reader: &Reader, unit: &Unit, states: &States, pieces: &Pieces, wait: bool) -> Result> { + fn compare( + &mut self, + reader: &Reader, + unit: &Unit, + states: &States, + pieces: &Pieces, + wait: bool, + ) -> Result> { let after = self.after(unit, states); let parts: std::collections::BTreeSet = pieces.iter().map(|p| p.0).collect(); let mut seen: Vec<(Vec>, Vec>)> = Vec::new(); @@ -966,7 +1260,10 @@ impl Player { if seen.iter().any(|(h, _)| *h == hashes) { continue; } - let data = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + let data = parts + .iter() + .map(|&p| reader.bytes(&reader.parts[p]).to_vec()) + .collect(); seen.push((hashes, data)); if seen.len() == 2 { break; @@ -978,9 +1275,16 @@ impl Player { && let Some((p, part)) = reader.parts.iter().enumerate().find(|(_, p)| p.id == *args) { let bytes = &reader.bytes(part)[*at as usize..]; - let words: Vec = bytes.chunks_exact(4).take(8).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect(); + let words: Vec = bytes + .chunks_exact(4) + .take(8) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect(); let each: HashSet<&Vec> = seen.iter().map(|s| &s.0[p]).collect(); - out.push(format!("arguments {words:x?} (the same in all runs: {})", each.len() == 1)); + out.push(format!( + "arguments {words:x?} (the same in all runs: {})", + each.len() == 1 + )); } self.at = after; let [(_, a), (_, b)] = &seen[..] else { @@ -988,13 +1292,19 @@ impl Player { return Ok(out); }; // And without the command. - let before = Unit { to: unit.to - 1, ..*unit }; + let before = Unit { + to: unit.to - 1, + ..*unit + }; self.put_back(states)?; self.go(&before, wait)?; self.at = self.after(&before, states); let now = self.at.clone(); self.hashes_now(reader, &now)?; - let without: Vec> = parts.iter().map(|&p| reader.bytes(&reader.parts[p]).to_vec()).collect(); + let without: Vec> = parts + .iter() + .map(|&p| reader.bytes(&reader.parts[p]).to_vec()) + .collect(); let to = self.folder.join("diverge"); let _ = std::fs::create_dir_all(&to); for (k, &p) in parts.iter().enumerate().take(12) { @@ -1002,13 +1312,28 @@ impl Player { // Both contents, to look at. let sub = part.sub.map_or(0, |s| s.0); let _ = std::fs::write(to.join(format!("{}-{sub}-0.bin", part.id)), &without[k]); - let changed = |v: &[u8]| v.chunks_exact(4).zip(without[k].chunks_exact(4)).filter(|(x, y)| x != y).count(); - out.push(format!("it changes {} dwords in one run, {} in another", changed(&a[k]), changed(&b[k]))); + let changed = |v: &[u8]| { + v.chunks_exact(4) + .zip(without[k].chunks_exact(4)) + .filter(|(x, y)| x != y) + .count() + }; + out.push(format!( + "it changes {} dwords in one run, {} in another", + changed(&a[k]), + changed(&b[k]) + )); let _ = std::fs::write(to.join(format!("{}-{sub}-a.bin", part.id)), &a[k]); let _ = std::fs::write(to.join(format!("{}-{sub}-b.bin", part.id)), &b[k]); - let words = |v: &[u8]| -> Vec { v.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())).collect() }; + let words = |v: &[u8]| -> Vec { + v.chunks_exact(4) + .map(|c| u32::from_le_bytes(c.try_into().unwrap_or_default())) + .collect() + }; let (x, y) = (words(&a[k]), words(&b[k])); - let differ: Vec = (0..x.len().min(y.len())).filter(|&i| x[i] != y[i]).collect(); + let differ: Vec = (0..x.len().min(y.len())) + .filter(|&i| x[i] != y[i]) + .collect(); if differ.is_empty() { continue; } @@ -1018,9 +1343,19 @@ impl Player { s.sort_unstable(); s }; - let order = if sorted(&x) == sorted(&y) { " (the same values in another order)" } else { "" }; - let sub = part.sub.map_or(String::new(), |(s, f)| format!(" subresource {s} pitch {}", f.Footprint.RowPitch)); - let sample: Vec = differ.iter().take(8).map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i])).collect(); + let order = if sorted(&x) == sorted(&y) { + " (the same values in another order)" + } else { + "" + }; + let sub = part.sub.map_or(String::new(), |(s, f)| { + format!(" subresource {s} pitch {}", f.Footprint.RowPitch) + }); + let sample: Vec = differ + .iter() + .take(8) + .map(|&i| format!("+{:#x}: {:08x} {:08x}", i * 4, x[i], y[i])) + .collect(); out.push(format!( "writes {}{sub}: {} of {} dwords differ, {:#x}..{:#x}{order}: {}", self.called(part.id), @@ -1041,6 +1376,11 @@ impl Player { impl Reader { fn bytes(&self, p: &Part) -> &[u8] { // SAFETY: a part of a mapped block; copies into it have run. - unsafe { std::slice::from_raw_parts((self.blocks[p.block].1 + p.at as usize) as *const u8, p.len as usize) } + unsafe { + std::slice::from_raw_parts( + (self.blocks[p.block].1 + p.at as usize) as *const u8, + p.len as usize, + ) + } } } diff --git a/crates/victory-gpu/src/replay/play/merge.rs b/crates/victory-gpu/src/replay/play/merge.rs new file mode 100644 index 0000000..daddcd0 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/merge.rs @@ -0,0 +1,291 @@ +//! What the CPU wrote, put in without what the card wrote. +//! +//! The host layer brings results of shaders back to title memory, and sends +//! pieces of title memory up again (64 KiB at a time) when the title changed +//! some of them. What goes up therefore holds results of the recorded frame. +//! Shaders that give out places with atomics give other places in every run: +//! the recorded results put over a replay's own leave lists and what points +//! into them of two different frames. So where a copy brings memory of the +//! CPU to a buffer the card writes, words the card has written since the +//! start of the frame (which are not what was last put there) stay. + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; + +use super::*; + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)" +cbuffer C : register(b0) { uint words; uint call; }; +ByteAddressBuffer from : register(t0); +RWByteAddressBuffer to : register(u0); +RWByteAddressBuffer base : register(u1); +// For each call: words put, words of the card's left that were to get +// another value, and of those the ones that were to get back what stood +// there before the card wrote. +RWByteAddressBuffer counts : register(u2); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= words) return; + uint at = id.x * 4; + uint v = from.Load(at), now = to.Load(at), was = base.Load(at), n; + if (now != was) { + if (v == now) return; + counts.InterlockedAdd(call * 12 + 4, 1, n); + if (v == was) counts.InterlockedAdd(call * 12 + 8, 1, n); + return; + } + if (v == now) return; + counts.InterlockedAdd(call * 12, 1, n); + to.Store(at, v); + base.Store(at, v); +} +"#; + +pub(super) struct Merger { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// For each buffer: what was last put there (at first, what it held at + /// the frame's start). + pub(super) bases: HashMap, + pub(super) counts: ID3D12Resource, + /// The merges recorded: buffer, offset, length (in `CALLS` at the most). + pub(super) calls: std::cell::RefCell>, +} + +const CALLS: u64 = 1 << 16; + +impl Player { + /// The copy of a piece of a card buffer's CPU side to it: its source's + /// address, then the buffer, offset, 0 and length. + pub(super) fn merged_copy(&self, c: &Cmd) -> Option<(u64, (u32, u64, u64, u64))> { + let Cmd::CopyBuffer { + dst, + dst_at, + src, + src_at, + len, + } = c + else { + return None; + }; + if !self.merging + || !self.pairs(*src, *dst) + || dst_at != src_at + || dst_at % 4 != 0 + || len % 4 != 0 + { + return None; + } + self.merger.as_ref()?.bases.get(dst)?; + let from = self.objects.get(src)?.va + src_at; + Some((from, (*dst, *dst_at, 0, *len))) + } + + /// Whether `src` is the CPU's side of card buffer `dst`. + fn pairs(&self, src: u32, dst: u32) -> bool { + let (Some(a), Some(b)) = (self.objects.get(&src), self.objects.get(&dst)) else { + return false; + }; + let (a, b) = ( + &self.frame.resources[a.index], + &self.frame.resources[b.index], + ); + let cpu = + matches!(&a.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::Cached); + cpu && b.name.ends_with("on the card") + && a.desc.width == b.desc.width + && self.card_writes.contains(&dst) + } + + /// Records merges: (buffer, offset in it, offset from `from`, length). + /// + /// # Safety + /// An open list; `from` is the address of memory that holds the bytes. + pub(super) unsafe fn merge_all( + &self, + list: &ID3D12GraphicsCommandList, + from: u64, + all: &[(u32, u64, u64, u64)], + ) { + let Some(m) = &self.merger else { return }; + // SAFETY: the caller's; live buffers. + unsafe { + list.SetComputeRootSignature(&m.root); + list.SetPipelineState(&m.pso); + for (id, at, source, len) in all { + let (Some(o), Some(base)) = (self.objects.get(id), m.bases.get(id)) else { + continue; + }; + let base = base.GetGPUVirtualAddress(); + // At most 65,535 groups in a dispatch. + const MOST: u64 = 8 << 20; + let mut done = 0; + while done < *len { + let n = MOST.min(len - done); + let words = (n / 4) as u32; + let mut calls = m.calls.borrow_mut(); + let call = (calls.len() as u64).min(CALLS - 1) as u32; + if calls.len() < CALLS as usize { + calls.push((*id, at + done, n)); + } + drop(calls); + list.SetComputeRoot32BitConstants(0, 2, [words, call].as_ptr().cast(), 0); + list.SetComputeRootUnorderedAccessView(4, m.counts.GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView(1, from + source + done); + list.SetComputeRootUnorderedAccessView(2, o.va + at + done); + list.SetComputeRootUnorderedAccessView(3, base + at + done); + list.Dispatch(words.div_ceil(64), 1, 1); + done += n; + } + } + } + } + + /// Switches merging on or off; makes what it needs at first. + pub(super) fn set_merging(&mut self, on: bool) -> Result<()> { + self.merging = on; + if let Some(m) = &self.merger { + m.calls.borrow_mut().clear(); + } + if !on || self.merger.is_some() { + return Ok(()); + } + let mut code: Option = None; + // SAFETY: the source and names live through the call; the blob's own + // bytes. + let (root, pso) = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + None, + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.context("no merge shader")?; + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = + self.device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + (root, pso) + }; + let mut ids: HashSet = HashSet::new(); + for c in self.commands.iter().flatten() { + if let Cmd::CopyBuffer { dst, src, .. } = c + && self.pairs(*src, *dst) + { + ids.insert(*dst); + } + } + ids.extend( + self.delta_parts + .iter() + .flatten() + .map(|(d, _)| d.res) + .filter(|id| self.card_writes.contains(id)), + ); + let mut bases = HashMap::new(); + let mut total = 0; + for id in ids { + if !self.masters.iter().any(|m| m.0 == id) { + continue; + } + let size = self.frame.resources[self.objects[&id].index].desc.width; + let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + bases.insert( + id, + gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, size, flags)?.0, + ); + total += size; + } + let masters: HashMap = self.masters.iter().cloned().collect(); + self.worker.run(|list| { + for (id, base) in &bases { + // SAFETY: an open list; live buffers of one size. + unsafe { list.CopyResource(base, &masters[id]) }; + } + })?; + tracing::info!( + buffers = bases.len(), + mb = total >> 20, + "bases of merged copies" + ); + let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let counts = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, CALLS * 12, flags)?.0; + self.merger = Some(Merger { + root, + pso, + bases, + counts, + calls: Default::default(), + }); + Ok(()) + } + + /// What the merges of the last run (of `loops`, which add up) found. + pub(super) fn merge_notes(&mut self, loops: u32) -> Result> { + let Some(m) = &self.merger else { + return Ok(Vec::new()); + }; + let (counts, calls) = (m.counts.clone(), m.calls.borrow().clone()); + let (back, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_READBACK, + CALLS * 12, + D3D12_RESOURCE_FLAG_NONE, + )?; + self.worker.run(|list| { + // SAFETY: an open list; live buffers. + unsafe { list.CopyBufferRegion(&back, 0, &counts, 0, CALLS * 12) }; + })?; + // SAFETY: the mapping; the copy into it has run. + let all = unsafe { std::slice::from_raw_parts(data.cast::(), CALLS as usize * 3) }; + let each = |k: usize| { + all.iter() + .skip(k) + .step_by(3) + .map(|&n| u64::from(n)) + .sum::() + / u64::from(loops.max(1)) + }; + let mut out = vec![format!( + "{} copies of what the CPU wrote to memory the card writes: {} words put; {} left as the card wrote them in this run, where other values were to go ({} of them the values from before the card wrote)", + calls.len(), + each(0), + each(1), + each(2) + )]; + let mut worst: Vec<(u32, usize)> = (0..calls.len()) + .map(|i| (all[i * 3 + 2], i)) + .filter(|w| w.0 > 0) + .collect(); + worst.sort_by(|a, b| b.0.cmp(&a.0)); + for (n, i) in worst.into_iter().take(8) { + let (id, at, len) = calls[i]; + out.push(format!( + " values from before the card wrote: {} words, {} +{at:#x} {len:#x} bytes", + n / loops.max(1), + self.called(id) + )); + } + Ok(out) + } +} diff --git a/crates/victory-gpu/src/replay/record.rs b/crates/victory-gpu/src/replay/record.rs index 67a77e3..232f7b7 100644 --- a/crates/victory-gpu/src/replay/record.rs +++ b/crates/victory-gpu/src/replay/record.rs @@ -609,7 +609,9 @@ impl Recorder { // would be a call into what is there then. if let Some(dead) = lock(&self.held).remove(&id) { std::mem::forget(dead); - self.problem("a resource died as the frame started: its contents may be missing"); + self.problem( + "a resource died as the frame started: its contents may be missing", + ); } self.ids.remove(ptr, id); write(&self.resources).remove(&id); diff --git a/crates/victory-gpu/src/replay/snap.rs b/crates/victory-gpu/src/replay/snap.rs index 07acb47..6c69042 100644 --- a/crates/victory-gpu/src/replay/snap.rs +++ b/crates/victory-gpu/src/replay/snap.rs @@ -406,9 +406,7 @@ impl Capture { } // SAFETY: the reference just taken. (The count does not tell // all that are dying: `Recorder::gone` takes those out.) - held.insert(res.id, unsafe { - ID3D12Resource::from_raw(object.as_raw()) - }); + held.insert(res.id, unsafe { ID3D12Resource::from_raw(object.as_raw()) }); all.push(res.clone()); } } diff --git a/docs/replay.md b/docs/replay.md index 7333348..352f976 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -64,6 +64,7 @@ with the presented one. | `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory | | `--one-submit` | one `ExecuteCommandLists`, with a full wait between the former ones | | `--only 3..7` | runs these lists; of the others only barriers | +| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) | | `--skip-shader ` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) | | `--no-restore` | leaves what a loop changed | | `--debug-layer` | D3D12's debug layer; its errors in the report | @@ -73,6 +74,29 @@ leaves out waits or work can draw another picture and, with wild data, lose the device: save work in other programs first. Do not run the title at the same time. +## Runs that differ + +Shaders that give out places with atomics (the title's culling) give other +ones in every run. The host layer brings such results to title memory and +sends 64 KiB pieces of it up again, so the recorded copies hold the recorded +run's results. Put over a replay's own, lists and what points into them are of +two runs, and things are drawn from other things' lists. So copies of what the +CPU wrote leave alone words the card has written in this run (`merge.rs`; the +report counts them). `--no-merge` runs the copies as recorded. + +| switch | does | +|---|---| +| `--wait-all` / `--wait-lists` | a full wait after every command / each list sent alone and waited for: if pictures still differ, waits are not what is missing | +| `--diverge [runs]` | runs each list this often from the very same memory, finds the first commands that make different memory of it, and says what differs (same values in another order: places given out); contents go to `diverge` in the capture | +| `--diverge-picture [runs]` | from each list on, runs the rest this often from the same memory: where the pictures start to agree, what lies before decides. `--lists 76 --commands 0..900 --step 8` goes into one list | +| `--diverge 10 --lists 76 --draws ` | each draw of the pipelines named, alone, this often: how many outcomes, and what it reads | +| `--watch ::` | which lists (with `--lists`: commands) change those words | +| `--slots :` | the heap slots its constants name | +| `--check-written` | that everything the frame changes is put back | +| `--dump ` | the DXIL of the pipelines named, in `shaders` | + +The `--diverge` family runs the recorded copies without the merge. + ## Limits - Not recorded, but reported when used: reserved (tiled) resources, bundles, From f1e89f21e7aadb388db0285a13552d2318bfb997 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:37:54 -0600 Subject: [PATCH 4/5] The hash passes over copies in the card's memory walk a piece with 64 threads Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/host.rs | 94 +++++++++++++++++++++--------- crates/victory-gpu/src/indirect.rs | 72 +++++++++++++++++++++-- 2 files changed, 135 insertions(+), 31 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4ae7669..ba0c44f 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1527,11 +1527,17 @@ unsafe impl Send for CardWork {} static CARD_WORK: Mutex> = Mutex::new(None); /// The compare of a declared range of a copy in the card's memory with -/// its bytes from before, one thread per 64 KiB piece (cut at multiples of +/// its bytes from before, one group per 64 KiB piece (cut at multiples of /// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` /// gets a dword per piece, 1 where a byte differs. The offsets are widened /// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a /// byte just outside the range costs a fetch that finds nothing. +/// +/// A piece's 64 threads walk it side by side, each every 64th 16 bytes, and +/// one of them hashes their 64 hashes: 64 steps after one another. One thread +/// walked the piece before, 4,096 steps; the passes took 24.8 ms of a frame's +/// 82 on the card (capture replay1, 405 of them), most of it waiting for +/// those steps. pub(crate) const CARD_COMPARE: &str = r#" #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" cbuffer Span : register(b0) { @@ -1547,22 +1553,31 @@ ByteAddressBuffer now : register(t0); // last sent up (or hashed whole, the first time). RWByteAddressBuffer hashes : register(u0); RWByteAddressBuffer differs : register(u1); +groupshared uint4 parts[64]; [RootSignature(RS)] [numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= pieces) return; +void main(uint3 id : SV_GroupID, uint thread : SV_GroupIndex) { uint piece = first + id.x; uint lo = piece * 65536u; lo = lo > skew ? lo - skew : 0u; uint hi = min((piece + 1u) * 65536u - skew, size); lo = lo & ~15u; hi = (hi + 15u) & ~15u; - uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu) + thread; [loop] - for (uint at = lo; at < hi; at += 16u) { + for (uint at = lo + thread * 16u; at < hi; at += 1024u) { h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); h = h.yzwx ^ (h >> 15); } + parts[thread] = h; + GroupMemoryBarrierWithGroupSync(); + if (thread != 0u) return; + h = parts[0]; + [loop] + for (uint i = 1u; i < 64u; ++i) { + h = (h ^ parts[i]) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } if (compare != 0u) { differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); // With the copy-back on its own thread: the next compare of the @@ -1574,16 +1589,36 @@ void main(uint3 id : SV_DispatchThreadID) { } "#; +/// One pass of [`CARD_COMPARE`] over a span's pieces, into `differs` from +/// dword `at` on (`mode` as the shader's `compare`): a group per piece, in +/// parts a dispatch can hold. +/// +/// # Safety +/// The list is open with the compare's root signature, pipeline and buffers +/// set, and the pieces lie in the buffer. +unsafe fn card_pass(list: &ID3D12GraphicsCommandList, span: &crate::shadow::CardSpan, size: u32, at: u32, mode: u32) { + const MOST: u32 = D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION; + let mut done = 0; + while done < span.pieces { + let n = (span.pieces - done).min(MOST); + let constants = [span.first + done, span.skew, size, n, (at + done) * 4, mode]; + // SAFETY: the caller's. + unsafe { + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(n, 1, 1); + } + done += n; + } +} + /// Whether the pieces hashed again after ranges were sent up to a copy in /// the card's memory are hashed in runs of pieces that touch, each piece /// once (`VICTORY_CARD_REHASH_RUNS=1`; off by default), and not in a pass /// per range sent up. /// /// These passes are ours, they run on the card before every submission's -/// lists, and no timing so far names them: each walks its 64 KiB pieces -/// 16 bytes at a time, 4,096 steps one after the other, so a pass takes -/// the time of one piece however few its pieces are. Run 102 sent up 514 -/// ranges a frame: 514 such passes. The same pieces are hashed either way; +/// lists: a pass takes the time of one piece however few its pieces are. +/// Run 102 sent up 514 ranges a frame: 514 such passes. The same pieces are hashed either way; /// a piece hashed when it need not be, or not hashed when it should, costs /// a fetch that finds nothing and loses no shader write. fn rehash_runs() -> bool { @@ -3263,8 +3298,12 @@ impl Host { (|| -> windows::core::Result<()> { allocator.Reset()?; list.Reset(allocator, None)?; + // Every copy first, then one barrier call, then every + // pass: a wait between each copy and its pass had the + // card do them one after the other. + let mut sent = Vec::new(); for (shadow, ranges) in &dirty { - let Some((staging, before, size)) = shadow.card_sides() else { + let Some((staging, before, _)) = shadow.card_sides() else { continue; }; for &(a, b) in ranges { @@ -3272,7 +3311,22 @@ impl Host { crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); } crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed); - let Some(before) = before else { + if before.is_some() && !ranges.is_empty() { + sent.push(transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )); + } + } + if !sent.is_empty() { + list.ResourceBarrier(&sent); + } + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + for (shadow, ranges) in &dirty { + let Some((_, Some(before), size)) = shadow.card_sides() else { continue; }; // No twin (it cost the card the copy's size again, @@ -3281,18 +3335,8 @@ impl Host { // hashed again, all of them the first time; the // compare after the lists hashes the declared // pieces and flags those whose hash is another. - if !ranges.is_empty() { - list.ResourceBarrier(&[transition( - &shadow.buffer, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )]); - } - list.SetComputeRootSignature(&work.root); - list.SetPipelineState(&work.pso); list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); let runs: Vec = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { vec![shadow.card_run(0, usize::MAX)] } else { @@ -3303,9 +3347,7 @@ impl Host { CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); for run in runs { - let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0]; - list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); - list.Dispatch(run.pieces.div_ceil(64), 1, 1); + card_pass(list, &run, size as u32, 0, 0); } } list.Close()?; @@ -3387,11 +3429,9 @@ impl Host { let Some((_, Some(before), size)) = r.shadow.card_sides() else { continue; }; - let constants = [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }]; - list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); - list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); + card_pass(list, &r.span, size as u32, r.at, if flown { 2 } else { 1 }); CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); } list.Close()?; diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index af7f010..95b33a4 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -525,13 +525,22 @@ void main() { impl WarpHarness { fn new() -> Option { - // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + Self::on(true) + } + + /// On the software adapter, or the first one (for measurements). + fn on(software: bool) -> Option { + // SAFETY: plain DXGI query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; - let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let adapter: IDXGIAdapter = if software { + factory.EnumWarpAdapter().ok()? + } else { + factory.EnumAdapters(0).ok()? + }; let desc = adapter.cast::().ok()?.GetDesc1().ok()?; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + if software != (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { return None; } let mut device: Option = None; @@ -760,7 +769,7 @@ void main() { warp.list.SetComputeRootShaderResourceView(1, now_gpu); warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); - warp.list.Dispatch(PIECES.div_ceil(64), 1, 1); + warp.list.Dispatch(PIECES, 1, 1); } warp.submit_and_wait(); // SAFETY: as above. @@ -790,6 +799,61 @@ void main() { assert_eq!(run(&mut warp, 2), [0, 0, 0]); } + /// What the passes over copies in the card's memory cost on the card + /// (ignored: a measurement): rounds of a few passes of some pieces and a + /// wait, as a frame has them. `VICTORY_BENCH_CS=` times another + /// source of the shader. + #[test] + #[ignore] + fn card_compare_costs() { + let Some(mut gpu) = WarpHarness::on(false) else { + return; + }; + let other = std::env::var("VICTORY_BENCH_CS").ok().map(|f| std::fs::read_to_string(f).unwrap()); + let source: &'static str = other.map_or(crate::host::CARD_COMPARE, |s| Box::leak(s.into_boxed_str())); + let walked_alone = source.contains("SV_DispatchThreadID"); + let compare = compile_cs(&gpu.device, source).expect("the compare must compile"); + let now = gpu.default_uav(256 << 20); + let hashes = gpu.default_uav(64 << 10); + let differs = gpu.default_uav(64 << 10); + for (rounds, passes, pieces) in [(80u32, 5u32, 1u32), (80, 5, 5), (80, 5, 64), (80, 5, 500), (1, 1, 4000)] { + let mut best = f64::MAX; + for _ in 0..6 { + // SAFETY: our open list, live buffers, the compare's own + // root signature; the pieces lie in the buffers. + unsafe { + gpu.list.SetComputeRootSignature(&compare.root); + gpu.list.SetPipelineState(&compare.pso); + gpu.list.SetComputeRootShaderResourceView(1, now.GetGPUVirtualAddress()); + gpu.list.SetComputeRootUnorderedAccessView(2, hashes.GetGPUVirtualAddress()); + gpu.list.SetComputeRootUnorderedAccessView(3, differs.GetGPUVirtualAddress()); + for _ in 0..rounds { + for pass in 0..passes { + let first = if pieces * passes < 4096 { pass * pieces } else { 0 }; + let constants = [first, 0u32, 256 << 20, pieces, 0, 1]; + gpu.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + gpu.list.Dispatch(if walked_alone { pieces.div_ceil(64) } else { pieces }, 1, 1); + } + gpu.list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + ..Default::default() + }]); + } + } + let t = std::time::Instant::now(); + gpu.submit_and_wait(); + best = best.min(t.elapsed().as_secs_f64() * 1e3); + } + let mb = f64::from(rounds * passes * pieces) / 16.0; + println!("{rounds} rounds of {passes} passes of {pieces} pieces: {best:.2} ms ({mb:.0} MB, {:.0} GB/s)", mb / best / 1.024); + } + } + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { From e4670d9af69bf7c97779281457a43566b70c80c7 Mon Sep 17 00:00:00 2001 From: local Date: Tue, 24 Nov 2026 21:39:04 -0600 Subject: [PATCH 5/5] Reads of title memory under flights done on the card (VICTORY_CARD_STEPS) The submitting thread stood 25-30 ms a frame for one 480-byte constant buffer and one 20 KiB buffer copy a frame whose source lies in the title's 174 MB heap, which a pass of nearly every flight is declared to write whole (a root view has no size). With VICTORY_CARD_STEPS=1 such a constant buffer, with =2 such a copy too, is made on the card by a list of ours in front of the submission's lists, behind the flights; anything the argument does not hold for waits as before. Off by default. Diagnostics: the five waits for flights that cost most, every second, by what waited, why it was not done on the card, the declared write and the shaders that declare it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/descriptor.rs | 14 + crates/victory-gpu/src/draw.rs | 9 +- crates/victory-gpu/src/host.rs | 234 ++++-- crates/victory-gpu/src/host/card_steps.rs | 868 ++++++++++++++++++++++ crates/victory-gpu/src/memory.rs | 2 + crates/victory-gpu/src/shadow.rs | 5 + 6 files changed, 1084 insertions(+), 48 deletions(-) create mode 100644 crates/victory-gpu/src/host/card_steps.rs diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 8485014..f50a96f 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -168,6 +168,20 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { } } +/// Makes dynamic slot `index` of the host heap behind the title heap at +/// `heap`, if that heap still exists, the constant buffer view of `size` +/// bytes at `gpu`. +#[cfg(windows)] +pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if heaps.iter().any(|&(_, _, h)| h == heap) + // SAFETY: registered heaps are live (removed when dropped). + && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() + { + host.constant_at(index, gpu, size); + } +} + #[cfg(windows)] impl Drop for Heap { fn drop(&mut self) { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7d290a3..6530abd 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1164,6 +1164,8 @@ impl State { let len = s.left(a).min(limit); s.refresh(list, a, len); if writes { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(a, len, self.pipeline); s.gpu_writes(list, a, len); } }; @@ -2213,7 +2215,8 @@ impl State { host.make_null(index); continue; }; - list.defer_fill(to, address as *const u8, size as usize); + let slot = (std::ptr::from_ref(heap) as usize, index); + list.defer_constants(to, address as *const u8, size as usize, slot); host.constant_at(index, gpu, size); } Some(view) => { @@ -2395,7 +2398,7 @@ impl State { }; let (from, to, stride) = (from as usize, to as usize, stride as usize); let n = rects as usize; - list.defer_host(move || { + list.defer_host_read(from, n * 3 * stride, move || { // The vertices are read in place, at submission: no change // of mapping under the read (see // `crate::watch::title_memory_reading`). @@ -2763,6 +2766,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) { // A shader that cannot store to buffers leaves the range as // the title has it: nothing to find afterwards. if STORES.get() || !write_skip() { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(address, len, 0); shadow.gpu_writes(list, address, len); } else { #[cfg(feature = "diagnostics")] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4ae7669..b2cbc74 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1642,16 +1642,19 @@ enum Step { /// A copy into title memory (destination, source, bytes): the title's /// buffer copies, which later refreshes must see. Copy(usize, usize, usize), - /// A copy of title memory into the list's own upload memory. - Fill(usize, usize, usize), + /// A copy of title memory into the list's own upload memory; if a + /// descriptor slot shows that memory and nothing else does (a constant + /// buffer of a table made for the draw), the title heap and the slot. + Fill(usize, usize, usize, Option<(usize, u32)>), /// Brings a range (address, bytes) of a buffer's host copy up to date: /// once per submission, whichever lists ask, until a `Copy` or `Run` /// intervenes. Refresh(std::sync::Arc, usize, usize), /// Work that may write title memory. Run(Box), - /// Work that writes host memory only. - Host(Box), + /// Work that writes host memory only, and the title memory it reads + /// (from, to; empty for none). + Host(Box, (usize, usize)), /// Shaders write a range (address, bytes) of a buffer's host copy. GpuWrite(std::sync::Arc, usize, usize), /// Brings a texture's staging buffer up to date: once per submission, @@ -2019,6 +2022,8 @@ struct Sent { number: u64, card: Option, back: Vec, + /// What was taken off it to be done on the card. + own: Option, /// Its bottom-of-pipe writes. writes: Vec<(usize, crate::queue::Written, usize)>, } @@ -2034,6 +2039,8 @@ struct Flight { order: Vec, card: Option, back: Vec, + /// The list of ours that ran ahead of them ([`card_steps`]). + own: Option, } /// One thing in the line of what waits for the card, in order. @@ -2067,6 +2074,8 @@ struct Line { /// With [`relay`]: the bottom-of-pipe writes of the flights being /// landed (taken out of `line`, not done yet), for [`late_met`]. in_hand: Vec<(usize, crate::queue::Written, usize)>, + /// With [`card_steps`]: what the flights being landed write. + landing: Vec, } // SAFETY: D3D12 objects (free-threaded) and host lists nothing records @@ -2082,6 +2091,7 @@ static LINE: Mutex = Mutex::new(Line { poke: false, landed: Vec::new(), in_hand: Vec::new(), + landing: Vec::new(), }); /// Told when a flight joins [`LINE`] or it is poked. static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); @@ -2152,14 +2162,14 @@ fn flying() -> bool { /// runs steps of ours that may read or write it anywhere; what the /// flights' shaders write is not there yet. fn late_blocked(runs: &[&HostList]) -> Option { - let written = { + let (written, copies) = { let line = line(); if line.written.is_empty() { return None; } - line.written.clone() + (line.written.clone(), card_steps::copies(&line)) }; - blocked_by(&written, runs, true) + blocked_by(&written, runs, true).or_else(|| card_steps::copied_read(&copies, runs).then_some(WHY_READ)) } /// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for @@ -2188,48 +2198,131 @@ fn fill_is_titles(src: usize, len: usize) -> bool { on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600)) } -/// Diagnostics: the reads that made a submission wait for flights: what -/// kind, where, how much, and the declared write it lies in; how often and -/// how long the wait was. +/// Diagnostics: the waits for flights, by what waited, why it was not done +/// on the card ([`card_steps`]), its bytes, and the declared write it lies +/// in (start, bytes). #[cfg(feature = "diagnostics")] -type Blame = std::collections::HashMap<(&'static str, usize, usize, usize, usize), (u64, u64)>; +type Blamed = (&'static str, &'static str, usize, usize, usize); +/// How often and how long, and the address the last one read. #[cfg(feature = "diagnostics")] -static BLAME: Mutex> = Mutex::new(None); +static BLAME: Mutex>> = Mutex::new(None); +/// What the wait that comes next is for, and why not on the card. #[cfg(feature = "diagnostics")] -static BLAMED: Mutex> = Mutex::new(None); +static BLAMED: Mutex<(Option<(Blamed, usize)>, &'static str)> = Mutex::new((None, "")); + +/// Diagnostics: shader writes declared over a megabyte or more: the range +/// (from, to) and what declares it ([`wide_write`]): how often, and its +/// shaders. +#[cfg(feature = "diagnostics")] +static WIDE_WRITES: Mutex>> = Mutex::new(None); + +/// Diagnostics: a draw or dispatch declares that it writes `len` bytes at +/// `address`, through a root view of `pipeline`, a view in a table (0) or a +/// raw address (1). +#[cfg(feature = "diagnostics")] +pub(crate) fn wide_write(address: u64, len: u64, pipeline: usize) { + if len < 1 << 20 { + return; + } + let mut all = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + let e = all + .get_or_insert_with(Default::default) + .entry((address as usize, (address + len) as usize, pipeline)) + .or_insert_with(|| { + let shaders = match pipeline { + 0 => "a view in a table".into(), + 1 => "a raw address".into(), + p => crate::pipeline::host_pipeline(p as crate::object::This).map_or_else(String::new, |p| { + p.stages.iter().map(|s| s.shader.hash.to_string()).collect::>().join("+") + }), + }; + (0, shaders) + }); + e.0 += 1; +} #[cfg(feature = "diagnostics")] fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) { let i = written.partition_point(|r| r.1 <= at); let (from, to) = written.get(i).copied().unwrap_or((0, 0)); - *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = Some((kind, at, len, from, to - from)); + let mut blamed = BLAMED.lock().unwrap_or_else(|e| e.into_inner()); + let why = blamed.1; + blamed.0 = Some(((kind, why, len, from, to - from), at)); } -/// The wait for what [`blame`] last named took `us`. +/// Why [`card_steps`] left the submission to the wait that comes next. #[cfg(feature = "diagnostics")] -fn blamed(us: u64) { - if let Some(key) = BLAMED.lock().unwrap_or_else(|e| e.into_inner()).take() { - let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner()); - let e = all.get_or_insert_with(Default::default).entry(key).or_insert((0, 0)); - e.0 += 1; - e.1 += us; - } +fn refused(why: &'static str) { + *BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = (None, why); } +/// The wait for what [`blame`] last named, or a wait of another reason than +/// title memory read, took `us`. +#[cfg(feature = "diagnostics")] +fn blamed(why: usize, us: u64) { + let (named, refused) = std::mem::replace(&mut *BLAMED.lock().unwrap_or_else(|e| e.into_inner()), (None, "")); + let (key, at) = match (why, named) { + (WHY_READ, Some(named)) => named, + (WHY_READ, None) => (("a host copy of what a copy done on the card wrote", refused, 0, 0, 0), 0), + _ => { + let kind = match why { + WHY_SYNC => "a synchronous submission, a present or the sweep", + WHY_VALUE => "a memory value", + WHY_STALE => "title memory changed under shader writes", + WHY_RUN => "a step of ours", + WHY_MOST => "lists in the air", + WHY_FENCE => "a blocking fence wait", + _ => "another reason", + }; + ((kind, "", 0, 0, 0), 0) + } + }; + let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner()); + let e = all.get_or_insert_with(Default::default).entry(key).or_default(); + *e = (e.0 + 1, e.1 + us, at); +} + +/// For the frame-rate line: the five that waited longest. #[cfg(feature = "diagnostics")] fn log_blame(frames: f64) { let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let wide = WIDE_WRITES.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); let mut all: Vec<_> = all.into_iter().collect(); - all.sort_unstable_by_key(|(_, (_, us))| std::cmp::Reverse(*us)); - for ((kind, at, len, from, size), (n, us)) in all.into_iter().take(8) { + all.sort_unstable_by_key(|(_, (_, us, _))| std::cmp::Reverse(*us)); + for ((kind, why, len, from, size), (n, us, at)) in all.into_iter().take(5) { + // The passes that declare it written, the ones that do so most. + let mut passes: std::collections::BTreeMap<&str, u64> = std::collections::BTreeMap::new(); + for ((a, b, _), (n, shaders)) in &wide { + if *a < at + len && at < *b { + *passes.entry(shaders).or_default() += n; + } + } + let mut passes: Vec<(&str, u64)> = passes.into_iter().collect(); + passes.sort_unstable_by_key(|p| std::cmp::Reverse(p.1)); + let passes: Vec = + passes.into_iter().take(5).map(|(shaders, n)| format!("{shaders} {:.1}x", n as f64 / frames)).collect(); tracing::info!( - "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} {at:#x}+{len:#x}, in shader writes declared over {from:#x}+{size:#x}", + "waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} +{len:#x} (last at {at:#x}), in shader writes declared \ + over {from:#x}+{size:#x} (declared per frame over a megabyte or more there, by shader: {}){}{why}", us as f64 / 1e3 / frames, - n as f64 / frames + n as f64 / frames, + passes.join(", "), + if why.is_empty() { "" } else { "; not done on the card: " }, ); } } +/// Whether flights that write `written` stop a read of `len` bytes at `src`. +fn read_blocked(written: &[(usize, usize)], src: usize, len: usize) -> bool { + touches(written, src, src + len) && !fill_is_titles(src, len) +} + +/// Whether they stop a title buffer copy, and if so whether by its source. +fn copy_blocked(written: &[(usize, usize)], dst: usize, src: usize, len: usize) -> Option { + let read = read_blocked(written, src, len); + (read || touches(written, dst, dst + len)).then_some(read) +} + /// [`late_blocked`] against `written`, the title memory flights' shaders /// may write (in order, joined); `count` whether the kind of read is /// counted for the frame line. @@ -2241,12 +2334,11 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op for step in &list.deferred().copies { match step { &Step::Copy(dst, src, len) => { - let read = touches(written, src, src + len) && !fill_is_titles(src, len); - if read || touches(written, dst, dst + len) { + if let Some(_read) = copy_blocked(written, dst, src, len) { if count { LATE_STATS[15].fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - if read { + if _read { blame("a buffer copy's source", written, src, len); } else { blame("a buffer copy's destination", written, dst, len); @@ -2255,8 +2347,8 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op return Some(WHY_READ); } } - &Step::Fill(_, src, len) => { - if touches(written, src, src + len) && !fill_is_titles(src, len) { + &Step::Fill(_, src, len, _) => { + if read_blocked(written, src, len) { if count { LATE_STATS[16].fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] @@ -2277,7 +2369,7 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op } } Step::Run(_) => return Some(WHY_RUN), - Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) => {} + Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {} } } } @@ -2517,7 +2609,7 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed); #[cfg(feature = "diagnostics")] - blamed(us); + blamed(why, us); } /// What the thread that lands flights fetches card copies' pieces with @@ -2582,6 +2674,9 @@ fn relay_worker() { _ => None, }) .collect(); + if card_steps::stage() > 0 { + line.landing = card_steps::writers(&items); + } break Ok(items); } }; @@ -2711,6 +2806,9 @@ fn late_line(frames: f64) { r[4] / 1000.0, ); } + card_steps::log(frames); + #[cfg(feature = "diagnostics")] + log_blame(frames); if late_exact() { let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); tracing::info!( @@ -2721,6 +2819,8 @@ fn late_line(frames: f64) { } } +mod card_steps; + #[cfg(test)] mod late_tests { use super::{continues, join_ranges, touches}; @@ -3691,6 +3791,9 @@ impl Host { if let Some(card) = flight.card { self.card_done(card); } + if let Some(own) = flight.own { + own.landed(); + } landed.push((flight.lists, flight.order)); } Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), @@ -3713,10 +3816,12 @@ impl Host { poke, landed: kept, in_hand, + landing, .. } = &mut *line; kept.extend(landed); in_hand.clear(); + landing.clear(); // What is still in the air, from the flights that are. written.clear(); *lists = 0; @@ -3909,6 +4014,7 @@ impl Host { order, card: sent.card, back: sent.back, + own: sent.own, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); *flying >= late_most() @@ -3953,6 +4059,7 @@ impl Host { order: Vec::new(), card: sent.card, back: sent.back, + own: sent.own, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } @@ -4133,17 +4240,32 @@ impl Host { // 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. + // Or the reads are done on the card, behind the flights. + let own = if late { self.card_steps(runs) } else { None }; if !late { self.settle(&mut submitted, WHY_SYNC); - } else if let Some(why) = late_blocked(runs) { + } else if own.is_none() + && let Some(why) = late_blocked(runs) + { if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. - relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + relay_wait(why, |line| { + blocked_by(&line.written, runs, false).is_none() && !card_steps::copied_read(&card_steps::copies(line), runs) + }); } else { self.settle(&mut submitted, why); } } + // That list runs first, and is one of the submission's from here on. + let with: Vec<&HostList>; + let runs = match &own { + Some(own) => { + with = std::iter::once(own.list()).chain(runs.iter().copied()).collect(); + &with[..] + } + None => runs, + }; 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 @@ -4214,7 +4336,7 @@ impl Host { settled += settling.elapsed(); } for list in runs { - list.run_deferred(&mut batch); + list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i))); firsts.push(lists.len()); if let Some(prelude) = list.prelude() { lists.push(Some(prelude)); @@ -4268,6 +4390,7 @@ impl Host { number: this_submission, card, back, + own, writes, }; working(was_working); @@ -5152,7 +5275,15 @@ impl HostList { pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { self.deferred() .copies - .push(Step::Fill(dst as usize, src as usize, len)); + .push(Step::Fill(dst as usize, src as usize, len, None)); + } + + /// As [`HostList::defer_fill`], for upload memory that only `slot` (a + /// title heap's address, and the slot) shows. + pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { + self.deferred() + .copies + .push(Step::Fill(dst as usize, src as usize, len, Some(slot))); } /// Brings `[address, address + len)` of a buffer's host copy up to date @@ -5272,7 +5403,7 @@ impl HostList { // list's last run (mesh dispatches: the largest group count // asked for, the groups asked in all; with the card's copy, as // the list's end copied them here): taken, then zeroed. - deferred.copies.push(Step::Host(Box::new(move || unsafe { + let notes = Box::new(move || unsafe { let words = at as *mut u32; let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); @@ -5280,7 +5411,8 @@ impl HostList { for k in 0..3 { words.add(k).write_volatile(0); } - }))); + }); + deferred.copies.push(Step::Host(notes, (0, 0))); drop(deferred); if let Some(card) = card { self.zero_card_budget(card); @@ -5456,7 +5588,13 @@ impl HostList { /// As [`HostList::defer`], for work that writes only host memory. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { - self.deferred().copies.push(Step::Host(Box::new(work))); + self.deferred().copies.push(Step::Host(Box::new(work), (0, 0))); + } + + /// As [`HostList::defer_host`], for work that reads `len` bytes of title + /// memory at `from`. + pub(crate) fn defer_host_read(&self, from: usize, len: usize, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Host(Box::new(work), (from, from + len))); } /// Brings a texture's staging buffer up to date when the list is @@ -5467,11 +5605,16 @@ impl HostList { /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most - /// lists of a submission, through many ranges). - fn run_deferred(&self, batch: &mut Batch) { + /// lists of a submission, through many ranges). Copies and fills that + /// `taken` names (by their place) are left out: they are done on the + /// card ([`card_steps`]). + fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; - for step in &self.deferred().copies { + for (i, step) in self.deferred().copies.iter().enumerate() { + if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) { + continue; + } let started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { @@ -5486,7 +5629,7 @@ impl HostList { crate::watch::wrote(dst, len); len } - &Step::Fill(dst, src, len) => { + &Step::Fill(dst, src, len, _) => { #[cfg(feature = "diagnostics")] { add(C::Copies, 1); @@ -5504,7 +5647,7 @@ impl HostList { batch.add(shadow, *address, *len); continue; } - Step::Run(work) | Step::Host(work) => { + Step::Run(work) | Step::Host(work, _) => { if matches!(step, Step::Run(_)) { batch.title_written(); } @@ -6254,7 +6397,6 @@ impl Meter { ); #[cfg(feature = "diagnostics")] { - log_blame(frames); let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames); tracing::info!( "what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps", diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs new file mode 100644 index 0000000..6c1f622 --- /dev/null +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -0,0 +1,868 @@ +//! Steps of a submission that read title memory flights in the air may +//! still write, done on the card in the flights' order instead of on the +//! CPU after a wait for them (`VICTORY_CARD_STEPS`, see [`stage`]). + +use std::sync::Arc; + +use super::*; +use crate::shadow::Shadow; + +/// The stage (`VICTORY_CARD_STEPS`; off by default): `1` constant buffers +/// of descriptor tables (`Step::Fill` with a slot of its own), `2` the +/// title's buffer copies (`Step::Copy`) too. Only with the relay's second +/// stage (`relay_exact`). +/// +/// Why: a root view has no size, so a pass that writes through one into the +/// title's 174 MB heap is declared to write all that is left of it, and +/// some pass of every flight does. The title's ring of constants lies in +/// the same heap. One constant buffer of 480 bytes and one copy of 20 KiB a +/// frame, at a new place of the ring each time, waited for nearly +/// everything in the air: 25-30 ms of a 105 ms frame, the submitting thread +/// standing (run record-1; with `VICTORY_FILL_TITLE=1` in run relaycopy-1 +/// the copy alone took over the wait). +/// +/// What is done: a list of ours goes to the card in front of the +/// submission's lists, in the same call. It copies the bytes read from the +/// host copy that the flights write into a buffer of ours, and from there +/// to the destination's host copy (a copy), or the fill's descriptor slot +/// is pointed at that buffer (a fill; the slot is the fill's alone, the +/// root signatures say such descriptors are volatile, and the list that +/// names it has not gone to the card). +/// +/// Why that is the value the CPU would have read after the wait. After the +/// wait title memory holds, for every byte read, what the title wrote, or +/// what the last of the flights that wrote it wrote (the landings put it +/// there, in order). The host copy on the card holds the same when our list +/// runs: every flight that may write one of these bytes writes this same +/// host copy ([`holder`]: a write through another host copy, a read-back +/// or a value written behind a flight there, and the old wait is taken), +/// they are all ahead of our list on the queue, and the title's own bytes +/// are brought up to date by a refresh step of our list, which is prepared +/// like any other list's (also under flights' declared writes: +/// `stale_under_flights`, which settles if it cannot). Nothing of this +/// submission writes these bytes earlier than our list: the steps are done +/// in front of all its lists in either case, and [`plan`] refuses when +/// another step of the submission writes what is read. Every draw that +/// reads a buffer view of the heap relies on the same refresh and the same +/// order; what is new is only that a constant buffer and a copy do too. +/// Where a page is not mapped the host copy may hold other bytes than the +/// CPU's copy would have left: refused. +/// +/// For a copy's destination our list declares a shader write, exactly the +/// bytes copied, after a refresh of them: from there on it is what any +/// shader's write is. The relay compares, and puts what changed into title +/// memory before the title is told anything of this flight (its +/// bottom-of-pipe writes and fences come after, in order); CPU steps of +/// later submissions that read it find it declared and wait, or are done +/// here. Refused: another step of the submission reads or writes the +/// destination on the CPU, or a refresh brings another host copy of it up +/// to date ([`plan`], [`elsewhere`]). While such a copy is in the air a +/// submission that refreshes another host copy of its destination, or +/// reads it in a step that is not checked otherwise, waits for it +/// ([`copied_read`]); with the copy done on the CPU it was there at once. +/// +/// What stage 2 does not see: code of ours that reads title memory away +/// from a submission's steps (the pass over textures picked by index, while +/// a list is recorded). With the CPU's copy such a read of the destination +/// found the bytes at once; now it finds them when the flight has landed. +/// The landing tells the guards (`crate::watch::landing`), so a texture +/// made from older bytes is made again. This is why stage 2 is its own. +pub(super) fn stage() -> u32 { + static STAGE: OnceLock = OnceLock::new(); + *STAGE.get_or_init(|| match std::env::var("VICTORY_CARD_STEPS").ok().as_deref() { + Some("1") => 1, + Some("2") => 2, + _ => 0, + }) +} + +/// The bytes of our buffer between reading and writing: what one submission +/// may do this way. +const BETWEEN: u64 = 1 << 20; + +/// Title memory something in the air writes: the host copy it goes through +/// (`None`: none, the bytes reach title memory when the flight lands), from, +/// to, and whether it is the destination of a copy done here. +pub(super) struct Writer { + shadow: Option>, + from: usize, + to: usize, + copy: bool, +} + +/// What `items` of the line write. +pub(super) fn writers(items: &[Late]) -> Vec { + let mut out = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + for (shadow, ranges) in &flight.back { + out.extend(ranges.iter().map(|&(from, to)| Writer { + shadow: Some(shadow.clone()), + from, + to, + copy: false, + })); + } + for &i in &flight.order { + for &(_, at, [row, rows, pitch]) in &flight.lists[i].host().deferred().backs { + out.push(Writer { + shadow: None, + from: at, + to: at + rows.saturating_sub(1) * pitch + row, + copy: false, + }); + } + } + out.extend(flight.own.iter().flat_map(Taken::copied)); + } + Late::Write(at, _, bytes) => out.push(Writer { + shadow: None, + from: *at, + to: *at + *bytes, + copy: false, + }), + Late::Signal(..) => {} + } + } + out +} + +/// The destinations of copies done here that have not landed. +pub(super) fn copies(line: &Line) -> Vec { + if stage() < 2 { + return Vec::new(); + } + let flying = line.line.iter().filter_map(|l| match l { + Late::Run(flight) => flight.own.as_ref(), + _ => None, + }); + let landing = line.landing.iter().filter(|w| w.copy).map(|w| Writer { + shadow: w.shadow.clone(), + ..*w + }); + flying.flat_map(Taken::copied).chain(landing).collect() +} + +/// Whether `runs` refresh another host copy of a destination in `copies`, +/// or read it in a step that flights are not waited for otherwise +/// (`Step::Host`): that reads title memory, where the copy is not yet. +pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { + if copies.is_empty() { + return false; + } + runs.iter().any(|list| { + list.deferred().copies.iter().any(|step| match step { + Step::Refresh(shadow, at, len) => copies + .iter() + .any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))), + Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to), + _ => false, + }) + }) +} + +/// What a step of a submission does to title memory, as the plan sees it. +/// `asked`: flights in the air stop it from being done on the CPU now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Does { + Copy { dst: usize, src: usize, len: usize, asked: bool }, + Fill { src: usize, len: usize, asked: bool, slot: Option<(usize, u32)> }, + /// Another read on the CPU (a texture, vertices expanded). + Read { from: usize, to: usize, asked: bool }, + /// A refresh of a host copy (named by its address). + Refresh { shadow: usize, from: usize, to: usize }, + /// Anything, anywhere. + Run, +} + +fn meet(a: (usize, usize), b: (usize, usize)) -> bool { + a.0 < b.1 && b.0 < a.1 +} + +/// The steps of `does` (by place) to be done on the card: all that are +/// asked for, or why not. Our list does them all in front of the +/// submission's, every read before every write, so that is right only if no +/// step, asked for or not, writes what one of them reads or writes, and no +/// CPU step reads what one of them writes. +fn plan(does: &[Does], stage: u32) -> Result, &'static str> { + let mut asked = Vec::new(); + for (i, d) in does.iter().enumerate() { + match *d { + Does::Run => return Err("a step of ours runs"), + Does::Read { asked: true, .. } => return Err("a texture reads it"), + Does::Fill { asked: true, slot: None, .. } => return Err("a fill without a descriptor slot of its own"), + Does::Copy { asked: true, .. } if stage < 2 => return Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"), + Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => asked.push(i), + _ => {} + } + } + for &i in &asked { + let (src, dst) = match does[i] { + Does::Copy { dst, src, len, .. } => ((src, src + len), Some((dst, dst + len))), + Does::Fill { src, len, .. } => ((src, src + len), None), + _ => continue, + }; + for (k, d) in does.iter().enumerate() { + let (read, written) = match *d { + Does::Copy { dst, src, len, .. } => (Some((src, src + len)), Some((dst, dst + len))), + Does::Fill { src, len, .. } => (Some((src, src + len)), None), + Does::Read { from, to, .. } => (Some((from, to)), None), + Does::Refresh { .. } | Does::Run => (None, None), + }; + if written.is_some_and(|w| meet(w, src)) { + return Err("a copy of the submission writes what it reads"); + } + let Some(dst) = dst else { + continue; + }; + if k != i && written.is_some_and(|w| meet(w, dst)) { + return Err("another copy of the submission writes what it writes"); + } + if read.is_some_and(|r| meet(r, dst)) { + return Err("a step of the submission reads what it writes"); + } + } + } + Ok(asked) +} + +/// Whether a refresh of `does` brings a host copy other than `shadow` up to +/// date in `[from, to)`. +fn elsewhere(does: &[Does], shadow: usize, from: usize, to: usize) -> bool { + does.iter().any(|d| match *d { + Does::Refresh { shadow: s, from: a, to: b } => s != shadow && meet((a, b), (from, to)), + _ => false, + }) +} + +/// The host copy that holds `[from, to)` on the card once what `writers` +/// write is there: the one they all write it through, or without any the +/// one shaders would be given. +fn holder(writers: &[Writer], from: usize, to: usize) -> Result, &'static str> { + let mut found: Option<&Arc> = None; + for w in writers.iter().filter(|w| meet((w.from, w.to), (from, to))) { + match (&w.shadow, found) { + (None, _) => return Err("a read-back or a value behind a flight is written there"), + (Some(s), Some(f)) if !Arc::ptr_eq(s, f) => return Err("flights write it through two host copies"), + (Some(s), _) => found = Some(s), + } + } + let shadow = match found { + Some(s) => s.clone(), + None => crate::shadow::find(from as u64, (to - from) as u64).ok_or("no host copy of it")?, + }; + let (start, len) = shadow.span(); + if shadow.in_place() || (from as u64) < start || to as u64 > start + len { + return Err("no host copy holds all of it"); + } + Ok(shadow) +} + +/// Whether every page of `[from, to)` can be read (through the kernel: +/// asking Windows walks the page tables, milliseconds in the title's heap). +fn mapped(from: usize, to: usize) -> bool { + let mut bytes = vec![0u8; to - from]; + read_into(from as *const u8, &mut bytes) +} + +/// A step done on the card. +struct Op { + from: (Arc, usize), + len: usize, + /// Its place in the buffer between. + at: u64, + to: To, +} + +enum To { + /// A host copy, and the title address. + Copy(Arc, usize), + /// A descriptor slot (title heap, slot). + Slot(usize, u32), +} + +/// Records what [`stage`] describes into `list` (open): `reads` are copied +/// into `between` (source, offset in it, offset in `between`, bytes), then +/// `writes` out of it (destination, offset in it, offset in `between`, +/// bytes). `between` is left readable as constants, the others in the +/// common state, as the submission's lists expect them. +fn record( + list: &ID3D12GraphicsCommandList, + between: &ID3D12Resource, + reads: &[(&ID3D12Resource, u64, u64, u64)], + writes: &[(&ID3D12Resource, u64, u64, u64)], +) { + let common = D3D12_RESOURCE_STATE_COMMON; + let (source, dest) = (D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + let mut sources: Vec<&ID3D12Resource> = Vec::new(); + let mut dests: Vec<&ID3D12Resource> = Vec::new(); + for (all, list) in [(reads, &mut sources), (writes, &mut dests)] { + for &(buffer, ..) in all { + if !list.iter().any(|b| b.as_raw() == buffer.as_raw()) { + list.push(buffer); + } + } + } + let both = |b: &ID3D12Resource| dests.iter().any(|d| d.as_raw() == b.as_raw()); + let mut barriers = vec![transition(between, dest, source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)]; + barriers.extend(sources.iter().map(|b| transition(b, source, if both(b) { dest } else { common }))); + let done: Vec = dests.iter().map(|b| transition(b, dest, common)).collect(); + // SAFETY: an open list; live buffers, and the callers' ranges lie in + // them. The buffers start in the common state (the list is the first of + // its call) and are promoted by their first use. + unsafe { + // What earlier lists' shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + for &(buffer, offset, at, len) in reads { + list.CopyBufferRegion(between, at, buffer, offset, len); + } + list.ResourceBarrier(&barriers); + for &(buffer, offset, at, len) in writes { + list.CopyBufferRegion(buffer, offset, between, at, len); + } + if !done.is_empty() { + list.ResourceBarrier(&done); + } + } +} + +/// The list in front of a submission's, and its buffer ([`BETWEEN`] bytes). +struct Own { + list: HostList, + between: ID3D12Resource, +} + +// SAFETY: D3D12 objects are free-threaded, and the list is touched by one +// thread at a time (the submitting one until it is sent, then the one that +// lands it, then nobody until it is taken out of `POOL`). +unsafe impl Send for Own {} + +/// Those that have landed: closed, their steps dropped. +static POOL: Mutex> = Mutex::new(Vec::new()); + +/// Since the last frame-rate line: fills and copies done on the card, their +/// bytes, and submissions that waited instead, refused by a check. +static DONE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// What [`Host::card_steps`] took off a submission: the list that does it, +/// for the submission to run first, and the steps the CPU leaves out (their +/// list by address, their place in it). +pub(super) struct Taken { + own: Own, + steps: std::collections::HashSet<(usize, usize)>, + copied: Vec<(Arc, usize, usize)>, +} + +impl Taken { + pub(super) fn list(&self) -> &HostList { + &self.own.list + } + + /// Whether step `i` of `list` is done by this. + pub(super) fn takes(&self, list: &HostList, i: usize) -> bool { + self.steps.contains(&(std::ptr::from_ref(list) as usize, i)) + } + + fn copied(&self) -> impl Iterator { + self.copied.iter().map(|(shadow, from, to)| Writer { + shadow: Some(shadow.clone()), + from: *from, + to: *to, + copy: true, + }) + } + + /// The submission has run and landed: the list and its buffer are free. + pub(super) fn landed(self) { + // The host copies its steps held go; its commands stay until the + // next use resets it. + drop(std::mem::take(&mut *self.own.list.deferred())); + POOL.lock().unwrap_or_else(|e| e.into_inner()).push(self.own); + } +} + +impl Host { + /// With flights in the air: if what keeps `runs` from being prepared + /// now is reads of title memory that can all be done on the card + /// ([`stage`]), the list that does them. `None` if nothing is in the + /// way or the old wait is due. Under the submission lock. + pub(super) fn card_steps(&self, runs: &[&HostList]) -> Option { + if stage() == 0 || !relay_exact() { + return None; + } + let (written, copies) = { + let line = line(); + if line.written.is_empty() { + return None; + } + (line.written.clone(), copies(&line)) + }; + blocked_by(&written, runs, false)?; + let taken = if copied_read(&copies, runs) { + Err("a copy done on the card is read through another host copy") + } else { + self.take_steps(&written, runs) + }; + match taken { + Ok(taken) => taken, + Err(why) => { + DONE[3].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + refused(why); + let _ = why; + None + } + } + } + + fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result, &'static str> { + let mut does = Vec::new(); + // Which step each is. One list's lock at a time: a submission may + // name a list twice. + let mut steps = Vec::new(); + for list in runs { + for (i, step) in list.deferred().copies.iter().enumerate() { + does.push(match step { + &Step::Copy(dst, src, len) => Does::Copy { + dst, + src, + len, + asked: copy_blocked(written, dst, src, len).is_some(), + }, + &Step::Fill(_, src, len, slot) => Does::Fill { + src, + len, + asked: read_blocked(written, src, len), + slot, + }, + Step::Texture(staging) => { + let (at, len) = staging.memory(); + Does::Read { + from: at, + to: at + len, + asked: touches(written, at, at + len), + } + } + &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false }, + Step::Refresh(shadow, at, len) => Does::Refresh { + shadow: Arc::as_ptr(shadow) as usize, + from: *at, + to: *at + *len, + }, + Step::Run(_) => Does::Run, + Step::GpuWrite(..) | Step::Host(..) => continue, + }); + steps.push((std::ptr::from_ref::(list) as usize, i)); + } + } + let chosen = plan(&does, stage())?; + if chosen.is_empty() { + return Ok(None); + } + let writers = { + let line = line(); + let mut all = writers(&line.line); + all.extend(line.landing.iter().map(|w| Writer { + shadow: w.shadow.clone(), + ..*w + })); + all + }; + let mut ops: Vec = Vec::with_capacity(chosen.len()); + let mut at = 0u64; + for &i in &chosen { + let (src, len) = match does[i] { + Does::Copy { src, len, .. } | Does::Fill { src, len, .. } => (src, len), + _ => continue, + }; + if len == 0 { + return Err("nothing to read"); + } + if at + len as u64 > BETWEEN { + return Err("too much at once"); + } + let from = holder(&writers, src, src + len)?; + if !mapped(src, src + len) { + return Err("not all of what it reads is mapped"); + } + let to = match does[i] { + Does::Copy { dst, .. } => { + let to = holder(&writers, dst, dst + len)?; + if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) { + return Err("another host copy of what it writes is read"); + } + if !mapped(dst, dst + len) { + return Err("not all of what it writes is mapped"); + } + To::Copy(to, dst) + } + Does::Fill { slot: Some((heap, index)), .. } => To::Slot(heap, index), + _ => continue, + }; + ops.push(Op { + from: (from, src), + len, + at, + to, + }); + at = (at + len as u64).next_multiple_of(256); + } + let Some(own) = self.own_list() else { + return Err("no host list or buffer for it"); + }; + let mut reads = Vec::new(); + let mut writes = Vec::new(); + let mut copied = Vec::new(); + // First every refresh, then the write: the bytes compared with are + // the title's. + for op in &ops { + op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64); + reads.push((&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, op.len as u64)); + if let To::Copy(to, dst) = &op.to { + to.refresh(&own.list, *dst as u64, op.len as u64); + writes.push((&to.buffer, to.offset(*dst as u64), op.at, op.len as u64)); + } + } + for op in &ops { + if let To::Copy(to, dst) = &op.to { + to.gpu_writes(&own.list, *dst as u64, op.len as u64); + copied.push((to.clone(), *dst, *dst + op.len)); + } + } + #[cfg(feature = "diagnostics")] + own.list.note_op(|| format!("{} copies of title memory done on the card, {at} bytes (VICTORY_CARD_STEPS)", ops.len())); + record(&own.list.list, &own.between, &reads, &writes); + own.list.close(); + // SAFETY: a live buffer. + let gpu = unsafe { own.between.GetGPUVirtualAddress() }; + for op in &ops { + DONE[2].fetch_add(op.len as u64, Ordering::Relaxed); + match &op.to { + To::Slot(heap, index) => { + DONE[0].fetch_add(1, Ordering::Relaxed); + // (A heap that is gone: nothing can read the slot.) + crate::descriptor::constant_slot(*heap, *index, gpu + op.at, op.len as u32); + } + To::Copy(..) => { + DONE[1].fetch_add(1, Ordering::Relaxed); + } + } + #[cfg(feature = "diagnostics")] + noted(op); + } + Ok(Some(Taken { + own, + steps: chosen.iter().map(|&i| steps[i]).collect(), + copied, + })) + } + + /// A list of ours open for recording, and its buffer. + fn own_list(&self) -> Option { + let pooled = POOL.lock().unwrap_or_else(|e| e.into_inner()).pop(); + if let Some(own) = pooled { + own.list.reset(); + return Some(own); + } + let between = self.uav_buffer(BETWEEN)?; + name(&between, || "copies of title memory on the card".into()); + let list = self.new_list().ok()?; + Some(Own { list, between }) + } +} + +/// Diagnostics: the copies and fills done on the card since the last +/// frame-rate line, by bytes, host copy read and host copy written (start +/// and length; zeros for a fill): how many, and the last title addresses. +#[cfg(feature = "diagnostics")] +type Noted = std::collections::HashMap<(usize, (u64, u64), (u64, u64)), (u64, usize, usize)>; +#[cfg(feature = "diagnostics")] +static NOTED: Mutex> = Mutex::new(None); + +#[cfg(feature = "diagnostics")] +fn noted(op: &Op) { + let (to, dst) = match &op.to { + To::Copy(to, dst) => (to.span(), *dst), + To::Slot(..) => ((0, 0), 0), + }; + let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()); + let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default(); + *e = (e.0 + 1, op.from.1, dst); +} + +/// For the frame-rate line. +pub(super) fn log(frames: f64) { + if stage() == 0 { + return; + } + let d: Vec = DONE.iter().map(|d| d.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "steps done on the card instead of waiting for flights, per frame (VICTORY_CARD_STEPS={}): {:.2} fills, {:.2} buffer \ + copies, {:.1} KB; {:.2} submissions refused and waited", + stage(), + d[0], + d[1], + d[2] / 1024.0, + d[3], + ); + #[cfg(feature = "diagnostics")] + { + let noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default(); + let mut noted: Vec<_> = noted.into_iter().collect(); + noted.sort_unstable_by_key(|(_, e)| std::cmp::Reverse(e.0)); + for ((len, from, to), (n, src, dst)) in noted.into_iter().take(5) { + let n = n as f64 / frames; + if to.1 == 0 { + tracing::info!("done on the card, per frame: {n:.2} fills of {len:#x} bytes from the host copy of {:#x}+{:#x} (last {src:#x})", from.0, from.1); + } else { + tracing::info!( + "done on the card, per frame: {n:.2} copies of {len:#x} bytes from the host copy of {:#x}+{:#x} (last {src:#x}) \ + to that of {:#x}+{:#x} (last {dst:#x})", + from.0, + from.1, + to.0, + to.1 + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn copy(dst: usize, src: usize, len: usize, asked: bool) -> Does { + Does::Copy { dst, src, len, asked } + } + + fn fill(src: usize, len: usize, asked: bool) -> Does { + Does::Fill { src, len, asked, slot: Some((1, 2)) } + } + + /// Only what is asked for is taken, all of it, and a step that stands + /// in none of their ways changes nothing. + #[test] + fn steps_apart_from_one_another_are_taken() { + let does = [ + copy(1000, 5000, 100, false), + fill(2000, 64, true), + Does::Refresh { shadow: 1, from: 0, to: 9000 }, + copy(3000, 6000, 100, true), + fill(1000, 64, false), + Does::Read { from: 3100, to: 4000, asked: false }, + ]; + assert_eq!(plan(&does, 2), Ok(vec![1, 3])); + // Two fills of the same bytes. + assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![0, 1])); + assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![])); + } + + /// Everything that could make the card's order another than the CPU's + /// refuses the lot, wherever in the submission it stands. + #[test] + fn steps_in_one_anothers_way_are_refused() { + let taken = copy(1000, 5000, 100, true); + let refused = |other: Does| { + assert!(plan(&[taken, other], 2).is_err(), "{other:?} after"); + assert!(plan(&[other, taken], 2).is_err(), "{other:?} before"); + }; + for asked in [false, true] { + // Writes what it reads. + refused(copy(5099, 9000, 1, asked)); + // Writes what it writes. + refused(copy(999, 9000, 2, asked)); + // Reads what it writes. + refused(copy(7000, 1050, 10, asked)); + refused(fill(1099, 64, asked)); + refused(Does::Read { from: 900, to: 1001, asked }); + } + refused(Does::Run); + // A texture that itself waits for flights; a fill with no slot. + refused(Does::Read { from: 1, to: 2, asked: true }); + refused(Does::Fill { src: 1, len: 1, asked: true, slot: None }); + // Into itself, and the same list twice. + assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err()); + assert!(plan(&[taken, taken], 2).is_err()); + // A fill of what a copy writes, and copies without stage 2. + assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 2).is_err()); + assert!(plan(&[taken], 1).is_err()); + // Ends that touch are apart. + assert!(plan(&[taken, copy(900, 9000, 100, false), copy(1100, 9000, 5, false), copy(4900, 9000, 100, false)], 2).is_ok()); + } + + #[test] + fn a_refresh_of_another_host_copy_is_seen() { + let does = [Does::Refresh { shadow: 7, from: 100, to: 200 }]; + assert!(!elsewhere(&does, 7, 100, 200)); + assert!(elsewhere(&does, 8, 199, 300)); + assert!(!elsewhere(&does, 8, 200, 300)); + } + + /// A value written behind a flight, or a read-back, is in no host copy + /// before it lands. + #[test] + fn what_no_host_copy_holds_is_refused() { + let writers = [Writer { shadow: None, from: 100, to: 108, copy: false }]; + assert!(holder(&writers, 104, 120).is_err()); + } + + /// Reads are all before writes, between two buffers and within one, and + /// the buffers are usable in the lists that follow in the same call. + #[test] + fn the_card_copies_what_is_recorded() { + let Some(host) = host() else { + return; // no host GPU + }; + let (a, a_data) = host.shared_buffer(1 << 16).unwrap(); + let (b, b_data) = host.shared_buffer(1 << 16).unwrap(); + // SAFETY: mappings of 64 KiB. + let (a_bytes, b_bytes) = + unsafe { (std::slice::from_raw_parts_mut(a_data, 1 << 16), std::slice::from_raw_parts_mut(b_data, 1 << 16)) }; + for (i, (x, y)) in a_bytes.iter_mut().zip(b_bytes.iter_mut()).enumerate() { + (*x, *y) = (i as u8 ^ (i >> 8) as u8, 0xee); + } + let was = a_bytes.to_vec(); + let own = host.own_list().unwrap(); + // Within `a` (there and back), from `a` to `b`, and a read alone. + record( + &own.list.list, + &own.between, + &[(&a, 33, 0, 100), (&a, 2000, 256, 100), (&a, 5001, 512, 7), (&a, 9, 1024, 4)], + &[(&a, 2000, 0, 100), (&a, 33, 256, 100), (&b, 77, 512, 7)], + ); + own.list.close(); + // A list behind it that uses the buffers in other ways. + let next = host.new_list().unwrap(); + let (out, out_data) = host.shared_buffer(1 << 16).unwrap(); + // SAFETY: an open list; live buffers. + unsafe { + next.list.CopyBufferRegion(&out, 0, &own.between, 1024, 4); + next.list.CopyBufferRegion(&b, 4096, &a, 33, 100); + } + next.close(); + host.execute(&[&own.list, &next]); + // With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics). + assert_eq!(host.log_messages(), None); + assert_eq!(a_bytes[2000..2100], was[33..133]); + assert_eq!(a_bytes[33..133], was[2000..2100]); + assert_eq!(b_bytes[77..84], was[5001..5008]); + assert_eq!(b_bytes[4096..4196], was[2000..2100]); + // SAFETY: a mapping of 64 KiB. + assert_eq!(unsafe { std::slice::from_raw_parts(out_data, 4) }, &was[9..13]); + assert!(b_bytes[..77].iter().all(|&x| x == 0xee)); + a_bytes[2000..2100].copy_from_slice(&was[2000..2100]); + a_bytes[33..133].copy_from_slice(&was[33..133]); + assert_eq!(a_bytes, &was[..]); + // As the landing does: its next use records anew. + POOL.lock().unwrap().push(own); + let own = host.own_list().unwrap(); + own.list.close(); + } + + /// The whole way, in a process of its own with the relay on: + /// `VICTORY_RELAY=2 VICTORY_CARD_STEPS=2 cargo test -p victory-gpu --lib + /// card_steps -- --ignored --test-threads=1`. A flight's list writes + /// part of what the next submission's copy reads, the title wrote the + /// rest; the copy is done on the card behind the flight, and a second + /// one reads what the first wrote. Title memory ends as on the CPU. + #[test] + #[ignore = "wants VICTORY_RELAY=2 VICTORY_CARD_STEPS=2 and a process of its own"] + fn a_copy_behind_a_flight_reads_what_the_flight_wrote() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const LEN: usize = 4 << 20; + const WRITE_WATCH: u32 = 0x20_0000; + let Some(host) = host() else { + return; + }; + assert!(relay_exact() && stage() == 2, "set VICTORY_RELAY=2 VICTORY_CARD_STEPS=2"); + // Two title buffers: in the first a copy within it, from it into the + // second, and back. + let (title, start) = { + // SAFETY: memory of our own, never freed. + let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE) }.cast::(); + assert!(!base.is_null()); + // SAFETY: `LEN` bytes just committed. + (unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize) + }; + const HALF: usize = LEN / 2; + crate::shadow::register(0x1111, start as u64, HALF as u64); + crate::shadow::register(0x2222, (start + HALF) as u64, HALF as u64); + let first = crate::shadow::find(start as u64, 64).unwrap(); + let (slow_from, slow_to) = (host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap()); + let before = DONE[1].load(Ordering::Relaxed); + let mut lists = Vec::new(); + for round in 0..8usize { + // The title writes; then a "shader" of a flight writes 300 bytes + // of what the copy reads, behind some work. + let seed = |i: usize| (i * 7 + round * 13 + i / 251) as u8; + for (i, b) in title[4000..6000].iter_mut().enumerate() { + *b = seed(i); + } + let (upload, data) = host.upload_buffer(4096).unwrap(); + for i in 0..300 { + // SAFETY: inside the mapping. + unsafe { data.add(i).write(0x80 | (round * 31 + i) as u8) }; + } + let a = host.new_list().unwrap(); + first.refresh(&a, start as u64, HALF as u64); + first.gpu_writes(&a, start as u64, HALF as u64); + // SAFETY: an open list; live buffers. + unsafe { + for _ in 0..24 { + a.list.CopyBufferRegion(&slow_to, 0, &slow_from, 0, 64 << 20); + } + a.list.CopyBufferRegion(&first.buffer, 4500, &upload, 0, 300); + a.list + .ResourceBarrier(&[transition(&first.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + } + a.close(); + host.execute_own(&a); + // With the flight in the air, beside what it writes. + for (i, b) in title[5300..5400].iter_mut().enumerate() { + *b = seed(1300 + i) ^ 0x5c; + } + // Into the second buffer, and within the first. + let b = host.new_list().unwrap(); + b.defer_copy((start + HALF + 100) as *mut u8, (start + 4001) as *const u8, 1500); + b.defer_copy((start + 900_001) as *mut u8, (start + 4400) as *const u8, 777); + b.close(); + host.execute_own(&b); + // What the first wrote, read by the next submission. + let c = host.new_list().unwrap(); + c.defer_copy((start + 1_200_000) as *mut u8, (start + HALF + 100) as *const u8, 1500); + c.close(); + let number = host.execute_own(&c); + settle_now(WHY_SYNC); + assert!(FINISHED.load(Ordering::Acquire) >= number); + let wanted: Vec = (0..2000) + .map(|i| match i { + 500..800 => 0x80 | (round * 31 + i - 500) as u8, + 1300..1400 => seed(i) ^ 0x5c, + _ => seed(i), + }) + .collect(); + assert!(title[4000..6000] == wanted[..], "what the flight wrote, round {round}"); + assert!(title[HALF + 100..HALF + 1600] == wanted[1..1501], "the copy to the other buffer, round {round}"); + assert!(title[900_001..900_778] == wanted[400..1177], "the copy within the buffer, round {round}"); + assert!(title[1_200_000..1_201_500] == wanted[1..1501], "the copy of the copy, round {round}"); + assert!(title[HALF..HALF + 100].iter().all(|&x| x == 0)); + assert!(title[HALF + 1600..].iter().all(|&x| x == 0)); + a.keep(&upload); + lists.extend([a, b, c]); + } + assert_eq!(host.log_messages(), None); + let done = DONE[1].load(Ordering::Relaxed) - before; + eprintln!("{done} of 24 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed)); + assert!(done >= 12, "only {done} copies were done on the card"); + } +} diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index c256367..67ebe7a 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -304,6 +304,8 @@ pub(crate) fn ready( shadow.refresh(list, start, len); } if writes && (first_write || n >= numbered) { + #[cfg(feature = "diagnostics")] + crate::host::wide_write(start, len, 1); shadow.gpu_writes(list, start, len); } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 68817e0..2d2c6c5 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1831,6 +1831,11 @@ impl Shadow { self.id } + /// Whether it is no copy but title memory in place (`crate::inplace`). + pub(crate) fn in_place(&self) -> bool { + self.place.is_some() + } + /// Offset of a title address from the buffer's start. pub(crate) fn offset(&self, address: u64) -> u64 { address - self.start + self.place.as_ref().map_or(0, |place| place.1)