Explorar o código

Parts of submissions prepared as one (VICTORY_JOIN_PARTS=8; off), fills cut free of copies at their place (VICTORY_PLACED_ORDER)

The thread that runs the line takes the Run entries that follow in the queue along, with
the waits they meet themselves and the signals between them (the idea: fxceless/victory-fork
39731795), as long as nothing of them reads on the CPU what those before them write; what
they refresh is brought up to date in one go in front (VICTORY_REFRESH_FRONT on its own:
measured at nothing); each part still goes to the queue in a call of its own.
Run submit-1, the dorm: 12 of 28 parts joined, 54.8 -> 51.4 ms a frame of that thread.

A copy at its place in a list is in the way of fills done on the card only from its place
on, and the submission is cut behind its list for those (opening, run n19: 40-60 ms a frame
of the submitting thread standing). Not seen in the dorm; not measured yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local hai 1 día
pai
achega
37332f4d6c

+ 356 - 37
crates/victory-gpu/src/host.rs

@@ -2944,6 +2944,87 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow:
     spans
     spans
 }
 }
 
 
+/// How many parts of submissions, and lists, the line's thread gives to the
+/// host as one (`VICTORY_JOIN_PARTS=<n>`; off by default, 1; `VICTORY_JOIN_LISTS`,
+/// 48).
+///
+/// The idea is fxceless/victory-fork's, commit 39731795 (GPL-3.0-or-later, as
+/// this): the title's lists wait for memory values, which cuts a frame into
+/// some 29 parts, each prepared on its own: the write watch asked, the heaps'
+/// records, the title's bytes under the flights' writes, a list that sends
+/// what changed and one that compares. (Run submit-1, the dorm, 12 of 28 parts
+/// joined, eight at most: the thread works 51.4 ms a frame instead of 54.8, the
+/// frame is 0.6 to 3 ms shorter.) What differs here: the parts are taken
+/// off one queue's entries of the line (`crate::queue`), still go to the queue
+/// in calls of their own, and everything they refresh is brought up to date in
+/// front of the first ([`refresh_front`], without which a later part's title
+/// bytes under an earlier part's declared writes would go missing).
+pub(crate) fn joins() -> (usize, usize) {
+    if ahead_of_writes() { joins_asked() } else { (1, 1) }
+}
+
+fn joins_asked() -> (usize, usize) {
+    static MOST: OnceLock<(usize, usize)> = OnceLock::new();
+    let of = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<usize>().ok());
+    let (parts, lists) = *MOST.get_or_init(|| (of("VICTORY_JOIN_PARTS").unwrap_or(1).max(1), of("VICTORY_JOIN_LISTS").unwrap_or(48).max(1)));
+    #[cfg(feature = "diagnostics")]
+    if let Some(on) = crate::ab::pick("VICTORY_JOIN_PARTS") {
+        return (if on { 8 } else { 1 }, lists);
+    }
+    (parts, lists)
+}
+
+/// Whether the part `next` can be prepared together with `ahead`, which goes
+/// before it and has not been sent: nothing done on the CPU for it reads what
+/// those give their shaders, write back or write when they are done, and it
+/// changes no title memory that they read ([`Step::Copy`], [`Step::Run`]).
+pub(crate) fn joinable<'a>(ahead: impl Iterator<Item = &'a HostList>, next: &[&HostList]) -> bool {
+    if next.iter().any(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_)))) {
+        return false;
+    }
+    let ahead: Vec<&HostList> = ahead.collect();
+    let mut written: Vec<(usize, usize)> = declared_writes(&ahead).into_iter().flat_map(|(_, ranges)| ranges).collect();
+    for list in &ahead {
+        let deferred = list.deferred();
+        written.extend(deferred.writes.iter().map(|&(at, _, bytes)| (at, at + bytes)));
+        written.extend(deferred.backs.iter().map(|&(_, at, [row, rows, pitch])| (at, at + rows.saturating_sub(1) * pitch + row)));
+    }
+    let mut joined = Vec::new();
+    join_ranges(&mut joined, written);
+    blocked_by(&joined, next, false).is_none()
+}
+
+/// Whether a bottom-of-pipe write of `list` meets `wait`.
+pub(crate) fn will_meet(list: &HostList, wait: &crate::list::ValueWait) -> bool {
+    let (address, bytes) = wait.place();
+    // The last write there says.
+    let deferred = list.deferred();
+    let last = deferred.writes.iter().rev().find(|(at, _, n)| *at < address + bytes && address < *at + *n);
+    matches!(last, Some((at, crate::queue::Written::Value(v), n)) if *at == address && *n >= bytes && wait.holds_for(*v))
+}
+
+/// Lists and the order they run in.
+type Run<T> = (Vec<T>, Vec<usize>);
+
+/// `order`'s first `cut` places and the rest, each with the lists they name;
+/// as it was if a list is named on both sides.
+fn split<T>(lists: Vec<T>, order: Vec<usize>, cut: usize) -> Result<[Run<T>; 2], Run<T>> {
+    let (first, second) = order.split_at(cut);
+    if first.is_empty() || second.is_empty() || first.iter().any(|i| second.contains(i)) {
+        return Err((lists, order));
+    }
+    let behind: Vec<bool> = (0..lists.len()).map(|i| second.contains(&i)).collect();
+    let place = |i: usize| behind[..i].iter().filter(|&&b| b == behind[i]).count();
+    let orders = [first, second].map(|half| half.iter().map(|&i| place(i)).collect::<Vec<_>>());
+    let mut halves: [Vec<T>; 2] = [Vec::new(), Vec::new()];
+    for (list, behind) in lists.into_iter().zip(&behind) {
+        halves[usize::from(*behind)].push(list);
+    }
+    let [a, b] = halves;
+    let [x, y] = orders;
+    Ok([(a, x), (b, y)])
+}
+
 /// A fence signal on a queue ([`late`]): goes behind the flights in the
 /// A fence signal on a queue ([`late`]): goes behind the flights in the
 /// air, if there are any, and is set when they are settled. Whether it
 /// air, if there are any, and is set when they are settled. Whether it
 /// did; if not the caller sets the fence now.
 /// did; if not the caller sets the fence now.
@@ -2973,11 +3054,20 @@ pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
 /// the value in a way not known here (shaders, a timestamp, another
 /// the value in a way not known here (shaders, a timestamp, another
 /// width), they are settled and memory is asked again.
 /// width), they are settled and memory is asked again.
 pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
 pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
+    if let Some(met) = late_met_known(wait) {
+        return met;
+    }
+    settle_now(WHY_VALUE);
+    wait.met()
+}
+
+/// [`late_met`] without a wait for the card; `None`: it has to be waited for.
+pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> Option<bool> {
     let (address, bytes) = wait.place();
     let (address, bytes) = wait.place();
     {
     {
         let line = line();
         let line = line();
         if line.line.is_empty() && line.in_hand.is_empty() {
         if line.line.is_empty() && line.in_hand.is_empty() {
-            return false;
+            return Some(false);
         }
         }
         let mut unsure = touches(&line.written, address, address + bytes);
         let mut unsure = touches(&line.written, address, address + bytes);
         // (With the relay: first the writes of flights being landed.)
         // (With the relay: first the writes of flights being landed.)
@@ -2993,18 +3083,17 @@ pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
                 crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
                 crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
                     if wait.holds_for(*v) {
                     if wait.holds_for(*v) {
                         LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
                         LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
-                        return true;
+                        return Some(true);
                     }
                     }
                 }
                 }
                 _ => unsure = true,
                 _ => unsure = true,
             }
             }
         }
         }
         if !unsure {
         if !unsure {
-            return false;
+            return Some(false);
         }
         }
     }
     }
-    settle_now(WHY_VALUE);
-    wait.met()
+    None
 }
 }
 
 
 /// Settles the flights in the air, if any ([`Host::settle`]), for reason
 /// Settles the flights in the air, if any ([`Host::settle`]), for reason
@@ -4016,30 +4105,13 @@ impl Host {
     /// `relay`).
     /// `relay`).
     /// `picked`: ranges that may be written too, and ranges to look at
     /// `picked`: ranges that may be written too, and ranges to look at
     /// (`crate::picked`).
     /// (`crate::picked`).
-    fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
+    fn card_before(&self, declared: &[Declared], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
         use std::sync::Arc;
         use std::sync::Arc;
         if !crate::shadow::cards() {
         if !crate::shadow::cards() {
             return None;
             return None;
         }
         }
         // The ranges this submission's shaders may write, per copy.
         // The ranges this submission's shaders may write, per copy.
-        let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
-        for list in runs {
-            for step in &list.deferred().copies {
-                if let Step::GpuWrite(shadow, address, len) = step
-                    && shadow.carded()
-                {
-                    let range = (*address, *address + *len);
-                    match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
-                        Some((_, ranges)) => {
-                            if !ranges.contains(&range) {
-                                ranges.push(range);
-                            }
-                        }
-                        None => declared.push((shadow.clone(), vec![range])),
-                    }
-                }
-            }
-        }
+        let declared: Vec<Declared> = declared.iter().filter(|(shadow, _)| shadow.carded()).cloned().collect();
         let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
         let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
         // (Of a copy with a declared range here, that says it.)
         // (Of a copy with a declared range here, that says it.)
         let looked: Vec<&crate::picked::Range> =
         let looked: Vec<&crate::picked::Range> =
@@ -4883,7 +4955,7 @@ impl Host {
     pub(crate) fn execute(&self, runs: &[&HostList]) {
     pub(crate) fn execute(&self, runs: &[&HostList]) {
         // Behind what the title's queues were given before it.
         // Behind what the title's queues were given before it.
         crate::queue::before_sync();
         crate::queue::before_sync();
-        let _ = self.submit(runs, false);
+        let _ = self.submit(runs, &[], false);
     }
     }
 
 
     /// A queue's submission with [`late`]: the host lists `lists`, taken
     /// A queue's submission with [`late`]: the host lists `lists`, taken
@@ -4893,14 +4965,39 @@ impl Host {
     /// ([`late`] lists those points); their host lists are reset and kept
     /// ([`late`] lists those points); their host lists are reset and kept
     /// for reuse then, as a queue does for the lists it ran.
     /// for reuse then, as a queue does for the lists it ran.
     pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
     pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
+        self.execute_parts(lists, order, &[]);
+    }
+
+    /// [`Host::execute_late`] of parts of submissions in one: another begins
+    /// at each place of `order` in `parts` ([`joins`]).
+    pub(crate) fn execute_parts(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) {
         if order.is_empty() {
         if order.is_empty() {
             crate::list::recycle(lists, &order);
             crate::list::recycle(lists, &order);
             return;
             return;
         }
         }
         late_threads();
         late_threads();
+        if let Some(cut) = {
+            let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
+            card_steps::cut_for(&runs)
+        } {
+            match split(lists, order, cut) {
+                Ok([(lists, order), (more, behind)]) => {
+                    let first: Vec<usize> = parts.iter().copied().filter(|&p| p < cut).collect();
+                    let second: Vec<usize> = parts.iter().filter(|&&p| p > cut).map(|p| p - cut).collect();
+                    self.execute_parts(lists, order, &first);
+                    self.execute_parts(more, behind, &second);
+                }
+                Err((lists, order)) => self.send_late(lists, order, parts),
+            }
+            return;
+        }
+        self.send_late(lists, order, parts);
+    }
+
+    fn send_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) {
         let sent = {
         let sent = {
             let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
             let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
-            self.submit(&runs, true)
+            self.submit(&runs, parts, true)
         };
         };
         let Some((mut submitted, sent)) = sent else {
         let Some((mut submitted, sent)) = sent else {
             // (Not reached: a submission sent ahead always comes back.)
             // (Not reached: a submission sent ahead always comes back.)
@@ -4950,7 +5047,7 @@ impl Host {
     /// it ran and was waited for after all.
     /// it ran and was waited for after all.
     fn execute_own(&self, list: &HostList) -> u64 {
     fn execute_own(&self, list: &HostList) -> u64 {
         late_threads();
         late_threads();
-        let Some((submitted, sent)) = self.submit(&[list], true) else {
+        let Some((submitted, sent)) = self.submit(&[list], &[], true) else {
             return 0;
             return 0;
         };
         };
         let number = sent.number;
         let number = sent.number;
@@ -5172,7 +5269,11 @@ impl Host {
     /// [`Host::execute_late`]: the lists are prepared and sent, and what is
     /// [`Host::execute_late`]: the lists are prepared and sent, and what is
     /// to be done once they have run comes back with the submission lock
     /// to be done once they have run comes back with the submission lock
     /// still held.
     /// still held.
-    fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
+    ///
+    /// `parts`: the lists of `runs` at which another part begins
+    /// ([`joins`]): those go to the queue in calls of their own, one after the
+    /// other, as they would have.
+    fn submit<'a>(&'a self, runs: &[&HostList], parts: &[usize], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
         #[cfg(feature = "diagnostics")]
         #[cfg(feature = "diagnostics")]
         let called = std::time::Instant::now();
         let called = std::time::Instant::now();
         #[cfg(feature = "diagnostics")]
         #[cfg(feature = "diagnostics")]
@@ -5225,6 +5326,7 @@ impl Host {
             }
             }
             None => runs,
             None => runs,
         };
         };
+        let parts: Vec<usize> = parts.iter().map(|&n| n + usize::from(own.is_some())).collect();
         stage.next("submit: the sweep");
         stage.next("submit: the sweep");
         let behind = late && flying();
         let behind = late && flying();
         // Before this submission counts as started: what the sweep lets go
         // Before this submission counts as started: what the sweep lets go
@@ -5320,7 +5422,9 @@ impl Host {
         // What flights in the air may write.
         // What flights in the air may write.
         let air = line().written.clone();
         let air = line().written.clone();
         stage.next("submit: refreshes ahead of writes");
         stage.next("submit: refreshes ahead of writes");
-        if ahead_of_writes() {
+        if refresh_front() {
+            batch.refresh_front(runs, &parts);
+        } else if ahead_of_writes() {
             batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
             batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
         }
         }
         stage.next("submit: the lists' steps");
         stage.next("submit: the lists' steps");
@@ -5367,7 +5471,8 @@ impl Host {
         for (shadow, at, len) in &picked.written {
         for (shadow, at, len) in &picked.written {
             shadow.writing(*at, *len);
             shadow.writing(*at, *len);
         }
         }
-        let card = self.card_before(runs, &picked, flown);
+        let declared = declared_writes(runs);
+        let card = self.card_before(&declared, &picked, flown);
         // The sends are taken: from here on the references hold what the
         // The sends are taken: from here on the references hold what the
         // copies in the lists put.
         // copies in the lists put.
         for (shadow, at, bytes) in batch.placed.drain(..) {
         for (shadow, at, bytes) in batch.placed.drain(..) {
@@ -5404,10 +5509,16 @@ impl Host {
             if let Some([front, behind]) = self.span_lists() {
             if let Some([front, behind]) = self.span_lists() {
                 lists.insert(0, Some(front));
                 lists.insert(0, Some(front));
                 lists.push(Some(behind));
                 lists.push(Some(behind));
+                firsts.iter_mut().for_each(|first| *first += 1);
             }
             }
+            let cuts: Vec<usize> = parts.iter().filter_map(|&n| firsts.get(n).copied()).collect();
             // SAFETY: closed lists; the fence is ours.
             // SAFETY: closed lists; the fence is ours.
             let signalled = unsafe {
             let signalled = unsafe {
-                self.queue.ExecuteCommandLists(&lists);
+                let mut from = 0;
+                for to in cuts.into_iter().chain([lists.len()]) {
+                    self.queue.ExecuteCommandLists(&lists[from..to]);
+                    from = to;
+                }
                 self.queue.Signal(&self.fence, *submitted)
                 self.queue.Signal(&self.fence, *submitted)
             };
             };
             awake::sent(&self.device);
             awake::sent(&self.device);
@@ -5420,7 +5531,7 @@ impl Host {
             }
             }
             #[cfg(feature = "diagnostics")]
             #[cfg(feature = "diagnostics")]
             split.part(5);
             split.part(5);
-            let back = crate::picked::with(declared_writes(runs), &picked.written);
+            let back = crate::picked::with(declared, &picked.written);
             let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
             SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
             submitting(0, 0);
             submitting(0, 0);
@@ -5545,7 +5656,7 @@ impl Host {
         if let Some(card) = &card {
         if let Some(card) = &card {
             self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
             self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
         }
         }
-        let back = crate::picked::with(declared_writes(runs), &picked.written);
+        let back = crate::picked::with(declared, &picked.written);
         hand_back(&back);
         hand_back(&back);
         if let Some(card) = card {
         if let Some(card) = card {
             self.card_done(card);
             self.card_done(card);
@@ -7182,6 +7293,9 @@ struct Batch {
     /// Copies (by address) brought up to date ahead of the steps, and the
     /// Copies (by address) brought up to date ahead of the steps, and the
     /// range (from, to) ([`Batch::refresh_ahead`]).
     /// range (from, to) ([`Batch::refresh_ahead`]).
     ahead: ByCopy<(usize, usize)>,
     ahead: ByCopy<(usize, usize)>,
+    /// `ahead` holds everything the submission refreshes
+    /// ([`Batch::refresh_front`]).
+    front: bool,
 }
 }
 
 
 /// Whether the copies that a submission's shaders write are brought up to
 /// Whether the copies that a submission's shaders write are brought up to
@@ -7195,6 +7309,73 @@ fn ahead_of_writes() -> bool {
     *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
     *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
 }
 }
 
 
+/// Whether everything a submission refreshes is brought up to date in one go,
+/// on several threads, ahead of its steps (`VICTORY_REFRESH_FRONT=1`, and with
+/// `VICTORY_JOIN_PARTS`, which needs it; else in groups where the steps ask
+/// for it). Measured on its own at nothing (run submit-1: refreshes 17.1 ms a
+/// frame without, 18.3 with).
+///
+/// A submission's refreshes were done in up to five groups one after the other
+/// (the copies its shaders write, those between its steps, what is left),
+/// each ending with the threads waiting for the last copy; and the submitting
+/// thread went over all the steps once for each question it has (what to ask
+/// about, what flights may write too, what shaders write). A refresh may come
+/// earlier than its step: the title's bytes are the same until a step writes
+/// title memory, and behind such a step everything is asked for again, as it
+/// was.
+fn refresh_front() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    ahead_of_writes() && (joins_asked().0 > 1 || *ON.get_or_init(|| crate::switch::on("VICTORY_REFRESH_FRONT")))
+}
+
+/// Per copy what is refreshed in front of a submission's steps, as
+/// [`written_spans`]'s but of all copies, up to the copy's first write by
+/// shaders in each part of the submission (`Touch::Part`: another begins).
+/// What a part refreshes of a copy it has given to its shaders stays where it
+/// stands: around what they write. What a later part refreshes is the
+/// title's bytes of before either.
+fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
+    let mut at: ByCopy<usize> = ByCopy::default();
+    // (Copy, from, to), in the order they come, and the part that gave it to
+    // shaders last.
+    let mut spans: Vec<(usize, usize, usize)> = Vec::new();
+    let mut given: Vec<u32> = Vec::new();
+    let (mut part, mut last) = (1, usize::MAX);
+    for step in steps {
+        match step {
+            Touch::Refresh(copy, from, to) => {
+                // (Most come several times on end.)
+                let i = if spans.get(last).is_some_and(|s| s.0 == copy) {
+                    last
+                } else {
+                    *at.entry(copy).or_insert_with(|| {
+                        spans.push((copy, usize::MAX, 0));
+                        given.push(0);
+                        spans.len() - 1
+                    })
+                };
+                last = i;
+                if given[i] != part {
+                    let span = &mut spans[i];
+                    (span.1, span.2) = (span.1.min(from), span.2.max(to));
+                }
+            }
+            Touch::Write(copy) => {
+                let i = *at.entry(copy).or_insert_with(|| {
+                    spans.push((copy, usize::MAX, 0));
+                    given.push(0);
+                    spans.len() - 1
+                });
+                given[i] = part;
+            }
+            Touch::Part => part += 1,
+            Touch::Title | Touch::Nothing => {}
+        }
+    }
+    spans.retain(|s| s.1 < s.2);
+    spans
+}
+
 /// What a step is to the copies' refreshes, for [`written_spans`].
 /// What a step is to the copies' refreshes, for [`written_spans`].
 enum Touch {
 enum Touch {
     /// A refresh of a copy (by address), from, to.
     /// A refresh of a copy (by address), from, to.
@@ -7204,6 +7385,8 @@ enum Touch {
     /// Title memory is written.
     /// Title memory is written.
     Title,
     Title,
     Nothing,
     Nothing,
+    /// Another part of the submission begins.
+    Part,
 }
 }
 
 
 /// Of `steps`, up to the first that writes title memory: the copies given to
 /// Of `steps`, up to the first that writes title memory: the copies given to
@@ -7226,7 +7409,7 @@ fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize
                 }
                 }
             }
             }
             Touch::Title => break,
             Touch::Title => break,
-            Touch::Nothing => {}
+            Touch::Nothing | Touch::Part => {}
         }
         }
     }
     }
     spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
     spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
@@ -7234,7 +7417,47 @@ fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize
 
 
 #[cfg(test)]
 #[cfg(test)]
 mod written_spans_tests {
 mod written_spans_tests {
-    use super::{Touch, written_spans};
+    use super::{Touch, front_spans, split, written_spans};
+
+    #[test]
+    fn everything_is_refreshed_in_front_but_what_a_part_gave_its_shaders() {
+        use Touch::{Nothing, Part, Refresh, Title, Write};
+        let found = front_spans(
+            [
+                Refresh(1, 10, 20),
+                Refresh(1, 12, 25),
+                Refresh(2, 0, 5),
+                Nothing,
+                Write(1),
+                // (Around what the part's own shaders write.)
+                Refresh(1, 0, 100),
+                Write(3),
+                Refresh(3, 1, 2),
+                Title,
+                Refresh(4, 7, 9),
+                Part,
+                // The next part's bytes under the first one's writes.
+                Refresh(1, 30, 40),
+                Write(4),
+                Refresh(4, 0, 9),
+            ]
+            .into_iter(),
+        );
+        assert_eq!(found, [(1, 10, 40), (2, 0, 5), (4, 7, 9)]);
+    }
+
+    #[test]
+    fn a_submission_is_cut_between_its_lists() {
+        // Lists c and e are in neither half's order: they go with the first.
+        let Ok([first, second]) = split(vec!['a', 'b', 'c', 'd', 'e'], vec![1, 3, 0], 1) else {
+            panic!("no list is named twice");
+        };
+        let run = |(lists, order): &(Vec<char>, Vec<usize>)| order.iter().map(|&i| lists[i]).collect::<String>();
+        assert_eq!((run(&first), run(&second)), ("b".into(), "da".into()));
+        assert_eq!(first.0.len() + second.0.len(), 5);
+        assert!(split(vec!['a', 'b'], vec![0, 1, 0], 2).is_err());
+        assert!(split(vec!['a', 'b'], vec![0, 1], 0).is_err());
+    }
 
 
     #[test]
     #[test]
     fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
     fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
@@ -7315,8 +7538,11 @@ impl Batch {
     /// Before shaders are given a range of `shadow`'s copy: its pending
     /// Before shaders are given a range of `shadow`'s copy: its pending
     /// refresh is done, the others stay pending.
     /// refresh is done, the others stay pending.
     fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
     fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
-        // From here on it is refreshed around what the shaders write.
-        self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
+        // From here on it is refreshed around what the shaders write. (What
+        // is in front of all the steps was, up to here.)
+        if !self.front {
+            self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
+        }
         let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
         let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
             return;
             return;
         };
         };
@@ -7365,6 +7591,99 @@ impl Batch {
         self.textures.clear();
         self.textures.clear();
     }
     }
 
 
+    /// Before the steps of `runs` ([`refresh_front`]), a new part of the
+    /// submission beginning at each of `parts`.
+    fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) {
+        let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
+        let mut due = Vec::new();
+        let mut touches = Vec::new();
+        for (n, list) in runs.iter().enumerate() {
+            if parts.contains(&n) {
+                touches.push(Touch::Part);
+            }
+            let mut last = 0;
+            for step in &list.deferred().copies {
+                match step {
+                    Step::Refresh(shadow, at, len) => {
+                        let key = std::sync::Arc::as_ptr(shadow) as usize;
+                        if key != last {
+                            copies.entry(key).or_insert_with(|| shadow.clone());
+                            last = key;
+                        }
+                        touches.push(Touch::Refresh(key, *at, *at + *len));
+                    }
+                    Step::GpuWrite(shadow, ..) => touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)),
+                    Step::Texture(staging) if wide_textures() => {
+                        if self.texture_due(staging) {
+                            due.push(staging.clone());
+                        }
+                    }
+                    _ => {}
+                }
+            }
+        }
+        let spans: Vec<_> = front_spans(touches.into_iter())
+            .into_iter()
+            .filter_map(|(key, from, to)| Some((copies.remove(&key)?, from, to)))
+            .collect();
+        self.front = true;
+        for (shadow, from, to) in &spans {
+            self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
+        }
+        #[cfg(feature = "diagnostics")]
+        {
+            FLUSHES[0].fetch_add(1, Ordering::Relaxed);
+            FLUSHES[1].fetch_add(spans.len() as u64, Ordering::Relaxed);
+        }
+        let _flush = crate::timeline::span("refreshes of copies");
+        let started = std::time::Instant::now();
+        let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed));
+        // Those known to copy nothing are said so here, unless they are very
+        // many: then beside the others.
+        const FEW: usize = 256;
+        let mut spans = spans;
+        let many = spans.len() > FEW;
+        if !many {
+            #[cfg(feature = "diagnostics")]
+            let all = spans.len();
+            spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
+            #[cfg(feature = "diagnostics")]
+            FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed);
+        }
+        let ahead = spans.len() > 1;
+        if ahead {
+            let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect();
+            crate::watch::ask_ahead(&ranges);
+        }
+        #[cfg(feature = "diagnostics")]
+        FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed);
+        crate::shadow::wide_each(spans.len() + due.len(), move |i| {
+            // The textures first: they are the longer pieces.
+            let Some(i) = i.checked_sub(due.len()) else {
+                due[i].refresh();
+                return;
+            };
+            let (shadow, from, to) = &spans[i];
+            if many && shadow.nothing_new(*from, *to - *from) {
+                #[cfg(feature = "diagnostics")]
+                FLUSHES[2].fetch_add(1, Ordering::Relaxed);
+                return;
+            }
+            Self::update(shadow, *from, *to);
+        });
+        if ahead {
+            crate::watch::ask_ahead_done();
+        }
+        // The time counted is the time it took, not the threads' sum.
+        let took = started.elapsed().as_micros() as u64;
+        let summed = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)).iter().zip(before).map(|(now, was)| now.saturating_sub(was)).collect::<Vec<_>>();
+        PREPARING[2].fetch_sub(summed[1], Ordering::Relaxed);
+        PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed);
+        PREPARING[0].fetch_add(took, Ordering::Relaxed);
+        #[cfg(feature = "diagnostics")]
+        SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
+    }
+
     /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
     /// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
     /// that `taken` names are not done on the CPU.
     /// that `taken` names are not done on the CPU.
     fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {
     fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {

+ 142 - 57
crates/victory-gpu/src/host/card_steps.rs

@@ -83,6 +83,23 @@ pub(super) fn stage() -> u32 {
     })
     })
 }
 }
 
 
