diff --git a/crates/metal2vulkan-runtime/src/in_place.rs b/crates/metal2vulkan-runtime/src/in_place.rs index dc4a8c31c..989ddddf6 100644 --- a/crates/metal2vulkan-runtime/src/in_place.rs +++ b/crates/metal2vulkan-runtime/src/in_place.rs @@ -30,7 +30,7 @@ //! textures that render, where the check shows a pass's load and store and the feedback loop //! moves leaving every byte alone too, whatever a linear image costs the GPU: a texture over the //! caller's pages is the GPU's to work on there, as a Mac's GPU works on them. The check -//! (`in_place_check.rs`) runs once per driver and release, per memory class ([`PagesClass`]) and +//! (`in_place_check.rs`) runs once per driver and its version, per memory class ([`PagesClass`]) and //! access ([`Access`]), and its verdicts are kept in the shader cache's content records //! ([`record_name`]); a class and access it did not pass keep the shadow. //! - **Which textures** ([`in_place`]): those whose declared usage (as Metal reports it, an @@ -44,9 +44,14 @@ //! Elsewhere the texture is a shadow (`shadow.rs`), its notice naming why ([`ShadowCause`]) and //! counted by cause (`WorkCounts::host_texture_shadows_*`, and those that render apart). //! - **Before the verdict.** A texture made before its class's verdict for its access is known -//! waits for nothing: it is a shadow ([`ShadowCause::CheckPending`], counted apart). The first -//! such texture starts the check on a thread of its own; a device whose record holds the -//! verdicts knows them as it is made, and starts none. +//! starts the check on a thread of its own, unless it started, and waits for that verdict, up to +//! [`VERDICT_WAIT`] (`WorkCounts::in_place_verdicts_waited` counts the textures whose wait +//! ended with it): a texture made as a program starts, a compositor's framebuffer among them, +//! would otherwise be a shadow for its life. The wait is the check's rounds of the class and +//! access, and of those before them, once per driver (each round's submission waiting, as an +//! internal one does, for the work submitted before it on the device's first `VkQueue`). Past +//! it the texture is a shadow ([`ShadowCause::CheckPending`], counted apart). A device whose +//! record holds the verdicts knows them as it is made, and starts none. //! - **Visibility.** A command reads the image's texels in the memory a buffer over the same pages //! reads: the pages' host-visible, host-coherent import (a dma-buf's own import is of the same //! memory type). So a CPU write reaches a command through the image as it reaches the buffer's @@ -328,6 +333,11 @@ pub(crate) fn in_place( } } +/// The longest a texture over host pages waits as it is made for its class's verdict for its +/// access while the device's check runs (the module docs): past it, the texture is a shadow +/// ([`ShadowCause::CheckPending`]). +pub(crate) const VERDICT_WAIT: Duration = Duration::from_secs(5); + /// A device's check verdicts (`DeviceShared::in_place`): one per class and access /// ([`VERDICTS`]), and whether its check started and settled. pub(crate) struct InPlaceChecks { @@ -382,6 +392,27 @@ impl InPlaceChecks { /// Give `class` its verdict for `access`. pub(crate) fn set(&self, class: PagesClass, access: Access, verdict: Verdict) { self.verdicts[verdict_index(class, access)].store(verdict.byte(), Ordering::Release); + // Under the lock a waiter reads the verdict under, so that none misses the wake. + let _held = lock(&self.settled); + self.wake.notify_all(); + } + + /// `class`'s verdict for `access` once it is known, the check settled, or `timeout` passed, + /// whichever comes first. + pub(crate) fn wait_for(&self, class: PagesClass, access: Access, timeout: Duration) -> Verdict { + let deadline = Instant::now() + timeout; + let mut settled = lock(&self.settled); + loop { + let verdict = self.verdict(class, access); + let left = deadline.saturating_duration_since(Instant::now()); + if verdict != Verdict::Pending || *settled || left.is_zero() { + return verdict; + } + settled = match self.wake.wait_timeout(settled, left) { + Ok((settled, _)) => settled, + Err(poisoned) => poisoned.into_inner().0, + }; + } } /// Whether the check is to fail whatever the moves did. @@ -430,9 +461,12 @@ impl InPlaceChecks { } } -/// The version of what the check does and of how a record of it is named and framed: a change to -/// either bumps it, and a record of another version is never read (its name differs, and so does -/// the version it holds). +/// The version of what the check does, of the images over host pages it checks as the product +/// makes them (their usage, layout and moves), and of how a record of it is named and framed: a +/// change to any of them bumps it, and a record of another version is never read (its name +/// differs, and so does the version it holds). The runtime's own version is not in the record: a +/// release that changes none of these keeps the verdicts the driver gave, so a device made after +/// it reads them again rather than checking anew. pub(crate) const CHECK_VERSION: u32 = 2; /// A record's first bytes. @@ -461,21 +495,14 @@ pub(crate) struct DriverIdentity { } impl DriverIdentity { - /// The SHA-256 of [`NAME_TAG`], [`CHECK_KIND`], [`CHECK_VERSION`], the runtime's - /// `RUNTIME_VERSION` and every field: what names a record and what the record holds again. + /// The SHA-256 of [`NAME_TAG`], [`CHECK_KIND`], [`CHECK_VERSION`] and every field: what names + /// a record and what the record holds again. What decides the check's answer alone: the + /// check, and the driver and device it ran on. pub(crate) fn digest(&self) -> [u8; 32] { - self.digest_for(NAME_TAG, CHECK_KIND, CHECK_VERSION) - } - - /// The SHA-256 of `tag`, `kind`, `version`, the runtime's `RUNTIME_VERSION` and every field: - /// what names the record of the check of `kind` at `version` (another device check's, as - /// [`digest`](Self::digest) is this one's), and what that record holds again. - pub(crate) fn digest_for(&self, tag: &[u8], kind: &[u8], version: u32) -> [u8; 32] { let mut hash = Sha256::new(); - hash.update(tag); - hash.update(kind); - hash.update(version.to_le_bytes()); - hash.update(metal2vulkan::cache::RUNTIME_VERSION.to_le_bytes()); + hash.update(NAME_TAG); + hash.update(CHECK_KIND); + hash.update(CHECK_VERSION.to_le_bytes()); hash.update(self.vendor_id.to_le_bytes()); hash.update(self.device_id.to_le_bytes()); hash.update(self.driver_version.to_le_bytes()); @@ -499,7 +526,6 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// ```text /// magic 8 bytes "M2VINPL\0" /// version u32 CHECK_VERSION -/// runtime u32 RUNTIME_VERSION /// identity 32 bytes DriverIdentity::digest /// verdicts 6 bytes one per class and access, VERDICTS' order (verdict_index) /// checksum 32 bytes SHA-256 of every byte before it @@ -510,7 +536,6 @@ pub(crate) fn encode(identity: &DriverIdentity, verdicts: [Verdict; VERDICTS]) - let mut bytes = Vec::with_capacity(RECORD_BYTES); bytes.extend_from_slice(&MAGIC); bytes.extend_from_slice(&CHECK_VERSION.to_le_bytes()); - bytes.extend_from_slice(&metal2vulkan::cache::RUNTIME_VERSION.to_le_bytes()); bytes.extend_from_slice(&identity.digest()); bytes.extend(verdicts.map(Verdict::byte)); let checksum: [u8; 32] = Sha256::digest(&bytes).into(); @@ -519,7 +544,7 @@ pub(crate) fn encode(identity: &DriverIdentity, verdicts: [Verdict; VERDICTS]) - } /// A record's length. -const RECORD_BYTES: usize = 8 + 4 + 4 + 32 + VERDICTS + 32; +const RECORD_BYTES: usize = 8 + 4 + 32 + VERDICTS + 32; /// The verdicts `bytes` record for `identity`: `None` for anything but a whole record of this /// version and runtime, for this identity, whose checksum holds and whose every verdict is an @@ -535,14 +560,9 @@ pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<[Verdict } let (magic, rest) = body.split_at(8); let (version, rest) = rest.split_at(4); - let (runtime, rest) = rest.split_at(4); let (digest, rest) = rest.split_at(32); let word = |bytes: &[u8]| u32::from_le_bytes(bytes.try_into().unwrap_or([0xff; 4])); - if magic != MAGIC - || word(version) != CHECK_VERSION - || word(runtime) != metal2vulkan::cache::RUNTIME_VERSION - || digest != identity.digest() - { + if magic != MAGIC || word(version) != CHECK_VERSION || digest != identity.digest() { return None; } let mut verdicts = [Verdict::Pending; VERDICTS]; @@ -620,12 +640,19 @@ impl Device { } } - /// `class`'s verdict for `access` for a texture asking it now: a pending one starts the - /// check, unless it started already. Never waits. + /// `class`'s verdict for `access` for a texture asking it as it is made: a pending one + /// starts the check, unless it started already, and waits for that verdict, up to + /// [`VERDICT_WAIT`] (the module docs). pub(crate) fn in_place_verdict(&self, class: PagesClass, access: Access) -> Verdict { - let verdict = self.shared().in_place.verdict(class, access); - if verdict == Verdict::Pending { - self.start_in_place_checks(); + let checks = &self.shared().in_place; + let verdict = checks.verdict(class, access); + if verdict != Verdict::Pending { + return verdict; + } + self.start_in_place_checks(); + let verdict = checks.wait_for(class, access, VERDICT_WAIT); + if verdict != Verdict::Pending { + self.shared().counts.in_place_verdict_waited(); } verdict } diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 25dadd7bc..d7e57a4fe 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -50,10 +50,12 @@ //! is the device's as it is known, so a class that passed takes textures in place while the //! next is checked. Counted (`WorkCounts::in_place_checks_*`). //! - **Kept.** Once every class answered, 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 -//! check's version and the runtime's ([`record_name`]): a device of the same driver and release -//! reads them as it is made and runs no check. A failed write leaves the verdicts for the -//! device's life. A forced failure is kept nowhere. +//! cache's content directory (`shader_cache/store.rs`), named by the driver's identity (its +//! version and the device's UUID among it) and the check's version ([`record_name`]), not the +//! runtime's: a device of the same driver and version reads them as it is made and runs no +//! check, whatever runtime release made it, until the check itself changes +//! (`in_place::CHECK_VERSION`). A failed write leaves the verdicts for the device's life. A +//! forced failure is kept nowhere. //! - **Its thread.** Each round's Vulkan work (the buffer, the texture, the submission and its //! wait, the releases) runs inside a section of the exit guard (`exit_guard.rs`), as every //! runtime thread's does. It holds its device through the registry of the runtime's own holds diff --git a/crates/metal2vulkan-runtime/src/tests/in_place.rs b/crates/metal2vulkan-runtime/src/tests/in_place.rs index 0acdf4f22..6ef74fb0c 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place.rs @@ -9,9 +9,11 @@ //! render check; else its read check), else a shadow naming the check's answer (pending, //! failed, unchecked) and the access. //! - **The record.** Its verdicts read back for the identity it was written for, and nothing else -//! reads: a record cut short or grown, of another check version or runtime, of another identity, -//! with a byte changed (its checksum), or holding a pending or unknown verdict. -//! - **Its name** changes with every field of the driver's identity. +//! reads: a record cut short or grown, of another check version, of another identity, with a +//! byte changed (its checksum), or holding a pending or unknown verdict. +//! - **Its name** changes with every field of the driver's identity, and with nothing else: not +//! the runtime's version, so a pin move keeps the driver's verdicts. +//! - **A waiter** for one verdict wakes as that verdict is given, or as the check settles. use crate::in_place::{ decode, encode, in_place, record_name, verdict_index, Access, DriverIdentity, InPlaceChecks, @@ -189,17 +191,13 @@ fn a_record_reads_back_for_its_identity_alone() { assert_eq!(decode(&identity, &changed), None, "byte {at}"); } - // Another check version, or another runtime, with a checksum that holds. + // Another check version, with a checksum that holds. let mut version = bytes.clone(); version[8..12].copy_from_slice(&(CHECK_VERSION + 1).to_le_bytes()); assert_eq!(decode(&identity, &rechecked(version)), None); - let mut runtime = bytes.clone(); - let other = metal2vulkan::cache::RUNTIME_VERSION.wrapping_add(1); - runtime[12..16].copy_from_slice(&other.to_le_bytes()); - assert_eq!(decode(&identity, &rechecked(runtime)), None); // A pending or unknown verdict, at any of their places, with a checksum that holds. - for at in 48..48 + VERDICTS { + for at in 44..44 + VERDICTS { for byte in [0u8, 4, 0xff] { let mut verdict = bytes.clone(); verdict[at] = byte; @@ -222,6 +220,24 @@ fn a_record_s_name_follows_every_field_of_the_identity() { let base = identity(); let name = record_name(&base); assert_eq!(name.len(), 64); + // The name hashes the check's tag, kind and version and the identity alone: no runtime + // version is in it. + let mut hash = Sha256::new(); + hash.update(b"metal2vulkan in-place check record\0"); + hash.update(b"first move\0"); + hash.update(CHECK_VERSION.to_le_bytes()); + hash.update(base.vendor_id.to_le_bytes()); + hash.update(base.device_id.to_le_bytes()); + hash.update(base.driver_version.to_le_bytes()); + hash.update(base.driver_id.to_le_bytes()); + for text in [&base.driver_name, &base.driver_info] { + hash.update((text.len() as u64).to_le_bytes()); + hash.update(text.as_bytes()); + } + hash.update(base.device_uuid); + let alone: [u8; 32] = hash.finalize().into(); + let hex: String = alone.iter().map(|byte| format!("{byte:02x}")).collect(); + assert_eq!(name, hex); let changes: [fn(&mut DriverIdentity); 7] = [ |id| id.vendor_id += 1, |id| id.device_id += 1, @@ -282,3 +298,27 @@ fn the_checks_state_settles_once_and_wakes_its_waiters() { assert_eq!(checks.took(), Some(Duration::from_millis(5))); assert!(InPlaceChecks::new(true).forced_failure()); } + +#[test] +fn a_waiter_for_a_verdict_wakes_as_it_is_given() { + let checks = InPlaceChecks::new(false); + let (class, access) = (PagesClass::Pointer, Access::Renders); + // Nothing given: the wait runs out, pending. + assert_eq!( + checks.wait_for(class, access, Duration::from_millis(1)), + Verdict::Pending + ); + std::thread::scope(|scope| { + let waiter = scope.spawn(|| checks.wait_for(class, access, Duration::from_secs(60))); + // Another verdict wakes it to wait on; its own ends the wait. + checks.set(class, Access::Reads, Verdict::Failed); + checks.set(class, access, Verdict::Passed); + assert_eq!(waiter.join().ok(), Some(Verdict::Passed)); + }); + // A settled check ends a wait for a verdict it never gave. + checks.settle(None); + assert_eq!( + checks.wait_for(PagesClass::DmaBuf, access, Duration::from_secs(60)), + Verdict::Pending + ); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index e3407634b..12a030ca6 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -376,6 +376,7 @@ pub(crate) struct Counters { in_place_checks_failed: AtomicU64, in_place_checks_unchecked: AtomicU64, in_place_checks_recalled: AtomicU64, + in_place_verdicts_waited: AtomicU64, fresh_page_buffers_made: AtomicU64, fresh_page_bytes: AtomicU64, new_buffer_bytes_cleared: AtomicU64, @@ -2984,6 +2985,12 @@ impl Counters { (self.in_place_checks_recalled).fetch_add(1, Ordering::Relaxed); } + /// A texture over host pages waited as it was made for its class's verdict for its access, + /// and the verdict came (`in_place.rs`). + pub(crate) fn in_place_verdict_waited(&self) { + (self.in_place_verdicts_waited).fetch_add(1, Ordering::Relaxed); + } + /// A buffer was made in `bytes` of fresh pages it imported, which read zero unwritten /// (`fresh_pages.rs`). pub(crate) fn fresh_page_buffer_made(&self, bytes: u64) { @@ -5926,6 +5933,12 @@ pub struct WorkCounts { /// Classes and accesses whose verdict was read from the record of an earlier check of the /// same driver, device and runtime: no check ran for them. pub in_place_checks_recalled: u64, + /// Textures over host pages made while the device's check had not answered for their class + /// and access, which waited as they were made for that verdict and had it: each took the + /// path the verdict answers rather than a shadow (`in_place.rs`, `in_place::VERDICT_WAIT`). A + /// wait that ran out leaves the texture a shadow, counted in + /// `host_texture_shadows_check_pending`. + pub in_place_verdicts_waited: u64, /// Buffers of the runtime's own made in fresh anonymous pages imported by their pointer /// (`VK_EXT_external_memory_host`), which read zero with nothing written: host-visible ones /// longer than half a pooled block, not of a heap, where the device takes such pages. A @@ -7145,6 +7158,7 @@ impl Device { in_place_checks_failed: counters.in_place_checks_failed.load(Ordering::Relaxed), in_place_checks_unchecked: counters.in_place_checks_unchecked.load(Ordering::Relaxed), in_place_checks_recalled: counters.in_place_checks_recalled.load(Ordering::Relaxed), + in_place_verdicts_waited: counters.in_place_verdicts_waited.load(Ordering::Relaxed), fresh_page_buffers_made: counters.fresh_page_buffers_made.load(Ordering::Relaxed), fresh_page_bytes: counters.fresh_page_bytes.load(Ordering::Relaxed), new_buffer_bytes_cleared: counters.new_buffer_bytes_cleared.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index fe79a2127..0ec93d224 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2795,6 +2795,7 @@ field metal2vulkan-runtime::WorkCounts.in_place_checks_passed pub in_place_check field metal2vulkan-runtime::WorkCounts.in_place_checks_recalled pub in_place_checks_recalled: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_run pub in_place_checks_run: u64 field metal2vulkan-runtime::WorkCounts.in_place_checks_unchecked pub in_place_checks_unchecked: u64 +field metal2vulkan-runtime::WorkCounts.in_place_verdicts_waited pub in_place_verdicts_waited: u64 field metal2vulkan-runtime::WorkCounts.indirect_chunks_kept pub indirect_chunks_kept: u64 field metal2vulkan-runtime::WorkCounts.indirect_commands_kept pub indirect_commands_kept: u64 field metal2vulkan-runtime::WorkCounts.indirect_draws_recorded pub indirect_draws_recorded: u64 diff --git a/docs/API.md b/docs/API.md index 2d9fcd943..e5ac4bf42 100644 --- a/docs/API.md +++ b/docs/API.md @@ -337,9 +337,11 @@ CPU thread writes beside their texels, and passes a kind only where every first byte; for a texture that renders it checks images made with `RenderTarget` usage apart, through their first move, their moves into the feedback loop layout and back, and a render pass that clears and stores them, while the CPU writes the bytes between their rows and after them. It runs -on a thread of its own, which the first such texture starts, once per driver, driver version and -runtime release: its verdicts are kept in the shader cache's directory (a device without one -checks once per process) and recalled as the next device is made +on a thread of its own, which the first such texture starts and waits for, up to 5 seconds, for +its kind of pages and access (`WorkCounts::in_place_verdicts_waited`; past it the texture is a +shadow), once per driver and driver version: its verdicts are kept in the shader cache's +directory, named by the driver and the check's own version, not the runtime's (a device without +one checks once per process), and recalled as the next device is made (`WorkCounts::in_place_checks_run`, `_passed`, `_failed`, `_unchecked`, `_recalled`). Such a texture's commands read and write the texels in the memory the buffer's commands read, so a CPU write reaches them as it reaches the buffer's. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index c1315a71e..31516f82b 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -38,7 +38,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | | Command queues on a device whose GPU idles when consecutive work comes from another `VkQueue` share `VkQueue`s by choice (`queue_share.rs`): the runtime's own self-check, not a `DriverFact` row, measures that idling once per driver, release and runtime on a thread of its own and keeps its verdict (`Idles`, `DoesNotIdle`, `Unchecked`) in the shader cache's directory, as the in-place check keeps its own (`queue_switch_check.rs`: 48.7 to 51.3 us a switch on the RTX 5080 Laptop GPU, NVIDIA 615.71.09, `Idles` above 20 us). A command queue that makes a command buffer while it holds no other uncompleted one moves onto the busy `VkQueue` of its family whose oldest batch has run under 0.5 ms, the most batches in flight first, so short command buffers of several queues run with no switch between them. A queue one of whose command buffers ran on the GPU for over 2 ms, by its own timestamps (not the host's view of how long it ran as its `VkQueue`'s oldest, which also holds its wait for the GPU to start it and the waiter's lateness to see it complete), is long: no queue joins its `VkQueue` while it lives, and it moves once more, at its next idle point, to an idle `VkQueue` no long or unshared queue holds. A queue whose command buffers must never wait behind another queue's (a compositor's beside an application's) is made with `Device::new_command_queue_unshared`: it never moves and no queue joins its `VkQueue`. Presenting queues and a queue that lent its `VkQueue` (`with_vk_queue`) never move. Before the verdict, and where it is not `Idles` or there are no two `VkQueue`s of one family (MoltenVK, RADV, lavapipe), every queue keeps the `VkQueue` it took at its creation; so does every queue of a device whose command buffers write no GPU timestamps it reads (`gpu_times_from_host`, or a driver whose timestamps wait for every queue's), which does not share and is counted (`WorkCounts::queue_sharing_untimed`). The runtime's: no pipeline differs. | `queue_sharing = QueueSharingPolicy::Adaptive` | `queue_sharing = QueueSharingPolicy::PerQueue`: each command queue keeps the `VkQueue` it took at its creation, round robin, and the check does not run | A command buffer waits behind the command buffers of the queues sharing its `VkQueue`, where Metal's queues wait for each other only inside one command. The residual stall: once per logical queue that goes long, for a queue that joined its `VkQueue` during its short phase, about one long command buffer's length: the command buffers committed behind that queue's first long one there wait for its whole length (and those behind its later ones while it holds work, until its next idle point). Measured on the RTX 5080 Laptop GPU beside an application that alternates draws with 30 ms command buffers: a shared compositor's commits at 4,800 a second had 64 completions over 10 ms, at most 26.4 to 30.1 ms, in each of 3 runs of each of two such shapes (one join each), against none over 10 ms under `PerQueue` in those 6 runs (at most 5.6 to 9.7 ms); with 2 ms of draws between long command buffers, none over 10 ms in 3 runs (at most 5.7 to 9.8 ms) against 7, 0 and 0 under `PerQueue` (at most 6.9 to 11.2 ms). On an unshared queue, 0 over 10 ms in every run. A command buffer's GPU start time includes the other queues' work before it. `QueueSharing` (`queue-sharing`), at the device's first join | Command buffers a second on the RTX 5080 Laptop GPU, one-draw command buffers, each thread its own queue, the default against `PerQueue`, runs after a lock hold's first: 8 threads with 3 in flight 50.7k to 54.7k against 27.4k to 28.0k (5 runs each); 8 threads with 1 in flight 47.0k to 50.1k against 13.9k to 14.3k (5); 2 threads with 3 in flight 28.0k to 53.7k against 21.4k to 28.0k (10 each, in turn, the default above `PerQueue` in each pair; no thread's queue marked long), and beside another process's 30 ms command buffers 5.1k to 6.7k against 4.0k to 4.1k (3 each; the host's view marked a thread's queue long in 1 of 3 runs, which then ran at `PerQueue`'s 4.1k); 2 threads with 1 in flight 16.9k to 20.7k against 10.1k to 11.5k (5); one thread over 16 queues in turn 21.7k to 43.3k against 10.2k to 11.1k, over 2,048 20.0k to 39.2k against 10.2k to 11.2k (4). Beside an application whose queue never shared with the compositor (isolation, 300 and 30 dispatches), both 0 over 10 ms | | A chain of `half` additions, subtractions and products on a device without `shaderFloat16` (vk12-floor, SwiftShader, Pascal; capability emulation: the module computes each in `float` and rounds it by the device's `OpQuantizeToF16`): an operation whose flags hold `contract` and `reassoc` and whose result only such operations read is held at `float` precision unrounded, so the chain rounds where a value leaves it (a store, an output, a conversion, a comparison, a call, a phi, a vector move, an operation without both flags), one quantize per exit instead of one per operation (`lower::arith::half_chain`). A device with `shaderFloat16` computes `half` alike under either value. | `half_chains = HalfChainPolicy::AtExits` | `half_chains = HalfChainPolicy::EachOperation`: every operation's result rounded to `half`, as the AIR computes it | The result may differ from the rounded operations' by the roundings the chain skips, each within half a unit in the last place of a `half` at its step, compounded along the chain; a value inside the chain past `half`'s range (65504) stays finite where the rounded operations reach infinity. Within the AIR's flags, which let a compiler regroup and fuse such operations. `FastMathRewrites` (`fast-math-rewrites`) | Not timed. Size on vk12-floor (the fixtures' SPIR-V words, the default against the accurate form): `hfb_filter_bank` 121,270 against 131,766 (1,024 quantizes against 2,464), `grd_half_many_samples` 82,019 against 84,627, `nan_half_fast` 9,808 against 9,832 | -| A texture that samples, reads or renders into it and does not write it through a shader (no `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, checked apart. A deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's rulings (2026-10-26, and 2026-10-27 and 2026-11-07 for render targets: the GPU works on the caller's pages in place as a Mac's does, whatever a linear image costs it; `in_place.rs`). The check runs once per driver, release and runtime, per class of pages and access, on a thread of its own, its verdicts kept in the shader cache's directory; a texture made before its verdict is a shadow. A texture whose usage writes through a shader, a check that failed or made no image, and a format, usage or pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`, those that render counted apart in `host_texture_shadows_render_target`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each, for an image that reads and one that renders (its pass a clear at load and a store; a resolve into it is not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | +| A texture that samples, reads or renders into it and does not write it through a shader (no `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device makes the image (its format and usage linear, at the pages' pitch) and its own check shows that the operations Vulkan lets read and write every byte bound to it leave every byte alone while the CPU writes beside it: the image's first move (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), and for one that renders a render pass's load and store operations and its moves into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` and back, checked apart. A deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's rulings (2026-10-26, and 2026-10-27 and 2026-11-07 for render targets: the GPU works on the caller's pages in place as a Mac's does, whatever a linear image costs it; `in_place.rs`). The check runs once per driver and driver version (its record named by the driver and the check's own version, not the runtime release), per class of pages and access, on a thread of its own, its verdicts kept in the shader cache's directory; a texture made before its verdict waits for it as it is made, up to `in_place::VERDICT_WAIT` (5 s), and past that is a shadow. A texture whose usage writes through a shader, a check that failed or made no image, and a format, usage or pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`, those that render counted apart in `host_texture_shadows_render_target`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each, for an image that reads and one that renders (its pass a clear at load and a store; a resolve into it is not among the rounds); a driver whose operations changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer, and a render target's shadow copies it in, keeps it and merges it back at each render pass instance | | A render or compute state's creation hands the driver's making of its predicted pipeline (`pipeline/predicted.rs`, `pipeline/dispatch_making.rs`) to the runtime's pool, kept by the state as a draw's or dispatch's making is, and waits for it `pipeline_creation_wait` at most; a committed command buffer's recordings wait until its commit plus `pipeline_commit_wait` at most, one deadline its commands share, for its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches) pipelines still being made (the scheduler wakes at the bound, `StepWaits::until`), an execution's replayed draws (`render/pending.rs`) among them, whose pipelines the commit's settle hands to the pool (a device replay's, one recording for every command, waits until made under either value), then record each such command as nothing: a draw's barriers and visibility query, a dispatch's barrier (a tile dispatch's copies into its scratch and back), no draw or dispatch, the command buffer running on without error. The making goes on, and the command buffers after it draw and dispatch with the pipeline once made. Metal compiles inside `newRenderPipelineState`, so no draw of a made state waits or is dropped; a host that creates a state inside a command buffer's encoding (the consumer creates a guest's state at an execution's first lookup of it) held that execution through the driver's whole compile: 11.59 s inside one execution on an M2 Pro (MoltenVK 1.4.2, a cold Metal compiler service; a sample of such a stall finds the compile's thread waiting in `MVKMetalCompiler::compile` for Metal's compiler), past the guest's 10 s FIFO check, which ended the guest's task. Each bound is 4.5 s: a creation and a commit may fall in one step of the guest's FIFO (a task's jobs run one after another, and a draw's own variant waits under its command buffer's bound), and no runtime call waits for both, so one step waits 9 s at most for makings, under that 10 s check. A creation waits on no command buffer's deadline and a `commit` on no creation's; a `commit` waits until its own deadline at most (it records there what it can, an execution of render commands the CPU writes among them), every other recording on the scheduler's thread, a host step's on one of the steps' threads. Made until made under either value, in the call that makes them: a draw that records nothing, one in a pass of custom sample positions and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its `commit`), and a failed making made again (`PipelineWaitPolicy`'s docs). The runtime's: no pipeline differs. | `pipeline_waits = PipelineWaitPolicy::Bounded`, `pipeline_creation_wait = 4.5 s`, `pipeline_commit_wait = 4.5 s` | `pipeline_waits = PipelineWaitPolicy::Exact`: the creation makes its predicted pipeline before it returns (a render state's first key on its own thread, the rest on the pool, joined; a compute state's on its own thread), an execution's settle makes its replayed draws' pipelines at the commit, and a command buffer waits for each draw's and dispatch's pipeline until it is made | A draw whose pipeline was still being made `pipeline_commit_wait` after its command buffer's commit renders nothing in that command buffer (only there: later ones draw it), where Metal's renders: content drawn once (a layer, a glyph cache) stays without it until redrawn. A creation returns after `pipeline_creation_wait` at most with its making in flight (`WorkCounts::creations_left_making`). `DrawDroppedStillMaking` (`draw-dropped-still-making`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `CommandBuffer::dropped_draw` names the first with `VK_TIMEOUT`; `WorkCounts::draws_dropped_still_making`; `deferred_calls::a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` and `under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands`. A dispatch whose pipeline was still being made then writes nothing in that command buffer, where Metal's runs: `DispatchDroppedStillMaking` (`dispatch-dropped-still-making`), `WorkCounts::dispatches_dropped_still_making`, the first named by `dropped_draw`; `deferred_calls::a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing`, `a_compute_state_s_creation_waits_its_bound_for_its_predicted_making` and `a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` | No GPU cost. The exact form holds the creating thread, and the command buffer, for the whole compile: up to 11.59 s on the M2 Pro's cold boot (that boot's 2,483 render state creations, translation included: 300 over 16 ms, 151 over 100 ms, 14 over 250 ms, 3 over 1 s, the longest 11.59 s, 5.82 s and 1.17 s), where the default holds a creation for 4.5 s at most and a command buffer for 4.5 s from its commit, which drops the draws of the compiles that outlast those (2 of that boot's 2,483 were over 4.5 s) for the command buffers committed before they land; bounds of 1 s dropped 39 draws in a cold boot on the M2 Pro, and the guest's menu bar, drawn once, stayed half drawn | | A line Apple's `setLineWidth:` widens (`w' = floor(16 w) / 16`, other than 1), and a triangle's edge in fill mode `Lines`, is drawn by the device's own lines at `w'` wherever it draws that width (`wideLines`, `w'` in `lineWidthRange` and above 0), where Metal draws the parallelogram Vulkan's non-strict wide lines may be (`render/line_width.rs`). They are exactly it on a non-strict device whose wide lines are parallelograms (`strictLines` unset, `nonStrictWideLinesUseParallelogram` set) at a width above 1 on its `lineWidthGranularity`, unannounced there; elsewhere they differ: a strict device's rectangle with square ends (lavapipe, NVIDIA), lines Vulkan does not state as parallelograms (ANV, and every width below 1), a width rounded to the granularity. A mesh draw's lines and edges and a tessellated patch draw's edges take the device's lines under either value, the band not drawing them (at the nearest width they draw where they do not draw `w'`, announced `lines-at-nearest-width`: a known gap below). The runtime's: no pipeline's code differs. | `wide_lines = WideLinePolicy::Device` | `wide_lines = WideLinePolicy::Exact`: a draw of lines or edges the device's lines draw otherwise than Metal is the pipeline's band variant (`VariantKey::line_band`, `pipeline::link::band`) on a device with `tessellationShader` (the device's lines where it has none, or where the translator refuses the state's band or the draw's): two triangles over each line's parallelogram, and each triangle's three edges' parallelograms facing as the triangle, through a tessellation control and evaluation stage; every other width other than 1 is the band under either value | The lines can cover pixels the parallelogram does not, and miss others, at each end and along each edge: up to half the width past each end (square ends), and a rounded width. `DeviceWideLines` (`device-wide-lines`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `WorkCounts::device_wide_line_draws`, `line_band_draws`, `nearest_width_line_draws`; `runtime_lane::line_widths` (the band matches Metal's maps of lines and of triangles' edges, their facing, culling, flat inputs, primitive IDs and depth on MoltenVK under both values, which has no `wideLines`; a band of edges under a depth bias is announced `wide-edge-depth-bias`) | Not measured. Expected from the band's form: a second pipeline variant made for each render state that draws such lines or edges (its two synthesized stages), each line tessellated as a patch of two control points into four corners and each triangle as a patch of three into 21 triangles (12 degenerate), and a strip, loop or fan drawn as the list of its primitives | | A blit or fill through a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed (`allowGPUOptimizedContents`, 16 texels or more a side, neither `ShaderWrite` nor `PixelFormatView` usage, one sample, not over a buffer) is the device's copy, which keeps the bytes it moves, on every device: Metal's GPU blit into, out of or between such textures moves the texels through its compression, which writes each 16-bit field's low six bits cleared and the alpha code clamped to `[384, 894]`, and its fill clears the low six bits alone (an Apple M3 Max under macOS 27.0.1, every direction, storage mode, usage and size that decides the compression; CPU copies keep the bytes on Metal too). A pass's draws through such an attachment are the device-gap row below. The runtime's choice: no pipeline differs (`compressed_blit.rs`). | `extended_range_blits = ExtendedRangeBlitPolicy::Kept` | `extended_range_blits = ExtendedRangeBlitPolicy::Canonical`: after a blit writes such a texture's region, or a blit out of one writes a buffer's words, a texture over a buffer's or another texture's, a compute dispatch (`bind::extended_canonical_module`, `extended_canonical.rs`) rewrites the texels it wrote in Metal's encoding: in place in a buffer's bytes, an image's through a scratch buffer, a copy out and back around the dispatch; a fill's texel is encoded before it is written. A buffer whose words the device cannot bind (an offset or pitch off 4 bytes, a region past `maxStorageBufferRange`) and a texture over a buffer whose rows share bytes keep the bytes under either value, announced | Bytes no Metal write left (uploaded, CPU-copied or kernel-written texels: a field's low six bits, an alpha code outside `[384, 894]`) keep what Metal's blit would rewrite; a texel reads the same value either way, its low six bits unread and its alpha read clamped. `ExtendedRangeBitsKept` (`extended-range-bits-kept`), once per device; under `Canonical` not for the blits it makes exact; `runtime_lane::compressed_blits` (both values on MoltenVK), the conformance cases `compressed-blits-bgra10xr` and `compressed-blits-bgra10xr-srgb` | Measured, `Canonical` against `Kept`, on `Private` `BGRA10_XR` textures Metal keeps compressed (the sRGB twin and fills not measured), 256x256 and 2048x2048, one whole-texture blit a command buffer: p50 of 300 blits a run, the two values interleaved in one process, three runs a host. RTX 5080 Laptop (NVIDIA 615.71.09, the command buffer's GPU time): a buffer into the texture 23.5 against 11.5 us and 761 against 244 us from a `Private` buffer, 42 against 30 us and 1,945 against 1,176 us from a `Shared` one; the texture into a `Private` buffer 14.1 against 11.2 us and 287 against 246 us, into a `Shared` one, whose words the dispatch rewrites in system memory, 66 against 27 us and 3,386 against 1,182 us; texture into texture 22.5 against 9.7 us and 630 against 80 us. Apple M3 Max (MoltenVK 1.4.2, whose GPU times are the host's, so per blit of 16 in one command buffer), the same blits: into the texture +38 to +57 us and +536 to +548 us, out of it into a buffer +15 us and +84 to +94 us, texture into texture +46 to +48 us and +535 to +541 us. Every figure is above its `Kept` one in every run, by more than the runs' spread (under 1 us on the 5080): measurable at both sizes on both hosts. Into an image a blit adds a copy out into a scratch buffer of the region's size, the dispatch, a copy back and the barriers between them; into a buffer the dispatch and a barrier. The scratch is made without zeros, since the copy out writes every byte the dispatch and the copy back read; the figures above were taken while it was zeroed first, by a command buffer of its own (a fill on the 5080, a copy on MoltenVK). CPU from the command buffer's making through its commit, a blit alone: +1 to +3 us on the M3 Max, +1 to +127 us on the 5080, whose host other builds loaded; 16 blits into 2048x2048 images in one command buffer hold 16 scratch buffers of 32 MiB, and encoding each costs 141 to 165 us (5080) and 286 to 356 us (M3 Max), new memory blocks among it, against 2 to 6 us under `Kept`. Nothing for a texture Metal keeps uncompressed or of another format | diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 431753e95..417e10745 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -296,15 +296,18 @@ back after, which would undo a CPU write made meanwhile, where Metal keeps every command buffer does not write. By default (`HostPageTexturePolicy::InPlace`) the runtime relies on the driver there, checked. A -texture whose declared usage only samples or reads it is a linear image aliasing the pages wherever -the device's own check passed for that kind of pages (pointer imports, dma-buf imports, fresh -pages): the check makes such images while a CPU thread writes beside their texels and passes a kind -only where every first move kept every byte. It runs on a thread of its own, started by the first -such texture, once per driver, driver version and runtime release; with a shader-cache directory -its verdict is kept there and recalled as the next device is made, else it runs once per process. -Until it answers, a texture is a shadow (`WorkCounts::host_texture_shadows_check_pending`), so the -first frames of a first session pay the shadow's copies. A texture that renders or writes -(`RenderTarget`, `ShaderWrite`, `ShaderAtomic`), one the check failed or could not cover, and one +texture whose declared usage samples, reads or renders into it and does not write it through a +shader is a linear image aliasing the pages wherever the device makes one and its own check passed +for that kind of pages (pointer imports, dma-buf imports, fresh pages) and that access (a texture +that renders is checked apart): the check makes such images while a CPU thread writes beside their +texels and passes a kind only where every first move (and render pass, for one that renders) kept +every byte. It runs on a thread of its own, started by the first such texture, once per driver and +driver version; with a shader-cache directory its verdicts are kept there, named by the driver and +the check's own version (not the runtime release), and recalled as the next device is made, else +it runs once per process. The first texture waits for its verdict as it is made, up to 5 seconds +(`WorkCounts::in_place_verdicts_waited`); past that it is a shadow +(`WorkCounts::host_texture_shadows_check_pending`). A texture that writes through a shader +(`ShaderWrite`, `ShaderAtomic`), one the check failed or could not cover, and one no image in place serves (a pitch the device's linear images do not take -- `host_texture_shadows_refused_pitch`; over dma-buf pages, a source that makes no one dma-buf of the texture's own pages, as a chunked `udmabuf` import does -- `host_texture_shadows_refused_source`)