From 2aa801ccb30d6880c67360258ccecdff06780902 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 03:48:12 -0800 Subject: [PATCH] WIP submission checks (squash target: replaced by the next commit's message) (cherry picked from commit bc0dd9f45e0e025508b25ece4f0524404d6f4e94) --- crates/metal2vulkan-runtime/src/buffer.rs | 9 +- .../src/command_buffer/group.rs | 36 +- .../src/command_buffer/mod.rs | 5 - .../metal2vulkan-runtime/src/device/holds.rs | 14 +- crates/metal2vulkan-runtime/src/device/mod.rs | 7 + .../src/host_residency.rs | 24 +- .../src/in_place_check.rs | 19 +- crates/metal2vulkan-runtime/src/lib.rs | 1 + .../metal2vulkan-runtime/src/submit_check.rs | 1228 +++++++++++++++++ .../metal2vulkan-runtime/src/tests/batches.rs | 61 +- .../src/tests/fresh_pages.rs | 20 +- .../src/tests/host_residency.rs | 11 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 9 + .../src/tests/pointer_residency.rs | 26 +- .../src/tests/submit_check.rs | 93 ++ .../src/tests/submit_check_device.rs | 158 +++ .../src/tests/unsubmitted.rs | 15 +- .../src/tests/waiter_submits.rs | 16 +- .../metal2vulkan-runtime/src/work_counts.rs | 31 + .../src/runtime_lane/grouped_submissions.rs | 29 +- .../src/runtime_lane/submit_per_import.rs | 30 +- .../metal2vulkan/src/device/driver_facts.rs | 124 +- .../src/device/tests/driver_facts.rs | 77 +- 23 files changed, 1719 insertions(+), 324 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/submit_check.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/submit_check.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/submit_check_device.rs diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 81505f454..4038dbb52 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -2211,9 +2211,12 @@ impl Device { .usage(usage(false)), ); // A heap's own buffer lies where its textures can too, and is never parked. A long - // host-visible one of the runtime's own lies in fresh pages where the device takes them. - let wants_fresh = - !of_heap && fresh_pages::takes_fresh_pages(size, class) && shared.host_import.is_ok(); + // host-visible one of the runtime's own lies in fresh pages where the device takes them + // and its check found a held import adds nothing to its submissions (`fresh_pages.rs`). + let wants_fresh = !of_heap + && fresh_pages::takes_fresh_pages(size, class) + && shared.host_import.is_ok() + && self.fresh_pages_pay(); let making = (!of_heap).then_some(BufferMaking { size, class, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs index 78c7b0526..0653468ec 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs @@ -1,13 +1,15 @@ //! Batches that go to the driver in one kernel submission (`CompletionPolicy::Grouped`). //! -//! On a driver measured to merge each `vkQueueSubmit`'s `VkSubmitInfo`s that signal nothing into -//! the next one's kernel submission ([`DriverFact::SubmissionsWithoutSignalsMerge`], whose -//! documentation holds what was measured where), batches that signal nothing but their queue's -//! timeline may wait and go in one call for the cost of one kernel submission. The question is -//! the driver's, and the fact answers it, never the driver's name: a driver without the fact -//! takes the ungrouped path, each batch its own `vkQueueSubmit`, which is what every batch took -//! before grouping and is exact alike -- a group changes when a `vkQueueSubmit` is made and -//! nothing it submits. +//! On a device whose check found one `vkQueueSubmit` of `VkSubmitInfo`s that signal nothing to +//! cost about one of its submissions (`submit_check.rs`, `Check::Merge`: Mesa's common queue +//! merges each into the next one's kernel submission, `vulkan/runtime/vk_queue.c`), batches that +//! signal nothing but their queue's timeline may wait and go in one call for the cost of one +//! kernel submission. The question is the device's, and its check answers it, never the driver's +//! name nor its GPU's: a device whose check found otherwise, or has not answered, takes the +//! ungrouped path, each batch its own `vkQueueSubmit`, which is what every batch took before +//! grouping and is exact alike -- a group changes when a `vkQueueSubmit` is made and nothing it +//! submits. Each command buffer of a group is exact on every driver by Vulkan's own rules (the +//! bullets below), so the check decides only where grouping pays. //! //! - **What waits.** A batch the scheduler submits waits here, submitted by nothing yet, where it //! signals nothing but its queue's timeline and its events' semaphores: no binary semaphore, @@ -88,8 +90,7 @@ use crate::exit_guard::{self, Call}; use crate::gpu_time; use crate::Device; use ash::vk; -use metal2vulkan::device::{CompletionPolicy, DriverFact}; -use std::collections::BTreeSet; +use metal2vulkan::device::CompletionPolicy; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -105,12 +106,11 @@ const BATCH_INFOS: usize = 2; const MOST_INFOS: usize = GROUP_BATCHES * BATCH_INFOS + 1 + BATCH_INFOS; /// Whether `device`'s batches on `VkQueue` `queue` may wait in a group: its policy groups them, -/// its driver is measured to merge a submission that signals nothing into the next (the module -/// docs), and the queue's failures are not relayed (each relayed batch takes a fence, -/// `device/relay.rs`). +/// its check found a submission that signals nothing merged into the next (the module docs), and +/// the queue's failures are not relayed (each relayed batch takes a fence, `device/relay.rs`). pub(crate) fn groups(device: &Device, queue: usize) -> bool { device.compile_device().policy().completion == CompletionPolicy::Grouped - && merges_submissions(&device.properties().driver_facts) + && device.submissions_merge() && device.shared().flights(queue).is_none() } @@ -174,14 +174,6 @@ const IN_GROUP: u8 = 1; /// A command buffer's `group_hold` bit: a thread waits for its completion. const WAITED_FOR: u8 = 2; -/// Whether the driver merges a `VkSubmitInfo` that signals nothing into the next one's kernel -/// submission ([`DriverFact::SubmissionsWithoutSignalsMerge`]): the driver's facts alone answer -/// it, and nothing of the driver's identity, so a test can hand it the facts of each committed -/// profile (`tests::batches::only_drivers_measured_to_merge_their_submissions_group_their_batches`). -pub(crate) fn merges_submissions(facts: &BTreeSet) -> bool { - facts.contains(&DriverFact::SubmissionsWithoutSignalsMerge) -} - /// What sent a group held (`WorkCounts::group_ends_full` and kin). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum GroupEnd { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 2df5b1ef7..c386c0101 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -54,11 +54,6 @@ mod submit; pub(super) use completion::Completion; pub(super) use first_submission::{NotedTable, ReplayTable}; use follow::{Follow, Release}; -/// Whether a driver's facts merge a submission that signals nothing into the next, for the test -/// that holds every committed profile to the fact -/// (`tests::batches::only_drivers_measured_to_merge_their_submissions_group_their_batches`). -#[cfg(test)] -pub(crate) use group::merges_submissions; pub(super) use group::{Group, GroupEnd, GROUP_BATCHES}; use rebound_use::{ReboundUse, Unlogged}; pub(super) use submit::{BatchLists, Submitting}; diff --git a/crates/metal2vulkan-runtime/src/device/holds.rs b/crates/metal2vulkan-runtime/src/device/holds.rs index 0656eef7e..927662122 100644 --- a/crates/metal2vulkan-runtime/src/device/holds.rs +++ b/crates/metal2vulkan-runtime/src/device/holds.rs @@ -1,6 +1,7 @@ -//! The runtime's own holds of a device: its check of textures in place (`in_place_check.rs`) and -//! its warm pass (`warm/pass.rs`), each on a thread of its own, which hold the device while they -//! make objects on it and let it go between their steps. +//! The runtime's own holds of a device: its check of textures in place (`in_place_check.rs`), its +//! submission checks (`submit_check.rs`) and its warm pass (`warm/pass.rs`), each on a thread of +//! its own, which hold the device while they make objects on it and let it go between their steps +//! (the submission checks, for their whole run, reading the stop between their steps). //! //! - **Two counts.** Every handle of the device is counted here, as the program's or as a //! holder's. A handle a holder takes ([`WeakDevice::hold`]) is a holder's, and so is each handle @@ -14,7 +15,8 @@ //! release of the program's last command buffer) it waits for nothing: those threads serve the //! work the holds may wait for, and the program's work there ends where it ends already. //! - **The wait is a step.** A holder reads the stop between its steps -//! ([`Device::holds_go_on`]): the check between its rounds, the warm pass between its records. +//! ([`Device::holds_go_on`]): the in-place check between its rounds, the submission checks +//! between theirs, the warm pass between its records. //! So the wait is at most the check's round in progress (and its release of its buffer), or the //! record the pass is making. It happens only at teardown. //! - **Exact.** A holder's take and a holder's handle's clone and drop count under the registry's @@ -43,6 +45,8 @@ pub(crate) enum Holder { InPlaceCheck, /// The warm pass, between its records. WarmPass, + /// The submission checks, between their rounds, phases and copies. + SubmitCheck, } /// A device's registry of its handles and the runtime's own holds (the module docs). @@ -63,7 +67,7 @@ pub(crate) struct Holds { /// The crate's device tests' holds of each holder between its steps /// (`tests/teardown_threads.rs`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - held: [crate::freed_memory::held::Held; 2], + held: [crate::freed_memory::held::Held; 3], } /// The registry's count of the holders' handles, and its stop. diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index d606c973c..3b79ef2d2 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -346,6 +346,9 @@ pub(super) struct DeviceShared { /// Its check of the first move of an image over host pages, per class of pages, and its /// verdicts (`in_place.rs`). pub(crate) in_place: crate::in_place::InPlaceChecks, + /// Its checks of what its submissions cost and whether its pointer imports follow their + /// address, and their verdicts (`submit_check.rs`). + pub(crate) submit_checks: crate::submit_check::SubmitChecks, /// How no-copy buffers import host memory, or why they are refused. pub(super) host_import: Result, /// Whether the device imports a pointer to shared memory, once asked @@ -1995,6 +1998,7 @@ impl Device { textures, shader_cache, in_place: crate::in_place::InPlaceChecks::new(fail_in_place_check), + submit_checks: crate::submit_check::SubmitChecks::new(), host_import, shared_pointer_imports: OnceLock::new(), extended_dynamic_state, @@ -2112,6 +2116,9 @@ impl Device { // Its check's verdict of the GPU idling between `VkQueue`s, where none is to be measured // or a record holds it (`queue_share.rs`). device.recall_queue_switch_check(); + // Its submission checks' verdicts, where a record holds them; else the checks start + // (`submit_check.rs`). + device.recall_submit_checks(); device.degrade_argument_buffers_unread(); device.degrade_float_tininess(); Ok(device) diff --git a/crates/metal2vulkan-runtime/src/host_residency.rs b/crates/metal2vulkan-runtime/src/host_residency.rs index fd889f831..ea5fc96d2 100644 --- a/crates/metal2vulkan-runtime/src/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/host_residency.rs @@ -21,12 +21,14 @@ //! pointer), where the device kept a descriptor of each dma-buf within the descriptors the //! process's devices keep at most ([`kept_fds_limit`]); an import past them is made as any //! other and stays imported; -//! - of its pages' pointer, on a driver whose pointer imports follow their address -//! (`DriverFact::PointerImportsFollowTheirAddress`: ANV on i915, RADV, lavapipe): there the -//! kept import reads, at each submission, the pages mapped at its pointer then, as an import -//! again at the same pointer does, so releasing it changes nothing a command reads. Elsewhere -//! a pointer import stays imported: the driver may keep the pages it was made over, as -//! Metal's buffer does, and an import again would read those a remap put there since. +//! - of its pages' pointer, on a device whose check found its pointer imports follow their +//! address (`submit_check.rs`, `Device::pointer_imports_follow_their_address`; ANV on i915, +//! RADV and lavapipe answered so): there the kept import reads, at each submission, the pages +//! mapped at its pointer then, as an import again at the same pointer does, so releasing it +//! changes nothing a command reads. Elsewhere, and in a buffer made before the check +//! answered, a pointer import stays imported: the driver may keep the pages it was made +//! over, as Metal's buffer does, and an import again would read those a remap put there +//! since. //! - **Blits alone.** It stays releasable while every read of its `VkBuffer` and memory was a //! blit's (`Buffer::blit_at`: a copy or fill naming the buffer, a copy between it and a //! texture, `synchronize_resource`), which holds what it read until its command buffer @@ -87,7 +89,6 @@ use super::exit_guard; use super::host_memory::ImportWindow; use super::memory::MemoryClass; use super::Device; -use metal2vulkan::device::DriverFact; use std::os::fd::OwnedFd; use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -210,17 +211,16 @@ impl Again { }) } - /// The pages imported at `pointer`, made again there: `None` where the device's driver may - /// keep the pages a pointer import was made over - /// (`DriverFact::PointerImportsFollowTheirAddress` not measured of it), so that the import + /// The pages imported at `pointer`, made again there: `None` where the device's pointer + /// imports may keep the pages they were made over (its check found they do, could not run, + /// or has not answered: `Device::pointer_imports_follow_their_address`), so that the import /// stays imported. pub(super) fn pointer( device: &Device, pointer: NonNull, (length, window, class): (u64, ImportWindow, MemoryClass), ) -> Option { - let follows = (device.properties().driver_facts) - .contains(&DriverFact::PointerImportsFollowTheirAddress); + let follows = device.pointer_imports_follow_their_address(); follows.then(|| Again { device: device.clone(), from: AgainFrom::Pointer(ImportedAt(pointer)), diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index feb2b98cb..6a5e71d61 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -8,9 +8,12 @@ //! refuses by their pointer, imported as dma-bufs), fills a window of it with a pattern, and //! makes a texture over it as the program does (`Buffer::new_runtime_texture`): the texture takes //! the image in place exactly as the product's would ([`checking`](crate::in_place::checking) -//! lets it whatever the verdict). A thread of its own then writes the pattern's complement into -//! the window, each byte once, at a stride that reaches texels, the bytes between rows and the -//! bytes after the image from its first writes, while the device makes the image's first move +//! lets it whatever the verdict); the fresh-pages class once the device's submission checks +//! answered whether its buffers take fresh pages (`submit_check.rs`), unchecked where they do +//! not, as the product then makes no such buffer. A thread of its own then writes the +//! pattern's complement into the window, each byte once, at a stride that reaches texels, the +//! bytes between rows and the bytes after the image from its first writes, while the device +//! makes the image's first move //! (an internal submission naming the texture, waited for) and until it completed. Every byte //! must then read the CPU's write where the CPU wrote it, and the pattern elsewhere. Each class //! runs every shape of [`SHAPES`] (texels of 1, 2, 4, 8 and 16 bytes, rows apart or one after @@ -119,6 +122,10 @@ impl Shape { } } +/// The longest the fresh-pages class waits for the device's submission checks, which answer +/// whether its buffers take fresh pages (`submit_check.rs`): their run takes milliseconds. +const SUBMIT_CHECKS_WAIT: std::time::Duration = std::time::Duration::from_secs(10); + /// The bytes of each class's buffer: past half a pooled block, so that a buffer of the runtime's /// own lies in fresh pages (`fresh_pages.rs`), and room for the largest shape's window. const BUFFER_BYTES: u64 = 40 << 20; @@ -303,6 +310,12 @@ impl ClassPages { /// A buffer of `length` bytes in pages of `class` on `device`, where the device makes one /// there; inside a section of its own. fn make(device: &Device, class: PagesClass, length: u64) -> Option { + // Whether the device's buffers take fresh pages is its submission checks' answer + // (`submit_check.rs`): the class is checked once they gave it, as the product makes its + // buffers then. + if matches!(class, PagesClass::Fresh) { + device.settle_submit_checks(SUBMIT_CHECKS_WAIT); + } let _busy = exit_guard::enter()?; match class { PagesClass::Pointer => pointer_pages(device, length), diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 606eab532..151d48730 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -222,6 +222,7 @@ mod spares; mod sparse; mod stencil_copy; mod storage_placeholder; +mod submit_check; mod tessellation; mod texture; mod texture_descriptor; diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs new file mode 100644 index 000000000..e016739c1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -0,0 +1,1228 @@ +//! 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 +//! the driver's ([`Check::Merge`]), whether a host-pointer import the device holds adds to the cost +//! of every submission ([`Check::ImportTax`]), and whether a pointer import reads the pages mapped +//! at its pointer at each submission ([`Check::Follows`]). Each answers a question the runtime +//! once read from the driver's identity, its `driverID`, vendor and `deviceID`, so that a GPU no +//! row named took every slow route: the check measures the device itself, and nothing of a +//! decision reads its identity. +//! +//! - **Merge.** [`ROUNDS`] rounds of each of two forms, alternating, each of [`MERGED`] empty +//! command buffers on the device's first `VkQueue`: one `vkQueueSubmit` of [`MERGED`] +//! `VkSubmitInfo`s, the last with a fence, against [`MERGED`] calls of one each, the last with +//! the fence; the time inside the calls. A driver whose one call costs at most [`MERGE_RATIO`] +//! of the calls apart merges them (`Holds`): Mesa's common queue does +//! (`vulkan/runtime/vk_queue.c`, `vk_queue_submits_merge`: "Don't merge if there are signals in +//! between"), so its batches may wait and go in one call (`command_buffer/group.rs`); elsewhere +//! each batch takes its own. Measured with a probe of the same rounds (2026-11-07, Mesa 26.2.6, +//! Linux 7.3.1): RADV on the Radeon 780M 13.2 against 37.3 us (0.35), the RX 7900 XTX 13.4 +//! against 35.0 (0.38), the RX 550 11.6 against 35.1 (0.33); ANV on the Iris Xe of RPL-P 5.1 +//! against 13.1 (0.39); MoltenVK 1.4.2 on the M3 Max 4.5 against 4.6 (0.98). +//! - **Import tax.** One import of [`TAX_BYTES`] of anonymous pages the check maps and writes, +//! by their pointer, held through every other of [`TAX_PHASES`] phases of [`TAX_SUBMITS`] +//! submissions of one empty command buffer with a fence, none held through the rest; the time +//! inside each call. Where the median with the import held passes the median without by more +//! than [`TAX_FLOOR`] or an eighth of it, whichever is more, a held import costs every +//! submission (`Holds`), and the runtime keeps its own long buffers out of fresh pages +//! (`fresh_pages.rs`): each would add that cost, and more for its length, to every submission +//! for its whole life, where its fresh pages save one clear of its bytes. RADV lists every +//! memory it imported in each kernel submission, and amdgpu gets every page of a pointer import +//! again in each (`amdgpu_cs_parser_bos`): the probe measured 10.3 us more a submission for one +//! import of 16 MiB on the Radeon 780M (24.1 for 64 MiB), 6.8 on the RX 7900 XTX (35.7), 45.8 +//! on the RX 550 (191.3), against 0.2 on the Iris Xe (as much as a plain allocation of 64 MiB +//! costs there) and none on the M3 Max. +//! - **Follows** (Linux alone). Two pages the check maps, the first written with a pattern, are +//! imported by their pointer and bound to a buffer; a copy of the first page into the second is +//! submitted, then new anonymous pages are mapped over the first (`mmap` with `MAP_FIXED`) and +//! written with another pattern, and the same copy submitted again; and a second pair, its first +//! page replaced before any submission, copied once. Where every copy read the pages mapped at +//! the first page's address as it was submitted, the driver's pointer imports follow their +//! address (`Holds`), and an idle no-copy buffer's import may be released and made again at its +//! pointer at its next use (`host_residency.rs`), which reads the pages the kept import would. +//! Where a copy read the pages the import was made over, the driver keeps them (`Fails`), as +//! NVIDIA's pins them, and as Metal wires a no-copy buffer's pages when it is made: such an +//! import stays live. Not run on another system: on macOS every Vulkan driver imports a pointer +//! through Metal, which wires the pages as it makes the buffer, so the import keeps them, and a +//! remap of pages the kernel wired is not made. Anonymous pages replace anonymous pages, mapped +//! throughout, so no submission meets a range without pages; only the first page of each pair +//! is replaced, and the GPU writes only the second. +//! - **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), with the same forms. +//! - **Its cost**: [`ROUNDS`] rounds of each merge form and [`TAX_PHASES`] phases of +//! [`TAX_SUBMITS`] submissions, each waited for, every command buffer empty; the import of +//! [`TAX_BYTES`] made and freed [`TAX_PHASES`] times over pages written once; and on Linux +//! three copies of 256 bytes. The probe's rounds took 3 to 12 ms on those devices. +//! - **Kept.** Once every check 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 +//! 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. +//! - **Its thread** holds its device through the registry of the runtime's own holds +//! (`device/holds.rs`) for its whole run, and reads the stop between its steps (each round, each +//! phase, each copy): the program's last drop stops it there and waits for the step in progress +//! and the release of its objects, so the device goes on the program's thread, and the check +//! ends unrecorded. Each step's Vulkan work runs inside a section of the exit guard +//! (`exit_guard.rs`). Its submissions are counted apart (`WorkCounts::submit_check_calls`), not +//! among the device's. + +use crate::device::holds::Holder; +use crate::device::relay::By; +use crate::device::submit_stalls::Uses; +use crate::device::{lock, Device, WeakDevice}; +use crate::exit_guard::{self, Call}; +use crate::in_place::DriverIdentity; +use crate::release; +use crate::shader_cache::store::{hex, Lookup}; +use ash::vk; +use sha2::{Digest, Sha256}; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicU8, Ordering}; +use std::sync::{Condvar, Mutex}; +use std::time::{Duration, Instant}; + +/// The command buffers of each merge round, and the `VkSubmitInfo`s of its one call. +pub(crate) const MERGED: usize = 4; + +/// The rounds of each merge form, after [`WARM`] of each untimed. +pub(crate) const ROUNDS: usize = 16; + +/// The untimed rounds of each form first. +const WARM: usize = 2; + +/// The most one call of the merge's infos costs, as a share of its calls apart, where the driver +/// merges them. +pub(crate) const MERGE_RATIO: f64 = 0.6; + +/// The bytes of the import the tax check holds: past the import's own cost, a length's +/// (amdgpu's work a page), half the shortest buffer of the runtime's own that takes fresh pages. +pub(crate) const TAX_BYTES: u64 = 16 << 20; + +/// The tax check's phases, every other one with the import held (the first without). +pub(crate) const TAX_PHASES: usize = 6; + +/// The submissions timed in each phase, after one untimed. +pub(crate) const TAX_SUBMITS: usize = 8; + +/// The least a held import adds to a submission, in nanoseconds, that the tax check counts: a +/// microsecond, about 0.25% of a core at the 2500 submissions a second of a guest's frames. +pub(crate) const TAX_FLOOR: i64 = 1_000; + +/// How long one wait for a fence lasts before it is repeated. +const WAIT_SLICE: Duration = Duration::from_millis(100); + +/// The bytes the follows check copies. +const COPIED: u64 = 256; + +/// A check, in the order they run and the record holds their verdicts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Check { + /// `VkSubmitInfo`s that signal nothing merge into one submission of the driver's. + Merge, + /// A held host-pointer import adds to every submission's cost. + ImportTax, + /// A pointer import reads the pages mapped at its pointer at each submission. + Follows, +} + +impl Check { + /// Every check, in order. + pub(crate) const ALL: [Check; 3] = [Check::Merge, Check::ImportTax, Check::Follows]; + + fn index(self) -> usize { + self as usize + } +} + +/// A check's verdict. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Verdict { + /// Not answered yet. + Pending, + /// The property holds. + Holds, + /// It does not. + Fails, + /// The check could not run. + Unchecked, +} + +impl Verdict { + fn byte(self) -> u8 { + match self { + Verdict::Pending => 0, + Verdict::Holds => 1, + Verdict::Fails => 2, + Verdict::Unchecked => 3, + } + } + + fn of_byte(byte: u8) -> Verdict { + match byte { + 1 => Verdict::Holds, + 2 => Verdict::Fails, + 3 => Verdict::Unchecked, + _ => Verdict::Pending, + } + } +} + +/// What the checks measured, in nanoseconds, in a record's order: one call of the merge's infos +/// and its calls apart (medians), and one submission with the import held and without. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Measured { + pub(crate) merged: i64, + pub(crate) apart: i64, + pub(crate) held: i64, + pub(crate) bare: i64, +} + +/// A device's verdicts of its submission checks, and their state (the module docs). +pub(crate) struct SubmitChecks { + verdicts: [AtomicU8; 3], + measured: [AtomicI64; 4], + started: AtomicBool, + settled: Mutex, + wake: Condvar, + /// The checks' run in this process, in nanoseconds; 0 where none ended. + took: AtomicU64, +} + +impl SubmitChecks { + /// A device's, every verdict pending. + pub(crate) fn new() -> SubmitChecks { + SubmitChecks { + verdicts: Default::default(), + measured: Default::default(), + started: AtomicBool::new(false), + settled: Mutex::new(false), + wake: Condvar::new(), + took: AtomicU64::new(0), + } + } + + /// `check`'s verdict now. + pub(crate) fn verdict(&self, check: Check) -> Verdict { + Verdict::of_byte(self.verdicts[check.index()].load(Ordering::Acquire)) + } + + /// Whether `check` answered that its property holds. + pub(crate) fn holds(&self, check: Check) -> bool { + self.verdict(check) == Verdict::Holds + } + + /// Whether `check` answered that its property does not hold. + pub(crate) fn fails(&self, check: Check) -> bool { + self.verdict(check) == Verdict::Fails + } + + fn set(&self, check: Check, verdict: Verdict) { + self.verdicts[check.index()].store(verdict.byte(), Ordering::Release); + } + + fn measured(&self) -> Measured { + let at = |i: usize| self.measured[i].load(Ordering::Acquire); + Measured { + merged: at(0), + apart: at(1), + held: at(2), + bare: at(3), + } + } + + 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); + } + } + + /// Note the checks started; whether they had not before. + fn start(&self) -> bool { + !self.started.swap(true, Ordering::AcqRel) + } + + /// Every verdict still pending is unchecked, and the checks settle. + fn settle_unchecked(&self) { + for check in Check::ALL { + if self.verdict(check) == Verdict::Pending { + self.set(check, Verdict::Unchecked); + } + } + self.settle(None); + } + + /// The verdicts are known, with the run where it ran here. + fn settle(&self, took: Option) { + if let Some(took) = took { + let nanos = u64::try_from(took.as_nanos()).unwrap_or(u64::MAX); + self.took.store(nanos.max(1), Ordering::Release); + } + *lock(&self.settled) = true; + self.wake.notify_all(); + } + + /// Wait until the verdicts are known, or `timeout` passed: whether they are. + fn wait(&self, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + let mut settled = lock(&self.settled); + while !*settled { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return false; + } + settled = match self.wake.wait_timeout(settled, left) { + Ok((settled, _)) => settled, + Err(poisoned) => poisoned.into_inner().0, + }; + } + true + } +} + +/// The merge's verdict from the medians of its two forms. +pub(crate) fn merge_verdict(merged: i64, apart: i64) -> Verdict { + match apart > 0 && merged as f64 <= MERGE_RATIO * apart as f64 { + true => Verdict::Holds, + false => Verdict::Fails, + } +} + +/// The import tax's verdict from the medians of a submission with the import held and without. +pub(crate) fn tax_verdict(held: i64, bare: i64) -> Verdict { + match held - bare > TAX_FLOOR.max(bare / 8) { + true => Verdict::Holds, + false => Verdict::Fails, + } +} + +/// The version of what the checks measure and of how their record is named and framed: a change +/// to either bumps it, and a record of another version is never read. +pub(crate) const CHECK_VERSION: u32 = 1; + +/// A record's first bytes. +const MAGIC: [u8; 8] = *b"M2VSUBC\0"; + +/// The domain tag of a record's name. +const NAME_TAG: &[u8] = b"metal2vulkan submission checks record\0"; + +/// A record's length: magic, version, runtime, identity, verdicts, measured, checksum. +const RECORD_BYTES: usize = 8 + 4 + 4 + 32 + 3 + 4 * 8 + 32; + +/// The kernel's release (`uname -r`), which the import tax's cost is the work of on RADV: empty +/// where the system answers none. +fn kernel_release() -> Vec { + #[cfg(unix)] + { + // SAFETY: an all-zero `utsname` is a valid value for `uname` to fill. + let mut name: libc::utsname = unsafe { std::mem::zeroed() }; + // SAFETY: `name` is a valid `utsname` to write. + if unsafe { libc::uname(&mut name) } == 0 { + return (name.release.iter()) + .take_while(|&&c| c != 0) + .map(|&c| c as u8) + .collect(); + } + } + Vec::new() +} + +/// The digest of `identity` and the kernel's release that names a record and that the record +/// holds again. +fn digest(identity: &DriverIdentity) -> [u8; 32] { + let mut kind = b"submissions\0".to_vec(); + kind.extend_from_slice(&kernel_release()); + kind.push(0); + identity.digest_for(NAME_TAG, &kind, CHECK_VERSION) +} + +/// The name of the record of `identity`'s verdicts in the shader cache's content directory. +pub(crate) fn record_name(identity: &DriverIdentity) -> String { + hex(&digest(identity)) +} + +/// The bytes of a record of `verdicts` and `measured` for `identity`: +/// +/// ```text +/// magic 8 bytes "M2VSUBC\0" +/// version u32 CHECK_VERSION +/// runtime u32 RUNTIME_VERSION +/// identity 32 bytes the identity's and the kernel's digest for these checks +/// verdicts 3 bytes one per check, in Check::ALL's order: Holds 1, Fails 2, Unchecked 3 +/// measured 4 x i64 merged, apart, held, bare, in nanoseconds +/// checksum 32 bytes SHA-256 of every byte before it +/// ``` +/// +/// Integers are little-endian. +pub(crate) fn encode( + identity: &DriverIdentity, + verdicts: [Verdict; 3], + measured: Measured, +) -> Vec { + 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(&digest(identity)); + bytes.extend(verdicts.map(Verdict::byte)); + for value in [ + measured.merged, + measured.apart, + measured.held, + measured.bare, + ] { + bytes.extend_from_slice(&value.to_le_bytes()); + } + let checksum: [u8; 32] = Sha256::digest(&bytes).into(); + bytes.extend_from_slice(&checksum); + 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. +pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<([Verdict; 3], Measured)> { + if bytes.len() != RECORD_BYTES { + return None; + } + let (body, checksum) = bytes.split_at(RECORD_BYTES - 32); + let computed: [u8; 32] = Sha256::digest(body).into(); + if computed[..] != *checksum { + return None; + } + let (magic, rest) = body.split_at(8); + let (version, rest) = rest.split_at(4); + let (runtime, rest) = rest.split_at(4); + let (identity_digest, rest) = rest.split_at(32); + let (verdicts, rest) = rest.split_at(3); + 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 + || identity_digest != digest(identity) + { + return None; + } + let verdicts = [0, 1, 2].map(|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), + apart: value(1), + held: value(2), + bare: value(3), + }; + Some((verdicts, measured)) +} + +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. + pub(crate) fn recall_submit_checks(&self) { + let shared = self.shared(); + 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); + return; + } + self.start_submit_checks(); + } + + /// 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) { + let checks = &self.shared().submit_checks; + if !checks.start() { + return; + } + let weak = self.downgrade(); + let builder = std::thread::Builder::new().name("m2v-submit-check".to_owned()); + if exit_guard::spawn(builder, move || run(&weak)).is_err() { + checks.settle_unchecked(); + } + } + + /// Whether the device's `VkSubmitInfo`s that signal nothing merge into one submission of the + /// driver's, as its check found (`submit_check.rs`), so that its batches may wait in a group + /// (`CompletionPolicy::Grouped`): `false` until it answers. A runtime extension for the lanes + /// that hold a device to the path it chooses. + #[doc(hidden)] + pub fn submissions_merge(&self) -> bool { + self.shared().submit_checks.holds(Check::Merge) + } + + /// Whether the device's long buffers of its own take fresh pages (`fresh_pages.rs`): its + /// check found a held import adds nothing to a submission's cost (`submit_check.rs`); `false` + /// until it answers. A runtime extension for the lanes that hold a device to the path it + /// chooses. + #[doc(hidden)] + pub fn fresh_pages_pay(&self) -> bool { + self.shared().submit_checks.fails(Check::ImportTax) + } + + /// No Metal counterpart: whether the device's imports of host memory by its pointer read the + /// pages mapped at the pointer at each submission, as its check found: `true` where they do, + /// and an idle no-copy buffer's import is released and made again at its next use; `false` + /// where they keep the pages they were made over (as Metal's no-copy buffer does), where the + /// check could not run or did not run (macOS), and until it answers + /// ([`settle_submit_checks`](Device::settle_submit_checks) waits for it). A runtime extension: + /// where it is `true`, pages mapped over a live no-copy buffer's addresses are what its later + /// command buffers read and write. + pub fn pointer_imports_follow_their_address(&self) -> bool { + self.shared().submit_checks.holds(Check::Follows) + } + + /// Wait until the device's submission checks answered, or `timeout` passed: whether they did. + /// A runtime extension for the lanes and benchmarks that hold a device to the paths its + /// verdicts choose. + #[doc(hidden)] + pub fn settle_submit_checks(&self, timeout: Duration) -> bool { + self.shared().submit_checks.wait(timeout) + } + + /// The device's submission checks' verdicts and measurements, and how long they ran in this + /// process, in words. A runtime extension for the lanes and benchmarks that report them. + #[doc(hidden)] + pub fn submit_check_report(&self) -> String { + let checks = &self.shared().submit_checks; + let m = checks.measured(); + let us = |nanos: i64| nanos as f64 / 1e3; + let took = match checks.took.load(Ordering::Acquire) { + 0 => "not run here".to_owned(), + nanos => format!("ran {:.2} ms", nanos as f64 / 1e6), + }; + format!( + "merge {:?} ({:.1} us in one call of {MERGED} against {:.1} us apart), import tax \ + {:?} ({:.1} us a submission with {} MiB held against {:.1} us), follows {:?}, {took}", + checks.verdict(Check::Merge), + us(m.merged), + us(m.apart), + checks.verdict(Check::ImportTax), + us(m.held), + TAX_BYTES >> 20, + us(m.bare), + checks.verdict(Check::Follows), + ) + } +} + +/// The checks' thread: the device held through its run, each check's verdict given as it is +/// known, then the record. Stopped by the program's last drop, it records nothing. +fn run(weak: &WeakDevice) { + let Some(device) = weak.hold() else { + return; + }; + let started = Instant::now(); + let checks = &device.shared().submit_checks; + let Some(objects) = Objects::make(&device) else { + checks.settle_unchecked(); + return; + }; + let ran = measure(&device, &objects); + let released = objects.release(&device); + let Some(measured) = ran.filter(|_| released) else { + // The process is exiting, or the program let the device go: nothing is kept. + return; + }; + checks.set_measured(measured); + device.shared().counts.submit_checks_ran(); + let verdicts = Check::ALL.map(|check| checks.verdict(check)); + if !verdicts.contains(&Verdict::Pending) { + let identity = device.driver_identity(); + let bytes = encode(&identity, verdicts, measured); + // A failed write leaves the verdicts to the device's life alone. + let _ = (device.shared().shader_cache.content_store()) + .write_record_soon(&record_name(&identity), bytes); + } + checks.settle(Some(started.elapsed())); +} + +/// Each check in turn, its verdict set as it is known: what they measured, `None` where the +/// process is exiting or the program's last drop stopped the device's holds. +fn measure(device: &Device, objects: &Objects) -> Option { + let checks = &device.shared().submit_checks; + let mut measured = Measured::default(); + match merge(device, objects)? { + Some((merged, apart)) => { + measured.merged = merged; + measured.apart = apart; + checks.set(Check::Merge, merge_verdict(merged, apart)); + } + None => checks.set(Check::Merge, Verdict::Unchecked), + } + match tax(device, objects)? { + Some((held, bare)) => { + measured.held = held; + measured.bare = bare; + checks.set(Check::ImportTax, tax_verdict(held, bare)); + } + None => checks.set(Check::ImportTax, Verdict::Unchecked), + } + checks.set(Check::Follows, follows(device, objects)?); + Some(measured) +} + +/// Whether the check goes on to its next step (the program's last drop stops it). +fn goes_on(device: &Device) -> bool { + device.holds_go_on(Holder::SubmitCheck) +} + +/// The merge's medians, in nanoseconds: one call of [`MERGED`] infos, and [`MERGED`] calls. +/// `Some(None)` where a call was refused; `None` where the check stops. +fn merge(device: &Device, objects: &Objects) -> Option> { + let mut merged = Vec::with_capacity(ROUNDS); + let mut apart = Vec::with_capacity(ROUNDS); + for round in 0..WARM + ROUNDS { + for together in [true, false] { + if !goes_on(device) { + return None; + } + let Some(nanos) = objects.submit_round(device, together)? else { + return Some(None); + }; + if round >= WARM { + match together { + true => merged.push(nanos), + false => apart.push(nanos), + } + } + } + } + Some(Some((median(&mut merged), median(&mut apart)))) +} + +/// The import tax's medians, in nanoseconds: a submission with the import of [`TAX_BYTES`] +/// 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(device: &Device, objects: &Objects) -> Option> { + let Some(pages) = Pages::map(TAX_BYTES) else { + return Some(None); + }; + pages.fill(0x5a); + let mut held = Vec::with_capacity(TAX_PHASES / 2 * TAX_SUBMITS); + let mut bare = Vec::with_capacity(TAX_PHASES / 2 * TAX_SUBMITS); + for phase in 0..TAX_PHASES { + let holding = phase % 2 == 1; + if !goes_on(device) { + return None; + } + let import = match holding { + true => match Import::make(device, &pages, false)? { + Some(import) => Some(import), + None => return Some(None), + }, + false => None, + }; + let mut times = Vec::with_capacity(TAX_SUBMITS); + let mut refused = false; + for submission in 0..=TAX_SUBMITS { + match objects.submit_one(device)? { + Some(nanos) if submission > 0 => times.push(nanos), + Some(_) => {} + None => { + refused = true; + break; + } + } + } + if let Some(import) = import { + import.release(device)?; + } + if refused { + return Some(None); + } + match holding { + true => held.extend(times), + false => bare.extend(times), + } + } + Some(Some((median(&mut held), median(&mut bare)))) +} + +/// The follows check's verdict (the module docs); `None` where the check stops. +#[cfg(target_os = "linux")] +fn follows(device: &Device, objects: &Objects) -> Option { + let Some(page) = crate::host_memory::host_page() else { + return Some(Verdict::Unchecked); + }; + // The kept import, its first page replaced between two submissions. + let Some(kept) = follows_pair(device, objects, page, false)? else { + return Some(Verdict::Unchecked); + }; + if !goes_on(device) { + return None; + } + // An import whose first page is replaced before its first submission. + let Some(fresh) = follows_pair(device, objects, page, true)? else { + return Some(Verdict::Unchecked); + }; + Some(match (kept, fresh) { + (Read::New, Read::New) => Verdict::Holds, + (Read::Old, Read::Old) => Verdict::Fails, + _ => Verdict::Unchecked, + }) +} + +/// Not run off Linux (the module docs). +#[cfg(not(target_os = "linux"))] +fn follows(_device: &Device, _objects: &Objects) -> Option { + Some(Verdict::Unchecked) +} + +/// What a copy of the replaced page read. +#[cfg(target_os = "linux")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Read { + /// The pages the import was made over. + Old, + /// The pages mapped over them. + New, + /// Neither. + Other, +} + +/// Patterns the follows check writes: the pages an import was made over, and those mapped over +/// them. +#[cfg(target_os = "linux")] +const OLD: u8 = 0xa1; +#[cfg(target_os = "linux")] +const NEW: u8 = 0xb2; + +/// One pair of pages imported and copied (the module docs): what the copy after the remap read +/// (`before_first` replaces the first page before any submission). `Some(None)` where the device +/// takes no such import or a copy failed; `None` where the check stops. +#[cfg(target_os = "linux")] +fn follows_pair( + device: &Device, + objects: &Objects, + page: u64, + before_first: bool, +) -> Option> { + let Some(pages) = Pages::map(2 * page) else { + return Some(None); + }; + pages.fill(OLD); + let Some(import) = Import::make(device, &pages, true)? else { + return Some(None); + }; + let read = |pages: &Pages| { + // SAFETY: the second page is the check's, mapped, and no copy into it is pending. + let bytes = unsafe { + std::slice::from_raw_parts(pages.start.as_ptr().add(page as usize), COPIED as usize) + }; + match bytes { + _ if bytes.iter().all(|&b| b == OLD) => Read::Old, + _ if bytes.iter().all(|&b| b == NEW) => Read::New, + _ => Read::Other, + } + }; + let answer = (|| { + if !before_first { + pages.clear_second(page); + if !objects.copy(device, &import, page)? { + return Some(None); + } + if read(&pages) != Read::Old { + return Some(None); + } + } + if !pages.replace_first(page) { + return Some(None); + } + pages.clear_second(page); + if !objects.copy(device, &import, page)? { + return Some(None); + } + Some(Some(read(&pages))) + })(); + import.release(device)?; + answer +} + +/// Anonymous private pages the check maps, read-write, unmapped as this goes, after every import +/// of them was freed. +struct Pages { + start: NonNull, + length: u64, +} + +impl Pages { + /// `length` bytes of new pages; `None` where the system maps none. + #[cfg(unix)] + fn map(length: u64) -> Option { + let bytes = usize::try_from(length).ok()?; + // SAFETY: a new private anonymous mapping, at an address the kernel picks. + let pointer = unsafe { + libc::mmap( + std::ptr::null_mut(), + bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_ANON | libc::MAP_PRIVATE, + -1, + 0, + ) + }; + if pointer == libc::MAP_FAILED { + return None; + } + Some(Pages { + start: NonNull::new(pointer.cast())?, + length, + }) + } + + /// None off Unix. + #[cfg(not(unix))] + fn map(_length: u64) -> Option { + None + } + + /// Write `byte` into every byte. + fn fill(&self, byte: u8) { + // SAFETY: the pages are the check's, mapped read-write, and nothing reads them meanwhile. + unsafe { std::ptr::write_bytes(self.start.as_ptr(), byte, self.length as usize) }; + } + + /// Zero the second page's bytes the copy writes. + #[cfg(target_os = "linux")] + fn clear_second(&self, page: u64) { + // SAFETY: as `fill`; no copy into the page is pending. + unsafe { + std::ptr::write_bytes(self.start.as_ptr().add(page as usize), 0, COPIED as usize) + }; + } + + /// Map new anonymous pages over the first page (`MAP_FIXED`), written with [`NEW`]: whether + /// the system did. + #[cfg(target_os = "linux")] + fn replace_first(&self, page: u64) -> bool { + // SAFETY: the first page is the check's own mapping, replaced in one call, so the range + // is mapped throughout; no copy of it is pending. + let pointer = unsafe { + libc::mmap( + self.start.as_ptr().cast(), + page as usize, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_ANON | libc::MAP_PRIVATE | libc::MAP_FIXED, + -1, + 0, + ) + }; + if pointer != self.start.as_ptr().cast() { + return false; + } + // SAFETY: the new page is mapped read-write, the check's. + unsafe { std::ptr::write_bytes(self.start.as_ptr(), NEW, page as usize) }; + true + } +} + +impl Drop for Pages { + fn drop(&mut self) { + #[cfg(unix)] + // SAFETY: the mapping is the check's, and every import of it was freed first (each + // `Import` is released before its pages go). + unsafe { + libc::munmap(self.start.as_ptr().cast(), self.length as usize); + } + } +} + +/// An import of a [`Pages`]' bytes by their pointer, in its own `VkDeviceMemory`, and, for the +/// follows check, a buffer bound to it. +struct Import { + memory: vk::DeviceMemory, + buffer: vk::Buffer, +} + +impl Import { + /// The import of `pages`, with a buffer bound where `bound`, in a host-coherent type the + /// pointer takes. `Some(None)` where the device imports no host pointer, the pages take no + /// such type, or a call was refused; `None` where the process is exiting. + fn make(device: &Device, pages: &Pages, bound: bool) -> Option> { + let shared = device.shared(); + let Ok(importer) = &shared.host_import else { + return Some(None); + }; + let _busy = exit_guard::enter()?; + let raw = shared.vk(); + // SAFETY: the pages are this process's, at a host page, whose size the import alignment + // divides where the device imports at all (it is checked below). + let Ok(types) = (unsafe { importer.memory_types(raw, pages.start) }) else { + return Some(None); + }; + let unit = importer.page.max(importer.alignment); + if !pages.length.is_multiple_of(unit) || !(pages.start.as_ptr() as u64).is_multiple_of(unit) + { + return Some(None); + } + let mut buffer = vk::Buffer::null(); + let mut allowed = types; + if bound { + let mut external = vk::ExternalMemoryBufferCreateInfo::default() + .handle_types(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .size(pages.length) + .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST) + .push_next(&mut external), + ); + // SAFETY: the device is live and `info` and its chain valid, inside a section. + buffer = match unsafe { crate::creation::buffer(raw, &info) } { + Ok(buffer) => buffer, + Err(_) => return Some(None), + }; + exit_guard::called(Call::CreateBuffer); + // SAFETY: `buffer` is a live buffer of this device. + let requirements = unsafe { raw.get_buffer_memory_requirements(buffer) }; + exit_guard::called(Call::GetBufferMemoryRequirements); + allowed &= requirements.memory_type_bits; + } + let coherent = + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; + let memory = lock(&shared.memory); + let type_index = (0..32).find(|&index| { + allowed & (1 << index) != 0 + && memory + .type_flags(index) + .is_some_and(|flags| flags.contains(coherent)) + }); + drop(memory); + let discard = |buffer: vk::Buffer| { + if buffer != vk::Buffer::null() { + // SAFETY: the buffer is unused. + unsafe { release::object(raw, buffer) }; + } + }; + let Some(type_index) = type_index else { + discard(buffer); + return Some(None); + }; + let mut import = vk::ImportMemoryHostPointerInfoEXT::default() + .handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT) + .host_pointer(pages.start.as_ptr().cast()); + let info = vk::MemoryAllocateInfo::default() + .allocation_size(pages.length) + .memory_type_index(type_index) + .push_next(&mut import); + // SAFETY: the pages stay mapped until after this memory is freed (`Pages` outlives every + // `Import`, released first), at a multiple of the import alignment, of a type they take. + let memory = match unsafe { crate::creation::allocate_memory(raw, &info) } { + Ok(memory) => memory, + Err(_) => { + exit_guard::called(Call::AllocateMemory); + discard(buffer); + return Some(None); + } + }; + exit_guard::called(Call::AllocateMemory); + if bound { + // SAFETY: the memory is the pages', of a type the buffer takes and its whole length; + // the buffer is unbound. + if unsafe { crate::creation::bind_buffer(raw, buffer, memory, 0) }.is_err() { + exit_guard::called(Call::BindBufferMemory); + discard(buffer); + // SAFETY: the memory is unused. + unsafe { release::object(raw, memory) }; + return Some(None); + } + exit_guard::called(Call::BindBufferMemory); + } + Some(Some(Import { memory, buffer })) + } + + /// Free it, inside a section: `None` where the process is exiting, the import then left to + /// its end (and its pages never unmapped before it, as the process ends first). + fn release(self, device: &Device) -> Option<()> { + let Some(_busy) = exit_guard::enter() else { + std::mem::forget(self); + return None; + }; + let raw = device.shared().vk(); + // SAFETY: no submission that names them is pending (each was waited for). + unsafe { + if self.buffer != vk::Buffer::null() { + release::object(raw, self.buffer); + } + release::object(raw, self.memory); + } + Some(()) + } +} + +/// The checks' Vulkan objects: a command pool of the first `VkQueue`'s family, [`MERGED`] empty +/// command buffers and one for the follows check's copy, and a fence. +struct Objects { + pool: vk::CommandPool, + empty: Vec, + copy: vk::CommandBuffer, + fence: vk::Fence, +} + +impl Objects { + /// The objects, the empty command buffers recorded; `None` where a call was refused (what was + /// made released) or the process is exiting. + fn make(device: &Device) -> Option { + let shared = device.shared(); + let _busy = exit_guard::enter()?; + let raw = shared.vk(); + let info = vk::CommandPoolCreateInfo::default() + .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER) + .queue_family_index(shared.queues[0].family); + // SAFETY: the device is live, inside a section. + let pool = unsafe { raw.create_command_pool(&info, None) }; + exit_guard::called(Call::CreateCommandPool); + let mut objects = Objects { + pool: pool.ok()?, + empty: Vec::new(), + copy: vk::CommandBuffer::null(), + fence: vk::Fence::null(), + }; + if objects.fill(device).is_none() { + drop(_busy); + objects.release(device); + return None; + } + Some(objects) + } + + /// Make and record the command buffers and make the fence, inside the caller's section. + fn fill(&mut self, device: &Device) -> Option<()> { + let shared = device.shared(); + let raw = shared.vk(); + let allocate = vk::CommandBufferAllocateInfo::default() + .command_pool(self.pool) + .level(vk::CommandBufferLevel::PRIMARY) + .command_buffer_count(MERGED as u32 + 1); + // SAFETY: the pool is the check's, which this thread alone uses; the device's loader word + // is put back first (`loader_word.rs`). + let allocated = unsafe { + shared.loader_word.restore(); + raw.allocate_command_buffers(&allocate) + }; + exit_guard::called(Call::AllocateCommandBuffers); + let mut buffers = allocated.ok()?; + self.copy = buffers.pop()?; + self.empty = buffers; + let begin = vk::CommandBufferBeginInfo::default(); + for &buffer in &self.empty { + // SAFETY: a new command buffer of the pool, recorded once on this thread. + unsafe { + raw.begin_command_buffer(buffer, &begin).ok()?; + exit_guard::called(Call::BeginCommandBuffer); + raw.end_command_buffer(buffer).ok()?; + exit_guard::called(Call::EndCommandBuffer); + } + } + // SAFETY: the device is live, inside a section. + self.fence = unsafe { raw.create_fence(&vk::FenceCreateInfo::default(), None) }.ok()?; + exit_guard::called(Call::CreateFence); + Some(()) + } + + /// Submit `infos` to the device's first `VkQueue`, the last signalling the fence, in one call + /// where `together`, else one call each, and wait for the fence: the nanoseconds inside the + /// calls. `Some(None)` where a call was refused or the wait failed; `None` where the process + /// is exiting. + fn submit( + &self, + device: &Device, + buffers: &[vk::CommandBuffer], + together: bool, + ) -> Option> { + let shared = device.shared(); + let calls = match together { + true => 1, + false => buffers.len(), + }; + let nanos = { + let _busy = exit_guard::enter()?; + let raw = shared.vk(); + let infos: Vec> = (buffers.iter()) + .map(|buffer| { + vk::SubmitInfo::default().command_buffers(std::slice::from_ref(buffer)) + }) + .collect(); + // SAFETY: the queue is used under its lock, inside a section; each command buffer is + // recorded, ended and in no pending submission (each round waits for the last); the + // fence is unsignaled and in no pending submission. + let submitted = shared.use_queue(0, By::Runtime, Uses::Unknown, |queue| unsafe { + let mut spent = Duration::ZERO; + let last = infos.len() - 1; + let parts: Vec<(&[vk::SubmitInfo<'_>], vk::Fence)> = match together { + true => vec![(&infos[..], self.fence)], + false => (infos.iter().enumerate()) + .map(|(i, info)| { + let fence = if i == last { + self.fence + } else { + vk::Fence::null() + }; + (std::slice::from_ref(info), fence) + }) + .collect(), + }; + for (infos, fence) in parts { + let start = Instant::now(); + let made = raw.queue_submit(queue, infos, fence); + spent += start.elapsed(); + if made.is_err() { + return Err(spent); + } + } + Ok(spent) + }); + exit_guard::called(Call::QueueSubmit); + shared.counts.submit_check_called(calls); + match submitted { + Ok(spent) => Some(spent), + Err(_) if calls > 1 => None, + Err(_) => return Some(None), + } + }; + // A refused call among several: those before it, and so the fence, were not all + // submitted, so the device waits for its queue rather than the fence. + let Some(nanos) = nanos else { + return self.idle(device).map(|_| None); + }; + if !self.wait(device)? { + return Some(None); + } + Some(Some(i64::try_from(nanos.as_nanos()).unwrap_or(i64::MAX))) + } + + /// One merge round ([`submit`](Self::submit) of every empty command buffer). + fn submit_round(&self, device: &Device, together: bool) -> Option> { + self.submit(device, &self.empty, together) + } + + /// One submission of one empty command buffer with the fence. + fn submit_one(&self, device: &Device) -> Option> { + self.submit(device, &self.empty[..1], true) + } + + /// Record and submit a copy of [`COPIED`] bytes from the start of `import`'s buffer to + /// `page` bytes in, then a barrier to the host's reads, and wait for it: whether it ran. + /// `None` where the process is exiting. + #[cfg(target_os = "linux")] + fn copy(&self, device: &Device, import: &Import, page: u64) -> Option { + { + let _busy = exit_guard::enter()?; + let raw = device.shared().vk(); + let region = vk::BufferCopy::default().dst_offset(page).size(COPIED); + let barrier = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) + .dst_access_mask(vk::AccessFlags::HOST_READ); + let begin = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + // SAFETY: the copy command buffer is the check's, in no pending submission (each is + // waited for), its pool made to reset its buffers; the buffer is live, and its two + // ranges do not overlap. + unsafe { + if raw.begin_command_buffer(self.copy, &begin).is_err() { + return Some(false); + } + exit_guard::called(Call::BeginCommandBuffer); + raw.cmd_copy_buffer(self.copy, import.buffer, import.buffer, &[region]); + exit_guard::called(Call::CmdCopyBuffer); + raw.cmd_pipeline_barrier( + self.copy, + vk::PipelineStageFlags::TRANSFER, + vk::PipelineStageFlags::HOST, + vk::DependencyFlags::empty(), + &[barrier], + &[], + &[], + ); + exit_guard::called(Call::CmdPipelineBarrier); + if raw.end_command_buffer(self.copy).is_err() { + return Some(false); + } + exit_guard::called(Call::EndCommandBuffer); + } + } + Some(self.submit(device, &[self.copy], true)?.is_some()) + } + + /// Wait for the fence, a slice at a time, each a section, then reset it: whether it was + /// signalled. `None` where the process is exiting. + fn wait(&self, device: &Device) -> Option { + loop { + let _busy = exit_guard::enter()?; + let raw = device.shared().vk(); + // SAFETY: the check's fence, signalled by a submission made. + let waited = + unsafe { raw.wait_for_fences(&[self.fence], true, WAIT_SLICE.as_nanos() as u64) }; + exit_guard::called(Call::WaitForFences); + match waited { + Ok(()) => { + // SAFETY: the fence is signalled, in no pending submission. + let reset = unsafe { raw.reset_fences(&[self.fence]) }; + exit_guard::called(Call::ResetFences); + return Some(reset.is_ok()); + } + Err(vk::Result::TIMEOUT) => continue, + Err(_) => return Some(false), + } + } + } + + /// Wait until the first `VkQueue` is idle and reset the fence, after a refused call: `None` + /// where the process is exiting. + fn idle(&self, device: &Device) -> Option<()> { + let _busy = exit_guard::enter()?; + let shared = device.shared(); + let raw = shared.vk(); + // SAFETY: the queue is used under its lock, inside a section. + let _ = shared.use_queue(0, By::Runtime, Uses::Unknown, |queue| unsafe { + raw.queue_wait_idle(queue) + }); + exit_guard::called(Call::QueueWaitIdle); + // SAFETY: no submission of the fence is pending once the queue is idle. + let _ = unsafe { raw.reset_fences(&[self.fence]) }; + exit_guard::called(Call::ResetFences); + Some(()) + } + + /// 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. + fn release(&self, device: &Device) -> bool { + let Some(_busy) = exit_guard::enter() else { + return false; + }; + let raw = device.shared().vk(); + // SAFETY: no pending submission names them; a null handle is skipped. + unsafe { + if self.fence != vk::Fence::null() { + release::object(raw, self.fence); + } + release::object(raw, self.pool); + } + true + } +} + +/// The median of `values` (sorted here); 0 for none. +fn median(values: &mut [i64]) -> i64 { + values.sort_unstable(); + values.get(values.len() / 2).copied().unwrap_or(0) +} diff --git a/crates/metal2vulkan-runtime/src/tests/batches.rs b/crates/metal2vulkan-runtime/src/tests/batches.rs index 4f8edd806..38e5c5c54 100644 --- a/crates/metal2vulkan-runtime/src/tests/batches.rs +++ b/crates/metal2vulkan-runtime/src/tests/batches.rs @@ -1,10 +1,9 @@ //! A command buffer's batches (`command_buffer/batches.rs`): where event waits and signals, and -//! binary semaphore waits and signals, split its encoders; which drivers' batches may wait in -//! a group (`command_buffer/group.rs`); and which drivers' queue failures are relayed -//! (`device/relay.rs`). +//! binary semaphore waits and signals, split its encoders; and which drivers' queue failures are +//! relayed (`device/relay.rs`). Which devices' batches may wait in a group is their check's +//! (`tests/submit_check.rs`). use crate::command_buffer::batches::{Batch, Batches}; -use crate::command_buffer::merges_submissions; use metal2vulkan::device::{DeviceDescription, DriverFact}; use metal2vulkan::vk::DriverId; @@ -265,60 +264,6 @@ fn signals_after_a_failing_encoder_are_dropped() { ); } -/// Whether a driver's batches may wait in one kernel submission is the driver's **fact**, never -/// its name (`command_buffer/group.rs`): a driver measured to merge a `vkQueueSubmit`'s -/// `VkSubmitInfo`s that signal nothing into the next one's kernel submission -/// (`DriverFact::SubmissionsWithoutSignalsMerge`) groups its batches; every other driver takes the -/// ungrouped path, each batch its own call, which is exact alike. -/// -/// The check over every committed profile: a profile groups only where its driver is one the fact -/// is measured of, so a decision that read the driver's name -- the Mesa drivers no lane measured -/// read alike there -- would answer otherwise for one of them. A `MEASURED` row written without a -/// measurement would show here as a MoltenVK, NVIDIA or SwiftShader profile that groups. -#[test] -fn only_drivers_measured_to_merge_their_submissions_group_their_batches() { - let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles"); - let mut read = 0; - let mut grouped = 0; - for entry in std::fs::read_dir(&dir).expect("validation/profiles is readable") { - let path = entry.expect("directory entry").path(); - if path.extension().is_none_or(|x| x != "json") { - continue; - } - let text = std::fs::read_to_string(&path).expect("profile is readable"); - let description = - DeviceDescription::from_khronos_json(&text, None).expect("profile parses"); - let merges = merges_submissions(&description.driver_facts()); - if merges { - // Only a driver the fact is measured of: Mesa's RADV, ANV and llvmpipe. - assert!( - matches!( - description.driver_id, - Some( - DriverId::MESA_RADV - | DriverId::INTEL_OPEN_SOURCE_MESA - | DriverId::MESA_LLVMPIPE - ) - ), - "{} groups its batches with no row of its driver", - path.display() - ); - grouped += 1; - } - read += 1; - } - assert!(read > 1, "profiles read: {read}"); - // The grouped form is reachable, and the fact alone chooses it. - assert!(grouped > 0, "profiles that group: {grouped}"); - assert!(merges_submissions( - &[DriverFact::SubmissionsWithoutSignalsMerge] - .into_iter() - .collect() - )); - assert!(!merges_submissions(&Default::default())); -} - /// Whether a device's queue failures are relayed to the command buffers that failed is the /// driver's **fact**, never its name (`device/mod.rs`, `device/relay.rs`): a driver that reports /// a command buffer's execution failure through the instance's messenger alone, and loses the diff --git a/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs b/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs index e7fdf6503..847a066e3 100644 --- a/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs +++ b/crates/metal2vulkan-runtime/src/tests/fresh_pages.rs @@ -2,8 +2,10 @@ //! //! - **A long new buffer reads zero, nothing written.** A `Shared` buffer, a write-combined one //! and a `Managed` one (with unified memory), each longer than half a pooled block: the `Shared` -//! one lies in fresh pages wherever the device imports host pointers -//! (`WorkCounts::fresh_page_buffers_made`), with the host setting none of its bytes to zero +//! one lies in fresh pages wherever the device imports host pointers and its check found a held +//! import adds nothing to a submission's cost (`submit_check.rs`; MoltenVK, ANV, lavapipe), and +//! never where it found it does (RADV) (`WorkCounts::fresh_page_buffers_made`), with the host +//! setting none of its bytes to zero //! (`new_buffer_bytes_cleared` unchanged); a class whose best memory type for the buffer takes //! no import lies where it would have, the host clearing every byte of it //! (a discrete card's write-combined class, measured below). Either way the buffer reads zero @@ -44,7 +46,7 @@ use std::path::Path; /// read too. const LONG: u64 = FRESH_PAGES_PAST + 4100; -/// The device the cfg selects, its shader cache in `cache`. +/// The device the cfg selects, its shader cache in `cache`, its submission checks answered. fn device(cache: &Path) -> Device { let options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { @@ -61,12 +63,18 @@ fn device(cache: &Path) -> Device { }, ..DeviceOptions::default() }; - Device::system_default_with(&options).unwrap() + let device = Device::system_default_with(&options).unwrap(); + assert!( + device.settle_submit_checks(crate::tests::SETTLE), + "the submission checks never answered" + ); + device } -/// Whether the device takes fresh pages: it imports host pointers. +/// Whether the device takes fresh pages: it imports host pointers, and its check found a held +/// import adds nothing to a submission's cost. fn takes_fresh_pages(device: &Device) -> bool { - device.shared().host_import.is_ok() + device.shared().host_import.is_ok() && device.fresh_pages_pay() } /// Fill `buffer` with `value` on the GPU, waited for. diff --git a/crates/metal2vulkan-runtime/src/tests/host_residency.rs b/crates/metal2vulkan-runtime/src/tests/host_residency.rs index eb137bbcc..4d4616fe1 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_residency.rs @@ -132,7 +132,7 @@ impl Drop for Scratch { } /// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache -/// in `cache`. +/// in `cache`, its submission checks answered. pub(super) fn device(cache: &Path) -> Device { let options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { @@ -149,7 +149,14 @@ pub(super) fn device(cache: &Path) -> Device { }, ..DeviceOptions::default() }; - Device::system_default_with(&options).unwrap() + let device = Device::system_default_with(&options).unwrap(); + // A no-copy buffer's pointer import is releasable only where the device's check found its + // pointer imports follow their address as the buffer was made (`submit_check.rs`). + assert!( + device.settle_submit_checks(crate::tests::SETTLE), + "the submission checks never answered" + ); + device } /// Run `test` on the device the cfg selects, where `/dev/udmabuf` opens. diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index d5f81d6fd..31e1a3b30 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -375,6 +375,9 @@ mod stage_entries_shared; mod staging_waits; mod stand_in; mod storage_form; +mod submit_check; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod submit_check_device; mod submit_stalls; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod submit_stalls_idle; @@ -431,3 +434,9 @@ mod ycbcr_device; mod ycbcr_in_place_loop; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod ycbcr_refresh; + +/// How long a device test waits for the device's submission checks to answer +/// (`Device::settle_submit_checks`): their run takes milliseconds alone, longer beside the +/// suite's other devices. +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +pub(crate) const SETTLE: std::time::Duration = std::time::Duration::from_secs(60); diff --git a/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs b/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs index ef4035d5e..3d764a892 100644 --- a/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs @@ -5,14 +5,15 @@ //! mapped shared, imported by its pointer (`HostMemory::new`), as ANV, NVIDIA and lavapipe import //! it; on a device that refuses that pointer (RADV, which imports the `memfd`'s dma-bufs, //! `tests/host_residency.rs`), private anonymous pages, which RADV imports by their pointer. Where -//! the driver's pointer imports follow their address -//! (`DriverFact::PointerImportsFollowTheirAddress`: ANV on i915, RADV, lavapipe), the device -//! releases such an import while idle and imports it again at the same pointer at its next blit. +//! the device's check found its pointer imports follow their address (`submit_check.rs`, +//! `Device::pointer_imports_follow_their_address`: ANV on i915, RADV and lavapipe answer so), the +//! device releases such an import while idle and imports it again at the same pointer at its next +//! blit. //! The tests release imports at once through the crate's hook (`Device::release_idle_host_imports`) //! and check: -//! - that a kept import reads the pages a remap put at its address, which is the fact itself, on -//! a device with it; on any other the test prints the pages it read, a measurement of the -//! driver; +//! - that a kept import reads the pages a remap put at its address, which is what the check +//! found, on a device where it found so, for the guest's shared pages too, which the check does +//! not map; on any other the test prints the pages it read, a measurement of the driver; //! - the counts that show the release and the import again ran (`WorkCounts::host_imports_released`, //! `host_imports_reimported`, `host_imports_resident`, `host_imports_live`), and none of a //! dma-buf's descriptors kept; @@ -21,7 +22,7 @@ //! - that a released import reads after a remap the pages the kept one would read; //! - that a buffer whose Metal address was handed out stays imported. //! -//! A device whose driver is not measured with the fact keeps every pointer import: the hook +//! A device whose check found otherwise keeps every pointer import: the hook //! releases none, and each test says so and passes. Where the device refuses the pointers of both //! kinds of pages each test says so and passes without running. //! @@ -32,14 +33,17 @@ use super::host_residency::{ counting, device, gpu_fill, gpu_read, host_page, read, release, residency, Ram, Scratch, }; use crate::{Buffer, Device, Error, HostMemory, ResourceOptions}; -use metal2vulkan::device::DriverFact; use metal2vulkan::error::Feature; use std::ptr::NonNull; -/// Whether `device`'s driver is measured to have its pointer imports follow their address, so -/// that the device releases them while idle. +/// Whether `device`'s check found its pointer imports follow their address, so that the device +/// releases them while idle: once its checks answered. pub(super) fn follows(device: &Device) -> bool { - (device.properties().driver_facts).contains(&DriverFact::PointerImportsFollowTheirAddress) + assert!( + device.settle_submit_checks(crate::tests::SETTLE), + "the submission checks never answered" + ); + device.pointer_imports_follow_their_address() } /// Run `test` on the device the cfg selects. diff --git a/crates/metal2vulkan-runtime/src/tests/submit_check.rs b/crates/metal2vulkan-runtime/src/tests/submit_check.rs new file mode 100644 index 000000000..8dc4906f1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/submit_check.rs @@ -0,0 +1,93 @@ +//! The device's submission checks' verdicts and records (`submit_check.rs`), from what they +//! measure: no device. + +use crate::in_place::DriverIdentity; +use crate::submit_check::{ + decode, encode, merge_verdict, record_name, tax_verdict, Measured, Verdict, MERGE_RATIO, + TAX_FLOOR, +}; + +/// 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 an +/// import of 16 MiB held and without. +const RADEON_780M: ([i64; 2], [i64; 2]) = ([13_200, 37_300], [20_700, 10_400]); +const RX_7900_XTX: ([i64; 2], [i64; 2]) = ([13_400, 35_000], [15_200, 8_400]); +const RX_550: ([i64; 2], [i64; 2]) = ([11_600, 35_100], [54_700, 8_900]); +const IRIS_XE: ([i64; 2], [i64; 2]) = ([5_100, 13_100], [4_700, 4_500]); +const M3_MAX: ([i64; 2], [i64; 2]) = ([4_500, 4_600], [2_700, 3_000]); + +/// Mesa's drivers merge the calls (RADV on three generations, ANV) and MoltenVK does not; RADV +/// taxes every submission for a held import and ANV and MoltenVK do not: the verdicts each +/// device's numbers give, whatever its identity. +#[test] +fn the_probe_s_numbers_give_each_device_its_verdicts() { + let cases = [ + ("Radeon 780M", RADEON_780M, Verdict::Holds, Verdict::Holds), + ("RX 7900 XTX", RX_7900_XTX, Verdict::Holds, Verdict::Holds), + ("RX 550", RX_550, Verdict::Holds, Verdict::Holds), + ("Iris Xe", IRIS_XE, Verdict::Holds, Verdict::Fails), + ("M3 Max", M3_MAX, Verdict::Fails, Verdict::Fails), + ]; + for (name, ([merged, apart], [held, bare]), merges, taxed) in cases { + assert_eq!(merge_verdict(merged, apart), merges, "{name}"); + assert_eq!(tax_verdict(held, bare), taxed, "{name}"); + } +} + +/// The bounds themselves: a call at the ratio merges and one past it does not; a held import +/// that adds the floor, or an eighth of a slow submission, is no tax, and one past it is; no +/// measurement (a check that timed nothing) merges. +#[test] +fn the_verdicts_meet_their_bounds() { + let apart = 10_000; + let at = (MERGE_RATIO * apart as f64) as i64; + assert_eq!(merge_verdict(at, apart), Verdict::Holds); + assert_eq!(merge_verdict(at + 1, apart), Verdict::Fails); + assert_eq!(merge_verdict(0, 0), Verdict::Fails); + assert_eq!(tax_verdict(4_000 + TAX_FLOOR, 4_000), Verdict::Fails); + assert_eq!(tax_verdict(4_001 + TAX_FLOOR, 4_000), Verdict::Holds); + let slow = 80_000; + assert_eq!(tax_verdict(slow + slow / 8, slow), Verdict::Fails); + assert_eq!(tax_verdict(slow + slow / 8 + 1, slow), Verdict::Holds); +} + +fn identity(device_id: u32) -> DriverIdentity { + DriverIdentity { + vendor_id: 0x1002, + device_id, + driver_version: 0x6802006, + driver_id: 3, + driver_name: "radv".into(), + driver_info: "Mesa 26.2.6".into(), + device_uuid: [7; 16], + } +} + +/// 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. +#[test] +fn a_record_holds_its_identity_s_verdicts() { + let (one, other) = (identity(0x15bf), identity(0x1114)); + let verdicts = [Verdict::Holds, Verdict::Holds, Verdict::Fails]; + let measured = Measured { + merged: 13_200, + apart: 37_300, + held: 20_700, + bare: 10_400, + }; + let bytes = encode(&one, verdicts, measured); + assert_eq!(decode(&one, &bytes), Some((verdicts, measured))); + assert_eq!(decode(&other, &bytes), None); + assert_ne!(record_name(&one), record_name(&other)); + assert_eq!(decode(&one, &bytes[..bytes.len() - 1]), None); + let mut changed = bytes.clone(); + changed[60] ^= 1; + assert_eq!(decode(&one, &changed), None); + let pending = encode( + &one, + [Verdict::Holds, Verdict::Pending, Verdict::Fails], + measured, + ); + assert_eq!(decode(&one, &pending), None); +} diff --git a/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs b/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs new file mode 100644 index 000000000..eccdeed69 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs @@ -0,0 +1,158 @@ +//! 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. +//! +//! - **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; the +//! follows check answered on Linux where the device imports host pointers), their calls counted +//! apart (`WorkCounts::submit_check_calls`); a second device over the same cache recalls them +//! (`submit_checks_recalled`), runs none, and holds the same verdicts. +//! - **The paths follow them.** Grouped batches where the merge holds +//! (`WorkCounts::grouped_submissions`), a long `Shared` buffer in fresh pages where a held +//! import adds nothing to a submission (`fresh_page_buffers_made`), a no-copy buffer's pointer +//! import released while idle where pointer imports follow their address +//! (`host_imports_released`, `tests/pointer_residency.rs` for the release itself). Each +//! verdict is printed, with what the checks measured: the evidence of which path the device +//! took. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). + +use super::blit_holds::{Scratch, WAIT}; +use crate::fresh_pages::FRESH_PAGES_PAST; +use crate::submit_check::{Check, Verdict}; +use crate::tests::SETTLE; +use crate::{ + CommandBufferStatus, Device, DeviceKind, DeviceOptions, EventRef, ResourceOptions, + ShaderCacheOptions, +}; +use std::path::Path; + +/// The device the cfg selects, its shader cache in `cache`. +fn device(cache: &Path) -> Device { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// Each check's verdict on `device`. +fn verdicts(device: &Device) -> [Verdict; 3] { + Check::ALL.map(|check| device.shared().submit_checks.verdict(check)) +} + +#[test] +fn the_checks_answer_once_and_a_second_device_recalls_them() { + let scratch = Scratch::new("submit-checks"); + let first = device(&scratch.0); + assert!( + first.settle_submit_checks(SETTLE), + "the checks never answered" + ); + let answered = verdicts(&first); + println!("{}: {}", first.name(), first.submit_check_report()); + assert!(!answered.contains(&Verdict::Pending), "{answered:?}"); + let imports = first.shared().host_import.is_ok(); + if imports && cfg!(target_os = "linux") { + assert_ne!( + answered[2], + Verdict::Unchecked, + "the follows check did not run" + ); + } + let counts = first.work_counts(); + assert_eq!(counts.submit_checks_run, 1); + assert_eq!(counts.submit_checks_recalled, 0); + assert!( + counts.submit_check_calls > 0, + "the checks' calls were not counted" + ); + // The record is written soon, not at once: wait for it, as a later process would find it. + let start = std::time::Instant::now(); + loop { + let second = device(&scratch.0); + assert!( + second.settle_submit_checks(SETTLE), + "the second device never answered" + ); + 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), answered); + break; + } + assert!(start.elapsed() < WAIT, "no device recalled the record"); + drop(second); + std::thread::sleep(std::time::Duration::from_millis(50)); + } +} + +/// The paths the verdicts choose: grouped batches, fresh pages, releasable pointer imports. +#[test] +fn the_paths_follow_the_verdicts() { + let scratch = Scratch::new("submit-check-paths"); + let device = device(&scratch.0); + assert!( + device.settle_submit_checks(SETTLE), + "the checks never answered" + ); + println!("{}: {}", device.name(), device.submit_check_report()); + // Batches ready together behind an event the host raises go grouped where the merge holds. + let queue = device.new_command_queue().unwrap(); + let event = device.new_shared_event().unwrap(); + let target = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let before = device.work_counts(); + let mut last = None; + for round in 0..8u8 { + let command_buffer = queue.command_buffer().unwrap(); + if round == 0 { + command_buffer + .encode_wait_for_event(EventRef::Shared(&event), 1) + .unwrap(); + } + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&target, 0..4096, round).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + last = Some(command_buffer); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + event.set_signaled_value(1); + let last = last.unwrap(); + assert!(last.wait_until_completed_for(WAIT).is_ok()); + assert_eq!(last.status(), CommandBufferStatus::Completed); + let after = device.work_counts(); + let grouped = after.grouped_submissions - before.grouped_submissions; + println!("grouped submissions: {grouped}"); + assert_eq!( + grouped > 0, + device.submissions_merge(), + "grouping against the merge verdict" + ); + // A long `Shared` buffer lies in fresh pages where a held import costs nothing. + let before = device.work_counts().fresh_page_buffers_made; + let long = device + .new_buffer(FRESH_PAGES_PAST + 4096, ResourceOptions::shared()) + .unwrap(); + let made = device.work_counts().fresh_page_buffers_made - before; + println!("fresh-page buffers made: {made}"); + let imports = device.shared().host_import.is_ok(); + assert_eq!( + made == 1, + imports && device.fresh_pages_pay(), + "fresh pages against the verdict" + ); + assert_eq!(long.in_fresh_pages(), made == 1); +} diff --git a/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs b/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs index 4d99cfd8f..0f4f59f91 100644 --- a/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs +++ b/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs @@ -11,7 +11,7 @@ //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. -use crate::command_buffer::merges_submissions; +use crate::tests::SETTLE; use crate::{ CommandBuffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, EventRef, ResourceOptions, @@ -152,9 +152,9 @@ fn an_empty_command_buffer_completes_with_no_submission() { /// macOS 27.0.1: its GPU times 65 to 135 us after the fill's `GPUEndTime`). /// /// Under `CompletionPolicy::Exact`, so on every driver, the empty command buffer is taken with no -/// submission in each round. Under the default, on a driver whose batches group -/// (`DriverFact::SubmissionsWithoutSignalsMerge`: lavapipe), the scheduler may hold the fill in its -/// group as it finds the empty one ready behind it, which then goes in the group's one +/// submission in each round. Under the default, on a device whose batches group (its check found +/// its submissions merge, `submit_check.rs`: lavapipe among them), the scheduler may hold the fill +/// in its group as it finds the empty one ready behind it, which then goes in the group's one /// submission with the fill: either way it makes no submission of its own. #[test] fn an_empty_command_buffer_completes_behind_its_queue_s_earlier_work() { @@ -166,8 +166,11 @@ fn an_empty_command_buffer_completes_behind_its_queue_s_earlier_work() { /// [`an_empty_command_buffer_completes_behind_its_queue_s_earlier_work`] under `completion`. fn completes_behind(completion: CompletionPolicy) { let device = device_with(completion); - let groups = completion == CompletionPolicy::Grouped - && merges_submissions(&device.properties().driver_facts); + assert!( + device.settle_submit_checks(SETTLE), + "the submission checks never answered" + ); + let groups = completion == CompletionPolicy::Grouped && device.submissions_merge(); let queue = device.new_command_queue().unwrap(); let target = device.new_buffer(FILL, ResourceOptions::private()).unwrap(); // Whether the fill was still running when the empty command buffer was committed, in some diff --git a/crates/metal2vulkan-runtime/src/tests/waiter_submits.rs b/crates/metal2vulkan-runtime/src/tests/waiter_submits.rs index f3a759336..353090e54 100644 --- a/crates/metal2vulkan-runtime/src/tests/waiter_submits.rs +++ b/crates/metal2vulkan-runtime/src/tests/waiter_submits.rs @@ -8,8 +8,8 @@ //! //! Nor does it submit a batch of a queue whose batches wait in the scheduler's group //! (`command_buffer/group.rs`), which is the scheduler thread's to hold and to send: under the -//! default `CompletionPolicy::Grouped`, on a driver measured to merge a submission that signals -//! nothing into the next (`DriverFact::SubmissionsWithoutSignalsMerge`), that is every queue. So +//! default `CompletionPolicy::Grouped`, on a device whose check found a submission that signals +//! nothing merged into the next (`submit_check.rs`), that is every queue. So //! the waiter's own submissions are counted under `CompletionPolicy::Exact`, where no queue's //! batches group on any driver, and under the default each test checks that a waiting thread //! submits nothing where the device's batches group, and submits as under `Exact` elsewhere. @@ -25,7 +25,7 @@ //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. -use crate::command_buffer::merges_submissions; +use crate::tests::SETTLE; use crate::{ Buffer, CommandBuffer, CommandQueue, Device, DeviceKind, DeviceOptions, ResourceOptions, ShaderCacheOptions, @@ -252,8 +252,8 @@ fn a_thread_about_to_block_submits_what_it_committed_unless_a_handler_must_run() }); } -/// Under the default `CompletionPolicy::Grouped`: where the device's batches group (its driver -/// merges a submission that signals nothing into the next, `merges_submissions`), every batch of +/// Under the default `CompletionPolicy::Grouped`: where the device's batches group (its check +/// found a submission that signals nothing merged into the next), every batch of /// a queue is the scheduler thread's to hold in its group, so a thread waiting for its `wait` /// submits none of [`ROUNDS`] (`scheduler::plain_ready`) and the scheduler's thread submits them /// all; elsewhere, the scheduler's thread [`Held`], it submits each, as under `Exact`. `submitted` runs the plain rounds @@ -267,7 +267,11 @@ fn under_the_default( let device = device(cache, CompletionPolicy::Grouped); let queue = device.new_command_queue().unwrap(); let side = device.new_command_queue().unwrap(); - let groups = merges_submissions(&device.properties().driver_facts); + assert!( + device.settle_submit_checks(SETTLE), + "the submission checks never answered" + ); + let groups = device.submissions_merge(); let batches = submitted(&device, &queue, (!groups).then_some(&side)); println!( "under the default, batches grouping {groups}: submitted by waiters for the {wait}: \ diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index d87270a9b..6f8edcdb9 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -230,6 +230,9 @@ pub(crate) struct Counters { joins_withheld_from_unshared: AtomicU64, queue_switch_checks_run: AtomicU64, queue_switch_checks_recalled: AtomicU64, + submit_checks_run: AtomicU64, + submit_checks_recalled: AtomicU64, + submit_check_calls: AtomicU64, queue_sharing_untimed: AtomicU64, slot_wait_nanos: AtomicU64, completed_waits: AtomicU64, @@ -2191,6 +2194,22 @@ impl Counters { (self.queue_switch_checks_recalled).fetch_add(1, Ordering::Relaxed); } + /// The device's submission checks ran in this process (`submit_check.rs`). + pub(crate) fn submit_checks_ran(&self) { + (self.submit_checks_run).fetch_add(1, Ordering::Relaxed); + } + + /// Their verdicts were read from the record of an earlier run (`submit_check.rs`). + pub(crate) fn submit_checks_recalled(&self) { + (self.submit_checks_recalled).fetch_add(1, Ordering::Relaxed); + } + + /// The submission checks made `calls` `vkQueueSubmit` calls, which `queue_submissions` does + /// not count (`submit_check.rs`). + pub(crate) fn submit_check_called(&self, calls: usize) { + (self.submit_check_calls).fetch_add(calls as u64, Ordering::Relaxed); + } + /// A device that could share `VkQueue`s does not: its command buffers write no timestamps it /// reads (`queue_switch_check::timed`). pub(crate) fn queue_sharing_untimed(&self) { @@ -4756,6 +4775,15 @@ pub struct WorkCounts { /// Devices whose verdict of that check was read from the record of an earlier one of the same /// driver, device and runtime: no check ran for them. pub queue_switch_checks_recalled: u64, + /// Runs in this process of the device's submission checks (`submit_check.rs`: whether + /// `VkSubmitInfo`s that signal nothing merge, whether a held host-pointer import adds to every + /// submission's cost, whether a pointer import follows its address), whatever they answered. + pub submit_checks_run: u64, + /// Devices whose submission checks' verdicts were read from the record of an earlier run of + /// the same driver, device, kernel and runtime: no check ran for them. + pub submit_checks_recalled: u64, + /// The `vkQueueSubmit` calls the submission checks made, which `queue_submissions` leaves out. + pub submit_check_calls: u64, /// Devices of `QueueSharingPolicy::Adaptive` with two `VkQueue`s of one family to share that /// do not share, because their command buffers write no calibrated GPU timestamps the host /// reads (`gpu_times_from_host`, a driver whose timestamps wait for every queue's, or none): @@ -6685,6 +6713,9 @@ impl Device { queue_switch_checks_recalled: counters .queue_switch_checks_recalled .load(Ordering::Relaxed), + submit_checks_run: counters.submit_checks_run.load(Ordering::Relaxed), + submit_checks_recalled: counters.submit_checks_recalled.load(Ordering::Relaxed), + submit_check_calls: counters.submit_check_calls.load(Ordering::Relaxed), queue_sharing_untimed: counters.queue_sharing_untimed.load(Ordering::Relaxed), completed_waits: counters.completed_waits.load(Ordering::Relaxed), event_waits_met: counters.event_waits_met.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs b/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs index a8c009c15..a8cba15e3 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/grouped_submissions.rs @@ -4,8 +4,8 @@ //! [`BATCHES`] command buffers committed on one queue, each filling a buffer of its own with a //! value of its own, the first after a wait for an event the host has not raised, all wait behind //! that wait; once the host raises it the scheduler finds them ready together. Under the default -//! `CompletionPolicy::Grouped`, on a driver measured to merge a submission that signals nothing -//! into the next one (`DriverFact::SubmissionsWithoutSignalsMerge`), they go in `vkQueueSubmit` +//! `CompletionPolicy::Grouped`, on a device whose check found a submission that signals nothing +//! merged into the next one (the runtime's `submit_check.rs`), they go in `vkQueueSubmit` //! calls of up to four batches each, only the last of each signalling //! (`WorkCounts::grouped_submissions`, //! `WorkCounts::batches_grouped`), announced once ([`GROUPED`]); under `CompletionPolicy::Exact`, @@ -53,7 +53,7 @@ use super::{ ScratchCache, WAIT, }; use crate::gpu::TEST_DEVICE; -use metal2vulkan::device::{CompletionPolicy, DeviceDescription, DriverFact}; +use metal2vulkan::device::CompletionPolicy; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, Degradation, DeviceOptions, EventRef, ResourceOptions, ShaderCacheOptions, WorkCounts, @@ -88,12 +88,17 @@ fn group_ends(before: &WorkCounts, after: &WorkCounts) -> [u64; 7] { std::array::from_fn(|at| after[at] - before[at]) } -/// Whether the device's driver merges a submission that signals nothing into the next: the -/// driver's fact answers it, never its name, and the runtime reads the same fact -/// (`DriverFact::SubmissionsWithoutSignalsMerge`, the runtime's `group.rs`), so a device whose -/// identity no lane measured takes the ungrouped path and this lane expects it. -fn merges(description: &DeviceDescription) -> bool { - (description.driver_facts()).contains(&DriverFact::SubmissionsWithoutSignalsMerge) +/// Whether the device's submissions that signal nothing merge into the next, as its check found +/// once it answered (the runtime's `submit_check.rs`, which its `group.rs` reads): the device's +/// own measurement, never its name nor its GPU's, so a GPU no lane measured groups where its +/// check finds the merge, and this lane expects what the check found. +fn merges(device: &metal2vulkan_runtime::Device) -> bool { + assert!( + device.settle_submit_checks(WAIT), + "the submission checks never answered" + ); + eprintln!("submission checks: {}", device.submit_check_report()); + device.submissions_merge() } /// Wait until a pass has taken in every command buffer committed before the call, and ended: @@ -136,7 +141,7 @@ fn run(completion: CompletionPolicy, checked: bool) -> (u64, u64, u64, usize, bo options.policy.completion = completion; }) .unwrap(); - let merging = merges(&device.properties().description); + let merging = merges(&device); let queue = device.new_command_queue().unwrap(); let event = device.new_shared_event().unwrap(); let buffers: Vec = (0..BATCHES) @@ -393,7 +398,7 @@ fn event_scenario(completion: CompletionPolicy, steps: &[Step], last: u64) -> Sc options.policy.completion = completion; }) .unwrap(); - let merging = merges(&device.properties().description); + let merging = merges(&device); let queues = [ device.new_command_queue().unwrap(), device.new_command_queue().unwrap(), @@ -866,7 +871,7 @@ fn behind_running_work(completion: CompletionPolicy, stretch: usize, carried: Ca options.policy.completion = completion; }) .unwrap(); - let merging = merges(&device.properties().description); + let merging = merges(&device); let queue = device.new_command_queue().unwrap(); let large = device .new_buffer(RUNNING_FILL, ResourceOptions::private()) diff --git a/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs b/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs index c0022bdf8..e2fb4e794 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs @@ -31,8 +31,8 @@ //! A second measurement holds a guest's shape (`submit_per_import_guest_shape`): [`GUEST_IMPORTS`] //! pointer imports, of which each frame's blits read [`GUEST_USED`], in frames of //! [`GUEST_PER_FRAME`] command buffers. It measures frames at once, every import resident, then, -//! where the driver's pointer imports follow their address -//! (`DriverFact::PointerImportsFollowTheirAddress`), again once the device's residency thread +//! where the device's check found its pointer imports follow their address (the runtime's +//! `submit_check.rs`), again once the device's residency thread //! released the idle ones while paced frames kept the read ones in use. Printed as //! `SUBMIT-GUEST-SHAPE` lines: the imports (`WorkCounts::host_imports_live`, //! `host_imports_resident`, `host_imports_released`, `host_imports_reimported`), a frame's wall @@ -70,7 +70,6 @@ use super::host_memory::{no_copy, Mapping}; use super::submit_costs::Execbuffers; use super::{validated_device_with, Messages, ScratchCache, WAIT}; use crate::gpu::TEST_DEVICE; -use metal2vulkan::device::DriverFact; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions, }; @@ -174,6 +173,21 @@ fn hold(device: &Device, kind: Kind, n: usize) -> Held { } } +/// Wait for `device`'s submission checks, whose verdicts choose its paths here (whether its +/// batches group, its long buffers take fresh pages and its idle pointer imports are released), +/// and print them. +fn settled(device: &Device) { + assert!( + device.settle_submit_checks(WAIT), + "the submission checks never answered" + ); + eprintln!( + "SUBMIT-CHECKS {}: {}", + device.name(), + device.submit_check_report() + ); +} + /// A command buffer of `queue` filling `target`'s 4 KiB with `value`, not committed. fn fill(queue: &CommandQueue, target: &Buffer, value: u8) -> CommandBuffer { let command_buffer = queue.command_buffer().unwrap(); @@ -274,6 +288,7 @@ fn submit_per_import() { options.record_executions = false; }) .unwrap(); + settled(&device); let queue = device.new_command_queue().unwrap(); let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); let dma_bufs = udmabuf_openable("submit per import"); @@ -375,6 +390,7 @@ fn submit_per_import_guest_shape() { options.record_executions = false; }) .unwrap(); + settled(&device); let queue = device.new_command_queue().unwrap(); let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); let pages = Mapping::anonymous(GUEST_IMPORTS * IMPORT_BYTES); @@ -390,11 +406,9 @@ fn submit_per_import_guest_shape() { .collect(); let used = &buffers[..GUEST_USED]; guest_measure(&device, &queue, &target, used, "at once"); - let follows = - (device.properties().driver_facts).contains(&DriverFact::PointerImportsFollowTheirAddress); - if !follows { + if !device.pointer_imports_follow_their_address() { eprintln!( - "SUBMIT-GUEST-SHAPE {}: pointer imports kept (the driver is not measured to have them \ + "SUBMIT-GUEST-SHAPE {}: pointer imports kept (the device's check did not find them \ follow their address)", device.name() ); @@ -494,6 +508,7 @@ fn submit_per_import_release_cost() { options.record_executions = false; }) .unwrap(); + settled(&device); let queue = device.new_command_queue().unwrap(); let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); let pages = Mapping::anonymous(GUEST_IMPORTS * IMPORT_BYTES); @@ -558,6 +573,7 @@ fn submit_per_fresh_page_buffer() { options.record_executions = false; }) .unwrap(); + settled(&device); let queue = device.new_command_queue().unwrap(); let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); for (name, count, length, shared) in FRESH_PHASES { diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index c9e652320..e811616d1 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -13,7 +13,12 @@ //! [`DeviceDescription::canonical_device_id`]. MoltenVK's `deviceID` on Apple's GPUs is the macOS //! release and the GPU family, so a row of one names every GPU of the family under that macOS. //! A driver or GPU no row names takes no fact: the reader takes the route each fact's docs name -//! for a driver without it. +//! for a driver without it. A question a device answers about itself in a few milliseconds is no +//! row: the runtime's device checks measure it on each device, once per driver and release +//! (whether its submissions that signal nothing merge, whether a held host-pointer import adds to +//! each submission's cost, whether a pointer import follows its address: the runtime's +//! `submit_check.rs`; textures in place over host pages, `in_place_check.rs`; the GPU's idling +//! between `VkQueue`s, `queue_switch_check.rs`). use crate::device::description::APPLE_VENDOR_ID; use crate::device::profile::DriverWorkaround; @@ -730,9 +735,6 @@ const AMD_VENDOR_ID: u32 = 0x1002; /// ([`DeviceDescription::canonical_device_id`]). pub(crate) const AMD_RADEON_780M: u32 = 0x15bf; -/// The `deviceID` of the Radeon RX 7900 XTX (Navi 31) its rows were measured under. -pub(crate) const AMD_RX_7900_XTX: u32 = 0x744c; - /// The `deviceID` of the Intel UHD Graphics 770 of Raptor Lake-S (the committed capture /// `intel-uhd770-rpls-anv`). pub(crate) const INTEL_UHD_770_RPL_S: u32 = 0xa780; @@ -1305,31 +1307,6 @@ pub enum DriverFact { /// with a 1 made a second `VkPipeline` there (Metal's specialization and pipeline compile, /// 5.6 to 24.5 ms). ConstantOffsetUniformReadsPreloaded, - /// A cost fact (the module docs): the driver's queue is Mesa's common one, where each - /// `vkQueueSubmit`'s `VkSubmitInfo`s that signal nothing merge into the next one's kernel - /// submission, so batches that signal nothing but their queue's timeline may wait and go in - /// one call for the cost of one kernel submission (Mesa 26.2.4, `vulkan/runtime/vk_queue.c`, - /// `vk_queue_submits_merge`: "Don't merge if there are signals in between"; ANV chains the - /// merged command buffers into one batch buffer, - /// `anv_queue_submit_cmd_buffers_locked`). Each kernel submission costs CPU time for every - /// `VkDeviceMemory` of the device there: ANV on i915 lists each in every execbuffer - /// (`i915/anv_batch_chain.c`, `setup_execbuf_for_cmd_buffers`), RADV each in every CS. On a - /// driver without it each batch takes its own `vkQueueSubmit`, which is the exact path and - /// the one every batch took before grouping: a group changes when a batch's `vkQueueSubmit` - /// is made and nothing it submits (`command_buffer/group.rs` in the runtime). - /// - /// Counted where the merge pays, on Mesa 26.2.4's ANV on the Intel UHD 770: 24 kernel - /// submissions a frame grouped against 30 ungrouped, at 67 command buffers a frame committed - /// 1 ms apart behind 1.3 ms of GPU work each, the GPU as idle either way (0.62 ms a frame). - /// - /// Measured without it, so not listed: MoltenVK, whose queue is its own and merges nothing - /// -- it commits a Metal command buffer for each `VkSubmitInfo` of a call and one for a call - /// of none with a fence (`MVKQueue::submit`), about 65 us of a thread of Metal's on an Apple - /// M3 Max whether or not the info holds work -- and NVIDIA's proprietary driver, which has - /// no Mesa queue. The Mesa drivers no lane measures (Turnip, V3DV, PanVK, NVK, Honeykrisp, - /// PowerVR) take no row: the merge is in the common queue they share, but no identity of - /// theirs was measured, so each takes the ungrouped exact path. - SubmissionsWithoutSignalsMerge, /// A defect fact (the module docs): the driver reports a command buffer's execution failure /// only to the instance's debug-utils messengers, naming the `VkQueue` and not the /// submission, and by default marks the whole `VkDevice` lost for it, where Metal fails the @@ -1458,28 +1435,6 @@ pub enum DriverFact { /// Metal's by construction. On a driver with it the runtime announces no `snorm-minimum-kept` /// or `shared-exponent-kept`. TileStoreIsMetals, - /// A buffer bound to memory the driver imported from a host pointer - /// (`VK_EXT_external_memory_host`) reads and writes, at each submission, the pages mapped at - /// that pointer then: pages the process maps over the address after the import (`mmap` with - /// `MAP_FIXED`) take the place of those it was made over, for the GPU as for the CPU. Vulkan - /// states nothing of a remap under a live import, and Metal's no-copy buffer keeps the pages - /// wired when it was made. ANV on i915 imports a pointer as a userptr object, whose pages the - /// kernel gets again at the next execbuffer once a remap invalidated them (Linux 7.2.9's - /// `i915_gem_object_userptr_submit_init`, or at its first execbuffer, before which nothing was - /// pinned); RADV imports it as an amdgpu userptr object, whose pages the kernel gets again in - /// each command submission once a remap invalidated them (Linux 7.2.9's - /// `amdgpu_cs_parser_bos`, through `amdgpu_ttm_tt_get_user_pages`), and refuses a shared - /// `memfd`'s pointer where it imports private anonymous pages'; lavapipe reads the memory - /// through the pointer itself (`lvp_AllocateMemory`'s `LVP_DEVICE_MEMORY_TYPE_USER_PTR`). On a - /// driver with it a no-copy buffer's own pointer import is released while idle and imported - /// again at the same pointer at its next blit, which reads the pages the kept import would - /// read (`host_residency.rs` in the runtime): on ANV on i915 every execbuffer lists every - /// memory of the device, an import of a pointer costing about 0.16 us of the kernel's time in - /// each, and on RADV amdgpu gets every page of each live pointer import again in each - /// submission: about 0.5 us an import and 29 ns a 4 KiB page on the RX 7900 XTX under Linux - /// 7.0.0, about a quarter of that a page on the Radeon 780M under Linux 7.2.9. Elsewhere such - /// an import stays imported, as the driver may keep the pages it was made over. - PointerImportsFollowTheirAddress, /// Consecutive draws of a subpass whose fragment shaders read and write a storage image in /// the ordered pixel interlock, every access coherent, are ordered by the interlock alone, as /// Vulkan states: each fragment's interlocked operations happen before those of a later draw's @@ -1940,26 +1895,6 @@ const DYNAMIC_RESTART_WARNING: DriverDiagnostic = DriverDiagnostic { /// left a third answer; RADV on the RX 7900 XTX, clean at dd718a7905 at Mesa 26.0.8 but not /// measured since; and every GPU not measured, which store with `STORE`. /// -/// `PointerImportsFollowTheirAddress`: ANV, Mesa 26.2.4 on the Iris Xe of RPL-P under Linux 7.2.9's -/// i915, measured with a probe outside the runtime (2026-10-17): a page of a `memfd` filled with -/// `0xaa`, mapped shared at an address and imported by its pointer as a buffer's memory, read -/// `0xaa` through a copy; another `memfd`'s page of `0xbb` mapped over the address with `MAP_FIXED`, -/// the next copy read `0xbb`; a page of `0xa2` imported and replaced by one of `0xb2` before any -/// submission, the first copy read `0xb2`. lavapipe (`MESA_LLVMPIPE`) from Mesa 26.0.8 through -/// 26.2.4 by construction, read in both releases' `lvp_AllocateMemory`, which binds an import's -/// buffers at the host pointer. RADV, Mesa 26.2.4 on the Radeon 780M under Linux 7.2.9's amdgpu, -/// measured through the runtime (2026-10-17): a no-copy buffer over two fresh anonymous private -/// pages, read by a blit; fresh anonymous pages mapped over the address with `MAP_FIXED` and -/// `Device::host_range_remapped` told, the next blit read the new pages, and the newer ones after a -/// second remap; remapped between the buffer's making and its first submission, the first blit -/// read the new pages. RADV, Mesa 26.2.4 on the RX 7900 XTX under the same kernel, measured through -/// the runtime (2026-10-22, `tests::pointer_residency` before its row): a no-copy buffer over two -/// fresh anonymous private pages, read by a blit; fresh anonymous pages mapped over the address -/// with `MAP_FIXED` and `Device::host_range_remapped` told, the next blit of the import kept all -/// along read the new pages; Mesa 26.0.8 on both under Linux 7.0.0 answered the same. -/// `tests::pointer_residency` in the runtime checks it on a device with it. Every other driver is -/// unmeasured, and keeps its pointer imports. -/// /// `InterlockOrdersDraws`, measured with no barrier between such draws on any driver (a scratch /// build of the commit that adds it), by `runtime_lane::interlocked_draw_order` (passes of 84 /// draws, fullscreen and held to bands, of two read-modify-writes of an `R32Uint` color that do @@ -2326,32 +2261,6 @@ pub(crate) const MEASURED: &[Measured] = &[ device: None, }, nvidia_on(DriverFact::RowCopiesDispatchFaster, NVIDIA_RTX_5080_LAPTOP), - Measured { - fact: DriverFact::SubmissionsWithoutSignalsMerge, - driver: DriverId::MESA_LLVMPIPE, - vendor: None, - device: None, - }, - mesa_on( - DriverFact::SubmissionsWithoutSignalsMerge, - DriverId::MESA_RADV, - (AMD_VENDOR_ID, AMD_RADEON_780M), - ), - mesa_on( - DriverFact::SubmissionsWithoutSignalsMerge, - DriverId::MESA_RADV, - (AMD_VENDOR_ID, AMD_RX_7900_XTX), - ), - mesa_on( - DriverFact::SubmissionsWithoutSignalsMerge, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), - ), - mesa_on( - DriverFact::SubmissionsWithoutSignalsMerge, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_UHD_770_RPL_S), - ), mesa_on( DriverFact::SampledDepthKeepsHiZ, DriverId::INTEL_OPEN_SOURCE_MESA, @@ -2363,27 +2272,6 @@ pub(crate) const MEASURED: &[Measured] = &[ (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), ), moltenvk_on_apple(DriverFact::TileStoreIsMetals), - mesa_on( - DriverFact::PointerImportsFollowTheirAddress, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), - ), - mesa_on( - DriverFact::PointerImportsFollowTheirAddress, - DriverId::MESA_RADV, - (AMD_VENDOR_ID, AMD_RADEON_780M), - ), - mesa_on( - DriverFact::PointerImportsFollowTheirAddress, - DriverId::MESA_RADV, - (AMD_VENDOR_ID, AMD_RX_7900_XTX), - ), - Measured { - fact: DriverFact::PointerImportsFollowTheirAddress, - driver: DriverId::MESA_LLVMPIPE, - vendor: None, - device: None, - }, mesa_on( DriverFact::InterlockOrdersDraws, DriverId::INTEL_OPEN_SOURCE_MESA, diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 29d51a3dd..199f1cdb4 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -4,7 +4,7 @@ use crate::device::driver_facts::{among, Measured, MEASURED, NVIDIA_RTX_3090}; use crate::device::{DeviceDescription, DriverFact}; use crate::vk::DriverId; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; const APPLE: u32 = 0x106B; @@ -403,14 +403,12 @@ const ONE_OF_METALS: DriverFact = DriverFact::DontCareStoreIsOneOfMetals; const COPY_BACK: DriverFact = DriverFact::ShadowCopyBackDispatchFaster; const COPY_IN: DriverFact = DriverFact::ShadowCopyInDispatchFaster; const ROWS: DriverFact = DriverFact::RowCopiesDispatchFaster; -const MERGES: DriverFact = DriverFact::SubmissionsWithoutSignalsMerge; const MESSENGER: DriverFact = DriverFact::QueueFailuresReportedByMessenger; const STALL: DriverFact = DriverFact::SemaphoreOperationsStallSubmits; const STALL_1024: DriverFact = DriverFact::SignallingSubmitsStallEvery1024; const SAMPLED_HIZ: DriverFact = DriverFact::SampledDepthKeepsHiZ; const MSAA_DEPTH: DriverFact = DriverFact::MultisampledDepthFasterOutOfGeneral; const TILE_STORE: DriverFact = DriverFact::TileStoreIsMetals; -const FOLLOWS: DriverFact = DriverFact::PointerImportsFollowTheirAddress; const INTERLOCK_ORDER: DriverFact = DriverFact::InterlockOrdersDraws; const BLENDLESS: DriverFact = DriverFact::BlendlessColorAttachmentsWarn; const HEAP_COLORS: DriverFact = DriverFact::ColorImagesLieAsMetalHeapTextures; @@ -441,41 +439,21 @@ fn the_committed_profiles_drivers_have_their_facts() { let expected: BTreeMap> = [ ( "amd-780m-hawkpoint-radv", - vec![ - ZERO, - FETCH, - SPLIT, - COLOR_BLOCKS, - BC6H, - BC7, - ONE_OF_METALS, - MERGES, - FOLLOWS, - ], + vec![ZERO, FETCH, SPLIT, COLOR_BLOCKS, BC6H, BC7, ONE_OF_METALS], ), ( "amd-780m-radv", - vec![ - ZERO, - FETCH, - SPLIT, - COLOR_BLOCKS, - BC6H, - BC7, - ONE_OF_METALS, - MERGES, - FOLLOWS, - ], + vec![ZERO, FETCH, SPLIT, COLOR_BLOCKS, BC6H, BC7, ONE_OF_METALS], ), ("amd-rdna2-apu-radv", vec![ZERO]), ("amd-rdna3-radv", vec![ZERO]), ( "gate-lavapipe", - vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H, MERGES, FOLLOWS], + vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H], ), ( "gate-lavapipe-x86_64", - vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H, MERGES, FOLLOWS], + vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H], ), ( "intel-arl-anv", @@ -498,10 +476,8 @@ fn the_committed_profiles_drivers_have_their_facts() { ONE_OF_METALS, COPY_BACK, ROWS, - MERGES, SAMPLED_HIZ, MSAA_DEPTH, - FOLLOWS, INTERLOCK_ORDER, ], ), @@ -518,13 +494,9 @@ fn the_committed_profiles_drivers_have_their_facts() { COPY_BACK, COPY_IN, ROWS, - MERGES, ], ), - ( - "lavapipe", - vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H, MERGES, FOLLOWS], - ), + ("lavapipe", vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H]), ( "moltenvk-m3", vec![ @@ -713,23 +685,32 @@ fn nvidia_s_every_1024th_signalling_submit_stall_holds_on_the_gpu_measured() { ); } -/// RADV on the RX 7900 XTX takes the facts measured on it: its pointer imports follow their -/// address and its submissions without signals merge, as the 780M's do, and it reads zero past a -/// bound index range, RADV's on every GPU; no answer measured on the 780M alone (its block decodes, -/// `DONT_CARE` stores, interlocked split, sampled fetch) is taken. Another release takes the same. +/// RADV on a GPU no row names takes RADV's driver-wide fact alone: the Radeon 780M's own +/// description presented under the RX 7900 XTX's `deviceID` (0x744c) and under one no table names +/// (0x1114) reads zero past a bound index range, as RADV does on every GPU, and takes no answer +/// measured on the 780M alone (its block decodes, `DONT_CARE` stores, interlocked split, sampled +/// fetch), at another release too. Whether its submissions merge and whether its pointer imports +/// follow their address are no facts of the table: the runtime's device checks answer them on +/// each device (`submit_check.rs` in the runtime), so a GPU no row names takes those paths too. #[test] -fn the_rx_7900_xtx_takes_the_facts_measured_on_it() { - use crate::device::driver_facts::AMD_RX_7900_XTX; +fn a_radv_gpu_no_row_names_takes_radv_s_driver_wide_fact_alone() { let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles"); let text = std::fs::read_to_string(dir.join("amd-780m-radv.json")).expect("amd-780m-radv"); - let mut navi31 = DeviceDescription::from_khronos_json(&text, None).expect("profile parses"); - navi31.device_id = AMD_RX_7900_XTX; - let measured = - std::collections::BTreeSet::from([FOLLOWS, MERGES, DriverFact::RobustIndexFetchReadsZero]); - assert_eq!(navi31.driver_facts(), measured); - let mut other = navi31.clone(); - other.driver_version += 1; - assert_eq!(other.driver_facts(), measured); + let phoenix = DeviceDescription::from_khronos_json(&text, None).expect("profile parses"); + let answers = BTreeSet::from([FETCH, SPLIT, COLOR_BLOCKS, BC6H, BC7, ONE_OF_METALS]); + let measured = BTreeSet::from([DriverFact::RobustIndexFetchReadsZero]); + assert_eq!( + phoenix.driver_facts(), + answers.union(&measured).copied().collect() + ); + for device_id in [0x744c, 0x1114] { + let mut unlisted = phoenix.clone(); + unlisted.device_id = device_id; + assert_eq!(unlisted.driver_facts(), measured, "{device_id:#x}"); + let mut other = unlisted.clone(); + other.driver_version += 1; + assert_eq!(other.driver_facts(), measured, "{device_id:#x}"); + } } /// MoltenVK's warning of a pipeline whose restart may be disabled (`MVKPipeline.mm` lines 881-893