Runtime: an event's value the host sees is one a host wait confirmed

A value the guest sees that a GPU signal raised (SharedEvent::signaled_value,
wait_until_signaled_value, a listener's value, and the completion thread's observation that ends
an event's watch and may free its semaphore) came from vkGetSemaphoreCounterValue alone. Vulkan
states an execution dependency only for a host wait on a semaphore (the memory model's "signal
operations happening before host operations that wait on them"), and the completion of command
buffers already retires only on a vkWaitSemaphores; the planner's reading: a retirement, a host
read of bytes the GPU wrote, a value the guest sees that a GPU signal raised and a free are gated
by vkWaitSemaphores (a timeout of 0 allowed), never by the counter read alone.

EventInner::reached replaces the bare counter read at every site that gates: the counter read
finds the value, complete::reached_by_wait (timeout 0) confirms it, and the highest value
confirmed is kept. A value read at or below it asks for no wait, so a steady event pays one
counter read as before. Where the wait does not confirm the value read, a lower candidate (the
completion thread's next pending value, a host wait's own value) is waited for, and otherwise the
last value confirmed stands: on the completion thread the event stays watched and the round's GPU
wait blocks on its next pending value, so a "not yet" never spins.

Test-only counts (Counters::event_reads: reads, waits, not yet, not yet on the completion
thread, the completion thread's wake-ups) and a test, a_value_the_host_sees_is_one_a_host_wait_
confirmed: 1,000 reads of a steady value make at most one wait, and with a signal pending behind
the busy gate the completion thread does not return from its GPU wait for 200 ms. No public item
changes; signaled_value's doc and the runtime README's timestamps paragraph say it.

Verification: not run when committed; lavapipe, the cards and the harness's cost rows follow on
this branch.
This commit is contained in:
Anees Iqbal committed 2026-11-27 04:44:55 -08:00
1 parent d50eeb3522
commit 58158f96a9
5 files changed
+211 -16

No files matched your search

+4 -1
View File
@@ -2629,7 +2629,10 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
retires only once a host wait has seen its submission's progress value: with one value pending
the completion thread asks only that wait, and with more, where the semaphore's counter read
runs ahead of the wait, `Metrics::waits_behind_counter` counts the round, and nothing retires
until the wait agrees. The device tests, the harness and the replay player
until the wait agrees. An event's value the host sees that a GPU signal raised
(`SharedEvent::signaled_value`, `wait_until_signaled_value`, a listener's value) is likewise
one a wait with a timeout of 0 confirmed, after the counter read found it; a read at or below
the value last confirmed asks for no wait. The device tests, the harness and the replay player
report both counts. Vulkan states no most queries a pool may hold or most pools a device may
make; the runtime's 4,096 a pool is the smallest met: Mesa's Apple-GPU driver makes each pool a
Metal counter heap, of at most 4,096 entries and at most 32 live in a process, so there at most
+15 -1
View File
@@ -229,6 +229,14 @@ impl Done {
*lock(&self.step) = step;
}
/// For the device tests: the values of the completion thread's GPU wait, where it waits on the
/// GPU (the progress semaphore's first, then the watched events', the wake semaphore's last).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn gpu_wait(&self) -> Option<Vec<u64>> {
let state = self.lock();
matches!(state.waiting, Waiting::Gpu { .. }).then(|| state.waits_for.clone())
}
/// For the device tests: what the completion side holds, read at once, for a wait that timed
/// out. The command buffers in flight (submitted and not retired) among its retirees; the
/// oldest retiree's progress value, the progress semaphore's counter, and whether a wait of
@@ -719,7 +727,11 @@ pub(crate) fn run(core: Arc<Core>) {
let mut index = 0;
while index < state.watched.len() {
let event = &state.watched[index];
if event.observe(event.counter().ok(), &mut fire) {
// Only a value a host wait confirmed is the event's (`EventInner::reached`); a
// value read that none confirmed leaves the event watched, and the round's GPU
// wait below blocks on its next pending value.
let reached = event.reached(event.next_pending()).ok();
if event.observe(reached, &mut fire) {
index += 1;
} else {
state.watched.swap_remove(index);
@@ -898,6 +910,8 @@ pub(crate) fn run(core: Arc<Core>) {
// SAFETY: every semaphore is a timeline semaphore of the device, live while the state
// holds its event or the core lives.
let result = unsafe { device.wait_semaphores(&wait, u64::MAX) };
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
core.counters.event_read(crate::counters::event_step::WAKE);
state = done.lock();
state.waiting = Waiting::Not;
match result {
@@ -714,6 +714,33 @@ pub struct Counters {
atomics: Arc<Atomics>,
}
/// An event's value reads (`EventInner::reached`) and the completion thread's wake-ups, for the
/// tests ([`Counters::event_reads`]).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct EventReads {
/// Counter reads.
pub(crate) reads: u64,
/// Host waits with a timeout of 0 that a read above the value confirmed asked for.
pub(crate) waits: u64,
/// Reads whose value no wait confirmed.
pub(crate) not_yet: u64,
/// Of those, the completion thread's.
pub(crate) not_yet_completing: u64,
/// The completion thread's returns from its GPU wait.
pub(crate) wakes: u64,
}
/// [`EventReads`]' steps, as [`Counters::event_read`] takes them.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) mod event_step {
pub(crate) const READ: usize = 0;
pub(crate) const WAIT: usize = 1;
pub(crate) const NOT_YET: usize = 2;
pub(crate) const NOT_YET_COMPLETING: usize = 3;
pub(crate) const WAKE: usize = 4;
}
#[derive(Default)]
struct Atomics {
/// [`Gauges::threads`]: each slot a running thread's id, 0 where none holds it.
@@ -988,6 +1015,11 @@ struct Atomics {
/// Segment ends whose barrier reaches the host, for the tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
host_reaches: AtomicU64,
/// An event's value reads (`EventInner::reached`), for the tests: its counter reads, the host
/// waits they made, the waits that did not confirm a value read ("not yet"), those of them on
/// the completion thread, and the completion thread's returns from its GPU wait.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
event_reads: [AtomicU64; 5],
/// Barriers that ended a blit of an image, and the global memory barriers they held, for the
/// tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -1733,6 +1765,26 @@ impl Counters {
self.atomics.host_reaches.load(Relaxed)
}
/// One more of an event's value reads' steps, [`EventReads`]'s field `step` in its order.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn event_read(&self, step: usize) {
self.atomics.event_reads[step].fetch_add(1, Relaxed);
}
/// The event value reads' steps so far.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn event_reads(&self) -> EventReads {
let [reads, waits, not_yet, not_yet_completing, wakes] =
(self.atomics.event_reads.each_ref()).map(|n| n.load(Relaxed));
EventReads {
reads,
waits,
not_yet,
not_yet_completing,
wakes,
}
}
/// The calibrations made.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn calibrations(&self) -> u64 {
+64 -10
View File
@@ -46,6 +46,8 @@ pub(crate) struct EventInner {
/// in flight may write was settled for the host (`crate::coherence`); 0, and never read, where
/// the Shared type is host-coherent.
settled: AtomicU64,
/// The highest value of the semaphore a host wait confirmed ([`EventInner::reached`]).
confirmed: AtomicU64,
}
pub(crate) struct EventState {
@@ -87,6 +89,7 @@ impl Device {
}),
changed: Condvar::new(),
settled: AtomicU64::new(0),
confirmed: AtomicU64::new(0),
}),
device: self.clone(),
})
@@ -138,7 +141,9 @@ impl Event {
}
impl SharedEvent {
/// `signaledValue`: the higher of the semaphore's value and the host's floor. Where the
/// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's
/// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout
/// of 0 confirms it where it is above the value last confirmed. Where the
/// semaphore's value rose since the host last saw it, the Shared memory command buffers in
/// flight may write is flushed and invalidated first (`crate::coherence`), so the host reads
/// what the GPU wrote before its signal.
@@ -148,7 +153,9 @@ impl SharedEvent {
let state = lock(&inner.state);
let floor = state.observed.max(state.floor);
// A lost device answers with what was seen before the loss.
return inner.counter().map_or(floor, |counter| counter.max(floor));
return inner
.reached(None)
.map_or(floor, |reached| reached.max(floor));
};
let (observed, floor) = {
let state = lock(&inner.state);
@@ -156,8 +163,8 @@ impl SharedEvent {
};
// A lost device answers with what was seen before the loss.
let signalled = inner
.counter()
.map_or(observed, |counter| counter.max(observed));
.reached(None)
.map_or(observed, |reached| reached.max(observed));
inner.seen(coherence, signalled);
signalled.max(floor)
}
@@ -203,7 +210,9 @@ impl SharedEvent {
match &inner.core.coherence {
None => {
if state.floor.max(state.observed) >= value
|| inner.counter().is_ok_and(|counter| counter >= value)
|| inner
.reached(Some(value))
.is_ok_and(|reached| reached >= value)
{
return Ok(true);
}
@@ -213,9 +222,9 @@ impl SharedEvent {
// writes before it are the host's first.
let met = match state.floor.max(state.observed) >= value {
true => Some(state.observed),
false => (inner.counter().ok())
.filter(|&counter| counter >= value)
.map(|counter| counter.max(state.observed)),
false => (inner.reached(Some(value)).ok())
.filter(|&reached| reached >= value)
.map(|reached| reached.max(state.observed)),
};
if let Some(signalled) = met {
drop(state);
@@ -300,8 +309,53 @@ impl EventInner {
}
}
/// The semaphore's value now.
pub(crate) fn counter(&self) -> Result<u64, Error> {
/// The semaphore's value a host wait confirmed, which a value the host sees that a GPU signal
/// raised never passes: a counter read finds the value, and a wait on it with a timeout of 0
/// (`complete::reached_by_wait`) confirms it (the completion thread's module doc). A value
/// read at or below the highest one confirmed asks for no wait. Where the wait does not
/// confirm the value read, `lower` is waited for instead where it lies between the two, and
/// otherwise the highest value confirmed stands.
///
/// Err: [`Error::Vulkan`] where the read or a wait fails.
pub(crate) fn reached(&self, lower: Option<u64>) -> Result<u64, Error> {
let confirmed = self.confirmed.load(Ordering::Acquire);
let read = self.counter()?;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
self.core
.counters
.event_read(crate::counters::event_step::READ);
if read <= confirmed {
return Ok(confirmed);
}
let lower = lower.filter(|&lower| confirmed < lower && lower < read);
for value in std::iter::once(read).chain(lower) {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
self.core
.counters
.event_read(crate::counters::event_step::WAIT);
let by = crate::complete::reached_by_wait(&self.core.device, self.semaphore, value)
.map_err(|loss| Error::Vulkan {
call: loss.call,
result: loss.result,
})?;
if by {
return Ok(self.confirmed.fetch_max(value, Ordering::AcqRel).max(value));
}
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
use crate::counters::event_step::{NOT_YET, NOT_YET_COMPLETING};
self.core.counters.event_read(NOT_YET);
if crate::device::on_completion_thread(&self.core) {
self.core.counters.event_read(NOT_YET_COMPLETING);
}
}
Ok(confirmed)
}
/// The semaphore's value now, as a counter read finds it: no host operation is ordered after
/// the signal that raised it ([`reached`](Self::reached) is).
fn counter(&self) -> Result<u64, Error> {
// SAFETY: the semaphore is a timeline semaphore of the device, live while `self` is.
unsafe { self.core.device.get_semaphore_counter_value(self.semaphore) }
.map_err(Error::vulkan("vkGetSemaphoreCounterValue"))
@@ -2,8 +2,10 @@
//! the highest value known is left out, whichever queue it is on; the host's value of a shared
//! event reads at once below a GPU signal still pending and never signals the semaphore, and a
//! host value above a pending GPU signal stays the event's value once that signal lands; the
//! largest value is kept; and a shared event's listeners run on one thread, not the posting one,
//! in the order posted.
//! largest value is kept; a value the host sees is one a host wait confirmed, a steady value
//! asking for no wait and the completion thread waiting on the GPU, not spinning, for a value
//! still to come; and a shared event's listeners run on one thread, not the posting one, in the
//! order posted.
//!
//! The GPU signals stay pending while the test reads the values: a [`Busy`] gate submitted ahead
//! of them holds every later command of the device's one `VkQueue` until the test opens it.
@@ -46,9 +48,10 @@ fn pending(event: &Event) -> Vec<u64> {
lock(&event.inner().state).pending.iter().copied().collect()
}
/// The value of `event`'s semaphore: an `MTLEvent`'s value, which no host call sets.
/// The value of `event`'s semaphore a host wait confirmed: an `MTLEvent`'s value, which no host
/// call sets.
fn counter(event: &Event) -> u64 {
event.inner().counter().expect("the semaphore's value")
(event.inner().reached(None)).expect("the semaphore's value")
}
/// The holds for an event's value the submit thread made, of every length.
@@ -198,6 +201,75 @@ fn the_largest_value_is_kept() {
});
}
/// A value the host sees that a GPU signal raised is one a host wait confirmed: the counter read
/// finds it and a wait with a timeout of 0 confirms it (`EventInner::reached`). On a steady event,
/// a value read at or below the one confirmed asks for no wait: 1,000 reads of a value the GPU
/// reached make at most one wait. With a signal pending behind the [`Busy`] gate, the event is
/// watched and the completion thread waits on the GPU for it: over 200 ms it does not return from
/// that wait, and a read none confirmed there ("not yet") leaves it waiting, not spinning. The
/// counts are printed.
#[test]
fn a_value_the_host_sees_is_one_a_host_wait_confirmed() {
each_device("event_confirmed_reads", |name, _, device| {
let event = shared_event(&device);
let queue = queue(&device);
let counters = device.counters();
let first = signal(name, &device, &queue, event.as_event(), 5);
finished(name, &first);
assert!(
(event.wait_until_signaled_value(5, PATIENCE)).expect("a wait outside a handler"),
"{name}"
);
// A steady event: every read finds the value confirmed.
let before = counters.event_reads();
for _ in 0..1000 {
assert_eq!(event.signaled_value(), 5, "{name}");
}
let steady = counters.event_reads();
let (reads, waits) = (steady.reads - before.reads, steady.waits - before.waits);
println!("{name}: a steady event: {reads} reads, {waits} waits");
assert!(reads >= 1000, "{name}: {reads} reads");
assert!(
waits <= 1,
"{name}: {waits} waits for 1,000 reads of a steady value"
);
// A signal pending: the completion thread waits on the GPU for it.
let busy = Busy::new(&device);
// A value no progress value of the device's reaches, so the GPU wait's values name it
// alone.
let later = 1 << 40;
let second = signal(name, &device, &queue, event.as_event(), later);
assert_eq!(pending(event.as_event()), [later], "{name}");
within(name, || {
(device.core().done.gpu_wait()).is_some_and(|values| values.contains(&later))
});
let idle = counters.event_reads();
std::thread::sleep(Duration::from_millis(200));
let after = counters.event_reads();
println!(
"{name}: a pending signal, 200 ms: {} wake-ups of the completion thread, {} not yet \
on it ({} in all); since the device opened {:?}",
after.wakes - idle.wakes,
after.not_yet_completing - idle.not_yet_completing,
after.not_yet - idle.not_yet,
after
);
assert_eq!(
after.wakes, idle.wakes,
"{name}: the completion thread returned from its GPU wait with nothing reached"
);
assert_eq!(event.signaled_value(), 5, "{name}: the GPU held");
busy.open();
finished(name, &second);
assert!(
(event.wait_until_signaled_value(later, PATIENCE)).expect("a wait outside a handler"),
"{name}"
);
assert_eq!(event.signaled_value(), later, "{name}");
drop((first, second, busy, queue, event, device));
});
}
/// The notifications of a shared event's listeners run off the posting thread, on one thread for
/// them all, in the order posted.
#[test]