Hold a shared event's wait instead of handing it to a VkQueue

Content: the tree of `development` at 2023604104, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:21 +02:00
1 parent fb2a637c05
commit 0f374bc9ec
7 files changed
+221 -44

No files matched your search

+28 -9
View File
@@ -4,6 +4,14 @@
//! - **One Vulkan object.** An event is a timeline semaphore. Its counter is a signal index that
//! [`EventTimeline`] maps to Metal's values: only the GPU signals the scheduler keeps raise it,
//! and a host set is a floor that never touches it.
//! - **A shared event's wait is never handed to Vulkan.** The host may set a shared event's value
//! (`MTLSharedEvent`), and Metal's set releases a command buffer's wait as soon as the value is
//! reached. No Vulkan wait a batch was submitted with can be released by the host, so a wait for
//! such a value is held by the scheduler until the value is reached, and goes with no Vulkan
//! wait (`event_timeline.rs`). Whatever reaches the value wakes the scheduler for it: the set,
//! and the observation of a GPU signal ([`EventShared::reached`], [`EventShared::value`]). A
//! plain event's (`MTLEvent`) wait, which no host call can satisfy, still chains on the
//! `VkQueue`.
//! - **Who observes.** A completion turn sees each batch complete, and with it the event
//! signals of the batch; reading the value reads the semaphore's counter too. Either one wakes
//! the host's waits and posts the listeners' notifications that came due.
@@ -143,7 +151,8 @@ impl Drop for EventShared {
}
impl EventShared {
fn new(device: &Device) -> Result<Arc<EventShared>, Error> {
/// `settable` for a shared event (`MTLSharedEvent`), whose value the host may set.
fn new(device: &Device, settable: bool) -> Result<Arc<EventShared>, Error> {
if device.is_lost() {
return Err(Error::DeviceLost);
}
@@ -160,7 +169,7 @@ impl EventShared {
device: device.clone(),
semaphore,
state: Mutex::new(EventState {
timeline: EventTimeline::default(),
timeline: EventTimeline::new(settable),
notifications: Vec::new(),
parked: 0,
}),
@@ -207,6 +216,7 @@ impl EventShared {
due(&mut state)
};
self.post(due);
self.woke();
}
/// The value now, from the semaphore's counter and the host's floor. A counter the read
@@ -236,18 +246,21 @@ impl EventShared {
error => Err(error),
})
};
let due = {
let (rose, due) = {
let mut state = lock(&self.state);
match state.timeline.observe_read(read, reaches) {
Ok(true) => {
self.rose(&state);
due(&mut state)
(true, due(&mut state))
}
Ok(false) | Err(_) => Vec::new(),
Ok(false) | Err(_) => (false, Vec::new()),
}
};
drop(busy);
self.post(due);
if rose {
self.woke();
}
}
}
lock(&self.state).timeline.value()
@@ -265,8 +278,7 @@ impl EventShared {
due(&mut state)
};
self.post(due);
// A batch held for this value may go now.
self.device.shared().scheduler.wake();
self.woke();
}
/// Wait until the value reaches `value`, at most `timeout`; a timeout past what the host's
@@ -331,6 +343,13 @@ impl EventShared {
self.device.shared().counts.event_wake(parked);
}
/// The value rose: a batch held for it may go now, so the scheduler looks again (its waits
/// for a value the host may set are held, never handed to Vulkan: the module docs). Called
/// without the event's lock, which the scheduler's thread takes under its own.
fn woke(&self) {
self.device.shared().scheduler.wake();
}
/// Post `due` notifications to their listeners.
fn post(self: &Arc<Self>, due: Vec<Notification>) {
for notification in due {
@@ -364,12 +383,12 @@ fn due(state: &mut EventState) -> Vec<Notification> {
impl Device {
/// `newEvent`.
pub fn new_event(&self) -> Result<Event, Error> {
Ok(Event(EventShared::new(self)?))
Ok(Event(EventShared::new(self, false)?))
}
/// `newSharedEvent`.
pub fn new_shared_event(&self) -> Result<SharedEvent, Error> {
Ok(SharedEvent(EventShared::new(self)?))
Ok(SharedEvent(EventShared::new(self, true)?))
}
/// `newSharedEventWithHandle:`: the event of `handle`, made by this device. Two calls of
@@ -19,9 +19,21 @@
//! ([`EventTimeline::known`]). A wait for a known value is satisfied by work already submitted,
//! or by the host: the scheduler submits only such waits.
//!
//! **The residual.** A wait already handed to Vulkan for a GPU signal's index is not released
//! early by a later host set above its value: it waits for that GPU signal, which was submitted
//! before it and so comes. Metal releases it at the host set.
//! **A wait the host may satisfy is never handed to Vulkan** ([`EventTimeline::settable`]). An
//! `MTLSharedEvent`'s value is one thing the host and the device both see, so `setSignaledValue:`
//! releases an `encodeWaitForEvent:` as soon as the value is reached, whatever the device is
//! running. A Vulkan wait a batch was submitted with cannot be released by the host: the semaphore
//! value it waits for is the signal index of a GPU signal submitted before it, and signalling that
//! index from the host would make that signal's own `vkQueueSubmit` illegal, since a timeline
//! semaphore signal operation's "value must have a value greater than the current value of the
//! semaphore when the semaphore signal operation is executed"
//! (`VUID-vkQueueSubmit-pSignalSemaphores-03242`). So a wait for a value the host may set is held
//! until the value is reached, by the GPU signal or by the set, and goes with no Vulkan wait at
//! all: [`EventTimeline::wait`] answers `None` while it is not reached. Only an `MTLEvent`, whose
//! value no host call sets, chains on the `VkQueue`.
//!
//! The held batch goes once the value is reached: a host set wakes the scheduler, and so does a
//! completion turn that observes the GPU signal (`event.rs`).
use crate::command_buffer::completion::seen;
use std::collections::VecDeque;
@@ -65,17 +77,29 @@ pub(super) struct EventTimeline<Q> {
pending: VecDeque<Pending<Q>>,
/// The highest value the host set.
floor: u64,
/// Whether the host may set the value: a shared event's (`MTLSharedEvent`), whose set must
/// release a wait at once, which no Vulkan wait can do (the module docs).
settable: bool,
}
impl<Q> Default for EventTimeline<Q> {
fn default() -> EventTimeline<Q> {
impl<Q> EventTimeline<Q> {
/// An event's timeline; `settable` for a shared event (`MTLSharedEvent`), whose value the host
/// may set, and `false` for a plain one (`MTLEvent`).
pub(super) fn new(settable: bool) -> EventTimeline<Q> {
EventTimeline {
reached: 0,
reached_value: 0,
pending: VecDeque::new(),
floor: 0,
settable,
}
}
/// Whether the host may set the value.
#[cfg(test)]
pub(super) fn settable(&self) -> bool {
self.settable
}
}
impl<Q: Copy + Eq> EventTimeline<Q> {
@@ -125,12 +149,16 @@ impl<Q: Copy + Eq> EventTimeline<Q> {
self.value() > before
}
/// How a batch submitted now waits for `value`; `None` when no submitted signal and no host
/// set reaches it yet, and the batch must be held.
/// How a batch submitted now waits for `value`; `None` while the batch must be held: no
/// submitted signal and no host set reaches it yet, or the host may set it and it is not
/// reached, which no Vulkan wait would answer to (the module docs).
pub(super) fn wait(&self, value: u64) -> Option<WaitFor> {
if value <= self.value() {
return Some(WaitFor::Reached);
}
if self.settable {
return None;
}
self.pending
.iter()
.find(|pending| pending.value >= value)
@@ -1,6 +1,8 @@
//! An event's signal indices and Metal's values (`event_timeline.rs`): monotone values, dropped
//! signals, the order of kept signals across `VkQueue`s, the host's floor, the waits a batch is
//! submitted with, and a counter read observed only once a host wait returned for it.
//! submitted with, and a counter read observed only once a host wait returned for it. A timeline
//! of a plain event (`MTLEvent`) is `new(false)`, one whose value the host may set
//! (`MTLSharedEvent`) `new(true)`; `host_settable_event_waits` holds the difference.
use crate::event_timeline::{EventTimeline, Signal, WaitFor};
@@ -15,7 +17,7 @@ fn submit(timeline: &mut EventTimeline<usize>, value: u64, queue: usize) -> Sign
#[test]
fn kept_signals_take_rising_indices() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(false);
assert_eq!(
submit(&mut timeline, 3, 0),
Signal::Kept {
@@ -50,7 +52,7 @@ fn kept_signals_take_rising_indices() {
#[test]
fn a_signal_not_above_what_is_known_is_dropped() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(false);
submit(&mut timeline, 7, 0);
// Lower and equal: Metal's maximum makes them no-ops (measured).
assert_eq!(submit(&mut timeline, 4, 1), Signal::Dropped);
@@ -63,13 +65,13 @@ fn a_signal_not_above_what_is_known_is_dropped() {
#[test]
fn either_submission_order_of_seven_and_four_ends_at_seven() {
// Seven first: the four is dropped.
let mut first = EventTimeline::default();
let mut first = EventTimeline::new(false);
submit(&mut first, 7, 0);
assert_eq!(submit(&mut first, 4, 1), Signal::Dropped);
first.observe(1);
assert_eq!(first.value(), 7);
// Four first: the seven is kept after it, and waits for it on another queue.
let mut second = EventTimeline::default();
let mut second = EventTimeline::new(false);
submit(&mut second, 4, 1);
assert_eq!(
submit(&mut second, 7, 0),
@@ -86,7 +88,7 @@ fn either_submission_order_of_seven_and_four_ends_at_seven() {
#[test]
fn a_kept_signal_waits_only_for_one_pending_on_another_queue() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(false);
submit(&mut timeline, 1, 0);
// Same queue: Vulkan's signal operation order keeps them in order.
assert_eq!(
@@ -117,7 +119,7 @@ fn a_kept_signal_waits_only_for_one_pending_on_another_queue() {
#[test]
fn waits_map_to_the_first_index_that_reaches_the_value() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(false);
submit(&mut timeline, 3, 0);
submit(&mut timeline, 8, 0);
assert_eq!(timeline.wait(0), Some(WaitFor::Reached));
@@ -133,7 +135,8 @@ fn waits_map_to_the_first_index_that_reaches_the_value() {
#[test]
fn the_host_floor_takes_effect_at_once_and_never_on_the_semaphore() {
let mut timeline = EventTimeline::default();
// A shared event: only its value may be set.
let mut timeline = EventTimeline::new(true);
submit(&mut timeline, 7, 0);
// A host set below the pending GPU signal: the value is 5 now.
assert!(timeline.set(5));
@@ -143,7 +146,8 @@ fn the_host_floor_takes_effect_at_once_and_never_on_the_semaphore() {
assert!(!timeline.set(5));
// A wait the floor reached needs no Vulkan wait, though a GPU signal above it is pending.
assert_eq!(timeline.wait(5), Some(WaitFor::Reached));
assert_eq!(timeline.wait(6), Some(WaitFor::Index(1)));
// One above it is held: a set the host makes next must release it, which no Vulkan wait would.
assert_eq!(timeline.wait(6), None);
// The GPU's seven lands above the floor.
assert!(timeline.observe(1));
assert_eq!(timeline.value(), 7);
@@ -151,7 +155,7 @@ fn the_host_floor_takes_effect_at_once_and_never_on_the_semaphore() {
#[test]
fn a_wait_only_the_host_floor_satisfies_is_never_a_vulkan_wait() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(true);
assert_eq!(timeline.wait(9), None);
timeline.set(9);
assert_eq!(timeline.known(), 9);
@@ -169,20 +173,19 @@ fn a_wait_only_the_host_floor_satisfies_is_never_a_vulkan_wait() {
}
);
assert_eq!(timeline.wait(9), Some(WaitFor::Reached));
assert_eq!(timeline.wait(10), Some(WaitFor::Index(1)));
// The twelve is pending, but the host may set ten: the batch is held, not handed a wait.
assert_eq!(timeline.wait(10), None);
}
#[test]
fn a_host_set_above_a_pending_signal_leaves_its_waits_on_that_signal() {
// The residual: a wait handed to Vulkan before the host set still waits for the GPU signal,
// which was submitted before it.
let mut timeline = EventTimeline::default();
fn a_host_set_above_a_pending_signal_reaches_every_wait_below_it() {
let mut timeline = EventTimeline::new(true);
submit(&mut timeline, 7, 0);
let handed = timeline.wait(5);
assert_eq!(handed, Some(WaitFor::Index(1)));
// Held, never handed to Vulkan: the host may set five, and a Vulkan wait for the seven's
// index would hold the batch until the seven's GPU work ran (`host_settable_event_waits`).
assert_eq!(timeline.wait(5), None);
timeline.set(9);
assert_eq!(timeline.value(), 9);
// A wait submitted now needs nothing.
assert_eq!(timeline.wait(5), Some(WaitFor::Reached));
// The GPU's seven reaches index 1, and the value stays at the floor.
assert!(!timeline.observe(1));
@@ -191,7 +194,7 @@ fn a_host_set_above_a_pending_signal_leaves_its_waits_on_that_signal() {
#[test]
fn the_largest_value_is_kept() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(true);
assert_eq!(
submit(&mut timeline, u64::MAX, 0),
Signal::Kept {
@@ -210,7 +213,7 @@ fn the_largest_value_is_kept() {
/// last seen covers asks for no wait, and a failed wait observes nothing.
#[test]
fn a_counter_read_is_observed_only_once_a_host_wait_returned_for_it() {
let mut timeline = EventTimeline::default();
let mut timeline = EventTimeline::new(false);
submit(&mut timeline, 3, 0);
submit(&mut timeline, 5, 0);
let mut asked = Vec::new();
@@ -0,0 +1,100 @@
//! A wait for a value the host may set is never handed to Vulkan (`event_timeline.rs`,
//! `event.rs`).
//!
//! Metal's `MTLSharedEvent` carries one value the host and the device both see, so
//! `setSignaledValue:` releases a command buffer's `encodeWaitForEvent:` as soon as the value is
//! reached, whatever the device is running. A Vulkan wait a batch was submitted with cannot be
//! released by the host: the value it waits for is the signal index of a GPU signal submitted
//! before it, and signalling that index from the host would make that signal's own
//! `vkQueueSubmit` illegal ("must have a value greater than the current value of the semaphore
//! when the semaphore signal operation is executed",
//! `VUID-vkQueueSubmit-pSignalSemaphores-03242`). So such a wait is held until the value is
//! reached and then goes with no Vulkan wait at all, and only a plain event's (`MTLEvent`, whose
//! value no host call sets) chains on the `VkQueue`.
use crate::event_timeline::{EventTimeline, Signal, WaitFor};
/// Submit a GPU signal of `value` on `queue`, kept when it is.
fn submit(timeline: &mut EventTimeline<usize>, value: u64, queue: usize) {
if let Signal::Kept { index, .. } = timeline.signal(value, queue) {
timeline.keep(index, value, queue);
}
}
/// The shape a consumer measured: a long command buffer's signal is pending, a later command
/// buffer waits for a value it reaches, and the host provides that value. Metal lets the waiter
/// go at the set; a Vulkan wait for the signal's index would hold it for the whole of the long
/// command buffer's work.
#[test]
fn a_wait_the_host_may_satisfy_is_held_instead_of_handed_to_vulkan() {
let mut timeline: EventTimeline<usize> = EventTimeline::new(true);
submit(&mut timeline, 0x9607, 0);
// Submitted and pending, so the value is known, and yet no batch may be handed a wait for it.
assert_eq!(timeline.known(), 0x9607);
for value in [1, 0x482, 0x9606, 0x9607] {
assert_eq!(timeline.wait(value), None, "{value:#x} handed to Vulkan");
}
// The host sets it: every wait it reaches goes at once, with no Vulkan wait.
assert!(timeline.set(0x9607));
for value in [1, 0x482, 0x9606, 0x9607] {
assert_eq!(timeline.wait(value), Some(WaitFor::Reached), "{value:#x}");
}
// One above the set is held again; the GPU signal still reaches only its own value.
assert_eq!(timeline.wait(0x9608), None);
assert!(!timeline.observe(1));
assert_eq!(timeline.value(), 0x9607);
}
/// The same wait, reached by the GPU signal instead: the batch is held until it is observed, and
/// then needs no Vulkan wait either.
#[test]
fn a_held_wait_goes_once_the_gpu_signal_is_observed() {
let mut timeline: EventTimeline<usize> = EventTimeline::new(true);
submit(&mut timeline, 100, 0);
assert_eq!(timeline.wait(50), None);
assert!(timeline.observe(1));
assert_eq!(timeline.value(), 100);
assert_eq!(timeline.wait(50), Some(WaitFor::Reached));
assert_eq!(timeline.wait(100), Some(WaitFor::Reached));
assert_eq!(timeline.wait(101), None);
}
/// A plain event's value no host call sets, so its wait is exact on the `VkQueue` and keeps
/// chaining there: the hold costs a scheduler pass and buys nothing.
#[test]
fn a_plain_event_s_wait_still_chains_on_the_vk_queue() {
let mut timeline: EventTimeline<usize> = EventTimeline::new(false);
submit(&mut timeline, 3, 0);
submit(&mut timeline, 8, 0);
assert_eq!(timeline.wait(0), Some(WaitFor::Reached));
assert_eq!(timeline.wait(3), Some(WaitFor::Index(1)));
assert_eq!(timeline.wait(4), Some(WaitFor::Index(2)));
assert_eq!(timeline.wait(8), Some(WaitFor::Index(2)));
// Beyond what is submitted, either kind is held.
assert_eq!(timeline.wait(9), None);
}
/// Holding changes nothing about the signals themselves: Metal's maximum drops a signal not above
/// what is known whichever kind the event is, and the kept ones take the same indices.
#[test]
fn the_signals_of_either_kind_take_the_same_indices() {
for settable in [false, true] {
let mut timeline: EventTimeline<usize> = EventTimeline::new(settable);
assert_eq!(
timeline.signal(4, 0),
Signal::Kept {
index: 1,
after: None
}
);
timeline.keep(1, 4, 0);
assert_eq!(timeline.signal(4, 1), Signal::Dropped);
assert_eq!(
timeline.signal(5, 1),
Signal::Kept {
index: 2,
after: Some(1)
}
);
}
}
@@ -124,6 +124,7 @@ mod host_import_counts;
mod host_memory;
#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))]
mod host_residency;
mod host_settable_event_waits;
mod host_shadow;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod host_step_neutrals;
@@ -3,6 +3,13 @@
//! `VkQueue` never deadlock, signals of one event from several queues end at the highest value,
//! and host sets racing pending GPU signals never deadlock.
//!
//! An event the program's host sets is a shared event ([`Model::sharing`]), whose waits are held
//! until the value is reached rather than handed to Vulkan (`host_settable_event_waits`); the
//! rest are plain events, whose waits chain on the `VkQueue`. A batch held for either reason goes
//! once what it waits for arrives, which in the runtime wakes the scheduler ([`EventShared::set`]
//! and [`EventShared::reached`], `event.rs`) and here makes a pass again ([`Model::host_set`],
//! [`Model::step`]).
//!
//! [`Order::take_first`], which a thread about to block submits with
//! (`scheduler::submit_plain_ready`), is tested here too: it takes the head committed first of
//! all and stops at it, so it passes no head over and needs no answer of
@@ -73,7 +80,7 @@ impl Model {
fn new(events: usize, vk_queue_of: &[usize]) -> Model {
let vk_queues = vk_queue_of.iter().max().map_or(0, |&last| last + 1);
Model {
events: (0..events).map(|_| EventTimeline::default()).collect(),
events: (0..events).map(|_| EventTimeline::new(false)).collect(),
counters: vec![0; events],
kept: vec![0; events],
order: Order::default(),
@@ -86,6 +93,15 @@ impl Model {
}
}
/// The events the program's host sets are shared events (`MTLSharedEvent`): only their value
/// may be set.
fn sharing(mut self, shared: &[usize]) -> Model {
for &event in shared {
self.events[event] = EventTimeline::new(true);
}
self
}
/// Commit a command buffer of `batches` on logical queue `queue`, then schedule: the batches'
/// identities.
fn commit(&mut self, queue: usize, batches: Vec<Spec>) -> Vec<usize> {
@@ -97,8 +113,13 @@ impl Model {
(first..self.next).collect()
}
/// The host sets `event` to `value`, then the scheduler looks again.
/// The host sets `event` to `value`, then the scheduler looks again. Only a shared event's
/// value is set ([`Model::sharing`]).
fn host_set(&mut self, event: usize, value: u64) {
assert!(
self.events[event].settable(),
"event {event} is a plain one"
);
self.events[event].set(value);
self.schedule();
}
@@ -170,6 +191,9 @@ impl Model {
self.events[event].observe(index);
}
self.executed.push(head.id);
// The signals seen let a batch held for one of their values go, as a completion turn
// wakes the scheduler for it (`event.rs`).
self.schedule();
true
}
@@ -315,7 +339,7 @@ fn a_wait_before_its_signal_on_one_vk_queue_never_deadlocks() {
fn a_held_batch_holds_back_only_its_own_queue() {
// As measured on Metal: a command buffer waiting for an event stays committed, holds the
// later command buffers of its queue, and lets other queues run.
let mut model = Model::new(1, &[0, 0]);
let mut model = Model::new(1, &[0, 0]).sharing(&[0]);
let held = model.commit(0, vec![waits(&[(0, 1)])]);
let behind = model.commit(0, vec![Spec::default()]);
let other = model.commit(1, vec![Spec::default()]);
@@ -391,7 +415,7 @@ fn a_host_set_racing_a_pending_signal_never_deadlocks() {
// Event 0's seven is submitted on VkQueue 0 but waits there for event 1, which queue 1
// signals on VkQueue 1. The host sets event 0 to 9 meanwhile.
for run_first in [0, 1] {
let mut model = Model::new(2, &[0, 1, 0, 1]);
let mut model = Model::new(2, &[0, 1, 0, 1]).sharing(&[0]);
model.commit(1, vec![signals(&[(1, 1)])]);
model.commit(
0,
@@ -400,7 +424,8 @@ fn a_host_set_racing_a_pending_signal_never_deadlocks() {
signals: vec![(0, 7)],
}],
);
// Submitted before the host set: waits for the seven's index (the residual).
// Event 0 is shared, so this one is held rather than handed a wait for the seven's
// index: the host set must release it, which no Vulkan wait would.
let early = model.commit(3, vec![waits(&[(0, 5)])]);
if run_first == 1 {
model.run(&mut |_| 0);
@@ -414,7 +439,7 @@ fn a_host_set_racing_a_pending_signal_never_deadlocks() {
assert_eq!(waits, &[], "a wait only the host's floor satisfies");
}
let (_, waits) = &model.submitted_waits[model.position(early[0])];
assert_eq!(waits, &[(0, 1)]);
assert_eq!(waits, &[], "a wait the host's set may satisfy");
model.run(&mut |count| count - 1);
assert!(model.finished(), "{:?}", model.vk_queues);
assert_eq!(model.events[0].value(), 9);
@@ -486,7 +511,8 @@ fn random_programs_complete_on_one_to_four_vk_queues() {
sets,
highest,
} = program(&mut rng, queues, events);
let mut model = Model::new(events, &vk_queue_of);
let shared: Vec<usize> = sets.iter().map(|&(event, _)| event).collect();
let mut model = Model::new(events, &vk_queue_of).sharing(&shared);
// Commit in a random interleaving of the queues (each queue's own order kept), with
// the host sets at random points and the device running at random points.
let mut lines: Vec<VecDeque<Vec<Spec>>> = (0..queues).map(|_| VecDeque::new()).collect();
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 450;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1638;
pub const RUNTIME_VERSION: u32 = 1640;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles