RUNTIME 2232: the scheduler loses no wake for a batch held behind an unshared queue or a kept group

A guest's commitAndWaitUntilSubmitted could stay unanswered until the next commit (reims, XTX
RADV at pin 71, 2 of 77 runs under load: "A was never submitted"; the GPU idle; the scheduler
asleep with the batch held for 10 s; an empty commit on another queue released it at once).

Cause (reims's finding, /tmp/xqtest/m2v-finding.md): on a host whose one graphics VkQueue an
unshared queue also holds (RADV, ANV; WindowServer's queues are unshared), batch A behind H was
held by held_for_unshared() while H was in the Flight. QueueSlot::completed publishes `completed`
(fetch_max) before waits.completed takes H out of the Flight. When H completed between those two
steps, the hold read a stale Flight and gated on completed + 1, which nothing meets.

Fix:
- Unshared hold: QueueWaits::hold_ahead reads the published completed value under the waits lock;
  Flight::ahead(ran, completed) counts batches at or below it as gone; Room::Hold { after, through }
  carries the oldest still in flight; await_unshared_room gates on `through`, fences, and reads
  again (completed >= through wakes it at once). No reorder of QueueSlot::completed.
- Kept group (submit_ready, Group::keeps read before gate_on): sets the gate, fences, then reads
  again (Group::pending_through), the protocol gate_heads and check_heads use.
- A WAIT_SLICE that ends with a batch held makes a pass, as the module docs promise, counted in
  WorkCounts::scheduler_slice_rescues (0 wherever every wake comes). api_signatures and host_ab
  updated.

Verified (perdraw5, msi 26135, lavapipe, at 3bd14c83ac on a2ac4433ca): clippy all features and
--cfg m2v_gpu, rustdoc -D warnings, api_signatures/api_surface green; 36/36 of scheduler_held_wakes,
scheduler_wakes, completion_wakes, scheduler, unshared_hold. tests::scheduler_held_wakes forces
each interleaving with test-only hold points (completion::trace, cfg(test) + device cfgs; `Leave`
sits between QueueSlot::completed's fetch_max and waits.completed):
- unshared: H held at Leave while the next is committed; it goes with 0 slice rescues.
- kept group: both completions published between keeps and the gate; it goes in that pass, 0.
- lost wake: completion wakes dropped; the held group goes at the next slice (1 rescue, 99 ms).
Negative controls each fail only their own test: old gate (unshared held until the slice at
101 ms, and with development's code until the next commit, reims's symptom); kept recheck
removed (102.9 ms, 1 rescue); a slice making no pass (never completed within 5 s).

RUNTIME_VERSION 2231 -> 2232.
This commit is contained in:
Anees Iqbal committed 2026-11-13 11:22:48 -08:00
1 parent b0a767a149
commit c7d652ca5e
14 files changed
+575 -70

No files matched your search

@@ -1679,6 +1679,7 @@ impl Gpu for Runtime {
("registrations_waited", c.registrations_waited),
("scheduler_wakes_completion", c.scheduler_wakes_completion),
("scheduler_sleep_slices", c.scheduler_sleep_slices),
("scheduler_slice_rescues", c.scheduler_slice_rescues),
("scheduler_gpu_waits", c.scheduler_gpu_waits),
("wakes_completion_waiters", c.wakes_completion_waiters),
(
@@ -1484,6 +1484,8 @@ fn poll(device: &Device, queue: usize, front: Front) -> Result<u64, CommandBuffe
reaches(value)
},
)?;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
trace::at(trace::Point::Publish);
slot.completed(value, &shared.counts);
// Freed memory that waits for the batches in flight goes once they completed, on a handler
// thread (`freed_memory.rs`).
@@ -1632,6 +1634,70 @@ pub(crate) mod trace {
}
}
/// A point of the runtime's threads a test holds a thread at ([`hold_at`]) until it lets it go
/// ([`release`]), to force an interleaving.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Point {
/// A queue's waiter, before it publishes a value its queue's timeline completed (`poll`).
Publish,
/// The scheduler's thread, once `Group::keeps` kept the group held past its pass and
/// before it leaves the group's gate for the completion turns (`scheduler/mod.rs`).
KeptGate,
/// A queue's waiter, once it published a value its queue's timeline completed and before
/// the batches at or below it leave the `VkQueue`'s flight (`QueueSlot::completed`).
Leave,
}
/// Of each [`Point`]: whether a test holds threads there, and whether one reached it since.
static POINTS: Mutex<[(bool, bool); 3]> = Mutex::new([(false, false); 3]);
static POINTS_CHANGED: std::sync::Condvar = std::sync::Condvar::new();
/// Hold every thread that reaches `point` from now on, until [`release`].
pub(crate) fn hold_at(point: Point) {
POINTS.lock().unwrap()[point as usize] = (true, false);
}
/// Let go of the threads held at `point`, and hold none there any more.
pub(crate) fn release(point: Point) {
POINTS.lock().unwrap()[point as usize].0 = false;
POINTS_CHANGED.notify_all();
}
/// Whether a thread reached `point`, held there, within `timeout`.
pub(crate) fn reached(point: Point, timeout: std::time::Duration) -> bool {
let points = POINTS.lock().unwrap();
let (points, _) = POINTS_CHANGED
.wait_timeout_while(points, timeout, |points| !points[point as usize].1)
.unwrap();
points[point as usize].1
}
/// A runtime thread is at `point`: held there while a test holds it.
pub(crate) fn at(point: Point) {
let mut points = POINTS.lock().unwrap();
if !points[point as usize].0 {
return;
}
points[point as usize].1 = true;
POINTS_CHANGED.notify_all();
drop(POINTS_CHANGED.wait_while(points, |points| points[point as usize].0));
}
/// Whether the completion turns wake the scheduler's thread for a met wait no more
/// ([`drop_completion_wakes`]).
static COMPLETION_WAKES_DROPPED: AtomicBool = AtomicBool::new(false);
/// From now on (`true`), or no more, the completion turns never wake the scheduler's thread
/// for what a head waited for (`Scheduler::completions`): a wake lost, whatever its cause.
pub(crate) fn drop_completion_wakes(drop: bool) {
COMPLETION_WAKES_DROPPED.store(drop, Ordering::SeqCst);
}
/// Whether a test drops the completion turns' wakes ([`drop_completion_wakes`]).
pub(crate) fn completion_wakes_dropped() -> bool {
COMPLETION_WAKES_DROPPED.load(Ordering::SeqCst)
}
/// Keep the commit's step `what` on its way to its submission, now.
pub(crate) fn submitting(what: &'static str) {
record(|| Traced::Submitting {
@@ -441,6 +441,17 @@ impl Group {
Some(value)
}
/// Whether its `VkQueue` has not completed `value` yet, as the host saw ([`keeps`]'s value),
/// read again after the scheduler left its gate for the completion turns.
///
/// [`keeps`]: Group::keeps
pub(crate) fn pending_through(&self, value: u64) -> bool {
(self.members.first()).is_some_and(|first| {
let device = first.submission.buffer().device();
device.shared().queues[self.queue].completed_value() < value
})
}
/// What the group's last submission did, for the scheduler to publish its batches
/// ([`made`](Group::made)) or fail them.
pub(crate) fn take_outcome(&mut self) -> Option<Result<(), CommandBufferError>> {
@@ -4692,10 +4692,11 @@ impl CommandBufferShared {
}
/// Where a batch of it, otherwise ready, is held back from its `VkQueue` for an unshared
/// queue there (`unshared_hold.rs`): that `VkQueue`'s index, and in how many nanoseconds the
/// work left ahead there falls under the budget where it does before its next completion;
/// `None` where it may go, as on a lost device, whose submissions fail at once.
pub(crate) fn held_for_unshared(&self) -> Option<(usize, Option<u64>)> {
/// queue there (`unshared_hold.rs`): that `VkQueue`'s index, the value of the oldest batch in
/// flight there the host has not seen complete, and in how many nanoseconds the work left
/// ahead there falls under the budget where it does before that batch completes; `None` where
/// it may go, as on a lost device, whose submissions fail at once.
pub(crate) fn held_for_unshared(&self) -> Option<(usize, u64, Option<u64>)> {
if self.queue.unshared() || self.device.is_lost() {
return None;
}
@@ -4703,9 +4704,10 @@ impl CommandBufferShared {
if !self.device.holds_back_for_unshared(index) {
return None;
}
match self.device.shared().queues[index].waits.hold_ahead() {
let slot = &self.device.shared().queues[index];
match slot.waits.hold_ahead(|| slot.completed_value()) {
crate::unshared_hold::Room::Go => None,
crate::unshared_hold::Room::Hold { after } => Some((index, after)),
crate::unshared_hold::Room::Hold { after, through } => Some((index, through, after)),
}
}
@@ -1393,6 +1393,10 @@ impl QueueSlot {
/// queues' batches it ends are timed (`queue_wait.rs`).
pub(super) fn completed(&self, value: u64, counts: &crate::work_counts::Counters) {
if self.completed.fetch_max(value, Ordering::AcqRel) < value {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
crate::command_buffer::completion::trace::at(
crate::command_buffer::completion::trace::Point::Leave,
);
self.share.completed();
self.waits.completed(value, counts);
}
@@ -199,10 +199,12 @@ impl QueueWaits {
}
/// Whether another command queue's batch may go to this `VkQueue` now, held against its
/// flight (`unshared_hold.rs`).
pub(crate) fn hold_ahead(&self) -> crate::unshared_hold::Room {
/// flight (`unshared_hold.rs`), the batches at or below `completed` (the value the host saw
/// the timeline reach, read under this lock) counted as left: a completion publishes its value
/// before it takes this lock to take them out ([`completed`](Self::completed)).
pub(crate) fn hold_ahead(&self, completed: impl FnOnce() -> u64) -> crate::unshared_hold::Room {
let ahead = lock(&self.0);
let ran = crate::gpu_time::host_nanos().saturating_sub(ahead.head_from);
ahead.flight.ahead(ran)
ahead.flight.ahead(ran, completed())
}
}
@@ -141,7 +141,9 @@
//! or its group, no head's bound and no driver's stall to take, nothing else can give it work,
//! so it sleeps with no timeout: an idle device's scheduler does not wake at all
//! (`WorkCounts::scheduler_sleep_slices`). With a batch held it still wakes at least every
//! [`WAIT_SLICE`], beside the completion that lets its batch go.
//! [`WAIT_SLICE`], beside the completion that lets its batch go, and passes: a batch whose
//! wait was met goes then even where the wake for it never came, counted
//! (`WorkCounts::scheduler_slice_rescues`, 0 where every wake comes).
//! - **The driver's stalls taken idle** (`device/submit_stalls.rs`). Where the driver stalls in
//! one signalling submission of every 1024 to a `VkQueue` (NVIDIA's), and a queue's next stall
//! may be due, the thread wakes once it has had nothing to submit for `IDLE_NANOS`, and
@@ -608,6 +610,10 @@ pub(crate) struct State {
/// A host signal marked the state since the thread last looked (a commit and a nudge are
/// the inbox's, `inbox.rs`).
dirty: bool,
/// The thread's last sleep ended at [`WAIT_SLICE`], nothing having woken it, with a batch
/// held: the state is marked for a pass, which counts itself where it lets a batch go
/// (`WorkCounts::scheduler_slice_rescues`).
sliced: bool,
stopping: bool,
/// The textures whose decoded twins have CPU decodes queued or running, each with how many
/// (`texture/twin_decode.rs`): a batch whose footprint names one waits for them.
@@ -635,6 +641,13 @@ pub(crate) struct State {
}
impl State {
/// The thread's sleep ended at [`WAIT_SLICE`] with nothing having woken it: marked for a pass
/// (the module docs).
fn mark_sliced(&mut self) {
self.dirty = true;
self.sliced = true;
}
/// The ticket of a pass that took batches with submission handlers ([`Turns`]), taken under
/// the lock in the order the passes ran.
fn handler_ticket(&mut self) -> u64 {
@@ -793,6 +806,7 @@ impl Scheduler {
waited: vec![vec![0; queues + crate::device::OWN_TIMELINES]; queues],
binary: BinarySignals::default(),
dirty: false,
sliced: false,
stopping: false,
decodes: BTreeMap::new(),
untracked_decodes: 0,
@@ -1149,6 +1163,10 @@ impl Scheduler {
.zip(gate)
.all(|(queue, &value)| queue.completed_value() >= value)
};
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if trace::completion_wakes_dropped() {
return;
}
// Where the thread waits for the GPU, it waits for the signals the turn saw land: it is
// nudged only for a lost device.
if device.is_lost() {
@@ -1320,6 +1338,11 @@ fn run(shared: &Arc<SchedulerShared>) {
shared.wakings[Woken::Slice as usize].fetch_add(1, Ordering::Relaxed);
}
state = lock(shared.inbox.state());
// A batch held, and a slice gone with no waking: a pass looks again, so a batch whose
// wait was met goes even where the wake for it never came (the module docs).
if timed_out && !short {
state.mark_sliced();
}
}
if state.stopping {
return;
@@ -1395,6 +1418,7 @@ fn wait_for_gpu<'a>(
Some(Ok(())) => {}
Some(Err(vk::Result::TIMEOUT)) if !short => {
shared.wakings[Woken::Slice as usize].fetch_add(1, Ordering::Relaxed);
state.mark_sliced();
}
Some(Err(vk::Result::TIMEOUT)) => {}
// A failed wait (a lost device) or an exit: a pass finds out.
@@ -1554,7 +1578,10 @@ fn pass(
) -> usize {
let taken = take_in(state, commits, &mut passed.spent);
state.dirty = false;
let sliced = state.sliced;
state.sliced = false;
fail_lost(state, left, (&mut passed.spent, &mut passed.settled));
let let_go = passed.spent.len();
let before = passed.handlers.len();
let ready = submit_ready(
state,
@@ -1563,6 +1590,10 @@ fn pass(
&mut passed.handlers,
awaits,
);
// A pass after a slice, taking no commit in, that let a batch go: the wake for it never came.
if let Some(buffer) = (passed.spent.get(let_go)).filter(|_| sliced && taken == 0) {
buffer.device().shared().counts.scheduler_slice_rescued();
}
// Its submission handlers run in this pass's turn ([`Turns`]).
if passed.handlers.len() > before {
let ticket = state.handler_ticket();
@@ -1700,8 +1731,9 @@ fn submit_ready(
let binary = &state.binary;
let decodes = &state.decodes;
let untracked_decodes = state.untracked_decodes;
// The earliest time a head held back for an unshared queue may go before its `VkQueue`'s
// next completion ([`await_unshared_room`]), and whether one was.
// The earliest time a head held back for an unshared queue may go before the completion
// of the oldest batch in flight on its `VkQueue` ([`await_unshared_room`]), and whether
// one was.
let (mut unshared_wake, mut isolating) = (None, false);
let behind = |order: &Order<Held>, sequence| is_behind(order, binary, &mut memo, sequence);
let next = state.order.next(goes_first, behind, |held| {
@@ -1738,9 +1770,9 @@ fn submit_ready(
}
// Held back from a `VkQueue` an unshared queue holds, while other queues' work enough
// is in flight there.
if let Some((queue, after)) = held.buffer.held_for_unshared() {
if let Some(room) = held.buffer.held_for_unshared() {
held.held_for(HeldFor::UnsharedIsolation);
await_unshared_room(held, (queue, after), awaits, &mut unshared_wake);
await_unshared_room(held, room, awaits, &mut unshared_wake);
isolating = true;
return None;
}
@@ -1775,8 +1807,17 @@ fn submit_ready(
drop(busy);
if !waiting && !landing && !holds_back_another_queue(&state.grouped, handlers) {
if let Some(value) = state.group.keeps() {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
trace::at(trace::Point::KeptGate);
// The gate goes to `awaits` before the completed value is read again, as
// [`Scheduler::completions`] says: a completion published since `keeps` read
// it, whose turn found no gate to wake the thread for, is seen here, and the
// group goes now.
awaits.gate_on(state.group.queue(), value, state.values.len());
return Ok(More(false));
fence(Ordering::SeqCst);
if state.group.pending_through(value) {
return Ok(More(false));
}
}
}
let end = match (state.order.is_empty(), left.is_empty()) {
@@ -1896,23 +1937,26 @@ fn goes_first(held: &Held) -> bool {
held.buffer.goes_ahead_of_held_work()
}
/// A head held back from `VkQueue` `queue` for an unshared queue there (`unshared_hold.rs`), the
/// work left ahead falling under the budget in `after` nanoseconds where it does before the next
/// completion: the thread waits for that `VkQueue`'s next completion (`awaits`), and until then at
/// most (`wake`). The gate goes to `awaits` before the completed value is read again, as
/// [`Scheduler::completions`] says: a completion published meanwhile wakes the thread at once.
/// A head held back from `VkQueue` `queue` for an unshared queue there (`unshared_hold.rs`) until
/// the batch there of value `through` completes, the oldest in flight past the completed value the
/// hold read, or, where the work left ahead falls under the budget before then, `after`
/// nanoseconds from now: the thread waits for that value (`awaits`), and until then at most
/// (`wake`). The gate is the value the hold read past, never one past a value read here: a
/// completion of `through` published between the hold's read and this one would leave a gate
/// above every batch in flight, which no completion meets. The gate goes to `awaits` before the
/// completed value is read again, as [`Scheduler::completions`] says: a completion published
/// before it wakes the thread at once, one after meets it.
fn await_unshared_room(
held: &Held,
(queue, after): (usize, Option<u64>),
(queue, through, after): (usize, u64, Option<u64>),
awaits: &Awaits,
wake: &mut Option<Instant>,
) {
let queues = &held.buffer.device().shared().queues;
let seen = queues[queue].completed_value();
awaits.gate_on(queue, seen + 1, queues.len());
awaits.gate_on(queue, through, queues.len());
fence(Ordering::SeqCst);
let now = Instant::now();
let at = match queues[queue].completed_value() > seen {
let at = match queues[queue].completed_value() >= through {
true => Some(now),
false => after.map(|nanos| now + Duration::from_nanos(nanos)),
};
@@ -604,6 +604,8 @@ mod sampler_sets;
mod sampler_table_binders;
mod scheduler;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod scheduler_held_wakes;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod scheduler_wakes;
#[cfg(all(m2v_gpu, target_os = "linux"))]
mod scroll_bos;
@@ -0,0 +1,289 @@
//! A batch the scheduler holds whose wait is met goes, whether or not the wake for it came
//! (`scheduler/mod.rs`, "Idle, it sleeps until it is woken" and "Woken by completions only when
//! they let a batch go"). Each test holds the runtime's threads at fixed points
//! (`completion::trace::hold_at`) to force the interleaving a loaded host makes now and then.
//!
//! - **A kept group's completion, published while it was kept, sends it.** Two submissions of a
//! `VkQueue` run, their completions not yet published, and a third command buffer's batch is held
//! in a group past its pass (`Group::keeps`). Between `keeps`' read of the completed value and the
//! gate it leaves the completion turns, both completions are published and their turns run: they
//! find no gate, and wake nothing. The scheduler reads the value again once it left the gate,
//! and sends the group in that pass: no pass after a slice lets it go
//! (`WorkCounts::scheduler_slice_rescues`).
//! - **A held batch goes at the next slice where its wake never came.** The same group, kept with
//! its gate left and the scheduler asleep; the completion turns wake it for no met wait
//! (`completion::trace::drop_completion_wakes`). The pass after the next sleep that ends at
//! `WAIT_SLICE` sends it, counted as a slice's rescue.
//! - **A batch held back for an unshared queue goes at the completion published as it was looked
//! at** (`unshared_hold.rs`). On a `VkQueue` an unshared queue holds, a queue's first command
//! buffer, of unknown length, runs; its completion is published, its batch not yet out of the
//! `VkQueue`'s flight ([`Point::Leave`]), as the queue's next is committed. The hold reads the
//! published value, so the next goes in that pass, or its gate is one that completion met; it
//! never waits for a slice's pass.
//!
//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects; the kept groups' batches group by
//! `DeviceOptions::assume_submissions_merge`.
use crate::command_buffer::completion::trace::{self, Point};
use crate::{
Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, DeviceKind, DeviceOptions,
ResourceOptions,
};
use metal2vulkan::device::QueueSharingPolicy;
use std::time::{Duration, Instant};
/// How long a held thread, or a command buffer, is waited for.
const BOUND: Duration = Duration::from_secs(5);
/// The device the cfg selects, its batches grouping where `merge`: a CPU device under
/// `m2v_cpu_icd`, else a GPU. Its command queues stay on the `VkQueue`s they were made on
/// (`QueueSharingPolicy::PerQueue`).
fn device(merge: bool) -> Device {
let mut options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
assume_submissions_merge: merge,
..DeviceOptions::default()
};
options.policy.queue_sharing = QueueSharingPolicy::PerQueue;
Device::system_default_with(&options).unwrap()
}
/// A command buffer of `queue` that fills `target` whole with `value`.
fn fill(queue: &CommandQueue, target: &Buffer, value: u8) -> CommandBuffer {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(target, 0..target.length(), value).unwrap();
blit.end_encoding().unwrap();
command_buffer
}
/// The points held, each let go as this drops, a failing test's unwinding too.
struct Held(Vec<Point>);
impl Held {
fn at(&mut self, point: Point) {
trace::hold_at(point);
self.0.push(point);
}
}
impl Drop for Held {
fn drop(&mut self) {
for &point in &self.0 {
trace::release(point);
}
trace::drop_completion_wakes(false);
}
}
/// On `device`'s `queue`, a group kept past its pass: two command buffers submitted, each alone
/// (waited for as scheduled), whose completions the queue waiters hold unpublished
/// ([`Point::Publish`]); then a third, `kept`, committed, whose batch the scheduler holds in a
/// group and keeps, held at [`Point::KeptGate`]. The two submitted first.
fn kept_group(
queue: &CommandQueue,
target: &Buffer,
held: &mut Held,
) -> (CommandBuffer, CommandBuffer, CommandBuffer) {
held.at(Point::Publish);
let first = fill(queue, target, 1);
first.commit().unwrap();
first.wait_until_scheduled().unwrap();
let second = fill(queue, target, 2);
second.commit().unwrap();
second.wait_until_scheduled().unwrap();
held.at(Point::KeptGate);
let kept = fill(queue, target, 3);
kept.commit().unwrap();
assert!(
trace::reached(Point::KeptGate, BOUND),
"the third command buffer's group was not kept past its pass"
);
(first, second, kept)
}
/// Poll `command_buffer`'s status, never waiting for it (a waiter sends a kept group), until it
/// completed, at most [`BOUND`]; how long that took.
fn completes(command_buffer: &CommandBuffer, what: &str) -> Duration {
let start = Instant::now();
while command_buffer.status() != CommandBufferStatus::Completed {
assert!(start.elapsed() < BOUND, "{what} never completed");
std::thread::sleep(Duration::from_millis(1));
}
start.elapsed()
}
/// The first and the warm-up: `queue`'s first work, completed, untimed.
fn warm(queue: &CommandQueue, target: &Buffer) {
let first = fill(queue, target, 0);
first.commit().unwrap();
first.wait_until_completed().unwrap();
}
#[test]
fn a_kept_group_whose_completion_was_published_as_it_was_kept_goes_in_that_pass() {
let device = device(true);
let queue = device.new_command_queue().unwrap();
let target = device
.new_buffer(1 << 16, ResourceOptions::private())
.unwrap();
warm(&queue, &target);
let before = device.work_counts();
let mut held = Held(Vec::new());
let (first, second, kept) = kept_group(&queue, &target, &mut held);
// Both completions published, and their turns' looks for a met gate made (each before its
// command buffer completes), while the scheduler has yet to leave the group's gate.
trace::release(Point::Publish);
completes(&first, "the first command buffer");
completes(&second, "the second command buffer");
trace::release(Point::KeptGate);
let took = completes(&kept, "the kept command buffer");
let after = device.work_counts();
let rescues = after.scheduler_slice_rescues - before.scheduler_slice_rescues;
let kept_groups = after.groups_kept_pending - before.groups_kept_pending;
println!(
"HELD-WAKES kept gate: completed {took:?} after the gate was let go; {kept_groups} \
groups kept, {rescues} slice rescues"
);
assert!(kept_groups > 0, "no group was kept");
assert_eq!(
rescues, 0,
"the kept group went only at a slice: the completion published as it was kept woke nothing"
);
}
#[test]
fn a_held_batch_whose_wake_never_came_goes_at_the_next_slice() {
let device = device(true);
let queue = device.new_command_queue().unwrap();
let target = device
.new_buffer(1 << 16, ResourceOptions::private())
.unwrap();
warm(&queue, &target);
let mut held = Held(Vec::new());
let (first, second, kept) = kept_group(&queue, &target, &mut held);
let before = device.work_counts();
// The gate left and the scheduler asleep, then the completions published with no wake for
// it.
trace::drop_completion_wakes(true);
trace::release(Point::KeptGate);
let start = Instant::now();
while !device.shared().scheduler.asleep() {
assert!(start.elapsed() < BOUND, "the scheduler never slept");
std::thread::sleep(Duration::from_millis(1));
}
trace::release(Point::Publish);
completes(&first, "the first command buffer");
completes(&second, "the second command buffer");
let took = completes(&kept, "the kept command buffer");
let after = device.work_counts();
let rescues = after.scheduler_slice_rescues - before.scheduler_slice_rescues;
let slices = after.scheduler_sleep_slices - before.scheduler_sleep_slices;
println!(
"HELD-WAKES lost wake: completed {took:?} after the completions were published; \
{slices} slices, {rescues} slice rescues"
);
assert!(rescues > 0, "the kept group went with no slice's pass");
}
/// An unshared queue made on `queue`'s `VkQueue`, the queues made on the way kept; none where 64
/// went elsewhere (a device that gives unshared queues `VkQueue`s of their own holds nothing back
/// for them).
fn unshared_beside(device: &Device, queue: &CommandQueue) -> Option<Vec<CommandQueue>> {
let at = queue.vk_queue_sharing().0;
let mut made = Vec::new();
for _ in 0..64 {
let unshared = device.new_command_queue_unshared(64).unwrap();
let there = unshared.vk_queue_sharing().0 == at;
made.push(unshared);
if there {
return Some(made);
}
}
None
}
#[test]
fn a_batch_held_for_an_unshared_queue_goes_at_the_completion_published_as_it_was_looked_at() {
let device = device(false);
let queue = device.new_command_queue().unwrap();
let Some(_unshared) = unshared_beside(&device, &queue) else {
println!("HELD-WAKES unshared: no unshared queue shares a VkQueue here; nothing is held");
return;
};
assert!(device.settle_queue_switch_check(BOUND), "the check settles");
let index = queue.vk_queue_sharing().0;
assert!(device.holds_back_for_unshared(index));
let slot = &device.shared().queues[index];
let target = device
.new_buffer(1 << 16, ResourceOptions::private())
.unwrap();
// Every value submitted there seen complete, so the completion held next is the first
// command buffer's.
let start = Instant::now();
while slot.completed_value() < slot.submitted_value() {
assert!(start.elapsed() < BOUND, "the VkQueue never went idle");
std::thread::sleep(Duration::from_millis(1));
}
let mut held = Held(Vec::new());
held.at(Point::Leave);
// The queue's first command buffer: of unknown length, so the next waits for its completion.
let ahead = fill(&queue, &target, 1);
ahead.commit().unwrap();
ahead.wait_until_scheduled().unwrap();
let value = slot.submitted_value();
assert!(
trace::reached(Point::Leave, BOUND),
"the first command buffer's completion was never published"
);
assert_eq!(
slot.completed_value(),
value,
"the completion held is the first command buffer's"
);
let before = device.work_counts();
let passes = device.shared().scheduler.passes();
let behind = fill(&queue, &target, 2);
behind.commit().unwrap();
// The scheduler's thread looked at it: it went, or it is held and the thread sleeps.
let start = Instant::now();
loop {
let went = matches!(
behind.status(),
CommandBufferStatus::Scheduled | CommandBufferStatus::Completed
);
let held_back = device.work_counts().heads_held_for_unshared_isolation
> before.heads_held_for_unshared_isolation;
let slept =
device.shared().scheduler.passes() > passes && device.shared().scheduler.asleep();
if went || (held_back && slept) {
break;
}
assert!(start.elapsed() < BOUND, "the scheduler never looked at it");
std::thread::sleep(Duration::from_millis(1));
}
let went = behind.status();
trace::release(Point::Leave);
let took = completes(&behind, "the command buffer behind");
completes(&ahead, "the first command buffer");
let after = device.work_counts();
let rescues = after.scheduler_slice_rescues - before.scheduler_slice_rescues;
let looks = after.heads_held_for_unshared_isolation - before.heads_held_for_unshared_isolation;
println!(
"HELD-WAKES unshared: {went:?} as the completion was let go, completed {took:?} after; \
{looks} looks held it, {rescues} slice rescues"
);
assert_eq!(
rescues, 0,
"the command buffer behind went only at a slice: the completion published as it was \
looked at woke nothing"
);
}
@@ -7,9 +7,10 @@
//! - **The flight.** Other queues' batches count their expected runs, an unshared queue's none;
//! the oldest one's run so far counts against its own expected run alone; a batch may go while
//! less than the budget is left and none of unknown length is in flight, else it waits for the
//! next completion, or for the time the oldest one's expected run brings the work left under
//! the budget; a run several batches complete in is shared among the other queues' batches, an
//! unshared queue's taking none.
//! oldest one's completion, or for the time the oldest one's expected run brings the work left
//! under the budget; a batch whose completion was published counts as left before it leaves; a
//! run several batches complete in is shared among the other queues' batches, an unshared
//! queue's taking none.
use crate::unshared_hold::{Expected, Flies, Flight, Room, BUDGET};
use std::sync::Arc;
@@ -35,22 +36,23 @@ fn a_queue_with_no_run_seen_has_no_expected_run() {
fn a_batch_of_unknown_length_holds_the_next_back_until_it_completes() {
let app = Arc::new(Expected::default());
let mut flight = Flight::default();
assert_eq!(flight.ahead(0), Room::Go, "the first goes");
assert_eq!(flight.ahead(0, 0), Room::Go, "the first goes");
flight.taken(1, Flies::Other(&app));
assert_eq!(flight.ahead(0), Room::Hold { after: None });
assert_eq!(
flight.ahead(500 * MS),
Room::Hold { after: None },
"however long it has run"
);
let first = Room::Hold {
after: None,
through: 1,
};
assert_eq!(flight.ahead(0, 0), first);
assert_eq!(flight.ahead(500 * MS, 0), first, "however long it has run");
flight.completed(1, 30 * MS);
assert_eq!(app.nanos(), Some(30 * MS));
assert_eq!(flight.ahead(0), Room::Go);
assert_eq!(flight.ahead(0, 0), Room::Go);
flight.taken(2, Flies::Other(&app));
assert_eq!(
flight.ahead(0),
flight.ahead(0, 0),
Room::Hold {
after: Some(28 * MS + 1)
after: Some(28 * MS + 1),
through: 2
}
);
}
@@ -84,7 +86,7 @@ fn a_queue_whose_batches_got_short_is_let_ahead_again_within_five_of_them() {
value += 1;
flight.taken(value, Flies::Other(&app));
// Another of its batches is ready as this one starts.
if flight.ahead(0) == Room::Go {
if flight.ahead(0, 0) == Room::Go {
break;
}
flight.completed(value, MS);
@@ -108,7 +110,7 @@ fn an_unshared_queue_s_batches_count_no_work_ahead() {
for value in 1..=8 {
flight.taken(value, Flies::Unshared);
}
assert_eq!(flight.ahead(0), Room::Go);
assert_eq!(flight.ahead(0, 0), Room::Go);
flight.taken(9, Flies::Not);
assert_eq!(flight.len(), 8, "a batch that flies not is not kept");
}
@@ -120,30 +122,36 @@ fn a_batch_goes_while_less_than_the_budget_is_left_ahead() {
flight.taken(1, Flies::Other(&app));
// 30 ms left at its start: held until 28 ms of it ran, or its completion.
assert_eq!(
flight.ahead(0),
flight.ahead(0, 0),
Room::Hold {
after: Some(28 * MS + 1)
after: Some(28 * MS + 1),
through: 1
}
);
assert_eq!(
flight.ahead(10 * MS),
flight.ahead(10 * MS, 0),
Room::Hold {
after: Some(18 * MS + 1)
after: Some(18 * MS + 1),
through: 1
}
);
assert_eq!(flight.ahead(28 * MS + 1), Room::Go);
assert_eq!(flight.ahead(28 * MS + 1, 0), Room::Go);
// The next one went: 30 ms more ahead, which the oldest's run left does not cover.
flight.taken(2, Flies::Other(&app));
assert_eq!(flight.ahead(29 * MS), Room::Hold { after: None });
let both = Room::Hold {
after: None,
through: 1,
};
assert_eq!(flight.ahead(29 * MS, 0), both);
// An overrun counts the oldest's expected run alone.
assert_eq!(flight.ahead(90 * MS), Room::Hold { after: None });
assert_eq!(flight.ahead(90 * MS, 0), both);
flight.completed(1, 31 * MS);
assert_eq!(
app.nanos(),
Some(31 * MS),
"its run raised the queue's expected one"
);
assert_eq!(flight.ahead(29 * MS + 1), Room::Go);
assert_eq!(flight.ahead(29 * MS + 1, 0), Room::Go);
}
#[test]
@@ -164,10 +172,10 @@ fn a_run_several_batches_complete_in_is_shared_among_the_other_queues_batches()
assert_eq!(second.nanos(), Some(4 * MS + MS / 2));
assert_eq!(flight.len(), 1, "the fourth is still in flight");
// Its own expected run was taken at its submission: 1 ms, under the budget.
assert_eq!(flight.ahead(0), Room::Go);
assert_eq!(flight.ahead(0, 0), Room::Go);
flight.completed(4, MS);
assert_eq!(flight.len(), 0);
assert_eq!(flight.ahead(0), Room::Go);
assert_eq!(flight.ahead(0, 0), Room::Go);
}
/// An application's 30 ms batch and the compositor's light one behind it, seen complete together:
@@ -183,9 +191,10 @@ fn an_unshared_batch_seen_complete_with_another_queue_s_leaves_it_the_whole_run(
assert_eq!(app.nanos(), Some(30 * MS));
flight.taken(3, Flies::Other(&app));
assert_eq!(
flight.ahead(14 * MS),
flight.ahead(14 * MS, 0),
Room::Hold {
after: Some(14 * MS + 1)
after: Some(14 * MS + 1),
through: 3
},
"half way through the next one, no other goes"
);
@@ -195,3 +204,35 @@ fn an_unshared_batch_seen_complete_with_another_queue_s_leaves_it_the_whole_run(
flight.completed(4, MS / 10);
assert_eq!(app.nanos(), Some(30 * MS));
}
/// A completion publishes its value before it takes its batches out of the flight
/// (`QueueSlot::completed`): the batches at or below it count as left already, so a held batch's
/// gate is never one the published value passed, and the oldest batch past them has no run yet.
#[test]
fn a_batch_whose_completion_was_published_counts_as_left_before_it_leaves() {
let app = Arc::new(Expected::default());
let mut flight = Flight::default();
flight.taken(1, Flies::Other(&app));
assert_eq!(
flight.ahead(0, 0),
Room::Hold {
after: None,
through: 1
}
);
assert_eq!(flight.ahead(0, 1), Room::Go, "published, not yet out");
let long = queue(30 * MS);
let mut flight = Flight::default();
flight.taken(1, Flies::Other(&long));
flight.taken(2, Flies::Other(&long));
assert_eq!(
flight.ahead(20 * MS, 1),
Room::Hold {
after: Some(28 * MS + 1),
through: 2
},
"the second's run counts from the first's completion, not the first's run"
);
assert_eq!(flight.ahead(0, 2), Room::Go);
assert_eq!(flight.len(), 2, "neither left");
}
@@ -34,10 +34,13 @@
//! gives its queue a run. So an application that commits several command buffers at once does
//! not put them all ahead of a compositor's before the first is seen; it costs the GPU one
//! completion's turn, once per such queue.
//! - **When it goes.** A pass that holds a batch so leaves the scheduler's thread waiting for its
//! `VkQueue`'s next completion (a gate, `scheduler/mod.rs`'s `Awaits`), and, where the oldest
//! batch's expected run still covers it, for the time the work left ahead falls under the
//! budget. A committing or waiting thread's own pass leaves such a batch to the scheduler's
//! - **When it goes.** A pass that holds a batch so leaves the scheduler's thread waiting for the
//! completion of the oldest batch in flight there (a gate on its value, `scheduler/mod.rs`'s
//! `Awaits`), and, where the oldest batch's expected run still covers it, for the time the work
//! left ahead falls under the budget. The hold is decided on the value the host published as
//! completed: a batch at or below it counts as left, though the completion that published it
//! has yet to take it out of the flight ([`Flight::ahead`]), so the gate a hold leaves is one
//! that value has not reached, and its completion wakes the thread. A committing or waiting thread's own pass leaves such a batch to the scheduler's
//! thread, which it wakes. A pass that finds such a batch let go and an unshared queue's
//! command buffer ready together on its `VkQueue` sends the unshared one first
//! (`scheduler/order.rs`, "Heads put first"): a pass the host ran late, after the room came,
@@ -130,10 +133,11 @@ pub(crate) struct Flight {
pub(crate) enum Room {
/// Less than [`BUDGET`] of other queues' expected work is left in flight.
Go,
/// [`BUDGET`] or more, or a batch of unknown length is in flight: held until the `VkQueue`'s
/// next completion, or, where only the budget holds it, until `after` nanoseconds from now,
/// where the oldest batch's expected run brings the work left under the budget then.
Hold { after: Option<u64> },
/// [`BUDGET`] or more, or a batch of unknown length is in flight: held until the oldest batch
/// in flight, of value `through`, completes, or, where only the budget holds it, until `after`
/// nanoseconds from now, where the oldest batch's expected run brings the work left under the
/// budget then.
Hold { after: Option<u64>, through: u64 },
}
impl Flight {
@@ -181,20 +185,45 @@ impl Flight {
}
/// Whether another queue's batch may go now, the oldest batch in flight having run `ran`
/// nanoseconds since it became so (the module docs).
pub(crate) fn ahead(&self, ran: u64) -> Room {
if self.unseen > 0 {
return Room::Hold { after: None };
/// nanoseconds since it became so (the module docs), the host having seen the timeline reach
/// `completed`. A batch at or below `completed` counts as left: its completion was published
/// before it takes it out ([`Flight::completed`]), so the answer follows the published value
/// alone, which a held batch's gate is read against. The oldest batch past it became so at
/// that completion, so none of its run counts yet.
pub(crate) fn ahead(&self, ran: u64, completed: u64) -> Room {
let left_already = self
.batches
.iter()
.take_while(|batch| batch.value <= completed);
let (gone, gone_expected, gone_unseen) =
left_already.fold((0, 0, 0), |(gone, expected, unseen), batch| {
(
gone + 1,
expected + batch.expected,
unseen + usize::from(batch.unseen),
)
});
let Some(oldest) = self.batches.get(gone) else {
return Room::Go;
};
let through = oldest.value;
if self.unseen > gone_unseen {
return Room::Hold {
after: None,
through,
};
}
let front = self.batches.front().map_or(0, |batch| batch.expected);
let credit = ran.min(front);
let left = self.expected - credit;
let credit = match gone {
0 => ran.min(oldest.expected),
_ => 0,
};
let left = self.expected - gone_expected - credit;
if left < BUDGET {
return Room::Go;
}
let over = left - BUDGET + 1;
let after = (front - credit >= over).then_some(over);
Room::Hold { after }
let after = (oldest.expected - credit >= over).then_some(over);
Room::Hold { after, through }
}
/// The batches in flight, of every queue.
+14 -1
View File
@@ -271,6 +271,7 @@ pub(crate) struct Counters {
batches_by_pending: [AtomicU64; 4],
groups_kept_pending: AtomicU64,
groups_sent_for_waits: AtomicU64,
scheduler_slice_rescues: AtomicU64,
/// By `HeldFor`, in its order: the looks that found a line's head held for each reason.
heads_held_for: [AtomicU64; HeldFor::COUNT],
heads_waiting_at_their_gate: AtomicU64,
@@ -3075,6 +3076,12 @@ impl Counters {
self.group_ends[end as usize].fetch_add(1, Ordering::Relaxed);
}
/// A pass after the scheduler's sleep ended at its longest wait let a batch go: a wake that
/// should have come did not (`scheduler/mod.rs`).
pub(crate) fn scheduler_slice_rescued(&self) {
self.scheduler_slice_rescues.fetch_add(1, Ordering::Relaxed);
}
/// A group of batches stayed held past the pass that found no batch ready, for the work its
/// `VkQueue` still ran (`command_buffer/group.rs`); once per group.
pub(crate) fn group_kept_pending(&self) {
@@ -6766,8 +6773,13 @@ pub struct WorkCounts {
/// for made, a texture decode finished, a command buffer encoded again after a rebind, the
/// rest of a pass a thread about to block or a committing thread left it, a lost device.
pub scheduler_wakes_host: u64,
/// Sleeps that ended at the thread's longest wait with nothing having woken it.
/// Sleeps that ended at the thread's longest wait with nothing having woken it. Each, with a
/// batch held, is followed by a pass.
pub scheduler_sleep_slices: u64,
/// Of the passes after those sleeps, the ones that let a batch go (submitted, held in a
/// group, or failed): what it waited for was met, and the wake that should have come with it
/// did not (`scheduler/mod.rs`). 0 where every wake comes.
pub scheduler_slice_rescues: u64,
/// Passes a thread about to block for a command buffer's completion made over the scheduler's
/// order itself, instead of waiting for the scheduler's thread to make one
/// (`CommandBuffer::wait_until_completed`, `scheduler/mod.rs`): one where the batches it
@@ -10327,6 +10339,7 @@ impl Device {
scheduler_wakes_completion: by_completion,
scheduler_wakes_host: by_host,
scheduler_sleep_slices: by_slice,
scheduler_slice_rescues: counters.scheduler_slice_rescues.load(Ordering::Relaxed),
scheduler_gpu_waits: gpu_waits,
scheduler_passes: self.shared().scheduler.passes(),
scheduler_passes_by_waiters: counters
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 518;
/// 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 = 2231;
pub const RUNTIME_VERSION: u32 = 2232;
/// 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
@@ -3381,6 +3381,7 @@ field metal2vulkan-runtime::WorkCounts.scheduler_passes pub scheduler_passes: u6
field metal2vulkan-runtime::WorkCounts.scheduler_passes_at_commit pub scheduler_passes_at_commit: u64
field metal2vulkan-runtime::WorkCounts.scheduler_passes_by_waiters pub scheduler_passes_by_waiters: u64
field metal2vulkan-runtime::WorkCounts.scheduler_sleep_slices pub scheduler_sleep_slices: u64
field metal2vulkan-runtime::WorkCounts.scheduler_slice_rescues pub scheduler_slice_rescues: u64
field metal2vulkan-runtime::WorkCounts.scheduler_sleeps pub scheduler_sleeps: u64
field metal2vulkan-runtime::WorkCounts.scheduler_wakes_commit pub scheduler_wakes_commit: u64
field metal2vulkan-runtime::WorkCounts.scheduler_wakes_completion pub scheduler_wakes_completion: u64
Can't render this file because it is too large.