From 7a6818deda79338fb17cee020e519b126a28ee69 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 28 Oct 2026 23:05:15 +0200 Subject: [PATCH] Take NVIDIA's stall in every 1024th signalling submit while idle dev-perf measured on an RTX 5080 Laptop GPU (NVIDIA 615.71.09, Linux) that one vkQueueSubmit in every 1024 that signals a fence or semaphore on a VkQueue spends 2.2-3.7 ms in the driver, counted per queue, and the batch it lands on, with everything committed behind it, waits that long. Every batch signals, so the stall can only be moved. device/submit_stalls.rs keeps each queue's place in the driver's period under the queue's lock (Period): every signalling call the runtime times is counted (batches via submit_logged, the device's own submission via use_queue(Uses::OneSignalling), the plan's empty ones); a use it cannot count (the program's, sparse binds, wait-idle, relay marks) or a due stall that did not come forgets it. Once the scheduler's thread has had nothing to submit for 1 ms and a queue's next stall is due within its next burst plus 32 calls (at most 128), it submits the calls left as empty submissions signalling a timeline semaphore of the queue's own, outside its lock, stopping where a commit or waker came. WorkCounts gains idle_submits, submit_stalls_idle, submit_stalls_on_work, submits_behind_idle_stalls, wait_behind_idle_stall_longest_nanos; host_ab prints them. FAST-PATHS records the stall among device gaps. Ports dev-perf 76bf5a3189, 28c42746a5, b76d910450, 1ef8316ecf, 9d2f46431e. Adapted: keyed as development keys driver facts, a cost fact DriverFact::SignallingSubmitsStallEvery1024 on NVIDIA's driver on the RTX 5080 Laptop GPU (0x2c19, the GPU measured) at every release (dev-perf's release-keyed DriverTrait table, fd2ddc8faa, not ported); the scheduler's short idle sleep bounds WAIT_SLICE (development has no head bound). Public API: DriverFact::SignallingSubmitsStallEvery1024 (translator and runtime re-export), five WorkCounts fields. RUNTIME_VERSION 1687. Runtime-sources pin recomputed. Tests: tests::submit_stalls (planner vs a model driver), device::tests::driver_facts (the fact's GPU scope, the 5080 profile's facts), device test tests::submit_stalls_idle (new: on a driver with the fact, at least one stall taken idle over 5000 command buffers; elsewhere no empty submission). Verified on an M3 Max (MoltenVK 1.4.2): touched-module tests 268 passed; api_signatures/api_surface 15 passed; the planner tests fail with due_idle forced to 0 (4 of 9) and pass restored; device tests 45 passed, the idle-stall test printing idle_submits 0 on MoltenVK; with the gating forced on, a run made 106 empty submissions without driver errors and the test failed as it should. Clippy plain and --cfg m2v_gpu, rustdoc -D warnings clean. The stall path itself needs the RTX 5080: see the round's 5080 run. --- .../examples/host_ab/main.rs | 10 + crates/metal2vulkan-runtime/src/device/mod.rs | 89 ++++- .../metal2vulkan-runtime/src/device/relay.rs | 50 ++- .../metal2vulkan-runtime/src/device/submit.rs | 5 +- .../src/device/submit_stalls.rs | 346 ++++++++++++++++++ crates/metal2vulkan-runtime/src/interop.rs | 5 +- .../metal2vulkan-runtime/src/scheduler/mod.rs | 78 +++- .../metal2vulkan-runtime/src/sparse/bind.rs | 3 +- .../src/tests/exit_guard.rs | 8 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 3 + .../src/tests/submit_stalls.rs | 242 ++++++++++++ .../src/tests/submit_stalls_idle.rs | 125 +++++++ .../metal2vulkan-runtime/src/work_counts.rs | 42 +++ .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- .../metal2vulkan/src/device/driver_facts.rs | 22 ++ .../src/device/tests/driver_facts.rs | 45 ++- crates/metal2vulkan/tests/api_signatures.tsv | 7 + docs/FAST-PATHS.md | 1 + 19 files changed, 1050 insertions(+), 35 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/device/submit_stalls.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/submit_stalls.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/submit_stalls_idle.rs diff --git a/crates/metal2vulkan-runtime/examples/host_ab/main.rs b/crates/metal2vulkan-runtime/examples/host_ab/main.rs index 22f541764..5d4fea1a8 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/main.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/main.rs @@ -449,6 +449,16 @@ fn child(side: &str, options: &Options) { c.scheduler_sleeps, c.scheduler_wakes_commit, ); + eprintln!( + "runtime submit stalls: idle_submits {} submit_stalls_idle {} \ + submit_stalls_on_work {} submits_behind_idle_stalls {} \ + wait_behind_idle_stall_longest_nanos {}", + c.idle_submits, + c.submit_stalls_idle, + c.submit_stalls_on_work, + c.submits_behind_idle_stalls, + c.wait_behind_idle_stall_longest_nanos, + ); eprintln!("runtime commands replayed: {:?}", c.commands_replayed); eprintln!( "runtime notices: {} (bound notices made {}), other messages heard {}", diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 6fd831232..0e0234264 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -29,6 +29,7 @@ pub(super) mod properties; pub(crate) mod relay; mod staging; pub(super) mod submit; +pub(crate) mod submit_stalls; pub use adopt::RawDevice; pub(crate) use compiles::holding; @@ -191,8 +192,9 @@ pub(super) struct DeviceShared { /// The primary queue family: its first queue's, where internal submissions go. pub(super) queue_family: u32, /// The `VkQueue`s the runtime submits to, the primary family's first queue first: at least - /// one. - pub(super) queues: Vec, + /// one. Shared with the scheduler's thread where it takes the driver's stalls idle + /// (`submit_stalls.rs`). + pub(super) queues: Arc<[QueueSlot]>, /// The families of those queues, the primary first, each once: what the device's buffers and /// images are shared among (`sharing.rs`). pub(super) queue_families: Vec, @@ -722,7 +724,7 @@ impl Drop for DeviceShared { exit_guard::called(Call::DeviceWaitIdle); // The scheduler's thread, which waited on its nudge, has stopped. release::object(self.vk(), self.nudge); - for queue in &self.queues { + for queue in self.queues.iter() { release::object(self.vk(), queue.timeline); // The marks after the last uses of the queue outside a batch (`relay.rs`). for fence in queue.flights.get().map(|f| f.drain()).unwrap_or_default() { @@ -739,8 +741,10 @@ impl Drop for DeviceShared { // with its state. self.timing.release(self.vk()); } - // Nor a kept barrier command buffer: the queues are idle. + // Nor a kept barrier command buffer, nor a submission taking a driver's stall idle: the + // queues are idle. self.scheduler.release_kept(self.vk()); + self.scheduler.release_idle(self.vk()); // No command buffer is left to give back a spare, or to hold one. self.spares.release(self); if let Some(internal) = lock(&self.internal).take() { @@ -812,9 +816,12 @@ impl Drop for DeviceShared { } /// One of the device's `VkQueue`s. -pub(super) struct QueueSlot { - /// The queue, under its lock: submissions are externally synchronized. - raw: Mutex, +pub(crate) struct QueueSlot { + /// The queue, under its lock: submissions are externally synchronized. With it, its place in + /// its driver's period of stalls (`submit_stalls.rs`), which each use under the lock moves. + raw: Mutex<(vk::Queue, submit_stalls::Period)>, + /// Its place's `Period::may_be_due`, as of the last use: read without the lock. + stall_due: AtomicBool, /// The queue's family, which the command pools of what it runs are made for. pub(super) family: u32, /// The family's queue flags: the commands it runs, and so the accesses a barrier recorded @@ -841,12 +848,56 @@ pub(super) struct QueueSlot { } impl QueueSlot { - /// `f` with the queue, under its lock, its loader word put back first. + /// `f` with the queue, under its lock, its loader word put back first: a use whose + /// signalling calls are not counted, so its place in its driver's period is forgotten + /// (`submit_stalls.rs`). pub(super) fn with(&self, f: impl FnOnce(vk::Queue) -> R) -> R { - let queue = lock(&self.raw); + let mut held = lock(&self.raw); + held.1.forget(); + self.stall_due.store(false, Ordering::Relaxed); // SAFETY: the queue lives while its slot does. unsafe { self.word.restore() }; - f(*queue) + f(held.0) + } + + /// `f` with the queue and its place in its driver's period, under its lock, its loader word + /// put back first: `f` counts each signalling call it makes (`Period::called`). For a use of + /// `caller`'s, also the wait for the lock where it waited behind a stall taken idle + /// (`Period::entered`). + pub(crate) fn with_counted( + &self, + caller: submit_stalls::Caller, + f: impl FnOnce(vk::Queue, &mut submit_stalls::Period) -> R, + ) -> (R, Option) { + let asked = gpu_time::host_nanos(); + let mut held = lock(&self.raw); + let behind = match caller { + submit_stalls::Caller::Work => { + let waited = gpu_time::host_nanos().saturating_sub(asked); + held.1.entered(waited) + } + submit_stalls::Caller::Empty => None, + }; + // SAFETY: the queue lives while its slot does. + unsafe { self.word.restore() }; + let (queue, period) = &mut *held; + let used = f(*queue, period); + self.stall_due.store(period.may_be_due(), Ordering::Relaxed); + (used, behind) + } + + /// `f` with the queue's place in its driver's period alone, under the queue's lock. + pub(crate) fn with_period(&self, f: impl FnOnce(&mut submit_stalls::Period) -> R) -> R { + let mut held = lock(&self.raw); + let answer = f(&mut held.1); + self.stall_due.store(held.1.may_be_due(), Ordering::Relaxed); + answer + } + + /// Whether its driver's next stall may be due within `submit_stalls::MOST_EMPTY` calls, as of + /// its last use (`Period::may_be_due`), read without its lock. + pub(crate) fn stall_may_be_due(&self) -> bool { + self.stall_due.load(Ordering::Relaxed) } /// The host saw the timeline reach `value`. @@ -1269,7 +1320,8 @@ impl Device { raw.get_device_queue(family, index) }; QueueSlot { - raw: Mutex::new(queue), + raw: Mutex::new((queue, submit_stalls::Period::default())), + stall_due: AtomicBool::new(false), family, flags: flags_of(family), // SAFETY: the queue was just returned, its word the loader's. @@ -1705,7 +1757,7 @@ impl Device { functions: Arc::new(functions), queue_family, round_robin: queues.len() - present_queues, - queues, + queues: queues.into(), queue_families, round_robin_made: AtomicU64::new(0), presenting_made: AtomicU64::new(0), @@ -1840,6 +1892,19 @@ impl Device { if waits_on_gpu { (shared.scheduler).wait_on_gpu(Functions::clone(&shared.functions), shared.nudge); } + // Where the driver stalls in one signalling submission of every 1024 to a `VkQueue` + // (`DriverFact::SignallingSubmitsStallEvery1024`), the scheduler's thread takes the + // stalls while idle, each queue's empty submissions signalling a semaphore of its own + // (`submit_stalls.rs`); a device that cannot make the semaphores takes none. + let stalls = metal2vulkan::device::DriverFact::SignallingSubmitsStallEvery1024; + if shared.properties.driver_facts.contains(&stalls) { + if let Some(semaphores) = submit_stalls::semaphores(shared.vk(), shared.queues.len()) { + let functions = Functions::clone(&shared.functions); + let queues = Arc::clone(&shared.queues); + let idle = submit_stalls::IdleStalls::new(functions, queues, semaphores); + shared.scheduler.take_stalls_idle(idle); + } + } let device = Device(shared); // The pages its replays held last go on its handler threads (`recorder`). if let Some(recorder) = device.shared().recorder() { diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs index 171a51083..174026986 100644 --- a/crates/metal2vulkan-runtime/src/device/relay.rs +++ b/crates/metal2vulkan-runtime/src/device/relay.rs @@ -50,6 +50,7 @@ use super::functions::Functions; use super::lock; +use super::submit_stalls::{Caller, Uses}; use crate::exit_guard::{self, Call}; use crate::loader_word::LoaderWord; use ash::vk::{self, Handle}; @@ -382,7 +383,8 @@ impl super::DeviceShared { /// batch that signals the queue's timeline to `value` notes it once submitted (the exit /// hook's value, and where freed memory waits for the batches in flight, theirs, under the /// gate's read lock: `freed_memory.rs`). The time `f` takes, the driver's, is counted - /// (`WorkCounts::batch_submit_nanos`). + /// (`WorkCounts::batch_submit_nanos`), and the call counted in the queue's place in its + /// driver's period of stalls (`submit_stalls.rs`): `f` makes one signalling call. pub(crate) fn submit_logged( &self, (queue, value): (usize, Option), @@ -393,14 +395,19 @@ impl super::DeviceShared { let slot = &self.queues[queue]; let logged = fence.zip(slot.flights.get()); let parking = self.parking.get(); - slot.with(|vk_queue| { + let (submitted, behind) = slot.with_counted(Caller::Work, |vk_queue, period| { let _gate = parking.map(|parking| parking.submitting()); if let Some((fence, flights)) = logged { flights.push(fence, By::Batch(Arc::clone(failed))); } let entered = crate::gpu_time::host_nanos(); let submitted = f(vk_queue); - (self.counts).batch_submitted_in(crate::gpu_time::host_nanos().saturating_sub(entered)); + let end = crate::gpu_time::host_nanos(); + let nanos = end.saturating_sub(entered); + (self.counts).batch_submitted_in(nanos); + if submitted.is_ok() && period.called(Caller::Work, nanos, end) { + self.counts.submit_stall_on_work(); + } match (&submitted, logged, value) { (Err(_), Some((fence, flights)), _) => flights.unpush(fence), (Ok(()), _, Some(value)) => { @@ -412,7 +419,11 @@ impl super::DeviceShared { _ => {} } submitted - }) + }); + if let Some(waited) = behind { + self.counts.submit_behind_idle_stall(waited); + } + submitted } /// `f` with `VkQueue` `queue` under its lock: a use outside a batch, `by`'s. Where the @@ -423,13 +434,38 @@ impl super::DeviceShared { /// such marks before `f` runs, which that submission signals too (`freed_memory.rs`); should /// the submission fail, the value counts as reached once the queue is idle. Each reach of the /// device is a section of the exit guard of its own (`f` runs outside one: it may be the - /// program's); once the process is exiting no mark is made. - pub(crate) fn use_queue(&self, queue: usize, by: By, f: impl FnOnce(vk::Queue) -> R) -> R { + /// program's); once the process is exiting no mark is made. A use of `uses` + /// [`Uses::OneSignalling`] is counted in the queue's place in its driver's period of stalls + /// (`submit_stalls.rs`); any other, or one with a mark, forgets the place. + pub(crate) fn use_queue( + &self, + queue: usize, + by: By, + uses: Uses, + f: impl FnOnce(vk::Queue) -> R, + ) -> R { let slot = &self.queues[queue]; let flights = slot.flights.get(); let parking = (self.parking.get()).filter(|_| matches!(by, By::Program)); if flights.is_none() && parking.is_none() { - return slot.with(f); + return match uses { + Uses::Unknown => slot.with(f), + Uses::OneSignalling => { + let (used, behind) = slot.with_counted(Caller::Work, |vk_queue, period| { + let entered = crate::gpu_time::host_nanos(); + let used = f(vk_queue); + let end = crate::gpu_time::host_nanos(); + if period.called(Caller::Work, end.saturating_sub(entered), end) { + self.counts.submit_stall_on_work(); + } + used + }); + if let Some(waited) = behind { + self.counts.submit_behind_idle_stall(waited); + } + used + } + }; } let fence = flights.and_then(|flights| { exit_guard::enter().and_then(|_busy| { diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index c72b4d5ea..e09eb3f0d 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -18,6 +18,7 @@ use super::functions::Vk; use super::relay::By; +use super::submit_stalls::Uses; use super::{lock, Device}; use crate::error::{vulkan, Error}; use crate::exit_guard::{self, Call}; @@ -242,7 +243,7 @@ impl Device { // SAFETY: the queue is used under its lock; the command buffers are executable; every // signal of the timeline is above its value. Where the queue's failures are relayed, a // failure of this submission loses the device (`relay.rs`). - let made = shared.use_queue(0, By::Runtime, |queue| unsafe { + let made = shared.use_queue(0, By::Runtime, Uses::OneSignalling, |queue| unsafe { // No buffer of addresses goes while it encodes (`freed_memory.rs`). let _gate = (shared.parking.get()).map(|parking| parking.submitting()); let buffers = submits @@ -315,7 +316,7 @@ impl Device { // family binds sparse memory, and the queue is used under its lock; the signal is above // the timeline's value (the internal lock is held). shared.counts.queue_submitted(0, 0); - let bound = shared.use_queue(0, By::Runtime, |queue| unsafe { + let bound = shared.use_queue(0, By::Runtime, Uses::Unknown, |queue| unsafe { raw.queue_bind_sparse(queue, &[info], vk::Fence::null()) }); exit_guard::called(Call::QueueBindSparse); diff --git a/crates/metal2vulkan-runtime/src/device/submit_stalls.rs b/crates/metal2vulkan-runtime/src/device/submit_stalls.rs new file mode 100644 index 000000000..597530dce --- /dev/null +++ b/crates/metal2vulkan-runtime/src/device/submit_stalls.rs @@ -0,0 +1,346 @@ +//! A driver's stall in one of every so many signalling submissions to a `VkQueue`, taken while +//! the device's scheduler is idle. +//! +//! **The driver.** NVIDIA's proprietary driver spends 2.2 to 3.7 ms in one `vkQueueSubmit` of +//! every 1024 that signal a fence or a semaphore on a `VkQueue`, whatever the call submits +//! (615.71.09, `driverVersion` 0x99d1c240, on an RTX 5080 Laptop GPU under Linux; 8192 calls a +//! form, timed one by one): one command buffer and a timeline signal, no command buffer and a +//! timeline signal, a fence alone, `vkQueueSubmit2`, and four signalling submit infos in one call +//! each stall once in 1024 calls, 100 us apart or back to back; a call that signals nothing never +//! stalls. The count is the `VkQueue`'s: two queues of one device, two devices of one process and +//! two processes each stall once in 1024 of their own calls; `vkQueueWaitIdle` counts as one. The +//! other calls take 1.6 us (p50). Vulkan states no such cost. Each batch the runtime submits +//! signals its queue's timeline, so one command buffer in 1024 waited there, and every one +//! committed behind it with it: `host_ab present` at 120 Hz (25 command buffers a frame) held a +//! submission 2.3 to 5.1 ms every 341.6 ms, in 30 of 1200 frames. +//! +//! **Taken idle** ([`Period`], [`IdleStalls`]), where the driver has the cost fact +//! (`DriverFact::SignallingSubmitsStallEvery1024`, the translator's `device/driver_facts.rs`): +//! +//! - **Learnt per queue.** Each signalling call the runtime makes under a queue's lock and times +//! (a batch's, a fence's with no work, the device's own submission, an empty one of the plan's) +//! is counted; one that took [`STALL_NANOS`] or more is the driver's stall, and the count starts +//! again from it. A use of the queue the runtime cannot count (the program's, a sparse binding, +//! a wait for its idle) forgets the count until the next stall, as does a due stall that did not +//! come: a release without the stall submits no empty submission after its first miss, and none +//! before a stall was seen. +//! - **Taken while idle.** Once the scheduler's thread has had nothing to submit for +//! [`IDLE_NANOS`] and a queue's next stall is due within its next burst of work (the most +//! signalling calls it made between two such idles over its last [`BURSTS`], plus [`MARGIN`]), +//! at most [`MOST_EMPTY`] calls away, the thread submits the calls left as empty submissions, +//! each signalling a timeline semaphore of the queue's own: the last takes the stall while +//! nothing waits for the queue. It stops before each one where a commit or a waker came +//! meanwhile, so work waits behind one stall at most. +//! - **Counted** (`WorkCounts`): the empty submissions (`idle_submits`), the stalls they took +//! (`submit_stalls_idle`), the stalls that fell on work (`submit_stalls_on_work`), and the work +//! that came while one taken idle ran (`submits_behind_idle_stalls`, with the longest wait, +//! `wait_behind_idle_stall_longest_nanos`): a submission that waited for the queue's lock +//! behind it, its wait, and a commit that reached the scheduler meanwhile, at most the stall's. +//! +//! An empty submission holds the queue's lock alone, which no completion turn's wait and no +//! handler takes. + +use super::functions::Functions; +use super::{lock, QueueSlot}; +use crate::exit_guard::{self, Call as Guarded}; +use ash::vk; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// The signalling calls to a `VkQueue` from one stall of the driver's to the next. +pub(crate) const PERIOD: u32 = 1024; + +/// A signalling call that took this long or longer, in nanoseconds, is the driver's stall: the +/// stalls measured took 2.2 ms or more, and no other signalling call 1.6 ms. +pub(crate) const STALL_NANOS: u64 = 2_000_000; + +/// How long the scheduler's thread has had nothing to submit before it takes a stall due, in +/// nanoseconds: it begins a gap between bursts of work (a frame's), not one between two commits +/// of a burst, which come microseconds apart. +pub(crate) const IDLE_NANOS: u64 = 1_000_000; + +/// The bursts of a queue's work the plan weighs: the next is taken to be no larger than the +/// largest of them. +pub(crate) const BURSTS: usize = 8; + +/// The calls a stall may come early by, beyond the largest burst, and still be taken idle: in +/// `host_ab present` on the RTX 5080 (2400 frames of 25 command buffers, 120 Hz), 5 of 58 +/// stalls came 24 calls before the 1024th, at the last command buffer of a frame, where the +/// plan's empty calls would have gone after it. +pub(crate) const MARGIN: u32 = 32; + +/// The most empty submissions taken at one idle: a stall further off waits for a later idle, or +/// falls on work. +pub(crate) const MOST_EMPTY: u32 = 128; + +/// A wait for the queue's lock, in nanoseconds, behind a stall taken idle that counts as one +/// (`WorkCounts::submits_behind_idle_stalls`): shorter, it waited for no stall. +pub(crate) const BEHIND_NANOS: u64 = 10_000; + +/// The signalling calls a use of a queue outside a batch makes (`DeviceShared::use_queue`). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Uses { + /// One `vkQueueSubmit` that signals a fence or a semaphore: counted. + OneSignalling, + /// Any calls (the program's, a sparse binding's): the queue's place is forgotten. + Unknown, +} + +/// Who made a signalling call to the queue. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Caller { + /// A submission of work, or the device's own. + Work, + /// An empty submission of the plan's, taken idle. + Empty, +} + +/// A queue's place in its driver's period, as counted, and its bursts of work (the module docs). +/// Kept under the queue's lock (`QueueSlot`). +#[derive(Default)] +pub(crate) struct Period { + /// The signalling calls since the last stall seen, each counted: `None` before one is seen, + /// once a use was not counted, or once a stall due did not come. + since: Option, + /// The signalling calls of work in the burst under way. + burst: u32, + /// The last bursts' calls, a ring. + bursts: [u32; BURSTS], + at: usize, + /// The host time the last call of work ended, in nanoseconds. + last_end: u64, + /// The last call was an empty one that stalled: one that took the lock meanwhile waited + /// behind it. + idle_stall: bool, +} + +impl Period { + /// A use of the queue the runtime cannot count: no stall is due until one is seen. + pub(crate) fn forget(&mut self) { + self.since = None; + self.idle_stall = false; + } + + /// The call that took the queue's lock now waited `waited` nanoseconds for it: `Some(waited)` + /// where it waited behind a stall taken idle ([`BEHIND_NANOS`]). + pub(crate) fn entered(&mut self, waited: u64) -> Option { + let behind = (self.idle_stall && waited >= BEHIND_NANOS).then_some(waited); + self.idle_stall = false; + behind + } + + /// A signalling call of `caller`'s that took `nanos` and ended at host time `end`, in + /// nanoseconds: whether it was the driver's stall. A call of work [`IDLE_NANOS`] or more + /// after the one before begins a burst. + pub(crate) fn called(&mut self, caller: Caller, nanos: u64, end: u64) -> bool { + let stalled = nanos >= STALL_NANOS; + if caller == Caller::Work { + let gap = end.saturating_sub(nanos).saturating_sub(self.last_end); + if gap >= IDLE_NANOS { + self.end_burst(); + } + self.burst = self.burst.saturating_add(1); + self.last_end = end; + } + self.idle_stall = stalled && caller == Caller::Empty; + self.since = match (stalled, self.since) { + (true, _) => Some(0), + // The stall due did not come: the count is wrong, or the driver stalls no more. + (false, Some(since)) if since + 1 >= PERIOD => None, + (false, since) => since.map(|since| since + 1), + }; + stalled + } + + fn end_burst(&mut self) { + if self.burst > 0 { + self.bursts[self.at] = self.burst; + self.at = (self.at + 1) % BURSTS; + self.burst = 0; + } + } + + /// Whether a stall may be due at the next idle: a cheap look, which changes nothing. + pub(crate) fn may_be_due(&self) -> bool { + self.since.is_some_and(|since| PERIOD - since <= MOST_EMPTY) + } + + /// The queue is idle: the burst under way ended, and the empty calls that take the next stall + /// now, the calls left up to and including the stall's, where it is due within the next + /// burst (the largest of the last [`BURSTS`], plus [`MARGIN`]) and [`MOST_EMPTY`] calls at + /// most; else 0. + pub(crate) fn due_idle(&mut self) -> u32 { + self.end_burst(); + let Some(since) = self.since else { + return 0; + }; + let left = PERIOD - since; + let next = self.bursts.iter().copied().max().unwrap_or(0); + match left <= next.saturating_add(MARGIN).min(MOST_EMPTY) { + true => left, + false => 0, + } + } +} + +/// `count` timeline semaphores at 0 of `raw`'s, one for each queue's empty submissions; `None` +/// where the device made not all of them (it releases those it made), and then takes no stall +/// idle. +pub(super) fn semaphores(raw: &ash::Device, count: usize) -> Option> { + let mut made = Vec::with_capacity(count); + for _ in 0..count { + let mut kind = vk::SemaphoreTypeCreateInfo::default() + .semaphore_type(vk::SemaphoreType::TIMELINE) + .initial_value(0); + let info = vk::SemaphoreCreateInfo::default().push_next(&mut kind); + // SAFETY: the device is live and enables `timelineSemaphore`. + match unsafe { raw.create_semaphore(&info, None) } { + Ok(semaphore) => made.push(semaphore), + Err(_) => { + for semaphore in made { + // SAFETY: made just now, used by nothing. + unsafe { crate::release::object(raw, semaphore) }; + } + return None; + } + } + } + Some(made) +} + +/// What the scheduler's thread takes the stalls idle with: the device's queues, a timeline +/// semaphore of each queue's own for the empty submissions to signal, and their counts. +pub(crate) struct IdleStalls { + functions: Functions, + queues: Arc<[QueueSlot]>, + /// By queue: the semaphore, and the value it was last signalled to. + signals: Mutex>, + counts: StallCounts, +} + +/// The counts of the stalls taken idle (the module docs). +#[derive(Default)] +struct StallCounts { + empty: AtomicU64, + idle: AtomicU64, + behind: AtomicU64, + behind_longest: AtomicU64, +} + +/// What [`IdleStalls::counts`] reads: the empty submissions made, the stalls they took, and the +/// commits that came while one ran, with the longest of those stalls in nanoseconds. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(crate) struct IdleCounts { + pub(crate) empty: u64, + pub(crate) idle: u64, + pub(crate) behind: u64, + pub(crate) behind_longest: u64, +} + +impl IdleStalls { + /// The plan of the device of `functions`, whose queues are `queues`, each with its own + /// semaphore of `semaphores`, timeline semaphores at 0, which the device releases after its + /// scheduler stopped ([`release`](Self::release)). + pub(super) fn new( + functions: Functions, + queues: Arc<[QueueSlot]>, + semaphores: Vec, + ) -> IdleStalls { + IdleStalls { + functions, + queues, + signals: Mutex::new(semaphores.into_iter().map(|s| (s, 0)).collect()), + counts: StallCounts::default(), + } + } + + /// Whether a stall may be due on any queue at the next idle ([`Period::may_be_due`]), read + /// without the queues' locks. + pub(crate) fn may_be_due(&self) -> bool { + self.queues.iter().any(QueueSlot::stall_may_be_due) + } + + /// The scheduler's thread has been idle [`IDLE_NANOS`]: on each queue whose next stall is due + /// ([`Period::due_idle`]), submit the calls left as empty submissions, one at a time under the + /// queue's lock, stopping before each one where `arrived` (a commit or a waker came) and after + /// the one that stalls. + pub(crate) fn take(&self, arrived: impl Fn() -> bool) { + for (queue, slot) in self.queues.iter().enumerate() { + let due = slot.with_period(Period::due_idle); + for _ in 0..due { + if arrived() { + return; + } + let Some(stalled) = self.submit_empty(queue, slot) else { + return; + }; + if let Some(nanos) = stalled { + self.counts.idle.fetch_add(1, Ordering::Relaxed); + if arrived() { + self.counts.behind.fetch_add(1, Ordering::Relaxed); + self.counts + .behind_longest + .fetch_max(nanos, Ordering::Relaxed); + } + break; + } + } + } + } + + /// One empty submission to `slot`, the device's queue `queue`, signalling its semaphore's + /// next value: `Some(Some(nanos))` where it stalled, `Some(None)` where not, `None` where it + /// failed (a lost device) or the process is exiting. + fn submit_empty(&self, queue: usize, slot: &QueueSlot) -> Option> { + let _busy = exit_guard::enter()?; + let (semaphore, value) = { + let mut signals = lock(&self.signals); + let (semaphore, value) = signals.get_mut(queue)?; + *value += 1; + (*semaphore, *value) + }; + let semaphores = [semaphore]; + let values = [value]; + let mut timeline = + vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(&values); + let info = vk::SubmitInfo::default() + .signal_semaphores(&semaphores) + .push_next(&mut timeline); + let raw = self.functions.get(); + let ((submitted, stalled), _) = slot.with_counted(Caller::Empty, |vk_queue, period| { + let start = crate::gpu_time::host_nanos(); + // SAFETY: a submission of no work signalling the queue's own semaphore of the plan's + // above every value it was signalled to (they rise under the plan's lock, by one + // thread); the queue is used under its lock, inside a section. + let submitted = unsafe { raw.queue_submit(vk_queue, &[info], vk::Fence::null()) }; + let end = crate::gpu_time::host_nanos(); + let nanos = end.saturating_sub(start); + let stalled = submitted.is_ok() && period.called(Caller::Empty, nanos, end); + (submitted, stalled.then_some(nanos)) + }); + exit_guard::called(Guarded::QueueSubmit); + self.counts.empty.fetch_add(1, Ordering::Relaxed); + submitted.ok().map(|()| stalled) + } + + /// The counts so far (`WorkCounts::idle_submits` and kin). + pub(crate) fn counts(&self) -> IdleCounts { + let counts = &self.counts; + IdleCounts { + empty: counts.empty.load(Ordering::Relaxed), + idle: counts.idle.load(Ordering::Relaxed), + behind: counts.behind.load(Ordering::Relaxed), + behind_longest: counts.behind_longest.load(Ordering::Relaxed), + } + } + + /// Release the semaphores, the device being torn down: its scheduler stopped and its queues + /// are idle. + pub(crate) fn release(&self, raw: &ash::Device) { + for (semaphore, _) in lock(&self.signals).drain(..) { + // SAFETY: no submission signalling it is pending (the queues are idle), and nothing + // submits again (the scheduler stopped). + unsafe { crate::release::object(raw, semaphore) }; + } + } +} diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index bf5e4e54a..0434ac260 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -20,6 +20,7 @@ use super::buffer::ReadApart; use super::device::relay::By; +use super::device::submit_stalls::Uses; use super::event::EventRef; use super::texture::wrapped::Wrapped; use super::{Buffer, CommandQueue, Device, SharedEvent, Texture}; @@ -186,7 +187,9 @@ impl CommandQueue { // Where the queue's failures are relayed, a mark after `f`'s submissions keeps a failure // of theirs the caller's (`device/relay.rs`); where freed memory waits for the work in // flight, it waits for that mark (`freed_memory.rs`). - let used = shared.use_queue(self.vk_queue(), By::Program, |queue| f(queue, family)); + let used = shared.use_queue(self.vk_queue(), By::Program, Uses::Unknown, |queue| { + f(queue, family) + }); if let Some(parking) = shared.parking.get() { parking.watch(self.device()); } diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index c750a0ffe..c208c64fe 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -91,6 +91,12 @@ //! ready together. //! - **Waits are bounded.** The thread wakes on a commit or a host signal, and at least every //! [`WAIT_SLICE`], so a stop is seen promptly. +//! - **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 +//! submits the calls left before the stall as empty submissions, without its lock, stopping +//! where a commit or a waker came meanwhile: the stall falls in the gap between bursts of work +//! rather than on a batch. That wake is no [`WAIT_SLICE`]'s. //! - **Woken by completions only when they let a batch go** ([`Awaits`]). A pass that leaves a //! head at its gate, its checks waiting for a GPU signal to land, or a group kept, leaves what //! it waits for: each `VkQueue`'s value to complete, each event value to be reached. A @@ -147,6 +153,7 @@ use super::command_buffer::CommandBufferShared; use super::command_buffer::{Group, GroupEnd, Submitting, GROUP_BATCHES}; use super::device::functions::Functions; use super::device::lock; +use super::device::submit_stalls::{IdleCounts, IdleStalls, IDLE_NANOS}; use super::error::{CommandBufferError, Error, MemoryKind}; use super::event::EventShared; use super::event_timeline::WaitFor; @@ -167,7 +174,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{fence, AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::thread::JoinHandle; -use std::time::Duration; +use std::time::{Duration, Instant}; /// How long the thread sleeps at most without looking for work. const WAIT_SLICE: Duration = Duration::from_millis(100); @@ -377,6 +384,9 @@ struct SchedulerShared { /// The device's recorder, where it records off the encoding thread (`recorder`): woken after /// a round that took commits in (the module docs). recorder: OnceLock>, + /// Where the device's driver stalls in one signalling submission of every 1024 to a queue, + /// what the thread takes those stalls idle with (the module docs). + stalls: OnceLock, } impl SchedulerShared { @@ -614,6 +624,7 @@ impl Scheduler { nudge: OnceLock::new(), spare_logs: SpareLogs::default(), recorder: OnceLock::new(), + stalls: OnceLock::new(), }); let thread = { let shared = Arc::clone(&shared); @@ -640,6 +651,27 @@ impl Scheduler { }); } + /// Take the driver's stalls in one signalling submission of every 1024 to a queue idle with + /// `stalls` (the module docs): on a device whose driver has them, which releases the + /// semaphores after stopping the thread ([`release_idle`](Self::release_idle)). + pub(crate) fn take_stalls_idle(&self, stalls: IdleStalls) { + let _ = self.shared.stalls.set(stalls); + } + + /// The counts of the stalls taken idle so far (`WorkCounts::idle_submits` and kin): none on + /// a device that takes none. + pub(crate) fn idle_stall_counts(&self) -> IdleCounts { + (self.shared.stalls.get()).map_or_else(IdleCounts::default, IdleStalls::counts) + } + + /// Release what the thread took the stalls idle with: the device is being torn down, its + /// thread stopped and its queues idle. + pub(crate) fn release_idle(&self, raw: &ash::Device) { + if let Some(stalls) = self.shared.stalls.get() { + stalls.release(raw); + } + } + /// Wake `recorder`, the device's, after each round that took commits in (the module docs). pub(crate) fn wake_recorder(&self, recorder: Arc) { let _ = self.shared.recorder.set(recorder); @@ -898,25 +930,51 @@ fn run(shared: &SchedulerShared) { let mut gpu = GpuWait::default(); loop { let mut state = lock(shared.inbox.state()); + // Since when the thread has had nothing to submit, and whether it looked for a driver's + // stall due since (the module docs): once an idle, once it lasted `IDLE_NANOS`. + let (idle_since, mut looked) = (Instant::now(), false); // A commit, or a nudge, left to this thread's pass may wait in the inbox (`inbox.rs`). while !state.dirty && !state.stopping && !shared.inbox.holds_commits() && !shared.inbox.nudged() { + // A stall due is taken without the lock, the empty submissions stopping where a + // commit or a waker came; the sleep before it ends at the idle's length, no slice. + let stalls = (shared.stalls.get()).filter(|stalls| !looked && stalls.may_be_due()); + let (slice, short) = match stalls { + Some(stalls) => { + let idle = Duration::from_nanos(IDLE_NANOS); + match idle.checked_sub(idle_since.elapsed()) { + Some(left) if !left.is_zero() => (WAIT_SLICE.min(left), left < WAIT_SLICE), + _ => { + looked = true; + drop(state); + stalls.take(|| { + shared.inbox.holds_commits() + || shared.inbox.nudged() + || lock(shared.inbox.state()).dirty + }); + state = lock(shared.inbox.state()); + continue; + } + } + } + None => (WAIT_SLICE, false), + }; shared.sleeps.fetch_add(1, Ordering::Relaxed); if let Some(nudge) = shared.nudge.get().filter(|_| shared.gpu_waits(&mut gpu)) { - state = wait_for_gpu(shared, state, nudge, &mut gpu); + state = wait_for_gpu(shared, state, nudge, &mut gpu, (slice, short)); continue; } state.asleep = true; let (woke, waited) = shared .wake - .wait_timeout(state, WAIT_SLICE) + .wait_timeout(state, slice) .unwrap_or_else(std::sync::PoisonError::into_inner); state = woke; state.asleep = false; - if waited.timed_out() { + if waited.timed_out() && !short { shared.wakings[Woken::Slice as usize].fetch_add(1, Ordering::Relaxed); } } @@ -941,13 +999,16 @@ fn run(shared: &SchedulerShared) { } /// Sleep on the GPU (the module docs): for any of `gpu`'s semaphores to reach its value, or the -/// nudge its next, at most [`WAIT_SLICE`], without the lock `state` holds, which comes back taken. -/// Where a value landed, its events observe their counters, and the state is marked for a pass. +/// nudge its next, at most `slice` ([`WAIT_SLICE`], or, where `short`, the idle's length before +/// a driver's stall is taken, whose end is no slice's), without the lock `state` holds, which +/// comes back taken. Where a value landed, its events observe their counters, and the state is +/// marked for a pass. fn wait_for_gpu<'a>( shared: &'a SchedulerShared, mut state: std::sync::MutexGuard<'a, State>, nudge: &Nudge, gpu: &mut GpuWait, + (slice, short): (Duration, bool), ) -> std::sync::MutexGuard<'a, State> { shared.gpu_waits.fetch_add(1, Ordering::Relaxed); let target = state.nudge_value + 1; @@ -965,7 +1026,7 @@ fn wait_for_gpu<'a>( // the thread stopped; each value is a submitted signal's, or the nudge's next, which a // waker signals. let waited = - unsafe { (nudge.functions.get()).wait_semaphores(&info, WAIT_SLICE.as_nanos() as u64) }; + unsafe { (nudge.functions.get()).wait_semaphores(&info, slice.as_nanos() as u64) }; exit_guard::called(exit_guard::Call::WaitSemaphores); waited }); @@ -988,9 +1049,10 @@ fn wait_for_gpu<'a>( } // Nudged: the waker counted the waking and marked the state. Some(Ok(())) => {} - Some(Err(vk::Result::TIMEOUT)) => { + Some(Err(vk::Result::TIMEOUT)) if !short => { shared.wakings[Woken::Slice as usize].fetch_add(1, Ordering::Relaxed); } + Some(Err(vk::Result::TIMEOUT)) => {} // A failed wait (a lost device) or an exit: a pass finds out. _ => state.dirty = true, } diff --git a/crates/metal2vulkan-runtime/src/sparse/bind.rs b/crates/metal2vulkan-runtime/src/sparse/bind.rs index 8bb81c7da..c464e573d 100644 --- a/crates/metal2vulkan-runtime/src/sparse/bind.rs +++ b/crates/metal2vulkan-runtime/src/sparse/bind.rs @@ -23,6 +23,7 @@ use super::mapping::{MetalUnit, UnitUpdate, VkUnit}; use super::texture::SparseImage; use crate::device::lock; use crate::device::relay::By; +use crate::device::submit_stalls::Uses; use crate::error::{internal, Error}; use crate::exit_guard::{self, Call}; use crate::heap::Heap; @@ -336,7 +337,7 @@ pub(crate) fn bind_batch( // lock. Where the queue's failures are relayed, one of the bind's loses the device // (`device/relay.rs`). shared.counts.queue_submitted(0, 0); - let bound = shared.use_queue(queue, By::Runtime, |vk_queue| unsafe { + let bound = shared.use_queue(queue, By::Runtime, Uses::Unknown, |vk_queue| unsafe { shared .vk() .queue_bind_sparse(vk_queue, &[info], vk::Fence::null()) diff --git a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs index 5af2d543a..65d20d68b 100644 --- a/crates/metal2vulkan-runtime/src/tests/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/tests/exit_guard.rs @@ -1649,7 +1649,7 @@ fn the_device_s_functions_are_reached_through_checked_accessors() { /// tuple field, a type argument or a by-value parameter) fails /// `only_the_listed_modules_keep_the_device_s_functions`; so does a listed module that keeps none /// any more. -const KEEPERS: [(&str, &str); 23] = [ +const KEEPERS: [(&str, &str); 24] = [ ( "binding.rs", "the push command (vkCmdPushDescriptorSet), a call's parameter (`push_set`) and the \ @@ -1678,6 +1678,12 @@ const KEEPERS: [(&str, &str); 23] = [ "device/relay.rs", "the queues' flights, taken back from the instance's relay first in the teardown", ), + ( + "device/submit_stalls.rs", + "the empty submissions that take a driver's stalls idle, made by the scheduler's thread \ + inside a section; the teardown waits for the device to idle, the thread having stopped, \ + before it releases their semaphores", + ), ( "draw_source.rs", "a draw's recording (vkCmd*), held by what holds its command buffer", diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index b04ef14c6..d426a8c8d 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -266,6 +266,9 @@ mod srgb_fetch_images; mod stage_entries_shared; mod stand_in; mod storage_form; +mod submit_stalls; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod submit_stalls_idle; mod surface_depth; mod surface_two_planes; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/tests/submit_stalls.rs b/crates/metal2vulkan-runtime/src/tests/submit_stalls.rs new file mode 100644 index 000000000..09e91989b --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/submit_stalls.rs @@ -0,0 +1,242 @@ +//! The plan that takes a driver's stall in one signalling submission of every 1024 to a queue +//! while the scheduler is idle (`device/submit_stalls.rs`), against a model of the driver. + +use crate::device::submit_stalls::{ + Caller, Period, BEHIND_NANOS, IDLE_NANOS, MARGIN, MOST_EMPTY, PERIOD, STALL_NANOS, +}; + +/// The stall the RTX 5080's driver took, and its other calls' time, in nanoseconds. +const STALL: u64 = 2_300_000; +const CALL: u64 = 2_000; + +/// A driver whose every [`PERIOD`]th signalling call to the queue stalls, its first at call +/// `first`, and every `early`th period `by` calls early; or none, where `stalls` is false. +struct Driver { + calls: u64, + first: u64, + stalls: bool, + /// The call that last stalled, and the periods so far. + last: Option, + periods: u64, + early: Option<(u64, u64)>, +} + +impl Driver { + fn new(first: u64, stalls: bool) -> Driver { + Driver { + calls: 0, + first, + stalls, + last: None, + periods: 0, + early: None, + } + } + + /// One signalling call: its time. + fn call(&mut self) -> u64 { + self.calls += 1; + let period = match self.early { + Some((every, by)) if (self.periods + 1).is_multiple_of(every) => u64::from(PERIOD) - by, + _ => u64::from(PERIOD), + }; + let stalls = self.stalls + && match self.last { + None => self.calls == self.first, + Some(last) => self.calls - last >= period, + }; + if !stalls { + return CALL; + } + if self.last.is_some() { + self.periods += 1; + } + self.last = Some(self.calls); + STALL + } +} + +/// What a run of frames did: the stalls on work, those taken idle, and the empty calls made. +#[derive(Debug, Default, PartialEq, Eq)] +struct Run { + on_work: u32, + idle: u32, + empty: u32, +} + +/// `frames` frames of `per_frame` submissions 15 us apart, each frame followed by an idle of 8 ms +/// in which the scheduler takes the stall due where `take`, as `IdleStalls::take` does. +fn frames(driver: &mut Driver, frames: u32, per_frame: u32, take: bool) -> Run { + let (mut period, mut run, mut now) = (Period::default(), Run::default(), 0); + for _ in 0..frames { + for _ in 0..per_frame { + let took = driver.call(); + now += took + 15_000; + if period.called(Caller::Work, took, now) { + run.on_work += 1; + } + } + now += 8_000_000; + if take && period.may_be_due() { + for _ in 0..period.due_idle() { + let took = driver.call(); + now += took; + run.empty += 1; + if period.called(Caller::Empty, took, now) { + run.idle += 1; + break; + } + } + } + } + run +} + +/// 200 frames of 25 command buffers (5000 submissions): without the plan, one in 1024 falls on +/// work; with it, the first alone, which teaches the plan the queue's place, and every later one +/// is taken idle, by no more empty calls a stall than a burst and the margin. +#[test] +fn every_stall_after_the_first_is_taken_idle() { + let without = frames(&mut Driver::new(28, true), 200, 25, false); + assert_eq!(without.on_work, 5, "{without:?}"); + let with = frames(&mut Driver::new(28, true), 200, 25, true); + assert_eq!(with.on_work, 1, "{with:?}"); + assert!(with.idle >= 4, "{with:?}"); + assert!(with.empty <= with.idle * (25 + MARGIN), "{with:?}"); + // Whatever the driver's place at the first stall. + for first in [1, 25, 26, 500, 1023, 1024] { + let with = frames(&mut Driver::new(first, true), 200, 25, true); + assert_eq!(with.on_work, 1, "first {first}: {with:?}"); + assert!(with.idle >= 4, "first {first}: {with:?}"); + } +} + +/// A stall that comes 24 calls before the 1024th, as 5 of 58 did on the RTX 5080, is taken +/// idle too: the margin covers it. +#[test] +fn a_stall_that_comes_early_is_taken_idle() { + let mut driver = Driver::new(28, true); + driver.early = Some((3, 24)); + let with = frames(&mut driver, 400, 25, true); + assert!(driver.periods >= 9, "{}", driver.periods); + assert_eq!(with.on_work, 1, "{with:?}"); + assert_eq!(u64::from(with.idle), driver.periods, "{with:?}"); +} + +/// A driver that never stalls gets no empty call: no place is learnt. +#[test] +fn no_stall_seen_takes_none() { + let run = frames(&mut Driver::new(28, false), 200, 25, true); + assert_eq!(run, Run::default()); +} + +/// A stall due that did not come forgets the place: no empty call until the next stall. +#[test] +fn a_stall_due_that_does_not_come_forgets_the_place() { + let mut period = Period::default(); + assert!(period.called(Caller::Work, STALL, 10 * STALL)); + for at in 0..PERIOD - 1 { + assert!(!period.called(Caller::Work, CALL, 20 * STALL + u64::from(at))); + } + assert!(period.may_be_due()); + assert!(!period.called(Caller::Work, CALL, 30 * STALL)); + assert!(!period.may_be_due()); + assert_eq!(period.due_idle(), 0); +} + +/// A use of the queue the runtime cannot count forgets the place. +#[test] +fn an_uncounted_use_forgets_the_place() { + let mut period = Period::default(); + period.called(Caller::Work, STALL, STALL); + for at in 0..PERIOD - 10 { + period.called(Caller::Work, CALL, STALL + 15_000 * u64::from(at)); + } + assert!(period.may_be_due()); + period.forget(); + assert!(!period.may_be_due()); + assert_eq!(period.due_idle(), 0); +} + +/// A stall further off than the next burst (the largest of the last, plus the margin) waits for +/// a later idle; one within it is due, the calls left up to and including its own; never more +/// than `MOST_EMPTY`. +#[test] +fn a_stall_is_taken_within_the_next_burst() { + let burst = |period: &mut Period, calls: u32, now: &mut u64| { + *now += 2 * IDLE_NANOS; + for _ in 0..calls { + *now += 15_000; + period.called(Caller::Work, CALL, *now); + } + }; + let (mut period, mut now) = (Period::default(), 0); + period.called(Caller::Work, STALL, STALL); + // 38 bursts of 25 after the stall (the first with the stall's call): 950 calls since, 74 + // left. + for _ in 0..38 { + burst(&mut period, 25, &mut now); + } + assert_eq!(period.due_idle(), 0, "74 left, past 26 + {MARGIN}"); + burst(&mut period, 25, &mut now); + assert_eq!( + period.due_idle(), + 49, + "49 left, within the next burst and the margin" + ); + // Bursts larger than the most: due within `MOST_EMPTY` calls alone. + let (mut period, mut now) = (Period::default(), 0); + period.called(Caller::Work, STALL, STALL); + burst(&mut period, 700, &mut now); + assert_eq!(period.due_idle(), 0, "324 left"); + burst(&mut period, 200, &mut now); + assert_eq!(period.due_idle(), 124, "124 left, within {MOST_EMPTY}"); +} + +/// Calls 15 us apart are one burst, and one an idle apart begins the next. +#[test] +fn an_idle_splits_bursts() { + let (mut period, mut now) = (Period::default(), 0); + period.called(Caller::Work, STALL, STALL); + for _ in 0..1000 { + now += 15_000; + period.called(Caller::Work, CALL, now); + } + // One burst of 1001 calls: 24 left, within the most. + assert_eq!(period.due_idle(), 24); + let (mut period, mut now) = (Period::default(), 0); + period.called(Caller::Work, STALL, STALL); + for at in 0..924 { + now += match at % 10 { + 0 => 2 * IDLE_NANOS, + _ => 15_000, + }; + period.called(Caller::Work, CALL, now); + } + // Bursts of 10 (the first with the stall's, 11): 100 left, past 11 + the margin. + assert_eq!(period.due_idle(), 0); +} + +/// A call under `STALL_NANOS` is no stall, whatever its length. +#[test] +fn a_long_call_short_of_a_stall_is_none() { + let mut period = Period::default(); + assert!(!period.called(Caller::Work, STALL_NANOS - 1, STALL_NANOS)); + assert!(!period.may_be_due()); + assert!(period.called(Caller::Work, STALL_NANOS, 3 * STALL_NANOS)); +} + +/// The call that takes the queue's lock next waited behind a stall taken idle where an empty +/// call stalled before it and it waited `BEHIND_NANOS` or more; the one after it did not, nor one +/// after a stall that fell on work. +#[test] +fn a_wait_behind_a_stall_taken_idle_is_counted_once() { + let mut period = Period::default(); + period.called(Caller::Empty, STALL, STALL); + assert_eq!(period.entered(BEHIND_NANOS - 1), None); + period.called(Caller::Empty, STALL, 2 * STALL); + assert_eq!(period.entered(STALL / 2), Some(STALL / 2)); + assert_eq!(period.entered(STALL / 2), None); + period.called(Caller::Work, STALL, 3 * STALL); + assert_eq!(period.entered(STALL / 2), None); +} diff --git a/crates/metal2vulkan-runtime/src/tests/submit_stalls_idle.rs b/crates/metal2vulkan-runtime/src/tests/submit_stalls_idle.rs new file mode 100644 index 000000000..4308ec46a --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/submit_stalls_idle.rs @@ -0,0 +1,125 @@ +//! The scheduler's thread takes a driver's stall in one signalling submission of every 1024 to a +//! queue while it is idle (`device/submit_stalls.rs`) on a device whose driver has the cost fact +//! (`DriverFact::SignallingSubmitsStallEvery1024`), and makes no empty submission on any other. +//! +//! 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. + +use crate::{CommandQueue, Device, DeviceKind, DeviceOptions, ResourceOptions, ShaderCacheOptions}; +use metal2vulkan::device::DriverFact; +use std::path::PathBuf; +use std::time::Duration; + +/// The frames, and each frame's command buffers: about five of the driver's periods of 1024 +/// signalling submissions, at the 25 command buffers a frame `host_ab present` commits. +const FRAMES: u32 = 200; +const PER_FRAME: u32 = 25; + +/// The gap after each frame: longer than the idle the scheduler's thread waits for before it +/// takes a stall due (`IDLE_NANOS`), with room for the stall itself. +const GAP: Duration = Duration::from_millis(8); + +/// A scratch directory for the device's shader cache, removed when dropped. +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Scratch { + let path = std::env::temp_dir().join(format!("m2v-submit-stalls-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + Scratch(path) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache in +/// `scratch`. +fn device(scratch: &Scratch) -> Device { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(scratch.0.clone()), + ..ShaderCacheOptions::default() + }, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// [`FRAMES`] frames of [`PER_FRAME`] command buffers of `queue`, each a fill of 16 bytes, +/// committed back to back, the last waited for, then [`GAP`] with nothing committed. +fn frames(device: &Device, queue: &CommandQueue) { + let target = device.new_buffer(16, ResourceOptions::shared()).unwrap(); + for frame in 0..FRAMES { + let mut last = None; + for _ in 0..PER_FRAME { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&target, 0..16, frame as u8).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + last = Some(command_buffer); + } + let last = last.unwrap(); + last.wait_until_completed().unwrap(); + assert_eq!(last.error(), None); + std::thread::sleep(GAP); + } +} + +/// Over about five periods of frames with idle gaps between them: on a driver with the stall, +/// the scheduler took at least one stall in a gap, by empty submissions that took at most the +/// burst and the margin a stall (`WorkCounts::submit_stalls_idle`, `WorkCounts::idle_submits`); +/// on every other driver it made no empty submission. The counts are printed either way. +#[test] +fn the_scheduler_takes_the_driver_s_stalls_while_idle_only_where_the_driver_has_them() { + let scratch = Scratch::new(); + let device = device(&scratch); + let queue = device.new_command_queue().unwrap(); + let stalls = + (device.properties().driver_facts).contains(&DriverFact::SignallingSubmitsStallEvery1024); + let before = device.work_counts(); + frames(&device, &queue); + let after = device.work_counts(); + let idle_submits = after.idle_submits - before.idle_submits; + let idle = after.submit_stalls_idle - before.submit_stalls_idle; + let on_work = after.submit_stalls_on_work - before.submit_stalls_on_work; + let behind = after.submits_behind_idle_stalls - before.submits_behind_idle_stalls; + println!( + "{}: driver stalls every 1024th signalling submit: {stalls}; over {} command buffers: \ + idle_submits {idle_submits} submit_stalls_idle {idle} submit_stalls_on_work {on_work} \ + submits_behind_idle_stalls {behind} wait_behind_idle_stall_longest_nanos {}", + device.name(), + FRAMES * PER_FRAME, + after.wait_behind_idle_stall_longest_nanos, + ); + match stalls { + true => { + assert!( + idle >= 1, + "no stall was taken idle over {} command buffers", + FRAMES * PER_FRAME + ); + let most = idle * u64::from(PER_FRAME + crate::device::submit_stalls::MARGIN); + assert!(idle_submits <= most, "{idle_submits} empty submissions"); + } + false => { + assert_eq!( + idle_submits, 0, + "an empty submission without the driver's stall" + ); + assert_eq!(idle, 0); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 1c127c5e9..0eeb8453a 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -147,6 +147,9 @@ pub(crate) struct Counters { submit_infos: AtomicU64, command_buffers_submitted: AtomicU64, batch_submit_nanos: AtomicU64, + submit_stalls_on_work: AtomicU64, + submits_behind_idle_stalls: AtomicU64, + wait_behind_idle_stall_longest_nanos: AtomicU64, command_buffers_begun: AtomicU64, encoder_command_buffers_begun: AtomicU64, command_buffers_begun_by: [AtomicU64; Begun::COUNT], @@ -1175,6 +1178,19 @@ impl Counters { self.batch_submit_nanos.fetch_add(nanos, Ordering::Relaxed); } + /// A signalling call of work took the driver's stall (`device/submit_stalls.rs`). + pub(crate) fn submit_stall_on_work(&self) { + self.submit_stalls_on_work.fetch_add(1, Ordering::Relaxed); + } + + /// A submission waited `nanos` nanoseconds for its queue's lock behind a stall taken idle + /// (`device/submit_stalls.rs`). + pub(crate) fn submit_behind_idle_stall(&self, nanos: u64) { + self.submits_behind_idle_stalls + .fetch_add(1, Ordering::Relaxed); + (self.wait_behind_idle_stall_longest_nanos).fetch_max(nanos, Ordering::Relaxed); + } + /// A render encoder ended (`RenderCommandEncoder::end_encoding`). pub(crate) fn render_encoder_ended(&self) { self.render_encoders_ended.fetch_add(1, Ordering::Relaxed); @@ -3345,6 +3361,23 @@ pub struct WorkCounts { /// the driver, so a lane that times the scheduler thread's take-up of later commits leaves it /// out (`runtime_lane::queue_order`). pub batch_submit_nanos: u64, + /// Empty submissions the scheduler's thread made while idle to take the driver's stall in + /// one signalling submission of every 1024 to a `VkQueue` then, on a driver that has it + /// (NVIDIA's; `device/submit_stalls.rs`): the calls left before the stall, where it was due + /// within the queue's next burst of work. + pub idle_submits: u64, + /// Of those, the ones that took the stall: 2.2 ms or more each on the RTX 5080 measured. + pub submit_stalls_idle: u64, + /// Signalling submissions of work that took 2 ms or more in the driver (on a driver with + /// the stall above, the stall where none was taken idle: before the first was seen, or after + /// a use of the queue the runtime cannot count). + pub submit_stalls_on_work: u64, + /// Work that came while a stall taken idle ran: a submission that waited 10 us or more for + /// its queue's lock behind it, and a commit that reached the scheduler meanwhile. + pub submits_behind_idle_stalls: u64, + /// The longest of those waits, in nanoseconds: a submission's wait for the lock, and for a + /// commit, the stall it came during (its wait at most). + pub wait_behind_idle_stall_longest_nanos: u64, /// `VkCommandBuffer`s the runtime began once the device was made: each encoder's, a render /// encoder's draws' secondary ones, segments', a batch's barrier and first-work ones, internal /// and staging submissions'. A driver may clear a command buffer's state as it begins one @@ -4728,6 +4761,7 @@ impl Device { |cause: Split| counters.instance_splits_by[cause as usize].load(Ordering::Relaxed); let (sleeps, [by_commit, by_completion, by_host, by_slice], scheduler_spared, gpu_waits) = self.shared().scheduler.sleeps_and_wakings(); + let idle_stalls = self.shared().scheduler.idle_stall_counts(); let (completion_wakes, completion_spared) = self.shared().completion.wakes(); let (handler_wakes, handler_spared) = self.shared().contexts.wakes(); let command_buffer_wakes = counters.command_buffer_wakes.load(Ordering::Relaxed); @@ -4939,6 +4973,14 @@ impl Device { submit_infos: counters.submit_infos.load(Ordering::Relaxed), command_buffers_submitted: counters.command_buffers_submitted.load(Ordering::Relaxed), batch_submit_nanos: counters.batch_submit_nanos.load(Ordering::Relaxed), + idle_submits: idle_stalls.empty, + submit_stalls_idle: idle_stalls.idle, + submit_stalls_on_work: counters.submit_stalls_on_work.load(Ordering::Relaxed), + submits_behind_idle_stalls: idle_stalls.behind + + counters.submits_behind_idle_stalls.load(Ordering::Relaxed), + wait_behind_idle_stall_longest_nanos: idle_stalls + .behind_longest + .max((counters.wait_behind_idle_stall_longest_nanos).load(Ordering::Relaxed)), command_buffers_begun: counters.command_buffers_begun.load(Ordering::Relaxed), command_buffers_begun_encoders: begun(Begun::Encoder), command_buffers_begun_segments: begun(Begun::Segment), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 9123a70f1..fbc20b3ea 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -bd3b5730fc4b2fbeb7731773b63c21aa7c3b5999d036e30377e083752cc795ef +ec4e574d095677009982b987db53730ab11c8a790d5deb679386daf96e84cab8 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d910a4032..2dbf673ce 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 477; /// 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 = 1684; +pub const RUNTIME_VERSION: u32 = 1687; /// 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 diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 67531f765..99e599202 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -1259,6 +1259,24 @@ pub enum DriverFact { /// a batch) for about 1 us of CPU a wait (`command_buffer/submit.rs` in the runtime). Held on /// the GPUs measured alone. SemaphoreOperationsStallSubmits, + /// A cost fact (the module docs): the driver spends milliseconds of the submitting thread's + /// CPU in one `vkQueueSubmit` of every 1024 that signal a fence or a semaphore on a + /// `VkQueue`, counted per queue, whatever the call submits. Measured with a probe outside the + /// runtime, 8192 calls of each form timed one by one: every 1024th signalling call took 2.2 + /// to 3.7 ms, the others 1.6 us (p50), for one command buffer and a timeline signal, no + /// command buffer and a timeline signal, a fence alone, `vkQueueSubmit2`, and four signalling + /// submit infos in one call, 100 us apart or back to back; a call that signals nothing never + /// stalled. Two queues of a device, two devices and two processes each counted their own, and + /// `vkQueueWaitIdle` counted as a call. This is the stall + /// [`DriverFact::SemaphoreOperationsStallSubmits`] counts by semaphore operations. On a driver + /// with it the runtime's scheduler takes the stall while it is idle: once it has seen one on + /// a queue, it counts the queue's signalling calls, and where the next stall is due within the + /// queue's next burst of work it submits the calls left as empty submissions in the gap + /// between bursts (`device/submit_stalls.rs` in the runtime); elsewhere it submits none. No + /// answer changes, only when the stall falls. NVIDIA's 615.71.09 on the RTX 5080 Laptop GPU + /// under Linux; RADV (Mesa 26.2.4 on the Radeon RX 7900 XTX) measured none over 1.4 ms and + /// none periodic, so is not listed. Held on the GPU measured alone. + SignallingSubmitsStallEvery1024, /// A cost fact (the module docs): the driver keeps a single-sample depth image's /// hierarchical depth, with which its depth test rejects hidden fragments a block at a time, /// in the `GENERAL` layout where the image has sampled usage, and drops it there, with the @@ -2065,6 +2083,10 @@ pub(crate) const MEASURED: &[Measured] = &[ NVIDIA_RTX_5080_LAPTOP, ), nvidia_on(DriverFact::SemaphoreOperationsStallSubmits, NVIDIA_RTX_3090), + nvidia_on( + DriverFact::SignallingSubmitsStallEvery1024, + NVIDIA_RTX_5080_LAPTOP, + ), moltenvk_on_apple(DriverFact::TimestampsWaitForEveryQueue), Measured { fact: DriverFact::TimestampPoolsAreCounterSampleBuffers, diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 34fecdf43..04a44d8dc 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -401,6 +401,7 @@ const ROWS: DriverFact = DriverFact::RowCopiesDispatchFaster; const MERGES: DriverFact = DriverFact::SubmissionsWithoutSignalsMerge; const MESSENGER: DriverFact = DriverFact::QueueFailuresReportedByMessenger; const STALL: DriverFact = DriverFact::SemaphoreOperationsStallSubmits; +const STALL_1024: DriverFact = DriverFact::SignallingSubmitsStallEvery1024; const SAMPLED_HIZ: DriverFact = DriverFact::SampledDepthKeepsHiZ; const MSAA_DEPTH: DriverFact = DriverFact::MultisampledDepthFasterOutOfGeneral; const TILE_STORE: DriverFact = DriverFact::TileStoreIsMetals; @@ -552,7 +553,7 @@ fn the_committed_profiles_drivers_have_their_facts() { ( "nvidia-rtx5080-laptop", vec![ - ZERO, DENORMALS, FETCH, SPLIT, PLANES, BC6H, BC7, ROWS, STALL, + ZERO, DENORMALS, FETCH, SPLIT, PLANES, BC6H, BC7, ROWS, STALL, STALL_1024, ], ), ] @@ -651,6 +652,48 @@ fn nvidia_s_semaphore_stall_holds_on_the_gpus_measured() { assert_eq!(drivers, [DriverId::NVIDIA_PROPRIETARY; 2]); } +/// NVIDIA's driver stalls in one signalling submission of every 1024 to a queue on the GPU +/// measured, the RTX 5080 Laptop GPU, at every release, so the runtime takes that stall while +/// idle there; the RTX 3090 and an RTX 5080 desktop GPU, not measured in that form, do not take +/// the fact, nor does RADV, measured without it, or any other driver. +#[test] +fn nvidia_s_every_1024th_signalling_submit_stall_holds_on_the_gpu_measured() { + use crate::device::driver_facts::NVIDIA_RTX_5080_LAPTOP; + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); + let read = |stem: &str| { + let text = std::fs::read_to_string(dir.join(format!("{stem}.json"))).expect(stem); + DeviceDescription::from_khronos_json(&text, None).expect("profile parses") + }; + let laptop = read("nvidia-rtx5080-laptop"); + assert!(laptop.driver_facts().contains(&STALL_1024)); + let mut later = laptop.clone(); + later.driver_version += 1 << 6; + assert!(later.driver_facts().contains(&STALL_1024)); + let mut rtx_3090 = laptop.clone(); + rtx_3090.device_id = NVIDIA_RTX_3090; + assert!(!rtx_3090.driver_facts().contains(&STALL_1024)); + let mut desktop = laptop.clone(); + desktop.device_id = 0x2c02; + assert!(!desktop.driver_facts().contains(&STALL_1024)); + for stem in [ + "amd-rdna3-radv", + "moltenvk-m3", + "intel-irisxe-rplp-anv", + "lavapipe", + ] { + assert!(!read(stem).driver_facts().contains(&STALL_1024), "{stem}"); + } + let rows: Vec<(DriverId, Option)> = MEASURED + .iter() + .filter(|row| row.fact == STALL_1024) + .map(|row| (row.driver, row.device)) + .collect(); + assert_eq!( + rows, + [(DriverId::NVIDIA_PROPRIETARY, Some(NVIDIA_RTX_5080_LAPTOP))] + ); +} + /// RADV on the RX 7900 XTX takes the facts measured on it: its pointer imports follow their /// address and its submissions without signals merge, as the 780M's do, and it reads zero past a /// bound index range, RADV's on every GPU; no answer measured on the 780M alone (its block decodes, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index bf52db595..da66a659f 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2619,6 +2619,7 @@ field metal2vulkan-runtime::WorkCounts.host_texture_shadows_render_target pub ho field metal2vulkan-runtime::WorkCounts.host_texture_shadows_shader_write pub host_texture_shadows_shader_write: u64 field metal2vulkan-runtime::WorkCounts.host_texture_shadows_unchecked pub host_texture_shadows_unchecked: u64 field metal2vulkan-runtime::WorkCounts.host_textures_in_place pub host_textures_in_place: u64 +field metal2vulkan-runtime::WorkCounts.idle_submits pub idle_submits: u64 field metal2vulkan-runtime::WorkCounts.image_blits_recorded pub image_blits_recorded: u64 field metal2vulkan-runtime::WorkCounts.images_started_on_the_host pub images_started_on_the_host: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_failed pub in_place_checks_failed: u64 @@ -2835,6 +2836,9 @@ field metal2vulkan-runtime::WorkCounts.storage_forms_taken pub storage_forms_tak field metal2vulkan-runtime::WorkCounts.storage_placeholder_attachments pub storage_placeholder_attachments: u64 field metal2vulkan-runtime::WorkCounts.storage_placeholders_made pub storage_placeholders_made: u64 field metal2vulkan-runtime::WorkCounts.submit_infos pub submit_infos: u64 +field metal2vulkan-runtime::WorkCounts.submit_stalls_idle pub submit_stalls_idle: u64 +field metal2vulkan-runtime::WorkCounts.submit_stalls_on_work pub submit_stalls_on_work: u64 +field metal2vulkan-runtime::WorkCounts.submits_behind_idle_stalls pub submits_behind_idle_stalls: u64 field metal2vulkan-runtime::WorkCounts.texel_shadow_bytes pub texel_shadow_bytes: u64 field metal2vulkan-runtime::WorkCounts.texel_shadow_reads pub texel_shadow_reads: u64 field metal2vulkan-runtime::WorkCounts.texel_shadows_dropped pub texel_shadows_dropped: u64 @@ -2857,6 +2861,7 @@ field metal2vulkan-runtime::WorkCounts.variants_taken_back pub variants_taken_ba field metal2vulkan-runtime::WorkCounts.view_shadows pub view_shadows: u64 field metal2vulkan-runtime::WorkCounts.views_through_swizzle pub views_through_swizzle: u64 field metal2vulkan-runtime::WorkCounts.visibility_queries_begun pub visibility_queries_begun: u64 +field metal2vulkan-runtime::WorkCounts.wait_behind_idle_stall_longest_nanos pub wait_behind_idle_stall_longest_nanos: u64 field metal2vulkan-runtime::WorkCounts.wakes_command_buffer_waiters pub wakes_command_buffer_waiters: u64 field metal2vulkan-runtime::WorkCounts.wakes_completion_waiters pub wakes_completion_waiters: u64 field metal2vulkan-runtime::WorkCounts.wakes_event_waiters pub wakes_event_waiters: u64 @@ -11050,6 +11055,7 @@ variant metal2vulkan-runtime::DriverFact::SampledFetchRecoversCodes SampledFetch variant metal2vulkan-runtime::DriverFact::SemaphoreOperationsStallSubmits SemaphoreOperationsStallSubmits variant metal2vulkan-runtime::DriverFact::ShadowCopyBackDispatchFaster ShadowCopyBackDispatchFaster variant metal2vulkan-runtime::DriverFact::ShadowCopyInDispatchFaster ShadowCopyInDispatchFaster +variant metal2vulkan-runtime::DriverFact::SignallingSubmitsStallEvery1024 SignallingSubmitsStallEvery1024 variant metal2vulkan-runtime::DriverFact::SubmissionsWithoutSignalsMerge SubmissionsWithoutSignalsMerge variant metal2vulkan-runtime::DriverFact::TileStoreIsMetals TileStoreIsMetals variant metal2vulkan-runtime::DriverFact::TimestampPoolsAreCounterSampleBuffers TimestampPoolsAreCounterSampleBuffers @@ -12272,6 +12278,7 @@ variant metal2vulkan::device::DriverFact::SampledFetchRecoversCodes SampledFetch variant metal2vulkan::device::DriverFact::SemaphoreOperationsStallSubmits SemaphoreOperationsStallSubmits variant metal2vulkan::device::DriverFact::ShadowCopyBackDispatchFaster ShadowCopyBackDispatchFaster variant metal2vulkan::device::DriverFact::ShadowCopyInDispatchFaster ShadowCopyInDispatchFaster +variant metal2vulkan::device::DriverFact::SignallingSubmitsStallEvery1024 SignallingSubmitsStallEvery1024 variant metal2vulkan::device::DriverFact::SubmissionsWithoutSignalsMerge SubmissionsWithoutSignalsMerge variant metal2vulkan::device::DriverFact::TileStoreIsMetals TileStoreIsMetals variant metal2vulkan::device::DriverFact::TimestampPoolsAreCounterSampleBuffers TimestampPoolsAreCounterSampleBuffers diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index e8f7893e4..0eb6626b3 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -82,6 +82,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | Float simdgroup reductions sum in the device's association order. | Apple's order is not modelled. | `ReductionOrder` (`reduction-order`) | | A vertex or fragment function keeps more than 16 KiB a thread of private memory, up to the 192 KiB Metal holds, on a device whose Function storage was not measured: it runs on the driver's scratch, which past what the driver holds answers wrongly or hangs the GPU with no error. | Vulkan states no amount of Function storage; only a measurement of the device does. No other form is exact: a fragment function's helper invocations may not write the memory it would move to, and a vertex function's, a compute pre-pass, is not built. | `FunctionStorageAssumed` (`function-storage-assumed`) | | A render pipeline of more color attachments than the device draws at once (the lesser of `maxColorAttachments` and `maxFragmentOutputAttachments`, four at Vulkan's floor; Metal takes eight) draws each draw once per group of that many, each group in a render pass of its own over a twin of the pass's depth and stencil. Every variant's vertex stage is one module, `Position` invariant, and every fragment variant's `FragDepth`, `SampleMask` and `FragStencilRefEXT` are `Invariant`; groups past the first may differ at discard or depth edges if the driver compiles the variants differently. | The device holds no more attachments in one subpass. Vulkan's invariance rules make only identical pipelines repeat exactly, and the groups' fragment modules and attachments differ. | `ColorAttachmentGroups` (`color-attachment-groups`) | +| On NVIDIA's driver (615.71.09 on an RTX 5080 Laptop GPU) one `vkQueueSubmit` in every 1024 that signal on a `VkQueue` takes 2.2 to 3.7 ms in the driver, which holds the command buffer whose batch it falls on, and the ones committed behind it, from the GPU that long. | The cost is the driver's, and every batch signals its completion. The scheduler's thread takes the stall while idle, by empty submissions, once one was seen (`DriverFact::SignallingSubmitsStallEvery1024`, `device/submit_stalls.rs`): it falls on work only before then, after a use of the queue the runtime cannot count, or on a queue that never idles 1 ms. Whether the driver's stall also holds other threads' semaphore calls is unsettled: a probe polling the timeline from a second thread during 10 stalls saw 5 of its 9 slow calls (up to 7.1 ms) overlap one in one run, and none of its 3 in another; in `host_ab present` the completion handlers of command buffers that completed during a stall taken idle ran 126 us (p50, 341 at most) after their GPU end, as elsewhere. | None (timing only; `WorkCounts::submit_stalls_on_work`, `WorkCounts::submit_stalls_idle`) | | Command buffers that share no resource run one after another, where Metal overlaps them while the GPU has room. | The runtime orders nothing between them and runs at each driver's floor for one completion signal per command buffer; a signal shared by several would hold an earlier one's completion for the later ones' work. | None (timing only) | | On MoltenVK a light queue's command buffer waits for the latest one another queue committed, where Metal waits for none: MoltenVK fences every encoder of every queue device-wide when argument buffers and a residency set are on. | The runtime needs argument buffers, and MoltenVK has no setting for its residency set; `runtime_lane::queue_storms` judges the runtime against Metal under those fences. | None (timing only) | | A `Counting` visibility result of a draw writing more than one color attachment, on ANV (Mesa 26.2.4): Metal's count multiplied by the colors written, not divided back. `Boolean` results stay exact. | The driver counts each sample once per color output (`RuntimeDriverDefect::OcclusionCountPerColorOutput`), no documented Vulkan form counts it once, and a refusal would withhold the Mac2 and Metal3 families. | `VisibilityCountPerColor` (`visibility-count-per-color`) |