diff --git a/apps/victory/src/replay.rs b/apps/victory/src/replay.rs index bfa5243..c10b13e 100644 --- a/apps/victory/src/replay.rs +++ b/apps/victory/src/replay.rs @@ -53,12 +53,21 @@ 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, @@ -124,6 +133,9 @@ pub(crate) struct Replay { /// 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, @@ -144,6 +156,10 @@ pub(crate) fn run(r: Replay) -> Result<()> { } 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) @@ -162,9 +178,11 @@ 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, 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/draw.rs b/crates/victory-gpu/src/draw.rs index 633088a..c2f61ce 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. @@ -2031,6 +2095,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); } @@ -2301,6 +2366,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 @@ -2702,6 +2768,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 { @@ -2803,6 +2870,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 { @@ -2814,6 +2882,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 @@ -2905,6 +3032,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 @@ -2928,7 +3065,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 @@ -3018,6 +3155,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`). diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 798b760..84b74ba 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -226,18 +226,29 @@ mod tests { // origin poll that times out (and starts the frame), then a // blocking flip wait. Each flip takes its own tick. const FLIP: u32 = 2; - assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + // (The ticks are far apart, and it may take a few tries: a busy PC + // wakes a wait tens of milliseconds late at times.) + assert_eq!(set_interval(null, null, 60_000, 3, 0), S_OK); let mut token = 0; - let flips: Vec = (0..4) - .map(|_| { - let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); - assert_eq!( - wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), - S_OK - ); - LAST[2].load(Ordering::Relaxed) - }) - .collect(); + let mut four = || -> Vec { + (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect() + }; + let mut flips = four(); + for _ in 0..10 { + if flips.windows(2).all(|w| w[1] == w[0] + 1) { + break; + } + flips = four(); + } assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); // Even when a flip wait begins on the tick another just ended on. let (tick, _) = next_tick(FLIP); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 185cfb4..4c6a9f9 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 @@ -1646,7 +1653,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")) @@ -1687,10 +1695,9 @@ 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; if a - /// descriptor slot shows that memory and nothing else does (a constant - /// buffer of a table made for the draw), the title heap and the slot. - Fill(usize, usize, usize, Option<(usize, u32)>), + /// 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. @@ -1980,13 +1987,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)] @@ -2301,13 +2311,23 @@ 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, Some(named)) => 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 { @@ -2352,7 +2372,11 @@ fn log_blame(frames: f64) { us as f64 / 1e3 / frames, n as f64 / frames, passes.join(", "), - if why.is_empty() { "" } else { "; not done on the card: " }, + match (why.is_empty(), kind) { + (true, _) => "", + (_, "title memory changed under shader writes") => "; not put in under them: ", + _ => "; not done on the card: ", + }, ); } } @@ -2426,7 +2450,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). @@ -2447,11 +2471,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 @@ -2672,6 +2700,8 @@ struct RelayFetch { buffer: Option<(ID3D12Resource, usize, u64)>, /// Pieces caught while a later flight was writing them. suspects: torn::Suspects, + /// 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 @@ -2750,8 +2780,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() { @@ -2764,27 +2802,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); + } } } @@ -2862,6 +2944,7 @@ fn late_line(frames: f64) { ); } } + crate::land::log(frames); card_steps::log(frames); #[cfg(feature = "diagnostics")] log_blame(frames); @@ -3244,6 +3327,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(), @@ -3673,6 +3757,7 @@ impl Host { sent: 0, buffer: None, suspects: torn::Suspects::default(), + had: crate::land::Had::default(), }) } } @@ -3686,33 +3771,103 @@ 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); + } + // 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 = differs.map(|(differs, dwords)| unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }); + if let Some(differs) = differs { + // Pieces caught while a later flight was at them (`torn`). + let suspects = fetch.as_ref().map(|f| &f.suspects); + let mut seen = std::collections::HashSet::new(); + for &(plan, behind) in plans { + let flags: Vec<(usize, u32, bool)> = plan + .ranges + .iter() + .flat_map(|r| { + (0..r.span.pieces).map(move |p| { + let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| torn::flagged(d)); + let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), r.span.first + p), flagged)); + (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, wanted) + }) + }) + .collect(); + let fetched = flagged_pieces(&flags); + for r in &plan.ranges { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + if upcheck::on() { + upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize); + } + for p in 0..r.span.pieces { + 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.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; + } + } + if upcheck::on() { + upcheck::fetched(r.shadow.id(), lo); + } + seen.insert((copy, lo, hi)); + pieces.push((r.shadow.clone(), lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + } + 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(); } // On the copy queue a later flight may be at a piece while it is - // fetched (`torn`). - let mut suspects = fetch.as_mut().filter(|f| f.queue.is_some() && torn::on()).map(|f| std::mem::take(&mut f.suspects)); - let mut pieces = Vec::new(); - 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) }; - pieces = torn::fetches(plans, differs, suspects.as_ref()); - for r in plans.iter().flat_map(|plan| &plan.ranges) { - crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); - } + // fetched: the pieces come down whole, to be hashed. + let check = (torn::on() && fetch.as_ref().is_some_and(|f| f.queue.is_some())) + .then(|| torn::Check::new(plans.iter().map(|p| p.0), differs.unwrap_or_default(), &mut pieces)); + if let Some(check) = &check { + total = check.total; } - let total = pieces.last().map_or(0, |p| p.at + (p.to - p.from) as u64); // 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. @@ -3721,9 +3876,6 @@ impl Host { false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), }; crate::shadow::relay_fetched(after); - if let (Some(f), Some(suspects)) = (fetch.as_mut(), suspects) { - f.suspects = suspects; - } return; } let Some(f) = fetch.as_mut() else { @@ -3740,6 +3892,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. @@ -3747,14 +3905,15 @@ impl Host { (|| -> windows::core::Result { allocator.Reset()?; list.Reset(&allocator, None)?; - for p in &pieces { - list.CopyBufferRegion(&buffer, p.at, &p.shadow.buffer, p.from as u64, (p.to - p.from) as u64); + for (shadow, lo, hi, at) in check.as_ref().map_or(&pieces, |c| &c.copies) { + list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); } list.Close()?; let lists = [Some(list.cast::()?)]; if let Some(queue) = ©_queue { queue.ExecuteCommandLists(&lists); queue.Signal(&fence, sent)?; + meanwhile(); fence.SetEventOnCompletion(sent, event)?; WaitForSingleObject(event, INFINITE); return Ok(behind); @@ -3767,6 +3926,7 @@ impl Host { drop(order); self.card_sent(); self.queue.Signal(&fence, sent)?; + meanwhile(); fence.SetEventOnCompletion(sent, event)?; WaitForSingleObject(event, INFINITE); Ok(after) @@ -3785,26 +3945,61 @@ 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 p 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 + p.at as usize) as *const u8, p.to - p.from) }; - if let (Some((piece, Some(hash))), Some(suspects)) = (p.check, &mut suspects) { - suspects.fetched((p.shadow.id(), piece), torn::hash(gpu) == hash); - } - for &(lo, hi) in &p.merged { - let gpu = &gpu[lo - p.from..hi - p.from]; - let merged = p.shadow.card_merge_relay(lo, gpu, after, &mut title); - p.shadow.walls_merged(gpu.len(), merged); - written += merged; + 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(); + if let Some(check) = &check { + for i in jobs[j].clone() { + // SAFETY: as below. + unsafe { check.look(i, data) }; + } + } + 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 (i, (shadow, lo, hi, at)) in pieces.iter().enumerate() { + if let Some(check) = &check { + // SAFETY: as below. + unsafe { check.look(i, data) }; + } + // 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; } } - if let (Some(f), Some(suspects)) = (fetch.as_mut(), suspects) { - f.suspects = suspects; + land::spent(land::stat::CARD, merging); + COPY_BACK[1].fetch_add(written, Ordering::Relaxed); + if let Some(f) = fetch.as_mut() { + if let Some(check) = &check { + check.done(&mut f.suspects); + } + 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); } @@ -3839,24 +4034,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 { @@ -3864,6 +4060,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); @@ -3872,8 +4069,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 { @@ -3886,16 +4084,24 @@ impl Host { 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(); @@ -4318,6 +4524,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 @@ -4428,13 +4668,13 @@ impl Host { if behind && upcheck::on() { upcheck::reads(runs); } - 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(); @@ -4905,6 +5145,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() { @@ -5387,7 +5628,14 @@ impl HostList { pub(crate) fn defer_constants(&self, dst: *mut u8, src: *const u8, len: usize, slot: (usize, u32)) { self.deferred() .copies - .push(Step::Fill(dst as usize, src as usize, len, Some(slot))); + .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 @@ -5439,7 +5687,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)) @@ -5626,6 +5875,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 diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 6c1f622..fd24a2c 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -9,17 +9,21 @@ use crate::shadow::Shadow; /// The stage (`VICTORY_CARD_STEPS`; off by default): `1` constant buffers /// of descriptor tables (`Step::Fill` with a slot of its own), `2` the -/// title's buffer copies (`Step::Copy`) too. Only with the relay's second -/// stage (`relay_exact`). +/// 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: a root view has no size, so a pass that writes through one into the -/// title's 174 MB heap is declared to write all that is left of it, and -/// some pass of every flight does. The title's ring of constants lies in -/// the same heap. One constant buffer of 480 bytes and one copy of 20 KiB a -/// frame, at a new place of the ring each time, waited for nearly -/// everything in the air: 25-30 ms of a 105 ms frame, the submitting thread -/// standing (run record-1; with `VICTORY_FILL_TITLE=1` in run relaycopy-1 -/// the copy alone took over the wait). +/// 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 @@ -41,8 +45,10 @@ use crate::shadow::Shadow; /// like any other list's (also under flights' declared writes: /// `stale_under_flights`, which settles if it cannot). Nothing of this /// submission writes these bytes earlier than our list: the steps are done -/// in front of all its lists in either case, and [`plan`] refuses when -/// another step of the submission writes what is read. Every draw that +/// 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 @@ -54,9 +60,10 @@ use crate::shadow::Shadow; /// memory before the title is told anything of this flight (its /// bottom-of-pipe writes and fences come after, in order); CPU steps of /// later submissions that read it find it declared and wait, or are done -/// here. Refused: another step of the submission reads or writes the -/// destination on the CPU, or a refresh brings another host copy of it up -/// to date ([`plan`], [`elsewhere`]). While such a copy is in the air a +/// 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. @@ -77,8 +84,22 @@ pub(super) fn stage() -> u32 { } /// The bytes of our buffer between reading and writing: what one submission -/// may do this way. -const BETWEEN: u64 = 1 << 20; +/// 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, @@ -167,7 +188,8 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Does { Copy { dst: usize, src: usize, len: usize, asked: bool }, - Fill { src: usize, len: usize, asked: bool, slot: Option<(usize, u32)> }, + /// `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). @@ -180,51 +202,125 @@ fn meet(a: (usize, usize), b: (usize, usize)) -> bool { a.0 < b.1 && b.0 < a.1 } -/// The steps of `does` (by place) to be done on the card: all that are -/// asked for, or why not. Our list does them all in front of the -/// submission's, every read before every write, so that is right only if no -/// step, asked for or not, writes what one of them reads or writes, and no -/// CPU step reads what one of them writes. -fn plan(does: &[Does], stage: u32) -> Result, &'static str> { - let mut asked = Vec::new(); +/// 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::Fill { asked: true, slot: None, .. } => return Err("a fill without a descriptor slot of its own"), - Does::Copy { asked: true, .. } if stage < 2 => return Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"), - Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => asked.push(i), + Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => more.push(i), _ => {} } } - for &i in &asked { - let (src, dst) = match does[i] { - Does::Copy { dst, src, len, .. } => ((src, src + len), Some((dst, dst + len))), - Does::Fill { src, len, .. } => ((src, src + len), None), - _ => continue, - }; - for (k, d) in does.iter().enumerate() { - let (read, written) = match *d { - Does::Copy { dst, src, len, .. } => (Some((src, src + len)), Some((dst, dst + len))), - Does::Fill { src, len, .. } => (Some((src, src + len)), None), - Does::Read { from, to, .. } => (Some((from, to)), None), - Does::Refresh { .. } | Does::Run => (None, None), - }; - if written.is_some_and(|w| meet(w, src)) { - return Err("a copy of the submission writes what it reads"); + 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]); } - let Some(dst) = dst else { + } + 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 k != i && written.is_some_and(|w| meet(w, dst)) { - return Err("another copy of the submission writes what it writes"); } - if read.is_some_and(|r| meet(r, dst)) { - return Err("a step of the submission reads what it writes"); + if let Some((r, w)) = reads_writes(d) + && (touched(&written, r) || touched(&written, w) || touched(&read, w)) + { + more.push(i); } } } - Ok(asked) + 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 @@ -272,6 +368,7 @@ struct Op { len: usize, /// Its place in the buffer between. at: u64, + level: u32, to: To, } @@ -280,14 +377,18 @@ enum To { Copy(Arc, usize), /// A descriptor slot (title heap, slot). Slot(usize, u32), + /// A buffer's beginning. + Buffer(ID3D12Resource), } -/// Records what [`stage`] describes into `list` (open): `reads` are copied -/// into `between` (source, offset in it, offset in `between`, bytes), then -/// `writes` out of it (destination, offset in it, offset in `between`, -/// bytes). `between` is left readable as constants, the others in the -/// common state, as the submission's lists expect them. +/// 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)], @@ -305,23 +406,28 @@ fn record( } } let both = |b: &ID3D12Resource| dests.iter().any(|d| d.as_raw() == b.as_raw()); - let mut barriers = vec![transition(between, dest, source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)]; + 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 { - // 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), - }), - }, - }]); + 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); } @@ -426,6 +532,8 @@ impl Host { 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(); @@ -438,11 +546,16 @@ impl Host { len, asked: copy_blocked(written, dst, src, len).is_some(), }, - &Step::Fill(_, src, len, slot) => Does::Fill { - src, - len, - asked: read_blocked(written, src, len), - slot, + Step::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(); @@ -468,7 +581,7 @@ impl Host { if chosen.is_empty() { return Ok(None); } - let writers = { + let mut writers = { let line = line(); let mut all = writers(&line.line); all.extend(line.landing.iter().map(|w| Writer { @@ -478,24 +591,39 @@ impl Host { all }; let mut ops: Vec = Vec::with_capacity(chosen.len()); - let mut at = 0u64; - for &i in &chosen { - let (src, len) = match does[i] { - Does::Copy { src, len, .. } | Does::Fill { src, len, .. } => (src, len), - _ => continue, + // 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"); } - if at + len as u64 > BETWEEN { - return Err("too much at once"); - } let from = holder(&writers, src, src + len)?; - if !mapped(src, src + len) { - return Err("not all of what it reads is mapped"); - } + let 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 { dst, .. } => { + 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"); @@ -503,35 +631,42 @@ impl Host { 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) } - Does::Fill { slot: Some((heap, index)), .. } => To::Slot(heap, index), - _ => continue, + _ => 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, }); - at = (at + len as u64).next_multiple_of(256); } let Some(own) = self.own_list() else { return Err("no host list or buffer for it"); }; - let mut reads = Vec::new(); - let mut writes = Vec::new(); - let mut copied = Vec::new(); - // First every refresh, then the write: the bytes compared with are + // 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); - reads.push((&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, op.len as u64)); if let To::Copy(to, dst) = &op.to { to.refresh(&own.list, *dst as u64, op.len as u64); - writes.push((&to.buffer, to.offset(*dst as u64), op.at, op.len as u64)); } } + 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); @@ -539,8 +674,26 @@ impl Host { } } #[cfg(feature = "diagnostics")] - own.list.note_op(|| format!("{} copies of title memory done on the card, {at} bytes (VICTORY_CARD_STEPS)", ops.len())); - record(&own.list.list, &own.between, &reads, &writes); + own.list.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() }; @@ -552,6 +705,9 @@ impl Host { // (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); } @@ -561,7 +717,7 @@ impl Host { } Ok(Some(Taken { own, - steps: chosen.iter().map(|&i| steps[i]).collect(), + steps: chosen.iter().map(|&(i, _)| steps[i]).collect(), copied, })) } @@ -592,7 +748,7 @@ static NOTED: Mutex> = Mutex::new(None); fn noted(op: &Op) { let (to, dst) = match &op.to { To::Copy(to, dst) => (to.span(), *dst), - To::Slot(..) => ((0, 0), 0), + 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(); @@ -646,11 +802,20 @@ mod tests { } fn fill(src: usize, len: usize, asked: bool) -> Does { - Does::Fill { src, len, asked, slot: Some((1, 2)) } + 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 changes nothing. + /// in none of their ways stays where it is. #[test] fn steps_apart_from_one_another_are_taken() { let does = [ @@ -660,44 +825,150 @@ mod tests { copy(3000, 6000, 100, true), fill(1000, 64, false), Does::Read { from: 3100, to: 4000, asked: false }, + stuck(3100, 5), ]; - assert_eq!(plan(&does, 2), Ok(vec![1, 3])); + 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, 1])); + 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)]); } - /// Everything that could make the card's order another than the CPU's - /// refuses the lot, wherever in the submission it stands. + /// 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_in_one_anothers_way_are_refused() { + fn steps_that_depend_on_one_another_are_taken_in_order() { let taken = copy(1000, 5000, 100, true); - let refused = |other: Does| { - assert!(plan(&[taken, other], 2).is_err(), "{other:?} after"); - assert!(plan(&[other, taken], 2).is_err(), "{other:?} before"); + // 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 }; - for asked in [false, true] { - // Writes what it reads. - refused(copy(5099, 9000, 1, asked)); - // Writes what it writes. - refused(copy(999, 9000, 2, asked)); - // Reads what it writes. - refused(copy(7000, 1050, 10, asked)); - refused(fill(1099, 64, asked)); - refused(Does::Read { from: 900, to: 1001, asked }); + 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:?}"); } - refused(Does::Run); - // A texture that itself waits for flights; a fill with no slot. - refused(Does::Read { from: 1, to: 2, asked: true }); - refused(Does::Fill { src: 1, len: 1, asked: true, slot: None }); - // Into itself, and the same list twice. + assert!(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, taken], 2).is_err()); - // A fill of what a copy writes, and copies without stage 2. - assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 2).is_err()); assert!(plan(&[taken], 1).is_err()); - // Ends that touch are apart. - assert!(plan(&[taken, copy(900, 9000, 100, false), copy(1100, 9000, 5, false), copy(4900, 9000, 100, false)], 2).is_ok()); + assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err()); } #[test] @@ -735,11 +1006,14 @@ mod tests { 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(); @@ -756,6 +1030,7 @@ mod tests { 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]); @@ -780,7 +1055,10 @@ mod tests { fn a_copy_behind_a_flight_reads_what_the_flight_wrote() { use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; const LEN: usize = 4 << 20; - const WRITE_WATCH: u32 = 0x20_0000; + // 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; }; @@ -789,7 +1067,7 @@ mod tests { // 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::(); + 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) @@ -831,10 +1109,21 @@ mod tests { 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. @@ -852,17 +1141,28 @@ mod tests { }) .collect(); assert!(title[4000..6000] == wanted[..], "what the flight wrote, round {round}"); - assert!(title[HALF + 100..HALF + 1600] == wanted[1..1501], "the copy to the other buffer, round {round}"); + // (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] == wanted[1..1501], "the copy of the copy, 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..].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 24 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed)); - assert!(done >= 12, "only {done} copies were done on the card"); + 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/host/torn.rs b/crates/victory-gpu/src/host/torn.rs index 3ff46d6..69f2f25 100644 --- a/crates/victory-gpu/src/host/torn.rs +++ b/crates/victory-gpu/src/host/torn.rs @@ -20,15 +20,16 @@ //! //! What it costs: pieces are fetched whole where a flight declared a part //! of one, and 64 KiB of what came down are hashed (some 4 us) just before -//! they are merged, which reads them again. +//! they are merged, on the thread that merges them (`crate::land`). use std::collections::{HashMap, HashSet}; +use std::sync::atomic::AtomicU8; use super::*; /// `VICTORY_FETCH_CHECK=1`; off by default until a run has shown how often a /// piece is caught (the frame-rate line says so) and what the hashes cost -/// (3-4 ms of the landing thread's time for 96 MB, beside the merge). +/// (3-4 ms for 96 MB beside the merge, spread over the threads that land). pub(super) fn on() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_FETCH_CHECK").is_some_and(|v| v == "1")) @@ -49,7 +50,7 @@ impl Suspects { /// Whether a flight that may write `piece` fetches it, its compare /// having flagged it or not. pub(super) fn wanted(&self, piece: Piece, flagged: bool) -> bool { - flagged || self.0.contains(&piece) + flagged || (!self.0.is_empty() && self.0.contains(&piece)) } /// `piece` was fetched; `same`: it was what the last of the flights @@ -67,104 +68,90 @@ impl Suspects { } } -/// A piece to fetch. -pub(super) struct Fetch { - pub(super) shadow: std::sync::Arc, - /// The offsets fetched, and where they come down. - pub(super) from: usize, - pub(super) to: usize, - pub(super) at: u64, - /// The offsets merged: what flights declared of it. - pub(super) merged: Vec<(usize, usize)>, - /// With the check: the piece, and the hash the last flight that may - /// have written it ended with. - pub(super) check: Option<(u32, Option)>, +/// What is landed: its copy, its offsets from and to, and where it comes +/// down. +pub(super) type Landed = (std::sync::Arc, usize, usize, u64); + +/// The pieces of a landing's fetch, whole, and what is known of them. +pub(super) struct Check { + /// What is copied down: whole pieces, as the compare hashes them. + pub(super) copies: Vec, + /// The bytes of them. + pub(super) total: u64, + /// Of each: the piece, and the hash the last flight that may have + /// written it ended with. + of: Vec<(Piece, Option)>, + /// Of what is landed, the piece (in `copies`) it is of. + within: Vec, + /// Of each piece: 0 not looked at yet, 1 as that flight ended with, 2 + /// not so. + found: Vec, } -/// What is fetched for `plans`, whose compares' results are in `differs`. -/// With `suspects`, pieces are fetched whole, with the hash to compare. -pub(super) fn fetches(plans: &[&CardPlan], differs: &[u32], suspects: Option<&Suspects>) -> Vec { - let mut out: Vec = Vec::new(); - let mut total = 0u64; - let mut seen = HashSet::new(); - // With `suspects`: where each piece is in `out`. - let mut index: HashMap = HashMap::new(); - for plan in plans { - let flags: Vec<(usize, u32, bool)> = plan - .ranges - .iter() - .flat_map(|r| { - (0..r.span.pieces).map(move |p| { - let piece = r.span.first + p; - let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| flagged(d)); - let wanted = suspects.map_or(flagged, |s| s.wanted((r.shadow.id(), piece), flagged)); - (std::sync::Arc::as_ptr(&r.shadow) as usize, piece, wanted) - }) - }) - .collect(); - let fetched = flagged_pieces(&flags); - for r in &plan.ranges { - let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; - if upcheck::on() { - upcheck::declared(r.shadow.id(), r.span.from as usize, r.span.to as usize); - } +impl Check { + /// For `landed`, parts of pieces that `plans` may have written, whose + /// compares' results are in `differs`: the parts are given their places + /// in the pieces that come down. + pub(super) fn new<'a>(plans: impl Iterator, differs: &[u32], landed: &mut [Landed]) -> Check { + let mut index: HashMap = HashMap::new(); + let (mut copies, mut of, mut within, mut total) = (Vec::new(), Vec::new(), Vec::new(), 0u64); + for (shadow, lo, _, at) in landed { + let number = shadow.card_piece_of(*lo); + let piece = (shadow.id(), number); + let i = *index.entry(piece).or_insert_with(|| { + let (from, to) = shadow.card_hashed(number); + copies.push((shadow.clone(), from, to, total)); + of.push((piece, None)); + total += (to - from) as u64; + copies.len() - 1 + }); + *at = copies[i].3 + (*lo - copies[i].1) as u64; + within.push(i); + } + // (The last flight's stands.) + for r in plans.flat_map(|plan| &plan.ranges).filter(|r| r.compared) { for p in 0..r.span.pieces { - let piece = r.span.first + p; - if !fetched.contains(&(copy, piece)) { - continue; - } - let (lo, hi) = r.shadow.card_piece(&r.span, p); - if lo >= hi || !seen.insert((copy, lo, hi)) { - continue; - } - if upcheck::on() { - upcheck::fetched(r.shadow.id(), lo); - } - if suspects.is_none() { - out.push(Fetch { - shadow: r.shadow.clone(), - from: lo, - to: hi, - at: total, - merged: vec![(lo, hi)], - check: None, - }); - total += (hi - lo) as u64; - continue; - } - let i = *index.entry((r.shadow.id(), piece)).or_insert_with(|| { - let (from, to) = r.shadow.card_hashed(piece); - out.push(Fetch { - shadow: r.shadow.clone(), - from, - to, - at: total, - merged: Vec::new(), - check: Some((piece, None)), - }); - total += (to - from) as u64; - out.len() - 1 - }); - out[i].merged.push((lo, hi)); - } - } - } - if suspects.is_some() { - // The hash of the last flight that may have written the piece. - for plan in plans { - for r in plan.ranges.iter().filter(|r| r.compared) { - for p in 0..r.span.pieces { - if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p)) - && let Some(&d) = differs.get((r.at + p) as usize) - && let Some((_, hash)) = &mut out[i].check - { - *hash = Some(folded(d)); - } + if let Some(&i) = index.get(&(r.shadow.id(), r.span.first + p)) + && let Some(&d) = differs.get((r.at + p) as usize) + { + of[i].1 = Some(folded(d)); } } } + let found = of.iter().map(|_| AtomicU8::new(0)).collect(); + Check { copies, total, of, within, found } + } + + /// Looks at the piece that part `i` of what is landed is of, if none of + /// its parts was looked at: on the thread that lands it, just before, so + /// that its bytes are near. + /// + /// # Safety + /// What was fetched is at `data`, and stays as it is during the call. + pub(super) unsafe fn look(&self, i: usize, data: usize) { + let i = self.within[i]; + if self.found[i].load(Ordering::Relaxed) != 0 { + return; + } + let Some(hash) = self.of[i].1 else { + return; + }; + let (_, from, to, at) = &self.copies[i]; + // SAFETY: the caller's. + let bytes = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, to - from) }; + self.found[i].store(if self::hash(bytes) == hash { 1 } else { 2 }, Ordering::Relaxed); + } + + /// All is landed: what was found is kept for later flights. + pub(super) fn done(&self, suspects: &mut Suspects) { + for ((piece, _), found) in self.of.iter().zip(&self.found) { + match found.load(Ordering::Relaxed) { + // Not compared on the card: fetched by every flight. + 0 => {} + found => suspects.fetched(*piece, found == 1), + } + } } - out } /// Of a result of the compare: whether the piece differs. diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 4c19c17..a4fa155 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, @@ -491,7 +561,7 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; @@ -521,6 +591,19 @@ void main() { event: HANDLE, clamp: Clamp, worker: Clamp, + /// Last, so given up last. + _turn: std::sync::MutexGuard<'static, ()>, + } + + /// The software adapter is one test's at a time. Two tests that compile + /// and run shaders on it at once (it is one device for the process) make + /// `d3d10warp.dll` (10.0.26100) crash now and then: access violations in + /// its own shader compiler, on its own worker threads, in 12% of runs of + /// all tests and 3% of runs of these alone on two threads; none in 100 + /// runs one after the other. + pub(crate) fn warp_turn() -> std::sync::MutexGuard<'static, ()> { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + TURN.lock().unwrap_or_else(|e| e.into_inner()) } impl WarpHarness { @@ -530,6 +613,7 @@ void main() { /// On the software adapter, or the first one (for measurements). fn on(software: bool) -> Option { + let turn = warp_turn(); // SAFETY: plain DXGI query and D3D12 test harness setup. unsafe { let factory: IDXGIFactory4 = @@ -572,6 +656,7 @@ void main() { event, clamp, worker, + _turn: turn, }) } } @@ -1726,6 +1811,318 @@ 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). 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 25461df..da3118a 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,6 +285,9 @@ 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)); } @@ -343,6 +349,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 @@ -1099,6 +1135,7 @@ mod tests { /// driver is what a run with `VICTORY_INPLACE_PROBE=1` adds. #[test] fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); @@ -1122,6 +1159,7 @@ mod tests { /// whole is turned down without asking the host. #[test] fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let _turn = crate::indirect::tests::warp_turn(); let Some(device) = warp() else { return }; if device.cast::().is_err() { return; @@ -1142,7 +1180,16 @@ mod tests { assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); drop(placed); // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + // The heap lets go of the pages a moment after its last + // reference, if the adapter is busy with other tests' work. + let gone = (0..500).any(|_| { + let done = mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + if !done { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + done + }); + assert!(gone, "the heap keeps the pages"); assert!(matches!(place_part(&device, start, len), Err(None))); mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } 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 2ecf3ab..8c5b164 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; @@ -68,5 +70,6 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping, + writing as kernel_will_write, }; 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/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 2c50537..c833679 100644 --- a/crates/victory-gpu/src/replay/play.rs +++ b/crates/victory-gpu/src/replay/play.rs @@ -66,9 +66,13 @@ 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 @@ -98,9 +102,11 @@ 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, @@ -119,6 +125,7 @@ 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 @@ -133,6 +140,7 @@ impl Options { no_barriers: false, merge_barriers: false, skip_clamps: false, + batch_clamps: 0, skip_hash_passes: false, one_submit: false, wait_all: false, @@ -246,6 +254,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); @@ -312,20 +346,65 @@ pub fn dump(folder: &Path, text: &str) -> Result> { 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" @@ -469,7 +548,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); @@ -559,7 +638,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 { @@ -603,7 +682,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), }; @@ -614,8 +693,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| { @@ -638,7 +724,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 { @@ -701,6 +787,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(()) } @@ -1801,6 +1892,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(); @@ -1819,6 +1921,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); @@ -1840,6 +1960,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 @@ -1863,6 +1992,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>> { @@ -2127,7 +2294,8 @@ impl Player { 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 @@ -2714,6 +2882,16 @@ 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() @@ -2725,45 +2903,51 @@ impl Player { 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)?; - 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((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)?; diff --git a/crates/victory-gpu/src/safecopy.rs b/crates/victory-gpu/src/safecopy.rs index 24eb646..66bb68a 100644 --- a/crates/victory-gpu/src/safecopy.rs +++ b/crates/victory-gpu/src/safecopy.rs @@ -75,6 +75,65 @@ std::arch::global_asm!( "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 +145,138 @@ unsafe extern "system" { fn victory_safe_put_at(); fn victory_safe_put_after(); fn victory_safe_put_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 [`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 +351,11 @@ 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_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)] @@ -266,6 +461,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 f910c6f..bd98113 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; @@ -49,6 +49,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`]. @@ -591,40 +596,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 } } @@ -1418,6 +1417,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)) @@ -1453,7 +1471,7 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { /// 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")) } @@ -1531,6 +1549,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}; @@ -1921,6 +1960,7 @@ impl Shadow { 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)], @@ -2320,7 +2360,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)); } @@ -2384,6 +2424,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 @@ -2459,6 +2505,7 @@ impl Shadow { return false; } if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + note_stale(0); return true; } let base = start / PAGE; @@ -2471,6 +2518,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 = { @@ -2496,6 +2544,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. @@ -2510,6 +2559,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(); @@ -2521,6 +2571,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 @@ -2538,6 +2589,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. @@ -2824,6 +2876,11 @@ impl Shadow { card_piece_of(self.start as usize, self.len as usize, span, i) } + /// The piece that holds offset `at`. + pub(crate) fn card_piece_of(&self, at: usize) -> u32 { + self.pieces(at, at + 1).start as u32 + } + /// The offsets the compare on the card hashes of a piece: what lies of /// it in the card's buffer (which may be longer than the copy), widened /// to 16 bytes. @@ -2984,6 +3041,271 @@ impl Shadow { } } +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/watch.rs b/crates/victory-gpu/src/watch.rs index 27774d6..debc8a9 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -449,7 +449,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 +485,42 @@ 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 +/// and is noted as written, as [`guard`] notes one "written through the +/// runtime": the next asking reports it, to every copy that has it, and has +/// nothing to protect. Noted after the bytes are in, never before: a copy +/// that takes the block while they go in notes it clean, and this makes it +/// written again; noted before, such a copy would keep the half it read. +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 g = guards(); + let mut last = usize::MAX; + for &page in pages { + let block = page * KERNEL_PAGE / BLOCK; + if block != last { + g.clean.remove(&block); + 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 { @@ -475,8 +532,9 @@ 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 +/// host copy last took it: guarded then, and the guard is off, or noted +/// written behind it. (Written by the title, or by us putting a flight's +/// shader writes into it, [`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 +543,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 @@ -732,10 +790,38 @@ pub fn title_memory_reading_now() -> Option { } } -/// The runtime mapped or unmapped title memory `[at, at + len)`: what it -/// shows is new and read-write, so it is no longer guarded (nor known -/// unmapped). +/// The runtime mapped title memory `[at, at + len)`: what it shows is new, +/// so it is no longer guarded (nor known unmapped), and read-write. +/// +/// The view is there before we are told of it, and a copy's refresh on +/// another thread may have guarded its blocks in between (it finds blocks +/// it knew absent committed, and holds [`GUARDS`], which we wait for). +/// Forgetting such a block and leaving it read-only would make the title's +/// next write to it an access violation nobody takes (`on_write` finds it +/// neither guarded nor writable) and a kernel read into it fail, so the +/// write access is given back. pub fn title_memory_remapped(at: usize, len: usize) { + open(&mut title_memory_changed(at, len), at, at.saturating_add(len)); +} + +/// The runtime is about to unmap title memory `[at, at + len)`: it is +/// nothing of ours any more. Its protection goes with it. +pub fn title_memory_unmapping(at: usize, len: usize) { + let mut g = title_memory_changed(at, len); + let blocks: Vec = g + .protected + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) + .copied() + .collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } +} + +/// Tells what keeps track of what title memory shows; the guards, with no +/// block of the range known unmapped. +fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> { // A placed texture there arrives, goes or changes with no descriptor // written. crate::descriptor::host::remapped(at, len); @@ -745,15 +831,11 @@ pub fn title_memory_remapped(at: usize, len: usize) { crate::inplace::title_memory_freeing(at, len); let mut g = guards(); let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); - let absent: Vec = g.absent.range(range.clone()).copied().collect(); + let absent: Vec = g.absent.range(range).copied().collect(); for block in absent { g.absent.remove(&block); } - let blocks: Vec = g.protected.range(range).copied().collect(); - for block in blocks { - g.protected.remove(&block); - g.clean.remove(&block); - } + g } /// Registers the handler that takes writes to guarded blocks, once, ahead @@ -843,16 +925,18 @@ mod tests { } as usize; assert_ne!(p, 0); let (start, end) = (p, p + 4 * PAGE); - let (_, before) = writes(start, end, false).expect("watched"); - assert!(before.is_empty()); + // The journal may hold pages of another test's memory that was here. + let (none, before) = writes(start, end, false).expect("watched"); + assert!(before.iter().all(|&(_, w)| w < none), "{before:?}"); // SAFETY: committed pages of ours. unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; let (now, after) = writes(start, end, false).expect("watched"); - assert_eq!(after, [(p / PAGE + 1, now)]); + let new = |w: Vec<(usize, u64)>| w.into_iter().filter(|w| w.1 > none).collect::>(); + assert_eq!(new(after), [(p / PAGE + 1, now)]); // Another asker after the kernel's bit was cleared still sees it. let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); assert!(later > now); - assert_eq!(again, [(p / PAGE + 1, now)]); + assert_eq!(new(again), [(p / PAGE + 1, now)]); let mut plain = vec![0u8; PAGE]; assert!( writes( @@ -911,6 +995,9 @@ mod tests { guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); + // Before the view goes, as the runtime does: the address may be + // another test's the moment it is free. + title_memory_unmapping(view, 2 * BLOCK); // SAFETY: our view. unsafe { UnmapViewOfFile( @@ -919,7 +1006,52 @@ mod tests { }, ) }; - title_memory_remapped(view, 2 * BLOCK); + } + + /// The runtime maps a view and then tells us; a copy's refresh on another + /// thread can guard it in between. Told, it is the title's to write: a + /// block left read-only and forgotten would be an access violation in + /// title code. + #[test] + fn a_block_guarded_before_we_were_told_of_its_view_can_be_written() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write; the + // view holds it. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK); + CloseHandle(section); + view + }; + let at = view.Value as usize; + assert_ne!(at, 0); + // The refresh, then the runtime's word. + assert!(guard(at, at + 2 * BLOCK).is_some()); + assert!(!writable(at) && !writable(at + BLOCK)); + title_memory_remapped(at, 2 * BLOCK); + assert!(writable(at) && writable(at + BLOCK)); + // SAFETY: inside the view; a fault would end the process. + unsafe { ((at + 8) as *mut u8).write_volatile(1) }; + // Looked at again as new, and guarded again. + assert_eq!( + guard(at, at + 2 * BLOCK), + Some((at / PAGE..at / PAGE + 2).collect()) + ); + assert!(!writable(at)); + title_memory_unmapping(at, 2 * BLOCK); + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; } #[test] @@ -934,7 +1066,7 @@ mod tests { struct View(MEMORY_MAPPED_VIEW_ADDRESS); impl Drop for View { fn drop(&mut self) { - title_memory_remapped(self.0.Value as usize, SIZE); + title_memory_unmapping(self.0.Value as usize, SIZE); // SAFETY: our view is still mapped. unsafe { UnmapViewOfFile(self.0) }; } @@ -1060,6 +1192,7 @@ mod tests { let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; assert!(!is_view(at, at + local.len())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1069,7 +1202,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// Blocks of a placeholder between views are reported once, then not @@ -1144,6 +1276,7 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + title_memory_unmapping(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1153,7 +1286,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// A write or mapping that runs past the end of the address space (a diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index fe5b4c5..56d56ca 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -1028,7 +1028,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) { continue; }; physical.forget_view(at, size, &slice); - victory_gpu::title_memory_remapped(at, size); + victory_gpu::title_memory_unmapping(at, size); // SAFETY: a view we mapped; it becomes a placeholder again. unsafe { UnmapViewOfFile2( 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..b4df3c2 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,8 @@ 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, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1486,6 +1546,11 @@ impl<'a> Lower<'a> { data_phis: Vec::new(), read_phis: HashSet::new(), stale: 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 +2129,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 +2155,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); @@ -2258,6 +2356,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 +2373,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 +2762,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 +2807,93 @@ 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 entry = |s: &Source| match s { + Source::Loaded { load, first } => self + .scalar + .get(load) + .filter(|a| a.dynamic.is_none()) + .map(|a| (a.param, a.offset + 4 * u32::from(*first))), + _ => None, + }; + let Some(this) = 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" + ) + && entry(&d.source) == Some(this) + }) + } + + /// 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` @@ -3052,6 +3281,11 @@ impl<'a> Lower<'a> { if self.exchange.is_some() && !self.local { need(made.unwrap_or(0)); } + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + let by = made.map(|b| &self.x.p.blocks[b]); + let def = by.and_then(|b| b.insts.iter().find(|i| i.writes.iter().any(|w| w.1 == lo))); + eprintln!("MASK-WHY {v:?} made in {made:?} by {:?} at {:x?}; read in block at {:#x}; phi {}", def.map(|i| i.name()), def.map(|i| i.machine.offset), self.x.p.blocks[self.cur_ir].offset, self.phi_at.contains_key(&lo)); + } return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { @@ -3116,6 +3350,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 +5636,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 +5907,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 +5980,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 +5997,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) { @@ -6610,6 +6883,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 +9833,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 +9897,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 +9950,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 +9963,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. 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..5c6c40e --- /dev/null +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -0,0 +1,268 @@ +//! 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()); +} 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 e2bb6e8..a132db3 100644 --- a/docs/replay.md +++ b/docs/replay.md @@ -56,12 +56,15 @@ 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) |