From 20e59d2dc34cb5ab5cdc039770209e5e4c2aecbe Mon Sep 17 00:00:00 2001 From: uncaney <190490737+uncaney@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:22:35 +0100 Subject: [PATCH 1/5] fix(gpu): ask the join of the whole run the per-queue pump kept together The coalesced pump and `take_ready_with` join ready segments of several queues into one host submission (#419). The lists of a piece are prepared together: all their steps run on the CPU before the GPU runs the first command of any of them. `can_join` keeps a list that reads title memory when its steps run (a copy, a move, a fill) out of a piece whose shaders write or that has work to do after it ran. It was asked only across queues, across a wait the piece's bottom-of-pipe writes hold, and across a fence wait on a deferred Signal; across queues, of the first segment of the queue's run only. Three places where the per-queue pump ran the piece first took the next segment with no question: - the queue's own Signal, deferred behind the piece: two submissions of one queue, ready together, became one piece; - a segment whose waits already hold, behind segments of its own queue (a list that starts with a wait, or the second half of a list cut at a wait); - the later segments of a queue's run joined across queues. In each, a list that reads title memory was prepared before the shaders of a segment ahead of it in the piece had run, and read the bytes of before. Now a segment of a queue whose Signal waits behind the piece, and a segment with waits, are join boundaries while the piece is not empty, and at every boundary `can_join` is asked of each segment of the run the per-queue pump kept together from there (`run_from_head`: the segment, then the segments after it with no waits, across fence waits that already hold, up to the queue's next Signal, segment with waits, wait that does not hold, or action). The run joins whole, or the piece runs and the run starts the next piece whole. So no run that pump kept together is split, and a piece never starts where that pump did not start one: a frame gets at most the pieces the per-queue pump gave. Where `can_join` agrees, nothing changes. A split is counted in `hazard_splits`. VICTORY_COALESCE_PIECES=0 still gives the per-queue pump. Tests (native): six in hold::tests, each failing on the commit before with the writer and the reader in one piece and no join asked, and passing here. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/hold.rs | 578 +++++++++++++++++++++++++++++++-- 1 file changed, 553 insertions(+), 25 deletions(-) diff --git a/crates/victory-gpu/src/hold.rs b/crates/victory-gpu/src/hold.rs index 9435b4464..098bcda0c 100644 --- a/crates/victory-gpu/src/hold.rs +++ b/crates/victory-gpu/src/hold.rs @@ -220,6 +220,43 @@ impl Held { /// Predicate checking whether a ready segment can join the in-progress coalesced piece. pub(crate) type CanJoin<'a, S> = &'a dyn Fn(&[(S, bool)], &S) -> bool; +/// The segments the per-queue pump ran as one piece from the head of +/// `items`, a segment: it, then each segment after it with no waits, across +/// fence Waits that already hold, up to the queue's next Signal, segment with +/// waits, or Wait that does not hold. +fn run_from_head<'a, S>( + items: &'a Fifo, + fence: &'a dyn Fn(usize) -> u64, +) -> impl Iterator + 'a { + items + .iter() + .enumerate() + .map_while(move |(i, (item, ..))| match item { + Item::Segment(s, waits) if i == 0 || waits.is_empty() => Some(Some(s)), + Item::FenceWait(f, v) if i > 0 && fence(*f) >= *v => Some(None), + _ => None, + }) + .flatten() +} + +/// Whether the run from the head of `items` ([`run_from_head`]) may join +/// `piece`, `can_join` asked of each of its segments against the piece as +/// it is (not of one another, which the per-queue pump ran together): the +/// count of its segments if so. +fn run_joins( + items: &Fifo, + fence: &dyn Fn(usize) -> u64, + piece: &[(S, bool)], + can_join: CanJoin<'_, S>, +) -> Option { + let mut segments = 0; + let joins = run_from_head(items, fence).all(|s| { + segments += 1; + can_join(piece, s) + }); + joins.then_some(segments) +} + /// What the pump needs from the outside world. pub(crate) struct World<'a, S> { /// A memory value (address, bytes). @@ -343,6 +380,11 @@ impl Held { /// earlier segment's deferred bottom-of-pipe write in the same piece to /// join behind a global UAV barrier (subject to `can_join`), and deferring /// mid-piece `Item::Signal`s until immediately after the piece completes. + /// Where the per-queue pump ran the piece first (before a segment with + /// waits, and before a Signal, deferred here) or the piece holds another + /// queue's work, `can_join` is asked of the whole run the per-queue pump + /// kept together from there ([`run_from_head`]): it joins whole or starts + /// the next piece whole. fn pump_coalesced(&mut self, w: &mut World) -> Pumped { enum Decision { Blocked, @@ -372,14 +414,22 @@ impl Held { let mut piece: Vec<(S, bool)> = Vec::new(); let mut pending_signals: Vec<(usize, u64)> = Vec::new(); let mut last_queue: Option = None; + // The queues a Signal of which waits behind the piece: the per-queue + // pump ran the work before a queue's Signal first, so each later + // segment of that queue is a join boundary until the piece runs, but + // for the run asked whole at the first of them. + let mut signalled: Vec = Vec::new(); loop { let mut moved = false; for (queue, items) in &mut self.queues { let mut pending_fence_barrier = false; + // Segments of a run asked whole at its first that are still + // to be taken, with no question. + let mut asked = 0usize; loop { let decision = match items.front_mut() { None => Decision::Blocked, - Some((Item::Segment(seg, waits), since, fresh)) => { + Some((Item::Segment(_, waits), since, fresh)) => { let mut ok = true; let mut via_bop = 0u32; let mut unknown = 0u32; @@ -396,28 +446,47 @@ impl Held { None => unknown += 1, } } - // Only check `can_join` when crossing a join boundary (another queue, - // a BoP-satisfied wait, or a deferred-signal fence wait). Consecutive - // ready segments on the same queue already ran together in one host - // submission in legacy mode and must never be shredded by `can_join`. - let is_join_boundary = !piece.is_empty() + // Only check `can_join` when crossing a join boundary: another + // queue, a segment with waits (held already or by a BoP write of + // the piece), a deferred-signal fence wait, or a deferred Signal of + // this queue. The per-queue pump ran the piece first at each of + // them but the first. It is asked of the whole run that pump kept + // together from there, whose later segments are then taken with no + // question: consecutive ready segments on the same queue with + // neither a Signal nor a wait between already ran together in one + // host submission in legacy mode and must never be shredded by + // `can_join`. + let is_join_boundary = asked == 0 + && !piece.is_empty() && (last_queue != Some(*queue) - || via_bop > 0 - || pending_fence_barrier); + || !waits.is_empty() + || pending_fence_barrier + || signalled.contains(queue)); if !ok { *fresh = false; done.unknown += unknown; Decision::Blocked - } else if is_join_boundary && !(w.can_join)(&piece, seg) { - Decision::FlushFirst } else { - if !*fresh { - done.waited.push((*queue, since.elapsed())); + let waited = (!*fresh).then(|| since.elapsed()); + let run = if is_join_boundary { + run_joins(items, w.fence, &piece, w.can_join) + } else { + Some(asked) + }; + match run { + None => Decision::FlushFirst, + Some(run) => { + asked = run.saturating_sub(1); + if let Some(waited) = waited { + done.waited.push((*queue, waited)); + } + done.unknown += unknown; + done.coalesced_bop_waits += via_bop; + let barrier = via_bop > 0 + || std::mem::take(&mut pending_fence_barrier); + Decision::TakeSegment(barrier) + } } - done.unknown += unknown; - done.coalesced_bop_waits += via_bop; - let barrier = via_bop > 0 || std::mem::take(&mut pending_fence_barrier); - Decision::TakeSegment(barrier) } } Some((Item::Signal(..), ..)) => Decision::TakeSignal, @@ -441,6 +510,7 @@ impl Held { Decision::FlushFirst => { done.hazard_splits += 1; flush(&mut piece, &mut pending_signals, &mut last_queue, w, &mut done); + signalled.clear(); pending_fence_barrier = false; moved = true; continue; @@ -460,6 +530,9 @@ impl Held { (w.signal)(fence, value); } else { pending_signals.push((fence, value)); + if !signalled.contains(queue) { + signalled.push(*queue); + } } } } @@ -475,6 +548,7 @@ impl Held { // signals included; nothing joins across it. moved = true; flush(&mut piece, &mut pending_signals, &mut last_queue, w, &mut done); + signalled.clear(); pending_fence_barrier = false; if let Some((Item::Action(act), ..)) = items.pop_front() { act(); @@ -488,6 +562,7 @@ impl Held { break; } flush(&mut piece, &mut pending_signals, &mut last_queue, w, &mut done); + signalled.clear(); } } self.queues.retain(|(_, items)| !items.is_empty()); @@ -515,7 +590,9 @@ impl Held { /// When `coalesce` is `true`, accumulates ready segments across all /// non-running queues (including segments whose memory waits are satisfied /// by an earlier segment's deferred bottom-of-pipe writes via `will_write`, - /// gated at cross-queue / BoP / fence-wait boundaries by `can_join`) and + /// gated at cross-queue / waits / fence-wait boundaries, and after a + /// deferred Signal of the segment's own queue, by `can_join` asked of the + /// whole run the per-queue pump kept together from there) and /// defers mid-batch `Item::Signal`s into `Ready::Segments::signals`. /// When [`Ready::Segments`] is returned, the caller must call /// [`Self::finish_running`] with `queues` once the submission call returns. @@ -540,6 +617,9 @@ impl Held { let mut hazard_splits = 0u32; let mut last_queue: Option = None; let mut split_now = false; + // As in `pump_coalesced`: the queues a Signal of which waits behind + // the piece, each later segment of which is a join boundary. + let mut signalled: Vec = Vec::new(); let mark_touched = |touched: &mut Vec, q: usize| { if !touched.contains(&q) { @@ -555,6 +635,9 @@ impl Held { } let mut pending_fence_barrier = false; let mut popped_pending_waits: Vec<(Item, Instant, bool)> = Vec::new(); + // As in `pump_coalesced`: segments of a run asked whole at its + // first that are still to be taken. + let mut asked = 0usize; loop { match items.front_mut() { None => break, @@ -601,11 +684,14 @@ impl Held { if let Some((Item::Signal(f, v), ..)) = items.pop_front() { popped_pending_waits.clear(); signals.push((f, v)); + if !signalled.contains(queue) { + signalled.push(*queue); + } mark_touched(&mut queues_touched, *queue); moved = true; } } - Some((Item::Segment(seg, waits), since, fresh)) => { + Some((Item::Segment(_, waits), since, fresh)) => { let mut ok = true; let mut via_bop = 0u32; let mut seg_unknown = 0u32; @@ -626,10 +712,12 @@ impl Held { None => seg_unknown += 1, } } - let is_join_boundary = !piece.is_empty() + let is_join_boundary = asked == 0 + && !piece.is_empty() && (last_queue != Some(*queue) - || via_bop > 0 - || pending_fence_barrier); + || !waits.is_empty() + || pending_fence_barrier + || signalled.contains(queue)); if !ok { *fresh = false; unknown += seg_unknown; @@ -638,16 +726,23 @@ impl Held { } break; } - if is_join_boundary && !can_join(&piece, seg) { + let waited_for = (!*fresh).then(|| since.elapsed()); + let run = if is_join_boundary { + run_joins(items, fence, &piece, can_join) + } else { + Some(asked) + }; + let Some(run) = run else { hazard_splits += 1; split_now = true; for entry in popped_pending_waits.drain(..).rev() { items.push_front(entry); } break; - } - if !*fresh { - waited.push((*queue, since.elapsed())); + }; + asked = run.saturating_sub(1); + if let Some(waited_for) = waited_for { + waited.push((*queue, waited_for)); } unknown += seg_unknown; coalesced_bop_waits += via_bop; @@ -1499,4 +1594,437 @@ mod tests { held.finish_running(&[3]); assert!(held.is_empty()); } + + /// Two submissions of one queue, the title's Signal between them, both + /// held and ready together. The first holds a shader's writes + /// (`has_gpu_write`); the second reads title memory when its steps run + /// (`has_cpu_read`: a copy or a fill). The + /// per-queue pump runs the first, signals, then runs the second: what + /// the shader wrote is in title memory when the second is prepared. The + /// coalesced pump defers the Signal; the second then joins the first's + /// piece only where `can_join` lets it, which it does not here, so it + /// is prepared after the first's shaders ran, as before #419. + #[test] + fn a_later_submission_of_a_queue_reading_title_memory_is_not_joined_behind_a_shaders_writes() { + let flags = |fake: &RefCell| { + let mut f = fake.borrow_mut(); + f.flags.insert( + "writer", + BatchFlags { + has_gpu_write: true, + ..Default::default() + }, + ); + f.flags.insert( + "fill", + BatchFlags { + has_cpu_read: true, + ..Default::default() + }, + ); + }; + let submissions = |held: &mut Held<&'static str>| { + held.push(1, Item::Segment("writer", vec![])); + held.push(1, Item::Signal(5, 1)); + held.push(1, Item::Segment("fill", vec![])); + held.push(1, Item::Signal(5, 2)); + }; + let apart = ["run: writer", "signal 5 1", "run: fill", "signal 5 2"]; + + // As before #419 (`VICTORY_COALESCE_PIECES=0`): two pieces. + let fake = RefCell::new(Fake::default()); + flags(&fake); + let mut held = Held::default(); + submissions(&mut held); + let p = pump(&mut held, &fake); + assert_eq!(fake.borrow().log, apart, "the per-queue pump"); + assert_eq!(p.pieces, 2); + + // Coalesced: the same two pieces are expected, the second's read of + // title memory coming after the first's shaders ran. + let fake = RefCell::new(Fake::default()); + flags(&fake); + let mut held = Held::default(); + submissions(&mut held); + let p = pump_coalesced(&mut held, &fake); + assert_eq!( + fake.borrow().log, + apart, + "the coalesced pump: one piece, and no join asked ({} hazard splits)", + p.hazard_splits + ); + assert_eq!((p.pieces, p.hazard_splits), (2, 1)); + } + + /// Flags of the segments of [`a_later_submissions_lists_behind_a_signal_each_ask_the_join`] + /// and its kin: one whose shaders write, one with neither a read of title + /// memory nor a write, and one that reads title memory when its steps run. + fn writer_plain_reader(fake: &RefCell) { + let mut f = fake.borrow_mut(); + let flags = [ + ( + "writer", + BatchFlags { + has_gpu_write: true, + ..Default::default() + }, + ), + ("plain", BatchFlags::default()), + ( + "reader", + BatchFlags { + has_cpu_read: true, + ..Default::default() + }, + ), + ]; + f.flags.extend(flags); + } + + /// The same where the later submission's first list neither reads title + /// memory nor writes, and a later list of it reads title memory (a list + /// that copies is rarely a submission's first). The join is asked + /// of every list of the queue's run behind its deferred Signal, not the + /// first alone, and the run joins or not whole: the reader and the list + /// before it start a piece after the writer's, as the per-queue pump ran + /// them. + #[test] + fn a_later_submissions_lists_behind_a_signal_each_ask_the_join() { + let fake = RefCell::new(Fake::default()); + writer_plain_reader(&fake); + let mut held = Held::default(); + held.push(1, Item::Segment("writer", vec![])); + held.push(1, Item::Signal(5, 1)); + held.push(1, Item::Segment("plain", vec![])); + held.push(1, Item::Segment("reader", vec![])); + held.push(1, Item::Signal(5, 2)); + let p = pump_coalesced(&mut held, &fake); + assert_eq!( + fake.borrow().log, + [ + "run: writer", + "signal 5 1", + "run: plain reader", + "signal 5 2" + ] + ); + assert_eq!((p.pieces, p.hazard_splits), (2, 1)); + + // Without a Signal between them the two are one submission of the + // title's as far as the pump knows: never split, as before #419. + let fake = RefCell::new(Fake::default()); + writer_plain_reader(&fake); + let mut held = Held::default(); + for s in ["writer", "plain", "reader"] { + held.push(1, Item::Segment(s, vec![])); + } + let p = pump_coalesced(&mut held, &fake); + assert_eq!(fake.borrow().log, ["run: writer plain reader"]); + assert_eq!((p.pieces, p.hazard_splits), (1, 0)); + } + + /// `take_ready_with`, which the submission worker pumps with (#447), + /// asks the join behind a deferred Signal of the same queue as the pump + /// does: the writer goes with the Signal, and the two lists after it are + /// the next batch, together. + #[test] + fn take_ready_asks_the_join_behind_a_signal_of_the_same_queue() { + let fake = RefCell::new(Fake::default()); + writer_plain_reader(&fake); + let f = fake.borrow(); + let mut held = Held::default(); + held.push(1, Item::Segment("writer", vec![])); + held.push(1, Item::Signal(5, 1)); + held.push(1, Item::Segment("plain", vec![])); + held.push(1, Item::Segment("reader", vec![])); + held.push(1, Item::Signal(5, 2)); + let read = |_: u64, _| Some(0u64); + let fence = |_: usize| 0u64; + let no_write = |_: &&str, _: &ValueWait| false; + let can_join = |piece: &[(&str, bool)], next: &&str| { + let existing = piece + .iter() + .fold(BatchFlags::default(), |acc, (s, _)| acc.merge(f.flags[s])); + can_join_batch(existing, f.flags[next], piece.len(), 64) + }; + let mut batches = Vec::new(); + while let Some(ready) = held.take_ready_with(&read, &fence, &no_write, &can_join, true) { + match ready { + Ready::Segments { + queues, + segments, + signals, + hazard_splits, + .. + } => { + batches.push((segments, signals, hazard_splits)); + held.finish_running(&queues); + } + Ready::Signal { .. } => panic!("no signal stands alone here"), + Ready::Action(_) => panic!("no action here"), + } + } + assert_eq!( + batches, + [ + (vec![("writer", false)], vec![(5, 1)], 1), + (vec![("plain", false), ("reader", false)], vec![(5, 2)], 0), + ] + ); + assert!(held.is_empty()); + } + + /// Whether, in a log of `Fake`, the piece holding `reader` runs after the + /// piece holding `writer` (what the shaders wrote is then in title memory + /// when the reader's steps run). + fn runs_after(log: &[String], writer: &str, reader: &str) -> bool { + let piece = |name: &str| { + log.iter().position(|l| { + l.strip_prefix("run: ").is_some_and(|names| { + names.split(' ').any(|s| s.trim_start_matches('|') == name) + }) + }) + }; + matches!((piece(writer), piece(reader)), (Some(w), Some(r)) if w < r) + } + + /// Two lists of one queue, no Signal between them; the second starts with + /// a wait whose value is already in memory (the title's compute lists + /// start with one). The per-queue pump runs the work before a segment + /// with waits first, so the second is prepared after the first's shaders + /// ran. The coalesced pump and `take_ready_with` took it into the first's + /// piece with no `can_join` asked, as neither another queue, nor a wait + /// held by the piece, nor a deferred Signal is between them; a segment + /// with waits is now a join boundary in both, as it was a place where + /// the per-queue pump ran the piece first. + #[test] + fn a_later_list_of_a_queue_behind_a_wait_that_holds_is_not_joined_behind_a_shaders_writes() { + let setup = || { + let fake = RefCell::new(Fake::default()); + { + let mut f = fake.borrow_mut(); + f.memory.insert(0x100, 1); + f.flags.insert( + "writer", + BatchFlags { + has_gpu_write: true, + ..Default::default() + }, + ); + f.flags.insert( + "reader", + BatchFlags { + has_cpu_read: true, + ..Default::default() + }, + ); + } + let mut held = Held::default(); + held.push(1, Item::Segment("writer", vec![])); + held.push(1, Item::Segment("reader", vec![ge(0x100, 1)])); + (fake, held) + }; + + // The per-queue pump: two pieces. + let (fake, mut held) = setup(); + let p = pump(&mut held, &fake); + assert_eq!( + fake.borrow().log, + ["run: writer", "run: reader"], + "the per-queue pump" + ); + assert_eq!(p.pieces, 2); + + // `take_ready_with`, coalescing (the submission worker, and the pump + // under VICTORY_FLIGHT1). + let (fake, mut held) = setup(); + let mut batches: Vec> = Vec::new(); + { + let f = fake.borrow(); + let read = |a: u64, _| Some(*f.memory.get(&a).unwrap_or(&0)); + let fence = |_: usize| 0u64; + let no_write = |_: &&str, _: &ValueWait| false; + let can_join = |piece: &[(&str, bool)], next: &&str| { + let existing = piece + .iter() + .fold(BatchFlags::default(), |acc, (s, _)| acc.merge(f.flags[s])); + can_join_batch(existing, f.flags[next], piece.len(), 64) + }; + while let Some(ready) = held.take_ready_with(&read, &fence, &no_write, &can_join, true) + { + if let Ready::Segments { + queues, segments, .. + } = ready + { + batches.push(segments); + held.finish_running(&queues); + } + } + } + + // The coalesced pump. + let (fake, mut held) = setup(); + let p = pump_coalesced(&mut held, &fake); + let log = fake.borrow().log.clone(); + assert!( + runs_after(&log, "writer", "reader") && batches.len() == 2, + "the coalesced pump: {log:?}, {} hazard splits; take_ready_with: {batches:?}", + p.hazard_splits + ); + } + + /// A queue waits for a fence that another queue signals behind a segment + /// whose shaders write; the waiting queue's second list reads title + /// memory when its steps run. The per-queue pump runs the writer, gives + /// the Signal, then runs both lists of the waiting queue. The coalesced + /// pump asked `can_join` of the waiting queue's first list only (another + /// queue, a fence wait held by a deferred Signal) and took the second + /// into the piece with no question; it now asks it of both, the run the + /// per-queue pump kept together. + #[test] + fn a_later_list_waiting_on_a_deferred_signal_is_not_joined_behind_a_shaders_writes() { + let setup = || { + let fake = RefCell::new(Fake::default()); + writer_plain_reader(&fake); + let mut held = Held::default(); + held.push(2, Item::FenceWait(5, 1)); + held.push(2, Item::Segment("plain", vec![])); + held.push(2, Item::Segment("reader", vec![])); + held.push(1, Item::Segment("writer", vec![])); + held.push(1, Item::Signal(5, 1)); + (fake, held) + }; + let (fake, mut held) = setup(); + pump(&mut held, &fake); + assert_eq!( + fake.borrow().log, + ["run: writer", "signal 5 1", "run: plain reader"], + "the per-queue pump" + ); + + let (fake, mut held) = setup(); + let p = pump_coalesced(&mut held, &fake); + let log = fake.borrow().log.clone(); + assert!( + runs_after(&log, "writer", "reader"), + "the coalesced pump: {log:?}, {} hazard splits", + p.hazard_splits + ); + } + + /// The hardest shape for the join, and the title's: a compute queue whose + /// lists start with a wait, ready behind another queue's list whose + /// shaders write. Its first list waits for the value that list writes at + /// its end and joins it behind a barrier, as before. Its second starts + /// with a wait that already holds and its shaders write; its third has no + /// wait and reads title memory (a list that copies). The per-queue + /// pump ran "g", "c0", then "c1 c2" together. Asking the segment with the + /// wait alone lets "c2" in behind "g" with no question; asking "c1" and + /// "c2" each as it comes splits "c1 c2", which that pump kept together. + /// The run is asked whole at "c1" and starts the next piece whole. + /// + /// And where a run asked whole may join, its later lists are not asked + /// again behind the earlier ones: "c1 c2" behind a Signal joins "a". + #[test] + fn a_run_the_per_queue_pump_kept_together_joins_whole_or_starts_the_next_piece_whole() { + let write = BatchFlags { + has_gpu_write: true, + ..Default::default() + }; + let read = BatchFlags { + has_cpu_read: true, + ..Default::default() + }; + let setup = || { + let fake = RefCell::new(Fake::default()); + { + let mut f = fake.borrow_mut(); + f.memory.insert(0x200, 1); + f.writes.insert("g", vec![(0x100, 1)]); + f.flags.extend([("g", write), ("c1", write), ("c2", read)]); + } + let mut held = Held::default(); + held.push(1, Item::Segment("g", vec![])); + held.push(2, Item::Segment("c0", vec![ge(0x100, 1)])); + held.push(2, Item::Segment("c1", vec![ge(0x200, 1)])); + held.push(2, Item::Segment("c2", vec![])); + (fake, held) + }; + + let (fake, mut held) = setup(); + let p = pump(&mut held, &fake); + assert_eq!( + fake.borrow().log, + ["run: g", "run: c0", "run: c1 c2"], + "the per-queue pump" + ); + assert_eq!(p.pieces, 3); + + let (fake, mut held) = setup(); + let p = pump_coalesced(&mut held, &fake); + assert_eq!( + fake.borrow().log, + ["run: g |c0", "run: c1 c2"], + "the coalesced pump" + ); + assert_eq!( + (p.pieces, p.hazard_splits, p.coalesced_bop_waits), + (2, 1, 1) + ); + + let (fake, mut held) = setup(); + let mut batches = Vec::new(); + { + let f = fake.borrow(); + let read = |a: u64, _| Some(*f.memory.get(&a).unwrap_or(&0)); + let fence = |_: usize| 0u64; + let will_write = |s: &&str, w: &ValueWait| *s == "g" && w.address == 0x100; + let can_join = |piece: &[(&str, bool)], next: &&str| { + let flags = |s: &str| f.flags.get(s).copied().unwrap_or_default(); + let existing = piece + .iter() + .fold(BatchFlags::default(), |acc, (s, _)| acc.merge(flags(s))); + can_join_batch(existing, flags(next), piece.len(), 64) + }; + while let Some(ready) = + held.take_ready_with(&read, &fence, &will_write, &can_join, true) + { + if let Ready::Segments { + queues, + segments, + hazard_splits, + .. + } = ready + { + batches.push((segments, hazard_splits)); + held.finish_running(&queues); + } + } + } + assert_eq!( + batches, + [ + (vec![("g", false), ("c0", true)], 1), + (vec![("c1", false), ("c2", false)], 0) + ], + "take_ready_with" + ); + + let fake = RefCell::new(Fake::default()); + fake.borrow_mut() + .flags + .extend([("c1", write), ("c2", read)]); + let mut held = Held::default(); + held.push(1, Item::Segment("a", vec![])); + held.push(1, Item::Signal(5, 1)); + held.push(1, Item::Segment("c1", vec![])); + held.push(1, Item::Segment("c2", vec![])); + held.push(1, Item::Signal(5, 2)); + let p = pump_coalesced(&mut held, &fake); + assert_eq!( + fake.borrow().log, + ["run: a c1 c2", "signal 5 1", "signal 5 2"] + ); + assert_eq!((p.pieces, p.hazard_splits), (1, 0)); + } } From 14377a3abd348d364d89f0e0f3ffd2724e39a7b9 Mon Sep 17 00:00:00 2001 From: uncaney <190490737+uncaney@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:07:19 +0100 Subject: [PATCH 2/5] fix(gpu): learn which constant ranges a later copy of a submission rewrites A list's title copies run on the CPU when it is submitted, in recorded order with the refreshes of host copies, and all before the GPU runs the submission's first command. A buffer's host copy so has one content per submission: what the last copy left. A pass that reads constants through a table, followed in the same submission by a title copy into them, reads the later values. This adds the bookkeeping that finds such ranges (`crate::rewritten`), with nothing using it yet: `Reads` holds the constant ranges a submission's passes read so far and the bytes its shaders were declared to write; a title copy into a read range enters the shared bytes in `Known`, from which the next recording takes a snapshot. The first submission showing a range is counted, not helped; a range not shown for 64 to 128 frames is forgotten; a range a shader of the submission writes before the pass is left in place. `VICTORY_SNAPSHOT_CONSTANTS=0` turns it off. `Ranges` gains `new` (const, for a static) and `overlaps`. The module is allowed to be unused until the commit that wires it into draws and submission. Tests (native): the learning rules in rewritten.rs and `overlapping_is_sharing_a_byte` in ranges.rs. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/Cargo.toml | 2 +- crates/victory-gpu/src/lib.rs | 5 + crates/victory-gpu/src/ranges.rs | 22 + crates/victory-gpu/src/rewritten.rs | 886 ++++++++++++++++++++++++++++ 4 files changed, 914 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/rewritten.rs diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 9a2894890..b7df7ddaa 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -11,7 +11,7 @@ publish.workspace = true blake3.workspace = true sha2.workspace = true miniz_oxide.workspace = true -smallvec = { version = "1.16", features = ["union"] } +smallvec = { version = "1.16", features = ["const_new", "union"] } tracing.workspace = true anyhow.workspace = true victory-formats.workspace = true diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 21e330da6..53eb5246f 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -97,6 +97,11 @@ mod recent; // The capture format is plain std: read, and tested, everywhere. pub mod replay; pub mod resource; +// Plain std, so its tests run everywhere. +#[cfg(any(windows, test))] +// Used by the submission from a later commit. +#[allow(dead_code)] +mod rewritten; pub mod root; #[cfg(windows)] mod sampler; diff --git a/crates/victory-gpu/src/ranges.rs b/crates/victory-gpu/src/ranges.rs index d5984b444..61c6f4a7c 100644 --- a/crates/victory-gpu/src/ranges.rs +++ b/crates/victory-gpu/src/ranges.rs @@ -86,6 +86,11 @@ pub(crate) fn coalesce_intervals( pub(crate) struct Ranges(SmallVec<[(usize, usize); 1]>); impl Ranges { + /// No ranges (for a static). + pub(crate) const fn new() -> Self { + Ranges(SmallVec::new_const()) + } + /// The ranges, in order. pub(crate) fn iter(&self) -> impl Iterator + '_ { self.0.iter().copied() @@ -96,6 +101,12 @@ impl Ranges { &self.0 } + /// Whether the set holds any byte of `[from, to)`. + pub(crate) fn overlaps(&self, from: usize, to: usize) -> bool { + let first = self.0.partition_point(|&(_, end)| end <= from); + from < to && self.0.get(first).is_some_and(|&(start, _)| start < to) + } + /// Adds `[from, to)`, joined with the ranges that overlap it or lie /// within `gap` bytes of it (the bytes between are then in the set). pub(crate) fn insert(&mut self, from: usize, to: usize, gap: usize) { @@ -379,6 +390,17 @@ mod tests { ); } + #[test] + fn overlapping_is_sharing_a_byte() { + let r = set(&[(10, 20), (30, 40)]); + assert!(r.overlaps(19, 25) && r.overlaps(0, 11) && r.overlaps(35, 36)); + assert!(r.overlaps(0, 100), "around both"); + assert!(!r.overlaps(20, 30), "between them, touching both"); + assert!(!r.overlaps(0, 10) && !r.overlaps(40, 50)); + assert!(!r.overlaps(15, 15), "no bytes asked for"); + assert!(!Ranges::new().overlaps(0, usize::MAX)); + } + /// Every operation against a bitmap, on a long run of random ones. #[test] fn ranges_match_a_bitmap() { diff --git a/crates/victory-gpu/src/rewritten.rs b/crates/victory-gpu/src/rewritten.rs new file mode 100644 index 000000000..72fc30820 --- /dev/null +++ b/crates/victory-gpu/src/rewritten.rs @@ -0,0 +1,886 @@ +//! Constants a title copy rewrites under a pass. +//! +//! A list's work on title memory (its buffer copies, the refreshes of host +//! copies) runs on the CPU when the list is submitted, in recorded order, +//! and all of it before the GPU runs any command of the submission +//! (`crate::host`, `run_deferred`). A buffer's host copy so has one content +//! for the whole submission: what the last copy into it left. On the +//! console a copy is a command and runs between the passes it was recorded +//! between. A title that keeps one small constant buffer and copies new +//! values into it between two passes of a list (a picture's size for the +//! full-size passes, then half of it for the half-size ones) had both +//! passes read the later values here: the full-size passes wrote a quarter +//! of their targets. +//! +//! A root constant view not aligned for the host reads a copy of its bytes +//! taken at its place among the list's steps (`HostList::fill_scratch`). A +//! constant view in a table reads its buffer's host copy, through the heap +//! slot every pass naming that table reads: to give one pass other bytes +//! its table is made afresh in slots of its own, with the constant view on +//! a snapshot (`crate::draw`, `tables`). Those slots are made when the pass +//! is recorded; a slot in place shows what the title's record holds when +//! the list is submitted, so the ones the title rewrote in between are made +//! again then (`crate::draw`, `remake_table`; a constant view rewritten so +//! reads its buffer's host copy, the snapshot being of the view before). +//! +//! A table made afresh costs slots and a copy per pass, and which passes +//! need one is known only once the later copy is recorded, so it is +//! learnt: while a submission's steps run, [`Reads`] holds the constant +//! ranges its passes read through tables, and a title copy that then +//! writes one of them enters the bytes they share in [`Known`]. A title +//! records the same frame again and again; from the next recording on, a +//! constant view of such bytes gets its snapshot. The submission that +//! shows a range first is not helped: its reads are counted ([`take`]). A +//! range no submission shows any more is forgotten ([`frame`]), and a +//! buffer no copy rewrites under a pass costs nothing but the note of its +//! range. +//! +//! A snapshot is taken on the CPU when the list is submitted, before the +//! GPU runs any pass of the submission, and from title memory: bytes a +//! shader of the same submission writes before the pass are not in it. +//! Constants can be such bytes (an unordered view of the same buffer), so +//! a range is left in place, as before snapshots, where a write is declared +//! over any byte of it before the pass (`Step::GpuWrite`: the range of an +//! unordered buffer view a table names, 1 MiB from a root view's address) +//! and no title copy has written that byte since: a copy runs on the CPU +//! like a snapshot, so what it leaves is in both. +//! A list knows its own declarations as it records, and asks for no +//! snapshot then (`HostList::shader_wrote`). Those of the submission's +//! earlier lists show when its steps run ([`Shader::Earlier`]): the range +//! is then left in place from the next recording on, for as long as +//! submissions show such a write before a read of it ([`Known::exclude`]), +//! and the snapshot already recorded for the pass is counted. The declared +//! ranges are whole views, so the shader may not write the constants at +//! all: a later copy then reaches the pass as before snapshots, which is +//! counted when the copy comes ([`Reached::left`]). +//! +//! A submission, in all of this, is the host's: the lists given to the +//! host GPU in one call, whose steps all run before the first command of +//! any of them (`Host::execute_with_barriers`, where [`Reads`] lives in the +//! `Batch`). It can be more than one of the title's: held work joins the +//! ready segments of several queues, and segments that waited for a value +//! an earlier one writes at its end, into one piece (`crate::hold`, +//! `pump_coalesced`). A copy the title submitted later, or on another +//! queue, then runs before a pass it submitted earlier: it is learnt, and +//! the pass given a snapshot, like a copy of the pass's own list. What is +//! joined depends on what is ready when the pump runs, so a range may show +//! in some frames only; it is kept [`KEEP_FRAMES`] frames at least, and a +//! snapshot no later copy of its piece rewrites holds the bytes its +//! buffer's host copy would. +//! A list holding a snapshot reads title memory when its steps run, and +//! says so where pieces are joined (`HostList::batch_flags`, as for a +//! fill): across queues, across a wait (held by the piece or already), and +//! behind a Signal of its own queue, where the pump of before joining ran +//! the work before first, it does not follow a segment whose shaders +//! write, their writes being in title memory only once that segment has +//! run. The join is asked there of the whole run of the queue that pump +//! ran as one piece, so a list later in the run is asked too. The segments +//! of one queue with neither a Signal nor a wait between them were one +//! piece before and are still; there a write before a snapshot is found as +//! above ([`Shader::Earlier`]). +//! shortcut: with `VICTORY_COALESCE_PIECES=0` under `VICTORY_FLIGHT1` or +//! `VICTORY_ASYNC_SUBMIT`, the submission worker's batches of one queue +//! take a segment whose waits hold with the segments before it (#447); a +//! write before a snapshot there is found the same way. +//! shortcut: a write through a view the shader takes from the heap at an +//! index it computes declares no range and is not seen here. +//! shortcut: other buffer views in tables, a root constant view aligned +//! for the host, root shader resource views, vertex and index buffers read +//! their buffer's host copy with no snapshot, so a title copy between two +//! passes reaches the earlier one there too. + +use std::ffi::OsStr; +use std::sync::RwLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use crate::ranges::Ranges; + +fn enabled_value(value: Option<&OsStr>) -> bool { + value != Some(OsStr::new("0")) +} + +/// Whether passes get snapshots of the constants a title copy rewrites +/// under them (`VICTORY_SNAPSHOT_CONSTANTS`, on unless `0`). Off, nothing is +/// noted either. +pub(crate) fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| enabled_value(std::env::var_os("VICTORY_SNAPSHOT_CONSTANTS").as_deref())) +} + +/// The constant ranges the passes of one submission read through tables so +/// far, in the order of its steps, and the bytes its shaders were declared +/// to write so far. +#[derive(Default)] +pub(crate) struct Reads { + /// Where each range starts and ends, whether the pass reads a snapshot + /// of it (else its buffer's host copy), and whether a write by a shader + /// was declared over a byte of it before the pass. + reads: Vec<(usize, usize, bool, bool)>, + /// What the submission's earlier lists declared written, and what the + /// list whose steps run now has so far. + earlier: Ranges, + own: Ranges, +} + +/// Whether a write by a shader was declared over a constant range before +/// the pass that reads it, in the same submission. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Shader { + No, + /// By the pass's own list, which so recorded the pass to read in place. + Own, + /// By an earlier list, which the pass's list could not know of. + Earlier, +} + +/// What a title copy tells about the reads before it ([`Reads::copied`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Reached { + /// Reads whose bytes it made known. + pub(crate) learnt: u64, + /// Those of them with no snapshot: their passes run with the copy's + /// bytes. + pub(crate) late: u64, + /// Reads left in place after a shader's declared write: their passes + /// run with the copy's bytes wherever the shader did not write. + pub(crate) left: u64, +} + +impl Reads { + /// The steps of the submission's next list run from here on. + pub(crate) fn next_list(&mut self) { + for (from, to) in std::mem::take(&mut self.own).iter() { + self.earlier.insert(from, to, 0); + } + } + + /// Shaders of the list write `[at, at + len)` from here on (what a list + /// declares: the whole range of a view). + pub(crate) fn shader_writes(&mut self, at: usize, len: usize) { + self.own.insert(at, at.saturating_add(len), 0); + } + + /// A pass reads `[address, address + len)` as constants. Returns + /// whether a shader's write was declared over a byte of it before: a + /// snapshot would miss what the shader wrote. + pub(crate) fn read(&mut self, address: usize, len: usize, snapshot: bool) -> Shader { + let end = address.saturating_add(len); + let shader = if self.earlier.overlaps(address, end) { + Shader::Earlier + } else if self.own.overlaps(address, end) { + Shader::Own + } else { + Shader::No + }; + if len > 0 { + self.reads + .push((address, end, snapshot, shader != Shader::No)); + } + shader + } + + /// A title copy writes `[at, at + len)` now and reaches no read + /// ([`Reads::copied`] otherwise): the bytes are the title's again. + fn title_wrote(&mut self, at: usize, len: usize) { + let end = at.saturating_add(len); + self.earlier.remove(at, end); + self.own.remove(at, end); + } + + /// Whether a copy into `[at, at + len)` writes bytes a pass read. + fn reached(&self, at: usize, len: usize) -> bool { + let end = at.saturating_add(len); + self.reads + .iter() + .any(|&(from, to, ..)| from < end && at < to) + } + + /// A title copy writes `[at, at + len)` now, after the reads so far: + /// the bytes it shares with each become `known`, unless a shader's + /// write was declared over the read before it, and the read is taken + /// out (the next copy into it tells nothing new). The bytes it writes + /// are the title's again, whatever shaders were declared to write + /// there before: the copy runs on the CPU like a snapshot. + pub(crate) fn copied(&mut self, at: usize, len: usize, known: &mut Known) -> Reached { + let end = at.saturating_add(len); + self.earlier.remove(at, end); + self.own.remove(at, end); + let mut reached = Reached::default(); + self.reads.retain(|&(from, to, snapshot, shader)| { + if from >= end || at >= to { + return true; + } + if shader { + reached.left += u64::from(!snapshot); + } else { + known.learn(from.max(at), to.min(end)); + reached.learnt += 1; + reached.late += u64::from(!snapshot); + } + false + }); + reached + } +} + +/// The bytes title copies rewrote under a pass, and the constant ranges +/// read after a shader's declared write of the same submission: of each, +/// those the submissions since the last [`Known::age`] showed, and those +/// the ones before it did. +pub(crate) struct Known { + now: Ranges, + before: Ranges, + shader_now: Ranges, + shader_before: Ranges, +} + +impl Known { + pub(crate) const fn new() -> Self { + Known { + now: Ranges::new(), + before: Ranges::new(), + shader_now: Ranges::new(), + shader_before: Ranges::new(), + } + } + + fn learn(&mut self, from: usize, to: usize) { + self.now.insert(from, to, 0); + } + + /// A pass read `[address, address + len)` as constants after a write by + /// a shader of an earlier list of its submission was declared over a + /// byte of it ([`Shader::Earlier`]): no snapshot of it from here on. + pub(crate) fn exclude(&mut self, address: usize, len: usize) { + self.shader_now + .insert(address, address.saturating_add(len), 0); + } + + /// Whether [`Known::exclude`] of the range would change nothing until + /// the next [`Known::age`]. + fn excluded_now(&self, address: usize, len: usize) -> bool { + let end = address.saturating_add(len); + self.shader_now.missing(address, end).next().is_none() + } + + /// Whether a constant view of `[address, address + len)` is to read a + /// snapshot: a copy rewrote some of its bytes under a pass, and none of + /// them is excluded ([`Known::exclude`]). + pub(crate) fn holds(&self, address: usize, len: usize) -> bool { + let end = address.saturating_add(len); + (self.now.overlaps(address, end) || self.before.overlaps(address, end)) + && !(self.shader_now.overlaps(address, end) + || self.shader_before.overlaps(address, end)) + } + + /// Forgets what no submission showed since the call before this one; + /// whether no rewritten bytes are left, and no excluded ranges. + fn age(&mut self) -> (bool, bool) { + self.before = std::mem::replace(&mut self.now, Ranges::new()); + self.shader_before = std::mem::replace(&mut self.shader_now, Ranges::new()); + ( + self.before.iter().next().is_none(), + self.shader_before.iter().next().is_none(), + ) + } +} + +static KNOWN: RwLock = RwLock::new(Known::new()); +/// Whether [`KNOWN`] may hold rewritten bytes (most titles never fill it). +static ANY: AtomicBool = AtomicBool::new(false); +/// Whether [`KNOWN`] may hold excluded ranges. +static EXCLUDED: AtomicBool = AtomicBool::new(false); + +/// Presented frames between two [`Known::age`]: a range lives this long +/// after the last submission that showed it, at least. +const KEEP_FRAMES: u64 = 64; + +/// Since the last [`take`]: reads that ran with a later copy's bytes, +/// snapshots taken and their bytes, reads left in place after a shader's +/// declared write that a later copy rewrote, snapshots taken after such a +/// write, the tables made afresh for snapshots, the host views made in +/// their slots, and the bytes of the title's records read for them at +/// submission. +static COUNTS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +const LATE: usize = 0; +const SNAPSHOTS: usize = 1; +const BYTES: usize = 2; +const LEFT: usize = 3; +const AFTER_SHADER: usize = 4; +const TABLES: usize = 5; +const VIEWS: usize = 6; +const RECORD_BYTES: usize = 7; + +/// Whether a constant view of `len` bytes at `address` in a table is to +/// read a snapshot (asked when its pass is recorded). +pub(crate) fn known(address: u64, len: u64) -> bool { + ANY.load(Ordering::Relaxed) + && KNOWN + .read() + .unwrap_or_else(|e| e.into_inner()) + .holds(address as usize, len as usize) +} + +/// Whether anything is known (a table without a known constant is not +/// looked into). +pub(crate) fn any() -> bool { + ANY.load(Ordering::Relaxed) +} + +/// At submission, in the order of its steps: a pass reads `[address, +/// address + len)` as constants, in a snapshot taken at this step +/// (`snapshot`) or in its buffer's host copy. After a write by a shader of +/// an earlier list of the submission declared over a byte of it, the range +/// gets no snapshot from the next recording on; a snapshot already taken +/// for this pass may miss what the shader wrote, and is counted. +pub(crate) fn read(reads: &mut Reads, address: usize, len: usize, snapshot: bool) { + if reads.read(address, len, snapshot) != Shader::Earlier { + return; + } + let excluded = KNOWN + .read() + .unwrap_or_else(|e| e.into_inner()) + .excluded_now(address, len); + if !excluded { + KNOWN + .write() + .unwrap_or_else(|e| e.into_inner()) + .exclude(address, len); + EXCLUDED.store(true, Ordering::Relaxed); + } + if snapshot { + COUNTS[AFTER_SHADER].fetch_add(1, Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!( + at = format_args!("{address:#x}"), + bytes = len, + "a pass read a snapshot of constants that a shader of an earlier list of its submission may have \ + written: such constants are read in place from the next recording on" + ) + }); + } +} + +/// At submission, before a title copy into `[at, at + len)` is done: what +/// it tells about the `reads` of the submission so far. +pub(crate) fn copied(reads: &mut Reads, at: usize, len: usize) { + if !reads.reached(at, len) { + reads.title_wrote(at, len); + return; + } + let reached = { + let mut known = KNOWN.write().unwrap_or_else(|e| e.into_inner()); + reads.copied(at, len, &mut known) + }; + COUNTS[LEFT].fetch_add(reached.left, Ordering::Relaxed); + if reached.left > 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + at = format_args!("{at:#x}"), + bytes = len, + "a title copy rewrites constants a pass of the same submission read through a table after a \ + write by a shader was declared over them: such constants are left in place, with no snapshot" + ) + }); + } + if reached.learnt == 0 { + return; + } + ANY.store(true, Ordering::Relaxed); + COUNTS[LATE].fetch_add(reached.late, Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + at = format_args!("{at:#x}"), + bytes = len, + "a title copy rewrites constants a pass of the same submission read through a table: \ + passes reading such constants get a snapshot of them from now on \ + (VICTORY_SNAPSHOT_CONSTANTS=0 turns this off)" + ) + }); +} + +/// A snapshot of `bytes` was taken for a pass. +pub(crate) fn snapshot_taken(bytes: u64) { + COUNTS[SNAPSHOTS].fetch_add(1, Ordering::Relaxed); + COUNTS[BYTES].fetch_add(bytes, Ordering::Relaxed); +} + +/// A table holding a snapshot was made afresh in `slots` dynamic slots, a +/// host view made in each (`crate::draw`, `tables`). +pub(crate) fn table_made(slots: u64) { + add_table_counts([1, slots, 0]); +} + +/// At submission, `bytes` of the title's records at a table made afresh +/// for a snapshot were read (`crate::draw`, `remake_table`). +pub(crate) fn records_read(bytes: u64) { + add_table_counts([0, 0, bytes]); +} + +/// At submission, `views` slots of a table made afresh for a snapshot were +/// made again where the title rewrote them (`crate::draw`, `remake_table`). +pub(crate) fn slots_remade(views: u64) { + add_table_counts([0, views, 0]); +} + +/// Adds tables made afresh, host views made in their slots and bytes of +/// their records read. +fn add_table_counts(add: [u64; 3]) { + for (i, n) in [TABLES, VIEWS, RECORD_BYTES].into_iter().zip(add) { + COUNTS[i].fetch_add(n, Ordering::Relaxed); + } + #[cfg(test)] + THREAD_TABLES.with(|t| t.set(std::array::from_fn(|i| t.get()[i] + add[i]))); +} + +#[cfg(test)] +thread_local! { + /// [`add_table_counts`] of this thread since its last + /// [`thread_table_counts`]: tests run at once, and share [`COUNTS`]. + static THREAD_TABLES: std::cell::Cell<[u64; 3]> = const { std::cell::Cell::new([0; 3]) }; +} + +/// The tables made afresh for snapshots, the host views made in their +/// slots and the bytes of their records read, on this thread since the +/// last call (tests). +#[cfg(test)] +pub(crate) fn thread_table_counts() -> [u64; 3] { + THREAD_TABLES.with(|t| t.replace([0; 3])) +} + +/// What [`take`] returns. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + /// Constant ranges passes read through tables that a later title copy + /// of their submission rewrote with no snapshot taken: the passes ran + /// with the later bytes. + pub(crate) late: u64, + /// Snapshots taken, and their bytes. + pub(crate) snapshots: u64, + pub(crate) bytes: u64, + /// Such ranges left in place because a write by a shader was declared + /// over them before the pass: it ran with the later bytes wherever the + /// shader did not write. + pub(crate) left: u64, + /// Snapshots a pass read after a write by a shader of an earlier list + /// of its submission was declared over their bytes: they may miss it. + pub(crate) after_shader: u64, + /// Tables made afresh for snapshots, the host views made in their slots + /// (when their passes were recorded, and again at submission where the + /// title rewrote a slot), and the bytes of the title's records read for + /// them at submission. + pub(crate) tables: u64, + pub(crate) views: u64, + pub(crate) record_bytes: u64, +} + +/// The counts since the last call. +pub(crate) fn take() -> Counts { + let [ + late, + snapshots, + bytes, + left, + after_shader, + tables, + views, + record_bytes, + ] = [ + LATE, + SNAPSHOTS, + BYTES, + LEFT, + AFTER_SHADER, + TABLES, + VIEWS, + RECORD_BYTES, + ] + .map(|i| COUNTS[i].swap(0, Ordering::Relaxed)); + Counts { + late, + snapshots, + bytes, + left, + after_shader, + tables, + views, + record_bytes, + } +} + +/// A frame was presented: every [`KEEP_FRAMES`], what no submission showed +/// since the last time is forgotten. +pub(crate) fn frame() { + static FRAMES: AtomicU64 = AtomicU64::new(0); + if !(any() || EXCLUDED.load(Ordering::Relaxed)) + || !(FRAMES.fetch_add(1, Ordering::Relaxed) + 1).is_multiple_of(KEEP_FRAMES) + { + return; + } + let mut known = KNOWN.write().unwrap_or_else(|e| e.into_inner()); + let (none_known, none_excluded) = known.age(); + if none_known { + ANY.store(false, Ordering::Relaxed); + } + if none_excluded { + EXCLUDED.store(false, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const X: (usize, usize) = (0x1000, 32); + const Y: (usize, usize) = (0x2000, 256); + const Z: (usize, usize) = (0x3000, 64); + + /// One submission's steps, in order. + enum Step { + /// A pass reads constants through a table. + Pass((usize, usize)), + /// A title copy writes a range. + Copy((usize, usize)), + /// A write by the shaders of the passes from here on is declared. + Write((usize, usize)), + /// The submission's next list begins. + Next, + } + use Step::{Copy, Next, Pass, Write}; + + /// What a submission's passes read, and what its copies told. + #[derive(Debug, Default, PartialEq, Eq)] + struct Ran { + /// Which passes read a snapshot. + snapshots: Vec, + reached: Reached, + /// Snapshots read after a write an earlier list declared. + after_shader: u64, + } + + /// Records a submission's lists and runs their steps as `crate::draw` + /// and `crate::host` do. A pass reads a snapshot when its range is + /// known as it is recorded (before the submission) and its own list + /// declared no write over it so far, else its buffer's host copy; a + /// read after a write an earlier list declared excludes its range. + fn run(known: &mut Known, steps: &[Step]) -> Ran { + // What `HostList` keeps of its own declarations as it records. + let mut own = Ranges::new(); + let mut snapshots = Vec::new(); + for step in steps { + match *step { + Pass((at, len)) => { + snapshots.push(known.holds(at, len) && !own.overlaps(at, at + len)) + } + Write((at, len)) => own.insert(at, at + len, 0), + Next => own = Ranges::new(), + Copy((at, len)) => own.remove(at, at + len), + } + } + let (mut reads, mut pass) = (Reads::default(), 0); + let mut ran = Ran::default(); + reads.next_list(); + for step in steps { + match *step { + Pass((at, len)) => { + if reads.read(at, len, snapshots[pass]) == Shader::Earlier { + known.exclude(at, len); + ran.after_shader += u64::from(snapshots[pass]); + } + pass += 1; + } + Copy((at, len)) => { + let reached = reads.copied(at, len, known); + ran.reached.learnt += reached.learnt; + ran.reached.late += reached.late; + ran.reached.left += reached.left; + } + Write((at, len)) => reads.shader_writes(at, len), + Next => reads.next_list(), + } + } + ran.snapshots = snapshots; + ran + } + + /// [`run`]: which passes read a snapshot and how many reads ran with a + /// later copy's bytes. + fn submit(known: &mut Known, steps: &[Step]) -> (Vec, u64) { + let ran = run(known, steps); + (ran.snapshots, ran.reached.late) + } + + /// The fault's shape: constants copied in, a pair of passes, constants + /// copied in again, another pair (a pair notes its range once). The + /// first submission shows it and is not helped (the first pair's read + /// is late); every later one gives both pairs a snapshot, and nothing + /// else gets one. + #[test] + fn passes_before_a_later_copy_of_their_submission_get_a_snapshot_from_the_next_on() { + let mut known = Known::new(); + let frame = [ + Copy(X), + Pass(X), + Copy(X), + Pass(X), + Pass(Y), + Copy(Z), + Pass(Z), + ]; + assert_eq!( + submit(&mut known, &frame), + (vec![false; 4], 1), + "seen, not helped yet" + ); + assert!(known.holds(X.0, X.1)); + for _ in 0..3 { + let (snapshots, late) = submit(&mut known, &frame); + assert_eq!(late, 0, "no pass runs with later bytes"); + assert_eq!( + snapshots, + [true, true, false, false], + "the rewritten constants' passes, before the copy between them and after it" + ); + } + // Y is read and never copied into; Z is copied into before its only pass. + assert!(!known.holds(Y.0, Y.1) && !known.holds(Z.0, Z.1)); + } + + #[test] + fn a_copy_tells_only_about_the_passes_before_it_in_its_own_submission() { + let mut known = Known::new(); + // Copy first, then the pass: nothing to learn. + assert_eq!(submit(&mut known, &[Copy(X), Pass(X)]), (vec![false], 0)); + assert!(!known.holds(X.0, X.1)); + // The pass in one submission, the copy in the next: the GPU ran between them. + assert_eq!(submit(&mut known, &[Pass(X)]), (vec![false], 0)); + assert_eq!(submit(&mut known, &[Copy(X)]), (vec![], 0)); + assert!(!known.holds(X.0, X.1)); + // The pass of one list, the copy of a later list of the same submission. + assert_eq!( + submit(&mut known, &[Pass(X), Pass(Y), Copy(X)]), + (vec![false, false], 1) + ); + assert!(known.holds(X.0, X.1) && !known.holds(Y.0, Y.1)); + } + + #[test] + fn a_read_counts_once_however_many_copies_follow() { + let mut known = Known::new(); + assert_eq!( + submit(&mut known, &[Pass(X), Copy(X), Copy(X), Copy(X)]).1, + 1 + ); + // Two passes noted apart (a copy elsewhere between them), both before the copy. + let mut known = Known::new(); + assert_eq!( + submit(&mut known, &[Pass(X), Copy(Y), Pass(X), Copy(X)]).1, + 2 + ); + } + + #[test] + fn what_is_known_is_the_bytes_a_pass_read_and_a_copy_then_wrote() { + let mut known = Known::new(); + // A copy over the second half of a 256-byte constant range and beyond. + submit(&mut known, &[Pass(Y), Copy((Y.0 + 128, 4096))]); + assert!(known.holds(Y.0, Y.1), "the view that was read"); + assert!(known.holds(Y.0 + 192, 16), "a view of bytes inside both"); + assert!(!known.holds(Y.0, 128), "a view of the half no copy wrote"); + assert!( + !known.holds(Y.0 + 256, 64), + "copied, read by no pass before" + ); + assert!(!known.holds(Y.0 + 128, 0), "no bytes"); + // Next to a known range is not in it. + let mut known = Known::new(); + submit(&mut known, &[Pass(X), Copy(X)]); + assert!(!known.holds(X.0 + X.1, 32) && !known.holds(X.0 - 32, 32)); + assert!(known.holds(X.0 + X.1 - 1, 32) && known.holds(X.0 - 31, 32)); + } + + #[test] + fn a_range_is_kept_while_submissions_show_it_and_forgotten_after() { + let mut known = Known::new(); + submit(&mut known, &[Pass(X), Copy(X), Pass(Z), Copy(Z)]); + assert!(!known.age().0, "kept through one ageing"); + assert!(known.holds(X.0, X.1) && known.holds(Z.0, Z.1)); + // X shows again, as snapshots now; Z does not. + assert_eq!( + submit(&mut known, &[Pass(X), Copy(X), Pass(Z)]), + (vec![true, true], 0) + ); + assert!(!known.age().0); + assert!(known.holds(X.0, X.1), "shown since the ageing before"); + assert!(!known.holds(Z.0, Z.1), "not shown since: forgotten"); + assert!(known.age().0, "nothing shown since the last ageing"); + assert!(!known.holds(X.0, X.1)); + } + + /// Constants a shader of the pass's own list was declared to write + /// before the pass (the whole range of a view over any byte of them): + /// read in place in every submission, and a later copy makes nothing + /// known; its reaching the pass is counted. + #[test] + fn constants_a_shader_of_the_list_wrote_before_their_pass_get_no_snapshot() { + let mut known = Known::new(); + let frame = [Write((X.0 - 64, 256)), Pass(X), Copy(X), Pass(Y), Copy(Y)]; + for _ in 0..3 { + let ran = run(&mut known, &frame); + assert_eq!(ran.snapshots, [false, false]); + assert_eq!( + ran.reached, + Reached { + learnt: 1, + late: 1, + left: 1 + }, + "X left in place, Y learnt" + ); + assert!(!known.holds(X.0, X.1)); + // Y is read after the write too, but the write is not over it. + known = Known::new(); + } + // A write declared after the pass is not before it. + let mut known = Known::new(); + run(&mut known, &[Pass(X), Write(X), Copy(X)]); + assert!(known.holds(X.0, X.1)); + } + + /// Known constants that a shader of the same list then begins to write + /// before one of their passes: that pass reads in place from its first + /// recording on, the pass before the write keeps its snapshot, and the + /// range stays known. + #[test] + fn a_list_takes_no_snapshot_after_its_own_shaders_write() { + let mut known = Known::new(); + submit(&mut known, &[Pass(X), Copy(X)]); + assert!(known.holds(X.0, X.1)); + for _ in 0..3 { + let ran = run(&mut known, &[Pass(X), Write(X), Pass(X), Copy(X)]); + assert_eq!(ran.snapshots, [true, false], "before the write, after it"); + assert_eq!(ran.after_shader, 0); + assert_eq!(ran.reached.late, 0); + assert!( + known.holds(X.0, X.1), + "the pass before the write shows it still" + ); + } + } + + /// The same of a write an earlier list of the submission declares: the + /// pass's list cannot know of it as it records, so the first such + /// submission reads a snapshot (counted); the range is read in place + /// from the next recording on, for as long as submissions show the + /// write before a read of it. + #[test] + fn a_write_declared_by_an_earlier_list_ends_the_snapshots_of_its_bytes() { + let mut known = Known::new(); + submit(&mut known, &[Pass(X), Copy(X)]); + let frame = [Write(X), Next, Pass(X), Copy(X)]; + let ran = run(&mut known, &frame); + assert_eq!( + (ran.snapshots, ran.after_shader), + (vec![true], 1), + "recorded with a snapshot" + ); + assert!(!known.holds(X.0, X.1), "excluded"); + for _ in 0..3 { + let ran = run(&mut known, &frame); + assert_eq!((ran.snapshots, ran.after_shader), (vec![false], 0)); + assert_eq!(ran.reached.left, 1, "the copy reaches it, in place"); + assert!(!known.holds(X.0, X.1)); + known.age(); + } + // A pass of a list before the writer's reads in place too: the + // range is excluded whole. + let ran = run( + &mut known, + &[Pass(X), Copy(X), Next, Write(X), Next, Pass(X), Copy(X)], + ); + assert_eq!(ran.snapshots, [false, false]); + assert_eq!( + ran.reached.late, 1, + "counted as running with the later bytes" + ); + // Once no submission shows the write before a read, the exclusion + // ages out and the copies make the range known again. + known.age(); + submit(&mut known, &[Pass(X), Copy(X)]); + assert!(!known.holds(X.0, X.1), "excluded through one ageing"); + known.age(); + assert_eq!( + submit(&mut known, &[Pass(X), Copy(X), Pass(X)]).0, + [true, true] + ); + } + + /// A title copy over the constants after a shader's declared write + /// makes them the title's again: it runs on the CPU, so a snapshot + /// taken after it holds what it left. A coarse declaration early in a + /// list (1 MiB from a root view's address, say) so does not end the + /// snapshots of constants the title copies in before each pass. + #[test] + fn a_title_copy_after_a_shaders_write_makes_the_bytes_the_titles_again() { + for earlier_list in [false, true] { + let mut known = Known::new(); + let mut frame = vec![Write((X.0 - 0x800, 1 << 20))]; + if earlier_list { + frame.push(Next); + } + frame.extend([Copy(X), Pass(X), Copy(X), Pass(X)]); + let ran = run(&mut known, &frame); + assert_eq!(ran.snapshots, [false, false]); + assert_eq!( + (ran.reached.late, ran.reached.left), + (1, 0), + "learnt as without the write" + ); + for _ in 0..3 { + let ran = run(&mut known, &frame); + assert_eq!(ran.snapshots, [true, true], "earlier list {earlier_list}"); + assert_eq!( + (ran.after_shader, ran.reached.late, ran.reached.left), + (0, 0, 0) + ); + } + } + // A copy over half of them leaves the other half the shader's. + let mut known = Known::new(); + let ran = run(&mut known, &[Write(Y), Copy((Y.0, 128)), Pass(Y), Copy(Y)]); + assert_eq!((ran.reached.learnt, ran.reached.left), (0, 1)); + assert!(!known.holds(Y.0, Y.1)); + } + + /// A range next to a declared write is not written. + #[test] + fn a_declared_write_next_to_constants_leaves_them_their_snapshot() { + let mut known = Known::new(); + submit(&mut known, &[Pass(X), Copy(X)]); + // As measured: 16 bytes bound for unordered access right after 32 + // bytes of constants, and one ending where they begin. + let frame = [ + Write((X.0 + X.1, 16)), + Write((X.0 - 16, 16)), + Next, + Write((X.0 + X.1, 16)), + Pass(X), + Copy(X), + ]; + for _ in 0..3 { + let ran = run(&mut known, &frame); + assert_eq!((ran.snapshots, ran.after_shader), (vec![true], 0)); + assert!(known.holds(X.0, X.1)); + } + } + + #[test] + fn the_switch_defaults_on_and_disables_with_zero() { + assert!(enabled_value(None)); + assert!(enabled_value(Some(OsStr::new("1")))); + assert!(!enabled_value(Some(OsStr::new("0")))); + } +} From bf57f9f790145802a51f03678114f0207928e280 Mon Sep 17 00:00:00 2001 From: uncaney <190490737+uncaney@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:07:19 +0100 Subject: [PATCH 3/5] fix(gpu): tell tables made afresh apart by twin, cap and snapshot A shader reads the title's descriptor tables in place unless something has to differ for it: the table reaches past a capped host heap, or the shader moves 16-bit float or signed buffer views as integers and is shown their unsigned twins. A constant view reading a snapshot (the commit before) is a third reason. `crate::fresh` holds why a table is made afresh (`Why`) and the key that tells two such tables apart within a list: each slot's record, whether the shader moves halves there, the snapshot a constant view reads there, and whether the slots are made again at submission. A table needing a twin and a snapshot is one table holding both, and no table with only one of them stands for it. Plain std, used from the next commit (allowed to be unused until then). Tests (native): the twin-and-snapshot key tests in fresh.rs. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/fresh.rs | 192 ++++++++++++++++++++++++++++++++ crates/victory-gpu/src/lib.rs | 5 + 2 files changed, 197 insertions(+) create mode 100644 crates/victory-gpu/src/fresh.rs diff --git a/crates/victory-gpu/src/fresh.rs b/crates/victory-gpu/src/fresh.rs new file mode 100644 index 000000000..84ee17816 --- /dev/null +++ b/crates/victory-gpu/src/fresh.rs @@ -0,0 +1,192 @@ +//! Tables made afresh: why, and what tells them apart. +//! +//! A shader reads the title's descriptor tables in place, from the host +//! slots that mirror the title's own, unless something has to differ for +//! that shader ([`Why`]): the table reaches past a capped host heap; the +//! shader moves a 16-bit float or signed buffer view as integers, and is +//! shown the unsigned view of the same layout, its twin +//! (`descriptor::host::half_view`); a constant view reads a snapshot of its +//! bytes (`crate::rewritten`). Such a table is made afresh in dynamic slots +//! (`crate::draw`, `State::tables`), once for all its reasons, and once +//! within a list for all the passes it serves alike. +//! +//! "Alike" is the [`key`]: each slot's record, whether the shader moves +//! halves there (the slot then holds a twin where another shader's holds +//! the title's view), the snapshot a constant view reads there (a title +//! copy ends it, and the passes after the copy read another), and whether +//! the table's slots are made again at submission where the title rewrote +//! them. A table that needs a twin and a snapshot is so one table holding +//! both, and no table with only one of the two, or with another snapshot, +//! stands for it. +//! +//! Plain std: the decisions are tested on any host. + +use std::hash::{Hash, Hasher}; + +/// Why a table is made afresh for a shader. Any of the three, together. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Why { + /// The shader moves halves through a descriptor at which the title has + /// a 16-bit float or signed buffer view: the slot shows its twin. + pub(crate) twin: bool, + /// The table reaches past a host heap smaller than the title's: the + /// title's slots there have no host slot of their own. + pub(crate) capped: bool, + /// The table holds a constant view of bytes a title copy rewrites under + /// a pass: the slot shows a snapshot of them. + pub(crate) snapshot: bool, +} + +impl Why { + /// Whether the shader reads the title's own slots when no dynamic slots + /// are left for the table: only if it was wanted afresh for nothing but + /// its snapshots, which the pass then does without, as before snapshots. + /// In place a shader that moves halves would read them through the + /// title's format, and past a capped heap there are no slots to read: + /// such a draw is dropped instead. + pub(crate) fn in_place_without_slots(self) -> bool { + self.snapshot && !self.twin && !self.capped + } + + /// Whether the table's slots are made again at submission where the + /// title rewrote them after the pass was recorded (`crate::draw`, + /// `remake_table`): every table that holds a snapshot, as its slots in + /// place would show the title's records of then, a twin among its + /// slots made again as a twin. Without a snapshot a table made afresh + /// stays as recorded, and so does one past a capped heap, with or + /// without a snapshot: both as they were before snapshots. + pub(crate) fn followed(self) -> bool { + self.snapshot && !self.capped + } +} + +/// One slot of a table made afresh, as far as it tells tables apart. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct Slot { + /// The title's record at the slot's place in its own table. + pub(crate) record: [u32; 3], + /// The shader moves 16-bit channels as integers through the view there + /// (`HostShader::half_views`): a 16-bit float or signed buffer view is + /// shown as its unsigned twin. + pub(crate) half: bool, + /// The snapshot a constant view there reads: its scratch buffer (by + /// address) and the offset in it. + pub(crate) snapshot: Option<(usize, u64)>, +} + +/// The key of the table holding `slots`, among the tables a list makes +/// afresh from one title table. `followed`: its slots are made again at +/// submission where the title rewrote them. +pub(crate) fn key(slots: &[Slot], followed: bool) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + slots.hash(&mut h); + followed.hash(&mut h); + h.finish() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A table that needs a twin and a snapshot keeps what each gives it: + /// it is never read in place (the shader would read the 16-bit view in + /// the title's format), and it follows the slots the title rewrites, as + /// a table made for a snapshot alone does. + #[test] + fn a_table_with_a_twin_and_a_snapshot_keeps_both() { + let why = |twin, capped, snapshot| Why { + twin, + capped, + snapshot, + }; + let both = why(true, false, true); + assert!( + !both.in_place_without_slots(), + "its draw is dropped without slots" + ); + assert!(both.followed(), "made again where the title rewrites it"); + // Each reason alone. + let snapshot = why(false, false, true); + assert!(snapshot.in_place_without_slots() && snapshot.followed()); + let twin = why(true, false, false); + assert!( + !twin.in_place_without_slots() && !twin.followed(), + "as recorded" + ); + let capped = why(false, true, false); + assert!( + !capped.in_place_without_slots() && !capped.followed(), + "as recorded" + ); + // Past a capped heap a snapshot changes nothing but the constants. + for twin in [false, true] { + let all = why(twin, true, true); + assert!(!all.in_place_without_slots() && !all.followed()); + } + } + + /// A table of three slots: constants, a 16-bit buffer view, a target. + fn table(half: bool, snapshot: Option<(usize, u64)>) -> [Slot; 3] { + let slot = |index, half, snapshot| Slot { + record: [0x5649, index, 1], + half, + snapshot, + }; + [ + slot(7, false, snapshot), + slot(8, half, None), + slot(9, false, None), + ] + } + + /// A table that needs a twin and a snapshot is one table: the passes + /// between two title copies share it, and the tables with one of the two + /// only, with another snapshot or with other records are other tables. + #[test] + fn a_table_with_a_twin_and_a_snapshot_is_a_table_of_its_own() { + let taken = Some((0x7000_1000, 256)); + let both = key(&table(true, taken), true); + assert_eq!( + both, + key(&table(true, taken), true), + "made once for the passes that read it alike" + ); + let others = [ + // Before the constants were known, or with snapshots off. + ("the twin alone", key(&table(true, None), false)), + // A shader that reads the 16-bit view in the title's format. + ("the snapshot alone", key(&table(false, taken), true)), + // The title's own slots, in dynamic ones (a capped heap). + ("neither", key(&table(false, None), false)), + // The same slots past a capped heap, which stay as recorded. + ("both, as recorded", key(&table(true, taken), false)), + // A title copy ended the snapshot. + ( + "a later snapshot", + key(&table(true, Some((0x7000_1000, 512))), true), + ), + ( + "a snapshot in another chunk", + key(&table(true, Some((0x7000_2000, 256))), true), + ), + ]; + for (k, (what, other)) in others.iter().enumerate() { + assert_ne!(both, *other, "{what}"); + for (earlier, same) in &others[..k] { + assert_ne!(other, same, "{what} and {earlier}"); + } + } + // The halves at another slot, the snapshot at another slot, another + // record at a slot, and a shorter table. + let mut moved = table(true, taken); + (moved[1].half, moved[2].half) = (false, true); + assert_ne!(both, key(&moved, true)); + let mut moved = table(true, taken); + (moved[0].snapshot, moved[2].snapshot) = (None, taken); + assert_ne!(both, key(&moved, true)); + let mut rewritten = table(true, taken); + rewritten[2].record[2] += 1; + assert_ne!(both, key(&rewritten, true)); + assert_ne!(both, key(&table(true, taken)[..2], true)); + } +} diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 53eb5246f..fa822a21e 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -60,6 +60,11 @@ pub mod dxgi; pub mod external; pub mod fence; pub mod frame; +// Plain std, so its tests run everywhere. +#[cfg(any(windows, test))] +// Used by the draws from a later commit. +#[allow(dead_code)] +mod fresh; #[cfg(windows)] mod heap_worker; #[cfg(any(windows, test))] From 12fe5e80038556e7d01c821856cda4b1f08e65c5 Mon Sep 17 00:00:00 2001 From: uncaney <190490737+uncaney@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:07:19 +0100 Subject: [PATCH 4/5] fix(gpu): give a pass a snapshot of constants a later copy of its submission rewrites A list's title copies run on the CPU when it is submitted, in recorded order with the refreshes of host copies, and all before the GPU runs the submission's first command. A buffer's host copy (or the title memory a host buffer shares its pages with) so has one content per submission: what the last copy left. A title that keeps one constant buffer and copies new values into it between two passes of a submission had both passes read the later values: a pass dispatched for a full-size target read a half size copied in for a later pass, and drew one quarter of it. A constant view in a table now reads a snapshot taken at its place among the list's steps once a title copy has been seen to write its bytes after a pass of the same submission read them (`crate::rewritten`, two commits before). This wires that learning and the tables made afresh (`crate::fresh`, the commit before) into the draws and the submission: `Step::Snapshot`, `Step::Constant` and `Step::Table` in the list's steps, `HostHeap::remake_at` for the slots made again at submission, and the unused-code allowances of the two commits before removed. - The table is made afresh in dynamic slots with that view on the list's scratch memory, as unaligned root constant views already read scratch. Its other slots follow the title's records at submission, as a table in place would; a table that also needs a 16-bit view as its unsigned twin is made afresh once with both (`crate::fresh`). - Which ranges need it is learnt at submission: a pass notes the constant ranges it reads through tables, a title copy into one later in the submission makes the shared bytes known, and the next recording snapshots them. The first submission showing a range is not helped and is counted; a range not shown for 64 to 128 frames is forgotten. - A snapshot cannot hold what a shader of the same submission wrote before its pass: where a shader write is declared over the constants before the pass, the pass reads them in place as before, and a snapshot already given is counted. - A snapshot reads title memory when the list is prepared, so `batch_flags` counts it as a fill: a list holding one joins no piece after a shader's writes (with the commit before, at every place the per-queue pump ran the work before first). - With the table memo (`VICTORY_TABLE_MEMO=1`) a remembered entry does not stand for a snapshot. Cost: one note per constant range and list for buffers no copy rewrites under a pass. One log line the first time, and a line with each frame-rate report that has snapshots or late reads to count (snapshots, tables made afresh with their host views and record bytes, late reads). In a diagnostics build the operation list says `snapshot` beside the view and describes the table made afresh. VICTORY_SNAPSHOT_CONSTANTS=0 turns all of it off. Tests: `a_pass_reads_its_constants_as_they_were_before_a_later_copy_of_its_submission` (GPU, under Wine; fails without the snapshots: the first pass reads the later copy's values), the twin, slot, memo, shader-write and count tests in draw.rs and the join test in host.rs (native). Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/descriptor/host.rs | 28 + crates/victory-gpu/src/draw.rs | 1601 ++++++++++++++++++++- crates/victory-gpu/src/hold.rs | 3 +- crates/victory-gpu/src/host.rs | 237 ++- crates/victory-gpu/src/lib.rs | 4 - crates/victory-gpu/src/shadow.rs | 7 +- 6 files changed, 1787 insertions(+), 93 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 71108d7dc..7ded37a60 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1086,6 +1086,34 @@ impl HostHeap { self.note_address(index, Some(view)); } + /// Makes slot `index` (a dynamic one) again from `record`, which the + /// title wrote at the slot's place in its own table after the slot was + /// made, and returns the view recorded. As [`HostHeap::mirror`] makes a + /// title slot when it is written and no draw reads it yet: a view of a + /// texture the title placed itself stays null, and nothing the view + /// needs is made for it. `half`: the shader the slot was made for moves + /// halves through it, so a 16-bit float or signed buffer view is made + /// as its unsigned twin ([`half_view`]), as when the table was made. + pub(crate) fn remake_at(&self, index: u32, record: [u32; 3], half: bool) -> Option { + let [tag, i, generation] = record; + let Some(view) = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten() else { + self.make_null(index); + return None; + }; + if is_placed_texture(&view) { + null_for(&view, self.cpu(index)); + self.keep(index, None); + self.set_stride(index, Some(&view)); + self.set_mark(index, None); + self.note_address(index, Some(&view)); + } else if let Some(twin) = half.then(|| half_view(&view)).flatten() { + self.make_at(index, &twin); + } else { + self.make_at(index, &view); + } + Some(view) + } + /// Makes slot `index` (a dynamic one) a raw view, shader resource or /// unordered access (`uav`), of `bytes` of `buffer` from byte `first` /// (both multiples of 4), which it holds; a null one for no buffer, or diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index fb20de871..2011a9794 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -90,6 +90,18 @@ pub(crate) struct State { dynamic: Vec<(usize, u64, u32, u32)>, /// A fresh table of the stage being bound could not be made. table_failed: bool, + /// The tables made afresh for each stage of the pipeline last bound + /// (root parameter, byte offset in the heap), and of each table made + /// afresh in this list (by its first dynamic slot) the entries that + /// read a snapshot and those shown as the unsigned twin of the title's + /// 16-bit view: the operation list describes the slots a shader reads, + /// which for such a table are not the title's (diagnostics). + #[cfg(feature = "diagnostics")] + bound_fresh: Vec>, + #[cfg(feature = "diagnostics")] + snapshot_entries: std::collections::HashMap>, + #[cfg(feature = "diagnostics")] + twin_entries: std::collections::HashMap>, /// The title-memory page table made for this list (`crate::memory`) /// and its view heap. memory: Option<(usize, crate::memory::Map)>, @@ -1208,6 +1220,8 @@ impl State { } crate::bindless::note_draw(writes); } + #[cfg(feature = "diagnostics")] + self.bound_fresh.clear(); for stage in &p.stages { let t = stage.translated(); self.table_failed = false; @@ -1974,11 +1988,23 @@ impl State { let views = (self.heaps[0] != 0) .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) .flatten(); - for stage in &p.stages { + for (i, stage) in p.stages.iter().enumerate() { let t = stage.translated(); let _ = write!(text, " | {}:", stage.shader.hash); for u in t.host.user_data.iter().filter(|u| !is_root_view(u)) { let v = self.user_value(compute, u.slot, u.root, u.dword); + // A table made afresh: the shader was given that table's + // offset, and reads none of the title's slots there. + if let Some(offset) = self.fresh(i, u.slot).filter(|_| u.root == RootType::Table) { + let _ = write!( + text, + " u{}={offset:#x} [heap {}: table made afresh, the title's at {}]", + u.index, + offset / 32, + v / 32 + ); + continue; + } let _ = write!(text, " u{}={v:#x}", u.index); let index = if u.root == RootType::Table { v / 32 } else { v }; if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { @@ -2015,7 +2041,7 @@ impl State { } } } - let _ = write!(text, " tables {:?}", self.reads(compute)); + let _ = write!(text, " tables {:?}", self.reads(compute, true)); if !compute { let mem = |r: usize| crate::resource::texture_memory(r as This).map_or(0, |(p, _)| p as u64); let targets: Vec = self.targets.iter().map(|&t| format!("{t:#x} mem {:#x}", mem(t))).collect(); @@ -2260,6 +2286,21 @@ impl State { /// with that view in the unsigned format of the same layout /// (`descriptor::host::half_view`): the title's own slot keeps the /// title's format for shaders that read it as floats. + /// + /// A table holding a constant view of bytes a title copy rewrites under + /// a pass (`crate::rewritten`) is made afresh too, that view on a copy + /// of the bytes taken at this place among the list's steps: the slots + /// in place show every pass what the submission's last copy leaves. + /// Such a table's slots are made again at submission where the title + /// rewrote them since ([`remake_table`]), as its slots in place are. + /// + /// A table with both is made afresh once and holds both: the constants + /// on their snapshot and the 16-bit view in its unsigned format (no + /// view is both: a constant view has no twin). The tables made within + /// the list are told apart by both as well (`crate::fresh`), and where + /// the title rewrites a slot of it, the slot is made again as it was + /// made: the twin of a 16-bit view where the shader moves halves. What + /// follows from each reason, alone or together, is `crate::fresh::Why`. pub(crate) fn tables( &mut self, list: &HostList, @@ -2283,7 +2324,9 @@ impl State { }; let prev_depth = TESTED_DEPTH.with(|d| d.replace((if compute { 0 } else { self.depth }, false))); let tables = |u: &&UsedResource| u.root == RootType::Table; - let mut fresh: Vec = Vec::new(); + // The tables made afresh, by root parameter, for each of the three + // reasons (`crate::fresh::Why`): a table may have several. + let (mut twin, mut capped, mut snapshot): (Vec, Vec, Vec) = Default::default(); // The view shown in place of the title's at dword `at` of the table // in root parameter `slot`, if the shader moves halves there and the // title's view is a 16-bit float or signed buffer view. @@ -2305,8 +2348,8 @@ impl State { continue; }; if crate::descriptor::host::half_view(&view).is_some() { - if !fresh.contains(&slot) { - fresh.push(slot); + if !twin.contains(&slot) { + twin.push(slot); } } else if let Some(format) = crate::descriptor::host::half_inexact(&view) { once!( @@ -2319,7 +2362,7 @@ impl State { // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the // title's slots there have no host slot of their own. for u in used.iter().filter(tables) { - if fresh.contains(&u.slot) { + if capped.contains(&u.slot) { continue; } let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { @@ -2333,9 +2376,42 @@ impl State { continue; }; if index >= host.count() { - fresh.push(u.slot); + capped.push(u.slot); + } + } + // Tables holding a constant view that reads a snapshot, whatever + // else they are made afresh for: a table with a 16-bit view shown + // as its unsigned twin, or past a capped heap, holds its snapshots + // in the one table made for it. + if crate::rewritten::any() { + for u in used + .iter() + .filter(tables) + .filter(|u| u.kind == ResourceType::Cbv) + { + if snapshot.contains(&u.slot) { + continue; + } + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) + else { + continue; + }; + if self + .heap_of(table) + .is_some_and(|heap| heap.host().is_some()) + && rewritten_constant(list, table + u64::from(u.table_offset_dwords) * 4) + .is_some() + { + snapshot.push(u.slot); + } } } + let why = |slot: u8| crate::fresh::Why { + twin: twin.contains(&slot), + capped: capped.contains(&slot), + snapshot: snapshot.contains(&slot), + }; + let mut fresh: Vec = [twin.as_slice(), &capped, &snapshot].concat(); fresh.sort_unstable(); fresh.dedup(); for u in used.iter().filter(tables) { @@ -2345,6 +2421,7 @@ impl State { } let mut made = Vec::new(); for slot in fresh { + let why = why(slot); let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { continue; }; @@ -2372,21 +2449,50 @@ impl State { ) .max() .unwrap_or(1); - // The table and what its entries hold (record words). - let key = { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - n.hash(&mut h); - for k in 0..n { + // The constants read as snapshots: entry, scratch buffer, offset + // in it and bytes. A title copy ends a snapshot, so the passes + // after it get another, and another table. + let snapshots: Vec<(u32, ID3D12Resource, u64, u64)> = if crate::rewritten::any() { + let constants = entries.iter().filter(|u| u.kind == ResourceType::Cbv); + constants + .filter_map(|u| { + let handle = table + u64::from(u.table_offset_dwords) * 4; + let (address, len) = rewritten_constant(list, handle)?; + let (buffer, at) = list.snapshot(address, len)?; + Some((u.table_offset_dwords / 8, buffer, at, len)) + }) + .collect() + } else { + Vec::new() + }; + // The records the title has at the table's slots now. + let records: Vec<[u32; 3]> = (0..n) + .map(|k| { let at = table + u64::from(k) * 32; // SAFETY: a descriptor slot in title memory. - unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); - // Another table than the same slots made for a shader - // that reads them in the title's formats. - half.contains(&(slot, k * 8)).hash(&mut h); - } - (table, h.finish()) - }; + unsafe { (at as *const [u32; 3]).read_unaligned() } + }) + .collect(); + // The table and what its slots hold (`crate::fresh`): the + // record, whether the shader moves halves there (another table + // than the same slots made for a shader that reads them in the + // title's formats) and the snapshot read there. + let slots: Vec = (0..n) + .zip(&records) + .map(|(k, &record)| crate::fresh::Slot { + record, + half: half.contains(&(slot, k * 8)), + snapshot: snapshots + .iter() + .find(|s| s.0 == k) + .map(|(_, buffer, at, _)| (buffer.as_raw() as usize, *at)), + }) + .collect(); + // A table whose slots are made again where the title rewrites + // them and one that stays as recorded do not stand for each + // other (the entries alone do not tell them apart: a table may + // reach further for a view the shader moves halves through). + let key = (table, crate::fresh::key(&slots, why.followed())); if let Some(&first) = self.fresh_tables.get(&key) { for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; @@ -2410,6 +2516,14 @@ impl State { continue; } let Some(first) = host.dynamic(n) else { + // A table wanted afresh only for its snapshots has its slots + // in place: the pass reads those, as before snapshots. + if why.in_place_without_slots() { + for u in &entries { + self.table_entry(list, u, compute, writes(u)); + } + continue; + } // Without its fresh table the shader would read the title's // slots, which for constant buffer tables hold no constant // view: a texture or null descriptor read as a buffer gives @@ -2421,16 +2535,33 @@ impl State { self.fresh_tables.insert(key, first); self.dynamic .push((std::ptr::from_ref(heap) as usize, host.id(), first, n)); + #[cfg(feature = "diagnostics")] + if !snapshots.is_empty() { + self.snapshot_entries + .insert(first, snapshots.iter().map(|s| s.0).collect()); + } + #[cfg(feature = "diagnostics")] + let mut twins: Vec = Vec::new(); // The whole range: a shader may index past the entries its // used-resource list names (descriptor arrays). for k in 0..n { let index = first + k; + if let Some((_, buffer, at, len)) = snapshots.iter().find(|s| s.0 == k) { + // As a constant view is made (`crate::descriptor::host`, + // `make`): a raw view of its bytes, here the snapshot's. + host.raw_view_at(index, Some(buffer), *at, *len, false); + continue; + } let used_entry = entries.iter().find(|u| u.table_offset_dwords / 8 == k); let view = crate::descriptor::view(table + u64::from(k) * 32); match view.as_deref() { Some(view) => { match halved(self, slot, k * 8) { - Some(twin) => host.make_at(index, &twin), + Some(twin) => { + host.make_at(index, &twin); + #[cfg(feature = "diagnostics")] + twins.push(k); + } None => host.make_at(index, view), } if let Some(u) = used_entry { @@ -2445,9 +2576,30 @@ impl State { } } } + #[cfg(feature = "diagnostics")] + if !twins.is_empty() { + self.twin_entries.insert(first, twins); + } + if why.snapshot { + crate::rewritten::table_made(u64::from(n)); + } + // The slots in place would show what the title's records hold + // when the list is submitted (17b669f): so does this table. A + // slot the shader moves halves through is made again as it was + // made here: the twin of a 16-bit view the title has there then. + if why.followed() { + let (heap, id) = (std::ptr::from_ref(heap) as usize, host.id()); + let made = std::sync::Mutex::new(records); + let halves: Vec = slots.iter().map(|s| s.half).collect(); + list.defer_table(move |refresh| { + remake_table((heap, id), table, first, &made, &halves, refresh) + }); + } made.push((slot, first * 32)); } TESTED_DEPTH.with(|d| d.set(prev_depth)); + #[cfg(feature = "diagnostics")] + self.bound_fresh.push(made.clone()); made } @@ -2479,7 +2631,7 @@ impl State { v.address, v.size, v.stride, - self.reads(false) + self.reads(false, false) ); if logged { tracing::debug!("draw {line}"); @@ -2591,43 +2743,23 @@ impl State { } /// What a draw's shaders read, one line per used resource (diagnostics - /// builds). + /// builds). `bound`: the draw's pipeline was bound last ([`State::bind`]), + /// so the tables made afresh for it are known; before that every table + /// is described in place. #[cfg(feature = "diagnostics")] - fn reads(&self, compute: bool) -> Vec { + fn reads(&self, compute: bool, bound: bool) -> Vec { let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { return vec!["no host pipeline".into()]; }; let mut out = Vec::new(); - for stage in &p.stages { + for (i, stage) in p.stages.iter().enumerate() { let t = stage.translated(); for u in &t.used { - let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) { - (RootType::Table, Some(Root::Table(table))) => { - let handle = table + u64::from(u.table_offset_dwords) * 4; - let view = crate::descriptor::view(handle); - let mut text = describe(view.as_deref()); - // The title's view words, and whether the host slot - // the shader reads was made from a view. - if let Some(View::Shader(_, Some(w)) | View::Unordered(_, _, Some(w))) = view.as_deref() { - text.push_str(&format!(" words {w:?}")); - } - let slot = (self.heaps[0] != 0) - .then(|| crate::descriptor::heap(self.heaps[0] as This)) - .and_then(|h| { - let i = handle.checked_sub(h.start)? / 32; - h.host()?.describe_slot(u32::try_from(i).ok()?) - }); - let current: String = view.as_deref().map(|v| format!("{v:?}")).unwrap_or_default().chars().take(120).collect(); - text.push_str(match slot.as_deref() { - Some("null") => " slot null", - Some(s) if s.starts_with(¤t) => " slot made", - Some(_) => " slot stale", - None => " slot unknown", - }); - text - } - (root, _) => format!("{root:?}"), - }; + let fresh = if bound { self.fresh(i, u.slot) } else { None }; + let what = (u.root == RootType::Table) + .then(|| self.table_read(u, compute, fresh)) + .flatten() + .unwrap_or_else(|| format!("{:?}", u.root)); out.push(format!( "{} {:?} s{}+{}: {what}", stage.shader.hash, u.kind, u.slot, u.table_offset_dwords @@ -2637,6 +2769,83 @@ impl State { out } + /// The byte offset of the table made afresh for root parameter `slot` + /// of stage `stage` of the pipeline last bound, if one was + /// (diagnostics). + #[cfg(feature = "diagnostics")] + fn fresh(&self, stage: usize, slot: u8) -> Option { + let made = self.bound_fresh.get(stage)?; + made.iter().find(|m| m.0 == slot).map(|m| m.1) + } + + /// What a shader reads through table entry `u` (diagnostics): the view + /// the title has there, and the state of the host slot the shader + /// reads. In place that is the title's own slot: `slot made` from the + /// view, `slot null`, or `slot stale` (made from another record). For + /// a table made afresh at byte offset `fresh` it is a dynamic slot, + /// made from the view when the pass was recorded: `fresh slot N made` + /// or `null` (the host could not make the view), after `snapshot` where + /// the entry reads a snapshot of its constants and `unsigned twin` + /// where it shows the title's 16-bit view in the unsigned format. None + /// if no table is set at the root parameter. + #[cfg(feature = "diagnostics")] + fn table_read(&self, u: &UsedResource, compute: bool, fresh: Option) -> Option { + let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + return None; + }; + let handle = table + u64::from(u.table_offset_dwords) * 4; + let view = crate::descriptor::view(handle); + let mut text = describe(view.as_deref()); + // The title's view words, and whether the host slot the shader + // reads was made from a view. + if let Some(View::Shader(_, Some(w)) | View::Unordered(_, _, Some(w))) = view.as_deref() { + text.push_str(&format!(" words {w:?}")); + } + let heap = (self.heaps[0] != 0).then(|| crate::descriptor::heap(self.heaps[0] as This)); + if let Some(offset) = fresh { + let (first, k) = (offset / 32, u.table_offset_dwords / 8); + if self + .snapshot_entries + .get(&first) + .is_some_and(|ks| ks.contains(&k)) + { + text.push_str(" snapshot"); + } + if self + .twin_entries + .get(&first) + .is_some_and(|ks| ks.contains(&k)) + { + text.push_str(" unsigned twin"); + } + let holds = heap.and_then(|h| h.host()).map(|h| h.kept(first + k)); + text.push_str(&match holds { + Some(true) => format!(" fresh slot {} made", first + k), + Some(false) => format!(" fresh slot {} null", first + k), + None => format!(" fresh slot {} unknown", first + k), + }); + return Some(text); + } + let slot = heap.and_then(|h| { + let i = handle.checked_sub(h.start)? / 32; + h.host()?.describe_slot(u32::try_from(i).ok()?) + }); + let current: String = view + .as_deref() + .map(|v| format!("{v:?}")) + .unwrap_or_default() + .chars() + .take(120) + .collect(); + text.push_str(match slot.as_deref() { + Some("null") => " slot null", + Some(s) if s.starts_with(¤t) => " slot made", + Some(_) => " slot stale", + None => " slot unknown", + }); + Some(text) + } + pub(crate) fn draw( &mut self, list: &HostList, @@ -3143,16 +3352,7 @@ fn readable_entry(list: &HostList, u: &UsedResource, view: &View, marked: bool, let view = placed.as_ref().unwrap_or(view); // Buffer views read title memory: their range is copied at submission; // what shaders write through unordered access goes back to it after. - // Constant buffers (raw views) to their copy's end at most; others in - // the copy their host view reads. - let range = match *view { - View::Constant(address, size) => crate::shadow::find(address, 1).map(|s| { - let len = u64::from(size).min(s.left(address)); - (s, address, len) - }), - _ => crate::descriptor::host::view_copy(view), - }; - if let Some((shadow, address, len)) = range + if let Some((shadow, address, len)) = buffer_of(view) && len > 0 { let uav_writes = u.kind == ResourceType::Uav && writes; @@ -3161,7 +3361,12 @@ fn readable_entry(list: &HostList, u: &UsedResource, view: &View, marked: bool, } else { (address, len) }; - shadow.refresh(list, refresh_at, refresh_len); + let asked = shadow.refresh(list, refresh_at, refresh_len); + // A title copy into a constant view's bytes later in the submission + // reaches this pass, which is how such bytes get known. + if asked && matches!(view, View::Constant(..)) && crate::rewritten::enabled() { + list.defer_constant(address as usize, len as usize); + } if uav_writes { shadow.gpu_writes(list, address, len, marked); } else if u.kind == ResourceType::Srv && crate::descriptor::host::three_channel_srv(view) { @@ -3220,6 +3425,120 @@ fn readable_entry(list: &HostList, u: &UsedResource, view: &View, marked: bool, } } +/// The title memory a buffer view reads and the host copy it is in. +/// Constant buffers (raw views) to their copy's end at most; others in the +/// copy their host view reads. +fn buffer_of(view: &View) -> Option<(std::sync::Arc, u64, u64)> { + match *view { + View::Constant(address, size) => crate::shadow::find(address, 1).map(|s| { + let len = u64::from(size).min(s.left(address)); + (s, address, len) + }), + _ => crate::descriptor::host::view_copy(view), + } +} + +/// At submission, for a table made afresh for a snapshot (`State::tables`) +/// in the `made.len()` dynamic slots from `first` of the host heap behind +/// the title heap at `heap.0`: each slot whose record at `table` is no +/// longer the one in `made`, which the slot was made from, is made again +/// from the record there now, and the buffer range its view reads is given +/// to `refresh`. The title rewrote such a slot after the pass was recorded; +/// a table in place shows the new view (and a `Slot` step brings its range +/// up to date), so this one does. A constant view rewritten so reads its +/// buffer's host copy like any other: its snapshot was of the view before. +/// `halves`: the slots the shader moves halves through, where a 16-bit +/// float or signed buffer view is made again as its unsigned twin. +/// +/// `heap.1` is the identity of the host heap the slots were taken from +/// (`HostHeap::id`): another one behind that address by now (the title +/// released its heap and a later heap took the address) is left alone, as +/// it is when dynamic slots are given back. +fn remake_table( + heap: (usize, u64), + table: u64, + first: u32, + made: &std::sync::Mutex>, + halves: &[bool], + refresh: &mut dyn FnMut(&std::sync::Arc, usize, usize), +) { + let mut made = made.lock().unwrap_or_else(|e| e.into_inner()); + // In one read, through the kernel: the title unmaps heap pages too. + let mut now = vec![0u8; made.len() * 32]; + if !crate::host::read_into(table as *const u8, &mut now) { + return; + } + crate::rewritten::records_read(now.len() as u64); + let record = |k: usize| -> [u32; 3] { + std::array::from_fn(|w| { + let at = 32 * k + 4 * w; + u32::from_le_bytes([now[at], now[at + 1], now[at + 2], now[at + 3]]) + }) + }; + if (0..made.len()).all(|k| record(k) == made[k]) { + return; + } + // The views are let go last, outside every lock taken here: a pin may + // hold the last reference of a resource the title released. No host + // heap, or another one: the title released the heap, and no one reads + // its slots. + let views = crate::descriptor::with_host(heap.0, |host| { + let mut views = Vec::new(); + if host.id() != heap.1 { + return views; + } + for (k, was) in made.iter_mut().enumerate() { + let record = record(k); + if record == *was { + continue; + } + *was = record; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + "the title rewrote a slot of a table made afresh for a snapshot of constants after its pass \ + was recorded: such slots are made again when the list is submitted" + ) + }); + let half = halves.get(k).copied().unwrap_or(false); + crate::rewritten::slots_remade(1); + let Some(view) = host.remake_at(first + k as u32, record, half) else { + continue; + }; + // None for a texture's view: nothing of it is copied here. + if let Some((shadow, address, len)) = buffer_of(&view) + && len > 0 + { + refresh(&shadow, address as usize, len as usize); + } + views.push(view); + } + views + }); + drop(made); + drop(views); +} + +/// The constant view the title has at `handle`, if a pass of `list` is to +/// read a snapshot of it: its address and as many of its bytes as its +/// buffer holds. A title copy rewrites bytes of it under a pass +/// (`crate::rewritten`), and the list declared no write by its shaders over +/// any of them since the last title copy there: what they wrote is in no +/// snapshot, so such constants are read in place. +fn rewritten_constant(list: &HostList, handle: u64) -> Option<(u64, u64)> { + let view = crate::descriptor::view(handle)?; + let View::Constant(address, size) = *view else { + return None; + }; + // Most constants are not: asked before their buffer is looked up. + if !crate::rewritten::known(address, u64::from(size)) { + return None; + } + let len = u64::from(size).min(crate::shadow::find(address, 1)?.left(address)); + (len > 0 && crate::rewritten::known(address, len) && !list.shader_wrote(address, len)) + .then_some((address, len)) +} + /// A view in a few words (diagnostics builds). #[cfg(feature = "diagnostics")] fn describe(view: Option<&View>) -> String { @@ -4764,16 +5083,34 @@ void main() { dst.Store4(0, asuint(src[0])); } #[test] fn a_table_slot_rewritten_before_submission_refreshes_its_new_view() { for mode in [Rewrite::Mirrored, Rewrite::Copied, Rewrite::DuringSubmission] { - check_table_slot_rewrite(mode); + check_table_slot_rewrite(mode, false); + } + } + + /// The same of a table made afresh because its constants are known as + /// rewritten under a pass (`crate::rewritten`): its slots are made when + /// the pass is recorded, and made again at submission from the records + /// the title has there by then, as a table in place shows them. + #[test] + fn a_table_made_afresh_for_a_snapshot_follows_a_slot_rewritten_before_submission() { + for mode in [ + Rewrite::Mirrored, + Rewrite::Copied, + Rewrite::DuringSubmission, + ] { + check_table_slot_rewrite(mode, true); } } /// `Copied` leaves the host mirror to the submission's heap sync; /// `DuringSubmission` rewrites after that sync, before deferred work. - fn check_table_slot_rewrite(mode: Rewrite) { + /// `known`: the constants the slot names first are known as rewritten + /// under a pass, so the table is made afresh (unless snapshots are off). + fn check_table_slot_rewrite(mode: Rewrite, known: bool) { let Some(host) = crate::host::host() else { return; // no host GPU here }; + let known = known && crate::rewritten::enabled(); let (a, b, out) = (buffer(256), buffer(256), buffer(256)); let (a_bytes, _) = crate::resource::buffer_bytes(a).unwrap(); let (b_bytes, _) = crate::resource::buffer_bytes(b).unwrap(); @@ -4841,15 +5178,47 @@ void main() { dst.Store4(0, asuint(src[0])); } crate::descriptor::create_cbv(std::ptr::null(), &b_desc, handle) }); } + if known { + // A pass reads the constants at `a` and a title copy of its + // submission then rewrites them. + let seen = host.new_list().unwrap(); + let mut state = State::default(); + state.set_heaps(&[heap]); + state.set_table(true, 0, title_heap.start); + assert!( + state + .tables( + &seen, + &[used(ResourceType::Cbv)], + &[false], + false, + &[], + true + ) + .is_empty() + ); + let zeros = [0u8; 256]; + seen.defer_copy(a_bytes as *mut u8, zeros.as_ptr(), 256); + seen.close(); + host.execute(&[&seen]); + assert!(crate::rewritten::known(a_bytes, 256), "known ({mode:?})"); + } let mut state = State::default(); state.set_heaps(&[heap]); state.set_table(true, 0, title_heap.start); - assert!( - state - .tables(&list, &[used(ResourceType::Srv)], &[false], false, &[], true) - .is_empty(), - "an in-place table" + let kind = if known { + ResourceType::Cbv + } else { + ResourceType::Srv + }; + let made = state.tables(&list, &[used(kind)], &[false], false, &[], true); + assert_eq!( + made.is_empty(), + !known, + "in place unless its constants are known ({mode:?})" ); + // The heap slot the shader's table of constants is at. + let table = made.first().map_or(0, |&(_, offset)| offset / 32); // The title replaces the record after recording, before submission. if mode == Rewrite::Copied { @@ -4877,7 +5246,8 @@ void main() { dst.Store4(0, asuint(src[0])); } list.list .SetDescriptorHeaps(&[Some(host_heap.heap.clone())]); list.list.SetComputeRootSignature(&root); - list.list.SetComputeRootDescriptorTable(0, host_heap.gpu(0)); + list.list + .SetComputeRootDescriptorTable(0, host_heap.gpu(table)); list.list.SetComputeRootDescriptorTable(1, host_heap.gpu(1)); list.list.SetComputeRoot32BitConstants(2, 2, [0u32; 2].as_ptr().cast(), 0); list.list.SetPipelineState(&pso); @@ -4888,7 +5258,7 @@ void main() { dst.Store4(0, asuint(src[0])); } assert_eq!( out_copy.read_host(out_bytes, 1), [0x2222_2222], - "the new descriptor's data ({mode:?})" + "the new descriptor's data ({mode:?}, known {known})" ); assert_eq!( crate::object::slot:: u32>(heap, 0x10)(heap), @@ -5016,6 +5386,1093 @@ void main() { dst.Store4(0, asuint(src[0])); } } } + /// Copies the eight dwords of the constants in the table at `t0` into + /// the buffer in the table at `u0`. + const CONSTANTS_OUT: &str = r#" +ByteAddressBuffer constants : register(t0); +RWByteAddressBuffer target : register(u0); +[numthreads(8, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + target.Store(id.x * 4, constants.Load(id.x * 4)); +} +"#; + + /// A title keeps one constant buffer and copies new values into it + /// between the passes of a list: each pass must read what the buffer + /// held where the title recorded it. The list's copies all run on the + /// CPU before the GPU runs its first pass, so a pass reading the + /// buffer's host copy gets what the last copy left; from the submission + /// after the one that shows this, its table is made afresh and reads a + /// snapshot (`crate::rewritten`). Switched off, it reads the last copy's + /// values in every submission. + /// + /// Once with the constants in a buffer with a host copy, and under + /// Rosetta once in title memory a host buffer shares its pages with + /// (`crate::alias`), where a copy reaches the GPU's bytes as it runs. + #[test] + fn a_pass_reads_its_constants_as_they_were_before_a_later_copy_of_its_submission() { + if crate::host::host().is_none() { + return; // no host GPU here + } + let copied = crate::resource::buffer_bytes(buffer(256)).unwrap().0 as u64; + check_constants_rewritten_under_a_pass(copied); + if crate::watch::rosetta() { + let page = crate::watch::tests::pool(1); + if crate::alias::alias_region(page, crate::watch::PAGE, false) { + // 16-byte aligned as the console asks, not the host's 256. + check_constants_rewritten_under_a_pass(page as u64 + 0xcd0); + crate::alias::unalias_region(page); + } else { + eprintln!("skipped: no title memory on a host buffer's pages here"); + } + crate::watch::tests::free(page); + } + } + + fn check_constants_rewritten_under_a_pass(constants: u64) { + let host = crate::host::host().unwrap(); + let on = crate::rewritten::enabled(); + let targets = [buffer(256), buffer(256), buffer(256)]; + let [first, second, third] = + targets.map(|b| crate::resource::buffer_bytes(b).unwrap().0 as u64); + let (heap, title_heap, heap_host) = view_heap(8); + let null = std::ptr::null(); + crate::descriptor::create_cbv( + null, + &[constants as u32, (constants >> 32) as u32, 32, 0], + title_heap.start, + ); + let raw: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + for (slot, target) in targets.iter().enumerate() { + let handle = title_heap.start + 32 * (slot as u64 + 1); + crate::descriptor::create_uav(null, *target, null, &raw, handle); + } + let out = |at: u64| { + let copy = crate::shadow::find(at, 256).expect("a target's host copy"); + copy.read_host(at, 8) + }; + let (root, pso) = compile_cs( + CONSTANTS_OUT, + &[Param::Table(&[srv(0, 1)]), Param::Table(&[uav(0, 1)])], + ); + let entry = used(ResourceType::Cbv); + // Records a pass writing the constants into the target at `slot`; + // returns the heap slot its table of constants is at. + let pass = |list: &HostList, state: &mut State, slot: u32| { + let made = state.tables(list, std::slice::from_ref(&entry), &[], true, &[], true); + let table = made.first().map_or(0, |&(_, offset)| offset / 32); + // SAFETY: an open list and live objects of ours. + unsafe { + list.list + .SetDescriptorHeaps(&[Some(heap_host.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list + .SetComputeRootDescriptorTable(0, heap_host.gpu(table)); + list.list + .SetComputeRootDescriptorTable(1, heap_host.gpu(slot)); + list.list.SetPipelineState(&pso); + list.list.Dispatch(1, 1, 1); + } + table + }; + let values = |tag: u32| -> [u32; 8] { std::array::from_fn(|k| tag << 8 | k as u32) }; + let copy = |list: &HostList, from: &[u32; 8]| { + list.defer_copy(constants as *mut u8, from.as_ptr().cast(), 32); + }; + let list = host.new_list().unwrap(); + // The title's frame, recorded and submitted three times: full-size + // constants, a pass, half-size constants, two passes. + for frame in 0..3u32 { + if frame > 0 { + list.reset(); + } + let (full, half) = (values(0x10 + frame), values(0x20 + frame)); + let mut state = State::default(); + state.set_heaps(&[heap]); + state.set_table(true, 0, title_heap.start); + copy(&list, &full); + let a = pass(&list, &mut state, 1); + copy(&list, &half); + let b = pass(&list, &mut state, 2); + let c = pass(&list, &mut state, 3); + list.close(); + host.execute(&[&list]); + assert_eq!(out(second), half, "after the last copy (frame {frame})"); + assert_eq!(out(third), half, "after the last copy (frame {frame})"); + if frame == 0 || !on { + // The submission that shows the range, and every one with + // snapshots off: tables in place, the last copy's values. + assert_eq!([a, b, c], [0; 3], "tables in place (frame {frame})"); + assert_eq!(out(first), half, "the last copy's values (frame {frame})"); + assert_eq!( + crate::rewritten::known(constants, 32), + on, + "seen unless off" + ); + continue; + } + assert_eq!( + out(first), + full, + "what the buffer held at the first pass (frame {frame})" + ); + assert!( + a != 0 && b != 0 && a != b, + "a table of its own on each side of the copy" + ); + assert_eq!(b, c, "one snapshot between two copies"); + } + // A pass before the first copy of its submission reads what the + // last submission left. + list.reset(); + let (left, new) = (values(0x22), values(0x30)); + let mut state = State::default(); + state.set_heaps(&[heap]); + state.set_table(true, 0, title_heap.start); + pass(&list, &mut state, 1); + copy(&list, &new); + pass(&list, &mut state, 2); + list.close(); + host.execute(&[&list]); + assert_eq!( + out(first), + if on { left } else { new }, + "before the submission's first copy" + ); + assert_eq!(out(second), new); + // SAFETY: the constants' own bytes. + let title = unsafe { (constants as *const [u32; 8]).read() }; + assert_eq!(title, new, "title memory has the last copy"); + } + + /// With the memo of table entries on (`VICTORY_TABLE_MEMO=1`, #462) a + /// list skips an entry it has prepared since its last title copy. + /// Whether a table's constants read a snapshot is asked for every pass, + /// before any entry is looked up: an entry remembered while its table + /// was read in place does not keep the table in place once the + /// constants are known as rewritten under a pass. A title copy ends the + /// list's snapshots and what it remembered together, so the pass after + /// it gets a snapshot of its own. + #[test] + fn a_remembered_table_entry_does_not_stand_for_a_snapshot() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + if !crate::rewritten::enabled() { + return; // no table is made afresh for a snapshot + } + let _memo = TableMemoGuard::set(1); + flush_memo_local(); + let hits = || local_memo_counts()[1]; + let constants = bytes_of(buffer(256)); + let targets = [buffer(256), buffer(256), buffer(256), buffer(256)]; + let [first, second, third, fourth] = targets.map(bytes_of); + let (heap, title_heap, heap_host) = view_heap(8); + let null = std::ptr::null(); + let cbv = |at: u64| [at as u32, (at >> 32) as u32, 32, 0]; + crate::descriptor::create_cbv(null, &cbv(constants), title_heap.start); + let raw: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + for (slot, target) in targets.iter().enumerate() { + let handle = title_heap.start + 32 * (slot as u64 + 1); + crate::descriptor::create_uav(null, *target, null, &raw, handle); + } + let (root, pso) = compile_cs( + CONSTANTS_OUT, + &[Param::Table(&[srv(0, 1)]), Param::Table(&[uav(0, 1)])], + ); + let entry = used(ResourceType::Cbv); + // The writes unknown, so that every entry goes through the memo. + let tables = |list: &HostList, state: &mut State| { + state.tables(list, std::slice::from_ref(&entry), &[], true, &[], true) + }; + // Records a pass writing the constants into the target at `slot`; + // returns the heap slot its table of constants is at. + let pass = |list: &HostList, state: &mut State, slot: u32| { + let table = tables(list, state) + .first() + .map_or(0, |&(_, offset)| offset / 32); + // SAFETY: an open list and live objects of ours. + unsafe { + list.list + .SetDescriptorHeaps(&[Some(heap_host.heap.clone())]); + list.list.SetComputeRootSignature(&root); + list.list + .SetComputeRootDescriptorTable(0, heap_host.gpu(table)); + list.list + .SetComputeRootDescriptorTable(1, heap_host.gpu(slot)); + list.list.SetPipelineState(&pso); + list.list.Dispatch(1, 1, 1); + } + table + }; + let state_at = |table: u64| { + let mut state = State::default(); + state.set_heaps(&[heap]); + state.set_table(true, 0, table); + state + }; + let (old, new) = (tagged(0xd0), tagged(0xd1)); + // SAFETY: the constants' own bytes. + unsafe { (constants as *mut [u32; 8]).write(old) }; + let list = host.new_list().unwrap(); + let mut state = state_at(title_heap.start); + // Two passes in place: the second finds its entry remembered. + let a = pass(&list, &mut state, 1); + let before = hits(); + let b = pass(&list, &mut state, 2); + assert_eq!([a, b], [0, 0], "in place: nothing is known yet"); + assert_eq!(hits(), before + 1, "the second pass's entry was remembered"); + // Another submission shows the range meanwhile: a pass reads the + // constants and a copy of its submission rewrites them (with the + // bytes they hold). + let seen = host.new_list().unwrap(); + assert!(tables(&seen, &mut state_at(title_heap.start)).is_empty()); + seen.defer_copy(constants as *mut u8, old.as_ptr().cast(), 32); + seen.close(); + host.execute(&[&seen]); + assert!(crate::rewritten::known(constants, 32), "known from here on"); + // The list has copied nothing since, so its entry is remembered + // still: the next pass gets its snapshot all the same. + let c = pass(&list, &mut state, 3); + assert_ne!(c, 0, "a table of its own past the remembered entry"); + // A copy, then a pass: another snapshot, in another table. + list.defer_copy(constants as *mut u8, new.as_ptr().cast(), 32); + let d = pass(&list, &mut state, 4); + assert!(d != 0 && d != c, "another table after the copy"); + // Something of the list reads the buffer's host copy after the copy, + // as a pass in place would: it holds the copy's bytes when the GPU + // runs the list. + let copy = crate::shadow::find(constants, 32).expect("the constants' host copy"); + assert!( + copy.refresh(&list, constants, 32), + "asked again after the copy" + ); + list.close(); + host.execute(&[&list]); + assert_eq!( + host_dwords(third), + old, + "the constants as they were at the third pass" + ); + assert_eq!(host_dwords(fourth), new, "and after the copy"); + // Recorded in place before the range was known: the copy reaches them. + assert_eq!(host_dwords(first), new); + assert_eq!(host_dwords(second), new); + + // The memo's verify mode runs the whole path again on a hit and + // counts what that changed: constants read in place a second time + // leave no step behind (their read is noted once per refresh asked). + let _verify = TableMemoGuard::set(2); + flush_memo_local(); + let plain = bytes_of(buffer(256)); + let handle = title_heap.start + 32 * 5; + crate::descriptor::create_cbv(null, &cbv(plain), handle); + let list = host.new_list().unwrap(); + let mut state = state_at(handle); + assert!(tables(&list, &mut state).is_empty() && tables(&list, &mut state).is_empty()); + let counts = local_memo_counts(); + assert_eq!( + (counts[1], counts[2], counts[3], counts[4]), + (1, 0, 0, 0), + "one hit, and nothing it changed" + ); + list.close(); + } + + /// Passes that copy the constants their table names into the buffer the + /// same table names after them (`CONSTANTS_OUT`), which `State::tables` + /// so declares as written by the pass's shader. + struct ConstantPasses { + heap: This, + title: &'static crate::descriptor::Heap, + host_heap: &'static crate::descriptor::host::HostHeap, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + entries: [UsedResource; 2], + } + + impl ConstantPasses { + /// With room for `tables` tables of two slots. + fn new(tables: u32) -> Self { + let (heap, title, host_heap) = view_heap(2 * tables); + let (root, pso) = compile_cs(CONSTANTS_OUT, &[Param::Table(&[srv(0, 1), uav(0, 1)])]); + let target = UsedResource { + table_offset_dwords: 8, + ..used(ResourceType::Uav) + }; + ConstantPasses { + heap, + title, + host_heap, + root, + pso, + entries: [used(ResourceType::Cbv), target], + } + } + + /// Table `t`: 32 bytes of constants at `constants`, and `target`. + fn table(&self, t: u32, constants: u64, target: This) { + let null = std::ptr::null(); + let at = self.title.start + 64 * u64::from(t); + crate::descriptor::create_cbv( + null, + &[constants as u32, (constants >> 32) as u32, 32, 0], + at, + ); + let raw: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + crate::descriptor::create_uav(null, target, null, &raw, at + 32); + } + + fn state(&self) -> State { + let mut state = State::default(); + state.set_heaps(&[self.heap]); + state + } + + /// Records a pass through table `t`; whether its table was made + /// afresh. + fn pass(&self, list: &HostList, state: &mut State, t: u32) -> bool { + state.set_table(true, 0, self.title.start + 64 * u64::from(t)); + let made = state.tables(list, &self.entries, &[], true, &[], true); + let table = made.first().map_or(2 * t, |&(_, offset)| offset / 32); + // SAFETY: an open list and live objects of ours. + unsafe { + list.list + .SetDescriptorHeaps(&[Some(self.host_heap.heap.clone())]); + list.list.SetComputeRootSignature(&self.root); + list.list + .SetComputeRootDescriptorTable(0, self.host_heap.gpu(table)); + list.list.SetPipelineState(&self.pso); + list.list.Dispatch(1, 1, 1); + // What the pass wrote is there for the next one. + list.list.ResourceBarrier(&[crate::host::uav_barrier()]); + } + !made.is_empty() + } + } + + /// A title buffer's address, and eight dwords tagged `tag`. + fn bytes_of(buffer: This) -> u64 { + crate::resource::buffer_bytes(buffer).unwrap().0 as u64 + } + + fn tagged(tag: u32) -> [u32; 8] { + std::array::from_fn(|k| tag << 8 | k as u32) + } + + fn host_dwords(at: u64) -> Vec { + crate::shadow::find(at, 256) + .expect("a host copy") + .read_host(at, 8) + } + + /// A table made afresh for a snapshot of its constants follows every + /// slot the title rewrites after the pass was recorded, as a table in + /// place does: here the buffer the pass writes into. The constants' + /// own slot was not rewritten and keeps its snapshot. + #[test] + fn a_table_made_afresh_for_a_snapshot_follows_its_other_slots_too() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + if !crate::rewritten::enabled() { + return; // no table is made afresh for a snapshot + } + let p = ConstantPasses::new(2); + let x = bytes_of(buffer(256)); + let outs = [buffer(256), buffer(256), buffer(256)]; + let [first, _, late] = outs.map(bytes_of); + p.table(0, x, outs[0]); + p.table(1, x, outs[1]); + let list = host.new_list().unwrap(); + let values = [0x30, 0x31].map(|tag| (tagged(tag), tagged(tag + 0x10))); + // The fault's shape twice: from the second on the passes read + // snapshots through tables made afresh. + for (frame, (full, half)) in values.iter().enumerate() { + if frame > 0 { + list.reset(); + } + let mut state = p.state(); + list.defer_copy(x as *mut u8, full.as_ptr().cast(), 32); + let fresh = p.pass(&list, &mut state, 0); + list.defer_copy(x as *mut u8, half.as_ptr().cast(), 32); + p.pass(&list, &mut state, 1); + assert_eq!(fresh, frame > 0, "a snapshot from the second on"); + if fresh { + // The first pass was recorded with `outs[0]` in this slot. + let raw: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + crate::descriptor::create_uav( + std::ptr::null(), + outs[2], + std::ptr::null(), + &raw, + p.title.start + 32, + ); + } + list.close(); + host.execute(&[&list]); + } + assert_eq!( + host_dwords(late), + values[1].0, + "written where the slot points at submission, from the snapshot" + ); + assert_eq!( + host_dwords(first), + values[0].1, + "not where it pointed when the pass was recorded" + ); + } + + /// The frame-rate report counts what the snapshots cost beside their + /// bytes (`crate::rewritten::take`): the tables made afresh for them, + /// the host views made in their slots, when the passes are recorded and + /// again at submission where the title rewrote a slot, and the bytes of + /// the title's records read for them at submission. A list makes one + /// table for all its passes through a title table that read the same + /// snapshot (`crate::fresh`): four passes here, two title tables of two + /// slots each, two tables. + #[test] + fn the_tables_made_afresh_for_snapshots_are_counted_with_their_views_and_records() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + if !crate::rewritten::enabled() { + return; // no table is made afresh for a snapshot + } + let p = ConstantPasses::new(2); + let x = bytes_of(buffer(256)); + let outs = [buffer(256), buffer(256), buffer(256)]; + p.table(0, x, outs[0]); + p.table(1, x, outs[1]); + let list = host.new_list().unwrap(); + let (full, half) = (tagged(0x60), tagged(0x61)); + let mut made = Vec::new(); + for frame in 0..2 { + if frame > 0 { + list.reset(); + } + crate::rewritten::thread_table_counts(); + let mut state = p.state(); + list.defer_copy(x as *mut u8, full.as_ptr().cast(), 32); + let fresh = [p.pass(&list, &mut state, 0), p.pass(&list, &mut state, 0)]; + list.defer_copy(x as *mut u8, half.as_ptr().cast(), 32); + p.pass(&list, &mut state, 1); + p.pass(&list, &mut state, 1); + assert_eq!(fresh, [frame > 0; 2], "a snapshot from the second on"); + if frame > 0 { + // A slot of the first table, after its passes were recorded. + let raw: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + crate::descriptor::create_uav( + std::ptr::null(), + outs[2], + std::ptr::null(), + &raw, + p.title.start + 32, + ); + } + list.close(); + host.execute(&[&list]); + made.push(crate::rewritten::thread_table_counts()); + } + assert_eq!(made[0], [0; 3], "in place before the constants are known"); + assert_eq!( + made[1], + [2, 2 * 2 + 1, 2 * 2 * 32], + "two tables of two slots, one slot made again, their records read once each" + ); + } + + /// Constants a shader wrote earlier in the submission are on the GPU + /// only by the time their pass runs: a snapshot taken on the CPU before + /// the submission runs holds what the last submission left. A pass of + /// a list that declared such a write before it reads the constants in + /// place, whatever title copies do to them later in the submission, and + /// those copies make nothing known (`crate::rewritten`). + #[test] + fn a_pass_reads_constants_a_shader_wrote_before_it_in_place() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let p = ConstantPasses::new(2); + let (source_buffer, x_buffer, out_buffer) = (buffer(256), buffer(256), buffer(256)); + let (source, x, out) = ( + bytes_of(source_buffer), + bytes_of(x_buffer), + bytes_of(out_buffer), + ); + // Table 0: the writer (constants at `source`, into X). Table 1: the + // reader (constants at X, into `out`). + p.table(0, source, x_buffer); + p.table(1, x, out_buffer); + let list = host.new_list().unwrap(); + for frame in 0..4u32 { + if frame > 0 { + list.reset(); + } + let (written, copied) = (tagged(0x40 + frame), tagged(0x50 + frame)); + let mut state = p.state(); + list.defer_copy(source as *mut u8, written.as_ptr().cast(), 32); + p.pass(&list, &mut state, 0); + let fresh = p.pass(&list, &mut state, 1); + // The title rewrites X after the pass that read it. + list.defer_copy(x as *mut u8, copied.as_ptr().cast(), 32); + list.close(); + host.execute(&[&list]); + assert_eq!( + host_dwords(out), + written, + "what the shader wrote before the pass (frame {frame})" + ); + assert!(!fresh, "read in place (frame {frame})"); + assert!( + !crate::rewritten::known(x, 32), + "nothing made known (frame {frame})" + ); + } + } + + /// The same of constants that were known as rewritten under a pass + /// before a shader began to write them. A list that declares the write + /// itself takes no snapshot from that recording on. A write declared by + /// an earlier list of the submission shows when the snapshot is taken: + /// that one submission reads it, and the constants are read in place + /// from the next recording on. + #[test] + fn known_constants_a_shader_then_writes_are_read_in_place_again() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + if !crate::rewritten::enabled() { + return; // nothing is known + } + for other_list in [false, true] { + let p = ConstantPasses::new(3); + let (source_buffer, x_buffer) = (buffer(256), buffer(256)); + let outs = [buffer(256), buffer(256)]; + let (source, x) = (bytes_of(source_buffer), bytes_of(x_buffer)); + let [first, second] = outs.map(bytes_of); + p.table(0, x, outs[0]); + p.table(1, x, outs[1]); + // Table 2: the writer (constants at `source`, into X). + p.table(2, source, x_buffer); + let (list, earlier) = (host.new_list().unwrap(), host.new_list().unwrap()); + // The fault's shape twice: X is known, and its passes read + // snapshots. + for frame in 0..2u32 { + if frame > 0 { + list.reset(); + } + let (full, half) = (tagged(0x60 + frame), tagged(0x70 + frame)); + let mut state = p.state(); + list.defer_copy(x as *mut u8, full.as_ptr().cast(), 32); + let fresh = p.pass(&list, &mut state, 0); + list.defer_copy(x as *mut u8, half.as_ptr().cast(), 32); + p.pass(&list, &mut state, 1); + list.close(); + host.execute(&[&list]); + assert_eq!(fresh, frame > 0, "a snapshot from the second on"); + assert_eq!(host_dwords(first), if fresh { full } else { half }); + assert_eq!(host_dwords(second), half); + } + assert!(crate::rewritten::known(x, 32)); + // Now a shader writes X before the pass that reads it. + for frame in 0..3u32 { + list.reset(); + if other_list && frame > 0 { + earlier.reset(); + } + let (written, copied) = (tagged(0x80 + frame), tagged(0x90 + frame)); + let mut state = p.state(); + if other_list { + let mut state = p.state(); + earlier.defer_copy(source as *mut u8, written.as_ptr().cast(), 32); + p.pass(&earlier, &mut state, 2); + earlier.close(); + } else { + list.defer_copy(source as *mut u8, written.as_ptr().cast(), 32); + p.pass(&list, &mut state, 2); + } + let fresh = p.pass(&list, &mut state, 0); + list.defer_copy(x as *mut u8, copied.as_ptr().cast(), 32); + list.close(); + if other_list { + host.execute(&[&earlier, &list]); + } else { + host.execute(&[&list]); + } + // A list knows what its own shaders write as it is recorded; + // another list's is seen at the first such submission, whose + // pass still reads the snapshot recorded for it. + if other_list && frame == 0 { + assert!(fresh, "recorded with a snapshot"); + assert!( + !crate::rewritten::known(x, 32), + "seen: in place from here on" + ); + continue; + } + assert_eq!( + host_dwords(first), + written, + "what the shader wrote before the pass (frame {frame}, other list {other_list})" + ); + assert!( + !fresh, + "read in place (frame {frame}, other list {other_list})" + ); + } + } + } + + /// A title copy over the constants after a shader's declared write + /// makes them the title's again: it runs on the CPU, so a snapshot + /// taken after it holds what it left (on the console the copy is a + /// command between the shader's write and the pass). In place the + /// shader's write, which runs after every copy of the submission, is + /// what both passes read. + #[test] + fn constants_copied_in_after_a_shaders_write_get_their_snapshot() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let on = crate::rewritten::enabled(); + let p = ConstantPasses::new(3); + let (source_buffer, x_buffer) = (buffer(256), buffer(256)); + let outs = [buffer(256), buffer(256)]; + let (source, x) = (bytes_of(source_buffer), bytes_of(x_buffer)); + let [first, second] = outs.map(bytes_of); + p.table(0, x, outs[0]); + p.table(1, x, outs[1]); + // Table 2: the writer (constants at `source`, into X). + p.table(2, source, x_buffer); + let list = host.new_list().unwrap(); + for frame in 0..3u32 { + if frame > 0 { + list.reset(); + } + let (written, full, half) = ( + tagged(0xa0 + frame), + tagged(0xb0 + frame), + tagged(0xc0 + frame), + ); + let mut state = p.state(); + list.defer_copy(source as *mut u8, written.as_ptr().cast(), 32); + p.pass(&list, &mut state, 2); + list.defer_copy(x as *mut u8, full.as_ptr().cast(), 32); + let fresh = p.pass(&list, &mut state, 0); + list.defer_copy(x as *mut u8, half.as_ptr().cast(), 32); + p.pass(&list, &mut state, 1); + list.close(); + host.execute(&[&list]); + assert_eq!( + fresh, + on && frame > 0, + "a snapshot from the second on (frame {frame})" + ); + let (a, b) = if fresh { + (full, half) + } else { + (written, written) + }; + assert_eq!(host_dwords(first), a, "the first pass (frame {frame})"); + assert_eq!(host_dwords(second), b, "the second pass (frame {frame})"); + } + } + + /// The operation list describes the slots a pass's shaders read. For a + /// table made afresh those are dynamic slots, made when the pass was + /// recorded: it names them, with `snapshot` at the constants read from + /// one, and says nothing of the title's own slots, which the pass does + /// not read and nothing has made for it. + #[cfg(feature = "diagnostics")] + #[test] + fn the_operation_list_describes_the_slots_of_a_table_made_afresh() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + if !crate::rewritten::enabled() { + return; // no table is made afresh for a snapshot + } + let p = ConstantPasses::new(2); + let x = bytes_of(buffer(256)); + let outs = [buffer(256), buffer(256)]; + p.table(0, x, outs[0]); + p.table(1, x, outs[1]); + let list = host.new_list().unwrap(); + let (full, half) = (tagged(0xd0), tagged(0xd1)); + // The fault's shape twice: the first pass reads in place, then a + // snapshot through a table made afresh. + for frame in 0..2 { + if frame > 0 { + list.reset(); + } + let mut state = p.state(); + list.defer_copy(x as *mut u8, full.as_ptr().cast(), 32); + let fresh = p.pass(&list, &mut state, 0); + let made = state.fresh(0, 0); + let text = p + .entries + .each_ref() + .map(|u| state.table_read(u, true, made).unwrap()); + assert_eq!(fresh, frame > 0); + match made { + None => assert!( + text.iter().all(|t| t.ends_with(" slot made")), + "in place: {text:?}" + ), + Some(offset) => { + let first = offset / 32; + assert!( + text[0].ends_with(&format!(" snapshot fresh slot {first} made")), + "{text:?}" + ); + assert!( + text[1].ends_with(&format!(" fresh slot {} made", first + 1)), + "{text:?}" + ); + assert!(!text[1].contains("snapshot"), "{text:?}"); + // Described in place, as before the pipeline is bound. + let in_place = state.table_read(&p.entries[0], true, None).unwrap(); + assert!( + !in_place.contains("fresh") && !in_place.contains("snapshot"), + "{in_place}" + ); + } + } + list.defer_copy(x as *mut u8, half.as_ptr().cast(), 32); + p.pass(&list, &mut state, 1); + list.close(); + host.execute(&[&list]); + } + } + + /// As `CONSTANTS_OUT`, with the eight elements of the 16-bit buffer in + /// the same table at `u0` after the constants in the target (now in a + /// table of its own at `u1`): each as the shader reads it through an + /// unsigned view, two dwords an element. + const CONSTANTS_AND_HALVES_OUT: &str = r#" +ByteAddressBuffer constants : register(t0); +RWBuffer halves : register(u0); +RWByteAddressBuffer target : register(u1); +[numthreads(8, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + target.Store(id.x * 4, constants.Load(id.x * 4)); + uint4 h = halves[id.x] & 0xffff; + target.Store(32 + id.x * 8, h.x | h.y << 16); + target.Store(36 + id.x * 8, h.z | h.w << 16); +} +"#; + + /// Passes through one title table of two slots, 32 bytes of constants + /// and a buffer of eight `R16G16B16A16_FLOAT` elements that their shader + /// moves as integers (`CONSTANTS_AND_HALVES_OUT`): a table with a view + /// to show as its unsigned twin (#407) and constants a title copy may + /// rewrite under a pass (`crate::rewritten`). The targets are in the + /// heap's slots from 2 on. + struct HalfPasses { + heap: This, + title: &'static crate::descriptor::Heap, + host_heap: &'static crate::descriptor::host::HostHeap, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + entries: [UsedResource; 2], + } + + impl HalfPasses { + /// The descriptor the shader moves halves through: dword 8 of the + /// table in root parameter 0 (`HostShader::half_views`). + const MOVED: [(u8, u32); 1] = [(0, 8)]; + + fn new(constants: u64, halves: This, targets: &[This]) -> Self { + let (heap, title, host_heap) = view_heap(2 + targets.len() as u32); + let tables = [ + Param::Table(&[srv(0, 1), uav(0, 1)]), + Param::Table(&[uav(1, 1)]), + ]; + let (root, pso) = compile_cs(CONSTANTS_AND_HALVES_OUT, &tables); + let null = std::ptr::null(); + crate::descriptor::create_cbv( + null, + &[constants as u32, (constants >> 32) as u32, 32, 0], + title.start, + ); + let raw: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0]; + for (slot, target) in targets.iter().enumerate() { + crate::descriptor::create_uav( + null, + *target, + null, + &raw, + title.start + 32 * (slot as u64 + 2), + ); + } + let moved = UsedResource { + table_offset_dwords: 8, + ..used(ResourceType::Uav) + }; + let p = HalfPasses { + heap, + title, + host_heap, + root, + pso, + entries: [used(ResourceType::Cbv), moved], + }; + p.view_halves(halves); + p + } + + /// The title's view at the table's second slot: eight + /// `R16G16B16A16_FLOAT` elements of `buffer`. + fn view_halves(&self, buffer: This) { + let float: [u32; 10] = [10, 1, 0, 0, 8, 0, 0, 0, 0, 0]; + crate::descriptor::create_uav( + std::ptr::null(), + buffer, + std::ptr::null(), + &float, + self.title.start + 32, + ); + } + + fn state(&self) -> State { + let mut state = State::default(); + state.set_heaps(&[self.heap]); + state.set_table(true, 0, self.title.start); + state + } + + /// Records a pass into target `target`; returns the heap slot of + /// the table made afresh for it, which there is always: one. + fn pass(&self, list: &HostList, state: &mut State, target: u32) -> u32 { + let made = state.tables(list, &self.entries, &[], true, &Self::MOVED, true); + let [(0, offset)] = made[..] else { + panic!("one table made afresh for the root parameter, not {made:?}"); + }; + // SAFETY: an open list and live objects of ours. + unsafe { + list.list + .SetDescriptorHeaps(&[Some(self.host_heap.heap.clone())]); + list.list.SetComputeRootSignature(&self.root); + list.list + .SetComputeRootDescriptorTable(0, self.host_heap.gpu(offset / 32)); + list.list + .SetComputeRootDescriptorTable(1, self.host_heap.gpu(2 + target)); + list.list.SetPipelineState(&self.pso); + list.list.Dispatch(1, 1, 1); + } + offset / 32 + } + + /// What a pass left in the target at `at`: the constants it read, + /// and the sixteen dwords of the 16-bit buffer as it read them. + fn out(at: u64) -> ([u32; 8], [u32; 16]) { + let all = crate::shadow::find(at, 256) + .expect("a target's host copy") + .read_host(at, 24); + (all[..8].try_into().unwrap(), all[8..].try_into().unwrap()) + } + } + + /// Thirty-two 16-bit patterns of every kind of half (NaNs with + /// payloads, an infinity, a negative zero, denormals, ordinary values), + /// none of which a conversion to a float and back to an integer leaves + /// as it is, as the sixteen dwords they lie in. + fn half_bits(tag: u16) -> [u32; 16] { + const BITS: [u16; 8] = [ + 0x7c01, 0xfc00, 0x8000, 0x0001, 0xffff, 0x3c00, 0x7bff, 0x03ff, + ]; + let half = |k: usize| u32::from(BITS[k % 8] ^ (k as u16 / 8) << 4 ^ tag); + std::array::from_fn(|k| half(2 * k) | half(2 * k + 1) << 16) + } + + /// A table that holds a 16-bit view its shader moves as integers and + /// constants a title copy rewrites under a pass is made afresh once for + /// both: the shader reads every 16-bit pattern as it is, through the + /// unsigned twin, and its constants as they were where its pass was + /// recorded, from a snapshot. The passes between two title copies share + /// one such table, the passes after a copy have another, and a shader + /// that reads the same slots in the title's formats is given neither. + /// Before the constants are known, and with snapshots off, the one + /// table of the twin serves every pass. + #[test] + fn a_table_with_a_twin_and_a_snapshot_is_made_afresh_once_with_both() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let on = crate::rewritten::enabled(); + let (constants, halves) = (bytes_of(buffer(256)), buffer(256)); + let targets = [buffer(256), buffer(256), buffer(256)]; + let [first, second, third] = targets.map(bytes_of); + let p = HalfPasses::new(constants, halves, &targets); + let bits = half_bits(0); + let list = host.new_list().unwrap(); + // The title's frame, recorded and submitted three times: full-size + // constants, a pass, half-size constants, two passes. From the + // second on the constants are known and read from snapshots. + for frame in 0..3u32 { + if frame > 0 { + list.reset(); + } + let (full, half) = (tagged(0xe0 + frame), tagged(0xf0 + frame)); + let mut state = p.state(); + list.defer_copy(bytes_of(halves) as *mut u8, bits.as_ptr().cast(), 64); + list.defer_copy(constants as *mut u8, full.as_ptr().cast(), 32); + let a = p.pass(&list, &mut state, 0); + // The operation list describes the slots the pass reads. + #[cfg(feature = "diagnostics")] + { + let text = p + .entries + .each_ref() + .map(|u| state.table_read(u, true, Some(a * 32)).unwrap()); + let snapshot = if on && frame > 0 { " snapshot" } else { "" }; + assert!( + text[0].ends_with(&format!("{snapshot} fresh slot {a} made")), + "{text:?}" + ); + assert_eq!(text[0].contains("snapshot"), on && frame > 0, "{text:?}"); + assert!( + text[1].ends_with(&format!(" unsigned twin fresh slot {} made", a + 1)), + "{text:?}" + ); + assert!( + !text[0].contains("twin") && !text[1].contains("snapshot"), + "{text:?}" + ); + } + list.defer_copy(constants as *mut u8, half.as_ptr().cast(), 32); + let b = p.pass(&list, &mut state, 1); + let c = p.pass(&list, &mut state, 2); + // A shader that reads the two slots in the title's formats. + let plain = state.tables(&list, &p.entries, &[], true, &[], true); + list.close(); + host.execute(&[&list]); + for target in [first, second, third] { + assert_eq!( + HalfPasses::out(target).1, + bits, + "every 16-bit pattern as it is (frame {frame})" + ); + } + assert_eq!(b, c, "one table between two copies (frame {frame})"); + assert!( + plain + .iter() + .all(|&(_, offset)| ![a, b].contains(&(offset / 32))), + "not a table with a twin" + ); + if frame == 0 || !on { + // The submission that shows the range, and every one with + // snapshots off: the twin's table serves the three passes. + // (What constants they read is not this test's: no snapshot + // is taken.) + assert_eq!(a, b, "one table for the twin alone (frame {frame})"); + assert!( + plain.is_empty(), + "in place for the title's formats (frame {frame})" + ); + continue; + } + assert_ne!( + a, b, + "a table of its own on each side of the copy (frame {frame})" + ); + assert_eq!( + HalfPasses::out(first).0, + full, + "what the buffer held at the first pass (frame {frame})" + ); + assert_eq!( + HalfPasses::out(second).0, + half, + "after the last copy (frame {frame})" + ); + assert_eq!( + HalfPasses::out(third).0, + half, + "after the last copy (frame {frame})" + ); + assert_eq!( + plain.len(), + 1, + "the snapshot alone for the title's formats (frame {frame})" + ); + } + } + + /// Such a table follows the slots the title rewrites after its pass was + /// recorded, as a table made afresh for a snapshot alone does, and the + /// slot its shader moves halves through is made again as it was made: + /// the unsigned twin of the 16-bit view the title has there by then. + /// The constants' slot was not rewritten and keeps its snapshot. + #[test] + fn a_table_with_a_twin_and_a_snapshot_follows_a_slot_rewritten_before_submission() { + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + if !crate::rewritten::enabled() { + return; // a table made afresh for a twin alone stays as recorded + } + let (constants, halves, later) = (bytes_of(buffer(256)), buffer(256), buffer(256)); + let targets = [buffer(256), buffer(256)]; + let [first, second] = targets.map(bytes_of); + let p = HalfPasses::new(constants, halves, &targets); + let (bits, later_bits) = (half_bits(0x0100), half_bits(0x0200)); + let list = host.new_list().unwrap(); + // The fault's shape twice: from the second on the passes read + // snapshots, each side of the copy through a table of its own. + for frame in 0..2u32 { + if frame > 0 { + list.reset(); + } + let (full, half) = (tagged(0x100 + frame), tagged(0x110 + frame)); + let mut state = p.state(); + p.view_halves(halves); + list.defer_copy(bytes_of(halves) as *mut u8, bits.as_ptr().cast(), 64); + list.defer_copy(bytes_of(later) as *mut u8, later_bits.as_ptr().cast(), 64); + list.defer_copy(constants as *mut u8, full.as_ptr().cast(), 32); + let a = p.pass(&list, &mut state, 0); + list.defer_copy(constants as *mut u8, half.as_ptr().cast(), 32); + let b = p.pass(&list, &mut state, 1); + assert_eq!( + a != b, + frame > 0, + "snapshots from the second on (frame {frame})" + ); + if frame > 0 { + // Both passes were recorded with `halves` in this slot. + p.view_halves(later); + } + list.close(); + host.execute(&[&list]); + let read = if frame > 0 { later_bits } else { bits }; + assert_eq!( + HalfPasses::out(first).1, + read, + "the view the slot holds at submission, as its twin (frame {frame})" + ); + assert_eq!( + HalfPasses::out(second).1, + read, + "the view the slot holds at submission, as its twin (frame {frame})" + ); + if frame > 0 { + assert_eq!( + HalfPasses::out(first).0, + full, + "the first pass's snapshot (frame {frame})" + ); + assert_eq!( + HalfPasses::out(second).0, + half, + "the second pass's snapshot (frame {frame})" + ); + } + } + } + /// Slots of a shader-visible view heap of ours. struct Slots(ID3D12DescriptorHeap, u32); diff --git a/crates/victory-gpu/src/hold.rs b/crates/victory-gpu/src/hold.rs index 098bcda0c..b7ac4ed96 100644 --- a/crates/victory-gpu/src/hold.rs +++ b/crates/victory-gpu/src/hold.rs @@ -78,7 +78,8 @@ impl ValueWait { pub(crate) struct BatchFlags { /// Writes into title CPU memory during deferred prep (`Step::Copy`, `Step::Move`). pub(crate) has_title_copy: bool, - /// Reads CPU title memory during deferred prep (`Step::Copy`, `Step::Move`, `Step::Fill`). + /// Reads CPU title memory during deferred prep (`Step::Copy`, `Step::Move`, `Step::Fill`, + /// `Step::Snapshot`). pub(crate) has_cpu_read: bool, /// Records GPU shader writes to a shadow buffer (`Step::GpuWrite`). pub(crate) has_gpu_write: bool, diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b0c31942c..4d70cd2a4 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1701,6 +1701,71 @@ pub(crate) mod tests { host.execute_with_barriers(&[&producer, &consumer], &[false, true]); assert_eq!(word, 9); } + + /// A list holding a snapshot of constants (`crate::rewritten`) reads + /// title memory when its steps run, as one holding a fill does: where + /// held pieces are joined (#419) it does not follow, across a wait, a + /// segment whose shaders write, whose writes are in title memory only + /// once that segment has run. A list that reads its constants in place, + /// or whose table follows the title's slots, holds no such copy. + #[test] + fn a_list_with_a_snapshot_of_constants_joins_no_piece_after_a_shaders_writes() { + use crate::hold::{BatchFlags, can_join_batch}; + let Some(host) = host() else { return }; + let (Ok(writer), Ok(in_place), Ok(snapshot)) = + (host.new_list(), host.new_list(), host.new_list()) + else { + return; + }; + let p = crate::watch::tests::pool(1); + crate::shadow::register(p, p as u64, crate::watch::PAGE as u64); + let shadow = crate::shadow::find(p as u64, crate::watch::PAGE as u64).expect("shadow"); + + writer.defer_gpu_write(&shadow, p, 256, false); + let wrote = writer.batch_flags(); + assert_eq!( + wrote, + BatchFlags { + has_gpu_write: true, + ..Default::default() + } + ); + + in_place.defer_constant(p, 32); + in_place.defer_table(|_| {}); + assert_eq!(in_place.deferred_steps(), 2); + assert_eq!( + in_place.batch_flags(), + BatchFlags::default(), + "no copy of title memory" + ); + assert!(can_join_batch(wrote, in_place.batch_flags(), 1, 64)); + + assert!( + snapshot.snapshot(p as u64, 32).is_some(), + "scratch for a snapshot" + ); + let read = snapshot.batch_flags(); + assert_eq!( + read, + BatchFlags { + has_cpu_read: true, + ..Default::default() + }, + "as a fill" + ); + assert!( + !can_join_batch(wrote, read, 1, 64), + "not after a shader's writes" + ); + assert!(can_join_batch(read, wrote, 1, 64), "a writer may follow it"); + assert!(can_join_batch(in_place.batch_flags(), read, 1, 64)); + + for list in [&writer, &in_place, &snapshot] { + list.close(); + } + crate::shadow::unregister(p, p as u64); + } } /// Monotonic command-list mutation epoch shared across all [`HostList`]s so @@ -2348,12 +2413,26 @@ enum Step { Move(usize, usize, usize), /// A copy of title memory into the list's own upload memory. Fill(usize, usize, usize), + /// As `Fill`, of constants a view in a table reads in place of its + /// buffer's host copy, which a later copy of the submission rewrites + /// (`crate::rewritten`). + Snapshot(usize, usize, usize), + /// A constant view in a table reads a range (address, bytes) in its + /// buffer's host copy: a title copy into it later in the submission + /// reaches its pass (`crate::rewritten`). + Constant(usize, usize), /// Brings a range (address, bytes) of a buffer's host copy up to date: /// once per submission, whichever lists ask, until a copy into it. Refresh(std::sync::Arc, usize, usize), /// Brings the current buffer view of a table slot up to date: the title /// may have rewritten the slot since the draw was recorded. Slot(std::sync::Arc, u32), + /// The same of a table made afresh for a snapshot, whose slots are + /// made when its pass is recorded: those the title rewrote since are + /// made again (`crate::draw`, `remake_table`), and the buffer ranges + /// their views read, which it names through its argument (host copy, + /// address, bytes), brought up to date. + Table(Remake), /// Work that writes host memory only. Host(Box), /// Shaders write a range (address, bytes) of a buffer's host copy; @@ -2373,6 +2452,10 @@ enum Step { Memory(usize), } +/// What a [`Step::Table`] runs. +type Remake = + Box, usize, usize)) + Send>; + /// What a list does on the CPU when it is submitted: copies between host /// memory regions (title buffers, upload buffers and buffer copies), and /// the upload buffers its GPU commands read, kept until the list is reset. @@ -2392,6 +2475,14 @@ struct Deferred { /// Unaligned root-CBV scratch copies (`(source, bytes)` → host GPU address) /// valid until the next title copy or list reset. filled_scratch: std::collections::HashMap<(usize, usize), u64>, + /// Snapshots of constants for views in tables (`(source, bytes)` → the + /// scratch buffer and the offset in it), valid as `filled_scratch` is. + snapshots: std::collections::HashMap<(usize, usize), (ID3D12Resource, u64)>, + /// The title memory the list's shaders were declared to write so far + /// (`Step::GpuWrite`) and no title copy of the list has written since, + /// kept while constants get snapshots: none is taken of bytes among + /// these (`crate::rewritten`). + written: crate::ranges::Ranges, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize)>, @@ -4646,10 +4737,16 @@ impl HostList { fn defer_title_copy(&self, step: Step) { let mut deferred = self.deferred(); + // What the copy writes is the title's again, whatever the list's + // shaders were declared to write there before it. + if let Step::Copy(dst, _, len) | Step::Move(dst, _, len) = step { + deferred.written.remove(dst, dst.saturating_add(len)); + } deferred.copies.push(step); deferred.refreshed.clear(); deferred.slots.clear(); deferred.filled_scratch.clear(); + deferred.snapshots.clear(); self.changed_deferred(); } @@ -4677,22 +4774,51 @@ impl HostList { Some(gpu) } + /// Scratch memory holding `len` bytes of title memory from `src` as of + /// this place among the list's steps at submission, for a constant view + /// in a table (`crate::rewritten`): the buffer and the offset in it, + /// reused by later passes until a title copy or list reset. + pub(crate) fn snapshot(&self, src: u64, len: u64) -> Option<(ID3D12Resource, u64)> { + let key = (src as usize, len as usize); + if let Some((buffer, at)) = self.deferred().snapshots.get(&key) { + return Some((buffer.clone(), *at)); + } + let (buffer, at, _, to) = self.scratch_in(len, 256)?; + let mut deferred = self.deferred(); + deferred + .copies + .push(Step::Snapshot(to as usize, src as usize, len as usize)); + deferred.snapshots.insert(key, (buffer.clone(), at)); + crate::rewritten::snapshot_taken(len); + Some((buffer, at)) + } + + /// A constant view in a table reads `[address, address + len)` in its + /// buffer's host copy from this place among the list's steps on + /// (`crate::rewritten`). + pub(crate) fn defer_constant(&self, address: usize, len: usize) { + self.deferred().copies.push(Step::Constant(address, len)); + } + /// Brings `[address, address + len)` of a buffer's host copy up to date /// when the list is submitted (once per range until a title copy - /// intervenes), keeping the copy alive until the list is reset. + /// intervenes), keeping the copy alive until the list is reset. Whether + /// the list had not asked for the range since its last title copy. pub(crate) fn defer_refresh( &self, shadow: &std::sync::Arc, address: usize, len: usize, - ) { + ) -> bool { let mut deferred = self.deferred(); let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); - if deferred.refreshed.insert(key) { + let asked = deferred.refreshed.insert(key); + if asked { deferred .copies .push(Step::Refresh(shadow.clone(), address, len)); } + asked } /// Brings the buffer range of the view currently in `index` up to date @@ -4709,6 +4835,19 @@ impl HostList { } } + /// Runs `remake` when the list is submitted, at this place among its + /// steps: it makes again the slots of a table made afresh that the title + /// rewrote since the list recorded them, and gives its argument the + /// buffer ranges their views read, to be brought up to date. + pub(crate) fn defer_table( + &self, + remake: impl Fn(&mut dyn FnMut(&std::sync::Arc, usize, usize)) + + Send + + 'static, + ) { + self.deferred().copies.push(Step::Table(Box::new(remake))); + } + /// Shaders of the list write `[address, address + len)` of a buffer's /// host copy: copied back into title memory once the list has run /// (`marked`: the pages they mark). @@ -4726,6 +4865,11 @@ impl HostList { deferred .copies .push(Step::GpuWrite(shadow.clone(), address, len, marked, memory)); + if crate::rewritten::enabled() { + deferred + .written + .insert(address, address.saturating_add(len), 0); + } } self.clamps .lock() @@ -4740,6 +4884,15 @@ impl HostList { self.deferred().marks = true; } + /// Whether the list declared, so far, that its shaders write a byte of + /// `[address, address + len)`, with no title copy into that byte since: + /// a snapshot of constants there, taken before the GPU runs, would miss + /// what they wrote (`crate::rewritten`). + pub(crate) fn shader_wrote(&self, address: u64, len: u64) -> bool { + let (from, to) = (address as usize, address.saturating_add(len) as usize); + self.deferred().written.overlaps(from, to) + } + /// Notes that an earlier command in this list may write arbitrary title /// buffers on the GPU (bindless heap UAVs or page-table memory writes). pub(crate) fn note_unknown_gpu_write(&self) { @@ -5080,14 +5233,22 @@ impl HostList { flags.has_title_copy = true; flags.has_cpu_read = true; } - Step::Fill(..) => flags.has_cpu_read = true, + // A snapshot of constants is title memory read when the + // list's steps run, as a fill is: what a shader of a segment + // before it in the piece writes there is not in it. + Step::Fill(..) | Step::Snapshot(..) => flags.has_cpu_read = true, Step::GpuWrite(..) => flags.has_gpu_write = true, Step::Texture(..) => flags.has_textures = true, + // `Constant` notes a read of a host copy, and `Table` makes + // slots from the title's records and asks for refreshes as + // `Slot` does: neither holds title memory as it was. Step::Refresh(..) | Step::Slot(..) | Step::Host(_) | Step::Heap(_) - | Step::Memory(_) => {} + | Step::Memory(_) + | Step::Constant(..) + | Step::Table(_) => {} } } flags @@ -5330,20 +5491,24 @@ impl HostList { fn run_deferred(&self, batch: &mut Batch) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; + batch.constants.next_list(); for step in &self.deferred().copies { #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); // The preparing report counts the copies' time only (the other // steps `continue` before it): they read no clock without // diagnostics. - let copy_started = matches!(step, Step::Copy(..) | Step::Move(..) | Step::Fill(..)) - .then(std::time::Instant::now); + let copy_started = matches!( + step, + Step::Copy(..) | Step::Move(..) | Step::Fill(..) | Step::Snapshot(..) + ) + .then(std::time::Instant::now); // The list-steps line: every step counted, all but the many // refreshes and slots timed. let step_kind = match step { - Step::Copy(..) | Step::Move(..) | Step::Fill(..) => 0, - Step::Refresh(..) => 1, - Step::Slot(..) => 2, + Step::Copy(..) | Step::Move(..) | Step::Fill(..) | Step::Snapshot(..) => 0, + Step::Refresh(..) | Step::Constant(..) => 1, + Step::Slot(..) | Step::Table(..) => 2, Step::Host(_) => 3, Step::GpuWrite(..) => 4, Step::Texture(..) => 5, @@ -5355,8 +5520,12 @@ impl HostList { let _timed = crate::watch::Timed( started, match step { - Step::Refresh(..) | Step::Slot(..) => C::StepRefreshUs, - Step::Copy(..) | Step::Move(..) | Step::Fill(..) => C::StepCopyUs, + Step::Refresh(..) | Step::Slot(..) | Step::Table(..) | Step::Constant(..) => { + C::StepRefreshUs + } + Step::Copy(..) | Step::Move(..) | Step::Fill(..) | Step::Snapshot(..) => { + C::StepCopyUs + } Step::Host(_) => C::StepWorkUs, Step::GpuWrite(..) => C::StepGpuWriteUs, Step::Texture(..) => C::StepTextureUs, @@ -5381,6 +5550,9 @@ impl HostList { add(C::CopyBytes, len as u64); } batch.title_copied(dst, len); + // The passes before it that read these bytes as + // constants run after it all the same. + crate::rewritten::copied(&mut batch.constants, dst, len); if matches!(step, Step::Move(..)) { move_mapped(dst as *mut u8, src as *const u8, len); } else { @@ -5397,7 +5569,7 @@ impl HostList { } len } - &Step::Fill(dst, src, len) => { + &Step::Fill(dst, src, len) | &Step::Snapshot(dst, src, len) => { #[cfg(feature = "diagnostics")] { add(C::Copies, 1); @@ -5405,8 +5577,15 @@ impl HostList { } flight::before_cpu_read(Some((src, len))); copy_mapped(dst as *mut u8, src as *const u8, len, false); + if matches!(step, Step::Snapshot(..)) { + crate::rewritten::read(&mut batch.constants, src, len, true); + } len } + &Step::Constant(address, len) => { + crate::rewritten::read(&mut batch.constants, address, len, false); + continue; + } Step::Refresh(shadow, address, len) => { #[cfg(feature = "diagnostics")] { @@ -5422,6 +5601,10 @@ impl HostList { } continue; } + Step::Table(remake) => { + remake(&mut |s, a, l| batch.add(s, a, l)); + continue; + } Step::Host(work) => { flight::before_cpu_read(None); work(); @@ -5444,6 +5627,11 @@ impl HostList { batch.flush(); } shadow.writing(*address, *len, *marked); + // Constants among these bytes are the shaders' from + // here on, which no snapshot holds. + if crate::rewritten::enabled() { + batch.constants.shader_writes(*address, *len); + } continue; } // Brought up to date before the submission's lists were made. @@ -5666,6 +5854,9 @@ struct Batch { /// Table slots (`(viewed_ptr, index)`) already asked since the last /// title write or copy ([`slot_once`]). slots_seen: SlotSet, + /// The constant ranges the submission's passes read through tables so + /// far: a title copy into one reaches passes recorded before it. + constants: crate::rewritten::Reads, } /// How far apart a copy's pending ranges may be and still be done as one, @@ -5723,6 +5914,7 @@ impl Batch { heaps_seen: buffers.heaps_seen, memories_seen: buffers.memories_seen, slots_seen: buffers.slots_seen, + constants: Default::default(), } } @@ -6764,6 +6956,7 @@ impl Meter { tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); self.frames += 1; crate::memory::log_frame(); + crate::rewritten::frame(); #[cfg(feature = "diagnostics")] crate::watch::frame_done(); let next = FrameWindow { @@ -6924,6 +7117,24 @@ impl Meter { if same_copy::mode() == same_copy::Mode::Skip { ", left out" } else { "" }, ); } + let c = crate::rewritten::take(); + if c.late + c.snapshots + c.left + c.after_shader + c.tables > 0 { + tracing::info!( + "constants a title copy rewrites under a pass: {:.1} snapshots/frame ({:.2} KB/frame), \ + {:.1} tables/frame made afresh for them ({:.0} host views/frame made in their slots, \ + {:.2} KB/frame of their records read at submission), \ + {:.1} reads/frame ran with a later copy's bytes; where a shader's write was declared \ + over them before the pass, {:.1} reads/frame left in place and {:.1} snapshots/frame taken", + c.snapshots as f64 / report_frames, + c.bytes as f64 / report_frames / 1e3, + c.tables as f64 / report_frames, + c.views as f64 / report_frames, + c.record_bytes as f64 / report_frames / 1e3, + c.late as f64 / report_frames, + c.left as f64 / report_frames, + c.after_shader as f64 / report_frames, + ); + } #[cfg(feature = "diagnostics")] { if let Some([(local, budget), (system, system_budget)]) = video_memory() { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index fa822a21e..8b2a0e1c1 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -62,8 +62,6 @@ pub mod fence; pub mod frame; // Plain std, so its tests run everywhere. #[cfg(any(windows, test))] -// Used by the draws from a later commit. -#[allow(dead_code)] mod fresh; #[cfg(windows)] mod heap_worker; @@ -104,8 +102,6 @@ pub mod replay; pub mod resource; // Plain std, so its tests run everywhere. #[cfg(any(windows, test))] -// Used by the submission from a later commit. -#[allow(dead_code)] mod rewritten; pub mod root; #[cfg(windows)] diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index c902ea886..5a4cdc77b 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -569,11 +569,12 @@ impl Shadow { } /// Brings `len` bytes at `address` up to date when `list` is submitted, - /// and keeps the copy alive until the list is reset. - pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) { + /// and keeps the copy alive until the list is reset. Whether the list + /// had not asked for them since its last title copy. + pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) -> bool { self.touch(); let len = len.min(self.start + self.len - address); - list.defer_refresh(self, address as usize, len as usize); + list.defer_refresh(self, address as usize, len as usize) } /// A view or a list asks for the copy in this frame. The refresh of From 0dd6730618c58dbb16eb812ba76f333744efa7e7 Mon Sep 17 00:00:00 2001 From: uncaney <190490737+uncaney@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:07:19 +0100 Subject: [PATCH 5/5] docs: describe the snapshots of constants and the join rule in docs/macos.md Says what a pass reading constants a later copy of its submission rewrites looked like, what the layer does about it now, what it costs, and the two switches: VICTORY_SNAPSHOT_CONSTANTS=0 and VICTORY_COALESCE_PIECES=0. Co-Authored-By: Claude Fable 5.2 --- docs/macos.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/macos.md b/docs/macos.md index 31352cd6f..d0f563c71 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -331,6 +331,22 @@ tools/macos/bench-ab.sh --exe --a "VICTORY_TWIN_UAV_READS=0" - It ends with `cargo xtask bench-compare `: each run's median frame time, each side's median, B - A, and a bootstrap 95 % interval of it. An interval that holds 0 means those runs cannot tell A from B; add runs. Reports and logs are in `target/bench/`. +## Constants a title copy rewrites between two passes + +A list's buffer copies run on the CPU when the list is submitted, in recorded order with the refreshes of host copies, and all of them before the GPU runs the first command of the submission. A buffer the title copies new values into between two passes of one submission so held, for both passes, what the last copy left; on the console the copy is a command and runs between them. A title that keeps one small constant buffer with a picture size for a group of compute passes, and copies the full size into it before the full-size passes and half of it before the half-size ones, so had its full-size passes read the half size: their targets were drawn in one quarter. + +A constant view in a table now reads a snapshot of its bytes, taken at its place among the list's steps, once a title copy has rewritten those bytes after a pass of the same submission read them: its table is made afresh in dynamic slots, with the constant view on the list's scratch memory (`victory-gpu/src/rewritten.rs`). The slots of such a table are made when its pass is recorded, and those the title rewrites between then and the submission are made again from its records when the list is submitted, as its slots in place would show them (`a_table_made_afresh_for_a_snapshot_follows_a_slot_rewritten_before_submission`). Which constants need this is learnt from the submissions themselves, so the first submission that shows a range is not helped, and a range that stops showing is forgotten 64 to 128 frames later. The log says `a title copy rewrites constants a pass of the same submission read through a table` once, and a frame-rate report with any to count is followed by `constants a title copy rewrites under a pass:` with the snapshots per frame, the tables made afresh for them per frame with the host views made in their slots (one per slot when a pass is recorded, and one per slot the title rewrote before submission) and the bytes of their records read at submission, the reads that still ran with a later copy's bytes and the two counts of the next paragraph. A list makes one such table for all its passes through a title table that read the same snapshot (`the_tables_made_afresh_for_snapshots_are_counted_with_their_views_and_records`); each list of a submission makes its own, as its snapshot is its own. `VICTORY_SNAPSHOT_CONSTANTS=0` turns all of it off. In a diagnostics build the command list of a listed frame (`VICTORY_D3D12_DRED=1`) describes such a pass by the slots its shader reads: `u= [heap N: table made afresh, the title's at M]` for the table, and for each entry `fresh slot N made` (or `null` where the host could not make the view), after `snapshot` at the constants read from one. `slot made`, `slot null` and `slot stale` are said of tables in place only, whose slots are the title's own. `a_pass_reads_its_constants_as_they_were_before_a_later_copy_of_its_submission` runs such passes on the GPU, once with the constants in a buffer with a host copy and once in memory on a host buffer's pages: without the snapshot the earlier pass reads the later values in both. + +A table may need this and a 16-bit view shown as its unsigned twin at once: a shader that moves the 16-bit channels of a float or signed buffer view as integers is shown that view in the unsigned format of the same layout, in a table made afresh as well (#407). Such a table is made afresh once and holds both, its constants on their snapshot and the 16-bit view in its unsigned format. The tables made within a list are told apart by both (`victory-gpu/src/fresh.rs`): the passes between two title copies share one, the passes after a copy have another, and a shader that reads the same slots in the title's formats is given neither. Its slots follow the title's records at submission like those of a table made for a snapshot alone, a rewritten 16-bit view being made again as its twin; a table made afresh for a twin alone stays as recorded, as it did before snapshots. With no dynamic slots left its draw is dropped, as that of a table with a twin alone, where a table wanted afresh only for a snapshot is read in place. The command list of a diagnostics build says `unsigned twin` at such an entry. `a_table_with_a_twin_and_a_snapshot_is_made_afresh_once_with_both` and `a_table_with_a_twin_and_a_snapshot_follows_a_slot_rewritten_before_submission` run such passes on the GPU: without the twin the shader reads converted values on D3DMetal 3.0, not the 16-bit patterns. + +A snapshot is taken on the CPU before the GPU runs the submission, so it cannot hold what a shader of the same submission wrote into the constants before their pass. Where a write by a shader is declared over any byte of a constant view before the pass that reads it (an unordered buffer view in a table, for its whole range; a root view, for 1 MiB from its address), the pass reads the constants in place as it did before snapshots. A list knows this of its own passes as it records them. A write declared by an earlier list of the same submission is seen when the submission's steps run: the constants are then read in place from the next recording on, for as long as submissions show such a write (and 64 to 128 frames more), and the one snapshot a pass had already been given is counted (`snapshots/frame taken` in the line above, with a warning the first time). The declared range is the view's, so the shader may not write the constants at all; a later copy then reaches the pass as it did before snapshots, and that is counted when the copy comes (`reads/frame left in place`). A write through a view the shader takes from the heap at an index it computes declares no range and is not seen. `a_pass_reads_constants_a_shader_wrote_before_it_in_place` and `known_constants_a_shader_then_writes_are_read_in_place_again` run these cases on the GPU. + +A submission, in all of this, is the host's: the lists given to the host GPU in one call. Since #419 that can be more than one of the title's: ready pieces of several queues, and pieces that waited for a value an earlier one writes at its end, are joined into one (`VICTORY_COALESCE_PIECES`, on unless `0`). A copy the title submitted later, or on another queue, then runs before a pass it submitted earlier; it is learnt, and the pass given a snapshot, like a copy of the pass's own list. What is joined depends on what is ready at the time, so a range can show in some frames only, and `reads/frame ran with a later copy's bytes` can then be above zero now and then. A list holding a snapshot reads title memory when it is prepared, as a list with an unaligned root constant view does, and is not joined behind a piece whose shaders write buffers, across queues, across a wait (one the piece holds, or one that holds already), or behind a Signal of its own queue: their writes reach title memory only once that piece has run (`a_list_with_a_snapshot_of_constants_joins_no_piece_after_a_shaders_writes`). These are the places where the pump of before #419 ran the work before first, and there the join is asked of the whole run of the queue that pump ran as one piece, not of its first list alone: a later list of the run is asked too, and the run joins whole or starts the next piece whole, so nothing that pump ran together is split (`a_run_the_per_queue_pump_kept_together_joins_whole_or_starts_the_next_piece_whole`, `a_later_list_of_a_queue_behind_a_wait_that_holds_is_not_joined_behind_a_shaders_writes`, `a_later_list_waiting_on_a_deferred_signal_is_not_joined_behind_a_shaders_writes`, `a_later_submissions_lists_behind_a_signal_each_ask_the_join`, and the same of the submission worker's pump, #447); upstream's own lists that copy or fill are kept so too. Such a run starts a piece of its own, which the line `held work this frame` counts in `hazard_splits`; each such split stands where the pump of before #419 made one, so a frame gets no more pieces than that pump gave it. The lists of one queue with neither a Signal nor a wait between them are taken together with no question, as before, and a snapshot there is caught as the paragraph before this one says, by the write an earlier list of the submission declared. With `VICTORY_COALESCE_PIECES=0` under `VICTORY_FLIGHT1` or `VICTORY_ASYNC_SUBMIT`, the submission worker's batches of one queue take a list whose wait holds with the lists before it (#447), and a snapshot there is caught the same way. + +The memo of table entries (`VICTORY_TABLE_MEMO`, #462) does not change which passes get a snapshot: that is asked for every pass before any entry is looked up, and a title copy ends a list's snapshots and what the list remembered together (`a_remembered_table_entry_does_not_stand_for_a_snapshot`). + +Root constant views aligned to 256 bytes, root shader resource views, other buffer views in tables and vertex and index buffers still read what the submission's last copy left. + ## Optional switches for slow storage, low memory and speed None of these changes the default, except `VICTORY_OUTPUT`, which sets the title's output size on a Mac (see above). Each is read from the environment when the game starts, and all of them are tools for testers, so please post what you see on #131 or #135 when you try one.