A command buffer's encoding, commit and property reads now make no call that waits for a powered-down GPU or for the scheduler's submission, as Metal's return at once. What changes: - Upload arenas (argument, handle and root tables, constant blobs, neutral buffers, status words) take host-cached, host-coherent system memory (MemoryClass::Shared) instead of write-combined memory, which preferred device-local memory on a discrete GPU. Unified-memory devices are unchanged; a device with no host-cached coherent memory keeps its device-local type. No flush is needed: Vulkan defines coherent memory as needing none, and a submission orders the host's earlier writes. New WorkCounts::upload_chunks_in_device_memory. - The calibration pair that places GPU times on the host clock (vkGetCalibratedTimestampsKHR) is read by the completion turn, not at commit. The placement and its pair cache are unchanged; UncalibratedGpuTimes now says the calibration failed as the command buffer completed. - A completed command buffer's settled spare pool begins one primary ahead on the completing thread, with the spares' lock released and only where no thread waits on the command buffer's gate, so the next command buffer's first encoder records into it instead of beginning one. The pool passes between threads under the spares' lock, which is all vkBeginCommandBuffer's external synchronization asks. WorkCounts primaries_begun_ahead and encoder_primaries_begun_ahead. - A timed command buffer's timestamp slot is reset on the host (vkResetQueryPool, a Vulkan 1.2 required feature the runtime enables) as it takes the slot, so no command buffer the GPU runs resets a query; an adopted device keeps the command resets. WorkCounts timestamp_slots_reset_on_host. - kernelStartTime and kernelEndTime are two atomics beside the command buffer's state, and status and error an atomic and a once-set error published at each transition, so a read waits for no replay or submission and a commit takes no new lock. An Error status always finds its error. - WorkCounts counts the command buffers begun by what they were begun for (encoders, segments, continuations, secondaries, batch work and barriers, kept barriers, internal), printed by frame_costs. - docs/HOWTO.md notes NVIDIA's runtime D3 wake (about 1 s after about 15 s idle) and how a host that wants none keeps the GPU powered; never required. Why: on an RTX 5080 laptop GPU in runtime D3, the first write into device-local host-visible memory after 20 s idle waited 977 ms for the wake, and so did the commit's timestamp read (a commit took 973-977 ms; Metal's returns at once). On ANV a begin clears the command state, 8 to 20 us each, 0.80 ms of the Iris guest's 17 ms frame. And the scheduler holds the state lock through a batch's replay and submission, so a status or kernel-time read waited 60-65 ms behind 131,072 fills. Verified: - RX 7900 XTX, release A/B: encoding-thread CPU 5.27 -> 4.79 ms a frame with cached uploads, the vertex-heavy GPU time unchanged (28.18 -> 28.19 ms); draws_setting_bytes_write_no_device_local_memory fails without the change on the XTX, RTX 3090 and RTX 5080. - RTX 5080 laptop: a frame's commit after 20 s idle 973-977 ms -> 0.02-0.03 ms; the wake is now in the wait, as Metal's commit-and-wait shows it. gpu_times and degrade_notices 27 passed on it and on lavapipe. Host-reset slots saved about 1-2 us of GPU time a command buffer there; neutral on the Iris Xe. - Iris Xe: encoding-thread CPU 4.96 -> 4.62 ms a frame and a pass open 5.71 -> 2.77 us with primaries begun ahead; 95.85 of 97 encoders a frame took one. - runtime_lane::property_reads on the RX 7900 XTX and Radeon 780M fails without the change (reads of 60.3-65.1 ms) and passes with it (longest read 0.022-0.097 ms); on the M3 Max under MoltenVK it passed with 0 slow reads and the commit allocation bound held at 4.00. A new test checks status reads Completed in the completed handler, after the wait and in a deallocator. - Unit tests: spares, gate, exit_guard, gpu_time, completion, command_buffer (up to 218 passed per run); clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
225 lines
8.1 KiB
Rust
225 lines
8.1 KiB
Rust
//! When a command buffer's waiters return: once it finished (its completed handlers ran) and the
|
|
//! runtime's threads let go of every reference they took to it.
|
|
//!
|
|
//! - **Apart from the command buffer.** The [`Gate`] is not part of what it guards, so a thread
|
|
//! lets go of its reference first and leaves the gate after: the gate never opens while a
|
|
//! runtime thread still holds the command buffer, or anything it held for it.
|
|
//! - **Why.** A program that waits for its last command buffer and then drops its last handles
|
|
//! destroys the device on its own thread, before the drop returns. Were a runtime thread to
|
|
//! hold the last reference instead, the device would go on that thread, perhaps while the
|
|
//! program exits, which drivers do not survive (RADV ended such a process with `SIGSEGV`).
|
|
//! - **And what fed its work** (`trails.rs`). A thread that made what the command buffer waited
|
|
//! for, and holds what it made it with past its signal, holds the device without holding the
|
|
//! command buffer: a pool piece between its making's settle and its give-back (a dispatch's or
|
|
//! a draw's pipeline, a capture's translation), the reaper with what such a piece gave back to a
|
|
//! released state, the twin-decode thread between a decode's end and its job's drop. Each opens
|
|
//! a trail before its signal and closes it after its last let-go; the command buffer takes the
|
|
//! device's trail mark as it completes, and `wait_until_completed` and its timed form, once the
|
|
//! gate opened, wait for the trails below it, so the program's drop right after the wait is the
|
|
//! device's last (`tests/teardown_threads.rs` holds a dispatch's piece between the two). The
|
|
//! gate itself, the status and the completed handlers do not wait for trails. Metal's
|
|
//! `waitUntilCompleted` returns after the completed handlers ended too (the M3 Max: 10 µs at the
|
|
//! median, 23 µs at p99, a handler of 20 ms included).
|
|
//! - **What it does not cover.** A program that learns of the completion otherwise (from a
|
|
//! handler, an event the command buffer signals, or its status) may drop its last handles while
|
|
//! the runtime's thread still holds the command buffer; the device then goes on that thread.
|
|
//! An exit meanwhile waits for that teardown, or skips it once begun (`exit_guard`).
|
|
//! - **Exit.** Once the process is exiting, the threads that would open a gate end, so a wait
|
|
//! answers at once, and one already blocked within `exit_guard::WAKE`.
|
|
|
|
use crate::device::lock;
|
|
use crate::error::{DeadlockCause, TimedOut};
|
|
use crate::exit_guard;
|
|
use std::ops::Deref;
|
|
use std::sync::{Arc, Condvar, Mutex};
|
|
use std::time::Instant;
|
|
|
|
/// A wait that cannot end: the process is exiting.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub(crate) struct Exiting;
|
|
|
|
impl From<Exiting> for DeadlockCause {
|
|
fn from(Exiting: Exiting) -> DeadlockCause {
|
|
DeadlockCause::Exiting
|
|
}
|
|
}
|
|
|
|
impl From<Exiting> for crate::error::Error {
|
|
fn from(exiting: Exiting) -> crate::error::Error {
|
|
DeadlockCause::from(exiting).into()
|
|
}
|
|
}
|
|
|
|
/// One command buffer's gate.
|
|
#[derive(Debug, Default)]
|
|
pub(crate) struct Gate {
|
|
state: Mutex<GateState>,
|
|
changed: Condvar,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
struct GateState {
|
|
/// The command buffer finished: its completed handlers ran.
|
|
finished: bool,
|
|
/// The [`Hold`]s alive.
|
|
held: usize,
|
|
/// The threads blocked until it opens ([`Gate::awaited`]).
|
|
waiting: usize,
|
|
}
|
|
|
|
impl GateState {
|
|
fn open(&self) -> bool {
|
|
self.finished && self.held == 0
|
|
}
|
|
}
|
|
|
|
impl Gate {
|
|
/// The command buffer finished; the gate opens once no [`Hold`] is left.
|
|
pub(crate) fn finish(&self) {
|
|
lock(&self.state).finished = true;
|
|
self.changed.notify_all();
|
|
}
|
|
|
|
/// Whether the waiters may return.
|
|
pub(crate) fn is_open(&self) -> bool {
|
|
lock(&self.state).open()
|
|
}
|
|
|
|
/// Whether a thread is blocked until the gate opens, in [`wait`](Self::wait) or
|
|
/// [`wait_until`](Self::wait_until): what the thread that finishes the command buffer does
|
|
/// before its hold goes delays that thread's return.
|
|
pub(crate) fn awaited(&self) -> bool {
|
|
lock(&self.state).waiting > 0
|
|
}
|
|
|
|
/// Block until the gate opens. `Err` once the process is exiting and it is not open: the
|
|
/// runtime's threads that would open it end (`exit_guard`).
|
|
pub(crate) fn wait(&self) -> Result<(), Exiting> {
|
|
self.wait_unless(exit_guard::closed)
|
|
}
|
|
|
|
/// [`Gate::wait`], with `exiting` saying whether the process is exiting (the exit guard's
|
|
/// [`closed`](exit_guard::closed), or a test's own).
|
|
pub(crate) fn wait_unless(&self, exiting: impl Fn() -> bool) -> Result<(), Exiting> {
|
|
let mut state = lock(&self.state);
|
|
state.waiting += 1;
|
|
let waited = loop {
|
|
if state.open() {
|
|
break Ok(());
|
|
}
|
|
if exiting() {
|
|
break Err(Exiting);
|
|
}
|
|
state = self
|
|
.changed
|
|
.wait_timeout(state, exit_guard::WAKE)
|
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
.0;
|
|
};
|
|
state.waiting -= 1;
|
|
waited
|
|
}
|
|
|
|
/// Block until the gate opens, or until `deadline`; at once once the process is exiting, as
|
|
/// [`Gate::wait`].
|
|
pub(crate) fn wait_until(&self, deadline: Instant) -> Result<(), TimedOut> {
|
|
let mut state = lock(&self.state);
|
|
state.waiting += 1;
|
|
let waited = loop {
|
|
if state.open() {
|
|
break Ok(());
|
|
}
|
|
let left = deadline.saturating_duration_since(Instant::now());
|
|
if left.is_zero() || exit_guard::closed() {
|
|
break Err(TimedOut);
|
|
}
|
|
state = self
|
|
.changed
|
|
.wait_timeout(state, left.min(exit_guard::WAKE))
|
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
|
.0;
|
|
};
|
|
state.waiting -= 1;
|
|
waited
|
|
}
|
|
|
|
fn enter(&self) {
|
|
lock(&self.state).held += 1;
|
|
}
|
|
|
|
fn leave(&self) {
|
|
let mut state = lock(&self.state);
|
|
state.held -= 1;
|
|
let open = state.open();
|
|
drop(state);
|
|
if open {
|
|
self.changed.notify_all();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A reference a runtime thread holds (the scheduler's, a completion turn's, a queue
|
|
/// context's transition), counted by a [`Gate`]. Its fields drop in declaration order: the
|
|
/// reference first, then the count, so the gate cannot open while the reference is alive.
|
|
pub(crate) struct Hold<T> {
|
|
value: Arc<T>,
|
|
_count: Count,
|
|
}
|
|
|
|
/// A [`Hold`]'s place in its gate's count.
|
|
struct Count(Arc<Gate>);
|
|
|
|
impl Drop for Count {
|
|
fn drop(&mut self) {
|
|
self.0.leave();
|
|
}
|
|
}
|
|
|
|
impl<T> Hold<T> {
|
|
/// A new reference to `value`, counted by `gate`.
|
|
pub(crate) fn new(value: &Arc<T>, gate: &Arc<Gate>) -> Hold<T> {
|
|
gate.enter();
|
|
Hold {
|
|
value: Arc::clone(value),
|
|
_count: Count(Arc::clone(gate)),
|
|
}
|
|
}
|
|
|
|
/// Whether `self` and `other` hold the same value.
|
|
pub(crate) fn same(&self, other: &Hold<T>) -> bool {
|
|
Arc::ptr_eq(&self.value, &other.value)
|
|
}
|
|
|
|
/// Let go of the reference here, and leave the gate after, unless it is the value's last:
|
|
/// then the value, still counted by the gate, for the caller to let go of on another thread
|
|
/// ([`Last`]). Whether it is the last is decided as it goes (`Arc::into_inner`), so another
|
|
/// holder's drop meanwhile never leaves the value's drop here.
|
|
pub(crate) fn let_go_short_of_last(self) -> Option<Last<T>> {
|
|
let Hold { value, _count } = self;
|
|
Arc::into_inner(value).map(|value| Last { value, _count })
|
|
}
|
|
}
|
|
|
|
/// A [`Hold`]'s value where the hold was its last reference ([`Hold::let_go_short_of_last`]),
|
|
/// still counted by its gate: dropped, it drops the value, then leaves the gate.
|
|
pub(crate) struct Last<T> {
|
|
value: T,
|
|
_count: Count,
|
|
}
|
|
|
|
impl<T> Deref for Last<T> {
|
|
type Target = T;
|
|
|
|
fn deref(&self) -> &T {
|
|
&self.value
|
|
}
|
|
}
|
|
|
|
impl<T> Deref for Hold<T> {
|
|
type Target = Arc<T>;
|
|
|
|
fn deref(&self) -> &Arc<T> {
|
|
&self.value
|
|
}
|
|
}
|