rt: no semaphore wait is submitted for an event's value

What: stage() no longer adds a semaphore wait to a segment for its waits on events' values. The
rule that a waiting segment leads its group goes with it. Unchanged:
- ready(), which holds a wait until the host's value meets it or a signal of its value is
  submitted;
- the events' signals, which signaled_value, host waits and listeners read;
- the presenting command buffer's binary signal;
- the sparse bind's timeline wait.
A segment that only waits now adds nothing to its submission.

Why: every wait rt submitted named a signal earlier in the same VkQueue's submission order:
- every guest queue submits on core.queues.runtime;
- ready() passes a wait only once its signal is staged, and staging a signal sends its group at
  once.
Every segment with commands ends in a global VkMemoryBarrier2 (record::end), from ALL_COMMANDS
with MEMORY_WRITE to ALL_COMMANDS with MEMORY_READ|MEMORY_WRITE, plus HOST where the segment
signals. A signal sits at the end of its segment, so its barrier orders every later command after
the signaller's, the waiter's TOP_OF_PIPE start timestamp included (vkspec 9465, 9481,
42773-42775). So the semaphore pair defined no dependency the barriers did not. The submitted wait
only made the driver wait on a value. On the RTX 2080 walk that came to a waiter starting 0.38 ms
p50 after its signaller's GPU end, against a 0.2 ms GPU run. The sparse bind's wait stays because
sparse binding is "not automatically ordered against command buffer execution, even within a
single queue" (vkspec 70233).

Tests: three tests held the GPU by waiting on a pretended signal that the host later gave; that
form no longer holds anything. They now hold the device with the busy work's gate batch, whose
wait holds every later command:
- the scheduled-as-submitted test: the waiter's value is now a real signal of another queue,
  submitted and not yet run;
- the device-loss test: its in-flight command buffer is held the same way;
- the chain test: each link copies the words of every link before it from the previous link's
  buffer and writes its own, so a link run before the one it waits on leaves wrong words. It
  checks that the links complete in order with every word right.
pretend_submitted_for_test had no other use and is deleted.

Docs: encode_wait_for_event, CommandBufferStatus::Scheduled, Device::new_shared_event, the
runtime README's submission and event paragraphs, and the infos() and stage() docs.

Effect on presents per second: not known until the walk at the pin.

How verified: the lane's compile gate (fmt, clippy in three cfgs, Windows clippy, Rustdoc,
signatures, the runtime suite on lavapipe).
This commit is contained in:
Anees Iqbal committed 2026-11-20 09:46:52 -08:00
1 parent a640235b0c
commit a075319ea1
5 files changed
+123 -113

No files matched your search

