diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index cad167a..147106a 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -53,15 +53,34 @@ pub(crate) struct Replay { /// Leave out the argument clamps: what they bound is kept from a first run. #[arg(long)] skip_clamps: bool, + /// The argument clamps in batches, as VICTORY_INDIRECT_BATCH does (2: + /// a wait before every indirect dispatch). + #[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)] + batch_clamps: u32, /// Leave out the hash and compare passes over card buffers. #[arg(long)] skip_hash_passes: bool, /// Where buffers lie. #[arg(long, value_enum, default_value_t = Buffers::AsRecorded)] buffers: Buffers, + /// With --buffers, only the buffers all of these match: `name=`, + /// `min=`, `max=`, `seen=`, + /// `id=..`, or `!` and one of those (may be given several times). + #[arg(long)] + only_buffers: Vec, /// 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, + /// 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 +89,48 @@ 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, + /// Only write the frame's buffers and the commands of these lists (`3..7`). + #[arg(long)] + listing: Option, /// Use the D3D12 debug layer (slow). #[arg(long)] debug_layer: bool, @@ -84,6 +145,16 @@ 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(()); + } + if let Some(text) = &r.listing { + let lists = range(text).with_context(|| format!("--listing {text}"))?; + return play::listing(&r.folder, lists, &mut |line| println!("{line}")); + } let only = match &r.only { Some(text) => Some( range(text) @@ -102,16 +173,84 @@ pub(crate) fn run(r: Replay) -> Result<()> { Buffers::Vram => play::Buffers::Card, Buffers::Sysmem => play::Buffers::Pc, }, + only_buffers: r.only_buffers, no_barriers: r.no_barriers, merge_barriers: r.merge_barriers, skip_clamps: r.skip_clamps, + batch_clamps: r.batch_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, 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/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index c817360..f334d20 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -598,6 +598,12 @@ fn check( if let Some(keep) = &checks.keep { lock(keep).push((label(), shader.clone())); } + // With `--list`: a hash of the module and of what the host binds for it, + // to show which shaders a change to the translator touches. + if t.list { + let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex(); + t.lines.push(format!("{} emitted {}", label(), &hash[..16])); + } // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. if t.list && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 2c069e4..71eb9d0 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -692,6 +692,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.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/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 2b065a2..213a11a 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 @@ -1047,6 +1161,13 @@ impl HostHeap { buffers.iter().copied().collect() } + /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every + /// slot is in the same part each time. + pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec { + let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + buffers.iter().copied().filter(|slot| slot % parts == part).collect() + } + /// The title slots whose buffer view was written, or went, since the /// last call. pub(crate) fn buffer_changes(&self) -> Vec { @@ -1103,7 +1224,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 +1534,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. @@ -2471,11 +2611,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 7d290a3..52bf2e4 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -186,6 +186,67 @@ fn windows() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) } +/// Whether indirect executions of one record are clamped in batches +/// (`crate::indirect::batch`; `VICTORY_INDIRECT_BATCH=0`: each on its own, +/// or in windows ([`windows`])). +/// +/// A frame of gameplay has 4,809 indirect executions (a capture: 3,523 mesh +/// draws, 948 dispatches, 338 draws), and with the windows still 2,355 +/// clamps: each a dispatch between two full waits, with the scratch buffer +/// moved twice. The replayed frame's 84.6 ms are 75.3 ms with the clamps in +/// 133 passes, and 77.7 ms in the 980 of this. +/// +/// A batch is opened by the first execution after a point where arguments +/// may have changed, and all executions up to the next such point read +/// theirs from it, each exactly the record it asks for (windows guess which +/// are next, and clamp what they do not know). Arguments in buffers change +/// by dispatches and by draws whose shaders store to buffers; those end the +/// batch, so the record an execution reads is clamped after all that was +/// recorded before it, and the pass waits for all of it, exactly as the +/// clamp of its own did. Between two executions of a batch is no wait of +/// ours: there is nothing between them to wait for but draws that store to +/// no buffer. +/// +/// `VICTORY_INDIRECT_BATCH=2`: a dispatch does not end the batch before the +/// title waits for it (a barrier, or a pipeline sync) or draws: what a +/// dispatch writes is not there for a later command without a wait, and +/// dispatches the title runs side by side (its tile classes, up to 92 at a +/// time) are not held up by waits of ours. Off: whether the title has ways +/// to wait that do not pass through its lists' methods is not known. +fn batches() -> u8 { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("VICTORY_INDIRECT_BATCH").as_deref() { + Ok("0") => 0, + Ok("2") => 2, + _ => 1, + }) +} + +/// The records clamped by the pass opened last ([`batches`]). +struct Batch { + table: crate::indirect::batch::Table, + scratch: ID3D12Resource, + /// Dispatches since, which may have written arguments + /// (`VICTORY_INDIRECT_BATCH=2`). + wrote: bool, +} + +/// The host copies arguments were read from last: what a batch opens with, +/// as the executions after the first may read theirs from another one. +static ARGUMENT_COPIES: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + +/// [`ARGUMENT_COPIES`] that live, and `first` put in front of them. +fn argument_copies(first: &std::sync::Arc) -> Vec<(u64, ID3D12Resource)> { + let mut copies = ARGUMENT_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let live: Vec<_> = copies.iter().filter_map(std::sync::Weak::upgrade).filter(|s| s.id() != first.id()).collect(); + *copies = std::iter::once(first) + .chain(&live) + .take(crate::indirect::batch::SOURCES) + .map(std::sync::Arc::downgrade) + .collect(); + live.iter().map(|s| (s.id(), s.buffer.clone())).collect() +} + /// What one title list has set, and what its host list was last given. #[derive(Default)] pub(crate) struct State { @@ -219,6 +280,9 @@ pub(crate) struct State { /// The indirect records clamped last, if later draws may still read /// them ([`windows`]). window: Option, + /// The records clamped in a batch, if later executions may still read + /// them ([`batches`]). + batch: Option, /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -365,6 +429,126 @@ pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); /// index ([`State::heap_buffers`]), and the microseconds they took. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Of the passes, nanoseconds since the last frame line: looking at slots, +/// the spans and refreshes of their copies, the texture side. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_SPLIT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// Passes after which every buffer slot of the heap was looked at again. +const HEAP_ROUND: u64 = 16; + +/// Whether the slots looked at again for no write are a part of them at +/// every pass, each slot at every sixteenth (`VICTORY_HEAP_SPREAD=0`: all of +/// them at every sixteenth pass, as before). +/// +/// All at once was some 115 ms on a thread that records the frame, every +/// sixteenth frame (72,000 slots; run record-1: 11 ms a pass in the lines +/// without such a pass, 22 in those of ten frames with one). A slot is +/// looked at as often as before. +fn heap_spread() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SPREAD").is_none_or(|v| v != "0")) +} + +/// The host copy and range the buffer view of each of a heap's slots reads +/// ([`State::heap_buffers`]), by slot. +#[derive(Default)] +struct HeapRanges(Vec>); + +impl HeapRanges { + fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) { + let slot = slot as usize; + if range.is_none() && slot >= self.0.len() { + return; + } + if slot >= self.0.len() { + self.0.resize_with(slot + 1, || None); + } + self.0[slot] = range; + } + + /// Forgets the slots of one of `parts` parts + /// (`HostHeap::buffer_slots_of`). + fn forget_part(&mut self, part: u32, parts: u32) { + self.0.iter_mut().skip(part as usize).step_by(parts as usize).for_each(|r| *r = None); + } + + fn ranges(&self) -> impl Iterator { + self.0.iter().flatten() + } +} + +#[cfg(test)] +mod heap_range_tests { + use super::{HEAP_ROUND, HeapRanges}; + + /// Round by round every slot is looked at again once, whatever was + /// written between, and what a slot holds is what was found last. + #[test] + fn every_slot_is_looked_at_again_in_a_round() { + const SLOTS: u32 = 1000; + let mut ranges = HeapRanges(Vec::new()); + ranges.set(7, None); + assert_eq!(ranges.ranges().count(), 0); + for slot in (0..SLOTS).step_by(3) { + ranges.set(slot, Some(((), 0, 1))); + } + let parts = HEAP_ROUND as u32; + for pass in 1..=HEAP_ROUND { + let part = (pass % HEAP_ROUND) as u32; + ranges.forget_part(part, parts); + for slot in (0..SLOTS).step_by(3).filter(|slot| slot % parts == part) { + assert!(ranges.0[slot as usize].is_none(), "slot {slot} not forgotten"); + ranges.set(slot, Some(((), pass, pass))); + } + assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize); + } + assert!(ranges.ranges().all(|r| r.1 != 0), "a slot not looked at in a round"); + ranges.set(3, None); + assert_eq!(ranges.ranges().count(), SLOTS.div_ceil(3) as usize - 1); + } + + /// The spans of 4,400 copies from the ranges of 72,000 slots, as a pass + /// makes them, by slot and from the table they were in. Run with + /// `--ignored --nocapture`. + #[test] + #[ignore] + fn spans_of_a_pass() { + use std::collections::HashMap; + use std::sync::Arc; + let copies: Vec> = (0..4400).map(Arc::new).collect(); + let (mut table, mut slots) = (HashMap::new(), HeapRanges(Vec::new())); + for slot in 0..72_000u32 { + let copy = &copies[slot as usize * 7919 % 4400]; + table.insert(slot, (copy.clone(), u64::from(slot), u64::from(slot) + 64)); + slots.set(slot, Some((copy.clone(), u64::from(slot), u64::from(slot) + 64))); + } + fn join(ranges: &mut dyn Iterator, u64, u64)>) -> usize { + let mut spans: HashMap, u64, u64), S> = HashMap::default(); + for (copy, from, to) in ranges { + let span = spans.entry(Arc::as_ptr(copy) as usize).or_insert_with(|| (copy.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + spans.len() + } + let best = |f: &mut dyn FnMut() -> usize| { + (0..30) + .map(|_| { + let t = std::time::Instant::now(); + assert_eq!(f(), 4400); + t.elapsed().as_secs_f64() * 1e3 + }) + .fold(f64::MAX, f64::min) + }; + println!( + "{:.2} ms from the table, {:.2} ms by slot", + best(&mut || join::(&mut table.values())), + best(&mut || join::>(&mut slots.ranges())), + ); + } +} + /// Textures brought up to date for shaders that pick them by index /// ([`State::heap_textures`]), the bytes of their memory, and the slots /// still waiting. @@ -383,6 +567,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 { @@ -915,6 +1111,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 { @@ -1164,6 +1363,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); } }; @@ -1368,18 +1569,25 @@ impl State { // at best); all of them every 16 passes, because a view of a // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. - type Ranges = std::collections::HashMap, u64, u64)>; + type Ranges = HeapRanges>; static RANGES: std::sync::Mutex>> = std::sync::Mutex::new(None); let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); let (passes, ranges) = kept .get_or_insert_with(Default::default) .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, Ranges::new())); + .or_insert_with(|| (0, HeapRanges(Vec::new()))); let changed = host.buffer_changes(); - let slots = if *passes % 16 == 0 { - ranges.clear(); + let slots = if *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()) { + ranges.0.clear(); host.buffer_slots() + } else if heap_spread() { + // The written ones, and this pass's part of the others. + let (part, parts) = ((*passes % HEAP_ROUND) as u32, HEAP_ROUND as u32); + ranges.forget_part(part, parts); + let mut slots = host.buffer_slots_of(part, parts); + slots.extend(changed); + slots } else { changed }; @@ -1389,7 +1597,7 @@ impl State { static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); for (n, &index) in slots.iter().enumerate() { - ranges.remove(&index); + ranges.set(index, None); let Some(handle) = heap.handle(index) else { continue; }; @@ -1420,13 +1628,15 @@ impl State { if host.shows(index, &shadow.buffer) == Some(false) { HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); } - ranges.insert(index, (shadow, address, address + len)); + ranges.set(index, Some((shadow, address, address + len))); } - let views = ranges.len() as u32; + #[cfg(feature = "diagnostics")] + let looked = std::time::Instant::now(); // Per host copy, the span its picked views cover. - let mut spans: std::collections::HashMap, u64, u64)> = - std::collections::HashMap::new(); - for (shadow, from, to) in ranges.values() { + let mut spans: crate::host::ByCopy<(std::sync::Arc, u64, u64)> = Default::default(); + let mut views = 0u32; + for (shadow, from, to) in ranges.ranges() { + views += 1; let key = std::sync::Arc::as_ptr(shadow) as usize; let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); span.1 = span.1.min(*from); @@ -1466,7 +1676,13 @@ impl State { } shadow.refresh(list, *from, to - from); } + #[cfg(feature = "diagnostics")] + let refreshed = std::time::Instant::now(); self.heap_textures(list, heap, host); + #[cfg(feature = "diagnostics")] + for (sum, time) in HEAP_SPLIT.iter().zip([looked - started, refreshed - looked, refreshed.elapsed()]) { + sum.fetch_add(time.as_nanos() as u64, Ordering::Relaxed); + } HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); static LOGGED: AtomicU64 = AtomicU64::new(0); @@ -1552,6 +1768,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 @@ -1615,6 +1902,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 @@ -1744,12 +2035,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); @@ -1916,6 +2230,7 @@ impl State { list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); // SAFETY: an open list with everything set. unsafe { list.list.Dispatch(x, y, z) }; + self.buffers_written(); DISPATCHED.fetch_add(1, Ordering::Relaxed); } @@ -1982,9 +2297,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) { @@ -2015,6 +2501,7 @@ impl State { self.mesh_scissor(list, true); // SAFETY: an open list with everything set. unsafe { l6.DispatchMesh(x, 1, 1) }; + self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); self.mesh_scissor(list, false); DRAWN.fetch_add(1, Ordering::Relaxed); true @@ -2028,6 +2515,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 @@ -2213,7 +2768,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) => { @@ -2347,6 +2903,7 @@ impl State { list.list .DrawInstanced(count, instances, from, first_instance) }; + self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); DRAWN.fetch_add(1, Ordering::Relaxed); } if !ran { @@ -2395,7 +2952,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`). @@ -2448,6 +3005,7 @@ impl State { list.list .DrawIndexedInstanced(indices, instances, first, base, first_instance) }; + self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); DRAWN.fetch_add(1, Ordering::Relaxed); } if !ran { @@ -2459,6 +3017,65 @@ impl State { } impl State { + /// Shaders that can write buffers were recorded: arguments may be others + /// from here on. + fn buffers_written(&mut self) { + match &mut self.batch { + Some(batch) if batches() == 2 => batch.wrote = true, + batch => *batch = None, + } + } + + /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`] + /// if its shaders can store to buffers). + fn drew(&mut self, p: Option<&HostPipeline>) { + if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) { + self.batch = None; + } + } + + /// The title waits for earlier work (a barrier or a pipeline sync). + pub(crate) fn synced(&mut self) { + if self.batch.as_ref().is_some_and(|b| b.wrote) { + self.batch = None; + } + } + + /// Where the clamped record of `kind` at `arguments` of the copy `args` + /// is, from the open batch or a new one ([`batches`]). `None` if it + /// cannot be clamped in one. + fn batched( + &mut self, + list: &HostList, + args: &std::sync::Arc, + arguments: u64, + kind: u32, + ) -> Option<(ID3D12Resource, u64)> { + const BATCH_USE: usize = usize::MAX - 0x78; + const DISPATCH: u32 = 2; + // Another host list, or this one after its reset ([`windows`]). + if list.first_use(BATCH_USE) { + self.batch = None; + } + // A draw after dispatches waits for them. + if kind != DISPATCH { + self.synced(); + } + let (id, offset) = (args.id(), args.offset(arguments)); + if let Some(b) = &mut self.batch + && let Some(at) = b.table.place(id, offset, kind) + { + return Some((b.scratch.clone(), at)); + } + self.batch = None; + let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?; + self.host_pipeline = 0; + self.host_roots[1] = 0; + let at = table.place(id, offset, kind)?; + self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false }); + Some((scratch, at)) + } + /// Indirect execution of a one-argument signature of `kind` (PC /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with /// records `stride` bytes apart at title address `arguments`, and the @@ -2550,6 +3167,16 @@ impl State { why("mesh draws are switched off (VICTORY_MESH_TEST=skip)"); return false; } + // One record without a count: clamped in a batch (`batches`). + let batch = if batches() > 0 && max == 1 && count.is_none() { + args.refresh(list, arguments, len); + self.batched(list, &args, arguments, kind) + } else { + None + }; + if batch.is_some() { + self.window = None; + } // A window of records clamped in one pass (`windows`): for single // records without a count buffer, drawn by shaders that store to no // buffer. Anything else ends the window: it uses the scratch buffer @@ -2573,7 +3200,7 @@ impl State { .filter(|w| same(w) && offset >= w.base) .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) .map(|w| (w.scratch.clone(), offset - w.base)); - let (bounded, at) = match hit { + let (bounded, at) = match batch.or(hit) { Some(hit) => hit, None => { // A record a short step after the last window's last one @@ -2663,6 +3290,11 @@ impl State { if kind == MESH { self.mesh_scissor(list, false); } + if kind == DISPATCH { + self.buffers_written(); + } else { + self.drew(Some(p)); + } // The scratch buffer stays readable as arguments: the next draw of // the window reads it with no barrier, and the next clamp moves it // back (`crate::indirect`). @@ -2763,6 +3395,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")] @@ -2823,6 +3457,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 4ae7669..eeeae77 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -767,6 +767,10 @@ mod tests { } } +/// The batches of clamped records in one scratch buffer +/// ([`HostList::batch_place`]). +const BATCHES: u32 = 8; + /// A host command list and its allocator, always used together. pub(crate) struct HostList { allocator: ID3D12CommandAllocator, @@ -802,6 +806,9 @@ pub(crate) struct HostList { /// Device-local scratch buffer for clamped indirect arguments (`indirect`), /// grown to the largest indirect execution recorded on the list. indirect_args: Mutex>, + /// Scratch buffers of the batched clamps (`crate::indirect::batch`), and + /// how many batches of this recording have a place in them. + batch_args: Mutex<(Vec, u32)>, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -1527,11 +1534,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 +1560,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 +1596,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 { @@ -1603,7 +1645,8 @@ static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atom /// settles: about 630 pieces and 40 MB a frame (run 104), each compared /// with the copy's CPU side byte by byte and put into title memory through /// the kernel. A piece is its own bytes of its copy and of title memory, -/// so eight threads take an eighth of them each. +/// so eight threads take an eighth of them each. (Not with [`relay`], whose +/// landings do not come here: `crate::land` has threads of its own.) fn wide_merge() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_WIDE_MERGE").is_some_and(|v| v == "1")) @@ -1642,16 +1685,18 @@ 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, and how + /// the card could bring the bytes instead. + Fill(usize, usize, usize, Option), /// 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, @@ -1932,13 +1977,16 @@ fn landable(line: &[Option], completed: u64) -> usize { /// For one plan of copies in the card's memory, with [`relay`]: `flags` /// holds, for every piece of every range of the plan, the copy, the /// piece's number in the copy and whether the compare flagged it there (or -/// did not run). The pieces to fetch, under whichever range: all of them -/// flagged under any. Two ranges of a plan may hold parts of the same +/// did not run). The pieces to fetch, under whichever range, in order: all +/// of them flagged under any. Two ranges of a plan may hold parts of the same /// 64 KiB piece; the compare hashes the whole piece for each and stores /// the hash, so the second of them may find it stored already and not /// flag it. -fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> { - flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() +fn flagged_pieces(flags: &[(usize, u32, bool)]) -> Vec<(usize, u32)> { + let mut pieces: Vec<(usize, u32)> = flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect(); + pieces.sort_unstable(); + pieces.dedup(); + pieces } #[cfg(test)] @@ -2019,6 +2067,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 +2084,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 +2119,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 +2136,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 +2207,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 +2243,145 @@ 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 that comes next is for these ranges ([`stale_under_flights`]). +#[cfg(feature = "diagnostics")] +fn blame_stale(stale: &[(std::sync::Arc, usize, usize)]) { + if let Some((shadow, from, _)) = stale.first() { + let (start, len) = shadow.span(); + let key = ("title memory changed under shader writes", crate::shadow::stale_why(), 0, start as usize, len as usize); + BLAMED.lock().unwrap_or_else(|e| e.into_inner()).0 = Some((key, *from)); } } +/// 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 | WHY_STALE, 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(", "), + match (why.is_empty(), kind) { + (true, _) => "", + (_, "title memory changed under shader writes") => "; not put in under them: ", + _ => "; 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 +2393,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 +2406,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 +2428,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(..) => {} } } } @@ -2289,7 +2440,7 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op /// may write and that the title wrote since it was last copied. The /// refresh leaves ranges shaders are writing alone (`Shadow::update`), so /// the title's bytes there would reach the card a submission late. -fn stale_under_flights(runs: &[&HostList]) -> bool { +fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc, usize, usize)> { use std::sync::Arc; // Per copy, the span of what is refreshed (a flush brings that much // up to date at most). @@ -2310,11 +2461,15 @@ fn stale_under_flights(runs: &[&HostList]) -> bool { // The title's bytes are put in beside the flights' writes; a // settle is still due where that could not be done. At most this // many changed runs go up to copies in the card's memory, each a - // copy of its own there. - let mut runs_left = 512; - return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + // copy of its own there. With [`card_steps`] the pages of the + // title's ring of constants come here too, which were waited for + // before: hundreds of short runs each, at about 1.5 us a run. + let mut runs_left = if card_steps::stage() > 0 { 4096 } else { 512 }; + spans.retain(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + return spans; } - spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) + spans.retain(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)); + spans } /// A fence signal on a queue ([`late`]): goes behind the flights in the @@ -2517,7 +2672,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 @@ -2533,6 +2688,8 @@ struct RelayFetch { sent: u64, /// Buffer, mapping, bytes. buffer: Option<(ID3D12Resource, usize, u64)>, + /// What earlier fetches brought of flights not landed yet. + had: crate::land::Had, } /// The thread that lands flights ([`relay`]): as soon as the card has run @@ -2582,6 +2739,9 @@ fn relay_worker() { _ => None, }) .collect(); + if card_steps::stage() > 0 { + line.landing = card_steps::writers(&items); + } break Ok(items); } }; @@ -2608,8 +2768,16 @@ fn relay_worker() { /// in the PC's memory goes into title memory. As [`hand_back`], each byte /// once, the pieces that differ found on several threads; but the merge is /// `Shadow::relay_merge`, which does not write the copy, and the ranges -/// are not done with here (each flight's are, afterwards). -fn relay_hand_back(back: &[Declared]) { +/// are not done with here (each flight's are, afterwards). In two steps: +/// what is to be looked through and what of it differs ([`RelayBack::look`], +/// which needs nothing that the fetch from the card's memory brings), and +/// the merge. +struct RelayBack { + work: Vec<(std::sync::Arc, usize, usize)>, + found: Option>>, +} + +fn relay_hand_back(back: &[Declared]) -> RelayBack { let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); for (shadow, declared) in back { if shadow.carded() { @@ -2622,27 +2790,71 @@ fn relay_hand_back(back: &[Declared]) { } work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); } - if work.is_empty() { - return; - } - #[cfg(feature = "diagnostics")] - let scanning = std::time::Instant::now(); - // Looked through without a lock: a piece that changes meanwhile (a - // later flight writing, the title's bytes going in) is found now or by - // that flight's landing, and the merge looks again under the lock. - let found = crate::shadow::find_all(&work); - #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); - let (mut now, mut title) = (Vec::new(), Vec::new()); - for ((shadow, from, to), found) in work.iter().zip(found) { - let mut written = 0; - for (at, n) in found { - written += shadow.relay_merge(at, n, &mut now, &mut title); + RelayBack { work, found: None } +} + +impl RelayBack { + /// Looks the ranges through, once; its time counts as `stat`. + fn look(&mut self, stat: usize) { + if self.work.is_empty() || self.found.is_some() { + return; } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); + let scanning = std::time::Instant::now(); + // Looked through without a lock: a piece that changes meanwhile (a + // later flight writing, the title's bytes going in) is found now or + // by that flight's landing, and the merge looks again under the + // lock. + self.found = Some(crate::shadow::find_all(&self.work)); + crate::land::spent(stat, scanning); #[cfg(feature = "diagnostics")] - crate::copystat::compared(*from, to - from, written); - let _ = (from, to); + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + } + + /// What differs goes into title memory. + fn merge(mut self) { + use crate::land; + self.look(land::stat::SCAN); + let Some(found) = self.found else { + return; + }; + let merging = std::time::Instant::now(); + let mut written: Vec = Vec::new(); + if land::on() { + // Pieces in the same block of title memory in one job, in order. + let pieces: Vec<(usize, usize, usize)> = + found.iter().enumerate().flat_map(|(i, found)| found.iter().map(move |&(at, n)| (i, at, n))).collect(); + let start = |i: usize| self.work[i].0.span().0 as usize; + let mut order: Vec = (0..pieces.len()).collect(); + order.sort_by_key(|&p| (start(pieces[p].0) + pieces[p].1) / crate::land::BLOCK); + let cut: Vec<(usize, usize)> = order.iter().map(|&p| (start(pieces[p].0) + pieces[p].1, pieces[p].2)).collect(); + let jobs = land::jobs(&cut); + let put: Vec = self.work.iter().map(|_| Default::default()).collect(); + land::each(jobs.len(), &|j| { + let working = std::time::Instant::now(); + let mut notes = land::Notes::default(); + for &p in &order[jobs[j].clone()] { + let (i, at, n) = pieces[p]; + put[i].fetch_add(self.work[i].0.land_back(at, n, &mut notes), Ordering::Relaxed); + } + notes.flush(); + land::spent(land::stat::BACK_ALL, working); + }); + land::count(land::stat::JOBS, jobs.len() as u64); + written.extend(put.iter().map(|p| p.load(Ordering::Relaxed))); + } else { + let (mut now, mut title) = (Vec::new(), Vec::new()); + for ((shadow, ..), found) in self.work.iter().zip(found) { + let merge = |(at, n)| shadow.relay_merge(at, n, &mut now, &mut title) as u64; + written.push(found.into_iter().map(merge).sum()); + } + } + land::spent(land::stat::BACK, merging); + for ((_, from, to), written) in self.work.iter().zip(written) { + COPY_BACK[1].fetch_add(written, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written as usize); + let _ = (from, to); + } } } @@ -2711,6 +2923,10 @@ fn late_line(frames: f64) { r[4] / 1000.0, ); } + crate::land::log(frames); + 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 +2937,8 @@ fn late_line(frames: f64) { } } +mod card_steps; + #[cfg(test)] mod late_tests { use super::{continues, join_ranges, touches}; @@ -2836,6 +3054,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`). /// @@ -2855,6 +3086,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); } } @@ -3060,6 +3304,7 @@ impl Host { budget: OnceLock::new(), card_budget: OnceLock::new(), indirect_args: Mutex::default(), + batch_args: Mutex::default(), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), @@ -3263,8 +3508,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 +3521,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 +3545,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 +3557,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 +3639,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()?; @@ -3475,6 +3725,7 @@ impl Host { event, sent: 0, buffer: None, + had: crate::land::Had::default(), }) } } @@ -3488,21 +3739,28 @@ impl Host { /// fetched under all ([`flagged_pieces`]); the fetch runs behind /// whatever was sent meanwhile, so it may bring a later flight's /// bytes, which that flight's landing then finds merged already; and - /// nothing is sent back up. - fn relay_card_back(&self, plans: &[&CardPlan], fetch: &mut Option) { + /// nothing is sent back up. `plans` come with the value signalled behind + /// their flight. `meanwhile` is called while the fetch is on its way, if + /// there is one. + fn relay_card_back(&self, plans: &[(&CardPlan, u64)], fetch: &mut Option, meanwhile: &mut dyn FnMut()) { + use crate::land; + let gathering = std::time::Instant::now(); let differs = { let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) }; let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); let mut total = 0u64; + if let (Some(fetch), Some(first)) = (fetch.as_mut(), plans.iter().map(|p| p.1).min()) { + fetch.had.landing(first); + } if let Some((differs, dwords)) = differs { // SAFETY: the mapping of the results. The compares of these // plans have run, and their dwords are given to no other plan // before these are done with (`card_done`). let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; let mut seen = std::collections::HashSet::new(); - for plan in plans { + for &(plan, behind) in plans { let flags: Vec<(usize, u32, bool)> = plan .ranges .iter() @@ -3517,11 +3775,20 @@ impl Host { for r in &plan.ranges { let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; for p in 0..r.span.pieces { - if !fetched.contains(&(copy, r.span.first + p)) { + if fetched.binary_search(&(copy, r.span.first + p)).is_err() { continue; } let (lo, hi) = r.shadow.card_piece(&r.span, p); - if lo < hi && seen.insert((copy, lo, hi)) { + if lo < hi && !seen.contains(&(copy, lo, hi)) { + let key = (r.shadow.id(), r.shadow.span().0 as usize + lo, hi - lo); + if fetch.as_ref().is_some_and(|f| f.had.holds(behind, key)) { + land::count(land::stat::HAD, 1); + land::count(land::stat::HAD_BYTES, (hi - lo) as u64); + if land::skip_on() { + continue; + } + } + seen.insert((copy, lo, hi)); pieces.push((r.shadow.clone(), lo, hi, total)); total += (hi - lo) as u64; } @@ -3530,12 +3797,29 @@ impl Host { } } } + if land::on() { + // In the order they are landed, each byte of a copy once. + let keys: Vec = + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)).collect(); + total = 0; + pieces = land::ordered(&keys) + .into_iter() + .map(|(i, title, len)| { + let shadow = &pieces[i].0; + let lo = title - shadow.span().0 as usize; + let at = total; + total += len as u64; + (shadow.clone(), lo, lo + len, at) + }) + .collect(); + } + land::spent(land::stat::GATHER, gathering); if fetch.is_none() { *fetch = self.make_relay_fetch(); } // The sends these flights ran behind, all a fetch on the copy queue // is known to have run behind. - let behind = plans.iter().map(|p| p.sent_as).max().unwrap_or(0); + let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0); if pieces.is_empty() { // Nothing to fetch: every send so far is older than the next // fetch, if that goes to the queue the sends went to. @@ -3560,6 +3844,12 @@ impl Host { let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); let copy_queue = f.queue.clone(); let waiting = std::time::Instant::now(); + // The flights the fetch runs behind: those in the line by now have + // been given to the queue. On the copy queue, those landed here. + let ahead = match copy_queue { + Some(_) => 0, + None => line().target, + }; // SAFETY: the list's last run was waited for by this thread; live // buffers (the copies are held by the plans); the fence and the // event are this thread's. @@ -3575,6 +3865,7 @@ impl Host { if let Some(queue) = ©_queue { queue.ExecuteCommandLists(&lists); queue.Signal(&fence, sent)?; + meanwhile(); fence.SetEventOnCompletion(sent, event)?; WaitForSingleObject(event, INFINITE); return Ok(behind); @@ -3587,6 +3878,7 @@ impl Host { drop(order); self.card_sent(); self.queue.Signal(&fence, sent)?; + meanwhile(); fence.SetEventOnCompletion(sent, event)?; WaitForSingleObject(event, INFINITE); Ok(after) @@ -3605,15 +3897,48 @@ impl Host { CARD_STATS[5].fetch_add(1, Ordering::Relaxed); CARD_STATS[6].fetch_add(us, Ordering::Relaxed); } - let mut title = Vec::new(); + let merging = std::time::Instant::now(); let mut written = 0; - for (shadow, lo, hi, at) in &pieces { - // 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); + if land::on() { + let titles: Vec<(usize, usize)> = + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.span().0 as usize + lo, hi - lo)).collect(); + let jobs = land::jobs(&titles); + let put = std::sync::atomic::AtomicU64::new(0); + land::each(jobs.len(), &|j| { + let working = std::time::Instant::now(); + let mut notes = land::Notes::default(); + for run in pieces[jobs[j].clone()].chunk_by(|a, b| std::sync::Arc::ptr_eq(&a.0, &b.0)) { + let addressed: Vec<(usize, usize, usize)> = + run.iter().map(|(_, lo, hi, at)| (*lo, *hi, data + *at as usize)).collect(); + // SAFETY: the mapping of the fetched bytes, `total` of + // them; the copy into it has run, and the next waits + // for this call. + put.fetch_add(unsafe { run[0].0.land_card(&addressed, after, &mut notes) }, Ordering::Relaxed); + } + notes.flush(); + land::spent(land::stat::CARD_ALL, working); + }); + land::count(land::stat::JOBS, jobs.len() as u64); + written = put.into_inner(); + } else { + let mut title = Vec::new(); + for (shadow, lo, hi, at) in &pieces { + // 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) }; + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged as u64; + } + } + land::spent(land::stat::CARD, merging); + COPY_BACK[1].fetch_add(written, Ordering::Relaxed); + if let Some(f) = fetch.as_mut() { + f.had.fetched( + ahead, + pieces.iter().map(|(shadow, lo, hi, _)| (shadow.id(), shadow.span().0 as usize + lo, hi - lo)), + ); } - COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); // Sends up to `after` are of no use to any later merge. crate::shadow::relay_fetched(after); } @@ -3648,24 +3973,25 @@ impl Host { last_notes(&runs) )); } - let plans: Vec<&CardPlan> = flights.iter().filter_map(|f| f.card.as_ref()).collect(); - self.relay_card_back(&plans, fetch); + let plans: Vec<(&CardPlan, u64)> = flights.iter().filter_map(|f| Some((f.card.as_ref()?, f.fence))).collect(); + // (Each byte once: the ranges are joined.) let mut back: Vec = Vec::new(); for flight in &flights { - for (shadow, ranges) in &flight.back { + for (shadow, ranges) in flight.back.iter().filter(|(shadow, _)| !shadow.carded()) { match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { - Some((_, all)) => { - for range in ranges { - if !all.contains(range) { - all.push(*range); - } - } - } + Some((_, all)) => all.extend_from_slice(ranges), None => back.push((shadow.clone(), ranges.clone())), } } } - relay_hand_back(&back); + let mut hand_back = relay_hand_back(&back); + self.relay_card_back(&plans, fetch, &mut || { + if crate::land::on() { + hand_back.look(crate::land::stat::SCAN_BESIDE); + } + }); + hand_back.merge(); + let finishing = std::time::Instant::now(); // Only now, and flight by flight: a range another flight // in the air declared too stays closed to refreshes. for flight in &flights { @@ -3673,6 +3999,7 @@ impl Host { shadow.copy_back_done(ranges); } } + crate::land::spent(crate::land::stat::DONE, finishing); COPY_BACK[0].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); @@ -3681,8 +4008,9 @@ impl Host { // In the order given: what tells the title the card is done. let mut last = 0; let mut landed = Vec::new(); + let mut telling = std::time::Instant::now(); for item in items { - match item { + telling = match item { Late::Run(flight) => { last = flight.number; for &i in &flight.order { @@ -3691,17 +4019,28 @@ 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)); + crate::land::spent(crate::land::stat::READ_BACKS, telling) } - Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), - Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), - } + Late::Write(at, what, bytes) => { + what.write(at as *mut u8, bytes); + crate::land::spent(crate::land::stat::TOLD, telling) + } + Late::Signal(fence, value) => { + crate::fence::set(fence as crate::object::This, value); + crate::land::spent(crate::land::stat::TOLD, telling) + } + }; } if last > 0 { FINISHED.store(last, Ordering::Release); bury(last); } self.log_messages(); + crate::land::spent(crate::land::stat::REST, telling); RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); { let mut line = line(); @@ -3713,10 +4052,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; @@ -3840,7 +4181,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 }) @@ -3855,7 +4198,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; } } } @@ -3909,6 +4254,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 +4299,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))); } @@ -4116,6 +4463,40 @@ impl Host { working(was_working); } + /// For a submission of `runs` that refreshes the ranges `stale` of host + /// copies, which flights may be writing and the title wrote too + /// ([`stale_under_flights`]): the flights land first. `ranges` are + /// those of the submission's one asking, which is made again. + /// + /// With [`card_steps`] only the flights that declared them: a range of + /// a copy nobody declared any more is refreshed like any other. What + /// they landed is title memory written, so everything is asked and + /// looked at again; what is left after three times waits as before. + fn settle_stale( + &self, + submitted: &mut u64, + runs: &[&HostList], + mut stale: Vec<(std::sync::Arc, usize, usize)>, + ranges: &[(usize, usize)], + ) { + if relay_exact() && card_steps::stage() > 0 { + for _ in 0..3 { + #[cfg(feature = "diagnostics")] + blame_stale(&stale); + relay_wait(WHY_STALE, |_| stale.iter().all(|(shadow, from, to)| !shadow.writes_pending_in(*from, *to))); + crate::watch::ask_once(ranges); + stale = stale_under_flights(runs); + if stale.is_empty() { + return; + } + } + } + #[cfg(feature = "diagnostics")] + blame_stale(&stale); + self.settle(submitted, WHY_STALE); + crate::watch::ask_once(ranges); + } + /// [`Host::execute`], or with `late` the first half of /// [`Host::execute_late`]: the lists are prepared and sent, and what is /// to be done once they have run comes back with the submission lock @@ -4133,17 +4514,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 @@ -4176,6 +4572,8 @@ impl Host { // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); + #[cfg(feature = "diagnostics")] + let split = Split::begin(); // The time a settle of flights takes inside this preparing: the // wait for the card and the copy-back have their own places on the // frame line (run 92 showed them twice, "preparing" 250 ms for 135). @@ -4183,7 +4581,7 @@ impl Host { // One write-watch asking for everything the submission refreshes // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. if crate::watch::once() { - let mut spans: std::collections::HashMap = std::collections::HashMap::new(); + let mut spans: ByCopy<(usize, usize)> = ByCopy::default(); for list in runs { for step in &list.deferred().copies { if let Step::Refresh(shadow, address, len) = step @@ -4198,23 +4596,27 @@ impl Host { } let ranges: Vec<(usize, usize)> = spans.into_values().collect(); crate::watch::ask_once(&ranges); + #[cfg(feature = "diagnostics")] + split.part(0); // Behind flights: the title wrote memory that a flight's shaders // may write too, and this submission refreshes it. The flights // are settled, and the asking made again: the copy-back wrote // title memory, which other copies of it must see. - if behind && stale_under_flights(runs) { + let stale = if behind { stale_under_flights(runs) } else { Vec::new() }; + if !stale.is_empty() { let settling = std::time::Instant::now(); - self.settle(&mut submitted, WHY_STALE); + self.settle_stale(&mut submitted, runs, stale, &ranges); settled += settling.elapsed(); - crate::watch::ask_once(&ranges); } - } else if behind && stale_under_flights(runs) { + } else if behind && !stale_under_flights(runs).is_empty() { let settling = std::time::Instant::now(); self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); } + #[cfg(feature = "diagnostics")] + split.part(1); 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)); @@ -4223,6 +4625,8 @@ impl Host { } batch.flush(); crate::watch::ask_once_end(); + #[cfg(feature = "diagnostics")] + split.part(2); // The snapshots of the ranges shaders may write, if they were left // for now (`crate::shadow::wide_back`): the refreshes are done, the // lists have not gone to the card. @@ -4233,6 +4637,8 @@ impl Host { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); } + #[cfg(feature = "diagnostics")] + split.part(3); // Copies in the card's memory: what changed on their CPU side goes // up ahead of the lists, and a compare of what the shaders may // write follows them in the same submission. @@ -4246,6 +4652,8 @@ impl Host { if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { lists.push(Some(check)); } + #[cfg(feature = "diagnostics")] + split.part(4); let prepared = std::time::Instant::now(); if late { *submitted += 1; @@ -4258,6 +4666,8 @@ impl Host { if let Err(e) = signalled { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } + #[cfg(feature = "diagnostics")] + split.part(5); let back = declared_writes(runs); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed); @@ -4268,6 +4678,7 @@ impl Host { number: this_submission, card, back, + own, writes, }; working(was_working); @@ -4678,6 +5089,7 @@ impl HostList { if let Some((scratch, _)) = scratch { self.indirect_common(&scratch); } + self.batches_common(); self.card_budget_out(); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { @@ -5152,7 +5564,22 @@ 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(card_steps::FillTo::Slot(slot.0, slot.1)))); + } + + /// As [`HostList::defer_fill`], for the beginning of a buffer + /// [`HostList::upload`] made. + pub(crate) fn defer_fill_buffer(&self, buffer: &ID3D12Resource, dst: *mut u8, src: *const u8, len: usize) { + let to = (card_steps::stage() > 1).then(|| card_steps::FillTo::Buffer(buffer.clone())); + self.deferred().copies.push(Step::Fill(dst as usize, src as usize, len, to)); } /// Brings `[address, address + len)` of a buffer's host copy up to date @@ -5204,7 +5631,8 @@ impl HostList { /// /// shortcut: one buffer per copy; pool them once uploads are frequent. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - let (buffer, data) = host.upload_buffer(size)?; + // With [`card_steps`] the card may be the one that fills it. + let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? }; name(&buffer, || format!("list upload {size:#x}")); self.deferred().hold_upload(buffer.clone(), size); Some((buffer, data)) @@ -5272,7 +5700,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 +5708,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); @@ -5390,6 +5819,43 @@ impl HostList { Some(buffer) } + /// Where the next batch of clamped records goes: a device-local buffer + /// the list keeps from recording to recording, the batch's place in it + /// and the state the buffer is in. Every batch of a recording has a place + /// of its own: the executions before it may still read theirs. + pub(crate) fn batch_place(&self) -> Option<(ID3D12Resource, u32, D3D12_RESOURCE_STATES)> { + use crate::indirect::batch::{JOBS, SLOT}; + let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); + let (buffer, i) = ((args.1 / BATCHES) as usize, args.1 % BATCHES); + if buffer == args.0.len() { + let size = u64::from(BATCHES * JOBS * SLOT); + let made = host()?.uav_buffer(size)?; + name(&made, || format!("indirect batches {size:#x}")); + args.0.push(made); + } + args.1 += 1; + // (Its first batch finds it as the recording before left it: + // `batches_common`.) + let state = if i == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + Some((args.0[buffer].clone(), i * JOBS * SLOT, state)) + } + + /// Before the list closes: the scratch buffers of the batched clamps go + /// back to the common state, where the next recording expects them. + fn batches_common(&self) { + let mut args = self.batch_args.lock().unwrap_or_else(|e| e.into_inner()); + let used = std::mem::take(&mut args.1).div_ceil(BATCHES) as usize; + let barriers: Vec = args.0[..used] + .iter() + .map(|b| transition(b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON)) + .collect(); + if !barriers.is_empty() { + // SAFETY: an open list and live buffers this recording left in + // `INDIRECT_ARGUMENT`. + unsafe { self.list.ResourceBarrier(&barriers) }; + } + } + /// Moves `scratch` back to the common state if a clamp left it readable /// as indirect arguments ([`HostList::indirect_readable`]): where the /// list's first clamp expects it. Done before the list closes and before @@ -5456,7 +5922,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,44 +5939,55 @@ 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 { - let started = std::time::Instant::now(); - let copied = match step { + // The time and the bytes of the copies and fills, some 13,000 a + // frame between 20,000 refreshes: summed here and added once. + let (mut us, mut bytes) = (std::time::Duration::ZERO, 0u64); + #[cfg(feature = "diagnostics")] + let (mut copies, mut refreshes, mut refreshed) = (0u64, 0u64, 0u64); + for (i, step) in self.deferred().copies.iter().enumerate() { + if matches!(step, Step::Copy(..) | Step::Fill(..)) && taken(i) { + continue; + } + let (started, copied) = match step { &Step::Copy(dst, src, len) => { + let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { - add(C::Copies, 1); - add(C::CopyBytes, len as u64); + copies += 1; } batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); // With the submission's one asking: the journal learns it. crate::watch::wrote(dst, len); - len + (started, len) } - &Step::Fill(dst, src, len) => { + &Step::Fill(dst, src, len, _) => { + let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] { - add(C::Copies, 1); - add(C::CopyBytes, len as u64); + copies += 1; } copy_mapped(dst as *mut u8, src as *const u8, len, false); - len + (started, len) } Step::Refresh(shadow, address, len) => { #[cfg(feature = "diagnostics")] { - add(C::Refreshes, 1); - add(C::RefreshBytes, *len as u64); + refreshes += 1; + refreshed += *len as u64; } batch.add(shadow, *address, *len); continue; } - Step::Run(work) | Step::Host(work) => { + Step::Run(work) | Step::Host(work, _) => { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); if matches!(step, Step::Run(_)) { batch.title_written(); } @@ -5545,12 +6028,130 @@ impl HostList { continue; } }; - PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); - PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + us += started.elapsed(); + bytes += copied as u64; + } + PREPARING[0].fetch_add(us.as_micros() as u64, Ordering::Relaxed); + PREPARING[1].fetch_add(bytes, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + add(C::Copies, copies); + add(C::CopyBytes, bytes); + add(C::Refreshes, refreshes); + add(C::RefreshBytes, refreshed); + SPLIT[7].fetch_add(us.as_nanos() as u64, Ordering::Relaxed); } } } +/// A table by a copy's address. +pub(crate) type ByCopy = std::collections::HashMap>; + +/// A hash for addresses of ours: the bits that tell them apart, spread. The +/// tables it serves are asked 40,000 times a frame, and hold no one's keys +/// but our own. +#[derive(Default)] +pub(crate) struct AddressHash(u64); + +impl std::hash::Hasher for AddressHash { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_usize(usize::from(b)); + } + } + fn write_usize(&mut self, n: usize) { + let h = (self.0.rotate_left(5) ^ n as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15); + self.0 = h ^ (h >> 32); + } +} + +/// Since the last frame-rate line, nanoseconds of the submitting thread's +/// preparing: the write-watch asking for a submission; the title's bytes put +/// in under flights' writes; the lists' steps, the refreshes among them; the +/// snapshots; what goes to copies in the card's memory; the lists sent; and +/// of the steps: the refreshes, and the copies and fills (those with the +/// refreshes a copy of title memory flushes). +#[cfg(feature = "diagnostics")] +static SPLIT: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// Since the last frame-rate line: flushes of refreshes, their refreshes, +/// those known to copy nothing, and those done on several threads. +#[cfg(feature = "diagnostics")] +static FLUSHES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Counts into [`SPLIT`]. +#[cfg(feature = "diagnostics")] +struct Split(std::cell::Cell); + +#[cfg(feature = "diagnostics")] +impl Split { + fn begin() -> Split { + Split(std::cell::Cell::new(std::time::Instant::now())) + } + + /// What came since the last part was part `i`. + fn part(&self, i: usize) { + let now = std::time::Instant::now(); + SPLIT[i].fetch_add((now - self.0.replace(now)).as_nanos() as u64, Ordering::Relaxed); + } +} + +/// The split of the preparing, per frame, for the frame-rate line. +#[cfg(feature = "diagnostics")] +fn split_line(frames: f64) { + let ms: Vec = SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let f: Vec = FLUSHES.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let a: Vec = crate::watch::asks().iter().map(|&n| n as f64 / frames).collect(); + let h: Vec = crate::draw::HEAP_SPLIT.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames).collect(); + let s: Vec = crate::shadow::send_stats().iter().map(|&n| n as f64 / (1 << 20) as f64 / frames).collect(); + tracing::info!( + "preparing per frame, the submitting thread: {:.1} ms asking the write watch, {:.1} putting the title's bytes under flights' \ + writes, {:.1} in the lists' steps (refreshes {:.1} in {:.0} flushes of {:.0}, {:.0} of them known to copy nothing, {:.0} on \ + several threads; copies and fills {:.1}, the refreshes before copies among them), {:.1} snapshots, {:.1} for copies in the \ + card's memory, {:.1} sending the lists (VICTORY_LIGHT_REFRESH is {})", + ms[0], + ms[1], + ms[2], + ms[6], + f[0], + f[1], + f[2], + f[3], + ms[7], + ms[3], + ms[4], + ms[5], + if crate::watch::light() { "on" } else { "off" }, + ); + tracing::info!( + "asking about title memory per frame, all threads: {:.0} kernel askings over {:.0} MB; view ranges: {:.0} answered by their \ + bits, {:.0} by the guards whole, {:.0} block by block; {:.0} blocks made read-only, {:.0} opened by ourselves; {:.1} ms \ + waiting for the guards, {:.1} ms changing protections; pages taken again for the card: {:.1} MB compared, {:.1} MB of them \ + as they were, {:.1} MB to go up (VICTORY_SEND_CHANGED)", + a[0], + a[1] / 1024.0, + a[2], + a[3], + a[4], + a[5], + a[6], + a[7] / 1e6, + a[8] / 1e6, + s[0], + s[1], + s[2], + ); + tracing::info!( + "the pass over the heap's views per frame: {:.1} ms looking at slots, {:.1} their copies' spans and refreshes, {:.1} textures", + h[0], + h[1], + h[2], + ); +} + /// Whether a submission's refreshes of host copies run on several threads, /// a copy to a thread (`VICTORY_WIDE_REFRESH=0` disables it; `=1` forces it). /// @@ -5612,7 +6213,7 @@ struct Batch { /// the heap's buffers ready adds some 4,100 copies, and searching them /// for every refresh of a submission was tens of millions of /// comparisons a frame. - index: std::collections::HashMap, + index: ByCopy, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -5644,7 +6245,13 @@ impl Batch { if let Some(moved) = self.refreshes.get(at) { self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } - Self::update(&shadow, from, to); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + if !(crate::watch::light() && shadow.nothing_new(from, to - from)) { + Self::update(&shadow, from, to); + } + #[cfg(feature = "diagnostics")] + SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); } /// Brings `[from, to)` of a copy up to date, timed. @@ -5673,6 +6280,36 @@ impl Batch { fn flush(&mut self) { self.index.clear(); + if self.refreshes.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let (began, all) = (std::time::Instant::now(), self.refreshes.len()); + self.flush_all(); + #[cfg(feature = "diagnostics")] + { + SPLIT[6].fetch_add(began.elapsed().as_nanos() as u64, Ordering::Relaxed); + FLUSHES[0].fetch_add(1, Ordering::Relaxed); + FLUSHES[1].fetch_add(all as u64, Ordering::Relaxed); + } + } + + fn flush_all(&mut self) { + // Most of a flush's copies are as they were: they are told so here, + // from what the submission's asking found, before anything is asked + // and any thread woken. (Thousands of them, the heap's buffer views + // once a frame: on the threads, below.) + const FEW: usize = 256; + let light = crate::watch::light(); + if light && self.refreshes.len() <= FEW { + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let all = self.refreshes.len(); + self.refreshes.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from)); + PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + FLUSHES[2].fetch_add((all - self.refreshes.len()) as u64, Ordering::Relaxed); + } // One write-watch asking for the copies that lie close together, // not one per copy. let ahead = self.refreshes.len() > 1; @@ -5693,12 +6330,28 @@ impl Batch { // The time counted is the time it took, not the threads' sum. let started = std::time::Instant::now(); let before = PREPARING[0].load(Ordering::Relaxed); - let jobs: Vec> = self - .refreshes - .drain(..) - .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) - .collect(); - crate::shadow::wide_run(jobs); + #[cfg(feature = "diagnostics")] + FLUSHES[3].fetch_add(self.refreshes.len() as u64, Ordering::Relaxed); + if light { + // A number to a free thread, not a job to each copy. + let refreshes = std::mem::take(&mut self.refreshes); + crate::shadow::wide_each(refreshes.len(), move |i| { + let (shadow, from, to) = &refreshes[i]; + if refreshes.len() > FEW && shadow.nothing_new(*from, *to - *from) { + #[cfg(feature = "diagnostics")] + FLUSHES[2].fetch_add(1, Ordering::Relaxed); + return; + } + Self::update(shadow, *from, *to); + }); + } else { + let jobs: Vec> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .collect(); + crate::shadow::wide_run(jobs); + } let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); PREPARING[0].fetch_sub(summed.saturating_sub(started.elapsed().as_micros() as u64), Ordering::Relaxed); } else { @@ -6116,6 +6769,8 @@ impl Meter { late_line(frames); card_clock_line(frames, ms); crate::shadow::back_line(frames); + #[cfg(feature = "diagnostics")] + split_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); if passes + compares > 0.0 { @@ -6254,7 +6909,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", @@ -6341,7 +6995,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; @@ -6437,6 +7101,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))?; @@ -6459,6 +7124,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, @@ -6538,9 +7204,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 @@ -6853,6 +7581,547 @@ mod spare { } } +#[cfg(test)] +mod refresh_tests { + use super::Batch; + use crate::shadow::Shadow; + use std::sync::Arc; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, + VirtualAlloc, + }; + + const PAGE: usize = 64 << 10; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + /// Title memory for the tests (never given back: copies of it stay in + /// the guards): write-watched, or a view of a section. + fn title(len: usize, view: bool) -> usize { + // SAFETY: plain allocations. + let at = unsafe { + if view { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + // As the runtime tells of it. + crate::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::title_memory_view(at, len, section as usize, 0); + at + } else { + VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize + } + }; + assert_ne!(at, 0); + at + } + + fn memory(len: usize) -> *mut u8 { + // SAFETY: a plain allocation. + unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE).cast() } + } + + struct Random(u64); + + impl Random { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 11) as usize % n + } + } + + /// Prepares as a submission does: one asking for all the ranges, the + /// refreshes in several flushes, the asking's end. + fn submission(ranges: &[(Arc, usize, usize)], flushes: usize) { + // One at a time, as submissions are. + static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + let asked: Vec<(usize, usize)> = ranges.iter().filter(|r| !r.0.unwatched()).map(|r| (r.1, r.1 + r.2)).collect(); + crate::watch::ask_once(&asked); + let mut batch = Batch::default(); + for part in ranges.chunks(ranges.len().div_ceil(flushes).max(1)) { + for (shadow, at, len) in part { + batch.add(shadow, *at, *len); + } + batch.flush(); + } + crate::watch::ask_once_end(); + } + + /// Whatever is written where, by the title or by us, and whichever + /// copies (of both kinds of memory, over one another, none on a page + /// line) are refreshed in which ranges: a refreshed range holds what + /// title memory holds. + #[test] + fn refreshed_ranges_hold_title_memory() { + // SAFETY (all blocks): title memory and copies of the test's own, + // written by this thread and, in `Batch::flush`, by the threads that + // refresh, which are done when it returns. + let mut random = Random(0x1234_5678_9ABC_DEF1); + const LEN: usize = 24 * PAGE; + let regions = [title(LEN, false), title(LEN, true)]; + let mut copies = Vec::new(); + for ®ion in ®ions { + for (from, to) in [(0, LEN), (100, LEN - 5000), (3 * PAGE + 777, 9 * PAGE + 10), (8 * PAGE, 8 * PAGE + 300), (PAGE, 20 * PAGE)] { + let data = memory(to - from); + copies.push((Shadow::unbacked((region + from) as u64, data, (to - from) as u64, false), data)); + } + } + let byte = |at: usize| unsafe { (at as *const u8).read_volatile() }; + for round in 0..600 { + for _ in 0..random.below(4) { + let at = regions[random.below(2)] + random.below(LEN - 64); + let n = 1 + random.below(60); + if random.below(3) == 0 { + // What shaders wrote. + let was: Vec = (0..n).map(|i| byte(at + i)).collect(); + let now: Vec = was.iter().map(|b| if random.below(2) == 0 { *b } else { random.below(256) as u8 }).collect(); + Shadow::put(at, &was, &now); + assert!(now.iter().enumerate().all(|(i, &b)| byte(at + i) == b), "not put"); + continue; + } + for i in 0..n { + unsafe { ((at + i) as *mut u8).write_volatile(random.below(256) as u8) }; + } + } + let mut ranges = Vec::new(); + for (shadow, _) in &copies { + if random.below(3) == 0 { + continue; + } + let (start, len) = shadow.span(); + let (start, len) = (start as usize, len as usize); + // Often the range of the time before, as a list's is. + let from = if random.below(2) == 0 { 0 } else { random.below(len) }; + let n = if random.below(2) == 0 { len - from } else { 1 + random.below(len - from) }; + ranges.push((shadow.clone(), start + from, n)); + } + if ranges.is_empty() { + continue; + } + let flushes = 1 + random.below(3); + submission(&ranges, flushes); + for (shadow, at, n) in &ranges { + let data = copies.iter().find(|c| Arc::ptr_eq(&c.0, shadow)).unwrap().1; + let start = shadow.span().0 as usize; + let same = unsafe { + std::slice::from_raw_parts(*at as *const u8, *n) == std::slice::from_raw_parts(data.add(at - start), *n) + }; + assert!(same, "round {round}: {at:#x}+{n:#x} of a copy at {start:#x}; first byte {}", byte(*at)); + } + } + } + + /// A copy in the card's memory, with the card's side and the sends to it + /// played by the test. + struct Carded { + shadow: Arc, + data: usize, + start: usize, + len: usize, + /// The last send, the last send every fetch to come is behind, and + /// the card's bytes: the queue's order is the order it is locked in. + card: std::sync::Mutex<(u64, u64, Vec)>, + /// Whether a flight that writes it has not landed. + flying: std::sync::atomic::AtomicBool, + /// The dword of each eight its shaders write. + class: usize, + } + + impl Carded { + fn new(start: usize, len: usize, class: usize) -> Carded { + let data = memory(len); + Carded { + shadow: Shadow::unbacked(start as u64, data, len as u64, true), + data: data as usize, + start, + len, + card: std::sync::Mutex::new((0, 0, vec![0; len])), + flying: std::sync::atomic::AtomicBool::new(false), + class, + } + } + + /// What changed on the CPU's side goes up. + fn send(&self) { + let mut card = self.card.lock().unwrap(); + card.0 += 1; + let (number, merged) = (card.0, card.1); + for (a, b) in self.shadow.send_up(number, merged) { + // SAFETY: the copy's bytes; nothing writes those that are to + // go up. + unsafe { std::ptr::copy_nonoverlapping((self.data + a) as *const u8, card.2[a..b].as_mut_ptr(), b - a) }; + } + } + } + + /// Everything at once: the title writes its memory on two threads, the + /// submitting thread puts its bytes in under shader writes + /// (`Shadow::merge_under_writes`), refreshes copies that overlap (two in + /// the card's memory, one not), sends up what changed and declares what + /// the next flight's shaders write, and what flights wrote is landed + /// meanwhile (`crate::land`, beside the guards). When all of it stands + /// still and the copies are refreshed once more, each of them, and the + /// card's side of those that have one, hold what title memory holds, and + /// title memory what was written last. + /// + /// (It fails in the first rounds if `landed_beside` notes nothing, or + /// only takes the block out of the guards' clean ones and leaves its bit, + /// or if a fault leaves the bit; in some thousand rounds, + /// `VICTORY_TEST_ROUNDS`, if what is landed is noted before it is in.) + #[test] + fn landings_title_writes_and_light_refreshes_at_once() { + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + assert!(crate::safecopy::on()); + const LEN: usize = 24 * PAGE; + let rounds: usize = std::env::var("VICTORY_TEST_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(400); + let region = title(LEN, true); + let dword = |at: usize| unsafe { &*((region + at) as *const AtomicU32) }; + let carded = [Carded::new(region, LEN, 3), Carded::new(region + 4 * PAGE + 1000, LEN - 6 * PAGE - 4, 5)]; + let plain = { + let (start, len) = (region + 700, LEN - 9000); + let data = memory(len); + (Shadow::unbacked(start as u64, data, len as u64, false), start, len, data as usize) + }; + let stop = AtomicBool::new(false); + // Also when an assertion fails on one of the threads. + struct Stop<'a>(&'a AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } + } + // Held shared by who writes title memory, alone while it is looked at. + let still = std::sync::RwLock::new(()); + let (fly, flights) = std::sync::mpsc::channel::<(usize, Vec<(usize, usize)>, u32)>(); + std::thread::scope(|s| { + for t in 0..2usize { + let (stop, still) = (&stop, &still); + s.spawn(move || { + let mut random = Random(0x7777_1234_0000_0001 + t as u64 * 0x1111); + let mut value = 0u32; + while !stop.load(Ordering::Relaxed) { + { + let _moving = still.read().unwrap(); + for _ in 0..3 { + value += 1; + // Of each eight dwords, one a thread. + let at = random.below(LEN / 32) * 32 + 4 * (1 + t); + dword(at).store(value, Ordering::Relaxed); + } + } + std::thread::sleep(std::time::Duration::from_micros(20)); + } + }); + } + // Lands flights. + { + let (carded, stop) = (&carded, &stop); + s.spawn(move || { + let _stop = Stop(stop); + while let Ok((which, ranges, value)) = flights.recv() { + let c = &carded[which]; + // Fetched: the card's bytes, behind every send so far. + let (after, now) = { + let card = c.card.lock().unwrap(); + (card.0, card.2.clone()) + }; + // By piece: 64 KiB of title memory. + let mut pieces = Vec::new(); + for &(from, to) in &ranges { + let mut at = from; + while at < to { + let next = ((c.start + at) / PAGE * PAGE + PAGE - c.start).min(to); + pieces.push((at, next, now.as_ptr() as usize + at)); + at = next; + } + } + let parts: Vec<_> = pieces.chunks(3).collect(); + crate::land::each(parts.len(), &|i| { + let mut notes = crate::land::Notes::default(); + // SAFETY: the bytes of `now`; each piece once. + unsafe { c.shadow.land_card(parts[i], after, &mut notes) }; + notes.flush(); + }); + for &(from, to) in &ranges { + for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) { + // (The next fetch may have brought more.) + assert!(dword(c.start - region + at).load(Ordering::Relaxed) >= value, "not landed"); + } + } + let done: Vec<_> = ranges.iter().map(|&(a, b)| (c.start + a, c.start + b)).collect(); + c.shadow.copy_back_done(&done); + c.card.lock().unwrap().1 = after; + c.flying.store(false, Ordering::Release); + } + }); + } + let _stop = Stop(&stop); + let mut random = Random(0xABCD_EF01_2345_6789); + let check = |round: usize, random: &mut Random, quiet: bool| { + for c in &carded { + if c.shadow.writes_pending() { + let mut runs = usize::MAX; + assert!(!c.shadow.merge_under_writes(c.start, c.len, &mut runs), "round {round}"); + } + } + let mut ranges = Vec::new(); + for (shadow, start, len) in + carded.iter().map(|c| (&c.shadow, c.start, c.len)).chain([(&plain.0, plain.1, plain.2)]) + { + // All of it, or a part; often the same part. + let (from, n) = match random.below(3) { + _ if quiet => (0, len), + 0 => (0, len), + 1 => (len / 3 / 4 * 4, len / 2 / 4 * 4), + _ => { + let from = random.below(len / 4) * 4; + (from, (4 + random.below((len - from) / 4) * 4).min(len - from)) + } + }; + ranges.push((shadow.clone(), start + from, n)); + } + submission(&ranges, 1 + random.below(3)); + carded.iter().for_each(Carded::send); + }; + let mut value = 1u32; + for round in 0..rounds { + check(round, &mut random, false); + // The flight of this submission: its shaders' writes. + for (which, c) in carded.iter().enumerate() { + if c.flying.swap(true, Ordering::Acquire) { + continue; + } + value += 1; + let mut ranges: Vec<(usize, usize)> = Vec::new(); + let first = random.below(6) * PAGE / 2; + for k in 0..2 { + let from = first + k * 9 * PAGE + 4 * random.below(9000); + let to = (from + 4 * (1 + random.below(7 * PAGE / 4))).min(c.len); + if from < to { + ranges.push((from, to)); + } + } + for &(from, to) in &ranges { + c.shadow.writing(c.start + from, to - from); + } + { + let mut card = c.card.lock().unwrap(); + for &(from, to) in &ranges { + for at in (from..to).filter(|at| (c.start - region + at) % 32 == 4 * c.class) { + card.2[at..at + 4].copy_from_slice(&value.to_le_bytes()); + } + } + } + fly.send((which, ranges, value)).unwrap(); + } + if round % 20 != 19 { + continue; + } + // Still: no flight in the air, no title write. + let _still = still.write().unwrap(); + while carded.iter().any(|c| c.flying.load(Ordering::Acquire)) { + assert!(!stop.load(Ordering::Relaxed), "the landing thread failed"); + std::thread::yield_now(); + } + check(round, &mut random, true); + // SAFETY: the test's own memory, written by nobody now. + let bytes = |at: usize, len: usize| unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let first = |a: &[u8], b: &[u8]| a.iter().zip(b).position(|(x, y)| x != y); + for c in &carded { + let (held, there) = (bytes(c.data, c.len), bytes(c.start, c.len)); + assert_eq!(first(held, there), None, "round {round}: a card copy's CPU side (class {})", c.class); + let card = c.card.lock().unwrap(); + assert_eq!(first(&card.2, there), None, "round {round}: a card copy's card side (class {})", c.class); + } + assert_eq!(first(bytes(plain.3, plain.2), bytes(plain.1, plain.2)), None, "round {round}: the other copy"); + } + drop(fly); + }); + } + + /// A range nothing wrote is known to be as it was, at its ends too, and + /// is so no more once something wrote it. + #[test] + fn unchanged_ranges_are_known() { + for view in [false, true] { + let region = title(8 * PAGE, view); + // (A page read for the first time counts as written.) + // SAFETY: the test's own memory. + unsafe { std::ptr::write_bytes(region as *mut u8, 1, 8 * PAGE) }; + let data = memory(8 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (8 * PAGE) as u64, false); + // Ends in the middle of pages. + let (at, len) = (region + 500, 5 * PAGE); + let look = |expected: bool, what: &str| { + // The submission's one asking, which takes two ranges. (Again + // if a submission of another test ended it.) + let mut known = false; + for _ in 0..100 { + crate::watch::ask_once(&[(at, at + len), (region + 7 * PAGE, region + 8 * PAGE)]); + known = copy.nothing_new(at, len); + if known || !expected { + break; + } + } + assert_eq!(known, expected, "view {view}: {what}"); + let copied = copy.update(at, len); + crate::watch::ask_once_end(); + copied + }; + assert_eq!(look(false, "never taken"), len); + assert_eq!(look(true, "taken"), 0); + assert_eq!(look(true, "taken"), 0); + // SAFETY: the test's own memory. + unsafe { ((region + 600) as *mut u8).write_volatile(1) }; + assert_eq!(look(false, "written at its end"), PAGE - 500); + assert_eq!(look(true, "taken again"), 0); + // Outside the range, on its last page. + // SAFETY: as above. + unsafe { ((region + 5 * PAGE + 600) as *mut u8).write_volatile(1) }; + assert_eq!(look(false, "written on its last page"), 500); + // A longer range was never taken whole. + assert!(!copy.nothing_new(region, 6 * PAGE)); + } + } + + /// A part of a copy in the card's memory taken again goes up only if it + /// differs (with `VICTORY_SEND_CHANGED=1`), whole when never taken. + #[test] + fn only_what_differs_goes_up() { + let region = title(4 * PAGE, true); + let data = memory(4 * PAGE); + let copy = Shadow::unbacked(region as u64, data, (4 * PAGE) as u64, true); + copy.update(region, 4 * PAGE); + assert_eq!(copy.take_dirty(), [(0, 4 * PAGE)], "all of it, though zeros are no change"); + // What the relay does: shader writes into title memory, and into the + // CPU's side. + crate::watch::landing(region + PAGE + 640, 64); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes((region + PAGE + 640) as *mut u8, 7, 64); + std::ptr::write_bytes(data.add(PAGE + 640), 7, 64); + } + copy.update(region, 4 * PAGE); + let again = copy.take_dirty(); + // SAFETY: as above. + unsafe { ((region + 2 * PAGE + 128) as *mut u8).write_volatile(9) }; + copy.update(region, 4 * PAGE); + let written = copy.take_dirty(); + if std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") { + assert_eq!(again, []); + assert_eq!(written, [(2 * PAGE + 128, 2 * PAGE + 192)]); + } else { + assert_eq!(again, [(PAGE, 2 * PAGE)]); + assert_eq!(written, [(2 * PAGE, 3 * PAGE)]); + } + // SAFETY: as above. + assert_eq!(unsafe { data.add(2 * PAGE + 128).read() }, 9); + } + + /// The refreshes of a frame as run record-1 had them: 30 submissions, the + /// first with a copy for each of 4,400 ranges, the others with 60 and a + /// big copy that 55 landed pieces and 9 title writes opened, while a + /// thread lands what shaders wrote. Run with `--ignored --nocapture`, + /// and with `VICTORY_LIGHT_REFRESH=0` for the way it was. + #[test] + #[ignore] + fn frame_of_refreshes() { + let mut random = Random(0x9876_5432_1234_5671); + const EACH: usize = 224 << 10; + const BIG: usize = 174 << 20; + let watched = title(3000 * EACH, false); + let views = title(1400 * EACH, true); + let big = title(BIG, true); + // SAFETY: the test's own memory. + unsafe { + std::ptr::write_bytes(watched as *mut u8, 1, 3000 * EACH); + std::ptr::write_bytes(views as *mut u8, 1, 1400 * EACH); + std::ptr::write_bytes(big as *mut u8, 1, BIG); + } + let mut small = Vec::new(); + for i in 0..4400 { + let (start, at) = if i < 3000 { (watched, i * EACH) } else { (views, (i - 3000) * EACH) }; + let data = memory(EACH); + // The range views read, not all of the copy. + small.push((Shadow::unbacked((start + at) as u64, data, EACH as u64, false), start + at + 4000, EACH - 9000)); + } + let heap = (Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true), big, BIG); + // The same memory, as another copy: what is landed is landed through + // it, and the refreshes are of the first. + let lands = Shadow::unbacked(big as u64, memory(BIG), BIG as u64, true); + let (mut best, mut asking) = ([f64::MAX; 2], [0f64; 2]); + let (mut sum, mut landing) = (0.0, 0.0); + const FRAMES: usize = 12; + for frame in 0..FRAMES { + let mut took = [0f64; 2]; + for i in 0..30 { + // The title's writes, and the relay's beside the submission. + for _ in 0..9 { + let at = views + random.below(1400 * EACH / 8) * 8; + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } + for _ in 0..60 { + let at = watched + random.below(3000 * EACH / 8) * 8; + // SAFETY: the test's own memory. + unsafe { (at as *mut u64).write_volatile(frame as u64) }; + } + let first = random.below(BIG / PAGE - 60); + let lands = lands.clone(); + let land = std::thread::spawn(move || { + let now = vec![frame as u8 ^ i as u8 ^ 0x55; PAGE]; + let started = std::time::Instant::now(); + for pieces in (first..first + 55).collect::>().chunks(4) { + let pieces: Vec<_> = + pieces.iter().map(|p| (p * PAGE + 8, (p + 1) * PAGE - 8, now.as_ptr() as usize)).collect(); + let mut notes = crate::land::Notes::default(); + // SAFETY: the bytes of `now`; nothing else lands here. + unsafe { lands.land_card(&pieces, 0, &mut notes) }; + notes.flush(); + } + started.elapsed().as_secs_f64() * 1e3 + }); + let ranges: Vec<(Arc, usize, usize)> = if i == 0 { + small.iter().cloned().chain([heap.clone()]).collect() + } else { + (0..60).map(|_| small[random.below(4400)].clone()).chain([heap.clone()]).collect() + }; + let started = std::time::Instant::now(); + submission(&ranges, 3); + took[usize::from(i != 0)] += started.elapsed().as_secs_f64() * 1e3; + let put = land.join().unwrap(); + if frame >= 2 { + landing += put; + } + heap.0.take_dirty(); + } + if frame >= 2 { + sum += took[0] + took[1]; + for k in 0..2 { + best[k] = best[k].min(took[k]); + asking[k] += took[k]; + } + } + } + println!( + "VICTORY_LIGHT_REFRESH {}: a frame's refreshes {:.2} ms in the mean; the submission of all copies {:.2} (best {:.2}), the 29 \ + others {:.2} (best {:.2}); the landing thread's puts {:.2}", + crate::watch::light(), + sum / (FRAMES - 2) as f64, + asking[0] / (FRAMES - 2) as f64, + best[0], + asking[1] / (FRAMES - 2) as f64, + best[1], + landing / (FRAMES - 2) as f64, + ); + #[cfg(feature = "diagnostics")] + println!("per frame, as `crate::watch::asks`: {:?}", crate::watch::asks().map(|n| n / FRAMES as u64)); + } +} + #[cfg(test)] mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; 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..fd24a2c --- /dev/null +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -0,0 +1,1168 @@ +//! 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, with the steps of the same +/// submission that depend on them. Only with the relay's second stage +/// (`relay_exact`). +/// +/// Why: eleven dispatches a frame (the skinning passes, in two early +/// submissions) write through a view of the title's whole 174 MB heap, at +/// places they read out of job records in buffers: no bound of what they +/// write is known before they ran (frame capture replay2: 17af15c4015cb4b6, +/// 55679a0547649d0b, 89d08e561897d4e5, fdd56d97a806bcca and three more, +/// all through one view at offset 5920 of the title's bindless table). 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 these passes to land: 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 among themselves in the +/// order they stand in wherever one depends on another: [`plan`] takes +/// every copy and fill of the submission that writes what a taken one +/// reads or writes, or reads what a taken one writes. 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: a step of the submission that cannot be taken (a texture, +/// vertices expanded, a fill of memory of another kind) reads the +/// destination behind the copy, 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 (each place read once, however many fills take it). +const BETWEEN: u64 = 4 << 20; + +/// The most steps of a submission done this way. +const MOST: usize = 4096; + +/// How a fill's bytes get where its list reads them, if the card brings +/// them. +#[derive(Clone)] +pub(super) enum FillTo { + /// A descriptor slot that shows the fill's memory, and nothing else does + /// (title heap, slot): it is made to show our buffer instead. + Slot(usize, u32), + /// A buffer the card can write, filled from its beginning. + Buffer(ID3D12Resource), +} + +/// 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 }, + /// `to`: its memory can be given the bytes on the card. + Fill { src: usize, len: usize, asked: bool, to: bool }, + /// 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 bytes `d` reads and writes as a copy or a fill (empty ranges for +/// what it does not). +fn reads_writes(d: &Does) -> Option<((usize, usize), (usize, usize))> { + match *d { + Does::Copy { dst, src, len, .. } => Some(((src, src + len), (dst, dst + len))), + Does::Fill { src, len, .. } => Some(((src, src + len), (0, 0))), + _ => None, + } +} + +fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool { + touches(ranges, r.0, r.1) +} + +/// The steps of `does` (by place) to be done on the card, in order, each +/// with its level; or why not. All that are asked for, and every copy and +/// fill that is in the way of one that is done there: it writes what that +/// one reads or writes, or reads what it writes, whichever comes first. So +/// what is left on the CPU writes none of their bytes, and reads of them +/// only what a taken copy has not been told to write yet: bytes a step +/// ahead of it reads, in title memory as it is. +/// +/// Steps of a level are done together, every read before every write; a +/// step that writes what an earlier one reads or writes, or reads what it +/// writes, is of a higher level. Our list does them level by level. +fn plan(does: &[Does], stage: u32) -> Result, &'static str> { + let takes = |d: &Does| match *d { + Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"), + Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"), + _ => Ok(()), + }; + let mut taken = vec![false; does.len()]; + let (mut read, mut written) = (Vec::new(), Vec::new()); + let mut more = 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::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => more.push(i), + _ => {} + } + } + while !more.is_empty() { + for i in std::mem::take(&mut more) { + takes(&does[i])?; + taken[i] = true; + if let Some((r, w)) = reads_writes(&does[i]) { + if w.0 < w.1 && meet(r, w) { + return Err("a copy onto itself"); + } + join_ranges(&mut read, [r]); + join_ranges(&mut written, [w]); + } + } + if taken.iter().filter(|t| **t).count() > MOST { + return Err("too many steps depend on it"); + } + for (i, d) in does.iter().enumerate() { + // A fill that cannot be taken is looked at below. + if taken[i] || matches!(d, Does::Fill { to: false, .. }) { + continue; + } + if let Some((r, w)) = reads_writes(d) + && (touched(&written, r) || touched(&written, w) || touched(&read, w)) + { + more.push(i); + } + } + } + let order: Vec = (0..does.len()).filter(|&i| taken[i]).collect(); + // What stays on the CPU and reads what an earlier taken copy writes + // would read it too early. + let mut behind: Vec<(usize, usize)> = Vec::new(); + for (i, d) in does.iter().enumerate() { + if taken[i] { + if let Some((_, w)) = reads_writes(d) { + join_ranges(&mut behind, [w]); + } + continue; + } + match *d { + Does::Read { from, to, .. } if touched(&behind, (from, to)) => { + return Err("a texture or expanded vertices read what it writes"); + } + Does::Fill { src, len, .. } if touched(&behind, (src, src + len)) => { + return Err("a fill of memory the card cannot be given the bytes of reads what it writes"); + } + _ => {} + } + } + let mut out: Vec<(usize, u32)> = Vec::with_capacity(order.len()); + // The copies among them, which alone put others behind them or have to + // stand behind others. + let mut copies: Vec = Vec::new(); + for &i in &order { + let Some((r, w)) = reads_writes(&does[i]) else { + continue; + }; + let writes = w.0 < w.1; + let mut level = 0; + // Behind what writes what this reads or writes, and, if this + // writes, behind what reads it. + let ahead: Box> = + if writes { Box::new(0..out.len()) } else { Box::new(copies.iter().copied()) }; + for k in ahead { + let (j, at): (usize, u32) = out[k]; + let Some((jr, jw)) = reads_writes(&does[j]) else { + continue; + }; + if at >= level && (meet(jw, r) || meet(jw, w) || meet(jr, w)) { + level = at + 1; + } + } + if writes { + copies.push(out.len()); + } + out.push((i, level)); + } + Ok(out) +} + +/// 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, + level: u32, + to: To, +} + +enum To { + /// A host copy, and the title address. + Copy(Arc, usize), + /// A descriptor slot (title heap, slot). + Slot(usize, u32), + /// A buffer's beginning. + Buffer(ID3D12Resource), +} + +/// Records a level of 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 (and must be +/// so, unless this is the `first` level), the others in the common state, +/// as the submission's lists expect them. +fn record( + first: bool, + 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 constants = source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; + let mut barriers = vec![transition(between, dest, constants)]; + 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 { + if first { + // 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), + }), + }, + }]); + } else { + list.ResourceBarrier(&[transition(between, constants, dest)]); + } + 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(); + // Where the fills' bytes go. + let mut fills = std::collections::HashMap::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, to) => Does::Fill { + src: *src, + len: *len, + asked: read_blocked(written, *src, *len), + to: { + if let Some(to) = to { + fills.insert(does.len(), to.clone()); + } + to.is_some() + }, + }, + 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 mut 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()); + // The places read (host copy, address, bytes, level): where in the + // buffer between their bytes are. + let mut places = std::collections::HashMap::new(); + let mut end = 0u64; + for &(i, level) in &chosen { + let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else { + continue; + }; + let (Does::Copy { len, .. } | Does::Fill { len, .. }) = does[i] else { + continue; + }; + if len == 0 { + return Err("nothing to read"); + } + let from = holder(&writers, src, src + len)?; + let place = (Arc::as_ptr(&from) as usize, src, len, level); + let at = match places.get(&place) { + Some(&at) => at, + None => { + if end + len as u64 > BETWEEN { + return Err("too much at once"); + } + if !mapped(src, src + len) { + return Err("not all of what it reads is mapped"); + } + let at = end; + end = (end + len as u64).next_multiple_of(256); + places.insert(place, at); + at + } + }; + let to = match does[i] { + Does::Copy { .. } => { + 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"); + } + // What the steps behind it read of it is in that host + // copy, or nowhere. + writers.push(Writer { + shadow: Some(to.clone()), + from: dst, + to: dst + len, + copy: true, + }); + To::Copy(to, dst) + } + _ => match fills.get(&i) { + Some(FillTo::Slot(heap, index)) => To::Slot(*heap, *index), + Some(FillTo::Buffer(buffer)) => To::Buffer(buffer.clone()), + None => continue, + }, + }; + ops.push(Op { + from: (from, src), + len, + at, + level, + to, + }); + } + let Some(own) = self.own_list() else { + return Err("no host list or buffer for it"); + }; + // First every refresh, then the writes: 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); + if let To::Copy(to, dst) = &op.to { + to.refresh(&own.list, *dst as u64, op.len as u64); + } + } + let mut copied = Vec::new(); + 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, {end} bytes (VICTORY_CARD_STEPS)", ops.len())); + let levels = ops.iter().map(|op| op.level).max().unwrap_or(0); + for level in 0..=levels { + let mut reads = Vec::new(); + let mut writes = Vec::new(); + for op in ops.iter().filter(|op| op.level == level) { + let len = op.len as u64; + let read = (&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, len); + // (Each place once.) + if places.remove(&(Arc::as_ptr(&op.from.0) as usize, op.from.1, op.len, level)).is_some() { + reads.push(read); + } + match &op.to { + To::Copy(to, dst) => writes.push((&to.buffer, to.offset(*dst as u64), op.at, len)), + To::Buffer(buffer) => writes.push((buffer, 0, op.at, len)), + To::Slot(..) => {} + } + } + record(level == 0, &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::Buffer(_) => { + DONE[0].fetch_add(1, Ordering::Relaxed); + } + 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(..) | To::Buffer(_) => ((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, to: true } + } + + fn stuck(src: usize, len: usize) -> Does { + Does::Fill { src, len, asked: false, to: false } + } + + /// What is done on the card, as (place, level), in stage 2. + fn planned(does: &[Does]) -> Vec<(usize, u32)> { + plan(does, 2).unwrap() + } + + /// Only what is asked for is taken, all of it, and a step that stands + /// in none of their ways stays where it is. + #[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 }, + stuck(3100, 5), + ]; + assert_eq!(planned(&does), [(1, 0), (3, 0)]); + // Two fills of the same bytes. + assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![(0, 0), (1, 0)])); + assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![])); + // Ends that touch are apart. + let does = [ + copy(1000, 5000, 100, true), + copy(900, 9000, 100, false), + copy(1100, 9000, 5, false), + copy(4900, 9000, 100, false), + ]; + assert_eq!(planned(&does), [(0, 0)]); + } + + /// What depends on a taken step, or it on it, is taken too, on the level + /// the order of the steps asks for. + #[test] + fn steps_that_depend_on_one_another_are_taken_in_order() { + let taken = copy(1000, 5000, 100, true); + // Reads what it writes, behind and ahead of it. + assert_eq!(planned(&[taken, fill(1099, 64, false)]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[fill(1099, 64, false), taken]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[taken, copy(7000, 1050, 10, false)]), [(0, 0), (1, 1)]); + // Writes what it reads, and what it writes. + assert_eq!(planned(&[copy(5099, 9000, 1, false), taken]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[taken, copy(5099, 9000, 1, false)]), [(0, 0), (1, 1)]); + assert_eq!(planned(&[taken, copy(999, 9000, 2, false)]), [(0, 0), (1, 1)]); + // The same list twice. + assert_eq!(planned(&[taken, taken]), [(0, 0), (1, 1)]); + // A chain, with steps apart from it in between, and two fills of one + // copy on one level. + let does = [ + copy(8000, 7000, 50, false), + taken, + copy(2000, 1010, 20, false), + fill(90_000, 10, false), + fill(2000, 20, false), + fill(2010, 20, true), + copy(1000, 2005, 5, false), + fill(1000, 100, false), + ]; + assert_eq!(planned(&does), [(1, 0), (2, 1), (4, 2), (5, 2), (6, 2), (7, 3)]); + // A fill is in nobody's way. + assert_eq!(planned(&[taken, fill(5000, 100, false)]), [(0, 0)]); + // A copy ahead that a taken one only shares its source with. + assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]); + } + + /// Whatever the steps, done level by level (in a level every read + /// before every write) they read and leave what they read and leave one + /// after the other, the CPU's steps ahead of all of them. + #[test] + fn levels_do_what_the_order_does() { + let mut seed = 12345u32; + let mut random = move |n: u32| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345); + (seed >> 16) % n + }; + let (mut done, mut refused) = (0, 0); + for _ in 0..4000 { + let does: Vec = (0..2 + random(9)) + .map(|_| { + let (at, other, len) = (random(60) as usize, random(60) as usize, 1 + random(8) as usize); + let asked = random(4) == 0; + match random(8) { + 0..4 => copy(at, other, len, asked), + 4..6 => fill(at, len, asked), + 6 => stuck(at, len), + _ => Does::Read { from: at, to: at + len, asked: false }, + } + }) + .collect(); + let Ok(chosen) = plan(&does, 2) else { + refused += 1; + continue; + }; + done += 1; + let start: Vec = (0..80).collect(); + // One after the other: what each reads, and what is left. + let mut memory = start.clone(); + let mut wanted = Vec::new(); + for d in &does { + let (from, to) = match *d { + Does::Read { from, to, .. } => (from, to), + _ => reads_writes(d).unwrap().0, + }; + wanted.push(memory[from..to].to_vec()); + if let Does::Copy { dst, src, len, .. } = *d { + memory.copy_within(src..src + len, dst); + } + } + // The CPU's, then the card's. + let mut cpu = start.clone(); + let taken = |i: usize| chosen.iter().any(|c| c.0 == i); + for (i, d) in does.iter().enumerate().filter(|&(i, _)| !taken(i)) { + let (from, to) = match *d { + Does::Read { from, to, .. } => (from, to), + _ => reads_writes(d).unwrap().0, + }; + assert_eq!(cpu[from..to], wanted[i][..], "step {i} of {does:?}"); + if let Does::Copy { dst, src, len, .. } = *d { + cpu.copy_within(src..src + len, dst); + } + } + let mut card = cpu.clone(); + for level in 0..=chosen.iter().map(|c| c.1).max().unwrap_or(0) { + let of: Vec = chosen.iter().filter(|c| c.1 == level).map(|c| c.0).collect(); + let before = card.clone(); + for i in of { + let ((from, to), (dst, _)) = reads_writes(&does[i]).unwrap(); + assert_eq!(before[from..to], wanted[i][..], "step {i} of {does:?}: {chosen:?}"); + if matches!(does[i], Does::Copy { .. }) { + card[dst..dst + to - from].copy_from_slice(&before[from..to]); + } + } + } + assert_eq!(card, memory, "{does:?}: {chosen:?}"); + } + assert!(done > 500 && refused > 100, "{done} {refused}"); + } + + /// What cannot be done on the card refuses the lot, where it stands in + /// the way. + #[test] + fn steps_in_the_way_are_refused() { + let taken = copy(1000, 5000, 100, true); + assert!(plan(&[taken, Does::Run], 2).is_err()); + // A texture that itself waits for flights; a fill that cannot be + // taken but waits. + assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2).is_err()); + assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2).is_err()); + // Reads on the CPU of what it writes: behind it, not ahead of it. + for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] { + assert!(plan(&[taken, read], 2).is_err(), "{read:?} behind"); + assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead"); + } + // Also of what is taken along. + assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2).is_err()); + // Into itself, and copies without stage 2. + assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err()); + assert!(plan(&[taken], 1).is_err()); + assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err()); + } + + #[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( + true, + &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)], + ); + // A level behind it, of what it wrote. + record(false, &own.list.list, &own.between, &[(&b, 77, 2048, 7)], &[(&b, 1077, 2048, 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[1077..1084], 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; + // Without it (`TEST_UNWATCHED=1`) the title's bytes cannot be put in + // under a flight's writes: the flights that declared them are waited + // for. + let write_watch = if std::env::var_os("TEST_UNWATCHED").is_some() { 0 } else { 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; + } + // Thousands of runs of bytes of its own. + for b in title[1_700_000..1_708_000].iter_mut().step_by(2) { + *b = 1 + round as u8; + } + // 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.defer_copy((start + HALF + 10_000) as *mut u8, (start + 1_700_000) as *const u8, 8000); + // What depends on them: a copy of the first copy, upload memory + // filled from that, and the first one's bytes copied over. + b.defer_copy((start + 1_500_000) as *mut u8, (start + HALF + 600) as *const u8, 700); + let (staging, staged) = b.upload(host, 4096).unwrap(); + b.defer_fill_buffer(&staging, staged, (start + 1_500_100) as *const u8, 500); + b.defer_copy((start + HALF + 300) as *mut u8, (start + 8000) as *const u8, 64); + 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}"); + // (The copy over the first one's bytes came last.) + let mut over = wanted[1..1501].to_vec(); + over[200..264].fill(0); + assert!(title[HALF + 100..HALF + 1600] == over[..], "the copy to the other buffer, round {round}"); + assert!(title[1_500_000..1_500_700] == wanted[501..1201], "the copy behind a copy, round {round}"); + // SAFETY: the mapping, which the flight wrote and has landed. + let staged = unsafe { std::slice::from_raw_parts(staged, 500) }; + assert!(staged == &wanted[601..1101], "the fill behind it, 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] == over[..], "the copy of the copy, round {round}"); + assert!(title[HALF..HALF + 100].iter().all(|&x| x == 0)); + assert!(title[HALF + 1600..HALF + 10_000].iter().all(|&x| x == 0)); + assert!(title[HALF + 18_000..].iter().all(|&x| x == 0)); + let runs = &title[HALF + 10_000..HALF + 18_000]; + assert!(runs.chunks(2).all(|b| b == [1 + round as u8, 0]), "the runs, round {round}"); + 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 48 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed)); + eprintln!("settles for title memory under shader writes: {}", LATE_STATS[WHY_STALE].load(Ordering::Relaxed)); + assert!(done >= 20, "only {done} copies were done on the card"); + } +} diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index b8128ea..ee50568 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -17,6 +17,10 @@ //! execution was followed by a move of the scratch buffer back to the //! common state, which drivers may treat as a full wait. //! +//! The executions of one record without a count buffer (all the title's) +//! are clamped in batches ([`batch`], `VICTORY_INDIRECT_BATCH`): the rest of +//! this is for the others. +//! //! When a count buffer is given, threads at or past `min(max, count)` return //! immediately without charging the list's budget or reading uninitialized //! tail slots. Each list has a budget (2^27 vertex instances or threads, @@ -36,6 +40,8 @@ use windows::core::s; use crate::host::{HostList, host, transition}; +pub(crate) mod batch; + const SOURCE: &str = r#" #define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" cbuffer Record : register(b0) { @@ -478,6 +484,70 @@ fn record_clamp_as( true } +/// The batched clamp's pipeline ([`batch`]). +fn batch_clamp() -> Option<&'static Clamp> { + static CLAMP: std::sync::OnceLock> = std::sync::OnceLock::new(); + CLAMP + .get_or_init(|| { + let made = host().ok_or_else(windows::core::Error::empty).and_then(|h| make_from(&h.device, batch::SOURCE)); + match made { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no batched argument clamp: records are clamped one at a time"); + None + } + } + }) + .as_ref() +} + +/// Opens a batch in `list` ([`batch`]): a pass that clamps the records of +/// the executions recorded after it, of `source` (a host copy's number and +/// buffer) and of the `recent` ones after it. The table to add them to, +/// and the scratch buffer its places are in. Replaces the list's compute +/// root signature and pipeline (callers bind theirs after). `None` if the +/// clamp is not available. +pub(crate) fn open_batch( + list: &HostList, + source: (u64, &ID3D12Resource), + recent: &[(u64, ID3D12Resource)], +) -> Option<(batch::Table, ID3D12Resource)> { + let c = batch_clamp()?; + let budget = list.budget()?; + let (jobs, at) = list.scratch(batch::TABLE)?; + let (dst, base, before) = list.batch_place()?; + let gpu = |b: &ID3D12Resource| { + // SAFETY: a live buffer. + Some(unsafe { b.GetGPUVirtualAddress() }).filter(|at| at.is_multiple_of(4)) + }; + // A source there is none of is the first again, which no job names. + let mut ids = [0u64; batch::SOURCES]; + let mut sources = [gpu(source.1)?; batch::SOURCES]; + ids[0] = source.0; + let others = recent.iter().filter(|r| r.0 != source.0).take(batch::SOURCES - 1); + for (i, (id, buffer)) in others.enumerate() { + if let Some(at) = gpu(buffer) { + // Bound, and read only if a job names it: kept alive like the + // copies draws read (`Shadow::refresh`). + list.keep(buffer); + (ids[i + 1], sources[i + 1]) = (*id, at); + } + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + batch::record(c, &list.list, (&dst, before), budget, sources, jobs); + // SAFETY: the list's own upload memory of that many bytes, 256-byte + // aligned, until it is reset. + Some((unsafe { batch::Table::new(at, base, ids) }, dst)) +} + +/// The batched clamp's root signature and pipeline on `device`, for the +/// replayer. +#[cfg(feature = "diagnostics")] +pub(crate) fn batch_for(device: &ID3D12Device) -> windows::core::Result<(ID3D12RootSignature, ID3D12PipelineState)> { + make_from(device, batch::SOURCE).map(|c| (c.root, c.pso)) +} + fn uav_barrier() -> D3D12_RESOURCE_BARRIER { D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, @@ -538,14 +608,23 @@ void main() { impl WarpHarness { fn new() -> Option { + Self::on(true) + } + + /// On the software adapter, or the first one (for measurements). + fn on(software: bool) -> Option { let turn = warp_turn(); - // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + // 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; @@ -775,7 +854,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. @@ -805,6 +884,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() { @@ -1667,8 +1801,921 @@ void main() { assert_eq!(hits, expected, "every record of both windows runs once"); } } + + /// A command signature of one argument of `kind` on `device`. + fn one_argument(device: &ID3D12Device, kind: u32, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + device.CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig).unwrap(); + } + sig.unwrap() + } + + /// What a batch's table says of records added to it: one job per + /// record, charged for every execution that reads it, and none for what + /// the pass cannot read. + #[test] + fn batch_tables() { + use batch::{JOBS, SLOT, TABLE, TIMES, Table, job}; + let mut memory = vec![0xffff_ffffu32; TABLE as usize / 4 + 1]; + // SAFETY: the vector holds the table and outlives its use. + let mut t = unsafe { Table::new(memory.as_mut_ptr().cast(), 4096, [7, 9, 0, 0]) }; + assert_eq!(t.place(7, 64, 10), Some(4096)); + assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT))); + assert_eq!(t.place(7, 64, 2), Some(4096 + 2 * u64::from(SLOT)), "another kind is another record"); + // The same record again: the same place, charged twice. + assert_eq!(t.place(9, 64, 10), Some(4096 + u64::from(SLOT))); + assert_eq!(&memory[..4], [3, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff]); + assert_eq!(memory[4..8], [job(0, 10, 1), 64, 4096, 0]); + assert_eq!(memory[8..12], [job(1, 10, 2), 64, 4096 + SLOT, 0]); + assert_eq!(job(1, 10, 2), 1 | 10 << 4 | 3 << 8 | 2 << 16); + // Not a copy of the pass, not on 4 bytes, past 32 bits, not a kind. + for (id, offset, kind) in [(8, 64, 10), (7, 66, 10), (7, 1 << 32, 10), (7, u64::from(u32::MAX) & !3, 10), (7, 64, 3)] { + assert_eq!(t.place(id, offset, kind), None); + } + // Read more often than one job may be charged for: another job. + for _ in 1..TIMES { + assert_eq!(t.place(7, 64, 10), Some(4096)); + } + assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT))); + assert_eq!(t.place(7, 64, 10), Some(4096 + 3 * u64::from(SLOT))); + for i in 4..u64::from(JOBS) { + assert_eq!(t.place(7, 1024 + 16 * i, 0), Some(4096 + i * u64::from(SLOT))); + } + assert_eq!(t.place(7, 1024, 1), None, "full"); + assert_eq!(t.place(7, 1024 + 16 * 5, 0), Some(4096 + 5 * u64::from(SLOT))); + assert_eq!((memory[0], memory[TABLE as usize / 4]), (JOBS, 0xffff_ffff)); + } + + /// A batch clamps records exactly as the clamp of one execution does, of + /// any kind, sensible or not; they are added to its table after the pass + /// was recorded; it charges each as often as it is read. + #[test] + fn warp_batch_clamps_as_the_clamp_of_one_does() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); + let kinds = [0u32, 1, 2, 10]; + let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX]; + // Every kind with many records, in two sources. + let mut records: Vec<(u32, [u32; 5])> = Vec::new(); + for kind in kinds { + for (i, a) in values.into_iter().enumerate() { + for (k, b) in values.into_iter().enumerate() { + records.push((kind, [a, b, values[(i * 3 + k) % 4], 77, 0xABCD])); + } + } + } + // In passes of so few that the budget holds whatever one asks for, + // and one pass of them all, which it does not. + let (src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10); + let (_other, other_ptr, other_gpu) = warp.shared_buffer(64 << 10); + for (i, (_, words)) in records.iter().enumerate() { + for (w, word) in words.iter().enumerate() { + // SAFETY: 400 records of 32 bytes in 64 KiB. + unsafe { + src_ptr.cast::().add(i * 8 + w).write_volatile(*word); + other_ptr.cast::().add(i * 8 + w).write_volatile(*word); + } + } + } + let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (back, back_ptr, _) = warp.shared_buffer(64 << 10); + let dst = warp.default_uav(64 << 10); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE); + for (i, (kind, _)) in records.iter().enumerate().step_by(3) { + let offset = i as u64 * 32; + let words = batch::words(*kind).unwrap(); + let stride = words * 4; + let read = |p: *mut u8| -> Vec { + // SAFETY: the mapping holds more. + (0..words as usize).map(|w| unsafe { p.cast::().add(w).read_volatile() }).collect() + }; + let mut seen = Vec::new(); + for batched in [false, true] { + // SAFETY: mapped buffers; nothing runs. + unsafe { std::ptr::write_bytes(budget_ptr, 0, 256) }; + if batched { + batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu, other_gpu, src_gpu, src_gpu], table_gpu); + // SAFETY: the mapped table; the list has not run. + let mut table = unsafe { batch::Table::new(table_ptr, 0, [1, 2, 0, 0]) }; + assert_eq!(table.place(1 + i as u64 % 2, offset, *kind), Some(0)); + } else { + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src, offset), + None, + (*kind, stride, 1), + false, + )); + } + // SAFETY: an open list; the records are readable as arguments. + unsafe { + warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + warp.list.CopyBufferRegion(&back, 0, &dst, 0, u64::from(stride)); + warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + } + warp.submit_and_wait(); + // SAFETY: the list has run; mapped words. + let budget: Vec = (0..3).map(|k| unsafe { budget_ptr.cast::().add(k).read_volatile() }).collect(); + seen.push((read(back_ptr), budget)); + } + // (A mesh record that asks for nothing notes nothing.) + assert_eq!(seen[0], seen[1], "record {i} of kind {kind}: {:?}", records[i].1); + } + } + + /// Records past the list's budget come out empty, and one read by many + /// executions is charged for each. + #[test] + fn warp_batch_charges_every_execution() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP"); + const BUDGET: u32 = 1 << 27; + // 2^26 vertices each, as much as a draw is let run: two fill it. + for (times, records, filled) in [(1u32, 3u64, 2usize), (2, 1, 1), (1, 1, 1), (3, 1, 0)] { + let (_src, src_ptr, src_gpu) = warp.shared_buffer(64 << 10); + let (_budget, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (back, back_ptr, _) = warp.shared_buffer(1024); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(batch::TABLE); + let dst = warp.default_uav(64 << 10); + batch::record(&pass, &warp.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu); + // SAFETY: mapped buffers, which the list has not read yet. + let mut table = unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + for r in 0..records { + for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() { + src_ptr.cast::().add(r as usize * 4 + w).write_volatile(word); + } + } + batch::Table::new(table_ptr, 0, [1, 0, 0, 0]) + }; + for _ in 0..times { + for r in 0..records { + assert_eq!(table.place(1, r * 16, 0), Some(r * u64::from(batch::SLOT))); + } + } + // SAFETY: an open list; the records are readable as arguments. + unsafe { + warp.list.ResourceBarrier(&[transition(&dst, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + warp.list.CopyBufferRegion(&back, 0, &dst, 0, 256); + } + warp.submit_and_wait(); + // SAFETY: the list has run; mapped words. + let (spent, out): (u32, Vec) = unsafe { + ( + budget_ptr.cast::().read_volatile(), + (0..records as usize).map(|r| back_ptr.cast::().add(r * batch::SLOT as usize / 4).read_volatile()).collect(), + ) + }; + assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}"); + assert!(out.iter().all(|&v| v == 0 || v == 1 << 24)); + assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32)); + } + } + + /// Two batches through a host list, twice (the second recording finds + /// the scratch buffer as the first one's end left it): executions with + /// nothing between them read what they asked for, of two source buffers, + /// the second batch while the first one's places are still read. With + /// the debug layer on no barrier names a state the buffer is not in. + #[test] + fn host_list_batches() { + let Some(host) = super::host() else { + return; + }; + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + let signature = one_argument(&host.device, 2, 12); + let mut sources = Vec::new(); + for first in [1u32, 100] { + let Some((buffer, ptr)) = host.shared_buffer(1024) else { + return; + }; + for i in 0..16u32 { + for (w, word) in [first + i, 1, 1].into_iter().enumerate() { + // SAFETY: inside the mapping. + unsafe { ptr.cast::().add(i as usize * 8 + w).write_volatile(word) }; + } + } + sources.push(buffer); + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for _ in 0..2 { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + let mut expected = 0; + // More batches than one scratch buffer holds. + for k in 0..12u32 { + let (mut table, scratch) = + open_batch(&list, (1, &sources[0]), &[(1, sources[0].clone()), (2, sources[1].clone())]).unwrap(); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + } + for (id, record) in [(1u64, 3 + k % 4), (2, 5), (1, 0), (2, 5)] { + let at = table.place(id, u64::from(record) * 32, 2).unwrap(); + // SAFETY: as above. + unsafe { list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0) }; + expected += record + if id == 1 { 1 } else { 100 }; + } + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, expected, "every execution runs what it asked for"); + } + } + + /// What clamps of a frame cost on the card one by one and in batches + /// (ignored: a measurement): 2,355 executions of an empty dispatch, in + /// 49 lists' worth of runs, as in the captured frame. + #[test] + #[ignore] + fn batch_costs() { + let Some(mut gpu) = WarpHarness::on(false) else { + return; + }; + const EXECUTIONS: u32 = 2355; + let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile"); + let sig = gpu.signature(2, 12); + let groups: Vec = vec![1; 2048]; + let src = dispatch_records(&gpu, &groups, 32); + // SAFETY: a live buffer. + let src_gpu = unsafe { src.GetGPUVirtualAddress() }; + let budget = gpu.default_uav(256); + let hits = gpu.default_uav(256); + // SAFETY: live buffers. + let (budget_gpu, hits_gpu) = unsafe { (budget.GetGPUVirtualAddress(), hits.GetGPUVirtualAddress()) }; + let (_tables, tables_ptr, tables_gpu) = gpu.shared_buffer(batch::TABLE * 2400); + let dst = gpu.default_uav(4 << 20); + for run in [0u32, 2355 / 49, 5, 1] { + let mut best = f64::MAX; + for _ in 0..6 { + let mut state = D3D12_RESOURCE_STATE_COMMON; + let mut table = batch::Table::default(); + for i in 0..EXECUTIONS { + if run == 0 { + assert!(record_clamp_as(&gpu.clamp, &gpu.list, (&dst, state), budget_gpu, (&src, u64::from(i % 2048) * 32), None, (2, 12, 1), false)); + } else if i % run == 0 { + let k = u64::from(i / run) * batch::TABLE; + batch::record(&pass, &gpu.list, (&dst, state), budget_gpu, [src_gpu; 4], tables_gpu + k); + // SAFETY: the mapped table; the list has not run. + table = unsafe { batch::Table::new(tables_ptr.add(k as usize), 0, [1, 0, 0, 0]) }; + } + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let at = if run == 0 { 0 } else { table.place(1, u64::from(i % 2048) * 32, 2).unwrap() }; + // SAFETY: an open list; live buffers. + unsafe { + if run == 0 || i % run == 0 { + gpu.list.SetComputeRootSignature(&gpu.worker.root); + gpu.list.SetPipelineState(&gpu.worker.pso); + gpu.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + } + gpu.list.ExecuteIndirect(&sig, 1, &dst, at, None, 0); + } + } + let t = std::time::Instant::now(); + gpu.submit_and_wait(); + best = best.min(t.elapsed().as_secs_f64() * 1e3); + } + let what = if run == 0 { "each clamped on its own".to_owned() } else { format!("a batch every {run}") }; + println!("{EXECUTIONS} indirect dispatches, {what}: {best:.2} ms"); + } + } } /// The benchmark of the clamp and its barriers (ignored by default). #[cfg(test)] mod bench; + +/// 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/indirect/batch.rs b/crates/victory-gpu/src/indirect/batch.rs new file mode 100644 index 0000000..1f65388 --- /dev/null +++ b/crates/victory-gpu/src/indirect/batch.rs @@ -0,0 +1,276 @@ +//! Clamps of many executions in one pass: the arguments of every indirect +//! execution between two points where they may change are bounded together, +//! at the first of them. +//! +//! The executions that come after it are not known yet when the pass is +//! recorded, so it reads what to clamp from a table of jobs in upload +//! memory, which the CPU goes on filling while the list is recorded: the +//! pass is as wide as the table and its threads past the count do nothing. +//! An execution that asks for a record already in the table (the title's +//! tile classes) reads the same clamped one. +//! +//! What the records charge the list's budget is as for records clamped +//! alone, times the executions that read them. + +use windows::Win32::Graphics::Direct3D12::*; + +use super::{Clamp, uav_barrier}; +use crate::host::transition; + +/// The jobs of one pass. +pub(crate) const JOBS: u32 = 256; +/// The bytes of its table in upload memory: the count, then the jobs. +pub(crate) const TABLE: u64 = 16 + 16 * JOBS as u64; +/// The bytes of a clamped record's place in the scratch buffer. +pub(crate) const SLOT: u32 = 32; +/// The source buffers a pass can read. +pub(crate) const SOURCES: usize = 4; +/// The most executions charged by one job: the most a record costs (2^26) +/// as often still fits 32 bits. +pub(crate) const TIMES: u32 = 31; + +pub(crate) const SOURCE: &str = r#" +#define RS "SRV(t0), SRV(t1), SRV(t2), SRV(t3), SRV(t4), UAV(u0), UAV(u1)" +ByteAddressBuffer src0 : register(t0); +ByteAddressBuffer src1 : register(t1); +ByteAddressBuffer src2 : register(t2); +ByteAddressBuffer src3 : register(t3); +// The count, 12 bytes of nothing, then per job: source (bits 0-1), kind +// (4-7), words (8-11) and the executions that read it (16-31); the +// record's offset in the source; its place in the scratch buffer; nothing. +ByteAddressBuffer jobs : register(t4); +RWByteAddressBuffer dst_args : register(u0); +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +static const uint GROUPS = 1u << 20; +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; +uint load(uint source, uint at) { + if (source == 0) return src0.Load(at); + if (source == 1) return src1.Load(at); + if (source == 2) return src2.Load(at); + return src3.Load(at); +} +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { + uint count = jobs.Load(0); + bool active = id.x < count; + uint4 job = uint4(0, 0, 0, 0); + uint record[5] = {0, 0, 0, 0, 0}; + uint cost = 0; + uint asked = 0; + uint kind = 0; + uint words = 0; + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + // As the clamp of one execution (`super::SOURCE`) bounds them. + if (active) { + job = jobs.Load4(16 + id.x * 16); + kind = (job.x >> 4) & 15; + words = min((job.x >> 8) & 15, 5); + for (uint w = 0; w < words; w++) { + record[w] = load(job.x & 3, job.y + w * 4); + } + if (kind <= 1) { + record[0] = min(record[0], 1u << 24); + record[1] = min(record[1], (1u << 26) / max(record[0], 1u)); + cost = record[0] * record[1]; + } else if (kind == 2) { + uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u)); + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + record[0] = g.x; + record[1] = g.y; + record[2] = g.z; + } else { + asked = record[0]; + record[0] = min(record[0], 65535u); + record[1] = min(record[1], 1u); + record[2] = min(record[2], 1u); + cost = record[0] * record[1] * record[2] * 128u; + } + cost *= job.x >> 16; + } + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind > 2) { + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); + } + uint first = id.x - gi; + uint n = count > first ? min(64u, count - first) : 0u; + if (gi == 0 && n > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = before; + for (uint j = 0; j < n; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + next = (BUDGET - next <= c) ? BUDGET : (next + c); + } + } + if (next == before) break; + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + uint at = before; + for (uint k = 0; k < n; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + } + fits[k] = fit; + } + } + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && n > 0 && all_asked > 0) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); + } + if (!active) { + return; + } + if (fits[gi] == 0) { + record[0] = 0; + record[1] = 0; + if (kind > 1) { + record[2] = 0; + } + } + for (uint s = 0; s < words; s++) { + dst_args.Store(job.z + s * 4, record[s]); + } +} +"#; + +/// The words of a record of `kind` (PC argument numbering). +pub(crate) fn words(kind: u32) -> Option { + super::min_stride(kind).map(|bytes| bytes / 4) +} + +/// A job's first word. +pub(crate) fn job(source: u32, kind: u32, times: u32) -> u32 { + source | (kind << 4) | (words(kind).unwrap_or(0) << 8) | (times << 16) +} + +/// The jobs of a pass as the CPU fills them ([`SOURCE`]), and where it +/// keeps which record is where. +#[derive(Default)] +pub(crate) struct Table { + /// The table in upload memory ([`TABLE`] bytes). + at: usize, + /// The place of the first clamped record in the scratch buffer. + base: u32, + /// The host copies it can read, by number ([`crate::shadow::Shadow::id`]; + /// 0: none). + sources: [u64; SOURCES], + /// How many executions each job is charged for so far. + times: Vec, + /// The job of a record (source, offset, kind). + known: std::collections::HashMap<(u32, u32, u32), u32>, +} + +impl Table { + /// A table at `at`, with no job yet. + /// + /// # Safety + /// `at` is [`TABLE`] bytes of mapped upload memory, 4-byte aligned, that + /// live until the list that reads them is recorded and is not run + /// before. + pub(crate) unsafe fn new(at: *mut u8, base: u32, sources: [u64; SOURCES]) -> Table { + // SAFETY: the caller's. + unsafe { at.cast::().write_volatile(0) }; + Table { at: at as usize, base, sources, ..Table::default() } + } + + /// The place in the scratch buffer of the record of `kind` at `offset` + /// of the host copy `id`, once the pass has run: a job of it is added if + /// there is none. `None` if the pass cannot read that copy or has no + /// room for another job. + pub(crate) fn place(&mut self, id: u64, offset: u64, kind: u32) -> Option { + let source = self.sources.iter().position(|&s| s == id)? as u32; + let offset = u32::try_from(offset).ok().filter(|o| o.is_multiple_of(4))?; + offset.checked_add(words(kind)? * 4)?; + let key = (source, offset, kind); + let table = self.at as *mut u32; + let place = |i: u32| u64::from(self.base + i * SLOT); + if let Some(&i) = self.known.get(&key) + && self.times[i as usize] < TIMES + { + self.times[i as usize] += 1; + // SAFETY: the job's own word of the table ([`Table::new`]). + unsafe { table.add(4 + 4 * i as usize).write_volatile(job(source, kind, self.times[i as usize])) }; + return Some(place(i)); + } + let i = self.times.len() as u32; + if i == JOBS { + return None; + } + self.times.push(1); + self.known.insert(key, i); + // SAFETY: inside the table: fewer than [`JOBS`] jobs before it. + unsafe { + let to = table.add(4 + 4 * i as usize); + to.write_volatile(job(source, kind, 1)); + to.add(1).write_volatile(offset); + to.add(2).write_volatile(self.base + i * SLOT); + to.add(3).write_volatile(0); + table.write_volatile(i + 1); + } + Some(place(i)) + } +} + +/// Records the pass over the table at `jobs` (a host address) into `dst`, +/// which is in state `before` and left in `INDIRECT_ARGUMENT`: after every +/// earlier shader write (the title's argument passes), before what reads +/// the clamped records. +pub(super) fn record( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + sources: [u64; SOURCES], + jobs: u64, +) { + let after = transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ); + // SAFETY: an open list; our root signature and pipeline; live buffers: + // the sources and the table are read in the common state (promoted). + unsafe { + l.ResourceBarrier(&[ + uav_barrier(), + transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + for (i, source) in sources.into_iter().enumerate() { + l.SetComputeRootShaderResourceView(i as u32, source); + } + l.SetComputeRootShaderResourceView(SOURCES as u32, jobs); + l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 1, dst.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView(SOURCES as u32 + 2, budget); + l.Dispatch(JOBS.div_ceil(64), 1, 1); + // Nothing else the pass writes is read before the next full wait + // (the budget, by the next pass): only the records have to be there. + l.ResourceBarrier(&[after]); + } +} diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index bcafed8..56a883b 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -269,9 +269,12 @@ struct Views { views: BTreeMap, /// Sections by handle: bytes, and whether made committed. sections: Vec<(usize, u64, bool)>, + /// Our own view of a whole section, by its handle (0: the host gave + /// none), made when first asked for ([`beside`]) and kept. + whole: Vec<(usize, usize)>, } -static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new() }); +static VIEWS: Mutex = Mutex::new(Views { views: BTreeMap::new(), sections: Vec::new(), whole: Vec::new() }); fn views() -> std::sync::MutexGuard<'static, Views> { VIEWS.lock().unwrap_or_else(|e| e.into_inner()) @@ -282,9 +285,28 @@ fn views() -> std::sync::MutexGuard<'static, Views> { pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { let mut v = views(); v.sections.retain(|s| s.0 != section); + // A handle's number given out again: the view was of the section that + // had it before (it stays mapped: someone may be writing through it). + v.whole.retain(|w| w.0 != section); v.sections.push((section, bytes, committed)); } +/// The runtime lets go of a section, and of its handle: no view the title +/// sees is of it any more, and [`beside`]'s view goes. +pub fn title_memory_section_gone(section: usize) { + let whole = { + let mut v = views(); + let at = v.whole.iter().position(|w| w.0 == section); + at.map(|i| v.whole.swap_remove(i).1) + }; + if let Some(base) = whole.filter(|&base| base != 0) { + // SAFETY: a view of ours. Who writes through it found the section + // in a view the title saw and holds off its unmapping + // (`crate::watch::title_memory_reading`), which came before this. + unsafe { mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: base as *mut c_void }) }; + } +} + /// The runtime mapped `[at, at + len)` as a view of `section` from /// `offset` on. Call after [`crate::title_memory_remapped`] of the range. pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { @@ -343,6 +365,36 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover { cover_in(&views().views, at, len) } +/// Another address of the title memory `[at, at + len)`, if it is a view of +/// the title's pages, all of it one run of a section: in a view of ours of +/// the whole section, which is never guarded (`crate::watch`) nor changed. +/// +/// The section's pages are reserved and the runtime commits each before it +/// shows it, which holds for every view of the section. The caller holds +/// `crate::watch::title_memory_reading`: until it lets go the title sees +/// the same pages at `at`. +pub(crate) fn beside(at: usize, len: usize) -> Option { + let mut v = views(); + let Cover::Run(section, offset) = cover_in(&v.views, at, len) else { + return None; + }; + let base = match v.whole.iter().find(|w| w.0 == section) { + Some(w) => w.1, + None => { + let &(_, bytes, _) = v.sections.iter().find(|s| s.0 == section)?; + // SAFETY: the whole of a section the runtime made; a view the + // title sees is of it, so its handle is open. + let base = unsafe { mem::MapViewOfFile(section as _, mem::FILE_MAP_WRITE, 0, 0, bytes as usize) }.Value as usize; + if base == 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "no view of the title's pages beside its own"); + } + v.whole.push((section, base)); + base + } + }; + (base != 0).then(|| base + offset as usize) +} + /// Whether `[at, at + len)` is private memory, all committed and /// read-write: what [`From::Part`] takes. One question to Windows (it /// walks the page tables to the end of the pages that share the first diff --git a/crates/victory-gpu/src/land.rs b/crates/victory-gpu/src/land.rs new file mode 100644 index 0000000..67ae9cd --- /dev/null +++ b/crates/victory-gpu/src/land.rs @@ -0,0 +1,556 @@ +//! What shaders wrote goes into title memory on a few threads +//! (`VICTORY_LAND`, on by default; `=0` merges piece by piece on the thread +//! that lands flights, as before). +//! +//! The relay's thread (`crate::host::relay`) was 58-60 ms of a 104 ms frame +//! landing (run record-1): some 1,500 pieces of 64 KiB, 98 MB, fetched from +//! copies in the card's memory, and each of them searched from both ends, +//! cleared room for, read from title memory, copied, merged and compared +//! again while it was put, one after the other; a lock and a protection +//! call to open the guard of each, and the kernel's fault on the first +//! write to each 4 KiB page of memory just made writable again. +//! +//! Here a piece is merged in one pass ([`crate::safecopy::merge`]): what +//! the card holds is compared with what it held 32 bytes at a time, title +//! memory is read only where they differ, just before the dwords that +//! change are stored. The pieces of a landing are cut into jobs for a few +//! threads kept for it ([`Pool`]). +//! +//! What stays in order: pieces in the same 64 KiB of title memory are in +//! one job, in the order they were given (two copies may hold the same +//! title memory); a landing's copies in the card's memory come before its +//! other copies; a landing is done, whole, before the title is told +//! anything and before the next one starts (`Host::relay_land`). +//! +//! With `VICTORY_LAND_BESIDE` (on by default) title memory that is a view of +//! the title's physical pages is written through a view of our own of the +//! same pages ([`crate::inplace::beside`]). The guards (`crate::watch`) are +//! read-only title views: they stay as they are, no protection changes, and +//! [`crate::watch::landed_beside`] notes the blocks written afterwards, so +//! that the next refresh takes them as before. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +/// The unit pieces are cut in (of title memory), and the guards' blocks. +pub(crate) const BLOCK: usize = 64 << 10; +/// The unit title memory is there or not in. +const PAGE: usize = 4096; +/// About this many bytes to a job. +const JOB: usize = 256 << 10; + +/// See the file. +pub(crate) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("VICTORY_LAND").is_none_or(|v| v != "0") && crate::safecopy::on() && crate::shadow::exact_back() + }) +} + +/// How many threads land, the relay's own counted (`VICTORY_LAND_THREADS`). +fn threads() -> usize { + static THREADS: OnceLock = OnceLock::new(); + *THREADS.get_or_init(|| { + let asked = std::env::var("VICTORY_LAND_THREADS").ok().and_then(|v| v.trim().parse().ok()); + asked.unwrap_or_else(|| std::thread::available_parallelism().map_or(2, |n| n.get() / 4).clamp(1, 4)).clamp(1, 16) + }) +} + +/// Whether views of the title's pages are written through one of ours. +fn beside_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_BESIDE").is_none_or(|v| v != "0")) +} + +/// Whether pieces an earlier fetch holds as they are now are left out +/// ([`Had`]; `VICTORY_LAND_SKIP=1`, off by default: counted either way). +pub(crate) fn skip_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LAND_SKIP").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line; microseconds first. +pub(crate) mod stat { + /// Which pieces to fetch; their list recorded and sent. + pub(crate) const GATHER: usize = 0; + /// Looking for what shaders wrote to copies in the PC's memory, the part + /// done while the fetch was on its way. + pub(crate) const SCAN_BESIDE: usize = 1; + /// The same, with nothing else to wait for. + pub(crate) const SCAN: usize = 2; + /// Merging what was fetched: until the last job is done, and the jobs' + /// time on all threads. + pub(crate) const CARD: usize = 3; + pub(crate) const CARD_ALL: usize = 4; + /// Merging what the scan found. + pub(crate) const BACK: usize = 5; + pub(crate) const BACK_ALL: usize = 6; + /// In the jobs: waiting for the lock against the title's bytes going in. + pub(crate) const LOCK: usize = 7; + /// In the jobs: guards opened before a write, or noted after one. + pub(crate) const NOTES: usize = 8; + /// The flights' ranges done with; reading back, resets; what the title + /// is told; the rest (the line's account). + pub(crate) const DONE: usize = 9; + pub(crate) const READ_BACKS: usize = 10; + pub(crate) const TOLD: usize = 11; + pub(crate) const REST: usize = 12; + /// Counts: pieces merged, those with a new byte, their 4 KiB pages, + /// those with a new byte, blocks of 32 bytes with a new byte, dwords put. + pub(crate) const PIECES: usize = 13; + pub(crate) const NEW_PIECES: usize = 14; + pub(crate) const PAGES: usize = 15; + pub(crate) const NEW_PAGES: usize = 16; + pub(crate) const NEW_BLOCKS: usize = 17; + pub(crate) const DWORDS: usize = 18; + /// Pieces put through a view of ours, through the title's; pages where + /// title memory was not there. + pub(crate) const BESIDE: usize = 19; + pub(crate) const DIRECT: usize = 20; + pub(crate) const MISSING: usize = 21; + /// Bytes asked for twice in a landing (fetched once); pieces and bytes + /// an earlier fetch held already. + pub(crate) const TWICE: usize = 22; + pub(crate) const HAD: usize = 23; + pub(crate) const HAD_BYTES: usize = 24; + /// Jobs. + pub(crate) const JOBS: usize = 25; + pub(crate) const COUNT: usize = 26; +} + +static STATS: [AtomicU64; stat::COUNT] = [const { AtomicU64::new(0) }; stat::COUNT]; + +pub(crate) fn count(which: usize, n: u64) { + STATS[which].fetch_add(n, Ordering::Relaxed); +} + +/// Adds the microseconds since `from` to `which`; now. +pub(crate) fn spent(which: usize, from: std::time::Instant) -> std::time::Instant { + let now = std::time::Instant::now(); + count(which, (now - from).as_micros() as u64); + now +} + +/// For the frame-rate line: where landing went, per frame. +pub(crate) fn log(frames: f64) { + let s: Vec = STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if s[stat::PIECES] == 0.0 && s[stat::REST] == 0.0 { + return; + } + let ms = |i: usize| s[i] / 1000.0; + let mb = |v: f64| v / (1 << 20) as f64; + tracing::info!( + "landing per frame (VICTORY_LAND={}, {} threads): which pieces to fetch {:.2} ms, then the fetches (the relay's line); \ + looking through copies in the PC's memory {:.2} ms beside them and {:.2} ms more; merging what was fetched {:.2} ms \ + ({:.2} ms on all threads, {:.0} jobs), merging the others {:.2} ms ({:.2} on all threads); of the threads' time \ + {:.2} ms waiting for the title's bytes going in, {:.2} ms opening or noting guards; then ranges done with {:.2} ms, \ + read-backs and lists {:.2}, the title told {:.2}, the rest {:.2}", + u8::from(on()), + threads(), + ms(stat::GATHER), + ms(stat::SCAN_BESIDE), + ms(stat::SCAN), + ms(stat::CARD), + ms(stat::CARD_ALL), + s[stat::JOBS], + ms(stat::BACK), + ms(stat::BACK_ALL), + ms(stat::LOCK), + ms(stat::NOTES), + ms(stat::DONE), + ms(stat::READ_BACKS), + ms(stat::TOLD), + ms(stat::REST), + ); + tracing::info!( + "landed per frame: {:.0} pieces, {:.0} with a new byte; of their {:.0} pages of 4 KiB {:.0} with a new byte ({:.1} MB), \ + {:.1} MB in blocks of 32 bytes with one, {:.2} MB put as dwords; {:.0} pieces through a view of ours \ + (VICTORY_LAND_BESIDE={}), {:.0} through the title's; {:.0} pages not there; asked for twice in a landing {:.1} MB; \ + held already by an earlier fetch {:.0} pieces {:.1} MB (VICTORY_LAND_SKIP={})", + s[stat::PIECES], + s[stat::NEW_PIECES], + s[stat::PAGES], + s[stat::NEW_PAGES], + mb(s[stat::NEW_PAGES] * PAGE as f64), + mb(s[stat::NEW_BLOCKS] * 32.0), + mb(s[stat::DWORDS] * 4.0), + s[stat::BESIDE], + u8::from(beside_on()), + s[stat::DIRECT], + s[stat::MISSING], + mb(s[stat::TWICE]), + s[stat::HAD], + mb(s[stat::HAD_BYTES]), + u8::from(skip_on()), + ); +} + +/// Threads kept for landing, and the work they are at. +struct Pool { + state: Mutex, + more: Condvar, + idle: Condvar, + /// One batch at a time. + turn: Mutex<()>, + threads: usize, +} + +struct State { + /// What to do with each number below `count`. + work: Option, + next: usize, + count: usize, + /// Helpers inside a call. + running: usize, + panicked: bool, +} + +#[derive(Clone, Copy)] +struct Work(*const (dyn Fn(usize) + Sync)); + +// SAFETY: the closure may be called from any thread (`Sync`), and +// `Pool::each` keeps it alive until no helper is inside a call. +unsafe impl Send for Work {} + +impl Pool { + fn state(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn new(threads: usize) -> &'static Pool { + let pool: &'static Pool = Box::leak(Box::new(Pool { + state: Mutex::new(State { work: None, next: 0, count: 0, running: 0, panicked: false }), + more: Condvar::new(), + idle: Condvar::new(), + turn: Mutex::new(()), + threads, + })); + for i in 1..threads { + // (A helper that is not there is only missed.) + let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || pool.help()); + } + pool + } + + fn help(&self) { + let mut state = self.state(); + loop { + let Some((work, i)) = take(&mut state) else { + state = self.more.wait(state).unwrap_or_else(|e| e.into_inner()); + continue; + }; + state.running += 1; + drop(state); + // SAFETY: counted in `running`, so `each` has not returned. + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*work.0)(i) })); + state = self.state(); + state.running -= 1; + state.panicked |= ran.is_err(); + if state.running == 0 { + self.idle.notify_all(); + } + } + } + + /// Calls `f` with every number below `count`, on the pool's threads and + /// this one, and returns when every call has. + fn each(&self, count: usize, f: &(dyn Fn(usize) + Sync)) { + if count < 2 || self.threads < 2 { + (0..count).for_each(f); + return; + } + let _turn = self.turn.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: the lifetime is left out only until this call returns, and + // it does not before no helper is inside `f` and none can enter. + let work = Work(unsafe { std::mem::transmute::<*const (dyn Fn(usize) + Sync + '_), *const (dyn Fn(usize) + Sync + 'static)>(f) }); + let mut state = self.state(); + (state.work, state.next, state.count, state.panicked) = (Some(work), 0, count, false); + drop(state); + if count > self.threads { + self.more.notify_all(); + } else { + (1..count).for_each(|_| self.more.notify_one()); + } + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + loop { + let Some((_, i)) = take(&mut self.state()) else { break }; + f(i); + } + })); + let mut state = self.state(); + // (After a panic here: nothing more is begun.) + state.work = None; + while state.running > 0 { + state = self.idle.wait(state).unwrap_or_else(|e| e.into_inner()); + } + let panicked = state.panicked; + drop(state); + if let Err(panic) = ran { + std::panic::resume_unwind(panic); + } + assert!(!panicked, "a job of landing panicked"); + } +} + +/// The next number of the batch, if there is one. +fn take(state: &mut State) -> Option<(Work, usize)> { + let work = state.work?; + if state.next >= state.count { + return None; + } + state.next += 1; + Some((work, state.next - 1)) +} + +/// [`Pool::each`] on the threads kept for landing. +pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) { + static POOL: OnceLock<&'static Pool> = OnceLock::new(); + POOL.get_or_init(|| Pool::new(threads())).each(count, f); +} + +/// A piece to land: the copy's number, the title address, its bytes. +pub(crate) type Piece = (u64, usize, usize); + +/// `pieces` in the order they are landed: by the 64 KiB block of title +/// memory they lie in, those in one block in the order given (each is +/// within one block). Where one copy alone has pieces in a block, those +/// that overlap or touch are one piece: a landing's flights declare parts +/// of the same memory, and what overlapped came down and was merged twice. +/// Each with the number of the piece given that it begins with. +pub(crate) fn ordered(pieces: &[Piece]) -> Vec<(usize, usize, usize)> { + let mut order: Vec = (0..pieces.len()).collect(); + order.sort_by_key(|&i| pieces[i].1 / BLOCK); + let mut out: Vec<(usize, usize, usize)> = Vec::with_capacity(order.len()); + for group in order.chunk_by(|&a, &b| pieces[a].1 / BLOCK == pieces[b].1 / BLOCK) { + let alone = group.len() > 1 && group.iter().all(|&i| pieces[i].0 == pieces[group[0]].0); + if !alone { + out.extend(group.iter().map(|&i| (i, pieces[i].1, pieces[i].2))); + continue; + } + let mut sorted = group.to_vec(); + sorted.sort_by_key(|&i| pieces[i].1); + let begun = out.len(); + for i in sorted { + let (_, at, len) = pieces[i]; + match out[begun..].last_mut() { + Some(last) if at <= last.1 + last.2 => { + let end = (last.1 + last.2).max(at + len); + count(stat::TWICE, (last.2 + len - (end - last.1)) as u64); + last.2 = end - last.1; + } + _ => out.push((i, at, len)), + } + } + } + out +} + +/// Pieces (title address, bytes; in [`ordered`]'s order) as jobs: runs of +/// about [`JOB`] bytes that end where a block ends. +pub(crate) fn jobs(pieces: &[(usize, usize)]) -> Vec> { + let mut out: Vec> = Vec::new(); + let (mut from, mut bytes) = (0, 0); + for (i, &(at, len)) in pieces.iter().enumerate() { + let new_block = i == 0 || pieces[i - 1].0 / BLOCK != at / BLOCK; + if bytes >= JOB && new_block { + out.push(from..i); + (from, bytes) = (i, 0); + } + bytes += len; + } + if from < pieces.len() { + out.push(from..pieces.len()); + } + out +} + +/// What earlier fetches brought, for as long as a flight they ran behind +/// has not landed: per fetch, the value the host's fence had been given +/// behind the last flight sent before it, and by copy (its number) and +/// piece the offsets it brought. +/// +/// A fetch on the drawing queue runs behind everything sent before it, so +/// it brings what those flights' shaders wrote too, and the merge of it put +/// that into title memory. Their own landings flag the same pieces and +/// fetched them again, to find every byte merged. A piece that a fetch held +/// whole, behind the flight that flags it, has nothing more of that flight. +/// (Bytes left out of that merge, the title's that went up behind the +/// fetch, went up behind that flight too, and stand over what it wrote.) +#[derive(Default)] +pub(crate) struct Had(Vec<(u64, std::collections::HashMap<(u64, usize), (usize, usize)>)>); + +impl Had { + /// Flights from the one behind which `fence` is signalled on are landed + /// next: what is of no use to them is dropped. + pub(crate) fn landing(&mut self, fence: u64) { + self.0.retain(|had| had.0 >= fence); + } + + /// A fetch that ran behind every flight up to `fence` brought (copy, + /// title address, bytes) `pieces`. They are merged before the next ask. + pub(crate) fn fetched(&mut self, fence: u64, pieces: impl Iterator) { + let mut all = std::collections::HashMap::new(); + for (copy, at, len) in pieces { + // (Two parts of a block that do not touch: the longer one.) + let had = all.entry((copy, at / BLOCK)).or_insert((at, at + len)); + if len > had.1 - had.0 { + *had = (at, at + len); + } + } + self.0.push((fence, all)); + } + + /// Whether a fetch behind the flight of `fence` brought all of the + /// piece. + pub(crate) fn holds(&self, fence: u64, (copy, at, len): Piece) -> bool { + self.0.iter().any(|(behind, all)| { + *behind >= fence && all.get(&(copy, at / BLOCK)).is_some_and(|had| had.0 <= at && at + len <= had.1) + }) + } +} + +/// What a job wrote beside the guards, to be noted ([`Notes::flush`]). +#[derive(Default)] +pub(crate) struct Notes { + /// Pages of 4 KiB, by number. + pages: Vec, + /// Per piece, from the first such page to the last: address, bytes. + spans: Vec<(usize, usize)>, +} + +impl Notes { + /// At the end of a job: what it wrote beside the guards is noted. + pub(crate) fn flush(&mut self) { + if self.pages.is_empty() { + return; + } + let noting = std::time::Instant::now(); + crate::watch::landed_beside(&self.pages, &self.spans); + self.pages.clear(); + self.spans.clear(); + spent(stat::NOTES, noting); + } +} + +/// Lands one piece: `parts` (offsets from and to) of the bytes at `now`, +/// which the card wrote, go into title memory from `title` on and into +/// `held` ([`crate::safecopy::merge`] says how, and what `take` is). The +/// piece lies in one 64 KiB block of title memory. Returns the bytes put. +/// +/// # Safety +/// `now` and `held` are ours from 0 to the last part's end, and nothing but +/// the card writes `now` there, nothing but this call `held`. +pub(crate) unsafe fn piece( + title: usize, + now: *const u8, + held: *mut u8, + parts: &[(usize, usize)], + take: bool, + notes: &mut Notes, +) -> u64 { + // SAFETY: the caller's. + unsafe { piece_at(title, now, held, parts, take, notes, beside_on()) } +} + +/// [`piece`], and whether a view of ours is looked for. +/// +/// # Safety +/// [`piece`]'s. +unsafe fn piece_at( + title: usize, + now: *const u8, + held: *mut u8, + parts: &[(usize, usize)], + take: bool, + notes: &mut Notes, + beside: bool, +) -> u64 { + let Some(end) = parts.last().map(|p| p.1) else { + return 0; + }; + // From here until the piece is put the runtime changes no mapping: our + // view's address stays where the title sees `title`. Not waited for: if + // a change is under way, the title's own address does. + let reading = beside.then(crate::watch::title_memory_reading_now).flatten(); + let beside = reading.as_ref().and_then(|_| crate::inplace::beside(title, end)); + count(stat::PIECES, 1); + count(if beside.is_some() { stat::BESIDE } else { stat::DIRECT }, 1); + // The pages that differ, before any is written: none, and the guard + // stays; else it is opened once for the piece. + let mut differing = [true; BLOCK / PAGE + 1]; + let base = title / PAGE; + if beside.is_none() { + drop(reading); + differing.fill(false); + for_pages(title, parts, |from, n| { + // SAFETY: the caller's. + if unsafe { crate::safecopy::differ(now.add(from), held.add(from), n) } { + differing[(title + from) / PAGE - base] = true; + } + }); + let Some(first) = differing.iter().position(|&d| d) else { + for_pages(title, parts, |_, _| count(stat::PAGES, 1)); + return 0; + }; + let last = differing.iter().rposition(|&d| d).unwrap_or(first); + let (from, to) = (((base + first) * PAGE).max(title), ((base + last + 1) * PAGE).min(title + end)); + let opening = std::time::Instant::now(); + crate::watch::landing(from, to - from); + spent(stat::NOTES, opening); + } + let into = beside.unwrap_or(title); + let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0); + let mut span: Option<(usize, usize)> = None; + for_pages(title, parts, |from, n| { + pages += 1; + if !differing[(title + from) / PAGE - base] { + return; + } + // SAFETY: the caller's; title memory, by an address that shows it + // (`beside`) or the title's own. + let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) }; + blocks += done.new; + dwords += done.dwords; + missing += u64::from(!done.there); + if done.new > 0 { + new_pages += 1; + if beside.is_some() { + let page = (title + from) / PAGE; + // (Two parts in one page.) + if notes.pages.last() != Some(&page) { + notes.pages.push(page); + } + let s = span.get_or_insert((title + from, title + from + n)); + s.1 = title + from + n; + } + } + }); + if let Some((from, to)) = span { + notes.spans.push((from, to - from)); + } + count(stat::NEW_PIECES, u64::from(new_pages > 0)); + count(stat::PAGES, pages); + count(stat::NEW_PAGES, new_pages); + count(stat::NEW_BLOCKS, blocks); + count(stat::DWORDS, dwords); + count(stat::MISSING, missing); + crate::shadow::PUT[0].fetch_add(u64::from(dwords > 0), Ordering::Relaxed); + crate::shadow::PUT[2].fetch_add(dwords * 4, Ordering::Relaxed); + dwords * 4 +} + +/// `parts` of a piece that begins at `title`, cut where 4 KiB pages of title +/// memory end: offset and bytes. +fn for_pages(title: usize, parts: &[(usize, usize)], mut f: impl FnMut(usize, usize)) { + for &(from, to) in parts { + let mut at = from; + while at < to { + let n = (PAGE - (title + at) % PAGE).min(to - at); + f(at, n); + at += n; + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/victory-gpu/src/land/tests.rs b/crates/victory-gpu/src/land/tests.rs new file mode 100644 index 0000000..f2fef9f --- /dev/null +++ b/crates/victory-gpu/src/land/tests.rs @@ -0,0 +1,433 @@ +use super::*; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize}; +use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, PAGE_READWRITE}; + +struct Random(u64); + +impl Random { + fn next(&mut self) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 8) as usize + } +} + +/// View memory as the runtime makes the title's: a view of a section, noted +/// as it notes it. Kept: the journal of what was written (`crate::watch`) +/// knows its addresses, which must not become another test's fresh memory. +struct Title { + at: usize, + len: usize, +} + +impl Title { + fn new(len: usize) -> Title { + // SAFETY: a pagefile section of our own and a view of it. + unsafe { + let section = + CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + assert!(!section.is_null()); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + assert_ne!(at, 0); + crate::inplace::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::inplace::title_memory_view(at, len, section as usize, 0); + Title { at, len } + } + } + + fn bytes(&self) -> &[u8] { + // SAFETY: the view. + unsafe { std::slice::from_raw_parts(self.at as *const u8, self.len) } + } +} + +/// Every number once, whatever the count and the threads, batch after batch +/// and from several callers. +#[test] +fn the_pool_calls_every_number_once() { + for threads in [1usize, 2, 4, 7] { + let pool = Pool::new(threads); + std::thread::scope(|s| { + for _ in 0..3 { + s.spawn(|| { + for round in 0..300usize { + let count = round * 7 % 50; + let calls: Vec = (0..count).map(|_| AtomicUsize::new(0)).collect(); + pool.each(count, &|i| { + calls[i].fetch_add(1, Ordering::Relaxed); + }); + assert!(calls.iter().all(|c| c.load(Ordering::Relaxed) == 1)); + } + }); + } + }); + } +} + +/// A job that panics is told to the caller, and the pool goes on. +#[test] +fn a_panicking_job_reaches_the_caller() { + let pool = Pool::new(3); + for bad in 0..8usize { + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + pool.each(8, &|i| assert_ne!(i, bad, "(expected)")); + })); + assert!(ran.is_err()); + let n = AtomicUsize::new(0); + pool.each(20, &|i| { + n.fetch_add(i, Ordering::Relaxed); + }); + assert_eq!(n.into_inner(), 190); + } +} + +/// The order pieces are landed in holds every byte of every piece, under its +/// copy, and no other; blocks come in order, pieces of several copies in one +/// block stay in the order given, and jobs never cut a block. +#[test] +fn ordered_pieces_hold_the_same_bytes() { + let mut random = Random(99); + for _ in 0..400 { + let count = random.next() % 40; + let pieces: Vec = (0..count) + .map(|_| { + let block = random.next() % 12 * BLOCK; + let from = random.next() % BLOCK / 4 * 4; + let to = (from + 4 + random.next() % BLOCK / 4 * 4).min(BLOCK); + (random.next() as u64 % 3, block + from, to - from) + }) + .collect(); + let out = ordered(&pieces); + let bytes = |copy: u64, at: usize, all: &[Piece]| all.iter().any(|p| p.0 == copy && p.1 <= at && at < p.1 + p.2); + let landed: Vec = out.iter().map(|&(i, at, len)| (pieces[i].0, at, len)).collect(); + for copy in 0..3 { + for at in (0..12 * BLOCK).step_by(1024 * 4) { + assert_eq!(bytes(copy, at, &pieces), bytes(copy, at, &landed), "{pieces:?}"); + } + } + assert!(out.iter().all(|&(_, at, len)| len > 0 && at / BLOCK == (at + len - 1) / BLOCK)); + assert!(out.windows(2).all(|w| w[0].1 / BLOCK <= w[1].1 / BLOCK)); + for block in 0..12 { + let given: Vec = pieces.iter().copied().filter(|p| p.1 / BLOCK == block).collect(); + let here: Vec = landed.iter().copied().filter(|p| p.1 / BLOCK == block).collect(); + if given.iter().any(|p| p.0 != given[0].0) { + assert_eq!(here, given); + } else { + assert!(here.windows(2).all(|w| w[0].1 + w[0].2 < w[1].1), "apart, in order"); + } + } + let cut: Vec<(usize, usize)> = out.iter().map(|&(_, at, len)| (at, len)).collect(); + let jobs = jobs(&cut); + assert_eq!(jobs.iter().cloned().flatten().collect::>(), (0..cut.len()).collect::>()); + for w in jobs.windows(2) { + assert_ne!(cut[w[0].end - 1].0 / BLOCK, cut[w[1].start].0 / BLOCK); + } + } +} + +/// A piece is left out only if a fetch behind its own flight, or behind a +/// later one, brought all of it, and is forgotten when that flight is done. +#[test] +fn only_what_a_fetch_behind_the_flight_brought_is_left_out() { + let mut had = Had::default(); + had.fetched(7, [(1, BLOCK, BLOCK), (2, 0x100, 0x200)].into_iter()); + assert!(had.holds(6, (1, BLOCK, BLOCK)) && had.holds(7, (1, BLOCK + 64, 128))); + assert!(!had.holds(8, (1, BLOCK, BLOCK)), "the fetch ran ahead of flight 8"); + assert!(!had.holds(7, (3, BLOCK, BLOCK)) && !had.holds(7, (1, 0, 64))); + assert!(had.holds(7, (2, 0x100, 0x200)) && !had.holds(7, (2, 0x100, 0x204)) && !had.holds(7, (2, 0xfc, 8))); + had.landing(7); + assert!(had.holds(7, (1, BLOCK, BLOCK))); + had.landing(8); + assert!(had.0.is_empty()); +} + +/// A piece landed through either address holds what the merge of one thread +/// and one pass ([`crate::safecopy::merge`]) is to leave, with parts left +/// out, wherever it begins and ends. +#[test] +fn a_piece_lands_what_the_card_wrote_in_its_parts() { + assert!(crate::safecopy::on()); + let title = Title::new(2 * BLOCK); + let mut random = Random(5); + for round in 0..300usize { + let from = (random.next() % 5000) & !3; + let len = (random.next() % BLOCK).min(BLOCK - from).max(1); + let base: Vec = (0..len).map(|_| random.next() as u8).collect(); + let (mut now, mut held) = (base.clone(), base.clone()); + for _ in 0..random.next() % 60 { + let at = random.next() % len; + let n = (random.next() % 300).min(len - at); + for b in &mut now[at..at + n] { + *b = random.next() as u8; + } + } + let mut there = base.clone(); + for _ in 0..random.next() % 60 { + there[random.next() % len] ^= 0x11; + } + // Left out: some ranges, anywhere. + let mut parts = vec![(0, len)]; + for _ in 0..round % 4 { + let a = random.next() % len; + let b = (a + random.next() % 200).min(len); + parts = parts + .into_iter() + .flat_map(|(x, y)| [(x, y.min(a)), (x.max(b), y)]) + .filter(|(x, y)| x < y) + .collect(); + } + // SAFETY: inside the view; `kernel_will_write`'s rule for our own + // writes: the guard goes first. + unsafe { + crate::watch::writing(title.at, 2 * BLOCK); + std::ptr::copy_nonoverlapping(there.as_ptr(), (title.at + from) as *mut u8, len); + } + // Guarded, as after a refresh, in two rounds of three. + if round % 3 != 0 { + assert!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).is_some()); + assert_eq!(crate::watch::writes(title.at, title.at + 2 * BLOCK, true).map(|w| w.1.len() > 2), Some(false)); + } + let asked = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view").0; + let mut notes = Notes::default(); + // SAFETY: vectors of `len` bytes. + let put = unsafe { piece(title.at + from, now.as_ptr(), held.as_mut_ptr(), &parts, true, &mut notes) }; + notes.flush(); + let mut expect_held = base.clone(); + let mut expect = there.clone(); + for &(a, b) in &parts { + for i in a..b { + if now[i] != base[i] { + expect[i] = now[i]; + expect_held[i] = now[i]; + } + } + } + assert!(held == expect_held, "round {round}"); + assert!(title.bytes()[from..from + len] == expect[..], "round {round}"); + // Told: a refresh from now on takes the block again. + let (_, written) = crate::watch::writes(title.at, title.at + BLOCK, true).expect("a view"); + let told = written.iter().any(|&(page, at)| page == title.at / BLOCK && at > asked); + assert!(told || put == 0, "round {round}: {put} bytes, {written:?} after {asked}"); + } +} + +/// Landings on several threads beside title threads that write the same +/// blocks (other dwords) and a thread that refreshes a copy, guarding what +/// it takes: no write of the title's is lost or undone, all the card wrote +/// arrives, and once everything stands still the next refresh takes the +/// last of it (no note is lost). +#[test] +fn landings_beside_the_title_and_its_refreshes_lose_nothing() { + assert!(crate::safecopy::on()); + const BLOCKS: usize = 24; + const LEN: usize = BLOCKS * BLOCK; + let title = Title::new(LEN); + let at = title.at; + // SAFETY: committed, aligned, touched as atomics or by the landing's + // stores of whole dwords. + let dword = |i: usize| unsafe { &*((at + i * 4) as *const AtomicU32) }; + let stop = AtomicBool::new(false); + // The copy: its bytes, and per block the asking that last took it. + let copy: Mutex<(Vec, Vec)> = Mutex::new((vec![0; LEN], vec![0; BLOCKS])); + let refresh = || { + let mut copy = copy.lock().unwrap_or_else(|e| e.into_inner()); + let (now, written) = crate::watch::writes(at, at + LEN, true).expect("a view"); + let (bytes, taken) = &mut *copy; + for block in 0..BLOCKS { + let write = written.iter().find(|w| w.0 == at / BLOCK + block).map_or(0, |w| w.1); + if taken[block] == 0 || write > taken[block] { + taken[block] = now; + let part = &mut bytes[block * BLOCK..(block + 1) * BLOCK]; + // SAFETY: inside the view; whoever writes it meanwhile is + // noted, and the block taken again. + assert!(unsafe { crate::safecopy::copy(part.as_mut_ptr(), (at + block * BLOCK) as *const u8, BLOCK) }); + } + } + }; + let mut held = vec![0u8; LEN]; + std::thread::scope(|s| { + let writers: Vec<_> = (0..3usize) + .map(|w| { + let stop = &stop; + s.spawn(move || { + let mut value = 1u32; + while !stop.load(Ordering::Relaxed) { + // Its own dwords, in every other block (in the rest + // only landings change anything). + for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) { + assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone"); + } + value += 1; + } + value - 1 + }) + }) + .collect(); + s.spawn(|| { + while !stop.load(Ordering::Relaxed) { + refresh(); + } + }); + let mut random = Random(77); + for round in 1..250u32 { + // The card's dwords: every fourth, from the third on, in some + // pages of some blocks. + let mut now = held.clone(); + for _ in 0..60 { + let page = random.next() % (LEN / PAGE); + for i in (page * 1024 + 3..(page + 1) * 1024).step_by(4) { + now[i * 4..i * 4 + 4].copy_from_slice(&(round * 4096 + i as u32).to_le_bytes()); + } + } + let pieces: Vec = (0..BLOCKS).map(|b| (1, at + b * BLOCK, BLOCK)).collect(); + let order = ordered(&pieces); + let cut: Vec<(usize, usize)> = order.iter().map(|&(_, at, len)| (at, len)).collect(); + let jobs = jobs(&cut); + let into = held.as_mut_ptr() as usize; + each(jobs.len(), &|j| { + let mut notes = Notes::default(); + for &(address, len) in &cut[jobs[j].clone()] { + let offset = address - at; + // SAFETY: each job its own pieces of the two vectors. + unsafe { + piece(address, now.as_ptr().add(offset), (into + offset) as *mut u8, &[(0, len)], true, &mut notes); + } + } + notes.flush(); + }); + assert!(held == now, "round {round}"); + for i in (3..LEN / 4).step_by(4 * 61) { + let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four")); + assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}"); + } + } + stop.store(true, Ordering::Relaxed); + for (w, writer) in writers.into_iter().enumerate() { + let last = writer.join().expect("nothing undone"); + for i in (w..LEN / 4).step_by(4 * 97).filter(|i| i * 4 / BLOCK % 2 == 0) { + assert_eq!(dword(i).load(Ordering::Relaxed), last); + } + } + }); + refresh(); + let copy = copy.into_inner().unwrap_or_else(|e| e.into_inner()); + assert!(copy.0 == title.bytes(), "a write was not told to the copy"); +} + +/// What a frame's landing costs (ignored: a measurement): 1,536 pieces of +/// 64 KiB, 96 MB, of a 174 MB heap of view memory in 15 landings, each block +/// guarded by a refresh before it; three quarters of the pages of a piece +/// with new bytes, every dword of them. As before, and here on one thread +/// and more, through the title's address and through a view of ours. +#[test] +#[ignore] +fn what_landing_costs() { + assert!(crate::safecopy::on()); + const HEAP: usize = 2784 * BLOCK; + const COUNT: usize = 1536; + let title = Title::new(HEAP); + let mut held = vec![0u8; HEAP]; + let mut card = vec![0u8; COUNT * BLOCK]; + let busy = AtomicBool::new(true); + // The pieces: runs of eight blocks, scattered. + let pieces: Vec = (0..COUNT).map(|i| (i / 8 * 1021 % (HEAP / BLOCK / 8)) * 8 + i % 8).collect(); + std::thread::scope(|s| { + // Other threads of the process at work (what a protection change + // has to reach). + for _ in 0..6 { + s.spawn(|| { + let mut v = vec![0u64; 1 << 14]; + while busy.load(Ordering::Relaxed) { + for (i, x) in v.iter_mut().enumerate() { + *x = x.wrapping_mul(31).wrapping_add(i as u64); + } + } + }); + } + let mut round = 0u32; + // `guarded`: 2 as a refresh leaves them, 1 opened again before (that + // is timed beside), 0 not at all, as they were after the last. + let mut frame = |label: &str, dense: bool, guarded: u8, land: &dyn Fn(&[(usize, usize, usize)])| { + let mut best = f64::MAX; + let (mut guards, mut opening) = (f64::MAX, f64::MAX); + for _ in 0..5 { + round += 1; + for (k, &block) in pieces.iter().enumerate() { + for page in 0..16 { + if page % 4 == 3 { + continue; + } + let from = k * BLOCK + page * PAGE; + let step = if dense { 4 } else { 64 }; + // (The rest as held.) + let old = block * BLOCK + page * PAGE; + card[from..from + PAGE].copy_from_slice(&held[old..old + PAGE]); + for b in card[from..from + PAGE].chunks_exact_mut(step) { + b[..4].copy_from_slice(&round.wrapping_mul(0x0101_0101).to_le_bytes()); + } + } + let (a, b) = (k * BLOCK + 12 * PAGE, block * BLOCK + 12 * PAGE); + for page in [3usize, 7, 11, 15] { + let (a, b) = (a - 12 * PAGE + page * PAGE, b - 12 * PAGE + page * PAGE); + card[a..a + PAGE].copy_from_slice(&held[b..b + PAGE]); + } + } + let t = std::time::Instant::now(); + if guarded > 0 { + assert!(crate::watch::writes(title.at, title.at + HEAP, true).is_some()); + } + guards = guards.min(t.elapsed().as_secs_f64() * 1e3); + let t = std::time::Instant::now(); + if guarded == 1 { + pieces.iter().for_each(|block| crate::watch::landing(title.at + block * BLOCK, BLOCK)); + } + opening = opening.min(t.elapsed().as_secs_f64() * 1e3); + let all: Vec<(usize, usize, usize)> = pieces + .iter() + .enumerate() + .map(|(k, &block)| { + (title.at + block * BLOCK, card.as_ptr() as usize + k * BLOCK, held.as_mut_ptr() as usize + block * BLOCK) + }) + .collect(); + let t = std::time::Instant::now(); + for landing in all.chunks(COUNT / 15 + 1) { + land(landing); + } + best = best.min(t.elapsed().as_secs_f64() * 1e3); + } + println!("{label}: {best:.1} ms a frame to land; the guards before it {guards:.1} ms, opening them {opening:.1} ms"); + }; + for dense in [true, false] { + println!("{}", if dense { "every dword of three pages in four new" } else { "every sixteenth dword of them new" }); + let before: &dyn Fn(&[(usize, usize, usize)]) = &|landing| { + let mut scratch: Vec = Vec::new(); + for &(at, now, held) in landing { + crate::shadow::land_as_before(at, now, held, BLOCK, &mut scratch); + } + }; + frame("as before", dense, 2, before); + frame("as before, guards opened ahead", dense, 1, before); + frame("as before, nothing guarded", dense, 0, before); + for threads in [1usize, 2, 3, 4, 5, 6, 8] { + let pool = Pool::new(threads); + for beside in [false, true] { + frame(&format!("{threads} threads, beside {beside}"), dense, 2, &|landing| { + let cut: Vec<(usize, usize)> = landing.iter().map(|p| (p.0, BLOCK)).collect(); + let jobs = jobs(&cut); + pool.each(jobs.len(), &|j| { + let mut notes = Notes::default(); + for &(at, now, held) in &landing[jobs[j].clone()] { + // SAFETY: each its own bytes. + unsafe { piece_at(at, now as *const u8, held as *mut u8, &[(0, BLOCK)], true, &mut notes, beside) }; + } + notes.flush(); + }); + }); + } + } + } + busy.store(false, Ordering::Relaxed); + }); +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index ab6102e..faabc53 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -33,6 +33,8 @@ mod host; mod indirect; #[cfg(windows)] mod inplace; +#[cfg(windows)] +mod land; pub mod list; pub mod object; pub mod pipeline; @@ -65,7 +67,7 @@ mod watch; #[cfg(windows)] pub use host::on_failure; #[cfg(windows)] -pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use watch::{ title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 44c8965..02ad326 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -742,6 +742,9 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> if let Some(list) = host_list(this) && !barriers.is_null() { + if count > 0 { + with_state(this, |_, state| state.synced()); + } // SAFETY: the title passes `count` barriers. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; let mut host: Vec = barriers @@ -971,7 +974,7 @@ extern "system" fn copy_texture_region( }; // The list owns this mapped D3D12 upload buffer. Wine can report // its address as MEM_FREE, so use the host-upload path. - list.defer_fill(staging, data, bytes as usize); + list.defer_fill_buffer(&buffer, staging, data, bytes as usize); from.resource = buffer.as_raw().cast_const().cast(); from.footprint.offset = 0; #[cfg(feature = "diagnostics")] @@ -1396,7 +1399,14 @@ extern "system" fn set_pipeline(this: This, pipeline: This) { /// bottom of the pipe `(flags, control, address, size)`. Host lists order /// their own work and every submission is waited for, so there is nothing /// to do. -extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {} +/// (Arguments may be what earlier shaders wrote from here on: +/// `State::synced`.) +extern "system" fn sync(this: This, _flags: u32, _control: u32, _address: u64, _size: u64) { + #[cfg(windows)] + with_state(this, |_, state| state.synced()); + #[cfg(not(windows))] + let _ = this; +} /// Reset with console flags `(allocator, pipeline, flags)`; the flags only /// tune the console's command memory. @@ -1943,6 +1953,7 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { && let Some(list) = host_list(this) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + with_state(this, |_, state| state.synced()); // SAFETY: the same layout; no resource named. let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. 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/replay/edit.rs b/crates/victory-gpu/src/replay/edit.rs index 08184a3..a9c7ce3 100644 --- a/crates/victory-gpu/src/replay/edit.rs +++ b/crates/victory-gpu/src/replay/edit.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet}; -use super::wire::{ALL, Barrier, Cmd, NONE, Va}; +use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot}; /// The buffer the clamped arguments of all clamp passes lie in, in lists /// edited by [`clamps`]. @@ -298,6 +298,276 @@ pub fn skip_clamps(cmds: Vec, clamps: &[Clamp]) -> Vec { out } +/// The root signature, pipeline and table of the batched clamp +/// (`crate::indirect::batch`), and the scratch buffer it writes in the +/// first list of the frame (the next lists' are the ids before it), in lists +/// edited by [`batch_clamps`]. +pub const BATCH_ROOT: u32 = u32::MAX - 2; +pub const BATCH: u32 = u32::MAX - 3; +pub const BATCH_JOBS: u32 = u32::MAX - 4; +pub const BATCH_SCRATCH: u32 = u32::MAX - 16; + +/// What [`batch_clamps`] did to a list. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Batched { + /// Clamp passes before; after; the records the latter clamp. + pub clamps: u32, + pub batches: u32, + pub jobs: u32, + /// The bytes of the scratch buffer. + pub scratch: u64, +} + +/// A clamp batch being filled by [`batch_clamps`]. +struct Batch { + /// Where its table is in the jobs, and its root views in the list. + table: usize, + at: usize, + sources: Vec, + /// By source, offset and kind: the job, and how often it is read. + known: HashMap<(u32, u64, u32), (u32, u32)>, + n: u32, + base: u64, +} + +/// The list with its clamps done in batches, as `crate::draw` does with +/// `VICTORY_INDIRECT_BATCH`: one pass at the first execution after a +/// point where arguments may have changed (a wait for shader writes, with +/// dispatches since the batch before it; or a draw, with dispatches since +/// the last wait). `careful`: before indirect dispatches too, with +/// dispatches since the last wait. `compute`: the pipelines that are compute +/// ones. The tables go to `jobs` (the contents of [`BATCH_JOBS`]). +pub fn batch_clamps( + cmds: Vec, + psos: &HashSet, + compute: &HashSet, + scratch: u32, + careful: bool, + jobs: &mut Vec, +) -> (Vec, Batched) { + use crate::indirect::batch::{JOBS, SLOT, SOURCES, TIMES, job}; + const DISPATCH: u32 = 2; + let mut done = Batched::default(); + let scratches: HashSet = { + let mut next = 0; + let found = find_clamps(&cmds, psos, &mut next); + found.iter().map(|c| c.scratch).collect() + }; + if scratches.is_empty() { + return (cmds, done); + } + let of_clamp = + |b: &Barrier| matches!(b, Barrier::Transition { res, .. } if scratches.contains(res)); + let moved = |before, after| Barrier::Transition { + flags: 0, + res: scratch, + sub: ALL, + before, + after, + }; + // What the last clamp into a scratch buffer clamped: source, offset, + // kind. + let mut clamps: HashMap = HashMap::new(); + let (mut bound, mut constants, mut views) = (NONE, [0u32; 6], [(NONE, 0u64); 5]); + let mut out: Vec = Vec::with_capacity(cmds.len()); + let mut open: Option = None; + let (mut written, mut dirty, mut readable) = (true, true, false); + let mut cmds = cmds.into_iter().peekable(); + while let Some(c) = cmds.next() { + match &c { + // A clamp's own commands: its root signature and all it sets. + Cmd::RootSignature { + graphics: false, .. + } if matches!(cmds.peek(), Some(Cmd::Pipeline { pso }) if psos.contains(pso)) => {} + Cmd::Pipeline { pso } => { + bound = *pso; + if !psos.contains(pso) { + out.push(c); + } + } + Cmd::Constants { + graphics: false, + values, + offset, + .. + } if psos.contains(&bound) => { + for (i, v) in values.iter().enumerate() { + if let Some(c) = constants.get_mut(*offset as usize + i) { + *c = *v; + } + } + } + Cmd::RootView { + graphics: false, + param, + va: Va::At { res, offset }, + .. + } if psos.contains(&bound) => { + if let Some(v) = views.get_mut(*param as usize) { + *v = (*res, *offset); + } + } + Cmd::Dispatch { .. } if psos.contains(&bound) => { + done.clamps += 1; + let (source, offset) = views[1]; + clamps.insert( + views[3].0, + (source, offset + u64::from(constants[3]), constants[0]), + ); + // What it was clamped for follows: a batch is open by then. + let full = + |o: &Batch| !o.sources.contains(&source) && o.sources.len() == SOURCES; + if dirty && (constants[0] != DISPATCH || careful) || open.as_ref().is_some_and(full) + { + open = None; + } + if open.is_some() { + continue; + } + done.batches += 1; + let table = jobs.len(); + jobs.resize(table + 16 + 16 * 2048, 0); + out.push(Cmd::Barriers { + all: vec![ + Barrier::Uav { + flags: 0, + res: NONE, + }, + moved(if readable { INDIRECT_ARGUMENT } else { 0 }, UNORDERED_ACCESS), + ], + }); + readable = true; + out.push(Cmd::RootSignature { + graphics: false, + root: BATCH_ROOT, + }); + out.push(Cmd::Pipeline { pso: BATCH }); + let at = out.len(); + let mut view = |kind, param: usize, res, offset| { + out.push(Cmd::RootView { + graphics: false, + kind, + param: param as u32, + va: Va::At { res, offset }, + }); + }; + for i in 0..SOURCES { + view(slot::SRV, i, source, 0); + } + view(slot::SRV, SOURCES, BATCH_JOBS, table as u64); + view(slot::UAV, SOURCES + 1, scratch, 0); + view(slot::UAV, SOURCES + 2, views[4].0, views[4].1); + out.push(Cmd::Dispatch { + groups: [JOBS.div_ceil(64), 1, 1], + }); + out.push(Cmd::Barriers { + all: vec![moved(UNORDERED_ACCESS, INDIRECT_ARGUMENT)], + }); + open = Some(Batch { + table, + at, + sources: Vec::new(), + known: HashMap::new(), + n: 0, + base: done.scratch, + }); + (written, dirty) = (false, false); + } + Cmd::Barriers { all } => { + if all.iter().any(of_clamp) { + continue; + } + let waits = |b: &Barrier| matches!(b, Barrier::Uav { res: NONE, .. }); + if all.iter().any(waits) { + if written { + open = None; + } + dirty = false; + } + out.push(c); + } + Cmd::Indirect { + signature, + most, + args, + at, + count, + count_at, + } if clamps.contains_key(args) => { + let (source, offset, kind) = clamps.get(args).copied().unwrap_or_default(); + let Some(o) = &mut open else { + // Not clamped by any batch: left out, which shows. + continue; + }; + let slot = match o.sources.iter().position(|&s| s == source) { + Some(i) => i, + None => { + o.sources.push(source); + let i = o.sources.len() - 1; + if let Some(Cmd::RootView { + va: Va::At { res, .. }, + .. + }) = out.get_mut(o.at + i) + { + *res = source; + } + i + } + }; + let offset = offset + at; + let entry = o.known.entry((source, offset, kind)).or_insert((o.n, 0)); + entry.1 += 1; + let (i, times) = *entry; + if i == o.n { + o.n += 1; + done.jobs += 1; + done.scratch = o.base + u64::from(o.n * SLOT); + // Wider than the live pass where its table is longer. + if let Some(Cmd::Dispatch { groups }) = out.get_mut(o.at + SOURCES + 3) { + groups[0] = groups[0].max(o.n.div_ceil(64)); + } + } + let place = o.base + u64::from(i * SLOT); + let words = [ + job(slot as u32, kind, times.min(TIMES)), + offset as u32, + place as u32, + 0, + ]; + let mut put = |at: usize, w: u32| { + jobs[o.table + at..o.table + at + 4].copy_from_slice(&w.to_le_bytes()); + }; + for (k, w) in words.into_iter().enumerate() { + put(16 + 16 * i as usize + 4 * k, w); + } + put(0, o.n); + out.push(Cmd::Indirect { + signature: *signature, + most: *most, + args: scratch, + at: place, + count: *count, + count_at: *count_at, + }); + if compute.contains(&bound) { + (written, dirty) = (true, true); + } + } + Cmd::Dispatch { .. } => { + (written, dirty) = (true, true); + out.push(c); + } + _ => out.push(c), + } + } + if readable { + out.push(Cmd::Barriers { + all: vec![moved(INDIRECT_ARGUMENT, 0)], + }); + } + (out, done) +} + #[cfg(test)] mod tests { use super::*; @@ -501,4 +771,111 @@ mod tests { [(RESULTS, 12), (RESULTS, 0), (6, 0), (RESULTS, 256 + 24)] ); } + + #[test] + fn clamps_are_batched() { + use crate::indirect::batch::job; + let clamp = |kind, offset, records, source| { + let view = |param, res| Cmd::RootView { + graphics: false, + kind: 2, + param, + va: Va::At { res, offset: 0 }, + }; + vec![ + barriers(&[uav(0), moved(5, 0x200, 8)]), + Cmd::RootSignature { + graphics: false, + root: 8, + }, + pso(9), + Cmd::Constants { + graphics: false, + param: 0, + offset: 0, + values: vec![kind, 32, records, offset, 0, 0], + }, + view(1, source), + view(2, source), + view(3, 5), + view(4, 6), + go(), + barriers(&[uav(0), moved(5, 8, 0x200)]), + ] + }; + let run = |at| Cmd::Indirect { + signature: 1, + most: 1, + args: 5, + at, + count: 0, + count_at: 0, + }; + // A dispatch, two indirect ones with a wait of the title's between + // them, then draws: a window of two and another buffer's. + let mut list = vec![pso(1), go()]; + list.extend(clamp(2, 0, 1, 70)); + list.extend([pso(1), run(0)]); + list.extend(clamp(2, 64, 1, 70)); + list.extend([pso(1), run(0), barriers(&[uav(0)])]); + list.extend(clamp(2, 64, 1, 70)); + list.extend([pso(1), run(0)]); + list.extend(clamp(10, 128, 2, 70)); + list.extend([pso(2), run(0), run(32), run(32)]); + list.extend(clamp(10, 256, 1, 71)); + list.extend([pso(2), run(0)]); + let (clamps, compute) = (HashSet::from([9]), HashSet::from([1])); + let table = 16 + 16 * 2048; + for (careful, batches) in [(false, 3), (true, 4)] { + let mut jobs = Vec::new(); + let (out, done) = batch_clamps(list.clone(), &clamps, &compute, 99, careful, &mut jobs); + assert_eq!((done.clamps, done.batches, done.jobs), (5, batches, 6), "careful {careful}"); + assert_eq!(jobs.len(), table * batches as usize); + let passes = out.iter().filter(|c| matches!(c, Cmd::Pipeline { pso: BATCH })).count(); + assert_eq!(passes, batches as usize); + // Nothing of the clamps is left; the title's wait is. + assert!(!out.contains(&pso(9)) && out.contains(&barriers(&[uav(0)]))); + let names_5 = |c: &Cmd| matches!(c, Cmd::Barriers { all } if all.iter().any(|b| matches!(b, Barrier::Transition { res: 5, .. }))); + assert!(!out.iter().any(names_5)); + let places: Vec = out + .iter() + .filter_map(|c| match c { + Cmd::Indirect { args: 99, at, .. } => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(places, [0, 32, 64, 96, 128, 128, 160]); + // The last table: two records, one read twice, then one of the + // other buffer. + let word = |i: usize| { + let at = jobs.len() - table + 4 * i; + u32::from_le_bytes(jobs[at..at + 4].try_into().unwrap()) + }; + assert_eq!(word(0), 3); + let all: Vec = (4..16).map(word).collect(); + assert_eq!( + all, + [ + [job(0, 10, 1), 128, 96, 0], + [job(0, 10, 2), 160, 128, 0], + [job(1, 10, 1), 256, 160, 0] + ] + .concat() + ); + let sources: Vec = out + .iter() + .filter_map(|c| match c { + Cmd::RootView { param: 1, va: Va::At { res, .. }, .. } => Some(*res), + _ => None, + }) + .collect(); + assert_eq!(sources.last(), Some(&71)); + // It ends common, as it began. + assert_eq!(out.last(), Some(&barriers(&[moved(99, 0x200, 0)]))); + } + // A list without clamps is left as it is. + let plain = vec![pso(1), go(), barriers(&[uav(0)])]; + let (out, done) = batch_clamps(plain.clone(), &clamps, &compute, 99, false, &mut Vec::new()); + assert_eq!((out, done), (plain, Batched::default())); + } } diff --git a/crates/victory-gpu/src/replay/play.rs b/crates/victory-gpu/src/replay/play.rs index 8543f6a..21ea8df 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -29,6 +29,9 @@ use super::wire::{ self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot, }; +pub mod diverge; +mod merge; + /// The name of the argument clamp's pipeline, by which its passes are /// recognised. pub const CLAMP: &str = "victory: argument clamp"; @@ -62,11 +65,22 @@ pub struct Options { /// Where the picture goes (default: `replay.png` in the capture). pub image: Option, pub buffers: Buffers, + /// Of those, only the ones all of these match ([`chosen`]). + pub only_buffers: Vec, pub no_barriers: bool, pub merge_barriers: bool, pub skip_clamps: bool, + /// The clamps in batches (`edit::batch_clamps`); 2: carefully. + pub batch_clamps: u32, 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. + 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 @@ -87,11 +101,16 @@ impl Default for Options { top: 20, image: None, buffers: Buffers::AsRecorded, + only_buffers: Vec::new(), no_barriers: false, merge_barriers: false, skip_clamps: false, + batch_clamps: 0, skip_hash_passes: false, one_submit: false, + merge: true, + wait_all: false, + wait_lists: false, only: None, skip_shaders: Vec::new(), compare: false, @@ -105,8 +124,11 @@ impl Options { self.no_barriers || self.merge_barriers || self.skip_clamps + || self.batch_clamps > 0 || self.skip_hash_passes || self.one_submit + || self.wait_all + || self.wait_lists || self.only.is_some() || !self.skip_shaders.is_empty() } @@ -117,8 +139,11 @@ impl Options { no_barriers: false, merge_barriers: false, skip_clamps: false, + batch_clamps: 0, skip_hash_passes: false, one_submit: false, + wait_all: false, + wait_lists: false, only: None, skip_shaders: Vec::new(), ..self.clone() @@ -144,6 +169,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 +232,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}"); } @@ -212,6 +253,32 @@ impl Report { } } +/// Whether `--only-buffers` means a buffer: all of `only` match it. +/// `name=`, `min=`, `max=`, +/// `seen=`, `id=..`; with `!` in front: that does not. +fn chosen(r: &wire::Resource, only: &[String]) -> bool { + only.iter().all(|f| { + let (no, f) = match f.strip_prefix('!') { + Some(f) => (true, f), + None => (false, f.as_str()), + }; + let (key, value) = f.split_once('=').unwrap_or(("name", f)); + let number = value.parse().unwrap_or(0u64); + let is = match key { + "min" => r.desc.width >= number, + "max" => r.desc.width <= number, + "seen" => { + matches!(&r.place, Place::Committed { props, .. } if format!("{:?}", gpu::seen(props)).eq_ignore_ascii_case(value)) + } + "id" => value.split_once("..").is_some_and(|(a, b)| { + (a.parse().unwrap_or(0)..b.parse().unwrap_or(u32::MAX)).contains(&r.id) + }), + _ => r.name.contains(value), + }; + is != no + }) +} + fn median(v: &[f64]) -> f64 { let mut v = v.to_vec(); v.sort_by(f64::total_cmp); @@ -241,20 +308,102 @@ 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) +} + +/// Writes, one line each, the commands of lists (by their place in the +/// frame), and before them the frame's buffers: `--listing`. +pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> Result<()> { + let frame = Frame::read(&find(folder)?.join("frame.bin"))?; + let pipelines: HashMap = + frame.pipelines.iter().map(|p| (p.id, p.name.as_str())).collect(); + for r in &frame.resources { + if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 { + let place = match &r.place { + Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)), + other => format!("{other:?}"), + }; + line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name)); + } + } + let mut place = 0; + for (i, s) in frame.submits.iter().enumerate() { + for &l in s.lists.iter().filter(|&&l| l != MISSING) { + let here = place; + place += 1; + if here < lists.0 || here > lists.1 { + continue; + } + line(&format!("list {here} of submission {i}")); + for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() { + match c { + Cmd::Pipeline { pso } => { + line(&format!("{n} Pipeline {pso} {}", pipelines.get(pso).copied().unwrap_or_default())); + } + c => line(&format!("{n} {c:?}")), + } + } + } + } + Ok(()) +} + /// 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> { let mut player = Player::load(folder, options)?; let mut out = Vec::new(); if options.compare && options.edited() { + // Turn by turn: what else the machine does falls on both. let image = Some(player.folder.join("replay-unchanged.png")); - out.push(( - "unchanged".into(), - player.run(&Options { - image, - ..options.plain() - })?, - )); + let plain = Options { + image, + ..options.plain() + }; + let mut a = player.prepare(&plain)?; + let mut b = player.prepare(options)?; + let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new()); + for _ in 0..options.loops.max(1) { + stamps_a = player.once(&plain, &mut a)?; + stamps_b = player.once(options, &mut b)?; + } + out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?)); + out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?)); + return Ok(out); } let what = if options.edited() { "with the experiments" @@ -307,11 +456,18 @@ 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>, /// 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, } @@ -370,9 +526,13 @@ 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, + at: States::default(), notes: frame .notes .iter() @@ -387,7 +547,7 @@ impl Player { *at = Instant::now(); }; let mut at = Instant::now(); - player.make_resources(options.buffers)?; + player.make_resources(options.buffers, &options.only_buffers)?; step("resources", &mut at); player.make_pipelines()?; step("pipelines", &mut at); @@ -395,12 +555,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(), @@ -467,7 +637,7 @@ impl Player { } } - fn make_resources(&mut self, buffers: Buffers) -> Result<()> { + fn make_resources(&mut self, buffers: Buffers, only: &[String]) -> Result<()> { // A heap of memory the CPU sees becomes one the card may write too: // what the CPU wrote is put back by the card. let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES { @@ -511,7 +681,7 @@ impl Player { for h in &self.frame.heaps { let desc = D3D12_HEAP_DESC { SizeInBytes: h.size, - Properties: props(&h.props, used_by_buffers_only.contains(&h.id)), + Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)), Alignment: h.alignment, Flags: D3D12_HEAP_FLAGS(h.flags & !DROP), }; @@ -522,8 +692,15 @@ impl Player { self._heaps.extend(heap.map(|heap| (h.id, heap))); } let mut failed = 0; + let mut moves: BTreeMap = BTreeMap::new(); for (index, r) in self.frame.resources.iter().enumerate() { let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0; + let moved = is_buffer && chosen(r, only); + if moved && let Place::Committed { props, .. } = &r.place { + let seen = gpu::seen(props); + let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64)); + *m = (m.0 + 1, m.1 + r.desc.width); + } let desc = gpu::to_desc(&r.desc); let mut made: Option = None; let clear: Option = r.clear.map(|c| { @@ -546,7 +723,7 @@ impl Player { None => Err(windows::core::Error::empty()), }, Place::Committed { props: p, flags } => { - let p = props(p, is_buffer); + let p = props(p, moved); let state = if p.Type == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { @@ -609,6 +786,11 @@ impl Player { if failed > 0 { self.note(format!("{failed} resources could not be made again")); } + if buffers != Buffers::AsRecorded { + self.notes.push(format!( + "--buffers is of, by how the CPU saw them (buffers, bytes): {moves:?}" + )); + } Ok(()) } @@ -1354,7 +1536,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 { @@ -1386,6 +1568,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] { @@ -1436,7 +1619,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. @@ -1469,6 +1652,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])); @@ -1500,7 +1685,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, @@ -1574,6 +1762,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(); @@ -1628,6 +1841,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); } })?; @@ -1671,6 +1891,17 @@ impl Player { .push(format!("{} pipelines match --skip-shader", skip.len())); } let hash = self.pipelines_named(COMPARE); + let clamp = self.pipelines_named(CLAMP); + let compute: HashSet = self + .frame + .pipelines + .iter() + .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0))) + .map(|p| p.id) + .collect(); + let mut batched = edit::Batched::default(); + let mut jobs = Vec::new(); + let mut scratches = Vec::new(); let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0); let mut place = 0; let mut out = Vec::new(); @@ -1689,6 +1920,24 @@ impl Player { { cmds = edit::skip_clamps(cmds, c); } + if o.batch_clamps > 0 { + let scratch = edit::BATCH_SCRATCH - here; + let done; + (cmds, done) = edit::batch_clamps( + cmds, + &clamp, + &compute, + scratch, + o.batch_clamps > 1, + &mut jobs, + ); + batched.clamps += done.clamps; + batched.batches += done.batches; + batched.jobs += done.jobs; + if done.scratch > 0 { + scratches.push((scratch, done.scratch)); + } + } let mut n; if !skip.is_empty() { (cmds, n) = edit::skip_pipelines(cmds, &skip); @@ -1710,6 +1959,15 @@ impl Player { } out.push(lists); } + if o.batch_clamps > 0 { + report.notes.push(format!( + "--batch-clamps: {} clamp passes became {}, of {} records", + batched.clamps, batched.batches, batched.jobs + )); + if let Err(e) = self.make_batches(&jobs, &scratches) { + report.notes.push(format!("--batch-clamps failed: {e:#}")); + } + } if !skip.is_empty() { report .notes @@ -1733,6 +1991,44 @@ impl Player { out } + /// What lists edited by [`edit::batch_clamps`] name: the pass, its + /// tables and scratch buffers. + fn make_batches(&mut self, jobs: &[u8], scratches: &[(u32, u64)]) -> Result<()> { + let (root, pso) = crate::indirect::batch_for(&self.device)?; + self.roots.insert(edit::BATCH_ROOT, root); + self.pipelines.insert(edit::BATCH, pso); + let (table, data) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_UPLOAD, + jobs.len().max(4) as u64, + D3D12_RESOURCE_FLAG_NONE, + )?; + // SAFETY: a mapping of as many bytes. + unsafe { std::ptr::copy_nonoverlapping(jobs.as_ptr(), data.cast(), jobs.len()) }; + let mut all = vec![(edit::BATCH_JOBS, table)]; + for &(id, bytes) in scratches { + let (scratch, _) = gpu::buffer( + &self.device, + D3D12_HEAP_TYPE_DEFAULT, + bytes.next_multiple_of(64 << 10), + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + )?; + all.push((id, scratch)); + } + for (id, res) in all { + // SAFETY: a live buffer. + let va = unsafe { res.GetGPUVirtualAddress() }; + let object = Object { + res, + va, + index: 0, + subs: 1, + }; + self.objects.insert(id, object); + } + Ok(()) + } + /// The clamp passes of each list of the frame, in order, and their /// results in [`RESULTS`] (by a run that keeps them). fn clamp_results(&mut self, report: &mut Report) -> Result>> { @@ -1769,7 +2065,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) } @@ -1818,10 +2114,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 @@ -1830,6 +2131,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())?) } @@ -1838,8 +2144,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,9 +2290,11 @@ 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); + let mut clamps = self.pipelines_named(CLAMP); + clamps.insert(edit::BATCH); let compares = self.pipelines_named(COMPARE); let mesh: HashSet = self .frame @@ -2003,13 +2316,55 @@ 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) }; + } let timed = c.works() || matches!(c, Cmd::Barriers { .. }); if timed && let Some((heap, next)) = &mut stamp { // SAFETY: as above. @@ -2474,7 +2829,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 +2844,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 +2859,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 @@ -2519,52 +2881,76 @@ impl Player { /// Runs the frame as the options say. pub fn run(&mut self, o: &Options) -> Result { + let mut made = self.prepare(o)?; + let mut stamps = Vec::new(); + for _ in 0..o.loops.max(1) { + stamps = self.once(o, &mut made)?; + } + self.finish(o, made, &stamps) + } + + /// The lists for a run as the options say. + fn prepare(&mut self, o: &Options) -> Result<(Sends, Report)> { let mut report = Report { notes: self.notes.clone(), ..Default::default() }; + self.set_merging(o.merge)?; let clamps = if o.skip_clamps { self.clamp_results(&mut report)? } else { Vec::new() }; let submits = self.edited(o, &mut report, &clamps); - let built = self.build(&submits, o)?; - let mut stamps = Vec::new(); - for _ in 0..o.loops.max(1) { - self.restore(o.restore)?; - self.fresh = false; - stamps = self.send(&built, o.one_submit)?; - let ms = |a: u32, b: u32| { - stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency - }; - let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); - let (Some(first), Some(last)) = (lists.first(), lists.last()) else { - bail!("no lists to run"); - }; - let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); - report.delta_ms.push( - delta - .filter(|d| d.first > first.first) - .map(|d| ms(d.first, d.last)) - .sum(), - ); - report.frame_ms.push(ms(first.first, last.last)); - let each = |l: &[Built]| match (l.first(), l.last()) { - (Some(a), Some(b)) => ms(a.first, b.last), - _ => 0.0, - }; - report.submits = built - .steps - .iter() - .map(|(_, l)| (l.len(), each(l))) - .collect(); - report - .busy_ms - .push(report.submits.iter().map(|s| s.1).sum()); + Ok((self.build(&submits, o)?, report)) + } + + /// One run of the frame, noted in the report; its timestamps. + fn once(&mut self, o: &Options, (built, report): &mut (Sends, Report)) -> Result> { + self.restore(o.restore)?; + self.fresh = false; + let 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 + }; + let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect(); + let (Some(first), Some(last)) = (lists.first(), lists.last()) else { + bail!("no lists to run"); + }; + let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref()); + report.delta_ms.push( + delta + .filter(|d| d.first > first.first) + .map(|d| ms(d.first, d.last)) + .sum(), + ); + report.frame_ms.push(ms(first.first, last.last)); + let each = |l: &[Built]| match (l.first(), l.last()) { + (Some(a), Some(b)) => ms(a.first, b.last), + _ => 0.0, + }; + report.submits = built + .steps + .iter() + .map(|(_, l)| (l.len(), each(l))) + .collect(); + report + .busy_ms + .push(report.submits.iter().map(|s| s.1).sum()); + Ok(stamps) + } + + /// The report after the last run. + fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result { if o.detailed { - self.detail(&built, &stamps, o, &mut report); + 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 { @@ -2607,6 +2993,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 +3210,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..a297040 --- /dev/null +++ b/crates/victory-gpu/src/replay/play/diverge.rs @@ -0,0 +1,1386 @@ +//! 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 }), + ), + } + } + + pub(super) 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/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 c839d60..232f7b7 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,14 @@ 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..6c69042 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,9 @@ 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 +593,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 +632,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 +682,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 +708,7 @@ impl Capture { list.CopyBufferRegion( &blocks[block].0, at + from as u64, - &b.res, + &*b.res, from as u64, (to - from) as u64, ) diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 6200d9e..1b74262 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1414,6 +1414,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 @@ -2100,6 +2304,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/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 24eb646..aa331eb 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,6 +75,105 @@ std::arch::global_asm!( "vzeroupper", "xor eax, eax", "ret", + ".globl victory_safe_update", + ".globl victory_safe_update_at", + ".globl victory_safe_update_after", + ".globl victory_safe_update_failed", + // rcx destination, rdx source, r8 bytes (whole 64s, not none), r9 where + // the offset of the first 64 bytes that differed goes (-1: none did) and + // behind it the offset of the end of the last: stores the 64s that + // differ. eax: whether all could be read. + "victory_safe_update:", + "xor r10d, r10d", + "mov r11, -1", + "xor eax, eax", + "2:", + "victory_safe_update_at:", + "vmovdqu ymm0, ymmword ptr [rdx + r10]", + "vmovdqu ymm1, ymmword ptr [rdx + r10 + 32]", + "victory_safe_update_after:", + "vpxor ymm2, ymm0, ymmword ptr [rcx + r10]", + "vpxor ymm3, ymm1, ymmword ptr [rcx + r10 + 32]", + "vpor ymm2, ymm2, ymm3", + "vptest ymm2, ymm2", + "jz 3f", + "vmovdqu ymmword ptr [rcx + r10], ymm0", + "vmovdqu ymmword ptr [rcx + r10 + 32], ymm1", + "cmp r11, -1", + "cmove r11, r10", + "lea rax, [r10 + 64]", + "3:", + "add r10, 64", + "cmp r10, r8", + "jb 2b", + "mov qword ptr [r9], r11", + "mov qword ptr [r9 + 8], rax", + "vzeroupper", + "mov eax, 1", + "ret", + "victory_safe_update_failed:", + "vzeroupper", + "xor eax, eax", + "ret", + ".globl victory_safe_merge", + ".globl victory_safe_merge_at", + ".globl victory_safe_merge_after", + ".globl victory_safe_merge_failed", + // rcx title memory, rdx what the card holds, r8 what it held when last + // looked at, r9 blocks of 32 bytes, fifth where the two counts go. Where + // a byte of the second differs from the third, it goes into title memory + // (as whole dwords, and only dwords that then differ from what is there) + // and into the third; each block of title memory is read just before it + // is written. rax: the blocks left when a page of title memory could not + // be read or written (0: all done). The counts: blocks in which the + // second and third differed, dwords stored in title memory. + "victory_safe_merge:", + "xor r10d, r10d", + "xor r11d, r11d", + "test r9, r9", + "jz 6f", + "vpcmpeqd ymm5, ymm5, ymm5", + "2:", + "vmovdqu ymm0, ymmword ptr [rdx]", + "vpcmpeqb ymm1, ymm0, ymmword ptr [r8]", + "vpmovmskb eax, ymm1", + "cmp eax, -1", + "je 5f", + "victory_safe_merge_at:", + "vmovdqu ymm2, ymmword ptr [rcx]", + "vpblendvb ymm3, ymm0, ymm2, ymm1", + "vpcmpeqd ymm4, ymm3, ymm2", + "vmovmskps eax, ymm4", + "xor eax, 255", + "jz 4f", + "cmp eax, 255", + "je 3f", + "vpxor ymm4, ymm4, ymm5", + "vpmaskmovd ymmword ptr [rcx], ymm4, ymm3", + "jmp 7f", + "3:", + "vmovdqu ymmword ptr [rcx], ymm3", + "victory_safe_merge_after:", + "7:", + "popcnt eax, eax", + "add r11, rax", + "4:", + "inc r10", + "vmovdqu ymmword ptr [r8], ymm0", + "5:", + "add rcx, 32", + "add rdx, 32", + "add r8, 32", + "dec r9", + "jnz 2b", + "6:", + "victory_safe_merge_failed:", + "vzeroupper", + "mov rax, qword ptr [rsp + 40]", + "mov qword ptr [rax], r10", + "mov qword ptr [rax + 8], r11", + "mov rax, r9", + "ret", ); unsafe extern "system" { @@ -86,6 +185,189 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_failed(); + fn victory_safe_update(dst: *mut u8, src: *const u8, len: usize, changed: *mut [usize; 2]) -> u32; + fn victory_safe_update_at(); + fn victory_safe_update_after(); + fn victory_safe_update_failed(); + fn victory_safe_merge(title: *mut u8, now: *const u8, held: *mut u8, blocks: usize, counts: *mut [u64; 2]) -> usize; + fn victory_safe_merge_at(); + fn victory_safe_merge_after(); + fn victory_safe_merge_failed(); +} + +/// What [`update`] found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Updated { + /// Every byte was the same already; nothing was stored. + Same, + /// The bytes that changed lie in these offsets. + Changed(usize, usize), + /// Not all of the source could be read; some may have been copied. + Failed, +} + +/// Makes `dst` hold what `src` holds, storing only what differs. The source +/// may change meanwhile: what is compared is what is stored, read once. +/// +/// # Safety +/// As [`copy`]'s, and the destination is memory of ours that nothing else +/// writes. +pub(crate) unsafe fn update(dst: *mut u8, src: *const u8, len: usize) -> Updated { + let whole = len / 64 * 64; + let (mut from, mut to) = (usize::MAX, 0); + if whole > 0 { + let mut changed = [usize::MAX, 0]; + // SAFETY: the source's faults leave through the failing exit; the + // rest is the caller's. + if unsafe { victory_safe_update(dst, src, whole, &mut changed) } == 0 { + return Updated::Failed; + } + [from, to] = changed; + } + if whole < len { + let mut rest = [0u8; 64]; + let rest = &mut rest[..len - whole]; + // SAFETY: as above; `rest` is ours. + unsafe { + if !copy(rest.as_mut_ptr(), src.add(whole), rest.len()) { + return Updated::Failed; + } + let held = std::slice::from_raw_parts_mut(dst.add(whole), rest.len()); + if held != rest { + held.copy_from_slice(rest); + (from, to) = (from.min(whole), len); + } + } + } + if from >= to { Updated::Same } else { Updated::Changed(from, to) } +} + +/// What [`merge`] did. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Merged { + /// Blocks of 32 bytes in which the card's bytes were new. + pub(crate) new: u64, + /// Dwords stored in title memory. + pub(crate) dwords: u64, + /// Whether title memory could be read and written wherever it had to be. + pub(crate) there: bool, +} + +/// What shaders wrote goes into title memory: every byte of `now` that +/// differs from the one in `held` goes to `title` and into `held`, every +/// other byte of both stays as it is. Title memory is read 32 bytes at a +/// time, each just before what changes of them is stored, and only the +/// dwords that change are stored (at ends that are no dword's, bytes): the +/// title's own threads may be writing those beside them. +/// +/// Where title memory cannot be read or written, the rest of `held` takes +/// `now` if `take` says so (the caller has the card's bytes nowhere else), +/// else it stays. +/// +/// # Safety +/// `now` and `held` are `len` bytes of ours, not overlapping, that nothing +/// else writes (but for `now` the card: it is read once); `title` is as +/// [`copy`]'s. The stretch lies in one page of 4 KiB of title memory. [`on`] +/// must have been asked. +pub(crate) unsafe fn merge(title: *mut u8, now: *const u8, held: *mut u8, len: usize, take: bool) -> Merged { + let mut out = Merged { there: true, ..Merged::default() }; + let mut at = 0; + while at < len { + let address = title.addr() + at; + let left = len - at; + if !address.is_multiple_of(4) || left < 4 { + // A dword only partly in the stretch: its bytes one by one. + // SAFETY: inside the stretch. + unsafe { + let byte = now.add(at).read_volatile(); + let mut there = 0u8; + if byte != held.add(at).read() { + out.new += 1; + let mut ok = copy(&mut there, title.add(at), 1); + if ok && there != byte { + ok = copy(title.add(at), &byte, 1); + out.dwords += u64::from(ok); + } + out.there &= ok; + if ok || take { + held.add(at).write(byte); + } + } + } + at += 1; + continue; + } + let into = address % 32; + let mut counts = [0u64; 2]; + if into != 0 || left < 32 { + // Part of a block: in a block of its own, equal beside the part. + let n = (32 - into).min(left) & !3; + let (mut new, mut old) = ([0u8; 32], [0u8; 32]); + // SAFETY: inside the stretch; the block of title memory around + // it lies in the same page, and nothing of it outside the part + // is stored (the two arrays are equal there). + unsafe { + std::ptr::copy_nonoverlapping(now.add(at), new.as_mut_ptr().add(into), n); + std::ptr::copy_nonoverlapping(held.add(at), old.as_mut_ptr().add(into), n); + let stuck = victory_safe_merge(title.wrapping_add(at).wrapping_sub(into), new.as_ptr(), old.as_mut_ptr(), 1, &mut counts); + out.there &= stuck == 0; + let from = if stuck != 0 && take { new.as_ptr() } else { old.as_ptr() }; + std::ptr::copy_nonoverlapping(from.add(into), held.add(at), n); + } + at += n; + } else { + let blocks = left / 32; + // SAFETY: whole blocks of the stretch. + let stuck = unsafe { victory_safe_merge(title.add(at), now.add(at), held.add(at), blocks, &mut counts) }; + if stuck != 0 { + out.there = false; + if take { + let from = at + (blocks - stuck) * 32; + // SAFETY: the blocks that were not done. + unsafe { std::ptr::copy_nonoverlapping(now.add(from), held.add(from), stuck * 32) }; + } + } + at += blocks * 32; + } + out.new += counts[0]; + out.dwords += counts[1]; + } + out +} + +/// Whether the `len` bytes at `a` and `b` differ. +/// +/// # Safety +/// Both are `len` bytes that can be read; the card may be writing them. +pub(crate) unsafe fn differ(a: *const u8, b: *const u8, len: usize) -> bool { + use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_or_si256, _mm256_setzero_si256, _mm256_testz_si256, _mm256_xor_si256}; + /// # Safety + /// [`differ`]'s; the processor has AVX2 (as the code above assumes). + #[target_feature(enable = "avx2")] + unsafe fn blocks(a: *const u8, b: *const u8, n: usize) -> bool { + let mut at = 0; + while at < n { + let mut any = _mm256_setzero_si256(); + for k in at..n.min(at + 4) { + // SAFETY: block `k`, inside both. + let (x, y) = unsafe { + (_mm256_loadu_si256(a.add(k * 32).cast::<__m256i>()), _mm256_loadu_si256(b.add(k * 32).cast::<__m256i>())) + }; + any = _mm256_or_si256(any, _mm256_xor_si256(x, y)); + } + if _mm256_testz_si256(any, any) == 0 { + return true; + } + at += 4; + } + false + } + // SAFETY: the caller's. + if unsafe { blocks(a, b, len / 32) } { + return true; + } + // SAFETY: the bytes behind the blocks. + (len / 32 * 32..len).any(|i| unsafe { a.add(i).read_volatile() != b.add(i).read_volatile() }) } /// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst` @@ -160,7 +442,15 @@ pub(crate) fn failing_exit(at: usize) -> Option { return Some(victory_safe_copy_failed as *const () as usize); } let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize); - (from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize) + if (from..to).contains(&at) { + return Some(victory_safe_put_failed as *const () as usize); + } + let (from, to) = (victory_safe_update_at as *const () as usize, victory_safe_update_after as *const () as usize); + if (from..to).contains(&at) { + return Some(victory_safe_update_failed as *const () as usize); + } + let (from, to) = (victory_safe_merge_at as *const () as usize, victory_safe_merge_after as *const () as usize); + (from..to).contains(&at).then_some(victory_safe_merge_failed as *const () as usize) } #[cfg(test)] @@ -214,6 +504,52 @@ mod tests { } } + /// An update makes the two the same, says where they differed (to 64 + /// bytes), stores nothing where they did not, and fails at a page that + /// is not there. + #[test] + fn updates_store_what_differs() { + assert!(on()); + let (src, dst) = (Pages::new(1 << 14), Pages::new(1 << 14)); + for len in [0usize, 1, 63, 64, 65, 200, 4096, 5000] { + for (da, sa) in [(0usize, 0usize), (3, 0), (0, 5)] { + for changed in [vec![], vec![0usize], vec![len / 2], vec![len.saturating_sub(1)], vec![1, len / 3, len / 2]] { + src.fill(); + // SAFETY: inside the two allocations. + unsafe { + std::ptr::write_bytes(dst.0, 0xEE, dst.1); + std::ptr::copy_nonoverlapping(src.0.add(sa), dst.0.add(da), len); + let at: std::collections::BTreeSet = changed.iter().copied().filter(|&i| i < len).collect(); + for &i in &at { + *src.0.add(sa + i) ^= 0x40; + } + let found = update(dst.0.add(da), src.0.add(sa), len); + match (at.iter().min(), at.iter().max()) { + (Some(&first), Some(&last)) => { + let Updated::Changed(from, to) = found else { + panic!("{len} {at:?}: {found:?}") + }; + assert_eq!(from, first / 64 * 64); + assert_eq!(to, ((last / 64 + 1) * 64).min(len)); + } + _ => assert_eq!(found, Updated::Same), + } + let (to, from) = (std::slice::from_raw_parts(dst.0, dst.1), std::slice::from_raw_parts(src.0, src.1)); + assert_eq!(to[da..da + len], from[sa..sa + len]); + assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE)); + } + } + } + } + // SAFETY: our allocation. + unsafe { + VirtualFree(src.0.add(4096).cast(), 4096, MEM_DECOMMIT); + assert_eq!(update(dst.0, src.0, 8192), Updated::Failed); + assert_eq!(update(dst.0, src.0.add(4096), 10), Updated::Failed); + assert_ne!(update(dst.0, src.0, 4096), Updated::Failed); + } + } + /// The dwords that changed are stored, and no byte of any other, at /// every alignment and length; a page that is not there fails. #[test] @@ -266,6 +602,173 @@ mod tests { } } + /// [`merge`] against what it is to do, byte by byte, for every kind of + /// start, end and change: the bytes the card changed arrive in title + /// memory and in what it held, no dword without one is stored. + #[test] + fn a_merge_puts_what_the_card_changed_and_nothing_else() { + assert!(on()); + let pages = Pages::new(1 << 12); + let mut seed = 1u32; + let mut random = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for round in 0..4000u32 { + let at = random() as usize % 100; + let len = random() as usize % 300; + let (from, to) = (at, (at + len).min(400)); + let n = to - from; + let base: Vec = (0..512).map(|_| random() as u8).collect(); + let was: Vec = base[from..to].to_vec(); + let mut held = was.clone(); + let mut now = was.clone(); + let mut title = base.clone(); + // The card's writes: dwords and single bytes; the title's: some + // in the same dwords, some the same values. + for _ in 0..random() % 12 { + if n > 0 { + let i = random() as usize % n; + now[i] = random() as u8; + } + let i = random() as usize % 512; + title[i] = if (from..to).contains(&i) && round % 3 == 0 { now[i - from] } else { random() as u8 }; + } + if round % 7 == 0 { + now.iter_mut().for_each(|b| *b = b.wrapping_add(1)); + } + // SAFETY: inside the allocation and the vectors. + let done = unsafe { + std::ptr::copy_nonoverlapping(title.as_ptr(), pages.0, 512); + merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, round % 2 == 0) + }; + assert!(done.there); + // SAFETY: inside the allocation. + let there = unsafe { std::slice::from_raw_parts(pages.0, 512) }; + for i in 0..512 { + let wrote = (from..to).contains(&i) && now[i - from] != was[i - from]; + let expect = if wrote { now[i - from] } else { title[i] }; + assert_eq!(there[i], expect, "round {round} byte {i} of {from}..{to}"); + } + assert_eq!(held, now, "round {round}"); + assert_eq!(done.new == 0, was == now); + // Found merged already. + // SAFETY: as above. + let again = unsafe { merge(pages.0.add(from), now.as_ptr(), held.as_mut_ptr(), n, false) }; + assert_eq!(again, Merged { new: 0, dwords: 0, there: true }); + } + } + + /// Title memory that is not there: what the card wrote stays to be + /// looked at again, or is taken, as asked; a page that only cannot be + /// written counts the same. + #[test] + fn a_merge_into_missing_memory_fails() { + assert!(on()); + let pages = Pages::new(1 << 13); + let mut old = 0; + for (missing, take) in [(true, false), (true, true), (false, false), (false, true)] { + for (at, len) in [(0usize, 4096usize), (4, 64), (7, 1), (40, 100)] { + let was = vec![1u8; len]; + let mut now = was.clone(); + now[len - 1] = 9; + let mut held = was.clone(); + // SAFETY: our allocation. + let done = unsafe { + if missing { + VirtualFree(pages.0.cast(), 4096, MEM_DECOMMIT); + } else { + VirtualProtect(pages.0.cast(), 4096, PAGE_READONLY, &mut old); + } + let done = merge(pages.0.add(at), now.as_ptr(), held.as_mut_ptr(), len, take); + VirtualAlloc(pages.0.cast(), 4096, MEM_COMMIT, PAGE_READWRITE); + VirtualProtect(pages.0.cast(), 4096, PAGE_READWRITE, &mut old); + done + }; + assert!(!done.there); + assert_eq!(held, if take { now.clone() } else { was.clone() }, "{missing} {take} {at} {len}"); + // Nothing to put: nothing fails. + let mut held = now.clone(); + // SAFETY: as above; the addresses are no one's. + let done = unsafe { merge(std::ptr::without_provenance_mut(0x1000 + at), now.as_ptr(), held.as_mut_ptr(), len, take) }; + assert!(done.there && done.new == 0); + } + } + } + + /// [`merge`] beside threads that write other dwords of the same memory: + /// none of their writes is lost or undone. + #[test] + fn merges_undo_no_write_of_other_threads() { + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + assert!(on()); + let pages = Pages::new(1 << 12); + let base = pages.0 as usize; + // SAFETY: committed, aligned memory, only touched as atomics or by + // the merge's stores of whole dwords. + let dword = |i: usize| unsafe { &*((base + i * 4) as *const AtomicU32) }; + let stop = AtomicBool::new(false); + std::thread::scope(|s| { + let writers: Vec<_> = (0..2usize) + .map(|w| { + let stop = &stop; + s.spawn(move || { + let mut value = 1u32; + while !stop.load(Ordering::Relaxed) { + for i in (w..1024).step_by(4) { + // This thread's own dword: nobody else's value. + assert_eq!(dword(i).load(Ordering::Relaxed), value - 1, "dword {i}"); + dword(i).store(value, Ordering::Relaxed); + } + value += 1; + } + }) + }) + .collect(); + // The card's dwords: every fourth, from the third on. + let mut held = vec![0u8; 4096]; + for round in 1..3000u32 { + let mut now = held.clone(); + for i in (2..1024).step_by(4) { + if i * 7 % 5 != round as usize % 5 { + now[i * 4..i * 4 + 4].copy_from_slice(&(round + i as u32).to_le_bytes()); + } + } + // SAFETY: the allocation, whole. + let done = unsafe { merge(base as *mut u8, now.as_ptr(), held.as_mut_ptr(), 4096, false) }; + assert!(done.there); + for i in (2..1024).step_by(4) { + let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().unwrap()); + assert_eq!(dword(i).load(Ordering::Relaxed), expect); + } + for i in (3..1024).step_by(4) { + assert_eq!(dword(i).load(Ordering::Relaxed), 0); + } + } + stop.store(true, Ordering::Relaxed); + for w in writers { + w.join().expect("no write was undone"); + } + }); + } + + #[test] + fn differences_are_seen_wherever_they_are() { + for len in [0usize, 1, 31, 32, 33, 127, 128, 129, 200] { + let a = vec![7u8; len]; + // SAFETY: the vectors' bytes. + assert!(!unsafe { differ(a.as_ptr(), a.clone().as_ptr(), len) }); + for at in 0..len { + let mut b = a.clone(); + b[at] = 8; + // SAFETY: as above. + assert!(unsafe { differ(a.as_ptr(), b.as_ptr(), len) }, "{len} {at}"); + } + } + } + /// What the copies cost (ignored: a measurement): 64 KiB pieces of /// scattered memory into a buffer the card reads, by the kernel and here. #[test] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 68817e0..091c5ed 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use windows::Win32::Graphics::Direct3D12::ID3D12Resource; @@ -35,6 +35,11 @@ pub(crate) struct Shadow { /// Per page of title memory from `start`'s on: the write-watch asking /// after which it was last copied (0: never). copied: Mutex>, + /// Two ranges of title memory taken whole, the last one and the longest, + /// and the asking after which each was ([`Shadow::copy_stale`]). A page + /// a range holds in part cannot say so in `copied`. Locked inside + /// `copied`'s lock. + ranged: Mutex<[(usize, usize, u64); 2]>, /// Whether the memory is write-watched: unknown, yes, no. watched: AtomicU8, /// Ranges shaders of a submission not yet copied back may be writing: @@ -49,6 +54,11 @@ pub(crate) struct Shadow { /// GPU wrote differs. Room for the whole copy; only those ranges' bytes /// are set (and read). before: Mutex>>, + /// Held shared while pieces of the copy are landed (`crate::land`), each + /// its own bytes of it on several threads, and alone while title bytes + /// go in under shader writes ([`Shadow::merge_under_writes`]), which + /// takes `before`'s lock too. Taken ahead of that one. + merging: RwLock<()>, /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot /// hold the copy's bytes as they are now, and whether the snapshot is /// counted in [`KEPT_BYTES`]. @@ -560,40 +570,34 @@ pub(crate) fn relay_fetched(number: u64) { /// writing: the next refresh would have put title bytes over what the /// second flight's shaders were writing. #[derive(Default)] -struct Flights(Vec<((usize, usize), u32, u64)>); +struct Flights(std::collections::HashMap<(usize, usize), (u32, u64)>); impl Flights { /// Submission `number` declares `range`: counted once for it, however /// often it declares it. fn declare(&mut self, range: (usize, usize), number: u64) { - match self.0.iter_mut().find(|f| f.0 == range) { - Some(f) => { - if f.2 != number { - f.1 += 1; - f.2 = number; - } - } - None => self.0.push((range, 1, number)), + let f = self.0.entry(range).or_insert((0, number)); + if f.0 == 0 || f.1 != number { + *f = (f.0 + 1, number); } } /// One submission that declared `ranges` (each once) is copied back: - /// the ranges no other submission still holds. + /// the ranges no other submission still holds, in order. fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { let mut free = Vec::new(); for range in ranges { - match self.0.iter().position(|f| f.0 == *range) { - Some(at) => { - self.0[at].1 = self.0[at].1.saturating_sub(1); - if self.0[at].1 == 0 { - self.0.swap_remove(at); - free.push(*range); - } + match self.0.get_mut(range) { + Some(f) if f.0 > 1 => f.0 -= 1, + Some(_) => { + self.0.remove(range); + free.push(*range); } // Not counted (declared before anything counted): free. None => free.push(*range), } } + free.sort_unstable(); free } } @@ -1028,6 +1032,11 @@ struct Workers { more: std::sync::Condvar, } +/// How many threads are kept for [`wide`]. +fn wide_threads() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6) +} + fn workers() -> &'static Workers { static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); static STARTED: std::sync::Once = std::sync::Once::new(); @@ -1036,8 +1045,7 @@ fn workers() -> &'static Workers { more: std::sync::Condvar::new(), }); STARTED.call_once(|| { - let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); - for i in 0..n { + for i in 0..wide_threads() { let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { let workers = WORKERS.get().expect("made above"); loop { @@ -1103,6 +1111,30 @@ pub(crate) fn wide_run(jobs: Vec>) { wide(jobs); } +/// Calls `work` with every number under `n`, on the kept threads and on +/// this one, the next number to whichever is free: for thousands of small +/// pieces of work, where a job each ([`wide`]) is mostly the jobs' queue. +pub(crate) fn wide_each(n: usize, work: impl Fn(usize) + Send + Sync + 'static) { + let next = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let work = Arc::new(work); + let threads = (wide_threads() + 1).min(n); + let jobs = (0..threads) + .map(|_| { + let (next, work) = (next.clone(), work.clone()); + Box::new(move || { + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= n { + break; + } + work(i); + } + }) as Job + }) + .collect(); + wide(jobs); +} + /// About this many bytes to a piece of work for [`wide`]. const WIDE_JOB: usize = 1 << 20; @@ -1377,6 +1409,25 @@ mod wide_tests { /// compared, changed runs put in, and their bytes. static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +/// Why [`Shadow::merge_under_writes`] last left the caller to wait. +static STALE_WHY: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn note_stale(why: usize) { + STALE_WHY.store(why, Ordering::Relaxed); +} + +/// [`STALE_WHY`] in words (diagnostics). +#[cfg(feature = "diagnostics")] +pub(crate) fn stale_why() -> &'static str { + const WHY: [&str; 4] = [ + "the memory is not watched", + "the journal does not say what was written", + "more changed runs than a submission sends up", + "no snapshot", + ]; + WHY[STALE_WHY.load(Ordering::Relaxed).min(3)] +} + /// [`MERGED`], taken. pub(crate) fn merged_stats() -> [u64; 3] { [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) @@ -1390,7 +1441,11 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { let mut runs = Vec::new(); let mut i = 0; while i < n { - // Equal bytes, eight at a time while they last. + // Equal bytes, many at a time while they last (a page looked at + // under a flight's writes hardly ever differs at all). + while i + 512 <= n && now[i..i + 512] == was[i..i + 512] { + i += 512; + } while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { i += 8; } @@ -1409,10 +1464,56 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { runs } +/// Whether pages of a copy in the card's memory that a refresh takes again +/// go up to the card only where they are not what the CPU's side holds +/// already (`VICTORY_SEND_CHANGED=1`; off by default). +/// +/// A refresh copies the 64 KiB pages that were written since it last took +/// them, and all of each went up and was hashed there again. Most of them +/// the title did not write: the relay put what shaders wrote into title +/// memory, and the card and the CPU's side hold those bytes already +/// ([`Shadow::card_merge_relay`]). Run record-1: 1,500 pieces (98 MB) a +/// frame fetched from the card, 103 MB in 328 ranges sent up, 322 hash +/// passes, while the title's own writes took some 260 guards off. +/// +/// What it rests on: the card's side holds what the CPU's side holds, but +/// for ranges shaders may be writing (no refresh touches them) and what is +/// still to go up. A page's first taking always goes up whole, so does one +/// that could not be read; after that every byte that changes on the CPU's +/// side goes up (the bytes compared are the bytes stored). +/// +/// Why it is not on by default: a shader that writes a copy through a view +/// nobody declared (`crate::draw`, buffers picked by index) breaks that +/// rule. Taken again, its page went up over what it wrote; with the switch +/// its bytes stay, as they would on the console, until the title changes the +/// same 64 bytes: clearing them to the zeros they held before is then no +/// change. +fn send_changed() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + #[cfg(feature = "diagnostics")] + if crate::copystat::mode() != 0 { + return false; + } + std::env::var_os("VICTORY_SEND_CHANGED").is_some_and(|v| v == "1") && crate::safecopy::on() + }) +} + +/// Since the last frame-rate line, of pages taken again into copies in the +/// card's memory ([`send_changed`]): bytes compared, those of pages that +/// held the same, and bytes to go up. +static SEND: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// [`SEND`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn send_stats() -> [u64; 3] { + [0, 1, 2].map(|i| SEND[i].swap(0, Ordering::Relaxed)) +} + /// Whether what shaders wrote goes into title memory run by run /// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole /// stretch from the first changed byte to the last, as before). -fn exact_back() -> bool { +pub(crate) fn exact_back() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0")) } @@ -1490,6 +1591,27 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize { written } +/// For `crate::land`'s measurement: a piece as [`Shadow::card_merge_relay`] +/// lands it without `VICTORY_LAND`: `n` bytes at `now`, `held` what the CPU's +/// side held, both the caller's alone. +#[cfg(test)] +pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, title: &mut Vec) { + // SAFETY: the caller's. + let (gpu, held) = unsafe { (std::slice::from_raw_parts(now as *const u8, n), std::slice::from_raw_parts_mut(held as *mut u8, n)) }; + let Some(first) = first_difference(gpu, held) else { + return; + }; + let last = last_difference(gpu, held).unwrap_or(first); + let n = last + 1 - first; + title.clear(); + title.resize(n, 0); + assert!(crate::host::read_into((start + first) as *const u8, title)); + let was = title.clone(); + if merge_piece(&gpu[first..=last], &mut held[first..=last], title) { + put_changed(start + first, &was, title); + } +} + #[cfg(test)] mod merge_tests { use super::{changed_runs, dword_runs}; @@ -1520,6 +1642,34 @@ mod merge_tests { /// The runs hold exactly the bytes that differ: putting them into the /// old bytes gives the new ones, and no run holds an equal byte. + /// What looking at a page that did not change costs, against the look + /// eight bytes at a time that it was (a frame has some 250 of them, on + /// the submitting thread). Run with `--ignored --nocapture`. + #[test] + #[ignore] + fn runs_of_equal_pages() { + let (a, b) = (vec![7u8; 64 << 10], vec![7u8; 64 << 10]); + let eights = || { + let (now, was) = (std::hint::black_box(&a), std::hint::black_box(&b)); + let mut i = 0; + while i + 8 <= now.len() && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + std::hint::black_box(i); + }; + let best = |f: &dyn Fn()| { + (0..500) + .map(|_| { + let t = std::time::Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1e6 + }) + .fold(f64::MAX, f64::min) + }; + let runs = || drop(std::hint::black_box(changed_runs(std::hint::black_box(&a), std::hint::black_box(&b)))); + println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs)); + } + #[test] fn changed_runs_are_exactly_the_bytes_that_differ() { let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); @@ -1831,6 +1981,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) @@ -1871,10 +2026,12 @@ impl Shadow { start, len, copied: Mutex::new(vec![0; pages as usize]), + ranged: Mutex::default(), watched: AtomicU8::new(0), pending: Mutex::default(), flights: Mutex::default(), before: Mutex::default(), + merging: RwLock::default(), kept: Mutex::default(), used: AtomicU64::new(crate::host::moment()), asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], @@ -2274,7 +2431,7 @@ impl Shadow { let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); if relay() { let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); - pending.retain(|r| !free.contains(r)); + pending.retain(|r| free.binary_search(r).is_err()); } else { pending.retain(|r| !ranges.contains(r)); } @@ -2338,6 +2495,12 @@ impl Shadow { !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() } + /// Whether one of those submissions may be writing in title memory + /// `[from, to)`. + pub(crate) fn writes_pending_in(&self, from: usize, to: usize) -> bool { + self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) + } + /// Whether [`Shadow::update`] of `[address, address + len)` would leave /// title bytes behind: a range shaders may be writing holds a page the /// title wrote since the copy last took it. The answer comes from the @@ -2413,6 +2576,7 @@ impl Shadow { return false; } if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + note_stale(0); return true; } let base = start / PAGE; @@ -2425,6 +2589,7 @@ impl Shadow { // those were all of run 99's cases: the flights were settled // 4-5 times a frame for "0 pages looked at". let Some((now, written)) = crate::watch::writes(a, e, true) else { + note_stale(1); return true; }; let stale: Vec = { @@ -2450,6 +2615,7 @@ impl Shadow { // reference under the same lock, and a page read before // such a merge and compared after it would take the card's // bytes for the title's. + let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner()); let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); // A page that is not there is left as it is, and looked at // again next time. @@ -2464,6 +2630,7 @@ impl Shadow { let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let runs = changed_runs(title, held); if runs.len() > *runs_left { + note_stale(2); return true; } *runs_left -= runs.len(); @@ -2475,6 +2642,7 @@ impl Shadow { } } else { let Some(snapshot) = before.as_mut() else { + note_stale(3); return true; }; // SAFETY: the snapshot's allocation holds the copy's @@ -2492,6 +2660,7 @@ impl Shadow { } } drop(before); + drop(_merging); // Taken, if the range holds all of the page that is in the // copy; else the rest of it is the refresh's, which notes // only whole pages, and the page is looked at again. @@ -2547,6 +2716,43 @@ impl Shadow { self.update_free(from, to) } + /// Whether [`Shadow::update`] of `[address, address + len)` would copy + /// nothing, and knows it without asking anything + /// (`crate::watch::nothing_new`). `false` if it would have to ask. + pub(crate) fn nothing_new(&self, address: usize, len: usize) -> bool { + if self.place.is_some() { + return true; + } + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return true; + } + if self.watched.load(Ordering::Relaxed) != 1 { + return false; + } + // Around ranges shaders are writing the refresh asks gap by gap. + if self.pending.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|&(a, e)| a < to && e > from) { + return false; + } + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let same = crate::watch::nothing_new(from, to, start / PAGE, &copied, self.ranged(from, to)); + #[cfg(feature = "diagnostics")] + if same { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from) as u64); + } + same + } + + /// The latest asking after which a range that holds `[from, to)` was + /// taken whole (0: none is known). The caller holds `copied`'s lock. + fn ranged(&self, from: usize, to: usize) -> u64 { + let ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); + ranged.iter().filter(|r| r.0 <= from && to <= r.1).map(|r| r.2).max().unwrap_or(0) + } + /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no /// shader writes. fn update_free(&self, from: usize, to: usize) -> usize { @@ -2554,6 +2760,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}; @@ -2574,6 +2781,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. @@ -2581,7 +2845,13 @@ impl Shadow { let base = self.start as usize / PAGE; let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); let mut writes = written.iter().peekable(); - let (mut bytes, mut run) = (0, None); + // Pages the range holds in part are never noted in `copied`, and + // were copied again at every refresh of the range, written or not: + // of the heap's buffer views alone two ends for each of 4,400 + // copies, every frame. A range that was taken whole, and not written + // since, is as it was. + let ranged = if crate::watch::light() { self.ranged(from, to) } else { 0 }; + let (mut runs, mut run) = (Vec::new(), None::<(usize, bool)>); let last = (to - 1) / PAGE; for page in from / PAGE..=last { let write = match writes.peek() { @@ -2592,25 +2862,111 @@ impl Shadow { _ => 0, }; let at = &mut copied[page - base]; - if *at == 0 || write > *at { + let taken = (*at).max(ranged); + if taken == 0 || write > taken { // A page only partly in the range is copied in part: it // stays stale for the rest. let (start, end) = (self.start as usize, (self.start + self.len) as usize); if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { *at = now; } - run.get_or_insert(page); - } else if let Some(first) = run.take() { - bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); + // Cut where pages taken before meet pages never taken. + let again = taken != 0; + if let Some((first, known)) = run + && known != again + { + runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); + run = None; + } + run.get_or_insert((page, again)); + } else if let Some((first, known)) = run.take() { + runs.push(((first * PAGE).max(from), (page * PAGE).min(to), known)); } } // Cut to the range: next to it shaders may be writing the copy. - if let Some(first) = run { - bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + if let Some((first, known)) = run { + runs.push(((first * PAGE).max(from), ((last + 1) * PAGE).min(to), known)); + } + let bytes = self.take_all(runs); + if crate::watch::light() { + // All of the range is in the copy as of this asking. + let mut ranged = self.ranged.lock().unwrap_or_else(|e| e.into_inner()); + ranged[0] = (from, to, now); + if to - from >= ranged[1].1 - ranged[1].0 { + ranged[1] = (from, to, now); + } } bytes } + /// [`Shadow::take`] of `runs` (from, to, known), on several threads if + /// they are long: the big heap's copy has some 4 MB of them in each of + /// 14 refreshes a frame, on one thread while the others had nothing. + fn take_all(&self, runs: Vec<(usize, usize, bool)>) -> usize { + const LONG: usize = 1 << 20; + const PART: usize = 256 << 10; + let bytes = runs.iter().map(|r| r.1 - r.0).sum(); + if bytes < LONG || !crate::watch::light() { + for (from, to, known) in runs { + self.take(from, to, known); + } + return bytes; + } + let mut parts = Vec::with_capacity(bytes / PART + runs.len()); + for (from, to, known) in runs { + let mut at = from; + while at < to { + // Whole pages to a part. + let next = ((at / PAGE) * PAGE + PART).min(to); + parts.push((at, next, known)); + at = next; + } + } + let this = std::ptr::from_ref(self) as usize; + wide_each(parts.len(), move |i| { + // SAFETY: `wide_each` returns when every part is done, before + // the borrow of `self` ends. The parts lie apart. + let this = unsafe { &*(this as *const Shadow) }; + let (from, to, known) = parts[i]; + this.take(from, to, known); + }); + bytes + } + + /// Copies title memory `[from, to)` (inside the buffer) into the copy; + /// `known`: the copy held it before ([`send_changed`]). + fn take(&self, from: usize, to: usize, known: bool) -> usize { + if !known || self.card.is_none() || !send_changed() { + return self.copy(from, to); + } + let start = self.start as usize; + let mut at = from; + while at < to { + let n = (PAGE - at % PAGE).min(to - at); + // SAFETY: inside the mapping of the copy's CPU side, which + // nothing else writes there: no shader's range holds it. + let found = unsafe { crate::safecopy::update(self.data.add(at - start), at as *const u8, n) }; + SEND[0].fetch_add(n as u64, Ordering::Relaxed); + match found { + crate::safecopy::Updated::Same => { + SEND[1].fetch_add(n as u64, Ordering::Relaxed); + } + crate::safecopy::Updated::Changed(a, b) => { + SEND[2].fetch_add((b - a) as u64, Ordering::Relaxed); + self.changed(at - start + a, at - start + b); + self.card_changed(at - start + a, at - start + b); + } + // A page is not there: as before, around it, and all of it + // goes up. + crate::safecopy::Updated::Failed => { + self.copy(at, at + n); + } + } + at += n; + } + to - from + } + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. fn copy(&self, from: usize, to: usize) -> usize { let (start, end) = (self.start as usize, (self.start + self.len) as usize); @@ -2693,6 +3049,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 @@ -2809,6 +3201,317 @@ impl Shadow { } } +/// For tests: copies with no host buffer behind them. +#[cfg(test)] +impl Shadow { + /// A copy at `data` of title memory `[start, start + len)`, with a card + /// side if `card`. It is never let go: there is no buffer to release. + pub(crate) fn unbacked(start: u64, data: *mut u8, len: u64, card: bool) -> Arc { + // SAFETY: an interface pointer nothing calls. + let none = || unsafe { std::mem::transmute::(8) }; + let mut shadow = Shadow::new(none(), data, 0, start, len); + if card { + shadow.card = Some(Card { + staging: none(), + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len.next_multiple_of(PIECE as u64), + }); + } + let shadow = Arc::new(shadow); + std::mem::forget(shadow.clone()); + shadow + } + + /// What shaders wrote goes into title memory ([`put_changed`]). + pub(crate) fn put(at: usize, title: &[u8], merged: &[u8]) { + put_changed(at, title, merged); + } + + /// What is to go up to the card, noted as sent with `number`, as + /// [`card_dirty`] does; notes of sends up to `merged` go. + pub(crate) fn send_up(&self, number: u64, merged: u64) -> Vec<(usize, usize)> { + let card = self.card.as_ref().unwrap(); + let mut dirty = card.dirty.lock().unwrap(); + let ranges = std::mem::take(&mut *dirty); + let mut sent = card.sent.lock().unwrap(); + sent.retain(|s| s.2 > merged); + sent.extend(ranges.iter().map(|&(a, b)| (a, b, number))); + ranges + } + + /// What is to go up to the card, taken. + pub(crate) fn take_dirty(&self) -> Vec<(usize, usize)> { + std::mem::take(&mut *self.card.as_ref().unwrap().dirty.lock().unwrap()) + } +} + +impl Shadow { + /// [`Shadow::card_merge_relay`] of several pieces, each within one + /// 64 KiB block of title memory: from and to (offsets in the copy), and + /// where the fetched bytes are. On any thread: several may land pieces + /// of one copy, no two the same bytes. Returns the bytes put into title + /// memory. + /// + /// What is left out is as there, asked once for all of them: the notes + /// of bytes that went up (or are to go up) behind the fetch only move + /// from `dirty` to `sent`, with a later number, and grow only by + /// [`Shadow::merge_under_writes`], which the lock held here keeps out. + /// + /// # Safety + /// The third of each piece is the address of its bytes, which stay as + /// they are during the call. + pub(crate) unsafe fn land_card(&self, pieces: &[(usize, usize, usize)], fetched_after: u64, notes: &mut crate::land::Notes) -> u64 { + let Some(card) = &self.card else { + return 0; + }; + let waiting = std::time::Instant::now(); + let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner()); + crate::land::spent(crate::land::stat::LOCK, waiting); + let (from, to) = pieces.iter().fold((usize::MAX, 0), |(a, b), p| (a.min(p.0), b.max(p.1))); + let skip: Vec<(usize, usize)> = { + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); + dirty + .iter() + .copied() + .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .filter(|&(a, b)| a < to && b > from) + .collect() + }; + let mut put = 0; + for &(lo, hi, now) in pieces { + if lo >= hi || hi > self.len as usize { + continue; + } + let near: Vec<(usize, usize)> = skip.iter().copied().filter(|&(a, b)| a < hi && b > lo).collect(); + let parts: Vec<(usize, usize)> = outside(lo, hi, near).into_iter().map(|(a, b)| (a - lo, b - lo)).collect(); + // SAFETY: inside the mapping (checked above), in a range + // declared and not done with, which no refresh writes; the + // title's bytes are kept out by the lock; the caller's. + // Where title memory is not mapped the CPU's side keeps what + // the card wrote, as before. + let merged = + unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes) }; + self.walls_merged(hi - lo, merged as usize); + put += merged; + } + put + } + + /// [`Shadow::relay_merge`] of a piece `[at, at + n)` (within one 64 KiB + /// block of title memory) of a copy in the PC's memory; on any thread, + /// as [`Shadow::land_card`]. The copy is read once and never written. + /// Returns the bytes put into title memory. + pub(crate) fn land_back(&self, at: usize, n: usize, notes: &mut crate::land::Notes) -> u64 { + if self.card.is_some() || n == 0 || at + n > self.len as usize { + return 0; + } + let waiting = std::time::Instant::now(); + let _merging = self.merging.read().unwrap_or_else(|e| e.into_inner()); + crate::land::spent(crate::land::stat::LOCK, waiting); + // The snapshot's memory stays where it is until the range is done + // with (`copy_back_done`), which comes after this. + let Some(held) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut().map(Vec::as_mut_ptr) else { + return 0; + }; + // SAFETY: inside the copy's mapping (checked above), which only the + // card writes there, and inside the snapshot's allocation, which + // holds the copy's length (`writing`): these offsets are in a range + // declared and not done with, whose bytes it holds, and the lock + // keeps out what else writes them. Title memory that is not there + // is looked at again when the next flight that declared the range + // lands. + unsafe { crate::land::piece(self.start as usize + at, self.data.add(at), held.add(at), &[(0, n)], false, notes) } + } +} + +#[cfg(test)] +mod land_tests { + use super::{Card, PIECE, Shadow}; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + + /// A copy in the card's memory of title memory at `title` (its card side + /// is never looked at here), all bytes 0 on the CPU's side. + fn copy_of(title: usize, len: usize) -> Option { + let (buffer, data) = crate::host::host()?.shared_buffer(len as u64)?; + // SAFETY: the mapping, `len` bytes. + unsafe { std::ptr::write_bytes(data, 0, len) }; + let mut shadow = Shadow::new(buffer.clone(), data, 0, title as u64, len as u64); + shadow.card = Some(Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len as u64, + }); + Some(shadow) + } + + /// Memory that stays (`crate::watch` knows its addresses): private, or a + /// view noted as the runtime notes the title's. + fn memory(len: usize, view: bool) -> usize { + use windows_sys::Win32::System::Memory as mem; + // SAFETY: plain allocations of our own. + unsafe { + if !view { + return mem::VirtualAlloc(std::ptr::null(), len, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as usize; + } + let section = mem::CreateFileMappingW(-1isize as _, std::ptr::null(), mem::PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let at = mem::MapViewOfFile(section, mem::FILE_MAP_WRITE, 0, 0, len).Value as usize; + crate::inplace::title_memory_section(section as usize, len as u64, true); + crate::title_memory_remapped(at, len); + crate::inplace::title_memory_view(at, len, section as usize, 0); + at + } + } + + fn random(seed: &mut u64) -> usize { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + (*seed >> 8) as usize + } + + /// [`Shadow::land_card`] leaves title memory and the CPU's side as + /// [`Shadow::card_merge_relay`] does, with title bytes that went up + /// behind the fetch, or have not gone up, left out. + #[test] + fn pieces_land_as_the_merge_one_by_one_lands_them() { + assert!(crate::safecopy::on()); + const LEN: usize = 3 * PIECE; + let mut seed = 0x1234_5678_9abcu64; + for view in [false, true] { + let (a, b) = (memory(LEN, view), memory(LEN, view)); + let (Some(one), Some(many)) = (copy_of(a, LEN), copy_of(b, LEN)) else { + return; // no host GPU + }; + // SAFETY: the two memories and the two mappings. + let bytes = |at: usize| unsafe { std::slice::from_raw_parts_mut(at as *mut u8, LEN) }; + for round in 0..40u32 { + let base: Vec = (0..LEN).map(|_| random(&mut seed) as u8).collect(); + let (mut held, mut title, mut now) = (base.clone(), base.clone(), base); + let (mut dirty, mut sent) = (Vec::new(), Vec::new()); + for k in 0..120 { + let at = random(&mut seed) % LEN / 4 * 4; + let n = (random(&mut seed) % 900 / 4 * 4).min(LEN - at); + match k % 4 { + 0 | 1 => now[at..at + n].fill(random(&mut seed) as u8), + 2 => title[at..at + n].fill(random(&mut seed) as u8), + // Title bytes put into the CPU's side meanwhile. + _ => { + let byte = random(&mut seed) as u8; + held[at..at + n].fill(byte); + title[at..at + n].fill(byte); + if k % 8 == 3 { + dirty.push((at, at + n)); + } else { + sent.push((at, at + n, u64::from(round % 3) + (k as u64 / 16))); + } + } + } + } + let after = 4u64; + for (shadow, at) in [(&one, a), (&many, b)] { + crate::watch::writing(at, LEN); + bytes(at).copy_from_slice(&title); + bytes(shadow.data as usize).copy_from_slice(&held); + let card = shadow.card.as_ref().expect("made with one"); + *card.dirty.lock().unwrap() = dirty.clone(); + *card.sent.lock().unwrap() = sent.clone(); + } + let pieces: Vec<(usize, usize)> = (0..3).map(|p| (p * PIECE + 16, (p + 1) * PIECE - 4)).collect(); + let mut scratch = Vec::new(); + for &(lo, hi) in &pieces { + one.card_merge_relay(lo, &now[lo..hi], after, &mut scratch); + } + let addressed: Vec<(usize, usize, usize)> = + pieces.iter().map(|&(lo, hi)| (lo, hi, now.as_ptr() as usize + lo)).collect(); + let mut notes = crate::land::Notes::default(); + // SAFETY: the fetched bytes are `now`'s. + unsafe { many.land_card(&addressed, after, &mut notes) }; + notes.flush(); + assert!(bytes(a) == bytes(b), "title memory, round {round}"); + assert!(bytes(one.data as usize) == bytes(many.data as usize), "the CPU's side, round {round}"); + } + } + } + + /// Landings of one copy on several threads, the title writing dwords of + /// the same blocks, and the title's bytes put into the CPU's side under + /// the shaders' writes ([`Shadow::merge_under_writes`]), all at once. The + /// card has never received the title's bytes: what is fetched holds older + /// ones there, which must not be taken for shaders' writes. + #[test] + fn landings_and_title_bytes_going_in_keep_each_others_bytes() { + assert!(crate::safecopy::on()); + const BLOCKS: usize = 16; + const LEN: usize = BLOCKS * PIECE; + let title = memory(LEN, true); + let Some(shadow) = copy_of(title, LEN) else { + return; // no host GPU + }; + shadow.pending.lock().unwrap().push((title, title + LEN)); + // SAFETY: committed, aligned; touched as atomics or by the landing's + // stores of whole dwords. + let dword = |i: usize| unsafe { &*((title + i * 4) as *const AtomicU32) }; + let stop = AtomicBool::new(false); + std::thread::scope(|s| { + let writer = s.spawn(|| { + let mut value = 1u32; + while !stop.load(Ordering::Relaxed) { + for i in (1..LEN / 4).step_by(4 * 331) { + assert_eq!(dword(i).swap(value, Ordering::Relaxed), value - 1, "dword {i}: undone"); + } + value += 1; + std::thread::sleep(std::time::Duration::from_micros(200)); + } + value - 1 + }); + s.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let mut runs = usize::MAX; + assert!(!shadow.merge_under_writes(title, LEN, &mut runs)); + // Sent up, as the preparing of a submission would: noted + // with a number behind the fetches'. + let card = shadow.card.as_ref().expect("made with one"); + let mut dirty = card.dirty.lock().unwrap(); + let mut sent = card.sent.lock().unwrap(); + let moved: Vec<_> = std::mem::take(&mut *dirty).into_iter().map(|(a, b)| (a, b, 9)).collect(); + sent.extend(moved); + sent.sort_unstable(); + sent.dedup(); + } + }); + let mut now = vec![0u8; LEN]; + for round in 1..200u32 { + for block in (0..BLOCKS).filter(|b| (*b as u32 * 5 + round) % 3 != 0) { + for i in (block * PIECE / 4 + 3..(block + 1) * PIECE / 4).step_by(4) { + now[i * 4..i * 4 + 4].copy_from_slice(&(round << 20 | i as u32).to_le_bytes()); + } + } + let at = now.as_ptr() as usize; + crate::land::each(BLOCKS, &|b| { + let mut notes = crate::land::Notes::default(); + let (lo, hi) = (b * PIECE, (b + 1) * PIECE); + // SAFETY: the fetched bytes are `now`'s; each block once. + unsafe { shadow.land_card(&[(lo, hi, at + lo)], 8, &mut notes) }; + notes.flush(); + }); + for i in (3..LEN / 4).step_by(4 * 53) { + let expect = u32::from_le_bytes(now[i * 4..i * 4 + 4].try_into().expect("four")); + assert_eq!(dword(i).load(Ordering::Relaxed), expect, "round {round} dword {i}"); + } + } + stop.store(true, Ordering::Relaxed); + let last = writer.join().expect("nothing undone"); + assert!((1..LEN / 4).step_by(4 * 331).all(|i| dword(i).load(Ordering::Relaxed) == last)); + }); + } +} + struct Entry { end: u64, shadow: Option>, diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index ee9fa51..267597e 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -989,6 +989,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-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 74b0d80..dfae9f4 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -149,6 +149,8 @@ fn kernel_written(first: usize, last: usize) -> Option> { add(C::Watches, 1); add(C::WatchUs, started.elapsed().as_micros() as u64); slow(started.elapsed().as_micros() as u64); + tally(0, 1); + tally(1, ((last - first) * (PAGE >> 10)) as u64); } let mut pages: Vec = found[..count].iter().map(|&at| at / PAGE).collect(); pages.dedup(); @@ -173,7 +175,9 @@ const AHEAD_MAX: usize = (1 << 30) / PAGE; pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { let mut pieces: Vec<(usize, usize)> = ranges .iter() - .filter(|r| r.0 < r.1) + // Not view memory known by its bits: the kernel would refuse the + // asking (and, asked together with others, theirs). + .filter(|r| r.0 < r.1 && !published(r.0, r.1)) .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) .collect(); if pieces.len() < 2 { @@ -291,7 +295,7 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) { // here, once; what is not write-watched stays with `writes`. let mut written = Vec::new(); for &(start, end) in ranges { - if start >= end { + if start >= end || published(start, end) { continue; } let (first, last) = (start / PAGE, end.div_ceil(PAGE)); @@ -384,15 +388,24 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve if let Some(known) = ahead(&journal()) { return Some(known); } + // Read-only since an asking noted it: the bits first, then the journal. + if guarded && published(start, end) { + #[cfg(feature = "diagnostics")] + tally(2, 1); + let j = journal(); + return Some((next_asking(), of(&j))); + } // Asked, and the answer noted, with the range held: nothing else asks // about any of it in between. let _range = Asking::hold(first, last); if let Some(known) = ahead(&journal()) { return Some(known); } + let mut guards_asked = false; let pages = match kernel_written(first, last) { Some(pages) => pages, None => { + guards_asked = true; if !guarded { return None; } @@ -418,15 +431,189 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let j = journal(); return Some((next_asking(), of(&j))); } - let mut j = journal_mut(); - let now = next_asking(); - j.written.extend(pages.into_iter().map(|page| (page, now))); - Some((now, of(&j))) + let answer = { + let mut j = journal_mut(); + let now = next_asking(); + j.written.extend(pages.iter().map(|&page| (page, now))); + (now, of(&j)) + }; + // Noted: what the guards made clean of it is known by its bits from + // now on. (The range is still held: no other asking of any of it came + // between.) + if guards_asked && light() { + publish(&pages); + } + Some(answer) +} + +/// Whether nothing of `[start, end)` was written that a copy with the notes +/// `copied` (the asking after which each page from page `base` on was taken) +/// and `ranged` (the asking after which a range that holds this one was +/// taken whole, or 0) does not hold, as [`writes`] would answer with nothing +/// asked: the submission's asking covers the range, or its blocks are known +/// by their bits. `false` if something would have to be asked. +pub(crate) fn nothing_new(start: usize, end: usize, base: usize, copied: &[u64], ranged: u64) -> bool { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + // The bits first, then the journal, as in `writes`. + let known = published(start, end); + let j = journal(); + if !known && !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return false; + } + let Some(taken) = first.checked_sub(base).and_then(|from| copied.get(from..last - base)) else { + return false; + }; + (ranged != 0 || taken.iter().all(|&at| at != 0)) + && j.written.range(first..last).all(|(&page, &write)| write <= taken[page - first].max(ranged)) } /// Guarded blocks of view memory. const BLOCK: usize = PAGE; +/// Whether the refreshes of host copies go the light way +/// (`VICTORY_LIGHT_REFRESH=0`: as before): view memory nothing wrote since +/// it was last asked about is known by its bits ([`PUBLISHED`]), a copy +/// nothing of whose range changed is told so before any thread is woken +/// for it (`crate::host`, `Shadow::nothing_new`), and the ends of a range, +/// pages the range holds in part, are not copied again at every refresh +/// (`Shadow::copy_stale`). +/// +/// A frame asked about view memory some 1,500 times, for nearly all of it +/// to hear that nothing was written, on up to seven threads at once, each +/// asking under the guards' one lock and behind [`ASKING`]'s: 94 ms a frame +/// of all threads' time (run record-1), most of it waiting. +pub(crate) fn light() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_LIGHT_REFRESH").is_none_or(|v| v != "0")) +} + +/// A bit per block of the address space, in pieces made when first needed +/// and never let go. +struct Bits([std::sync::atomic::AtomicPtr; Bits::PIECES]); + +/// The bits of 4 GiB. +type BitsPiece = [std::sync::atomic::AtomicU64; Bits::WORDS]; + +impl Bits { + const WORDS: usize = 1 << 10; + /// 128 TiB, what a process has. + const PIECES: usize = 1 << 15; + + const fn new() -> Bits { + Bits([const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; Bits::PIECES]) + } + + fn piece(&self, word: usize) -> Option<&BitsPiece> { + let piece = self.0.get(word / Bits::WORDS)?.load(std::sync::atomic::Ordering::Acquire); + // SAFETY: null, or a piece made by `set`, which is never freed. + unsafe { piece.as_ref() } + } + + /// One caller at a time (under the guards' lock). + fn set(&self, block: usize) { + use std::sync::atomic::Ordering::{Relaxed, Release}; + let word = block / 64; + let Some(place) = self.0.get(word / Bits::WORDS) else { + return; + }; + if place.load(Relaxed).is_null() { + let piece: Box = Box::new([const { std::sync::atomic::AtomicU64::new(0) }; Bits::WORDS]); + place.store(Box::into_raw(piece), Release); + } + if let Some(piece) = self.piece(word) { + piece[word % Bits::WORDS].fetch_or(1 << (block % 64), Release); + } + } + + fn clear(&self, block: usize) { + let word = block / 64; + if let Some(piece) = self.piece(word) { + // Ahead of the protection's change, and seen by whoever the + // writer tells of its write. + piece[word % Bits::WORDS].fetch_and(!(1 << (block % 64)), std::sync::atomic::Ordering::SeqCst); + } + } + + /// Whether the bits of all of `[first, last)` are set (not so of none). + fn all(&self, first: usize, last: usize) -> bool { + let mut block = first; + while block < last { + let word = block / 64; + let until = ((word + 1) * 64).min(last); + let mask = (u64::MAX >> (64 - (until - block))) << (block % 64); + let Some(piece) = self.piece(word) else { + return false; + }; + if piece[word % Bits::WORDS].load(std::sync::atomic::Ordering::Acquire) & mask != mask { + return false; + } + block = until; + } + first < last + } +} + +/// The blocks that are read-only by our hand, not written since, and of +/// which the journal holds every write from before that: for those, what +/// [`writes`] answers is in the journal, and neither the kernel, nor the +/// guards' lock, nor [`ASKING`] need be asked. +/// +/// Why that is so: a block's bit is set under the guards' lock while the +/// block is clean, by the asking that made it clean, after that asking noted +/// in the journal what it found ([`publish`]). It is cleared under the same +/// lock, before the block becomes writable again ([`open`]) or is forgotten +/// ([`title_memory_remapped`]). So while the bit is set nothing can have +/// written the block through this address, and who sees the bit and looks +/// at the journal after that finds every earlier write in it. A write that +/// comes while the bit is looked at is no different from one that comes just +/// after an asking: the next asking finds the block open. +static PUBLISHED: Bits = Bits::new(); + +/// An asking made blocks of `pages` clean and noted them in the journal. +fn publish(pages: &[usize]) { + let g = guards(); + for page in pages { + if g.clean.contains(page) { + PUBLISHED.set(*page); + } + } +} + +/// Whether nothing of `[start, end)` can have been written since an asking +/// noted it in the journal ([`PUBLISHED`]). +fn published(start: usize, end: usize) -> bool { + light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK)) +} + +/// Since the last frame line: what asking about title memory was. Kernel +/// askings and the KiB they walked; view ranges answered by their bits, by +/// the guards whole clean, and block by block; blocks made read-only; blocks +/// opened by ourselves; nanoseconds waiting for the guards' lock and +/// nanoseconds of changing protections (all threads). +#[cfg(feature = "diagnostics")] +static ASKS: [std::sync::atomic::AtomicU64; 9] = [const { std::sync::atomic::AtomicU64::new(0) }; 9]; + +#[cfg(feature = "diagnostics")] +fn tally(what: usize, n: u64) { + ASKS[what].fetch_add(n, std::sync::atomic::Ordering::Relaxed); +} + +/// [`ASKS`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn asks() -> [u64; 9] { + std::array::from_fn(|i| ASKS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The guards' lock, the wait for it counted. +fn guards_timed() -> std::sync::MutexGuard<'static, Guards> { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + let g = guards(); + #[cfg(feature = "diagnostics")] + tally(7, started.elapsed().as_nanos() as u64); + g +} + struct Guards { /// Blocks we made read-only. protected: BTreeSet, @@ -449,7 +636,28 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { /// The 4 KiB pages of title memory that what shaders wrote was put into, /// and the frame it last was. -static LANDED: Mutex>> = Mutex::new(None); +static LANDED: Mutex>>> = Mutex::new(None); + +/// A page's number, spread: some 20,000 a frame are noted in [`LANDED`]. +#[derive(Default)] +struct PageHash(u64); + +impl std::hash::Hasher for PageHash { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &byte in bytes { + self.write_u64(u64::from(byte)); + } + } + fn write_u64(&mut self, n: u64) { + self.0 = (self.0 ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(26).wrapping_mul(0x9e37_79b9_7f4a_7c15); + } + fn write_usize(&mut self, n: usize) { + self.write_u64(n as u64); + } +} /// What shaders wrote is about to go into title memory at `[at, at + len)`. pub(crate) fn landing(at: usize, len: usize) { @@ -464,6 +672,48 @@ pub(crate) fn landing(at: usize, len: usize) { writing(at, len); } + +/// What shaders wrote went into title memory through another view of the +/// same pages (`crate::inplace::beside`): `pages` (of 4 KiB, by number) +/// hold some of it, all of them in `spans` (address, bytes). +/// +/// Nothing faulted and no guard was opened. A guarded block stays read-only, +/// clean, and known by its bit ([`PUBLISHED`]), all of which say that the +/// title wrote nothing there: our write is an entry of the journal, which +/// every answer about the block comes from, the quick ones and the guards' +/// alike (a block whose guard is off they report anyway). So neither the +/// guards' lock nor a protection is touched here, or by the next refresh. +/// Noted after the bytes are in, never before: a copy that read the block +/// before they were did so with the number of an asking made before that, +/// which is under the one given here, and takes it again; noted before, a +/// copy could read the older bytes with a number above the note's. +pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) { + { + let frame = crate::frame::current(); + let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner()); + let landed = landed.get_or_insert_with(Default::default); + for &page in pages { + landed.insert(page, frame); + } + } + { + let mut j = journal_mut(); + let now = next_asking(); + let mut last = usize::MAX; + for &page in pages { + let block = page * KERNEL_PAGE / PAGE; + if block != last { + j.written.insert(block, now); + last = block; + } + } + } + for &(at, len) in spans { + // A placed texture there changes with no descriptor written. + crate::descriptor::host::remapped(at, len); + } +} + /// Whether shaders' writes went into a page of `[at, at + len)` in the last /// `frames` frames. pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { @@ -476,7 +726,8 @@ pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool { /// Whether every block of `[at, at + len)` is view memory written since a /// host copy last took it: guarded then, and the guard is off. (Written by -/// the title, or by us putting a flight's shader writes into it.) Not for +/// the title, or by us putting a flight's shader writes into it, if not +/// beside the guard, [`landed_beside`].) Not for /// blocks no copy ever took, which were never guarded: the caller's range /// lies in a copy a flight was given, which took all of it. pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { @@ -485,7 +736,7 @@ pub(crate) fn written_since_taken(at: usize, len: usize) -> bool { } let g = guards(); (at / BLOCK..=(at + len - 1) / BLOCK) - .all(|b| !g.protected.contains(&b) && !g.clean.contains(&b) && !g.absent.contains(&b)) + .all(|b| !g.clean.contains(&b) && !g.absent.contains(&b)) } /// For view memory: the pages of `[start, end)`'s blocks written since @@ -501,7 +752,7 @@ fn guard(start: usize, end: usize) -> Option> { // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); let known = !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { - let g = guards(); + let g = guards_timed(); let first = start / BLOCK; g.protected.contains(&first) || g.absent.contains(&first) }; @@ -509,7 +760,7 @@ fn guard(start: usize, end: usize) -> Option> { return None; } install(); - let mut g = guards(); + let mut g = guards_timed(); let mut written = Vec::new(); let mut run: Option = None; let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); @@ -521,8 +772,12 @@ fn guard(start: usize, end: usize) -> Option> { let clean: Vec = g.clean.range(first..last).copied().collect(); if clean.len() == last - first { // Nothing written, mapped or new since the range was last taken. + #[cfg(feature = "diagnostics")] + tally(3, 1); return Some(written); } + #[cfg(feature = "diagnostics")] + tally(4, 1); let mut next_clean = 0; let mut uncommitted_until = first; for block in first..=last { @@ -610,15 +865,23 @@ fn protect(g: &mut Guards, from: usize, to: usize) { use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; let set = |from: usize, to: usize| { let mut old = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); // SAFETY: title view memory; only its protection changes. - unsafe { + let done = unsafe { VirtualProtect( (from * BLOCK) as *const _, (to - from) * BLOCK, PAGE_READONLY, &mut old, ) != 0 + }; + #[cfg(feature = "diagnostics")] + { + tally(5, (to - from) as u64); + tally(8, started.elapsed().as_nanos() as u64); } + done }; let note = |g: &mut Guards, from: usize, to: usize| { g.protected.extend(from..to); @@ -662,13 +925,21 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { .range(start / BLOCK..end.div_ceil(BLOCK)) .copied() .collect(); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); for &block in &blocks { g.protected.remove(&block); g.clean.remove(&block); + // Before the block can be written. + PUBLISHED.clear(block); let mut old = 0; // SAFETY: a block we made read-only. unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; } + #[cfg(feature = "diagnostics")] + if !blocks.is_empty() { + tally(8, started.elapsed().as_nanos() as u64); + } !blocks.is_empty() } @@ -678,7 +949,14 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { /// reads into its own memory. pub fn writing(at: usize, len: usize) { // The length is the title's (`fread`'s size times count, saturated). - open(&mut guards(), at, at.saturating_add(len)); + { + let mut g = guards_timed(); + #[cfg(feature = "diagnostics")] + let held = g.protected.len(); + open(&mut g, at, at.saturating_add(len)); + #[cfg(feature = "diagnostics")] + tally(6, (held - g.protected.len()) as u64); + } // A placed texture there changes with no descriptor written. crate::descriptor::host::remapped(at, len); } @@ -758,6 +1036,7 @@ pub fn title_memory_unmapping(at: usize, len: usize) { for block in blocks { g.protected.remove(&block); g.clean.remove(&block); + PUBLISHED.clear(block); } } @@ -1338,4 +1617,111 @@ mod many_askers_tests { // SAFETY: the reservation made above. unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) }; } + + /// The same of view memory, which is guarded: what its bits answer + /// misses no write either, however often blocks are opened and guarded + /// again between. + #[test] + fn no_write_to_views_is_lost_between_askers() { + const PAGES: usize = 12; + const THREADS: usize = 8; + // SAFETY: a view of a section of our own. + let at = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (PAGES * PAGE) as u32, + std::ptr::null(), + ); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, PAGES * PAGE).Value as usize; + crate::title_memory_section(section as usize, (PAGES * PAGE) as u64, true); + super::title_memory_remapped(at, PAGES * PAGE); + crate::title_memory_view(at, PAGES * PAGE, section as usize, 0); + at + }; + assert!(at != 0 && at.is_multiple_of(PAGE)); + let by_bits = std::sync::atomic::AtomicUsize::new(0); + let past = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|s| { + for t in 0..THREADS { + let (by_bits, past) = (&by_bits, &past); + s.spawn(move || { + let mut last = [0u64; PAGES]; + let mut seed = t as u64 * 7919 + 1; + let mut next = |n: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for _ in 0..500 { + let page = next(PAGES); + let from = page - next(page.min(3) + 1); + let to = page + 1 + next((PAGES - page).min(3)); + if next(4) != 0 { + // As in the test above, or after a word of ours, + // or past the guard. + let word = at + page * PAGE + t * 8; + // SAFETY (both): as above. + let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten(); + let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8)); + if let Some(to) = beside { + unsafe { (to as *mut u64).write_volatile(2) }; + super::landed_beside(&[word / 4096], &[(word, 8)]); + past.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere"); + } else { + if next(4) == 0 { + super::writing(word, 8); + } + unsafe { (word as *mut u64).write_volatile(1) }; + } + } else { + // Nothing written: what is asked counts as before. + by_bits.fetch_add( + usize::from(super::published(at + from * PAGE, at + to * PAGE)), + std::sync::atomic::Ordering::Relaxed, + ); + let (now, _) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + for l in &mut last[from..to] { + *l = now; + } + continue; + } + let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view"); + let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1); + assert!(number > last[page], "page {page}: {number} is not after {}", last[page]); + for l in &mut last[from..to] { + *l = now; + } + } + }); + } + }); + assert!(by_bits.into_inner() > 0, "the bits answered none"); + assert!(past.into_inner() > 0, "nothing was put past the guards"); + // (The view stays: at its address other tests' memory would be told + // of these writes.) + } + + /// A range's bits are all of its blocks', whatever lies beside them. + #[test] + fn bits_of_ranges() { + static BITS: super::Bits = super::Bits::new(); + let blocks = [0usize, 1, 63, 64, 65, 127, 128, 200, 65535, 65536, 65537, 1 << 20, (1 << 31) - 1]; + for &b in &blocks { + assert!(!BITS.all(b, b + 1)); + BITS.set(b); + assert!(BITS.all(b, b + 1)); + } + assert!(BITS.all(0, 2) && BITS.all(63, 66) && BITS.all(127, 129) && BITS.all(65535, 65538)); + assert!(!BITS.all(0, 3) && !BITS.all(62, 64) && !BITS.all(65534, 65536) && !BITS.all(5, 5)); + for b in 300..700 { + BITS.set(b); + } + assert!(BITS.all(300, 700) && !BITS.all(299, 700) && !BITS.all(300, 701)); + BITS.clear(511); + assert!(!BITS.all(300, 700) && BITS.all(300, 511) && BITS.all(512, 700)); + assert!(!BITS.all(1 << 40, (1 << 40) + 1), "outside the address space"); + } } diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index cf5be26..87e635e 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); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 56d56ca..36dd2bd 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -419,6 +419,7 @@ impl Drop for Section { }) }; } + victory_gpu::title_memory_section_gone(self.handle as usize); // SAFETY: our handle; views keep the section alive on their own. unsafe { CloseHandle(self.handle) }; } diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 13551c3..89dc8b7 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -63,6 +63,8 @@ pub const ALL: u32 = MODULE | FIRST; pub(crate) struct Usage { /// A wave or quad operation. pub wave_ops: bool, + /// A rasterizer ordered view. + pub rovs: bool, /// A 64-bit integer, as a result or an operand. pub int64: bool, /// A typed load of several components from a UAV. @@ -388,7 +390,7 @@ impl Module { } /// An integer constant's width and value (the bits of that width). - fn int_k(&self, v: V) -> Option<(u32, u64)> { + pub(crate) fn int_k(&self, v: V) -> Option<(u32, u64)> { let V::Const(i) = v else { return None }; let (ty, Const::Int(x)) = &self.consts[i as usize] else { return None; @@ -1009,6 +1011,8 @@ impl Module { Some((_, 0)) => u.heap_views = true, _ => u.heap_samplers = true, } + } else if name == "annotateHandle" { + u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0); } else if name.starts_with("atomic") && name.ends_with(".i64") { u.atomic64 = true; } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c2a9d35..899255f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -107,6 +107,64 @@ pub(crate) fn lower(parts: &Parts) -> Result { const TWO_PI: f32 = std::f32::consts::TAU; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; +/// `s_sendmsg` id that ends a pixel wave's ordered section. +const ORDERED_PS_DONE: u16 = 7; +/// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in +/// before it waits for the waves it overlaps. +const POPS_PACKER: u16 = 25; +/// The operand `src_pops_exiting_wave_id`. +const POPS_EXITING: u8 = 239; + +/// The instructions inside a pixel program's ordered section +/// (primitive-ordered pixel shading, which the console compiler makes of +/// rasterizer ordered views): from the write of `POPS_PACKER`, along every +/// path, to the message that ends the section or the program's end. The +/// console waits there until the waves holding earlier primitives' samples +/// of the same pixels have left their sections; a host's rasterizer ordered +/// views wait by themselves, at their first access. Empty for a program +/// without such a section. +fn ordered_section(p: &Program) -> HashSet { + let starts = |i: &Inst| { + i.name() == "s_setreg_b32" + && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER) + }; + let ends = |i: &Inst| { + i.name() == "s_sendmsg" + && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE) + }; + let mut section = HashSet::new(); + let mut entered = vec![false; p.blocks.len()]; + let mut work: Vec = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + (0..block.insts.len()) + .filter(|&i| starts(&block.insts[i])) + .map(move |i| (b, i)) + }) + .collect(); + while let Some((b, from)) = work.pop() { + let block = &p.blocks[b]; + let mut done = false; + for i in from..block.insts.len() { + if ends(&block.insts[i]) { + done = true; + break; + } + section.insert((b, i)); + } + if done { + continue; + } + for (t, next) in p.blocks.iter().enumerate() { + if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) { + work.push((t, 0)); + } + } + } + section +} /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). @@ -194,6 +252,13 @@ struct Lower<'a> { /// Descriptor dwords with no host value (addresses, formats, all of a constant /// buffer's): no program reads them as numbers ([`Self::dead`]). stale: HashSet, + /// See [`ordered_section`] (pixel programs). + ordered: HashSet, + /// Raw UAV buffers (see [`Lower::entry`]) the program loads from past its + /// wave's cache (GLC): other groups write what it waits for. On the host + /// they are globally coherent; a load in a loop that only waits would + /// be made once otherwise. + coherent: HashSet<(usize, u32)>, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1486,6 +1551,12 @@ impl<'a> Lower<'a> { data_phis: Vec::new(), read_phis: HashSet::new(), stale: HashSet::new(), + coherent: HashSet::new(), + ordered: if x.native.stage == HwStage::Ps { + ordered_section(p) + } else { + HashSet::new() + }, params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), @@ -2064,9 +2135,12 @@ impl<'a> Lower<'a> { /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange /// their halves' sums for the last addition. The high half of the result is lane 0's, /// which no `v_add_f16` writes. - /// That needs every lane of a full wave there to be read: refused where not every lane - /// runs, in a thread group that does not fill its waves, and for each half-wave on its - /// own (half a sum is no sum). + /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere + /// count as the console's do (it masks them to +0): a partner's partial sum is read from + /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host + /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread + /// group that does not fill its waves, and for each half-wave on its own (half a sum is + /// no sum). fn half_sum(&mut self, x: V) -> Result { const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; @@ -2087,24 +2161,54 @@ impl<'a> Lower<'a> { } else { all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) }; - if !every { - if halves { - need(self.cur_ir); - } + if !every && halves { + need(self.cur_ir); return Err(WHERE); } let c = self.cur; let i32t = self.s.t.i32; let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + // the lanes that are here, when not all are + let here = (!every).then(|| { + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let yes = self.s.m.bool(true); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]); + (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)) + }); + // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none + let first_of = |l: &mut Self, v: V, base: V, n: u32| { + let Some((lo, hi)) = here else { + return l.read_lane(v, base); + }; + let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32)); + let lower = l.s.m.cmp(c, pred::IULT, base, k32); + let word = l.s.m.select(c, lower, lo, hi); + let shift = l.s.m.bin(c, Bin::And, base, k31); + let word = l.s.m.bin(c, Bin::LShr, word, shift); + let run = l.s.m.i32(u32::MAX >> (32 - n)); + let word = l.s.m.bin(c, Bin::And, word, run); + let any = l.s.m.cmp(c, pred::NE, word, zero); + let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]); + let from = l.s.m.bin(c, Bin::Add, base, nth); + // (no lane there: this one, which is here; the read is not used) + let from = l.s.m.select(c, any, from, lane); + let got = l.read_lane(v, from); + l.s.m.select(c, any, got, zero) + }; let mut sum = x; for step in 0..if halves { 5 } else { 6 } { let bit = self.s.m.i32(1 << step); - let partner = self.s.m.bin(c, Bin::Xor, lane, bit); - let theirs = self.read_lane(sum, partner); + let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit); + if !every { + let run = self.s.m.i32(!((1 << step) - 1)); + partner = self.s.m.bin(c, Bin::And, partner, run); + } + let theirs = first_of(self, sum, partner, 1 << step); sum = self.add_halves(sum, theirs); } - let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); - let first = self.read_lane(x, zero); + let first = first_of(self, x, zero, 1); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); let mine = self.s.m.bin(c, Bin::Or, first, sum); @@ -2121,6 +2225,7 @@ impl<'a> Lower<'a> { fn run(mut self) -> Result { let p = self.x.p; + self.find_coherent(); let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { self.rpo[b] = n; @@ -2258,6 +2363,8 @@ impl<'a> Lower<'a> { // paths only seem to allow it before any save: the lane of a VGPR // nobody wrote, and VGPRs nobody set read as zero. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), + // No wave overlaps this one (see `ordered_section`). + None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)), None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), @@ -2273,6 +2380,36 @@ impl<'a> Lower<'a> { Ok(()) } + /// Whether the input SGPR `v` is the POPS collision wave id: a program + /// with an ordered section only takes its fields apart (bit 31 says + /// that the wave overlaps another, the others which packer and waves). + fn pops_collision(&self, v: Value) -> bool { + if self.ordered.is_empty() { + return false; + } + let mut packer = false; + for block in &self.x.p.blocks { + if block.phis.iter().any(|p| p.args.contains(&v)) { + return false; + } + for i in &block.insts { + if !i.reads.iter().any(|r| r.1 == v) { + continue; + } + let Fields::Sop { src, .. } = &i.fields else { + return false; + }; + match (i.name(), src.get(1)) { + // bits 28 and 29: the packer + ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true, + ("s_bfe_u32" | "s_lshr_b32", _) => {} + _ => return false, + } + } + } + packer + } + fn input(&mut self, input: Input) -> Val { let (kind, col) = match input { Input::VertexId => (1, 0), @@ -2632,6 +2769,18 @@ impl<'a> Lower<'a> { self.s.m.extract(entry, r, index % 4) } + /// Whether some instruction reads `v` as a number (or may, through a + /// join), rather than in a descriptor operand. + fn read_as_number(&self, v: Value) -> bool { + self.x.p.blocks.iter().any(|b| { + b.phis.iter().any(|p| p.args.contains(&v)) + || b.insts.iter().any(|i| { + matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_)) + && i.reads.iter().any(|r| r.1 == v) + }) + }) + } + /// Whether some instruction computes with `v` (scalar or vector /// arithmetic), rather than only naming it in a descriptor operand, /// moving it (at most `depth` moves are followed) or comparing it: a @@ -2665,6 +2814,112 @@ impl<'a> Lower<'a> { }) } + /// Whether the image `src` names is one of 32-bit integers (one channel): + /// the program has an integer atomic on the same table entry, which + /// takes no other view. + fn is_counter(&self, src: &Source) -> bool { + let Some(this) = self.entry(src) else { + return false; + }; + self.x.res.descriptors.iter().any(|d| { + let i = &self.x.p.blocks[d.site.0].insts[d.site.1]; + d.role == Role::Resource + && matches!(i.fields, Fields::Image { dmask: 1, .. }) + && matches!( + i.name(), + "image_atomic_add" + | "image_atomic_sub" + | "image_atomic_and" + | "image_atomic_or" + | "image_atomic_xor" + | "image_atomic_smin" + | "image_atomic_smax" + | "image_atomic_umin" + | "image_atomic_umax" + ) + && self.entry(&d.source) == Some(this) + }) + } + + /// Which table entry `src` is loaded from: its root parameter and byte. + fn entry(&self, src: &Source) -> Option<(usize, u32)> { + let Source::Loaded { load, first } = src else { + return None; + }; + let a = self.scalar.get(load).filter(|a| a.dynamic.is_none())?; + Some((a.param, a.offset + 4 * u32::from(*first))) + } + + /// See [`Lower::coherent`]. + fn find_coherent(&mut self) { + let found: Vec<_> = self + .x + .res + .descriptors + .iter() + .filter(|d| { + let i = &self.x.p.blocks[d.site.0].insts[d.site.1]; + matches!(&i.fields, Fields::Buffer { cache, .. } if cache.glc) + && i.name().starts_with("buffer_load_dword") + && self.used_kind(&d.source).is_some_and(|u| u.kind == ResourceType::Uav) + }) + .filter_map(|d| self.entry(&d.source)) + .collect(); + self.coherent.extend(found); + } + + /// The kind of a view no instruction uses (in this program, or through + /// another load of its address), by what the code reads of the + /// descriptor the load `inst` at `site` writes to the SGPRs from `code`: + /// `Some(true)` for a 2D image, read only for its size, `Some(false)` + /// for a structured buffer, read only for its record count. + /// + /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the + /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one + /// `s_bfe_u32`) and the base level or the last (dword 3); of an array, + /// a cube or a volume also dword 4. + /// - Four dwords at a table entry the used resources list as an SRV or + /// UAV are a buffer's. A stride above 4 bytes there is an element's + /// (a typed or raw view has at most 4): a test for a null view reads + /// the record count, nothing else. + fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option { + let dword = |k: u8| inst.write(Reg::S(code + k)); + let read = |v: Value| { + self.x.p.blocks.iter().any(|b| { + b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v)) + || b.phis.iter().any(|p| p.args.contains(&v)) + }) + }; + let only = |allowed: &[u8]| { + (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read)) + }; + match count { + 8 => { + const HEIGHT: u32 = 16 << 16 | 14; + let v = dword(2)?; + let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + i.name() == "s_bfe_u32" + && i.reads.iter().any(|r| r.1 == v) + && matches!(&i.fields, Fields::Sop { src, .. } + if matches!(src.get(1), Some(Operand::Literal(HEIGHT)))) + }); + (height && only(&[1, 2, 3])).then_some(true) + } + 4 => { + let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?; + let a = self.scalar.get(&site)?; + let buffer = used.dwords == 4 + && a.dynamic.is_none() + && used.table_offset_dwords == a.offset / 4 + && matches!(used.kind, ResourceType::Srv | ResourceType::Uav) + && used.stride > 4 + && used.stride.is_multiple_of(4); + (buffer && only(&[2])).then_some(false) + } + _ => None, + } + } + /// The title address (low dword, bits from 32 up) of the buffer view /// whose descriptor the scalar load at `site` reads from the start of /// a table entry, as the host tells it when it binds (`shader.rs` @@ -3116,6 +3371,8 @@ impl<'a> Lower<'a> { let bit = self.scc_in(inst)?; Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32)) } + // Nothing to wait for (see `ordered_section`). + Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)), Operand::Const(c) => crate::resource::inline(c) .map(|x| self.s.m.i32(x)) .ok_or("a special operand (vccz, execz, scc, lds_direct)"), @@ -5400,12 +5657,30 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; - match self.get(v)? { - Val::Bit(x) => Ok(x), - _ => Err("SCC without a value"), + match self.get(v) { + Ok(Val::Bit(x)) => Ok(x), + Ok(_) => Err("SCC without a value"), + // Of a mask operation whose result lies within EXEC: whether + // some lane is left. + Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v), + Err(why) => Err(why), } } + /// Whether the mask operation that sets the SCC value `scc` gives no + /// lane outside EXEC a bit. + fn within_exec(&self, scc: Value) -> bool { + let Some(&b) = self.def_block.get(&scc) else { + return false; + }; + let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc)); + by.is_some_and(|i| { + i.write(Reg::S(EXEC)).is_some() + || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. } + if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo))) + }) + } + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Fields::Smem { data, @@ -5653,7 +5928,12 @@ impl<'a> Lower<'a> { .find_map(|(s, _)| use_of(*s)) }; let use_at = use_of(site).or_else(twin); - let Some((at, first)) = use_at else { + // A view whose kind no use tells, but what is read of it does. + let sized = match use_at { + Some(_) => None, + None => self.sized_view(inst, site, code, count), + }; + let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else { // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only // copies its dwords and compares them, lane against first lane, and every load // that reaches those lanes reads one address. Each dword stands in as its place @@ -5721,6 +6001,8 @@ impl<'a> Lower<'a> { || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let (props, image) = match &ui.fields { + _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)), + _ if sized.is_some() => ((11 | u, 0), None), // A ray-tracing structure in a buffer of the host: read raw. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), Fields::Image { dim, .. } => { @@ -5736,13 +6018,25 @@ impl<'a> Lower<'a> { } Fields::Buffer { idxen, format, .. } => { let stride = used.map_or(0, |u| u.stride); + let counted = inst + .write(Reg::S(code + first + 2)) + .is_some_and(|v| self.read_as_number(v)); let props = if un.starts_with("buffer_load_format") || un.starts_with("buffer_store_format") { (10 | u, 0x409) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { + } else if !counted + && *idxen + && format.is_none() + && stride >= 4 + && stride.is_multiple_of(4) + { + // Nothing reads the count: the query is cleaned up. (12 | u, stride) } else { + // Structured ones too: the host's views of them are raw + // (see `buffer`), which count bytes, and a size asked + // for as a structured view's is that count on AMD. (11 | u, 0) }; if used.is_some_and(|u| u.kind == ResourceType::Cbv) { @@ -5816,9 +6110,20 @@ impl<'a> Lower<'a> { // A raw view counts bytes; the descriptor's record count is in elements. let n = field(self, 0); let stride = used.map_or(0, |u| u.stride); + let counted = inst + .write(Reg::S(code + first + 2)) + .is_some_and(|v| self.read_as_number(v)); let n = if props.0 & 0xFF == 11 && stride > 1 { let k = self.s.m.i32(stride); self.s.m.bin(c, Bin::UDiv, n, k) + } else if props.0 & 0xFF == 11 + && counted + && let Some(stride) = self.slot_stride(&src)? + { + // Picked from the heap: the host's table has the stride. + let (i32t, one) = (self.s.t.i32, self.s.m.i32(1)); + let k = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 39, &[stride, one]); + self.s.m.bin(c, Bin::UDiv, n, k) } else { n }; @@ -6610,6 +6915,17 @@ impl<'a> Lower<'a> { self.lane(inst, Some(true)); return Ok(()); } + // One lane of a VGPR a whole-wave section left. + if name == "v_readlane_b32" + && let Some(&(_, w)) = inst.writes.first() + && let Some(sh) = self.sections.get(&b).and_then(|s| { + s.iter().filter(|s| s.1.end < i).find_map(|s| s.1.reads.get(&w).copied()) + }) + { + let x = self.shape(sh, false)?; + self.vals.insert(w, Val::I32(x)); + return Ok(()); + } if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { let r = if v.dpp.is_some() { Err("a compare with DPP") @@ -9549,7 +9865,13 @@ impl<'a> Lower<'a> { || self .used_kind(src) .is_some_and(|u| u.kind == ResourceType::Uav); - let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + // A UAV inside an ordered section is a rasterizer ordered view. + let ordered = uav && self.ordered.contains(&site); + if ordered { + self.s.flags |= flags::ROVS; + } + let rov = if ordered { 0x2000 } else { 0 }; + let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409); if let Some(op) = name.strip_prefix("image_atomic_") { // GLC returns the old value. DXIL implements subtraction by adding // the two's complement of the operand at the same width. @@ -9607,7 +9929,7 @@ impl<'a> Lower<'a> { } else { original }; - let h = self.handle(site, src, false, (kind | 0x1000, component))?; + let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?; let mut args = vec![h]; let (intrinsic, opcode) = if compare { let comparand = if wide { @@ -9660,7 +9982,9 @@ impl<'a> Lower<'a> { } // shortcut: stores are taken to write all four channels of a // float format (the console converts by the view's format). - if *dmask != 0xF { + // One channel goes into a view the program also counts in. + let counter = *dmask == 1 && self.is_counter(src); + if *dmask != 0xF && !counter { return Err("an image store of some channels"); } let iu = self.s.m.undef(self.s.t.i32); @@ -9671,6 +9995,34 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image store data"); }; + if counter { + let v = inst.read(Reg::V(reg)).ok_or("image store data")?; + let x = self.i32_of(v)?; + // A 16-bit integer, extended by the view's sign: the same + // number either way only if it is known to be small. + if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) { + return Err("a 16-bit image store of one channel"); + } + let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?; + let at = self.begin_guarded(guard); + // All four channels are written (the validator wants them + // all): the view has the first alone. + let mut args = vec![h]; + args.extend(cs); + args.extend([x; 4]); + args.push(self.s.m.i8(0xF)); + let void = self.s.t.void; + self.s.op( + self.cur, + "textureStore.i32", + Attr::NoUnwind, + void, + 67, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } let mut vals = Vec::new(); for k in 0..4u8 { // d16: two f16 channels per VGPR, low half first. @@ -10445,7 +10797,10 @@ impl<'a> Lower<'a> { return Ok(()); } let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; + let mut u = if uav { 0x1000 } else { 0 }; + if uav && !typed && self.entry(src).is_some_and(|e| self.coherent.contains(&e)) { + u |= 0x4000; + } let iu = self.s.m.undef(self.s.t.i32); if let Some((bits, signed)) = narrow { // Below a dword: raw buffers are read and written in dwords on diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 9ca8313..d919660 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -99,6 +99,8 @@ mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] +mod size_tests; +#[cfg(all(test, windows))] mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; @@ -859,6 +861,134 @@ mod tests { assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); } + /// A pixel program with an ordered section, as the console compiler + /// makes one of rasterizer ordered views (the title's hair cards keep + /// their nearest layers that way): the wait for overlapped waves is + /// skipped, the views inside the section are the host's ordered ones, + /// the one after it is not. + #[test] + fn an_ordered_section_uses_rasterizer_ordered_views() { + let section = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00_0000, + 0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c + 0x0002_001C, + 0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000 + 0x000A_0000, + 0x8F10_8110, // s_lshl_b32 s16, s16, 1 + 0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010 + 0x000A_0010, + 0xBE91_0711, // s_not_b32 s17, s17 + 0x9013_9F01, // s_lshr_b32 s19, s1, 31 + 0x8810_8110, // s_or_b32 s16, s16, 1 + 0x8112_1112, // s_add_i32 s18, s18, s17 + 0xBF06_8013, // s_cmp_eq_u32 s19, 0 + 0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16 + 0x8514_807E, // s_cselect_b32 s20, exec_lo, 0 + 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF08_1215, // s_cmp_gt_u32 s21, s18 + 0x8516_807E, // s_cselect_b32 s22, exec_lo, 0 + 0x8814_1614, // s_or_b32 s20, s20, s22 + 0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20 + 0xBF87_0004, // s_cbranch_vccnz past the wait + 0xBF8E_FFFF, // s_sleep 0xffff + 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF0A_1512, // s_cmp_lt_u32 s18, s21 + 0xBF84_FFFC, // s_cbranch_scc0 back to the sleep + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc + 0x0002_0200, + 0x0604_04F2, // v_add_f32 v2, 1.0, v2 + 0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc + 0x0002_0200, + 0xBEFC_0380, // s_mov_b32 m0, 0 + 0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE) + ]; + let end = [ + 0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm + 0x0202_0202, + 0xBF81_0000, // s_endpgm + ]; + // A store after the section, through an ordinary view. + let after = [0xF020_3F08u32, 0x0002_0200]; + let lower = |words: Vec| { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![crate::native::RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![crate::native::UsedResource { + kind: crate::native::ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 8, + user_data: 0, + slot: 0, + }], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + let out = emit(&c, &native, &p, &st, &io, &res)?; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + Ok::(u64::from_le_bytes(sfi0.try_into().unwrap())) + }; + // D3D_SHADER_REQUIRES_ROVS + let features = lower([§ion[..], &end].concat()).unwrap(); + assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs"); + lower([§ion[..], &after, &end].concat()).unwrap(); + // The same accesses outside a section: ordinary views, no feature. + let plain = [§ion[..4], §ion[28..35], &end].concat(); + let features = lower(plain).unwrap(); + assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs"); + // Without the section's start the wait stays unknown. + let mut unmarked = [§ion[..], &end].concat(); + unmarked.remove(16); + assert!(lower(unmarked).is_err()); + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 28a36f1..eb6d589 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -76,6 +76,7 @@ pub(crate) mod flags { pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const BARYCENTRICS: u64 = 1 << 22; pub const INT64: u64 = 1 << 20; @@ -455,6 +456,7 @@ impl Shader { self.m.optimise(passes); let used = self.m.usage(); for (flag, used) in [ + (flags::ROVS, used.rovs), (flags::WAVE_OPS, used.wave_ops), (flags::INT64, used.int64), (flags::TYPED_UAV_LOADS, used.typed_uav_loads), @@ -787,6 +789,9 @@ impl Shader { if self.flags & flags::TYPED_UAV_LOADS != 0 { features |= 0x800; } + if self.flags & flags::ROVS != 0 { + features |= 0x1000; + } if self.flags & flags::WAVE_OPS != 0 { features |= 0x4000; } diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs new file mode 100644 index 0000000..a0023b8 --- /dev/null +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -0,0 +1,300 @@ +//! End-to-end tests of what a program tells about a view by how it uses it: +//! descriptors read for sizes (the dwords of a view no instruction uses) and +//! counters, lowered to DXIL, validated by `dxil.dll` when present, and run +//! on the host GPU and WARP. + +use super::host::{Stride, View}; +use super::waterfall_tests::run; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Lowers a wave32 compute program of one thread with the table of views at +/// s0 and the view heap at s1; `srv`: the dwords and the stride of the used +/// resource at the table's first entry (the third is a raw UAV). +fn build(words: &[u32], srv: (u8, u32)) -> Result { + let param = |root, user_data| RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: 0, + }; + let range = |kind, table_offset_dwords, dwords, stride| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data: 0, + slot: 0, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![param(RootType::Table, 0), param(RootType::ResourceHeap, 1)], + used: vec![ + range(ResourceType::Srv, 0, srv.0, srv.1), + range(ResourceType::Uav, 16, 4, 0), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + })?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + Ok(shader) +} + +/// The table at s[2:3], its raw UAV's descriptor in s[20:23]. +const TABLE: &[u32] = &[ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0501, // s_load_dwordx4 s[20:23], s[2:3], 64 + 0xFA00_0040, +]; + +/// Stores s4 and s5 at bytes 0 and 4 of the UAV. +const STORE: &[u32] = &[ + 0x7E08_0204, // v_mov_b32 v4, s4 + 0x7E0A_0205, // v_mov_b32 v5, s5 + 0xE070_0000, // buffer_store_dword v4, off, s[20:23], 0 + 0x8005_0400, + 0xE070_0004, // buffer_store_dword v5, off, s[20:23], 0 offset:4 + 0x8005_0500, + 0xBF81_0000, // s_endpgm +]; + +/// `GetDimensions` of a texture as the console compiler expands it, from +/// the descriptor in s[8:15]: width in s4, height in s5, base level in s6. +const SIZES: &[u32] = &[ + 0x9004_9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05_820A, // s_lshl_b32 s5, s10, 2 + 0x8804_0504, // s_or_b32 s4, s4, s5 + 0x8704_FF04, // s_and_b32 s4, s4, 0xffff + 0x0000_FFFF, + 0x9385_FF0A, // s_bfe_u32 s5, s10, 0x10000e + 0x0010_000E, + 0x9386_FF0B, // s_bfe_u32 s6, s11, 0x4000c + 0x0004_000C, + 0x8104_8104, // s_add_i32 s4, s4, 1 + 0x8105_8105, // s_add_i32 s5, s5, 1 + 0x9004_0604, // s_lshr_b32 s4, s4, s6 + 0x9005_0605, // s_lshr_b32 s5, s5, s6 +]; + +/// s_load_dwordx8 s[8:15], s[6:7], s12: entry 1 of the view heap. +const FROM_HEAP: &[u32] = &[ + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xBE8C_03A0, // s_mov_b32 s12, 32 + 0xF40C_0203, + 0x1800_0000, +]; + +/// `s_load_dwordx4 s[8:11], s[2:3], 0`, then the record count in s4 and 0 +/// in s5. +const COUNT: &[u32] = &[ + 0xF408_0201, + 0xFA00_0000, + 0xBE84_030A, // s_mov_b32 s4, s10 + 0xBE85_0380, // s_mov_b32 s5, 0 +]; + +/// A puddle pass of the title picks three textures from the view heap, +/// reads the first one's size and samples the other two. +#[test] +fn the_size_of_a_heap_texture_nothing_reads() { + let words = [TABLE, FROM_HEAP, SIZES, STORE].concat(); + let shader = build(&words, (8, 0)).expect("translates"); + let (one, texels) = ([[0.0; 4]; 1], [[0.0; 4]; 15]); + let views = [ + View::Texture(1, 1, &one), + View::Texture(5, 3, &texels), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [5, 3], "{label}"); + } +} + +/// Without the height nothing tells a 2D texture from the others, and a +/// volume's depth or an array's layers are no 2D texture's. +#[test] +fn sizes_of_unknown_dimensions_stay_untranslated() { + let width = [ + 0x9004_9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05_820A, // s_lshl_b32 s5, s10, 2 + 0x8804_0504, // s_or_b32 s4, s4, s5 + ]; + let words = [TABLE, FROM_HEAP, &width, STORE].concat(); + assert!(build(&words, (8, 0)).is_err()); + let depth = [ + 0x8805_0C05, // s_or_b32 s5, s5, s12 + ]; + let words = [TABLE, FROM_HEAP, SIZES, &depth, STORE].concat(); + assert!(build(&words, (8, 0)).is_err()); +} + +/// A water simulation step runs only while a structured buffer is bound: +/// it tests the record count of a view it never reads. +#[test] +fn the_record_count_of_a_structured_buffer_nothing_reads() { + let words = [TABLE, COUNT, STORE].concat(); + let shader = build(&words, (4, 16)).expect("translates"); + let (data, texel) = ([0u32; 12], [[0.0; 4]; 1]); + // The runtime makes structured views raw. + let views = [ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [3, 0], "{label}"); + } + // A stride of 4 or less may be a typed view's component count. + assert!(build(&words, (4, 4)).is_err()); + assert!(build(&words, (4, 0)).is_err()); +} + +/// As [`the_record_count_of_a_structured_buffer_nothing_reads`], of one the +/// program also reads by index. +#[test] +fn the_record_count_of_a_structured_buffer_read_by_index() { + let load = [ + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xE030_2000, // buffer_load_dword v5, v3, s[8:11], 0 idxen + 0x8002_0503, + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5 + ]; + let words = [TABLE, COUNT, &load, STORE].concat(); + let shader = build(&words, (4, 16)).expect("translates"); + let (mut data, texel) = ([0u32; 12], [[0.0; 4]; 1]); + data[0] = 77; + let views = [ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [3, 77], "{label}"); + } +} + +/// An upscaler counts its groups in a texture with atomics and sets the +/// counter back with a store of one channel, 16 bits wide. +#[test] +fn a_counter_texture_is_set_by_a_store_of_one_channel() { + let program = |store: [u32; 2], value: u32| { + let words = [ + 0xF40C_0201u32, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00_0000, + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0283, // v_mov_b32 v2, 3 + 0xF044_3108, // image_atomic_add v2, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002_0200, + value, // v_mov_b32 v3, .. + store[0], + store[1], + 0x7E08_0281, // v_mov_b32 v4, 1 + 0xF044_3108, // image_atomic_add v4, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002_0400, + 0xBE84_0380, // s_mov_b32 s4, 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + ]; + build(&[TABLE, &words, STORE].concat(), (8, 0)) + }; + // image_store v3, v[0:1], s[8:15] dmask:0x1 2D, with and without d16 + for store in [[0xF020_1108, 0x0002_0300], [0xF020_1108, 0x8002_0300]] { + let shader = program(store, 0x7E06_0289).expect("translates"); // v3 = 9 + let texel = [[0.0; 4]; 1]; + let views = [ + View::UintTextureUav(1, 1), + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[0], 10, "{label}"); + } + } + // Sixteen bits of a number only the card knows may be signed. + assert!(program([0xF020_1108, 0x8002_0300], 0x7E06_0302).is_err()); // v3 = v2 + // A store of two channels says nothing about the view. + assert!(program([0xF020_1308, 0x0002_0300], 0x7E06_0289).is_err()); +} + +/// A load past the wave's cache (GLC) of a buffer other groups write: its +/// view is globally coherent on the host, as is every access to it. +#[test] +fn a_buffer_loaded_past_the_cache_is_coherent() { + let program = |load: u32| { + let words = [ + 0x7E04_028Bu32, // v_mov_b32 v2, 11 + 0xE070_0008, // buffer_store_dword v2, off, s[20:23], 0 offset:8 + 0x8005_0200, + load, // buffer_load_dword v3, off, s[20:23], 0 offset:8 + 0x8005_0300, + 0x7E08_0503, // v_readfirstlane_b32 s4, v3 + 0xBE85_0380, // s_mov_b32 s5, 0 + ]; + build(&[TABLE, &words, STORE].concat(), (8, 0)).expect("translates") + }; + let (plain, coherent) = (program(0xE030_0008), program(0xE030_C008)); + // the annotations of the store's and the load's handles + assert_ne!(plain.dxil, coherent.dxil); + let texel = [[0.0; 4]; 1]; + let views = [ + View::Texture(1, 1, &texel), + View::Texture(1, 1, &texel), + View::RawUav(3), + ]; + for shader in [&plain, &coherent] { + for (label, got) in run(shader, &views) { + assert_eq!(got[..3], [11, 0, 11], "{label}"); + } + } +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 365883a..31dadd6 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -97,7 +97,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { /// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the /// hardware GPU and on WARP (each skipped without a device) and returns, /// per one that ran, the UAV's 32 dwords. -fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { +pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { let samplers = [D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 1d7a91b..56f981b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -143,6 +143,10 @@ pub(crate) enum Shape { pub(crate) struct Section { pub end: usize, pub shapes: HashMap, + /// What a `v_readlane_b32` of one lane takes, later in the block, from a + /// VGPR the section leaves (by the scalar it writes): the last lanes of + /// a reduction hold it before the first do. + pub reads: HashMap, } /// Every whole-wave section of `block`, by start index. @@ -180,8 +184,25 @@ pub(crate) fn sections(p: &Program, block: usize) -> HashMap { let Some(end) = end else { break; }; - let shapes = simulate(&insts[i + 1..end], wave, saved); - out.insert(i, Section { end, shapes }); + let (vec, uni) = simulate(&insts[i + 1..end], wave, saved); + let mut reads = HashMap::new(); + for later in insts[end + 1..].iter().filter(|i| i.name() == "v_readlane_b32") { + if let Fields::Valu(v) = &later.fields + && let (Some(Operand::Scalar { code, .. }), [Operand::Vector { reg, .. }, lane]) = + (v.dst, &v.src[..]) + && let Some(left) = later.read(Reg::V(*reg)).and_then(|x| vec.get(&x)) + && let Some(w) = later.write(Reg::S(code)) + && let Some(l) = lane_number(lane) + && let Some(&sym) = left.get(l as usize) + // (a lane's own value stays a lane read) + && !matches!(sym, Sym::Own(_)) + && let Some(shape) = single(sym, wave) + { + reads.insert(w, shape); + } + } + let shapes = shapes(vec, uni, wave); + out.insert(i, Section { end, shapes, reads }); i = end + 1; } out @@ -268,7 +289,19 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym { } } -fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { +/// The lane a `v_readlane_b32` names. +fn lane_number(op: &Operand) -> Option { + match *op { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +/// The lanes' values of the VGPRs the section writes, and its scalars. +type Left = (HashMap>, HashMap); + +fn simulate(insts: &[Inst], wave: u32, saved: Value) -> Left { let all = if wave == 64 { u64::MAX } else { @@ -289,7 +322,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { .then(|| constant(inst)) .flatten(); let Some(k) = lo else { - return shapes(vec, uni, wave); + return (vec, uni); }; exec = (if name == "s_mov_b64" { k @@ -304,7 +337,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { .then(|| constant(inst)) .flatten() else { - return shapes(vec, uni, wave); + return (vec, uni); }; exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; continue; @@ -371,11 +404,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { else { continue; }; - let l = match *lane { - Operand::Const(c) => crate::resource::inline(c), - Operand::Literal(x) => Some(x), - _ => None, - }; + let l = lane_number(lane); let x = lanes(src, &vec, &uni); if let Some(w) = inst.write(Reg::S(code)) { let s = l @@ -664,7 +693,7 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { .collect(); vec.insert(dst, merged); } - shapes(vec, uni, wave) + (vec, uni) } fn constant(inst: &Inst) -> Option { @@ -688,19 +717,10 @@ fn constant(inst: &Inst) -> Option { } } -/// The shape of each value, where every lane agrees on one. -fn shapes( - vec: HashMap>, - uni: HashMap, - wave: u32, -) -> HashMap { - let all = if wave == 64 { - u64::MAX - } else { - u64::from(u32::MAX) - }; - let mut out = HashMap::new(); - let single = |s: Sym| match s { +/// The shape of a scalar. +fn single(s: Sym, wave: u32) -> Option { + let all = u64::MAX >> (64 - wave); + match s { Sym::K(k) => Some(Shape::K(k)), Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)), Sym::Red { @@ -718,9 +738,19 @@ fn shapes( high, } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), _ => None, - }; + } +} + +/// The shape of each value, where every lane agrees on one. +fn shapes( + vec: HashMap>, + uni: HashMap, + wave: u32, +) -> HashMap { + let all = u64::MAX >> (64 - wave); + let mut out = HashMap::new(); for (v, s) in uni { - if let Some(sh) = single(s) { + if let Some(sh) = single(s, wave) { out.insert(v, sh); } } @@ -1074,6 +1104,40 @@ mod tests { } } + /// A wave OR whose last step stays in the section's VGPR: the lower + /// lanes add the first half's to themselves, so only the upper ones + /// hold the whole, and the last lane is read after the section (an + /// upscaler's programs). + #[test] + fn one_lane_of_what_a_section_leaves_is_read_after_it() { + let words = |lane: u32| { + let mut w = WAVE_OR_V7_TO_S7[..14].to_vec(); // .. v_or_b32 v1, v2, v1 + w.extend([ + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0x3802_0207, // v_or_b32 v1, s7, v1 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + 0xD760_0006, + 0x0001_0101 | lane << 9, // v_readlane_b32 s6, v1, lane + S_ENDPGM, + ]); + w + }; + let read = |lane: u32| { + let p = build(&words(lane), true); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(4)).unwrap(); + let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); + let got = insts[insts.len() - 2].write(Reg::S(6)).unwrap(); + let sec = §ions(&p, 0)[&0]; + (sec.reads.get(&got).copied(), Shape::Active(Op::Or, v7, saved, 0)) + }; + let (found, whole) = read(63); + assert_eq!(found, Some(whole)); + // Lane 0 has the first half's alone: still a lane read. + assert_eq!(read(0).0, None); + } + /// `WaveActiveSum` of 16-bit floats, as compiled in /// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the /// lowering reproduces. A tree in another order is not followed. diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index db82f33..1bdd117 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -199,6 +199,162 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } +/// "Some lane is left" of a mask operation as a number: an upscaler's programs wait for +/// other groups in a loop that ends when every lane saw its flag, or after enough rounds: +/// both tests become -1 or 0 and SCC of `timeout | ~waiting` ends it. +#[test] +fn some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on() { + let native = native(&[ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD766_0001, + 0x0002_02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1 + 0x7D84_0200, // v_cmp_eq_u32 vcc, s0, v1 + 0x8792_7E6A, // s_and_b64 s[18:19], vcc, exec + 0x8592_80C1, // s_cselect_b64 s[18:19], -1, 0 + 0xBF09_8501, // s_cmp_ge_u32 s1, 5 + 0x8594_80C1, // s_cselect_b64 s[20:21], -1, 0 + 0x8B92_1214, // s_orn2_b64 s[18:19], s[20:21], s[18:19] + 0x8506_8081, // s_cselect_b32 s6, 1, 0 + 0x7E04_0206, // v_mov_b32 v2, s6 + 0xE070_0000, + 0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0 + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = on_64_lanes(&native, &p); + // (lane s0 waits, if there is one; s1 rounds) + for (wait, rounds, done) in [(0, 0, 0), (37, 4, 0), (63, 4, 0), (64, 0, 1), (37, 5, 1), (64, 9, 1)] { + let Some(out) = dispatched(&shader, &[wait, rounds]) else { + return; + }; + assert_eq!(out, done, "lane {wait} after {rounds} rounds"); + } +} + +/// `native` for a host of 64-lane waves. +fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { + let st = structure::structure(p).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(64)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered.expect("lower"); + assert_eq!(lowered.wave_size, Some(64)); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + shader +} + +/// Dword 0 of the UAV after `shader` ran with root constants `constants`; none without a +/// device that takes it. +fn dispatched(shader: &HostShader, constants: &[u32]) -> Option { + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 64?): {e}; not run"); + return None; + } + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Constants { + ud[u.index as usize] = constants.get(u.dword as usize).copied().unwrap_or(0); + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out[0][0]) +} + +/// The same sum inside `if (t >= s0) { ... }` on a host of 64-lane waves: the lanes below s0 +/// are elsewhere, and count as +0 in the console's tree. +#[test] +fn a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64() { + let mut words = vec![ + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + 0x7D86_0000, // v_cmp_le_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | 23, // s_cbranch_execz to the restore of EXEC + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = on_64_lanes(&native, &p); + let wide = |h: u16| match h { + 0 => 0.0, + h => f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13), + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + for from in [0u32, 1, 5, 31, 32, 37, 63] { + let mut tree: Vec = (0..64u16).map(|t| if u32::from(t) < from { 0 } else { 0x3C00 + 37 * t }).collect(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| narrow(wide(c[0]) + wide(c[1]))).collect(); + } + let Some(out) = dispatched(&shader, &[from]) else { + return; + }; + assert_eq!(out, u32::from(tree[0]), "lanes from {from}"); + } +} + /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 /// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The /// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c..577fbc1 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -15,6 +15,8 @@ //! operand's whole possible range: from the encoded register up to the //! program's VGPR count, all read (and all written, for a destination). +use std::collections::{HashMap, HashSet}; + use crate::ShaderError; use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; @@ -149,7 +151,7 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Result; 256] = [None; 256]; // the last such use let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); @@ -314,7 +325,7 @@ fn unspill( match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, - Reg::V(r) => other[usize::from(r)] = true, + Reg::V(r) => other[usize::from(r)] = Some(parks.len()), Reg::Scc => {} } } @@ -323,16 +334,33 @@ fn unspill( written.push(codes); read.push(from); } - for (i, park) in parks.iter_mut().enumerate() { - if park.is_some_and(|p| other[usize::from(p.1)]) { - *park = None; + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + for reg in 0..256 { + let Some(last) = other[reg] else { continue }; + let of = |p: &Option<(bool, u8, u8, u32)>| p.filter(|p| usize::from(p.1) == reg); + let first = parks.iter().position(|p| of(p).is_some_and(|p| p.0)); + let late = first.is_some_and(|first| { + let end = parks.iter().rposition(|p| of(p).is_some()).unwrap_or(first); + let mut saved = Vec::new(); + last < first + && !(first + 1..=end).any(leader) + && parks[first..=end].iter().filter_map(of).all(|(save, _, _, lane)| { + if save { + saved.push(lane); + } + saved.contains(&lane) + }) + }); + let from = if late { first.unwrap_or(0) } else { parks.len() }; + for park in &mut parks[..from] { + if of(park).is_some() { + *park = None; + } } - let _ = i; } if parks.iter().all(Option::is_none) { return Vec::new(); } - let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); // Lane pairs (register, lower lane) that always move together: each // save of the lower lane is followed, in the same block and before its // register changes, by the save of the next register into the next @@ -342,9 +370,6 @@ fn unspill( // compiler puts loads and constants between the two: five instructions later // in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask // is one dword, and a pair move of it with its neighbour would hide it. - let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect(); - slots.sort_unstable(); - slots.dedup(); // instruction -> the instruction that completes its pair let partner = |i: usize| -> Option { let (save, reg, code, lane) = parks[i]?; @@ -385,52 +410,163 @@ fn unspill( None } }; - let mut pairs: Vec<(u8, u32)> = Vec::new(); - for &(reg, lane) in &slots { - if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { - continue; + // The store each parking instruction uses, and what the stores are lanes + // of: one per (VGPR, lane), or (`split`) one per life of it. + let stores_of = |split: bool| -> (Vec, Vec<(u8, u32)>) { + let slot = |i: usize| parks[i].map(|p| (p.1, p.3)); + // Instructions of one store, by the first of them. + let mut first: Vec = (0..list.len()).collect(); + if split { + fn root(first: &mut [usize], mut i: usize) -> usize { + while first[i] != i { + first[i] = first[first[i]]; + i = first[i]; + } + i + } + let at = |offset: usize| list.partition_point(|i| i.offset < offset); + for save in (0..list.len()).filter(|&i| parks[i].is_some_and(|p| p.0)) { + let mut seen = HashSet::new(); + let mut work = vec![save + 1]; + while let Some(from) = work.pop() { + for i in from..list.len() { + if slot(i).is_some() && slot(i) == slot(save) { + if parks[i].is_some_and(|p| p.0) { + break; + } + let (a, b) = (root(&mut first, save), root(&mut first, i)); + first[a.max(b)] = a.min(b); + } + let mut go = |to: usize| { + if seen.insert(to) { + work.push(to); + } + }; + match flows[i] { + Flow::Next if i + 1 < list.len() && leader(i + 1) => go(i + 1), + Flow::Next => continue, + Flow::Stop => {} + Flow::Jump(t) => go(at(t)), + Flow::Branch(t) => { + go(at(t)); + go(i + 1); + } + } + break; + } + } + } + for i in 0..list.len() { + first[i] = root(&mut first, i); + } + } else { + let mut of: HashMap<(u8, u32), usize> = HashMap::new(); + for i in 0..list.len() { + if let Some(s) = slot(i) { + first[i] = *of.entry(s).or_insert(i); + } + } } - let lower: Vec = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); - let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); - let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); - let mut distinct: Vec = partners.iter().flatten().copied().collect(); - distinct.sort_unstable(); - distinct.dedup(); - if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { - pairs.push((reg, lane)); + let mut stores: Vec<((u8, u32), usize)> = (0..list.len()) + .filter(|&i| first[i] == i) + .filter_map(|i| Some((slot(i)?, i))) + .collect(); + stores.sort_unstable(); + let number = |i: usize| stores.iter().position(|s| s.1 == first[i]); + let of = (0..list.len()) + .map(|i| parks[i].and_then(|_| number(i)).unwrap_or(usize::MAX)) + .collect(); + (of, stores.into_iter().map(|s| s.0).collect()) + }; + // The stores that move as pairs (lower, upper) and every store's code; + // none if the spare codes do not suffice. + let plan = |split: bool| -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + let (mut of, stores) = stores_of(split); + let mut pairs: Vec<(usize, usize)> = Vec::new(); + for (n, &(reg, lane)) in stores.iter().enumerate() { + if !wave64 || pairs.iter().any(|&(_, upper)| upper == n) { + continue; + } + let lower: Vec = (0..list.len()).filter(|&i| of[i] == n).collect(); + let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); + let mut distinct: Vec = partners.iter().flatten().copied().collect(); + distinct.sort_unstable(); + distinct.dedup(); + let Some(upper) = distinct.first().map(|&j| of[j]) else { + continue; + }; + if stores[upper] == (reg, lane + 1) + && partners.iter().all(Option::is_some) + && distinct.len() == lower.len() + && distinct.iter().all(|&j| of[j] == upper) + && of.iter().filter(|&&o| o == upper).count() == lower.len() + { + pairs.push((n, upper)); + } } - } - // Codes for the parked scalars: the trap temporaries (108..=123), then - // user SGPRs the program never names, from the top, then the codes past - // the machine's (`PARKED`..=254; 255 stays unused so that the code after a - // parked one always exists). A material resolve program parks up to 63 - // scalars and leaves about 20 machine codes unused. - let past = usize::from(PARKED); - let mut free = [false; 256]; - for c in (0..105).chain(108..=123) { - free[c] = !used[c]; - } - free[past..255].fill(true); - let mut codes: Vec<((u8, u32), u8)> = Vec::new(); - for &(reg, lane) in &pairs { - let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); - // Not enough spare codes: leave the program as it is. - let Some(c) = at else { return Vec::new() }; - (free[c], free[c + 1]) = (false, false); - codes.push(((reg, lane), c as u8)); - codes.push(((reg, lane + 1), c as u8 + 1)); - } - for &slot in &slots { - if codes.iter().any(|c| c.0 == slot) { - continue; - } - let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { - return Vec::new(); + // Lives of one lane that move alike share a code, as they share the lane. + let role = |n: usize| { + let (lower, upper) = (pairs.iter().any(|p| p.0 == n), pairs.iter().any(|p| p.1 == n)); + (stores[n], u8::from(lower) + 2 * u8::from(upper)) }; - free[c] = false; - codes.push((slot, c as u8)); + let mut shared: Vec<_> = (0..stores.len()).map(role).collect(); + let place: Vec = { + let all = shared.clone(); + shared.sort_unstable(); + shared.dedup(); + all.iter().filter_map(|r| shared.binary_search(r).ok()).collect() + }; + for o in of.iter_mut().filter(|o| **o != usize::MAX) { + *o = place[*o]; + } + for p in &mut pairs { + *p = (place[p.0], place[p.1]); + } + pairs.sort_unstable(); + pairs.dedup(); + // Codes for the parked scalars: the trap temporaries (108..=123), then + // user SGPRs the program never names, from the top, then the codes past + // the machine's (`PARKED`..=254; 255 stays unused so that the code after a + // parked one always exists). A material resolve program parks up to 63 + // scalars and leaves about 20 machine codes unused. + let past = usize::from(PARKED); + let mut free = [false; 256]; + for c in (0..105).chain(108..=123) { + free[c] = !used[c]; + } + free[past..255].fill(true); + let mut codes: Vec> = vec![None; shared.len()]; + for &(lower, upper) in &pairs { + let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); + // Not enough spare codes: leave the program as it is. + let c = at?; + (free[c], free[c + 1]) = (false, false); + codes[lower] = Some(c as u8); + codes[upper] = Some(c as u8 + 1); + } + for code in codes.iter_mut().filter(|c| c.is_none()) { + let c = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c])?; + free[c] = false; + *code = Some(c as u8); + } + Some((of, pairs, codes.into_iter().flatten().collect())) + }; + let Some(mut chosen) = plan(false) else { return Vec::new() }; + let lonely = |(of, pairs, _): &(Vec, Vec<(usize, usize)>, Vec)| { + (0..list.len()).any(|i| { + parks[i].is_some_and(|p| p.0) + && partner(i).is_some() + && !pairs.iter().any(|&(lower, upper)| of[i] == lower || of[i] == upper) + }) + }; + if wave64 + && lonely(&chosen) + && let Some(split) = plan(true) + && split.1.len() > chosen.1.len() + { + chosen = split; } - let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1); + let (store, pairs, codes) = chosen; let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { list[i] = gfx10::Instruction { offset: list[i].offset, @@ -446,11 +582,11 @@ fn unspill( const NOP: u32 = 0xBF80_0000; let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new(); for i in 0..list.len() { - let Some((save, reg, code, lane)) = parks[i] else { + let Some((save, _, code, _)) = parks[i] else { continue; }; - let Some(slot) = code_of(reg, lane) else { return Vec::new() }; - if pairs.contains(&(reg, lane)) { + let slot = codes[store[i]]; + if pairs.iter().any(|p| p.0 == store[i]) { let Some(j) = partner(i) else { return Vec::new() }; // A save moves the pair where its second half is saved; a // restore where its first half is restored. @@ -458,7 +594,7 @@ fn unspill( let (dst, src) = if save { (slot, code) } else { (code, slot) }; edits.push((at, Some((true, dst, src)))); edits.push((gone, None)); - } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + } else if pairs.iter().any(|p| p.1 == store[i]) { // the upper half of a pair: moved with the lower } else { let (dst, src) = if save { (slot, code) } else { (code, slot) }; diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index d63d2b3..835c067 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2611,6 +2611,94 @@ pub(crate) mod tests { assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]); } + /// A VGPR a wave reduction used is free again after it: from the first + /// save on it holds parked scalars alone (an upscaler program parks a + /// constant buffer's descriptor that way). + #[test] + fn a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save() { + let before = [ + 0x7E00_0281, // v_mov_b32 v0, 1 + 0x7E02_0300, // v_mov_b32 v1, v0 + ]; + let park = [ + 0xD761_0000, + 0x0001_0609, // v_writelane_b32 v0, s9, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + 0xBE83_0380, // s_mov_b32 s3, 0 + ]; + let load = [ + 0xF40C_0001, + 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + ]; + let words = [&before[..], &park, &load].concat(); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + assert_eq!(r.scalar, [((0, 5), at(0, 0x20))]); + // Still lane reads: a lane restored before it is saved, and a + // register with an ordinary use after the first save. + let restored_first = [&before[..], &park[2..4], &park[..2], &load].concat(); + let used_after = [&before[..], &park, &before[1..], &load].concat(); + for words in [restored_first, used_after] { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let insts = p.blocks.iter().flat_map(|b| &b.insts); + assert_eq!(insts.filter(|i| i.name() == "v_readlane_b32").count(), 1); + } + } + + /// Two lanes hold a pair (a lane mask, say) and later one of them a + /// scalar, as in a water volume program that parks more than the lanes + /// of one VGPR hold: the pair still moves as one. + #[test] + fn a_lane_spilled_to_again_later_does_not_split_an_earlier_pair() { + let pair = [ + 0xD761_0000u32, + 0x0001_0004, // v_writelane_b32 v0, s4, 0 + 0xD761_0000, + 0x0001_0205, // v_writelane_b32 v0, s5, 1 + 0xBE84_0380, // s_mov_b32 s4, 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xD760_0004, + 0x0001_0100, // v_readlane_b32 s4, v0, 0 + 0xD760_0005, + 0x0001_0300, // v_readlane_b32 s5, v0, 1 + ]; + let scalar = [ + 0xD761_0000u32, + 0x0001_0006, // v_writelane_b32 v0, s6, 0 + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xD760_0006, + 0x0001_0100, // v_readlane_b32 s6, v0, 0 + S_ENDPGM, + ]; + let moves = |words: &[u32]| { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let names: Vec<_> = p.blocks[0].insts.iter().map(|i| i.name()).collect(); + assert!(!names.iter().any(|n| n.contains("lane"))); + names.iter().filter(|n| **n == "s_mov_b64").count() + }; + assert_eq!(moves(&[&pair[..], &scalar].concat()), 2); + // A restore both saves reach keeps the lane one scalar. + let joined = [ + &pair[..4], + &[0xBF84_0002], // s_cbranch_scc0 past the second save + &scalar[..2], + &pair[4..], + &scalar[2..], + ] + .concat(); + assert_eq!(moves_anywhere(&joined), 0); + } + + fn moves_anywhere(words: &[u32]) -> usize { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let insts = p.blocks.iter().flat_map(|b| &b.insts); + insts.filter(|i| i.name() == "s_mov_b64").count() + } + #[test] fn descriptors_joined_by_control_flow_are_traced_per_edge() { let r = track_words( diff --git a/docs/replay.md b/docs/replay.md index 7333348..88dd0f3 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -56,14 +56,18 @@ with the presented one. | switch | does | |---|---| -| `--compare` | runs the frame unchanged first and prints the difference | +| `--compare` | runs the frame unchanged and with the experiments turn by turn, and prints the difference | | `--skip-clamps` | no argument clamps and no barriers of their scratch buffers; draws read arguments kept from a first run | +| `--batch-clamps` / `--batch-clamps 2` | argument clamps in batches, as `VICTORY_INDIRECT_BATCH=2` / `=1` does | | `--skip-hash-passes` | no compare/rehash passes over card buffers | | `--no-barriers` | no unordered-access barriers | | `--merge-barriers` | joins barrier calls with no work between them | | `--buffers vram` / `sysmem` | all buffers in the card's / the PC's memory | +| `--only-buffers ` | with `--buffers`: only the buffers all of these match: `name=`, `min=`, `max=`, `seen=No`, `Cached` or `Combined`, `id=..`, or `!` and one of them (repeatable) | +| `--listing 3..7` | only writes the frame's buffers and those lists' commands | | `--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 +77,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,