Files
metal2vulkan/crates/metal2vulkan-runtime/src/command_buffer/submit.rs
T
Anees Iqbal d8666d430f RUNTIME 2302: render encoders record into the VkCommandBuffer of the encoders before them
A render encoder took a VkCommandBuffer of its own at every open, so a compute, render
and blit step began 2.71 and submitted 4 VkCommandBuffers per step (dispatch_chain
renders, lavapipe). A render encoder with a log of its calls now takes part in the
encoder fold:

- One whose pass records at its end (draws in a secondary) joins the group before it;
  one whose first instance records inline joins none and may lead a group.
- No barrier records inside a pass: a joined render encoder records one barrier from
  everything of the group's earlier encoders (FoldOrder::everything) at its open,
  counted in command_barriers.
- Color groups, rasterization-rate maps and a depth attachment out of GENERAL take no
  group; segments, fence updates and Overwrites end the group after the encoder.
  Logless devices keep one VkCommandBuffer per render encoder.
- A folded member's layout moves go before its group's first part (GroupPlaces).
- A check splits a group with a render member at its pass's submission (as RUNTIME
  2297 does for blits).
- A group's order is built as its second encoder joins, not as its first ends.

A/B (lavapipe, dispatch_chain, per step, base vs tip): renders 2.71 -> 1.35
VkCommandBuffers begun, 4 -> 2 submitted, GPU 119.5 -> 97.7 us; renders-apart
3.71 -> 1.00, 4 -> about 0, 143.6 -> 94.6 us; passes unchanged in buffers, the
encoder's open about 250-480 ns more on the host (the group an inline pass begins),
the whole pass within the host's noise.

Tests: tests::render_fold (device), tests::held_depth, shadow_runs' rebind expectation
(a rebind encodes a group whole). Docs: encoder_fold.rs, API.md, FAST-PATHS known gap
and ANV row.

Verified (msi, lavapipe): the full runtime suite 2683/2684 at c502efba29, the one
failure the race test fixed in ca5042567b; clippy plain and --cfg m2v_cpu_icd, rustdoc,
fast_paths 0. Negative control (the explicit order removed, renderfold-negctl): the
hazard tests fail on their barrier counts; lavapipe shows no wrong texel because it
completes each command as it runs, so the texel proof is a GPU that overlaps work.
2026-11-14 08:59:50 -08:00

2327 lines
119 KiB
Rust

