rt: a group is held only while the completion thread waits on the GPU

The submit thread holds a queue's groups while IN_FLIGHT of its submissions are not seen
complete. The completion thread marked submissions seen when it observed the GPU, then ran the
round's retirements, completed handlers and listeners, and observed nothing newer until they
ended. So a slow completed handler held every later command buffer's submission behind it.

Done now carries a busy flag. The completion thread sets it (SeqCst) for the whole retire round,
before it pokes the submit thread, and clears it before it waits on the GPU again. While it is
set, the submit thread sends held groups: goes and unheld take busy as seen. A group is held
only while the completion thread waits on the GPU. Handlers still run in order on the completion
thread, so a slow handler delays the later command buffers' retirement, status and handlers, in
that order, though not their submission. The README's grouping and completion paragraphs say
both. Metal's MTLCommandBuffer.h says nothing about handler order across command buffers, so
the README states only what rt does.

Verified: job m3-max-58790 (homelab-um870-1, lavapipe under the validation layer 1.4.363.0).
every_device_submits_while_a_completed_handler_runs FAILED with rt's src at the previous commit
(nextest exit 100, its wait timed out after 60 s) and PASSED at this one (exit 0). The compile
gate at this commit was all 0: fmt; clippy plain, --cfg m2v_gpu and --cfg m2v_cpu_icd; Windows
clippy and rt's Windows Rustdoc (gnullvm, msvc); workspace Rustdoc; the signatures check; rt's
suite on lavapipe (447 passed); metal2vulkan's api_signatures.

Measured with the validation layer off, on a probe branch not for landing: a 60 Hz compositor
loop with two writer command buffers a frame, each with a completed handler that sleeps 5 ms.
In one interleaved, exclusive job on the UHD 630 (m3-max-58733), writer commit to submitted
(p50 / p99 / max) was 191 / 233 / 449 and 206 / 232 / 564 us before the form (probes at
6121dd20a6), and 202 / 229 / 318 and 191 / 218 / 293 us with it (probes at 15c4075b55):
neither arm held there, and the form cost nothing. An earlier run before the form had held
(m3-max-58675: 64 / 1590 / 2259 us). On the Iris Xe: 316 / 535 / 596 us before (m3-max-58677)
and 313 / 511 / 564 us after (m3-max-58720).
This commit is contained in:
Anees Iqbal committed 2026-11-20 07:15:24 -08:00
1 parent 5ba6d094bf
commit 8012fff5a1
3 files changed
+49 -16

No files matched your search

