Group ready batches into one kernel submission on Mesa's drivers, and order a queue's batches by their ends
On ANV over i915 every kernel submission lists every VkDeviceMemory of the device, at a cost per
object; the consumer's guest drag on the Iris Xe had 302 entries per execbuffer (260 of them host
imports) at 112 to 128 execbuffers a frame. The runtime now makes fewer kernel submissions and
fewer command buffers per frame, under two new runtime policies.
What changes:
- DevicePolicy::completion, CompletionPolicy { Grouped (default), Exact }; exact_answers()
selects Exact. Under Grouped, on a driver whose queue merges consecutive submits (Mesa's common
queue: ANV, RADV, lavapipe, NVK and the rest), the scheduler holds ready batches of one VkQueue
and submits up to four in one vkQueueSubmit, only the last signalling, so Mesa merges them into
one kernel submission:
- a batch whose only signals are events' joins, the group's end signalling each event to the
highest index held; a batch waiting for a signal the group holds sends the group first;
- only a group's first member may wait for anything not yet seen complete, since Mesa gathers
every member's waits before the first member's commands; a later waiter goes alone after the
group in the same call. Metal never holds one command buffer back for another's wait;
- batches that cannot join (first work, binary semaphores, fences, sparse updates, wrapped
images, storage-form switches) submit the held group first;
- a pass that finds nothing ready keeps the group held while two or more earlier submissions of
its queue are not seen complete, gated on the second-to-last, so commits arriving meanwhile
join. It goes once full, when a head waits for the GPU, or when a thread waits for one of its
command buffers;
- a held batch that ends its command buffer turns Scheduled, takes its kernel end time and runs
its submission handlers as it is held, so waitUntilScheduled returns at once, as Metal
schedules a command buffer committed behind running work within 0.2 ms;
- submission checks run ahead for up to three batches behind a line's head, so checked command
buffers are found ready together; a failed group restores its waits, signals its last value
and fails each member once; the group's submission allocates nothing.
New degradation kind grouped-completion (Precision), announced once per device: a group's
members but the last are seen complete late, by at most three later batches' GPU time plus one
completion turn, and intermediate event values are seen late, never wrong.
- An event-signalling batch's end goes into its work's last command buffer, as every other batch's,
unless its signal must wait for another queue's earlier signal.
- DevicePolicy::batch_order, BatchOrderPolicy { Ends (default), Exact }; exact_answers() selects
Exact. On ANV, RADV and NVIDIA's driver, measured to run a queue's submissions one after another,
each batch ends with a barrier to every later command of its queue, the tracker takes an earlier
batch of that queue as ordered (no barrier per dependency), and a batch's start timestamp with
nothing planned before it is written at the bottom of the pipe. Other drivers and Exact keep the
barriers per dependency.
- WorkCounts: grouped_submissions, batches_grouped, group_ends_full / _wait / _apart /
_first_work / _drained / _checks / _held, event_waits_met, batches_with_none_pending and kin by
pending depth, groups_kept_pending and groups_sent_for_waits; frame_costs prints them, with
kernel submissions and ioctl time where the i915 execbuffer script is loaded, and gains guest-
shaped legs over 260 and 520 host imports.
- Docs: FAST-PATHS rows for both policies (the grouping row with the guest's frame rates), API.md
entries, add_submission_handler's doc, the runtime README and the scheduler modules' docs.
Why: each fewer kernel submission saves the scheduler thread an ioctl of about 80 to 130 us there,
and each barrier per dependency buys nothing on drivers that run a queue's submissions in order.
The bound of four was kept: eight measured about three fewer submissions a frame for twice the
completion lateness and no frame-time change.
Verified:
- Iris Xe, guest shape over 520 host imports, Grouped against Exact: 26.2-26.7 execbuffers a frame
against 67.0, ioctl 2.77-2.81 against 6.89-6.96 ms, scheduler 52-53 against 122-123 us per
command buffer, through completion 5.98 against 8.70 ms a frame.
- UHD 770, the held group at a 1 ms commit pace: 25.0 kernel submissions a frame against 58.1,
scheduler 67-82 against 113-124 us per command buffer, the same frame time and GPU idle;
completion seen 1.82-1.86 ms after GPU end against 0.43-0.46 ms.
- In the guest on the Iris Xe, Grouped made 24.4-27.5 kernel submissions a frame against Exact's
42.4-43.8 and saved 0.4-1.7 ms of scheduler CPU a frame; the frame rate was alike within
boot-to-boot noise (15.7-17.3 against 16.4-17.6 fps).
- runtime_lane::grouped_submissions (held signals on one and two queues, waiters leading, groups
held behind running work with and without submission handlers and checks, both policies, the
validation layer silent): 19 of 19 on ANV and lavapipe; the held-handler case fails without its
change. commit_work, gpu_times, grouped_submissions, queue_order, events and first-use lanes 77 of
77 on the Radeon 780M, RX 7900 XTX and RTX 5080; under synchronization validation 34 of 34 on
the UHD 770. The runtime's device tests 1066 of 1066 on ANV; the unit suites 4534 of 4534.
- clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc.
This commit is contained in:
1 parent
ed3ca3aa1f
commit
ca8340b4ee
41 files changed
+3614
-346
No files matched your search
@@ -19,7 +19,13 @@
|
||||
//! thread, without its own lock or the command buffer's, it then runs the check of each
|
||||
//! submission that begins in the batch, and again of each that a host step of the batch
|
||||
//! recorded commands for (what they reach is known only then), then submits the batch in its
|
||||
//! order.
|
||||
//! order. Where the scheduler groups batches (`CompletionPolicy::Grouped` on a driver that
|
||||
//! merges submissions, `group.rs`), it runs the checks of up to three batches right behind a
|
||||
//! head that goes with the head's, in commit order, each once its batch is otherwise ready and
|
||||
//! its events' values reached on the device or by the host, none committed after another
|
||||
//! queue's batch: so they go to the driver together. Such a check runs before the previous
|
||||
//! batch's `vkQueueSubmit`, in the pass that submits its own batch, where alone it runs after
|
||||
//! it. `CompletionPolicy::Exact` checks each head alone.
|
||||
//! - **Stricter than Metal: the re-check after a host step.** Metal checks a submission once,
|
||||
//! with what it knows as it submits it, and cannot know what the commands the GPU writes into
|
||||
//! an indirect command buffer reach before they run (an earlier encoder of the same submission
|
||||
|
||||
@@ -68,17 +68,17 @@
|
||||
//! every light queue's burst of the queue storm (`runtime_lane::queue_storms`) into its tail.
|
||||
//! While its waiter makes a turn, a queue's next batch waits for that turn to end before its wait
|
||||
//! begins; its fence and value stay signaled meanwhile.
|
||||
//! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes
|
||||
//! once the batch completed: its last command buffer makes them available to the host
|
||||
//! (`Barrier::to_host`), before its signal in submission order, and the host's reads come after
|
||||
//! a host wait for that signal. Vulkan orders host operations after a signal only through a
|
||||
//! wait: "signal operations happening before host operations that wait on them"
|
||||
//! system-synchronize-with them (the memory model), and a fence's "execution dependency is
|
||||
//! defined by waiting for a fence to become signaled, either via `vkWaitForFences` or by
|
||||
//! polling on `vkGetFenceStatus`". It gives `vkGetSemaphoreCounterValue` no such dependency (its
|
||||
//! value "may immediately be out of date"). So a value the read shows past the one a wait
|
||||
//! returned for (later batches that completed meanwhile, or the front's after a wait that ran
|
||||
//! out) is waited for in turn, a wait that returns at once ("If the condition is satisfied when
|
||||
//! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes once
|
||||
//! the batch completed: its last command buffer makes them available to the host
|
||||
//! (`Barrier::to_host`, or `Barrier::to_all`), before its signal in submission order, and the
|
||||
//! host's reads come after a host wait for that signal. Vulkan orders host operations after a
|
||||
//! signal only through a wait: "signal operations happening before host operations that wait on
|
||||
//! them" system-synchronize-with them (the memory model), and a fence's "execution dependency is
|
||||
//! defined by waiting for a fence to become signaled, either via `vkWaitForFences` or by polling
|
||||
//! on `vkGetFenceStatus`". It gives `vkGetSemaphoreCounterValue` no such dependency (its value
|
||||
//! "may immediately be out of date"). So a value the read shows past the one a wait returned for
|
||||
//! (later batches that completed meanwhile, or the front's after a wait that ran out) is waited
|
||||
//! for in turn, a wait that returns at once ("If the condition is satisfied when
|
||||
//! `vkWaitSemaphores` is called, then `vkWaitSemaphores` returns immediately"), before it is
|
||||
//! published: one call more, and only where the read ran ahead.
|
||||
//! - **Waits are bounded.** A waiter waits at most [`WAIT_SLICE`] at a time, so a stop is seen
|
||||
|
||||
@@ -1,2 +1,593 @@
|
||||
//! Batches that go to the driver in one kernel submission (`CompletionPolicy::Grouped`).
|
||||
//!
|
||||
//! On a driver whose queue is Mesa's common one, each `vkQueueSubmit`'s `VkSubmitInfo`s that
|
||||
//! signal nothing merge into the next one's kernel submission (Mesa 26.2.4,
|
||||
//! `vulkan/runtime/vk_queue.c`, `vk_queue_submits_merge`: "Don't merge if there are signals in
|
||||
//! between"), and ANV chains the merged command buffers into one batch buffer
|
||||
//! (`anv_queue_submit_cmd_buffers_locked`). Each kernel submission costs CPU time for every
|
||||
//! `VkDeviceMemory` of the device: ANV on i915 lists each in every execbuffer
|
||||
//! (`i915/anv_batch_chain.c`, `setup_execbuf_for_cmd_buffers`), RADV each in every CS.
|
||||
//!
|
||||
//! - **What waits.** A batch the scheduler submits waits here, submitted by nothing yet, where it
|
||||
//! signals nothing but its queue's timeline and its events' semaphores: no binary semaphore,
|
||||
//! no fence; binds no sparse update; does no first work; moves none of the caller's wrapped
|
||||
//! images; and waits for no event index a batch held signals (only the group's end would meet
|
||||
//! it: on one `VkQueue` that wait would never be met). Every other batch goes as before, after
|
||||
//! the group held on its `VkQueue` went (`Submitting::AfterGroup`), and so does one of another
|
||||
//! `VkQueue`, so a wait there for a held signal follows the group's submission too. A batch
|
||||
//! that waits for anything not seen complete (an event, another `VkQueue`'s work, first work)
|
||||
//! leads a group and never joins one: it goes after a group held, in a submission of its own.
|
||||
//! A group goes at once when it holds [`GROUP_BATCHES`], so no submission holds more.
|
||||
//! - **Checked ahead.** A batch with submission checks is ready only once they ran
|
||||
//! (`checks.rs`), which the scheduler does for each line's head; here it runs those of the
|
||||
//! batches right behind a head that goes too, so a line of checked batches (the consumer checks
|
||||
//! every command buffer) is found ready together (`scheduler::check_heads`).
|
||||
//! - **One submission.** [`Group::submit`] submits every batch held, in order, in one
|
||||
//! `vkQueueSubmit` where only the last `VkSubmitInfo` signals: each event's semaphore to the
|
||||
//! highest index a batch held signals it to, then the queue's timeline to the last batch's
|
||||
//! value. Each is above every other batch's signal of it, so it reaches theirs too ("the
|
||||
//! semaphore's value is set to the signal value" once the batch's commands complete, and a value
|
||||
//! reached is reached by every wait for a lower one; the first synchronization scope of a signal
|
||||
//! holds "every command in the same batch ... and all commands that occur earlier in submission
|
||||
//! order", `vkQueueSubmit`). An event's indices rise in its signals' submission order
|
||||
//! (`event_timeline.rs`), so its earlier values land with the group's end, late, never wrong:
|
||||
//! a wait on another `VkQueue` for one is met by the higher index, and the host's waits, value
|
||||
//! reads and listeners see the event's value rise once that index is seen. Each batch keeps its
|
||||
//! own commands, barriers and its end's barrier to the host. Only the first batch may wait for a
|
||||
//! value not seen complete, for a signal submitted before it, the scheduler's order: the merge
|
||||
//! gathers every batch's waits before the first one's commands, so a later batch's wait would
|
||||
//! hold back the earlier ones' start until it is met, and none is held.
|
||||
//! - **Taken as made.** What a batch's submission changes in the scheduler's state (the tracker's
|
||||
//! plan, its queue's value, the completed values its queue waited for) is changed as it is held,
|
||||
//! so the next batch is planned after it. Where it ends its command buffer, on which no switch of
|
||||
//! storage forms rides, the command buffer's kernel end and its transition to `Scheduled` come as
|
||||
//! it is held, its submission handlers run before that on the scheduler's thread once its lock is
|
||||
//! free, as a submitted batch's do ([`Group::schedule_held`]), as Metal schedules a command
|
||||
//! buffer committed behind running work at once: on an M3 Max under macOS 27.0.1, each of 8
|
||||
//! committed behind a 55 ms kernel on its queue was `Scheduled` 0.04 to 0.18 ms after its commit,
|
||||
//! its scheduled handler run, about 55 ms before that kernel ended (probe `scheduled`). Its queue
|
||||
//! waiter's watch comes once the group is submitted. A submission that fails without losing the
|
||||
//! device changed nothing (`vkQueueSubmit`), so the events' semaphores and the timeline are
|
||||
//! brought to the group's end by a submission of those signals alone, the waits taken are put
|
||||
//! back, and each batch's command buffer fails (one already `Scheduled` from there); where that
|
||||
//! fails too, the device is lost to the runtime, its timeline short of the values its tracker
|
||||
//! holds.
|
||||
//! - **Kept while its queue runs earlier work** ([`Group::keeps`]). A pass that finds no batch
|
||||
//! ready sends the group, unless two or more submissions of its `VkQueue` are not seen complete
|
||||
//! (`QueueSlot::pending_beyond_one`): the GPU runs those first in any case, in submission order,
|
||||
//! so the group stays held for the batches committed meanwhile, gated on the value whose
|
||||
//! completion leaves one submission in flight, at which a completion turn wakes the scheduler.
|
||||
//! It goes with one in flight rather than two: on the UHD 770 two cut the kernel submissions
|
||||
//! less (30 a frame against 24, at 67 command buffers a frame committed 1 ms apart behind 1.3 ms
|
||||
//! of GPU work each) and left the GPU as idle (0.62 ms a frame with either).
|
||||
//! It goes then, or once it fills, a batch that cannot join sends it, a head waits for the GPU
|
||||
//! (at a gate, or for a signal to land, which may be the group's), or a thread waits for one of
|
||||
//! its command buffers' completion (`CommandBuffer::wait_until_completed` marks it and wakes the
|
||||
//! scheduler: [`CommandBufferShared::waits_for_completion`]). A group whose batch ends a command
|
||||
//! buffer with a switch of storage forms riding on it is never kept: the switch settles by the
|
||||
//! submission's outcome, before the command buffer is `Scheduled`. A kept batch is seen
|
||||
//! complete late by its group's later batches' GPU time, as any member, and where the one
|
||||
//! submission left in flight ends before the group reaches the GPU, by that gap besides: at most
|
||||
//! a completion turn's reaction and the group's `vkQueueSubmit`. Counted:
|
||||
//! `WorkCounts::groups_kept_pending`, `WorkCounts::groups_sent_for_waits`.
|
||||
//! - **Counted by its end.** Each group held counts once by what sent it ([`GroupEnd`],
|
||||
//! `WorkCounts::group_ends_full` and kin): so the consumer's counts say why its groups hold
|
||||
//! fewer batches than they may.
|
||||
//! - **No allocation.** A group's submission names at most [`MOST_INFOS`] `VkSubmitInfo`s, built
|
||||
//! in arrays on the thread's stack; its end's signals and its submissions go to lists the group
|
||||
//! keeps with their room: the scheduler thread allocates nothing for it
|
||||
//! (`runtime_lane::frame_costs`, `a_frame_s_commits_allocate_within_their_bound`).
|
||||
|
||||
use super::submit::Submission;
|
||||
use super::{submission_error, CommandBufferShared};
|
||||
use crate::degradation::Degradation;
|
||||
use crate::device::relay::Relayed;
|
||||
use crate::error::CommandBufferError;
|
||||
use crate::exit_guard::{self, Call};
|
||||
use crate::gpu_time;
|
||||
use crate::Device;
|
||||
use ash::vk;
|
||||
use metal2vulkan::device::CompletionPolicy;
|
||||
use metal2vulkan::vk::DriverId;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The most batches one kernel submission holds: the first is seen complete late by the GPU time
|
||||
/// of at most this many less one.
|
||||
pub(crate) const GROUP_BATCHES: usize = 4;
|
||||
|
||||
/// The most `VkSubmitInfo`s a batch names: its work's and its finale's (`submit.rs`).
|
||||
const BATCH_INFOS: usize = 2;
|
||||
|
||||
/// The most `VkSubmitInfo`s one group's `vkQueueSubmit` names: [`BATCH_INFOS`] for each batch
|
||||
/// held, and for the batch after them its first work's beside its own.
|
||||
const MOST_INFOS: usize = GROUP_BATCHES * BATCH_INFOS + 1 + BATCH_INFOS;
|
||||
|
||||
/// Whether `device`'s batches on `VkQueue` `queue` may wait in a group: its policy groups them,
|
||||
/// its driver merges a submission that signals nothing into the next (the module docs), and the
|
||||
/// queue's failures are not relayed (each relayed batch takes a fence, `device/relay.rs`).
|
||||
pub(crate) fn groups(device: &Device, queue: usize) -> bool {
|
||||
device.compile_device().policy().completion == CompletionPolicy::Grouped
|
||||
&& merges_submissions(device.properties().description.driver_id)
|
||||
&& device.shared().flights(queue).is_none()
|
||||
}
|
||||
|
||||
impl CommandBufferShared {
|
||||
/// Whether its batches may wait in a group ([`groups`]).
|
||||
pub(crate) fn groups(&self) -> bool {
|
||||
groups(&self.device, self.queue.vk_queue())
|
||||
}
|
||||
|
||||
/// A batch of it was held in the scheduler's group.
|
||||
pub(crate) fn held_in_group(&self) {
|
||||
self.group_hold.fetch_or(IN_GROUP, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Its batches held in the group went, or failed.
|
||||
pub(crate) fn left_group(&self) {
|
||||
self.group_hold.fetch_and(!IN_GROUP, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// A thread begins to wait for its completion: where a batch of it is held in the group, the
|
||||
/// scheduler is woken, and sends the group at once ([`Group::keeps`]). The scheduler marks a
|
||||
/// batch held before it looks for a waiter, and the waiter marks its wait before it looks for
|
||||
/// a batch held, each on the same word, so one of the two sees the other.
|
||||
pub(crate) fn waits_for_completion(&self) {
|
||||
let before = self.group_hold.fetch_or(WAITED_FOR, Ordering::SeqCst);
|
||||
if before & IN_GROUP != 0 {
|
||||
self.device.shared().scheduler.wake();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a thread waits for its completion.
|
||||
fn is_waited_for(&self) -> bool {
|
||||
self.group_hold.load(Ordering::SeqCst) & WAITED_FOR != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// A command buffer's `group_hold` bit: a batch of it is held in the scheduler's group.
|
||||
const IN_GROUP: u8 = 1;
|
||||
|
||||
/// A command buffer's `group_hold` bit: a thread waits for its completion.
|
||||
const WAITED_FOR: u8 = 2;
|
||||
|
||||
/// Whether the driver's queue is Mesa's common one with kernel submissions of their own: the
|
||||
/// drivers that merge a `VkSubmitInfo` that signals nothing into the next.
|
||||
fn merges_submissions(driver: Option<DriverId>) -> bool {
|
||||
matches!(
|
||||
driver,
|
||||
Some(
|
||||
DriverId::MESA_RADV
|
||||
| DriverId::INTEL_OPEN_SOURCE_MESA
|
||||
| DriverId::MESA_LLVMPIPE
|
||||
| DriverId::MESA_TURNIP
|
||||
| DriverId::MESA_V3DV
|
||||
| DriverId::MESA_PANVK
|
||||
| DriverId::MESA_NVK
|
||||
| DriverId::MESA_HONEYKRISP
|
||||
| DriverId::IMAGINATION_OPEN_SOURCE_MESA
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// What sent a group held (`WorkCounts::group_ends_full` and kin).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum GroupEnd {
|
||||
/// It held [`GROUP_BATCHES`].
|
||||
Full,
|
||||
/// A batch waits: for an event index a batch held signals, which only the group's end meets,
|
||||
/// or for anything else not seen complete (it goes after the group, never in it).
|
||||
Wait,
|
||||
/// A batch that may not wait in a group (a binary semaphore, a fence, a sparse update, a move
|
||||
/// of bytes that waits for every submission), or one of another `VkQueue`.
|
||||
Apart,
|
||||
/// A batch that may join did first work or names a wrapped image: it went last in the group's
|
||||
/// call.
|
||||
FirstWork,
|
||||
/// The pass found no batch left to submit.
|
||||
Drained,
|
||||
/// The pass found none ready, with submission checks or host steps left for the thread to run.
|
||||
Checks,
|
||||
/// The pass found none ready, the rest held for events, gates, binary semaphores or decodes.
|
||||
Held,
|
||||
}
|
||||
|
||||
/// One `VkSubmitInfo`'s lists, kept with their room from batch to batch.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Info {
|
||||
wait_semaphores: Vec<vk::Semaphore>,
|
||||
wait_values: Vec<u64>,
|
||||
wait_stages: Vec<vk::PipelineStageFlags>,
|
||||
buffers: Vec<vk::CommandBuffer>,
|
||||
signal_semaphores: Vec<vk::Semaphore>,
|
||||
signal_values: Vec<u64>,
|
||||
}
|
||||
|
||||
/// What one `VkSubmitInfo` waits for, runs and signals, borrowed.
|
||||
pub(crate) struct InfoParts<'a> {
|
||||
pub(crate) waits: (&'a [vk::Semaphore], &'a [u64], &'a [vk::PipelineStageFlags]),
|
||||
pub(crate) buffers: &'a [vk::CommandBuffer],
|
||||
pub(crate) signals: (&'a [vk::Semaphore], &'a [u64]),
|
||||
}
|
||||
|
||||
impl Info {
|
||||
fn fill(&mut self, parts: &InfoParts<'_>) {
|
||||
let (semaphores, values, stages) = parts.waits;
|
||||
self.wait_semaphores.clear();
|
||||
self.wait_semaphores.extend_from_slice(semaphores);
|
||||
self.wait_values.clear();
|
||||
self.wait_values.extend_from_slice(values);
|
||||
self.wait_stages.clear();
|
||||
self.wait_stages.extend_from_slice(stages);
|
||||
self.buffers.clear();
|
||||
self.buffers.extend_from_slice(parts.buffers);
|
||||
let (semaphores, values) = parts.signals;
|
||||
self.signal_semaphores.clear();
|
||||
self.signal_semaphores.extend_from_slice(semaphores);
|
||||
self.signal_values.clear();
|
||||
self.signal_values.extend_from_slice(values);
|
||||
}
|
||||
}
|
||||
|
||||
/// A batch held: its `VkSubmitInfo`s, how many command buffers they hold, and its submission,
|
||||
/// published once the group is submitted.
|
||||
struct Member {
|
||||
infos: Vec<Info>,
|
||||
buffers: usize,
|
||||
submission: Submission,
|
||||
}
|
||||
|
||||
/// The batches held for one kernel submission on one `VkQueue` (the module docs), in the
|
||||
/// scheduler's state.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Group {
|
||||
queue: usize,
|
||||
members: Vec<Member>,
|
||||
/// It stayed held past a pass for the work its queue ran ([`keeps`](Group::keeps)).
|
||||
kept: bool,
|
||||
/// The completed values `queue` waited for before the first batch held: put back where the
|
||||
/// group's submission fails.
|
||||
waited: Vec<u64>,
|
||||
/// The events' semaphores the batches held signal, each with the lowest and the highest index
|
||||
/// they signal it to: the group's end signals the highest (the module docs).
|
||||
events: Vec<(vk::Semaphore, u64, u64)>,
|
||||
/// The lists of batches submitted, kept with their room.
|
||||
spare: Vec<Vec<Info>>,
|
||||
/// The end's signals: each event's semaphore, then the queue's timeline, and their values;
|
||||
/// kept with their room.
|
||||
end_semaphores: Vec<vk::Semaphore>,
|
||||
end_values: Vec<u64>,
|
||||
/// The batches the group's last submission made, in order, until the scheduler takes them
|
||||
/// ([`made`](Group::made)); kept with their room.
|
||||
made: Vec<Submission>,
|
||||
/// What the group's last submission did, until the scheduler takes it
|
||||
/// ([`take_outcome`](Group::take_outcome)): made ([`made`](Group::made)), or failed.
|
||||
outcome: Option<Result<(), CommandBufferError>>,
|
||||
}
|
||||
|
||||
/// A batch submitted after the group, in the same `vkQueueSubmit` ([`Group::submit`]).
|
||||
pub(crate) struct After<'a> {
|
||||
/// Its `VkQueue`: the group's, where one is held.
|
||||
pub(crate) queue: usize,
|
||||
pub(crate) infos: &'a [vk::SubmitInfo<'a>],
|
||||
pub(crate) buffers: usize,
|
||||
/// The value it signals on the queue's timeline.
|
||||
pub(crate) value: u64,
|
||||
pub(crate) fence: Option<vk::Fence>,
|
||||
pub(crate) relayed: &'a Arc<Relayed>,
|
||||
}
|
||||
|
||||
impl Group {
|
||||
/// The `VkQueue` of the batches held.
|
||||
pub(crate) fn queue(&self) -> usize {
|
||||
self.queue
|
||||
}
|
||||
|
||||
/// Whether it holds a batch.
|
||||
pub(crate) fn holds(&self) -> bool {
|
||||
!self.members.is_empty()
|
||||
}
|
||||
|
||||
/// Whether a batch on `VkQueue` `queue` may be submitted now, the group held so far going
|
||||
/// first: the group is empty, or the batch may wait in it (`joins`) on its queue with room.
|
||||
pub(crate) fn admits(&self, queue: usize, joins: bool) -> bool {
|
||||
self.members.is_empty()
|
||||
|| (joins && self.queue == queue && self.members.len() < GROUP_BATCHES)
|
||||
}
|
||||
|
||||
/// Whether a batch held signals the event of `semaphore` to `index` or above: only the group's
|
||||
/// end meets a wait for it, so a batch with that wait goes after the group, in a submission
|
||||
/// of its own (the module docs). A lower index was signalled before the group.
|
||||
pub(crate) fn meets(&self, (semaphore, index): (vk::Semaphore, u64)) -> bool {
|
||||
(self.events.iter()).any(|&(signaled, lowest, _)| signaled == semaphore && index >= lowest)
|
||||
}
|
||||
|
||||
/// Whether the group holds [`GROUP_BATCHES`]: the scheduler submits it at once. A batch that
|
||||
/// may join, found with room, goes with at most a batch less held, so no submission holds
|
||||
/// more.
|
||||
pub(crate) fn full(&self) -> bool {
|
||||
self.members.len() >= GROUP_BATCHES
|
||||
}
|
||||
|
||||
/// A batch on `VkQueue` `queue` is held, before its submission changes the scheduler's
|
||||
/// state: `waited` is what `queue` waited for so far, put back where the group's submission
|
||||
/// fails. Its lists come once its changes are made ([`hold`](Group::hold)).
|
||||
pub(crate) fn open(&mut self, queue: usize, waited: &[u64]) {
|
||||
if self.members.is_empty() {
|
||||
self.queue = queue;
|
||||
self.waited.clear();
|
||||
self.waited.extend_from_slice(waited);
|
||||
}
|
||||
}
|
||||
|
||||
/// The batch [`open`](Group::open) took: its `VkSubmitInfo`s are `infos` (at most
|
||||
/// [`BATCH_INFOS`]), with `buffers` command buffers, and its submission is published once the
|
||||
/// group's is made. It signals each event's semaphore it names to its index, which the
|
||||
/// group's end signals instead.
|
||||
pub(crate) fn hold(&mut self, infos: &[InfoParts<'_>], buffers: usize, submission: Submission) {
|
||||
for (semaphore, index) in submission.event_signals() {
|
||||
match self.events.iter_mut().find(|(held, ..)| *held == semaphore) {
|
||||
Some((_, lowest, highest)) => {
|
||||
*lowest = (*lowest).min(index);
|
||||
*highest = (*highest).max(index);
|
||||
}
|
||||
None => self.events.push((semaphore, index, index)),
|
||||
}
|
||||
}
|
||||
let mut held = self.spare.pop().unwrap_or_default();
|
||||
held.resize_with(infos.len(), Info::default);
|
||||
for (info, parts) in held.iter_mut().zip(infos) {
|
||||
info.fill(parts);
|
||||
}
|
||||
self.members.push(Member {
|
||||
infos: held,
|
||||
buffers,
|
||||
submission,
|
||||
});
|
||||
}
|
||||
|
||||
/// The batch [`hold`](Group::hold) took last, after the section that held it ended: where it
|
||||
/// ends its command buffer and no switch of storage forms rides on it, its kernel end and its
|
||||
/// transition to `Scheduled` now, not once the group is submitted, and its submission
|
||||
/// handlers for the scheduler's thread to run now, once its lock is free (the module docs):
|
||||
/// whether it has them.
|
||||
pub(crate) fn schedule_held(&mut self) -> bool {
|
||||
(self.members.last_mut()).is_some_and(|member| member.submission.schedule_held())
|
||||
}
|
||||
|
||||
/// Whether the batches held stay held past the pass that found no batch ready (the module
|
||||
/// docs): the group has room, two or more submissions of its `VkQueue` are not seen complete,
|
||||
/// no batch held ends a command buffer with a switch of storage forms riding on it (it settles
|
||||
/// by the submission's outcome), no thread waits for one of their command buffers, and the
|
||||
/// device is not lost.
|
||||
/// The value of that queue's timeline whose completion leaves one submission in flight, for
|
||||
/// the completion turns to wake the scheduler at. Counted once per group, and once more where
|
||||
/// a waiter sends a group kept before.
|
||||
pub(crate) fn keeps(&mut self) -> Option<u64> {
|
||||
let first = self.members.first()?;
|
||||
let device = first.submission.buffer().device();
|
||||
if self.full()
|
||||
|| device.is_lost()
|
||||
|| (self.members.iter()).any(|member| member.submission.rides_forms())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let counts = &device.shared().counts;
|
||||
if (self.members.iter()).any(|member| member.submission.buffer().is_waited_for()) {
|
||||
if self.kept {
|
||||
counts.group_sent_for_wait();
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let value = device.shared().queues[self.queue].pending_beyond_one()?;
|
||||
if !self.kept {
|
||||
self.kept = true;
|
||||
counts.group_kept_pending();
|
||||
}
|
||||
Some(value)
|
||||
}
|
||||
|
||||
/// What the group's last submission did, for the scheduler to publish its batches
|
||||
/// ([`made`](Group::made)) or fail them.
|
||||
pub(crate) fn take_outcome(&mut self) -> Option<Result<(), CommandBufferError>> {
|
||||
self.outcome.take()
|
||||
}
|
||||
|
||||
/// The batches the group's last submission made, in order, for the scheduler to publish.
|
||||
pub(crate) fn made(&mut self) -> std::vec::Drain<'_, Submission> {
|
||||
self.made.drain(..)
|
||||
}
|
||||
|
||||
/// Submit every batch held, then `after` where given, in one `vkQueueSubmit` on the group's
|
||||
/// `VkQueue` of `device`, only the last signalling (the module docs); `waited` is the
|
||||
/// scheduler's list of what that queue waited for. Inside a section of the exit guard. The
|
||||
/// held batches' outcome is kept for the scheduler ([`take_outcome`](Group::take_outcome));
|
||||
/// the call's own result is `after`'s, as the `vkQueueSubmit` returned it.
|
||||
pub(crate) fn submit(
|
||||
&mut self,
|
||||
device: &Device,
|
||||
waited: &mut [u64],
|
||||
after: Option<After<'_>>,
|
||||
) -> Result<(), vk::Result> {
|
||||
if self.members.is_empty() {
|
||||
return match after {
|
||||
None => Ok(()),
|
||||
Some(after) => submit_alone(device, after),
|
||||
};
|
||||
}
|
||||
let shared = device.shared();
|
||||
let raw = shared.vk();
|
||||
let queue = self.queue;
|
||||
let count = self.members.len();
|
||||
let alone = after.is_none();
|
||||
self.kept = false;
|
||||
let held_value = self.members[count - 1].submission.value();
|
||||
// The held batches' end: each event's semaphore to the highest index a batch held
|
||||
// signals it to, then the queue's timeline to the last one's value. It ends the
|
||||
// submission, or, where a batch goes after the group and the held ones signal an event,
|
||||
// their part of it (that batch's infos then follow a signal, so the driver submits them
|
||||
// apart).
|
||||
let ends = alone || !self.events.is_empty();
|
||||
self.end_semaphores.clear();
|
||||
(self.end_semaphores).extend((self.events.iter()).map(|&(semaphore, ..)| semaphore));
|
||||
(self.end_semaphores).push(shared.queues[queue].timeline);
|
||||
self.end_values.clear();
|
||||
(self.end_values).extend((self.events.iter()).map(|&(_, _, highest)| highest));
|
||||
self.end_values.push(held_value);
|
||||
let (end_semaphores, end_values) = (&self.end_semaphores, &self.end_values);
|
||||
// Only the held batches' last `VkSubmitInfo` signals: every other one's signals (its
|
||||
// queue's timeline and its events') are reached by the end's higher values.
|
||||
let held = || (self.members.iter()).flat_map(|member| &member.infos);
|
||||
let infos = held().count();
|
||||
let submitting = infos + after.as_ref().map_or(0, |after| after.infos.len());
|
||||
// Each batch's `VkSubmitInfo`s are its work's and its finale's (`submit.rs`), and the
|
||||
// group holds at most `GROUP_BATCHES`: none is left out of the arrays.
|
||||
assert!(
|
||||
submitting <= MOST_INFOS,
|
||||
"{submitting} VkSubmitInfos in one submission"
|
||||
);
|
||||
let signals = |at: usize| ends && at + 1 == infos;
|
||||
let mut timelines = [vk::TimelineSemaphoreSubmitInfo::default(); MOST_INFOS];
|
||||
for (at, (timeline, info)) in timelines.iter_mut().zip(held()).enumerate() {
|
||||
let values: &[u64] = if signals(at) { end_values } else { &[] };
|
||||
*timeline = vk::TimelineSemaphoreSubmitInfo::default()
|
||||
.wait_semaphore_values(&info.wait_values)
|
||||
.signal_semaphore_values(values);
|
||||
}
|
||||
let mut submits = [vk::SubmitInfo::default(); MOST_INFOS];
|
||||
let built = submits.iter_mut().zip(timelines.iter_mut()).zip(held());
|
||||
for (at, ((submit, timeline), info)) in built.enumerate() {
|
||||
let semaphores: &[vk::Semaphore] = if signals(at) { end_semaphores } else { &[] };
|
||||
*submit = vk::SubmitInfo::default()
|
||||
.wait_semaphores(&info.wait_semaphores)
|
||||
.wait_dst_stage_mask(&info.wait_stages)
|
||||
.command_buffers(&info.buffers)
|
||||
.signal_semaphores(semaphores)
|
||||
.push_next(timeline);
|
||||
}
|
||||
let mut buffers: usize = (self.members.iter()).map(|member| member.buffers).sum();
|
||||
let last = &self.members[count - 1].submission;
|
||||
let relayed = Arc::clone(match &after {
|
||||
Some(after) => after.relayed,
|
||||
None => &last.buffer().relayed,
|
||||
});
|
||||
let (value, fence) = match &after {
|
||||
Some(after) => {
|
||||
submits[infos..submitting].copy_from_slice(after.infos);
|
||||
buffers += after.buffers;
|
||||
(after.value, after.fence)
|
||||
}
|
||||
None => (held_value, None),
|
||||
};
|
||||
let submits = &submits[..submitting];
|
||||
// SAFETY: as each batch's own submission (`submit.rs`): every command buffer is
|
||||
// executable and submitted once; every wait is for a signal submitted before; the one
|
||||
// timeline signal is above the queue's value; the `VkQueue` is used under its lock.
|
||||
let submitted =
|
||||
shared.submit_logged((queue, Some(value)), fence, &relayed, |vk_queue| unsafe {
|
||||
shared.counts.queue_submitted(buffers);
|
||||
raw.queue_submit(vk_queue, submits, fence.unwrap_or(vk::Fence::null()))
|
||||
});
|
||||
exit_guard::called(Call::QueueSubmit);
|
||||
self.events.clear();
|
||||
let several = count + usize::from(!alone) > 1;
|
||||
let outcome = match submitted {
|
||||
Ok(()) => {
|
||||
let now = gpu_time::host_nanos();
|
||||
for member in self.members.drain(..) {
|
||||
self.spare.push(member.infos);
|
||||
if member.submission.ends() && !member.submission.scheduled() {
|
||||
member.submission.buffer().kernel.end_at(now);
|
||||
}
|
||||
self.made.push(member.submission);
|
||||
}
|
||||
if several {
|
||||
shared.counts.batches_grouped(count + usize::from(!alone));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
for member in self.members.drain(..) {
|
||||
self.spare.push(member.infos);
|
||||
}
|
||||
waited.copy_from_slice(&self.waited);
|
||||
let failure = submission_error(device, error);
|
||||
if !device.is_lost()
|
||||
&& signal_alone(
|
||||
device,
|
||||
queue,
|
||||
(&self.end_semaphores, &self.end_values),
|
||||
&relayed,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
device.mark_lost();
|
||||
}
|
||||
if matches!(failure, CommandBufferError::DeviceLost) && alone {
|
||||
device.drain_queues();
|
||||
}
|
||||
Err(failure)
|
||||
}
|
||||
};
|
||||
if several && outcome.is_ok() {
|
||||
let batches = count + usize::from(!alone);
|
||||
device.degrade_once(Degradation::GroupedCompletion, || {
|
||||
(
|
||||
format!("{batches} batches of command buffers on one queue"),
|
||||
"the scheduler found them ready together, on a driver that merges a \
|
||||
submission that signals nothing into the next one"
|
||||
.to_owned(),
|
||||
)
|
||||
});
|
||||
}
|
||||
self.outcome = Some(outcome);
|
||||
submitted
|
||||
}
|
||||
}
|
||||
|
||||
/// Submit `after` alone on its `VkQueue` of `device`: the group's submission with no batch held.
|
||||
fn submit_alone(device: &Device, after: After<'_>) -> Result<(), vk::Result> {
|
||||
let shared = device.shared();
|
||||
let raw = shared.vk();
|
||||
let After {
|
||||
queue,
|
||||
infos,
|
||||
buffers,
|
||||
value,
|
||||
fence,
|
||||
relayed,
|
||||
} = after;
|
||||
// SAFETY: the batch's submission's own (`submit.rs`).
|
||||
let submitted = shared.submit_logged((queue, Some(value)), fence, relayed, |vk_queue| unsafe {
|
||||
shared.counts.queue_submitted(buffers);
|
||||
raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null()))
|
||||
});
|
||||
exit_guard::called(Call::QueueSubmit);
|
||||
submitted
|
||||
}
|
||||
|
||||
/// Signal the end a failed group held (its events' semaphores to their indices, then `VkQueue`
|
||||
/// `queue`'s timeline to its last value) with a submission of nothing else, after the group's
|
||||
/// submission failed without losing the device (the module docs).
|
||||
fn signal_alone(
|
||||
device: &Device,
|
||||
queue: usize,
|
||||
(semaphores, values): (&[vk::Semaphore], &[u64]),
|
||||
relayed: &Arc<Relayed>,
|
||||
) -> Result<(), vk::Result> {
|
||||
let shared = device.shared();
|
||||
let raw = shared.vk();
|
||||
let value = values.last().copied();
|
||||
let mut timeline = vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(values);
|
||||
let info = vk::SubmitInfo::default()
|
||||
.signal_semaphores(semaphores)
|
||||
.push_next(&mut timeline);
|
||||
// SAFETY: a submission of the signals a failed group's end held, each above its semaphore's
|
||||
// value (no batch signalled them); the `VkQueue` is used under its lock.
|
||||
let submitted = shared.submit_logged((queue, value), None, relayed, |vk_queue| unsafe {
|
||||
shared.counts.queue_submitted(0);
|
||||
raw.queue_submit(vk_queue, &[info], vk::Fence::null())
|
||||
});
|
||||
exit_guard::called(Call::QueueSubmit);
|
||||
submitted
|
||||
}
|
||||
@@ -2,20 +2,20 @@
|
||||
//!
|
||||
//! A batch with encoders submits a command buffer of barriers before each encoder the tracker
|
||||
//! planned a barrier for (before its first, whatever was planned, where the driver's submissions
|
||||
//! stall on semaphore operations: `Barrier::after_completed`, `submit.rs`), and, where its end
|
||||
//! did not go into its last encoder's command buffer, one after its last (`Barrier::to_host`;
|
||||
//! `submit.rs`): batch after batch, the same few lists of barriers. A timed command buffer's
|
||||
//! first batch also resets its slot of the device's timestamp
|
||||
//! pools and writes the start timestamp first, in a command buffer before its first encoder (of
|
||||
//! the barrier planned for it, or of none), and its last batch writes the end timestamp in its
|
||||
//! end (`gpu_time.rs`). Each list's command buffer is recorded once, kept by the scheduler, and
|
||||
//! stall on semaphore operations: `Barrier::after_completed`, `submit.rs`), and, where its end did
|
||||
//! not go into its last encoder's command buffer, one after its last (`Barrier::to_host`, or
|
||||
//! `Barrier::to_all`: `batch_order.rs`; `submit.rs`): batch after batch, the same few lists of
|
||||
//! barriers. A timed command buffer's first batch also resets its slot of the device's timestamp
|
||||
//! pools and writes the start timestamp first, in a command buffer before its first encoder (of the
|
||||
//! barrier planned for it, or of none), and its last batch writes the end timestamp in its end
|
||||
//! (`gpu_time.rs`). Each list's command buffer is recorded once, kept by the scheduler, and
|
||||
//! submitted again by a later batch once the batch that last carried it completed, its queue's
|
||||
//! timeline at that batch's value as the host saw it: the same commands, in the same place of the
|
||||
//! same submission, and no command buffer begun for them as a batch is submitted. ANV clears a
|
||||
//! command buffer's state as its pool resets it and again as it begins it (Mesa 26.2.4,
|
||||
//! `anv_cmd_state_init`, 62,776 bytes), and packs the standard sample pattern at each primary
|
||||
//! one's begin where `VK_EXT_sample_locations` is enabled (`genX(BeginCommandBuffer)`): on ms01's
|
||||
//! Iris Xe those begins were 53% of the scheduler thread's user time, two a command buffer.
|
||||
//! `anv_cmd_state_init`, 62,776 bytes), and packs the standard sample pattern at each primary one's
|
||||
//! begin where `VK_EXT_sample_locations` is enabled (`genX(BeginCommandBuffer)`): on ms01's Iris Xe
|
||||
//! those begins were 53% of the scheduler thread's user time, two a command buffer.
|
||||
//!
|
||||
//! - **Never pending twice.** A kept command buffer is recorded without
|
||||
//! `VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT` and goes to one batch at a time: ANV chains a
|
||||
@@ -84,8 +84,9 @@ pub(crate) struct KeptBarriers {
|
||||
|
||||
/// The timestamps a barrier command buffer writes into a timed command buffer's slot of the
|
||||
/// device's timestamp pools (`gpu_time::Slot`): with `start`, the slot reset before its barriers
|
||||
/// and the start timestamp before them at the top of the pipe, or with `after` after them at the
|
||||
/// bottom of the pipe; with `end`, the end timestamp after them.
|
||||
/// and the start timestamp before them at the top of the pipe (the bottom where batches are
|
||||
/// ordered by their ends: `batch_order.rs`), or with `after` after them at the bottom of the pipe;
|
||||
/// with `end`, the end timestamp after them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct SlotStamps {
|
||||
/// The slot's timestamp pool.
|
||||
@@ -369,8 +370,8 @@ impl KeptBarriers {
|
||||
exit_guard::called(Call::CmdResetQueryPool);
|
||||
}
|
||||
if !stamps.after {
|
||||
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, top, stamps.queries, stamps.first);
|
||||
let stage = crate::batch_order::start_stage(shared.by_ends);
|
||||
raw.cmd_write_timestamp(buffer, stage, stamps.queries, stamps.first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,11 +14,8 @@
|
||||
//! `Completed` or `Error`. The transitions after `Committed` run in the queue's serial context on
|
||||
//! the device's handler threads ([`contexts`](super::contexts)), in the queue's order: to
|
||||
//! `Scheduled` once its last batch is submitted (every wait of it satisfied), with its scheduled
|
||||
//! handlers; to `Completed` once its work completed, with its completed handlers and the release
|
||||
//! of what it retained. As on Metal, a queue's command buffer whose work completed stays
|
||||
//! `Committed` while an earlier transition of its queue, a handler, still runs. Its submission
|
||||
//! handlers (a runtime extension) run before its transition to `Scheduled`, on the thread that
|
||||
//! submitted its last batch, which the transition waits for.
|
||||
//! thread that took its last batch for its queue (submitted it, or held it for one kernel
|
||||
//! submission with later batches: `group.rs`), which the transition waits for.
|
||||
//!
|
||||
//! Encoders write their commands' own data (tables, neutral buffers) into the command buffer's
|
||||
//! upload arena ([`upload`](super::upload)), and the execution status words its commands share; the
|
||||
@@ -31,6 +28,7 @@ pub(super) mod completion;
|
||||
pub(super) mod fences;
|
||||
mod first_submission;
|
||||
pub(super) mod gate;
|
||||
mod group;
|
||||
pub(super) mod kept_barriers;
|
||||
pub(super) mod own;
|
||||
mod reencode;
|
||||
@@ -39,7 +37,8 @@ mod submit;
|
||||
|
||||
pub(super) use completion::Completion;
|
||||
pub(super) use first_submission::NotedTable;
|
||||
pub(super) use submit::BatchLists;
|
||||
pub(super) use group::{Group, GroupEnd, GROUP_BATCHES};
|
||||
pub(super) use submit::{BatchLists, Submitting};
|
||||
|
||||
use super::contexts::{self, Run};
|
||||
use super::deferred::{Deferred, Prepared};
|
||||
@@ -76,7 +75,7 @@ use super::sparse::encoder::SparseUpdate;
|
||||
use super::sparse::indirect::{self, ReadFailure};
|
||||
use super::texture::storage_form::Riding;
|
||||
use super::texture::Texture;
|
||||
use super::tracker::{Barrier, Footprint};
|
||||
use super::tracker::Footprint;
|
||||
use super::upload::{Upload, Uploads};
|
||||
use super::used_resources::{EncoderKind, EncoderRecord, Reached, ReadRecord};
|
||||
use super::values::CommandBufferStatus;
|
||||
@@ -100,7 +99,7 @@ use own::{
|
||||
use std::any::Any;
|
||||
use std::collections::{BTreeSet, HashSet, VecDeque};
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -182,6 +181,9 @@ pub(super) struct CommandBufferShared {
|
||||
/// here: no lock is taken first at a commit (on Apple's hosts a mutex allocates at its first
|
||||
/// lock).
|
||||
error: OnceLock<CommandBufferError>,
|
||||
/// Whether a batch of it is held in the scheduler's group, and whether a thread waits for its
|
||||
/// completion: a group kept past a pass goes at once once one does (`group.rs`).
|
||||
group_hold: AtomicU8,
|
||||
}
|
||||
|
||||
/// The word [`CommandBufferShared::status`] holds for `status`: its raw value.
|
||||
@@ -423,9 +425,10 @@ pub(super) struct State {
|
||||
batches: Batches<Arc<EventShared>, vk::Semaphore>,
|
||||
scheduled: VecDeque<Handler>,
|
||||
/// Its submission handlers ([`CommandBuffer::add_submission_handler`]): run on the thread
|
||||
/// that submits its last batch, before its transition to `Scheduled`.
|
||||
/// that takes its last batch for its queue (submits it, or holds it in a group), before its
|
||||
/// transition to `Scheduled`.
|
||||
submission: VecDeque<Handler>,
|
||||
/// The thread that submitted its last batch has its submission handlers to run, or the
|
||||
/// The thread that took its last batch has its submission handlers to run, or the
|
||||
/// switch of storage forms riding on it to end (`texture/storage_form.rs`): its transition to
|
||||
/// `Scheduled` waits until it did.
|
||||
submitting: bool,
|
||||
@@ -1006,13 +1009,18 @@ impl State {
|
||||
.unwrap_or(batches.len() - 1)
|
||||
}
|
||||
|
||||
/// Whether batch `index`'s end may go into its last `VkCommandBuffer` (`submit.rs`): it
|
||||
/// signals no event (whose kept signal may need the end after a wait for another queue's),
|
||||
/// and its parts leave no segment or sparse update for its submission (whose recordings go
|
||||
/// among or after the parts' own), and name no texture over the caller's image that moves
|
||||
/// between layouts (whose move back its submission plans before the end).
|
||||
/// Whether batch `index`'s end may go into its last `VkCommandBuffer` (`submit.rs`): its
|
||||
/// parts leave no segment or sparse update for its submission (whose recordings go among or
|
||||
/// after the parts' own), nor its last part a write into an ASTC carrier (whose second twin's
|
||||
/// decode its submission may record after it, `texture/decoded_twin.rs`), and name no texture
|
||||
/// over the caller's image that moves between layouts (whose move back its submission plans
|
||||
/// before the end). An event's kept signal that waits for another queue's still goes after
|
||||
/// that wait, in an end of its own at the submission (`submit.rs`).
|
||||
fn may_fold(&self, device: &Device, index: usize) -> bool {
|
||||
let parts = &self.recorded[self.batch_range(index)];
|
||||
parts
|
||||
.iter()
|
||||
.all(|part| part.segments.is_empty() && part.sparse.is_empty())
|
||||
&& parts.last().is_none_or(|part| part.twin_writes.is_empty())
|
||||
&& device
|
||||
.shared()
|
||||
@@ -1380,6 +1388,7 @@ impl CommandBuffer {
|
||||
kernel: KernelTimes::default(),
|
||||
status: AtomicU8::new(status_word(CommandBufferStatus::NotEnqueued)),
|
||||
error: OnceLock::new(),
|
||||
group_hold: AtomicU8::new(0),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1482,11 +1491,15 @@ impl CommandBuffer {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Call `handler` once the command buffer's last batch reached its `VkQueue`, on the thread
|
||||
/// that submitted it, before the command buffer becomes `Scheduled`: a runtime extension, no
|
||||
/// Metal call (docs/API.md, "A command buffer's submission handlers"). Metal submits on its
|
||||
/// own thread and tells a program of it only through `Scheduled` (EV SUB-sched1-m4); a
|
||||
/// program that models what Metal does as it submits takes that point here.
|
||||
/// Call `handler` once the runtime took the command buffer's last batch for its `VkQueue`,
|
||||
/// on the thread that took it, before the command buffer becomes `Scheduled`: a runtime
|
||||
/// extension, no Metal call (docs/API.md, "A command buffer's submission handlers"). The
|
||||
/// batch is taken where it is submitted, or held for one kernel submission with the batches
|
||||
/// committed after it (`CompletionPolicy::Grouped`, on a driver that merges submissions): its
|
||||
/// commands and its place in its queue's order are fixed then, so nothing committed later on
|
||||
/// the queue runs before it. Metal submits on its own thread and tells a program of it only
|
||||
/// through `Scheduled`; a program that models what Metal does as it
|
||||
/// submits takes that point here.
|
||||
///
|
||||
/// - **The thread.** The device's scheduler thread, which makes every submission: `commit`
|
||||
/// returns at once, as Metal's does, and submits nothing itself. It runs with no lock of the
|
||||
@@ -1495,10 +1508,11 @@ impl CommandBuffer {
|
||||
/// before [`wait_until_scheduled`](Self::wait_until_scheduled) returns, before its
|
||||
/// scheduled handlers run, and before it can complete. The GPU may run the work meanwhile:
|
||||
/// a value of an event its work signals can rise before they ran.
|
||||
/// - **Never** for a command buffer that fails before its last batch is submitted (a
|
||||
/// submission or host step that fails, a lost device); they are dropped with it. A command
|
||||
/// buffer committed as failed ([`commit_failed`](Self::commit_failed)) submits its batches
|
||||
/// and runs them.
|
||||
/// - **Never** for a command buffer that fails before its last batch is taken (a submission
|
||||
/// or host step that fails, a lost device); they are dropped with it. One whose last batch
|
||||
/// was held ran them, and fails from `Scheduled` where the group's submission fails. A
|
||||
/// command buffer committed as failed ([`commit_failed`](Self::commit_failed)) submits its
|
||||
/// batches and runs them.
|
||||
/// - **Keep it short.** It holds back its command buffer's scheduling and the device's other
|
||||
/// submissions, among them those of a commit made meanwhile, which the thread takes in only
|
||||
/// after its handlers (`scheduler/inbox.rs`). A wait in it
|
||||
@@ -2040,7 +2054,9 @@ impl CommandBuffer {
|
||||
}
|
||||
|
||||
/// `kernelEndTime`: the host time at which the device's scheduler finished submitting the
|
||||
/// command buffer's work to Vulkan (it is then `Scheduled`); 0 before.
|
||||
/// command buffer's work to Vulkan, or held its last batch for one kernel submission with
|
||||
/// later ones (`CompletionPolicy::Grouped`); it is then `Scheduled`; 0 before. Like Metal's,
|
||||
/// the read waits for no submission in progress and no GPU work.
|
||||
pub fn kernel_end_time(&self) -> f64 {
|
||||
gpu_time::seconds(self.0.kernel.end())
|
||||
}
|
||||
@@ -2183,7 +2199,9 @@ impl CommandBuffer {
|
||||
}
|
||||
|
||||
/// `waitUntilCompleted`: block until the command buffer completed or failed and its
|
||||
/// completed handlers ran. It returns on device loss (the status is then `Error`).
|
||||
/// completed handlers ran. It returns on device loss (the status is then `Error`). Where a
|
||||
/// batch of it is held for one kernel submission with later ones while its queue's earlier
|
||||
/// work runs (`CompletionPolicy::Grouped`), the wait sends it at once.
|
||||
///
|
||||
/// It returns only once the runtime's threads let go of the command buffer, and of what they
|
||||
/// held to make what its work waited for (a pipeline made on the device's pool, a texture's
|
||||
@@ -2226,6 +2244,7 @@ impl CommandBuffer {
|
||||
Answer::Wait => None,
|
||||
Answer::Block(from) => Some(contexts::block(from, self.0.context())?),
|
||||
};
|
||||
self.0.waits_for_completion();
|
||||
self.0.gate.wait()?;
|
||||
self.trailed(None)
|
||||
.map_err(|_| DeadlockCause::Exiting.into())
|
||||
@@ -2244,6 +2263,7 @@ impl CommandBuffer {
|
||||
Some(contexts::block(from, self.0.context()).map_err(|_| TimedOut)?)
|
||||
}
|
||||
};
|
||||
self.0.waits_for_completion();
|
||||
self.0.gate.wait_until(deadline)?;
|
||||
self.trailed(Some(deadline)).map_err(|_| TimedOut)
|
||||
}
|
||||
@@ -2561,7 +2581,7 @@ impl CommandBufferShared {
|
||||
// lock; the slot's queries were reset by the batch's start, before it in submission
|
||||
// order (`submit.rs`).
|
||||
unsafe {
|
||||
Barrier::to_host().record(device, raw);
|
||||
crate::batch_order::end(self.device.shared().by_ends).record(device, raw);
|
||||
if let Some((queries, first)) = stamp {
|
||||
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
|
||||
device.cmd_write_timestamp(raw, bottom, queries, first + 1);
|
||||
@@ -2728,11 +2748,13 @@ impl CommandBufferShared {
|
||||
true
|
||||
}
|
||||
|
||||
/// Where the device writes timestamps into slots of three queries and `raw`, just begun, is
|
||||
/// the first `VkCommandBuffer` of the command buffer's first encoder, which opens its first
|
||||
/// batch: take the slot now, and write the start into its third query as `raw`'s first
|
||||
/// commands, the reset of the end and of that query, then the timestamp at the top of the pipe
|
||||
/// (`gpu_time.rs`). The first batch's submission decides which start is read (`submit.rs`).
|
||||
/// Where the device writes timestamps into slots of three queries and `raw`, just begun, is the
|
||||
/// first `VkCommandBuffer` of the command buffer's first encoder, which opens its first batch:
|
||||
/// take the slot now, and write the start into its third query as `raw`'s first commands, the
|
||||
/// reset of the end and of that query (where the device does not reset the slot on the host as
|
||||
/// it takes it), then the timestamp at the top of the pipe (the bottom where batches are
|
||||
/// ordered by their ends: `batch_order.rs`; `gpu_time.rs`). The first batch's submission
|
||||
/// decides which start is read (`submit.rs`).
|
||||
fn open_start(&self, state: &mut State, raw: vk::CommandBuffer) {
|
||||
let timing = &self.device.shared().timing;
|
||||
let first_batch = match state.batches.all() {
|
||||
@@ -2764,6 +2786,8 @@ impl CommandBufferShared {
|
||||
device.cmd_reset_query_pool(raw, queries, prefix - 1, 2);
|
||||
exit_guard::called(Call::CmdResetQueryPool);
|
||||
}
|
||||
let stage = crate::batch_order::start_stage(self.device.shared().by_ends);
|
||||
device.cmd_write_timestamp(raw, stage, queries, prefix);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
state.prefix = Some(raw);
|
||||
@@ -2873,8 +2897,8 @@ impl CommandBufferShared {
|
||||
});
|
||||
}
|
||||
|
||||
/// The scheduler submitted the last batch: in the queue's context, once the submitting
|
||||
/// thread ran its submission handlers, become `Scheduled`, then run the scheduled handlers on
|
||||
/// The scheduler submitted the last batch, or held it in a group (`group.rs`): in the queue's
|
||||
/// context, once the submitting thread ran its submission handlers, become `Scheduled`, then run the scheduled handlers on
|
||||
/// this thread, in the order added, then let `wait_until_scheduled` return. Metal's status
|
||||
/// reads `Scheduled` just before its first scheduled handler starts, and its wait returns
|
||||
/// once the last returned (EV SUB-sched1-m4: an M4, macOS 27.0.1).
|
||||
@@ -2911,9 +2935,10 @@ impl CommandBufferShared {
|
||||
self.changed.notify_all();
|
||||
}
|
||||
|
||||
/// Its last batch was submitted on this thread, which holds no lock of the runtime's: run
|
||||
/// its submission handlers here, in the order added, then let its transition to `Scheduled`
|
||||
/// run ([`CommandBuffer::add_submission_handler`]).
|
||||
|
||||
/// Its last batch was submitted, or held in a group, on this thread, which holds no lock of
|
||||
/// the runtime's: run its submission handlers here, in the order added, then let its
|
||||
/// transition to `Scheduled` run ([`CommandBuffer::add_submission_handler`]).
|
||||
pub(crate) fn run_submission_handlers(self: &Arc<Self>) {
|
||||
let buffer = CommandBuffer(Arc::clone(self));
|
||||
{
|
||||
@@ -2935,7 +2960,9 @@ impl CommandBufferShared {
|
||||
/// submitted value in `values`, and, where a command buffer ends at a fence
|
||||
/// ([`fences::ends_at_fence`]), at one submitted after it, as a command buffer whose last
|
||||
/// batch was submitted finishes; at the value alone when the queue takes no such fence (a
|
||||
/// lost device). Its submission and scheduled handlers never run; they are dropped with it.
|
||||
/// lost device). Its submission and scheduled handlers never run; they are dropped with it,
|
||||
/// unless it became `Scheduled` as its last batch was held in a group (`group.rs`), which
|
||||
/// then fails from `Scheduled`.
|
||||
pub(crate) fn failed(self: &Arc<Self>, error: CommandBufferError, values: &[u64]) {
|
||||
let vk_queue = self.queue.vk_queue();
|
||||
lock(&self.state).failure = Some(error);
|
||||
@@ -2984,10 +3011,8 @@ impl CommandBufferShared {
|
||||
}
|
||||
}
|
||||
|
||||
/// The command buffer's last batch is submitted: post its transition to `Scheduled` to its
|
||||
/// queue's context: [`plain`](Transition::plain) where it has no scheduled handler (none is
|
||||
/// added after the commit) and waits for no submission handler.
|
||||
pub(crate) fn post_scheduled(self: &Arc<Self>) {
|
||||
/// The command buffer's last batch is submitted, or held in a group (`group.rs`), on the
|
||||
/// scheduler's thread under its lock: its transition to `Scheduled` runs here where it is [`plain`](Transition::plain) (it has no
|
||||
let plain = {
|
||||
let state = lock(&self.state);
|
||||
state.scheduled.is_empty() && !state.submitting
|
||||
|
||||
@@ -24,12 +24,12 @@
|
||||
//! close a cycle of such waits, or leave its device's pool with no thread that is not blocked
|
||||
//! so (`contexts::block`).
|
||||
//!
|
||||
//! A submission handler (a runtime extension, Metal has none) runs on the thread that submitted its
|
||||
//! command buffer's last batch, and that command buffer's transition to `Scheduled`, with every
|
||||
//! later transition of its queue, waits for it. On the scheduler thread, the device's later
|
||||
//! submissions wait for it too. So any wait there for what has not happened (a command buffer's
|
||||
//! scheduling or completion, a slot of a full queue no uncommitted command buffer holds) is refused
|
||||
//! at once (`DeadlockCause::SubmissionHandler`); one for what happened returns.
|
||||
//! A submission handler (a runtime extension, Metal has none) runs on the thread that took its
|
||||
//! command buffer's last batch for its queue, and that command buffer's transition to `Scheduled`,
|
||||
//! with every later transition of its queue, waits for it. On the scheduler thread, the device's
|
||||
//! later submissions wait for it too. So any wait there for what has not happened (a command
|
||||
//! buffer's scheduling or completion, a slot of a full queue no uncommitted command buffer holds)
|
||||
//! is refused at once (`DeadlockCause::SubmissionHandler`); one for what happened returns.
|
||||
|
||||
use crate::error::DeadlockCause;
|
||||
use std::cell::Cell;
|
||||
@@ -43,7 +43,7 @@ pub(crate) enum Step {
|
||||
CompletedHandlers,
|
||||
/// The release of what it retained (a no-copy buffer's deallocator may run here).
|
||||
Release,
|
||||
/// Its submission handlers, on the thread that submitted its last batch (the scheduler's,
|
||||
/// Its submission handlers, on the thread that took its last batch (the scheduler's,
|
||||
/// or a committing one, which may be a handler thread): its transition to `Scheduled`, and
|
||||
/// so every later transition of its queue, waits for them.
|
||||
SubmissionHandlers,
|
||||
|
||||
@@ -7,11 +7,23 @@
|
||||
//! `VkCommandBuffer`s (an encoder's segments among its own), each encoder after the barrier the
|
||||
//! tracker planned for it. What completed work wrote is made visible by a wait or a barrier,
|
||||
//! see below.
|
||||
//! 2. The end: the barrier that makes every write visible to the host ([`Barrier::to_host`]),
|
||||
//! then the signals: the events' kept signal indices, the caller's binary semaphores and the
|
||||
//! queue's timeline value. When an event's previous kept signal is pending on another
|
||||
//! `VkQueue`, this part waits for it, so the event's semaphore is signaled in index order
|
||||
//! without holding back the work.
|
||||
//! 2. The end: the barrier that makes every write visible to the host ([`Barrier::to_host`]), or,
|
||||
//! where batches are ordered by their ends (`batch_order.rs`), to the host and to every later
|
||||
//! command of the `VkQueue` ([`Barrier::to_all`]; so a later batch there plans no barrier from
|
||||
//! this one's accesses, `tracker.rs`), then the signals: the events' kept signal indices, the
|
||||
//! caller's binary semaphores and the queue's timeline value. When an event's previous kept
|
||||
//! signal is pending on another `VkQueue`, this part waits for it, so the event's semaphore is
|
||||
//! signaled in index order without holding back the work.
|
||||
//!
|
||||
//! **Grouped** ([`Submitting::Grouped`], `group.rs`). Where the scheduler groups batches (under
|
||||
//! `CompletionPolicy::Grouped`, on a driver that merges submissions), a batch that signals nothing
|
||||
//! but its queue's timeline and its events, past its first work, without a fence or a wrapped
|
||||
//! image to move, and waits for no event index a batch held signals, is not submitted: its two
|
||||
//! `VkSubmitInfo`s are held, its signals left to the group's end, and it is tracked as submitted
|
||||
//! (its events keep their signals' indices). One that may join but took first work or names a
|
||||
//! wrapped image goes with the held group, in its call, last; one that may not, or finds the
|
||||
//! group of another `VkQueue`, changes nothing ([`Submitting::AfterGroup`]): the scheduler
|
||||
//! submits the group and offers the batch again.
|
||||
//!
|
||||
//! **What completed work wrote.** The tracker forgets a batch once the host saw its queue's
|
||||
//! timeline pass it, and the device's own submissions outside the batches (`device/submit.rs`,
|
||||
@@ -54,12 +66,13 @@
|
||||
//! joins its batch, its batch ends at encode time, or the command buffer commits
|
||||
//! (`CommandBufferShared::close_tail`). Where its batch ended there, the end goes into it before
|
||||
//! it ends: the barrier to the host, then, in the last batch of a timed command buffer, the end
|
||||
//! timestamp, as the end's own command buffer holds them. Only where the batch signals no event
|
||||
//! (a kept signal may need the end after a wait for another `VkQueue`'s, above), leaves its
|
||||
//! timestamp, as the end's own command buffer holds them. Only where the batch leaves its
|
||||
//! submission no segment or sparse update (recorded at the submission, among or before the
|
||||
//! work's command buffers), and names no texture over the caller's image that moves between
|
||||
//! layouts (its move back is planned at the submission, before the end). The batch's submission
|
||||
//! then has no end of its own, and the signals join the work's `VkSubmitInfo`: "The first
|
||||
//! then has no end of its own, unless an event's kept signal waits for another `VkQueue`'s
|
||||
//! (above): its end then holds the barrier to the host alone, between that wait and the signals,
|
||||
//! the work's end timestamp written. Else the signals join the work's `VkSubmitInfo`: "The first
|
||||
//! synchronization scope of each semaphore signal operation defined by this command includes
|
||||
//! every command in the same batch that the signal operation is defined in, and all commands that
|
||||
//! occur earlier in submission order" (`vkQueueSubmit`). Where that command buffer does not go
|
||||
@@ -115,26 +128,27 @@
|
||||
//! where its driver reads the command buffer's objects after its value
|
||||
//! ([`fences`](super::fences)), at which the command buffer then finishes.
|
||||
//!
|
||||
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at
|
||||
//! the top of the pipe, before every barrier and encoder of its first batch: by its first
|
||||
//! encoder's first command buffer, which wrote it into its slot's third query as it opened, where
|
||||
//! the batch plans nothing before that encoder (no barrier, no image moved, and no
|
||||
//! **GPU times** (`gpu_time.rs`). In a timed command buffer, the start timestamp is written at the
|
||||
//! top of the pipe, before every barrier and encoder of its first batch: by its first encoder's
|
||||
//! first command buffer, which wrote it into its slot's third query as it opened, where the batch
|
||||
//! plans nothing before that encoder (no barrier, no image moved, and no
|
||||
//! [`Barrier::after_completed`] where the driver stalls on semaphore operations) and the command
|
||||
//! buffer goes to the queue as recorded first (`WorkCounts::prefixed_starts`); else by the
|
||||
//! batch's first command buffer, a command buffer of barriers, which resets the slot's first two
|
||||
//! queries first. Where the batch plans a barrier before its first encoder for earlier work (the
|
||||
//! encoder's own, or the one before the images it moves), the start is written after that
|
||||
//! barrier instead, at the bottom of the pipe: once every command submitted before it on the
|
||||
//! queue completed. Vulkan (`vkCmdWriteTimestamp`): its "first synchronization scope includes
|
||||
//! all commands that occur earlier in submission order", and `VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT`
|
||||
//! "is equivalent to `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT` with `VkAccessFlags` set to `0` when
|
||||
//! specified in the first synchronization scope". So a command buffer whose first encoder depends
|
||||
//! on work still running starts after that work ended, as Metal's does: on an M3 Max under macOS
|
||||
//! 27.0.1, a fill committed behind a running fill of the same bytes started 0.5 to 0.9 us after
|
||||
//! the first's `GPUEndTime` (10 of 10), and one of other bytes while the first ran (probe
|
||||
//! `gpustart`). The end of its last batch writes the end timestamp at the bottom of the pipe,
|
||||
//! after its barriers. The scheduler's host times as it begins the first batch and ends the last
|
||||
//! submission are the kernel times.
|
||||
//! buffer goes to the queue as recorded first (`WorkCounts::prefixed_starts`); else by the batch's
|
||||
//! first command buffer, a command buffer of barriers, which resets the slot's first two queries
|
||||
//! first. Where the batch plans a barrier before its first encoder for earlier work (the encoder's
|
||||
//! own, or the one before the images it moves), the start is written after that barrier instead, at
|
||||
//! the bottom of the pipe: once every command submitted before it on the queue completed. Vulkan
|
||||
//! (`vkCmdWriteTimestamp`): its "first synchronization scope includes all commands that occur
|
||||
//! earlier in submission order", and `VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT` "is equivalent to
|
||||
//! `VK_PIPELINE_STAGE_ALL_COMMANDS_BIT` with `VkAccessFlags` set to `0` when specified in the first
|
||||
//! synchronization scope". So a command buffer whose first encoder depends on work still running
|
||||
//! starts after that work ended, as Metal's does: on an M3 Max under macOS 27.0.1, a fill committed
|
||||
//! behind a running fill of the same bytes started 0.5 to 0.9 us after the first's `GPUEndTime` (10
|
||||
//! of 10), and one of other bytes while the first ran (probe `gpustart`). Where batches are ordered
|
||||
//! by their ends (`batch_order.rs`), every start is written at the bottom of the pipe, as such a
|
||||
//! driver starts no batch before the ones before it ended. The end of its last batch writes the end
|
||||
//! timestamp at the bottom of the pipe, after its barriers. The scheduler's host times as it begins
|
||||
//! the first batch and ends the last submission are the kernel times.
|
||||
//!
|
||||
//! The tracker keeps the plan, and the events their kept signals, only once the submission is
|
||||
//! made; a batch that is not submitted changes neither.
|
||||
@@ -146,10 +160,13 @@
|
||||
//! registered destructors, so an exit the program makes once it learned of the submission runs
|
||||
//! the hook before them.
|
||||
//!
|
||||
//! The submission of a command buffer's last batch leaves its submission handlers to the submitting
|
||||
//! thread, once the scheduler's lock is free; its transition to `Scheduled` waits for them.
|
||||
//! The submission of a command buffer's last batch, or its hold in a group (`group.rs`), leaves its
|
||||
//! submission handlers to the submitting thread, once the scheduler's lock is free; its transition
|
||||
//! to `Scheduled` waits for them.
|
||||
|
||||
use super::completion::Submitted;
|
||||
use super::gate::Hold;
|
||||
use super::group::{self, After, GroupEnd, InfoParts};
|
||||
use super::kept_barriers::{KeptBarriers, SlotStamps};
|
||||
use super::{lock, recording_error, submission_error, CommandBufferShared, State};
|
||||
use crate::deferred::Deferred;
|
||||
@@ -205,33 +222,114 @@ pub(crate) struct Submission {
|
||||
queue: usize,
|
||||
batch: Submitted,
|
||||
/// It ends a command buffer with submission handlers, or with a switch of storage forms riding
|
||||
/// on it, which the submitting thread runs or ends once the scheduler's lock is free
|
||||
/// ([`Submission::runs_handlers`]).
|
||||
/// on it, which the submitting thread still runs or ends once the scheduler's lock is free
|
||||
/// ([`Submission::runs_handlers`]); false once a hold in a group gave them to the thread
|
||||
/// ([`schedule_held`](Submission::schedule_held)).
|
||||
handlers: bool,
|
||||
/// It ends a command buffer with a switch of storage forms riding on it, which settles by its
|
||||
/// submission's outcome ([`Submission::rides_forms`]).
|
||||
forms: bool,
|
||||
/// Its command buffer became `Scheduled` as it was held in a group
|
||||
/// ([`schedule_held`](Submission::schedule_held)).
|
||||
scheduled: bool,
|
||||
}
|
||||
|
||||
/// What [`CommandBufferShared::submit_batch`] did with a batch.
|
||||
#[must_use = "a batch submitted or held must be published, one held back must be put back"]
|
||||
pub(crate) enum Submitting {
|
||||
/// Submitted, alone or after the group held before it: for the scheduler to publish.
|
||||
Submitted(Submission),
|
||||
/// Held in the scheduler's group (`group.rs`), its submission's changes made: its command
|
||||
/// buffer's transition to `Scheduled` as it is held, where it ends it
|
||||
/// ([`Submission::schedule_held`]), the rest published once the group is submitted.
|
||||
Grouped,
|
||||
/// Nothing submitted or changed: its first submission waits for encoders of it a rebind
|
||||
/// encodes again (`reencode.rs`).
|
||||
Later,
|
||||
/// Nothing submitted or changed: the group held goes first, sent by what this says.
|
||||
AfterGroup(GroupEnd),
|
||||
}
|
||||
|
||||
impl Submission {
|
||||
/// The value its queue's timeline reaches once it completed.
|
||||
pub(super) fn value(&self) -> u64 {
|
||||
self.batch.value
|
||||
}
|
||||
|
||||
/// Whether it ends its command buffer.
|
||||
pub(super) fn ends(&self) -> bool {
|
||||
self.batch.last
|
||||
}
|
||||
|
||||
/// Its command buffer.
|
||||
pub(super) fn buffer(&self) -> &Hold<CommandBufferShared> {
|
||||
&self.batch.buffer
|
||||
}
|
||||
|
||||
/// Each event's semaphore it signals, with the signal's index.
|
||||
pub(super) fn event_signals(&self) -> impl Iterator<Item = (vk::Semaphore, u64)> + '_ {
|
||||
(self.batch.signals.iter()).map(|(event, index)| (event.semaphore(), *index))
|
||||
}
|
||||
|
||||
/// Whether the submitting thread runs its command buffer's submission handlers
|
||||
/// ([`CommandBufferShared::run_submission_handlers`]) once it holds no lock, after it ended
|
||||
/// the switch of storage forms riding on it: its transition to `Scheduled` waits for them.
|
||||
pub(crate) fn runs_handlers(&self) -> bool {
|
||||
self.handlers
|
||||
}
|
||||
|
||||
/// Whether it ends a command buffer on which a switch of storage forms rides
|
||||
/// (`texture/storage_form.rs`): the switch settles by its submission's outcome, so it is
|
||||
/// `Scheduled` and its submission handlers run only once the group holding it was submitted.
|
||||
pub(super) fn rides_forms(&self) -> bool {
|
||||
self.forms
|
||||
}
|
||||
|
||||
/// It was held in a group (`group.rs`), on the scheduler's thread under its lock, after the
|
||||
/// section that held it ended: where it ends its command buffer and no switch of storage
|
||||
/// forms rides on it, the command buffer's kernel end and its transition to `Scheduled` now,
|
||||
/// which [`publish`](CommandBufferShared::publish) then leaves out, and its submission
|
||||
/// handlers go to the scheduler's thread to run once its lock is free, before that
|
||||
/// transition, as a submitted batch's do: whether they do (none is left for the group's
|
||||
/// submission). Its tracker plan, its queue's value and its events' signal indices were
|
||||
/// taken as it was held, so nothing committed later on its queue goes before it; only its
|
||||
/// kernel submission and its queue waiter's watch wait for the group.
|
||||
pub(super) fn schedule_held(&mut self) -> bool {
|
||||
if !self.batch.last || self.forms || self.scheduled {
|
||||
return false;
|
||||
}
|
||||
self.scheduled = true;
|
||||
self.batch.buffer.kernel.end_at(gpu_time::host_nanos());
|
||||
self.batch.buffer.schedule();
|
||||
let handlers = self.handlers;
|
||||
self.handlers = false;
|
||||
handlers
|
||||
}
|
||||
|
||||
/// Whether its command buffer became `Scheduled` as it was held.
|
||||
pub(super) fn scheduled(&self) -> bool {
|
||||
self.scheduled
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandBufferShared {
|
||||
/// Submit batch `index` of the command buffer (`last` when it ends it) after the Vulkan waits
|
||||
/// `event_waits` for its events, against the scheduler's tracker and timeline values. The
|
||||
/// batch is for the caller to [`publish`](Self::publish) once its section ended.
|
||||
/// `Ok(None)`, nothing submitted or changed, while its first submission waits for encoders
|
||||
/// of it a rebind encodes again (`reencode.rs`): the caller holds the batch back at its place.
|
||||
/// batch is for the caller to [`publish`](Self::publish) once its section ended
|
||||
/// ([`Submitting::Submitted`]), or waits in the scheduler's group for one kernel submission
|
||||
/// with the batches after it, its submission's changes made ([`Submitting::Grouped`],
|
||||
/// `group.rs`). Nothing submitted or changed while its first submission waits for encoders
|
||||
/// of it a rebind encodes again (`reencode.rs`, [`Submitting::Later`]), or while the group
|
||||
/// held must go first ([`Submitting::AfterGroup`]): the caller holds the batch back at its
|
||||
/// place. Where the group went in this batch's submission, its outcome is the group's
|
||||
/// (`Group::take_outcome`).
|
||||
pub(crate) fn submit_batch(
|
||||
self: &Arc<Self>,
|
||||
index: usize,
|
||||
last: bool,
|
||||
event_waits: &[(vk::Semaphore, u64)],
|
||||
scheduler: &mut scheduler::State,
|
||||
) -> Result<Option<Submission>, CommandBufferError> {
|
||||
) -> Result<Submitting, CommandBufferError> {
|
||||
let device = &self.device;
|
||||
if device.is_lost() {
|
||||
return Err(CommandBufferError::DeviceLost);
|
||||
@@ -240,6 +338,28 @@ impl CommandBufferShared {
|
||||
let raw = shared.vk();
|
||||
let queue = self.queue.vk_queue();
|
||||
let mut state = lock(&self.state);
|
||||
// Whether the batch may wait in the scheduler's group for one kernel submission with the
|
||||
// batches after it (`group.rs`), as far as is known before anything changes; first work
|
||||
// it takes still sends it now. One that may not, or of another `VkQueue`, waits,
|
||||
// a wait for an event a batch held signals, which only that end meets, goes after it.
|
||||
let met = (event_waits.iter()).any(|&wait| scheduler.group.meets(wait));
|
||||
let joins = {
|
||||
let sync = &state.batches.all()[index];
|
||||
group::groups(device, queue)
|
||||
&& !(last && super::fences::ends_at_fence(device, queue))
|
||||
&& !met
|
||||
&& sync.binary_waits.is_empty()
|
||||
&& sync.binary_signals.is_empty()
|
||||
&& (state.recorded[state.batch_range(index)].iter())
|
||||
.all(|recorded| recorded.sparse.is_empty())
|
||||
};
|
||||
if !scheduler.group.admits(queue, joins) {
|
||||
let end = match met {
|
||||
true => GroupEnd::Wait,
|
||||
false => GroupEnd::Apart,
|
||||
};
|
||||
return Ok(Submitting::AfterGroup(end));
|
||||
}
|
||||
// A host step that failed fails the command buffer here; else the batch's segments go in
|
||||
// their places.
|
||||
if let Some(error) = state.step_failure.take() {
|
||||
@@ -252,7 +372,7 @@ impl CommandBufferShared {
|
||||
.first_submission(device, self)
|
||||
.map_err(|error| recording_error(device, error))?;
|
||||
if !first {
|
||||
return Ok(None);
|
||||
return Ok(Submitting::Later);
|
||||
}
|
||||
}
|
||||
// Each of Metal's submissions it found rebound, or holding a detached buffer, fails as
|
||||
@@ -341,6 +461,10 @@ impl CommandBufferShared {
|
||||
reached.push((value > 0).then_some((vk_queue.timeline, value)));
|
||||
}
|
||||
reached.extend(device.own_completed());
|
||||
// The batches before it on its queue that the host has not seen complete: each took the
|
||||
// next value (`WorkCounts::batches_with_none_pending` and kin).
|
||||
let completed = shared.queues[queue].completed_value();
|
||||
(shared.counts).batch_submitted_behind(scheduler.values[queue].saturating_sub(completed));
|
||||
if index == 0 {
|
||||
self.kernel.begin();
|
||||
}
|
||||
@@ -655,13 +779,12 @@ impl CommandBufferShared {
|
||||
// where that command buffer goes to the queue as recorded: then the batch has no end of
|
||||
// its own. One that does not go (its encoder runs nothing, or was encoded again) leaves
|
||||
// the end to its own command buffer, as every other batch's.
|
||||
let folded = match state.fold(index).filter(|(raw, _)| work.contains(raw)) {
|
||||
let in_work = match state.fold(index).filter(|(raw, _)| work.contains(raw)) {
|
||||
None => false,
|
||||
Some((raw, stamped)) => {
|
||||
let ends = work.last() == Some(&raw)
|
||||
&& exit_barrier.is_none()
|
||||
&& exits.is_empty()
|
||||
&& order_semaphores.is_empty()
|
||||
&& start_stamp.is_none()
|
||||
&& stamped == (last && slot.is_some());
|
||||
debug_assert!(ends, "a batch's end recorded where the batch does not end");
|
||||
@@ -672,6 +795,10 @@ impl CommandBufferShared {
|
||||
true
|
||||
}
|
||||
};
|
||||
// An event's kept signal that waits for another `VkQueue`'s earlier one goes after that
|
||||
// wait, in an end of its own (the module docs): the end the work holds made its writes
|
||||
// visible and wrote its end timestamp, so that one records the barrier alone.
|
||||
let folded = in_work && order_semaphores.is_empty();
|
||||
// The end, where the batch has something to end. A batch with no work, no wait, no image
|
||||
// to move back and no timestamp records none: none of its commands wrote anything, every
|
||||
// batch before it on any `VkQueue` made its own writes visible to the host before its
|
||||
@@ -680,7 +807,7 @@ impl CommandBufferShared {
|
||||
let stamps = Stamps {
|
||||
start: start_stamp.take(),
|
||||
after: false,
|
||||
end: slot.filter(|_| last),
|
||||
end: slot.filter(|_| last && !in_work),
|
||||
};
|
||||
let ends = !single
|
||||
|| !order_semaphores.is_empty()
|
||||
@@ -692,7 +819,7 @@ impl CommandBufferShared {
|
||||
true => {
|
||||
let finale_barriers: Vec<Barrier> = exit_barrier
|
||||
.into_iter()
|
||||
.chain([Barrier::to_host()])
|
||||
.chain([crate::batch_order::end(shared.by_ends)])
|
||||
.collect();
|
||||
let kept = &mut scheduler.kept;
|
||||
vec![self.barrier_buffer(&mut state, kept, at, &finale_barriers, &exits, stamps)?]
|
||||
@@ -778,42 +905,71 @@ impl CommandBufferShared {
|
||||
if let Some(ticket) = state.heaps.submit(device) {
|
||||
state.retained.push(Box::new(ticket));
|
||||
}
|
||||
// SAFETY: every command buffer is executable and submitted once; every wait is for a
|
||||
// signal already submitted (the scheduler's order, and for a binary semaphore the
|
||||
// caller's contract of `encode_wait_for_vk_semaphore`); every signal of a timeline is
|
||||
// above its value and any earlier one (the queue's values rise, and an event's kept
|
||||
// indices rise and wait for the previous one on another queue), and every binary one is
|
||||
// of an unsignaled semaphore with no signal pending (`encode_signal_vk_semaphore`); every
|
||||
// transition is of a live image of the caller's in the layout it is in (its contract,
|
||||
// `new_texture_with_vk_image`); the fence is unsignaled and in no pending submission;
|
||||
// the `VkQueue` is used under its lock.
|
||||
let submitted = shared.submit_logged(
|
||||
(queue, Some(at.value)),
|
||||
fence,
|
||||
&self.relayed,
|
||||
|vk_queue| unsafe {
|
||||
shared.counts.queue_submitted(buffers);
|
||||
raw.queue_submit(vk_queue, &submits, fence.unwrap_or(vk::Fence::null()))
|
||||
},
|
||||
);
|
||||
exit_guard::called(Call::QueueSubmit);
|
||||
if let Err(error) = submitted {
|
||||
if let Some(fence) = fence {
|
||||
// SAFETY: the failed submission is not pending; inside the section. Released,
|
||||
// not kept: Vulkan leaves a fence's state after a failed submission unsaid.
|
||||
unsafe { release::object(raw, fence) };
|
||||
// The batch waits in the group, its submission's changes made below, where it may and
|
||||
// took no first work, the device wrapped no image of the caller's it names since it was
|
||||
// found ready, and it waits for nothing but values seen complete where a group is held: a
|
||||
// batch with a wait leads a group, never joins one, so the merge, which gathers every
|
||||
// batch's waits before the first one's commands, never holds back an earlier batch for
|
||||
// another's wait. Else it goes now, after the group where one is held.
|
||||
let waits = wait_semaphores.len() - waited.len() + order_semaphores.len();
|
||||
let leads = !scheduler.group.holds() || waits == 0;
|
||||
let grouped = joins
|
||||
&& leads
|
||||
&& !first_work.has_first()
|
||||
&& !first_work.has_staged()
|
||||
&& images.is_empty();
|
||||
if grouped {
|
||||
scheduler.group.open(queue, &scheduler.waited[queue]);
|
||||
} else {
|
||||
// SAFETY: every command buffer is executable and submitted once; every wait is for a
|
||||
// signal already submitted (the scheduler's order, and for a binary semaphore the
|
||||
// caller's contract of `encode_wait_for_vk_semaphore`); every signal of a timeline is
|
||||
// above its value and any earlier one (the queue's values rise, and an event's kept
|
||||
// indices rise and wait for the previous one on another queue), and every binary one
|
||||
// is of an unsignaled semaphore with no signal pending (`encode_signal_vk_semaphore`);
|
||||
// every transition is of a live image of the caller's in the layout it is in (its
|
||||
// contract, `new_texture_with_vk_image`); the fence is unsignaled and in no pending
|
||||
// submission; the `VkQueue` is used under its lock (`Group::submit`).
|
||||
if scheduler.group.holds() {
|
||||
let end = match leads {
|
||||
true => GroupEnd::FirstWork,
|
||||
false => GroupEnd::Wait,
|
||||
};
|
||||
shared.counts.group_ended(end);
|
||||
}
|
||||
// A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or
|
||||
// loses the device: the first work goes back, still to be done, as `first_work`
|
||||
// drops. Where the device is lost, its command buffers, of this command buffer's pool
|
||||
// that goes as the command buffer fails, go once the driver's own completion of what
|
||||
// the call ran did (`Device::drain_queues`).
|
||||
let error = submission_error(device, error);
|
||||
if matches!(error, CommandBufferError::DeviceLost) {
|
||||
device.drain_queues();
|
||||
let after = After {
|
||||
queue,
|
||||
infos: &submits,
|
||||
buffers,
|
||||
value: at.value,
|
||||
fence,
|
||||
relayed: &self.relayed,
|
||||
};
|
||||
let submitted =
|
||||
scheduler
|
||||
.group
|
||||
.submit(device, &mut scheduler.waited[queue], Some(after));
|
||||
if let Err(error) = submitted {
|
||||
if let Some(fence) = fence {
|
||||
// SAFETY: the failed submission is not pending; inside the section.
|
||||
// Released, not kept: Vulkan leaves a fence's state after a failed
|
||||
// submission unsaid.
|
||||
unsafe { release::object(raw, fence) };
|
||||
}
|
||||
// A `vkQueueSubmit` that fails leaves what its submissions reference as it was,
|
||||
// or loses the device: the first work goes back, still to be done, as
|
||||
// `first_work` drops. Where the device is lost, its command buffers, of this
|
||||
// command buffer's pool that goes as the command buffer fails, go once the
|
||||
// driver's own completion of what the call ran did (`Device::drain_queues`).
|
||||
let error = submission_error(device, error);
|
||||
if matches!(error, CommandBufferError::DeviceLost) {
|
||||
device.drain_queues();
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
// A held batch's kernel end is its group's (`Group::submit`).
|
||||
if last && !grouped {
|
||||
self.kernel.end_at(gpu_time::host_nanos());
|
||||
}
|
||||
if !single {
|
||||
@@ -834,8 +990,9 @@ impl CommandBufferShared {
|
||||
}
|
||||
// Its submission handlers run on this thread once the scheduler's lock is free, and a
|
||||
// switch of storage forms riding on it ends there first (`scheduler/mod.rs`); its
|
||||
// transition to `Scheduled`, posted as it is published, waits for them.
|
||||
let handlers = last && (!state.submission.is_empty() || state.storage_form.is_some());
|
||||
// transition to `Scheduled`, posted as it is published or held, waits for them.
|
||||
let forms = last && state.storage_form.is_some();
|
||||
let handlers = last && (!state.submission.is_empty() || forms);
|
||||
state.submitting = handlers;
|
||||
scheduler.tracker.apply(plan);
|
||||
held_moves.submitted();
|
||||
@@ -865,7 +1022,7 @@ impl CommandBufferShared {
|
||||
device.degrade_encoded_use_rebound();
|
||||
}
|
||||
device.reach_stale_detached(reaches);
|
||||
Ok(Some(Submission {
|
||||
let submission = Submission {
|
||||
queue,
|
||||
batch: Submitted {
|
||||
value: at.value,
|
||||
@@ -878,18 +1035,43 @@ impl CommandBufferShared {
|
||||
.collect(),
|
||||
},
|
||||
handlers,
|
||||
}))
|
||||
forms,
|
||||
scheduled: false,
|
||||
};
|
||||
if !grouped {
|
||||
return Ok(Submitting::Submitted(submission));
|
||||
}
|
||||
let first = InfoParts {
|
||||
waits: (wait_semaphores, wait_values, wait_stages),
|
||||
buffers: &work,
|
||||
signals: (work_signals, work_signal_values),
|
||||
};
|
||||
let second = InfoParts {
|
||||
waits: (&order_semaphores, &order_values, &order_stages),
|
||||
buffers: &finale,
|
||||
signals: (&signal_semaphores, &signal_values),
|
||||
};
|
||||
let parts = [first, second];
|
||||
let parts = match (single, folded) {
|
||||
(true, _) => &parts[1..],
|
||||
(false, true) => &parts[..1],
|
||||
(false, false) => &parts[..],
|
||||
};
|
||||
scheduler.group.hold(parts, buffers, submission);
|
||||
Ok(Submitting::Grouped)
|
||||
}
|
||||
|
||||
/// Publish a batch [`submit_batch`](Self::submit_batch) submitted, after the section that
|
||||
/// submitted it ended: when it ends the command buffer, its transition to `Scheduled`, then
|
||||
/// its queue waiter's watch for it. From the watch on, the command buffer may complete
|
||||
/// and run its release on its queue's handler thread before the caller lets go of anything
|
||||
/// it took, so the caller holds nothing of what its commands or encoders took
|
||||
/// (`scheduler::Spent`).
|
||||
/// (`CommandBufferShared::schedule`) unless it made it as it was held in a group
|
||||
/// ([`Submission::schedule_held`]), then its queue waiter's watch for it. From the watch
|
||||
pub(crate) fn publish(self: &Arc<Self>, submission: Submission) {
|
||||
let Submission { queue, batch, .. } = submission;
|
||||
if batch.last {
|
||||
let Submission {
|
||||
queue,
|
||||
batch,
|
||||
scheduled,
|
||||
..
|
||||
} = submission;
|
||||
if batch.last && !scheduled {
|
||||
// Before a completion turn can see it finish, so the queue's context runs its
|
||||
// transition to `Scheduled` first.
|
||||
self.post_scheduled();
|
||||
@@ -1100,8 +1282,8 @@ impl CommandBufferShared {
|
||||
exit_guard::called(Call::CmdResetQueryPool);
|
||||
}
|
||||
if !stamps.after {
|
||||
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
|
||||
raw.cmd_write_timestamp(buffer, top, queries, first);
|
||||
let stage = crate::batch_order::start_stage(device.shared().by_ends);
|
||||
raw.cmd_write_timestamp(buffer, stage, queries, first);
|
||||
exit_guard::called(Call::CmdWriteTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user