Group ready batches into one kernel submission on Mesa's drivers, and order a queue's batches by their ends

On ANV over i915 every kernel submission lists every VkDeviceMemory of the device, at a cost per
object; the consumer's guest drag on the Iris Xe had 302 entries per execbuffer (260 of them host
imports) at 112 to 128 execbuffers a frame. The runtime now makes fewer kernel submissions and
fewer command buffers per frame, under two new runtime policies.

What changes:
- DevicePolicy::completion, CompletionPolicy { Grouped (default), Exact }; exact_answers()
  selects Exact. Under Grouped, on a driver whose queue merges consecutive submits (Mesa's common
  queue: ANV, RADV, lavapipe, NVK and the rest), the scheduler holds ready batches of one VkQueue
  and submits up to four in one vkQueueSubmit, only the last signalling, so Mesa merges them into
  one kernel submission:
  - a batch whose only signals are events' joins, the group's end signalling each event to the
    highest index held; a batch waiting for a signal the group holds sends the group first;
  - only a group's first member may wait for anything not yet seen complete, since Mesa gathers
    every member's waits before the first member's commands; a later waiter goes alone after the
    group in the same call. Metal never holds one command buffer back for another's wait;
  - batches that cannot join (first work, binary semaphores, fences, sparse updates, wrapped
    images, storage-form switches) submit the held group first;
  - a pass that finds nothing ready keeps the group held while two or more earlier submissions of
    its queue are not seen complete, gated on the second-to-last, so commits arriving meanwhile
    join. It goes once full, when a head waits for the GPU, or when a thread waits for one of its
    command buffers;
  - a held batch that ends its command buffer turns Scheduled, takes its kernel end time and runs
    its submission handlers as it is held, so waitUntilScheduled returns at once, as Metal
    schedules a command buffer committed behind running work within 0.2 ms;
  - submission checks run ahead for up to three batches behind a line's head, so checked command
    buffers are found ready together; a failed group restores its waits, signals its last value
    and fails each member once; the group's submission allocates nothing.
  New degradation kind grouped-completion (Precision), announced once per device: a group's
  members but the last are seen complete late, by at most three later batches' GPU time plus one
  completion turn, and intermediate event values are seen late, never wrong.
- An event-signalling batch's end goes into its work's last command buffer, as every other batch's,
  unless its signal must wait for another queue's earlier signal.
- DevicePolicy::batch_order, BatchOrderPolicy { Ends (default), Exact }; exact_answers() selects
  Exact. On ANV, RADV and NVIDIA's driver, measured to run a queue's submissions one after another,
  each batch ends with a barrier to every later command of its queue, the tracker takes an earlier
  batch of that queue as ordered (no barrier per dependency), and a batch's start timestamp with
  nothing planned before it is written at the bottom of the pipe. Other drivers and Exact keep the
  barriers per dependency.
- WorkCounts: grouped_submissions, batches_grouped, group_ends_full / _wait / _apart /
  _first_work / _drained / _checks / _held, event_waits_met, batches_with_none_pending and kin by
  pending depth, groups_kept_pending and groups_sent_for_waits; frame_costs prints them, with
  kernel submissions and ioctl time where the i915 execbuffer script is loaded, and gains guest-
  shaped legs over 260 and 520 host imports.