+/// Whether a copy at its place in a list ([`place`]) is only in the way of
+/// what is done on the card in front of the lists if that stands behind it in
+/// them (`VICTORY_PLACED_ORDER=0`: wherever it stands, as before), and a
+/// submission where it does is cut behind the copy's list ([`cut_for`]).
+///
+/// The fills of constant buffers read the title's ring (7,500 a frame in the
+/// opening), and one copy of a few hundred bytes a frame writes into it at its
+/// place in a list. The whole submission was refused for it, and stood 40 to
+/// 60 ms until the flights had landed (run n19).
+fn placed_order() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_PLACED_ORDER").is_none_or(|v| v != "0"))
+}
+
+/// Why [`plan`] refuses for [`place`].
+const BEHIND_PLACED: &str = "a copy at its place in a list writes what it reads, or reads or writes what it writes";
+
 /// The bytes of our buffer between reading and writing: what one submission
 /// The bytes of our buffer between reading and writing: what one submission
 /// may do this way (each place read once, however many fills take it).
 /// may do this way (each place read once, however many fills take it).
 const BETWEEN: u64 = 4 << 20;
 const BETWEEN: u64 = 4 << 20;
@@ -226,10 +243,13 @@ fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool {
 /// only what a taken copy has not been told to write yet: bytes a step
 /// only what a taken copy has not been told to write yet: bytes a step
 /// ahead of it reads, in title memory as it is.
 /// ahead of it reads, in title memory as it is.
 ///
 ///
+/// `behind`: for [`BEHIND_PLACED`], the copy at its place and the first step
+/// behind it that is in its way.
+///
 /// Steps of a level are done together, every read before every write; a
 /// Steps of a level are done together, every read before every write; a
 /// step that writes what an earlier one reads or writes, or reads what it
 /// step that writes what an earlier one reads or writes, or reads what it
 /// writes, is of a higher level. Our list does them level by level.
 /// writes, is of a higher level. Our list does them level by level.
-fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
+fn plan(does: &[Does], stage: u32, by_order: bool, behind: &mut Option<(usize, usize)>) -> Result<Vec<(usize, u32)>, &'static str> {
     let takes = |d: &Does| match *d {
     let takes = |d: &Does| match *d {
         Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"),
         Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"),
         Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"),
         Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"),
@@ -281,12 +301,21 @@ fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
         }
         }
     }
     }
     // A copy at its place in a list comes after what is done in front of all
     // A copy at its place in a list comes after what is done in front of all
