From 7996b9a1645ed8ebe8db155e0d309e8d075db0fd Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 06:12:25 -0800 Subject: [PATCH] Mark a queue long by its command buffer's own GPU time, not the host's view of its head's age What: a command queue is now marked long where one of its command buffers' own timestamps (its first batch's start to its last's end) span over LONG_HEAD (2 ms), in the completion turn that read them (CommandBufferShared::place_gpu_times), before the turn finishes it. The waiter's host-age check in command_buffer/completion.rs (HeadWatch, Device::head_watch) is removed, and went_long returns at once unless the device shares. A device whose command buffers write no timestamps the host reads (gpu_times_from_host, a driver whose timestamps wait for every queue's, or no calibrated timestamps) no longer shares: queue_switch_check::timed() gates the check, and recall settles Unchecked and counts the new WorkCounts::queue_sharing_untimed where the device has two VkQueues of one family to share. Two runtime extensions, doc-hidden, for the lanes and the probe: CommandQueue::vk_queue_sharing() (its VkQueue and long mark) and Device::shares_vk_queues(). Why: the host's view of a batch's age as its VkQueue's oldest also holds its wait for the GPU to start it and the waiter's lateness to see it complete, so short command buffers marked their queues long for good. On the RTX 5080 Laptop GPU, 2x3 runs in a slow stretch had each thread's queue marked long mid-run (at 20 ms to 1,238 ms) and settled apart, the PerQueue placement, at PerQueue's rates. Measured cause, with a diagnostic build printing each host-age mark beside the command buffer's own GPU span: beside another process's 30 ms command buffers, draws of 11 and 16 us of GPU time were seen 2.0 and 2.3 ms after they became their VkQueue's oldest, 1.8 and 2.1 ms of that before they started; that run's thread queue settled apart and ran at PerQueue's 4.1k. In the runs without contention, every true mark had a GPU span within 1.2 ms of its host age (the 30 ms command buffers and the probe's 2.7 ms sizing one); under contention the sizing command buffer's host age exceeded its span by 4.2 ms. Neither suggested alternative fits: the false marks came mid-run, not only in a queue's first command buffers, and decaying the mark after short heads would let the trap and alternating shapes' long queues rejoin and stall the compositor again. Tests: tests::queue_share_device gains a_device_that_answers_gpu_times_from_the_host_does_not_ share_and_counts_it (expected, not run, to fail without the gate on the 5080: there it printed "Unchecked ... could share: true", so the recorded Idles verdict would make it share), and asserts queue_sharing_untimed == 0 elsewhere; its isolation runs print each queue's VkQueue and mark over the run. The queues lane's a_queue_joining_another_s_busy_vk_queue_is_announced_once now makes its device under QueueSharingPolicy::Adaptive (over the lane's exact_answers()), lets the busy queue's fills be submitted first, and asserts queue_joins > 0 exactly where the device shares, saying why where it does not. cross_queue_shadows gains the signal-in-between and the waiting-writer cases on one VkQueue: no spin, Adaptive, the check settled, queue 2 joining queue 1's busy VkQueue; they assert the join, neither queue long, the hold still withheld while the waiting writer has not completed, and the bytes. Docs: QueueSharingPolicy::Adaptive, the FAST-PATHS row (the rule, the untimed exclusion, the new ranges), docs/API.md (the policy section and the notice), the queue-sharing notice's cost text, queue.rs and queue_share.rs; api_signatures blessed (additions only). Verified on the RTX 5080 Laptop GPU (NVIDIA 615.71.09, msi, under gpu-locks, no VM), release probe: - 2 threads x 3 in flight, 10 runs each in turn: Adaptive 48.3, 28.0, 50.7, 52.9, 28.1, 53.7, 48.6, 29.9, 31.5, 53.0k against PerQueue 21.4, 24.9, 27.8, 28.0, 27.6, 27.4, 27.1, 23.3, 26.9, 27.3k, Adaptive above PerQueue in each pair; no thread's queue marked long in any run (gone long 1 each: the probe's sizing queue). The 28-31k runs keep the shared placement, with waiter parks 0.23 against 0.02-0.05 per command buffer in the fast ones: a host-side mode, not a move. - Beside another process's 30 ms command buffers, 3 runs each: the old rule 4.1k (a thread's queue marked long by its host age), 5.2k, 6.6k; this rule 6.7k, 5.4k, 5.1k (no mark); PerQueue 4.1k, 4.1k, 4.0k. There, draws' own spans reached 1.16 to 1.52 ms (timesliced), under the bound. - Isolation, 3 runs each: trap and slow-alternating 64 completions over 10 ms under Adaptive (the one first-long stall, at most 26.4 to 30.1 ms) against none under PerQueue (at most 5.6 to 9.7 ms); alternating none under Adaptive (at most 5.7 to 9.8 ms) against 7, 0, 0 under PerQueue. Unchanged from the host-age rule's runs. - 8 threads: 3 in flight 53.4k, 54.4k against 27.8k, 27.4k; 1 in flight 50.1k, 49.3k against 14.0k, 13.9k. - Device tests (debug, --cfg m2v_gpu): tests::queue_share_device 8/8, the joining lane test and cross_queue_shadows 7/7 (the one-VkQueue cases: X's and Y's queues both on VkQueue 1, neither long, holds withheld 2, gated copies in 2). The compositor isolation test, old rule and new in turn, 3 each: p99 2.66-2.94 ms against 2.16-2.83 ms, 0 stalls, the same placement (the compositor alone on VkQueue 1, the application long on VkQueue 0, gone long 1). Its one earlier failure under this rule (p99 7.93 ms, 20 stalls, 5,579 of ~9,600 commits made) ran right after a 74 s compile inside the hold, with the same placement and gone long 1: host load, not the rule. On the M3 Max (MoltenVK, no sharing), tests::queue_share*, command_queues, cross_queue_shadows, gpu_time and host_memory: 90/90. clippy -D warnings plain and --cfg m2v_gpu; RUSTDOCFLAGS=-D warnings cargo doc; fast_paths, degradation*, api_signatures, api_surface, work_counts pass. No RUNTIME_VERSION bump or pin here. (cherry picked from commit 4fd88b7564cd9cd3651543bb3f8cd529b021709e, two claims corrected to what was run) (cherry picked from commit eb0153e9d0fe6d272f2411c65f0a1ecda2c78bc2) --- .../examples/queue_share.rs | 32 ++- .../src/command_buffer/completion.rs | 11 - .../src/command_buffer/mod.rs | 14 +- .../metal2vulkan-runtime/src/degradation.rs | 5 +- crates/metal2vulkan-runtime/src/queue.rs | 31 ++- .../metal2vulkan-runtime/src/queue_share.rs | 91 ++++---- .../src/queue_switch_check.rs | 18 +- .../src/tests/queue_share_device.rs | 95 ++++++-- .../metal2vulkan-runtime/src/work_counts.rs | 17 +- .../src/runtime_lane/command_queues.rs | 40 +++- .../src/runtime_lane/cross_queue_shadows.rs | 214 +++++++++++++++++- crates/metal2vulkan/src/device/policy.rs | 22 +- crates/metal2vulkan/tests/api_signatures.tsv | 3 + docs/API.md | 15 +- docs/FAST-PATHS.md | 2 +- 15 files changed, 484 insertions(+), 126 deletions(-) diff --git a/crates/metal2vulkan-runtime/examples/queue_share.rs b/crates/metal2vulkan-runtime/examples/queue_share.rs index 21ef48e9e..ec444b32b 100644 --- a/crates/metal2vulkan-runtime/examples/queue_share.rs +++ b/crates/metal2vulkan-runtime/examples/queue_share.rs @@ -323,6 +323,10 @@ fn fixture_bitcode() -> Vec { /// Each draw's queue number and its GPU start and end there, in seconds. type Times = Arc>>; +/// A queue's changes of `VkQueue` or long mark: its command buffers made by then, the +/// microseconds into the run, and its `VkQueue` and mark. +type Seen = Vec<(u64, u128, (usize, bool))>; + /// The p50, p99 and largest of `samples` (milliseconds), and how many are stalls. fn summary(samples: &mut [f64]) -> String { if samples.is_empty() { @@ -629,8 +633,16 @@ fn rate(kit: &Arc, options: &Options, threads: usize, in_flight: usize) { let target = kit.target(); let mut flying = std::collections::VecDeque::new(); let mut made = 0u64; + // Each change of the queue's `VkQueue` or long mark: at which command buffer, + // how far into the run. + let mut seen = Vec::new(); + let started = Instant::now(); while !stop.load(Ordering::Relaxed) { let command_buffer = kit.draw(&queue, &target); + let now = queue.vk_queue_sharing(); + if seen.last().is_none_or(|&(_, _, last)| last != now) { + seen.push((made, started.elapsed().as_micros(), now)); + } let times = Arc::clone(×); let latencies = Arc::clone(&latencies); let committed = Arc::new(Mutex::new(0.0)); @@ -660,13 +672,14 @@ fn rate(kit: &Arc, options: &Options, threads: usize, in_flight: usize) { for done in flying { done.wait_until_completed().unwrap(); } - made + (made, seen) }) }) .collect(); std::thread::sleep(Duration::from_secs_f64(options.seconds)); stop.store(true, Ordering::Relaxed); - let made: u64 = handles.into_iter().map(|h| h.join().unwrap()).sum(); + let each: Vec<(u64, Seen)> = handles.into_iter().map(|h| h.join().unwrap()).collect(); + let made: u64 = each.iter().map(|(made, _)| made).sum(); let elapsed = began.elapsed().as_secs_f64(); let cpu_after = thread_ticks(); std::thread::sleep(Duration::from_millis(100)); @@ -710,6 +723,21 @@ fn rate(kit: &Arc, options: &Options, threads: usize, in_flight: usize) { per(after.batch_submit_nanos, counts.batch_submit_nanos) / 1e3, ); println!(" threads' CPU: {}", busiest(&cpu, &cpu_after, elapsed)); + for (thread, (made, seen)) in each.iter().enumerate() { + let changes: Vec = seen + .iter() + .map(|(at, us, (vk_queue, long))| { + format!( + "#{at} {us}us VkQueue {vk_queue}{}", + if *long { " long" } else { "" } + ) + }) + .collect(); + println!( + " thread {thread}: {made} command buffers; {}", + changes.join(", ") + ); + } } fn idle_queues(kit: &Arc, options: &Options, count: usize) { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index 32f26127a..be0a8492a 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -909,9 +909,6 @@ fn wait_for_queue(watch: &Watch, queue: usize) { continue; }; device.shared().counts.completion_armed(slept); - // Where the device shares `VkQueue`s, how long the front ran as its queue's oldest is read - // once its wait saw it complete (`queue_share.rs`). - let head = device.head_watch(queue); // The wait is a section of the exit guard; once the process is exiting the waiters end, // and what is pending stays pending, as Metal's does. let polled = match exit_guard::enter() { @@ -922,7 +919,6 @@ fn wait_for_queue(watch: &Watch, queue: usize) { } None => None, }; - let long = head.is_some_and(|head| matches!(&polled, Some(Ok(v)) if head.ran_long(*v))); // Let go of the device before the report: until then the front is pending (nothing // finishes or takes it while this waits), and holds the device, so this is never its // last handle, which goes on the program's or the handlers' threads (`teardown_threads`). @@ -944,13 +940,6 @@ fn wait_for_queue(watch: &Watch, queue: usize) { pending.failed.get_or_insert(error); } } - // A front that ran long marks its command queue long, before any turn finishes it, so - // before that queue makes its next command buffer. - if long { - if let Some(batch) = (pending.queues[queue].iter()).find(|b| b.value >= front.value) { - batch.buffer.queue.went_long(); - } - } // This waiter finishes what it saw, where no turn is under way; the one under way takes // it at its next look, which takes this lock. A drain waits for the wait to end. let turn = !pending.turning && due(&pending, queue); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 0890aedb9..1e5d7a9eb 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -4302,7 +4302,9 @@ impl CommandBufferShared { /// timestamps takes its times here: encoder-less, where its queue reached it; answered from /// the host, its kernel end (or its queue's latest end) and its completion. Every one moves /// its queue's latest GPU end: its own, or its completion where it has none (an upper bound - /// of its GPU end). + /// of its GPU end). One whose timestamps say its GPU work ran for over + /// `queue_share::LONG_HEAD` marks its queue long, before the turn finishes it + /// (`queue_share.rs`). pub(super) fn place_gpu_times(&self) { let shared = self.device.shared(); let mut state = lock(&self.state); @@ -4343,6 +4345,16 @@ impl CommandBufferShared { } } }); + let long = match (state.times.stamped, shared.timing.clock()) { + (Stamped::Read(Some((start, end))), Some(clock)) => { + clock.duration(start, end) > crate::queue_share::LONG_HEAD + } + _ => false, + }; + drop(state); + if long { + self.queue.went_long(); + } } /// The scheduler submitted the last batch, or held it in a group (`group.rs`): in the queue's diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 99a4b5eb2..da6de31b1 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1809,9 +1809,8 @@ degradations! { QueueSharing = "queue-sharing", Performance, "its command buffers run in one `VkQueue`'s order with those of the command queues \ that share it, where Metal's queues wait for each other only inside one command: \ - the first command buffer of each such queue that runs as its `VkQueue`'s oldest for \ - over 2 ms holds the command buffers the others committed behind it for its whole \ - length, and its later ones while its queue holds work, until that queue moves at \ + the first command buffer of each such queue whose GPU work runs over 2 ms holds \ + the command buffers the others committed behind it for its whole length, and its later ones while its queue holds work, until that queue moves at \ its next idle point; a command buffer's GPU start time includes the other queues' \ work before it; QueueSharingPolicy::PerQueue keeps each command queue on the \ `VkQueue` it took at its creation"; diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs index bfdc204f4..554fdceb7 100644 --- a/crates/metal2vulkan-runtime/src/queue.rs +++ b/crates/metal2vulkan-runtime/src/queue.rs @@ -28,10 +28,10 @@ //! Past them, and on a device whose families have one queue each (MoltenVK's four, RADV's and //! lavapipe's single graphics queue), queues share and the waiting stands; each queue that takes a //! `VkQueue` another took is counted (`WorkCounts::queues_sharing_a_vk_queue`). Where queues move, -//! they share by choice, to spare the GPU's idling at each switch, and a queue whose command -//! buffer ran over 2 ms as its `VkQueue`'s oldest is long: it holds the queues that shared with it -//! through that command buffer and while it holds work, then moves to a `VkQueue` of its own at -//! its next idle point, and no queue joins it (`queue-sharing`, `queue_share.rs`). +//! they share by choice, to spare the GPU's idling at each switch, and a queue whose command buffer +//! ran on the GPU for over 2 ms, by its own timestamps, is long: it holds the queues that shared +//! with it through that command buffer and while it holds work, then moves to a `VkQueue` of its +//! own at its next idle point, and no queue joins it (`queue-sharing`, `queue_share.rs`). //! //! **Isolation.** A queue made with `Device::new_command_queue_unshared` never moves, and no queue //! joins its `VkQueue`: where the device shares, it takes a `VkQueue` no command queue holds where @@ -560,19 +560,21 @@ impl CommandQueue { joined } - /// One of the queue's command buffers ran as its `VkQueue`'s oldest in flight for over - /// `queue_share::LONG_HEAD`: a round robin's queue is long from now on, counted once on its - /// `VkQueue` (`WorkCounts::queues_gone_long`). Called by the waiter that saw it complete, - /// under the completion's lock, while the command buffer holds its slot, so the queue moves - /// meanwhile no more than it holds another `VkQueue` (`command_buffer/completion.rs`). + /// One of the queue's command buffers ran on the GPU for over `queue_share::LONG_HEAD`, by + /// its own timestamps: where the device shares, a round robin's queue is long from now on, + /// counted once on its `VkQueue` (`WorkCounts::queues_gone_long`). Called by the completion + /// turn that read them, before it finishes the command buffer, which holds its slot until + /// then, so the queue moves meanwhile no more than it holds another `VkQueue` + /// (`CommandBufferShared::place_gpu_times`). pub(super) fn went_long(&self) { let queue = &self.0; + let shared = queue.device.shared(); if queue.kind != Kind::RoundRobin + || !shared.queue_switch.shares() || queue.sharing.fetch_or(LONG, Ordering::AcqRel) & LONG != 0 { return; } - let shared = queue.device.shared(); let vk_queue = queue.vk_queue.load(Ordering::Acquire); shared.queues[vk_queue].share.went_long(); shared.counts.queue_went_long(); @@ -612,6 +614,15 @@ impl CommandQueue { self.0.vk_queue.load(Ordering::Acquire) } + /// No Metal counterpart, for the lanes that watch command queues share `VkQueue`s + /// (`queue_share.rs`): the index of the device's `VkQueue` the queue submits to now, and + /// whether it is long. + #[doc(hidden)] + pub fn vk_queue_sharing(&self) -> (usize, bool) { + let long = self.0.sharing.load(Ordering::Acquire) & LONG != 0; + (self.vk_queue(), long) + } + /// The backings of memoryless attachments the queue keeps for its passes /// (`attachment_stand_in::pooled_backing`). pub(super) fn memoryless_backings(&self) -> &Mutex { diff --git a/crates/metal2vulkan-runtime/src/queue_share.rs b/crates/metal2vulkan-runtime/src/queue_share.rs index 6dea59414..8a1628784 100644 --- a/crates/metal2vulkan-runtime/src/queue_share.rs +++ b/crates/metal2vulkan-runtime/src/queue_share.rs @@ -31,10 +31,19 @@ //! the one with the most batches in flight, then the latest submission; else it stays, unless a //! long or unshared queue holds its own `VkQueue`; then the most recently used idle one; else it //! stays. -//! - **Long queues.** A batch that ran as its `VkQueue`'s oldest in flight for over [`LONG_HEAD`] -//! marks its command queue long, from the waiter that saw it complete, under the completion's -//! lock, before the turn that finishes it, so before the queue's next command buffer is made -//! (`command_buffer/completion.rs`). A long queue moves once more, at its next such make: to an +//! - **Long queues.** A command buffer whose GPU work ran for over [`LONG_HEAD`], by its own +//! timestamps (its first batch's start to its last's end), marks its command queue long, in the +//! completion turn that read them, before the turn finishes it, so before the queue's next +//! command buffer is made (`CommandBufferShared::place_gpu_times`). Its own GPU time, not the +//! host's view of how long it ran as its `VkQueue`'s oldest: that view also holds its wait for +//! the GPU to start it and the waiter's lateness to see it complete, which marked a queue of +//! one-draw command buffers long on the RTX 5080 Laptop GPU beside another process's 30 ms ones +//! (draws of 11 and 16 us of GPU time seen 2.0 and 2.3 ms after they became their `VkQueue`'s +//! oldest, 1.8 and 2.1 ms of it before they started). A device whose command buffers write no +//! timestamps the host can read +//! (`gpu_times_from_host`, a driver whose timestamps wait for every queue's, or no calibrated +//! timestamps) does not share ([`Verdict::Unchecked`], +//! `WorkCounts::queue_sharing_untimed`). A long queue moves once more, at its next such make: to an //! idle `VkQueue` of its family that no long or unshared queue holds, the one used least //! recently, else it stays; then never again. So the first long command buffer of a queue that //! shared holds the command buffers the queues sharing its `VkQueue` committed behind it for its @@ -63,14 +72,16 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, AtomicUsize, use std::sync::{Condvar, Mutex}; use std::time::{Duration, Instant}; -/// A batch that ran as its `VkQueue`'s oldest in flight for longer than this, in nanoseconds, -/// marks its command queue long: 2 ms. Measured against 10 ms on the RTX 5080 Laptop GPU, beside -/// an application queue of 30 ms command buffers: both mark that queue at its first one, but only -/// 2 ms also marks a queue of 2 to 10 ms command buffers, which at 10 ms the queues sharing with it -/// would stall behind again and again (the compositor's p99 4.81 ms against 24.0 ms where the long -/// queue stays home, 2.15 against 3.48 ms where it moves). The cost: a queue whose short command -/// buffers the GPU slices behind another `VkQueue`'s work for over 2 ms (measured in 3 of 7 runs, -/// at 2 to 6 ms) is marked long too, which only stops it sharing. +/// A command buffer whose GPU work ran for longer than this, in nanoseconds, by its own +/// timestamps, marks its command queue long: 2 ms. Measured against 10 ms on the RTX 5080 Laptop +/// GPU (each batch timed by its host-seen age as its `VkQueue`'s oldest), beside an application +/// queue of 30 ms command buffers: both mark that queue at its first +/// one, but only 2 ms also marks a queue of 2 to 10 ms command buffers, which at 10 ms the queues +/// sharing with it would stall behind again and again (the compositor's p99 4.81 ms against +/// 24.0 ms where the long queue stays home, 2.15 against 3.48 ms where it moves). A command buffer +/// the GPU runs in slices between other work counts those slices too, which only stops its queue +/// sharing: one-draw command buffers beside another process's 30 ms ones spanned up to 1.52 ms +/// there. pub(crate) const LONG_HEAD: u64 = 2_000_000; /// A busy `VkQueue` is joined only while its oldest batch in flight has run less than this, in @@ -282,8 +293,10 @@ pub(crate) enum Verdict { /// It does not. DoesNotIdle, /// No measurement: the device has no two `VkQueue`s of its primary family in the round - /// robin, writes no timestamps there or calibrates none (timestamps of two `VkQueue`s compare - /// only on a calibrated device), its policy is `PerQueue`, or a run failed. + /// robin, writes no timestamps there, calibrates none (timestamps of two `VkQueue`s compare + /// only on a calibrated device) or answers GPU times from the host + /// ([`queue_switch_check::timed`](crate::queue_switch_check::timed)), its policy is + /// `PerQueue`, or a run failed. Unchecked, } @@ -464,41 +477,7 @@ pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<(Verdict matches!(verdict, Verdict::Idles | Verdict::DoesNotIdle).then_some((verdict, cost)) } -/// What a `VkQueue`'s waiter reads before its wait for the queue's oldest batch in flight, where -/// the device shares `VkQueue`s ([`Device::head_watch`]). -#[derive(Clone, Copy, Debug)] -pub(crate) struct HeadWatch { - /// The value the host saw the queue's timeline reach. - completed: u64, - /// When the batch became the queue's oldest. - since: u64, -} - -impl HeadWatch { - /// Whether the batch, seen complete as the wait's value moved to `value`, ran as its queue's - /// oldest for over [`LONG_HEAD`]. A value that did not move says nothing of the batch. - pub(crate) fn ran_long(&self, value: u64) -> bool { - value > self.completed - && crate::gpu_time::host_nanos().saturating_sub(self.since) > LONG_HEAD - } -} - impl Device { - /// For `VkQueue` `queue`'s waiter, where the device shares `VkQueue`s and the queue is the - /// round robin's: what it reads before its wait ([`HeadWatch`]); `None` elsewhere, or where - /// the queue's oldest batch became its oldest before the device shared. - pub(crate) fn head_watch(&self, queue: usize) -> Option { - let shared = self.shared(); - if !self.shares_queues() || queue >= shared.round_robin() { - return None; - } - let slot = &shared.queues[queue]; - Some(HeadWatch { - completed: slot.completed_value(), - since: slot.share.head_since()?, - }) - } - /// Whether the device shares `VkQueue`s now ([`QueueSwitch::shares`]). pub(crate) fn shares_queues(&self) -> bool { self.shared().queue_switch.shares() @@ -615,7 +594,8 @@ impl Device { /// As the device is made: its verdict where the check cannot measure (`Unchecked`, below) or /// a record holds it (settled, the round robin's `VkQueue`s then watched where it shares); /// else it waits for the check, which the first command queue of the round robin starts. A - /// record that does not decode is no record. + /// record that does not decode is no record. A device with two `VkQueue`s to share whose + /// command buffers write no timestamps it reads is counted (`WorkCounts::queue_sharing_untimed`). pub(crate) fn recall_queue_switch_check(&self) { let shared = self.shared(); let switch = &shared.queue_switch; @@ -623,6 +603,11 @@ impl Device { switch.settle(Verdict::Unchecked, 0, None); return; } + if !crate::queue_switch_check::timed(self) { + shared.counts.queue_sharing_untimed(); + switch.settle(Verdict::Unchecked, 0, None); + return; + } let identity = self.driver_identity(); let name = record_name(&identity); let looked = (shared.shader_cache.content_store()) @@ -654,6 +639,14 @@ impl Device { self.shared().queue_switch.wait(timeout) } + /// No Metal counterpart: whether the device shares `VkQueue`s now, its policy `Adaptive` and + /// its check's verdict `Idles` (the module docs). A runtime extension for the lanes that + /// assert a queue joined another's `VkQueue` where the device shares. + #[doc(hidden)] + pub fn shares_vk_queues(&self) -> bool { + self.shares_queues() + } + /// The device's check's verdict, the switch cost it measured, how long it ran in this process /// (where it ran), and whether the device shares `VkQueue`s now, in words. A runtime extension /// for the lanes and benchmarks that report it. diff --git a/crates/metal2vulkan-runtime/src/queue_switch_check.rs b/crates/metal2vulkan-runtime/src/queue_switch_check.rs index 66ac6202c..0fae6ee68 100644 --- a/crates/metal2vulkan-runtime/src/queue_switch_check.rs +++ b/crates/metal2vulkan-runtime/src/queue_switch_check.rs @@ -58,16 +58,26 @@ const WAIT_SLICE: Duration = Duration::from_millis(100); const FEWEST: usize = ROUNDS / 2; /// The two `VkQueue`s the check measures, by index among the device's: the first two the round -/// robin lends of the primary family, where the device calibrates its timestamps and that family -/// writes them; `None` elsewhere. +/// robin lends of the primary family; `None` where it lends fewer. pub(crate) fn pair(device: &Device) -> Option<(usize, usize)> { let shared = device.shared(); - shared.timing.clock()?.calibration?; let mut same = (0..shared.round_robin()) .filter(|&index| shared.queues[index].family == shared.queue_family); Some((same.next()?, same.next()?)) } +/// Whether the device's command buffers write timestamps the host reads, and it calibrates them: +/// the check compares two `VkQueue`s' timestamps, and a queue is known long only by its command +/// buffers' own (`queue_share.rs`). Not where it answers GPU times from the host +/// (`gpu_times_from_host`, or a driver whose timestamps wait for every queue's). +pub(crate) fn timed(device: &Device) -> bool { + let timing = &device.shared().timing; + !timing.answers_from_host() + && timing + .clock() + .is_some_and(|clock| clock.calibration.is_some()) +} + /// Start the check on a thread of its own: whether it started. pub(crate) fn start(device: &Device) -> bool { let weak = device.downgrade(); @@ -81,7 +91,7 @@ fn run(weak: crate::device::WeakDevice) { let Some(device) = weak.upgrade() else { return; }; - let Some(pair) = pair(&device) else { + let Some(pair) = pair(&device).filter(|_| timed(&device)) else { device.settle_queue_switch(Verdict::Unchecked, 0, None); return; }; diff --git a/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs b/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs index a7632f6e2..0a7acae13 100644 --- a/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/queue_share_device.rs @@ -13,6 +13,9 @@ //! `VkQueue` read, `joins_withheld_from_unshared` above 0 where the device shares), a queue //! placed on one leaves it at its next idle point (`queue_moves_off_unshared`), and under //! `PerQueue` an unshared queue takes the round robin's next `VkQueue`, as any queue does. +//! - **Untimed devices.** A device that answers GPU times from the host (`gpu_times_from_host`) +//! does not share, and counts it (`queue_sharing_untimed`) where it has two `VkQueue`s of one +//! family to share: a queue is known long only by its command buffers' timestamps. //! - **Isolation.** A compositor's small command buffers, committed at 4,800 a second and never //! waited for, beside an application's command buffers of about 30 ms each: once the //! application's queue went long, the compositor's 99th percentile over 2 s stays under 5 ms @@ -45,9 +48,8 @@ const SETTLING: Duration = Duration::from_millis(50); /// The bytes one fill of a long command buffer writes. const FILL_BYTES: u64 = 64 << 20; -/// The device the cfg selects under `queue_sharing`, its shader cache in `cache`, its check -/// settled. -fn device(cache: &Scratch, queue_sharing: QueueSharingPolicy) -> Device { +/// The options of the device the cfg selects under `queue_sharing`, its shader cache in `cache`. +fn options(cache: &Scratch, queue_sharing: QueueSharingPolicy) -> DeviceOptions { let mut options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], @@ -65,7 +67,12 @@ fn device(cache: &Scratch, queue_sharing: QueueSharingPolicy) -> Device { }; options.policy = DevicePolicy::UNTRUSTED; options.policy.queue_sharing = queue_sharing; - let device = Device::system_default_with(&options).unwrap(); + options +} + +/// That device, its check settled. +fn device(cache: &Scratch, queue_sharing: QueueSharingPolicy) -> Device { + let device = Device::system_default_with(&options(cache, queue_sharing)).unwrap(); assert!(device.settle_queue_switch_check(WAIT), "the check settles"); println!("{queue_sharing:?}: {}", device.queue_switch_check_report()); device @@ -81,6 +88,7 @@ fn each_policy(leg: &str, test: impl Fn(&Device, bool)) { !shares || policy == QueueSharingPolicy::Adaptive, "no device shares under PerQueue" ); + assert_eq!(device.work_counts().queue_sharing_untimed, 0, "{policy:?}"); test(&device, shares); if !shares { assert_eq!(device.work_counts().queue_moves, 0, "{policy:?}"); @@ -342,6 +350,9 @@ fn under_per_queue_an_unshared_queue_takes_the_round_robin_s_next_vk_queue() { /// What one isolation run measured: the compositor's latencies in milliseconds. struct Isolation { latencies: Vec, + /// Each queue's changes of `VkQueue` or long mark (`CommandQueue::vk_queue_sharing`) over the + /// run, in words. + moves: String, } impl Isolation { @@ -395,14 +406,18 @@ fn isolation( let fills = long_fills(&app, &big); let small = device.new_buffer(4096, ResourceOptions::private()).unwrap(); let stop = Arc::new(AtomicBool::new(false)); + let began = Instant::now(); let application = { let stop = Arc::clone(&stop); std::thread::spawn(move || { + let mut seen = Seen::default(); while !stop.load(Ordering::Relaxed) { let command_buffer = long(&app, &big, fills); + seen.note(&app, began); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); } + seen.0 }) }; let latencies = Arc::new(Mutex::new(Vec::new())); @@ -417,8 +432,10 @@ fn isolation( let period = Duration::from_secs_f64(1.0 / 4800.0); let mut next = Instant::now(); let mut last = None; + let mut seen = Seen::default(); while !stop.load(Ordering::Relaxed) { let command_buffer = compositor.command_buffer().unwrap(); + seen.note(&compositor, began); let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.fill_buffer(&small, 0..256, 3).unwrap(); blit.end_encoding().unwrap(); @@ -444,10 +461,11 @@ fn isolation( if let Some(last) = last { last.wait_until_completed_for(WAIT).unwrap(); } + seen.0 }) }; - let began = Instant::now(); - while !ready(device) && began.elapsed() < WAIT { + let waiting = Instant::now(); + while !ready(device) && waiting.elapsed() < WAIT { std::thread::sleep(Duration::from_millis(5)); } assert!(ready(device), "the run did not reach its measured part"); @@ -456,15 +474,65 @@ fn isolation( std::thread::sleep(Duration::from_secs(2)); recording.store(false, Ordering::Relaxed); stop.store(true, Ordering::Relaxed); - composing.join().unwrap(); - application.join().unwrap(); + let counts = device.work_counts(); + let moves = format!( + "compositor {}; application {}; moves {} joins {} gone long {} settles {}", + composing.join().unwrap(), + application.join().unwrap(), + counts.queue_moves, + counts.queue_joins, + counts.queues_gone_long, + counts.long_queue_settles + ); let latencies = latencies.lock().unwrap().clone(); assert!( latencies.len() > 1000, "{} compositor samples", latencies.len() ); - Isolation { latencies } + Isolation { latencies, moves } +} + +/// A queue's changes of `VkQueue` or long mark, each at its command buffer's count and the +/// milliseconds into the run, in words. +#[derive(Default)] +struct Seen(String, u64, Option<(usize, bool)>); + +impl Seen { + fn note(&mut self, queue: &CommandQueue, began: Instant) { + let now = queue.vk_queue_sharing(); + if self.2 != Some(now) { + let long = if now.1 { " long" } else { "" }; + let at = began.elapsed().as_secs_f64() * 1e3; + self.0 += &format!("#{} {at:.1} ms VkQueue {}{long}, ", self.1, now.0); + self.2 = Some(now); + } + self.1 += 1; + } +} + +#[test] +fn a_device_that_answers_gpu_times_from_the_host_does_not_share_and_counts_it() { + let scratch = Scratch::new("queue-share-untimed"); + let mut options = options(&scratch, QueueSharingPolicy::Adaptive); + options.gpu_times_from_host = true; + let device = Device::system_default_with(&options).unwrap(); + assert!(device.settle_queue_switch_check(WAIT), "the check settles"); + let counts = device.work_counts(); + let could = crate::queue_switch_check::pair(&device).is_some(); + println!( + "{}; could share: {could}", + device.queue_switch_check_report() + ); + assert!(!device.shares_queues()); + assert_eq!(counts.queue_sharing_untimed, u64::from(could)); + assert_eq!(counts.queue_switch_checks_run, 0); + let queue = device.new_command_queue().unwrap(); + let target = device + .new_buffer(1 << 20, ResourceOptions::private()) + .unwrap(); + wait_all(burst(&queue, &target, 8)); + assert_eq!(device.work_counts().queue_moves, 0); } #[test] @@ -477,11 +545,11 @@ fn a_compositor_beside_a_long_queue_keeps_its_latency_once_that_queue_went_long( let ready = |device: &Device| device.work_counts().queues_gone_long >= 1; let run = isolation(device, compositor, ready); println!( - "p99 {:.2} ms, {} stalls of {} samples; {:?}", + "p99 {:.2} ms, {} stalls of {} samples; {}", run.p99(), run.stalls(), run.latencies.len(), - device.work_counts().queues_gone_long + run.moves ); assert!(run.p99() < 5.0, "p99 {:.2} ms", run.p99()); assert!(run.stalls() <= 1, "{} stalls", run.stalls()); @@ -497,10 +565,11 @@ fn an_unshared_compositor_beside_a_long_queue_never_stalls() { let compositor = device.new_command_queue_unshared(64).unwrap(); let run = isolation(device, compositor, |_| true); println!( - "p99 {:.2} ms, {} stalls of {} samples", + "p99 {:.2} ms, {} stalls of {} samples; {}", run.p99(), run.stalls(), - run.latencies.len() + run.latencies.len(), + run.moves ); assert!(run.p99() < 5.0, "p99 {:.2} ms", run.p99()); assert_eq!(run.stalls(), 0, "the unshared compositor stalled"); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 12b6e57f3..dbbda1978 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -207,6 +207,7 @@ pub(crate) struct Counters { joins_withheld_from_unshared: AtomicU64, queue_switch_checks_run: AtomicU64, queue_switch_checks_recalled: AtomicU64, + queue_sharing_untimed: AtomicU64, slot_wait_nanos: AtomicU64, completed_waits: AtomicU64, event_waits_met: AtomicU64, @@ -1567,6 +1568,12 @@ impl Counters { (self.queue_switch_checks_recalled).fetch_add(1, Ordering::Relaxed); } + /// A device that could share `VkQueue`s does not: its command buffers write no timestamps it + /// reads (`queue_switch_check::timed`). + pub(crate) fn queue_sharing_untimed(&self) { + (self.queue_sharing_untimed).fetch_add(1, Ordering::Relaxed); + } + /// A batch with work was submitted waiting for `waits` timelines at values the host saw them /// reach (`command_buffer/submit.rs`). pub(crate) fn completed_waited(&self, waits: usize) { @@ -4079,8 +4086,8 @@ pub struct WorkCounts { pub queue_moves: u64, /// Of `queue_moves`, those onto a `VkQueue` with another command queue's work in flight. pub queue_joins: u64, - /// Command queues marked long: one of their command buffers ran as its `VkQueue`'s oldest in - /// flight for over 2 ms, so no queue joins their `VkQueue` from then on. + /// Command queues marked long: one of their command buffers ran on the GPU for over 2 ms, by + /// its own timestamps, so no queue joins their `VkQueue` from then on. pub queues_gone_long: u64, /// Long command queues that settled, at their next idle point: on an idle `VkQueue` no long or /// unshared queue holds (a move, counted in `queue_moves` too), or where they were. @@ -4097,6 +4104,11 @@ pub struct WorkCounts { /// Devices whose verdict of that check was read from the record of an earlier one of the same /// driver, device and runtime: no check ran for them. pub queue_switch_checks_recalled: u64, + /// Devices of `QueueSharingPolicy::Adaptive` with two `VkQueue`s of one family to share that + /// do not share, because their command buffers write no calibrated GPU timestamps the host + /// reads (`gpu_times_from_host`, a driver whose timestamps wait for every queue's, or none): + /// a queue is known long only by its command buffers' own GPU time. No check ran for them. + pub queue_sharing_untimed: u64, /// The waits batches with work made for timelines at values the host had seen them reach, /// which make what completed work wrote visible to them: one per timeline whose completed /// value moved since a batch of the same `VkQueue` last waited for it. @@ -5755,6 +5767,7 @@ impl Device { queue_switch_checks_recalled: counters .queue_switch_checks_recalled .load(Ordering::Relaxed), + queue_sharing_untimed: counters.queue_sharing_untimed.load(Ordering::Relaxed), completed_waits: counters.completed_waits.load(Ordering::Relaxed), event_waits_met: counters.event_waits_met.load(Ordering::Relaxed), shared_event_waits_held: counters.shared_event_waits_held.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/command_queues.rs b/crates/metal2vulkan-validation/src/runtime_lane/command_queues.rs index ee0cc3cec..2c6453973 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/command_queues.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/command_queues.rs @@ -12,8 +12,11 @@ //! [`WAIT`]. use super::host_memory::Mapping; -use super::{layer_reported_nothing_at_all, validated_device, Messages, ScratchCache}; +use super::{ + layer_reported_nothing_at_all, validated_device, validated_device_with, Messages, ScratchCache, +}; use crate::gpu::TEST_DEVICE; +use metal2vulkan::device::QueueSharingPolicy; use metal2vulkan_runtime::{ BufferContents, BufferDescriptor, CommandBuffer, CommandQueue, DeadlockCause, Deallocator, Degradation, Device, Error, EventRef, HostMemory, Invalid, KeepAlive, Problem, ResourceOptions, @@ -442,18 +445,30 @@ pub(super) const QUEUE_SHARING: [Degradation; 1] = [Degradation::QueueSharing]; /// A command queue that makes a command buffer while it holds no other uncompleted one, beside a /// queue whose short command buffers keep its `VkQueue` busy, joins that `VkQueue` where the device -/// shares (`QueueSharingPolicy::Adaptive` on a device whose check finds its GPU idle between -/// `VkQueue`s: NVIDIA's), and the device announces `queue-sharing` once however many queues join: -/// each notice a join (`WorkCounts::queue_joins`), never one without. On a device that shares no -/// `VkQueue` (lavapipe, RADV, MoltenVK) nothing joins and nothing is announced. +/// shares (`QueueSharingPolicy::Adaptive`, set here over the lane's `exact_answers()`, on a device +/// whose check finds its GPU idle between `VkQueue`s: NVIDIA's), and the device announces +/// `queue-sharing` once however many queues join: each notice a join (`WorkCounts::queue_joins`, +/// above 0 where the device shares), never one without. On a device that shares no `VkQueue` +/// (lavapipe, RADV, MoltenVK) nothing joins and nothing is announced, and the test says why. #[test] fn a_queue_joining_another_s_busy_vk_queue_is_announced_once() { use metal2vulkan_runtime::ResourceOptions; let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); { - let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.policy.queue_sharing = QueueSharingPolicy::Adaptive; + }) + .unwrap(); assert!(device.settle_queue_switch_check(WAIT), "the check settles"); + let shares = device.shares_vk_queues(); + if !shares { + println!( + "{} shares no VkQueue, so no queue joins: {}", + device.name(), + device.queue_switch_check_report() + ); + } let sharing_kinds = || -> usize { messages .take_notices() @@ -462,13 +477,15 @@ fn a_queue_joining_another_s_busy_vk_queue_is_announced_once() { .filter(|notice| QUEUE_SHARING.contains(¬ice.degradation)) .count() }; + // 16 MiB a fill: tens of microseconds each on the RTX 5080 Laptop GPU, so the busy queue's + // oldest batch is young when a joiner looks and no command buffer runs long. let buffer = device - .new_buffer(1 << 20, ResourceOptions::private()) + .new_buffer(16 << 20, ResourceOptions::private()) .unwrap(); let fill = |queue: &CommandQueue| { let command_buffer = queue.command_buffer().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(&buffer, 0..(1 << 20), 0x5a).unwrap(); + blit.fill_buffer(&buffer, 0..(16 << 20), 0x5a).unwrap(); blit.end_encoding().unwrap(); command_buffer.commit().unwrap(); command_buffer @@ -479,6 +496,8 @@ fn a_queue_joining_another_s_busy_vk_queue_is_announced_once() { .collect(); for joiner in &joiners { let kept: Vec = (0..24).map(|_| fill(&busy)).collect(); + // Submitted, so the busy `VkQueue` has work in flight as the joiner makes its own. + kept.last().unwrap().wait_until_scheduled().unwrap(); let joined = fill(joiner); joined.wait_until_completed_for(WAIT).unwrap(); for command_buffer in kept { @@ -486,6 +505,11 @@ fn a_queue_joining_another_s_busy_vk_queue_is_announced_once() { } } let joins = device.work_counts().queue_joins; + assert_eq!( + joins > 0, + shares, + "{joins} joins where the device shares: {shares}" + ); assert_eq!( sharing_kinds(), usize::from(joins > 0), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs b/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs index 69a22645e..481d0cca9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/cross_queue_shadows.rs @@ -29,6 +29,14 @@ //! log. Command buffer Z of queue 1, committed after X, reads it: the tracker runs it after Y's //! fill, and its read holds the fill, though the fill was reported to the log at Y's commit, //! before X's hold. +//! - **Both on one `VkQueue`.** The signal in between and the waiting writer again, with no spin +//! and on a device made under `QueueSharingPolicy::Adaptive` (over the lane's `exact_answers()`) +//! whose check has answered: queue 2 makes Y while queue 1 keeps short command buffers in +//! flight, so where the device shares it joins queue 1's `VkQueue` (`queue_share.rs`), and X and +//! Z run there beside Y, none long. Y is held until X's signal was submitted, so it goes after +//! X's first batch on that `VkQueue`: the read after the signal holds Y's fill, X's hold is +//! still withheld while Y has not completed, and Z's read holds the fill. Where the device +//! shares no `VkQueue` the cases run on two and say so. //! //! The spin is the owned fixture `kernel_spin_on_an_unraised_word`, dispatched again and again to //! a cap of loads timed on the device beforehand ([`Spin`]). The GPU does not see a CPU store to @@ -48,12 +56,13 @@ use super::{ }; use crate::air_library::AirLibrary as _; use crate::gpu::TEST_DEVICE; +use metal2vulkan::device::QueueSharingPolicy; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan_devtools::llvm_assemble; use metal2vulkan_runtime::{ - Buffer, CommandBuffer, CommandBufferStatus, ComputeCommandEncoder, ComputePipelineState, - Device, EventRef, HostMemory, PipelineOptions, ResourceOptions, Size, Texture, - TextureDescriptor, + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, + ComputePipelineState, Device, DeviceOptions, EventRef, HostMemory, PipelineOptions, + ResourceOptions, Size, Texture, TextureDescriptor, }; use std::path::Path; use std::sync::Arc; @@ -207,7 +216,18 @@ fn fill_row(command_buffer: &CommandBuffer, truth: &Buffer, row: u64, value: u8) /// A device under the validation layer, its texel kernels, each run once so that no later dispatch /// of them waits at a host step for its `VkPipeline`, and the spin. fn lane(messages: &Messages, cache: &ScratchCache) -> (Device, TexelKernels, Spin) { - let device = validated_device_with(TEST_DEVICE, messages, cache.path(), |_| {}).unwrap(); + let (device, kernels) = lane_device(messages, cache, |_| {}); + let spin = Spin::new(&device); + (device, kernels, spin) +} + +/// [`lane`]'s device, with `adjust`'s options, and its texel kernels, each run once. +fn lane_device( + messages: &Messages, + cache: &ScratchCache, + adjust: impl FnOnce(&mut DeviceOptions), +) -> (Device, TexelKernels) { + let device = validated_device_with(TEST_DEVICE, messages, cache.path(), adjust).unwrap(); let kernels = texel_kernels(&device); let scratch = buffer_with(&device, &vec![0; BYTES as usize]).unwrap(); let texture = shadowed(&device, &scratch); @@ -221,8 +241,190 @@ fn lane(messages: &Messages, cache: &ScratchCache) -> (Device, TexelKernels, Spi texel_dispatch(&warm, &kernels.read, &texture, &words); warm.commit().unwrap(); completed(&warm); - let spin = Spin::new(&device); - (device, kernels, spin) + (device, kernels) +} + +/// [`lane_device`] under `QueueSharingPolicy::Adaptive`, its check answered: whether it shares +/// `VkQueue`s, said where it does not. +fn sharing_lane(messages: &Messages, cache: &ScratchCache) -> (Device, TexelKernels, bool) { + let (device, kernels) = lane_device(messages, cache, |options| { + options.policy.queue_sharing = QueueSharingPolicy::Adaptive; + }); + assert!( + device.settle_queue_switch_check(Duration::from_secs(20)), + "the check settles" + ); + let shares = device.shares_vk_queues(); + if !shares { + println!( + "{} shares no VkQueue, so the one-VkQueue cases run on two: {}", + device.name(), + device.queue_switch_check_report() + ); + } + (device, kernels, shares) +} + +/// Keep `busy`'s `VkQueue` busy with short fills of `scratch`, then make `joiner`'s command buffer, +/// which joins that `VkQueue` where the device shares (the module docs): the command buffer, and +/// the fills, to be waited for once the case ran. Where it shares, both queues are on one +/// `VkQueue` and neither is long. +fn joined( + device: &Device, + busy: &CommandQueue, + joiner: &CommandQueue, + shares: bool, +) -> (CommandBuffer, Vec) { + let scratch = device + .new_buffer(16 << 20, ResourceOptions::private()) + .unwrap(); + let fills: Vec = (0..24) + .map(|_| { + let command_buffer = busy.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&scratch, 0..(16 << 20), 0x77).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer + }) + .collect(); + fills.last().unwrap().wait_until_scheduled().unwrap(); + let joins = device.work_counts().queue_joins; + let made = joiner.command_buffer().unwrap(); + let (on, with) = (joiner.vk_queue_sharing(), busy.vk_queue_sharing()); + if shares { + assert!(device.work_counts().queue_joins > joins, "the queue joined"); + assert_eq!(on, with, "both queues on one VkQueue, neither long"); + assert!(!on.1, "neither queue is long"); + } + (made, fills) +} + +/// [`an_encoder_after_a_signal_reads_what_another_queue_wrote_after_it`] with the two queues on +/// one `VkQueue` where the device shares (the module docs). +#[test] +fn an_encoder_after_a_signal_reads_another_queue_s_write_on_one_vk_queue() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let (device, kernels, shares) = sharing_lane(&messages, &cache); + let (first, second) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let initial = Rng(0x5162).bytes(BYTES); + let (row, value) = (6, 0x4d); + let truth = buffer_with(&device, &initial).unwrap(); + let texture = shadowed(&device, &truth); + let event = device.new_event().unwrap(); + let reads = [(); 2].map(|_| read_target(&device)); + let (y, fills) = joined(&device, &first, &second, shares); + y.encode_wait_for_event(EventRef::Event(&event), 1).unwrap(); + fill_row(&y, &truth, row, value); + y.commit().unwrap(); + let x = first.command_buffer().unwrap(); + texel_dispatch(&x, &kernels.read, &texture, &reads[0]); + x.encode_signal_event(EventRef::Event(&event), 1).unwrap(); + texel_dispatch(&x, &kernels.read, &texture, &reads[1]); + x.commit().unwrap(); + for command_buffer in fills.iter().chain([&x, &y]) { + completed(command_buffer); + } + println!( + "ONE-VKQUEUE-SIGNAL on {}: sharing {shares}, X's queue {:?}, Y's {:?}", + device.name(), + first.vk_queue_sharing(), + second.vk_queue_sharing() + ); + let read = |at: usize| read_buffer(&reads[at], 0, 4 * WORDS).unwrap(); + assert_eq!( + read(0), + texels_of(&initial), + "the encoder before the signal" + ); + assert_eq!( + read(1), + texels_of(&filled(&initial, row, value)), + "the encoder after the signal, which Y's fill runs before" + ); + drop((texture, truth, first, second, kernels, event)); + drop(device); + layer_reported_nothing_at_all(&messages); +} + +/// [`a_write_of_logged_pages_after_an_event_wait_reaches_a_copy_in_behind_a_later_hold`] with no +/// spin and the two queues on one `VkQueue` where the device shares (the module docs). +#[test] +fn a_waiting_writer_s_hold_is_withheld_on_one_vk_queue() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let (device, kernels, shares) = sharing_lane(&messages, &cache); + let (first, second) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let mapping = Mapping::anonymous(GUEST_PAGE); + let initial = Rng(0x9A6F).bytes(BYTES); + mapping.write(0, &initial); + let log = Arc::new(GuestLog::default()); + log.told(0..BYTES); + // SAFETY: the mapping outlives the buffer, dropped first, and stays writable. + let memory = unsafe { HostMemory::new(mapping.pointer()) }.with_dirty_pages(Arc::clone(&log)); + // SAFETY: as above. + let pages = unsafe { + device.new_buffer_with_bytes_no_copy( + memory, + GUEST_PAGE as u64, + ResourceOptions::default(), + None, + ) + } + .unwrap(); + let texture = shadowed(&device, &pages); + let event = device.new_event().unwrap(); + let (row, value) = (2, 0x5b); + let reads = [(); 2].map(|_| read_target(&device)); + let before = gated(&device.work_counts()); + let withheld = device.work_counts().dirty_holds_withheld; + let (y, fills) = joined(&device, &first, &second, shares); + y.encode_wait_for_event(EventRef::Event(&event), 1).unwrap(); + fill_row(&y, &pages, row, value); + y.commit().unwrap(); + let x = first.command_buffer().unwrap(); + texel_dispatch(&x, &kernels.read, &texture, &reads[0]); + x.encode_signal_event(EventRef::Event(&event), 1).unwrap(); + x.commit().unwrap(); + let z = first.command_buffer().unwrap(); + texel_dispatch(&z, &kernels.read, &texture, &reads[1]); + z.commit().unwrap(); + for command_buffer in fills.iter().chain([&x, &y, &z]) { + completed(command_buffer); + } + let after = gated(&device.work_counts()); + let counts: [u64; 5] = std::array::from_fn(|i| after[i] - before[i]); + let withheld = device.work_counts().dirty_holds_withheld - withheld; + println!( + "ONE-VKQUEUE-HOLD on {}: sharing {shares}, X's queue {:?}, Y's {:?}, gated copies in \ + (gated, whole, skipped, bytes whole, bytes copied) {counts:?}, holds withheld {withheld}", + device.name(), + first.vk_queue_sharing(), + second.vk_queue_sharing() + ); + assert!(counts[0] > 0, "the copies in were gated"); + assert!( + withheld > 0, + "X's hold was withheld while Y, which waits, had not completed" + ); + let read = |at: usize| read_buffer(&reads[at], 0, 4 * WORDS).unwrap(); + assert_eq!(read(0), texels_of(&initial), "X's read, before the signal"); + assert_eq!( + read(1), + texels_of(&filled(&initial, row, value)), + "Z's read, after Y's fill" + ); + drop((texture, pages, first, second, kernels, event)); + drop(device); + drop(mapping); + layer_reported_nothing_at_all(&messages); } /// Another queue's encoder of the texture ends between a command buffer's two, and the CPU writes diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index b2b1f997e..b1226e09a 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -434,16 +434,18 @@ pub enum ExtendedRangeBlitPolicy { #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum QueueSharingPolicy { /// The default, on a device whose own check, run once per driver and release, finds the GPU - /// idle when consecutive work comes from another `VkQueue` of one family; elsewhere, and - /// before the check answered, as [`PerQueue`](Self::PerQueue). A command queue that makes a - /// command buffer while it holds no other uncompleted one takes the busiest `VkQueue` of its - /// family whose oldest batch has run under 0.5 ms, else stays. A queue one of whose batches - /// ran as its `VkQueue`'s oldest for over 2 ms is long from then on: at its next such point - /// it takes an idle `VkQueue` no long queue holds and stays there, and no queue moves onto a - /// long queue's `VkQueue`. So the first long command buffer of a queue that shared holds the - /// command buffers the queues sharing with it committed behind it, once per queue that goes - /// long. Announced `queue-sharing` at the first move onto a `VkQueue` with another queue's - /// work in flight. + /// idle when consecutive work comes from another `VkQueue` of one family; elsewhere, and before + /// the check answered, as [`PerQueue`](Self::PerQueue). A command queue that makes a command + /// buffer while it holds no other uncompleted one takes the busiest `VkQueue` of its family + /// whose oldest batch has run under 0.5 ms, else stays. A queue one of whose command buffers + /// ran on the GPU for over 2 ms, by its own timestamps, is long from then on: at its next such + /// point it takes an idle `VkQueue` no long queue holds and stays there, and no queue moves + /// onto a long queue's `VkQueue`. So the first long command buffer of a queue that shared holds + /// the command buffers the queues sharing with it committed behind it, once per queue that goes + /// long. Announced `queue-sharing` at the first move onto a `VkQueue` with another queue's work + /// in flight. A device whose command buffers write no GPU timestamps the host reads (the + /// runtime's `gpu_times_from_host`, or a driver whose timestamps wait for every queue's) does + /// not share, and the runtime counts it (`WorkCounts::queue_sharing_untimed`). #[default] Adaptive, /// Each command queue on the `VkQueue` it took at its creation, round robin, for its life: diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 1a768137d..9d1d71877 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2817,6 +2817,7 @@ field metal2vulkan-runtime::WorkCounts.queue_drains pub queue_drains: u64 field metal2vulkan-runtime::WorkCounts.queue_joins pub queue_joins: u64 field metal2vulkan-runtime::WorkCounts.queue_moves pub queue_moves: u64 field metal2vulkan-runtime::WorkCounts.queue_moves_off_unshared pub queue_moves_off_unshared: u64 +field metal2vulkan-runtime::WorkCounts.queue_sharing_untimed pub queue_sharing_untimed: u64 field metal2vulkan-runtime::WorkCounts.queue_submissions pub queue_submissions: u64 field metal2vulkan-runtime::WorkCounts.queue_switch_checks_recalled pub queue_switch_checks_recalled: u64 field metal2vulkan-runtime::WorkCounts.queue_switch_checks_run pub queue_switch_checks_run: u64 @@ -7675,6 +7676,7 @@ method metal2vulkan-runtime::CommandQueue::command_buffer pub fn command_buffer( method metal2vulkan-runtime::CommandQueue::device pub fn device(&self) -> &Device method metal2vulkan-runtime::CommandQueue::label pub fn label(&self) -> Option method metal2vulkan-runtime::CommandQueue::set_label pub fn set_label(&self, label: &str) +method metal2vulkan-runtime::CommandQueue::vk_queue_sharing pub fn vk_queue_sharing(&self) -> (usize, bool) method metal2vulkan-runtime::CommandQueue::with_vk_queue pub unsafe fn with_vk_queue(&self, f: impl FnOnce(vk::Queue, u32) -> R) -> R method metal2vulkan-runtime::CommitFailure::new pub fn new(code: u64) -> CommitFailure method metal2vulkan-runtime::ComputeCommandEncoder::dispatch_threadgroups pub fn dispatch_threadgroups(&mut self, groups: Size, threads: Size) -> Result<(), Error> @@ -7833,6 +7835,7 @@ method metal2vulkan-runtime::Device::settle_in_place_checks pub fn settle_in_pla method metal2vulkan-runtime::Device::settle_queue_switch_check pub fn settle_queue_switch_check(&self, timeout: Duration) -> bool method metal2vulkan-runtime::Device::shader_cache_directory pub fn shader_cache_directory(&self) -> &Path method metal2vulkan-runtime::Device::shader_cache_statistics pub fn shader_cache_statistics(&self) -> ShaderCacheStatistics +method metal2vulkan-runtime::Device::shares_vk_queues pub fn shares_vk_queues(&self) -> bool method metal2vulkan-runtime::Device::sparse_tile_size pub fn sparse_tile_size(&self, texture_type: TextureType, pixel_format: PixelFormat, sample_count: u64) -> Size method metal2vulkan-runtime::Device::sparse_tile_size_for_page pub fn sparse_tile_size_for_page(&self, _texture_type: TextureType, pixel_format: PixelFormat, sample_count: u64, page: SparsePageSize) -> Size method metal2vulkan-runtime::Device::sparse_tile_size_in_bytes pub fn sparse_tile_size_in_bytes(&self) -> u64 diff --git a/docs/API.md b/docs/API.md index 695ea740f..42b7a8f30 100644 --- a/docs/API.md +++ b/docs/API.md @@ -225,9 +225,9 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: on the RTX 5080 Laptop GPU idles about 50 us at each such switch), a command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, so short command buffers of several queues run - with no switch between them. A queue whose batch ran over 2 ms as its `VkQueue`'s oldest is - long: no queue joins its `VkQueue`, and it moves once more, at its next such make, to an idle - `VkQueue` of its own. So a queue waits behind another's long command buffer once per queue + with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, + by its own timestamps, is long: no queue joins its `VkQueue`, and it moves once more, at its next + such make, to an idle `VkQueue` of its own. So a queue waits behind another's long command buffer once per queue that goes long, about that command buffer's length: the first long command buffer of a queue that shared holds the command buffers committed behind it there for its whole length, announced `queue-sharing` at the device's first join (section 9). A queue made with @@ -237,7 +237,10 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: where a shared one's had one stall of 30 ms beside 30 ms command buffers). Presenting queues, and a queue that lent its `VkQueue` (`CommandQueue::with_vk_queue`), never move. Before the check answers, and on a device whose check finds no idling or that has no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), - each queue keeps the `VkQueue` it took at its creation, round robin. + each queue keeps the `VkQueue` it took at its creation, round robin. So does a device whose + command buffers write no GPU timestamps it reads (`DeviceOptions::gpu_times_from_host`, or a + driver whose timestamps wait for every queue's), counted `WorkCounts::queue_sharing_untimed`: a + queue is known long only by its command buffers' timestamps. `queue_sharing = QueueSharingPolicy::PerQueue`, which `exact_answers()` selects, keeps each command queue on that `VkQueue` everywhere and runs no check. @@ -2614,8 +2617,8 @@ bound. `Device::new_command_queue_unshared`, which never move and which no queue joins. Cost: its command buffers run in one `VkQueue`'s order with those of the command queues that share it, where Metal's queues wait for each other only inside one command: the first command buffer of - each such queue that runs as its `VkQueue`'s oldest for over 2 ms holds the command buffers the - others committed behind it for its whole length, and its later ones while its queue holds work, + each such queue whose GPU work runs over 2 ms holds the command buffers the others committed + behind it for its whole length, and its later ones while its queue holds work, until that queue moves at its next idle point; a command buffer's GPU start time includes the other queues' work before it; QueueSharingPolicy::PerQueue keeps each command queue on the `VkQueue` it took at its creation. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index f2653473e..b80db1582 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -36,7 +36,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | A heap's colour texture that Metal keeps losslessly compressed (`allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or `ShaderAtomic` usage, 16 texels or more a side), on a driver whose compressed images may keep their texels apart from the memory they are bound to (`DriverFact::CompressedImagesHideAliasedWrites`: ANV), is the driver's compressed optimal image, its compression and fast clears kept. A texture Metal keeps uncompressed takes the uncompressed image under either value. The runtime's choice: no pipeline differs. | `heap_compression = HeapCompressionPolicy::Compressed` | `heap_compression = HeapCompressionPolicy::Uncompressed`: an image the driver keeps uncompressed in the heap's bytes, as for a texture Metal keeps uncompressed: host-transfer usage where the device enabled `hostImageCopy` (`heap-texture-host-transfer`), else a linear image (`heap-texture-linear`), else the optimal one (`heap-texture-hides-aliased-writes`) | A write through a buffer or another texture over the texture's bytes may leave its texels as they were or change them otherwise than as written, where Metal's texture reads opaque magenta (`0xffff00ff`) in every texel of drawn content the write covers and the written bytes where it held only a clear; the texture's own writes may show in those bytes compressed. Within Metal's contract: Metal documents such a texture's layout as its own (`allowGPUOptimizedContents` lets it "adjust the private layout"), so no write through another view over its bytes has a defined result there either. `HeapTextureCompressed` (`heap-texture-compressed`), announced once per device where such a texture is made; `runtime_lane::heap_textures` | ANV (Iris Xe of RPL-P; `heap_textures::heap_compression_costs`), a 2048x2048 `RGBA8Unorm` render target in a `Private` placement heap: a pass that clears it 26.9 us against 676.2-676.5 us; a copy into another such texture 647.7-649.1 us against 673.9-693.2 us | | Batches of command buffers committed on one queue that the scheduler finds ready together (a backlog) go to the driver in one `vkQueueSubmit`, at most four, only the last signalling the queue's timeline, on a driver measured to merge a submission that signals nothing into the next (`DriverFact::SubmissionsWithoutSignalsMerge`: Mesa 26.2.4's ANV on the Iris Xe of RPL-P and the UHD 770 of RPL-S, RADV on the Radeon 780M and the RX 7900 XTX, and llvmpipe; every other driver, measured or not, takes the ungrouped form under either value of the switch): one kernel submission, where ANV on i915 lists every `VkDeviceMemory` in each (the consumer's guest drag on the Iris Xe: about 300 entries per execbuffer, 260 of them its host imports, at 112 to 128 execbuffers a frame). A batch's event signals ride to the group's end, which signals each event's semaphore to the highest index the batches held signal it to (an event's indices rise in commit order). A batch that signals a binary semaphore, takes a fence, binds a sparse update, does first work, names the caller's wrapped image, or waits for anything not seen complete (an event, another queue's work) goes alone, after the batches held: a batch with a wait leads a group, never joins one. So that checked command buffers (the consumer checks each) are found ready together, the submission checks of up to three batches right behind a line's head that goes run with the head's, in commit order, none committed after another queue's batch: such a check runs before the previous batch's `vkQueueSubmit` rather than after it, in the scheduler pass that submits its own batch. A pass that finds no batch ready sends the batches held, unless two or more earlier submissions of their `VkQueue` are not seen complete: the GPU runs those first in any case, so the batches stay held, and those committed meanwhile join them, until one submission is left in flight (a completion turn wakes the scheduler at its value), the group fills, a later batch sends it, a head waits for the GPU, or a thread waits for one of their command buffers' completion, which sends them at once; a batch that ends a command buffer with a switch of storage forms riding on it, which settles by its submission's outcome, is never kept so. A held batch that ends its command buffer is `Scheduled` as it is held, its submission handlers run first, then its scheduled handlers, and its kernel end time set, as an M3 Max schedules a command buffer committed behind running work 0.04 to 0.18 ms after its commit. The runtime's: no pipeline differs. | `completion = CompletionPolicy::Grouped` | `completion = CompletionPolicy::Exact`: one submission per batch, each signalling its own values; each line's head checked alone | Each command buffer of a submission but the last is seen complete (status, completed handlers, waits), and the event values it signals are reached (by the GPU waits on other queues, the host's waits, value reads and listeners), once the last completed: late by the GPU time of at most three later batches (about 0.1 to 0.2 ms each in the consumer's compositor frames on the Iris Xe; about 20 ms behind a 20 ms batch), never early, in commit order. Metal's contract states no bound on when completion is seen (an M3 Max reports a command buffer complete, its handlers, status, waits and event listeners alike, 0.04 to 0.10 ms after its GPU end), and no member but the first waits, so no wait holds a member back: a valid program sees only later completion, as of slower GPU work. A batch kept while earlier work runs is seen complete within the same bound, and, where the one submission left in flight ends before its group reaches the GPU, late besides by that gap: at most a completion turn's reaction and the group's `vkQueueSubmit`. Commands, barriers and GPU times are unchanged. `GroupedCompletion` (`grouped-completion`), announced once per device at its first such submission; `runtime_lane::grouped_submissions` | ANV (Iris Xe of RPL-P; `frame_costs::frame_costs_over_imports`, the checked device, 67 command buffers a frame, GPU at 467-783 MHz), with 520 host imports live, where the Exact form's submissions fall behind the commits as the guest's do: 32.0-33.2 kernel submissions a frame against 67.0, 3.4-3.5 ms of execbuffer ioctl a frame against 6.9-7.9 ms, the scheduler thread's CPU 61-63 us a command buffer against 121-136 us, a frame through completion 4.7-5.9 ms against 8.6-9.7 ms; in the guest's shape with 520 (a second queue taking every 20th command buffer, each signalling a shared event, every 10th waiting for one): 26.2-26.7 kernel submissions a frame against 67.0, 2.8 ms of ioctl a frame against 6.9-7.0 ms, the scheduler 52-53 us a command buffer against 122-123 us, a frame through completion 6.0 ms against 8.7 ms; with 260, where it keeps up, 64.9-66.3 kernel submissions a frame against 67.0, the CPU and wall times alike. The cost (`grouped_submissions::grouped_completion_delays`, 8 command buffers of 0.3-0.5 ms of GPU work ready together): the host saw each but a group's last complete later by the later ones' GPU time, the last 0.1-0.3 ms later than alone (the completion turn's per-command-buffer work for the group, done at its end). Keeping a group while earlier work runs (UHD 770 of RPL-S, ANV, the guest's shape with 520 host imports, a submission handler on every command buffer and a 16 MiB fill ahead of each, about 1.3 ms of GPU each; the kept form against the batches sent as found): committed every 1 ms, 18.1-18.2 groups kept a frame, 24.9-25.0 kernel submissions a frame against 57.9, 2.18-2.90 ms of execbuffer ioctl a frame against 4.64-5.43 ms, the scheduler thread's CPU 67-82 us a command buffer against 113-118 us, the GPU idle within a frame's span 0.61 ms against 0.68-0.69 ms, a frame through completion 89.5-89.6 ms alike, completion seen later (GPU end to completed handler: mean 1.82-1.86 ms against 0.43-0.46 ms, p50 1.57-1.60 against 0.11-0.13, p99 4.35-4.37 against 4.09-4.11, max 4.52-4.55 against 4.18-4.23); committed at once, 18.0 kernel submissions a frame against 23.4; with no fill, 18.0 against 20.6, the GPU idle 0.59 ms against 0.58-0.66 ms. In the consumer's guest drag on the Iris Xe (i9-13900H; three passes each way): 24.4-27.5 kernel submissions a frame against 42.4-43.8, the scheduler thread 0.4-1.7 ms of CPU a frame less, 15.7-17.3 frames a second against 16.4-17.6: the frame rate alike within noise, as the scheduler thread does not bound that frame | | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | -| Command queues on a device whose GPU idles when consecutive work comes from another `VkQueue` share `VkQueue`s by choice (`queue_share.rs`): the runtime's own self-check, not a `DriverFact` row, measures that idling once per driver, release and runtime on a thread of its own and keeps its verdict (`Idles`, `DoesNotIdle`, `Unchecked`) in the shader cache's directory, as the in-place check keeps its own (`queue_switch_check.rs`: 48.7 to 51.3 us a switch on the RTX 5080 Laptop GPU, NVIDIA 615.71.09, `Idles` above 20 us). A command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, the most batches in flight first, so short command buffers of several queues run with no switch between them. A queue whose batch ran over 2 ms as its `VkQueue`'s oldest is long: no queue joins its `VkQueue` while it lives, and it moves once more, at its next idle point, to an idle `VkQueue` no long or unshared queue holds. A queue whose command buffers must never wait behind another queue's (a compositor's beside an application's) is made with `Device::new_command_queue_unshared`: it never moves and no queue joins its `VkQueue`. Presenting queues and a queue that lent its `VkQueue` (`with_vk_queue`) never move. Before the verdict, and where it is not `Idles` or there are no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), every queue keeps the `VkQueue` it took at its creation. The runtime's: no pipeline differs. | `queue_sharing = QueueSharingPolicy::Adaptive` | `queue_sharing = QueueSharingPolicy::PerQueue`: each command queue keeps the `VkQueue` it took at its creation, round robin, and the check does not run | A command buffer waits behind the command buffers of the queues sharing its `VkQueue`, where Metal's queues wait for each other only inside one command. The residual stall: once per logical queue that goes long, for a queue that joined its `VkQueue` during its short phase, about one long command buffer's length: the command buffers committed behind that queue's first long one there wait for its whole length (and those behind its later ones while it holds work, until its next idle point). Measured on the RTX 5080 Laptop GPU beside an application that alternates draws with 30 ms command buffers: a shared compositor's commits at 4,800 a second had 64 completions over 10 ms, at most 29.4 to 30.6 ms, in each of 3 runs of each of two such shapes (one join each), against none over 10 ms under `PerQueue` in 5 of those 6 runs and 4 in the sixth (at most 3.7 to 10.7 ms). On an unshared queue, 0 over 10 ms in every run. A command buffer's GPU start time includes the other queues' work before it. `QueueSharing` (`queue-sharing`), at the device's first join | Command buffers a second on the RTX 5080 Laptop GPU, one-draw command buffers, each thread its own queue, the default against `PerQueue`, runs after a lock hold's first: 8 threads with 3 in flight 50.7k to 54.7k against 27.9k to 28.0k (3 runs each); 8 threads with 1 in flight 47.0k to 48.1k against 14.3k (3); 2 threads with 3 in flight 27.0k to 46.5k in 13 runs, falling within one hold as the GPU warmed, and 15.4k and 17.7k in 2 more in which one of the two queues was marked long as it began, against 25.2k to 27.7k (14); 2 threads with 1 in flight 16.9k to 20.7k against 10.1k to 11.5k (5); one thread over 16 queues in turn 21.7k to 43.3k against 10.2k to 11.1k, over 2,048 20.0k to 39.2k against 10.2k to 11.2k (4). Beside an application whose queue never shared with the compositor (isolation, 300 and 30 dispatches), both 0 over 10 ms | +| Command queues on a device whose GPU idles when consecutive work comes from another `VkQueue` share `VkQueue`s by choice (`queue_share.rs`): the runtime's own self-check, not a `DriverFact` row, measures that idling once per driver, release and runtime on a thread of its own and keeps its verdict (`Idles`, `DoesNotIdle`, `Unchecked`) in the shader cache's directory, as the in-place check keeps its own (`queue_switch_check.rs`: 48.7 to 51.3 us a switch on the RTX 5080 Laptop GPU, NVIDIA 615.71.09, `Idles` above 20 us). A command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, the most batches in flight first, so short command buffers of several queues run with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, by its own timestamps (not the host's view of how long it ran as its `VkQueue`'s oldest, which also holds its wait for the GPU to start it and the waiter's lateness to see it complete), is long: no queue joins its `VkQueue` while it lives, and it moves once more, at its next idle point, to an idle `VkQueue` no long or unshared queue holds. A queue whose command buffers must never wait behind another queue's (a compositor's beside an application's) is made with `Device::new_command_queue_unshared`: it never moves and no queue joins its `VkQueue`. Presenting queues and a queue that lent its `VkQueue` (`with_vk_queue`) never move. Before the verdict, and where it is not `Idles` or there are no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), every queue keeps the `VkQueue` it took at its creation; so does every queue of a device whose command buffers write no GPU timestamps it reads (`gpu_times_from_host`, or a driver whose timestamps wait for every queue's), which does not share and is counted (`WorkCounts::queue_sharing_untimed`). The runtime's: no pipeline differs. | `queue_sharing = QueueSharingPolicy::Adaptive` | `queue_sharing = QueueSharingPolicy::PerQueue`: each command queue keeps the `VkQueue` it took at its creation, round robin, and the check does not run | A command buffer waits behind the command buffers of the queues sharing its `VkQueue`, where Metal's queues wait for each other only inside one command. The residual stall: once per logical queue that goes long, for a queue that joined its `VkQueue` during its short phase, about one long command buffer's length: the command buffers committed behind that queue's first long one there wait for its whole length (and those behind its later ones while it holds work, until its next idle point). Measured on the RTX 5080 Laptop GPU beside an application that alternates draws with 30 ms command buffers: a shared compositor's commits at 4,800 a second had 64 completions over 10 ms, at most 26.4 to 30.1 ms, in each of 3 runs of each of two such shapes (one join each), against none over 10 ms under `PerQueue` in those 6 runs (at most 5.6 to 9.7 ms); with 2 ms of draws between long command buffers, none over 10 ms in 3 runs (at most 5.7 to 9.8 ms) against 7, 0 and 0 under `PerQueue` (at most 6.9 to 11.2 ms). On an unshared queue, 0 over 10 ms in every run. A command buffer's GPU start time includes the other queues' work before it. `QueueSharing` (`queue-sharing`), at the device's first join | Command buffers a second on the RTX 5080 Laptop GPU, one-draw command buffers, each thread its own queue, the default against `PerQueue`, runs after a lock hold's first: 8 threads with 3 in flight 50.7k to 54.7k against 27.4k to 28.0k (5 runs each); 8 threads with 1 in flight 47.0k to 50.1k against 13.9k to 14.3k (5); 2 threads with 3 in flight 28.0k to 53.7k against 21.4k to 28.0k (10 each, in turn, the default above `PerQueue` in each pair; no thread's queue marked long), and beside another process's 30 ms command buffers 5.1k to 6.7k against 4.0k to 4.1k (3 each; the host's view marked a thread's queue long in 1 of 3 runs, which then ran at `PerQueue`'s 4.1k); 2 threads with 1 in flight 16.9k to 20.7k against 10.1k to 11.5k (5); one thread over 16 queues in turn 21.7k to 43.3k against 10.2k to 11.1k, over 2,048 20.0k to 39.2k against 10.2k to 11.2k (4). Beside an application whose queue never shared with the compositor (isolation, 300 and 30 dispatches), both 0 over 10 ms | | A chain of `half` additions, subtractions and products on a device without `shaderFloat16` (vk12-floor, SwiftShader, Pascal; capability emulation: the module computes each in `float` and rounds it by the device's `OpQuantizeToF16`): an operation whose flags hold `contract` and `reassoc` and whose result only such operations read is held at `float` precision unrounded, so the chain rounds where a value leaves it (a store, an output, a conversion, a comparison, a call, a phi, a vector move, an operation without both flags), one quantize per exit instead of one per operation (`lower::arith::half_chain`). A device with `shaderFloat16` computes `half` alike under either value. | `half_chains = HalfChainPolicy::AtExits` | `half_chains = HalfChainPolicy::EachOperation`: every operation's result rounded to `half`, as the AIR computes it | The result may differ from the rounded operations' by the roundings the chain skips, each within half a unit in the last place of a `half` at its step, compounded along the chain; a value inside the chain past `half`'s range (65504) stays finite where the rounded operations reach infinity. Within the AIR's flags, which let a compiler regroup and fuse such operations. `FastMathRewrites` (`fast-math-rewrites`) | Not timed. Size on vk12-floor (the fixtures' SPIR-V words, the default against the accurate form): `hfb_filter_bank` 121,270 against 131,766 (1,024 quantizes against 2,464), `grd_half_many_samples` 82,019 against 84,627, `nan_half_fast` 9,808 against 9,832 | | A texture that only samples or reads (no `RenderTarget`, `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device's own check shows that the image's first move, which Vulkan lets read and write every byte bound to it (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), leaves every byte alone while the CPU writes beside it: a deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's ruling (`in_place.rs`). The check runs once per driver, release and runtime, per class of pages, on a thread of its own, its verdict kept in the shader cache's directory; a texture made before its class's verdict is a shadow. A texture whose usage renders or writes, a check that failed or made no image, and a pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each; a driver whose first move changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer | | A render or compute state's creation hands the driver's making of its predicted pipeline (`pipeline/predicted.rs`, `pipeline/dispatch_making.rs`) to the runtime's pool, kept by the state as a draw's or dispatch's making is, and waits for it `pipeline_creation_wait` at most; a committed command buffer's recordings wait until its commit plus `pipeline_commit_wait` at most, one deadline its commands share, for its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches) pipelines still being made (the scheduler wakes at the bound, `StepWaits::until`), an execution's replayed draws (`render/pending.rs`) among them, whose pipelines the commit's settle hands to the pool (a device replay's, one recording for every command, waits until made under either value), then record each such command as nothing: a draw's barriers and visibility query, a dispatch's barrier (a tile dispatch's copies into its scratch and back), no draw or dispatch, the command buffer running on without error. The making goes on, and the command buffers after it draw and dispatch with the pipeline once made. Metal compiles inside `newRenderPipelineState`, so no draw of a made state waits or is dropped; a host that creates a state inside a command buffer's encoding (the consumer creates a guest's state at an execution's first lookup of it) held that execution through the driver's whole compile: 11.59 s inside one execution on an M2 Pro (MoltenVK 1.4.2, a cold Metal compiler service; a sample of such a stall finds the compile's thread waiting in `MVKMetalCompiler::compile` for Metal's compiler), past the guest's 10 s FIFO check, which ended the guest's task. Each bound is 4.5 s: a creation and a commit may fall in one step of the guest's FIFO (a task's jobs run one after another, and a draw's own variant waits under its command buffer's bound), and no runtime call waits for both, so one step waits 9 s at most for makings, under that 10 s check. A creation waits on no command buffer's deadline and a `commit` on no creation's; a `commit` waits until its own deadline at most (it records there what it can, an execution of render commands the CPU writes among them), every other recording on the scheduler's thread. Made until made under either value, in the call that makes them: a draw that records nothing, one in a pass of custom sample positions and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its `commit`), and a failed making made again (`PipelineWaitPolicy`'s docs). The runtime's: no pipeline differs. | `pipeline_waits = PipelineWaitPolicy::Bounded`, `pipeline_creation_wait = 4.5 s`, `pipeline_commit_wait = 4.5 s` | `pipeline_waits = PipelineWaitPolicy::Exact`: the creation makes its predicted pipeline before it returns (a render state's first key on its own thread, the rest on the pool, joined; a compute state's on its own thread), an execution's settle makes its replayed draws' pipelines at the commit, and a command buffer waits for each draw's and dispatch's pipeline until it is made | A draw whose pipeline was still being made `pipeline_commit_wait` after its command buffer's commit renders nothing in that command buffer (only there: later ones draw it), where Metal's renders: content drawn once (a layer, a glyph cache) stays without it until redrawn. A creation returns after `pipeline_creation_wait` at most with its making in flight (`WorkCounts::creations_left_making`). `DrawDroppedStillMaking` (`draw-dropped-still-making`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `CommandBuffer::dropped_draw` names the first with `VK_TIMEOUT`; `WorkCounts::draws_dropped_still_making`; `deferred_calls::a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` and `under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands`. A dispatch whose pipeline was still being made then writes nothing in that command buffer, where Metal's runs: `DispatchDroppedStillMaking` (`dispatch-dropped-still-making`), `WorkCounts::dispatches_dropped_still_making`, the first named by `dropped_draw`; `deferred_calls::a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing`, `a_compute_state_s_creation_waits_its_bound_for_its_predicted_making` and `a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` | No GPU cost. The exact form holds the creating thread, and the command buffer, for the whole compile: up to 11.59 s on the M2 Pro's cold boot (that boot's 2,483 render state creations, translation included: 300 over 16 ms, 151 over 100 ms, 14 over 250 ms, 3 over 1 s, the longest 11.59 s, 5.82 s and 1.17 s), where the default holds a creation for 4.5 s at most and a command buffer for 4.5 s from its commit, which drops the draws of the compiles that outlast those (2 of that boot's 2,483 were over 4.5 s) for the command buffers committed before they land; bounds of 1 s dropped 39 draws in a cold boot on the M2 Pro, and the guest's menu bar, drawn once, stayed half drawn |