rt: a queue's command buffers behind one held for a shared event stay Committed, in order

What: a command buffer that joins a submission while an earlier command buffer of its queue is
held at Committed (its wait for a shared event's value not yet reached) is held too, waits or
none, and the completion thread schedules a queue's held command buffers in submission order:
each once its own waits are reached and the ones before it are scheduled, its scheduled handlers
run, or as it retires. The queue counts its held command buffers (QueueInner::held); the count
falls only after the earlier one's status is set and its handlers have run, so a later command
buffer of the queue never reads Scheduled first. A command buffer with nothing for the GPU takes
the same hold. Submission is unchanged: only when Scheduled is reported moves.

Why: Metal, on an M3 Max (macOS 27.0.1), six runs of six: the next command buffer on the
waiter's queue, waiting for nothing, reads as the waiter does. Behind a wait for an
MTLSharedEvent's value it reads Committed with no scheduled handler run; behind a wait for an
MTLEvent's value, Scheduled with its handler run. Apple's definition of Scheduled ("All
dependencies have been resolved and the command buffer has been scheduled for execution") with a
queue's in-order scheduling gives the same.

Test: every_device_schedules_a_wait_for_a_shared_event_once_its_value_is_reached now commits a
"next" command buffer behind each waiter: the plain pair both Scheduled with handlers; the shared
pair both Committed with no handler until the host sets the value, then both Scheduled in order;
and the held one under the completion hold stays Committed after the queue goes idle. The loss
test waits for the submission count instead of Scheduled.

Verified: cargo fmt only here; the check, the negative, lavapipe, the GPU legs, KosmicKrisp and
the UHD 630 run as chain events2.
This commit is contained in:
Anees Iqbal committed 2026-11-19 01:21:10 -08:00
1 parent deca5649b3
commit 80bebc8c3f
7 files changed
+185 -78

No files matched your search

+4 -2
View File
@@ -856,11 +856,13 @@ made, with no lock, and never rewritten for layouts.
"Presenting"). One that waits for a shared event's value not yet reached when its last segment
joins a submission stays `Committed` until the value is: the completion thread schedules it, and
runs its scheduled handlers, once it sees the signal land or the host set the value, and before
it completes where its own completion comes first. Apple defines `Scheduled` as "All dependencies
it completes where its own completion comes first. Its queue's later command buffers stay
`Committed` behind it, waits or none, and are scheduled after it in order. Apple defines `Scheduled` as "All dependencies
have been resolved and the command buffer has been scheduled for execution", and Metal applies
it so to shared-event waits only: recorded on the M3 Max, a command buffer behind a signal still
running reads `Committed` with no handler where it waits for an `MTLSharedEvent`, and `Scheduled`
with its scheduled handler run where it waits for an `MTLEvent`, as here. A command buffer whose
with its scheduled handler run where it waits for an `MTLEvent`, as here; the next command buffer
on its queue, which waits for nothing, reads as it does. A command buffer whose
segments hold no commands, no event wait and no event signal takes no submission: the submit thread schedules it as it reaches it, and it completes
with its queue's command buffer before it, in flight, or at once where that one has completed. Where that one is in a group held, it joins the group, which
goes at once, so its completion waits only on submitted work.
+9 -6
View File
@@ -64,8 +64,9 @@ pub enum CommandBufferStatus {
/// has passed `vkQueueSubmit2`. One that waits for a [`SharedEvent`](crate::SharedEvent)'s
/// value not yet reached when its last segment joins a submission is scheduled once the value
/// is, as the completion thread sees the signal or the host's set, and always before it
/// completes. Apple defines the status as "All dependencies have been resolved and the command
/// buffer has been scheduled for execution"; Metal applies that to a shared event's wait only
/// completes; its queue's later command buffers are scheduled after it, in order. Apple
/// defines the status as "All dependencies have been resolved and the command buffer has been
/// scheduled for execution"; Metal applies that to a shared event's wait only
/// ([`Device::new_shared_event`](crate::Device::new_shared_event)).
Scheduled,
/// `MTLCommandBufferStatusCompleted`.
@@ -282,9 +283,11 @@ pub(crate) struct Pending {
pub(crate) handlers: Handlers,
/// It took a pair of timestamp queries.
pub(crate) timed: bool,
/// Its waits for a shared event's value not reached when its last segment joined a
/// submission: it is scheduled once they are (`crate::complete`), not as it joins.
pub(crate) held: Vec<(Arc<EventInner>, u64)>,
/// Where it is held at `Committed` as its last segment joins a submission, scheduled by the
/// completion thread rather than as it joins (`crate::complete`): its waits for a shared
/// event's value not reached then, none where it is held only behind an earlier command
/// buffer of its queue that is held.
pub(crate) held: Option<Vec<(Arc<EventInner>, u64)>>,
}
impl Pending {
@@ -616,7 +619,7 @@ impl CommandBuffer {
gpu,
handlers,
timed: stamps.is_some(),
held: Vec::new(),
held: None,
};
state.status = CommandBufferStatus::Committed;
self.inner.changed.notify_all();
+56 -23
View File
@@ -8,6 +8,7 @@ use crate::counters::Metric;
use crate::device::{lock, Core};
use crate::error::Error;
use crate::event::{self, EventInner, Listener};
use crate::queue::QueueInner;
use crate::submit::{Ended, Finished, Upload};
use crate::times::{self, Calibration};
use ash::vk;
@@ -41,8 +42,9 @@ struct DoneState {
watched: Vec<Arc<EventInner>>,
/// Events whose listeners, or whose held command buffers' waits, a host value may reach.
fire: Vec<Arc<EventInner>>,
/// Submitted command buffers held at `Committed` for a shared event's value
/// (`Pending::held`), each scheduled once its waits are reached, or as it retires.
/// Submitted command buffers held at `Committed` (`Pending::held`), in their submission order:
/// each scheduled once its waits are reached and its queue's held ones before it are
/// scheduled, or as it retires.
held: Vec<Held>,
waiting: Waiting,
/// The wake semaphore's last value.
@@ -68,8 +70,28 @@ struct Retiree {
item: Item,
}
/// A command buffer held at `Committed` for a shared event's value: its waits and its scheduled
/// handlers.
impl DoneState {
/// `cb`, held at `Committed` with `waits`, taking its scheduled handlers from `handlers`: the
/// thread looks at it from its next round.
fn hold(
&mut self,
cb: &Arc<CbInner>,
waits: Vec<(Arc<EventInner>, u64)>,
handlers: &mut Handlers,
) {
for (event, _) in &waits {
lock(&event.state).holds += 1;
}
self.held.push(Held {
cb: Arc::clone(cb),
waits,
scheduled: std::mem::take(&mut handlers.scheduled),
});
}
}
/// A command buffer held at `Committed`: its waits for a shared event's value (none for one held
/// only behind an earlier one of its queue) and its scheduled handlers.
struct Held {
cb: Arc<CbInner>,
waits: Vec<(Arc<EventInner>, u64)>,
@@ -83,14 +105,26 @@ impl Held {
}
}
/// Takes out of `held` the command buffers to schedule now: those whose waits are reached, and
/// those that retire in `retire`, which are scheduled, where they ran, before they complete. Each
/// event's count of held waits falls with them.
/// Takes out of `held` the command buffers to schedule now, in order: those whose waits are
/// reached with no held one of their queue left before them, and those that retire in `retire`,
/// which are scheduled, where they ran, before they complete. Each event's count of held waits
/// falls with them; each queue's count of held command buffers falls once each is scheduled.
fn due(held: &mut Vec<Held>, retire: &[Retiree]) -> Vec<Held> {
let due: Vec<Held> = (held.extract_if(.., |entry| {
entry.reached() || retire.iter().any(|retiree| retiree.is(&entry.cb))
}))
.collect();
// The queues with a held command buffer left, by address: a later one of each waits for it.
let mut blocked: Vec<*const QueueInner> = Vec::new();
let mut due = Vec::new();
let mut index = 0;
while index < held.len() {
let entry = &held[index];
let queue = Arc::as_ptr(&entry.cb.queue);
let retires = retire.iter().any(|retiree| retiree.is(&entry.cb));
if retires || (entry.reached() && !blocked.contains(&queue)) {
due.push(held.remove(index));
} else {
blocked.push(queue);
index += 1;
}
}
for (event, _) in due.iter().flat_map(|entry| &entry.waits) {
lock(&event.state).holds -= 1;
}
@@ -244,16 +278,8 @@ impl Done {
held,
..
} = pending;
// Held at `Committed`: the thread looks at its waits from its next round.
if !held.is_empty() {
for (event, _) in &held {
lock(&event.state).holds += 1;
}
state.held.push(Held {
cb: Arc::clone(&cb),
waits: held,
scheduled: std::mem::take(&mut handlers.scheduled),
});
if let Some(waits) = held {
state.hold(&cb, waits, &mut handlers);
flight_only = false;
}
state.flight.push_back(Retiree {
@@ -284,9 +310,13 @@ impl Done {
let Pending {
value,
gpu,
handlers,
mut handlers,
held,
..
} = pending;
if let Some(waits) = held {
state.hold(&cb, waits, &mut handlers);
}
let retiree = Retiree {
value,
item: Item::Command {
@@ -536,8 +566,10 @@ pub(crate) fn run(core: Arc<Core>) {
}
// 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 scheduled handlers run as it retires, as a failed submission's do. Its queue's
// later command buffers are held behind it until then, its handlers run.
for Held { cb, scheduled, .. } in due {
let queue = Arc::clone(&cb.queue);
match retire.iter_mut().find_map(|retiree| retiree.failed(&cb)) {
Some(handlers) => handlers.scheduled = scheduled,
None => {
@@ -547,6 +579,7 @@ pub(crate) fn run(core: Arc<Core>) {
}
}
}
queue.held.fetch_sub(1, Ordering::SeqCst);
}
// Handlers and listeners run with no lock held.
// Each completed command buffer's timestamps are placed on the host clock by the
+3 -1
View File
@@ -111,7 +111,9 @@ impl Device {
/// runs alike), a command buffer committed on another queue behind one whose signal still runs
/// (that one `Scheduled`, its signal not landed) reads `Scheduled` with its scheduled handler
/// run where it waits for an `MTLEvent`, and `Committed` with no handler run and the value 0
/// where it waits for an `MTLSharedEvent`.
/// where it waits for an `MTLSharedEvent`. The next command buffer on its queue, which waits
/// for nothing, reads the same as it, six runs of six: so a queue's later command buffers are
/// scheduled after a held one here, in order.
///
/// Err: [`Error::Vulkan`] where the semaphore cannot be made.
pub fn new_shared_event(&self) -> Result<SharedEvent, Error> {
+6 -1
View File
@@ -5,7 +5,7 @@ use crate::counters::{Counters, Gauge};
use crate::device::{lock, Core, Device};
use crate::error::{Error, Refusal};
use crate::kept::Objects;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError, Weak};
/// `MTLCommandQueue`: one FIFO on the submit thread. Every queue submits to the device's one
@@ -32,6 +32,10 @@ pub(crate) struct QueueInner {
/// the next one's kernel start is placed at the latest, as Metal schedules a queue's command
/// buffers in order.
pub(crate) last_scheduled: AtomicU64,
/// Its command buffers submitted and held at `Committed` (`Pending::held`), not yet
/// scheduled: while any is, a later one of the queue is held behind it, as Metal schedules a
/// queue's command buffers in order.
pub(crate) held: AtomicUsize,
/// The GPU run, in nanoseconds, its next command buffer is expected to take
/// ([`expected_run`](Self::expected_run)); `u64::MAX` before one of its command buffers
/// retired with its GPU times.
@@ -76,6 +80,7 @@ impl Device {
room: Condvar::new(),
last_end: AtomicU64::new(0),
last_scheduled: AtomicU64::new(0),
held: AtomicUsize::new(0),
run: AtomicU64::new(u64::MAX),
retired: AtomicU64::new(0),
counters: core.counters.clone(),
+33 -22
View File
@@ -1446,9 +1446,8 @@ impl WorkState {
/// ended command buffer behind its queue's work. A command buffer whose last segment joins a
/// 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 that waits for a shared event's value not yet reached, which the
/// completion thread schedules once it is ([`held`]); one ended with nothing held goes to
/// `ended`.
/// `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 {
let Some(index) = self.next_ready() else {
return Step::Idle;
@@ -1476,8 +1475,9 @@ impl WorkState {
let Some(pending) = entry.pending.as_mut() else {
return Step::Idle;
};
// A command buffer with nothing for the GPU takes no submission: it is scheduled now and
// completes with its queue's work before it.
// A command buffer with nothing for the GPU takes no submission: it is scheduled now, or
// behind its queue's command buffer held ([`hold`]), and completes with its queue's work
// before it.
if pending.gpu.is_empty() {
if let Some(Entry {
cb,
@@ -1485,10 +1485,13 @@ impl WorkState {
..
}) = fifo.entries.pop_front()
{
cb.scheduled(now);
let scheduled = std::mem::take(&mut pending.handlers.scheduled);
if !scheduled.is_empty() {
joined.push((Arc::clone(&cb), scheduled));
pending.held = hold(&fifo.queue, &pending.gpu);
if pending.held.is_none() {
cb.scheduled(now);
let scheduled = std::mem::take(&mut pending.handlers.scheduled);
if !scheduled.is_empty() {
joined.push((Arc::clone(&cb), scheduled));
}
}
fifo.behind_held(cb, pending, None, ended);
}
@@ -1625,8 +1628,8 @@ impl WorkState {
else {
return Step::Staged;
};
pending.held = held(&pending.gpu);
if !pending.gpu.presents() && pending.held.is_empty() {
pending.held = hold(&fifo.queue, &pending.gpu);
if !pending.gpu.presents() && pending.held.is_none() {
cb.scheduled(now);
let scheduled = std::mem::take(&mut pending.handlers.scheduled);
if !scheduled.is_empty() {
@@ -1766,18 +1769,26 @@ impl Fifo {
}
}
/// The waits of `gpu`'s segments for a shared event's value the host does not yet see reached,
/// as its last segment joins a submission: its command buffer stays `Committed` until the
/// completion thread sees each reached (`Pending::held`). Metal holds a command buffer that waits
/// for an `MTLSharedEvent`'s value at `Committed`, with no scheduled handler run, while the
/// signal it waits for runs, and schedules one that waits for an `MTLEvent`'s, so a plain event's
/// wait holds nothing here.
fn held(gpu: &Gpu) -> Vec<(Arc<EventInner>, u64)> {
(gpu.segments.iter())
/// Whether a command buffer of `queue` whose segments are `gpu`'s is held at `Committed` as its
/// last segment joins a submission, and so counted in the queue's held ones: with its waits for a
/// shared event's value the host does not yet see reached, or with none behind a command buffer of
/// its queue held already. The completion thread schedules it once each wait is reached and the
/// queue's held ones before it are scheduled (`Pending::held`). Metal holds a command buffer that
/// waits for an `MTLSharedEvent`'s value at `Committed`, with no scheduled handler run, while the
/// signal it waits for runs, and the queue's next command buffer with it, though that one waits
/// for nothing; it schedules one that waits for an `MTLEvent`'s value, so a plain event's wait
/// holds nothing here.
fn hold(queue: &QueueInner, gpu: &Gpu) -> Option<Vec<(Arc<EventInner>, u64)>> {
let waits: Vec<(Arc<EventInner>, u64)> = (gpu.segments.iter())
.flat_map(|segment| &segment.waits)
.filter(|(event, value)| event.shared && !event.reached(*value))
.map(|(event, value)| (Arc::clone(event), *value))
.collect()
.collect();
let behind = queue.held.load(Ordering::SeqCst) > 0;
(behind || !waits.is_empty()).then(|| {
queue.held.fetch_add(1, Ordering::SeqCst);
waits
})
}
/// Whether every wait of `segment` is met by the host's value or by a submitted signal.
@@ -2145,10 +2156,10 @@ fn submit(core: &Core, value: u64, upload: Option<Upload>, batch: Batch) {
// its own scheduled handlers' included, waits on a submitted signal. They run before the
// completion thread learns of it below, so before its completed handlers. One whose
// submission failed is not scheduled; its scheduled handlers run as it retires. One held
// for a shared event's value is scheduled by the completion thread ([`held`]).
// at `Committed` is scheduled by the completion thread ([`hold`]).
let now = times::host_time();
for (cb, pending, error) in &mut finished {
if error.is_none() && pending.gpu.presents() && pending.held.is_empty() {
if error.is_none() && pending.gpu.presents() && pending.held.is_none() {
cb.scheduled(now);
let scheduled = std::mem::take(&mut pending.handlers.scheduled);
if !scheduled.is_empty() {
+74 -23
View File
@@ -894,15 +894,24 @@ pub(crate) mod on_device {
/// stays `Committed`, no scheduled handler run, until the value is reached, and is scheduled
/// before it completes: by the host's set of the value, while its GPU wait still holds it, and
/// where the value arrives only as it completes (the completion thread held meanwhile), in
/// the round that retires it. A wait for a plain event's value submitted so is scheduled as
/// it is submitted. Metal answers so (`event-wait-behind-a-running-signal`, recorded on the M3
/// Max): `Committed` with no handler for an `MTLSharedEvent`, `Scheduled` with its scheduled
/// handler run for an `MTLEvent`.
/// the round that retires it. The queue's next command buffer, which waits for nothing, stays
/// `Committed` with it and is scheduled after it. A wait for a plain event's value submitted
/// so is scheduled as it is submitted, and so is the next command buffer. Metal answers so
/// (`event-wait-behind-a-running-signal`, recorded on the M3 Max, and the next command buffer
/// read by probe 0f13fbc709, job m3-max-50646): `Committed` with no handler, the next one too,
/// for an `MTLSharedEvent`; `Scheduled` with its scheduled handler run, the next one too, for
/// an `MTLEvent`.
#[test]
fn every_device_schedules_a_wait_for_a_shared_event_once_its_value_is_reached() {
each_device("shared_wait_scheduled", |name, _, device| {
let mut arena = Arena::new(&device);
let (a, b, c) = (arena.buffer(), arena.buffer(), arena.buffer());
let (a, b, c, d, e) = (
arena.buffer(),
arena.buffer(),
arena.buffer(),
arena.buffer(),
arena.buffer(),
);
let queue = queue(&device);
let log = Log::default();
let signal = |semaphore: vk::Semaphore| {
@@ -912,11 +921,13 @@ pub(crate) mod on_device {
// SAFETY: the semaphore is the device's, and 1 is above its value.
unsafe { device.raw().device.signal_semaphore(&signal) }.expect("a host signal");
};
// Commits a command buffer that waits for `event` at 1 and fills `buffer`, and
// returns it once its submission is counted.
let waiting = |label: &str, event: &crate::Event, buffer: &Buffer, word| {
// Commits a command buffer that waits for `event` at 1, where there is one, and fills
// `buffer`, and returns it once its submission is counted.
let waiting = |label: &str, event: Option<&crate::Event>, buffer: &Buffer, word| {
let command_buffer = queue.command_buffer().expect("a command buffer");
(command_buffer.encode_wait_for_event(event, 1)).expect("a wait");
if let Some(event) = event {
(command_buffer.encode_wait_for_event(event, 1)).expect("a wait");
}
fill(&command_buffer, buffer, word);
log.handlers(label, &command_buffer);
let before = device.counters().metrics().submissions;
@@ -928,29 +939,61 @@ pub(crate) mod on_device {
// A plain event's wait: scheduled as it is submitted.
let plain = device.new_event().expect("an event");
plain.pretend_submitted_for_test(1);
let on_plain = waiting("plain", &plain, &a, 1);
assert_eq!(on_plain.status(), CommandBufferStatus::Scheduled, "{name}");
assert_eq!(log.lines(), ["plain scheduled Scheduled"], "{name}");
let on_plain = waiting("plain", Some(&plain), &a, 1);
let next = waiting("plain next", None, &d, 4);
assert_eq!(
(on_plain.status(), next.status()),
(
CommandBufferStatus::Scheduled,
CommandBufferStatus::Scheduled
),
"{name}"
);
assert_eq!(
log.lines(),
[
"plain scheduled Scheduled",
"plain next scheduled Scheduled"
],
"{name}"
);
signal(plain.inner().semaphore);
finished(name, &on_plain);
finished(name, &next);
// A shared event's: held at `Committed` until the host sets the value, then scheduled
// while its GPU wait, on the semaphore, still holds it.
let shared = shared_event(&device);
shared.pretend_submitted_for_test(1);
let on_set = waiting("set", shared.as_event(), &b, 2);
let on_set = waiting("set", Some(shared.as_event()), &b, 2);
let next = waiting("set next", None, &e, 5);
assert_eq!(
on_set.status(),
CommandBufferStatus::Committed,
"{name}: held"
(on_set.status(), next.status()),
(
CommandBufferStatus::Committed,
CommandBufferStatus::Committed
),
"{name}: held, and the next one behind it"
);
assert_eq!(log.lines().len(), 2, "{name}: no scheduled handler");
assert_eq!(log.lines().len(), 4, "{name}: no scheduled handler");
shared.set_signaled_value(1);
(on_set.wait_until_scheduled()).expect("a wait outside a scheduled handler");
assert_eq!(on_set.status(), CommandBufferStatus::Scheduled, "{name}");
assert_eq!(log.lines()[2..], ["set scheduled Scheduled"], "{name}");
(next.wait_until_scheduled()).expect("a wait outside a scheduled handler");
assert_eq!(
(on_set.status(), next.status()),
(
CommandBufferStatus::Scheduled,
CommandBufferStatus::Scheduled
),
"{name}: their GPU waits, on the semaphore, still hold them"
);
assert_eq!(
log.lines()[4..],
["set scheduled Scheduled", "set next scheduled Scheduled"],
"{name}"
);
signal(shared.as_event().inner().semaphore);
finished(name, &on_set);
finished(name, &next);
// A shared event's value that arrives only as the command buffer completes: the
// completion thread, held meanwhile, schedules it in the round that retires it.
@@ -958,7 +1001,7 @@ pub(crate) mod on_device {
late.pretend_submitted_for_test(1);
let core = device.core();
let hold = core.hold_completions.write().expect("the hold");
let on_late = waiting("late", late.as_event(), &c, 3);
let on_late = waiting("late", Some(late.as_event()), &c, 3);
assert_eq!(
on_late.status(),
CommandBufferStatus::Committed,
@@ -981,16 +1024,24 @@ pub(crate) mod on_device {
log.lines(),
[
"plain scheduled Scheduled",
"plain next scheduled Scheduled",
"plain completed Completed None",
"plain next completed Completed None",
"set scheduled Scheduled",
"set next scheduled Scheduled",
"set completed Completed None",
"set next completed Completed None",
"late scheduled Scheduled",
"late completed Completed None",
],
"{name}"
);
assert_eq!((word(&a), word(&b), word(&c)), (1, 2, 3), "{name}");
drop((a, b, c, arena, plain, shared, late, queue, device));
assert_eq!(
[&a, &b, &c, &d, &e].map(word),
[1, 2, 3, 4, 5],
"{name}: every fill ran"
);
drop((a, b, c, d, e, arena, plain, shared, late, queue, device));
});
}