- Docs: FAST-PATHS rows for both policies (the grouping row with the guest's frame rates), API.md
  entries, add_submission_handler's doc, the runtime README and the scheduler modules' docs.

Why: each fewer kernel submission saves the scheduler thread an ioctl of about 80 to 130 us there,
and each barrier per dependency buys nothing on drivers that run a queue's submissions in order.
The bound of four was kept: eight measured about three fewer submissions a frame for twice the
completion lateness and no frame-time change.

Verified:
- Iris Xe, guest shape over 520 host imports, Grouped against Exact: 26.2-26.7 execbuffers a frame
  against 67.0, ioctl 2.77-2.81 against 6.89-6.96 ms, scheduler 52-53 against 122-123 us per
  command buffer, through completion 5.98 against 8.70 ms a frame.
- UHD 770, the held group at a 1 ms commit pace: 25.0 kernel submissions a frame against 58.1,
  scheduler 67-82 against 113-124 us per command buffer, the same frame time and GPU idle;
  completion seen 1.82-1.86 ms after GPU end against 0.43-0.46 ms.
- In the guest on the Iris Xe, Grouped made 24.4-27.5 kernel submissions a frame against Exact's
  42.4-43.8 and saved 0.4-1.7 ms of scheduler CPU a frame; the frame rate was alike within
  boot-to-boot noise (15.7-17.3 against 16.4-17.6 fps).
- runtime_lane::grouped_submissions (held signals on one and two queues, waiters leading, groups
  held behind running work with and without submission handlers and checks, both policies, the
  validation layer silent): 19 of 19 on ANV and lavapipe; the held-handler case fails without its
  change. commit_work, gpu_times, grouped_submissions, queue_order, events and first-use lanes 77 of
  77 on the Radeon 780M, RX 7900 XTX and RTX 5080; under synchronization validation 34 of 34 on
  the UHD 770. The runtime's device tests 1066 of 1066 on ANV; the unit suites 4534 of 4534.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
This commit is contained in:
Anees Iqbal committed 2026-10-19 00:16:00 +03:00
1 parent ed3ca3aa1f
commit ca8340b4ee
41 files changed
+3614 -346

No files matched your search

+3 -2
View File
@@ -222,8 +222,9 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
encoders Metal would still run and keeping its signals, as a consumer measured on an M3 Max.
- `CommandBuffer::set_submission_check` runs a check as the command buffer is submitted, and fails
it as Metal fails a submission.
- `CommandBuffer::add_submission_handler` is called when the command buffer's last batch is
submitted; `add_executed_commands_handler` each time an execution's indirect records are read.
- `CommandBuffer::add_submission_handler` is called when the runtime takes the command buffer's
last batch for its queue (submits it, or holds it for one kernel submission with later ones);
`add_executed_commands_handler` each time an execution's indirect records are read.
- `RenderCommandEncoder::set_color_resolve_target`, `set_depth_resolve_target` and
`set_stencil_resolve_target` change where a pass resolves until it ends (the last target set
wins), as Metal's private calls do.
@@ -0,0 +1,73 @@
//! How a batch of command buffers on one `VkQueue` begins after the batches before it there
//! (`DevicePolicy::batch_order`).
//!
//! Metal orders a command buffer after the earlier ones of its queue only where its work depends
//! on theirs: an independent fill committed behind a running fill of other bytes started while
//! the first ran, on an M3 Max under macOS 27.0.1 (probe `gpustart`). The exact form copies that:
//! a batch begins with a barrier for each access that depends on an earlier batch's of its
//! `VkQueue` (`tracker.rs`), its first encoder's GPU start written at the top of the pipe, and
//! ends with [`Barrier::to_host`], which orders only the host's reads and writes after it.
//!
//! Some drivers run no two kernel submissions of one queue side by side anyway. Measured with a
//! probe outside the runtime: batches A and B, each a command buffer of a start timestamp, one of
//! work and one of an end barrier and an end timestamp, signalling the queue's timeline, B's work
//! independent of A's; work of one workgroup of 64 invocations running a dependent multiply-add
//! chain of about 3 to 10 ms (so two run side by side in about one's time), or fills of other
//! buffers; with no end barrier, `to_host`'s or [`Barrier::to_all`]'s; in two `vkQueueSubmit`
//! calls or one; with and without the timestamps, the queries reset on the host or the GPU, and
//! with only the last submission signalling. On each of these, every shape ran B after A, in
//! about the sum of their times (20.0 ms for two 10 ms batches on the RTX 5080 Laptop GPU, 18.5
//! on the RX 7900 XTX, 20.0 on the UHD 770), where the same two dispatches recorded in one command
//! buffer ran side by side (10.0, 9.3 and 10.0 ms):
//! - ANV (Mesa 26.2.4) on the UHD 770 of RPL-S;
//! - RADV (Mesa 26.0.8) on the Radeon 780M and the RX 7900 XTX;
//! - NVIDIA's driver (615.71.09) on the RTX 5080 Laptop GPU.
//!
//! On those drivers ([`ends_order`]) the default form orders batches by their ends: every batch
//! ends with [`Barrier::to_all`], every write before every access of every later command of its
//! `VkQueue`, so the tracker plans no barrier after an access of an earlier batch there
//! ([`Tracker::by_ends`](crate::tracker::Tracker)), and a batch's start timestamp is written at the
//! bottom of the pipe ([`start_stage`]): once everything before it in submission order completed,
//! which is when such a driver starts it. A batch no longer needs a command buffer of barriers
//! for a dependency on the batch before it (on the UHD 770, with the consumer's frames over 520
//! host imports, 67.0 command buffers submitted a frame against 129.3 to 129.7), and runs as the
//! driver ran it before. Elsewhere, and under `BatchOrderPolicy::Exact`, the exact form.
use crate::tracker::Barrier;
use ash::vk;
use metal2vulkan::device::{BatchOrderPolicy, DevicePolicy};
use metal2vulkan::vk::DriverId;
/// Whether a device of `policy` and `driver` orders its batches by their ends (the module docs):
/// its policy asks for it and its driver is measured to run no two kernel submissions of one
/// queue side by side.
pub(crate) fn by_ends(policy: &DevicePolicy, driver: Option<DriverId>) -> bool {
policy.batch_order == BatchOrderPolicy::Ends && ends_order(driver)
}
/// Whether the driver is measured to run the kernel submissions of one queue one after another,
/// with or without a barrier between them (the module docs).
fn ends_order(driver: Option<DriverId>) -> bool {
matches!(
driver,
Some(DriverId::INTEL_OPEN_SOURCE_MESA | DriverId::MESA_RADV | DriverId::NVIDIA_PROPRIETARY)
)
}
/// The barrier that ends each batch of a device that orders its batches `by_ends` or not.
pub(crate) fn end(by_ends: bool) -> Barrier {
match by_ends {
true => Barrier::to_all(),
false => Barrier::to_host(),
}
}
/// The stage a batch's start timestamp is written at where nothing is planned before it: the
/// top of the pipe, as its work begins, or, where batches are ordered `by_ends`, the bottom,
/// once everything before it completed.
pub(crate) fn start_stage(by_ends: bool) -> vk::PipelineStageFlags {
match by_ends {
true => vk::PipelineStageFlags::BOTTOM_OF_PIPE,
false => vk::PipelineStageFlags::TOP_OF_PIPE,
}
}
@@ -19,7 +19,13 @@
//! thread, without its own lock or the command buffer's, it then runs the check of each
//! submission that begins in the batch, and again of each that a host step of the batch
//! recorded commands for (what they reach is known only then), then submits the batch in its
//! order.
//! order. Where the scheduler groups batches (`CompletionPolicy::Grouped` on a driver that
//! merges submissions, `group.rs`), it runs the checks of up to three batches right behind a
//! head that goes with the head's, in commit order, each once its batch is otherwise ready and
//! its events' values reached on the device or by the host, none committed after another
//! queue's batch: so they go to the driver together. Such a check runs before the previous
//! batch's `vkQueueSubmit`, in the pass that submits its own batch, where alone it runs after
//! it. `CompletionPolicy::Exact` checks each head alone.
//! - **Stricter than Metal: the re-check after a host step.** Metal checks a submission once,
//! with what it knows as it submits it, and cannot know what the commands the GPU writes into
//! an indirect command buffer reach before they run (an earlier encoder of the same submission
@@ -68,17 +68,17 @@
//! every light queue's burst of the queue storm (`runtime_lane::queue_storms`) into its tail.
//! While its waiter makes a turn, a queue's next batch waits for that turn to end before its wait
//! begins; its fence and value stay signaled meanwhile.
//! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes
//! once the batch completed: its last command buffer makes them available to the host
//! (`Barrier::to_host`), before its signal in submission order, and the host's reads come after
//! a host wait for that signal. Vulkan orders host operations after a signal only through a
//! wait: "signal operations happening before host operations that wait on them"
//! system-synchronize-with them (the memory model), and a fence's "execution dependency is
//! defined by waiting for a fence to become signaled, either via `vkWaitForFences` or by
//! polling on `vkGetFenceStatus`". It gives `vkGetSemaphoreCounterValue` no such dependency (its
//! value "may immediately be out of date"). So a value the read shows past the one a wait
//! returned for (later batches that completed meanwhile, or the front's after a wait that ran
//! out) is waited for in turn, a wait that returns at once ("If the condition is satisfied when
//! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes once
//! the batch completed: its last command buffer makes them available to the host
//! (`Barrier::to_host`, or `Barrier::to_all`), before its signal in submission order, and the
//! host's reads come after a host wait for that signal. Vulkan orders host operations after a
//! signal only through a wait: "signal operations happening before host operations that wait on
//! them" system-synchronize-with them (the memory model), and a fence's "execution dependency is
//! defined by waiting for a fence to become signaled, either via `vkWaitForFences` or by polling
//! on `vkGetFenceStatus`". It gives `vkGetSemaphoreCounterValue` no such dependency (its value
//! "may immediately be out of date"). So a value the read shows past the one a wait returned for
//! (later batches that completed meanwhile, or the front's after a wait that ran out) is waited
//! for in turn, a wait that returns at once ("If the condition is satisfied when
//! `vkWaitSemaphores` is called, then `vkWaitSemaphores` returns immediately"), before it is
//! published: one call more, and only where the read ran ahead.
//! - **Waits are bounded.** A waiter waits at most [`WAIT_SLICE`] at a time, so a stop is seen
@@ -1,2 +1,593 @@
//! Batches that go to the driver in one kernel submission (`CompletionPolicy::Grouped`).
//!
//! On a driver whose queue is Mesa's common one, each `vkQueueSubmit`'s `VkSubmitInfo`s that
//! signal nothing merge into the next one's kernel submission (Mesa 26.2.4,
//! `vulkan/runtime/vk_queue.c`, `vk_queue_submits_merge`: "Don't merge if there are signals in
//! between"), and 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: ANV on i915 lists each in every execbuffer
//! (`i915/anv_batch_chain.c`, `setup_execbuf_for_cmd_buffers`), RADV each in every CS.
//!
//! - **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,
//! no fence; binds no sparse update; does no first work; moves none of the caller's wrapped
//! images; and waits for no event index a batch held signals (only the group's end would meet
//! it: on one `VkQueue` that wait would never be met). Every other batch goes as before, after
//! the group held on its `VkQueue` went (`Submitting::AfterGroup`), and so does one of another
//! `VkQueue`, so a wait there for a held signal follows the group's submission too. A batch
//! that waits for anything not seen complete (an event, another `VkQueue`'s work, first work)
//! leads a group and never joins one: it goes after a group held, in a submission of its own.
//! A group goes at once when it holds [`GROUP_BATCHES`], so no submission holds more.
//! - **Checked ahead.** A batch with submission checks is ready only once they ran
//! (`checks.rs`), which the scheduler does for each line's head; here it runs those of the
//! batches right behind a head that goes too, so a line of checked batches (the consumer checks
//! every command buffer) is found ready together (`scheduler::check_heads`).
//! - **One submission.** [`Group::submit`] submits every batch held, in order, in one
//! `vkQueueSubmit` where only the last `VkSubmitInfo` signals: each event's semaphore to the
//! highest index a batch held signals it to, then the queue's timeline to the last batch's
//! value. Each is above every other batch's signal of it, so it reaches theirs too ("the
//! semaphore's value is set to the signal value" once the batch's commands complete, and a value
//! reached is reached by every wait for a lower one; the first synchronization scope of a signal
//! holds "every command in the same batch ... and all commands that occur earlier in submission
//! order", `vkQueueSubmit`). An event's indices rise in its signals' submission order
//! (`event_timeline.rs`), so its earlier values land with the group's end, late, never wrong:
//! a wait on another `VkQueue` for one is met by the higher index, and the host's waits, value
//! reads and listeners see the event's value rise once that index is seen. Each batch keeps its
//! own commands, barriers and its end's barrier to the host. Only the first batch may wait for a
//! value not seen complete, for a signal submitted before it, the scheduler's order: the merge
//! gathers every batch's waits before the first one's commands, so a later batch's wait would
//! hold back the earlier ones' start until it is met, and none is held.
//! - **Taken as made.** What a batch's submission changes in the scheduler's state (the tracker's
//! plan, its queue's value, the completed values its queue waited for) is changed as it is held,
//! so the next batch is planned after it. Where it ends its command buffer, on which no switch of
//! storage forms rides, the command buffer's kernel end and its transition to `Scheduled` come as
//! it is held, its submission handlers run before that on the scheduler's thread once its lock is
//! free, as a submitted batch's do ([`Group::schedule_held`]), as Metal schedules a command
//! buffer committed behind running work at once: on an M3 Max under macOS 27.0.1, each of 8
//! committed behind a 55 ms kernel on its queue was `Scheduled` 0.04 to 0.18 ms after its commit,
//! its scheduled handler run, about 55 ms before that kernel ended (probe `scheduled`). Its queue
//! waiter's watch comes once the group is submitted. A submission that fails without losing the
//! device changed nothing (`vkQueueSubmit`), so the events' semaphores and the timeline are
//! brought to the group's end by a submission of those signals alone, the waits taken are put
//! back, and each batch's command buffer fails (one already `Scheduled` from there); where that
//! fails too, the device is lost to the runtime, its timeline short of the values its tracker
//! holds.
//! - **Kept while its queue runs earlier work** ([`Group::keeps`]). A pass that finds no batch
//! ready sends the group, unless two or more submissions of its `VkQueue` are not seen complete
//! (`QueueSlot::pending_beyond_one`): the GPU runs those first in any case, in submission order,
//! so the group stays held for the batches committed meanwhile, gated on the value whose
//! completion leaves one submission in flight, at which a completion turn wakes the scheduler.
//! It goes with one in flight rather than two: on the UHD 770 two cut the kernel submissions
//! less (30 a frame against 24, at 67 command buffers a frame committed 1 ms apart behind 1.3 ms
//! of GPU work each) and left the GPU as idle (0.62 ms a frame with either).
//! It goes then, or once it fills, a batch that cannot join sends it, a head waits for the GPU
//! (at a gate, or for a signal to land, which may be the group's), or a thread waits for one of
//! its command buffers' completion (`CommandBuffer::wait_until_completed` marks it and wakes the
//! scheduler: [`CommandBufferShared::waits_for_completion`]). A group whose batch ends a command
//! buffer with a switch of storage forms riding on it is never kept: the switch settles by the
//! submission's outcome, before the command buffer is `Scheduled`. A kept batch is seen
//! complete late by its group's later batches' GPU time, as any member, and where the one
//! submission left in flight ends before the group reaches the GPU, by that gap besides: at most
//! a completion turn's reaction and the group's `vkQueueSubmit`. Counted:
//! `WorkCounts::groups_kept_pending`, `WorkCounts::groups_sent_for_waits`.
//! - **Counted by its end.** Each group held counts once by what sent it ([`GroupEnd`],
//! `WorkCounts::group_ends_full` and kin): so the consumer's counts say why its groups hold
//! fewer batches than they may.
//! - **No allocation.** A group's submission names at most [`MOST_INFOS`] `VkSubmitInfo`s, built
//! in arrays on the thread's stack; its end's signals and its submissions go to lists the group
//! keeps with their room: the scheduler thread allocates nothing for it
//! (`runtime_lane::frame_costs`, `a_frame_s_commits_allocate_within_their_bound`).
use super::submit::Submission;
use super::{submission_error, CommandBufferShared};
use crate::degradation::Degradation;
use crate::device::relay::Relayed;
use crate::error::CommandBufferError;
use crate::exit_guard::{self, Call};
use crate::gpu_time;
use crate::Device;
use ash::vk;
use metal2vulkan::device::CompletionPolicy;
use metal2vulkan::vk::DriverId;
use std::sync::atomic::Ordering;
use std::sync::Arc;
/// The most batches one kernel submission holds: the first is seen complete late by the GPU time
/// of at most this many less one.
pub(crate) const GROUP_BATCHES: usize = 4;
/// The most `VkSubmitInfo`s a batch names: its work's and its finale's (`submit.rs`).
const BATCH_INFOS: usize = 2;
/// The most `VkSubmitInfo`s one group's `vkQueueSubmit` names: [`BATCH_INFOS`] for each batch
/// held, and for the batch after them its first work's beside its own.
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 merges 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`).
pub(crate) fn groups(device: &Device, queue: usize) -> bool {
device.compile_device().policy().completion == CompletionPolicy::Grouped
&& merges_submissions(device.properties().description.driver_id)
&& device.shared().flights(queue).is_none()
}
impl CommandBufferShared {
/// Whether its batches may wait in a group ([`groups`]).
pub(crate) fn groups(&self) -> bool {
groups(&self.device, self.queue.vk_queue())
}
/// A batch of it was held in the scheduler's group.
pub(crate) fn held_in_group(&self) {
self.group_hold.fetch_or(IN_GROUP, Ordering::SeqCst);
}
/// Its batches held in the group went, or failed.
pub(crate) fn left_group(&self) {
self.group_hold.fetch_and(!IN_GROUP, Ordering::SeqCst);
}
/// A thread begins to wait for its completion: where a batch of it is held in the group, the
/// scheduler is woken, and sends the group at once ([`Group::keeps`]). The scheduler marks a
/// batch held before it looks for a waiter, and the waiter marks its wait before it looks for
/// a batch held, each on the same word, so one of the two sees the other.
pub(crate) fn waits_for_completion(&self) {
let before = self.group_hold.fetch_or(WAITED_FOR, Ordering::SeqCst);
if before & IN_GROUP != 0 {
self.device.shared().scheduler.wake();
}
}
/// Whether a thread waits for its completion.
fn is_waited_for(&self) -> bool {
self.group_hold.load(Ordering::SeqCst) & WAITED_FOR != 0
}
}
/// A command buffer's `group_hold` bit: a batch of it is held in the scheduler's group.
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's queue is Mesa's common one with kernel submissions of their own: the
/// drivers that merge a `VkSubmitInfo` that signals nothing into the next.
fn merges_submissions(driver: Option<DriverId>) -> bool {
matches!(
driver,
Some(
DriverId::MESA_RADV
| DriverId::INTEL_OPEN_SOURCE_MESA
| DriverId::MESA_LLVMPIPE
| DriverId::MESA_TURNIP
| DriverId::MESA_V3DV
| DriverId::MESA_PANVK
| DriverId::MESA_NVK
| DriverId::MESA_HONEYKRISP
| DriverId::IMAGINATION_OPEN_SOURCE_MESA
)
)
}
/// What sent a group held (`WorkCounts::group_ends_full` and kin).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GroupEnd {
/// It held [`GROUP_BATCHES`].
Full,
/// A batch waits: for an event index a batch held signals, which only the group's end meets,
/// or for anything else not seen complete (it goes after the group, never in it).
Wait,
/// A batch that may not wait in a group (a binary semaphore, a fence, a sparse update, a move
/// of bytes that waits for every submission), or one of another `VkQueue`.
Apart,
/// A batch that may join did first work or names a wrapped image: it went last in the group's
/// call.
FirstWork,
/// The pass found no batch left to submit.
Drained,
/// The pass found none ready, with submission checks or host steps left for the thread to run.
Checks,
/// The pass found none ready, the rest held for events, gates, binary semaphores or decodes.
Held,
}
/// One `VkSubmitInfo`'s lists, kept with their room from batch to batch.
#[derive(Default)]
pub(crate) struct Info {
wait_semaphores: Vec<vk::Semaphore>,
wait_values: Vec<u64>,
wait_stages: Vec<vk::PipelineStageFlags>,
buffers: Vec<vk::CommandBuffer>,
signal_semaphores: Vec<vk::Semaphore>,
signal_values: Vec<u64>,
}
/// What one `VkSubmitInfo` waits for, runs and signals, borrowed.
pub(crate) struct InfoParts<'a> {
pub(crate) waits: (&'a [vk::Semaphore], &'a [u64], &'a [vk::PipelineStageFlags]),
pub(crate) buffers: &'a [vk::CommandBuffer],
pub(crate) signals: (&'a [vk::Semaphore], &'a [u64]),
}
impl Info {
fn fill(&mut self, parts: &InfoParts<'_>) {
let (semaphores, values, stages) = parts.waits;
self.wait_semaphores.clear();
self.wait_semaphores.extend_from_slice(semaphores);
self.wait_values.clear();
self.wait_values.extend_from_slice(values);
self.wait_stages.clear();
self.wait_stages.extend_from_slice(stages);
self.buffers.clear();
self.buffers.extend_from_slice(parts.buffers);
let (semaphores, values) = parts.signals;
self.signal_semaphores.clear();
self.signal_semaphores.extend_from_slice(semaphores);
self.signal_values.clear();
self.signal_values.extend_from_slice(values);
}
}
/// A batch held: its `VkSubmitInfo`s, how many command buffers they hold, and its submission,
/// published once the group is submitted.
struct Member {
infos: Vec<Info>,
buffers: usize,
submission: Submission,
}
/// The batches held for one kernel submission on one `VkQueue` (the module docs), in the
/// scheduler's state.
#[derive(Default)]
pub(crate) struct Group {
queue: usize,
members: Vec<Member>,
/// It stayed held past a pass for the work its queue ran ([`keeps`](Group::keeps)).
kept: bool,
/// The completed values `queue` waited for before the first batch held: put back where the
/// group's submission fails.
waited: Vec<u64>,
/// The events' semaphores the batches held signal, each with the lowest and the highest index
/// they signal it to: the group's end signals the highest (the module docs).
events: Vec<(vk::Semaphore, u64, u64)>,
/// The lists of batches submitted, kept with their room.
spare: Vec<Vec<Info>>,
/// The end's signals: each event's semaphore, then the queue's timeline, and their values;
/// kept with their room.
end_semaphores: Vec<vk::Semaphore>,
end_values: Vec<u64>,
/// The batches the group's last submission made, in order, until the scheduler takes them
/// ([`made`](Group::made)); kept with their room.
made: Vec<Submission>,
/// What the group's last submission did, until the scheduler takes it
/// ([`take_outcome`](Group::take_outcome)): made ([`made`](Group::made)), or failed.
outcome: Option<Result<(), CommandBufferError>>,
}
/// A batch submitted after the group, in the same `vkQueueSubmit` ([`Group::submit`]).
pub(crate) struct After<'a> {
/// Its `VkQueue`: the group's, where one is held.
pub(crate) queue: usize,
pub(crate) infos: &'a [vk::SubmitInfo<'a>],
pub(crate) buffers: usize,
/// The value it signals on the queue's timeline.
pub(crate) value: u64,
pub(crate) fence: Option<vk::Fence>,
pub(crate) relayed: &'a Arc<Relayed>,
}
impl Group {
/// The `VkQueue` of the batches held.
pub(crate) fn queue(&self) -> usize {
self.queue
}
/// Whether it holds a batch.
pub(crate) fn holds(&self) -> bool {
!self.members.is_empty()
}
/// Whether a batch on `VkQueue` `queue` may be submitted now, the group held so far going
/// first: the group is empty, or the batch may wait in it (`joins`) on its queue with room.
pub(crate) fn admits(&self, queue: usize, joins: bool) -> bool {
self.members.is_empty()
|| (joins && self.queue == queue && self.members.len() < GROUP_BATCHES)
}
/// Whether a batch held signals the event of `semaphore` to `index` or above: only the group's
/// end meets a wait for it, so a batch with that wait goes after the group, in a submission
/// of its own (the module docs). A lower index was signalled before the group.
pub(crate) fn meets(&self, (semaphore, index): (vk::Semaphore, u64)) -> bool {
(self.events.iter()).any(|&(signaled, lowest, _)| signaled == semaphore && index >= lowest)
}
/// Whether the group holds [`GROUP_BATCHES`]: the scheduler submits it at once. A batch that
/// may join, found with room, goes with at most a batch less held, so no submission holds
/// more.
pub(crate) fn full(&self) -> bool {
self.members.len() >= GROUP_BATCHES
}
/// A batch on `VkQueue` `queue` is held, before its submission changes the scheduler's
/// state: `waited` is what `queue` waited for so far, put back where the group's submission
/// fails. Its lists come once its changes are made ([`hold`](Group::hold)).
pub(crate) fn open(&mut self, queue: usize, waited: &[u64]) {
if self.members.is_empty() {
self.queue = queue;
self.waited.clear();
self.waited.extend_from_slice(waited);
}
}
/// The batch [`open`](Group::open) took: its `VkSubmitInfo`s are `infos` (at most
/// [`BATCH_INFOS`]), with `buffers` command buffers, and its submission is published once the
/// group's is made. It signals each event's semaphore it names to its index, which the
/// group's end signals instead.
pub(crate) fn hold(&mut self, infos: &[InfoParts<'_>], buffers: usize, submission: Submission) {
for (semaphore, index) in submission.event_signals() {
match self.events.iter_mut().find(|(held, ..)| *held == semaphore) {
Some((_, lowest, highest)) => {
*lowest = (*lowest).min(index);
*highest = (*highest).max(index);
}
None => self.events.push((semaphore, index, index)),
}
}
let mut held = self.spare.pop().unwrap_or_default();
held.resize_with(infos.len(), Info::default);
for (info, parts) in held.iter_mut().zip(infos) {
info.fill(parts);
}
self.members.push(Member {
infos: held,
buffers,
submission,
});
}
/// The batch [`hold`](Group::hold) took last, after the section that held it ended: where it
/// ends its command buffer and no switch of storage forms rides on it, its kernel end and its
/// transition to `Scheduled` now, not once the group is submitted, and its submission
/// handlers for the scheduler's thread to run now, once its lock is free (the module docs):
/// whether it has them.
pub(crate) fn schedule_held(&mut self) -> bool {
(self.members.last_mut()).is_some_and(|member| member.submission.schedule_held())
}
/// Whether the batches held stay held past the pass that found no batch ready (the module
/// docs): the group has room, two or more submissions of its `VkQueue` are not seen complete,
/// no batch held ends a command buffer with a switch of storage forms riding on it (it settles
/// by the submission's outcome), no thread waits for one of their command buffers, and the
/// device is not lost.
/// The value of that queue's timeline whose completion leaves one submission in flight, for
/// the completion turns to wake the scheduler at. Counted once per group, and once more where
/// a waiter sends a group kept before.
pub(crate) fn keeps(&mut self) -> Option<u64> {
let first = self.members.first()?;
let device = first.submission.buffer().device();
if self.full()
|| device.is_lost()
|| (self.members.iter()).any(|member| member.submission.rides_forms())
{
return None;
}
let counts = &device.shared().counts;
if (self.members.iter()).any(|member| member.submission.buffer().is_waited_for()) {
if self.kept {
counts.group_sent_for_wait();
}
return None;
}
let value = device.shared().queues[self.queue].pending_beyond_one()?;
if !self.kept {
self.kept = true;
counts.group_kept_pending();
}
Some(value)
}
/// What the group's last submission did, for the scheduler to publish its batches
/// ([`made`](Group::made)) or fail them.
pub(crate) fn take_outcome(&mut self) -> Option<Result<(), CommandBufferError>> {
self.outcome.take()
}
/// The batches the group's last submission made, in order, for the scheduler to publish.
pub(crate) fn made(&mut self) -> std::vec::Drain<'_, Submission> {
self.made.drain(..)
}
/// Submit every batch held, then `after` where given, in one `vkQueueSubmit` on the group's
/// `VkQueue` of `device`, only the last signalling (the module docs); `waited` is the
/// scheduler's list of what that queue waited for. Inside a section of the exit guard. The
/// held batches' outcome is kept for the scheduler ([`take_outcome`](Group::take_outcome));
/// the call's own result is `after`'s, as the `vkQueueSubmit` returned it.
pub(crate) fn submit(
&mut self,
device: &Device,
waited: &mut [u64],
after: Option<After<'_>>,
) -> Result<(), vk::Result> {
if self.members.is_empty() {
return match after {
None => Ok(()),
Some(after) => submit_alone(device, after),
};
}
let shared = device.shared();
let raw = shared.vk();
let queue = self.queue;
let count = self.members.len();
let alone = after.is_none();
self.kept = false;
let held_value = self.members[count - 1].submission.value();
// The held batches' end: each event's semaphore to the highest index a batch held
// signals it to, then the queue's timeline to the last one's value. It ends the
// submission, or, where a batch goes after the group and the held ones signal an event,
// their part of it (that batch's infos then follow a signal, so the driver submits them
// apart).
let ends = alone || !self.events.is_empty();
self.end_semaphores.clear();
(self.end_semaphores).extend((self.events.iter()).map(|&(semaphore, ..)| semaphore));
(self.end_semaphores).push(shared.queues[queue].timeline);
self.end_values.clear();
(self.end_values).extend((self.events.iter()).map(|&(_, _, highest)| highest));
self.end_values.push(held_value);
let (end_semaphores, end_values) = (&self.end_semaphores, &self.end_values);
// Only the held batches' last `VkSubmitInfo` signals: every other one's signals (its
// queue's timeline and its events') are reached by the end's higher values.
let held = || (self.members.iter()).flat_map(|member| &member.infos);
let infos = held().count();
let submitting = infos + after.as_ref().map_or(0, |after| after.infos.len());
// Each batch's `VkSubmitInfo`s are its work's and its finale's (`submit.rs`), and the
// group holds at most `GROUP_BATCHES`: none is left out of the arrays.
assert!(
submitting <= MOST_INFOS,
"{submitting} VkSubmitInfos in one submission"
);
let signals = |at: usize| ends && at + 1 == infos;
let mut timelines = [vk::TimelineSemaphoreSubmitInfo::default(); MOST_INFOS];
for (at, (timeline, info)) in timelines.iter_mut().zip(held()).enumerate() {
let values: &[u64] = if signals(at) { end_values } else { &[] };
*timeline = vk::TimelineSemaphoreSubmitInfo::default()
.wait_semaphore_values(&info.wait_values)
.signal_semaphore_values(values);
}
let mut submits = [vk::SubmitInfo::default(); MOST_INFOS];
let built = submits.iter_mut().zip(timelines.iter_mut()).zip(held());
for (at, ((submit, timeline), info)) in built.enumerate() {
let semaphores: &[vk::Semaphore] = if signals(at) { end_semaphores } else { &[] };
*submit = vk::SubmitInfo::default()
.wait_semaphores(&info.wait_semaphores)
.wait_dst_stage_mask(&info.wait_stages)
.command_buffers(&info.buffers)
.signal_semaphores(semaphores)
.push_next(timeline);
}
let mut buffers: usize = (self.members.iter()).map(|member| member.buffers).sum();
let last = &self.members[count - 1].submission;
let relayed = Arc::clone(match &after {
Some(after) => after.relayed,
None => &last.buffer().relayed,
});
let (value, fence) = match &after {
Some(after) => {
submits[infos..submitting].copy_from_slice(after.infos);
buffers += after.buffers;
(after.value, after.fence)
}
None => (held_value, None),
};
let submits = &submits[..submitting];
// SAFETY: as each batch's own submission (`submit.rs`): every command buffer is
// executable and submitted once; every wait is for a signal submitted before; the one
// timeline signal is above the queue's value; the `VkQueue` is used under its lock.
let submitted =
shared.submit_logged((queue, Some(value)), fence, &relayed, |vk_queue| unsafe {
shared.counts.queue_submitted(buffers);
raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null()))
});
exit_guard::called(Call::QueueSubmit);
self.events.clear();
let several = count + usize::from(!alone) > 1;
let outcome = match submitted {
Ok(()) => {
let now = gpu_time::host_nanos();
for member in self.members.drain(..) {
self.spare.push(member.infos);
if member.submission.ends() && !member.submission.scheduled() {
member.submission.buffer().kernel.end_at(now);
}
self.made.push(member.submission);
}
if several {
shared.counts.batches_grouped(count + usize::from(!alone));
}
Ok(())
}
Err(error) => {
for member in self.members.drain(..) {
self.spare.push(member.infos);
}
waited.copy_from_slice(&self.waited);
let failure = submission_error(device, error);
if !device.is_lost()
&& signal_alone(
device,
queue,
(&self.end_semaphores, &self.end_values),
&relayed,
)
.is_err()
{
device.mark_lost();
}
if matches!(failure, CommandBufferError::DeviceLost) && alone {
device.drain_queues();
}
Err(failure)
}
};
if several && outcome.is_ok() {
let batches = count + usize::from(!alone);
device.degrade_once(Degradation::GroupedCompletion, || {
(
format!("{batches} batches of command buffers on one queue"),
"the scheduler found them ready together, on a driver that merges a \
submission that signals nothing into the next one"
.to_owned(),
)
});
}
self.outcome = Some(outcome);
submitted
}
}
/// Submit `after` alone on its `VkQueue` of `device`: the group's submission with no batch held.
fn submit_alone(device: &Device, after: After<'_>) -> Result<(), vk::Result> {
let shared = device.shared();
let raw = shared.vk();
let After {
queue,
infos,
buffers,
value,
fence,
relayed,
} = after;
// SAFETY: the batch's submission's own (`submit.rs`).
let submitted = shared.submit_logged((queue, Some(value)), fence, relayed, |vk_queue| unsafe {
shared.counts.queue_submitted(buffers);
raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null()))
});
exit_guard::called(Call::QueueSubmit);
submitted
}
/// Signal the end a failed group held (its events' semaphores to their indices, then `VkQueue`
/// `queue`'s timeline to its last value) with a submission of nothing else, after the group's
/// submission failed without losing the device (the module docs).
fn signal_alone(
device: &Device,
queue: usize,
(semaphores, values): (&[vk::Semaphore], &[u64]),
relayed: &Arc<Relayed>,
) -> Result<(), vk::Result> {
let shared = device.shared();
let raw = shared.vk();
let value = values.last().copied();
let mut timeline = vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(values);
let info = vk::SubmitInfo::default()
.signal_semaphores(semaphores)
.push_next(&mut timeline);
// SAFETY: a submission of the signals a failed group's end held, each above its semaphore's
// value (no batch signalled them); the `VkQueue` is used under its lock.
let submitted = shared.submit_logged((queue, value), None, relayed, |vk_queue| unsafe {
shared.counts.queue_submitted(0);
raw.queue_submit(vk_queue, &[info], vk::Fence::null())
});
exit_guard::called(Call::QueueSubmit);
submitted
}
@@ -2,20 +2,20 @@
//!
//! A batch with encoders submits a command buffer of barriers before each encoder the tracker
//! planned a barrier for (before its first, whatever was planned, where the driver's submissions
//! stall on semaphore operations: `Barrier::after_completed`, `submit.rs`), and, where its end
//! did not go into its last encoder's command buffer, one after its last (`Barrier::to_host`;
//! `submit.rs`): batch after batch, the same few lists of barriers. A timed command buffer's
//! first batch also resets its slot of the device's timestamp
//! pools and writes the start timestamp first, in a command buffer before its first encoder (of
//! the barrier planned for it, or of none), and its last batch writes the end timestamp in its
//! end (`gpu_time.rs`). Each list's command buffer is recorded once, kept by the scheduler, and
//! stall on semaphore operations: `Barrier::after_completed`, `submit.rs`), and, where its end did
//! not go into its last encoder's command buffer, one after its last (`Barrier::to_host`, or
//! `Barrier::to_all`: `batch_order.rs`; `submit.rs`): batch after batch, the same few lists of
//! barriers. A timed command buffer's first batch also resets its slot of the device's timestamp
//! pools and writes the start timestamp first, in a command buffer before its first encoder (of the
//! barrier planned for it, or of none), and its last batch writes the end timestamp in its end
//! (`gpu_time.rs`). Each list's command buffer is recorded once, kept by the scheduler, and
//! submitted again by a later batch once the batch that last carried it completed, its queue's
//! timeline at that batch's value as the host saw it: the same commands, in the same place of the
//! same submission, and no command buffer begun for them as a batch is submitted. ANV clears a
//! command buffer's state as its pool resets it and again as it begins it (Mesa 26.2.4,
//! `anv_cmd_state_init`, 62,776 bytes), and packs the standard sample pattern at each primary
//! one's begin where `VK_EXT_sample_locations` is enabled (`genX(BeginCommandBuffer)`): on ms01's
//! Iris Xe those begins were 53% of the scheduler thread's user time, two a command buffer.
//! `anv_cmd_state_init`, 62,776 bytes), and packs the standard sample pattern at each primary one's
//! begin where `VK_EXT_sample_locations` is enabled (`genX(BeginCommandBuffer)`): on ms01's Iris Xe
//! those begins were 53% of the scheduler thread's user time, two a command buffer.
//!
//! - **Never pending twice.** A kept command buffer is recorded without
//! `VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT` and goes to one batch at a time: ANV chains a
@@ -84,8 +84,9 @@ pub(crate) struct KeptBarriers {
/// The timestamps a barrier command buffer writes into a timed command buffer's slot of the
/// device's timestamp pools (`gpu_time::Slot`): with `start`, the slot reset before its barriers
/// and the start timestamp before them at the top of the pipe, or with `after` after them at the
/// bottom of the pipe; with `end`, the end timestamp after them.
/// and the start timestamp before them at the top of the pipe (the bottom where batches are
/// ordered by their ends: `batch_order.rs`), or with `after` after them at the bottom of the pipe;
/// with `end`, the end timestamp after them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct SlotStamps {
/// The slot's timestamp pool.
@@ -369,8 +370,8 @@ impl KeptBarriers {
exit_guard::called(Call::CmdResetQueryPool);
}
if !stamps.after {
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
raw.cmd_write_timestamp(buffer, top, stamps.queries, stamps.first);
let stage = crate::batch_order::start_stage(shared.by_ends);
raw.cmd_write_timestamp(buffer, stage, stamps.queries, stamps.first);
exit_guard::called(Call::CmdWriteTimestamp);
}
}
@@ -14,11 +14,8 @@
//! `Completed` or `Error`. The transitions after `Committed` run in the queue's serial context on
//! the device's handler threads ([`contexts`](super::contexts)), in the queue's order: to
//! `Scheduled` once its last batch is submitted (every wait of it satisfied), with its scheduled
//! handlers; to `Completed` once its work completed, with its completed handlers and the release
//! of what it retained. As on Metal, a queue's command buffer whose work completed stays
//! `Committed` while an earlier transition of its queue, a handler, still runs. Its submission
//! handlers (a runtime extension) run before its transition to `Scheduled`, on the thread that
//! submitted its last batch, which the transition waits for.
//! thread that took its last batch for its queue (submitted it, or held it for one kernel
//! submission with later batches: `group.rs`), which the transition waits for.
//!
//! Encoders write their commands' own data (tables, neutral buffers) into the command buffer's
//! upload arena ([`upload`](super::upload)), and the execution status words its commands share; the
@@ -31,6 +28,7 @@ pub(super) mod completion;
pub(super) mod fences;
mod first_submission;
pub(super) mod gate;
mod group;
pub(super) mod kept_barriers;
pub(super) mod own;
mod reencode;
@@ -39,7 +37,8 @@ mod submit;
pub(super) use completion::Completion;
pub(super) use first_submission::NotedTable;
pub(super) use submit::BatchLists;
pub(super) use group::{Group, GroupEnd, GROUP_BATCHES};
pub(super) use submit::{BatchLists, Submitting};
use super::contexts::{self, Run};
use super::deferred::{Deferred, Prepared};
@@ -76,7 +75,7 @@ use super::sparse::encoder::SparseUpdate;
use super::sparse::indirect::{self, ReadFailure};
use super::texture::storage_form::Riding;
use super::texture::Texture;
use super::tracker::{Barrier, Footprint};
use super::tracker::Footprint;
use super::upload::{Upload, Uploads};
use super::used_resources::{EncoderKind, EncoderRecord, Reached, ReadRecord};
use super::values::CommandBufferStatus;
@@ -100,7 +99,7 @@ use own::{
use std::any::Any;
use std::collections::{BTreeSet, HashSet, VecDeque};
use std::ops::Range;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};
@@ -182,6 +181,9 @@ pub(super) struct CommandBufferShared {
/// here: no lock is taken first at a commit (on Apple's hosts a mutex allocates at its first
/// lock).
error: OnceLock<CommandBufferError>,
/// Whether a batch of it is held in the scheduler's group, and whether a thread waits for its
/// completion: a group kept past a pass goes at once once one does (`group.rs`).
group_hold: AtomicU8,
}
/// The word [`CommandBufferShared::status`] holds for `status`: its raw value.
@@ -423,9 +425,10 @@ pub(super) struct State {
batches: Batches<Arc<EventShared>, vk::Semaphore>,
scheduled: VecDeque<Handler>,
/// Its submission handlers ([`CommandBuffer::add_submission_handler`]): run on the thread
/// that submits its last batch, before its transition to `Scheduled`.
/// that takes its last batch for its queue (submits it, or holds it in a group), before its
/// transition to `Scheduled`.
submission: VecDeque<Handler>,
/// The thread that submitted its last batch has its submission handlers to run, or the
/// The thread that took its last batch has its submission handlers to run, or the
/// switch of storage forms riding on it to end (`texture/storage_form.rs`): its transition to
/// `Scheduled` waits until it did.
submitting: bool,
@@ -1006,13 +1009,18 @@ impl State {
.unwrap_or(batches.len() - 1)
}
/// Whether batch `index`'s end may go into its last `VkCommandBuffer` (`submit.rs`): it
/// signals no event (whose kept signal may need the end after a wait for another queue's),
/// and its parts leave no segment or sparse update for its submission (whose recordings go
/// among or after the parts' own), and name no texture over the caller's image that moves
/// between layouts (whose move back its submission plans before the end).
/// Whether batch `index`'s end may go into its last `VkCommandBuffer` (`submit.rs`): its
/// parts leave no segment or sparse update for its submission (whose recordings go among or
/// after the parts' own), nor its last part a write into an ASTC carrier (whose second twin's
/// decode its submission may record after it, `texture/decoded_twin.rs`), and name no texture
/// over the caller's image that moves between layouts (whose move back its submission plans
/// before the end). An event's kept signal that waits for another queue's still goes after
/// that wait, in an end of its own at the submission (`submit.rs`).
fn may_fold(&self, device: &Device, index: usize) -> bool {
let parts = &self.recorded[self.batch_range(index)];
parts
.iter()
.all(|part| part.segments.is_empty() && part.sparse.is_empty())
&& parts.last().is_none_or(|part| part.twin_writes.is_empty())
&& device
.shared()
@@ -1380,6 +1388,7 @@ impl CommandBuffer {
kernel: KernelTimes::default(),
status: AtomicU8::new(status_word(CommandBufferStatus::NotEnqueued)),
error: OnceLock::new(),
group_hold: AtomicU8::new(0),
}))
}
@@ -1482,11 +1491,15 @@ impl CommandBuffer {
Ok(())
}
/// Call `handler` once the command buffer's last batch reached its `VkQueue`, on the thread
/// that submitted it, before the command buffer becomes `Scheduled`: a runtime extension, no
/// Metal call (docs/API.md, "A command buffer's submission handlers"). Metal submits on its
/// own thread and tells a program of it only through `Scheduled` (EV SUB-sched1-m4); a
/// program that models what Metal does as it submits takes that point here.
/// Call `handler` once the runtime took the command buffer's last batch for its `VkQueue`,
/// on the thread that took it, before the command buffer becomes `Scheduled`: a runtime
/// extension, no Metal call (docs/API.md, "A command buffer's submission handlers"). The
/// batch is taken where it is submitted, or held for one kernel submission with the batches
/// committed after it (`CompletionPolicy::Grouped`, on a driver that merges submissions): its
/// commands and its place in its queue's order are fixed then, so nothing committed later on
/// the queue runs before it. Metal submits on its own thread and tells a program of it only
/// through `Scheduled`; a program that models what Metal does as it
/// submits takes that point here.
///
/// - **The thread.** The device's scheduler thread, which makes every submission: `commit`
/// returns at once, as Metal's does, and submits nothing itself. It runs with no lock of the
@@ -1495,10 +1508,11 @@ impl CommandBuffer {
/// before [`wait_until_scheduled`](Self::wait_until_scheduled) returns, before its
/// scheduled handlers run, and before it can complete. The GPU may run the work meanwhile:
/// a value of an event its work signals can rise before they ran.
/// - **Never** for a command buffer that fails before its last batch is submitted (a
/// submission or host step that fails, a lost device); they are dropped with it. A command
/// buffer committed as failed ([`commit_failed`](Self::commit_failed)) submits its batches
/// and runs them.
/// - **Never** for a command buffer that fails before its last batch is taken (a submission
/// or host step that fails, a lost device); they are dropped with it. One whose last batch
/// was held ran them, and fails from `Scheduled` where the group's submission fails. A
/// command buffer committed as failed ([`commit_failed`](Self::commit_failed)) submits its
/// batches and runs them.
/// - **Keep it short.** It holds back its command buffer's scheduling and the device's other
/// submissions, among them those of a commit made meanwhile, which the thread takes in only
/// after its handlers (`scheduler/inbox.rs`). A wait in it
@@ -2040,7 +2054,9 @@ impl CommandBuffer {
}
/// `kernelEndTime`: the host time at which the device's scheduler finished submitting the
/// command buffer's work to Vulkan (it is then `Scheduled`); 0 before.
/// command buffer's work to Vulkan, or held its last batch for one kernel submission with
/// later ones (`CompletionPolicy::Grouped`); it is then `Scheduled`; 0 before. Like Metal's,
/// the read waits for no submission in progress and no GPU work.
pub fn kernel_end_time(&self) -> f64 {
gpu_time::seconds(self.0.kernel.end())
}
@@ -2183,7 +2199,9 @@ impl CommandBuffer {
}
/// `waitUntilCompleted`: block until the command buffer completed or failed and its
/// completed handlers ran. It returns on device loss (the status is then `Error`).
/// completed handlers ran. It returns on device loss (the status is then `Error`). Where a
/// batch of it is held for one kernel submission with later ones while its queue's earlier
/// work runs (`CompletionPolicy::Grouped`), the wait sends it at once.
///
/// It returns only once the runtime's threads let go of the command buffer, and of what they
/// held to make what its work waited for (a pipeline made on the device's pool, a texture's
@@ -2226,6 +2244,7 @@ impl CommandBuffer {
Answer::Wait => None,
Answer::Block(from) => Some(contexts::block(from, self.0.context())?),
};
self.0.waits_for_completion();
self.0.gate.wait()?;
self.trailed(None)
.map_err(|_| DeadlockCause::Exiting.into())
@@ -2244,6 +2263,7 @@ impl CommandBuffer {
Some(contexts::block(from, self.0.context()).map_err(|_| TimedOut)?)
}
};
self.0.waits_for_completion();
self.0.gate.wait_until(deadline)?;
self.trailed(Some(deadline)).map_err(|_| TimedOut)
}
@@ -2561,7 +2581,7 @@ impl CommandBufferShared {
// lock; the slot's queries were reset by the batch's start, before it in submission
// order (`submit.rs`).
unsafe {
Barrier::to_host().record(device, raw);
crate::batch_order::end(self.device.shared().by_ends).record(device, raw);
if let Some((queries, first)) = stamp {
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
device.cmd_write_timestamp(raw, bottom, queries, first + 1);
@@ -2728,11 +2748,13 @@ impl CommandBufferShared {
true
}
/// Where the device writes timestamps into slots of three queries and `raw`, just begun, is
/// the first `VkCommandBuffer` of the command buffer's first encoder, which opens its first
/// batch: take the slot now, and write the start into its third query as `raw`'s first
/// commands, the reset of the end and of that query, then the timestamp at the top of the pipe
/// (`gpu_time.rs`). The first batch's submission decides which start is read (`submit.rs`).
/// Where the device writes timestamps into slots of three queries and `raw`, just begun, is the
/// first `VkCommandBuffer` of the command buffer's first encoder, which opens its first batch:
/// take the slot now, and write the start into its third query as `raw`'s first commands, the
/// reset of the end and of that query (where the device does not reset the slot on the host as
/// it takes it), then the timestamp at the top of the pipe (the bottom where batches are
/// ordered by their ends: `batch_order.rs`; `gpu_time.rs`). The first batch's submission
/// decides which start is read (`submit.rs`).
fn open_start(&self, state: &mut State, raw: vk::CommandBuffer) {
let timing = &self.device.shared().timing;
let first_batch = match state.batches.all() {
@@ -2764,6 +2786,8 @@ impl CommandBufferShared {
device.cmd_reset_query_pool(raw, queries, prefix - 1, 2);
exit_guard::called(Call::CmdResetQueryPool);
}
let stage = crate::batch_order::start_stage(self.device.shared().by_ends);
device.cmd_write_timestamp(raw, stage, queries, prefix);
exit_guard::called(Call::CmdWriteTimestamp);
}
state.prefix = Some(raw);
@@ -2873,8 +2897,8 @@ impl CommandBufferShared {
});
}
/// The scheduler submitted the last batch: in the queue's context, once the submitting
/// thread ran its submission handlers, become `Scheduled`, then run the scheduled handlers on
/// The scheduler submitted the last batch, or held it in a group (`group.rs`): in the queue's
/// context, once the submitting thread ran its submission handlers, become `Scheduled`, then run the scheduled handlers on
/// this thread, in the order added, then let `wait_until_scheduled` return. Metal's status
/// reads `Scheduled` just before its first scheduled handler starts, and its wait returns
/// once the last returned (EV SUB-sched1-m4: an M4, macOS 27.0.1).
@@ -2911,9 +2935,10 @@ impl CommandBufferShared {
self.changed.notify_all();
}
/// Its last batch was submitted on this thread, which holds no lock of the runtime's: run
/// its submission handlers here, in the order added, then let its transition to `Scheduled`
/// run ([`CommandBuffer::add_submission_handler`]).
/// Its last batch was submitted, or held in a group, on this thread, which holds no lock of
/// the runtime's: run its submission handlers here, in the order added, then let its
/// transition to `Scheduled` run ([`CommandBuffer::add_submission_handler`]).
pub(crate) fn run_submission_handlers(self: &Arc<Self>) {
let buffer = CommandBuffer(Arc::clone(self));
{
@@ -2935,7 +2960,9 @@ impl CommandBufferShared {
/// submitted value in `values`, and, where a command buffer ends at a fence
/// ([`fences::ends_at_fence`]), at one submitted after it, as a command buffer whose last
/// batch was submitted finishes; at the value alone when the queue takes no such fence (a
/// lost device). Its submission and scheduled handlers never run; they are dropped with it.
/// lost device). Its submission and scheduled handlers never run; they are dropped with it,
/// unless it became `Scheduled` as its last batch was held in a group (`group.rs`), which
/// then fails from `Scheduled`.
pub(crate) fn failed(self: &Arc<Self>, error: CommandBufferError, values: &[u64]) {
let vk_queue = self.queue.vk_queue();
lock(&self.state).failure = Some(error);
@@ -2984,10 +3011,8 @@ impl CommandBufferShared {
}
}
/// The command buffer's last batch is submitted: post its transition to `Scheduled` to its
/// queue's context: [`plain`](Transition::plain) where it has no scheduled handler (none is
/// added after the commit) and waits for no submission handler.
pub(crate) fn post_scheduled(self: &Arc<Self>) {
/// The command buffer's last batch is submitted, or held in a group (`group.rs`), on the
/// scheduler's thread under its lock: its transition to `Scheduled` runs here where it is [`plain`](Transition::plain) (it has no
let plain = {
let state = lock(&self.state);
state.scheduled.is_empty() && !state.submitting
@@ -24,12 +24,12 @@
//! close a cycle of such waits, or leave its device's pool with no thread that is not blocked
//! so (`contexts::block`).
//!
//! A submission handler (a runtime extension, Metal has none) runs on the thread that submitted its
//! command buffer's last batch, and that command buffer's transition to `Scheduled`, with every
//! later transition of its queue, waits for it. On the scheduler thread, the device's later
//! submissions wait for it too. So any wait there for what has not happened (a command buffer's
//! scheduling or completion, a slot of a full queue no uncommitted command buffer holds) is refused
//! at once (`DeadlockCause::SubmissionHandler`); one for what happened returns.
//! A submission handler (a runtime extension, Metal has none) runs on the thread that took its
//! command buffer's last batch for its queue, and that command buffer's transition to `Scheduled`,
//! with every later transition of its queue, waits for it. On the scheduler thread, the device's
//! later submissions wait for it too. So any wait there for what has not happened (a command
//! buffer's scheduling or completion, a slot of a full queue no uncommitted command buffer holds)
//! is refused at once (`DeadlockCause::SubmissionHandler`); one for what happened returns.
use crate::error::DeadlockCause;
use std::cell::Cell;
@@ -43,7 +43,7 @@ pub(crate) enum Step {
CompletedHandlers,
/// The release of what it retained (a no-copy buffer's deallocator may run here).
Release,
/// Its submission handlers, on the thread that submitted its last batch (the scheduler's,
/// Its submission handlers, on the thread that took its last batch (the scheduler's,
/// or a committing one, which may be a handler thread): its transition to `Scheduled`, and
/// so every later transition of its queue, waits for them.
SubmissionHandlers,
@@ -7,11 +7,23 @@
//! `VkCommandBuffer`s (an encoder's segments among its own), each encoder after the barrier the
//! tracker planned for it. What completed work wrote is made visible by a wait or a barrier,
//! see below.
//! 2. The end: the barrier that makes every write visible to the host ([`Barrier::to_host`]),
//! then the signals: the events' kept signal indices, the caller's binary semaphores and the
//! queue's timeline value. When an event's previous kept signal is pending on another
//! `VkQueue`, this part waits for it, so the event's semaphore is signaled in index order
//! without holding back the work.
//! 2. The end: the barrier that makes every write visible to the host ([`Barrier::to_host`]), or,
//! where batches are ordered by their ends (`batch_order.rs`), to the host and to every later
//! command of the `VkQueue` ([`Barrier::to_all`]; so a later batch there plans no barrier from
//! this one's accesses, `tracker.rs`), then the signals: the events' kept signal indices, the
//! caller's binary semaphores and the queue's timeline value. When an event's previous kept
//! signal is pending on another `VkQueue`, this part waits for it, so the event's semaphore is
//! signaled in index order without holding back the work.
//!
//! **Grouped** ([`Submitting::Grouped`], `group.rs`). Where the scheduler groups batches (under
//! `CompletionPolicy::Grouped`, on a driver that merges submissions), a batch that signals nothing
//! but its queue's timeline and its events, past its first work, without a fence or a wrapped
//! image to move, and waits for no event index a batch held signals, is not submitted: its two
//! `VkSubmitInfo`s are held, its signals left to the group's end, and it is tracked as submitted
//! (its events keep their signals' indices). One that may join but took first work or names a
//! wrapped image goes with the held group, in its call, last; one that may not, or finds the
//! group of another `VkQueue`, changes nothing ([`Submitting::AfterGroup`]): the scheduler
//! submits the group and offers the batch again.
//!
//! **What completed work wrote.** The tracker forgets a batch once the host saw its queue's
//! timeline pass it, and the device's own submissions outside the batches (`device/submit.rs`,
@@ -54,12 +66,13 @@
//! joins its batch, its batch ends at encode time, or the command buffer commits
//! (`CommandBufferShared::close_tail`). Where its batch ended there, the end goes into it before
//! it ends: the barrier to the host, then, in the last batch of a timed command buffer, the end
//! timestamp, as the end's own command buffer holds them. Only where the batch signals no event
//! (a kept signal may need the end after a wait for another `VkQueue`'s, above), leaves its
//! timestamp, as the end's own command buffer holds them. Only where the batch leaves its
//! submission no segment or sparse update (recorded at the submission, among or before the
//! work's command buffers), and names no texture over the caller's image that moves between
//! layouts (its move back is planned at the submission, before the end). The batch's submission
//! then has no end of its own, and the signals join the work's `VkSubmitInfo`: "The first
//! then has no end of its own, unless an event's kept signal waits for another `VkQueue`'s
//! (above): its end then holds the barrier to the host alone, between that wait and the signals,
//! the work's end timestamp written. Else the signals join the work's `VkSubmitInfo`: "The first
//! synchronization scope of each semaphore signal operation defined by this command includes
//! every command in the same batch that the signal operation is defined in, and all commands that
//! occur earlier in submission order" (`vkQueueSubmit`). Where that command buffer does not go
@@ -115,26 +128,27 @@
//! where its driver reads the command buffer's objects after its value
//! ([`fences`](super::fences)), at which the command buffer then finishes.
//!
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at
//! the top of the pipe, before every barrier and encoder of its first batch: by its first
//! encoder's first command buffer, which wrote it into its slot's third query as it opened, where
//! the batch plans nothing before that encoder (no barrier, no image moved, and no
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at the
//! top of the pipe, before every barrier and encoder of its first batch: by its first encoder's
//! first command buffer, which wrote it into its slot's third query as it opened, where the batch
//! plans nothing before that encoder (no barrier, no image moved, and no
//! [`Barrier::after_completed`] where the driver stalls on semaphore operations) and the command
//! buffer goes to the queue as recorded first (`WorkCounts::prefixed_starts`); else by the
//! batch's first command buffer, a command buffer of barriers, which resets the slot's first two
//! queries first. Where the batch plans a barrier before its first encoder for earlier work (the
//! encoder's own, or the one before the images it moves), the start is written after that
//! barrier instead, at the bottom of the pipe: once every command submitted before it on the
//! queue completed. Vulkan (`vkCmdWriteTimestamp`): its "first synchronization scope includes
//! all commands that occur earlier in submission order", and `VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT`
//! "is equivalent to `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT` with `VkAccessFlags` set to `0` when
//! specified in the first synchronization scope". So a command buffer whose first encoder depends
//! on work still running starts after that work ended, as Metal's does: on an M3 Max under macOS
//! 27.0.1, a fill committed behind a running fill of the same bytes started 0.5 to 0.9 us after
//! the first's `GPUEndTime` (10 of 10), and one of other bytes while the first ran (probe
//! `gpustart`). The end of its last batch writes the end timestamp at the bottom of the pipe,
//! after its barriers. The scheduler's host times as it begins the first batch and ends the last
//! submission are the kernel times.
//! buffer goes to the queue as recorded first (`WorkCounts::prefixed_starts`); else by the batch's
//! first command buffer, a command buffer of barriers, which resets the slot's first two queries
//! first. Where the batch plans a barrier before its first encoder for earlier work (the encoder's
//! own, or the one before the images it moves), the start is written after that barrier instead, at
//! the bottom of the pipe: once every command submitted before it on the queue completed. Vulkan
//! (`vkCmdWriteTimestamp`): its "first synchronization scope includes all commands that occur
//! earlier in submission order", and `VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT` "is equivalent to
//! `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT` with `VkAccessFlags` set to `0` when specified in the first
//! synchronization scope". So a command buffer whose first encoder depends on work still running
//! starts after that work ended, as Metal's does: on an M3 Max under macOS 27.0.1, a fill committed
//! behind a running fill of the same bytes started 0.5 to 0.9 us after the first's `GPUEndTime` (10
//! of 10), and one of other bytes while the first ran (probe `gpustart`). Where batches are ordered
//! by their ends (`batch_order.rs`), every start is written at the bottom of the pipe, as such a
//! driver starts no batch before the ones before it ended. The end of its last batch writes the end
//! timestamp at the bottom of the pipe, after its barriers. The scheduler's host times as it begins
//! the first batch and ends the last submission are the kernel times.
//!
//! The tracker keeps the plan, and the events their kept signals, only once the submission is
//! made; a batch that is not submitted changes neither.
@@ -146,10 +160,13 @@
//! registered destructors, so an exit the program makes once it learned of the submission runs
//! the hook before them.
//!
//! The submission of a command buffer's last batch leaves its submission handlers to the submitting
//! thread, once the scheduler's lock is free; its transition to `Scheduled` waits for them.
//! The submission of a command buffer's last batch, or its hold in a group (`group.rs`), leaves its
//! submission handlers to the submitting thread, once the scheduler's lock is free; its transition
//! to `Scheduled` waits for them.
use super::completion::Submitted;
use super::gate::Hold;
use super::group::{self, After, GroupEnd, InfoParts};
use super::kept_barriers::{KeptBarriers, SlotStamps};
use super::{lock, recording_error, submission_error, CommandBufferShared, State};
use crate::deferred::Deferred;
@@ -205,33 +222,114 @@ pub(crate) struct Submission {
queue: usize,
batch: Submitted,
/// It ends a command buffer with submission handlers, or with a switch of storage forms riding
/// on it, which the submitting thread runs or ends once the scheduler's lock is free
/// ([`Submission::runs_handlers`]).
/// on it, which the submitting thread still runs or ends once the scheduler's lock is free
/// ([`Submission::runs_handlers`]); false once a hold in a group gave them to the thread
/// ([`schedule_held`](Submission::schedule_held)).
handlers: bool,
/// It ends a command buffer with a switch of storage forms riding on it, which settles by its
/// submission's outcome ([`Submission::rides_forms`]).
forms: bool,
/// Its command buffer became `Scheduled` as it was held in a group
/// ([`schedule_held`](Submission::schedule_held)).
scheduled: bool,
}
/// What [`CommandBufferShared::submit_batch`] did with a batch.
#[must_use = "a batch submitted or held must be published, one held back must be put back"]
pub(crate) enum Submitting {
/// Submitted, alone or after the group held before it: for the scheduler to publish.
Submitted(Submission),
/// Held in the scheduler's group (`group.rs`), its submission's changes made: its command
/// buffer's transition to `Scheduled` as it is held, where it ends it
/// ([`Submission::schedule_held`]), the rest published once the group is submitted.
Grouped,
/// Nothing submitted or changed: its first submission waits for encoders of it a rebind
/// encodes again (`reencode.rs`).
Later,
/// Nothing submitted or changed: the group held goes first, sent by what this says.
AfterGroup(GroupEnd),
}
impl Submission {
/// The value its queue's timeline reaches once it completed.
pub(super) fn value(&self) -> u64 {
self.batch.value
}
/// Whether it ends its command buffer.
pub(super) fn ends(&self) -> bool {
self.batch.last
}
/// Its command buffer.
pub(super) fn buffer(&self) -> &Hold<CommandBufferShared> {
&self.batch.buffer
}
/// Each event's semaphore it signals, with the signal's index.
pub(super) fn event_signals(&self) -> impl Iterator<Item = (vk::Semaphore, u64)> + '_ {
(self.batch.signals.iter()).map(|(event, index)| (event.semaphore(), *index))
}
/// Whether the submitting thread runs its command buffer's submission handlers
/// ([`CommandBufferShared::run_submission_handlers`]) once it holds no lock, after it ended
/// the switch of storage forms riding on it: its transition to `Scheduled` waits for them.
pub(crate) fn runs_handlers(&self) -> bool {
self.handlers
}
/// Whether it ends a command buffer on which a switch of storage forms rides
/// (`texture/storage_form.rs`): the switch settles by its submission's outcome, so it is
/// `Scheduled` and its submission handlers run only once the group holding it was submitted.
pub(super) fn rides_forms(&self) -> bool {
self.forms
}
/// It was held in a group (`group.rs`), on the scheduler's thread under its lock, after the
/// section that held it ended: where it ends its command buffer and no switch of storage
/// forms rides on it, the command buffer's kernel end and its transition to `Scheduled` now,
/// which [`publish`](CommandBufferShared::publish) then leaves out, and its submission
/// handlers go to the scheduler's thread to run once its lock is free, before that
/// transition, as a submitted batch's do: whether they do (none is left for the group's
/// submission). Its tracker plan, its queue's value and its events' signal indices were
/// taken as it was held, so nothing committed later on its queue goes before it; only its
/// kernel submission and its queue waiter's watch wait for the group.
pub(super) fn schedule_held(&mut self) -> bool {
if !self.batch.last || self.forms || self.scheduled {
return false;
}
self.scheduled = true;
self.batch.buffer.kernel.end_at(gpu_time::host_nanos());
self.batch.buffer.schedule();
let handlers = self.handlers;
self.handlers = false;
handlers
}
/// Whether its command buffer became `Scheduled` as it was held.
pub(super) fn scheduled(&self) -> bool {
self.scheduled
}
}
impl CommandBufferShared {
/// Submit batch `index` of the command buffer (`last` when it ends it) after the Vulkan waits
/// `event_waits` for its events, against the scheduler's tracker and timeline values. The
/// batch is for the caller to [`publish`](Self::publish) once its section ended.
/// `Ok(None)`, nothing submitted or changed, while its first submission waits for encoders
/// of it a rebind encodes again (`reencode.rs`): the caller holds the batch back at its place.
/// batch is for the caller to [`publish`](Self::publish) once its section ended
/// ([`Submitting::Submitted`]), or waits in the scheduler's group for one kernel submission
/// with the batches after it, its submission's changes made ([`Submitting::Grouped`],
/// `group.rs`). Nothing submitted or changed while its first submission waits for encoders
/// of it a rebind encodes again (`reencode.rs`, [`Submitting::Later`]), or while the group
/// held must go first ([`Submitting::AfterGroup`]): the caller holds the batch back at its
/// place. Where the group went in this batch's submission, its outcome is the group's
/// (`Group::take_outcome`).
pub(crate) fn submit_batch(
self: &Arc<Self>,
index: usize,
last: bool,
event_waits: &[(vk::Semaphore, u64)],
scheduler: &mut scheduler::State,
) -> Result<Option<Submission>, CommandBufferError> {
) -> Result<Submitting, CommandBufferError> {
let device = &self.device;
if device.is_lost() {
return Err(CommandBufferError::DeviceLost);
@@ -240,6 +338,28 @@ impl CommandBufferShared {
let raw = shared.vk();
let queue = self.queue.vk_queue();
let mut state = lock(&self.state);
// Whether the batch may wait in the scheduler's group for one kernel submission with the
// batches after it (`group.rs`), as far as is known before anything changes; first work
// it takes still sends it now. One that may not, or of another `VkQueue`, waits,
// a wait for an event a batch held signals, which only that end meets, goes after it.
let met = (event_waits.iter()).any(|&wait| scheduler.group.meets(wait));
let joins = {
let sync = &state.batches.all()[index];
group::groups(device, queue)
&& !(last && super::fences::ends_at_fence(device, queue))
&& !met
&& sync.binary_waits.is_empty()
&& sync.binary_signals.is_empty()
&& (state.recorded[state.batch_range(index)].iter())
.all(|recorded| recorded.sparse.is_empty())
};
if !scheduler.group.admits(queue, joins) {
let end = match met {
true => GroupEnd::Wait,
false => GroupEnd::Apart,
};
return Ok(Submitting::AfterGroup(end));
}
// A host step that failed fails the command buffer here; else the batch's segments go in
// their places.
if let Some(error) = state.step_failure.take() {
@@ -252,7 +372,7 @@ impl CommandBufferShared {
.first_submission(device, self)
.map_err(|error| recording_error(device, error))?;
if !first {
return Ok(None);
return Ok(Submitting::Later);
}
}
// Each of Metal's submissions it found rebound, or holding a detached buffer, fails as
@@ -341,6 +461,10 @@ impl CommandBufferShared {
reached.push((value > 0).then_some((vk_queue.timeline, value)));
}
reached.extend(device.own_completed());
// The batches before it on its queue that the host has not seen complete: each took the
// next value (`WorkCounts::batches_with_none_pending` and kin).
let completed = shared.queues[queue].completed_value();
(shared.counts).batch_submitted_behind(scheduler.values[queue].saturating_sub(completed));
if index == 0 {
self.kernel.begin();
}
@@ -655,13 +779,12 @@ impl CommandBufferShared {
// where that command buffer goes to the queue as recorded: then the batch has no end of
// its own. One that does not go (its encoder runs nothing, or was encoded again) leaves
// the end to its own command buffer, as every other batch's.
let folded = match state.fold(index).filter(|(raw, _)| work.contains(raw)) {
let in_work = match state.fold(index).filter(|(raw, _)| work.contains(raw)) {
None => false,
Some((raw, stamped)) => {
let ends = work.last() == Some(&raw)
&& exit_barrier.is_none()
&& exits.is_empty()
&& order_semaphores.is_empty()
&& start_stamp.is_none()
&& stamped == (last && slot.is_some());
debug_assert!(ends, "a batch's end recorded where the batch does not end");
@@ -672,6 +795,10 @@ impl CommandBufferShared {
true
}
};
// An event's kept signal that waits for another `VkQueue`'s earlier one goes after that
// wait, in an end of its own (the module docs): the end the work holds made its writes
// visible and wrote its end timestamp, so that one records the barrier alone.
let folded = in_work && order_semaphores.is_empty();
// The end, where the batch has something to end. A batch with no work, no wait, no image
// to move back and no timestamp records none: none of its commands wrote anything, every
// batch before it on any `VkQueue` made its own writes visible to the host before its
@@ -680,7 +807,7 @@ impl CommandBufferShared {
let stamps = Stamps {
start: start_stamp.take(),
after: false,
end: slot.filter(|_| last),
end: slot.filter(|_| last && !in_work),
};
let ends = !single
|| !order_semaphores.is_empty()
@@ -692,7 +819,7 @@ impl CommandBufferShared {
true => {
let finale_barriers: Vec<Barrier> = exit_barrier
.into_iter()
.chain([Barrier::to_host()])
.chain([crate::batch_order::end(shared.by_ends)])
.collect();
let kept = &mut scheduler.kept;
vec![self.barrier_buffer(&mut state, kept, at, &finale_barriers, &exits, stamps)?]
@@ -778,42 +905,71 @@ impl CommandBufferShared {
if let Some(ticket) = state.heaps.submit(device) {
state.retained.push(Box::new(ticket));
}
// SAFETY: every command buffer is executable and submitted once; every wait is for a
// signal already submitted (the scheduler's order, and for a binary semaphore the
// caller's contract of `encode_wait_for_vk_semaphore`); every signal of a timeline is
// above its value and any earlier one (the queue's values rise, and an event's kept
// indices rise and wait for the previous one on another queue), and every binary one is
// of an unsignaled semaphore with no signal pending (`encode_signal_vk_semaphore`); every
// transition is of a live image of the caller's in the layout it is in (its contract,
// `new_texture_with_vk_image`); the fence is unsignaled and in no pending submission;
// the `VkQueue` is used under its lock.
let submitted = shared.submit_logged(
(queue, Some(at.value)),
fence,
&self.relayed,
|vk_queue| unsafe {
shared.counts.queue_submitted(buffers);
raw.queue_submit(vk_queue, &submits, fence.unwrap_or(vk::Fence::null()))
},
);
exit_guard::called(Call::QueueSubmit);
if let Err(error) = submitted {
if let Some(fence) = fence {
// SAFETY: the failed submission is not pending; inside the section. Released,
// not kept: Vulkan leaves a fence's state after a failed submission unsaid.
unsafe { release::object(raw, fence) };
// The batch waits in the group, its submission's changes made below, where it may and
// took no first work, the device wrapped no image of the caller's it names since it was
// found ready, and it waits for nothing but values seen complete where a group is held: a
// batch with a wait leads a group, never joins one, so the merge, which gathers every
// batch's waits before the first one's commands, never holds back an earlier batch for
// another's wait. Else it goes now, after the group where one is held.
let waits = wait_semaphores.len() - waited.len() + order_semaphores.len();
let leads = !scheduler.group.holds() || waits == 0;
let grouped = joins
&& leads
&& !first_work.has_first()
&& !first_work.has_staged()
&& images.is_empty();
if grouped {
scheduler.group.open(queue, &scheduler.waited[queue]);
} else {
// SAFETY: every command buffer is executable and submitted once; every wait is for a
// signal already submitted (the scheduler's order, and for a binary semaphore the
// caller's contract of `encode_wait_for_vk_semaphore`); every signal of a timeline is
// above its value and any earlier one (the queue's values rise, and an event's kept
// indices rise and wait for the previous one on another queue), and every binary one
// is of an unsignaled semaphore with no signal pending (`encode_signal_vk_semaphore`);
// every transition is of a live image of the caller's in the layout it is in (its
// contract, `new_texture_with_vk_image`); the fence is unsignaled and in no pending
// submission; the `VkQueue` is used under its lock (`Group::submit`).
if scheduler.group.holds() {
let end = match leads {
true => GroupEnd::FirstWork,
false => GroupEnd::Wait,
};
shared.counts.group_ended(end);
}
// A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or
// loses the device: the first work goes back, still to be done, as `first_work`
// drops. Where the device is lost, its command buffers, of this command buffer's pool
// that goes as the command buffer fails, go once the driver's own completion of what
// the call ran did (`Device::drain_queues`).
let error = submission_error(device, error);
if matches!(error, CommandBufferError::DeviceLost) {
device.drain_queues();
let after = After {
queue,
infos: &submits,
buffers,
value: at.value,
fence,
relayed: &self.relayed,
};
let submitted =
scheduler
.group
.submit(device, &mut scheduler.waited[queue], Some(after));
if let Err(error) = submitted {
if let Some(fence) = fence {
// SAFETY: the failed submission is not pending; inside the section.
// Released, not kept: Vulkan leaves a fence's state after a failed
// submission unsaid.
unsafe { release::object(raw, fence) };
}
// A `vkQueueSubmit` that fails leaves what its submissions reference as it was,
// or loses the device: the first work goes back, still to be done, as
// `first_work` drops. Where the device is lost, its command buffers, of this
// command buffer's pool that goes as the command buffer fails, go once the
// driver's own completion of what the call ran did (`Device::drain_queues`).
let error = submission_error(device, error);
if matches!(error, CommandBufferError::DeviceLost) {
device.drain_queues();
}
return Err(error);
}
return Err(error);
}
// A held batch's kernel end is its group's (`Group::submit`).
if last && !grouped {
self.kernel.end_at(gpu_time::host_nanos());
}
if !single {
@@ -834,8 +990,9 @@ impl CommandBufferShared {
}
// Its submission handlers run on this thread once the scheduler's lock is free, and a
// switch of storage forms riding on it ends there first (`scheduler/mod.rs`); its
// transition to `Scheduled`, posted as it is published, waits for them.
let handlers = last && (!state.submission.is_empty() || state.storage_form.is_some());
// transition to `Scheduled`, posted as it is published or held, waits for them.
let forms = last && state.storage_form.is_some();
let handlers = last && (!state.submission.is_empty() || forms);
state.submitting = handlers;
scheduler.tracker.apply(plan);
held_moves.submitted();
@@ -865,7 +1022,7 @@ impl CommandBufferShared {
device.degrade_encoded_use_rebound();
}
device.reach_stale_detached(reaches);
Ok(Some(Submission {
let submission = Submission {
queue,
batch: Submitted {
value: at.value,
@@ -878,18 +1035,43 @@ impl CommandBufferShared {
.collect(),
},
handlers,
}))
forms,
scheduled: false,
};
if !grouped {
return Ok(Submitting::Submitted(submission));
}
let first = InfoParts {
waits: (wait_semaphores, wait_values, wait_stages),
buffers: &work,
signals: (work_signals, work_signal_values),
};
let second = InfoParts {
waits: (&order_semaphores, &order_values, &order_stages),
buffers: &finale,
signals: (&signal_semaphores, &signal_values),
};
let parts = [first, second];
let parts = match (single, folded) {
(true, _) => &parts[1..],
(false, true) => &parts[..1],
(false, false) => &parts[..],
};
scheduler.group.hold(parts, buffers, submission);
Ok(Submitting::Grouped)
}
/// Publish a batch [`submit_batch`](Self::submit_batch) submitted, after the section that
/// submitted it ended: when it ends the command buffer, its transition to `Scheduled`, then
/// its queue waiter's watch for it. From the watch on, the command buffer may complete
/// and run its release on its queue's handler thread before the caller lets go of anything
/// it took, so the caller holds nothing of what its commands or encoders took
/// (`scheduler::Spent`).
/// (`CommandBufferShared::schedule`) unless it made it as it was held in a group
/// ([`Submission::schedule_held`]), then its queue waiter's watch for it. From the watch
pub(crate) fn publish(self: &Arc<Self>, submission: Submission) {
let Submission { queue, batch, .. } = submission;
if batch.last {
let Submission {
queue,
batch,
scheduled,
..
} = submission;
if batch.last && !scheduled {
// Before a completion turn can see it finish, so the queue's context runs its
// transition to `Scheduled` first.
self.post_scheduled();
@@ -1100,8 +1282,8 @@ impl CommandBufferShared {
exit_guard::called(Call::CmdResetQueryPool);
}
if !stamps.after {
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
raw.cmd_write_timestamp(buffer, top, queries, first);
let stage = crate::batch_order::start_stage(device.shared().by_ends);
raw.cmd_write_timestamp(buffer, stage, queries, first);
exit_guard::called(Call::CmdWriteTimestamp);
}
}
@@ -4,14 +4,11 @@
//! - **What a context runs.** In its queue's order, each command buffer's transitions: to
//! `Scheduled` with its scheduled handlers, and to `Completed` (or `Error`) with its completed
//! handlers and the release of what it retained. The scheduler posts them ([`Contexts::post`]),
//! and so does a completion turn, but for a transition that runs none of the program's code,
//! which the turn runs itself where the context runs on no thread and holds only such
//! transitions, in order after them ([`Contexts::run_here`], `command_buffer/completion.rs`);
//! neither runs a handler. (A transition to `Scheduled` waits for its command buffer's
//! submission handlers, which the thread that submitted its last batch runs.) A release the
//! scheduler's thread hands off (`Device::let_go_elsewhere`) runs in a context of its own,
//! behind no queue's handlers.
//! - **Metal's order** (measured on an M4, macOS 27.0.1, EV `RT4-metal-order`): while one of a
//! and so does a completion turn, but for a transition that runs none of the program's code: the
//! turn runs such a transition to `Completed` itself where the context runs on no thread and
//! for its command buffer's submission handlers, which the thread that took its last batch for
//! its queue runs.) A release the scheduler's thread hands off (`Device::let_go_elsewhere`) runs
//! in a context of its own, behind no queue's handlers.
//! queue's handlers blocks, the queue's later transitions wait, even of a command buffer whose
//! work already ran; another queue's transitions and handlers go on, on another thread. Metal
//! ran 256 queues' handlers blocked at once, on 256 threads, and reached no limit.
@@ -1656,6 +1656,25 @@ degradations! {
"the deallocator runs once every command buffer that may still reach the pages \
(through a texture over them, or a table of the live buffers it holds) lets go of \
them, where Metal's runs at the release; the pages stay mapped until then";
/// Batches of command buffers committed on one queue that the scheduler found ready
/// together, or held while two or more earlier submissions of their queue ran, went to the
/// driver in one `vkQueueSubmit`, only the last signalling its queue's timeline and their
/// events (`CompletionPolicy::Grouped`, the default, on a driver whose queue
/// merges a submission that signals nothing into the next one: Mesa's drivers;
/// `command_buffer/group.rs`): one kernel submission for up to four batches. Announced
/// once per device, on the scheduler's thread, as the first such submission is made,
/// whatever `DeviceOptions::announce_each` says: no program call or host step meets it.
GroupedCompletion = "grouped-completion", Precision,
"each command buffer of the submission but the last is seen complete (its status, \
completed handlers and waits), and the event values it signals are reached, once \
the last completed, late by the GPU time of the batches after it, at most three, \
never early and in commit order, and a submission held while earlier ones of its \
queue ran late besides by any gap between the last of those and its own start on \
the GPU, at most a completion turn's reaction and its vkQueueSubmit; and the \
submission checks of the batches behind \
a queue's next one run with its own, before the batch before them is submitted; \
their commands, barriers and GPU times are unchanged; CompletionPolicy::Exact \
submits and checks each batch alone";
/// In a build without debug assertions, a notice announced where the runtime's rule
/// announces none ([`DegradeNotice::misplaced`] names its kind and [`NoticePlace`]):
/// inside a pipeline pool's piece, or, for a kind announced at every occurrence, outside
+31 -3
View File
@@ -241,6 +241,10 @@ pub(super) struct DeviceShared {
/// submissions stall on semaphore operations (`DriverFact::SemaphoreOperationsStallSubmits`,
/// `command_buffer/submit.rs`).
pub(super) completed_by_barrier: bool,
/// Each batch ends with `Barrier::to_all`, so a later batch of its `VkQueue` plans no barrier
/// for its accesses, and a batch's start timestamp is written at the bottom of the pipe
/// (`batch_order.rs`).
pub(crate) by_ends: bool,
/// The last sparse binding of a no-copy buffer's dma-bufs (`dma_buf.rs`) the host has not
/// seen complete: the internal timeline and the value it signals, which every later
/// submission that may use the buffer waits for (`submit.rs`).
@@ -672,6 +676,10 @@ pub(super) struct QueueSlot {
/// The value of the last batch submitted here: what the exit hook waits for on a device
/// whose queues run in this process ([`exit_guard::InProcess`]).
submitted: AtomicU64,
/// The value of the submission before the last that signalled the timeline here: while it is
/// not seen complete, two or more submissions here are in flight
/// ([`pending_beyond_one`](Self::pending_beyond_one)).
submitted_before: AtomicU64,
}
impl QueueSlot {
@@ -694,9 +702,23 @@ impl QueueSlot {
}
/// A batch signalling `value` was submitted here, inside its section of the exit guard: the
/// hook, which waits for that section, sees it.
/// hook, which waits for that section, sees it. Submissions here are made under the queue's
/// lock, so the last two values move together.
pub(super) fn submitted(&self, value: u64) {
self.submitted.fetch_max(value, Ordering::AcqRel);
let before = self.submitted.fetch_max(value, Ordering::AcqRel);
if before < value {
self.submitted_before.store(before, Ordering::Release);
}
}
/// Where two or more submissions that signalled the timeline here are not seen complete, the
/// value of the one before the last, whose completion leaves one in flight: each submission
/// signals a higher value, and the timeline completes them in order
/// (`command_buffer/group.rs`). Read without the queue's lock, so a submission made meanwhile
/// is seen or not.
pub(super) fn pending_beyond_one(&self) -> Option<u64> {
let before = self.submitted_before.load(Ordering::Acquire);
(self.completed_value() < before).then_some(before)
}
/// The value of the last batch submitted here; 0 before the first.
@@ -998,9 +1020,13 @@ impl Device {
}
}
}
// Each batch ends with a barrier that orders all its commands before every later one of
// its queue, where the driver runs a queue's submissions one after another anyway
// (`batch_order.rs`).
let by_ends = crate::batch_order::by_ends(compile.policy(), description.driver_id);
let threads = Contexts::start(THREADS).and_then(|contexts| {
match Completion::start(queue_places.len()) {
Ok(completion) => match Scheduler::start(queue_places.len()) {
Ok(completion) => match Scheduler::start(queue_places.len(), by_ends) {
Ok(scheduler) => Ok((contexts, completion, scheduler)),
Err(error) => {
completion.stop();
@@ -1050,6 +1076,7 @@ impl Device {
timeline,
completed: AtomicU64::new(0),
submitted: AtomicU64::new(0),
submitted_before: AtomicU64::new(0),
}
})
.collect();
@@ -1435,6 +1462,7 @@ impl Device {
internal_done: OwnTimeline::default(),
staging_done: OwnTimeline::default(),
completed_by_barrier,
by_ends,
bound_at: Mutex::new(None),
staging,
scheduler,
+3 -1
View File
@@ -20,7 +20,9 @@
//! plans no barrier before that encoder and its command buffer reaches the queue as recorded,
//! the batch begins with no command buffer of its own, and the prefix's start is the command
//! buffer's. It is the same place: either start is written at the top of the pipe, after every
//! command submitted before the batch's work and before any of it. Elsewhere (a barrier planned
//! command submitted before the batch's work and before any of it; where batches are ordered by
//! their ends (`batch_order.rs`), at the bottom, once every command submitted before it
//! completed, when such a driver starts the batch. Elsewhere (a barrier planned
//! there, a caller's image moved first, the encoder run again or not at all) a command buffer of
//! barriers writes the first start before the barrier, as without a prefix, and that start is
//! read; the prefix's is written after it and never read. A Metal counter sample buffer's slot
@@ -10,8 +10,8 @@
//! names after an image barrier whose destination stage is `ALL_COMMANDS` ("all read accesses ...
//! valid where it is used"), and [`ImageDst::Every`] names exactly that. The host reaches no
//! image's memory: it moves texels by copies, and a heap buffer's bytes reach the host through
//! the global barrier that ends every batch (`tracker::Barrier::to_host`) or an internal
//! submission (`texture::transfer_barrier`), which no image barrier stands for.
//! the global barrier that ends every batch (`tracker::Barrier::to_host` or `to_all`) or an
//! internal submission (`texture::transfer_barrier`), which no image barrier stands for.
//! - **The recording family's reads.** `ALL_COMMANDS` stands for the stages the recording queue
//! family supports, and an access mask may name only accesses those stages make
//! (VUID-vkCmdPipelineBarrier-pImageMemoryBarriers-02820). So [`ImageDst::Every`] is the reads
+1
View File
@@ -34,6 +34,7 @@ mod astc;
mod attachment_stand_in;
mod attachmentless;
mod attributes;
mod batch_order;
mod binary_archive;
mod binding;
mod binding_view;
+276 -59
View File
@@ -29,14 +29,13 @@
//! at creation); each `VkQueue` signals its own timeline semaphore with every batch, which is
//! the [`Point`] the tracker and the completion turns know the batch by.
//! - **Scheduled.** A command buffer is scheduled once its last batch is submitted (its every
//! wait was satisfied): this thread posts its transition to `Scheduled` to its queue's context ([`contexts`](super::contexts)), which
//! runs its scheduled handlers. No submission runs a scheduled handler, so none holds back a
//! submission.
//! wait was satisfied), or held in a group (below): this thread posts its transition to
//! `Scheduled` to its queue's context
//! - **Submission handlers** (a runtime extension). This thread runs a command buffer's
//! submission handlers once it submitted its last batch, in submission order among the command
//! buffers its passes submitted, once it let go of the lock and before it lets go of the command
//! buffers, before its next pass, which they hold back. The command buffer's transition to
//! `Scheduled` waits for them.
//! submission handlers once it submitted its last batch, or held it in a group (below), in
//! submission order among the command buffers its passes took so, once it let go of the lock
//! and before it lets go of the command buffers, before its next pass, which they hold back.
//! The command buffer's transition to `Scheduled` waits for them.
//! - **Host steps**. A batch that executes commands the GPU may write
//! (`CommandBufferShared::needs_host_step`) is held, once otherwise ready, until every
//! `VkQueue` completed what was submitted to it by then (its gate, a snapshot of the queues'
@@ -52,8 +51,25 @@
//! submitted GPU signal reaches is held for until that signal landed, as Metal submits (and
//! checks) only then. A completion turn sees each finished batch's event signals before it
//! wakes the thread, as for a gate. A command buffer without a check costs one flag per batch.
//! - **Grouped submissions** (`command_buffer/group.rs`). Under `CompletionPolicy::Grouped`, on a
//! driver whose queue merges a submission that signals nothing into the next (Mesa's), a pass
//! holds up to four ready batches of one `VkQueue` that signal nothing but its timeline, after
//! their first work, and submits them in one `vkQueueSubmit` whose last batch alone signals: one
//! kernel submission where there were four. Each held batch is tracked and its queue's value
//! applied as it is held, and its command buffer scheduled where it ends it, its submission
//! handlers run first (a switch of storage forms riding on it waits for the group); the group
//! goes once it holds four, with or before a batch that cannot join, or when the pass runs out of
//! ready batches, unless two or more earlier submissions of its `VkQueue` are not seen complete
//! and no head waits for the GPU: then it stays held until one is left (a completion turn wakes
//! the thread for it), it fills, a later batch sends it, or a thread waits for one of its command
//! buffers (`Group::keeps`). The submission checks of up to three batches right behind a line's
//! head that goes run with the head's ([`check_heads`]), so a line of checked batches is found
//! ready together.
//! - **Waits are bounded.** The thread wakes on a commit or a host signal, and at least every
//! [`WAIT_SLICE`], so a stop is seen promptly.
//! head at its gate, its checks waiting for a GPU signal to land, or a group kept, leaves what
//! it waits for: each `VkQueue`'s value to complete, each event value to be reached. A
//! completion turn wakes
//! - **Exit.** Each submission is a section of the exit guard ([`exit_guard`]); once the process
//! is exiting, the thread ends, and what it holds stays held.
//! - **Let go without the lock.** A submitted batch's hold of its command buffer goes after the
@@ -76,8 +92,9 @@ use super::command_buffer::gate::Hold;
use super::command_buffer::kept_barriers::KeptBarriers;
use super::command_buffer::BatchLists;
use super::command_buffer::CommandBufferShared;
use super::command_buffer::{Group, GroupEnd, Submitting, GROUP_BATCHES};
use super::device::lock;
use super::error::{Error, MemoryKind};
use super::error::{CommandBufferError, Error, MemoryKind};
use super::event::EventShared;
use super::event_timeline::WaitFor;
use super::exit_guard;
@@ -98,6 +115,15 @@ use std::time::Duration;
/// How long the thread sleeps at most without looking for work.
const WAIT_SLICE: Duration = Duration::from_millis(100);
/// The group held waits for `VkQueue` `queue`, of `queues`, to complete `value`
/// (`Group::keeps`): a gate of no other queue's value.
fn gate_on(&self, queue: usize, value: u64, queues: usize) {
let mut list = lock(&self.list);
list.queues = queues;
(list.gates).extend((0..queues).map(|at| if at == queue { value } else { 0 }));
self.any.store(true, Ordering::SeqCst);
}
/// One device's scheduler thread.
pub(crate) struct Scheduler {
shared: Arc<SchedulerShared>,
@@ -145,6 +171,13 @@ pub(crate) struct State {
/// The lists each batch's submission fills and empties, with their room
/// (`command_buffer/submit.rs`).
pub(crate) lists: BatchLists,
/// The batches held for one kernel submission on one `VkQueue` (`command_buffer/group.rs`),
/// submitted before the pass ends, or kept past it while that queue runs earlier work
/// (`Group::keeps`).
pub(crate) group: Group,
/// Those batches as the order held them, with their logical queues, in order.
grouped: Vec<(u64, Held)>,
}
}
/// A commit not yet taken into the order: the command buffer, its logical queue, its batches.
@@ -199,13 +232,17 @@ pub(crate) struct BatchSync {
}
impl Scheduler {
/// Start the thread of a device with `queues` `VkQueue`s; refused when the host cannot start
/// Start the thread of a device with `queues` `VkQueue`s, whose batches each end with
/// `Barrier::to_all` where `by_ends` (`batch_order.rs`); refused when the host cannot start
/// one.
pub(crate) fn start(queues: usize) -> Result<Scheduler, Error> {
pub(crate) fn start(queues: usize, by_ends: bool) -> Result<Scheduler, Error> {
let shared = Arc::new(SchedulerShared {
inbox: Inbox::new(State {
order: Order::default(),
tracker: Tracker::default(),
tracker: match by_ends {
true => Tracker::by_ends(),
false => Tracker::default(),
},
values: vec![0; queues],
waited: vec![vec![0; queues + 2]; queues],
binary: BinarySignals::default(),
@@ -215,6 +252,8 @@ impl Scheduler {
untracked_decodes: 0,
kept: KeptBarriers::default(),
lists: BatchLists::default(),
group: Group::default(),
grouped: Vec::new(),
}),
wake: Condvar::new(),
gated: AtomicBool::new(false),
@@ -270,10 +309,12 @@ impl Scheduler {
}
/// Whether every batch committed so far was submitted: none is held for an event, a binary
/// semaphore, a host step or a check, or waits in the inbox (`texture/storage_form.rs`).
/// semaphore, a host step, a check or a group, or waits in the inbox
/// (`texture/storage_form.rs`).
pub(crate) fn holds_none(&self) -> bool {
let inbox = &self.shared.inbox;
lock(inbox.state()).order.is_empty() && !inbox.holds_commits()
let state = lock(inbox.state());
state.order.is_empty() && state.grouped.is_empty() && !inbox.holds_commits()
}
/// A CPU decode into the decoded twin of the resource `key` was queued: every batch whose
@@ -517,19 +558,22 @@ fn pass(
/// it.
type Spent = Vec<Hold<CommandBufferShared>>;
/// Submit every batch that is ready, in order, until none is; each submission is a section of
/// the exit guard. A batch is published (or its failure posted) only after its section ended, so
/// the exit hook's registration at the section's end comes before anything the program can
/// learn of it (`exit_guard`). A batch's events are let go of before its command buffer
/// (`gate`), whose holds go to `spent`, for the caller to drop without the lock. A batch whose
/// host step may run now goes to `left` as a step (once), for the caller to record without the
/// lock; `gated` says whether one still waits at its gate. A batch whose submission checks may run
/// now goes to `left` as a check (once), for the caller to run without the lock. A command buffer whose
/// last batch was submitted, or that failed, and on which a fetched target's storage form rides
/// (`texture/storage_form.rs`) is settled and goes to `settled`, for the caller to announce
/// without the lock ([`settle`]). A command buffer whose last batch was submitted with
/// submission handlers goes to `handlers`, in submission order, for the caller to run them
/// without the lock ([`run_submission_handlers`]). `Err` once the process is exiting.
/// Submit every batch that is ready, in order, until none is; each submission is a section of the
/// exit guard. A batch is published (or its failure posted) only after its section ended, so the
/// exit hook's registration at the section's end comes before anything the program can learn of it
/// (`exit_guard`). A batch's events are let go of before its command buffer (`gate`), whose holds
/// go to `spent`, for the caller to drop without the lock. A batch whose host step may run now goes
/// to `left` as a step (once), for the caller to record without the lock; `awaits` holds what the
/// heads still waiting at their gates wait for. A batch whose submission checks may run now goes to
/// `left` as a check (once), for the caller to run without the lock; `awaits` holds the GPU signals
/// those still waiting to land wait for. A command buffer whose last batch was submitted, or that
/// failed, and on which a fetched target's storage form rides (`texture/storage_form.rs`) is
/// settled and goes to `settled`, for the caller to announce without the lock ([`settle`]). A
/// command buffer whose last batch was submitted, or held in a group (`command_buffer/group.rs`),
/// with submission handlers goes to `handlers`, in that order, for the caller to run them without
/// the lock ([`run_submission_handlers`]). Once it let go of [`PASS_SUBMISSIONS`] batches' holds,
/// it stops where no batch is held for a group, answering `More(true)`, for the caller to let go of
/// them and pass again. `Err` once the process is exiting.
fn submit_ready(
state: &mut State,
(spent, settled): (&mut Spent, &mut Settled),
@@ -585,22 +629,76 @@ fn submit_ready(
event_waits(held)
});
let Some((queue, sequence, held, waits)) = next else {
// The batches held go before the pass ends, unless they stay held while their
// `VkQueue` runs two or more earlier submissions and no head waits for the GPU
// (`Group::keeps`): a completion turn wakes the thread once one is left, a commit or
// a waiter for one of their command buffers sooner. Their submission makes no batch
// ready: none of them signals a binary semaphore, and their events' signals counted
// as submitted as they were held.
drop(busy);
if !waiting && !landing {
if let Some(value) = state.group.keeps() {
awaits.gate_on(state.group.queue(), value, state.values.len());
return Ok(More(false));
}
}
let end = match (state.order.is_empty(), left.is_empty()) {
(true, _) => GroupEnd::Drained,
(false, false) => GroupEnd::Checks,
(false, true) => GroupEnd::Held,
};
submit_group(state, (spent, settled), handlers, end)?;
if !waiting && !landing {
gated.store(false, Ordering::SeqCst);
}
return Ok(());
};
let submitted = held
.buffer
.submit_batch(held.index, held.last, &waits, state)
.transpose();
// A rebind marked it since it was found ready: back at its place, which it keeps, until
// the rebind encoded its encoders again (`command_buffer/reencode.rs`), which wakes the
// thread.
let Some(submitted) = submitted else {
drop(busy);
state.order.put_back(queue, sequence, held);
continue;
.submit_batch(held.index, held.last, &waits, state);
// Its waits for values found reached go: it waits for none of them.
if matches!(
submitted,
Ok(Submitting::Submitted(_) | Submitting::Grouped)
) {
let met = held.waits.len() - waits.len();
if met > 0 {
held.buffer.device().shared().counts.event_waits_met(met);
}
}
let submitted = match submitted {
Ok(Submitting::Submitted(submission)) => Ok(submission),
Err(error) => Err(error),
// A rebind marked it since it was found ready: back at its place, which it keeps,
// until the rebind encoded its encoders again (`command_buffer/reencode.rs`), which
// wakes the thread.
Ok(Submitting::Later) => {
drop(busy);
state.order.put_back(queue, sequence, held);
continue;
}
// The batches held go first: back at its place, then looked for again.
Ok(Submitting::AfterGroup(end)) => {
drop(busy);
state.order.put_back(queue, sequence, held);
submit_group(state, (spent, settled), handlers, end)?;
continue;
}
// Held for one kernel submission with the batches after it: published once that is
// made (`command_buffer/group.rs`), at once where the group is full.
Ok(Submitting::Grouped) => {
drop(busy);
// Scheduled as it is held, out of the section, its submission handlers run first
// (`group.rs`).
if state.group.schedule_held() {
handlers.push(held.buffer.hold());
}
held.buffer.held_in_group();
state.grouped.push((queue, held));
if state.group.full() {
submit_group(state, (spent, settled), handlers, GroupEnd::Full)?;
}
continue;
}
};
let Held {
buffer,
@@ -612,6 +710,11 @@ fn submit_ready(
} = held;
drop(events);
drop(busy);
// Where batches were held, they went first, in this batch's `vkQueueSubmit` (first work it
// took sent it at once).
if let Some(outcome) = state.group.take_outcome() {
settle_group(state, outcome, (spent, settled), handlers);
}
match submitted {
Ok(submission) => {
state.binary.submitted(&binary_needs, &binary_signals);
@@ -647,6 +750,104 @@ fn submit_ready(
/// The process is exiting ([`exit_guard`]): the thread submits no more.
struct Exiting;
/// Submit the batches held for one kernel submission (`command_buffer/group.rs`), sent by `end`
/// (counted), a section of the exit guard, then publish them, or fail their command buffers
/// ([`settle_group`]). `Err` once the process is exiting: they stay held.
fn submit_group(
state: &mut State,
(spent, settled): (&mut Spent, &mut Settled),
handlers: &mut Handlers,
end: GroupEnd,
) -> Result<(), Exiting> {
let Some(device) = (state.grouped.first()).map(|(_, held)| held.buffer.device().clone()) else {
return Ok(());
};
let busy = exit_guard::enter().ok_or(Exiting)?;
device.shared().counts.group_ended(end);
let queue = state.group.queue();
let State { group, waited, .. } = &mut *state;
// The call's own result is a batch's submitted after the group, of which there is none.
let _ = group.submit(&device, &mut waited[queue], None);
drop(busy);
if let Some(outcome) = state.group.take_outcome() {
settle_group(state, outcome, (spent, settled), handlers);
}
Ok(())
}
/// Publish the batches held for a kernel submission that was made, in order, as [`submit_ready`]
/// publishes one; or, where it failed, fail each one's command buffer, once, and drop the rest of
/// its batches, as a batch whose submission failed. Their holds go to `spent`.
fn settle_group(
state: &mut State,
outcome: Result<(), CommandBufferError>,
(spent, settled): (&mut Spent, &mut Settled),
handlers: &mut Handlers,
) {
let State {
order,
binary,
values,
grouped,
group,
..
} = state;
match outcome {
Ok(()) => {
for ((_, held), submission) in grouped.drain(..).zip(group.made()) {
let Held {
buffer,
last,
waits: events,
binary_needs,
binary_signals,
..
} = held;
drop(events);
binary.submitted(&binary_needs, &binary_signals);
if submission.runs_handlers() {
handlers.push(buffer.hold());
}
buffer.left_group();
buffer.publish(submission);
if last && buffer.settle_storage_forms() {
settled.push(buffer.hold());
}
spent.push(buffer);
}
}
Err(error) => {
let mut failed: Vec<Hold<CommandBufferShared>> = Vec::new();
for (queue, held) in grouped.drain(..) {
let Held {
buffer,
waits: events,
binary_needs,
..
} = held;
drop(events);
binary.dropped(&binary_needs);
buffer.left_group();
if !failed.iter().any(|done| done.same(&buffer)) {
// The rest of the command buffer never runs (dropped here, before it can
// finish).
let rest = order.drop_head(queue, |next| next.buffer.same(&buffer));
for held in &rest {
binary.dropped(&held.binary_needs);
}
spent.extend(rest.into_iter().map(|held| held.buffer));
buffer.failed(error, values);
if buffer.settle_storage_forms() {
settled.push(buffer.hold());
}
failed.push(buffer.hold());
}
spent.push(buffer);
}
}
}
}
/// Whether `held` may read a texture of `decodes`: its footprint names one, or it has none it can
/// know before its submission (sparse work, a segment whose uses its host step finds).
fn reads_decoding(held: &Held, decodes: &BTreeMap<ResourceKey, usize>) -> bool {
@@ -676,8 +877,8 @@ fn settle(settled: &mut Settled) {
/// The command buffers whose storage forms the scheduler settled, to end without its lock.
type Settled = Vec<Hold<CommandBufferShared>>;
/// The command buffers whose last batch a pass submitted with submission handlers, in
/// submission order, for the submitting thread to run without the lock.
/// The command buffers whose last batch a pass submitted or held in a group with submission
/// handlers, in that order, for the submitting thread to run without the lock.
type Handlers = Vec<Hold<CommandBufferShared>>;
/// Run the submission handlers of `handlers`' command buffers on this thread, which holds none of
@@ -698,42 +899,58 @@ type Work = (Hold<CommandBufferShared>, usize);
/// ready (its binary semaphores' signals submitted, its events' values reached, its host step
/// recorded, not `behind` an earlier commit) and waits for its checks: once every value it waits
/// for was reached on the device or by the host, not only by a submitted GPU signal (or the device
/// is lost), it goes to `left` as a check, unless there already. `gated` is set before the events
/// are read again, as [`Scheduler::completions`] says. Whether a head still waits for a GPU signal
/// to land.
fn check_heads(
state: &mut State,
behind: &[u64],
left: &mut Left<Work>,
gated: &AtomicBool,
) -> bool {
///
/// Where the line's batches may go in one kernel submission (`command_buffer/group.rs`), the
/// batches right behind a head that goes (its checks in `left` or none due, otherwise ready, its
/// events' values reached on the device or by the host) are looked at too, at most
/// [`GROUP_BATCHES`] less one and none committed after another line's batch
/// ([`Order::leading_mut`]), each that goes taking its checks to `left` likewise: so the next pass
/// finds them ready together. Each check still runs in commit order before its own batch's
/// submission, within the pass before it, where a head's alone runs after the batch before it
/// was submitted.
let State { order, binary, .. } = state;
let mut landing = false;
for held in order.heads_mut(behind) {
if !held.checked
|| !binary.ready(&held.binary_needs)
|| (held.segments && held.buffer.needs_host_step(held.index))
|| !held.buffer.needs_check(held.index)
|| left.holds(Kind::Check, |(buffer, index)| {
order.leading_mut(behind, GROUP_BATCHES - 1, |held, head| {
let otherwise_ready = binary.ready(&held.binary_needs)
&& !(held.segments && held.buffer.needs_host_step(held.index));
let due = held.checked
&& held.buffer.needs_check(held.index)
&& !left.holds(Kind::Check, |(buffer, index)| {
buffer.same(&held.buffer) && *index == held.index
})
{
continue;
});
// Whether it goes as far as its checks know: the batches after it may be checked now.
let goes = |held: &Held| {
otherwise_ready
&& held.buffer.groups()
&& event_waits(held).is_some_and(|waits| waits.is_empty())
};
if !head {
if !goes(held) {
return false;
}
if due {
left.push(Kind::Check, (held.buffer.hold(), held.index));
}
return true;
}
if !held.checked || !otherwise_ready || !due {
return !due && goes(held);
}
match event_waits(held) {
None => continue,
None => return false,
Some(waits) if !waits.is_empty() && !held.buffer.device().is_lost() => {
gated.store(true, Ordering::SeqCst);
fence(Ordering::SeqCst);
if event_waits(held).is_some_and(|waits| !waits.is_empty()) {
landing = true;
continue;
return false;
}
}
Some(_) => {}
}
left.push(Kind::Check, (held.buffer.hold(), held.index));
}
goes(held)
});
landing
}
@@ -256,6 +256,43 @@ impl<B> Order<B> {
})
}
/// Each line's head not `behind`, then the batches after it, at most `count` of them, up to
/// the first committed after a batch another line holds, to update in place: `visit` takes
/// each, told whether it is the head, and answers whether to go on along its line. No batch
/// it reaches waits behind another line's ([`is_behind`](Self::is_behind)): every batch
/// committed before it is its line's.
pub(crate) fn leading_mut(
&mut self,
behind: &[u64],
count: usize,
mut visit: impl FnMut(&mut B, bool) -> bool,
) {
let firsts: Vec<u64> = (self.lines.iter())
.map(|(_, line)| line.front().map_or(u64::MAX, |(sequence, _)| *sequence))
.collect();
for (at, (_, line)) in self.lines.iter_mut().enumerate() {
if line
.front()
.is_none_or(|(sequence, _)| behind.contains(sequence))
{
continue;
}
let before = (firsts.iter().enumerate())
.filter(|&(other, _)| other != at)
.map(|(_, &first)| first)
.min()
.unwrap_or(u64::MAX);
for (position, (sequence, batch)) in line.iter_mut().take(1 + count).enumerate() {
if position > 0 && *sequence > before {
break;
}
if !visit(batch, position == 0) {
break;
}
}
}
}
/// Drop the batches at the head of `queue`'s line while `drop` holds (the rest of a command
/// buffer that failed), and give them back.
pub(crate) fn drop_head(&mut self, queue: u64, mut drop: impl FnMut(&B) -> bool) -> Vec<B> {
@@ -25,7 +25,8 @@
//! of the buffer's bytes in `COMPUTE_SHADER`, which the encoder's tracker orders as any command's
//! (after a pass's `COLOR_ATTACHMENT_OUTPUT` writes; before the buffer's next use). Before the
//! host reads the bytes, the command buffer's last barrier makes every write available to the
//! host (`tracker::Barrier::to_host`, `ALL_COMMANDS`/`MEMORY_WRITE` to `HOST`/`HOST_READ`).
//! host (`tracker::Barrier::to_host`, `ALL_COMMANDS`/`MEMORY_WRITE` to `HOST`/`HOST_READ`, or
//! `Barrier::to_all`, which adds every later command of its `VkQueue`: `batch_order.rs`).
//!
//! **Where the copy stays.** A device without the fact, a texel of another width, a texture of
//! more levels or slices, bytes copied through a staging buffer, a region past the device's
@@ -167,6 +167,10 @@ pub(super) fn over_host(device: &Device, host: &Host, runs: &Arc<AtomicUsize>) -
}
}
/// A command buffer of `queue`'s that fills `target` [`FILLS`] times, committed, once its batch's
/// `vkQueueSubmit` was made (a kernel submission counted, `WorkCounts::queue_submissions`; its
/// kernel times are no such sign, as `freed_memory.rs`'s `filling` says): the work the blit waits
/// behind.
pub(super) fn busy(queue: &CommandQueue, target: &Buffer) -> CommandBuffer {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
@@ -174,8 +178,10 @@ pub(super) fn busy(queue: &CommandQueue, target: &Buffer) -> CommandBuffer {
blit.fill_buffer(target, 0..FILLED, value as u8).unwrap();
}
blit.end_encoding().unwrap();
let before = queue.device().work_counts().queue_submissions;
command_buffer.commit().unwrap();
let deadline = Instant::now() + WAIT;
while queue.device().work_counts().queue_submissions == before {
assert!(Instant::now() < deadline, "the batch was never submitted");
std::thread::yield_now();
}
@@ -1060,7 +1060,7 @@ fn the_threads_that_take_command_buffers_to_their_handlers_run_at_the_user_inter
let _ = note.send((name, qos_class_self()));
}));
});
let scheduler = Scheduler::start(1).unwrap();
let scheduler = Scheduler::start(1, false).unwrap();
let completion = Completion::start(2).unwrap();
// The pool's first thread runs an item that blocks; another queue's item then starts
// a thread of its own.
@@ -1219,7 +1219,7 @@ fn the_threads_that_take_command_buffers_to_their_handlers_run_with_the_utilizat
let _ = note.send((name, with_child()));
}));
});
let scheduler = Scheduler::start(1).unwrap();
let scheduler = Scheduler::start(1, false).unwrap();
let completion = Completion::start(2).unwrap();
// The pool's first thread runs an item that blocks; another queue's item then starts
// a thread of its own.
@@ -128,8 +128,13 @@ fn unused(device: &Device, host: &Host, runs: &Arc<Runs>) -> Option<crate::Buffe
}
}
/// A command buffer of `queue`'s that fills `target` [`FILLS`] times, committed, once its batch
/// was submitted.
/// A command buffer of `queue`'s that fills `target` [`FILLS`] times, committed, once its batch's
/// `vkQueueSubmit` was made: a kernel submission counted (`WorkCounts::queue_submissions`, counted
/// under the parking gate's read lock that the store of the batch's value holds too, so a block's
/// note after it sees the value). Its kernel times are no such sign: the scheduler stores its
/// start as it begins the batch, before replaying and submitting it, and under
/// `CompletionPolicy::Grouped` its end as it holds the batch for a kernel submission with later
/// ones.
fn filling(queue: &CommandQueue, target: &crate::Buffer) -> CommandBuffer {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
@@ -137,9 +142,10 @@ fn filling(queue: &CommandQueue, target: &crate::Buffer) -> CommandBuffer {
blit.fill_buffer(target, 0..FILLED, value as u8).unwrap();
}
blit.end_encoding().unwrap();
let before = queue.device().work_counts().queue_submissions;
command_buffer.commit().unwrap();
let deadline = Instant::now() + WAIT;
while command_buffer.kernel_start_time() == 0.0 {
while queue.device().work_counts().queue_submissions == before {
assert!(Instant::now() < deadline, "the batch was never submitted");
std::thread::yield_now();
}
@@ -1087,6 +1087,108 @@ fn logical_queues_on_one_vk_queue_order_by_barriers() {
assert_eq!(waits, []);
}
/// Where every batch ends with [`Barrier::to_all`] (`batch_order.rs`), every write before every
/// access of every later command of its `VkQueue`, whichever logical queue committed it (logical
/// queues sharing a `VkQueue` share its submission order), a later batch there needs no barrier
/// from an earlier one's writes, reads or fence updates. Inside a batch the encoders still order
/// among themselves, and a batch of another `VkQueue` still waits.
#[test]
fn batches_of_one_vk_queue_ordered_by_their_ends_need_no_barrier_between_them() {
let fence: Key = 100;
let mut update = EncoderUses::<Key>::new(true);
update.record(TRANSFER, &[writes(1, bytes(0..256), copy_write())], None);
update.update_fence(fence, None);
let mut waiting = EncoderUses::<Key>::new(false);
waiting.wait_for_fence(fence, None);
waiting.record(COMPUTE, &[], None);
let mut queue = Tracker::by_ends();
assert_eq!(commit(&mut queue, &[update.finish()], 1), [None]);
// A read after the write, a write after the read, a wait for the fence.
let read = one(&[reads(1, bytes(0..256), shader_read())]);
assert_eq!(commit(&mut queue, std::slice::from_ref(&read), 2), [None]);
let write = one(&[writes(1, bytes(0..256), shader_write())]);
assert_eq!(commit(&mut queue, std::slice::from_ref(&write), 3), [None]);
assert_eq!(commit(&mut queue, &[waiting.finish()], 4), [None]);
// A read and a write after it in one batch: an execution dependency between them alone.
let copy = one(&[writes(1, bytes(0..256), copy_write())]);
assert_eq!(
commit(&mut queue, &[read, copy], 5),
[
None,
barrier(
Access::new(COMPUTE, NO_ACCESS),
Access::new(TRANSFER, NO_ACCESS)
)
]
);
// Another `VkQueue` waits for the last write.
let (barriers, waits) = submit(
&mut queue,
&[one(&[reads(1, bytes(0..256), copy_read())])],
on(1, 1),
);
assert_eq!(barriers, [None]);
assert_eq!(waits, [wait(at(5), TRANSFER)]);
}
/// The same batches in the exact form plan a barrier for each dependency on an earlier batch of
/// the `VkQueue`, as within one.
#[test]
fn batches_of_one_vk_queue_in_the_exact_form_order_by_barriers() {
let mut queue = Tracker::default();
assert_eq!(
commit(
&mut queue,
&[one(&[writes(1, bytes(0..256), copy_write())])],
1
),
[None]
);
let read = one(&[reads(1, bytes(0..256), shader_read())]);
assert_eq!(
commit(&mut queue, std::slice::from_ref(&read), 2),
[barrier(copy_write(), shader_read())]
);
assert_eq!(
commit(
&mut queue,
&[one(&[writes(1, bytes(0..256), shader_write())])],
3
),
// After the read, and after the copy's write, which the read's barrier made visible to
// reads alone.
[barrier(
Access::new(TRANSFER | COMPUTE, vk::AccessFlags2::TRANSFER_WRITE),
shader_write()
)]
);
}
/// Merged entries ordered by their batches' ends: a write over the merged reads of earlier
/// batches needs nothing on their `VkQueue`, and one on another waits for them at their latest.
#[test]
fn merged_entries_ordered_by_their_ends_still_order_another_queue() {
let mut queue = Tracker::by_ends();
for serial in 0..1000u64 {
let start = serial % 120;
let got = commit(
&mut queue,
&[one(&[reads(1, bytes(start..start + 8), copy_read())])],
serial + 1,
);
assert_eq!(got, [None]);
assert!(queue.entries() <= ENTRIES_PER_KEY);
}
let write = one(&[writes(1, bytes(32..48), shader_write())]);
assert_eq!(
commit(&mut queue, std::slice::from_ref(&write), 1001),
[None]
);
let (barriers, waits) = submit(&mut queue, &[write], on(1, 1));
assert_eq!(barriers, [None]);
assert_eq!(waits, [wait(at(1001), COMPUTE)]);
}
#[test]
fn a_fence_updated_on_another_queue_is_a_wait() {
let fence: Key = 100;
@@ -1315,6 +1417,19 @@ fn the_command_buffer_barriers_keep_their_masks() {
dst_access: vk::AccessFlags::HOST_READ | vk::AccessFlags::HOST_WRITE,
}
);
let all = Barrier::to_all().legacy();
assert_eq!(
all,
LegacyBarrier {
src_stages: vk::PipelineStageFlags::ALL_COMMANDS,
src_access: vk::AccessFlags::MEMORY_WRITE,
dst_stages: vk::PipelineStageFlags::HOST | vk::PipelineStageFlags::ALL_COMMANDS,
dst_access: vk::AccessFlags::HOST_READ
| vk::AccessFlags::HOST_WRITE
| vk::AccessFlags::MEMORY_READ
| vk::AccessFlags::MEMORY_WRITE,
}
);
}
#[test]
+83 -24
View File
@@ -29,6 +29,12 @@
//! image outside them, which the plan orders as any other. An access after one of the same
//! `VkQueue` needs a [`Barrier`]: one global memory barrier, everything in `src` before everything
//! in `dst`, which orders buffer and image memory alike; Vulkan's submission order on one
//! `VkQueue` makes it cover the earlier batches of every logical queue there. A tracker that
//! orders batches by their ends ([`Tracker::by_ends`], `batch_order.rs`) plans none after an
//! access of an earlier batch of the same `VkQueue`: every batch there ends with
//! [`Barrier::to_all`], every write before every access of every later command, which submission
//! order makes cover the later batches of every logical queue (an execution dependency on every
//! stage, so a write after an earlier batch's read is ordered too). An access after one
//! of another `VkQueue` needs a [`Wait`] of its batch for that queue's timeline semaphore at the
//! earlier batch's [`Point`]: the signal makes the earlier writes available and the wait makes
//! them visible to the waiting stages of this batch and of every later one of its queue. That
@@ -347,6 +353,26 @@ impl Barrier {
}
}
/// The end of every batch where batches are ordered by their ends (`batch_order.rs`):
/// [`to_host`](Barrier::to_host)'s, and every earlier command before every access of every
/// later command of its `VkQueue`, so later batches there need no barrier from its accesses
/// ([`Tracker`]'s module docs).
pub(super) fn to_all() -> Barrier {
Barrier {
src: Access::new(
vk::PipelineStageFlags2::ALL_COMMANDS,
vk::AccessFlags2::MEMORY_WRITE,
),
dst: Access::new(
vk::PipelineStageFlags2::HOST | vk::PipelineStageFlags2::ALL_COMMANDS,
vk::AccessFlags2::HOST_READ
| vk::AccessFlags2::HOST_WRITE
| vk::AccessFlags2::MEMORY_READ
| vk::AccessFlags2::MEMORY_WRITE,
),
}
}
/// Everything recorded before, before everything recorded after: a shadowed texture's copy
/// in an encoder whose commands Metal does not order (`shadow.rs`).
pub(super) fn everything() -> Barrier {
@@ -747,19 +773,23 @@ impl Entry {
entry
}
/// What a use at `at` of this entry's range needs ordered before it.
fn depend(&self, read: Access, write: Access, at: Point, needs: &mut Needs) {
/// What a use at `at` of this entry's range needs ordered before it, where the accesses of
/// its queue's batches below `since` are ordered by their ends (0 where none is).
fn depend(&self, read: Access, write: Access, (at, since): (Point, u64), needs: &mut Needs) {
if !read.is_empty() {
self.after_writes(read, at, needs);
self.after_writes(read, (at, since), needs);
}
if !write.is_empty() {
self.after_writes(write, at, needs);
self.after_writes(write, (at, since), needs);
for reads in self.reads.iter() {
if reads.at.queue == at.queue {
needs.barrier.add(
Access::new(reads.stages, vk::AccessFlags2::NONE),
Access::new(write.stages, vk::AccessFlags2::NONE),
);
// Reads of a batch ordered by its end need nothing.
if reads.at.value >= since {
needs.barrier.add(
Access::new(reads.stages, vk::AccessFlags2::NONE),
Access::new(write.stages, vk::AccessFlags2::NONE),
);
}
} else {
add_wait(
&mut needs.waits,
@@ -774,11 +804,12 @@ impl Entry {
}
/// What `access` at `at` needs after the last writes: a barrier from a write of its own
/// queue not yet visible to it, and a wait for a write of another queue not yet waited for.
fn after_writes(&self, access: Access, at: Point, needs: &mut Needs) {
/// queue not yet visible to it (a write of a batch below `since` its batch's end made
/// visible), and a wait for a write of another queue not yet waited for.
fn after_writes(&self, access: Access, (at, since): (Point, u64), needs: &mut Needs) {
for writer in self.writers.iter() {
if writer.at.queue == at.queue {
if !writer.visible.covers(access) {
if writer.at.value >= since && !writer.visible.covers(access) {
needs.barrier.add(self.write, access);
}
} else if !writer.waited_by(at.queue).contains(access.stages) {
@@ -891,13 +922,13 @@ impl<S: Eq + Hash, H: BuildHasher> Entries<S> for HashMap<S, Vec<Entry>, H> {
}
/// What the uses (sorted by key, one per key and range) at `at` need after the accesses in
/// `state`.
fn depend<S>(state: &impl Entries<S>, uses: &[Use<S>], at: Point) -> Needs {
/// `state`, those of its queue's batches below `since` ordered by their ends.
fn depend<S>(state: &impl Entries<S>, uses: &[Use<S>], (at, since): (Point, u64)) -> Needs {
let mut needs = Needs::default();
for used in uses {
for entry in state.of(&used.key).into_iter().flatten() {
if entry.range.overlaps(&used.range) {
entry.depend(used.read, used.write, at, &mut needs);
entry.depend(used.read, used.write, (at, since), &mut needs);
}
}
}
@@ -1091,7 +1122,7 @@ impl<K: Copy + Ord + Hash> EncoderUses<K> {
return None;
}
// One encoder runs on one queue: its commands need barriers, never waits.
depend(&self.inside, &inside_uses(uses), Point::default())
depend(&self.inside, &inside_uses(uses), (Point::default(), 0))
.barrier
.needed()
}
@@ -1802,6 +1833,9 @@ pub(super) struct Tracker<K> {
/// Lists a plan applied before gave back, cleared, for the next plans to fill
/// ([`Spares`]).
spares: Spares<K>,
/// Every batch ends with [`Barrier::to_all`], so the accesses of earlier batches of a
/// `VkQueue` need no barrier there ([`Tracker::by_ends`]).
by_ends: bool,
}
/// A resource or a fence an applied plan touched ([`Tracker::touched`]).
@@ -1870,6 +1904,7 @@ impl<K> Default for Tracker<K> {
completed: Vec::new(),
touched: Vec::new(),
spares: Spares::default(),
by_ends: false,
}
}
}
@@ -1985,6 +2020,26 @@ impl<K> Plan<K> {
}
}
impl<K> Tracker<K> {
/// A tracker of a device whose batches each end with [`Barrier::to_all`] (`batch_order.rs`):
/// it plans no barrier after an access of an earlier batch of the same `VkQueue`.
pub(super) fn by_ends() -> Tracker<K> {
Tracker {
by_ends: true,
..Tracker::default()
}
}
/// The value below which the batches of `at`'s queue are ordered by their ends: `at`'s own
/// where every batch ends with [`Barrier::to_all`], else 0.
fn since(&self, at: Point) -> u64 {
match self.by_ends {
true => at.value,
false => 0,
}
}
}
impl<K: Copy + Ord + Hash> Tracker<K> {
/// Every batch of `queue` through timeline value `value` completed, and the host saw it: the
/// state forgets what they did. Only the resources and fences those batches touched are looked
@@ -2043,6 +2098,7 @@ impl<K: Copy + Ord + Hash> Tracker<K> {
where
K: 'a,
{
let since = self.since(at);
let spares = &mut self.spares;
let PlanLists {
barriers,
@@ -2073,13 +2129,16 @@ impl<K: Copy + Ord + Hash> Tracker<K> {
// The stages the call names wait, and the encoder's work outside its draws.
let stages = wait.covered(summary.stages);
if update.at.queue == at.queue {
barrier.add(
Access::new(update.stages, vk::AccessFlags2::MEMORY_WRITE),
Access::new(
summary.stages,
vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE,
),
);
// An update of a batch ordered by its end needs nothing.
if update.at.value >= since {
barrier.add(
Access::new(update.stages, vk::AccessFlags2::MEMORY_WRITE),
Access::new(
stages,
vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE,
),
);
}
} else {
add_wait(
&mut plan.waits,
@@ -2103,8 +2162,8 @@ impl<K: Copy + Ord + Hash> Tracker<K> {
}
}
let needs = match alone {
true => depend(&self.resources, &summary.uses, at),
false => depend(&plan.resources, &summary.uses, at),
true => depend(&self.resources, &summary.uses, (at, since)),
false => depend(&plan.resources, &summary.uses, (at, since)),
};
barrier.add(needs.barrier.src, needs.barrier.dst);
for wait in needs.waits {
+132 -4
View File
@@ -5,6 +5,7 @@
//! resident one by one on MoltenVK; and the completion waits that missed their wake, which a test
//! holds to none. Not part of the API.
use super::command_buffer::GroupEnd;
use super::degradation::Degradation;
use super::device::lock;
use super::Device;
@@ -89,7 +90,17 @@ pub(crate) struct Counters {
stamped_buffers_reused: AtomicU64,
finales_folded: AtomicU64,
finales_apart: AtomicU64,
grouped_submissions: AtomicU64,
batches_grouped: AtomicU64,
/// By `GroupEnd`, in its order.
group_ends: [AtomicU64; 7],
/// Batches submitted, by how many earlier batches of their `VkQueue` were pending then: none,
/// one, two or three, four or more.
batches_by_pending: [AtomicU64; 4],
groups_kept_pending: AtomicU64,
groups_sent_for_waits: AtomicU64,
completed_waits: AtomicU64,
event_waits_met: AtomicU64,
bare_starts: AtomicU64,
prefixed_starts: AtomicU64,
unrun_instances_ended: AtomicU64,
@@ -607,6 +618,42 @@ impl Counters {
self.finales_apart.fetch_add(1, Ordering::Relaxed);
}
/// One `vkQueueSubmit` submitted `batches` batches, more than one, only the last signalling
/// (`command_buffer/group.rs`).
pub(crate) fn batches_grouped(&self, batches: usize) {
self.grouped_submissions.fetch_add(1, Ordering::Relaxed);
(self.batches_grouped).fetch_add(batches as u64, Ordering::Relaxed);
}
/// A batch was submitted, or held in a group, while `pending` earlier batches of its
/// `VkQueue` were submitted or held and not seen complete (`command_buffer/submit.rs`).
pub(crate) fn batch_submitted_behind(&self, pending: u64) {
let bucket = match pending {
0 => 0,
1 => 1,
2 | 3 => 2,
_ => 3,
};
self.batches_by_pending[bucket].fetch_add(1, Ordering::Relaxed);
}
/// A group of batches held for one kernel submission went, sent by `end`
/// (`command_buffer/group.rs`).
pub(crate) fn group_ended(&self, end: GroupEnd) {
self.group_ends[end as usize].fetch_add(1, Ordering::Relaxed);
}
/// A group of batches stayed held past the pass that found no batch ready, for the work its
/// `VkQueue` still ran (`command_buffer/group.rs`); once per group.
pub(crate) fn group_kept_pending(&self) {
self.groups_kept_pending.fetch_add(1, Ordering::Relaxed);
}
/// Such a group went at once because a thread waits for one of its command buffers.
pub(crate) fn group_sent_for_wait(&self) {
self.groups_sent_for_waits.fetch_add(1, Ordering::Relaxed);
}
/// A batch with work was submitted waiting for `waits` timelines at values the host saw them
/// reach (`command_buffer/submit.rs`).
pub(crate) fn completed_waited(&self, waits: usize) {
@@ -614,6 +661,14 @@ impl Counters {
.fetch_add(waits as u64, Ordering::Relaxed);
}
/// A batch went (submitted, or held in a group) with `waits` of its event waits for values
/// the scheduler found reached as it took the batch, so it waits for none of them
/// (`scheduler/mod.rs`).
pub(crate) fn event_waits_met(&self, waits: usize) {
self.event_waits_met
.fetch_add(waits as u64, Ordering::Relaxed);
}
/// A batch with work was submitted with no command buffer of barriers before its first
/// encoder.
pub(crate) fn bare_start(&self) {
@@ -1568,15 +1623,70 @@ pub struct WorkCounts {
/// command buffer's last batch its end timestamp) recorded into their last command buffer as
/// they ended, the end's own command buffer saved (`command_buffer/submit.rs`).
pub finales_folded: u64,
/// Batches with work submitted with their end in a command buffer of its own: one that
/// signals an event, leaves its submission a segment or sparse update, names a texture over
/// the caller's image that moves between layouts, or whose last command buffer does not go
/// to the queue as recorded.
/// Batches with work submitted with their end in a command buffer of its own: one whose
/// event signal waits for another `VkQueue`'s earlier one, leaves its submission a segment or
/// sparse update, names a texture over the caller's image that moves between layouts, or
/// whose last command buffer does not go to the queue as recorded.
pub finales_apart: u64,
/// `vkQueueSubmit` calls that submitted more than one batch, of command buffers committed on
/// one queue and found ready together, only the last signalling its queue's timeline
/// (`CompletionPolicy::Grouped`, `command_buffer/group.rs`): one kernel submission for them all
/// on Mesa's drivers.
pub grouped_submissions: u64,
/// The batches those calls submitted.
pub batches_grouped: u64,
/// Groups of batches held for one kernel submission (`CompletionPolicy::Grouped`) that went
/// holding the most they may (four), each group counted once by what sent it; with the six
/// fields after this one, every group. Their spread says why a device's groups hold fewer.
pub group_ends_full: u64,
/// Groups that went before a batch that waits for an event value a batch they held signals,
/// which only the group's end meets, or in the call of a batch that waits for anything else
/// not seen complete, submitted after them: a batch with a wait leads a group, never joins one.
pub group_ends_wait: u64,
/// Groups that went before a batch that may not wait in one (it signals a binary semaphore,
/// takes a fence, binds a sparse update, or moves bytes that wait for every submission) or
/// is of another `VkQueue`.
pub group_ends_apart: u64,
/// Groups that went in the call of a batch that could join but did first work or names a
/// texture over the caller's image, submitted last.
pub group_ends_first_work: u64,
/// Groups that went when the scheduler found no batch left to submit.
pub group_ends_drained: u64,
/// Groups that went when the scheduler found no batch ready, with submission checks or host
/// steps left for its thread to run.
pub group_ends_checks: u64,
/// Groups that went when the scheduler found no batch ready, the rest held for events'
/// values, host steps' gates, binary semaphores or texture decodes.
pub group_ends_held: u64,
/// Batches submitted (each held in a group counted as it is held) while no earlier batch of
/// their `VkQueue` was pending: every one submitted before them the host had seen complete
/// (their queue's timeline at their values). With the three fields after this one, every
/// batch, by how far its queue's work ran behind its submission.
pub batches_with_none_pending: u64,
/// Batches submitted while one earlier batch of their `VkQueue` was pending.
pub batches_with_one_pending: u64,
/// Batches submitted while two or three earlier batches of their `VkQueue` were pending.
pub batches_with_two_or_three_pending: u64,
/// Batches submitted while four or more earlier batches of their `VkQueue` were pending.
pub batches_with_four_or_more_pending: u64,
/// Groups of batches held for one kernel submission that stayed held past the pass that found
/// no batch ready, while two or more earlier submissions of their `VkQueue` were not seen
/// complete, until one was left or the group filled (`command_buffer/group.rs`); each group
/// counted once, then by what sent it among the group ends.
pub groups_kept_pending: u64,
/// Of those, the groups that went at once because a thread began to wait for one of their
/// command buffers' completion (`CommandBuffer::wait_until_completed`).
pub groups_sent_for_waits: u64,
/// The waits batches with work made for timelines at values the host had seen them reach,
/// which make what completed work wrote visible to them: one per timeline whose completed
/// value moved since a batch of the same `VkQueue` last waited for it.
pub completed_waits: u64,
/// Event waits (`encode_wait_for_event`) for values the scheduler found reached as it took
/// their batch, submitting it or holding it in a group (`scheduler/mod.rs`): by a signal
/// seen complete, or the host's. Their batch waits for none of them, so it may join a group
/// (`CompletionPolicy::Grouped`) as a batch with no wait does; the others' waits make it lead
/// one or go alone (`group_ends_wait`).
pub event_waits_met: u64,
/// Batches with work submitted with no command buffer of barriers before their first
/// encoder: nothing planned before it, and no start timestamp to write there (none, or one
/// its first encoder wrote, `WorkCounts::prefixed_starts`).
@@ -1998,6 +2108,8 @@ impl Device {
#[doc(hidden)]
pub fn work_counts(&self) -> WorkCounts {
let counters = &self.shared().counts;
let group_end = |end: GroupEnd| counters.group_ends[end as usize].load(Ordering::Relaxed);
let pending = |bucket: usize| counters.batches_by_pending[bucket].load(Ordering::Relaxed);
let begun =
|what: Begun| counters.command_buffers_begun_by[what as usize].load(Ordering::Relaxed);
let (allocated, census, (parked, waiting), (made, freed)) = {
@@ -2123,7 +2235,23 @@ impl Device {
stamped_buffers_reused: counters.stamped_buffers_reused.load(Ordering::Relaxed),
finales_folded: counters.finales_folded.load(Ordering::Relaxed),
finales_apart: counters.finales_apart.load(Ordering::Relaxed),
grouped_submissions: counters.grouped_submissions.load(Ordering::Relaxed),
batches_grouped: counters.batches_grouped.load(Ordering::Relaxed),
group_ends_full: group_end(GroupEnd::Full),
group_ends_wait: group_end(GroupEnd::Wait),
group_ends_apart: group_end(GroupEnd::Apart),
group_ends_first_work: group_end(GroupEnd::FirstWork),
group_ends_drained: group_end(GroupEnd::Drained),
group_ends_checks: group_end(GroupEnd::Checks),
group_ends_held: group_end(GroupEnd::Held),
batches_with_none_pending: pending(0),
batches_with_one_pending: pending(1),
batches_with_two_or_three_pending: pending(2),
batches_with_four_or_more_pending: pending(3),
groups_kept_pending: counters.groups_kept_pending.load(Ordering::Relaxed),
groups_sent_for_waits: counters.groups_sent_for_waits.load(Ordering::Relaxed),
completed_waits: counters.completed_waits.load(Ordering::Relaxed),
event_waits_met: counters.event_waits_met.load(Ordering::Relaxed),
bare_starts: counters.bare_starts.load(Ordering::Relaxed),
prefixed_starts: counters.prefixed_starts.load(Ordering::Relaxed),
unrun_instances_ended: counters.unrun_instances_ended.load(Ordering::Relaxed),
@@ -422,6 +422,8 @@ mod global_builtins;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod gpu_times;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod grouped_submissions;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod guarded_effects;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod half_output_blends;
@@ -35,12 +35,13 @@
//! Previously a pool given back past the spares (or that made more than 64 command buffers) was
//! destroyed as its command buffer completed, where NVIDIA 615.71.09's `vkDestroyCommandPool`
//! intermittently never returned.
//! - **The end in the work.** A batch that signals no event ends in its last command buffer: the
//! barrier to the host (and a timed command buffer's end timestamp) go there as the batch
//! ends, and its submission holds no end of its own (`WorkCounts::finales_folded`); before, each
//! batch's end was a command buffer of its own, about 9 us of GPU time on an Iris Xe. A batch
//! that signals an event keeps its end apart (`WorkCounts::finales_apart`). The host reads what
//! either wrote once it completed.
//! - **The end in the work.** A batch ends in its last command buffer: the barrier to the host
//! (and a timed command buffer's end timestamp) go there as the batch ends, and its submission
//! holds no end of its own (`WorkCounts::finales_folded`), an event's signal included; before,
//! each batch's end was a command buffer of its own, about 9 us of GPU time on an Iris Xe. Only
//! an event's signal that waits for another `VkQueue`'s earlier one, still pending, keeps an
//! end apart, after that wait (`WorkCounts::finales_apart`). The host reads what either wrote
//! once it completed.
//! - **Completed work, waited for.** A batch's submission waits for each timeline whose
//! completed value the host saw move since a batch of its `VkQueue` last waited for it, each
//! queue's and the device's own (`WorkCounts::completed_waits`), which makes what completed
@@ -51,6 +52,15 @@
//! semaphore operations (`DriverFact::SemaphoreOperationsStallSubmits`) each still begins with
//! that command buffer and waits for nothing completed. Copies read what completed fills on
//! another command queue and a host copy into a texture wrote.
//! - **Batches of one queue, ordered by their ends** (`BatchOrderPolicy::Ends`, on a driver
//! measured to run a queue's submissions one after another: [`orders_by_ends`]). Every batch
//! ends with a barrier from every write to the host's accesses and to every later command of
//! its `VkQueue`, so a batch there plans no barrier from an earlier batch's accesses, still in
//! flight or not: a chain of command buffers on one command queue, each copying what the one
//! before wrote while a long fill ahead of them runs, each begins with no command buffer of
//! barriers (`WorkCounts::bare_starts`), and the last reads the first's fill. Under
//! `BatchOrderPolicy::Exact`, and on any other driver, each but the first begins with one that
//! orders it after the batch before, and reads the same bytes.
//! - **Addressable buffers**. The program's buffers take their device addresses from their memory
//! blocks, so making them makes no buffer with the device-address usage beyond a new block's;
//! before, each was one, which MoltenVK made resident one by one in every encoder whose pipeline
@@ -58,9 +68,10 @@
use super::degrade_notices::{on_device, on_device_with};
use super::{bound_buffers, encode_case, pipeline_state, public_case, CaseResources, WAIT};
use metal2vulkan::device::DriverFact;
use metal2vulkan::device::{BatchOrderPolicy, DriverFact};
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::{PixelFormat, TextureUsage};
use metal2vulkan::vk::DriverId;
use metal2vulkan_runtime::{
BlitOption, Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, EventRef, Origin,
Region, ResourceOptions, Size, TextureDescriptor,
@@ -302,10 +313,13 @@ fn bytes(buffer: &Buffer) -> Vec<u8> {
unsafe { std::slice::from_raw_parts(contents.as_ptr(), buffer.length() as usize) }.to_vec()
}
/// A fill's batch ends in the fill's own command buffer, and one that signals an event in a
/// command buffer of its own (the module docs): the host reads each fill once it completed.
/// A fill's batch ends in the fill's own command buffer, one that signals an event too (the
/// module docs): the host reads each fill once it completed. A fill on a second queue that signals
/// the next value of an event a first queue's fill signalled just before ends once, in its work
/// or, where its signal waits for the first's still pending on another `VkQueue`, apart; the
/// event reaches the second value.
#[test]
fn a_batch_ends_in_its_last_command_buffer_unless_it_signals_an_event() {
fn a_batch_ends_in_its_last_command_buffer() {
on_device(|device, _| {
let queue = device.new_command_queue().unwrap();
let buffer = device.new_buffer(4096, ResourceOptions::shared()).unwrap();
@@ -334,10 +348,45 @@ fn a_batch_ends_in_its_last_command_buffer_unless_it_signals_an_event() {
assert_eq!(filled(0x11, None), (1, 0), "a fill");
assert_eq!(
filled(0x22, Some(1)),
(0, 1),
(1, 0),
"a fill that signals an event"
);
assert_eq!(filled(0x33, None), (1, 0), "a fill after it");
// Across two queues, the second's signal right after the first's.
let other = device.new_command_queue().unwrap();
let event = device.new_shared_event().unwrap();
let large = device
.new_buffer(64 << 20, ResourceOptions::private())
.unwrap();
let before = device.work_counts();
let signalled: Vec<CommandBuffer> = [(&queue, &large, 1), (&other, &buffer, 2)]
.into_iter()
.map(|(on, target, value)| {
let command_buffer = on.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(target, 0..target.length(), 0x44).unwrap();
blit.end_encoding().unwrap();
command_buffer
.encode_signal_event(EventRef::from(&event), value)
.unwrap();
command_buffer.commit().unwrap();
command_buffer
})
.collect();
for command_buffer in &signalled {
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
let after = device.work_counts();
assert!(bytes(&buffer).iter().all(|&b| b == 0x44), "the second fill");
assert!(
event.wait_until_signaled_value(2, WAIT),
"{}",
event.signaled_value()
);
let ends = (after.finales_folded - before.finales_folded)
+ (after.finales_apart - before.finales_apart);
assert_eq!(ends, 2, "one end each");
});
}
@@ -449,6 +498,125 @@ fn batches_with_nothing_planned_wait_for_completed_work_instead_of_a_barrier() {
);
}
/// Whether a device of the driver orders its batches by their ends under `batch_order`: the
/// runtime's table of drivers measured to run a queue's submissions one after another
/// (`batch_order.rs`).
pub(super) fn orders_by_ends(device: &Device, batch_order: BatchOrderPolicy) -> bool {
batch_order == BatchOrderPolicy::Ends
&& matches!(
device.properties().description.driver_id,
Some(
DriverId::INTEL_OPEN_SOURCE_MESA
| DriverId::MESA_RADV
| DriverId::NVIDIA_PROPRIETARY
)
)
}
/// Under the default, on a device made with `gpu_times_from_host` (so no start timestamp is
/// written before a batch's work): a long fill, waiting for a shared event, then a chain of
/// command buffers on the same command queue, each copying what the one before wrote, the first
/// copying the long one's last fill; the host raises the event once all are committed, so none
/// is complete as the next is planned. Where the device orders batches by their ends, every batch
/// begins with no command buffer of barriers, as the end of the batch before orders it (the
/// module docs), and the chain's last copy reads the long one's fill. Elsewhere
/// [`batches_of_one_queue_in_the_exact_form_begin_with_their_barriers`]'s.
#[test]
fn batches_of_one_queue_ordered_by_their_ends_begin_with_no_barrier() {
chained_batches(BatchOrderPolicy::Ends);
}
/// The same under `BatchOrderPolicy::Exact`: each batch of the chain begins with a command buffer
/// of barriers for the copy before it, still in flight, and the last reads the same bytes.
#[test]
fn batches_of_one_queue_in_the_exact_form_begin_with_their_barriers() {
chained_batches(BatchOrderPolicy::Exact);
}
/// The two tests above under `batch_order`. Where the driver's submissions stall on semaphore
/// operations (`DriverFact::SemaphoreOperationsStallSubmits`), every batch begins with its command
/// buffer of barriers under either.
fn chained_batches(batch_order: BatchOrderPolicy) {
const CHAIN: usize = 8;
const LONG_FILLS: u64 = 64;
on_device_with(
|options| {
options.gpu_times_from_host = true;
options.policy.batch_order = batch_order;
},
|device, _| {
let by_barrier = device
.properties()
.driver_facts
.contains(&DriverFact::SemaphoreOperationsStallSubmits);
let by_ends = orders_by_ends(device, batch_order);
let queue = device.new_command_queue().unwrap();
let scratch = device
.new_buffer(16 << 20, ResourceOptions::private())
.unwrap();
let links: Vec<Buffer> = (0..CHAIN)
.map(|_| device.new_buffer(4096, ResourceOptions::private()).unwrap())
.collect();
let read = device.new_buffer(4096, ResourceOptions::shared()).unwrap();
// Each buffer's first work, completed.
for buffer in links.iter().chain([&scratch, &read]) {
finish(&fill(&queue, buffer));
}
let before = device.work_counts();
let event = device.new_shared_event().unwrap();
let long = queue.command_buffer().unwrap();
long.encode_wait_for_event(EventRef::from(&event), 1)
.unwrap();
let mut blit = long.blit_command_encoder().unwrap();
for round in 0..LONG_FILLS {
blit.fill_buffer(&scratch, 0..scratch.length(), round as u8)
.unwrap();
}
blit.fill_buffer(&links[0], 0..4096, 0xc3).unwrap();
blit.end_encoding().unwrap();
long.commit().unwrap();
let chain: Vec<CommandBuffer> = (1..CHAIN)
.map(|at| (&links[at - 1], &links[at]))
.chain([(&links[CHAIN - 1], &read)])
.map(|(from, to)| {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.copy_from_buffer_to_buffer(from, 0, to, 0, 4096)
.unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
})
.collect();
event.set_signaled_value(1);
for command_buffer in chain.iter().chain([&long]) {
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
let after = device.work_counts();
let bare = after.bare_starts - before.bare_starts;
eprintln!(
"CHAINED-BATCHES {} {batch_order:?}: {bare} bare starts of {} batches",
device.name(),
CHAIN + 1,
);
// The long fill begins bare under either: what it depends on completed. Each copy
// behind it plans a barrier for the copy before it, in flight, unless batches are
// ordered by their ends.
let expected = match (by_barrier, by_ends) {
(true, _) => 0,
(false, true) => CHAIN as u64 + 1,
(false, false) => 1,
};
assert_eq!(bare, expected, "bare starts");
assert!(
bytes(&read).iter().all(|&byte| byte == 0xc3),
"the long fill's bytes through the chain"
);
},
);
}
/// Command buffers that each end in one submission, empty or of a blit, complete at their
/// fences where the driver reads a command buffer's objects after its value
/// (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`): the queues' waiters wait for
@@ -108,6 +108,8 @@
//! over a buffer they do not store through the image its texture keeps in `kept_buffer_bytes`
//! ([`KEPT_BYTES`]), the device's
//! first sparse texture on a driver whose first sparse resource waits for every queue's work in
//! `first_use` ([`FIRST_SPARSE`]), command buffers a submission of several batches completes
//! counts of draws writing several colors on a driver that counts each sample once per color in
//! `color_groups` ([`PER_COLOR_COUNTS`]), passes that load and draw a signed normalized attachment
//! holding a minimum code, or an `RGB9E5Float` one holding an unnormalized word, in
//! `snorm_tile_store` ([`SNORM_MINIMUM`], [`SHARED_EXPONENT`]),
@@ -163,6 +165,7 @@ use super::format_copies::MEMMOVES;
use super::fragment_imageblocks::FRAGMENT_IMAGEBLOCKS;
use super::framebuffer_fetch::{FETCHES, PLANES, SHADER_DEPTH, STORAGE_FORMS};
use super::fresh_contents::FRESH_PATTERNS;
use super::grouped_submissions::GROUPED;
use super::heap_layouts::HEAP_LAYOUTS;
use super::heap_metal_sizes::{PAST_METAL_SIZES, UNMODELLED_SIZES};
use super::heap_textures::{ALIASES, APART, COMPRESSED, OPTIMIZED};
@@ -551,6 +554,7 @@ fn every_kind_has_a_site_a_lane_test_takes() {
&SYNTHESIZED_GEOMETRY,
&EMULATED_TESSELLATION,
&EXACT_FORMS_OVER_LIMIT,
&GROUPED,
];
for kind in lists.into_iter().flatten().copied().chain(stage_kinds) {
assert!(listed.insert(kind), "{kind:?} is listed twice");
@@ -44,6 +44,8 @@
//! layouts of equal shapes (`WorkCounts::set_zero_equal_shape_switches` and kin), the passes whose
//! first instance recorded inline and the others by the check that ruled it out
//! (`WorkCounts::inline_passes`, `WorkCounts::passes_not_inline_actions` and kin)
//! `VkDeviceMemory` by kind after the timed frames (ANV on i915 lists each in every kernel
//! submission). Then the CPU time of the
//! process's other threads over the timed frames, their waits included, per command buffer (on
//! Linux, from each thread's `schedstat`), with its user-space part (from its `stat`, in clock
//! ticks) and how often they slept (their voluntary context switches, from their `status`: the
@@ -56,6 +58,26 @@
//! `frame_costs_announced` measure one alone, in a process of its own, for a profile of it
//! (`perf record -g` of the test's process).
//!
//! `frame_costs_over_imports` measures the checked device holding host imports live beside its
//! own memory, as the consumer's guest does, each in every kernel submission on ANV and RADV, for
//! each count of [`IMPORTS`], then with the more in the guest's shape (a second queue taking every
//! [`SECOND_QUEUE_EVERY`]th command buffer, every command buffer carrying a submission handler, as
//! the consumer's queue gives each one, and signalling a shared event at its end, every
//! [`PAGING_WAIT_EVERY`]th of the first queue's waiting for one the second signals):
//! under the default `CompletionPolicy::Grouped`, then under `CompletionPolicy::Exact`, twice each
//! in turn, each on a device of its own. Its lines also count the `vkQueueSubmit` calls
//! that held several batches (`WorkCounts::grouped_submissions`) and their batches, the batches
//! that ended in their work's last command buffer or in one of their own
//! (`WorkCounts::finales_folded`, `WorkCounts::finales_apart`), and the groups
//! by what sent them (`WorkCounts::group_ends_full` and kin), those kept for their queue's earlier
//! work and those of them a wait sent (`WorkCounts::groups_kept_pending`,
//! `WorkCounts::groups_sent_for_waits`), the batches by how many earlier
//! batches of their queue were pending as each went (`WorkCounts::batches_with_none_pending` and
//! kin), and the scheduler thread's sleeps
//! kernel-submission counter is loaded (`scripts/i915-execbuffers`, `LD_PRELOAD`), every
//! measurement's lines count the kernel submissions of its timed frames, the objects each lists
//! and the time each spent in the ioctl.
//!
//! `frame_costs_over_buffers` measures the plain device with window layers that are textures over
//! `Shared` buffers at tight rows (2048 bytes, which RADV and ANV render in place, as linear images
//! over the buffers' memory) in place of private textures, their passes loaded and stored, loaded
@@ -103,6 +125,7 @@
use super::render_arguments::{Members, ORDERED};
use super::renders::public_render;
use super::submit_costs::Execbuffers;
use super::{buffer_with, loader, open_device, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::candidate::engine::graphics::Assembly;
@@ -112,6 +135,7 @@ use crate::case::indirect_commands::metal_primitive_type;
use crate::gpu::TEST_DEVICE;
use crate::worker::alloc;
use metal2vulkan::bind::{DrawCall, SamplerDescriptor};
use metal2vulkan::device::CompletionPolicy;
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
use metal2vulkan::metal::{
@@ -122,11 +146,12 @@ use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
Buffer, ClearColor, CommandBuffer, CommandBufferStatus, CommandQueue, Degradation,
DegradationCategory, Device, DeviceOptions, Library, LoadAction, MessageSink, PipelineOptions,
Region, RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions,
SamplerState, ShaderCacheOptions, StoreAction, SubmissionCheck, Texture, TextureDescriptor,
WorkCounts,
DegradationCategory, Device, DeviceOptions, EventRef, Library, LoadAction, MessageSink,
PipelineOptions, Region, RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState,
ResourceOptions, SamplerState, ShaderCacheOptions, SharedEvent, StoreAction, SubmissionCheck,
Texture, TextureDescriptor, WorkCounts,
};
use std::cell::Cell;
use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::{Arc, Mutex};
@@ -153,6 +178,18 @@ const TEXTURES: usize = 16;
const TEXTURE_SIDE: u64 = 64;
/// The bytes of `zwd_shapes`' `ZwdShape`: rectangle, fill, outline and shape.
const SHAPE_BYTES: usize = 64;
/// The host imports a run over imports holds live: the consumer's guest drag on the Iris Xe held
/// 259 to 556, each in every kernel submission. With the fewer, the Iris Xe's scheduler thread
/// keeps up with the encoding thread; with the more, its submissions fall behind the commits, as
/// the guest's do (its commits' handlers ran 4 to 9 ms after them).
const IMPORTS: [usize; 2] = [260, 520];
/// In the guest's shape ([`Run::guest`]), the share of command buffers the second queue takes
/// (every 20th, about 5%, as the guest's blit queue against its exec queue), and of the first
/// queue's that wait for the second's paging event first (every 10th, about 10%).
const SECOND_QUEUE_EVERY: usize = 20;
const PAGING_WAIT_EVERY: usize = 10;
/// The bytes of each, over pages of its own.
const IMPORT_BYTES: usize = 512 << 10;
/// The most allocations a frame's draw makes on the encoding thread on average, its state changes
/// and its draw call together, once every pipeline is made: the binder writes each draw's commands
/// over the last draw's (`BindingPlan::instantiate_draw_into`), and the draw its uses, descriptor
@@ -210,22 +247,26 @@ const FIRST_LOCK_ALLOCATIONS: f64 = if cfg!(target_vendor = "apple") {
};
/// The most allocations the process's other threads make per command buffer of a checked frame:
/// the scheduler thread's pass, its check and its submission, its completion and its handlers.
/// Measured: 11.6 to 12.2 on ANV (Iris Xe), 11.7 on RADV (Radeon 780M), 11.7 to 12.5 on NVIDIA
/// (RTX 5080 Laptop GPU), 12.8 to 13.0 on lavapipe, 13.0 on NVIDIA (RTX 3090); more on the M3 Max
/// through MoltenVK, where the queues' waiters wait for each command buffer's fence too
/// Measured: 14.9 to 15.4 on lavapipe, its batches' grouped submissions allocating nothing
/// (`command_buffer/group.rs`); more on the M3 Max through MoltenVK, where the queues' waiters
/// wait for each command buffer's fence too
/// (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`) and whose locks allocate at their
/// first use.
#[cfg(not(m2v_system_alloc))]
const SUBMIT_ALLOCATIONS: f64 = 20.0;
/// One run's device, commits and layers: whether the device announces every precision kind,
/// whether each command buffer commits with a submission check ([`Checks`]), and what the window
/// layers are.
/// whether each command buffer commits with a submission check ([`Checks`]), what the window
/// layers are, how many host imports the device holds live beside them ([`IMPORT_BYTES`] each),
/// and its policy's `completion`.
#[derive(Clone, Copy)]
struct Run {
announced: bool,
checked: bool,
layers: Layers,
imports: usize,
completion: CompletionPolicy,
guest: bool,
/// Whether the [`REPEATED`] draws of each pass are drawn again with no call before them.
repeats: bool,
}
@@ -235,23 +276,34 @@ impl Run {
announced: false,
checked: false,
layers: Layers::Private,
imports: 0,
completion: CompletionPolicy::Grouped,
guest: false,
repeats: false,
};
const CHECKED: Run = Run {
announced: false,
checked: true,
layers: Layers::Private,
..Run::PLAIN
};
const ANNOUNCED: Run = Run {
announced: true,
checked: false,
layers: Layers::Private,
..Run::PLAIN
};
const REPEATING: Run = Run {
repeats: true,
..Run::PLAIN
};
/// The checked device's run with `imports` host imports live, under `completion`, in the
/// guest's shape where `guest` ([`Workload::guest`]).
const fn over_imports(imports: usize, completion: CompletionPolicy, guest: bool) -> Run {
Run {
imports,
completion,
guest,
..Run::CHECKED
}
}
/// The plain device's run with layers over buffers, its passes loading and storing them so.
const fn over_buffers(load: LoadAction, store: StoreAction) -> Run {
@@ -268,11 +320,16 @@ impl Run {
(true, false) => "announced",
(true, true) => "announced checked",
};
match self.layers {
let device = match self.layers {
Layers::Private => device.to_owned(),
Layers::OverBuffers(load, store) => {
format!("{device}, layers over buffers, {load:?} load, {store:?} store")
}
};
let device = match self.guest {
false => device,
true => format!("{device}, the guest's queues and events"),
};
let device = match self.repeats {
false => device,
true => format!("{device}, draws repeated with no call before them"),
@@ -281,6 +338,14 @@ impl Run {
"{device}, {buffers} command buffers of 1 pass of {draws} masked shapes \
alternating between two pipeline states of one layout, the guest's loads"
),
match self.imports {
0 => device,
imports => format!(
"{device}, {imports} host imports, {:?} completion",
self.completion
),
}
}
/// `buffers` command buffers of one pass of `draws` masked shapes, which switch between the
/// mask's pipeline state and the gathering mask's ([`Workload::gather`]) at every draw,
/// loading as [`GUEST_LOADS`].
@@ -331,12 +396,20 @@ struct Pipelines {
panel: RenderPipelineState,
}
/// The device, its queue, and what the frames draw with.
/// The device, its queues, and what the frames draw with.
struct Workload {
device: Device,
layers: Layers,
/// The buffers the layers lie over, where they do.
layer_buffers: Vec<Buffer>,
/// The command queues a frame's command buffers are committed on: the first alone, or, in
/// the guest's shape, the second taking every [`SECOND_QUEUE_EVERY`]th.
queues: Vec<CommandQueue>,
/// In the guest's shape, the shared events every command buffer signals at its end with the
/// next value (the guest's FIFO event), and the second queue's command buffers signal too,
/// for every [`PAGING_WAIT_EVERY`]th of the first queue's to wait for first (its paging
/// event), with the values signalled so far.
guest: Option<GuestEvents>,
/// Whether each pass draws its [`REPEATED`] draws again with no call before them.
repeats: bool,
/// A checked run's submissions checked.
@@ -531,6 +604,14 @@ impl Workload {
Workload {
layers,
layer_buffers,
queues: (0..1 + usize::from(guest))
.map(|_| device.new_command_queue().unwrap())
.collect(),
guest: guest.then(|| GuestEvents {
fifo: device.new_shared_event().unwrap(),
paging: device.new_shared_event().unwrap(),
values: Cell::new((0, 0)),
}),
repeats,
checks: checked.then(Arc::default),
pipelines,
@@ -666,23 +747,18 @@ impl Workload {
/// plain frame's).
fn frame_reading(&self, reads: Reads) -> Frame {
let mut frame = Frame::default();
let mut last: Option<CommandBuffer> = None;
// Each queue's last command buffer of the frame.
let mut lasts: Vec<Option<CommandBuffer>> = self.queues.iter().map(|_| None).collect();
let counts = || reads.work_counts.then(|| self.device.work_counts());
let switches = thread_switches();
let cpu = thread_cpu();
let start = Instant::now();
let at_start = counts();
let mut begun = [Begun::default(); 4];
for pass in 0..BUFFERS {
let command_buffer = self.queue.command_buffer().unwrap();
let descriptor = self.pass(pass);
let before = counts();
let (mut encoder, open) = step(reads.instructions, || {
command_buffer.render_command_encoder(&descriptor).unwrap()
});
frame.open.push(open);
if let Some(before) = &before {
begun[0].add(Begun::since(&self.device, before));
let queue = usize::from(
);
let command_buffer = self.queues[queue].command_buffer().unwrap();
if let Some(guest) = &self.guest {
}
for draw in 0..DRAWS {
let before = counts();
@@ -694,11 +770,8 @@ impl Workload {
}
}
}
let before = counts();
let ((), ended) = step(reads.instructions, || encoder.end_encoding().unwrap());
frame.end.push(ended);
if let Some(before) = &before {
begun[2].add(Begun::since(&self.device, before));
if let Some(guest) = &self.guest {
guest.end(&command_buffer, queue);
}
// The consumer makes each command buffer's check before its commit call.
let check = self.checks.as_ref().map(Checks::check);
@@ -722,7 +795,7 @@ impl Workload {
.handed
.push(after.commits_handed_off > before.commits_handed_off);
}
last = Some(command_buffer);
lasts[queue] = Some(command_buffer);
}
frame.begun = begun;
frame.wall = start.elapsed();
@@ -730,11 +803,14 @@ impl Workload {
frame.switches = switches
.zip(thread_switches())
.map(|(before, after)| after.since(before));
let last = last.unwrap();
last.wait_until_completed_for(WAIT).unwrap();
for last in lasts.iter().flatten() {
last.wait_until_completed_for(WAIT).unwrap();
}
frame.done = start.elapsed();
frame.whole = at_start.map(|before| Begun::since(&self.device, &before));
assert_eq!(last.status(), CommandBufferStatus::Completed);
for last in lasts.iter().flatten() {
assert_eq!(last.status(), CommandBufferStatus::Completed);
}
frame
}
}
@@ -1099,8 +1175,14 @@ fn spent_by_group(
/// A device as the consumer makes its own (the module docs), announcing every precision kind at
/// every occurrence where `announced`, into `heard`.
fn device(cache: &ScratchCache, announced: bool, heard: &Heard) -> Device {
fn device(
cache: &ScratchCache,
announced: bool,
heard: &Heard,
completion: CompletionPolicy,
) -> Device {
let mut options = DeviceOptions::default();
options.policy.completion = completion;
options.shader_cache = ShaderCacheOptions::in_directory(cache.path());
options.loader = loader();
options.gpu_times_from_host = true;
@@ -1130,10 +1212,11 @@ fn measure(runs: &[Run]) {
let cache = ScratchCache::new().unwrap();
let heard = Heard::default();
let work = Workload::new(
device(&cache, run.announced, &heard),
device(&cache, run.announced, &heard, run.completion),
run.checked,
run.layers,
);
let _imports = imports(&work.device, run.imports);
let label = run.label();
let name = work.device.name().to_owned();
let ms = |d: Duration| d.as_secs_f64() * 1e3;
@@ -1167,7 +1250,9 @@ fn measure(runs: &[Run]) {
let checks_before = work.checks.as_ref().map_or(0, |checks| checks.count());
let threads_before = other_threads_cpu();
let allocations_before = others_allocations();
let kernel_before = Execbuffers::read();
let frames: Vec<Frame> = (0..TIMED).map(|_| work.frame()).collect();
let kernel = Execbuffers::read();
let allocations = others_allocations();
let threads = other_threads_cpu();
let checks = work.checks.as_ref().map_or(0, |checks| checks.count());
@@ -1292,6 +1377,11 @@ fn measure(runs: &[Run]) {
per_frame(|c| c.command_buffers_submitted),
per_frame(|c| c.command_buffers_submitted) / BUFFERS as f64,
per_frame(|c| c.queue_submissions),
per_frame(|c| c.grouped_submissions),
per_frame(|c| c.batches_grouped),
per_frame(|c| c.finales_folded),
per_frame(|c| c.finales_apart),
);
eprintln!(
"FRAME-COST {name} {label}: a frame's command buffers begun by what for: {:.1} \
encoders' own, {:.1} segments, {:.1} continuations, {:.1} draws' secondaries, {:.1} \
@@ -1308,8 +1398,53 @@ fn measure(runs: &[Run]) {
per_frame(|c| c.command_buffers_replayed),
per_frame(|c| c.command_buffers_replayed_inline),
);
eprintln!(
"FRAME-COST {name} {label}: a frame's groups of batches by what sent them: {:.1} \
full, {:.1} before a wait for a signal held, {:.1} before a batch apart, {:.1} with \
first work, {:.1} with no batch left, {:.1} with checks or steps left, {:.1} with the \
rest held back; {:.1} of them kept for their queue's earlier work, {:.1} of those \
sent by a wait; its batches by the earlier ones of their queue pending as each went: \
{:.1} none, {:.1} one, {:.1} two or three, {:.1} four or more",
per_frame(|c| c.group_ends_full),
per_frame(|c| c.group_ends_wait),
per_frame(|c| c.group_ends_apart),
per_frame(|c| c.group_ends_first_work),
per_frame(|c| c.group_ends_drained),
per_frame(|c| c.group_ends_checks),
per_frame(|c| c.group_ends_held),
per_frame(|c| c.groups_kept_pending),
per_frame(|c| c.groups_sent_for_waits),
per_frame(|c| c.batches_with_none_pending),
per_frame(|c| c.batches_with_one_pending),
per_frame(|c| c.batches_with_two_or_three_pending),
per_frame(|c| c.batches_with_four_or_more_pending),
);
let buffers = (TIMED * BUFFERS) as f64;
eprintln!(
"FRAME-COST {name} {label}: the device's live VkDeviceMemory after the timed frames \
(what ANV on i915 lists in each kernel submission, beside its own buffer objects): \
{} pooled blocks in use, {} empty, {} dedicated, {} host imports, {} dma-buf \
imports of buffers, {} of images",
counts.memory_blocks_live,
counts.empty_memory_blocks_live,
counts.dedicated_memory_blocks_live,
counts.host_imports_live,
counts.dma_buf_memories_live,
counts.dma_buf_image_memories_live,
);
if let (Some(before), Some(after)) = (kernel_before, kernel) {
let execbuffers = after.execbuffers - before.execbuffers;
let each = |count: u64| count as f64 / execbuffers.max(1) as f64;
eprintln!(
"FRAME-COST {name} {label}: the kernel submissions (scripts/i915-execbuffers): \
{:.1} a frame, {:.1} objects each ({:.1} host imports), {:.1} us each in the \
ioctl, {:.3} ms a frame",
execbuffers as f64 / TIMED as f64,
each(after.objects - before.objects),
each(after.userptr - before.userptr),
(after.nanos - before.nanos) as f64 / 1e3 / execbuffers.max(1) as f64,
(after.nanos - before.nanos) as f64 / 1e6 / TIMED as f64,
);
}
let threads = match (&threads_before, &threads) {
(Some(before), Some(after)) => spent_by_group(before, after)
.iter()
@@ -1347,6 +1482,26 @@ fn measure(runs: &[Run]) {
}
}
/// `count` host imports of `device`, each [`IMPORT_BYTES`] over pages of its own, live until
/// dropped: the buffers, then the pages.
fn imports(device: &Device, count: usize) -> Option<(Vec<Buffer>, Mapping)> {
if count == 0 {
return None;
}
let pages = Mapping::anonymous(count * IMPORT_BYTES);
pages.fill(0x5a);
let buffers = (0..count)
.map(|i| {
// SAFETY: the pages are this process's, mapped read and write, and outlive the
// buffers (the tuple's order).
let at = unsafe { pages.pointer().add(i * IMPORT_BYTES) };
// SAFETY: as above.
unsafe { no_copy(device, at, IMPORT_BYTES, ResourceOptions::shared(), None) }.unwrap()
})
.collect();
Some((buffers, pages))
}
/// How often the encoding thread blocked (in its commits too) and was preempted in `frames`, on
/// average, where it was read.
fn blocks<'a>(frames: impl IntoIterator<Item = &'a Frame>) -> String {
@@ -1415,6 +1570,65 @@ fn frame_costs_alternating() {
})]);
}
#[test]
#[ignore = "a measurement, not a check: run by name with --run-ignored all"]
fn frame_costs_over_imports() {
let legs = IMPORTS
.into_iter()
.map(|imports| (imports, false))
.chain([(IMPORTS[1], true)]);
let runs: Vec<Run> = legs
.flat_map(|(imports, guest)| {
[CompletionPolicy::Grouped, CompletionPolicy::Exact]
.repeat(2)
.into_iter()
.map(move |completion| Run::over_imports(imports, completion, guest))
})
.collect();
measure(&runs);
}
/// The guest's events in a run in its shape ([`Workload::guest`]).
struct GuestEvents {
fifo: SharedEvent,
paging: SharedEvent,
/// The last values signalled to each.
values: Cell<(u64, u64)>,
}
impl GuestEvents {
/// Before its encoders: every command buffer carries a submission handler, as the consumer's
/// queue gives each one, and every [`PAGING_WAIT_EVERY`]th of the first queue waits for the
/// paging event's last value.
fn begin(&self, command_buffer: &CommandBuffer, queue: usize, pass: usize) {
command_buffer
.add_submission_handler(Box::new(|_: &CommandBuffer| {}))
.unwrap();
let (_, paging) = self.values.get();
if queue == 0 && pass % PAGING_WAIT_EVERY == PAGING_WAIT_EVERY / 2 && paging > 0 {
command_buffer
.encode_wait_for_event(EventRef::from(&self.paging), paging)
.unwrap();
}
}
/// After its encoders: every command buffer signals the FIFO event's next value, the second
/// queue's the paging event's next one first.
fn end(&self, command_buffer: &CommandBuffer, queue: usize) {
let (fifo, mut paging) = self.values.get();
if queue == 1 {
paging += 1;
command_buffer
.encode_signal_event(EventRef::from(&self.paging), paging)
.unwrap();
}
command_buffer
.encode_signal_event(EventRef::from(&self.fifo), fifo + 1)
.unwrap();
self.values.set((fifo + 1, paging));
}
}
#[test]
#[ignore = "a measurement, not a check: run by name with --run-ignored all"]
fn frame_costs_over_buffers() {
@@ -1431,7 +1645,11 @@ fn frame_costs_over_buffers() {
fn counted() -> (String, Frame) {
let cache = ScratchCache::new().unwrap();
let heard = Heard::default();
let work = Workload::new(device(&cache, false, &heard), false, Layers::Private);
let work = Workload::new(
device(&cache, false, &heard, CompletionPolicy::default()),
false,
Layers::Private,
);
for _ in 0..WARM {
work.frame();
}
@@ -1499,11 +1717,20 @@ fn a_frame_s_draws_and_pass_ends_allocate_within_their_bounds() {
/// its draws' secondary never begun. By what they were begun for
/// (`WorkCounts::command_buffers_begun_encoders` and kin), the encoders' are each command
/// buffer's one encoder's own and their draws' secondaries, and the device's own submissions begin
/// none. Each command buffer's one batch counts once by the earlier batches of its queue pending
/// as it went (`WorkCounts::batches_with_none_pending` and kin). Each group kept for its queue's
/// earlier work (`WorkCounts::groups_kept_pending`) went within the frame, counted once among the
/// groups by what sent them, and only a kept one counts as sent by a wait
/// (`WorkCounts::groups_sent_for_waits`).
#[test]
fn a_frame_s_passes_and_commits_begin_their_command_buffers_within_their_bound() {
let cache = ScratchCache::new().unwrap();
let heard = Heard::default();
let work = Workload::new(device(&cache, false, &heard), false, Layers::Private);
let work = Workload::new(
device(&cache, false, &heard, CompletionPolicy::default()),
false,
Layers::Private,
);
// Every pipeline made, and every pool piece done, before the frame that counts.
for _ in 0..WARM {
work.frame();
@@ -1583,6 +1810,35 @@ fn a_frame_s_passes_and_commits_begin_their_command_buffers_within_their_bound()
0,
"the device's own submissions began command buffers"
);
// Each command buffer's one batch counted once by the earlier batches pending as it went.
let by_pending = begun(|c| c.batches_with_none_pending)
+ begun(|c| c.batches_with_one_pending)
+ begun(|c| c.batches_with_two_or_three_pending)
+ begun(|c| c.batches_with_four_or_more_pending);
assert_eq!(
by_pending, passes,
"batches counted by the earlier ones pending"
);
let ends = begun(|c| c.group_ends_full)
+ begun(|c| c.group_ends_wait)
+ begun(|c| c.group_ends_apart)
+ begun(|c| c.group_ends_first_work)
+ begun(|c| c.group_ends_drained)
+ begun(|c| c.group_ends_checks)
+ begun(|c| c.group_ends_held);
let (kept, sent) = (
begun(|c| c.groups_kept_pending),
begun(|c| c.groups_sent_for_waits),
);
eprintln!(
"FRAME-COST {}: {ends} groups went, {kept} kept for their queue's earlier work, {sent} \
of those sent by a wait",
work.device.name()
);
assert!(
kept <= ends && sent <= kept,
"{kept} groups kept and {sent} sent by a wait, of {ends} that went"
);
// The frame's batches' submissions, on whichever thread made them.
let own = whole.all - whole.encoder - whole.kept;
match late_reads {
@@ -1628,7 +1884,11 @@ fn a_frame_s_pass_opens_allocate_within_their_bound() {
fn a_frame_s_commits_allocate_within_their_bound() {
let cache = ScratchCache::new().unwrap();
let heard = Heard::default();
let work = Workload::new(device(&cache, false, &heard), true, Layers::Private);
let work = Workload::new(
device(&cache, false, &heard, CompletionPolicy::default()),
true,
Layers::Private,
);
// Every pipeline made, and every pool piece done, before the frames that count.
for _ in 0..WARM {
work.frame();
@@ -66,6 +66,10 @@ fn a_buffer_released_behind_work_that_reads_device_addresses_fails_none_of_it()
long.commit().unwrap();
behind.commit().unwrap();
let deadline = Instant::now() + WAIT;
// Scheduled once the CPU finished scheduling it (`kernelEndTime`): submitted, or,
// under `CompletionPolicy::Grouped` on a driver that merges submissions, held for one
// with later batches; a driver with the defect (MoltenVK) merges none. Its kernel
// start is stored as scheduling begins, before its batch is replayed and submitted.
while behind.kernel_end_time() == 0.0 {
assert!(
Instant::now() < deadline,
@@ -58,12 +58,13 @@
//! and its queue's command buffers in order (Metal's overlaps counted and printed; the runtime's
//! none).
use super::commit_work::orders_by_ends;
use super::degrade_notices::{assert_once, counts, FROM_HOST, GPU_TIMES, UNTIMED};
use super::presenting::Adopted;
use super::{validated_device, validated_device_with, Messages, ScratchCache};
use crate::gpu::TEST_DEVICE;
use ash::vk;
use metal2vulkan::device::DriverFact;
use metal2vulkan::device::{BatchOrderPolicy, DriverFact};
use metal2vulkan::error::{Feature, RuntimeDriverDefect};
use metal2vulkan_runtime::{
host_time, CommandBuffer, CommandQueue, Degradation, Device, Error, EventRef, ResourceOptions,
@@ -511,13 +512,34 @@ fn command_buffers_one_after_another_are_each_timed_on_their_own() {
/// M3 Max under macOS 27.0.1: 0.5 to 0.9 us after it, 10 of 10). Where the first encoder writes
/// the start ([`starts_in_the_first_encoder`]), every first started in its fill's command buffer
/// and at least one second did not (`WorkCounts::prefixed_starts`, printed); elsewhere none did.
/// The validation layer reported nothing.
/// The validation layer reported nothing. Under `BatchOrderPolicy::Exact`; the default's is
/// [`a_start_behind_work_of_batches_ordered_by_their_ends_follows_it`].
#[test]
fn a_start_behind_a_planned_barrier_follows_the_work_before_it() {
start_behind_work(BatchOrderPolicy::Exact);
}
/// The same under the default. Where the device orders batches by their ends (the runtime's
/// `batch_order.rs`), the second plans no barrier for the first's writes, as the first's end
/// orders it, and its fill's own command buffer writes its start at the bottom of the pipe, once
/// every command before it completed: every first and every second started in its fill's command
/// buffer where the first encoder writes the start, and each second no earlier than the first
/// ended. Elsewhere as under `BatchOrderPolicy::Exact`.
#[test]
fn a_start_behind_work_of_batches_ordered_by_their_ends_follows_it() {
start_behind_work(BatchOrderPolicy::Ends);
}
/// The two tests above under `batch_order`.
fn start_behind_work(batch_order: BatchOrderPolicy) {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
{
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.policy.batch_order = batch_order;
})
.unwrap();
let by_ends = orders_by_ends(&device, batch_order);
let venue = Venue::of(&device);
if venue.bits == 0 || from_host_by_driver(&device) {
eprintln!(
@@ -587,13 +609,18 @@ fn a_start_behind_a_planned_barrier_follows_the_work_before_it() {
let after_rounds = device.work_counts();
let prefixed = after_rounds.prefixed_starts - before_rounds.prefixed_starts;
eprintln!(
"runtime gpu times: {}: {BEHIND_ROUNDS} pairs, the second behind the first: {prefixed} \
started by their fill's own command buffer",
"runtime gpu times: {} {batch_order:?}: {BEHIND_ROUNDS} pairs, the second behind the \
first: {prefixed} started by their fill's own command buffer",
device.name()
);
match starts_in_the_first_encoder(&device) {
false => assert_eq!(prefixed, 0),
true => assert!(
match (starts_in_the_first_encoder(&device), by_ends) {
(false, _) => assert_eq!(prefixed, 0),
(true, true) => assert_eq!(
prefixed,
2 * BEHIND_ROUNDS as u64,
"started by their fill's command buffer: every first and every second"
),
(true, false) => assert!(
(BEHIND_ROUNDS as u64..2 * BEHIND_ROUNDS as u64).contains(&prefixed),
"{prefixed} started by their fill's command buffer: every first, and not every \
second"
File diff suppressed because it is too large. Load diff
@@ -1 +1,5 @@
// Scheduled once the CPU finished scheduling it (`kernelEndTime`): submitted, or held
// for its pass's kernel submission (`CompletionPolicy::Grouped`), which the sleep
// below outlasts. Its kernel start is stored as scheduling begins, before its batch is
// replayed and submitted.
while command_buffer.kernel_end_time() == 0.0 {
@@ -3,6 +3,19 @@
//! and `error` reads wait for no GPU work and for no submission in progress.
//!
//! GPU busy work is committed first (`first_use::Busy`, released by the test), then on the same
//! queue one blit encoder of fills of distinct words, whose submission replays its deferred command
//! buffer (`recorder`) between its kernel start and its kernel end; its fills are doubled until
//! that span is at least [`LONG_SUBMISSION`]. One thread reads the two kernel times over and over,
//! from the commit until [`BEHIND_BUSY`] after the submission, while the fills wait behind the busy
//! work, and another reads `status` and `error` over the same time, each between a read of the
//! kernel start and a read of the kernel end. The submission may come only as the busy work drains:
//! where no kernel end was read [`HELD_READS`] after the commit, the reading thread releases the
//! busy work, and the reads go on until the submission, however late. The claim is structural: each
//! thread's reads land inside the submission, some answering between a kernel start and no kernel
//! end yet, where a read that waited for the submission returns only after its kernel end. And each
//! read is timed: at most one in a thousand of each thread's takes [`SLOW_READ`] or more, a bound a
//! host that preempts the reading thread now and then keeps, which no longest read is on a loaded
//! Mac (`PROPERTY-READS`).
//!
//! And `status` reads `Completed` before anything else shows the completion, as Metal's does: in
//! the command buffer's completed handler, once its `wait_until_completed` returned, and in the
@@ -11,6 +24,9 @@
use super::first_use::{release, Busy};
use super::host_memory::{no_copy, not_importable, on_device, Mapping, GUEST_PAGE};
use metal2vulkan_runtime::{
Buffer, CommandBuffer, CommandBufferStatus, Deallocator, ResourceOptions,
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -29,6 +45,12 @@ const LONG_SUBMISSION: Duration = Duration::from_millis(40);
/// How long the reads go on once the command buffer is submitted, its work behind the busy work.
const BEHIND_BUSY: Duration = Duration::from_millis(100);
/// How long after the commit the reads go on with the busy work held where no kernel end was read
/// by then; the reading thread then releases it. On the Radeon 780M (RADV) beside the full suite,
/// the fills' kernel end came 1007.5 ms after their kernel start, once the test released the busy
/// work after a second of reads; alone, and as six copies at once, they were submitted 3 to 80 ms
/// after their commit.
const HELD_READS: Duration = Duration::from_millis(100);
/// A slow read: a quarter of [`LONG_SUBMISSION`]. On the M3 Max beside the full suite, a reading
/// thread's longest reads took 20 to 54 ms each round, of over a million reads, the thread
@@ -50,6 +72,9 @@ struct Reads {
inside: usize,
/// When, after the commit, a read first answered a kernel end (the kernel times' thread).
submitted: Option<Duration>,
/// The kernel times' thread released the busy work, no kernel end read [`HELD_READS`] after
/// the commit.
released: bool,
}
impl Reads {
@@ -69,6 +94,9 @@ impl Reads {
}
/// Read `command_buffer`'s kernel times over and over from `committed` on, until [`BEHIND_BUSY`]
/// after a read first answered its kernel end, or [`WAIT`] after `committed` where none did;
/// releasing the busy work of `words` where none did [`HELD_READS`] after `committed`.
fn read(command_buffer: &CommandBuffer, committed: Instant, words: &Buffer) -> Reads {
let mut reads = Reads::default();
loop {
let before = Instant::now();
@@ -83,6 +111,11 @@ impl Reads {
let since = after.duration_since(committed);
match reads.submitted {
None if end != 0.0 => reads.submitted = Some(since),
None if since >= WAIT => return reads,
None if since >= HELD_READS && !reads.released => {
release(words);
reads.released = true;
}
Some(submitted) if since >= submitted + BEHIND_BUSY => return reads,
_ => {}
}
@@ -90,8 +123,11 @@ impl Reads {
}
/// Read `command_buffer`'s `status` and `error` over and over, each pair between a read of the
/// kernel start and one of the kernel end, until `done`, or until [`WAIT`] and [`BEHIND_BUSY`]
/// after `committed`.
fn read_status(command_buffer: &CommandBuffer, committed: Instant, done: &AtomicBool) -> Reads {
let mut reads = Reads::default();
while !done.load(Ordering::Acquire) && committed.elapsed() < WAIT + BEHIND_BUSY {
let start = command_buffer.kernel_start_time();
let before = Instant::now();
let _ = command_buffer.status();
@@ -131,6 +167,7 @@ fn property_reads_wait_for_no_submission_and_no_busy_work() {
let done = AtomicBool::new(false);
let (reads, status) = std::thread::scope(|scope| {
let reader = scope.spawn(|| {
let reads = read(&command_buffer, committed, &words);
done.store(true, Ordering::Release);
reads
});
@@ -149,8 +186,12 @@ fn property_reads_wait_for_no_submission_and_no_busy_work() {
let ms = |d: Duration| d.as_secs_f64() * 1e3;
eprintln!(
"PROPERTY-READS {name}: {fills} fills, kernel span {:.1} ms, submitted {:?} after \
the commit (the busy work released first: {}); {} kernel time reads, {} inside \
the submission, {} slow, the longest {:.3} ms; {} status and error reads, {} \
inside, {} slow, the longest {:.3} ms",
ms(span),
reads.submitted,
reads.released,
reads.count,
reads.inside,
reads.slow,
@@ -162,6 +203,7 @@ fn property_reads_wait_for_no_submission_and_no_busy_work() {
);
assert!(
reads.submitted.is_some(),
"the fills were not submitted within {WAIT:?} of their commit: {reads:?}"
);
if span < LONG_SUBMISSION && fills < MOST_FILLS {
fills *= 2;
@@ -356,12 +356,117 @@ fn a_checked_command_buffer_committed_during_a_submission_is_submitted_promptly(
completed(&[&first, &submitting, &left]);
let after = left.kernel_end_time() - free;
assert!(
after < PROMPTLY.as_secs_f64(),
"submitted {after:.4} s after the VkQueue was free, on {}",
device.name()
device.name(),
left.kernel_end_time() - left.kernel_start_time()
);
// In commit order: each copied the number the one before it filled.
let ran = read_buffer(&seen, 0, 12).unwrap();
assert_eq!(ran, [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]);
});
}
/// How many rounds [`checked_commits_during_submissions_are_taken_up_promptly`] runs.
const ROUNDS: usize = 40;
/// run, as the consumer's queue gives every command buffer.
let command_buffer = numbered(queue, tracked, seen, number);
command_buffer
.add_submission_handler(Box::new(|_: &CommandBuffer| {}))
.unwrap();
command_buffer
}
/// What one round of [`checked_commits_during_submissions_are_taken_up_promptly`] saw of the two
#[derive(Debug)]
struct Round {
/// How long after the `VkQueue` was free the scheduler's thread took up each (its kernel
taken_up: [f64; 2],
/// How long each one's own submission took, from its kernel start to its kernel end.
submissions: [f64; 2],
/// The thread's sleeps that ended at their time limit between the `VkQueue`'s release and the
/// later kernel start.
slept: u64,
}
/// One round of [`checked_commits_during_submissions_are_taken_up_promptly`].
fn taken_up(device: &Device, queue: &CommandQueue) -> Round {
let tracked = buffer_with(device, &[0; 4]).unwrap();
let seen = buffer_with(device, &[0xff; 16]).unwrap();
let left = [
];
// The scheduler's thread checks and submits it, then sleeps afresh, its pass over.
first.commit().unwrap();
first.wait_until_scheduled().unwrap();
std::thread::sleep(Duration::from_millis(5));
let (held, holding) = mpsc::channel();
let (release, released) = mpsc::channel::<()>();
let holder = {
let queue = queue.clone();
std::thread::spawn(move || {
// SAFETY: the closure keeps no handle and calls nothing of the runtime's; it waits
// only for this round's release.
unsafe {
queue.with_vk_queue(|_, _| {
held.send(()).unwrap();
let _ = released.recv_timeout(WAIT);
})
}
})
};
holding.recv_timeout(WAIT).unwrap();
submitting.commit().unwrap();
// The scheduler thread's pass runs the check, then waits for the `VkQueue` under the
// scheduler's lock.
std::thread::sleep(Duration::from_millis(20));
for command_buffer in &left {
command_buffer.commit().unwrap();
}
let slices = || device.work_counts().scheduler_sleep_slices;
let before = slices();
let free = host_time();
release.send(()).unwrap();
holder.join().unwrap();
// Read the thread's sleeps as soon as the later one is taken up: a sleep that ended at its
// limit takes 100 ms, and these reads take microseconds.
let deadline = std::time::Instant::now() + WAIT;
while left[1].kernel_start_time() == 0.0 {
assert!(
std::time::Instant::now() < deadline,
"the later command buffer was not taken up"
);
std::hint::spin_loop();
}
let slept = slices() - before;
completed(&[&first, &submitting, &left[0], &left[1]]);
// In commit order: each copied the number the one before it filled.
let ran = read_buffer(&seen, 0, 16).unwrap();
assert_eq!(ran, [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]);
Round {
submissions: (left.each_ref()).map(|c| c.kernel_end_time() - c.kernel_start_time()),
slept,
}
}
/// [`ROUNDS`] times, every command buffer carrying a submission handler and a check (as the
/// consumer's queue gives every one), and two committed while the scheduler's thread waits for
/// the `VkQueue` to submit another: each time, the thread takes up both (runs their checks and
#[test]
fn checked_commits_during_submissions_are_taken_up_promptly() {
on_device(|device, _| {
let queue = device.new_command_queue().unwrap();
let rounds: Vec<_> = (0..ROUNDS).map(|_| taken_up(device, &queue)).collect();
let most =
|of: fn(&Round) -> [f64; 2]| (rounds.iter().flat_map(of)).fold(f64::MIN, f64::max);
let slept: u64 = rounds.iter().map(|round| round.slept).sum();
eprintln!(
"TAKEN-UP {}: {ROUNDS} rounds, taken up at most {:.3} ms after the VkQueue was free, \
device.name(),
);
for (number, round) in rounds.iter().enumerate() {
assert!(
"round {number} on {}: {round:?}",
device.name()
);
}
});
}
@@ -2,12 +2,13 @@
//! extension) and of `wait_until_scheduled`'s answer, on the device the cfg selects, under the
//! validation layer.
//!
//! A submission handler runs once the command buffer's last batch reached its `VkQueue`, on the
//! A submission handler runs once the scheduler took the command buffer's last batch for its
//! `VkQueue` (submitted it, or held it for one kernel submission with later ones), on the
//! device's scheduler thread, which makes every submission (`commit` returns at once and submits
//! nothing), before the command buffer is `Scheduled`: once the commit is taken in where its waits
//! are met, once an event the host raised releases it, and once another command buffer's GPU signal
//! that releases it is submitted. Never for a command buffer that fails before its last batch is
//! submitted.
//! taken.
//!
//! Metal's answers (EV SUB-sched1-m4: an M4, macOS 27.0.1): `commit` returns before the command
//! buffer is scheduled, on Metal's own thread; its status reads `Scheduled` just before its first
+3 -2
View File
@@ -66,8 +66,9 @@ pub use enables::{EnableSet, Exposure};
pub(crate) use mechanism::mechanism;
pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd};
pub use policy::{
ContainmentPolicy, DevicePolicy, FloatMathsPolicy, HalfBlendPolicy, HalfRoundingPolicy,
NanMinMaxPolicy, PaddedReadsPolicy, RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy,
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DecodedTexelsPolicy, DevicePolicy,
FloatMathsPolicy, HalfBlendPolicy, HalfRoundingPolicy, HeapCompressionPolicy, NanMinMaxPolicy,
ResolvePolicy, RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, TileStorePolicy,
Unorm8LinearFilterPolicy, YCbCrFilterPolicy,
};
pub(crate) use profile::whole_point_size;
+79 -6
View File
@@ -3,10 +3,12 @@
use crate::device::profile::{FramebufferFetchPolicy, GuestIsolation, HandleDomain, PointerDomain};
/// Policy inputs of `Device::new`. Every field but `padded_reads` can change emitted code, so the
/// profile carries it (containment as the encoding it selects) and its fingerprint covers it;
/// `padded_reads` is the runtime's alone (how it makes a texture over a buffer), and no profile
/// carries it.
/// `completion`, `tile_store`, `resolve` and `batch_order` can change emitted code, so the profile
/// carries it (containment as the encoding it selects) and its fingerprint covers it; those six
/// are the runtime's alone (the texels of a carried texture's decoded twin, a heap's compressed
/// texture's image, when the host sees a command buffer complete, what a render pass's load leaves
/// in the texels its draws do not write, how a multisampled color attachment resolves, and how a
/// batch begins after the earlier ones of its queue), and no profile carries them.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
@@ -67,12 +69,22 @@ pub struct DevicePolicy {
/// default) or one the driver keeps uncompressed in the heap's bytes. The runtime's choice
/// alone: no emitted code changes.
pub heap_compression: HeapCompressionPolicy,
/// Whether command buffers committed on one `VkQueue` that the runtime's scheduler finds ready
/// together go to the driver in one kernel submission, each seen complete once the last of
/// them completed (the default, on a driver that merges such submissions), or each in a
/// submission of its own, seen complete at its own end. The runtime's choice alone: no
/// emitted code changes.
pub completion: CompletionPolicy,
/// Whether a render pass that loads a signed normalized or `RGB9E5Float` color attachment and
/// draws keeps the texels its draws do not write as the device's load and store leave them
/// (the default), or as Metal's tile store writes them back in the tiles a draw reaches. The
/// runtime's choice alone: no emitted code changes.
pub tile_store: TileStorePolicy,
/// Whether a batch of command buffers on one `VkQueue` begins after the batches before it
/// there by their ends (the default, on a driver measured to run no two kernel submissions of
/// one queue side by side), or by a barrier for each access that depends on theirs. The
/// runtime's choice alone: no emitted code changes.
pub batch_order: BatchOrderPolicy,
}
impl DevicePolicy {
@@ -81,8 +93,8 @@ impl DevicePolicy {
/// emulation runs, native device sampling (a two-plane YCbCr texture's samples among them),
/// native device maths, the device's own texel
/// conversions, native half rounding, the device's NaN and minimum and maximum, the device's
/// rounding order, the device's blend of a `half` output into a 16-bit float attachment, and
/// an image over a texture's padded rows where the texture only reads.
/// attachment, the device's resolve of a multisampled color attachment, and batches of one
/// queue ordered by their ends where the driver runs them one after another.
pub const UNTRUSTED: DevicePolicy = DevicePolicy {
pointer_domain: PointerDomain::ResidentTable,
handle_domain: HandleDomain::Table,
@@ -100,7 +112,9 @@ impl DevicePolicy {
half_blend: HalfBlendPolicy::Device,
decoded_texels: DecodedTexelsPolicy::Compact,
heap_compression: HeapCompressionPolicy::Compressed,
completion: CompletionPolicy::Grouped,
tile_store: TileStorePolicy::Device,
batch_order: BatchOrderPolicy::Ends,
};
/// This policy with Metal's answer wherever the choices offer it: its maths functions,
@@ -110,6 +124,9 @@ impl DevicePolicy {
/// ([`RoundingOrderPolicy::Exact`]), its 16-bit float blend of a `half` output
/// ([`HalfBlendPolicy::Exact`]), its filter of a two-plane YCbCr texture
/// as written ([`HeapCompressionPolicy::Uncompressed`]), each command buffer seen complete
/// store leaves them ([`TileStorePolicy::Exact`]), its multisample color resolve
/// ([`ResolvePolicy::Exact`]), and each batch ordered after the earlier ones of its queue by
/// the accesses it depends on alone ([`BatchOrderPolicy::Exact`]). Sampling and every other
/// field are kept.
pub const fn exact_answers(self) -> DevicePolicy {
DevicePolicy {
@@ -122,7 +139,9 @@ impl DevicePolicy {
half_blend: HalfBlendPolicy::Exact,
decoded_texels: DecodedTexelsPolicy::Exact,
heap_compression: HeapCompressionPolicy::Uncompressed,
completion: CompletionPolicy::Exact,
tile_store: TileStorePolicy::Exact,
batch_order: BatchOrderPolicy::Exact,
..self
}
}
@@ -451,6 +470,36 @@ pub enum HeapCompressionPolicy {
Uncompressed,
}
/// When the host sees a command buffer complete, on a driver that merges a submission signalling
/// nothing into the next one in the same `vkQueueSubmit` (Mesa's common queue,
/// `vk_queue_submits_merge`: ANV, RADV, lavapipe, NVK, Turnip and the other Mesa drivers of a kernel
/// submission), where each kernel submission costs CPU time for every `VkDeviceMemory` of the
/// device (ANV on i915 lists each in every execbuffer). Elsewhere every command buffer goes in a
/// submission of its own under either value. The runtime's choice alone: no emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CompletionPolicy {
/// Up to four batches of command buffers on one `VkQueue` that the scheduler finds ready
/// together, none of which signals a binary semaphore, takes a fence, moves the caller's
/// images or does first work, and none but the first of which waits for anything not seen
/// complete, go in one `vkQueueSubmit`, and only the last signals, the queue's timeline and
/// every event they signal (the default): one kernel submission for all of them. The commands,
/// their barriers and their GPU times are unchanged; each but the last is seen complete (its
/// status, handlers and waits) once the last completed, and an event's values they signal are
/// reached then, late by the GPU time of the batches after it, never early and in commit
/// order. The submission checks of up to three batches right behind a queue's next batch run
/// with its own, in commit order, so checked command buffers are found ready together: such a
/// check runs before the previous batch's submission rather than after it. Announced
/// `grouped-completion` at the first such submission.
#[default]
Grouped,
/// Each batch in a submission of its own that signals its own values, so each command buffer
/// is seen complete, and its event signals land, at its own end, as Metal's are; each batch's
/// submission checks run once the batch before it was submitted.
Exact,
}
/// What a render pass that loads a single-sampled color attachment of a signed normalized format
/// (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`) or of
/// `RGB9E5Float`, stores it and draws leaves in the texels its draws do not write. An Apple GPU
@@ -478,4 +527,28 @@ pub enum TileStorePolicy {
/// [`Device`](Self::Device).
Exact,
}
/// How a batch of command buffers on one `VkQueue` (the work the runtime submits for a command
/// buffer between its event waits and signals) begins after the earlier batches there. Metal
/// orders a command buffer after the earlier ones of its queue only where its work depends on
/// theirs, so an independent one may run beside the one before it; it writes its `GPUStartTime`
/// as its work begins. The runtime's choice alone: no emitted code changes.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BatchOrderPolicy {
/// By their ends (the default) on a driver measured to run no two kernel submissions of one
/// queue side by side, with or without a barrier between them, where it runs the same work
/// recorded in one command buffer side by side (ANV, RADV and NVIDIA's driver): every batch
/// ends with a barrier that orders all its commands before every command after it on its
/// queue, so a later batch plans no barrier for the accesses of earlier ones, and its first
/// encoder's GPU start time is written once the work before it ended, at the bottom of the
/// pipe. Each batch then still starts once the one before it ended, as those drivers start it
/// anyway. On any other driver, as [`Exact`](Self::Exact).
#[default]
Ends,
/// A barrier at a batch's start for each access that depends on an earlier batch's, as for
/// the accesses within a batch, and its first encoder's GPU start time written as it begins,
/// at the top of the pipe, where the driver may run it beside the batch before it.
Exact,
}
+46 -2
View File
@@ -7,8 +7,9 @@
//! classed, and so reaches the ledger.
use crate::device::{
DevicePolicy, FloatMathsPolicy, FramebufferFetchPolicy, HalfBlendPolicy, HalfRoundingPolicy,
NanMinMaxPolicy, PaddedReadsPolicy, RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy,
BatchOrderPolicy, CompletionPolicy, DecodedTexelsPolicy, DevicePolicy, FloatMathsPolicy,
HalfBlendPolicy, HalfRoundingPolicy, HeapCompressionPolicy, NanMinMaxPolicy, ResolvePolicy,
RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, TileStorePolicy,
Unorm8LinearFilterPolicy, YCbCrFilterPolicy,
};
use crate::pipeline::PrecisionNote;
@@ -69,9 +70,13 @@ fn choices() -> Vec<Choice> {
nan_and_min_max: _,
rounding_order: _,
half_blend: _,
// tile store, a multisampled color attachment's resolve, and how a batch begins after the
// earlier ones of its queue.
decoded_texels: _,
heap_compression: _,
completion: _,
tile_store: _,
batch_order: _,
} = p;
vec![
choice!(p.framebuffer_fetch: FramebufferFetchPolicy { RequireOrdered, AcceptUnordered }),
@@ -86,7 +91,9 @@ fn choices() -> Vec<Choice> {
choice!(p.half_blend: HalfBlendPolicy { Device, Exact }),
choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }),
choice!(p.heap_compression: HeapCompressionPolicy { Compressed, Uncompressed }),
choice!(p.completion: CompletionPolicy { Grouped, Exact }),
choice!(p.tile_store: TileStorePolicy { Device, Exact }),
choice!(p.batch_order: BatchOrderPolicy { Ends, Exact }),
]
}
@@ -400,6 +407,24 @@ fn the_runtime_s_heap_compression_choice_keys_no_profile() {
}
}
/// The runtime's choice of when the host sees a command buffer complete (`completion`) moves no
/// committed profile's fingerprint: no profile carries it, so no translation follows it.
#[test]
fn the_runtime_s_completion_choice_keys_no_profile() {
use crate::spirv::testing::committed_profiles_with;
let grouped = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles");
let exact = committed_profiles_with(DevicePolicy {
completion: CompletionPolicy::Exact,
..DevicePolicy::UNTRUSTED
})
.expect("profiles");
assert_eq!(grouped.len(), exact.len());
for ((stem, g), (other, e)) in grouped.iter().zip(&exact) {
assert_eq!(stem, other);
assert_eq!(g.fingerprint(), e.fingerprint(), "{stem}");
}
}
/// The runtime's choice of a loaded attachment's tile store (`tile_store`) moves no committed
/// profile's fingerprint: no profile carries it, so no translation follows it.
#[test]
@@ -418,6 +443,25 @@ fn the_runtime_s_tile_store_choice_keys_no_profile() {
}
}
/// The runtime's choice of how a batch begins after the earlier ones of its queue
/// (`batch_order`) moves no committed profile's fingerprint: no profile carries it, so no
/// translation follows it.
#[test]
fn the_runtime_s_batch_order_choice_keys_no_profile() {
use crate::spirv::testing::committed_profiles_with;
let ends = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles");
let exact = committed_profiles_with(DevicePolicy {
batch_order: BatchOrderPolicy::Exact,
..DevicePolicy::UNTRUSTED
})
.expect("profiles");
assert_eq!(ends.len(), exact.len());
for ((stem, e), (other, x)) in ends.iter().zip(&exact) {
assert_eq!(stem, other);
assert_eq!(e.fingerprint(), x.fingerprint(), "{stem}");
}
}
/// The runtime's choice of a carried texture's decoded twin (`decoded_texels`) moves no committed
/// profile's fingerprint: no profile carries it, so no translation follows it.
#[test]
+2
View File
@@ -231,7 +231,9 @@ surface! {
enum HalfBlendPolicy N;
enum DecodedTexelsPolicy N;
enum HeapCompressionPolicy N;
enum CompletionPolicy N;
enum TileStorePolicy N;
enum BatchOrderPolicy N;
struct DeviceProfile O;
struct SpirvValidation N;
struct EnabledCaps N;
+30 -1
View File
@@ -103,6 +103,18 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`:
`tile_store = TileStorePolicy::Exact`, which `exact_answers()` selects, rewrites them before
the pass as Metal's store leaves them, through the extended-range attachments' load pass. On
MoltenVK the pass is a Metal pass and stores them as Metal's under either value.
- **Batches of a queue ordered by their ends** (`BatchOrderPolicy::Ends`, the runtime's choice; no
pipeline differs). On ANV, RADV and NVIDIA's driver, each measured to start no kernel submission
of a `VkQueue` before the one before it completed, each batch of command buffers ends with a
barrier ordering its work before every later command of its `VkQueue`: a batch that depends on
an earlier one there begins with no barrier of its own, and a command buffer's GPU start is
taken once the work before it completed, which is when such a driver starts it. Nothing is
announced: on those drivers the work's order, its results and its GPU times are the same under
either value. `batch_order = BatchOrderPolicy::Exact`, which `exact_answers()` selects, orders
each batch after the earlier ones of its queue only by its work's dependencies on theirs, as
Metal does (an M3 Max starts an independent command buffer committed behind running work while
that work runs), and takes a command buffer's GPU start as its work begins. Every other driver
takes that form under either value.
Loops run as written: no execution bound is translated in.
@@ -1326,7 +1338,9 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
the texture's own image before its store action was known, the pass executes render commands,
or the device copies no image of the format) does the pass render in place, announced so. Cost:
the attachment's texels after the pass are each its earlier texel or the one the pass rendered,
both Metal's answers, but not always the one Metal's tiler keeps.
both Metal's answers, but not always the one Metal's tiler keeps. Within Metal's contract:
`MTLStoreAction.dontCare` lets the GPU leave arbitrary data ("You need to assume that GPU
discarded the texture's contents").
- `metal2vulkan-degrade-dont-care-load-tiles` (precision). `DontCareLoadTiles`: An attachment loaded
with `DontCare` and stored, in a pass that draws, is cleared before the draws to zero (a color) or
its clear value (depth, stencil) over the render area and the tiles past it a clear reaches, where
@@ -1966,6 +1980,21 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
it is freed: not announced.
Cost: the deallocator runs once every such command buffer lets go of the pages, or those batches
complete, where Metal's runs at the release; the pages stay mapped until then.
- `metal2vulkan-degrade-grouped-completion` (precision). `GroupedCompletion`: Batches of command
buffers committed on one queue that the scheduler found ready together, or held while two or more
earlier submissions of their queue ran, went to the driver in one `vkQueueSubmit`, only the last
signalling its queue's timeline and their events (`CompletionPolicy::Grouped`, the default, on a
driver whose queue merges a submission that signals nothing into the next one: Mesa's drivers):
one kernel submission for up to four batches, where each kernel submission costs CPU time for
every `VkDeviceMemory` of the device. Announced once per device, on the scheduler's thread. Cost:
each command buffer of the submission but the last is seen complete (its status, completed
handlers and waits), and the event values it signals are reached, once the last completed, late by
the GPU time of the batches after it, at most three, never early and in commit order, and a
submission held while earlier ones of its queue ran late besides by any gap between the last of
those and its own start on the GPU, at most a completion turn's reaction and its vkQueueSubmit;
and the submission checks of the batches behind a queue's next one run with its own, before the
batch before them is submitted; their commands, barriers and GPU times are unchanged;
`CompletionPolicy::Exact` submits and checks each batch alone.
- `metal2vulkan-degrade-misplaced-notice` (performance). `MisplacedNotice`: In a build without debug
assertions, a notice announced where the runtime's rule announces none (`DegradeNotice::misplaced`
names its kind and `NoticePlace`): inside a pipeline pool's piece, or, for a kind announced at
+4
View File
@@ -47,6 +47,10 @@ a cell that names another source took its numbers there.
| A bicubic sample of an 8- or 16-bit normalized texture sums its taps exactly and rounds half up; Metal truncates its row terms, row sums and column terms first. Every device. | The exact sum (no switch) | **Not built yet:** Metal's datapath is pinned (17.75M lanes measured, no miss); its emitter is not written | One grid step (1/4080 at 8 bits) within about 2^-21 of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | Not measured (Metal's form is expected no larger) |
| A bicubic sample of an extended-range texture (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their sRGB twins) sums its taps' steps exactly, rounds half up and clamps into the format's decoded endpoints; within 0.014 of a grid step of a rounding tie Metal may round the other way. Every device. | The exact sum (no switch) | **None known:** no model of Metal's datapath tried fits; 3,317,760 lanes measured on the M3 Max (macOS 26.7) | One grid step (1/8160 a color lane, 1/8192 an sRGB color lane, 1/4080 alpha), 4,050 of the lanes measured, each within 0.014 of a step of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | No accurate form |
| A texture of an ASTC LDR format on a device without that ASTC format reads a decoded twin of 8-bit codes, each channel the code nearest Metal's 12-bit value (`C >> 4` over 4095). (An sRGB form's twin holds Metal's own 8-bit codes under either value, which its slots decode through Metal's table: exact.) A texture of an EAC 11-bit format (`R11`, `RG11`, unsigned and signed) on a device without ETC2 reads one of 16-bit normalized codes, each nearest Metal's value (`c / 2047`, signed `c / 1023`). The runtime's choice: no pipeline differs. | `decoded_texels = DecodedTexelsPolicy::Compact` | `decoded_texels = DecodedTexelsPolicy::Exact`: Metal's values in an `R32G32B32A32_SFLOAT` twin (an EAC 11-bit one's in `R32_SFLOAT` or `R32G32_SFLOAT`) | Within 1/510 of Metal's value. An EAC 11-bit channel within half a 16-bit step (1/131070, signed 1/65534). `decoded-texel-precision`, announced where such a texture is made; `runtime_lane::astc_textures`, `runtime_lane::etc_textures` | The twin's memory, 16 bytes a texel against 4 (a 2048 x 2048 texture's chain: 85 MiB against 21 MiB), and as much again for a second twin once the texture is viewed in its other colour space; an EAC 11-bit twin's 4 bytes a channel against 2. The CPU decode of that chain of 8 x 8 blocks on one core of the Iris Xe host: 79 ms against 68 ms. Sampling not measured |
| A heap's colour texture that Metal keeps losslessly compressed (`allowGPUOptimizedContents`, no `ShaderWrite`, `PixelFormatView` or `ShaderAtomic` usage, 16 texels or more a side), on a driver whose compressed images may keep their texels apart from the memory they are bound to (`DriverFact::CompressedImagesHideAliasedWrites`: ANV), is the driver's compressed optimal image, its compression and fast clears kept. A texture Metal keeps uncompressed takes the uncompressed image under either value. The runtime's choice: no pipeline differs. | `heap_compression = HeapCompressionPolicy::Compressed` | `heap_compression = HeapCompressionPolicy::Uncompressed`: an image the driver keeps uncompressed in the heap's bytes, as for a texture Metal keeps uncompressed: host-transfer usage where the device enabled `hostImageCopy` (`heap-texture-host-transfer`), else a linear image (`heap-texture-linear`), else the optimal one (`heap-texture-hides-aliased-writes`) | A write through a buffer or another texture over the texture's bytes may leave its texels as they were or change them otherwise than as written, where Metal's texture reads opaque magenta (`0xffff00ff`) in every texel of drawn content the write covers and the written bytes where it held only a clear; the texture's own writes may show in those bytes compressed. Within Metal's contract: Metal documents such a texture's layout as its own (`allowGPUOptimizedContents` lets it "adjust the private layout"), so no write through another view over its bytes has a defined result there either. `HeapTextureCompressed` (`heap-texture-compressed`), announced once per device where such a texture is made; `runtime_lane::heap_textures` | ANV (Iris Xe of RPL-P; `heap_textures::heap_compression_costs`), a 2048x2048 `RGBA8Unorm` render target in a `Private` placement heap: a pass that clears it 26.9 us against 676.2-676.5 us; a copy into another such texture 647.7-649.1 us against 673.9-693.2 us |
| A signed normalized color attachment (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`) or an `RGB9E5Float` one, single-sampled and loaded by a pass that draws, keeps the texels its draws do not write as they were, where Metal's tile store writes each 32x32 tile a draw reaches back through its values: a channel's minimum code (-128, or -32768) as the code above it (-127, -32767), and a shared-exponent word whose largest mantissa is below 256 under an exponent above 0 normalized (its mantissas shifted up as the exponent steps down). The runtime's: no pipeline differs. Not on a driver whose pass stores them as Metal's (`DriverFact::TileStoreIsMetals`: MoltenVK on Apple's GPUs), under either value, with no load pass and no notice. | `tile_store = TileStorePolicy::Device` | `tile_store = TileStorePolicy::Exact`: the extended-range attachments' load pass (`render/unused_bits_load.rs`) takes such an attachment too, raising each minimum code and normalizing each word in the tiles the pass's draws reach (`bind::unused_bits_module` of the format); one it cannot take (a texture held as a shadow, a sparse one, or one whose image the device does not copy both ways) keeps the device's, announced | One code, only at a minimum code, which no Metal write leaves (uploaded or copied bytes); none in value for a shared-exponent word (another encoding of the same value). Within Metal's contract: `MTLLoadAction.load` is documented as "The GPU preserves the existing contents", which the kept texels are; the rewrite is Apple's tile store's own. `SnormMinimumKept` (`snorm-minimum-kept`) and `SharedExponentKept` (`shared-exponent-kept`), announced at each such draw; `runtime_lane::snorm_tile_store` | The load pass before each such pass: the render area copied into a scratch buffer and back, with a dispatch. Timed for the extended-range attachments, whose load pass runs under both values: at 1920x1080 on the Radeon 780M (RADV), a pass that loads one and draws a full-screen triangle takes 1,959 us of GPU time for `BGRA10_XR` against 135 us for `RGBA16Float`, and 1,341 us for `BGR10_XR` and 1,378 us for `RG16Bfloat` against 69 us for `RGBA8Unorm`: about 1.3 ms a loaded attachment for a 4-byte texel and 1.8 ms for an 8-byte one. Under `Exact` a snorm or `RGB9E5Float` attachment takes the same pass (not timed) |
| Batches of command buffers committed on one queue that the scheduler finds ready together (a backlog) go to the driver in one `vkQueueSubmit`, at most four, only the last signalling the queue's timeline, on a driver whose queue merges a submission that signals nothing into the next (Mesa's: ANV, RADV, lavapipe, NVK, Turnip and kin): one kernel submission, where ANV on i915 lists every `VkDeviceMemory` in each (the consumer's guest drag on the Iris Xe: about 300 entries per execbuffer, 260 of them its host imports, at 112 to 128 execbuffers a frame). A batch's event signals ride to the group's end, which signals each event's semaphore to the highest index the batches held signal it to (an event's indices rise in commit order). A batch that signals a binary semaphore, takes a fence, binds a sparse update, does first work, names the caller's wrapped image, or waits for anything not seen complete (an event, another queue's work) goes alone, after the batches held: a batch with a wait leads a group, never joins one. So that checked command buffers (the consumer checks each) are found ready together, the submission checks of up to three batches right behind a line's head that goes run with the head's, in commit order, none committed after another queue's batch: such a check runs before the previous batch's `vkQueueSubmit` rather than after it, in the scheduler pass that submits its own batch. A pass that finds no batch ready sends the batches held, unless two or more earlier submissions of their `VkQueue` are not seen complete: the GPU runs those first in any case, so the batches stay held, and those committed meanwhile join them, until one submission is left in flight (a completion turn wakes the scheduler at its value), the group fills, a later batch sends it, a head waits for the GPU, or a thread waits for one of their command buffers' completion, which sends them at once; a batch that ends a command buffer with a switch of storage forms riding on it, which settles by its submission's outcome, is never kept so. A held batch that ends its command buffer is `Scheduled` as it is held, its submission handlers run first, then its scheduled handlers, and its kernel end time set, as an M3 Max schedules a command buffer committed behind running work 0.04 to 0.18 ms after its commit. The runtime's: no pipeline differs. | `completion = CompletionPolicy::Grouped` | `completion = CompletionPolicy::Exact`: one submission per batch, each signalling its own values; each line's head checked alone | Each command buffer of a submission but the last is seen complete (status, completed handlers, waits), and the event values it signals are reached (by the GPU waits on other queues, the host's waits, value reads and listeners), once the last completed: late by the GPU time of at most three later batches (about 0.1 to 0.2 ms each in the consumer's compositor frames on the Iris Xe; about 20 ms behind a 20 ms batch), never early, in commit order. Metal's contract states no bound on when completion is seen (an M3 Max reports a command buffer complete, its handlers, status, waits and event listeners alike, 0.04 to 0.10 ms after its GPU end), and no member but the first waits, so no wait holds a member back: a valid program sees only later completion, as of slower GPU work. A batch kept while earlier work runs is seen complete within the same bound, and, where the one submission left in flight ends before its group reaches the GPU, late besides by that gap: at most a completion turn's reaction and the group's `vkQueueSubmit`. Commands, barriers and GPU times are unchanged. `GroupedCompletion` (`grouped-completion`), announced once per device at its first such submission; `runtime_lane::grouped_submissions` | ANV (Iris Xe of RPL-P; `frame_costs::frame_costs_over_imports`, the checked device, 67 command buffers a frame, GPU at 467-783 MHz), with 520 host imports live, where the Exact form's submissions fall behind the commits as the guest's do: 32.0-33.2 kernel submissions a frame against 67.0, 3.4-3.5 ms of execbuffer ioctl a frame against 6.9-7.9 ms, the scheduler thread's CPU 61-63 us a command buffer against 121-136 us, a frame through completion 4.7-5.9 ms against 8.6-9.7 ms; in the guest's shape with 520 (a second queue taking every 20th command buffer, each signalling a shared event, every 10th waiting for one): 26.2-26.7 kernel submissions a frame against 67.0, 2.8 ms of ioctl a frame against 6.9-7.0 ms, the scheduler 52-53 us a command buffer against 122-123 us, a frame through completion 6.0 ms against 8.7 ms; with 260, where it keeps up, 64.9-66.3 kernel submissions a frame against 67.0, the CPU and wall times alike. The cost (`grouped_submissions::grouped_completion_delays`, 8 command buffers of 0.3-0.5 ms of GPU work ready together): the host saw each but a group's last complete later by the later ones' GPU time, the last 0.1-0.3 ms later than alone (the completion turn's per-command-buffer work for the group, done at its eLine truncated
| Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) |
All at once: `DevicePolicy::exact_answers()` sets every switch above but sampling's (validation
adds `sampling = SamplingPolicy::Exact`). Against master 1ee783c77 it cost A2X 0.99-1.04 → 17.5 s,