-    // of them.
-    for d in does {
+    // of them: as it should after the steps ahead of it, but not after those
+    // behind it that read or write its bytes.
+    for (p, d) in does.iter().enumerate() {
         if let Does::Placed { dst, src, len } = *d
         if let Does::Placed { dst, src, len } = *d
             && (touched(&read, (dst, dst + len)) || touched(&written, (dst, dst + len)) || touched(&written, (src, src + len)))
             && (touched(&read, (dst, dst + len)) || touched(&written, (dst, dst + len)) || touched(&written, (src, src + len)))
         {
         {
-            return Err("a copy at its place in a list writes what it reads, or reads or writes what it writes");
+            let (to, from) = ((dst, dst + len), (src, src + len));
+            let in_the_way = |i: usize| {
+                reads_writes(&does[i]).is_some_and(|(r, w)| meet(r, to) || w.0 < w.1 && (meet(w, to) || meet(w, from)))
+            };
+            let found = (p + 1..does.len()).find(|&i| taken[i] && in_the_way(i));
+            *behind = found.map(|i| (p, i));
+            if !by_order || found.is_some() {
+                return Err(BEHIND_PLACED);
+            }
         }
         }
     }
     }
     let order: Vec<usize> = (0..does.len()).filter(|&i| taken[i]).collect();
     let order: Vec<usize> = (0..does.len()).filter(|&i| taken[i]).collect();
