On ANV over i915 every kernel submission lists every VkDeviceMemory of the device, at a cost per
object; the consumer's guest drag on the Iris Xe had 302 entries per execbuffer (260 of them host
imports) at 112 to 128 execbuffers a frame. The runtime now makes fewer kernel submissions and
fewer command buffers per frame, under two new runtime policies.
What changes:
- DevicePolicy::completion, CompletionPolicy { Grouped (default), Exact }; exact_answers()
selects Exact. Under Grouped, on a driver whose queue merges consecutive submits (Mesa's common
queue: ANV, RADV, lavapipe, NVK and the rest), the scheduler holds ready batches of one VkQueue
and submits up to four in one vkQueueSubmit, only the last signalling, so Mesa merges them into
one kernel submission:
- a batch whose only signals are events' joins, the group's end signalling each event to the
highest index held; a batch waiting for a signal the group holds sends the group first;
- only a group's first member may wait for anything not yet seen complete, since Mesa gathers
every member's waits before the first member's commands; a later waiter goes alone after the
group in the same call. Metal never holds one command buffer back for another's wait;
- batches that cannot join (first work, binary semaphores, fences, sparse updates, wrapped
images, storage-form switches) submit the held group first;
- a pass that finds nothing ready keeps the group held while two or more earlier submissions of
its queue are not seen complete, gated on the second-to-last, so commits arriving meanwhile
join. It goes once full, when a head waits for the GPU, or when a thread waits for one of its
command buffers;
- a held batch that ends its command buffer turns Scheduled, takes its kernel end time and runs
its submission handlers as it is held, so waitUntilScheduled returns at once, as Metal
schedules a command buffer committed behind running work within 0.2 ms;
- submission checks run ahead for up to three batches behind a line's head, so checked command
buffers are found ready together; a failed group restores its waits, signals its last value
and fails each member once; the group's submission allocates nothing.
New degradation kind grouped-completion (Precision), announced once per device: a group's
members but the last are seen complete late, by at most three later batches' GPU time plus one
completion turn, and intermediate event values are seen late, never wrong.
- An event-signalling batch's end goes into its work's last command buffer, as every other batch's,
unless its signal must wait for another queue's earlier signal.
- DevicePolicy::batch_order, BatchOrderPolicy { Ends (default), Exact }; exact_answers() selects
Exact. On ANV, RADV and NVIDIA's driver, measured to run a queue's submissions one after another,
each batch ends with a barrier to every later command of its queue, the tracker takes an earlier
batch of that queue as ordered (no barrier per dependency), and a batch's start timestamp with
nothing planned before it is written at the bottom of the pipe. Other drivers and Exact keep the
barriers per dependency.
- WorkCounts: grouped_submissions, batches_grouped, group_ends_full / _wait / _apart /
_first_work / _drained / _checks / _held, event_waits_met, batches_with_none_pending and kin by
pending depth, groups_kept_pending and groups_sent_for_waits; frame_costs prints them, with
kernel submissions and ioctl time where the i915 execbuffer script is loaded, and gains guest-
shaped legs over 260 and 520 host imports.
- Docs: FAST-PATHS rows for both policies (the grouping row with the guest's frame rates), API.md
entries, add_submission_handler's doc, the runtime README and the scheduler modules' docs.
Why: each fewer kernel submission saves the scheduler thread an ioctl of about 80 to 130 us there,
and each barrier per dependency buys nothing on drivers that run a queue's submissions in order.
The bound of four was kept: eight measured about three fewer submissions a frame for twice the
completion lateness and no frame-time change.
Verified:
- Iris Xe, guest shape over 520 host imports, Grouped against Exact: 26.2-26.7 execbuffers a frame
against 67.0, ioctl 2.77-2.81 against 6.89-6.96 ms, scheduler 52-53 against 122-123 us per
command buffer, through completion 5.98 against 8.70 ms a frame.
- UHD 770, the held group at a 1 ms commit pace: 25.0 kernel submissions a frame against 58.1,
scheduler 67-82 against 113-124 us per command buffer, the same frame time and GPU idle;
completion seen 1.82-1.86 ms after GPU end against 0.43-0.46 ms.
- In the guest on the Iris Xe, Grouped made 24.4-27.5 kernel submissions a frame against Exact's
42.4-43.8 and saved 0.4-1.7 ms of scheduler CPU a frame; the frame rate was alike within
boot-to-boot noise (15.7-17.3 against 16.4-17.6 fps).
- runtime_lane::grouped_submissions (held signals on one and two queues, waiters leading, groups
held behind running work with and without submission handlers and checks, both policies, the
validation layer silent): 19 of 19 on ANV and lavapipe; the held-handler case fails without its
change. commit_work, gpu_times, grouped_submissions, queue_order, events and first-use lanes 77 of
77 on the Radeon 780M, RX 7900 XTX and RTX 5080; under synchronization validation 34 of 34 on
the UHD 770. The runtime's device tests 1066 of 1066 on ANV; the unit suites 4534 of 4534.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
231 lines
9.1 KiB
Rust
231 lines
9.1 KiB
Rust
//! Waits from inside the runtime's handler threads: what a command buffer wait answers when it is
|
|
//! called from a scheduled handler, a completed handler, or a deallocator that runs as a command
|
|
//! buffer releases what it retained.
|
|
//!
|
|
//! Those run in their queue's serial context ([`contexts`](crate::contexts)): a queue's
|
|
//! transitions to `Scheduled` and to `Completed`, with their handlers, run one at a time in the
|
|
//! queue's order. A wait there for a transition still to come in the same queue would wait for
|
|
//! itself.
|
|
//!
|
|
//! Metal's answers (measured on an M4 with macOS 27.0.1, with and without API validation, EVs
|
|
//! `RT4-metal-selfwait`, `-selfwait2`, `-selfwait3` and `RT4-metal-order`):
|
|
//! - a deallocator run as Metal releases a buffer returns from its wait for the completion of the
|
|
//! command buffer that held it; the runtime returns too;
|
|
//! - a completed handler returns from its wait for its command buffer's scheduling; so does the
|
|
//! runtime (that transition ran before);
|
|
//! - a handler's wait for its own command buffer's transition in progress, and for any later
|
|
//! transition of its queue (a command buffer committed after its own, before or inside the
|
|
//! handler), never returns, even when that command buffer's work already ran. The runtime does
|
|
//! not copy the hang: it refuses those waits at once (`Error::WaitWouldDeadlock` of
|
|
//! `DeadlockCause::OwnQueue`, or `TimedOut` for the bounded wait);
|
|
//! - a handler's wait for a command buffer of another queue returns, whether that command buffer
|
|
//! was committed before the handler or inside it; so does the runtime's. It blocks the handler's
|
|
//! thread, counted ([`Waits`]), and is refused only where it would deadlock: when it would
|
|
//! close a cycle of such waits, or leave its device's pool with no thread that is not blocked
|
|
//! so (`contexts::block`).
|
|
//!
|
|
//! A submission handler (a runtime extension, Metal has none) runs on the thread that took its
|
|
//! command buffer's last batch for its queue, and that command buffer's transition to `Scheduled`,
|
|
//! with every later transition of its queue, waits for it. On the scheduler thread, the device's
|
|
//! later submissions wait for it too. So any wait there for what has not happened (a command
|
|
//! buffer's scheduling or completion, a slot of a full queue no uncommitted command buffer holds)
|
|
//! is refused at once (`DeadlockCause::SubmissionHandler`); one for what happened returns.
|
|
|
|
use crate::error::DeadlockCause;
|
|
use std::cell::Cell;
|
|
|
|
/// A step of a command buffer's transitions.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub(crate) enum Step {
|
|
/// Its scheduled handlers.
|
|
ScheduledHandlers,
|
|
/// Its completed handlers.
|
|
CompletedHandlers,
|
|
/// The release of what it retained (a no-copy buffer's deallocator may run here).
|
|
Release,
|
|
/// Its submission handlers, on the thread that took its last batch (the scheduler's,
|
|
/// or a committing one, which may be a handler thread): its transition to `Scheduled`, and
|
|
/// so every later transition of its queue, waits for them.
|
|
SubmissionHandlers,
|
|
}
|
|
|
|
/// A logical queue's serial context: its device (by the shared state's address) and the queue's
|
|
/// identity there.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub(crate) struct Context {
|
|
pub(crate) device: usize,
|
|
pub(crate) queue: u64,
|
|
}
|
|
|
|
/// What a handler thread runs: a step of a command buffer (by its shared state's address) in its
|
|
/// queue's context.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub(crate) struct Marker {
|
|
pub(crate) context: Context,
|
|
pub(crate) buffer: usize,
|
|
pub(crate) step: Step,
|
|
}
|
|
|
|
/// The command buffer a wait is for, in its queue's context.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub(crate) struct Target {
|
|
pub(crate) context: Context,
|
|
pub(crate) buffer: usize,
|
|
}
|
|
|
|
thread_local! {
|
|
static RUNNING: Cell<Option<Marker>> = const { Cell::new(None) };
|
|
}
|
|
|
|
/// This thread runs a marked step until the value is dropped; the marker before it comes back
|
|
/// then.
|
|
pub(crate) struct Running {
|
|
previous: Option<Marker>,
|
|
}
|
|
|
|
impl Running {
|
|
/// Mark this thread as running `marker`'s step.
|
|
pub(crate) fn enter(marker: Marker) -> Running {
|
|
let previous = RUNNING.get();
|
|
RUNNING.set(Some(marker));
|
|
Running { previous }
|
|
}
|
|
}
|
|
|
|
impl Drop for Running {
|
|
fn drop(&mut self) {
|
|
RUNNING.set(self.previous);
|
|
}
|
|
}
|
|
|
|
/// The step this thread runs, if any.
|
|
pub(crate) fn running() -> Option<Marker> {
|
|
RUNNING.get()
|
|
}
|
|
|
|
/// What a wait answers.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub(crate) enum Answer {
|
|
/// Wait as usual: this is not a handler thread, or what it waits for happened.
|
|
Wait,
|
|
/// Return at once, as Metal does.
|
|
Return,
|
|
/// Refuse, for its cause: what it waits for comes later in this thread's own context
|
|
/// (`DeadlockCause::OwnQueue`).
|
|
Refuse(DeadlockCause),
|
|
/// Wait for another queue's context, from this one: counted while it blocks, and refused
|
|
/// where it would deadlock.
|
|
Block(Context),
|
|
}
|
|
|
|
/// What `wait_until_completed` on `target` answers on a thread running `marker`; `finished`
|
|
/// says whether its waiters may already return.
|
|
pub(crate) fn completed_wait(marker: Option<Marker>, target: Target, finished: bool) -> Answer {
|
|
let Some(marker) = marker else {
|
|
return Answer::Wait;
|
|
};
|
|
if finished {
|
|
Answer::Wait
|
|
} else if marker.step == Step::SubmissionHandlers {
|
|
Answer::Refuse(DeadlockCause::SubmissionHandler)
|
|
} else if marker.buffer == target.buffer && marker.step == Step::Release {
|
|
Answer::Return
|
|
} else if marker.context == target.context {
|
|
Answer::Refuse(DeadlockCause::OwnQueue)
|
|
} else {
|
|
Answer::Block(marker.context)
|
|
}
|
|
}
|
|
|
|
/// What `wait_until_scheduled` on `target` answers on a thread running `marker`; `scheduled`
|
|
/// says whether its transition to `Scheduled` ran.
|
|
pub(crate) fn scheduled_wait(marker: Option<Marker>, target: Target, scheduled: bool) -> Answer {
|
|
let Some(marker) = marker else {
|
|
return Answer::Wait;
|
|
};
|
|
if marker.buffer == target.buffer && marker.step == Step::ScheduledHandlers {
|
|
// That transition is in progress: Metal's never returns there.
|
|
Answer::Refuse(DeadlockCause::OwnQueue)
|
|
} else if scheduled {
|
|
Answer::Wait
|
|
} else if marker.step == Step::SubmissionHandlers {
|
|
Answer::Refuse(DeadlockCause::SubmissionHandler)
|
|
} else if marker.context == target.context {
|
|
Answer::Refuse(DeadlockCause::OwnQueue)
|
|
} else {
|
|
Answer::Block(marker.context)
|
|
}
|
|
}
|
|
|
|
/// What a new command buffer's wait for a slot of the full queue `queue` answers on a thread
|
|
/// running `marker` (`CommandQueue::command_buffer`); `open` says whether a command buffer not
|
|
/// committed holds one of the queue's slots, which the program may give back by dropping it.
|
|
///
|
|
/// A committed command buffer gives its slot back only in its queue's context, after its
|
|
/// completed handlers. In that context, then, no committed command buffer can give one back:
|
|
/// Metal's make never returns there (RT10-qlprobe3: a completed handler's make on its own full
|
|
/// queue). The runtime refuses it, unless an uncommitted command buffer may still be dropped.
|
|
pub(crate) fn slot_wait(marker: Option<Marker>, queue: Context, open: bool) -> Answer {
|
|
let Some(marker) = marker else {
|
|
return Answer::Wait;
|
|
};
|
|
if marker.step == Step::SubmissionHandlers {
|
|
return if open {
|
|
Answer::Wait
|
|
} else {
|
|
Answer::Refuse(DeadlockCause::SubmissionHandler)
|
|
};
|
|
}
|
|
if marker.context != queue {
|
|
Answer::Block(marker.context)
|
|
} else if open {
|
|
Answer::Wait
|
|
} else {
|
|
Answer::Refuse(DeadlockCause::OwnQueue)
|
|
}
|
|
}
|
|
|
|
/// The handler threads' waits for other contexts, as edges from the waiting context to the
|
|
/// awaited one. A context runs one item at a time, so it has at most one edge out.
|
|
#[derive(Debug)]
|
|
pub(crate) struct Waits {
|
|
edges: Vec<(Context, Context)>,
|
|
}
|
|
|
|
impl Waits {
|
|
/// No wait.
|
|
pub(crate) const fn new() -> Waits {
|
|
Waits { edges: Vec::new() }
|
|
}
|
|
|
|
/// Whether a wait of `from` for `to` would close a cycle: `to` waits, through the contexts
|
|
/// it waits for, for `from`.
|
|
pub(crate) fn closes_cycle(&self, from: Context, to: Context) -> bool {
|
|
let mut at = to;
|
|
// Each step follows a distinct edge, unless the edges hold a cycle already (they never
|
|
// do: no wait that closes one is added).
|
|
for _ in 0..=self.edges.len() {
|
|
if at == from {
|
|
return true;
|
|
}
|
|
match self.edges.iter().find(|(waiting, _)| *waiting == at) {
|
|
Some(&(_, next)) => at = next,
|
|
None => return false,
|
|
}
|
|
}
|
|
true
|
|
}
|
|
|
|
/// `from` waits for `to`.
|
|
pub(crate) fn insert(&mut self, from: Context, to: Context) {
|
|
self.edges.push((from, to));
|
|
}
|
|
|
|
/// `from` no longer waits for `to`.
|
|
pub(crate) fn remove(&mut self, from: Context, to: Context) {
|
|
if let Some(at) = self.edges.iter().position(|&edge| edge == (from, to)) {
|
|
self.edges.swap_remove(at);
|
|
}
|
|
}
|
|
}
|