+10 -6
View File
@@ -1549,7 +1549,7 @@ made, with no lock, and never rewritten for layouts.
A commit only takes its number; the first call after it begins the next upload, and the
submission ends the last upload it carries with the one barrier that makes their writes visible
and records the moves home of every texture they keep in one barrier. Consecutive command
buffers that no event wait or signal separates share one submit info, the uploads with the
buffers that no event signal separates share one submit info, the uploads with the
first: the GPU runs them in order either way, and a driver may pay for each info (the UHD 630's
paid about 160 us apiece). `Metrics::submit_infos` counts them. The uploads not yet submitted
record at most 4,096 calls and keep at most 64 MiB on their own account: the staging buffers of
@@ -1602,8 +1602,10 @@ made, with no lock, and never rewritten for layouts.
a submission: passed to `vkQueueSubmit2`, or in a group held; a command buffer that presents a
drawable is never held, and is scheduled once its submission has passed `vkQueueSubmit2` (see
"Presenting"). One that waits for an event's value whose signal is submitted, of an `Event` or
a `SharedEvent`, is scheduled so too, while the GPU still waits for the value: the wait goes to
the driver with the submission, and the queue's later command buffers go behind it. Apple's
a `SharedEvent`, is scheduled so too, while its commands wait on the GPU for the signaller's:
every queue submits on the device's one `VkQueue`, so the signal's submission is earlier in its
submission order, and the barrier ending each segment orders every later command after the
signaller's, so no semaphore wait is submitted for an event's value. Apple's
MTLCommandBuffer.h describes `Scheduled` as "All dependencies have been resolved and the command
buffer has been scheduled for execution" (lines 47-48), and `encodeWaitForEvent:value:` as a
command that "pauses execution of this command buffer until the specified event reaches a given
@@ -1689,9 +1691,11 @@ made, with no lock, and never rewritten for layouts.
commands, or whose last segment has none, records a `VkCommandBuffer` for its timestamps. One
that ends with an error has GPU times of 0.
- `Event` and `SharedEvent` are timeline semaphores whose values are Metal's values. A host set
(`SharedEvent::set_signaled_value`) raises a floor and never signals the semaphore; a wait the
floor meets is submitted with no semaphore wait, and a GPU signal not above the highest value
submitted or set is left out, so the semaphore only rises and never races a host set.
(`SharedEvent::set_signaled_value`) raises a floor and never signals the semaphore. A wait
submits no semaphore wait: it is held until the floor meets it or a signal of its value is
submitted, earlier on the one `VkQueue`, whose segment's end barrier orders the waiter's commands
after the signaller's. A GPU signal not above the highest value submitted or set is left out, so
the semaphore only rises and never races a host set.
`signaled_value` is the higher of the semaphore and the floor. `notify_listener` runs its
listener on the completion thread when the value is reached, at a signal in the middle of a
command buffer as well as at its end; `wait_until_signaled_value` wakes then too.
+6 -4
View File
@@ -62,8 +62,8 @@ pub enum CommandBufferStatus {
/// goes with no other call. A command buffer that presents a drawable
/// ([`CommandBuffer::present_drawable`]) is never held: it is scheduled once its submission
/// has passed `vkQueueSubmit2`. One that waits for an event's value, an [`Event`]'s or a
/// [`SharedEvent`](crate::SharedEvent)'s, is scheduled so too, while the GPU still waits for
/// the value: MTLCommandBuffer.h describes the status as "All dependencies have been resolved
/// [`SharedEvent`](crate::SharedEvent)'s, is scheduled so too, while its commands wait on the
/// GPU for the signaller's: MTLCommandBuffer.h describes the status as "All dependencies have been resolved
/// and the command buffer has been scheduled for execution", and `encodeWaitForEvent:value:`
/// as a command that "pauses execution of this command buffer until the specified event
/// reaches a given value", so execution pauses after scheduling. What differs: the M3 Max
@@ -416,8 +416,10 @@ impl CommandBuffer {
/// `encodeWaitForEvent:value:`: the commands after it run once the event reaches `value`.
///
/// The submit thread holds this segment, and its queue behind it, until the host's value
/// reaches `value` (then no semaphore wait is submitted) or a signal of at least `value` is
/// submitted (then the segment waits on the semaphore). Other queues go on.
/// reaches `value` or a signal of at least `value` is submitted. No semaphore wait is
/// submitted: every queue's command buffers go to the device's one `VkQueue`, so the signal's
/// submission is earlier in its submission order, and the barrier ending each segment orders
/// every later command after the signaller's. Other queues go on.
///
/// Err: [`Refusal::Committed`]; [`Refusal::OtherDevice`] for another device's event;
/// [`Error::Vulkan`] where ending the segment's commands fails.
+3 -18
View File
@@ -88,8 +88,9 @@ impl Device {
/// `newSharedEvent`.
///
/// A command buffer that waits for a value of it is `Scheduled` as it is submitted, while the
/// GPU still waits for the value, as one that waits for an [`Event`]'s value is: Apple's
/// A command buffer that waits for a value of it is `Scheduled` as it is submitted, while its
/// commands wait on the GPU for the signaller's, as one that waits for an [`Event`]'s value
/// is: Apple's
/// MTLCommandBuffer.h describes `MTLCommandBufferStatusScheduled` as "All dependencies have
/// been resolved and the command buffer has been scheduled for execution", and
/// `encodeWaitForEvent:value:` as a command that "pauses execution of this command buffer
@@ -239,22 +240,6 @@ impl SharedEvent {
pub fn as_event(&self) -> &Event {
&self.event
}
/// For the device tests: records a GPU signal of `value` as submitted, so a wait for it waits
/// on the semaphore, which the test then signals from the host.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn pretend_submitted_for_test(&self, value: u64) {
self.event.pretend_submitted_for_test(value);
}
}
impl Event {
/// As [`SharedEvent::pretend_submitted_for_test`].
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn pretend_submitted_for_test(&self, value: u64) {
let mut state = lock(&self.inner.state);
state.submitted = state.submitted.max(value);
}
}
impl EventInner {
+8 -21
View File
@@ -460,8 +460,8 @@ pub(crate) struct Info<'a> {
}
/// The submit infos of a submission's segments, in order: a segment that waits on nothing joins
/// the info before it where that one signals nothing, so only an event wait or signal starts a new
/// one. The GPU runs the command buffers of one info in order, as it runs those of consecutive
/// the info before it where that one signals nothing, so only a signal, or the wait for a sparse
/// bind, starts a new one. The GPU runs the command buffers of one info in order, as it runs those of consecutive
/// infos, and a driver may pay for each info: the UHD 630's paid about 160 us apiece (probe
/// 06860a3848, job m3-max-43935).
pub(crate) fn infos(segments: &[Staged]) -> Vec<Info<'_>> {
@@ -1501,12 +1501,6 @@ impl WorkState {
return Step::Staged;
}
let segment = &pending.gpu.segments[pending.next];
// A segment that waits on a semaphore leads its group: a driver that merges a submission's
// entries gathers their waits ahead of the first one's commands.
let waits = (segment.waits.iter()).any(|(event, value)| lock(&event.state).floor < *value);
if waits && fifo.group.is_some() {
return Step::Goes(index);
}
// A segment that leans on the leading copy for a buffer an earlier segment of the group
// wrote leads its group, so its copy follows the write (`crate::over`).
if (fifo.group.as_ref()).is_some_and(|group| group.leans.conflicts(&segment.overs)) {
@@ -1758,7 +1752,10 @@ fn ready(segment: &Segment) -> bool {
})
}
/// A ready segment's submit info. A wait the host's value meets submits no semaphore wait; a
/// A ready segment's submit info. Its waits for events' values submit nothing: a ready segment's
/// every wait is met by the host's value or by a signal already submitted on the device's one
/// `VkQueue`, earlier in its submission order, and the barrier ending each segment with commands
/// (`record::end`) orders every later command after the signaller's, as a semaphore wait would. A
/// signal not above the highest value submitted or set is left out, so the semaphore only rises.
/// The consumer's binary semaphores of a presenting command buffer's last segment are signalled
/// with it.
@@ -1769,17 +1766,6 @@ fn stage(segment: &Segment, watch: &mut Vec<Arc<EventInner>>) -> Staged {
.map(|command| vk::CommandBufferSubmitInfo::default().command_buffer(command)),
..Staged::default()
};
for (event, value) in &segment.waits {
if lock(&event.state).floor >= *value {
continue;
}
staged.waits.push(
vk::SemaphoreSubmitInfo::default()
.semaphore(event.semaphore)
.value(*value)
.stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS),
);
}
for (event, value) in &segment.signals {
let mut state = lock(&event.state);
if *value <= state.submitted.max(state.floor) {
@@ -2199,7 +2185,8 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
}
let began = times::host_time();
// SAFETY: every command buffer is executable and in no other pending submission;
// every wait is on a signal submitted earlier, and every signal raises its semaphore;
// the one wait, a sparse bind's, is on a signal submitted earlier, and every signal
// raises its semaphore;
// the queue is held.
ok = unsafe { device.queue_submit2(*queue, &infos, vk::Fence::null()) }.is_ok();
let nanos = times::host_time().saturating_sub(began);
@@ -960,8 +960,8 @@ pub(crate) mod on_device {
}
/// A command buffer whose wait for an event's value is met only by a submitted signal not yet
/// run (one the test makes as if submitted, then gives from the host) is `Scheduled` as it is
/// submitted, its scheduled handler run, while the GPU still waits for the value, and so is the
/// run (another queue's, held with every later command behind busy work) is `Scheduled` as it
/// is submitted, its scheduled handler run, while the signal has not run, and so is the
/// queue's next command buffer, which waits for nothing: for a plain event's value and for a
/// shared event's alike. MTLCommandBuffer.h describes `Scheduled` as "All dependencies have
/// been resolved and the command buffer has been scheduled for execution", and
@@ -978,14 +978,12 @@ pub(crate) mod on_device {
arena.buffer(),
arena.buffer(),
);
let queue = queue(&device);
let (queue, signaller_queue) = (queue(&device), self::queue(&device));
let log = Log::default();
let signal = |semaphore: vk::Semaphore| {
let signal = vk::SemaphoreSignalInfo::default()
.semaphore(semaphore)
.value(1);
// SAFETY: the semaphore is the device's, and 1 is above its value.
unsafe { device.raw().device.signal_semaphore(&signal) }.expect("a host signal");
let submitted = |command_buffer: &CommandBuffer| {
let before = device.counters().metrics().submissions;
command_buffer.commit().expect("a commit");
within(name, || device.counters().metrics().submissions > before);
};
// 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.
@@ -996,9 +994,7 @@ pub(crate) mod on_device {
}
fill(&command_buffer, buffer, word);
log.handlers(label, &command_buffer);
let before = device.counters().metrics().submissions;
command_buffer.commit().expect("a commit");
within(name, || device.counters().metrics().submissions > before);
submitted(&command_buffer);
command_buffer
};
let plain = device.new_event().expect("an event");
@@ -1007,7 +1003,10 @@ pub(crate) mod on_device {
("plain", &plain, (&a, &b), 1),
("shared", shared.as_event(), (&c, &d), 3),
] {
event.pretend_submitted_for_test(1);
let busy = Busy::new(&device);
let signaller = signaller_queue.command_buffer().expect("a command buffer");
(signaller.encode_signal_event(event, 1)).expect("a signal");
submitted(&signaller);
let waiter = waiting(label, Some(event), buffer, word);
let next_label = format!("{label} next");
let next = waiting(&next_label, None, next_buffer, word + 1);
@@ -1017,7 +1016,7 @@ pub(crate) mod on_device {
CommandBufferStatus::Scheduled,
CommandBufferStatus::Scheduled
),
"{name}: {label}: scheduled as submitted, the GPU wait still holding them"
"{name}: {label}: scheduled as submitted, the signal not yet run"
);
// A scheduled handler runs after its command buffer's status reads `Scheduled`.
within(name, || log.lines().len() == 2);
@@ -1029,28 +1028,44 @@ pub(crate) mod on_device {
],
"{name}: {label}"
);
signal(event.inner().semaphore);
finished(name, &waiter);
finished(name, &next);
busy.open();
for command_buffer in [&signaller, &waiter, &next] {
finished(name, command_buffer);
}
within(name, || log.lines().len() == 4);
lock(&log.0).clear();
drop(busy);
}
assert_eq!(
[&a, &b, &c, &d].map(word),
[1, 2, 3, 4],
"{name}: every fill ran"
);
drop((a, b, c, d, arena, plain, shared, queue, device));
drop((
a,
b,
c,
d,
arena,
plain,
shared,
queue,
signaller_queue,
device,
));
});
}
/// Links of a chain on two queues, each waiting for the shared event's value the link before
/// it signals and signalling the next, the first behind a value the test gives from the host
/// last: every link goes to the driver and reads `Scheduled`, its scheduled handler run, while
/// the first has not run, so the queues' later work is submitted before the earlier completes,
/// and the submit thread holds none of them for a value. Once the first is let go, the links
/// complete in order. A link waiting for a value no submitted signal promises is held, at
/// `Committed`, until the host sets it, and counted in `Metrics::event_holds` as it goes.
/// Links of a chain on two queues, each but the first waiting for the shared event's value the
/// link before it signals, then copying the words of every link before it from that link's
/// buffer, writing its own after them, and signalling the next, all behind busy work: every
/// link goes to the driver and reads `Scheduled`, its scheduled handler run, before the first
/// has run, and the submit thread holds none of them for a value. No semaphore wait is
/// submitted for a link: once the busy work ends, the links complete in order, and each holds
/// the words of every link before it and its own, as the barrier ending each link's commands
/// orders the next link's after them on the device's one queue. A link waiting for a value no
/// submitted signal promises is held, at `Committed`, until the host sets it, and counted in
/// `Metrics::event_holds` as it goes.
#[test]
fn every_device_submits_a_shared_event_chain_across_two_queues_before_its_first_link_runs() {
const LINKS: u32 = 5;
@@ -1059,21 +1074,53 @@ pub(crate) mod on_device {
let buffers: Vec<Buffer> = (0..=LINKS).map(|_| arena.buffer()).collect();
let queues = [queue(&device), queue(&device)];
let log = Log::default();
let gate = device.new_event().expect("an event");
gate.pretend_submitted_for_test(1);
let chain = shared_event(&device);
let holds = || device.counters().metrics().event_holds;
let before = holds();
// Link `link`'s commands: the words of every link before it, from the buffer of the
// one before it, then its own word, `link + 1`, after them.
let record = |command_buffer: &CommandBuffer, link: u32| {
let at = link as usize;
let (own, own_offset) = buffers[at].device_range();
let earlier = at.checked_sub(1).map(|before| &buffers[before]);
let kept: Vec<&Buffer> = earlier.into_iter().chain([&buffers[at]]).collect();
let bytes = 4 * u64::from(link);
command_buffer
.record_for_test(&kept, |device, command| {
if let Some(earlier) = earlier {
let (source, source_offset) = earlier.device_range();
let region = vk::BufferCopy::default()
.src_offset(source_offset)
.dst_offset(own_offset)
.size(bytes);
// SAFETY: the command buffer is recording outside any render pass;
// the regions are the buffers' own and do not overlap.
unsafe { device.cmd_copy_buffer(command, source, own, &[region]) };
}
// SAFETY: as above; the word is the buffer's, past the copy's words.
unsafe {
device.cmd_fill_buffer(command, own, own_offset + bytes, 4, link + 1)
};
})
.expect("a link's commands");
};
let words = |buffer: &Buffer, count: usize| -> Vec<u32> {
let contents = buffer.contents().expect("a Shared buffer");
// SAFETY: the buffer is alive and 256 bytes long, past `count` words.
(0..count)
.map(|at| unsafe { contents.cast::<u32>().as_ptr().add(at).read_volatile() })
.collect()
};
let busy = Busy::new(&device);
let links: Vec<CommandBuffer> = (0..LINKS)
.map(|link| {
let queue = &queues[link as usize % 2];
let command_buffer = queue.command_buffer().expect("a command buffer");
let (event, value) = match link {
0 => (&gate, 1),
_ => (chain.as_event(), u64::from(link)),
};
(command_buffer.encode_wait_for_event(event, value)).expect("a wait");
fill(&command_buffer, &buffers[link as usize], link + 1);
if link > 0 {
(command_buffer.encode_wait_for_event(chain.as_event(), u64::from(link)))
.expect("a wait");
}
record(&command_buffer, link);
(command_buffer.encode_signal_event(chain.as_event(), u64::from(link) + 1))
.expect("a signal");
log.handlers(&format!("link {link}"), &command_buffer);
@@ -1091,7 +1138,7 @@ pub(crate) mod on_device {
assert_eq!(
chain.signaled_value(),
0,
"{name}: no link has run, the first waiting on the GPU"
"{name}: no link has run, the busy work holding the device"
);
assert_eq!(holds(), before, "{name}: no link held for a value");
// A link waiting for a value no submitted signal promises: held until the host sets
@@ -1099,14 +1146,10 @@ pub(crate) mod on_device {
let last = queues[0].command_buffer().expect("a command buffer");
let value = u64::from(LINKS) + 2;
(last.encode_wait_for_event(chain.as_event(), value)).expect("a wait");
fill(&last, &buffers[LINKS as usize], LINKS + 1);
record(&last, LINKS);
last.commit().expect("a commit");
// The first link, then the rest in order.
let signal = vk::SemaphoreSignalInfo::default()
.semaphore(gate.inner().semaphore)
.value(1);
// SAFETY: the semaphore is the device's, and 1 is above its value.
unsafe { device.raw().device.signal_semaphore(&signal) }.expect("a host signal");
busy.open();
for command_buffer in &links {
finished(name, command_buffer);
}
@@ -1137,12 +1180,14 @@ pub(crate) mod on_device {
.map(|link| format!("link {link} completed Completed None"))
.collect();
assert_eq!(completed, expected, "{name}: the links completed in order");
assert_eq!(
buffers.iter().map(word).collect::<Vec<u32>>(),
(1..=LINKS + 1).collect::<Vec<u32>>(),
"{name}: every fill ran"
);
drop((last, links, buffers, arena, gate, chain, queues, device));
for (at, buffer) in buffers.iter().enumerate() {
assert_eq!(
words(buffer, at + 1),
(1..=at as u32 + 1).collect::<Vec<u32>>(),
"{name}: link {at}'s words: every link's before it, then its own"
);
}
drop((last, links, busy, buffers, arena, chain, queues, device));
});
}
@@ -3476,20 +3521,12 @@ pub(crate) mod on_device {
#[test]
fn every_device_ends_its_work_at_a_loss_and_a_new_device_opens() {
each_device("device_loss", |name, instance, device| {
let (e, f, g) = (
shared_event(&device),
shared_event(&device),
shared_event(&device),
);
let (f, g) = (shared_event(&device), shared_event(&device));
let queue = queue(&device);
let other = self::queue(&device);
// In flight: its wait is on a signal the test makes as if submitted, then gives from
// the host.
e.pretend_submitted_for_test(1);
// In flight: held with every later command behind busy work.
let busy = Busy::new(&device);
let in_flight = queue.command_buffer().expect("a command buffer");
in_flight
.encode_wait_for_event(e.as_event(), 1)
.expect("a wait");
in_flight
.encode_signal_event(g.as_event(), 1)
.expect("a signal");
@@ -3516,12 +3553,7 @@ pub(crate) mod on_device {
"{name}: a wait for a pending signal ends at the loss"
);
let raw = device.raw();
let signal = vk::SemaphoreSignalInfo::default()
.semaphore(e.as_event().inner().semaphore)
.value(1);
// SAFETY: the semaphore is the device's, and 1 is above its value.
unsafe { raw.device.signal_semaphore(&signal) }.expect("a host signal");
busy.open();
finished(name, &in_flight);
finished(name, &held);
let late = queue.command_buffer().expect("a command buffer");
@@ -3536,7 +3568,7 @@ pub(crate) mod on_device {
);
}
let physical = physical_of(instance, &device);
drop((e, f, g, queue, other, device));
drop((busy, f, g, queue, other, device));
let device = Device::new(&physical, DeviceOptions::default()).expect("a new device");
let counters = device.counters();