@@ -375,6 +404,78 @@ fn holder(writers: &[Writer], from: usize, to: usize) -> Result<Arc<Shadow>, &'s
     Ok(shadow)
     Ok(shadow)
 }
 }
 
 
+/// What the steps of `runs` do, and which step each is (its list by address,
+/// its place in it). `written`: what flights may write.
+fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec<Does>, Vec<(usize, usize)>) {
+    let mut does = Vec::new();
+    // Which step each is. One list's lock at a time: a submission may
+    // name a list twice.
+    let mut steps = Vec::new();
+    for list in runs {
+        for (i, step) in list.deferred().copies.iter().enumerate() {
+            does.push(match step {
+                &Step::Copy(dst, src, len) => Does::Copy {
+                    dst,
+                    src,
+                    len,
+                    asked: copy_blocked(written, dst, src, len).is_some(),
+                },
+                Step::Fill(_, src, len, to) => Does::Fill {
+                    src: *src,
+                    len: *len,
+                    asked: read_blocked(written, *src, *len),
+                    to: to.is_some(),
+                },
+                Step::Texture(staging) => {
+                    let (at, len) = staging.memory();
+                    Does::Read {
+                        from: at,
+                        to: at + len,
+                        asked: touches(written, at, at + len),
+                    }
+                }
+                &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
+                Step::Refresh(shadow, at, len) => Does::Refresh {
+                    shadow: Arc::as_ptr(shadow) as usize,
+                    from: *at,
+                    to: *at + *len,
+                },
+                Step::Run(_) => Does::Run,
+                Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len },
+                Step::GpuWrite(..) | Step::Host(..) => continue,
+            });
+            steps.push((std::ptr::from_ref::<HostList>(list) as usize, i));
+        }
+    }
+    (does, steps)
+}
+
+/// With flights in the air: before which of `runs` the submission is cut so
+/// that what reads or writes the bytes of a copy at its place in an earlier
+/// list ([`BEHIND_PLACED`]) is done on the card in front of a submission of
+/// its own, behind that copy.
+pub(super) fn cut_for(runs: &[&HostList]) -> Option<usize> {
+    if stage() == 0 || !relay_exact() || !placed_order() || runs.len() < 2 {
+        return None;
+    }
+    // (Most submissions have none.)
+    let first = runs.iter().position(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Placed(_))))?;
+    if first + 1 == runs.len() {
+        return None;
+    }
+    let written = line().written.clone();
+    blocked_by(&written, runs, false)?;
+    let (does, steps) = does_of(&written, runs);
+    let mut behind = None;
+    if plan(&does, stage(), true, &mut behind) != Err(BEHIND_PLACED) {
+        return None;
+    }
+    let (placed, reader) = behind?;
+    let place = |i: usize| runs.iter().position(|l| std::ptr::from_ref::<HostList>(l) as usize == steps[i].0);
+    let cut = place(placed)? + 1;
+    (place(reader)? >= cut).then_some(cut)
+}
+
 /// Whether every page of `[from, to)` can be read (through the kernel:
 /// Whether every page of `[from, to)` can be read (through the kernel:
 /// asking Windows walks the page tables, milliseconds in the title's heap).
 /// asking Windows walks the page tables, milliseconds in the title's heap).
 /// `room`: for what is read.
 /// `room`: for what is read.
@@ -567,47 +668,8 @@ impl Host {
     }
     }
 
 
     fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
     fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
