diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 8bb69e57f..e135f2b12 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -919,16 +919,60 @@ impl DeviceShared { /// its `VkQueue`s is under way; else the time since the last such use ended /// (`queue_quiet.rs`). pub(crate) fn work_quiet_for(&self) -> Option { - if self.batch_in_flight() || !self.scheduler.holds_none() { - return None; - } - self.queue_quiet.unused_for() + quiet_for( + &self.queues, + || self.scheduler.holds_none(), + &self.queue_quiet, + ) } /// Whether a batch submitted to one of the device's `VkQueue`s is not seen complete there. pub(crate) fn batch_in_flight(&self) -> bool { - (self.queues.iter()).any(|slot| slot.completed_value() < slot.submitted_value()) + in_flight(&self.queues) } + + /// A share of what tells whether its work is quiet, for a thread that holds no device + /// (`submit_check.rs`). + pub(crate) fn work_share(&self) -> WorkShare { + WorkShare { + queues: Arc::clone(&self.queues), + holds: self.scheduler.holds_share(), + uses: Arc::clone(&self.queue_quiet), + } + } +} + +/// What tells whether a device's work is quiet ([`DeviceShared::work_quiet_for`]), shared with a +/// thread that holds no device: its `VkQueue`s, the scheduler's holds and its queue uses. +pub(crate) struct WorkShare { + queues: Arc<[QueueSlot]>, + holds: crate::scheduler::HoldsShare, + uses: Arc, +} + +impl WorkShare { + /// [`DeviceShared::work_quiet_for`]. + pub(crate) fn quiet_for(&self) -> Option { + quiet_for(&self.queues, || self.holds.holds_none(), &self.uses) + } +} + +/// Whether a batch submitted to one of `queues` is not seen complete there. +fn in_flight(queues: &[QueueSlot]) -> bool { + (queues.iter()).any(|slot| slot.completed_value() < slot.submitted_value()) +} + +/// How long the work of a device of `queues`, whose scheduler holds none of it where `holds_none` +/// and whose queue uses are `uses`, has been quiet ([`DeviceShared::work_quiet_for`]). +fn quiet_for( + queues: &[QueueSlot], + holds_none: impl FnOnce() -> bool, + uses: &queue_quiet::QueueQuiet, +) -> Option { + if in_flight(queues) || !holds_none() { + return None; + } + uses.unused_for() } impl DeviceShared { diff --git a/crates/metal2vulkan-runtime/src/loader_word.rs b/crates/metal2vulkan-runtime/src/loader_word.rs index 16620ff96..3c9ba3ccc 100644 --- a/crates/metal2vulkan-runtime/src/loader_word.rs +++ b/crates/metal2vulkan-runtime/src/loader_word.rs @@ -35,7 +35,8 @@ //! mark after it ([`DeviceWord::end_step`]: the use's last submission on the queue, whose Metal //! command buffer completes after the check's own), so the //! runtime's loader-served calls on other threads may wait for one step of theirs, once, while they -//! run (the checks run once per driver and runtime, for milliseconds); elsewhere the word never +//! run (the checks run for milliseconds, as a device is made and, where an answer of the +//! submission checks stands only for now, again in its life); elsewhere the word never //! changes and they hold it across their submission calls alone. A narrower hold, around the calls //! that read the word alone, cannot exclude the writer: MoltenVK writes from its own threads as //! each of the checks' Metal command buffers completes, at no call of the runtime's, so only diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index c5cccb3fa..2d414dcfa 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -483,6 +483,17 @@ pub(crate) struct Scheduler { thread: Mutex>>, } +/// A share of the scheduler's state that reads whether it holds any batch committed and not +/// submitted ([`Scheduler::holds_share`]). +pub(crate) struct HoldsShare(Arc); + +impl HoldsShare { + /// [`Scheduler::holds_none`]. + pub(crate) fn holds_none(&self) -> bool { + self.0.holds_none() + } +} + struct SchedulerShared { /// The state, under the lock a pass holds, with the commits a pass under way takes in. inbox: Inbox, @@ -644,6 +655,13 @@ impl Posted { } impl SchedulerShared { + /// [`Scheduler::holds_none`]. + fn holds_none(&self) -> bool { + let inbox = &self.inbox; + let state = lock(inbox.state()); + state.order.is_empty() && state.grouped.is_empty() && !inbox.holds_commits() + } + /// A pass that took in `taken` commits ended, its submissions made and counted, under the /// lock: counted, released after them (`WorkCounts::commits_taken_in`). fn took_in(&self, taken: usize) { @@ -1278,9 +1296,13 @@ impl Scheduler { /// semaphore, a host step, a check or a group, or waits in the inbox /// (`texture/storage_form.rs`). pub(crate) fn holds_none(&self) -> bool { - let inbox = &self.shared.inbox; - let state = lock(inbox.state()); - state.order.is_empty() && state.grouped.is_empty() && !inbox.holds_commits() + self.shared.holds_none() + } + + /// A share of its state that reads [`holds_none`](Self::holds_none) alone, for a thread that + /// holds no device (`submit_check.rs`). + pub(crate) fn holds_share(&self) -> HoldsShare { + HoldsShare(Arc::clone(&self.shared)) } /// A CPU decode into the decoded twin of the resource `key` was queued: every batch whose diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs index a9302653e..2194d2058 100644 --- a/crates/metal2vulkan-runtime/src/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -1,5 +1,7 @@ //! The device's checks of its submissions, on a thread of its own, once per driver, release, -//! kernel and runtime: whether `VkSubmitInfo`s that signal nothing merge into one submission of +//! kernel and runtime for each answer that earns its record, at each device's making and again in +//! its life for the others ("Answers for now", below): whether `VkSubmitInfo`s that signal nothing +//! merge into one submission of //! the driver's ([`Check::Merge`]), and whether a host-pointer import the device holds adds to the //! cost of every submission ([`Check::ImportTax`]). Each answers a question the runtime once read //! from the driver's identity, its `driverID`, vendor and `deviceID`, so that a GPU no @@ -58,8 +60,7 @@ //! its rounds or phases, and answers only where the two halves agree. Each half holds several //! rounds or phases of each form, so one that load lengthened throughout moves no floor. A try //! whose halves disagree is made again, at most [`TRIES`] times; where none agrees, the check -//! answers `Unchecked` for the device's life and the record is not written, so the next device -//! measures again. Seen on the Radeon 780M while the checks compared medians of single tries: a +//! answers `Unchecked` for now (below) and the record is not written. Seen on the Radeon 780M while the checks compared medians of single tries: a //! device made while a test's thread made and released buffers in a loop //! (`tests/in_place_check.rs`) placed its long buffers in fresh pages, which follows only from //! an answer that a held import adds nothing, where the quiet devices of the same run answered @@ -76,16 +77,15 @@ //! devices answered `Fails` from 2.1 to 2.2 us held and bare alike (2026-11-09), and that //! process took the routes of a taxed device the quiet ones never take. So an import tax //! `Holds` stands only where its try's floors pass its bound [`TAX_MARGIN`] times over: short -//! of that it answers `Fails` for the device's life, unrecorded, and the next device measures -//! again. Past it, it is recorded only where each of [`TAX_REPEATS`] tries more passes so -//! again; short of that, it answers for the device's life alone. The same load splits a +//! of that it answers `Fails` for now, unrecorded. Past it, it is recorded only where each of +//! [`TAX_REPEATS`] tries more passes so again; short of that, it answers for now. The same load splits a //! try's halves: on the M3 Max, in three runs of the runtime's device tests (2026-11-09, //! MoltenVK 1.4.2), one of the six devices that printed their verdicts had all three of its //! import tax tries split, its last 2.5 against 1.2 us over all its phases, where the other five //! answered `Fails` (1.1 to 2.6 us against 1.2 to 3.0), and it answered `Unchecked`, so its long //! buffers took no fresh pages where the others' did. Tries that all split so answer `Fails` for -//! the device's life, unrecorded, where the last one's floors fall short of the margin, and -//! `Unchecked` only past it. Load moves the merge's floors either way, its halves agreeing: in +//! now, unrecorded, where the last one's floors fall short of the margin, and `Unchecked` only +//! past it. Load moves the merge's floors either way, its halves agreeing: in //! one full run of the runtime's and the validation crate's device tests on the Radeon 780M //! (RADV, Mesa 26.2.6, Linux 7.3.1), 32 of 2,531 devices answered `Fails`, one call of four at //! 0.6 to 1.15 of the calls apart where a quiet device's is 0.35; and on the M3 Max beside loops @@ -94,8 +94,7 @@ //! the kernel's release. So a merge verdict is recorded only where its try's floors are clear of //! that load ([`merge_clear`]: a `Holds` at most [`MERGE_HOLDS_CLEAR`] of the calls apart, a //! `Fails` at least [`MERGE_FAILS_CLEAR`]) and each of [`MERGE_REPEATS`] tries more answers it -//! so ([`merge_tried`]); short of that it answers for the device's life, unrecorded, and the -//! next device measures again. Those `Holds` on the M3 Max came from floors that were each the +//! so ([`merge_tried`]); short of that it answers for now, unrecorded. Those `Holds` on the M3 Max came from floors that were each the //! least of a form's rounds, inside one call for the one call of the infos and inside //! [`MERGED`] for the calls apart: load that lengthened any one call of a round lengthened its //! sum, so each round of the calls apart took a hit about [`MERGED`] times as often, and their @@ -105,12 +104,45 @@ //! buffer of its own. So each call apart has a floor of its own, over as many rounds as the //! one call's, and the form's floor is their sum ([`apart_floor`]): each floor is the least of //! as many calls, equally exposed to the load, and a hit to one call of each round, whichever, -//! moves none. +//! moves none. A lift of one call of every round in both forms alike still reads as a `Fails`, +//! and past [`MERGE_FAILS_CLEAR`]: on the Radeon 780M beside other jobs on its host (job +//! m3-max-39740, a load average of 18 to 24 on 16 threads), two of four devices' merges +//! answered `Fails` from 76.8 us in one call against 106.9 apart (0.72) and 67.6 against 90.7 +//! (0.745), 58 to 67 us past the other two's one call (9.3 and 9.5 us) and 64 to 80 past +//! their calls apart (26.6 and 27.1), whose answer was `Holds`; and those two devices grouped +//! no batch for their lives. Their checks waited up to 9.4 and 38.6 ms for one of their +//! submissions, the quiet ones' 0.09 ms. Threads of the checks' own process that spun, or +//! wrote fresh pages, on twice the host's 16 threads lifted every call alike instead, by up to +//! 30 us, and each of the eight devices made beside them answered `Holds`, its tries at 0.23 to +//! 0.64 of the calls apart (job m3-max-39786). +//! - **Answers for now.** So an answer stands for now unless it earned more ([`Stands`]): a +//! merge `Holds` clear of the load and repeated, an import tax `Holds` past its margin and +//! repeated, and an `Unchecked` of a call refused or of a device that imports no host pointer +//! are recorded (below); a `Fails` clear of the load (the merge's past [`MERGE_FAILS_CLEAR`] +//! and repeated, the import tax's with a held import adding at most a +//! [`TAX_FAILS_CLEAR`]th of its bound) whose every try ran quiet stands for the device's life +//! and is never recorded ([`merge_stands`], [`tax_stands`]). A try ran quiet ([`Load`]) where +//! each stand-by before its rounds or submissions found the device's work quiet (below), none +//! of them took past [`QUIET_ROUND_MOST`] from its first call to its fence's reset, and all of +//! them no more than [`QUIET_TRY_MOST`]. The checks' thread keeps its command buffers and +//! fence and checks again each answer that stands for now: [`RECHECK_FIRST`] after the +//! device's first answers, then each time twice as long after the last up to 64 s, then every +//! [`RECHECK_EVERY`] ([`recheck_after`]), until none does. Each answer of a check again takes +//! the place of the one before (tries that all split keep it), so a merge that answered +//! `Fails` under a load that passed groups once a check again answers `Holds`. +//! - **Stood by.** Before each round and each submission of a phase, the thread stands by until +//! the device's work is quiet (`DeviceShared::work_quiet_for`): none of its batches held or in +//! flight, and no use of its `VkQueue`s under way for [`ROUND_QUIET`], or none since its own +//! last round. It stands by [`STAND_BY_MOST`] at most, and not at all while a call waits for +//! its verdicts; a round that goes without finding the work quiet leaves its try not quiet. //! - **Its verdicts** are `Pending` until it answers, and the device takes the form a driver //! without each answer takes: every batch its own call, its long buffers placed and cleared as //! ever, every pointer import kept. `Unchecked` where a check could not run (no //! `VK_EXT_external_memory_host`, a call refused, too few rounds) or its tries disagreed (the -//! import tax's only past its margin, above), with the same forms. +//! import tax's only past its margin, above), with the same forms. A verdict changes in the +//! device's life only where a check again answers otherwise; each path reads it as it decides +//! (a batch whether it waits in a group, a buffer as it is made whether it takes fresh pages), +//! and what it decided before stays. //! - **Its cost**: [`ROUNDS`] rounds of each merge form and [`TAX_PHASES`] phases of //! [`TAX_SUBMITS`] submissions, each waited for, every command buffer empty; the //! [`TAX_IMPORTS`] imports of [`TAX_BYTES`] in all made and freed once a try, over pages @@ -118,18 +150,25 @@ //! [`TRIES`] times in all, where its halves disagree, and the import tax's [`TAX_REPEATS`] //! tries more where it answers `Holds` past its margin, and the merge's [`MERGE_REPEATS`] where //! its answer is clear of the load beside it. The probe's rounds took 3 to 12 ms on those -//! devices. -//! - **Kept.** Once every check answered and each timed check's answer earned its record (no -//! check's tries all disagreed; the merge's answer was clear of the load and repeated, and an -//! import tax `Holds` passed its margin and repeated, above), -//! the verdicts are written as one record in the shader cache's content directory -//! (`shader_cache/store.rs`), named by the driver's identity, the kernel's release (the import -//! tax is the kernel's work on RADV), the check's version and the runtime's ([`record_name`]): -//! a device of the same driver, release and kernel reads them as it is made and runs no check. -//! A failed write leaves the verdicts for the device's life. A device made with +//! devices. Where an answer stands for now, as much again at each check again, the first 1 s +//! after the first answers and the eighth and later a minute apart; and a device that does not +//! merge, or holds an import with no cost, pays its merge's or its import tax's tries at each +//! making, a `Fails` never being recorded (below): on a driver that does neither (the M3 Max's +//! MoltenVK, NVIDIA's), every device runs both checks, as it did before any record, and, where +//! no try of its first answers ran quiet, once more at least. +//! - **Kept.** Once a check's answer earned its record (above), the verdicts recorded are +//! written as one record in the shader cache's content directory (`shader_cache/store.rs`), +//! named by the driver's identity, the kernel's release (the import tax is the kernel's work on +//! RADV), the check's version and the runtime's ([`record_name`]), with no answer of a check +//! whose answer earned none; written again as a check again earns one. A device of the same +//! driver, release and kernel reads it as it is made: it takes each `Holds` and `Unchecked` +//! there and does not check that again, and runs the checks the record holds no answer of, or +//! a `Fails` of, which it takes as a hint and no answer ([`recalled`]): a `Fails` of the load +//! beside one device's checks would hold every later device of the release to it. A failed +//! write leaves the verdicts for the device's life. A device made with //! `DeviceOptions::assume_submissions_merge` (a test hook) reads and writes no record: its merge //! check holds from its making, the merge's floors only reported, and its other checks answer -//! for its life. +//! for its life, never checked again. //! - **Out of the device's way.** Before each step that allocates, frees, maps or unmaps pages, //! or submits (each round, each import and its release, each submission of a phase), the //! thread steps aside for the device's allocations and frees on other threads @@ -182,7 +221,7 @@ use crate::command_buffer::fences::Fences; use crate::device::functions::{Functions, Vk}; use crate::device::relay::{By, QueueUses}; use crate::device::submit_stalls::Uses; -use crate::device::{lock, Device, QueueSlot}; +use crate::device::{lock, Device, QueueSlot, WorkShare}; use crate::driver_facts::inform_through; use crate::exit_guard::{self, Call}; use crate::freed_memory::Parking; @@ -211,8 +250,8 @@ pub(crate) const ROUNDS: usize = 16; /// The untimed rounds of each form first. const WARM: usize = 2; -/// The tries of a timed check (the merge, the import tax) whose halves disagree, before -/// it answers `Unchecked` for the device's life and nothing is recorded (the module docs). +/// The tries of a timed check (the merge, the import tax) whose halves disagree, before it +/// answers `Unchecked` for now and nothing is recorded (the module docs). pub(crate) const TRIES: usize = 3; /// The most one call of the merge's infos costs, as a share of its calls apart, where the driver @@ -273,6 +312,77 @@ pub(crate) const TAX_MARGIN: i64 = 2; /// it is recorded. pub(crate) const TAX_REPEATS: usize = 2; +/// What a held import may add to a submission at most over a whole try, as a part of its bound +/// ([`tax_bound`]), for an import tax `Fails` to be clear of the load beside it +/// ([`tax_stands`]): the bound divided by this, a half. +pub(crate) const TAX_FAILS_CLEAR: i64 = 2; + +/// How long no use of the device's `VkQueue`s may have been under way, none of its batches in +/// flight or held, before a round or a submission of the checks goes ([`Parts::stand_by`]): the +/// gap that ends a burst of submissions (`queue_quiet::SETTLE`). +const ROUND_QUIET: Duration = crate::device::queue_quiet::SETTLE; + +/// The longest a stand-by lasts ([`Parts::stand_by`]): past it the round goes beside the device's +/// work, and its try did not run quiet ([`Load::ran_quiet`]). +pub(crate) const STAND_BY_MOST: Duration = Duration::from_millis(20); + +/// How often a stand-by looks again. +const LOOK_EVERY: Duration = Duration::from_micros(250); + +/// The longest a round or a submission of a try that ran quiet took, from its first call to its +/// fence's reset, in nanoseconds ([`Load::ran_quiet`]): about twenty times a quiet one's (the +/// Radeon 780M's longest, 0.09 ms), where the loaded checks of the module docs waited 9.4 to +/// 38.6 ms for one. +pub(crate) const QUIET_ROUND_MOST: i64 = 2_000_000; + +/// The longest the rounds or submissions of a try that ran quiet took in all, in nanoseconds +/// ([`Load::ran_quiet`]): the probe's rounds took 3 to 12 ms on its devices. +pub(crate) const QUIET_TRY_MOST: i64 = 30_000_000; + +/// The wait before the first check again of an answer that stands only for now ([`Stands::Now`], +/// [`recheck_after`]), from the end of the device's first answers. +pub(crate) const RECHECK_FIRST: Duration = Duration::from_secs(1); + +/// The checks again whose wait doubles the one before ([`recheck_after`]): from [`RECHECK_FIRST`] +/// to 64 s. +pub(crate) const RECHECK_DOUBLINGS: u32 = 6; + +/// The wait between checks again past those ([`recheck_after`]): one a minute. +pub(crate) const RECHECK_EVERY: Duration = Duration::from_secs(60); + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +thread_local! { + /// The merge tries of the next device this thread makes that a device test lifts + /// ([`lift_next_merge_tries`]). + static LIFTED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The answers the next device this thread makes takes as a record's, every one standing + /// ([`answer_next_device`]). + static ANSWERED: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// Lift the first `tries` merge tries of the next device this thread makes as the load beside +/// them lifted the Radeon 780M's (the module docs, "Load beside it"): [`LIFT`] more on the first +/// call of each of their rounds, and none of their stand-bys found quiet. A device test's. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) fn lift_next_merge_tries(tries: u32) { + LIFTED.with(|lifted| lifted.set(tries)); +} + +/// What [`lift_next_merge_tries`] adds to the first call of each round, in nanoseconds: about +/// what the load lifted the Radeon 780M's one call of the infos by (the module docs). +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) const LIFT: i64 = 70_000; + +/// The next device this thread makes takes `answers` as its submission checks' verdicts, as a +/// record's that each stand, and runs no check: a device test's, for one that holds the device +/// to the paths those verdicts choose from its making (a record's `Fails` is no answer, +/// [`recalled`]). +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) fn answer_next_device(answers: [Verdict; Check::COUNT]) { + ANSWERED.with(|answered| answered.set(Some(answers))); +} + /// How long one wait for a fence lasts before it is repeated. const WAIT_SLICE: Duration = Duration::from_millis(100); @@ -356,9 +466,131 @@ pub(crate) struct Measured { pub(crate) bare: i64, } +/// How long a check's answer stands (the module docs, "Load beside it"). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Stands { + /// Recorded: a later device of the same driver, release and kernel reads it and does not + /// check again. A `Holds` its tries earned, clear of the load beside them and repeated, or an + /// `Unchecked` of a call refused or of a device that imports no host pointer. + Recorded, + /// For the device's life, unrecorded, so the next device checks again: a `Fails` clear of + /// the load beside it whose tries each ran quiet ([`Load::ran_quiet`]). + Life, + /// Until the check runs again, later in the device's life ([`recheck_after`]): any other + /// answer. + Now, +} + +impl Stands { + fn byte(self) -> u8 { + match self { + Stands::Recorded => 1, + Stands::Life => 2, + Stands::Now => 3, + } + } + + fn of_byte(byte: u8) -> Option { + match byte { + 1 => Some(Stands::Recorded), + 2 => Some(Stands::Life), + 3 => Some(Stands::Now), + _ => None, + } + } +} + +/// A check's answer from one run of its tries: its verdict, its floors (those of its first try +/// that answered) and how long it stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Answer { + pub(crate) verdict: Verdict, + pub(crate) floors: (i64, i64), + pub(crate) stands: Stands, +} + +/// How long a merge answer stands: `verdict` with its floors over its tries ([`merge_tried`]), +/// `earned` where it is clear of the load and repeated (or an `Unchecked` of a refused call), +/// each try run quiet where `quiet`. A `Holds` earned is recorded; a `Fails` earned stands for +/// the device's life where its tries ran quiet and is never recorded, since load that lifts one +/// call of each form alike reads as a `Fails` (the module docs); every other answer stands for +/// now. +pub(crate) fn merge_stands(verdict: Verdict, earned: bool, quiet: bool) -> Stands { + match (verdict, earned) { + (Verdict::Holds | Verdict::Unchecked, true) => Stands::Recorded, + (Verdict::Fails, true) if quiet => Stands::Life, + _ => Stands::Now, + } +} + +/// How long an import tax answer stands: `verdict` with `floors`, `(held, bare)`, over its tries +/// ([`tax_tried`]), `kept` where they may be recorded, each try run quiet where `quiet`. A `Holds` +/// kept (past its margin and repeated) is recorded, and so is an `Unchecked` kept (a call +/// refused, no pointer import); a `Fails` kept stands for the device's life where its tries ran +/// quiet and a held import added at most a [`TAX_FAILS_CLEAR`]th of its bound, and is never +/// recorded; every other answer stands for now. +pub(crate) fn tax_stands(verdict: Verdict, floors: (i64, i64), kept: bool, quiet: bool) -> Stands { + let (held, bare) = floors; + match (verdict, kept) { + (Verdict::Holds | Verdict::Unchecked, true) => Stands::Recorded, + (Verdict::Fails, true) if quiet && held - bare <= tax_bound(bare) / TAX_FAILS_CLEAR => { + Stands::Life + } + _ => Stands::Now, + } +} + +/// The wait before the checks' thread checks again, the `done`th time from 0, an answer that +/// stands for now: [`RECHECK_FIRST`], doubled for each of the next [`RECHECK_DOUBLINGS`] (1, 2, +/// 4 ... 64 s), then [`RECHECK_EVERY`]. +pub(crate) fn recheck_after(done: u32) -> Duration { + match done <= RECHECK_DOUBLINGS { + true => RECHECK_FIRST * (1 << done), + false => RECHECK_EVERY, + } +} + +/// What a device that reads a record takes of its verdict for a check: a `Holds` or an `Unchecked` +/// stands; a `Fails` is a hint, no answer, and the check runs again, as for a check the record +/// holds no answer of (`Pending`) (the module docs, "Kept"). +pub(crate) fn recalled(verdict: Verdict) -> Option { + match verdict { + Verdict::Holds | Verdict::Unchecked => Some(verdict), + Verdict::Fails | Verdict::Pending => None, + } +} + +/// What a try's rounds or submissions read of the load beside them: whether a stand-by before one +/// of them went without finding the device's work quiet ([`Parts::stand_by`]), and the longest +/// one and all of them together, each from its first call to its fence's reset, in nanoseconds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Load { + pub(crate) missed: bool, + pub(crate) longest: i64, + pub(crate) total: i64, +} + +impl Load { + /// A round or submission that found the device's work quiet where `quiet`, and took `nanos`. + pub(crate) fn round(&mut self, quiet: bool, nanos: i64) { + self.missed |= !quiet; + self.longest = self.longest.max(nanos); + self.total = self.total.saturating_add(nanos); + } + + /// Whether the try ran quiet: each of its stand-bys found the device's work quiet, no round or + /// submission took past [`QUIET_ROUND_MOST`], and all of them no more than + /// [`QUIET_TRY_MOST`]. + pub(crate) fn ran_quiet(&self) -> bool { + !self.missed && self.longest <= QUIET_ROUND_MOST && self.total <= QUIET_TRY_MOST + } +} + /// A device's verdicts of its submission checks, and their state (the module docs). pub(crate) struct SubmitChecks { verdicts: [AtomicU8; Check::COUNT], + /// How long each check's last answer stands ([`Stands`]), 0 before one. + stands: [AtomicU8; Check::COUNT], measured: [AtomicI64; 4], started: AtomicBool, settled: Mutex, @@ -381,6 +613,10 @@ pub(crate) struct SubmitChecks { /// The import tax's tries, in this process: each makes and releases [`TAX_IMPORTS`] imports /// once ([`tax_holds`]). pub(crate) tax_tries: AtomicU64, + /// The merge's tries, in this process. + pub(crate) merge_tries: AtomicU64, + /// The checks again of answers that stood for now, in this process ([`recheck_after`]). + pub(crate) rechecks: AtomicU64, /// The device's teardown stopped the checks ([`SubmitChecks::stop`]): read between steps. stopping: AtomicBool, /// The calls waiting for the verdicts ([`SubmitChecks::wait`]), for which no step steps @@ -389,6 +625,9 @@ pub(crate) struct SubmitChecks { /// Whether the checks' thread runs, and what tells its end. running: Mutex, ending: Condvar, + /// What wakes the checks' thread from its rest between checks again + /// ([`SubmitChecks::rest`]), under `running`'s lock: the device's teardown. + rest: Condvar, /// The longest the checks waited for one of their submissions in this process, in /// nanoseconds, a stalled one's wait included ([`STALL`]). longest_wait: AtomicU64, @@ -418,6 +657,9 @@ pub(crate) struct SubmitChecks { /// test's. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) stall: Mutex>, + /// The merge tries still to lift ([`lift_next_merge_tries`]): a device test's. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + lifted: AtomicU32, } /// A device test's injection into the next submission of the checks @@ -440,6 +682,7 @@ impl SubmitChecks { pub(crate) fn new(merge_assumed: bool) -> SubmitChecks { let checks = SubmitChecks { verdicts: Default::default(), + stands: Default::default(), measured: Default::default(), started: AtomicBool::new(false), settled: Mutex::new(false), @@ -451,10 +694,13 @@ impl SubmitChecks { merge_unearned: AtomicBool::new(false), merge_assumed, tax_tries: AtomicU64::new(0), + merge_tries: AtomicU64::new(0), + rechecks: AtomicU64::new(0), stopping: AtomicBool::new(false), waiters: AtomicU32::new(0), running: Mutex::new(false), ending: Condvar::new(), + rest: Condvar::new(), longest_wait: AtomicU64::new(0), stalled: AtomicBool::new(false), left: Mutex::new(None), @@ -468,6 +714,8 @@ impl SubmitChecks { idles: AtomicU64::new(0), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] stall: Mutex::new(None), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + lifted: AtomicU32::new(LIFTED.with(|lifted| lifted.replace(0))), }; if merge_assumed { checks.set(Check::Merge, Verdict::Holds); @@ -494,6 +742,20 @@ impl SubmitChecks { self.verdicts[check.index()].store(verdict.byte(), Ordering::Release); } + /// How long `check`'s last answer stands; `None` before one, and for a verdict read from a + /// record. + pub(crate) fn stands(&self, check: Check) -> Option { + Stands::of_byte(self.stands[check.index()].load(Ordering::Acquire)) + } + + /// `check`'s floors in what the checks measured: the merge's `(merged, apart)`, the import + /// tax's `(held, bare)`. + fn set_floors(&self, check: Check, (first, second): (i64, i64)) { + let at = 2 * check.index(); + self.measured[at].store(first, Ordering::Release); + self.measured[at + 1].store(second, Ordering::Release); + } + fn measured(&self) -> Measured { let at = |i: usize| self.measured[i].load(Ordering::Acquire); Measured { @@ -508,19 +770,14 @@ impl SubmitChecks { /// chooses, whatever the device measured (`tests/host_ram_dma_buf.rs`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] pub(crate) fn force(&self, check: Check, verdict: Verdict) { + // It stands for the device's life: no check again takes its place. + self.stands[check.index()].store(Stands::Life.byte(), Ordering::Release); self.set(check, verdict); } fn set_measured(&self, measured: Measured) { - let values = [ - measured.merged, - measured.apart, - measured.held, - measured.bare, - ]; - for (slot, value) in self.measured.iter().zip(values) { - slot.store(value, Ordering::Release); - } + self.set_floors(Check::Merge, (measured.merged, measured.apart)); + self.set_floors(Check::ImportTax, (measured.held, measured.bare)); } /// Note the checks started; whether they had not before. @@ -558,6 +815,8 @@ impl SubmitChecks { self.stopping.store(true, Ordering::SeqCst); { let mut running = lock(&self.running); + // Its thread may rest between checks again ([`SubmitChecks::rest`]). + self.rest.notify_all(); while *running { running = (self.ending.wait(running)).unwrap_or_else(std::sync::PoisonError::into_inner); @@ -567,6 +826,26 @@ impl SubmitChecks { left.is_none_or(|left| left.release_once_complete(raw, self.bound())) } + /// The checks' thread rests for `wait` before it checks again ([`recheck_after`]): whether it + /// goes on, `false` once the device's teardown stops it, which wakes it at once. + fn rest(&self, wait: Duration) -> bool { + let deadline = Instant::now() + wait; + let mut running = lock(&self.running); + loop { + if self.stopping() { + return false; + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return true; + } + running = match self.rest.wait_timeout(running, left) { + Ok((running, _)) => running, + Err(poisoned) => poisoned.into_inner().0, + }; + } + } + /// The longest the checks wait for one of their submissions, and the teardown for a stalled /// one: [`STALL`], or a device test's bound. fn bound(&self) -> Duration { @@ -751,8 +1030,8 @@ fn floor(times: &[i64]) -> i64 { /// framed: a change to any bumps it, and a record of another version is never read (one of 3 may /// hold an import tax `Holds` short of [`TAX_MARGIN`], one of 5 a merge verdict of one loaded /// try, one of 6 three verdicts, one of 7 a merge verdict from the least of the calls apart's -/// sums rather than [`apart_floor`]). -pub(crate) const CHECK_VERSION: u32 = 8; +/// sums rather than [`apart_floor`], one of 8 a `Fails` taken as an answer). +pub(crate) const CHECK_VERSION: u32 = 9; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VSUBC\0"; @@ -802,7 +1081,8 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// version u32 CHECK_VERSION /// runtime u32 RUNTIME_VERSION /// identity 32 bytes the identity's and the kernel's digest for these checks -/// verdicts 2 bytes one per check, in Check::ALL's order: Holds 1, Fails 2, Unchecked 3 +/// verdicts 2 bytes one per check, in Check::ALL's order: Holds 1, Fails 2, Unchecked 3, +/// or 0 where the record holds no answer of it /// measured 4 x i64 merged, apart, held, bare, in nanoseconds /// checksum 32 bytes SHA-256 of every byte before it /// ``` @@ -832,9 +1112,9 @@ pub(crate) fn encode( bytes } -/// The verdicts and measurements `bytes` record for `identity`: `None` for anything but a whole -/// record of this version and runtime, for this identity and kernel, whose checksum holds and -/// whose every verdict is an answer. +/// The verdicts and measurements `bytes` record for `identity`, `Pending` for a check it holds no +/// answer of: `None` for anything but a whole record of this version and runtime, for this +/// identity and kernel, whose checksum holds. A device takes of them what [`recalled`] keeps. pub(crate) fn decode( identity: &DriverIdentity, bytes: &[u8], @@ -861,9 +1141,6 @@ pub(crate) fn decode( return None; } let verdicts: [Verdict; Check::COUNT] = std::array::from_fn(|i| Verdict::of_byte(verdicts[i])); - if verdicts.contains(&Verdict::Pending) { - return None; - } let value = |i: usize| i64::from_le_bytes(rest[8 * i..8 * i + 8].try_into().unwrap_or([0; 8])); let measured = Measured { merged: value(0), @@ -875,37 +1152,59 @@ pub(crate) fn decode( } impl Device { - /// As the device is made: its verdicts where a record holds them (settled then), else its - /// checks start on a thread of their own. A record that does not decode is no record. Where - /// the merge check holds without its answer (`DeviceOptions::assume_submissions_merge`), no - /// record is read: the checks run, and keep none. + /// As the device is made: its verdicts where a record holds them, else its checks start on a + /// thread of their own. Of a record, a `Holds` or an `Unchecked` stands ([`recalled`]); a + /// check it holds a `Fails` of, or no answer, runs (the module docs, "Kept"), and the + /// verdicts settle once those answered; where none does, they settle at once. A record that + /// does not decode is no record. Where the merge check holds without its answer + /// (`DeviceOptions::assume_submissions_merge`), no record is read: the checks run, and keep + /// none. pub(crate) fn recall_submit_checks(&self) { let shared = self.shared(); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + if let Some(answers) = ANSWERED.with(std::cell::Cell::take) { + let checks = &shared.submit_checks; + for (check, verdict) in Check::ALL.into_iter().zip(answers) { + checks.set(check, verdict); + } + shared.counts.submit_checks_recalled(); + checks.start(); + checks.settle(None); + return; + } + let none = [Verdict::Pending; Check::COUNT]; if shared.submit_checks.merge_assumed { - self.start_submit_checks(); + self.start_submit_checks([true; Check::COUNT], none); return; } let identity = self.driver_identity(); let name = record_name(&identity); let looked = (shared.shader_cache.content_store()) .load_content(&name, |bytes| decode(&identity, &bytes)); - if let Lookup::Hit((verdicts, measured)) = looked { - let checks = &shared.submit_checks; - for (check, verdict) in Check::ALL.into_iter().zip(verdicts) { - checks.set(check, verdict); - } - checks.set_measured(measured); - checks.start(); - shared.counts.submit_checks_recalled(); - checks.settle(None); + let Lookup::Hit((verdicts, measured)) = looked else { + self.start_submit_checks([true; Check::COUNT], none); + return; + }; + let checks = &shared.submit_checks; + let kept = verdicts.map(|verdict| recalled(verdict).unwrap_or(Verdict::Pending)); + for (check, verdict) in Check::ALL.into_iter().zip(kept) { + checks.set(check, verdict); + } + checks.set_measured(measured); + shared.counts.submit_checks_recalled(); + let open = kept.map(|verdict| verdict == Verdict::Pending); + if open.contains(&true) { + self.start_submit_checks(open, kept); return; } - self.start_submit_checks(); + checks.start(); + checks.settle(None); } - /// Start the checks on a thread of their own, where they have not started. Where the thread - /// cannot start, every verdict is unchecked. - fn start_submit_checks(&self) { + /// Start the checks that are `open` on a thread of their own, where they have not started, + /// the record holding `recorded` (`Pending` for none). Where the thread cannot start, every + /// verdict not answered is unchecked. + fn start_submit_checks(&self, open: [bool; Check::COUNT], recorded: [Verdict; Check::COUNT]) { let checks = &self.shared().submit_checks; if !checks.start() { return; @@ -927,7 +1226,7 @@ impl Device { crate::loader_word::on_a_check_s_thread(); crate::step_aside::mark_a_check_s_thread(crate::step_aside::Counted::Apart); let parts = parts; - run(&parts, made); + run(&parts, made, (open, recorded)); }); if spawned.is_err() { // SAFETY: the pool is the checks' and nothing of it was used. @@ -1032,6 +1331,20 @@ impl Device { 0 => String::new(), tries => format!(", {tries} import tax tries"), }; + let merge_tries = match checks.merge_tries.load(Ordering::Relaxed) { + 0 => String::new(), + tries => format!(", {tries} merge tries"), + }; + let rechecks = match checks.rechecks.load(Ordering::Relaxed) { + 0 => String::new(), + again => format!(", checked again {again} times"), + }; + let stands = |check: Check| match checks.stands(check) { + Some(Stands::Recorded) => ", recorded", + Some(Stands::Life) => ", for the device's life", + Some(Stands::Now) => ", for now", + None => "", + }; let assumed = match checks.merge_assumed { true => " assumed", false => "", @@ -1048,13 +1361,16 @@ impl Device { false => "", }; format!( - "merge {:?}{assumed} ({:.1} us in one call of {MERGED} against {:.1} us apart), import tax \ - {:?} ({:.1} us a submission with {} imports of {} MiB in all held against {:.1} us), \ - {took}{split}{merge_unearned}{unearned}{short}{tax_tries}{longest}{stalled} (floors)", + "merge {:?}{assumed}{} ({:.1} us in one call of {MERGED} against {:.1} us apart), \ + import tax {:?}{} ({:.1} us a submission with {} imports of {} MiB in all held \ + against {:.1} us), {took}{split}{merge_unearned}{unearned}{short}{merge_tries}\ + {tax_tries}{rechecks}{longest}{stalled} (floors)", checks.verdict(Check::Merge), + stands(Check::Merge), us(m.merged), us(m.apart), checks.verdict(Check::ImportTax), + stands(Check::ImportTax), us(m.held), TAX_IMPORTS, TAX_BYTES >> 20, @@ -1078,6 +1394,9 @@ struct Parts { /// The device's allocations, whose work in progress the checks step aside for /// (`step_aside.rs`). allocations: Arc, + /// What tells whether the device's work is quiet, which the checks stand by for + /// ([`Parts::stand_by`]). + work: WorkShare, store: Arc, /// The device's import of host pointers, where it imports them. pointers: Option, @@ -1141,6 +1460,7 @@ impl Parts { loader_word: Arc::clone(&shared.loader_word), checks: Arc::clone(&shared.submit_checks), allocations: Arc::clone(&shared.allocations.allocations), + work: shared.work_share(), store: shared.shader_cache.content_store_share(), pointers: (shared.host_import.as_ref().ok()) .and_then(Importer::pointers) @@ -1203,6 +1523,85 @@ impl Parts { !self.checks.stopping() } + /// Before a round or a submission, stand by until the device's work is quiet + /// (`DeviceShared::work_quiet_for`): none of its batches held or in flight, and no use of its + /// `VkQueue`s under way for [`ROUND_QUIET`], or none since the checks' own last use, which + /// ended by `own`. At most [`STAND_BY_MOST`], and not while a call waits for the verdicts or + /// the checks stop: whether it found the work quiet. + fn stand_by(&self, own: Option) -> bool { + let checks = &*self.checks; + let began = Instant::now(); + loop { + let pause = match self.work.quiet_for() { + Some(unused) + if own + .is_some_and(|own| unused.saturating_add(LOOK_EVERY) >= own.elapsed()) => + { + return true; + } + Some(unused) => match ROUND_QUIET.checked_sub(unused) { + None | Some(Duration::ZERO) => return true, + Some(left) => left, + }, + None => LOOK_EVERY, + }; + if checks.stopping() || checks.awaited() || began.elapsed() >= STAND_BY_MOST { + return false; + } + std::thread::sleep(pause.min(LOOK_EVERY)); + } + } + + /// Take `check`'s `answer`, `first` where it is among the device's first: its verdict (but + /// the merge's where it holds without its answer), its floors and how long it stands. A + /// check again whose tries all split keeps the verdict and floors before it: they tell + /// nothing but the load beside them. Whether the answer earned a record `recorded` does not + /// hold, which it then holds. + fn take( + &self, + check: Check, + answer: Answer, + recorded: &mut [Verdict; Check::COUNT], + first: bool, + ) -> bool { + let checks = &*self.checks; + let at = check.index(); + // A check again answers only while the check stands for now (a device test's forced + // verdict stands for the device's life). + if !first && Stands::of_byte(checks.stands[at].load(Ordering::Acquire)) != Some(Stands::Now) + { + return false; + } + let split = !first && answer.verdict == Verdict::Unchecked && answer.stands == Stands::Now; + // The merge's verdict holds from the device's making where it is assumed. + let assumed = check == Check::Merge && checks.merge_assumed; + if !split && !assumed { + checks.set(check, answer.verdict); + } + if !split { + checks.set_floors(check, answer.floors); + } + checks.stands[at].store(answer.stands.byte(), Ordering::Release); + let earned = answer.stands == Stands::Recorded && recorded[at] != answer.verdict; + if earned { + recorded[at] = answer.verdict; + } + earned + } + + /// Write the device's record of `recorded`, with what the checks measured: not where the + /// merge holds without its answer or the store has no directory. A failed write leaves the + /// verdicts to the device's life alone. + fn record(&self, recorded: [Verdict; Check::COUNT]) { + let checks = &*self.checks; + if checks.merge_assumed || !self.store.has_directory() { + return; + } + let identity = &self.identity; + let bytes = encode(identity, recorded, checks.measured()); + let _ = self.store.write_record_soon(&record_name(identity), bytes); + } + /// Step aside for the device's allocations and frees on other threads before a step that /// allocates, frees, maps or submits (`step_aside.rs`): not while the checks stop or a call /// waits for their verdicts. Counted where it waited. @@ -1233,9 +1632,17 @@ impl Drop for Ends { } } -/// The checks' thread: each check's verdict given as it is known, then the record. Stopped by -/// the device's teardown, it settles what it had not answered `Unchecked` and records nothing. -fn run(parts: &Parts, made: Made) { +/// The checks' thread: each check that is `open` answers, its verdict given as it is known, and +/// the record is written where an answer earned it; the verdicts settle; then each answer that +/// stands for now ([`Stands::Now`]) is checked again later in the device's life +/// ([`recheck_after`]), until none does. `recorded` is what the device's record holds +/// (`Pending` for no answer). Stopped by the device's teardown before its first answers, it +/// settles what it had not answered `Unchecked` and records nothing. +fn run( + parts: &Parts, + made: Made, + (open, recorded): ([bool; Check::COUNT], [Verdict; Check::COUNT]), +) { let checks = &*parts.checks; let started = Instant::now(); parts.step(); @@ -1243,64 +1650,102 @@ fn run(parts: &Parts, made: Made) { checks.settle_unchecked(); return; }; - let ran = measure(parts, &objects); - if checks.stalled() { - // The stalled submission's fence and command buffers are still pending: they go with the - // device's teardown, once it sees it complete ([`SubmitChecks::stop`]). - *lock(&checks.left) = Some(objects); + let mut recorded = recorded; + let Some(mut again) = measure(parts, &objects, open, &mut recorded, true) else { + // The process is exiting, or the device's teardown, its loss or a stalled submission + // stopped the checks: nothing is kept. + end(parts, objects); checks.settle_unchecked(); return; + }; + parts.counts.submit_checks_ran(); + checks.settle(Some(started.elapsed())); + let mut done = 0; + while !checks.merge_assumed && again.contains(&true) && checks.rest(recheck_after(done)) { + done += 1; + checks.rechecks.fetch_add(1, Ordering::Relaxed); + match measure(parts, &objects, again, &mut recorded, false) { + Some(open) => again = open, + None => break, + } + } + end(parts, objects); +} + +/// The checks' objects as their thread ends: left to the device's teardown where a submission of +/// theirs stalled, still pending ([`SubmitChecks::stop`]); else released. +fn end(parts: &Parts, objects: Objects) { + if parts.checks.stalled() { + *lock(&parts.checks.left) = Some(objects); + return; } parts.step(); - let released = objects.release(parts); - let Some((measured, kept)) = ran.filter(|_| released) else { - // The process is exiting, or the device's teardown stopped the checks: nothing is kept. - checks.settle_unchecked(); - return; - }; - checks.set_measured(measured); - parts.counts.submit_checks_ran(); - let verdicts = Check::ALL.map(|check| checks.verdict(check)); - // A failed write, or a store with no directory, leaves the verdicts to the device's life - // alone. - let recorded = !checks.merge_assumed && !verdicts.contains(&Verdict::Pending); - if kept && recorded && parts.store.has_directory() { - let identity = &parts.identity; - let bytes = encode(identity, verdicts, measured); - let _ = parts.store.write_record_soon(&record_name(identity), bytes); - } - checks.settle(Some(started.elapsed())); + objects.release(parts); } -/// Each check in turn, its verdict set as it is known: what they measured, and whether their -/// verdicts may be recorded (no timed check's tries all disagreed, an import tax `Holds` earned -/// its record: [`tax_tried`]); `None` where the process is exiting, or the device's teardown or -/// its loss stopped the checks. -fn measure(parts: &Parts, objects: &Objects) -> Option<(Measured, bool)> { - let checks = &parts.checks; - let (merges, (merged, apart), merge_kept) = merge_tried(checks, || merge(parts, objects))?; - if !checks.merge_assumed { - checks.set(Check::Merge, merges); - } - let (taxed, (held, bare), tax_kept) = tax_tried(checks, || { - checks.tax_tries.fetch_add(1, Ordering::Relaxed); - tax(parts, objects) - })?; - checks.set(Check::ImportTax, taxed); - let measured = Measured { - merged, - apart, - held, - bare, +/// Each check that is `open` in turn, its answer taken as it is known ([`Parts::take`]); then, +/// where an answer earned a record the device's does not hold (`recorded`), the record written +/// again. `first` where these are the device's first answers. Which checks stand for now, to +/// check again; `None` where the process is exiting, or the device's teardown, its loss or a +/// stalled submission stopped the checks. +fn measure( + parts: &Parts, + objects: &Objects, + open: [bool; Check::COUNT], + recorded: &mut [Verdict; Check::COUNT], + first: bool, +) -> Option<[bool; Check::COUNT]> { + let checks = &*parts.checks; + let mut again = [false; Check::COUNT]; + let mut earned = false; + // A check again runs only while its answer stands for now (a device test's forced verdict + // stands for the device's life). + let runs = |check: &Check| { + open[check.index()] && (first || checks.stands(*check) == Some(Stands::Now)) }; - Some((measured, merge_kept && tax_kept)) + for check in Check::ALL.into_iter().filter(runs) { + // Whether each of the answer's tries ran quiet ([`Load::ran_quiet`]). + let quiet = Cell::new(true); + let answer = match check { + Check::Merge => { + let (verdict, floors, kept) = merge_tried(checks, || { + checks.merge_tries.fetch_add(1, Ordering::Relaxed); + merge(parts, objects, &quiet) + })?; + let stands = merge_stands(verdict, kept, quiet.get()); + Answer { + verdict, + floors, + stands, + } + } + Check::ImportTax => { + let (verdict, floors, kept) = tax_tried(checks, || { + checks.tax_tries.fetch_add(1, Ordering::Relaxed); + tax(parts, objects, &quiet) + })?; + let stands = tax_stands(verdict, floors, kept, quiet.get()); + Answer { + verdict, + floors, + stands, + } + } + }; + earned |= parts.take(check, answer, recorded, first); + again[check.index()] = checks.stands(check) == Some(Stands::Now); + } + if earned { + parts.record(*recorded); + } + Some(again) } /// A timed check's verdict and floors over at most [`TRIES`] tries of `once`, and whether they /// may be recorded: the first try whose blocks or phases agree answers. Where none does, the -/// check is `Unchecked` for the device's life and not recorded (load beside the check may have -/// split them, and the next device measures again). `Unchecked`, recorded, where a call was -/// refused (`once` answered `Some(None)`); `None` where the check stops. +/// check is `Unchecked` for now and not recorded (load beside the check may have split them, and +/// it runs again: [`Stands::Now`]). `Unchecked`, recorded, where a call was refused (`once` +/// answered `Some(None)`); `None` where the check stops. pub(crate) fn tried( checks: &SubmitChecks, mut once: impl FnMut() -> Option>, @@ -1319,13 +1764,13 @@ pub(crate) fn tried( Some((Verdict::Unchecked, floors, false)) } -/// The merge's verdict and floors over its tries of `once` ([`tried`]), and whether they may be -/// recorded (the module docs, "Load beside it"). A `Holds` or a `Fails` is recorded only where its -/// try's floors are clear of the load beside it ([`merge_clear`]) and each of [`MERGE_REPEATS`] -/// tries more answers it so again; short of that it answers for the device's life alone, with the -/// floors of its first try, and the next device measures again; a refused call ends the repeats, -/// unrecorded. Tries that all split, or a refused call, answer as [`tried`] does. `None` where the -/// check stops. +/// The merge's verdict and floors over its tries of `once` ([`tried`]), and whether they earned +/// more than now (the module docs, "Load beside it"): a `Holds` or a `Fails` only where its try's +/// floors are clear of the load beside it ([`merge_clear`]) and each of [`MERGE_REPEATS`] tries +/// more answers it so again ([`merge_stands`]: a `Holds` so is recorded, a `Fails` never is); +/// short of that it answers for now, with the floors of its first try; a refused call ends the +/// repeats, unearned. Tries that all split, or a refused call, answer as [`tried`] does. `None` +/// where the check stops. pub(crate) fn merge_tried( checks: &SubmitChecks, mut once: impl FnMut() -> Option>, @@ -1351,14 +1796,14 @@ pub(crate) fn merge_tried( } /// The import tax's verdict and floors over its tries of `once` ([`tried`]), and whether they may -/// be recorded (the module docs, "Load beside it"). A `Holds` stands only where its floors pass -/// the bound [`TAX_MARGIN`] times over ([`tax_clear`]), and is recorded only where each of -/// [`TAX_REPEATS`] tries more answers `Holds` so again; short of the repeats it answers for the -/// device's life alone, with the floors of its first try, and the next device measures again; a -/// refused call ends the repeats, unrecorded. A `Holds` short of the margin, and tries that all -/// split where the last one's floors over all its phases fall short of it, answer `Fails` for the -/// device's life, unrecorded: a cost no try told from the load beside it. Tries that all split -/// past it answer `Unchecked` so. `None` where the check stops. +/// be kept (the module docs, "Load beside it"). A `Holds` stands only where its floors pass the +/// bound [`TAX_MARGIN`] times over ([`tax_clear`]), and is recorded only where each of +/// [`TAX_REPEATS`] tries more answers `Holds` so again; short of the repeats it answers for now, +/// with the floors of its first try; a refused call ends the repeats, unrecorded. A `Holds` short +/// of the margin, and tries that all split where the last one's floors over all its phases fall +/// short of it, answer `Fails` for now, unrecorded: a cost no try told from the load beside it. +/// Tries that all split past it answer `Unchecked` so. A `Fails` kept is never recorded +/// ([`tax_stands`]). `None` where the check stops. pub(crate) fn tax_tried( checks: &SubmitChecks, mut once: impl FnMut() -> Option>, @@ -1390,20 +1835,37 @@ pub(crate) fn tax_tried( Some((verdict, floors, earned)) } -/// One merge try ([`merge_try`]) of one call of [`MERGED`] infos against [`MERGED`] calls. -/// `Some(None)` where a call was refused; `None` where the check stops. -fn merge(parts: &Parts, objects: &Objects) -> Option> { +/// One merge try ([`merge_try`]) of one call of [`MERGED`] infos against [`MERGED`] calls, each +/// round after a stand-by ([`Parts::stand_by`]); `quiet` keeps whether it ran quiet, with the +/// tries before it ([`Load::ran_quiet`]). `Some(None)` where a call was refused; `None` where the +/// check stops. +fn merge(parts: &Parts, objects: &Objects, quiet: &Cell) -> Option> { let mut merged = Vec::with_capacity(ROUNDS); let mut apart = Vec::with_capacity(ROUNDS); + let mut load = Load::default(); + // When the checks' own last use of the queue ended, at the latest. + let mut own = None; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + let lifted = (parts.checks.lifted) + .try_update(Ordering::AcqRel, Ordering::Acquire, |left| { + left.checked_sub(1) + }) + .is_ok(); for round in 0..WARM + ROUNDS { for together in [true, false] { if !parts.goes_on() { return None; } + let found = parts.stand_by(own); + let began = Instant::now(); let Some(calls) = objects.submit_round(parts, together)? else { return Some(None); }; + own = Some(Instant::now()); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + let (found, calls) = lifted_round(lifted, found, calls); if round >= WARM { + load.round(found, nanos(began.elapsed())); match together { true => merged.push(calls.iter().sum()), false => apart.push(std::array::from_fn(|at| calls[at])), @@ -1411,13 +1873,31 @@ fn merge(parts: &Parts, objects: &Objects) -> Option> { } } } + quiet.set(quiet.get() && load.ran_quiet()); Some(Some(merge_try(&merged, &apart))) } +/// A merge round of a try a device test lifts where `lifted` ([`lift_next_merge_tries`]): [`LIFT`] +/// more on its first call, and its stand-by not found quiet. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +fn lifted_round(lifted: bool, found: bool, mut calls: Vec) -> (bool, Vec) { + if lifted { + calls[0] += LIFT; + } + (found && !lifted, calls) +} + +/// `elapsed` in nanoseconds. +fn nanos(elapsed: Duration) -> i64 { + i64::try_from(elapsed.as_nanos()).unwrap_or(i64::MAX) +} + /// One import tax try ([`tax_try`]) of a submission with the [`TAX_IMPORTS`] imports of -/// [`TAX_BYTES`] in all held, and without. `Some(None)` where the device imports no host pointer, -/// the system maps no pages or a call was refused; `None` where the check stops. -fn tax(parts: &Parts, objects: &Objects) -> Option> { +/// [`TAX_BYTES`] in all held, and without, each submission after a stand-by +/// ([`Parts::stand_by`]); `quiet` keeps whether it ran quiet, with the tries before it +/// ([`Load::ran_quiet`]). `Some(None)` where the device imports no host pointer, the system maps +/// no pages or a call was refused; `None` where the check stops. +fn tax(parts: &Parts, objects: &Objects, quiet: &Cell) -> Option> { let Some(pieces) = (0..TAX_IMPORTS) .map(|_| { parts.step(); @@ -1434,6 +1914,9 @@ fn tax(parts: &Parts, objects: &Objects) -> Option> { // One set of imports, made before the first phase that holds them and released after the // last ([`tax_holds`]). let mut imports = Vec::new(); + let mut load = Load::default(); + // When the checks' own last use of the queue ended, at the latest. + let mut own = None; for phase in 0..TAX_PHASES { if !parts.goes_on() { return release_all(parts, imports.drain(..)).and(None); @@ -1451,11 +1934,17 @@ fn tax(parts: &Parts, objects: &Objects) -> Option> { let mut refused = false; for submission in 0..=TAX_SUBMITS { parts.step(); + let found = parts.stand_by(own); + let began = Instant::now(); let Some(submitted) = objects.submit_one(parts) else { return release_all(parts, imports.drain(..)).and(None); }; + own = Some(Instant::now()); match submitted { - Some(nanos) if submission > 0 => times.push(nanos), + Some(nanos) if submission > 0 => { + load.round(found, self::nanos(began.elapsed())); + times.push(nanos); + } Some(_) => {} None => { refused = true; @@ -1471,6 +1960,7 @@ fn tax(parts: &Parts, objects: &Objects) -> Option> { } phases.push(times); } + quiet.set(quiet.get() && load.ran_quiet()); Some(Some(tax_try(&phases))) } @@ -1805,7 +2295,7 @@ impl Objects { } let start = Instant::now(); submitted = raw.queue_submit(queue, infos, fence); - spent.push(i64::try_from(start.elapsed().as_nanos()).unwrap_or(i64::MAX)); + spent.push(nanos(start.elapsed())); if submitted.is_err() { break; } @@ -1966,13 +2456,13 @@ impl Objects { } } - /// Let the objects go, inside a section: whether it ran (`false` once the process is - /// exiting, the objects then left to its end). No submission naming them is pending: each - /// was waited for, or the device was lost, which Vulkan counts as their completion. - fn release(&self, parts: &Parts) -> bool { + /// Let the objects go, inside a section: once the process is exiting, they are left to its + /// end. No submission naming them is pending: each was waited for, or the device was lost, + /// which Vulkan counts as their completion. + fn release(&self, parts: &Parts) { let _held = parts.step_held(); let Some(_busy) = exit_guard::enter() else { - return false; + return; }; let raw = parts.vk(); // SAFETY: no pending submission names them; a null handle is skipped. @@ -1982,7 +2472,6 @@ impl Objects { } release::object(raw, self.pool); } - true } /// The objects a stalled submission names ([`SubmitChecks::stop`]), inside the device's diff --git a/crates/metal2vulkan-runtime/src/tests/drag_submit_bench.rs b/crates/metal2vulkan-runtime/src/tests/drag_submit_bench.rs index 0aeefb49a..d4cd79903 100644 --- a/crates/metal2vulkan-runtime/src/tests/drag_submit_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/drag_submit_bench.rs @@ -32,7 +32,9 @@ //! (`CommandBuffer::submit_returned_time`, the device noting queue times: its planning, any //! hold in a group, and the call), and from there to its GPU start; and why the commits' passes //! left batches (the `WorkCounts::scheduler_at_commit_left_*` counts) and the groups held past -//! a pass for two submissions in flight (`WorkCounts::groups_kept_pending`). And (`DRAG-FRAME`) +//! a pass for two submissions in flight (`WorkCounts::groups_kept_pending`); the device's +//! submission checks' report (`Device::submit_check_report`) heads them and ends them, as the +//! merge check decides whether its batches group. And (`DRAG-FRAME`) //! each frame's whole (medians and 90th percentiles): from its first commit call to the GPU start //! and the GPU end of its last part with work, and its commit calls' time, the committing //! thread's for the frame. A part's time from its own commit call leaves out the commit calls @@ -112,10 +114,11 @@ fn drag_submit_bench() { // Each command buffer's submission's return (`CommandBuffer::submit_returned_time`). device.shared().timing.note_queue_times(); println!( - "DRAG-PATH on {}: completion {:?}, submissions merge {}", + "DRAG-PATH on {}: completion {:?}, submissions merge {}; its submission checks: {}", device.name(), device.compile_device().policy().completion, device.submissions_merge(), + device.submit_check_report(), ); let len = 2 * LISTED * LISTED_BYTES; let ram = Ram::new(len, 0, len); @@ -316,5 +319,10 @@ fn drag_submit_bench() { device.fast_submit_call_every(None); device.leave_calls_from(None); } + println!( + "DRAG-PATH after the measurements: submissions merge {}; its submission checks: {}", + device.submissions_merge(), + device.submit_check_report(), + ); drop(listed); } diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index d0b006a73..749c8a1b8 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -10,13 +10,13 @@ //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. Each device's shader cache is a fresh //! directory, so no record holds its verdicts and its check runs; the two devices the placement -//! test compares find there only a record of the same submission-check answers ([`answering`]). +//! test compares take the same submission-check answers ([`answering`]). use super::blit_holds::{device, options, Scratch}; use crate::address::{PAGE, SPACE_BASE, SPACE_END}; use crate::fresh_pages::FRESH_PAGES_PAST; use crate::in_place::{verdict_index, Access, PagesClass, RowEnds, Verdict as InPlaceVerdict}; -use crate::submit_check::{encode, record_name, Check, Measured, Verdict}; +use crate::submit_check::{answer_next_device, Check, Verdict}; use crate::{ AddressPlacement, Buffer, BufferContents, BufferDescriptor, DebugMessage, Device, DeviceOptions, Error, GpuAddress, MessageSink, ResourceId, ResourceIdKind, ResourceOptions, @@ -24,7 +24,7 @@ use crate::{ }; use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{PixelFormat, TextureUsage}; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -49,43 +49,16 @@ const ANSWERS: [Verdict; Check::COUNT] = [Verdict::Fails, Verdict::Fails]; /// long buffers take no fresh pages (`fresh_pages.rs`). const TAXED: [Verdict; Check::COUNT] = [Verdict::Fails, Verdict::Holds]; -/// A record of submission-check answers for the driver of the device the cfg selects, and its -/// path under a shader cache's directory. -struct AnswersRecord { - answers: [Verdict; Check::COUNT], - bytes: Vec, - under: PathBuf, -} - -impl AnswersRecord { - /// The record of `answers`, its identity and path read from a device made over a cache of its - /// own and dropped before any device that recalls the record is made. - fn new(answers: [Verdict; Check::COUNT]) -> AnswersRecord { - let scratch = Scratch::new("in-place-check-identity"); - let probe = device(&scratch.0); - let identity = probe.driver_identity(); - let path = (probe.shared().shader_cache.content_store().directory()) - .expect("a device over a cache of its own") - .record_path(&record_name(&identity)); - let under = path.strip_prefix(&scratch.0).unwrap().to_owned(); - AnswersRecord { - answers, - bytes: encode(&identity, answers, Measured::default()), - under, - } - } -} - -/// A device over `scratch`'s shader cache that recalls `record`'s answers, written there before -/// it is made, and runs no submission check (`submit_check.rs`): what places the product's long -/// buffers in fresh pages or not (`fresh_pages.rs`). Two devices made so place them alike, where -/// the submission checks each timed under the load beside it can answer apart: a held import -/// measured to cost 1.2 us a submission on one llvmpipe device and 0.3 us on the next, either side -/// of the check's 1 us (`TAX_FLOOR`). -fn answering(scratch: &Scratch, record: &AnswersRecord) -> Device { - let path = scratch.0.join(&record.under); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, &record.bytes).unwrap(); +/// A device over `scratch`'s shader cache that takes `answers` as its submission checks' +/// verdicts, as a record's, and runs no submission check (`submit_check.rs`, +/// `answer_next_device`): what places the product's long buffers in fresh pages or not +/// (`fresh_pages.rs`). Two devices made so place them alike, where the submission checks each +/// timed under the load beside it can answer apart: a held import measured to cost 1.2 us a +/// submission on one llvmpipe device and 0.3 us on the next, either side of the check's 1 us +/// (`TAX_FLOOR`). A record's `Fails` is no answer (the device checks again), so a record could +/// not hold these. +fn answering(scratch: &Scratch, answers: [Verdict; Check::COUNT]) -> Device { + answer_next_device(answers); let device = device(&scratch.0); let counts = device.work_counts(); assert_eq!( @@ -94,10 +67,7 @@ fn answering(scratch: &Scratch, record: &AnswersRecord) -> Device { "the device recalled the written answers and ran no submission check" ); let recalled = Check::ALL.map(|check| device.shared().submit_checks.verdict(check)); - assert_eq!( - recalled, record.answers, - "the recalled submission-check verdicts" - ); + assert_eq!(recalled, answers, "the recalled submission-check verdicts"); device } @@ -132,10 +102,9 @@ fn the_in_place_check_takes_no_range_of_the_metal_space() { .take(lines) .collect() }; - let record = AnswersRecord::new(ANSWERS); let reference = { let scratch = Scratch::new("in-place-check-reference"); - let device = answering(&scratch, &record); + let device = answering(&scratch, ANSWERS); assert!( device.settle_in_place_checks(WAIT), "the reference check answered" @@ -143,7 +112,7 @@ fn the_in_place_check_takes_no_range_of_the_metal_space() { verdicts(&device) }; let scratch = Scratch::new("in-place-check-placement"); - let device = answering(&scratch, &record); + let device = answering(&scratch, ANSWERS); let rest = SPACE_BASE + LOW; // The pool's span is its pages and one guard page, to the space's end. let pool = device @@ -189,12 +158,12 @@ fn the_in_place_check_takes_no_range_of_the_metal_space() { fn the_in_place_check_checks_fresh_pages_where_held_imports_cost_submissions() { let takes = { let scratch = Scratch::new("in-place-check-untaxed"); - let device = answering(&scratch, &AnswersRecord::new(ANSWERS)); + let device = answering(&scratch, ANSWERS); let buffer = device.new_buffer(2 * FRESH_PAGES_PAST, ResourceOptions::shared()); buffer.unwrap().in_fresh_pages() }; let scratch = Scratch::new("in-place-check-taxed"); - let device = answering(&scratch, &AnswersRecord::new(TAXED)); + let device = answering(&scratch, TAXED); assert!( !device.fresh_pages_pay(), "the recalled answers keep long buffers out of fresh pages" @@ -242,13 +211,12 @@ fn the_in_place_check_checks_fresh_pages_where_held_imports_cost_submissions() { #[test] fn an_unchecked_verdict_is_checked_again_where_its_cause_may_pass_and_kept_where_it_lasts() { let scratch = Scratch::new("in-place-check-unmade-pages"); - let record = AnswersRecord::new(ANSWERS); let pointer_reads = |device: &Device| { let checks = &device.shared().in_place; RowEnds::ALL.map(|rows| checks.verdict(PagesClass::Pointer, Access::Reads, rows)) }; let (first, note, first_notes) = { - let device = answering(&scratch, &record); + let device = answering(&scratch, ANSWERS); device.fail_next_host_imports(1); assert!( device.settle_in_place_checks(WAIT), @@ -279,7 +247,7 @@ fn an_unchecked_verdict_is_checked_again_where_its_cause_may_pass_and_kept_where }; let dma_buf_reads = verdict_index(PagesClass::DmaBuf, Access::Reads, RowEnds::InLines); let (second_reads, second_recalled) = { - let device = answering(&scratch, &record); + let device = answering(&scratch, ANSWERS); let recalled = device.shared().in_place.verdicts(); let held = recalled .iter() @@ -335,7 +303,7 @@ fn an_unchecked_verdict_is_checked_again_where_its_cause_may_pass_and_kept_where .count(); (reads, (held, unchecked)) }; - let device = answering(&scratch, &record); + let device = answering(&scratch, ANSWERS); assert_eq!( pointer_reads(&device), second_reads, diff --git a/crates/metal2vulkan-runtime/src/tests/submit_check.rs b/crates/metal2vulkan-runtime/src/tests/submit_check.rs index 0f7a2bd95..a6df4333c 100644 --- a/crates/metal2vulkan-runtime/src/tests/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/submit_check.rs @@ -3,11 +3,14 @@ use crate::in_place::DriverIdentity; use crate::submit_check::{ - apart_floor, decode, encode, merge_clear, merge_tried, merge_try, merge_verdict, record_name, - tax_clear, tax_holds, tax_tried, tax_try, tax_verdict, tried, Measured, SubmitChecks, Timed, - Verdict, MERGED, MERGE_FAILS_CLEAR, MERGE_HOLDS_CLEAR, MERGE_RATIO, MERGE_REPEATS, ROUNDS, - TAX_FLOOR, TAX_MARGIN, TAX_PHASES, TAX_REPEATS, TAX_SUBMITS, TRIES, + apart_floor, decode, encode, merge_clear, merge_stands, merge_tried, merge_try, merge_verdict, + recalled, recheck_after, record_name, tax_clear, tax_holds, tax_stands, tax_tried, tax_try, + tax_verdict, tried, Load, Measured, Stands, SubmitChecks, Timed, Verdict, MERGED, + MERGE_FAILS_CLEAR, MERGE_HOLDS_CLEAR, MERGE_RATIO, MERGE_REPEATS, QUIET_ROUND_MOST, + QUIET_TRY_MOST, RECHECK_EVERY, RECHECK_FIRST, ROUNDS, TAX_FLOOR, TAX_MARGIN, TAX_PHASES, + TAX_REPEATS, TAX_SUBMITS, TRIES, }; +use std::time::Duration; /// The probe's medians (2026-11-07, Mesa 26.2.6 under Linux 7.3.1, MoltenVK 1.4.2 under macOS /// 27.0.1), in nanoseconds: one call of four infos and four calls apart; a submission with one @@ -460,8 +463,8 @@ fn identity(device_id: u32) -> DriverIdentity { } /// A record decodes for its own identity alone, every verdict and measurement as written, and -/// names itself apart from another identity's; a record with a pending verdict, a truncated one -/// and one whose bytes changed decode to nothing. +/// names itself apart from another identity's; a record with no answer of a check holds it +/// pending; a truncated one and one whose bytes changed decode to nothing. #[test] fn a_record_holds_its_identity_s_verdicts() { let (one, other) = (identity(0x15bf), identity(0x1114)); @@ -480,6 +483,117 @@ fn a_record_holds_its_identity_s_verdicts() { let mut changed = bytes.clone(); changed[60] ^= 1; assert_eq!(decode(&one, &changed), None); - let pending = encode(&one, [Verdict::Holds, Verdict::Pending], measured); - assert_eq!(decode(&one, &pending), None); + let pending = [Verdict::Holds, Verdict::Pending]; + let bytes = encode(&one, pending, measured); + assert_eq!(decode(&one, &bytes), Some((pending, measured))); +} + +/// A record's `Holds` and `Unchecked` stand for the device that reads it; its `Fails` is a hint +/// and no answer, as a check it holds none of: the device checks again (the load of one device's +/// checks would otherwise hold every later device of the release to a `Fails`). +#[test] +fn a_recorded_fails_is_no_answer() { + assert_eq!(recalled(Verdict::Holds), Some(Verdict::Holds)); + assert_eq!(recalled(Verdict::Unchecked), Some(Verdict::Unchecked)); + assert_eq!(recalled(Verdict::Fails), None); + assert_eq!(recalled(Verdict::Pending), None); +} + +/// How far each answer stands: a `Holds` earned (clear of the load and repeated, past its margin +/// for the import tax) is recorded, and so is an `Unchecked` of a call refused; a `Fails` clear +/// of the load whose tries each ran quiet stands for the device's life and no further; every other +/// answer stands for now: a `Holds` or a `Fails` short of its record, a `Fails` whose tries did +/// not all run quiet, tries that all split. An import tax `Fails` is clear where a held import +/// adds at most half its bound: 2.1 against 2.2 us, as the RTX 5080's quiet devices measured, but +/// not 0.7 us more where the bound is 1 us. +#[test] +fn an_answer_stands_as_far_as_it_earned() { + let earned = [ + (Verdict::Holds, true, Stands::Recorded), + (Verdict::Holds, false, Stands::Recorded), + (Verdict::Unchecked, true, Stands::Recorded), + (Verdict::Fails, true, Stands::Life), + (Verdict::Fails, false, Stands::Now), + ]; + for (verdict, quiet, stands) in earned { + assert_eq!( + merge_stands(verdict, true, quiet), + stands, + "{verdict:?} quiet {quiet}" + ); + } + for verdict in [Verdict::Holds, Verdict::Fails, Verdict::Unchecked] { + for quiet in [true, false] { + assert_eq!( + merge_stands(verdict, false, quiet), + Stands::Now, + "{verdict:?} unearned" + ); + } + } + let clear = (2_100, 2_200); + let held = (1_900 + TAX_FLOOR, 1_900); + assert_eq!( + tax_stands(Verdict::Holds, held, true, false), + Stands::Recorded + ); + assert_eq!( + tax_stands(Verdict::Unchecked, (0, 0), true, true), + Stands::Recorded + ); + assert_eq!(tax_stands(Verdict::Fails, clear, true, true), Stands::Life); + assert_eq!(tax_stands(Verdict::Fails, clear, true, false), Stands::Now); + assert_eq!( + tax_stands(Verdict::Fails, (1_900, 1_200), true, true), + Stands::Now + ); + assert_eq!(tax_stands(Verdict::Fails, clear, false, true), Stands::Now); + assert_eq!(tax_stands(Verdict::Holds, held, false, true), Stands::Now); + assert_eq!( + tax_stands(Verdict::Unchecked, clear, false, true), + Stands::Now + ); +} + +/// An answer for now is checked again 1, 2, 4 ... 64 s after the one before, then each minute. +#[test] +fn checks_again_wait_twice_as_long_up_to_a_minute_apart() { + let waits: Vec = (0..10).map(recheck_after).collect(); + let seconds = |s: u64| Duration::from_secs(s); + assert_eq!(waits[0], RECHECK_FIRST); + assert_eq!( + waits, + [1, 2, 4, 8, 16, 32, 64, 60, 60, 60].map(seconds).to_vec() + ); + assert_eq!(recheck_after(u32::MAX), RECHECK_EVERY); +} + +/// A try ran quiet where each of its stand-bys found the device's work quiet, no round took past +/// [`QUIET_ROUND_MOST`] and all of them no more than [`QUIET_TRY_MOST`]: the Radeon 780M's quiet +/// tries (rounds of 61 to 104 us, the longest 1.3 ms, 4 to 6 ms a try) did; its loaded ones, +/// which waited 9.4 ms and more for a submission, did not. +#[test] +fn a_try_runs_quiet_within_its_bounds() { + let rounds = |quiet: bool, each: i64, count: usize| { + let mut load = Load::default(); + for _ in 0..count { + load.round(quiet, each); + } + load + }; + // A merge try's timed rounds, of both forms. + let count = 2 * ROUNDS; + assert!(rounds(true, 64_000, count).ran_quiet(), "a quiet try"); + assert!( + !rounds(false, 64_000, count).ran_quiet(), + "a stand-by not found quiet" + ); + let mut long = rounds(true, 64_000, count); + long.round(true, 9_400_000); + assert!(!long.ran_quiet(), "a round of 9.4 ms"); + let mut longest = rounds(true, 64_000, count); + longest.round(true, QUIET_ROUND_MOST); + assert!(longest.ran_quiet(), "a round at the bound"); + let slow = rounds(true, QUIET_TRY_MOST / count as i64 + 1, count); + assert!(!slow.ran_quiet(), "a try past its bound in all"); } diff --git a/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs b/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs index 4b87aa52c..73b25397a 100644 --- a/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs @@ -1,6 +1,6 @@ //! The device's submission checks (`submit_check.rs`) on the device the cfg selects: they answer, -//! a second device of the same driver reads their record and runs none, and the paths they choose -//! follow their verdicts alone. +//! a second device of the same driver reads their record and runs those it holds, and the paths +//! they choose follow their verdicts alone. //! //! - **They answer.** A device made over a fresh shader cache runs its checks once //! (`WorkCounts::submit_checks_run`), each verdict an answer (never pending once settled), their @@ -8,10 +8,12 @@ //! (`device_checks`), and their commands among none of the device's (`commands_recorded`: a //! device that ran them recorded the copies one that recalled them did, besides its priming's, //! which a device made again on what stays loaded leaves out); a later device over the -//! same cache recalls them -//! (`submit_checks_recalled`), runs none, and holds the verdicts of the last device that ran -//! them: the first's, or, where load split its tries or its import tax answered `Holds` short -//! of a record and nothing was recorded, those of the next device that ran them. +//! same cache recalls each answer the first recorded (`submit_checks_recalled`) and checks again +//! each other, a `Fails` among them: a record's `Fails` is no answer +//! ([`a_recorded_fails_is_checked_again`]). +//! - **Load lifts an answer for now.** A merge answer whose tries load lifted is checked again +//! in the device's life, which comes to the answer of tries clear of it and records no `Fails` +//! ([`a_lifted_merge_answer_is_checked_again`]). //! - **No remap under an import.** The checks map no page over a live import of it: they make and //! bind no buffer, and every import of theirs is freed by the time they answer //! ([`a_device_s_checks_map_no_pages_over_a_live_import`]). @@ -31,7 +33,10 @@ use super::blit_holds::{Scratch, WAIT}; use crate::fresh_pages::FRESH_PAGES_PAST; -use crate::submit_check::{record_name, Check, Verdict, MERGED, TAX_IMPORTS}; +use crate::submit_check::{ + decode, encode, lift_next_merge_tries, record_name, Check, Measured, Stands, Verdict, MERGED, + MERGE_REPEATS, TAX_IMPORTS, +}; use crate::tests::SETTLE; use crate::{ CommandBufferStatus, Device, DeviceKind, DeviceOptions, EventRef, LayerSetting, @@ -118,7 +123,7 @@ fn the_checks_answer_once_and_a_second_device_recalls_them() { let counts = first.work_counts(); // The copies besides its priming's, which a device made again on what stays loaded leaves // out. - let mut copies = counts.commands_recorded.cmd_copy_buffer - primed; + let copies = counts.commands_recorded.cmd_copy_buffer - primed; assert_eq!(counts.submit_checks_run, 1); assert_eq!(counts.submit_checks_recalled, 0); assert!( @@ -148,50 +153,213 @@ fn the_checks_answer_once_and_a_second_device_recalls_them() { // it) as it goes, so the second is a new device over the same directory, as a later // process's would be. let identity = first.driver_identity(); + let recorded = recorded_of(&first); drop(first); - // The verdicts of the last device that ran the checks, which its record holds where it wrote - // one (a device whose tries split, or whose import tax `Holds` fell short of its margin or of - // its record, writes none, and the next runs them again). - let mut ran = answered; - let start = std::time::Instant::now(); - loop { - let (second, primed) = device_primed(&scratch.0); - assert!( - second.settle_submit_checks(SETTLE), - "the second device never answered" + // The second recalls each answer the first recorded, and checks again each other: a `Fails` + // (never recorded), and an answer for now (tries split or short of their record). + let (second, primed) = device_primed(&scratch.0); + assert!( + second.settle_submit_checks(SETTLE), + "the second device never answered" + ); + let counts = second.work_counts(); + let checks = &second.shared().submit_checks; + let tries = [ + checks.merge_tries.load(Ordering::Relaxed), + checks.tax_tries.load(Ordering::Relaxed), + ]; + println!( + "{} again, the first's answers recorded {recorded:?}: {}", + second.name(), + second.submit_check_report() + ); + let name = record_name(&identity); + assert_eq!( + counts.submit_checks_recalled, + u64::from(recorded.iter().any(Option::is_some)), + "the record {name} was read where the first recorded an answer: found at {:?}, \ + identities {identity:?} and {:?}", + files_named(&scratch.0, &name), + second.driver_identity(), + ); + for (at, check) in Check::ALL.into_iter().enumerate() { + match recorded[at] { + Some(verdict) => { + assert_eq!( + tries[at], 0, + "{check:?}: a recorded answer was checked again" + ); + assert_eq!( + checks.verdict(check), + verdict, + "{check:?}: the recorded answer" + ); + } + None => assert!( + tries[at] > 0, + "{check:?}: an answer that earned no record was not checked again" + ), + } + } + if recorded.iter().all(Option::is_some) { + assert_eq!(counts.submit_checks_run, 0); + assert_eq!(counts.submit_check_calls, 0); + assert_eq!(verdicts(&second), answered); + assert_eq!( + counts.commands_recorded.cmd_copy_buffer - primed, + copies, + "the device that ran the checks recorded other copies than one that recalled them" ); - let counts = second.work_counts(); - if counts.submit_checks_recalled == 1 { - assert_eq!(counts.submit_checks_run, 0); - assert_eq!(counts.submit_check_calls, 0); - assert_eq!(verdicts(&second), ran); - assert_eq!( - counts.commands_recorded.cmd_copy_buffer - primed, - copies, - "the device that ran the checks recorded other copies than one that recalled them" - ); + } +} + +/// Each answer of `device`'s checks that earned a record (`Stands::Recorded`), by check. +fn recorded_of(device: &Device) -> [Option; Check::COUNT] { + let checks = &device.shared().submit_checks; + Check::ALL.map(|check| { + (checks.stands(check) == Some(Stands::Recorded)).then(|| checks.verdict(check)) + }) +} + +/// A record's `Fails` is a hint and no answer (`submit_check.rs`, "Kept"): a device that reads a +/// record holding a `Fails` of each check, as an earlier device's checks under load could have +/// written, checks both again; one that reads a merge `Holds` and an import tax `Fails` takes the +/// `Holds` and checks the import tax again. Printed (`STALE-FAILS`). +#[test] +fn a_recorded_fails_is_checked_again() { + let scratch = Scratch::new("submit-check-stale-fails"); + let first = device(&scratch.0); + assert!( + first.settle_submit_checks(SETTLE), + "the checks never answered" + ); + let identity = first.driver_identity(); + let path = (first.shared().shader_cache.content_store().directory()) + .expect("a device over a cache of its own") + .record_path(&record_name(&identity)); + // Its own record, where it wrote one, is in place once it is gone. + drop(first); + for planted in [ + [Verdict::Fails, Verdict::Fails], + [Verdict::Holds, Verdict::Fails], + ] { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, encode(&identity, planted, Measured::default())).unwrap(); + let device = device(&scratch.0); + assert!( + device.settle_submit_checks(SETTLE), + "the checks never answered" + ); + let checks = &device.shared().submit_checks; + let tries = [ + checks.merge_tries.load(Ordering::Relaxed), + checks.tax_tries.load(Ordering::Relaxed), + ]; + println!( + "STALE-FAILS {} read {planted:?}: {}", + device.name(), + device.submit_check_report() + ); + assert_eq!( + device.work_counts().submit_checks_recalled, + 1, + "the planted record was not read" + ); + for (at, check) in Check::ALL.into_iter().enumerate() { + match planted[at] { + Verdict::Fails => { + assert!( + tries[at] > 0, + "{check:?}: a recorded Fails was taken as its answer" + ); + assert!( + checks.stands(check).is_some(), + "{check:?}: checked again, it gave no answer" + ); + } + verdict => { + assert_eq!( + tries[at], 0, + "{check:?}: a recorded {verdict:?} was checked again" + ); + assert_eq!(checks.verdict(check), verdict); + } + } + } + drop(device); + } +} + +/// A merge answer whose tries the load beside them lifted stands only for now: the device checks +/// again later in its life, takes the answer of tries clear of that load, and records no `Fails` +/// (`submit_check.rs`, "Load beside it", "Answers for now"). The load is the one the Radeon +/// 780M's checks met beside other jobs on its host: one call of every round of both forms about +/// 70 us longer, which `lift_next_merge_tries` adds to each try of the device's first merge +/// answer (`LIFT`), each of them read as not quiet. A device of the same driver made before it +/// over a cache of its own gives the answer the lifted one comes to. Printed (`LIFTED`). +#[test] +fn a_lifted_merge_answer_is_checked_again() { + let quiet = Scratch::new("submit-check-unlifted"); + let reference = device(&quiet.0); + assert!( + reference.settle_submit_checks(SETTLE), + "the checks never answered" + ); + let scratch = Scratch::new("submit-check-lifted"); + lift_next_merge_tries(1 + MERGE_REPEATS as u32); + let device = device(&scratch.0); + assert!( + device.settle_submit_checks(SETTLE), + "the checks never answered" + ); + let checks = &device.shared().submit_checks; + let first = (checks.verdict(Check::Merge), checks.stands(Check::Merge)); + println!( + "LIFTED {} first: {}", + device.name(), + device.submit_check_report() + ); + assert_eq!( + first.1, + Some(Stands::Now), + "a lifted answer stood past now: {first:?}" + ); + // Within the first checks again, the device comes to the answer the device beside it gives. + let deadline = Instant::now() + WAIT; + loop { + let expected = reference.shared().submit_checks.verdict(Check::Merge); + let rechecked = checks.rechecks.load(Ordering::Relaxed) > 0; + if rechecked && checks.verdict(Check::Merge) == expected { break; } - if counts.submit_checks_run == 1 { - println!("{} again: {}", second.name(), second.submit_check_report()); - ran = verdicts(&second); - copies = counts.commands_recorded.cmd_copy_buffer - primed; - } - if start.elapsed() >= WAIT { - let name = record_name(&second.driver_identity()); - let found = files_named(&scratch.0, &name); - let statistics = second.shader_cache_statistics(); - panic!( - "no device recalled the record {name}: found at {found:?}; the second device's \ - cache rejected {} and failed {} reads; identities {:?} and {:?}", - statistics.rejected, - statistics.read_failures, - identity, - second.driver_identity(), - ); - } - drop(second); - std::thread::sleep(std::time::Duration::from_millis(50)); + assert!( + Instant::now() < deadline, + "the lifted device kept {:?} where the other answers {expected:?}: {}; the other: {}", + checks.verdict(Check::Merge), + device.submit_check_report(), + reference.submit_check_report(), + ); + std::thread::sleep(Duration::from_millis(10)); + } + println!( + "LIFTED {} then: {}; the device beside it: {}", + device.name(), + device.submit_check_report(), + reference.submit_check_report() + ); + // Its record, where it wrote one, holds no merge `Fails`. + let path = (device.shared().shader_cache.content_store().directory()) + .expect("a device over a cache of its own") + .record_path(&record_name(&device.driver_identity())); + let identity = device.driver_identity(); + drop(device); + if let Ok(bytes) = std::fs::read(&path) { + let (verdicts, _) = decode(&identity, &bytes).expect("the device's record decodes"); + assert_ne!( + verdicts[0], + Verdict::Fails, + "the record holds the merge's Fails" + ); } } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index dad44adbb..7aed45e2c 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 525; /// 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 = 2534; +pub const RUNTIME_VERSION: u32 = 2538; /// 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/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 3a8e1c45b..caab0dda2 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -35,7 +35,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | A blend into a packed 16-bit attachment the device renders through its word view (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080; `WordAttachment`), which the function computes in the interlocked storage form, reads the attachment's codes, where Metal's tile holds the pass's clear and each earlier blend's result as a `half`, finer; under fast math it also sums a few states otherwise than Metal. Every device rendering such an attachment. | The in-shader blend over the codes (no switch) | **Not built yet:** the extended-range attachments' `half` shadow (`render/extended_shadow.rs`, `VariantKey::extended_shadows`) taken by word attachments: the runtime's shadow start and end, its load of the codes and the clear's halves, and the word's shadowed variant in `lower::fragment::fetch`, for a single-sampled pass and a multisampled one (an extended-range color's shadow holds per sample, from the pass's clear). Fast math's regrouped sums have no model | One code: without fast math exact over a loaded attachment (the 2,891 states of the M3 sweep, every channel), under fast math 3,527 of 94,732,288 channels a code apart; after a clear or an earlier blend in the pass, a code apart where the two readings store different codes. `DeviceColorConversion` (`device-color-conversion`) | Not measured. Expected from the shadow's form: an `R16G16B16A16_SFLOAT` image of the pass's extent per such color (8 bytes a pixel, 16.6 MB at 1920x1080), set at the draw it starts by a fill or a load dispatch, and an 8-byte storage read and write per blended fragment inside the interlock beside the word's | | 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. The compressed image lies in the heap only where the heap's answer holds it (`heap_answers = HeapAnswerPolicy::Device`, the next row). This 2048x2048 texture's does not under either answer policy, so it takes the linear image under either compression value: a clear 963.5 us against 958.4 us under `heap_answers = HeapAnswerPolicy::Metal`, 955.3 us against 971.4 us under the default, the copy 488-496 us | | A heap texture whose image of the route the device takes for it needs more bytes or a coarser alignment of the heap than Metal's answer (each of a guest compositor's 22 heap shapes, `RGBA16Float` 2D arrays of one slice and 2D textures to 456x255: on ANV, whose compressed images align to 64 KiB; on the RTX 3090 at 1024; on the RX 7900 XTX at 256 to 64 KiB, where Metal answers 128 for each but the 299x299 array's 16 KiB): the size query (`heapTextureSizeAndAlign`) answers the larger of Metal's answer and that image's, and the texture lies in that image in the heap's bytes. A `Shared` texture's answer also holds the linear image a heap over host pages binds for it. Its alignment is the device's up to a heap's memory's own, 256 KiB, past which no image binds there (on the RX 7900 XTX, 128 KiB for a depth image and 256 KiB for a 4-sample render target past 128 texels a side). Where that image's alignment is past 256 KiB, or past both 4 KiB and the texture's size, the texture's image that a 4 KiB alignment holds takes its place (host-transfer usage, else linear), the answer that one's; else Metal's answer, as under the switch. A multisample texture takes it too and lies in its image in the heap's bytes, in the driver's layout of its samples, where under the switch it is a shadow of its samples in Metal's tiles (`heap_placed_targets`: a frame's 4-sample `RGBA16Float` and `Depth32Float` targets placed in a tracked `Private` heap). Metal's measured answers (4:2:2, one-plane YCbCr, two-plane extended-range, `X32_Stencil8`, `BlockWritesOnly` textures) and textures whose image lies in memory of its own keep Metal's answer. The runtime's choice: no pipeline differs. | `heap_answers = HeapAnswerPolicy::Device` | `heap_answers = HeapAnswerPolicy::Metal`: Metal's answer; the texture lies in an image that fits it (host-transfer usage, else linear: `heap-texture-host-transfer`, `heap-texture-linear`), else is a shadow of the heap's bytes in Metal's tiles, copied in before and out after the commands that use it (`shadowed-texture`) | A heap holds fewer such textures than Metal's: of the 22 shapes, the small arrays answer 4096 bytes where Metal answers 128 to 2176 (on ANV and the XTX; the XTX's 1x1 answers 256), and the 22 answers take 3769962 bytes of heaps placed one after another on ANV and 4155498 on the XTX, against Metal's 3656426 (`heap_texture_images`, `HEAP-COUNT`). A program that places a heap's resources by sizes of its own rather than the query's may overlap the texture with its neighbour; Metal's answer differs by GPU too (65536 on an AMD Radeon Pro 5300M, 4096 on an Intel UHD 630, 128 on an M3). `HeapTextureLargerThanMetal` (`heap-texture-larger-than-metal`), announced once per device; `tests::heap`, `tests::heap_placed_targets`, `heap_shadow_costs::heap_texture_images` | Of the 22 shapes made in heaps under the switch (`heap_texture_images`), on ANV (Iris Xe of RPL-P) 14 lie in an image put in place of their first one and 7 are shadows in Metal's tiles; on the RX 7900 XTX (RADV) 1 and 8, every other answer Metal's; under the default none on either. ANV (`heap_shadow_costs::heap_texture_shadow_costs`), a 1x1 `RGBA16Float` array held as a shadow: a frame that clears it and blits it 34.7 us in the heap against 8.2 us outside | -| 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 and at most 16 ms of their queues' expected GPU runs summed (`GROUP_RUN`, `command_buffer/group.rs`: a kernel job that a timeout ends as a whole, as Linux's amdgpu ends one past 2 s by default, never carries more of the others' expected work than that), only the last signalling the queue's timeline, on a device whose own check finds a submission that signals nothing merged into the next (`submit_check.rs`, once per driver, release and kernel: one `vkQueueSubmit` of four empty infos against four calls of one, merged where the one costs at most 0.6 of the four; Mesa 26.2.6's RADV on the Radeon 780M, the RX 7900 XTX and the RX 550 at 0.33-0.38, ANV on the Iris Xe of RPL-P at 0.39, MoltenVK 1.4.2 on the M3 Max at 0.98; a device whose check has not answered, or that does not merge, 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. Nor does an unshared queue's batch (`Device::new_command_queue_unshared`) on a `VkQueue` whose other queues' work is held back for it (`UnsharedIsolationPolicy::Bounded`, the default), and no group is kept there while earlier work runs (below): on RADV, ANV and lavapipe, whose one graphics `VkQueue` every command queue shares, a live unshared queue so keeps no group of any queue. Each batch on a `VkQueue` whose batches group that goes in a kernel submission of its own counts once by why (`WorkCounts::batches_alone_unshared` and kin), and `WorkCounts::batches_of_unshared_queues` counts the unshared queues' batches under either value. So does a batch whose queue's expected run is unknown (none of its batches seen complete yet) or would take the group past 16 ms (`WorkCounts::group_ends_long`), leading the next group where its own run is within the bound; a queue's expected GPU run follows its command buffers' own GPU times by their timestamps (raised at once by a longer one, halved toward a shorter one), which other `VkDevice`s' work on the GPU does not lengthen; with `DeviceOptions::gpu_times_from_host` it follows those host times, which hold other clients' work on the GPU too, so under contention there a queue's batches may stop grouping. 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; nor are they kept where the scheduler's thread runs next a submission handler of another queue's command buffer (one a pass that settled a switch of storage forms keeps; the thread hands every other pass's to the device's handler threads, where none holds its passes back): they go first, as Metal schedules a queue's command buffers whatever another queue's handler does (an M3 Max, probe `cross_queue_handler_waits`); 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 batch a committing thread submits (`CommandBuffer::commit_and_submit`) goes alone where its `VkQueue` runs at most one earlier submission not seen complete, as the pass that held it would send the group at once; where two or more run it is left to the scheduler's thread, which holds it. 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; but a command buffer the program marks to join the next (`CommandBuffer::set_completion_joins_next`, a runtime extension the consumer sets on the parts of one of its own command buffers whose completion nothing observes) groups as under the default, on a device whose check finds the merge and only there: its batches wait in the group within the pass that found them ready (no group is kept past its pass), the first batch of its `VkQueue` behind them that is not marked goes last in the group, which then goes at once (`WorkCounts::group_ends_closed`), so that one is seen complete at its own end and never held back, and its check runs with theirs; a marked batch held alone whose group went at the pass's end counts `WorkCounts::batches_held_alone_unkept` | 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), at most 16 ms of their expected runs, 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. Measured in the consumer's macOS 26.7.2 guest walks on RADV at ca6259f7d1, the lateness of command buffers seen complete after a later one's GPU end was, at the 99th percentile, 18.4 ms against `Exact`'s 2.1 ms (60 ms at most) on the Radeon 780M and 5.1 ms against 2.4 ms (17.5 ms at most) on the RX 7900 XTX, where the consumer's Metal oracles (an M3 Max under macOS 27.0.1, two x86 Macs under 26.7.1) ran a completed handler at most 0.28 ms after its command buffer's GPU end at the 99th percentile. The bounds are on expected runs, so a later batch that runs longer than its queue's recent ones makes the members before it late by its actual run, which no bound set ahead of the run can cap. `CompletionPolicy::Exact` adds none of this lateness: each command buffer is seen complete at its own end. 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. A batch a committing thread submits alone (RADV, Mesa 26.2.6, RX 7900 XTX, whose check finds submissions merged; two rounds each against the form that left every batch that may wait in a group to the scheduler's thread, `tests::completion_latency`): a checked fill's `commit_and_submit` to its submission handler p50 30.4-32.8 us, p90 32.3-35.9, p99 48.8-57.8 against 36.2-55.7, 56.4-176.3 and 112.1-198.5, the call returning after its submission (32-34 us against 4-8); committed 2 ms apart between two shapes of `commit`, its commit to submission p50 31.9-36.1 us, p90 102.6-135.7 against 39.2-50.1 and 152.1-169.7, and the `commit`s beside it alike (p50 32.1-47.3 us against 38.9-46.7, the scheduler thread's wake p50 4.0-4.5 us against 4.1), as the committing thread wakes that thread after a batch it submitted alone, as the batch's hand-off to it would have. On lavapipe, whose check finds no merge, the two forms alike, the scheduler's thread woken alike (a checked fill's p50 12.5-13.4 us against 12.4-13.4). The bound on a group's expected runs (`GROUP_RUN`, 16 ms; RADV, Mesa 26.2.6, Radeon 780M, `frame_costs::frame_costs_over_imports`, one run with it and one without on one host at a load of 11 to 14, each leg twice): grouped `vkQueueSubmit` calls a frame 22.3-22.5 against 23.9-24.8 with 260 host imports (calls in all 23.8-24.4 against 25.4-26.5), 17.0 against 17.0 with 520, 17.2-17.5 against 17.3-17.4 in the guest's shape; no group went for a batch's expected run (`group_ends_long` 0.0 a frame). | +| 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 and at most 16 ms of their queues' expected GPU runs summed (`GROUP_RUN`, `command_buffer/group.rs`: a kernel job that a timeout ends as a whole, as Linux's amdgpu ends one past 2 s by default, never carries more of the others' expected work than that), only the last signalling the queue's timeline, on a device whose own check finds a submission that signals nothing merged into the next (`submit_check.rs`, once per driver, release and kernel where it finds the merge, at each device's making where it does not, a `Fails` never recorded, and again in the device's life, 1, 2, 4 ... 64 s after its first answer and then each minute, where load beside its tries left the answer open: one `vkQueueSubmit` of four empty infos against four calls of one, merged where the one costs at most 0.6 of the four; Mesa 26.2.6's RADV on the Radeon 780M, the RX 7900 XTX and the RX 550 at 0.33-0.38, ANV on the Iris Xe of RPL-P at 0.39, MoltenVK 1.4.2 on the M3 Max at 0.98; a device whose check has not answered, or that does not merge, takes the ungrouped form under either value of the switch, and one whose check answers `Holds` later in its life groups from then): 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. Nor does an unshared queue's batch (`Device::new_command_queue_unshared`) on a `VkQueue` whose other queues' work is held back for it (`UnsharedIsolationPolicy::Bounded`, the default), and no group is kept there while earlier work runs (below): on RADV, ANV and lavapipe, whose one graphics `VkQueue` every command queue shares, a live unshared queue so keeps no group of any queue. Each batch on a `VkQueue` whose batches group that goes in a kernel submission of its own counts once by why (`WorkCounts::batches_alone_unshared` and kin), and `WorkCounts::batches_of_unshared_queues` counts the unshared queues' batches under either value. So does a batch whose queue's expected run is unknown (none of its batches seen complete yet) or would take the group past 16 ms (`WorkCounts::group_ends_long`), leading the next group where its own run is within the bound; a queue's expected GPU run follows its command buffers' own GPU times by their timestamps (raised at once by a longer one, halved toward a shorter one), which other `VkDevice`s' work on the GPU does not lengthen; with `DeviceOptions::gpu_times_from_host` it follows those host times, which hold other clients' work on the GPU too, so under contention there a queue's batches may stop grouping. 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; nor are they kept where the scheduler's thread runs next a submission handler of another queue's command buffer (one a pass that settled a switch of storage forms keeps; the thread hands every other pass's to the device's handler threads, where none holds its passes back): they go first, as Metal schedules a queue's command buffers whatever another queue's handler does (an M3 Max, probe `cross_queue_handler_waits`); 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 batch a committing thread submits (`CommandBuffer::commit_and_submit`) goes alone where its `VkQueue` runs at most one earlier submission not seen complete, as the pass that held it would send the group at once; where two or more run it is left to the scheduler's thread, which holds it. 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; but a command buffer the program marks to join the next (`CommandBuffer::set_completion_joins_next`, a runtime extension the consumer sets on the parts of one of its own command buffers whose completion nothing observes) groups as under the default, on a device whose check finds the merge and only there: its batches wait in the group within the pass that found them ready (no group is kept past its pass), the first batch of its `VkQueue` behind them that is not marked goes last in the group, which then goes at once (`WorkCounts::group_ends_closed`), so that one is seen complete at its own end and never held back, and its check runs with theirs; a marked batch held alone whose group went at the pass's end counts `WorkCounts::batches_held_alone_unkept` | 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), at most 16 ms of their expected runs, 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. Measured in the consumer's macOS 26.7.2 guest walks on RADV at ca6259f7d1, the lateness of command buffers seen complete after a later one's GPU end was, at the 99th percentile, 18.4 ms against `Exact`'s 2.1 ms (60 ms at most) on the Radeon 780M and 5.1 ms against 2.4 ms (17.5 ms at most) on the RX 7900 XTX, where the consumer's Metal oracles (an M3 Max under macOS 27.0.1, two x86 Macs under 26.7.1) ran a completed handler at most 0.28 ms after its command buffer's GPU end at the 99th percentile. The bounds are on expected runs, so a later batch that runs longer than its queue's recent ones makes the members before it late by its actual run, which no bound set ahead of the run can cap. `CompletionPolicy::Exact` adds none of this lateness: each command buffer is seen complete at its own end. 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. A batch a committing thread submits alone (RADV, Mesa 26.2.6, RX 7900 XTX, whose check finds submissions merged; two rounds each against the form that left every batch that may wait in a group to the scheduler's thread, `tests::completion_latency`): a checked fill's `commit_and_submit` to its submission handler p50 30.4-32.8 us, p90 32.3-35.9, p99 48.8-57.8 against 36.2-55.7, 56.4-176.3 and 112.1-198.5, the call returning after its submission (32-34 us against 4-8); committed 2 ms apart between two shapes of `commit`, its commit to submission p50 31.9-36.1 us, p90 102.6-135.7 against 39.2-50.1 and 152.1-169.7, and the `commit`s beside it alike (p50 32.1-47.3 us against 38.9-46.7, the scheduler thread's wake p50 4.0-4.5 us against 4.1), as the committing thread wakes that thread after a batch it submitted alone, as the batch's hand-off to it would have. On lavapipe, whose check finds no merge, the two forms alike, the scheduler's thread woken alike (a checked fill's p50 12.5-13.4 us against 12.4-13.4). The bound on a group's expected runs (`GROUP_RUN`, 16 ms; RADV, Mesa 26.2.6, Radeon 780M, `frame_costs::frame_costs_over_imports`, one run with it and one without on one host at a load of 11 to 14, each leg twice): grouped `vkQueueSubmit` calls a frame 22.3-22.5 against 23.9-24.8 with 260 host imports (calls in all 23.8-24.4 against 25.4-26.5), 17.0 against 17.0 with 520, 17.2-17.5 against 17.3-17.4 in the guest's shape; no group went for a batch's expected run (`group_ends_long` 0.0 a 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 GPU start, written at the top of the pipe, waits behind that end barrier until 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 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), or held its `VkQueue` for over 2 ms from the submission of a batch that waited on the GPU for another `VkQueue`'s work (an `MTLEvent`'s signal, the tracker's wait, new resources' first work) to its own GPU end, 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`. Under either value, as a queue is made, it takes the round robin's `VkQueue` the fewest live command queues hold, of those no unshared queue holds, in turn among equals, and an unshared queue one no command queue holds where one is free (one pass over the `VkQueue`s' counts; one that finds none shares the one the fewest hold, `WorkCounts::unshared_queues_sharing_a_vk_queue`). 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 (the fewest live queues' as above), 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 | diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 140df6aad..f4fe21831 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -424,8 +424,11 @@ released: does. A blit whose released buffer the device cannot import again (out of memory) is refused. - An import of the pointer, on a device whose held pointer imports add to every submission's cost, - as the device checks once per driver, release and kernel (its import tax check, which holds 32 - imports of its own pages through timed submissions; RADV and ANV on i915 pay it). The new import + as the device checks (its import tax check, which holds 32 imports of its own pages through + timed submissions; RADV and ANV on i915 pay it): once per driver, release and kernel where it + finds that cost, at each device's making where it does not (an answer that no import costs is + never recorded), and again in the device's life where load beside its tries left the answer + open. The new import at the same pointer reads the pages the kept one did: `HostMemory::new`'s contract keeps the caller's pages mapped there, with the same backing, while the buffer lives. Buffers made before the check answered keep their imports. A blit whose released buffer the device cannot import