//! Submitting one batch of a command buffer, on the scheduler's thread, in its order, under its
//! lock.
//!
//! One `vkQueueSubmit` of two `VkSubmitInfo`s on the queue's `VkQueue`:
//! 1. The work: the batch's waits, Vulkan waits for its events' signal indices, for the caller's
//! binary semaphores and the tracker's waits for other `VkQueue`s' timelines, then its encoders'
//! `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`]), 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`,
//! `device/staging.rs`) it never tracks: their writes are ordered before a later batch by their
//! completion alone. The work waits for each such timeline, each `VkQueue`'s and the device's two
//! own, at the value the host saw it reach, where a batch of its `VkQueue` did not wait for that
//! value already: a wait that is satisfied as it is submitted. The signal made the writes
//! available ("The first access scope includes all memory access performed by the device",
//! semaphore signaling), and the wait makes them visible: the submission's "second
//! synchronization scope of each semaphore wait operation defined by this command includes every
//! command in the same batch that the wait operation is defined in, and all commands that occur
//! later in submission order", and the wait's "second access scope includes all memory access
//! performed by the device" (`vkQueueSubmit`, semaphore waiting). So one wait per value serves
//! every later batch of its `VkQueue`. A batch with nothing planned before its first encoder then
//! needs no command buffer before it, a timed command buffer's first batch included where its
//! first encoder wrote the start (**GPU times**, below): on an RTX 5080 and a Radeon 780M, nearly
//! every batch of a frame of draws, and of command buffers committed from several threads. A wait costs CPU in `vkQueueSubmit`: about
//! 1.1 us on ms01's Iris Xe (ANV), 1.6 us on a Radeon 780M (RADV) and 0.5 us on an RTX 5080,
//! where a command buffer of barriers cost about 12 us of the Iris Xe's GPU. Counted:
//! `WorkCounts::completed_waits`, `WorkCounts::bare_starts` (the batches with work that began
//! with no command buffer of barriers).
//!
//! A driver measured to stall its submissions on semaphore operations
//! (`DriverFact::SemaphoreOperationsStallSubmits`: NVIDIA's 615.71.09 on the RTX 5080 Laptop GPU
//! and the RTX 3090, about 2 ms of CPU in one `vkQueueSubmit` in about every thousand waits and
//! signals) takes no such wait: each batch with work starts instead with a command buffer of
//! barriers whose first is [`Barrier::after_completed`], which makes what completed batches
//! wrote visible to every later command. Where every batch waited, about twice as many of its
//! submissions took that long as where batches only signal.
//!
//! **The staging queue's copies.** On every driver, a batch waits on the GPU for the staging
//! queue's last submission while the host has not seen it complete (`Device::staging_wait`),
//! unless a batch of its `VkQueue` already waited for that submission: the wait's second
//! synchronization scope holds every command later in submission order there, so one wait per
//! `VkQueue` makes the copies visible to every later batch of it, as one wait per value does for
//! completed work above. A submission that carries the copies a burst of host calls queued is
//! made just before the batch and waited for on the GPU, not the host
//! (`texture/staging_copy.rs`). The batches after the one that waits may then join a group
//! (**Grouped**, above), which a batch with a wait for work the host has not seen complete only
//! leads. Counted: `WorkCounts::staging_gpu_waits`.
//!
//! Each barrier goes in a command buffer of barriers alone, which the scheduler records once per
//! list of barriers and submits again once the batch that last carried it completed
//! ([`kept_barriers`](super::kept_barriers)); one that also writes a command buffer's timestamps
//! once per list and slot, submitted again only by a later holding of the slot; one that moves
//! the caller's images is recorded by its batch.
//!
//! **The end in the work's last command buffer.** An encoder's last `VkCommandBuffer` stays
//! recording after the encoder ended, as its command buffer's tail, until an encoder after it
//! 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 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, 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
//! to the queue as recorded (its encoder runs nothing, or a rebind encoded it again), the end is
//! a command buffer of its own, as every other batch's. Each command buffer a submission holds
//! costs GPU time of its own: a probe of one 1x1 copy took 42.6 us of GPU time as three primary
//! command buffers (a start, the copy, an end) and 25.6 us as one on ms01's Iris Xe (ANV), 19.6
//! and 13.6 cold on a Radeon 780M (RADV), 15.4 to 17.4 and 7.9 to 9.0 on an RTX 5080. Counted:
//! `WorkCounts::finales_folded`, `WorkCounts::finales_apart`.
//!
//! A batch with no work is one `VkSubmitInfo` of every wait, the end and the signals: a wait
//! orders only its own `VkSubmitInfo`'s commands, and a signal follows commands, not waits
//! (`vkQueueSubmit`'s synchronization scopes), so a signal after a wait needs both in one, with
//! the end's barrier, a command, between. Where it has no wait, no image to move back and no
//! timestamp to write either (an empty command buffer's batch that carries the device's first
//! work, one of signals alone), its end
//! records nothing and the `VkSubmitInfo` holds no `VkCommandBuffer`: none of its commands wrote
//! anything, every batch before it made its own writes visible to the host before its signals,
//! and its signals follow every command submitted before them. ANV on i915 lists every
//! `VkDeviceMemory` of the device, and its own buffer objects, in each kernel submission of
//! commands, and two objects in one of none (Mesa 26.2.4, `i915/anv_batch_chain.c`).
//!
//! **The caller's images** ([`Device::new_texture_with_vk_image`]). A batch whose encoders use a
//! wrapped image that is not at rest in `GENERAL` moves it there before its first encoder and back
//! to its home layout in the end, before the signals. The moves are planned with the encoders, as
//! writes of the whole image outside them
//! ([`WrappedImage::transition_use`](crate::texture::wrapped::WrappedImage::transition_use)),
//! so the tracker orders them against every other use of the image on any queue, and each is
//! recorded as an image memory barrier from all commands before to all commands after.
//!
//! **Held depths** (`texture/held_depth.rs`). Before each encoder that names a held multisampled
//! depth, the encoder's command buffer of barriers moves it into the layout the encoder needs
//! where the batches submitted before, or the batch's earlier encoders, left it in another. The
//! moves are planned with the encoders as the caller's images' are, each a write of the whole
//! image outside the encoder joined to its summary, and recorded the same way, after the barrier
//! the tracker planned for the encoder. The layouts the batch leaves count from its submission on.
//!
//! **Writes through the residency** (`State::resident_writes`). Residency is the command
//! buffer's (`residency.rs`), so a function of any of its encoders may write a resource any of
//! them made resident for writing, in an encoder whose commands name it nowhere. Each batch with a
//! part plans those writes with its first part, as writes of each whole resource in every stage
//! that widen none of the stages the part's fences cover: the tracker then holds the batch as their
//! last writer, so what reads them later on any queue, and a later host step's gate
//! (`scheduler/mod.rs`'s `gate_heads`), orders after it. A resource made resident for reading
//! alone is planned as the commands that name it use it.
//!
//! **New resources' first work** (`texture/first_move.rs`). Every batch first does the first GPU
//! work of the resources made since the device's last submission: each new image's move to
//! `GENERAL`, and the zeros a new texture, stand-in or buffer reads. It runs before every command
//! of the batch, whether a use names the resource or not (a command may reach a texture through its
//! resource ID, a buffer through its address), and the batch holds what it worked on until it
//! completes. On a device of several `VkQueue`s every batch on another one waits for it until it
//! completed. It is recorded first in the command buffer that leads the batch's work's
//! `VkSubmitInfo` (in a batch with no work, its end's) -- its own, or, where the batch also has
//! host calls' staged copies, the one that holds the copies after it -- so it waits for what the
//! work waits for: Vulkan's
//! submission order puts it before every command of the batch ("the order in which command
//! buffers are specified in the pCommandBuffers member of VkSubmitInfo ... determines their
//! submission order", the Vulkan specification, Submission Order), and its last barrier,
//! recorded outside a render pass, orders it before them all: "the first synchronization scope
//! includes all commands that occur earlier in submission order ... the second synchronization
//! scope includes all commands that occur later in submission order" (`vkCmdPipelineBarrier`).
//! MoltenVK 1.4.1 runs each `VkSubmitInfo` as a Metal command buffer of its own
//! (`MVKQueue::submit`), each about 65 us of a thread of Metal's on an M3 Max, so the first work
//! adds none (`WorkCounts::submit_infos`). It takes no barrier that names a host read of an image
//! (`image_barrier.rs`), the one MoltenVK took for a read back over a heap texture's own storage
//! at its Metal command buffer's completion. A failed `vkQueueSubmit` made none of it, or lost
//! the device.
//!
//! [`Device::new_texture_with_vk_image`]: crate::Device::new_texture_with_vk_image
//!
//! The submission of the batch that ends a command buffer also signals a fence of the device's
//! 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
//! [`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`). 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.
//!
//! The submission is a section of the exit guard ([`exit_guard`]). What it did is published
//! ([`CommandBufferShared::publish`]: the transition to `Scheduled`, which runs the scheduled
//! handlers and ends waits for scheduling, and the queue waiter's watch) only after that
//! section ended. A section ends by registering the exit hook again when its calls may have
//! 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, 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.
//!
//! **No GPU work, no submission** ([`State::needs_no_gpu`]). A command buffer whose encoders
//! recorded nothing and whose one batch waits for and signals no event and no binary semaphore (so
//! presents no drawable) is taken, once it leads its logical queue's line, no group is held and
//! no first work of the device's waits (`texture/first_move.rs`), with no `vkQueueSubmit`: its batch is watched at its `VkQueue`'s last submitted value, so it
//! completes in its queue's order, once the queue's work before it completed, or at once where the
//! queue has none in flight (`Completion::watch_unsubmitted`). Everything else its last batch's
//! taking does is done as for a submitted one: its kernel times, its scheduling (by a hang's
//! thread where one makes it), its submission handlers, its holds. Metal completes such a command
//! buffer without its GPU too: on the M3 Max (macOS 27.0.1) one committed and waited for on an
//! idle queue returned in 15 us at the median of 1000, its `GPUStartTime` equal to its
//! `GPUEndTime` (within 0.3 us) 1 to 2 us after its `kernelEndTime`; one committed behind a fill
//! completed after the fill, its GPU times 65 to 135 us after the fill's `GPUEndTime`. Counted:
//! `WorkCounts::command_buffers_unsubmitted`.
use super::completion::{Submitted, Waited};
use super::follow::{Follow, Release};
use super::gate::Hold;
use super::group::{After, GroupEnd, InfoParts};
use super::hang;
use super::kept_barriers::{KeptBarriers, SlotStamps};
use super::{lock, recording_error, submission_error, CommandBufferShared, State};
use crate::deferred::Deferred;
use crate::encoder::{count_shadow_copies, OverwriteBy, Recorded, RecordedSegment};
use crate::encoder_fold::GroupPlaces;
use crate::error::CommandBufferError;
use crate::error::{internal, Error};
use crate::event::EventShared;
use crate::event_timeline::Signal;
use crate::exit_guard::{self, Call};
use crate::gpu_time;
use crate::managed_copy::AtCompletion;
use crate::managed_sync::SyncCopy;
use crate::release;
use crate::resource::{ObjectId, ResourceKey};
use crate::scheduler;
use crate::shadow::ShadowCopies;
use crate::shadow_standing::{LetGo, Missed, Unskipped};
use crate::slow_submissions::{self, Phase, Watch};
use crate::sparse::bind::{bind_batch, BindFailure, Bound};
use crate::sparse::encoder::SparseUpdate;
use crate::submit_failure::{Carried, TypeFlags};
use crate::texture::decoded_twin::{SecondDecode, TwinWrite};
use crate::texture::faces::FaceFix;
use crate::texture::first_move::{last_of_each, FillTake};
use crate::texture::wrapped::Transition;
use crate::texture::Texture;
use crate::tracker::{Barrier, Point, Summary};
use crate::used_resources::{EncoderKind, EncoderRecord};
use crate::work_counts::Begun;
use ash::vk;
use std::collections::BTreeSet;
use std::sync::Arc;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
use {crate::tracker::Footprint, std::sync::Mutex};
/// The command buffers a device test watches (`tests::kept_heap_uses`), by the address of their
/// shared state, and the footprints of the batches the scheduler planned of each, in order.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
static PLANNED: Mutex<Vec<(usize, Vec<Footprint<ResourceKey>>)>> = Mutex::new(Vec::new());
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
impl super::CommandBuffer {
/// Note the footprint of each batch of it the scheduler plans from now on: a device test's
/// (`tests::kept_heap_uses`), before its commit.
pub(crate) fn watch_planned(&self) {
lock(&PLANNED).push((Arc::as_ptr(&self.0) as usize, Vec::new()));
}
/// The footprints of its batches the scheduler planned since [`watch_planned`]: their tracked
/// uses, as the tracker planned them. Watched no more.
///
/// [`watch_planned`]: Self::watch_planned
pub(crate) fn planned(&self) -> Vec<Footprint<ResourceKey>> {
let mut planned = lock(&PLANNED);
let at = Arc::as_ptr(&self.0) as usize;
match planned.iter().position(|(of, _)| *of == at) {
Some(index) => planned.swap_remove(index).1,
None => Vec::new(),
}
}
}
/// The lists a batch's submission fills and empties, kept in the scheduler's state from batch to
/// batch with their room, so that a submission allocates none of them once they have room for
/// what it puts in them ([`CommandBufferShared::submit_batch`]).
#[derive(Default)]
pub(crate) struct BatchLists {
/// What each timeline whose writes the tracker forgets completed through as the host saw
/// it, each `VkQueue`'s, then the device's own: none where it is at 0.
reached: Vec<Option<(vk::Semaphore, u64)>>,
/// The work's waits.
waits: BatchWaits,
/// Of `reached`, the timelines (by place) and values the work waits for.
waited: Vec<(usize, u64)>,
}
/// A `VkSubmitInfo`'s waits: the semaphores, their values and their stages.
#[derive(Default)]
struct BatchWaits {
semaphores: Vec<vk::Semaphore>,
values: Vec<u64>,
stages: Vec<vk::PipelineStageFlags>,
}
/// A batch submitted, which nothing has seen yet: for the scheduler to
/// [`publish`](CommandBufferShared::publish).
#[must_use = "a batch not published never finishes its command buffer"]
pub(crate) struct Submission {
/// Its `VkQueue`.
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 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,
/// It makes its command buffer `Scheduled`: it ends it, and no hang's thread makes or made it
/// (`hang::schedules`).
schedules: bool,
/// Its command buffer became `Scheduled` as it was held in a group
/// ([`schedule_held`](Submission::schedule_held)).
scheduled: bool,
/// It was taken with no `vkQueueSubmit`: its command buffer needs no GPU work
/// ([`State::needs_no_gpu`]).
unsubmitted: 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: the submission of its event group 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 makes its command buffer `Scheduled` ([`Submission::schedules`]).
pub(super) fn schedules(&self) -> bool {
self.schedules
}
/// 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.schedules || 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 State {
/// Whether the command buffer needs no GPU work (the module docs): none of its encoders
/// recorded anything (none ended, and no storage form's switch rides on it with a part of its
/// own), and its one batch waits for and signals no event and no binary semaphore. Read from
/// what it recorded, never from a name.
pub(super) fn needs_no_gpu(&self) -> bool {
let [batch] = self.batches.all() else {
return false;
};
self.recorded.is_empty()
&& self.storage_form.is_none()
&& batch.waits.is_empty()
&& batch.signals.is_empty()
&& batch.binary_waits.is_empty()
&& batch.binary_signals.is_empty()
}
}
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
/// ([`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 the submission of its event group 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`). With `alone`, it never waits in the group: a thread other than
/// the scheduler's submits it (`scheduler::submit_plain_ready`).
pub(crate) fn submit_batch(
self: &Arc<Self>,
index: usize,
last: bool,
event_waits: &[(vk::Semaphore, u64)],
alone: bool,
scheduler: &mut scheduler::State,
) -> Result<Submitting, CommandBufferError> {
let _for = self.notices_for();
let device = &self.device;
if device.is_lost() {
return Err(CommandBufferError::DeviceLost);
}
// Where the device notes queue times, the submission timed phase by phase on this thread
// (`slow_submissions.rs`).
let mut watch = Watch::start(device.shared().timing.queue_times());
// A batch that waits for an event value its commit's copy in came before copies the
// copied host buffers in again, its wait met (`copies_again.rs`).
self.copy_in_again(index)?;
let shared = device.shared();
// Where the spares' frees left their pools holding command buffers untrimmed past their
// bound, a trim round, before any batch takes a kept barrier command buffer
// (`scheduler::State::trim_round`). Not while the group holds batches, whose kept ones
// are taken and not yet submitted.
if shared.spares.trim_due() && !scheduler.group.holds() {
scheduler.trim_round(shared);
}
let raw = shared.vk();
let queue = self.queue.vk_queue();
let mut state = lock(&self.state);
// What its encoders were, as the encoder trail names them (`encoder_trail.rs`).
let trail = match shared.encoder_trail {
true => batch_trail(&state.recorded[state.batch_range(index)]),
false => None,
};
// 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,
// nothing changed, for the group to go first. Its event signals ride to the group's end;
// 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));
// A batch whose work a segment cut into pieces goes in a submission of its own, whose
// pieces are `VkSubmitInfo`s of their own (below).
let pieced = (state.recorded[state.batch_range(index)].iter())
.flat_map(|recorded| &recorded.segments)
.filter_map(|segment| segment.recorded.as_ref())
.any(|done| !done.piece_ends.is_empty());
let joins = {
let sync = &state.batches.all()[index];
!alone
&& !pieced
&& self.groups()
&& !(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() {
return Err(error);
}
// Its first submission resolves what its commands reach as Metal's does, before any of
// its batches goes to the `VkQueue` (`first_submission.rs`).
if !state.submitted {
let first = state
.first_submission(device, self)
.map_err(|error| recording_error(device, error))?;
if !first {
return Ok(Submitting::Later);
}
}
// A later event group's, as its first batch is submitted, unless a rebind encodes
// encoders of it again.
if !state.later_group(device, self, index) {
return Ok(Submitting::Later);
}
// Each of Metal's submissions it found rebound, or holding a detached buffer, fails as
// its own batch is submitted, after the batch's checks: one a check failed keeps the
// check's code.
let rebound = state.failing_at(device, index);
// One that needs no GPU work goes with no submission, in its queue's order (the module
// docs); behind a group held, it goes with the group as any batch that joins does, and
// where the device's first work waits, it carries it as any batch does: on a device with
// a fill queue, first work but the fills of the program's memory, which a batch whose
// commands name nothing leaves waiting (`texture/first_move.rs`, `FillTake::Reached`).
let fills_named_only = |key: ResourceKey| {
device.has_fill_queue() && crate::used_resources::owner_of(shared, key).is_some()
};
if !rebound
&& !scheduler.group.holds()
&& state.needs_no_gpu()
&& (shared.textures.first_moves).none_waiting_but(fills_named_only)
{
let taken = self.take_unsubmitted(&mut state, index, last, scheduler);
return Ok(Submitting::Submitted(taken));
}
let range = state.batch_range(index);
// A batch that begins with resource state encoders binds their updates first, after its
// waits, which its work then waits for through the bind.
let updates: Vec<SparseUpdate> = state.recorded[range.clone()]
.iter()
.flat_map(|recorded| recorded.sparse.iter().cloned())
.collect();
// Where the updates leave work on emulated textures or tile maps and bind nothing, the
// values the work waits for in the bind's place: every queue's last.
let mut after_all = None;
let bound = if updates.is_empty() {
None
} else {
let binary = &state.batches.all()[index].binary_waits;
let waits: Vec<(vk::Semaphore, u64)> = event_waits
.iter()
.copied()
.chain(binary.iter().map(|&semaphore| (semaphore, 0)))
.collect();
let Bound {
unbound,
signalled,
mappings,
} = bind_batch(device, queue, &updates, &waits, &scheduler.values)
.map_err(|failure| bind_error(device, failure))?;
state.retained.push(Box::new(unbound));
if !mappings.is_empty() {
// The work's first command buffer, in the first resource state encoder's place,
// which the tracker sees write what it writes.
let uses = mappings
.uses()
.map_err(|error| recording_error(device, error))?;
let raw = self.record_raw(&mut state, |state, buffer| {
// SAFETY: the command buffer is recording; the textures are live (the
// command buffer holds them), in `GENERAL`; the work waits for the bind, or
// for every queue's last value.
let held = unsafe { mappings.record(device, &mut state.uploads, buffer) }?;
if !held.is_empty() {
state.retained.push(Box::new(held));
}
Ok(())
})?;
let first = &mut state.recorded[range.start];
first.raws.push(raw);
first.summary.join(Summary::outside_encoders(uses));
if !signalled {
after_all = Some(scheduler.values.clone());
}
}
signalled.then(|| {
scheduler.values[queue] += 1;
scheduler.values[queue]
})
};
// The scrubs of emulated textures' writes, as mapped now; then every segment in its
// place.
self.record_scrubs(&mut state, range.clone())?;
state
.place(range.clone())
.map_err(|error| recording_error(device, error))?;
// No work of an encoder that recorded nothing for a command (a buffer it named was
// detached), nor of one whose submission failed rebound or detached, goes to the queue.
state
.runs_nothing_unrunnable(range.clone())
.map_err(|error| recording_error(device, error))?;
// The copies out of buffers with a host copy its parts hold, settled by the writes noted
// so far; then its own writes noted.
let at = Point {
queue,
value: scheduler.values[queue] + 1,
};
self.settle_syncs_out(&mut state, range.clone(), at)?;
// The decodes into ASTC carriers' second decoded twins: those queued, before its work;
// its blits' writes', after each part.
self.record_second_decodes(&mut state, range.clone())?;
// The copies between textures' faces around its work, for turns whose passes have not
// run (`texture/faces.rs`).
self.record_face_fixes(&mut state, range.clone())?;
// What each timeline whose writes the tracker forgets completed through as the host saw
// it, each `VkQueue`'s, then the device's own (the module docs): read once, for the
// tracker and for the work's waits alike.
let BatchLists {
reached,
waits,
waited,
} = &mut scheduler.lists;
reached.clear();
for (slot, vk_queue) in shared.queues.iter().enumerate() {
let value = vk_queue.completed_value();
scheduler.tracker.completed(slot, value);
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, as of the value
// the tracker just took, which its plan orders by: each took the next value
// (`WorkCounts::batches_with_none_pending` and kin). A second read of the queue's value
// could see a completion the plan did not.
(shared.counts).batch_submitted_behind(scheduler.tracker.pending_before(at));
// One a hang's thread made `Scheduled` early began then (`hang.rs`).
if index == 0 && self.kernel.start() == 0 {
self.kernel.begin();
}
let slot = state
.times
.slot
.as_ref()
.map(|slot| (slot.queries(), slot.first(), slot.lease()));
// The start timestamp goes into the first command buffer of the first batch, a barrier
// one (with the barrier planned before its first encoder, if any), or into its end when
// it has no work, unless its first encoder wrote it (below).
let mut start_stamp = slot.filter(|_| index == 0);
let batches = state.batches.all();
let (start, end) = (range.start, range.end);
let binary_waits = batches[index].binary_waits.clone();
let binary_signals = batches[index].binary_signals.clone();
// Whether its `VkQueue` waits on the GPU for work of another `VkQueue`'s the host had not
// seen complete: an event's signal pending there (below, the tracker's and the first
// work's waits too), which holds the `VkQueue` until that work ends (`queue_share.rs`).
let mut across = !event_waits.is_empty()
&& (batches[index].waits.iter())
.any(|(event, value)| event.waits_across(*value, queue));
let mut kept = Vec::new();
let mut order_waits = Vec::new();
for (event, value) in &batches[index].signals {
if let Signal::Kept {
index: signal,
after,
} = event.signal(*value, queue)
{
if let Some(after) = after {
order_waits.push((event.semaphore(), after));
}
kept.push((Arc::clone(event), signal, *value));
}
}
let images = shared.interop.wrapped.among(
state.recorded[start..end]
.iter()
.flat_map(|recorded| recorded.summary.keys()),
);
// The textures its encoders made for their own commands (`Device::new_planned_texture`),
// which it holds until it completes.
let own: Vec<Texture> = lock(&self.own_textures).drain(..).collect();
if !own.is_empty() {
state.retained.push(Box::new(own));
}
let encoders = &state.recorded[start..end];
let mut entries = Vec::new();
let mut exits = Vec::new();
let (mut entry_uses, mut exit_uses) = (Vec::new(), Vec::new());
for image in &images {
let (entry, exit) = image.transitions();
if let Some(entry) = entry {
entries.push(entry);
entry_uses.push(image.transition_use());
}
if let Some(exit) = exit {
exits.push(exit);
exit_uses.push(image.transition_use());
}
}
// The new resources' first work, before every command (`texture/first_move.rs`), given
// back if the submission is not made. A batch's commands may reach every texture
// unnamed, so it takes every move, those of images bound to host pages among them, whose
// pages it then holds. Its commands bind the heap sets, so it holds the texture slots'
// writes until its submission was made (`heap_sets::hold`).
slow_submissions::enter(&mut watch, Phase::FirstWork);
// A test holds the thread here to stand in for a slow first work's take.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
super::completion::trace::at(super::completion::trace::Point::FirstWork);
let firsts = &shared.textures.first_moves;
// On a device with a fill queue it takes the fills of memory its commands may reach
// alone, and of memory no use of the program's names (`FillTake::Reached`): the rest wait
// for a batch that may reach them, so this one neither makes them nor waits for them.
// Either way it learns what owns the memory of the work it takes.
let owner_of = |key: ResourceKey| crate::used_resources::owner_of(shared, key);
let reaches = |owner: ObjectId| state.parts_reach(shared, start..end, &[owner]);
// An upload of bytes a later commit took waits for that commit's batches.
let commit = state.commit;
let fill_take = match device.has_fill_queue() {
true => FillTake::Reached {
owner_of: &owner_of,
reaches: &reaches,
commit,
},
false => FillTake::Owned {
owner_of: &owner_of,
reaches: &reaches,
commit,
},
};
let hold = || crate::heap_sets::hold(device);
// The new textures its commands' first use writes whole before any reads them: their
// moves' zeros go unrecorded (`texture/first_move.rs`).
let overwritten = first_overwrites(encoders, &state.ended);
let overwrites = |key: ResourceKey| overwritten.contains(&key);
let mut first_work = firsts.take_holding(|_| true, fill_take, hold, overwrites);
let every_fill = first_work.every_fill();
// What owns the memory of the first work it took, its fills for the fill queue among it.
let taken_owners = first_work.owners();
// Whether it took a move that keeps a buffer's bytes by copies around its transition.
let keeps = first_work.keeps();
// Its buffers' fills go to the device's fill queue where it has one with a command buffer
// free, in a submission of their own that the batch waits for (below,
// `device/staging.rs`), where they write at least `FILL_QUEUE_LEAST` bytes in all: not
// where a group holds batches of this `VkQueue`, whose values that submission would wait
// for before their signals were submitted, nor where the batch waits for a binary
// semaphore, which its one wait consumes.
let fills = (!scheduler.group.holds()
&& binary_waits.is_empty()
&& first_work.has_first()
&& device.fill_queue_has_room())
.then(|| first_work.take_fills(crate::device::FILL_QUEUE_LEAST))
.flatten();
// The copies queued for the staging queue, submitted there first, which the batch waits
// for on the GPU (below), holding what they copied until it completed
// (`texture/staging_copy.rs`).
slow_submissions::enter(&mut watch, Phase::Staging);
let staged = device
.flush_staging()
.map_err(|error| recording_error(device, error))?;
slow_submissions::enter(&mut watch, Phase::Planning);
let entry = (!entries.is_empty()).then(|| Summary::outside_encoders(entry_uses));
let exit = (!exits.is_empty()).then(|| Summary::outside_encoders(exit_uses));
// The held depths' moves before each encoder that names one, into the layout it needs
// (`texture/held_depth.rs`): writes the tracker plans with the encoder's uses, before
// them, so each waits for what came before it and orders what follows. Those of an
// encoder whose commands a group's shared `VkCommandBuffer` holds go before the group
// (`encoder_fold::GroupPlaces`).
let unnamed = BTreeSet::new();
let mut places = GroupPlaces::default();
let held_moves =
(shared.textures.held).moves(encoders.iter().enumerate().map(|(at, recorded)| {
match state.ended.get(recorded.encoder) {
Some(record) => (
places.place(at, recorded.encoder, record.group.as_ref()),
&record.keys,
record.held.as_slice(),
),
None => (at, &unnamed, &[][..]),
}
}));
// Each encoder's summary with its moves' uses joined, where it has moves; the first's
// with what the command buffer's work may write through its residency, which any of its
// encoders may write (`State::resident_writes`).
let resident_writes = state.resident_writes.as_ref();
let moved: Vec<Option<Summary<ResourceKey>>> =
match held_moves.is_empty() && resident_writes.is_none() {
true => Vec::new(),
false => (encoders.iter().enumerate())
.map(|(at, recorded)| {
let uses = held_moves.uses(at);
let writes = resident_writes.filter(|_| at == 0);
(!uses.is_empty() || writes.is_some()).then(|| {
let mut summary = recorded.summary.clone();
if !uses.is_empty() {
summary.join(Summary::outside_encoders(uses.to_vec()));
}
if let Some(writes) = writes {
summary.join(writes.clone());
}
summary
})
})
.collect(),
};
let summaries = (encoders.iter().enumerate()).map(|(at, recorded)| {
let moved = moved.get(at).and_then(Option::as_ref);
moved.unwrap_or(&recorded.summary)
});
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
let summaries = (encoders.iter().enumerate()).map(|(at, recorded)| {
let moved = moved.get(at).and_then(Option::as_ref);
moved.unwrap_or(&recorded.summary)
});
let address = Arc::as_ptr(self) as usize;
let mut planned = lock(&PLANNED);
if let Some((_, batches)) = planned.iter_mut().find(|(of, _)| *of == address) {
batches.push(Footprint::of(entry.iter().chain(summaries).chain(&exit)));
}
}
let plan = scheduler
.tracker
.plan(entry.iter().chain(summaries).chain(&exit), at);
// One barrier per summary planned: the entry's, the encoders', the exit's.
let mut barriers = plan.barriers();
let mut entry_barrier = None;
if let (Some(_), Some((&first, rest))) = (&entry, barriers.split_first()) {
entry_barrier = first;
barriers = rest;
}
let mut exit_barrier = None;
if let (Some(_), Some((&last, rest))) = (&exit, barriers.split_last()) {
exit_barrier = last;
barriers = rest;
}
// Where the driver's submissions stall on semaphore operations, the first command buffer
// of barriers makes what completed work wrote visible, in place of the work's waits (the
// module docs).
let by_barrier = shared.completed_by_barrier;
let mut completed_barrier = by_barrier.then(Barrier::after_completed);
// The first encoder's prefix wrote the start where the batch plans nothing before that
// encoder (no barrier, no image moved, no barrier for completed work) and its first
// command buffer goes to the queue as recorded (`gpu_time.rs`): then no command buffer of
// barriers starts the batch for the timestamp's sake.
let prefix = state.prefix;
let prefixed = start_stamp.is_some()
&& completed_barrier.is_none()
&& entry.is_none()
&& barriers.first().is_some_and(Option::is_none)
&& held_moves.transitions(0).is_empty()
&& prefix.is_some_and(|raw| {
state
.recorded
.get(start)
.and_then(|first| first.raws.first())
== Some(&raw)
});
if prefixed {
start_stamp = None;
}
if index == 0 {
state.times.prefixed = prefixed;
}
let mut work = Vec::with_capacity(2 * (end - start) + 1);
// Whether a command buffer of barriers goes before the first encoder.
let mut started = false;
// A barrier planned before the first encoder, for earlier work that may still run, or a
// held depth's move there, which waits for all of it: the start goes after the last such
// barrier, once every command before it completed (the module docs).
let encoder_behind =
barriers.first().is_some_and(Option::is_some) || !held_moves.transitions(0).is_empty();
if entry.is_some() {
started = true;
let globals: Vec<Barrier> = completed_barrier
.take()
.into_iter()
.chain(entry_barrier)
.collect();
let stamps = Stamps {
start: start_stamp.filter(|_| !encoder_behind),
after: entry_barrier.is_some(),
end: None,
};
if stamps.start.is_some() {
start_stamp = None;
}
work.push(self.record_barriers(&mut state, &globals, &entries, stamps)?);
}
for (offset, barrier) in barriers.iter().enumerate() {
let moves = held_moves.transitions(offset);
// An encoder whose own command buffer leads it, begun with a barrier from everything
// before (`encoder.rs`, past `PLANNED_BARRIERS`), holds the barrier planned before
// it: no command buffer of barriers goes there, but one that also carries the
// completed work's barrier, the start or a held depth's move.
let part = &state.recorded[start + offset];
let barriered = (part.barriered).is_some_and(|raw| part.raws.first() == Some(&raw));
if barriered && completed_barrier.is_none() && start_stamp.is_none() && moves.is_empty()
{
work.extend(&part.raws);
continue;
}
let globals: Vec<Barrier> = completed_barrier
.take()
.into_iter()
.chain(*barrier)
.collect();
if !globals.is_empty() || start_stamp.is_some() || !moves.is_empty() {
started |= offset == 0;
let stamps = Stamps {
start: start_stamp.take(),
after: barrier.is_some() || !moves.is_empty(),
end: None,
};
let kept = &mut scheduler.kept;
work.push(self.barrier_buffer(&mut state, kept, at, &globals, moves, stamps)?);
}
work.extend(&state.recorded[start + offset].raws);
}
// The first work goes first in the batch's work, or in a batch with no work in its end
// (the module docs). Host calls' staged copies go at the batch's start, after it, in the
// same command buffer: the two went in two command buffers of one `VkSubmitInfo`, which
// puts them in the same submission order one command buffer's recording order does ("the
// order in which command buffers are specified in the pCommandBuffers member of
// VkSubmitInfo ... determines their submission order", the Vulkan specification,
// Submission Order; inside one command buffer, the order they were recorded), and a
// command buffer boundary is no dependency of its own, so the copies' own leading barrier
// (`FirstMoves::record_staged`) covers the moves recorded before it either way. One
// command buffer where the batch has both (counted:
// `WorkCounts::command_buffers_begun_batch_work`).
let has_first = first_work.has_first();
let has_staged = first_work.has_staged();
let recorded = (has_first || has_staged)
.then(|| {
self.record_raw(&mut state, |_, buffer| {
if has_first {
// SAFETY: the command buffer is recording, outside a render pass; it is
// submitted first in the batch, before any later one, and every batch on
// another `VkQueue` waits for the batch (`FirstMoves::waits`).
unsafe {
let family = shared.queue_flags_of(queue);
first_work.record((raw, &shared.counts), buffer, family);
};
}
if has_staged {
// SAFETY: the command buffer is recording, outside a render pass; every
// image's move is in this command buffer, before it, or a submission
// before.
unsafe { first_work.record_staged(raw, buffer) };
}
Ok(())
})
})
.transpose()?;
// Where it holds staged copies it goes at the batch's start, as they did, so the batch
// has work; the first work alone goes first in the work, or in the end where the batch
// has none (below).
let lead = match has_staged {
true => {
work.insert(0, recorded.expect("recorded where there are staged copies"));
None
}
false => recorded,
};
let BatchWaits {
semaphores: wait_semaphores,
values: wait_values,
stages: wait_stages,
} = waits;
wait_semaphores.clear();
wait_values.clear();
wait_stages.clear();
if let Some(value) = bound {
// The bind waited for the batch's waits; the work waits for the bind.
wait_semaphores.push(shared.queues[queue].timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
} else {
for &(semaphore, value) in event_waits {
wait_semaphores.push(semaphore);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
for &semaphore in &binary_waits {
// A binary semaphore's value is ignored.
wait_semaphores.push(semaphore);
wait_values.push(0);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
for (slot, &value) in shared.queues.iter().zip(after_all.iter().flatten()) {
if value > 0 {
wait_semaphores.push(slot.timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
}
}
for wait in plan.waits() {
across |= wait.at.queue != queue;
wait_semaphores.push(shared.queues[wait.at.queue].timeline);
wait_values.push(wait.at.value);
wait_stages.push(wait.legacy_stages());
}
// Every batch on another `VkQueue` that did new resources' first work whose memory its
// commands, or the first work it took, may reach, until it completed: memory a resource
// its encoders' uses name or make resident owns, every memory where a command may reach
// memory no use names or where that work's owner is unknown, and the memory of the first
// work it took, which comes after that work's. Counted (`WorkCounts::first_work_waits`).
let completed = |point: Point| shared.queues[point.queue].completed_value() >= point.value;
let first_reaches = |owners: Option<&[ObjectId]>| match (owners, taken_owners.as_deref()) {
(Some(owners), Some(taken)) => {
owners.iter().any(|owner| taken.contains(owner))
|| state.parts_reach(shared, start..end, owners)
}
_ => true,
};
let first_waits: Vec<Point> = (firsts.waits(queue, completed).into_iter())
.filter(|(_, owners)| first_reaches(owners.as_deref()))
.map(|(point, _)| point)
.collect();
if !first_waits.is_empty() {
shared.counts.first_work_waited(true);
}
for point in last_of_each(first_waits) {
across |= point.queue != queue;
wait_semaphores.push(shared.queues[point.queue].timeline);
wait_values.push(point.value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
// And, where it took a move that keeps a buffer's bytes by copies around its transition
// (`texture/first_move.rs`'s `GpuKeep`), every earlier submission on the device's other
// `VkQueue`s not seen complete, whose commands may access those bytes while the
// transition rewrites them.
if keeps {
for (other, slot) in shared.queues.iter().enumerate() {
let value = slot.submitted_value();
if other != queue && value > slot.completed_value() {
across = true;
wait_semaphores.push(slot.timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
}
}
// And the internal submission on the first `VkQueue` that did some, until it completed.
if let Some((timeline, value)) = firsts.internal_wait().filter(|_| queue != 0) {
wait_semaphores.push(timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
// And the last binding of a no-copy buffer's dma-bufs, on every `VkQueue`, the first
// too (a binding is ordered with no later submission), until it completed.
if let Some((timeline, value)) = device.binding_wait() {
wait_semaphores.push(timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
// And the staging queue's last submission, until the host saw it complete: what it
// copied may be among what the work reads (`device/staging.rs`). Where a batch of this
// `VkQueue` already waited for it, every later command there follows that wait in
// submission order, this batch's too (the module docs): one wait serves them all. The
// staging queue's place among the timelines follows the `VkQueue`s' and the internal
// submissions' (`Device::own_completed`).
let staging_place = shared.queues.len() + 1;
let staging_wait = (device.staging_wait())
.filter(|&(_, value)| value > scheduler.waited[queue][staging_place]);
if let Some((timeline, value)) = staging_wait {
wait_semaphores.push(timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
shared.counts.staging_gpu_wait();
}
// And the last of the fill queue's submissions that the host may not have seen complete
// and whose fills its commands may reach, as the staging queue's, its place after the
// staging queue's (`device/staging.rs`): what it filled may be among what the work
// reads. Each of them where a command may reach memory no use names, or where it took
// every fill waiting; else those of memory its encoders' uses name.
let fill_place = shared.queues.len() + 2;
let fill_reaches = |owners: Option<&[ObjectId]>| {
every_fill || owners.is_none_or(|owners| state.parts_reach(shared, start..end, owners))
};
let fill_wait =
device.fill_queue_wait_for(scheduler.waited[queue][fill_place], fill_reaches);
if let Some((timeline, value)) = fill_wait {
wait_semaphores.push(timeline);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
// Its own fills, there: after the batches before it on its `VkQueue` (through the value
// before its own), what it waits for and what completed, as at the start of its work
// (`device/staging.rs`); its work waits for them.
let filled = match fills {
None => None,
Some(fills) => {
let before = (shared.queues[queue].timeline, at.value - 1);
let after: Vec<(vk::Semaphore, u64)> = (wait_semaphores.iter().copied())
.zip(wait_values.iter().copied())
.chain(reached.iter().flatten().copied())
.chain([before])
.collect();
(device.submit_fills(fills, &after))
.map_err(|error| recording_error(device, error))?
}
};
if let Some(filled) = &filled {
wait_semaphores.push(filled.timeline);
wait_values.push(filled.value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
}
// Whether its commands may reach what the fill-queue submissions it waits for filled,
// counted (`WorkCounts::fill_queue_waits`): its own, and those of the others' it waits
// for that the host may not have seen complete.
if fill_wait.is_some() || filled.is_some() {
let own =
(filled.as_ref()).is_some_and(|filled| fill_reaches(filled.owners.as_deref()));
let after = scheduler.waited[queue][fill_place];
let others = fill_wait.is_some_and(|(_, value)| {
device
.fill_queue_reached((after, value), fill_reaches)
.is_some()
});
shared.counts.fill_queue_waited(own || others);
}
let mut order_semaphores: Vec<vk::Semaphore> =
order_waits.iter().map(|&(s, _)| s).collect();
let mut order_values: Vec<u64> = order_waits.iter().map(|&(_, value)| value).collect();
let mut order_stages = vec![vk::PipelineStageFlags::ALL_COMMANDS; order_waits.len()];
// No work: every wait goes with the end, which it then orders.
let single = work.is_empty();
if single {
order_semaphores.append(wait_semaphores);
order_values.append(wait_values);
order_stages.append(wait_stages);
}
// The work waits for what completed, where its `VkQueue` did not already and no barrier
// made it visible (the module docs); the waits are taken as made once the submission is.
waited.clear();
if !single && !by_barrier {
for (source, &timeline) in reached.iter().enumerate() {
let Some((semaphore, value)) = timeline else {
continue;
};
if value > scheduler.waited[queue][source] {
wait_semaphores.push(semaphore);
wait_values.push(value);
wait_stages.push(vk::PipelineStageFlags::ALL_COMMANDS);
waited.push((source, value));
}
}
}
// The end went into the work's last command buffer as the batch ended (the module docs),
// 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 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()
&& start_stamp.is_none()
&& stamped == (last && slot.is_some());
debug_assert!(ends, "a batch's end recorded where the batch does not end");
if !ends {
let error = internal("a batch's end recorded where the batch does not end");
return Err(recording_error(device, error));
}
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
// signals, and its signals follow every command submitted before them. A wait needs it:
// a wait orders the commands of its batch, and a signal follows those, not the wait.
let stamps = Stamps {
start: start_stamp.take(),
after: false,
end: slot.filter(|_| last && !in_work),
};
let ends = !single
|| !order_semaphores.is_empty()
|| exit_barrier.is_some()
|| !exits.is_empty()
|| stamps.start.is_some()
|| stamps.end.is_some();
let mut finale: Vec<vk::CommandBuffer> = match ends && !folded {
true => {
let finale_barriers: Vec<Barrier> = exit_barrier
.into_iter()
.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)?]
}
false => Vec::new(),
};
let signal_semaphores: Vec<vk::Semaphore> = kept
.iter()
.map(|(event, _, _)| event.semaphore())
.chain(binary_signals.iter().copied())
.chain([shared.queues[queue].timeline])
.collect();
let signal_values: Vec<u64> = kept
.iter()
.map(|&(_, signal, _)| signal)
.chain(binary_signals.iter().map(|_| 0))
.chain([at.value])
.collect();
// A batch whose end its work holds signals with its work.
let (work_signals, work_signal_values) = match folded {
true => (&signal_semaphores[..], &signal_values[..]),
false => (&[][..], &[][..]),
};
// The first work, first in the batch's work or, where it has none, in its end: it waits
// for what the batch's commands wait for (a heap's fill another queue did comes before a
// move of an image placed in it; an event the program waits for before reusing a heap's
// memory).
if let Some(lead) = lead {
match single {
true => finale.insert(0, lead),
false => work.insert(0, lead),
}
}
// The pieces the batch's segments cut its work into (`RecordedSegment::piece_ends`,
// `rate_mapped_pass.rs`'s **Pieces**): each but the last a `VkSubmitInfo` of its own that
// signals its `VkQueue`'s timeline of pieces (`QueueSlot::pieces`), so no driver merges it
// into the next, as Mesa's common queue merges a submission that signals nothing into the
// next one's kernel submission (`group.rs`). The first takes the work's waits, the last
// its signals. Each piece runs after the one before it in submission order, and begins
// with a barrier from everything before (`EncoderCore::cut_piece`).
let cuts: Vec<usize> = (1..work.len())
.filter(|&at| state.piece_ends.contains(&work[at - 1]))
.collect();
state.piece_ends.retain(|raw| !work.contains(raw));
let pieces = cuts.len();
if pieces > 0 {
shared.counts.rate_map_pieces(pieces as u64);
}
let piece_from = match pieces {
0 => 0,
count => shared.queues[queue].piece_values(count as u64),
};
let piece_values: Vec<u64> = (0..pieces as u64).map(|k| piece_from + k).collect();
let piece_semaphore = [shared.queues[queue].pieces];
let starts: Vec<usize> = [0].into_iter().chain(cuts.iter().copied()).collect();
let ends: Vec<usize> = cuts.iter().copied().chain([work.len()]).collect();
let mut work_timelines: Vec<vk::TimelineSemaphoreSubmitInfo> = (0..=pieces)
.map(|k| {
let waits: &[u64] = match k {
0 => &wait_values[..],
_ => &[],
};
let signals: &[u64] = match piece_values.get(k) {
Some(value) => std::slice::from_ref(value),
None => work_signal_values,
};
vk::TimelineSemaphoreSubmitInfo::default()
.wait_semaphore_values(waits)
.signal_semaphore_values(signals)
})
.collect();
let mut infos: Vec<vk::SubmitInfo> = Vec::with_capacity(pieces + 2);
for (k, timeline) in work_timelines.iter_mut().enumerate() {
let (waits, stages): (&[vk::Semaphore], &[vk::PipelineStageFlags]) = match k {
0 => (&wait_semaphores[..], &wait_stages[..]),
_ => (&[], &[]),
};
let signals: &[vk::Semaphore] = match k < pieces {
true => &piece_semaphore,
false => work_signals,
};
infos.push(
vk::SubmitInfo::default()
.wait_semaphores(waits)
.wait_dst_stage_mask(stages)
.command_buffers(&work[starts[k]..ends[k]])
.signal_semaphores(signals)
.push_next(timeline),
);
}
// The fence the last batch signals where the driver reads a command buffer's objects
// after its value, and every batch where the queue's failures are relayed
// (`device/relay.rs`): taken before the submission, given back if it fails. Elsewhere
// the batch takes none (`fences::ends_at_fence`).
let fence = if (last || shared.flights(queue).is_some())
&& super::fences::ends_at_fence(device, queue)
{
// SAFETY: the device's fences, inside the scheduler's section.
Some(
unsafe { shared.fences.take(raw) }
.map_err(|error| submission_error(device, error))?,
)
} else {
None
};
let mut end_timeline = vk::TimelineSemaphoreSubmitInfo::default()
.wait_semaphore_values(&order_values)
.signal_semaphore_values(&signal_values);
let second = vk::SubmitInfo::default()
.wait_semaphores(&order_semaphores)
.wait_dst_stage_mask(&order_stages)
.command_buffers(&finale)
.signal_semaphores(&signal_semaphores)
.push_next(&mut end_timeline);
match (single, folded) {
(true, _) => infos = vec![second],
(false, true) => {}
(false, false) => infos.push(second),
}
let submits = &infos[..];
let buffers = (submits.iter())
.map(|info| info.command_buffer_count as usize)
.sum();
// From here its heap set versions may be pending: nothing writes them any more, and its
// first batch takes the ticket a texture that goes from now on waits for
// (`heap_sets.rs`). One committed and not yet submitted holds no gone texture.
if let Some(ticket) = state.heaps.submit(device) {
state.retained.push(Box::new(ticket));
}
if let Some(staged) = staged {
state.retained.push(Box::new(staged));
}
// 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()
&& filled.is_none()
&& images.is_empty();
// What the batch's submission carries, to its value, from here: the device's pending
// audit's (`pending_audit.rs`), where it is on.
let carried = (shared.queues[queue].timeline, at.value);
if let Some(audit) = raw.pending_audit() {
audit.submitted(raw, carried, &[work.as_slice(), finale.as_slice()]);
}
// The host time its submission was called, where it went now (`Group::submit`).
let mut called = None;
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);
}
// What the batch carried, for the line its failed submission logs
// (`submit_failure.rs`): read only once the call failed.
let kept_signals = kept.len();
let kept_barriers = &scheduler.kept;
let carry = |carried: &mut Carried, types: &TypeFlags| {
carried
.binary
.extend(binary_waits.iter().chain(&binary_signals));
carried
.events
.extend(event_waits.iter().map(|&(semaphore, _)| semaphore));
carried
.events
.extend(signal_semaphores[..kept_signals].iter());
carried.events.extend(order_semaphores.iter());
self.carry(&state, (Some(index), Some(start..end)), carried, types);
let roles = &mut carried.roles;
roles.extend(recorded.map(|raw| (raw, "first work".to_owned())));
roles.extend(finale.iter().map(|&raw| (raw, "end".to_owned())));
for &raw in &work {
if roles.iter().any(|(known, _)| *known == raw) {
continue;
}
let role = match kept_barriers.kept(queue, raw) {
Some(taken) => format!("kept barriers, taken for {taken}"),
None => "barriers".to_owned(),
};
roles.push((raw, role));
}
};
let after = After {
queue,
infos: submits,
buffers,
value: at.value,
fence,
relayed: &self.relayed,
carry: &carry,
};
let submitted =
scheduler
.group
.submit(device, &mut scheduler.waited[queue], Some(after));
// A watched submission held its thread long before the call: its line
// (`slow_submissions.rs`).
if let (Some(watch), Ok(at)) = (watch.take(), &submitted) {
let batches = state.batches.all().len();
watch.called(
device,
(index, batches),
queue,
(*at, gpu_time::host_nanos()),
);
}
// Where the device notes queue times, the call's return, for the command buffer this
// batch ends (`CommandBuffer::submit_returned_time`).
if last && submitted.is_ok() && shared.timing.queue_times() {
self.kernel.returned_at(gpu_time::host_nanos());
}
// A test's stand-in for a scheduler thread preempted once the call returned.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
super::completion::trace::submit_returned();
if let Err(error) = submitted {
if let Some(audit) = raw.pending_audit() {
audit.withdrawn(carried, &[work.as_slice(), finale.as_slice()]);
}
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);
}
called = submitted.ok();
// A sync file's signal among its signals is now submitted (`sync_file.rs`).
#[cfg(unix)]
self.sync_file_submitted(&mut state, &binary_signals);
// The first call that carried a batch of it: the earliest its GPU work began at,
// where GPU times are answered from the host (`place_gpu_times`).
if let Some(at) = called {
self.kernel.submitted_at(at);
}
}
// From the first batch whose `VkQueue` waits on the GPU for another's work, its `VkQueue`
// holds it: its long mark counts from that batch's submission (`place_gpu_times`).
if across && state.times.waited_across.is_none() {
state.times.waited_across = Some(called.unwrap_or_else(gpu_time::host_nanos));
}
// It makes its command buffer `Scheduled` where it ends it, unless a hang's thread makes
// it (`hang.rs`): the command buffer's own hang's, once this batch, the one before the
// hang's wait, is taken (the thread waits for it on `changed`), or, for one committed
// during a hang, early, where it did not wait past the hang. Its kernel end is the host
// time its submission was called, which no GPU end of its work can precede
// (`Group::submit`); a held batch's is its group's.
let (schedules, took) = hang::schedules(&mut state.hang_scheduling, index, last);
if took {
let parked = state.parked > 0;
self.wake_parked(parked);
}
if let (true, Some(at)) = (schedules, called) {
self.kernel.end_at(at);
}
if !single {
match folded {
true => shared.counts.finale_folded(),
false => shared.counts.finale_apart(),
}
}
for &(source, value) in waited.iter() {
scheduler.waited[queue][source] = value;
}
// Its staging wait, made or held: a held group goes to its `VkQueue` before any later
// batch there, and one whose submission fails puts the values back.
if let Some((_, value)) = staging_wait {
scheduler.waited[queue][staging_place] = value;
}
let fill_waited = fill_wait.map(|(_, value)| value);
let fill_waited = fill_waited.max(filled.as_ref().map(|filled| filled.value));
if let Some(value) = fill_waited {
scheduler.waited[queue][fill_place] = value;
}
// What its fills hold, until it completed.
if let Some(filled) = filled {
state.retained.push(Box::new(filled));
}
shared.counts.completed_waited(waited.len());
if !single && !started {
shared.counts.bare_start();
}
if prefixed {
shared.counts.prefixed_start();
}
// 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 or held, waits for them.
let forms = last && state.storage_form.is_some();
let handlers = (schedules && !state.submission.is_empty()) || forms;
state.submitting = handlers;
scheduler.tracker.apply(plan);
// The standings across command buffers, in the order the tracker took the batch
// (`shadow_standing.rs`): its writes let go of those they meet; then, where it ends the
// command buffer with its last encoder and nothing failed it or reached memory unnamed,
// the shadows its end left holding every texel of their truth stand.
let unnamed = state.reaches_unnamed;
let clean = state.failure.is_none()
&& state.fails_from.is_none()
&& state.faulted.is_empty()
&& state.hang.is_none()
&& !rebound;
let ends = last && start < end && end == state.recorded.len() && clean && !unnamed;
// Each shadow the end carries that it leaves no standing notes why
// (`shadow_standing::Missed`).
let held = match (last, &state.shadow_carry) {
(true, Some(carry)) => carry.standing_at_end(ends),
_ => Vec::new(),
};
let summaries = (state.recorded[start..end].iter()).map(|recorded| &recorded.summary);
shared.standings.submitted(summaries, unnamed, &held);
held_moves.submitted();
shared.counts.held_depths_released(held_moves.released);
let several = shared.queues.len() > 1;
let held = first_work.submitted(several.then_some(at));
if !held.is_empty() {
state.retained.push(Box::new(held));
}
scheduler.values[queue] = at.value;
// Its command buffer's wait behind another command queue's batch there, from its first
// batch's submission or hold (`queue_wait.rs`).
let on = &shared.queues[queue];
let first = (index == 0).then(|| crate::queue_wait::First {
since: called.unwrap_or_else(gpu_time::host_nanos),
unshared: self.queue.unshared(),
});
let completed = || on.completed_value();
// Its place in the `VkQueue`'s flight, where an unshared queue holds it
// (`unshared_hold.rs`).
let flies = device.flies(queue, self.queue.unshared(), self.queue.expected());
let taken = (at.value, self.queue.id(), flies);
(on.waits).taken(taken, first, completed, &shared.counts);
for image in &images {
image.submitted();
// One that rests in `GENERAL` from now on (an encode-time image after its first
// batch) is moved by no later batch.
if image.settled() {
shared.interop.wrapped.forget(image);
}
}
// Its signals are seen at its completion turn alone where it may write a copied host
// buffer, whose bytes reach the pages there (`event_timeline.rs`).
let behind_merge = !kept.is_empty() && shared.copied.any();
if behind_merge {
shared.counts.event_signals_behind_merge(kept.len());
}
// A last batch's signals name its command buffer, which another queue's command buffer
// that waits for one completes after; its transition to `Completed` lets them go
// (`follow.rs`).
let follow = (last && !kept.is_empty())
.then(|| Arc::new(Follow::new(self.queue.id(), Arc::as_ptr(self) as usize)));
for (event, signal, value) in &kept {
event.keep(
*signal,
*value,
(queue, at.value),
follow.clone(),
behind_merge,
);
}
if let Some(follow) = follow {
let signals = (kept.iter()).map(|(event, signal, _)| (Arc::clone(event), *signal));
let signals = signals.collect();
state.release = Some(Release { follow, signals });
}
// Its commands may reach every texture through its resource ID where one bound a heap
// set: the stale-reach degrade's trigger decides (`detach.rs`).
let reaches = state.heaps.bound();
let rebound_use = state.rebound_use.clone();
// The holds its completion lets go (`State::holds_until`).
let holds = state.holds_until(index);
// What it completes after: the batches of other `VkQueue`s whose GPU signals its event
// waits were met by, not finished yet, and the command buffers of other queues they end
// (`completion.rs`, "After what it waited for").
let after = {
let State {
batches, waited, ..
} = &mut *state;
finishes_after(&batches.all()[index].waits, (queue, self), waited)
};
drop(state);
if rebound {
device.degrade_encoded_use_rebound(rebound_use);
}
device.reach_stale_detached(reaches);
let submission = Submission {
queue,
batch: Submitted {
value: at.value,
buffer: self.hold(),
last,
fence,
signals: kept
.into_iter()
.map(|(event, signal, _)| (event, signal))
.collect(),
holds,
after,
held: false,
trail,
},
handlers,
forms,
schedules,
scheduled: false,
unsubmitted: 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)
}
/// Take batch `index` (`last` where it ends the command buffer) of a command buffer that needs
/// no GPU work ([`State::needs_no_gpu`]) with no submission, as its submission would take it
/// but for the `vkQueueSubmit` (the module docs): its batch is watched at its `VkQueue`'s last
/// submitted value in `scheduler`, with no fence and no signal.
fn take_unsubmitted(
self: &Arc<Self>,
state: &mut State,
index: usize,
last: bool,
scheduler: &scheduler::State,
) -> Submission {
let device = &self.device;
let queue = self.queue.vk_queue();
if index == 0 && self.kernel.start() == 0 {
self.kernel.begin();
}
// What it holds until it completes, as a submitted batch takes it.
let own: Vec<Texture> = lock(&self.own_textures).drain(..).collect();
if !own.is_empty() {
state.retained.push(Box::new(own));
}
if let Some(ticket) = state.heaps.submit(device) {
state.retained.push(Box::new(ticket));
}
// Scheduled by its last batch's taking, unless a hang's thread makes it (`hang.rs`).
let (schedules, took) = hang::schedules(&mut state.hang_scheduling, index, last);
if took {
let parked = state.parked > 0;
self.wake_parked(parked);
}
if schedules {
self.kernel.end_at(gpu_time::host_nanos());
}
let forms = last && state.storage_form.is_some();
let handlers = (schedules && !state.submission.is_empty()) || forms;
state.submitting = handlers;
let holds = state.holds_until(index);
device.shared().counts.command_buffer_unsubmitted();
Submission {
queue,
batch: Submitted {
value: scheduler.values[queue],
buffer: self.hold(),
last,
fence: None,
signals: Vec::new(),
holds,
after: Vec::new(),
held: false,
trail: None,
},
handlers,
forms,
schedules,
scheduled: false,
unsubmitted: true,
}
}
/// 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`
/// (`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
/// 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`).
pub(crate) fn publish(self: &Arc<Self>, submission: Submission) {
let Submission {
queue,
batch,
schedules,
scheduled,
unsubmitted,
..
} = submission;
if schedules && !scheduled {
// Before a completion turn can see it finish, so the queue's context runs its
// transition to `Scheduled` first.
self.schedule();
}
let completion = &self.device.shared().completion;
match unsubmitted {
// The caller makes the turn that finishes it where its queue reached its value and no
// turn is under way, once it holds no lock (`Completion::turn_owed`).
true => completion.watch_unsubmitted(queue, batch),
false => completion.watch(queue, batch),
}
}
/// A command buffer of this command buffer's pool holding what `record` records into it,
/// with the state at hand.
fn record_raw(
&self,
state: &mut State,
record: impl FnOnce(&mut State, vk::CommandBuffer) -> Result<(), Error>,
) -> Result<vk::CommandBuffer, CommandBufferError> {
let device = &self.device;
let raw = device.shared().vk();
let buffer = self
.allocate_raw(state)
.map_err(|error| recording_error(device, error))?;
let begin = vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
// SAFETY: the command buffer was just allocated from the pool, under the state lock, and
// only this call records it.
let begun = unsafe { raw.begin_command_buffer(buffer, &begin) };
exit_guard::called(Call::BeginCommandBuffer);
begun.map_err(|error| submission_error(device, error))?;
device
.shared()
.counts
.command_buffer_begun(Begun::BatchWork);
record(state, buffer).map_err(|error| recording_error(device, error))?;
// SAFETY: as above.
let ended = unsafe { self.end_raw(buffer) };
exit_guard::called(Call::EndCommandBuffer);
ended.map_err(|error| submission_error(device, error))?;
Ok(buffer)
}
/// Record the copies between textures' faces that the batch of parts `range` takes around
/// its work for turns whose passes have not run (`texture/faces.rs`, `FaceSwaps::fixes`):
/// each from the face that holds the truth into the face the batch names, in a command buffer
/// before its first part's own, and back after its last part's where the batch may write the
/// face it names, each joined to its part's summary, so the tracker orders them with the
/// batch's work and the standings across command buffers count their writes. The faces are
/// held until the command buffer completes. A part that runs nothing (its encoder failed, or
/// its use was rebound) leaves a turn of its pass to the next batch that names its face.
fn record_face_fixes(
&self,
state: &mut State,
range: std::ops::Range<usize>,
) -> Result<(), CommandBufferError> {
let device = &self.device;
let swaps = &device.shared().face_swaps;
if !swaps.any() || range.is_empty() {
return Ok(());
}
let unnamed = state.reaches_unnamed || state.heaps.bound();
let parts = &state.recorded[range.clone()];
let summaries = parts.iter().map(|part| &part.summary);
let ran = |part: usize| {
let at = part.checked_sub(range.start);
(at.and_then(|at| parts.get(at))).is_some_and(|part| !part.raws.is_empty())
};
let fixes = swaps.fixes(self.address(), (range.clone(), &ran), summaries, unnamed);
if fixes.is_empty() {
return Ok(());
}
let raw = device.shared().vk();
let (front, back): (Vec<_>, Vec<_>) = fixes.iter().map(FaceFix::uses).unzip();
let record = |state: &mut State, forward: bool| {
self.record_raw(state, |_, buffer| {
for fix in fixes.iter().filter(|fix| forward || fix.back) {
// SAFETY: the command buffer is recording, outside a render pass; both faces
// are live (held below until the command buffer completes) and rest in
// `GENERAL`.
unsafe { fix.record(raw, buffer, forward) };
}
Ok(())
})
};
let before = record(state, true)?;
let first = &mut state.recorded[range.start];
first.raws.insert(0, before);
for summary in front {
first.summary.join(summary);
}
let back: Vec<Summary<ResourceKey>> = back.into_iter().flatten().collect();
if !back.is_empty() {
let after = record(state, false)?;
let last = &mut state.recorded[range.end - 1];
last.raws.push(after);
for summary in back {
last.summary.join(summary);
}
}
let counts = &device.shared().counts;
for fix in &fixes {
let texels = fix.texels();
counts.attached_read_swap_fix(texels);
if fix.back {
counts.attached_read_swap_fix(texels);
}
}
state.retained.push(Box::new(fixes));
Ok(())
}
/// Record the segments of encoders `range` that their batch's submission records: the
/// scrubs (`Deferred::SparseScrub`), with the mappings it applied, and the gated copies in
/// (`Deferred::GatedCopyIn`), with the regions their logs say changed since the commit's
/// stamp, published by now; and the merges of runs of passes over a linear attachment or a
/// shadowed texture (`Deferred::RunMerge`), each the run's last pass's (or the last before a
/// pass encoded again), the ones taken over recording nothing.
fn record_scrubs(
&self,
state: &mut State,
range: std::ops::Range<usize>,
) -> Result<(), CommandBufferError> {
let mut scrubs = Vec::new();
for (encoder, recorded) in state.recorded[range.clone()].iter().enumerate() {
for (at, segment) in recorded.segments.iter().enumerate() {
let at_submission = matches!(
segment.work,
Deferred::SparseScrub(_) | Deferred::GatedCopyIn(_) | Deferred::RunMerge(_)
);
if at_submission && segment.recorded.is_none() {
scrubs.push((range.start + encoder, at, segment.work.clone()));
}
}
}
let device = &self.device;
for (encoder, at, work) in scrubs {
// A run's merge a later pass took over records nothing (`pass_runs.rs`).
if let Deferred::RunMerge(merge) = &work {
if merge.taken() {
state.recorded[encoder].segments[at].recorded =
Some(RecordedSegment::submitted(Vec::new()));
continue;
}
}
// A copy in its shadow's standing decides moves nothing where the image stands now,
// or the texels inside the rectangle it stands stale in alone
// (`shadow_standing.rs`).
let standing = match &work {
Deferred::GatedCopyIn(copy) => copy.standing(),
_ => None,
};
let decided = standing.map(|copies| self.stands(state, encoder, copies));
let stands = decided.and_then(Result::ok);
let raw = self.record_raw(state, |state, buffer| {
match &work {
// SAFETY: the command buffer is recording; the texture is live (its encoder's
// command buffer holds it), in `GENERAL`, and its batch's updates applied.
Deferred::SparseScrub(scrub) => {
let held = unsafe { scrub.record(device, buffer) }?;
if !held.is_empty() {
state.retained.push(Box::new(held));
}
}
// SAFETY: the command buffer is recording, outside a render pass; the
// shadowed texture is live (its encoder's command buffer holds it), its
// image in `GENERAL`.
Deferred::GatedCopyIn(copy) => unsafe {
copy.record(device.shared().vk(), buffer, stands)
},
// SAFETY: the command buffer is recording, outside a render pass; the merge,
// its images and its scratch are held until it completes (its pass's encoder
// retains them, and the segment its copies), and the images rest in
// `GENERAL`.
Deferred::RunMerge(merge) => {
unsafe { merge.record(device.shared().vk(), buffer) };
let counts = &device.shared().counts;
match merge.shadow() {
Some(copy) => count_shadow_copies(counts, std::slice::from_ref(copy)),
None => counts.linear_merge_recorded(),
}
}
_ => {}
}
Ok(())
})?;
state.recorded[encoder].segments[at].recorded =
Some(RecordedSegment::submitted(vec![raw]));
if let (Some(decided), Deferred::GatedCopyIn(copy)) = (decided, &work) {
let counts = &device.shared().counts;
let (texels, moved) = (copy.texels(), copy.texels_moved(stands));
counts.shadow_copy_in_against_standing(stands.is_some(), texels - moved);
match decided {
Err((at, let_go, missed)) => {
counts.shadow_copy_in_unskipped(at, let_go, missed, texels);
}
Ok(Some(_)) if moved > 0 => {
let missed =
standing.map_or(Missed::Unmet, |copies| copies.standing.last_missed());
counts.shadow_copy_in_unskipped(
Unskipped::StaleWithin,
None,
missed,
moved,
);
}
Ok(_) => {}
}
}
}
Ok(())
}
/// Settle the copies out of buffers with a host copy that the blits of parts `range` decided
/// and recorded as they were encoded (`managed_sync.rs`, **What the encoding cannot see**):
/// the writes of other command buffers noted since each one's encoding go into a
/// `VkCommandBuffer` just before its part, where any were. Then note the parts' writes, the
/// command buffer's writes through its residency, and where it may write memory no use names,
/// the batch at `at`.
fn settle_syncs_out(
&self,
state: &mut State,
range: std::ops::Range<usize>,
at: Point,
) -> Result<(), CommandBufferError> {
let shared = self.device.shared();
let writes = &shared.gpu_writes;
let completed = |point: Point| {
(shared.queues.get(point.queue)).is_some_and(|on| on.completed_value() >= point.value)
};
let by = self.id.get();
let copies: Vec<Arc<SyncCopy>> = (lock(&self.at_completion).iter())
.filter_map(|work| match work {
AtCompletion::Synced(copy) => Some(Arc::clone(copy)),
AtCompletion::Undo(_) => None,
})
.collect();
for part in range.clone() {
for copy in &copies {
if !copy.unsettled_in(&state.recorded[part].raws) {
continue;
}
let top_up = copy.settle(writes, by, &completed);
if top_up.is_empty() {
continue;
}
let raw = self.record_raw(state, |_, buffer| {
// SAFETY: the command buffer is recording, outside a render pass; it goes to
// the queue just before the part that holds the copy's command, whose encoder
// holds the buffer and the copy's target until it completes.
unsafe { copy.record_top_up(shared.vk(), buffer, &top_up) };
Ok(())
})?;
state.recorded[part].raws.insert(0, raw);
}
}
if writes.keeps_any() {
let parts = state.recorded[range].iter().map(|part| &part.summary);
writes.note(parts.chain(&state.resident_writes), by);
}
if state.writes_unnamed {
writes.note_unnamed(at, &completed);
}
Ok(())
}
/// Whether `copies`' image stands across command buffers (`shadow_standing.rs`) for a copy
/// in of encoder `encoder`, submitted now: it stands, no earlier encoder of the command
/// buffer wrote the truth or the image, and none of its commands may reach memory no use
/// names; and the rectangle it stands stale inside alone, where it does
/// (`Standings::standing`). Where not, where that was decided, what its standing held
/// (`shadow_standing::Unskipped`, `LetGo`; none where it stood) and what last kept a command
/// buffer's end from leaving it standing (`Missed`).
fn stands(
&self,
state: &State,
encoder: usize,
copies: &ShadowCopies,
) -> Result<Option<[u32; 4]>, (Unskipped, Option<LetGo>, Missed)> {
let missed = copies.standing.last_missed();
if !copies.stands_across() {
return Err((Unskipped::Unstanding, None, missed));
}
let keys = copies.standing_keys();
let wrote =
(state.recorded[..encoder].iter()).any(|recorded| recorded.summary.writes_any(&keys));
let standing = self.device.shared().standings.standing(copies);
match (state.reaches_unnamed || wrote, standing) {
(false, Ok(stale)) => Ok(stale),
(true, standing) => Err((Unskipped::CommandBuffer, standing.err(), missed)),
(false, Err(let_go)) => Err((Unskipped::LetGo, Some(let_go), missed)),
}
}
/// Record the decodes into ASTC carriers' second decoded twins (`texture/decoded_twin.rs`) of
/// the batch of encoders `range`, a batch with work: those queued (as each twin was made,
/// and after host calls wrote its carrier), in one command buffer before the first part's
/// own, their uses joined to its summary, so the barrier and waits planned before that part
/// order them after the earlier writes of their images; but those of an image a part of the
/// batch wrote without a decode (the image had no second twin as the write was encoded), which
/// stay queued for a later batch: a twin made since reads the carrier as this batch leaves it.
/// Then after each part's own command buffers, the decodes its writes made as they were
/// encoded, their uses joined to its summary. Nothing, and no command buffer, where there is
/// none (counted: `WorkCounts::second_twin_checks`, `WorkCounts::second_twin_decodes`).
fn record_second_decodes(
&self,
state: &mut State,
range: std::ops::Range<usize>,
) -> Result<(), CommandBufferError> {
let device = &self.device;
let counts = &device.shared().counts;
if range.is_empty() {
return Ok(());
}
let held: Vec<ResourceKey> = state.recorded[range.clone()]
.iter()
.flat_map(|part| &part.twin_writes)
.filter_map(TwinWrite::without_decode)
.collect();
let queued = device.take_second_decodes(|key| held.contains(&key));
if !queued.is_empty() {
let raw = self.record_raw(state, |_, buffer| {
for decode in &queued {
// SAFETY: the command buffer is recording, outside a render pass, on the
// device's queue family; the decode is retained until the command buffer
// completes.
unsafe { decode.record(device.shared().vk(), buffer) };
}
Ok(())
})?;
let uses = queued.iter().flat_map(|decode| decode.uses()).cloned();
let first = &mut state.recorded[range.start];
first.raws.insert(0, raw);
first
.summary
.join(Summary::outside_encoders(uses.collect()));
counts.second_twin_decodes(queued.len());
state.retained.push(Box::new(queued));
}
for part in range {
let mut checked = 0;
let mut decodes: Vec<SecondDecode> = Vec::new();
for write in state.recorded[part].twin_writes.drain(..) {
checked += 1;
decodes.extend(write.into_decode());
}
counts.second_twin_checks(checked);
if decodes.is_empty() {
continue;
}
let raw = self.record_raw(state, |_, buffer| {
for decode in &decodes {
// SAFETY: as above.
unsafe { decode.record(device.shared().vk(), buffer) };
}
Ok(())
})?;
let uses = decodes.iter().flat_map(|decode| decode.uses()).cloned();
let recorded = &mut state.recorded[part];
recorded.raws.push(raw);
recorded
.summary
.join(Summary::outside_encoders(uses.collect()));
counts.second_twin_decodes(decodes.len());
state.retained.push(Box::new(decodes));
}
Ok(())
}
/// A command buffer holding only `barriers`, in order, then `transitions` of the caller's
/// images or of held depths, between the `stamps` it writes, for the batch that signals `at`: where it moves no
/// image, one the scheduler keeps (`kept_barriers.rs`; one that writes timestamps, kept for
/// their slot) on a queue whose command buffers end at their timeline's value
/// (`fences::ends_at_fence`), and else, or past the kept ones' bounds, one recorded into this
/// command buffer's pool ([`record_barriers`](Self::record_barriers)).
fn barrier_buffer(
&self,
state: &mut State,
kept: &mut KeptBarriers,
at: Point,
barriers: &[Barrier],
transitions: &[Transition],
stamps: Stamps,
) -> Result<vk::CommandBuffer, CommandBufferError> {
let device = &self.device;
if transitions.is_empty() && !super::fences::ends_at_fence(device, at.queue) {
let taken = kept
.take(device, at.queue, barriers, stamps.kept(), at.value)
.map_err(|error| recording_error(device, error))?;
if let Some(buffer) = taken {
return Ok(buffer);
}
}
self.record_barriers(state, barriers, transitions, stamps)
}
/// A command buffer of this command buffer's pool holding only `barriers`, in order, then
/// `transitions` of the caller's images or of held depths, from all commands before to all
/// commands after, between the `stamps` it writes.
fn record_barriers(
&self,
state: &mut State,
barriers: &[Barrier],
transitions: &[Transition],
stamps: Stamps,
) -> Result<vk::CommandBuffer, CommandBufferError> {
let device = &self.device;
let raw = device.shared().vk();
let buffer = self
.allocate_raw(state)
.map_err(|error| recording_error(device, error))?;
let begin = vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
// SAFETY: the command buffer was just allocated from the pool, under the state lock, and
// only this call records it.
unsafe {
let begun = raw.begin_command_buffer(buffer, &begin);
exit_guard::called(Call::BeginCommandBuffer);
begun.map_err(|error| submission_error(device, error))?;
device
.shared()
.counts
.command_buffer_begun(Begun::BatchBarriers);
if let Some((queries, first, _)) = stamps.start {
// The slot's start and end, where it was not reset on the host (`gpu_time.rs`).
if !device.shared().timing.resets_on_host() {
raw.cmd_reset_query_pool(buffer, queries, first, 2);
exit_guard::called(Call::CmdResetQueryPool);
}
if !stamps.after {
let stage = crate::batch_order::start_stage(device.shared().by_ends);
raw.cmd_write_timestamp(buffer, stage, queries, first);
exit_guard::called(Call::CmdWriteTimestamp);
}
}
for barrier in barriers {
barrier.record(raw, buffer);
exit_guard::called(Call::CmdPipelineBarrier);
}
if !transitions.is_empty() {
let family = device.shared().queue_flags_of(self.queue.vk_queue());
let images: Vec<vk::ImageMemoryBarrier<'_>> = (transitions.iter())
.map(|transition| transition.barrier(family))
.collect();
let all = vk::PipelineStageFlags::ALL_COMMANDS;
raw.cmd_pipeline_barrier(
buffer,
all,
all,
vk::DependencyFlags::empty(),
&[],
&[],
&images,
);
exit_guard::called(Call::CmdPipelineBarrier);
}
if let Some((queries, first, _)) = stamps.start.filter(|_| stamps.after) {
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
raw.cmd_write_timestamp(buffer, bottom, queries, first);
exit_guard::called(Call::CmdWriteTimestamp);
}
if let Some((queries, first, _)) = stamps.end {
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
raw.cmd_write_timestamp(buffer, bottom, queries, first + 1);
exit_guard::called(Call::CmdWriteTimestamp);
}
let ended = self.end_raw(buffer);
exit_guard::called(Call::EndCommandBuffer);
ended.map_err(|error| submission_error(device, error))?;
}
Ok(buffer)
}
}
/// The command buffer's failure for a batch's sparse binding that failed: the device's memory, or
/// the bind itself.
fn bind_error(device: &crate::Device, failure: BindFailure) -> CommandBufferError {
match failure {
BindFailure::Memory(error) => recording_error(device, error),
BindFailure::Vulkan(error) => submission_error(device, error),
}
}
/// The timestamps a barrier command buffer writes into its command buffer's slot of the device's
/// timestamp pools, each the slot's pool, its first query and the holding's lease
/// (`gpu_time::Slot::lease`): the start (after resetting the slot) before its barriers at the top
/// of the pipe, or with `after` after them at the bottom of the pipe; the end after them.
#[derive(Clone, Copy)]
struct Stamps {
start: Option<(vk::QueryPool, u32, u64)>,
after: bool,
end: Option<(vk::QueryPool, u32, u64)>,
}
impl Stamps {
/// What a kept command buffer writes for these (`kept_barriers.rs`): `None` where they are
/// none.
fn kept(self) -> Option<SlotStamps> {
let (queries, first, lease) = self.start.or(self.end)?;
Some(SlotStamps {
queries,
first,
lease,
start: self.start.is_some(),
after: self.after,
end: self.end.is_some(),
})
}
}
/// The batches of `VkQueue`s other than `queue` that a batch of `buffer` waiting for `waits`
/// finishes after: for each wait, the batch whose kept GPU signal reaches its value, where that
/// batch's completion turn has not run; and, added to `waited`, the command buffers of other queues
/// those batches end, whose transitions to `Completed` have not run up to their completed handlers
/// (`EventShared::signallers`, `follow.rs`). None, and nothing allocated, for a batch that waits
/// for no event.
fn finishes_after(
waits: &[(Arc<EventShared>, u64)],
(queue, buffer): (usize, &CommandBufferShared),
waited: &mut Vec<Arc<Follow>>,
) -> Vec<Waited> {
let mut after: Vec<Waited> = Vec::new();
for (event, value) in waits {
let (batch, signaller) = event.signallers(*value);
if let Some((other, value)) = batch.filter(|(other, _)| *other != queue) {
let signaller = Waited {
queue: other,
value,
};
if !after.contains(&signaller) {
after.push(signaller);
}
}
// Of another queue: one of its own queue's is before it in its context.
let other_queue = |signaller: &Arc<Follow>| signaller.queue() != buffer.queue.id();
if let Some(signaller) = signaller.filter(other_queue) {
if !waited.iter().any(|known| Arc::ptr_eq(known, &signaller)) {
waited.push(signaller);
}
}
}
after
}
/// What a batch's encoders (or parts of them) `recorded` were, as the encoder trail names them
/// (`encoder_trail.rs`): each noted one, in order; `None` where none was noted.
fn batch_trail(recorded: &[Recorded]) -> Option<crate::encoder_trail::Named> {
crate::encoder_trail::Named::joined(recorded.iter().filter_map(|part| part.trail.as_ref()))
}
/// The images whose first use among `parts` (a batch's, in order) writes every texel before any
/// command reads one, by its encoder's own description (`Recorded::overwrites`), whose first
/// moves' zeros the batch's take leaves out (`FirstMoves::take_holding`): an overwrite by a part
/// with no segment (work recorded later, which may go before its commands), that only blit
/// parts with no segment naming nothing of the image come before (any other encoder's commands
/// may reach a texture through its resource ID, unnamed), and whose own uses read nothing of the
/// image but its attachment's own reads after its load (a pass's; a copy into or out of an image
/// standing in for it, or a shadow's copy, reads it otherwise) or nothing at all (a blit's). Empty, and
/// nothing allocated, where no part has an overwrite.
fn first_overwrites(parts: &[Recorded], ended: &[EncoderRecord]) -> Vec<ResourceKey> {
if parts.iter().all(|part| part.overwrites.is_empty()) {
return Vec::new();
}
// An attachment's own reads in its pass, after its load: blending, the depth and stencil
// tests, a fetch through an input attachment.
let attachment_reads = vk::AccessFlags2::COLOR_ATTACHMENT_READ
| vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_READ
| vk::AccessFlags2::INPUT_ATTACHMENT_READ;
let mut named = BTreeSet::new();
let mut overwritten = Vec::new();
for part in parts {
for overwrite in &part.overwrites {
let reads = (part.summary.uses().iter())
.filter(|used| used.key == overwrite.key)
.fold(vk::AccessFlags2::NONE, |reads, used| {
reads | used.read.access
});
let unread = match overwrite.by {
OverwriteBy::Pass => (reads & !attachment_reads).is_empty(),
OverwriteBy::Blit => reads.is_empty(),
};
if unread && part.segments.is_empty() && !named.contains(&overwrite.key) {
overwritten.push(overwrite.key);
}
}
let blit = (ended.get(part.encoder)).is_some_and(|record| record.kind == EncoderKind::Blit);
if !blit || !part.segments.is_empty() {
break;
}
named.extend(part.summary.keys());
}
overwritten
}