-        let mut does = Vec::new();
-        // Which step each is. One list's lock at a time: a submission may
-        // name a list twice.
-        let mut steps = Vec::new();
-        for list in runs {
-            for (i, step) in list.deferred().copies.iter().enumerate() {
-                does.push(match step {
-                    &Step::Copy(dst, src, len) => Does::Copy {
-                        dst,
-                        src,
-                        len,
-                        asked: copy_blocked(written, dst, src, len).is_some(),
-                    },
-                    Step::Fill(_, src, len, to) => Does::Fill {
-                        src: *src,
-                        len: *len,
-                        asked: read_blocked(written, *src, *len),
-                        to: to.is_some(),
-                    },
-                    Step::Texture(staging) => {
-                        let (at, len) = staging.memory();
-                        Does::Read {
-                            from: at,
-                            to: at + len,
-                            asked: touches(written, at, at + len),
-                        }
-                    }
-                    &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
-                    Step::Refresh(shadow, at, len) => Does::Refresh {
-                        shadow: Arc::as_ptr(shadow) as usize,
-                        from: *at,
-                        to: *at + *len,
-                    },
-                    Step::Run(_) => Does::Run,
-                    Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len },
-                    Step::GpuWrite(..) | Step::Host(..) => continue,
-                });
-                steps.push((std::ptr::from_ref::<HostList>(list) as usize, i));
-            }
-        }
-        let chosen = plan(&does, stage())?;
+        let (does, steps) = does_of(written, runs);
+        let chosen = plan(&does, stage(), placed_order(), &mut None)?;
         if chosen.is_empty() {
         if chosen.is_empty() {
             return Ok(None);
             return Ok(None);
         }
         }
@@ -863,7 +925,7 @@ mod tests {
 
 
     /// What is done on the card, as (place, level), in stage 2.
     /// What is done on the card, as (place, level), in stage 2.
     fn planned(does: &[Does]) -> Vec<(usize, u32)> {
     fn planned(does: &[Does]) -> Vec<(usize, u32)> {
-        plan(does, 2).unwrap()
+        plan(does, 2, true, &mut None).unwrap()
     }
     }
 
 
     /// Only what is asked for is taken, all of it, and a step that stands
     /// Only what is asked for is taken, all of it, and a step that stands
@@ -881,8 +943,8 @@ mod tests {
         ];
         ];
         assert_eq!(planned(&does), [(1, 0), (3, 0)]);
         assert_eq!(planned(&does), [(1, 0), (3, 0)]);
         // Two fills of the same bytes.
         // Two fills of the same bytes.
-        assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![(0, 0), (1, 0)]));
-        assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![]));
+        assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1, true, &mut None), Ok(vec![(0, 0), (1, 0)]));
+        assert_eq!(plan(&[fill(0, 64, false)], 1, true, &mut None), Ok(vec![]));
         // Ends that touch are apart.
         // Ends that touch are apart.
         let does = [
         let does = [
             copy(1000, 5000, 100, true),
             copy(1000, 5000, 100, true),
@@ -927,6 +989,29 @@ mod tests {
         assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]);
         assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]);
     }
     }
 
 
+    /// A copy at its place in a list is in the way of what reads or writes its
+    /// bytes behind it, not of what did ahead of it.
+    #[test]
+    fn copies_at_their_place_stand_in_the_way_of_what_is_behind_them() {
+        let placed = Does::Placed { dst: 2000, src: 3000, len: 64 };
+        let behind = |does: &[Does]| {
+            let mut found = None;
+            let refused = plan(does, 2, true, &mut found);
+            assert!(refused.is_ok() || found.is_some() && refused == Err(BEHIND_PLACED));
+            assert_eq!(plan(does, 2, false, &mut None).is_err(), does.len() > 1 && !matches!(does, [_, Does::Fill { src: 5000, .. }]));
+            found
+        };
+        assert_eq!(behind(&[fill(2032, 64, true), placed]), None);
+        assert_eq!(behind(&[placed, fill(2032, 64, true)]), Some((0, 1)));
+        assert_eq!(behind(&[placed, fill(5000, 64, true)]), None);
+        assert_eq!(behind(&[fill(2000, 8, true), placed, fill(2000, 8, true)]), Some((1, 2)));
+        // One that writes what it copies from, and one that writes over it.
+        assert_eq!(behind(&[copy(3000, 5000, 8, true), placed]), None);
+        assert_eq!(behind(&[placed, copy(3000, 5000, 8, true)]), Some((0, 1)));
+        assert_eq!(behind(&[copy(2060, 5000, 8, true), placed]), None);
+        assert_eq!(behind(&[placed, copy(2060, 5000, 8, true)]), Some((0, 1)));
+    }
+
     /// Whatever the steps, done level by level (in a level every read
     /// Whatever the steps, done level by level (in a level every read
     /// before every write) they read and leave what they read and leave one
     /// before every write) they read and leave what they read and leave one
     /// after the other, the CPU's steps ahead of all of them.
     /// after the other, the CPU's steps ahead of all of them.
@@ -951,7 +1036,7 @@ mod tests {
                     }
                     }
                 })
                 })
                 .collect();
                 .collect();
-            let Ok(chosen) = plan(&does, 2) else {
+            let Ok(chosen) = plan(&does, 2, true, &mut None) else {
                 refused += 1;
                 refused += 1;
                 continue;
                 continue;
             };
             };
@@ -1005,22 +1090,22 @@ mod tests {
     #[test]
     #[test]
     fn steps_in_the_way_are_refused() {
     fn steps_in_the_way_are_refused() {
         let taken = copy(1000, 5000, 100, true);
         let taken = copy(1000, 5000, 100, true);
-        assert!(plan(&[taken, Does::Run], 2).is_err());
+        assert!(plan(&[taken, Does::Run], 2, true, &mut None).is_err());
         // A texture that itself waits for flights; a fill that cannot be
         // A texture that itself waits for flights; a fill that cannot be
         // taken but waits.
         // taken but waits.
-        assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2).is_err());
-        assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2).is_err());
+        assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2, true, &mut None).is_err());
+        assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2, true, &mut None).is_err());
         // Reads on the CPU of what it writes: behind it, not ahead of it.
         // Reads on the CPU of what it writes: behind it, not ahead of it.
         for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] {
         for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] {
-            assert!(plan(&[taken, read], 2).is_err(), "{read:?} behind");
+            assert!(plan(&[taken, read], 2, true, &mut None).is_err(), "{read:?} behind");
             assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead");
             assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead");
         }
         }
         // Also of what is taken along.
         // Also of what is taken along.
-        assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2).is_err());
+        assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2, true, &mut None).is_err());
         // Into itself, and copies without stage 2.
         // Into itself, and copies without stage 2.
-        assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err());
-        assert!(plan(&[taken], 1).is_err());
-        assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err());
+        assert!(plan(&[copy(1000, 1050, 100, true)], 2, true, &mut None).is_err());
+        assert!(plan(&[taken], 1, true, &mut None).is_err());
+        assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1, true, &mut None).is_err());
     }
     }
 
 
     #[test]
     #[test]

+ 175 - 8
crates/victory-gpu/src/queue/behind.rs