+6 -2
View File
@@ -1526,7 +1526,10 @@ made, with no lock, and never rewritten for layouts.
goes at once, alone. While three are, the ones committed meanwhile are held in one group, each
scheduled as it joins, and the group goes when it holds sixteen, when a completion leaves fewer
than three in flight (the completion thread wakes the submit thread as it retires; no commit or
wait is needed), when the host is to wait for one of them (`wait_until_completed`, or
wait is needed), while the completion thread runs a round of retirements, completed handlers and
listeners (it sees no completion until the round ends: a group is held only while the completion
thread waits on the GPU, so a slow completed handler holds no later submission), when the host
is to wait for one of them (`wait_until_completed`, or
`CommandQueue::send_now`, the hint for a wait the runtime does not see), or at teardown. Waiting
for a place in the queue sends nothing. A segment that signals an event ends its group, which goes
at once, and so does a presenting command buffer's last (see "Presenting"); one that waits on an
@@ -1593,7 +1596,8 @@ made, with no lock, and never rewritten for layouts.
- The completion thread retires command buffers as the progress semaphore reaches them, a
submission's in commit order: the status, the blocks they kept, their recorders and their place
in the queue, then the completed handlers. Completed handlers and listeners run on it, in
turn. A wait in one for what that thread has not yet done is `Refusal::WaitOnOwnThread`, and one
turn, so a slow completed handler delays the later command buffers' retirement, status and
handlers, in that order, though not their submission (above). A wait in one for what that thread has not yet done is `Refusal::WaitOnOwnThread`, and one
already met answers at once: `wait_until_completed` for a command buffer not yet completed (its
own handler's command buffer has), `wait_until_scheduled` for one not yet scheduled,
`wait_until_signaled_value` for a value not yet reached (a timed wait too: it is refused, never
+17 -5
View File
@@ -14,7 +14,7 @@ use crate::submit::{Ended, Finished, Upload};
use crate::times::{self, Calibration};
use ash::vk;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};
@@ -32,6 +32,10 @@ pub(crate) struct Done {
wake: vk::Semaphore,
/// The highest progress value the completion thread has seen reached.
completed: AtomicU64,
/// The completion thread runs a round of retirements, completed handlers and listeners, from
/// the observation that began it: it sees no completion until the round ends, so the submit
/// thread holds no group meanwhile (`crate::submit`).
busy: AtomicBool,
}
struct DoneState {
@@ -210,6 +214,7 @@ impl Done {
progress,
wake,
completed: AtomicU64::new(0),
busy: AtomicBool::new(false),
})
}
@@ -235,6 +240,11 @@ impl Done {
self.completed.load(Ordering::SeqCst)
}
/// Whether the completion thread runs a round of retirements, handlers and listeners.
pub(crate) fn busy(&self) -> bool {
self.busy.load(Ordering::SeqCst)
}
/// Wakes the completion thread where it waits. With `flight_only` (the change is only more
/// work in flight), a thread that already waits for the progress semaphore is left to wait.
fn wake(&self, state: &mut DoneState, device: &ash::Device, flight_only: bool) {
@@ -572,10 +582,11 @@ pub(crate) fn run(core: Arc<Core>) {
if newly_lost {
core.work.lose();
}
if !retire.is_empty() {
// A batch kept while submissions were in flight may go.
core.work.completed();
}
// Set before the submit thread's mark is read (`Work::completed`): a group it keeps
// while submissions were in flight goes, a completion having left fewer of them, or
// this round, which sees no completion, running while it is held.
done.busy.store(true, Ordering::SeqCst);
core.work.completed();
// Each held command buffer whose waits are reached, or that retires now, is scheduled
// before any retires, so before it completes. One that retires with an error is not:
// its scheduled handlers run as it retires, as a failed submission's do. Its queue's
@@ -621,6 +632,7 @@ pub(crate) fn run(core: Arc<Core>) {
listener(value);
}
drop(fired);
done.busy.store(false, Ordering::SeqCst);
state = done.lock();
continue;
}
+26 -9
View File
@@ -6,6 +6,8 @@
//! not seen complete, each of its command buffers goes at once, alone. While that many run, the
//! ones committed meanwhile are held in one group of at most [`GROUP`], which goes when it fills,
//! when a completion leaves fewer running (the completion thread wakes the thread as it retires),
//! while the completion thread runs a round of retirements, completed handlers and listeners (it
//! sees no completion until the round ends, so a group is held only while it waits on the GPU),
//! when the host is to wait for one of them ([`Work::send`]), when a command buffer of another
//! queue that waits on a fence one of them updates is to go (`crate::fence`), or at teardown. The
//! driver runs a submission's command buffers as one kernel job, which a job timeout ends as a
@@ -1427,8 +1429,16 @@ impl WorkState {
/// group is scheduled at `now`, its scheduled handlers going to `joined`, but one that
/// presents a drawable, which `submit` schedules once its submission has passed
/// `vkQueueSubmit2`, and one held at `Committed`, which the completion thread schedules
/// ([`hold`]); one ended with nothing held goes to `ended`.
fn step(&mut self, now: u64, joined: &mut Vec<Joined>, ended: &mut Vec<Ended>) -> Step {
/// ([`hold`]); one ended with nothing held goes to `ended`. With `busy` (the completion
/// thread runs a round of retirements and handlers, `Done::busy`) a group goes as each
/// command buffer joins it, as no completion would send it until the round ends.
fn step(
&mut self,
now: u64,
busy: bool,
joined: &mut Vec<Joined>,
ended: &mut Vec<Ended>,
) -> Step {
let Some(index) = self.next_ready() else {
return Step::Idle;
};
@@ -1602,6 +1612,7 @@ impl WorkState {
group.count += 1;
let goes = signals
|| stop
|| busy
|| group.count >= GROUP
|| fifo.in_flight.len() < IN_FLIGHT
|| fifo.send_through >= group.first;
@@ -1653,11 +1664,15 @@ impl WorkState {
}
/// The first FIFO whose group goes at the end of a pass: unless its queue has [`IN_FLIGHT`]
/// submissions not seen complete and no host wait is to come for it.
fn unheld(&self) -> Option<usize> {
/// submissions not seen complete, no host wait is to come for it, and the completion thread
/// waits for the GPU (not `busy` with a round of retirements and handlers).
fn unheld(&self, busy: bool) -> Option<usize> {
self.fifos.iter().position(|fifo| {
fifo.group.as_ref().is_some_and(|group| {
self.stop || fifo.in_flight.len() < IN_FLIGHT || fifo.send_through >= group.first
self.stop
|| busy
|| fifo.in_flight.len() < IN_FLIGHT
|| fifo.send_through >= group.first
})
})
}
@@ -1890,16 +1905,18 @@ pub(crate) fn run(core: Arc<Core>) {
/// goes as it closes, then each group its queue no longer holds, then an upload to flush alone.
fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard<'a, WorkState> {
let work = &core.work;
// Marked before the completed value is read: a completion the read misses sees the mark and
// wakes the thread.
// Marked before the completed value and the completion thread's busy mark are read: a
// completion the read misses, or a round of the completion thread's begun after its read,
// sees the mark and wakes the thread.
work.keeping.store(true, Ordering::SeqCst);
state.settle(core.done.completed());
let mut joined: Vec<Joined> = Vec::new();
let mut ended: Vec<Ended> = Vec::new();
let mut sent = false;
loop {
let index = match state.step(times::host_time(), &mut joined, &mut ended) {
Step::Idle => match state.unheld() {
let busy = core.done.busy();
let index = match state.step(times::host_time(), busy, &mut joined, &mut ended) {
Step::Idle => match state.unheld(busy) {
Some(index) => index,
None => break,
},