Files
metal2vulkan/crates/metal2vulkan-runtime/src/unshared_hold.rs
T
Anees Iqbal c7d652ca5e 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.
2026-11-13 11:22:48 -08:00

260 lines
13 KiB
Rust

//! Other command queues' work held back from a `VkQueue` an unshared queue shares with them
//! (`UnsharedIsolationPolicy::Bounded`, the default): only about [`BUDGET`] of their expected GPU
//! work is submitted ahead of the unshared queue's next command buffer.
//!
//! - **Why.** A `VkQueue` runs its submissions in order. On a device whose graphics family has
//! one queue (RADV, ANV, lavapipe), every command queue submits to it,
//! `Device::new_command_queue_unshared`'s (a compositor's) included, so a compositor's light
//! command buffer waits for every batch submitted before it there. On a Radeon 780M (RADV,
//! Mesa 26.2.6), a compositor committing one draw every 16 ms beside an application keeping
//! three 30 ms command buffers in flight waited 76 ms at the median and 112 ms at worst, every
//! one of its frames over 16 ms, with 7 batches in flight ahead of it on average. The kernel
//! does not reorder within a `VkQueue`, and another `VkDevice`'s work (its own kernel context on
//! i915) interleaves only between submissions, never inside one, whatever its priority.
//! - **Where.** A batch of a command queue not made unshared, on a `VkQueue` that an unshared
//! queue holds (`SlotShare::unshared`), on a device whose policy is `Bounded`. Where an unshared
//! queue has a `VkQueue` of its own, no other command queue's batch goes there, and nothing is
//! held.
//! - **The bound.** Such a batch, otherwise ready, is submitted only while less than [`BUDGET`] of
//! expected GPU work of other queues' batches is left in flight on its `VkQueue` ([`Flight`]):
//! the expected runs of the batches submitted there and not seen complete, less what the oldest
//! one has run since it became the oldest, up to its own expected run. So an unshared queue's
//! command buffer goes in behind about one batch of theirs, and the next batch goes in before
//! the one ahead of it ends, so the GPU is not left idle between them. A held batch keeps its
//! place in the scheduler's order (`scheduler/order.rs`): a later commit of another queue whose
//! footprint runs in commit order with it waits behind it, as behind any held batch.
//! - **Expected runs** ([`Expected`]). Each command queue's: the host's view of how long its
//! recent batches ran as their `VkQueue`'s oldest in flight (`queue_wait.rs`'s runs), raised at
//! once by a longer one and halved toward a shorter one, so a queue whose batches got shorter
//! takes its new length within a few batches, while one long batch counts at once. A run several
//! batches complete in shares among the other queues' batches among them; an unshared queue's
//! takes no share.
//! - **Unknown length.** A batch of a queue with no run seen yet may be of any length: while one
//! is in flight, no other batch of the other queues goes there until it is seen complete, which
//! 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 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,
//! would otherwise put the whole batch ahead of it.
//! - **What it costs.** A batch longer than its queue's recent ones still holds the unshared
//! queue's command buffer for its whole length: one command buffer's batch is one submission,
//! which the GPU runs to its end. The next batch goes in about [`BUDGET`] before the one ahead
//! ends, where `Off` keeps every ready batch queued, so the GPU waits for the scheduler's thread
//! where the host's CPU is loaded: on the Iris Xe at a load of about 10, an application's 5 ms
//! command buffers ran 181.8 a second against 189.3 (docs/FAST-PATHS.md); on a quiet host no
//! throughput was lost. Every batch on such a `VkQueue` costs a place in its [`Flight`] and a
//! lock of its own at the submission and the completion. Counted:
//! `WorkCounts::heads_held_for_unshared_isolation` (each look that held a head so).
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
/// The expected GPU work of other queues' batches, in nanoseconds, below which another of their
/// batches is submitted to a `VkQueue` an unshared queue holds: 2 ms, the length past which a
/// command buffer marks its queue long where queues share `VkQueue`s (`queue_share::LONG_HEAD`).
pub(crate) const BUDGET: u64 = 2_000_000;
/// A command queue's expected run of one batch (the module docs), in nanoseconds; 0 before the
/// first is seen.
#[derive(Debug, Default)]
pub(crate) struct Expected(AtomicU64);
impl Expected {
/// The run its next batch is expected to take: none where none was seen.
pub(crate) fn nanos(&self) -> Option<u64> {
match self.0.load(Ordering::Relaxed) {
0 => None,
nanos => Some(nanos),
}
}
/// One of its batches ran `run` nanoseconds: taken at once where longer, halved toward it
/// where shorter.
pub(crate) fn observed(&self, run: u64) {
let run = run.max(1);
let _ = (self.0).try_update(Ordering::Relaxed, Ordering::Relaxed, |was| {
Some(match was {
0 => run,
was if run >= was => run,
was => was - (was - run) / 2,
})
});
}
}
/// How a batch taken on a `VkQueue` enters its [`Flight`].
pub(crate) enum Flies<'a> {
/// Not at all: no unshared queue holds the `VkQueue`, or the device's policy is `Off`.
Not,
/// As an unshared queue's: in flight, with no expected run of other queues' work.
Unshared,
/// As another queue's, with its queue's expected run.
Other(&'a Arc<Expected>),
}
/// One batch in a [`Flight`].
#[derive(Debug)]
struct InFlight {
/// Its value of its `VkQueue`'s timeline.
value: u64,
/// Its expected run, counted in [`Flight::expected`]; 0 for an unshared queue's, and for one
/// whose queue had no run seen.
expected: u64,
/// Its queue had no run seen at its submission: of unknown length.
unseen: bool,
/// Its queue's expected run, which its run updates; none for an unshared queue's.
of: Option<Arc<Expected>>,
}
/// The batches taken on one `VkQueue` an unshared queue holds and not seen complete
/// (`queue_wait::Ahead::flight`), under that `VkQueue`'s waits' lock.
#[derive(Debug, Default)]
pub(crate) struct Flight {
/// In the order of their values, which rises.
batches: VecDeque<InFlight>,
/// The expected runs of the other queues' among them, summed.
expected: u64,
/// How many among them are of unknown length.
unseen: usize,
}
/// Whether a batch may go to a `VkQueue` now ([`Flight::ahead`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
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 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 {
/// A batch took `value`, entering as `flies` says.
pub(crate) fn taken(&mut self, value: u64, flies: Flies<'_>) {
let (expected, of) = match flies {
Flies::Not => return,
Flies::Unshared => (Some(0), None),
Flies::Other(of) => (of.nanos(), Some(Arc::clone(of))),
};
let unseen = expected.is_none();
let expected = expected.unwrap_or(0);
self.expected += expected;
self.unseen += usize::from(unseen);
self.batches.push_back(InFlight {
value,
expected,
unseen,
of,
});
}
/// The host saw the timeline reach `value`, `run` nanoseconds after the oldest batch in flight
/// became so: each batch at or below `value` leaves, and each other queue's among them updates
/// its queue's expected run with an equal share of `run`. An unshared queue's batch takes no
/// share: a compositor's light batch is seen complete with the application's batch ahead of
/// it, and a share of that batch's run would halve the application's expected one.
pub(crate) fn completed(&mut self, value: u64, run: u64) {
let done = self
.batches
.iter()
.take_while(|batch| batch.value <= value)
.count();
let others = (self.batches.iter().take(done))
.filter(|batch| batch.of.is_some())
.count();
let share = run / others.max(1) as u64;
for batch in self.batches.drain(..done) {
self.expected -= batch.expected;
self.unseen -= usize::from(batch.unseen);
if let Some(of) = batch.of {
of.observed(share);
}
}
}
/// Whether another queue's batch may go now, the oldest batch in flight having run `ran`
/// 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 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 = (oldest.expected - credit >= over).then_some(over);
Room::Hold { after, through }
}
/// The batches in flight, of every queue.
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.batches.len()
}
}
impl crate::Device {
/// Whether other queues' batches are held back from `VkQueue` `index` (the module docs): an
/// unshared queue holds it, and the device's policy is `Bounded`.
pub(crate) fn holds_back_for_unshared(&self, index: usize) -> bool {
self.holds_unshared(index)
&& self.compile_device().policy().unshared_isolation
== metal2vulkan::device::UnsharedIsolationPolicy::Bounded
}
/// How a batch of a command queue (`unshared` where made so) taken on `VkQueue` `index` enters
/// its flight, `expected` its queue's expected run.
pub(crate) fn flies<'a>(
&self,
index: usize,
unshared: bool,
expected: &'a Arc<Expected>,
) -> Flies<'a> {
match (self.holds_back_for_unshared(index), unshared) {
(false, _) => Flies::Not,
(true, true) => Flies::Unshared,
(true, false) => Flies::Other(expected),
}
}
}