@@ -61,6 +61,14 @@ pub(super) trait Work: Send {
     fn shows(&self) -> bool;
     fn shows(&self) -> bool;
     /// Whether it is a submission.
     /// Whether it is a submission.
     fn runs(&self) -> bool;
     fn runs(&self) -> bool;
+    /// Takes `next`, what its queue was given behind it, along to be done with
+    /// it; or gives it back. Whether it is a submission that was taken.
+    fn take_along(&mut self, next: Self) -> Result<bool, Self>
+    where
+        Self: Sized,
+    {
+        Err(next)
+    }
     /// Does it. `forced`: its wait was not met.
     /// Does it. `forced`: its wait was not met.
     fn go(self, forced: bool);
     fn go(self, forced: bool);
 }
 }
@@ -263,7 +271,7 @@ impl<W: Work> Lane<W> {
                 (first, true)
                 (first, true)
             }
             }
         };
         };
-        let entry = {
+        let mut entry = {
             let mut state = self.lock();
             let mut state = self.lock();
             let Some(at) = state.items.iter().position(|e| e.number == number) else {
             let Some(at) = state.items.iter().position(|e| e.number == number) else {
                 return false;
                 return false;
@@ -274,13 +282,34 @@ impl<W: Work> Lane<W> {
             state.running = Some(entry.queue);
             state.running = Some(entry.queue);
             entry
             entry
         };
         };
-        let (shows, runs) = (entry.what.shows(), entry.what.runs());
+        let (shows, mut runs) = (entry.what.shows(), usize::from(entry.what.runs()));
+        // What follows it in its queue, if that can go with it. (Nobody else
+        // takes anything out, and what comes in goes to the end.)
+        while runs > 0 && !forced {
+            let next = {
+                let mut state = self.lock();
+                let at = state.items.iter().position(|e| e.queue == entry.queue && e.number < limit);
+                at.and_then(|at| state.items.remove(at))
+            };
+            let Some(Entry { number, queue, what }) = next else {
+                break;
+            };
+            match entry.what.take_along(what) {
+                Ok(run) => runs += usize::from(run),
+                Err(what) => {
+                    let mut state = self.lock();
+                    let at = state.items.iter().position(|e| e.number > number).unwrap_or(state.items.len());
+                    state.items.insert(at, Entry { number, queue, what });
+                    break;
+                }
+            }
+        }
         entry.what.go(forced);
         entry.what.go(forced);
         {
         {
             let mut state = self.lock();
             let mut state = self.lock();
             state.running = None;
             state.running = None;
             state.presents -= usize::from(shows);
             state.presents -= usize::from(shows);
-            state.runs -= usize::from(runs);
+            state.runs -= runs;
         }
         }
         self.moved.notify_all();
         self.moved.notify_all();
         true
         true
@@ -296,6 +325,9 @@ enum Job {
     /// A submission, or a part of one: the lists' host sides and the order
     /// A submission, or a part of one: the lists' host sides and the order
     /// they run in.
     /// they run in.
     Run(usize, Vec<crate::list::Detached>, Vec<usize>),
     Run(usize, Vec<crate::list::Detached>, Vec<usize>),
+    /// Parts taken along with a submission ([`crate::host::joins`]): where they
+    /// begin in the order, and the signals given behind them.
+    Joined(usize, Vec<crate::list::Detached>, Vec<usize>, Vec<usize>, Vec<(usize, u64)>),
     /// A signal of the queue's.
     /// A signal of the queue's.
     Signal(usize, u64),
     Signal(usize, u64),
     /// A frame is shown: the texture and the state its lists leave it in.
     /// A frame is shown: the texture and the state its lists leave it in.
@@ -335,13 +367,73 @@ impl Work for Job {
     }
     }
 
 
     fn runs(&self) -> bool {
     fn runs(&self) -> bool {
-        matches!(self, Job::Run(..))
+        matches!(self, Job::Run(..) | Job::Joined(..))
+    }
+
+    fn take_along(&mut self, next: Job) -> Result<bool, Job> {
+        let (most, most_lists) = crate::host::joins();
+        if most < 2 {
+            return Err(next);
+        }
+        // Nothing but waits and signals that a submission may follow.
+        let (count, lists, signals) = match self {
+            Job::Run(_, lists, order) => (1, (&*lists, &*order), &[][..]),
+            Job::Joined(_, lists, order, parts, signals) => (1 + parts.len(), (&*lists, &*order), &signals[..]),
+            _ => return Err(next),
+        };
+        let hosts = || lists.1.iter().map(|&i| lists.0[i].host());
+        match &next {
+            Job::Value(wait) => {
+                let met = wait.met()
+                    || crate::host::late_met_known(wait) == Some(true)
+                    || hosts().any(|list| crate::host::will_meet(list, wait));
+                if !met {
+                    return Err(next);
+                }
+            }
+            &Job::Wait(fence, value) => {
+                if crate::fence::completed(fence as This) < value && !signals.iter().any(|&(f, v)| f == fence && v >= value) {
+                    return Err(next);
+                }
+            }
+            Job::Signal(..) => {}
+            Job::Run(_, more, order) => {
+                let runs: Vec<&crate::host::HostList> = order.iter().map(|&i| more[i].host()).collect();
+                if count >= most || lists.1.len() + runs.len() > most_lists || !crate::host::joinable(hosts(), &runs) {
+                    return Err(next);
+                }
+            }
+            Job::Joined(..) | Job::Present(..) => return Err(next),
+        }
+        let taken = std::mem::replace(self, Job::Wait(0, 0));
+        let (queue, mut lists, mut order, mut parts, mut signals) = match taken {
+            Job::Run(queue, lists, order) => (queue, lists, order, Vec::new(), Vec::new()),
+            Job::Joined(queue, lists, order, parts, signals) => (queue, lists, order, parts, signals),
+            other => {
+                *self = other;
+                return Err(next);
+            }
+        };
+        let run = matches!(next, Job::Run(..));
+        match next {
+            Job::Run(_, more, then) => {
+                parts.push(order.len());
+                order.extend(then.into_iter().map(|i| i + lists.len()));
+                lists.extend(more);
+                STATS[JOINED].fetch_add(1, Relaxed);
+            }
+            Job::Signal(fence, value) => signals.push((fence, value)),
+            _ => {}
+        }
+        *self = Job::Joined(queue, lists, order, parts, signals);
+        Ok(run)
     }
     }
 
 
     fn go(self, forced: bool) {
     fn go(self, forced: bool) {
         let began = Instant::now();
         let began = Instant::now();
         let _doing = crate::timeline::span(match self {
         let _doing = crate::timeline::span(match self {
             Job::Run(..) => "the line: a submission",
             Job::Run(..) => "the line: a submission",
+            Job::Joined(..) => "the line: submissions joined",
             Job::Present(..) => "the line: a present",
             Job::Present(..) => "the line: a present",
             Job::Signal(..) => "the line: a signal",
             Job::Signal(..) => "the line: a signal",
             _ => "the line: a wait that is met",
             _ => "the line: a wait that is met",
@@ -365,6 +457,24 @@ impl Work for Job {
                 }
                 }
                 QUEUED.fetch_sub(1, Relaxed);
                 QUEUED.fetch_sub(1, Relaxed);
             }
             }
+            Job::Joined(queue, lists, order, parts, signals) => {
+                let _ = queue;
+                #[cfg(feature = "diagnostics")]
+                crate::capture::op(queue, || {
+                    format!("RUN {} parts of submissions in one, {} lists (its thread's)", 1 + parts.len(), order.len())
+                });
+                match crate::host::host() {
+                    Some(host) => host.execute_parts(lists, order, &parts),
+                    None => drop(lists),
+                }
+                // (A part that had no list is one all the same.)
+                QUEUED.fetch_sub(1 + parts.len() as u64, Relaxed);
+                for (fence, value) in signals {
+                    if !crate::host::late_signal(fence, value) {
+                        crate::fence::set(fence as This, value);
+                    }
+                }
+            }
             Job::Signal(fence, value) => {
             Job::Signal(fence, value) => {
                 if !crate::host::late_signal(fence, value) {
                 if !crate::host::late_signal(fence, value) {
                     crate::fence::set(fence as This, value);
                     crate::fence::set(fence as This, value);
@@ -392,7 +502,7 @@ static QUEUED: AtomicU64 = AtomicU64::new(0);
 /// threads of the title waited, in microseconds, for room in the line, at a
 /// threads of the title waited, in microseconds, for room in the line, at a
 /// present, and for a drain, and the drains; what our thread worked; waits
 /// present, and for a drain, and the drains; what our thread worked; waits
 /// not met at a present.
 /// not met at a present.
-static STATS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10];
+static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11];
 const RUNS: usize = 0;
 const RUNS: usize = 0;
 const PRESENTS: usize = 1;
 const PRESENTS: usize = 1;
 const DEPTH: usize = 2;
 const DEPTH: usize = 2;
@@ -403,6 +513,8 @@ const DRAINING: usize = 6;
 const DRAINS: usize = 7;
 const DRAINS: usize = 7;
 const BUSY: usize = 8;
 const BUSY: usize = 8;
 const FORCED: usize = 9;
 const FORCED: usize = 9;
+/// Parts prepared together with the one before them.
+const JOINED: usize = 10;
 
 
 /// How many submissions may be in the line when a submit call returns
 /// How many submissions may be in the line when a submit call returns
 /// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's).
 /// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's).
@@ -593,7 +705,8 @@ pub(super) fn line(frames: f64) {
     tracing::info!(
     tracing::info!(
         "submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \
         "submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \
          when one was added (at most {:.0}); that thread worked {:.1} ms; threads of the title waited {:.1} ms for room in the \
          when one was added (at most {:.0}); that thread worked {:.1} ms; threads of the title waited {:.1} ms for room in the \
-         line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}",
+         line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}; {:.1} of the \
+         submissions were prepared together with the one before them (VICTORY_JOIN_PARTS)",
         s[RUNS] / frames,
         s[RUNS] / frames,
         s[PRESENTS] / frames,
         s[PRESENTS] / frames,
         s[DEPTH] / s[RUNS].max(1.0),
         s[DEPTH] / s[RUNS].max(1.0),
@@ -603,7 +716,8 @@ pub(super) fn line(frames: f64) {
         ms(AT_PRESENT),
         ms(AT_PRESENT),
         ms(DRAINING),
         ms(DRAINING),
         s[DRAINS] / frames,
         s[DRAINS] / frames,
-        s[FORCED] / frames
+        s[FORCED] / frames,
+        s[JOINED] / frames
     );
     );
 }
 }
 
 
@@ -623,6 +737,8 @@ mod tests {
         Slow(&'static str, Log, Arc<(Mutex<bool>, Condvar)>),
         Slow(&'static str, Log, Arc<(Mutex<bool>, Condvar)>),
         Signal(usize, u64, Log),
         Signal(usize, u64, Log),
         Present(&'static str, Log),
         Present(&'static str, Log),
+        /// Takes others of its kind, waits that are met, and signals along.
+        Group(Vec<&'static str>, Log, Vec<(usize, u64)>),
     }
     }
 
 
     impl Work for T {
     impl Work for T {
@@ -640,7 +756,24 @@ mod tests {
             matches!(self, T::Present(..))
             matches!(self, T::Present(..))
         }
         }
         fn runs(&self) -> bool {
         fn runs(&self) -> bool {
-            matches!(self, T::Run(..) | T::Slow(..))
+            matches!(self, T::Run(..) | T::Slow(..) | T::Group(..))
+        }
+        fn take_along(&mut self, next: T) -> Result<bool, T> {
+            let T::Group(names, _, signals) = self else {
+                return Err(next);
+            };
+            match next {
+                T::Group(more, ..) if names.len() < 3 => {
+                    names.extend(more);
+                    Ok(true)
+                }
+                T::Wait(f, v) if crate::fence::completed(f as This) >= v || signals.contains(&(f, v)) => Ok(false),
+                T::Signal(f, v, _) => {
+                    signals.push((f, v));
+                    Ok(false)
+                }
+                other => Err(other),
+            }
         }
         }
         fn go(self, forced: bool) {
         fn go(self, forced: bool) {
             match self {
             match self {
@@ -661,6 +794,12 @@ mod tests {
                     log.lock().unwrap().push(format!("signal {value}"));
                     log.lock().unwrap().push(format!("signal {value}"));
                     crate::fence::set(fence as This, value);
                     crate::fence::set(fence as This, value);
                 }
                 }
+                T::Group(names, log, signals) => {
+                    log.lock().unwrap().push(names.join("+"));
+                    for (fence, value) in signals {
+                        crate::fence::set(fence as This, value);
+                    }
+                }
             }
             }
         }
         }
     }
     }
@@ -706,6 +845,34 @@ mod tests {
         assert!(done);
         assert!(done);
     }
     }
 
 
+    /// A submission takes what follows it in its queue along, up to what it
+    /// cannot take, which stays at its place; the counts come out even.
+    #[test]
+    fn submissions_take_those_behind_them_along() {
+        let lane = Lane::new();
+        let log: Log = Default::default();
+        let f = fence();
+        let part = |name| T::Group(vec![name], log.clone(), Vec::new());
+        lane.push(1, [part("a"), T::Wait(f, 0), part("b")]);
+        lane.push(2, [part("other queue"), T::Wait(f, 1), part("behind a's signal")]);
+        lane.push(1, [T::Signal(f, 1, log.clone()), T::Wait(f, 1), part("c"), part("d")]);
+        lane.push(1, [T::Wait(f, 9), part("held"), T::Present("present", log.clone()), part("next frame")]);
+        // What came after the look was asked for is not touched.
+        let limit = lane.lock().next;
+        lane.push(1, [part("later")]);
+        lane.look(limit);
+        assert_eq!(
+            *log.lock().unwrap(),
+            ["a+b+c", "other queue+behind a's signal", "d", "held", "present", "next frame"],
+            "{:?}",
+            lane.lock().items.len()
+        );
+        look(&lane);
+        assert_eq!(log.lock().unwrap().last().unwrap(), "later");
+        let state = lane.lock();
+        assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0));
+    }
+
     /// A wait that nothing meets holds its queue until a present, which
     /// A wait that nothing meets holds its queue until a present, which
     /// comes behind everything given before it and before what comes after.
     /// comes behind everything given before it and before what comes after.
     #[test]
     #[test]