RUNTIME 2455: Spares: primaries are begun ahead on a device thread, one for each encoder the pool last served, eight at most

Verified: m3-max-36547 at 5774363889, lavapipe begin_ahead|spares|draw_again|pending_audit 72/72, clippy (host, m2v_cpu_icd) 0; m3-max-36546 clippy --cfg m2v_gpu 0; m3-max-36541 at 9f9a9a2019 rustdoc 0; negative control m3-max-36540 (AHEAD = 1) fails both new tests (taken 1 against 5; missed 1 against 5). PHOENIX (m3-max-36549) runs after the merge.
This commit is contained in:
Anees Iqbal committed 2026-11-16 06:53:04 -08:00
1 parent 566dc02f9d
commit 9afd9699e1
21 files changed
+824 -290

No files matched your search

+6 -5
View File
@@ -350,11 +350,12 @@ const POOL_STATE: &str = "a reading of how many pieces the device's pipeline poo
/// Why `encoder_primaries_begun_ahead` is reported and never gated.
///
/// The runtime documents it as a `VkCommandBuffer` begun "by the thread that completed the command
/// buffer that gave it back where no thread waited for that one", so whether this case's first
/// encoder finds a primary already begun depends on whether a completion thread got round to
/// beginning it, for a pool an earlier case gave back. It is also a *split* of
/// `encoder_command_buffers_begun`, which stays gated, so no work escapes the gate by it.
/// The runtime documents it as a `VkCommandBuffer` "begun on the device's begin-ahead thread once
/// the command buffer that gave it back completed", so whether this case's first encoder finds a
/// primary already begun depends on whether that thread got round to beginning it, for a pool an
/// earlier case gave back. It is also a *split* of `encoder_command_buffers_begun`, which stays
/// gated, so no work escapes the gate by it. Its own split `encoder_primaries_begun_ahead_missed`,
/// the encoders the thread had not reached yet, shares the name, and so the race and the reason.
///
/// Measured: `chroma-pair-copies-gbgr422` and `chroma-pair-texel-samples-gbgr422` read 2 and 1
/// inside the 393-case set where the measurement's most was 0, and **0** when each runs alone --
@@ -1661,6 +1661,10 @@ impl Gpu for Runtime {
"encoder_primaries_begun_ahead",
c.encoder_primaries_begun_ahead,
),
(
"encoder_primaries_begun_ahead_missed",
c.encoder_primaries_begun_ahead_missed,
),
("primaries_begun_ahead", c.primaries_begun_ahead),
("barrier_buffers_kept", c.barrier_buffers_kept),
("stamped_buffers_kept", c.stamped_buffers_kept),
@@ -0,0 +1,163 @@
//! The device's begin-ahead thread: a settled spare command pool's primaries are begun here, for
//! the encoders of the command buffer that takes the pool next (`spares.rs`), off the thread that
//! completed the command buffer that gave the pool back.
//!
//! - **What is posted.** The first command pool of a command buffer that completed and ended
//! every command buffer its pools handed out, once its completed handlers ran, before its gate
//! opens (`command_buffer/mod.rs`, `command_buffer/gate.rs`): the completing thread posts the
//! pool and goes on, so neither the command buffer's waiters nor its queue's next transitions
//! wait for a begin, and a waiter's return comes after the post. On ANV a begin was 8 to 20 us
//! (`spares.rs`), which the completing thread spent before, one a command buffer, while the
//! queue's context was held, and only where no thread waited for the command buffer.
//! - **What it begins.** As many of the pool's primaries as encoders of the command buffer that
//! gave it back opened their own in it, one at least and `spares::AHEAD` at most, one at a time,
//! the pool out of the spares only while it begins one (`spares.rs`'s
//! `BeginTargets::begin_ahead`). A command buffer that takes the pool before the thread came
//! to it, or between two begins, takes it as it is: its encoders past those begun begin their
//! own, counted (`WorkCounts::encoder_primaries_begun_ahead_missed`).
//! - **Bounded.** One thread a device, started by its first post. At most [`QUEUE`] pools wait;
//! a pool posted while it waits waits once, and one that finds the queue full, the device's
//! teardown begun, or no thread, is begun by none: its command buffer's encoders begin their
//! own. Stopped and joined by the device's teardown, before the spares are released
//! ([`BeginAhead::stop`]).
//! - **Holds nothing of the device**: the spares' command pools, the device's functions, its
//! loader word and its counts (`spares.rs`'s `BeginTargets`), as the free thread does
//! (`free_thread.rs`). No release of the device's runs on it.
//! - **A section of the exit guard** for each begin (`exit_guard.rs`); once the process exits,
//! nothing more is begun and the thread ends.
//! - **At the user-interactive class** ([`exit_guard::spawn_user_interactive`]), as the handler
//! threads that began the primaries before: its begins race the next command buffer's take.
use crate::device::lock;
use crate::exit_guard;
use crate::spares::BeginTargets;
use ash::vk;
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::thread::JoinHandle;
/// The most pools that wait for the thread (the module docs).
pub(crate) const QUEUE: usize = 64;
/// A device's begin-ahead thread (the module docs).
#[derive(Default)]
pub(crate) struct BeginAhead {
shared: Arc<Shared>,
thread: Mutex<Option<JoinHandle<()>>>,
}
/// What the thread and the posters share.
#[derive(Default)]
struct Shared {
state: Mutex<State>,
/// A pool was posted, or the thread is asked to stop.
work: Condvar,
/// The crate's device tests' hold of each posted pool's begins as they start
/// (`tests/begin_ahead.rs`).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
held: crate::freed_memory::held::Held,
/// A posted pool's begins ended, for the crate's device tests ([`BeginAhead::settle`]).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
idle: Condvar,
}
#[derive(Default)]
struct State {
queue: VecDeque<vk::CommandPool>,
/// The thread was started, or a start failed.
started: bool,
stopping: bool,
/// The thread makes a posted pool's begins, for the crate's device tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
running: bool,
}
impl BeginAhead {
/// Post the spare command pool `raw`, given back settled, for its primaries to be begun ahead
/// on the thread, started unless it runs, with what `targets` gives; nothing where the pool
/// waits already, the queue is full, the device's teardown began or the host starts no
/// thread (the module docs).
pub(crate) fn post(&self, raw: vk::CommandPool, targets: impl FnOnce() -> BeginTargets) {
let mut state = lock(&self.shared.state);
if state.stopping || state.queue.len() >= QUEUE || state.queue.contains(&raw) {
return;
}
if !state.started {
state.started = true;
let (shared, targets) = (Arc::clone(&self.shared), targets());
let builder = std::thread::Builder::new().name("metal2vulkan-begin-ahead".into());
match exit_guard::spawn_user_interactive(builder, move || run(&shared, &targets)) {
Ok(handle) => *lock(&self.thread) = Some(handle),
Err(_) => return,
}
}
if lock(&self.thread).is_none() {
return;
}
state.queue.push_back(raw);
drop(state);
self.shared.work.notify_one();
}
/// The device's teardown, before it releases the spares: no pool is posted from here on, the
/// thread ends once its begins in progress are done, joined; those still waiting are begun by
/// none.
pub(crate) fn stop(&self) {
lock(&self.shared.state).stopping = true;
self.shared.work.notify_all();
let handle = lock(&self.thread).take();
if let Some(handle) = handle {
let _ = handle.join();
}
}
/// The tests' hold of each posted pool's begins as they start.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn held(&self) -> &crate::freed_memory::held::Held {
&self.shared.held
}
/// Wait until no posted pool waits and the thread makes no begins, for the crate's device
/// tests: what the spares hold, and the counts of the begins, are then final for the command
/// buffers whose waits returned, as a waiter's return comes after its command buffer's post.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn settle(&self) {
let mut state = lock(&self.shared.state);
while state.running || !state.queue.is_empty() && lock(&self.thread).is_some() {
state = (self.shared.idle.wait(state)).unwrap_or_else(PoisonError::into_inner);
}
}
}
/// The thread's loop: each posted pool's begins in turn, until stopped or the process exits.
fn run(shared: &Shared, targets: &BeginTargets) {
loop {
let raw = {
let mut state = lock(&shared.state);
loop {
if state.stopping {
return;
}
if let Some(raw) = state.queue.pop_front() {
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
state.running = true;
}
break raw;
}
state = (shared.work.wait(state)).unwrap_or_else(PoisonError::into_inner);
}
};
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
shared.held.pass();
if exit_guard::closed() {
return;
}
targets.begin_ahead(raw);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
{
lock(&shared.state).running = false;
shared.idle.notify_all();
}
}
}
@@ -83,8 +83,6 @@ struct GateState {
finished: bool,
/// The [`Hold`]s alive.
held: usize,
/// The threads blocked until it opens ([`Gate::awaited`]).
waiting: usize,
}
impl GateState {
@@ -117,13 +115,6 @@ impl Gate {
lock(&self.state).open()
}
/// Whether a thread is blocked until the gate opens, in [`wait`](Self::wait) or
/// [`wait_until`](Self::wait_until): what the thread that finishes the command buffer does
/// before its hold goes delays that thread's return.
pub(crate) fn awaited(&self) -> bool {
lock(&self.state).waiting > 0
}
/// Block until the gate opens, answering what the wait did ([`Waited`]). `Err` once the
/// process is exiting and it is not open: the runtime's threads that would open it end
/// (`exit_guard`).
@@ -135,7 +126,6 @@ impl Gate {
/// [`closed`](exit_guard::closed), or a test's own).
pub(crate) fn wait_unless(&self, exiting: impl Fn() -> bool) -> Result<Waited, Exiting> {
let mut state = lock(&self.state);
state.waiting += 1;
let mut did = Waited::default();
// Whether the sleep before this look ended at a notify rather than at its slice.
let mut notified = false;
@@ -155,7 +145,6 @@ impl Gate {
state = woke;
notified = !how.timed_out();
};
state.waiting -= 1;
waited
}
@@ -163,7 +152,6 @@ impl Gate {
/// at once once the process is exiting, as [`Gate::wait`].
pub(crate) fn wait_until(&self, deadline: Instant) -> Result<Waited, TimedOut> {
let mut state = lock(&self.state);
state.waiting += 1;
let mut did = Waited::default();
// Whether the sleep before this look ended at a notify rather than at its slice.
let mut notified = false;
@@ -184,7 +172,6 @@ impl Gate {
state = woke;
notified = !how.timed_out();
};
state.waiting -= 1;
waited
}
@@ -117,7 +117,7 @@ use super::resource::{ObjectId, ResourceKey};
use super::retained::Lately;
use super::scheduler::{BatchSync, Hand, StepWaits};
use super::shadow::{ShadowCarry, Takes};
use super::spares::CommandPool;
use super::spares::{CommandPool, Opened};
use super::sparse::encoder::SparseUpdate;
use super::sparse::indirect;
use super::submit_failure::{submit_failed, try_lock, Failed};
@@ -3641,7 +3641,7 @@ impl CommandBuffer {
}
/// An encoder's own primary `VkCommandBuffer` from this command buffer's pool, and whether it
/// is begun: the pool's primary begun ahead where it holds one (`spares.rs`), else as
/// is begun: one of the pool's primaries begun ahead where it holds any (`spares.rs`), else as
/// [`allocate_raw`](Self::allocate_raw) hands one out, to begin. The caller holds `state`.
pub(super) fn encoder_primary(
&self,
@@ -6130,10 +6130,13 @@ impl CommandBufferShared {
}
}
/// [`CommandBuffer::encoder_primary`].
/// [`CommandBuffer::encoder_primary`]: a primary its pool's begin ahead missed counted
/// (`WorkCounts::encoder_primaries_begun_ahead_missed`).
fn encoder_primary(&self, state: &mut State) -> Result<(vk::CommandBuffer, bool), Error> {
if let Some(buffer) = self.pool(state)?.take_begun() {
return Ok((buffer, true));
match self.pool(state)?.open_encoder() {
Opened::Begun(buffer) => return Ok((buffer, true)),
Opened::Missed => (self.device.shared().counts).encoder_primary_begun_ahead_missed(),
Opened::Own => {}
}
Ok((self.allocate_raw(state)?, false))
}
@@ -6929,7 +6932,7 @@ impl CommandBufferShared {
fn complete_seen(self: &Arc<Self>, result: Result<(), CommandBufferError>) -> Rest {
// A thread sleeps on `changed`, as the state's lock below reads.
let parked;
// Its command pool, where it settled, whose primary the device's spares begin ahead once
// Its first command pool, where it settled, posted to the device's begin-ahead thread once
// its completed handlers ran (below).
let mut settled_pool = None;
// The heap versions its commands bound, let go of once its completed handlers ran.
@@ -7135,15 +7138,20 @@ impl CommandBufferShared {
// wait), so nothing of its pools is pending: its command pool goes to the device's
// spares whatever its status, never released on this thread (`spares.rs`); its
// descriptor pools go once its completed handlers ran (below).
let pools = state.pools();
if let Some(first) = pools.first() {
let mut pools = state.pools();
if !pools.is_empty() {
// None of the pools' command buffers is recording where it completed and ended
// every one the pools handed out: a recording it left unused leaves one so.
let ended = self.raws_ended.load(Ordering::Relaxed);
let handed: usize = pools.iter().map(CommandPool::handed_out).sum();
let settled = state.status == CommandBufferStatus::Completed
&& u64::try_from(handed).is_ok_and(|handed| handed == ended);
settled_pool = settled.then_some(first.raw);
// Its first, whose primaries its encoders took, is posted to the device's
// begin-ahead thread once its completed handlers ran (below, `begin_ahead.rs`).
if settled {
pools[0].begin_ahead_due();
settled_pool = Some(pools[0].raw);
}
let shared = self.device.shared();
let recorded = self.recorded.load(Ordering::Relaxed);
for pool in pools {
@@ -7310,13 +7318,13 @@ impl CommandBufferShared {
// hold holds it from: the notify for them is that hold's, as it goes (`gate.rs`).
let notified = self.gate.finish();
self.device.shared().counts.command_buffer_wake(notified);
// Its pool's primary begun ahead, where no command buffer took the pool since
// (`spares.rs`), and no thread waits for the gate, which opens only once this
// transition's hold goes: a waiter's return is never delayed by the begin, but for one
// that came after this check.
if let Some(pool) = settled_pool.filter(|_| !self.gate.awaited()) {
// Its pool's primaries begun ahead, where no command buffer took the pool since
// (`spares.rs`), on the device's begin-ahead thread: this thread only posts the pool, so
// neither a waiter's return nor the queue's next transitions wait for a begin
// (`begin_ahead.rs`).
if let Some(pool) = settled_pool {
let shared = self.device.shared();
shared.spares.begin_ahead(shared, pool);
(shared.begin_ahead).post(pool, || shared.spares.begin_targets(shared));
}
}
}
@@ -7353,8 +7361,8 @@ enum To {
/// What a command buffer's transition to `Completed` or `Error` still does once its status is
/// final and its completion-seen handlers ran (`CommandBufferShared::complete_rest`).
pub(crate) struct Rest {
/// Its command pool, where it settled, whose primary the device's spares begin ahead once its
/// completed handlers ran.
/// Its first command pool, where it settled, whose primaries the device's begin-ahead thread
/// begins once its completed handlers ran (`begin_ahead.rs`).
settled_pool: Option<vk::CommandPool>,
/// The heap versions its commands bound, let go of once its completed handlers ran.
released_versions: Vec<Arc<super::heap_sets::SetVersion>>,
+32 -11
View File
@@ -718,6 +718,9 @@ pub(super) struct DeviceShared {
/// What lets go of its kept empty memory blocks and parked objects once their time passed,
/// whether or not the program makes anything more, and its thread (`idle_sweep.rs`).
pub(super) idle_sweep: crate::idle_sweep::IdleSweep,
/// The thread its settled spare command pools' primaries are begun ahead on
/// (`begin_ahead.rs`).
pub(crate) begin_ahead: crate::begin_ahead::BeginAhead,
/// How its command buffers are timed on the GPU (`gpu_time.rs`).
pub(super) timing: Timing,
/// Its Vulkan views may present an image in another component layout: it has no portability
@@ -782,7 +785,8 @@ pub(super) struct DeviceShared {
/// split, which the next such instances take (`render/inline_splits.rs`).
pub(super) kept_rooms: crate::render::SpareKept,
/// Counts of its commit path's work, for the lanes (`work_counts.rs`). Shared with the
/// queue-switch check's thread (`queue_switch_check.rs`).
/// queue-switch check's thread (`queue_switch_check.rs`) and the begin-ahead thread
/// (`begin_ahead.rs`).
pub(super) counts: Arc<super::work_counts::Counters>,
/// Its uses of its `VkQueue`s seen as one, which its blocks made ahead wait on for a moment
/// right after a burst of submissions (`queue_quiet.rs`, `memory/ready.rs`). Shared with
@@ -1097,19 +1101,12 @@ impl DeviceShared {
&self,
info: &vk::CommandBufferAllocateInfo<'_>,
) -> Result<Vec<vk::CommandBuffer>, Error> {
// SAFETY: the device is live; `info` names one of its pools, which the caller holds
// exclusively.
let allocated = unsafe {
self.loader_word
.restored(|| self.vk().allocate_command_buffers(info))
};
exit_guard::called(Call::AllocateCommandBuffers);
let allocated = allocate_command_buffers(self.vk(), &self.loader_word, &self.counts, info);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if allocated.is_ok() {
self.counts.command_buffers_made(info.command_buffer_count);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
(self.spares).allocated(std::panic::Location::caller(), info.command_buffer_count);
}
allocated.map_err(super::error::vulkan)
allocated
}
/// Name `pipeline`, just made and held by this thread alone, for the layers' messages:
@@ -1269,6 +1266,9 @@ impl Drop for DeviceShared {
self.idle_sweep.stop();
self.completion.stop();
self.contexts.stop();
// No command buffer is left to post a pool to the begin-ahead thread, which holds nothing
// of the device: it ends before the spares go below (`begin_ahead.rs`).
self.begin_ahead.stop();
// The encoder times' last summary, where they are on: no completion tallies more
// (`encoder_times.rs`).
for line in self.timing.encoders().last() {
@@ -2063,6 +2063,26 @@ impl Device {
}
}
/// `vkAllocateCommandBuffers` of `info` through `vk`: the loader serves it and reads the device's
/// loader word `word` first ([`DeviceWord::restored`]); counted in `counts`. The device's
/// ([`DeviceShared::allocate_command_buffers`]), and its begin-ahead thread's, which holds no
/// device (`spares.rs`'s `BeginTargets`).
pub(crate) fn allocate_command_buffers(
vk: &Vk,
word: &DeviceWord,
counts: &super::work_counts::Counters,
info: &vk::CommandBufferAllocateInfo<'_>,
) -> Result<Vec<vk::CommandBuffer>, Error> {
// SAFETY: the device is live; `info` names one of its pools, which the caller holds
// exclusively.
let allocated = unsafe { word.restored(|| vk.allocate_command_buffers(info)) };
exit_guard::called(Call::AllocateCommandBuffers);
if allocated.is_ok() {
counts.command_buffers_made(info.command_buffer_count);
}
allocated.map_err(super::error::vulkan)
}
/// The parts [`DeviceShared`] is built from, by `create.rs` and `adopt.rs` alike.
pub(super) struct Parts {
pub(super) instance: Arc<InstanceShared>,
@@ -3312,6 +3332,7 @@ impl Device {
#[cfg(unix)]
dma_buf_files: Default::default(),
idle_sweep,
begin_ahead: Default::default(),
timing,
view_reinterpretation,
generated_commands,
+1 -1
View File
@@ -790,7 +790,7 @@ impl EncoderCore {
(fold.tail, None)
}
None => {
// The pool's primary begun ahead where it holds one (`spares.rs`).
// One of the pool's primaries begun ahead where it holds any (`spares.rs`).
let (raw, begun) = command_buffer.encoder_primary(&mut state)?;
if !begun {
let begin = vk::CommandBufferBeginInfo::default()
@@ -1259,8 +1259,10 @@ where
/// with the utilization floor at its top on Linux, from its start ([`run_at_user_interactive`]):
/// the scheduler's (`scheduler/`), each `VkQueue`'s waiter, which makes the completion turns
/// (`command_buffer/completion.rs`), every thread of the handler
/// pool (`contexts/`), the device's lowering thread (`render/lowering_worker.rs`), and a predicated loop's check's (`command_buffer/rerun.rs`),
/// whose work the program's command buffers wait for. A thread one of them starts (a program's
/// pool (`contexts/`), the device's lowering thread (`render/lowering_worker.rs`), a predicated
/// loop's check's (`command_buffer/rerun.rs`), whose work the program's command buffers wait for,
/// and the device's begin-ahead thread (`begin_ahead.rs`), whose begins race the next command
/// buffer's take of a pool. A thread one of them starts (a program's
/// thread made in a handler) does not take either: it starts at the default class on macOS
/// ([`spawn`]), and with no floor on Linux.
pub(crate) fn spawn_user_interactive<F, T>(
+1
View File
@@ -42,6 +42,7 @@ mod attachment_stand_in;
mod attachmentless;
mod attributes;
mod batch_order;
mod begin_ahead;
mod binary_archive;
mod binding;
mod binding_view;
+229 -91
View File
@@ -234,33 +234,40 @@
//! 0 to 5 of a run's 4020 pass opens made one, 16 allocations each against 14. A making that
//! fails is left to that open, and one the bound leaves no room for is freed with the rest
//! past it.
//! - **A settled pool given back holds a primary already begun.** The thread that completed its
//! command buffer begins one of its primaries once the completed handlers ran
//! (`ONE_TIME_SUBMIT`, as every encoder begins its own; recording nothing), inside a section of
//! the exit guard, where no command buffer took the pool since ([`Spares::begin_ahead`]). It
//! takes the pool out of the spares under their lock and begins with no lock held, then keeps
//! - **A settled pool given back holds primaries already begun.** The thread that completed its
//! command buffer posts the pool to the device's begin-ahead thread once the completed handlers
//! ran, before the command buffer's gate opens (`begin_ahead.rs`, `command_buffer/gate.rs`), and
//! begins none itself: neither a waiter's return nor the queue's next transitions wait for a
//! begin. That thread begins as many of the pool's primaries as encoders of its last command
//! buffer opened their own in it, one at least and [`AHEAD`] at most (`ONE_TIME_SUBMIT`, as
//! every encoder begins its own; recording nothing), each inside a section of the exit guard,
//! while no command buffer took the pool since ([`BeginTargets::begin_ahead`]). For each it
//! takes the pool out of the spares under their lock, begins one with no lock held, then keeps
//! it again, the newest: a taker meanwhile takes another spare, or makes a pool, and never
//! waits for that begin (a wait on the lock across it was 747 waits of the guest's encoding
//! thread in 255 frames, 11 us at the median, on ANV). The command buffer's gate opens only
//! once that thread's hold goes (`command_buffer/gate.rs`), so it begins none where a thread
//! waits for the gate: a waiter's return waits for no begin, but for one wait that came after
//! the check. The first encoder of the command buffer that takes the pool takes the primary
//! begun (`EncoderCore::open`), so the thread that encodes makes no `vkBeginCommandBuffer` for
//! it. On ANV, whose begin clears the command buffer's state (Mesa 26.2.4,
//! waits for a begin (a wait on the lock across one was 747 waits of the guest's encoding
//! thread in 255 frames, 11 us at the median, on ANV), and a taker between two begins takes the
//! pool with those begun so far. Each encoder of the command buffer that takes the pool that
//! opens its own primary takes one begun while the pool holds any (`EncoderCore::open`), so the
//! thread that encodes makes no `vkBeginCommandBuffer` for it. On ANV, whose begin clears the
//! command buffer's state (Mesa 26.2.4,
//! `genX(BeginCommandBuffer)`), that begin was 8 to 20 us of the encoding thread's time a
//! command buffer (above). Vulkan asks only external synchronization of a command buffer and
//! its pool, never one thread: `vkBeginCommandBuffer`, and every command recorded, "Host access
//! to commandBuffer must be externally synchronized" and "Host access to the VkCommandPool that
//! commandBuffer was allocated from must be externally synchronized". The pool passes between
//! threads through the spares, under their lock, and is never in use on two threads at once, so
//! a command buffer begun on one thread is recorded on another. Only the first encoder takes
//! it: the primaries every other path makes (segments, continuations, a batch's barriers) are
//! never the begun one. A pool whose taker resets it (one given back unsettled) resets the begun
//! primary with the rest, which is then an ordinary one again. A pool given back unsettled, or
//! while a thread waited, or whose begin fails, holds none; nor does one holding no primary
//! where the spares hold [`HELD`] command buffers. A taker takes a spare holding one first
//! ([`take_command_pool`]). Counted: `WorkCounts::primaries_begun_ahead`, and
//! those encoders took, `WorkCounts::encoder_primaries_begun_ahead`.
//! a command buffer begun on one thread is recorded on another. Only an encoder's own primary
//! is one begun: the primaries every other path makes (segments, continuations, a batch's
//! barriers) never are. Those no encoder took stay begun for the pool's next command buffer,
//! beside the [`POOL_HOLDS`] of a level a command buffer it serves past its first grows it to. A
//! pool whose taker resets it (one given back unsettled) resets the begun primaries with the
//! rest, which are then ordinary ones again. A pool given back unsettled, or whose begin fails,
//! holds none; nor does one holding no primary where the spares hold [`HELD`] command buffers.
//! A taker takes a spare holding one first ([`take_command_pool`]). Counted:
//! `WorkCounts::primaries_begun_ahead`; those encoders took,
//! `WorkCounts::encoder_primaries_begun_ahead`; and the encoders among as many as the pool's
//! begin ahead begins that found none, the pool taken before the thread made its begins, or out
//! of the spares as the thread came to it, `WorkCounts::encoder_primaries_begun_ahead_missed`.
//! - **Descriptor pools are reset by the taker**, on the thread that encodes: the program's own, or
//! one running the program's code (a handler).
//! - **Taken in sections only where they need no reset.** A section of the exit guard (a host
@@ -285,11 +292,14 @@
//! every begin is (`device/functions.rs`).
use super::descriptor_arena::{Room, SetNeeds};
use super::device::functions::Functions;
use super::device::{lock, DeviceShared};
use super::error::{vulkan, Error};
use super::exit_guard::{self, Call};
use super::loader_word::DeviceWord;
use super::pending_audit::Freeing;
use super::release::{self, Released};
use super::work_counts::Counters;
use ash::vk;
use std::cmp::Reverse;
use std::collections::VecDeque;
@@ -342,6 +352,12 @@ pub(super) const TRIMMED_AT_ONCE: usize = 1024;
/// at about 110 bytes a region draw of three commands (its viewport, its scissor, its draw).
pub(super) const RECORDED: u64 = 1 << 14;
/// The most primaries a settled spare command pool holds begun ahead: as many as encoders of its
/// last command buffer opened their own in it, up to this (the module docs). A program that deals
/// a frame's command buffer into a dozen side by side opened 5.6 encoders' own in each, on
/// average (measured on ANV).
pub(super) const AHEAD: usize = 8;
/// The command buffers of a level a command buffer makes in one pool, where no spare holds one;
/// past them it takes a pool for more, a spare holding none of the level or a new one (the module
/// docs): what a pool out may hold unused while every other spare holding one is out.
@@ -383,9 +399,21 @@ pub(super) struct CommandPool {
family: u32,
made: [Vec<vk::CommandBuffer>; 2],
handed: [usize; 2],
/// A primary made from the pool, begun ahead while the pool was a spare and recording
/// nothing, not among `made` until an encoder takes it ([`take_begun`](Self::take_begun)).
pub(super) begun: Option<vk::CommandBuffer>,
/// Primaries made from the pool, begun ahead while the pool was a spare and recording
/// nothing, none among `made` until an encoder takes it ([`open_encoder`](Self::open_encoder)).
pub(super) begun: Vec<vk::CommandBuffer>,
/// The encoders of the command buffer that took it last that opened their own primary in it,
/// so far ([`open_encoder`](Self::open_encoder)), and of the one before, as it gave the pool
/// back: the primaries its begin ahead begins ([`ahead`](Self::ahead)).
opened: usize,
last_opened: usize,
/// Given back settled, it was posted to the device's begin-ahead thread, which has not made
/// its begins yet (the module docs).
pub(super) due: bool,
/// The primaries its begin ahead was due to begin as the command buffer that holds it took it
/// ([`ahead`](Self::ahead)), where it was `due` then, else 0: an encoder among as many that
/// finds none begun counts one missed ([`Opened::Missed`]).
owed: usize,
/// One of its command buffers may still be recording: the command buffer that gave it back
/// did not complete, or left one it was handed unended (the module docs), so its taker
/// resets it.
@@ -416,7 +444,11 @@ impl CommandPool {
family,
made: [Vec::new(), Vec::new()],
handed: [0, 0],
begun: None,
begun: Vec::new(),
opened: 0,
last_opened: 0,
due: false,
owed: 0,
recording: false,
uses: VecDeque::new(),
spans: None,
@@ -438,6 +470,7 @@ impl CommandPool {
}
self.uses.push_back(self.handed);
self.given = Some(now);
self.last_opened = self.opened;
let (start, mut current, mut last) = self.spans.unwrap_or((now, [0, 0], [0, 0]));
let start = match now.saturating_duration_since(start) {
since if since < RECENT_FOR => start,
@@ -473,15 +506,16 @@ impl CommandPool {
/// Whether no command buffer took it since one gave it back [`IDLE_FOR`] or longer before
/// `now`, and it holds a command buffer (the module docs).
fn idle(&self, now: Instant) -> bool {
let holds = self.begun.is_some() || self.made.iter().any(|made| !made.is_empty());
let holds = !self.begun.is_empty() || self.made.iter().any(|made| !made.is_empty());
let since = self.given.map(|given| now.saturating_duration_since(given));
holds && since.is_some_and(|since| since >= IDLE_FOR)
}
/// Every command buffer it holds, taken out of it to be freed, the primary begun ahead first:
/// a spare left idle (the module docs).
/// Every command buffer it holds, taken out of it to be freed, the primaries begun ahead
/// first: a spare left idle (the module docs).
pub(super) fn shed(&mut self) -> Vec<vk::CommandBuffer> {
let mut shed: Vec<vk::CommandBuffer> = self.begun.take().into_iter().collect();
let mut shed = Vec::with_capacity(self.held());
shed.append(&mut self.begun);
self.freed[level_index(vk::CommandBufferLevel::PRIMARY)] += shed.len();
for (at, made) in self.made.iter_mut().enumerate().rev() {
self.freed[at] += made.len();
@@ -491,8 +525,8 @@ impl CommandPool {
}
/// Its command buffers past `keep` in all, the last made, taken out of it to be freed:
/// secondaries first, one kept, then primaries, then that secondary, then the primary begun
/// ahead, so that it holds at most `keep` (the module docs).
/// secondaries first, one kept, then primaries, then that secondary, then the primaries begun
/// ahead, the last begun first, so that it holds at most `keep` (the module docs).
pub(super) fn past(&mut self, keep: usize) -> Vec<vk::CommandBuffer> {
let mut over = self.held().saturating_sub(keep);
let mut past = Vec::new();
@@ -504,29 +538,39 @@ impl CommandPool {
self.freed[at] += made.len() - from;
past.extend(made.drain(from..));
}
// Past every one made, only the primary begun ahead is left over.
if over > 0 {
if let Some(begun) = self.begun.take() {
self.freed[level_index(vk::CommandBufferLevel::PRIMARY)] += 1;
past.push(begun);
}
}
// Past every one made, only the primaries begun ahead are left over.
let from = self.begun.len() - over.min(self.begun.len());
self.freed[level_index(vk::CommandBufferLevel::PRIMARY)] += self.begun.len() - from;
past.extend(self.begun.drain(from..).rev());
past
}
/// The command buffers it holds, the primary begun ahead among them.
/// The command buffers it holds, the primaries begun ahead among them.
pub(super) fn held(&self) -> usize {
self.made[0].len() + self.made[1].len() + usize::from(self.begun.is_some())
self.made[0].len() + self.made[1].len() + self.begun.len()
}
/// The pool's primary begun ahead (the module docs), handed out: taken by the first encoder
/// of the command buffer that took the pool. `None` where it holds none.
pub(super) fn take_begun(&mut self) -> Option<vk::CommandBuffer> {
let buffer = self.begun.take()?;
/// An encoder of the command buffer that took the pool opens its own primary in it (the
/// module docs), counted for the pool's next begin ahead: one of its primaries begun ahead,
/// handed out, where it holds any; else whether its begin ahead missed it.
pub(super) fn open_encoder(&mut self) -> Opened {
self.opened += 1;
let Some(buffer) = self.begun.pop() else {
return match self.opened <= self.owed {
true => Opened::Missed,
false => Opened::Own,
};
};
let at = level_index(vk::CommandBufferLevel::PRIMARY);
self.made[at].insert(self.handed[at], buffer);
self.handed[at] += 1;
Some(buffer)
Opened::Begun(buffer)
}
/// The primaries its begin ahead begins: as many as encoders of the command buffer that gave
/// it back last opened their own in it, one at least and [`AHEAD`] at most (the module docs).
fn ahead(&self) -> usize {
self.last_opened.clamp(1, AHEAD)
}
/// A command buffer of `level` made from the pool before a command buffer last took it, not
@@ -575,25 +619,37 @@ impl CommandPool {
}
/// A command buffer took the pool, reset where it was [`recording`](Self::recording): none of
/// the command buffers made from it is handed out, and none is recording but the primary
/// begun ahead, where the pool was not reset.
/// the command buffers made from it is handed out, and none is recording but the primaries
/// begun ahead, where the pool was not reset. What its begin ahead still owed it, where it
/// was due, is noted for its encoders ([`open_encoder`](Self::open_encoder)).
pub(super) fn taken(&mut self) {
if self.recording {
// The reset left the primary begun ahead in the initial state.
if let Some(buffer) = self.begun.take() {
self.made[level_index(vk::CommandBufferLevel::PRIMARY)].push(buffer);
}
// The reset left the primaries begun ahead in the initial state.
let at = level_index(vk::CommandBufferLevel::PRIMARY);
self.made[at].append(&mut self.begun);
}
self.handed = [0, 0];
self.recording = false;
self.owed = match self.due {
true => self.ahead(),
false => 0,
};
self.due = false;
self.opened = 0;
}
/// Every command buffer made from the pool, of both levels, the primary begun ahead among
/// The command buffer giving the pool back settled posts it to the device's begin-ahead
/// thread (the module docs): it is due its begins until the thread made them.
pub(super) fn begin_ahead_due(&mut self) {
self.due = true;
}
/// Every command buffer made from the pool, of both levels, the primaries begun ahead among
/// them: what its reset or give-back frees (the device's pending audit, `pending_audit.rs`).
fn buffers(&self) -> Vec<vk::CommandBuffer> {
let [primaries, secondaries] = &self.made;
let made = primaries.iter().chain(secondaries).copied();
made.chain(self.begun).collect()
made.chain(self.begun.iter().copied()).collect()
}
/// Whether the pool made no secondary command buffer (the module docs).
@@ -631,9 +687,9 @@ impl CommandPool {
}
/// Whether the pool may begin a primary ahead: none of its command buffers is recording or
/// pending, and it holds none begun (the module docs).
/// pending, and it holds fewer begun than its begin ahead begins ([`ahead`](Self::ahead)).
fn begins_ahead(&self) -> bool {
!self.recording && self.begun.is_none()
!self.recording && self.begun.len() < self.ahead()
}
/// The command buffers its begin ahead makes: one where it holds no primary to begin.
@@ -644,9 +700,9 @@ impl CommandPool {
/// Begin one of the pool's primaries ahead, where it [`begins_ahead`](Self::begins_ahead): one
/// it made, which its begin resets, or a new one, counted out with the pool as it was taken
/// ([`CommandPools::take_to_begin`]). Inside a section of the exit guard, on a pool taken out
/// of the spares; nothing where the guard is closing, and none begun where the making or the
/// begin fails. Whether it began one.
fn begin_ahead(&mut self, device: &DeviceShared) -> bool {
/// of the spares, on the device's begin-ahead thread (`begin_ahead.rs`); nothing where the
/// guard is closing, and none begun where the making or the begin fails. Whether it began one.
fn begin_ahead(&mut self, targets: &BeginTargets) -> bool {
if !self.begins_ahead() {
return false;
}
@@ -661,7 +717,7 @@ impl CommandPool {
.command_pool(self.raw)
.level(vk::CommandBufferLevel::PRIMARY)
.command_buffer_count(1);
match device.allocate_command_buffers(&info) {
match targets.allocate_command_buffers(&info) {
Ok(made) if !made.is_empty() => {
self.making(at);
made[0]
@@ -673,13 +729,14 @@ impl CommandPool {
let begin = vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
// SAFETY: the pool is out of the spares, this thread's alone, and none of its command
// buffers is pending or recording (settled): the buffer is executable, invalid or
// initial, and its begin resets it (`VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`).
let begun = unsafe { device.vk().begin_command_buffer(buffer, &begin) };
// buffers is pending or recording (settled) but those begun ahead, which are not among
// `made`: the buffer is executable, invalid or initial, and its begin resets it
// (`VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT`).
let begun = unsafe { targets.functions.get().begin_command_buffer(buffer, &begin) };
exit_guard::called(Call::BeginCommandBuffer);
match begun {
Ok(()) => {
self.begun = Some(buffer);
self.begun.push(buffer);
true
}
// Begun again at its next use, which resets it.
@@ -691,6 +748,19 @@ impl CommandPool {
}
}
/// What an encoder opening its own primary in its command buffer's pool found there
/// ([`CommandPool::open_encoder`]).
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Opened {
/// A primary begun ahead, handed out.
Begun(vk::CommandBuffer),
/// None, where the pool's begin ahead owed it one: the pool was taken before the device's
/// begin-ahead thread made its begins, or was out of the spares as the thread came to it.
Missed,
/// None, past those its begin ahead begins, or in a pool not due any.
Own,
}
/// A descriptor pool, with the room it was made with.
pub(super) struct DescriptorPool {
pub(super) raw: vk::DescriptorPool,
@@ -733,14 +803,18 @@ impl CommandPools {
}
/// The spare command pool `raw`, taken out to begin a primary ahead in
/// ([`Spares::begin_ahead`]), where it is still among the spares and may begin one
/// ([`BeginTargets::begin_ahead`]), where it is still among the spares and may begin one
/// ([`CommandPool::begins_ahead`]), and where its begin makes the primary, only while that
/// leaves the spares holding at most [`HELD`] command buffers: counted out with the one it
/// makes, so that a give-back meanwhile keeps the bound with it (the module docs).
/// makes, so that a give-back meanwhile keeps the bound with it (the module docs). A spare
/// that may begin no more is due no more ([`CommandPool::due`]).
pub(super) fn take_to_begin(&mut self, raw: vk::CommandPool) -> Option<CommandPool> {
let at = (self.spares.iter()).rposition(|pool| pool.raw == raw && pool.begins_ahead())?;
let at = (self.spares.iter()).rposition(|pool| pool.raw == raw)?;
let makes = self.spares[at].begin_makes();
if makes > 0 && self.held() + makes > HELD {
let held = self.held();
let pool = &mut self.spares[at];
if !pool.begins_ahead() || (makes > 0 && held + makes > HELD) {
pool.due = false;
return None;
}
let mut pool = self.spares.remove(at);
@@ -751,6 +825,78 @@ impl CommandPools {
}
}
/// What the device's begin-ahead thread begins a settled spare command pool's primaries with
/// (`begin_ahead.rs`, [`Spares::begin_targets`]): the spare command pools, the device's functions,
/// its loader word and its counts, none of them the device.
pub(crate) struct BeginTargets {
pools: Arc<Mutex<CommandPools>>,
functions: Arc<Functions>,
loader_word: Arc<DeviceWord>,
counts: Arc<Counters>,
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
churn: Arc<Mutex<Churn>>,
}
impl BeginTargets {
/// Begin primaries ahead in the spare command pool `raw`, one at a time, while it is still a
/// spare, settled, holding fewer begun than its begin ahead begins, and the bound leaves room
/// for the primary a begin makes, if it holds none (the module docs): each time taken out of
/// the spares under their lock, one begun with no lock held, so a taker meanwhile takes
/// another spare rather than wait for the begin, and kept again, the newest. Each counted
/// (`WorkCounts::primaries_begun_ahead`) once its pool is kept again, so a taker that saw the
/// count finds the pool among the spares. The pool is due no more once it may begin no more,
/// or a begin fails. The primaries it began.
pub(crate) fn begin_ahead(&self, raw: vk::CommandPool) -> usize {
let mut began = 0;
loop {
let taken = lock(&self.pools).take_to_begin(raw);
let Some(mut pool) = taken else {
return began;
};
let begun = pool.begin_ahead(self);
{
let mut pools = lock(&self.pools);
pools.came_back(&mut pool);
pool.due &= begun;
keep_command_pool(&mut pools.spares, pool);
}
if !begun {
return began;
}
self.counts.primary_begun_ahead();
began += 1;
}
}
/// `vkAllocateCommandBuffers` of `info`, as the device's (`DeviceShared::allocate_command_buffers`),
/// counted by the place that asked for the crate's device tests (`Spares::churn`).
#[cfg_attr(test, track_caller)]
fn allocate_command_buffers(
&self,
info: &vk::CommandBufferAllocateInfo<'_>,
) -> Result<Vec<vk::CommandBuffer>, Error> {
let vk = self.functions.get();
let made =
super::device::allocate_command_buffers(vk, &self.loader_word, &self.counts, info);
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
if made.is_ok() {
allocated(
&self.churn,
std::panic::Location::caller(),
info.command_buffer_count,
);
}
made
}
}
/// `count` command buffers allocated, asked for `at`, into `churn`, for the crate's device tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
fn allocated(churn: &Mutex<Churn>, at: &std::panic::Location<'_>, count: u32) {
let place = format!("{}:{}", at.file(), at.line());
*lock(churn).allocated.entry(place).or_default() += u64::from(count);
}
/// A device's spares.
pub(super) struct Spares {
/// Shared with the device's free thread, which keeps a pool again once its command buffers
@@ -767,9 +913,10 @@ pub(super) struct Spares {
/// crate's device tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
freed_on: Arc<Mutex<Vec<String>>>,
/// The device's command buffers allocated and the spares' freed, for the crate's device tests.
/// The device's command buffers allocated and the spares' freed, for the crate's device tests;
/// shared with the device's begin-ahead thread ([`BeginTargets`]).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
churn: Mutex<Churn>,
churn: Arc<Mutex<Churn>>,
/// The command buffers' arenas', oldest first.
descriptor_pools: Mutex<VecDeque<DescriptorPool>>,
/// The fitted arenas' (the module docs), oldest first.
@@ -1050,8 +1197,7 @@ impl Spares {
/// (`DeviceShared::allocate_command_buffers`), for the crate's device tests.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(super) fn allocated(&self, at: &std::panic::Location<'_>, count: u32) {
let place = format!("{}:{}", at.file(), at.line());
*lock(&self.churn).allocated.entry(place).or_default() += u64::from(count);
allocated(&self.churn, at, count);
}
/// The device's command buffers allocated and the spares' freed so far, for the crate's
@@ -1098,25 +1244,17 @@ impl Spares {
.collect()
}
/// Begin a primary ahead in the spare command pool `raw` of `device`, where it is still a
/// spare, settled, and holds none begun, and where the bound leaves room for the primary it
/// makes, if it holds none (the module docs): taken out of the spares under their lock,
/// begun with no lock held, so a taker meanwhile takes another spare rather than wait for the
/// begin, and kept again, the newest. Counted (`WorkCounts::primaries_begun_ahead`) once it is
/// kept again, so a taker that saw the count finds the pool among the spares.
pub(super) fn begin_ahead(&self, device: &DeviceShared, raw: vk::CommandPool) {
let taken = lock(&self.command_pools).take_to_begin(raw);
let Some(mut pool) = taken else {
return;
};
let begun = pool.begin_ahead(device);
{
let mut pools = lock(&self.command_pools);
pools.came_back(&mut pool);
keep_command_pool(&mut pools.spares, pool);
}
if begun {
device.counts.primary_begun_ahead();
/// What the device's begin-ahead thread begins its spare command pools' primaries with
/// (`begin_ahead.rs`): the spare command pools, and what making and beginning a command
/// buffer takes of `device`, never the device itself.
pub(crate) fn begin_targets(&self, device: &DeviceShared) -> BeginTargets {
BeginTargets {
pools: Arc::clone(&self.command_pools),
functions: device.functions(),
loader_word: Arc::clone(&device.loader_word),
counts: Arc::clone(&device.counts),
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
churn: Arc::clone(&self.churn),
}
}
@@ -1354,7 +1492,7 @@ pub(super) fn take_command_pool(
.filter(|(_, pool)| pool.family == family && !(settled && pool.recording))
.min_by_key(|&(index, pool)| {
let held = pool.held();
(pool.begun.is_none(), held == 0, held, Reverse(index))
(pool.begun.is_empty(), held == 0, held, Reverse(index))
})?;
Some(pools.remove(fewest))
}
@@ -1374,7 +1512,7 @@ pub(super) fn take_command_pool_holding(
.filter(|(_, pool)| {
pool.family == family && !(settled && pool.recording) && !pool.made[at].is_empty()
})
.max_by_key(|&(index, pool)| (pool.made[at].len(), pool.begun.is_none(), index))?;
.max_by_key(|&(index, pool)| (pool.made[at].len(), pool.begun.is_empty(), index))?;
Some(pools.remove(most))
}
@@ -0,0 +1,155 @@
//! The device's begin-ahead thread (`begin_ahead.rs`): a command buffer that gives its pool back
//! settled posts it, and the thread begins as many of the pool's primaries as encoders of that
//! command buffer opened their own, for the encoders of the command buffer that takes the pool
//! next; the completing thread begins none itself, so a waiter's return waits for no begin.
//!
//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The function is the owned fixture
//! `validation/fixtures/public/engine/tob_renders.ll` (`llvm-as`).
use super::blit_holds::{Scratch, WAIT};
use super::draw_again::{adding_state, device, rectangles, run_into, Heard};
use crate::begin_ahead::BeginAhead;
use crate::{
Device, RenderCommandEncoder, ResourceOptions, Texture, TextureDescriptor, WorkCounts,
};
use metal2vulkan::metal::{PixelFormat, TextureUsage};
/// The render encoders of each command buffer: fewer than `spares::AHEAD`, with the readback's
/// blit encoder after them.
const ENCODERS: usize = 5;
/// The device's begin-ahead thread held at each posted pool's begins until this drops, a failing
/// case's unwinding too, so that the device's teardown, which joins the thread, never waits for
/// a hold left behind.
pub(super) struct HeldBegins<'a>(&'a BeginAhead);
impl HeldBegins<'_> {
pub(super) fn new(device: &Device) -> HeldBegins<'_> {
let begin_ahead = &device.shared().begin_ahead;
begin_ahead.held().hold();
HeldBegins(begin_ahead)
}
}
impl Drop for HeldBegins<'_> {
fn drop(&mut self) {
self.0.held().release();
}
}
/// A new `RGBA8Unorm` render target, 16 texels square.
fn target(device: &Device) -> Texture {
let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 16, 16, false);
descriptor.usage = TextureUsage::RENDER_TARGET;
descriptor.resource_options = ResourceOptions::private();
device.new_texture(&descriptor).unwrap()
}
/// The primaries begun ahead so far (`WorkCounts::primaries_begun_ahead`).
fn begun(device: &Device) -> u64 {
device.work_counts().primaries_begun_ahead
}
/// A command buffer of [`ENCODERS`] render encoders, each of which begins its own primary in the
/// new pool it takes, gives its pool back settled: once its wait returned and the device's
/// begin-ahead thread settled, the thread began as many of the pool's primaries ahead, and more
/// for the readback's blit encoder, `spares::AHEAD` at most. The next command buffer of
/// [`ENCODERS`] render encoders takes that pool, the device's only spare, and opens each from a
/// primary begun ahead (`WorkCounts::encoder_primaries_begun_ahead`), none missed, with the
/// pixels of the first.
#[test]
fn each_render_encoder_after_a_settled_command_buffer_opens_from_a_primary_begun_ahead() {
let scratch = Scratch::new("begin-ahead-encoders");
let heard = Heard::default();
let device = device(&scratch.0, &[], &heard);
let state = adding_state(&device);
let draw = |encoder: &mut RenderCommandEncoder| rectangles(encoder, &state, |_| {});
let target = target(&device);
let queue = device.new_command_queue().unwrap();
let taken = |counts: &WorkCounts| counts.encoder_primaries_begun_ahead;
let missed = |counts: &WorkCounts| counts.encoder_primaries_begun_ahead_missed;
let before = begun(&device);
let first = run_into(&device, &queue, (&target, ENCODERS), draw, true);
device.shared().begin_ahead.settle();
let ahead = begun(&device) - before;
let spares = device.shared().spares.command_pools_held();
println!(
"BEGIN-AHEAD {}: {ahead} primaries begun ahead after a command buffer of {ENCODERS} \
render encoders; the spares hold {spares:?}",
device.name()
);
assert_eq!(first.counted(taken), 0, "a new pool holds none begun");
assert_eq!(first.commands["begin_command_buffer"], ENCODERS as u64);
assert!(
(ENCODERS as u64..=8).contains(&ahead),
"{ahead} begun ahead for {ENCODERS} render encoders and a blit encoder"
);
assert_eq!(spares.len(), 1, "the first command buffer's pool alone");
let second = run_into(&device, &queue, (&target, ENCODERS), draw, true);
assert_eq!(
second.counted(taken),
ENCODERS as u64,
"each render encoder opened from a primary begun ahead: {}",
second.moved()
);
assert_eq!(second.counted(missed), 0, "none missed");
assert_eq!(second.commands["begin_command_buffer"], ENCODERS as u64);
assert_eq!(second.words, first.words, "the pixels");
}
/// A command buffer's waiter returns while the device's begin-ahead thread, held, has not begun
/// its pool's primaries: the completing thread only posted the pool, which the thread holds at
/// its begins. The next command buffer takes the pool before the begins, and each of its render
/// encoders, which the pool's begin ahead owed one, counts a miss
/// (`WorkCounts::encoder_primaries_begun_ahead_missed`) and begins its own. Released, the
/// thread begins the pool's primaries once that command buffer gave it back, and the one after
/// opens each render encoder from one.
#[test]
fn a_waiter_returns_before_the_begins_and_a_taker_before_them_counts_its_encoders_missed() {
let scratch = Scratch::new("begin-ahead-missed");
let heard = Heard::default();
let device = device(&scratch.0, &[], &heard);
let state = adding_state(&device);
let draw = |encoder: &mut RenderCommandEncoder| rectangles(encoder, &state, |_| {});
let target = target(&device);
let queue = device.new_command_queue().unwrap();
let taken = |counts: &WorkCounts| counts.encoder_primaries_begun_ahead;
let missed = |counts: &WorkCounts| counts.encoder_primaries_begun_ahead_missed;
let held = HeldBegins::new(&device);
let before = begun(&device);
let first = run_into(&device, &queue, (&target, ENCODERS), draw, true);
// The waiter returned; the thread holds the posted pool at its begins.
device.shared().begin_ahead.held().until_waiting(1, WAIT);
assert_eq!(
begun(&device),
before,
"the waiter returned before any begin"
);
let second = run_into(&device, &queue, (&target, ENCODERS), draw, true);
assert_eq!(
second.counted(taken),
0,
"none begun before the second took the pool"
);
assert_eq!(
second.counted(missed),
ENCODERS as u64,
"each render encoder the begin ahead owed one: {}",
second.moved()
);
assert_eq!(second.commands["begin_command_buffer"], ENCODERS as u64);
drop(held);
device.shared().begin_ahead.settle();
assert!(
begun(&device) - before >= ENCODERS as u64,
"begun once released"
);
let third = run_into(&device, &queue, (&target, ENCODERS), draw, true);
assert_eq!(third.counted(taken), ENCODERS as u64, "{}", third.moved());
assert_eq!(third.counted(missed), 0);
assert_eq!(
(second.words, third.words),
(first.words.clone(), first.words)
);
}
@@ -197,9 +197,9 @@ pub(super) fn commands_of(recorded: &crate::CommandsRecorded) -> BTreeMap<String
/// recorded and drew. Its begins (`begin_command_buffer`) are the `VkCommandBuffer`s its encoders
/// began (`WorkCounts::encoder_command_buffers_begun`), its primary among them whether its encoder
/// began it or took it begun ahead (`WorkCounts::encoder_primaries_begun_ahead`), and no other
/// thread's: the device's count of `vkBeginCommandBuffer` also takes the primaries that the threads
/// completing other command buffers begin ahead in their spare pools where no thread waited for
/// those (`spares.rs`), whenever the GPU's completions come, so a begin there may or may not fall
/// thread's: the device's count of `vkBeginCommandBuffer` also takes the primaries that the
/// device's begin-ahead thread begins in spare pools as other command buffers give them back
/// (`begin_ahead.rs`), whenever the GPU's completions come, so a begin there may or may not fall
/// while the run encodes.
pub(super) fn run(device: &Device, encode: impl Fn(&mut RenderCommandEncoder)) -> Ran {
let queue = device.new_command_queue().unwrap();
@@ -329,33 +329,27 @@ pub(super) fn checks_ended(device: &Device) {
}
/// A run's commands count its primary as begun whether its encoder began it or took it begun
/// ahead ([`run`]): a run after a command buffer that completed while no thread waited for it,
/// whose pool's primary its completing thread began ahead (`WorkCounts::primaries_begun_ahead`)
/// and the run's encoder took, counts the commands of a run whose encoder began its own.
/// ahead ([`run`]): with the device's begin-ahead thread held from the start (`begin_ahead.rs`),
/// no spare pool holds a primary begun ahead, so a run's encoder begins its own; released, the
/// thread begins primaries ahead in the pools given back (`WorkCounts::primaries_begun_ahead`),
/// and a run after a command buffer that completed while no thread waited for it, whose encoder
/// takes one, counts the commands of the run whose encoder began its own.
#[test]
fn a_run_counts_its_primary_begun_by_its_encoder_or_ahead_alike() {
let scratch = Scratch::new("draw-again-begun-ahead");
let heard = Heard::default();
let device = device(&scratch.0, &[], &heard);
let held = super::begin_ahead::HeldBegins::new(&device);
let state = adding_state(&device);
let plain = |encoder: &mut RenderCommandEncoder| rectangles(encoder, &state, |_| {});
warm(&device, plain);
let taken = |ran: &Ran| ran.counted(|counts| counts.encoder_primaries_begun_ahead);
// A run whose encoder began its own primary, as one after a command buffer a thread waited
// for at its completion does.
let own = std::cell::RefCell::new(None);
until("a run whose encoder began its own primary", || {
let ran = run(&device, plain);
let began = taken(&ran) == 0;
if began {
own.replace(Some(ran));
}
began
});
let own = own.into_inner().unwrap();
// A run that completes while no thread waits for it, then the primary its pool's completing
// thread begins ahead, and a run on the same queue: a pool serves its queue family's command
// buffers alone, and a new queue may lie in another family.
let own = run(&device, plain);
assert_eq!(taken(&own), 0, "the encoder began its own primary");
drop(held);
// A run that completes while no thread waits for it, then the primaries the begin-ahead
// thread begins ahead in its pool, and a run on the same queue: a pool serves its queue
// family's command buffers alone, and a new queue may lie in another family.
let ahead = |counts: &WorkCounts| counts.primaries_begun_ahead;
let begun = ahead(&device.work_counts());
let queue = device.new_command_queue().unwrap();
@@ -363,6 +357,7 @@ fn a_run_counts_its_primary_begun_by_its_encoder_or_ahead_alike() {
until("its pool's primary begun ahead", || {
ahead(&device.work_counts()) > begun
});
device.shared().begin_ahead.settle();
let after_ahead = run_on(&device, &queue, plain, true);
assert_eq!(
taken(&after_ahead),
@@ -375,13 +370,16 @@ fn a_run_counts_its_primary_begun_by_its_encoder_or_ahead_alike() {
/// A primary another thread begins ahead while a run encodes is no begin of the run's ([`run`]):
/// a command buffer on another queue that waits for an event the run's encoding signals completes
/// while the run encodes, with no thread waiting for it, so the thread that completes it begins
/// its pool's primary ahead then (`spares.rs`); the run counts the begins of a run alone.
/// while the run encodes, so the device's begin-ahead thread begins its pool's primary ahead then
/// (`begin_ahead.rs`); the run counts the begins of a run alone. The thread is held until that
/// command buffer was committed, so no spare it could take held a primary begun ahead, and its
/// pool, given back, is due one.
#[test]
fn a_primary_begun_ahead_while_a_run_encodes_is_no_begin_of_the_run_s() {
let scratch = Scratch::new("draw-again-begun-meanwhile");
let heard = Heard::default();
let device = device(&scratch.0, &[], &heard);
let begins = super::begin_ahead::HeldBegins::new(&device);
let state = adding_state(&device);
let plain = |encoder: &mut RenderCommandEncoder| rectangles(encoder, &state, |_| {});
warm(&device, plain);
@@ -399,6 +397,7 @@ fn a_primary_begun_ahead_while_a_run_encodes_is_no_begin_of_the_run_s() {
blit.fill_buffer(&filled, 0..4096, 1).unwrap();
blit.end_encoding().unwrap();
held.commit().unwrap();
drop(begins);
let ahead = |counts: &WorkCounts| counts.primaries_begun_ahead;
let meanwhile = run(&device, |encoder| {
let begun = ahead(&device.work_counts());
@@ -480,7 +479,7 @@ pub(super) fn rectangle(encoder: &mut RenderCommandEncoder) {
}
/// [`DRAWS`] draws of the rectangle, with `between` called before each but the first.
fn rectangles(
pub(super) fn rectangles(
encoder: &mut RenderCommandEncoder,
state: &RenderPipelineState,
between: impl Fn(&mut RenderCommandEncoder),
+2 -45
View File
@@ -119,11 +119,8 @@ fn a_waiter_returns_after_the_last_hold_is_gone() {
})
};
// The waiter blocks before the finish, so the finish's notify, were one made, would reach it.
let deadline = Instant::now() + Duration::from_secs(10);
while !gate.awaited() {
assert!(Instant::now() < deadline, "no waiter blocked");
std::thread::yield_now();
}
std::thread::sleep(Duration::from_millis(20));
assert!(!waiter.is_finished());
assert!(!gate.finish(), "a finish behind a hold notified the waiter");
assert_eq!(
gate.wait_until(Instant::now() + Duration::from_millis(50)),
@@ -164,43 +161,3 @@ fn a_wait_once_the_process_is_exiting_is_refused_for_that_cause() {
assert!(gate.finish());
assert_eq!(gate.wait_unless(|| true), Ok(Waited::default()));
}
/// A gate is awaited only while a thread is blocked in `wait` or `wait_until`, whichever way the
/// wait ends: what the finishing thread does before its hold goes delays only such a thread.
#[test]
fn a_gate_is_awaited_while_a_thread_is_blocked_on_it() {
let gate = Arc::new(Gate::default());
let value = Arc::new(7_u32);
assert!(!gate.awaited());
assert_eq!(gate.wait_until(Instant::now()), Err(TimedOut));
assert!(!gate.awaited(), "a wait that timed out is not counted");
let held = Hold::new(&value, &gate);
let waiters: Vec<_> = (0..2)
.map(|n| {
let gate = Arc::clone(&gate);
std::thread::spawn(move || match n {
0 => gate.wait().is_ok(),
_ => gate
.wait_until(Instant::now() + Duration::from_secs(60))
.is_ok(),
})
})
.collect();
let deadline = Instant::now() + Duration::from_secs(10);
while !gate.awaited() {
assert!(Instant::now() < deadline, "no waiter blocked");
std::thread::yield_now();
}
assert!(!gate.finish());
assert!(
gate.awaited(),
"the gate is not open while the hold is alive"
);
drop(held);
for waiter in waiters {
assert!(waiter.join().unwrap());
}
assert!(!gate.awaited());
assert_eq!(gate.wait(), Ok(Waited::default()));
assert!(!gate.awaited(), "a wait of an open gate is not counted");
}
@@ -383,9 +383,9 @@ fn moved((before, after): &(WorkCounts, WorkCounts)) -> (Copies, Keeps) {
/// The commands a frame recorded, by kind (`WorkCounts::commands_recorded`), its begins the
/// `VkCommandBuffer`s it began (`WorkCounts::command_buffers_begun`, which counts a primary begun
/// ahead in a spare command pool as the encoder that takes it records into it). Not the device's
/// count of `vkBeginCommandBuffer`, which takes such a primary as it is begun: the thread that
/// completed a command buffer no thread waited for begins it once the completed handlers ran
/// (`spares.rs`), whenever that completion comes. So one begun ahead for the frame before, or
/// count of `vkBeginCommandBuffer`, which takes such a primary as it is begun: the device's
/// begin-ahead thread begins it once a command buffer gave its pool back (`begin_ahead.rs`),
/// whenever that completion comes. So one begun ahead for the frame before, or
/// after the targets' clears, may land in either frame's window, and the frame's encoder may take
/// one begun before its window opened.
fn recorded(counts: &(WorkCounts, WorkCounts)) -> BTreeMap<String, u64> {
@@ -36,6 +36,8 @@ mod attributes;
mod batches;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod bc_own_image;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod begin_ahead;
mod binary;
mod binary_archive;
mod binding_view;
@@ -1,9 +1,9 @@
//! The pending audit on a device (`pending_audit.rs`): a command pool given back to the device's
//! spares while a command buffer of it waits on the GPU is found, once for each command buffer of
//! the pool the waiting batch carries, each said in a line; the command buffer that then takes that
//! pool (its taking resets it), the primary its completing thread begins ahead in the pool, and the
//! command buffer that takes that primary are each checked, and none is found pending. The command
//! buffer is held on the GPU by its wait for a plain event's signal reserved for the caller
//! pool (its taking resets it), the primaries the device's begin-ahead thread begins ahead in the
//! pool, and the command buffer that takes one are each checked, and none is found pending. The
//! command buffer is held on the GPU by its wait for a plain event's signal reserved for the caller
//! (`Event::reserve_vk_signal`), which the test makes from the host once the give-back was found:
//! the contract's signal where the caller's submission is not made.
//!
@@ -115,9 +115,9 @@ fn a_pool_given_back_while_its_command_buffer_waits_on_the_gpu_is_found() {
held.wait_until_completed_for(WAIT).unwrap();
assert_eq!(held.status(), CommandBufferStatus::Completed);
// The pool given back, taken (and reset) by the next command buffer, which completes while
// no thread waits for it, so its completing thread begins a primary of the pool ahead; then a
// command buffer that takes that primary. Nothing is found pending.
// The pool given back, taken (and reset) by the next command buffer, which completes and
// posts it to the device's begin-ahead thread, which begins primaries of the pool ahead; then
// a command buffer that takes one. Nothing is found pending.
let checked = counts(&device);
let work = device.work_counts();
let next = filling(&queue, &target, None);
@@ -128,6 +128,7 @@ fn a_pool_given_back_while_its_command_buffer_waits_on_the_gpu_is_found() {
until("its pool's primary begun ahead", || {
device.work_counts().primaries_begun_ahead > work.primaries_begun_ahead
});
device.shared().begin_ahead.settle();
let last = filling(&queue, &target, None);
last.wait_until_completed_for(WAIT).unwrap();
let done = device.work_counts();
+141 -62
View File
@@ -6,8 +6,8 @@ use crate::descriptor_arena::{Room, SetNeeds};
use crate::spares::{
keep_command_pool, keep_descriptor_pool, keep_idle_command_pool, past_held, take_command_pool,
take_command_pool_holding, take_descriptor_pool, take_idle, take_to_trim, CommandPool,
CommandPools, DescriptorPool, DESCRIPTORS, DESCRIPTOR_POOLS, HELD, IDLE_FOR, RECENT_FOR,
RECENT_USES, TRIMMED_AT_ONCE,
CommandPools, DescriptorPool, Opened, AHEAD, DESCRIPTORS, DESCRIPTOR_POOLS, HELD, IDLE_FOR,
RECENT_FOR, RECENT_USES, TRIMMED_AT_ONCE,
};
use ash::vk::{self, Handle};
use std::collections::VecDeque;
@@ -79,39 +79,89 @@ fn a_pool_without_a_secondary_is_stocked_with_one_for_its_next_taker() {
assert!(!made.wants_secondary(), "one made already");
}
/// A spare command pool's primary begun ahead goes to the first encoder of the command buffer
/// that takes the pool, handed out among the pool's command buffers (so the pool settles only
/// once it ended too), never to `reuse`, which hands out the others; a pool its taker resets (one
/// given back recording) holds it as an ordinary primary again.
/// A spare command pool's primaries begun ahead go to the encoders of the command buffer that
/// takes the pool that open their own, one each, handed out among the pool's command buffers (so
/// the pool settles only once they ended too), never to `reuse`, which hands out the others; past
/// them an encoder begins its own; a pool its taker resets (one given back recording) holds them
/// as ordinary primaries again.
#[test]
fn a_primary_begun_ahead_goes_to_the_first_encoder_alone() {
fn primaries_begun_ahead_go_to_the_encoders_that_open_their_own() {
let primary = vk::CommandBufferLevel::PRIMARY;
let raw = vk::CommandBuffer::from_raw;
let mut pool = CommandPool::new(vk::CommandPool::from_raw(1), 0);
pool.made(primary, vk::CommandBuffer::from_raw(10));
pool.begun = Some(vk::CommandBuffer::from_raw(11));
pool.made(primary, raw(10));
pool.begun = vec![raw(11), raw(12)];
pool.taken();
assert_eq!(pool.reuse(primary), Some(vk::CommandBuffer::from_raw(10)));
assert_eq!(pool.reuse(primary), None, "the begun one is not reused");
assert_eq!(pool.take_begun(), Some(vk::CommandBuffer::from_raw(11)));
assert_eq!(pool.take_begun(), None, "taken once");
assert_eq!(pool.handed_out(), 2, "the begun one counts as handed out");
assert_eq!(pool.reuse(primary), Some(raw(10)));
assert_eq!(pool.reuse(primary), None, "the begun ones are not reused");
assert_eq!(pool.open_encoder(), Opened::Begun(raw(12)));
assert_eq!(pool.open_encoder(), Opened::Begun(raw(11)));
assert_eq!(pool.open_encoder(), Opened::Own, "past them, and owed none");
assert_eq!(pool.handed_out(), 3, "the begun ones count as handed out");
pool.taken();
assert_eq!(pool.reuse(primary), Some(vk::CommandBuffer::from_raw(10)));
let reused: Vec<_> = (0..3).filter_map(|_| pool.reuse(primary)).collect();
assert_eq!(
pool.reuse(primary),
Some(vk::CommandBuffer::from_raw(11)),
"taken, it is an ordinary primary of the pool"
reused,
[raw(10), raw(12), raw(11)],
"taken, they are ordinary primaries of the pool"
);
let mut reset = CommandPool::new(vk::CommandPool::from_raw(2), 0);
reset.begun = Some(vk::CommandBuffer::from_raw(20));
reset.begun = vec![raw(20)];
reset.recording = true;
reset.taken();
assert_eq!(
reset.take_begun(),
None,
reset.open_encoder(),
Opened::Own,
"the reset left it in the initial state"
);
assert_eq!(reset.reuse(primary), Some(vk::CommandBuffer::from_raw(20)));
assert_eq!(reset.reuse(primary), Some(raw(20)));
}
/// A pool given back settled and posted to the begin-ahead thread is due as many begins as
/// encoders of the command buffer that gave it back opened their own in it, [`AHEAD`] at most:
/// taken before the thread made them all, each of that many encoders that finds none begun counts
/// a miss, and those past them begin their own uncounted; a pool not due counts none.
#[test]
fn encoders_a_pool_s_begin_ahead_owed_and_found_none_begun_are_missed() {
let raw = vk::CommandBuffer::from_raw;
let mut pool = CommandPool::new(vk::CommandPool::from_raw(1), 0);
pool.taken();
for _ in 0..3 {
assert_eq!(pool.open_encoder(), Opened::Own, "a new pool is owed none");
}
assert!(pool.given_back(Instant::now()).is_empty());
pool.begin_ahead_due();
// The thread began one of the three before a command buffer took the pool.
pool.begun = vec![raw(30)];
pool.taken();
let opened: Vec<_> = (0..4).map(|_| pool.open_encoder()).collect();
assert_eq!(
opened,
[
Opened::Begun(raw(30)),
Opened::Missed,
Opened::Missed,
Opened::Own
]
);
assert!(!pool.due, "taken, it is due no more");
// Of a use that opened more than [`AHEAD`] encoders' own, the begin ahead owes that many.
assert!(pool.given_back(Instant::now()).is_empty());
pool.taken();
for _ in 0..AHEAD + 4 {
pool.open_encoder();
}
assert!(pool.given_back(Instant::now()).is_empty());
pool.begin_ahead_due();
pool.taken();
let missed = (0..AHEAD + 4)
.filter(|_| pool.open_encoder() == Opened::Missed)
.count();
assert_eq!(missed, AHEAD);
// Not posted, none is owed.
assert!(pool.given_back(Instant::now()).is_empty());
pool.taken();
assert_eq!(pool.open_encoder(), Opened::Own);
}
/// A command buffer takes a spare command pool of its queue's family that holds a primary begun
@@ -122,7 +172,7 @@ fn a_spare_command_pool_holding_a_begun_primary_is_taken_first() {
for (raw, begun) in [(1, false), (2, true), (3, false)] {
let mut pool = CommandPool::new(vk::CommandPool::from_raw(raw), 0);
if begun {
pool.begun = Some(vk::CommandBuffer::from_raw(raw * 10));
pool.begun = vec![vk::CommandBuffer::from_raw(raw * 10)];
}
keep_command_pool(&mut pools, pool);
}
@@ -149,8 +199,8 @@ fn a_taker_takes_the_fewest_and_one_past_its_first_pool_the_most() {
holding(4, 40, 0),
holding(5, 9, 1),
];
pools[0].begun = Some(vk::CommandBuffer::from_raw(10));
pools[1].begun = Some(vk::CommandBuffer::from_raw(20));
pools[0].begun = vec![vk::CommandBuffer::from_raw(10)];
pools[1].begun = vec![vk::CommandBuffer::from_raw(20)];
let raws = |pools: &[CommandPool]| pools.iter().map(|p| p.raw.as_raw()).collect::<Vec<_>>();
let taken = |pool: Option<CommandPool>| pool.map(|pool| pool.raw.as_raw());
assert_eq!(
@@ -177,8 +227,8 @@ fn a_taker_takes_the_fewest_and_one_past_its_first_pool_the_most() {
holding(4, 0, 0),
holding(5, 9, 1),
];
pools[0].begun = Some(vk::CommandBuffer::from_raw(10));
pools[1].begun = Some(vk::CommandBuffer::from_raw(20));
pools[0].begun = vec![vk::CommandBuffer::from_raw(10)];
pools[1].begun = vec![vk::CommandBuffer::from_raw(20)];
// Those holding a primary begun ahead, then the fewest of those holding any, then the empty.
for expected in [1, 2, 3, 5, 4] {
assert_eq!(
@@ -392,9 +442,10 @@ fn spare_descriptor_pools_are_bounded_and_taken_by_room() {
assert_eq!(pools.len(), 3);
}
/// A spare command pool a completing thread begins a primary ahead in is out of the spares while
/// it begins, so a taker meanwhile takes another, and never waits for the begin; a pool that may
/// not begin one (recording, or holding one begun) stays; kept again, it is the newest.
/// A spare command pool the begin-ahead thread begins a primary ahead in is out of the spares
/// while it begins, so a taker meanwhile takes another, and never waits for the begin; a pool that
/// may not begin one (recording, or holding as many begun as its begin ahead begins) stays, due no
/// more; kept again, it is the newest.
#[test]
fn a_spare_command_pool_begins_ahead_out_of_the_spares() {
let pool = |n: u64| CommandPool::new(vk::CommandPool::from_raw(n), 0);
@@ -418,8 +469,13 @@ fn a_spare_command_pool_begins_ahead_out_of_the_spares() {
keep_command_pool(&mut pools.spares, taken);
let raws: Vec<_> = pools.spares.iter().map(|pool| pool.raw.as_raw()).collect();
assert_eq!(raws, [1, 2], "kept again, the newest");
pools.spares[1].begun = Some(vk::CommandBuffer::from_raw(20));
pools.spares[1].begun = vec![vk::CommandBuffer::from_raw(20)];
pools.spares[1].due = true;
assert!(pools.take_to_begin(vk::CommandPool::from_raw(2)).is_none());
assert!(
!pools.spares[1].due,
"a pool that may begin no more is due no more"
);
pools.spares[0].recording = true;
assert!(pools.take_to_begin(vk::CommandPool::from_raw(1)).is_none());
assert!(pools.take_to_begin(vk::CommandPool::from_raw(3)).is_none());
@@ -590,7 +646,7 @@ fn a_spare_left_idle_sheds_its_command_buffers_and_goes_back_the_oldest() {
pool
};
let mut pools = vec![pool(1, start), pool(2, start + IDLE_FOR / 2)];
pools[0].begun = Some(vk::CommandBuffer::from_raw(19));
pools[0].begun = vec![vk::CommandBuffer::from_raw(19)];
let mut empty = CommandPool::new(vk::CommandPool::from_raw(3), 0);
assert!(empty.given_back(start).is_empty());
keep_command_pool(&mut pools, empty);
@@ -673,7 +729,7 @@ fn the_spares_and_a_pool_given_back_hold_at_most_held_command_buffers() {
// A pool given back of more than the bound alone.
let over = HELD as u64 + 10;
let mut given = holding(6, 4, over);
given.begun = Some(vk::CommandBuffer::from_raw(99));
given.begun = vec![vk::CommandBuffer::from_raw(99)];
let (oldest, past) = past_held(&mut pools, 0, &mut given);
assert_eq!(raws(&oldest), [3, 4], "every spare that holds any");
assert_eq!(given.held(), HELD, "the pool given back keeps the bound");
@@ -684,10 +740,10 @@ fn the_spares_and_a_pool_given_back_hold_at_most_held_command_buffers() {
Some(&vk::CommandBuffer::from_raw(last - past.len() as u64 + 1)),
"its last made secondaries"
);
assert_eq!(given.begun, Some(vk::CommandBuffer::from_raw(99)));
assert_eq!(given.begun, [vk::CommandBuffer::from_raw(99)]);
// Past the bound in primaries and the begun one, a secondary is kept.
let mut given = holding(7, HELD as u64 + 5, 3);
given.begun = Some(vk::CommandBuffer::from_raw(98));
given.begun = vec![vk::CommandBuffer::from_raw(98)];
let (_, past) = past_held(&mut Vec::new(), 0, &mut given);
assert_eq!(
past.len(),
@@ -703,12 +759,12 @@ fn the_spares_and_a_pool_given_back_hold_at_most_held_command_buffers() {
assert_eq!((past.len(), given.held()), (200, 100));
// Room for one: the primaries go, then the secondary, the begun primary kept.
let mut given = holding(9, 2, 1);
given.begun = Some(vk::CommandBuffer::from_raw(97));
given.begun = vec![vk::CommandBuffer::from_raw(97)];
let (_, past) = past_held(&mut Vec::new(), HELD - 1, &mut given);
let last = (9 << 32) + (1 << 20) + 1;
assert_eq!(past.len(), 3, "the primaries, then the secondary");
assert_eq!(past.last(), Some(&vk::CommandBuffer::from_raw(last)));
assert_eq!(given.begun, Some(vk::CommandBuffer::from_raw(97)));
assert_eq!(given.begun, [vk::CommandBuffer::from_raw(97)]);
// The pools out of the spares count the bound: the pool given back keeps none, the begun
// primary neither.
let (_, past) = past_held(&mut Vec::new(), HELD, &mut given);
@@ -725,10 +781,11 @@ fn the_spares_and_a_pool_given_back_hold_at_most_held_command_buffers() {
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod device {
use super::{HELD, RECENT_FOR, RECENT_USES};
use super::{AHEAD, HELD, RECENT_FOR, RECENT_USES};
use crate::command_buffer::kept_barriers::KEPT;
use crate::free_thread::FreeThread;
use crate::spares::{FREED_AT_ONCE, POOL_HOLDS, RECORDED};
use crate::tests::begin_ahead::HeldBegins;
use crate::tests::encoder_holds::library;
use crate::tests::freed_memory::device;
use crate::{
@@ -770,8 +827,8 @@ mod device {
const FREE_THREAD: &str = "metal2vulkan-frees";
/// Commit a command buffer of `queue` of `device` of `encoders` blit encoders, each filling
/// `target`, and wait for it, then for the frees its pool's give-back posted to the device's
/// free thread, so that the next command buffer takes the pool again.
/// `target`, and wait for it, then for the begins ahead and the frees its pool's give-back
/// posted ([`settled`]), so that the next command buffer takes the pool again.
fn fills(
device: &Device,
queue: &CommandQueue,
@@ -785,10 +842,18 @@ mod device {
/// command buffer's status once it completed or failed.
fn fills_of(device: &Device, queue: &CommandQueue, targets: &[&Buffer]) -> CommandBufferStatus {
let status = committed(queue, targets);
device.shared().frees.drain();
settled(device);
status
}
/// Wait for the begins ahead that pools given back posted to `device`'s begin-ahead thread
/// (`begin_ahead.rs`), then for the frees they posted to its free thread: what the spares
/// hold is final then for the command buffers whose waits returned.
fn settled(device: &Device) {
device.shared().begin_ahead.settle();
device.shared().frees.drain();
}
/// A command buffer of `queue` of one blit encoder for each of `targets`, filling its first
/// 256 bytes, committed and waited for, not the frees its pool's give-back posted; its status
/// once it completed or failed.
@@ -844,8 +909,9 @@ mod device {
/// pool's recent uses and the spans of its uses no longer reaching them, freed on the
/// device's free thread, never on the thread that saw a command buffer complete. Each count
/// is read once [`fills`] returned, which is final: a command buffer's wait returns once its
/// completion's transition ran, its pool's give-back and begin ahead among it
/// (`command_buffer/gate.rs`), and the drain once the frees that give-back posted ran.
/// completion's transition ran, its pool's give-back and its post to the begin-ahead thread
/// among it (`command_buffer/gate.rs`), and [`settled`] once the begins and the frees that
/// give-back posted ran.
#[test]
fn command_buffers_the_spares_hold_fall_back_after_a_burst_freed_on_the_free_thread() {
let scratch = std::env::temp_dir().join(format!("m2v-spares-{}", std::process::id()));
@@ -970,7 +1036,9 @@ mod device {
/// none while the spares hold them (`spares.rs`). [`KINDS_EACH`] small command buffers and as
/// many large ones are encoded, each holding its pools, then committed and waited for: the
/// spares then hold the large ones' command buffers, in pools of at most [`POOL_HOLDS`] of a
/// level beside a primary begun ahead and a secondary. Where a taker took the newest spare,
/// level beside up to [`AHEAD`] primaries begun ahead and a secondary: a pool that holds some
/// begun ahead and serves a command buffer past its first holds them still, besides those it
/// grows to. Where a taker took the newest spare,
/// the next small command buffer took a large one's pool, so pools out with small command
/// buffers held the large ones' command buffers, past [`HELD`] together under a load of many
/// in flight; where a large one made what it lacked in its first pool until it had handed out
@@ -1000,7 +1068,7 @@ mod device {
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
drop(command_buffers);
shared.frees.drain();
settled(&device);
};
// Each holds its pools while the next is encoded, so each takes pools of its own.
let mut first = Vec::new();
@@ -1008,13 +1076,14 @@ mod device {
first.extend((0..KINDS_EACH).map(|_| encoded(encoders)));
}
run(first);
// A taker takes a spare holding a primary begun ahead first, and a settled pool given
// back begins one only where no thread waited on its command buffer's gate as it
// completed, which `run`'s waits may or may not have: each spare begins one now, so they
// differ only in what they hold. Left to that timing, a small command buffer took a
// large one's pool, the only spare holding one, under load (msi, one run).
// A taker takes a spare holding a primary begun ahead first, and only the first pool of
// each command buffer is posted to the begin-ahead thread: each spare begins its
// primaries ahead now, so they differ only in what they hold. Left to which pools held
// one, a small command buffer took a large one's pool, the only spare holding one, under
// load (msi, one run).
let targets = shared.spares.begin_targets(shared);
for (raw, _) in shared.spares.command_pools_held() {
shared.spares.begin_ahead(shared, raw);
targets.begin_ahead(raw);
}
let before = shared.spares.command_pools_held();
let made = device.work_counts().command_buffers_made;
@@ -1045,9 +1114,9 @@ mod device {
);
let most = (before.iter()).map(|&(_, held)| held).max().unwrap_or(0);
assert!(
most <= POOL_HOLDS + 2,
"a spare held {most}, past {POOL_HOLDS} of a level, a primary begun ahead and a \
secondary"
most <= POOL_HOLDS + AHEAD + 1,
"a spare held {most}, past {POOL_HOLDS} of a level, {AHEAD} primaries begun ahead \
and a secondary"
);
assert!(
past_first > 0,
@@ -1091,7 +1160,7 @@ mod device {
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
drop(command_buffers);
device.shared().frees.drain();
settled(&device);
let begun = device.work_counts().command_buffers_begun - begun;
let held = device.shared().spares.command_buffers_held();
let freed_on = device.shared().spares.freed_on();
@@ -1115,8 +1184,9 @@ mod device {
/// a begin ahead in it then makes no primary: the spares hold [`HELD`] once both came back,
/// and still after the begin. The free thread is held at each free (the crate's hook) until
/// both pools were given back: the order a loaded suite met by chance in
/// [`command_buffers_alive_at_once_leave_the_spares_holding_at_most_held`]. A pool holding a
/// primary still begins it ahead at the bound, making none.
/// [`command_buffers_alive_at_once_leave_the_spares_holding_at_most_held`]. A pool holding
/// primaries still begins them ahead at the bound, [`AHEAD`] at most, making none. The
/// device's begin-ahead thread is held throughout, so the begins ahead are the test's alone.
#[test]
fn a_pool_given_back_while_the_bound_is_out_freeing_keeps_none_past_it() {
let scratch = std::env::temp_dir().join(format!("m2v-spares-out-{}", std::process::id()));
@@ -1125,6 +1195,7 @@ mod device {
let shared = device.shared();
let queue = device.new_command_queue().unwrap();
let target = device.new_buffer(4096, ResourceOptions::private()).unwrap();
let begins = HeldBegins::new(&device);
let hold = Hold::new(&shared.frees);
let large = committed(&queue, &vec![&target; HELD + 64]);
let trimmed = shared.spares.churn().past_held;
@@ -1136,15 +1207,17 @@ mod device {
let held: usize = pools.iter().map(|(_, held)| held).sum();
let (newest, last) = *pools.last().unwrap();
let begun = device.work_counts().primaries_begun_ahead;
shared.spares.begin_ahead(shared, newest);
let targets = shared.spares.begin_targets(shared);
let in_newest = targets.begin_ahead(newest);
let after = shared.spares.command_pools_held();
let (largest, _) = *pools.iter().max_by_key(|(_, held)| *held).unwrap();
shared.spares.begin_ahead(shared, largest);
let in_largest = targets.begin_ahead(largest);
let begun = device.work_counts().primaries_begun_ahead - begun;
println!(
"SPARES-OUT {}: the large command buffer's pool freed {trimmed} past the bound, \
{} frees ran before the small one's give-back; the spares hold {pools:?} once both \
came back, {after:?} after the begin ahead in the newest; {begun} begun ahead",
came back, {after:?} after the begin ahead in the newest; {begun} begun ahead, \
{in_newest} in the newest and {in_largest} in the largest",
device.name(),
freed.len()
);
@@ -1162,8 +1235,14 @@ mod device {
assert_eq!(last, 0, "the pool given back last holds {last}");
let after: usize = after.iter().map(|(_, held)| held).sum();
assert_eq!(after, HELD, "the spares hold {after} after its begin ahead");
assert_eq!(begun, 1, "the pool holding primaries began one ahead");
assert_eq!(in_newest, 0, "the pool holding none made none at the bound");
assert!(
(1..=AHEAD).contains(&in_largest),
"the pool holding primaries began {in_largest} ahead"
);
assert_eq!(begun, in_largest as u64, "the test's begins alone");
assert_eq!(shared.spares.command_buffers_held(), HELD);
drop(begins);
drop((target, queue, device));
let _ = std::fs::remove_dir_all(&scratch);
}
@@ -1300,7 +1379,7 @@ mod device {
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
device.shared().frees.drain();
settled(device);
command_buffer.status()
}
+19 -3
View File
@@ -295,6 +295,7 @@ pub(crate) struct Counters {
rate_map_gpu_copied_draws: AtomicU64,
rate_map_boxed_vertex_regions: AtomicU64,
encoder_primaries_begun_ahead: AtomicU64,
encoder_primaries_begun_ahead_missed: AtomicU64,
primaries_begun_ahead: AtomicU64,
barrier_buffers_kept: AtomicU64,
stamped_buffers_kept: AtomicU64,
@@ -3625,6 +3626,12 @@ impl Counters {
(self.encoder_primaries_begun_ahead).fetch_add(1, Ordering::Relaxed);
}
/// An encoder began its own `VkCommandBuffer` where its spare command pool's begin ahead owed
/// it one: the device's begin-ahead thread had not made it (`begin_ahead.rs`).
pub(crate) fn encoder_primary_begun_ahead_missed(&self) {
(self.encoder_primaries_begun_ahead_missed).fetch_add(1, Ordering::Relaxed);
}
/// A spare command pool's primary was begun ahead, and the pool kept among the spares again
/// (`spares.rs`).
pub(crate) fn primary_begun_ahead(&self) {
@@ -7838,10 +7845,17 @@ pub struct WorkCounts {
/// Of `command_buffers_begun`, the device's own submissions' and staging submissions'.
pub command_buffers_begun_internal: u64,
/// Of `encoder_command_buffers_begun`, the encoders' own `VkCommandBuffer`s begun ahead: a
/// settled spare command pool's primary, begun by the thread that completed the command
/// buffer that gave it back where no thread waited for that one, which the first encoder of
/// the command buffer that takes the pool records into, begun no more on its thread.
/// settled spare command pool's primaries, begun on the device's begin-ahead thread once the
/// command buffer that gave it back completed, as many as encoders of that command buffer
/// opened their own in it (eight at most), which the encoders of the command buffer that
/// takes the pool record into, begun no more on its thread.
pub encoder_primaries_begun_ahead: u64,
/// Of `encoder_command_buffers_begun`, the encoders' own `VkCommandBuffer`s their spare
/// command pool's begin ahead owed them and had not begun (`encoder_primaries_begun_ahead`):
/// the command buffer took the pool before the device's begin-ahead thread made its begins,
/// or the pool was out of the spares as the thread came to it. Each was begun on the
/// encoding thread, as one in a pool owed none.
pub encoder_primaries_begun_ahead_missed: u64,
/// The spare command pools' primaries begun ahead (`encoder_primaries_begun_ahead`), taken
/// by an encoder or not yet: not among `command_buffers_begun` until one is taken. Each is
/// counted once its pool is among the spares again, so a command buffer made after the count
@@ -12344,6 +12358,8 @@ impl Device {
.load(Ordering::Relaxed),
encoder_primaries_begun_ahead: (counters.encoder_primaries_begun_ahead)
.load(Ordering::Relaxed),
encoder_primaries_begun_ahead_missed: (counters.encoder_primaries_begun_ahead_missed)
.load(Ordering::Relaxed),
primaries_begun_ahead: counters.primaries_begun_ahead.load(Ordering::Relaxed),
barrier_buffers_kept: counters.barrier_buffers_kept.load(Ordering::Relaxed),
stamped_buffers_kept: counters.stamped_buffers_kept.load(Ordering::Relaxed),
@@ -142,8 +142,8 @@ fn empty_command_buffers_take_the_spare_command_pool() {
}
/// A command buffer's first encoder takes the primary its spare command pool holds begun ahead
/// (`spares.rs`): the command buffer before, which gave the pool back, began it as it completed,
/// where no thread waited for it (`WorkCounts::primaries_begun_ahead`), and the encoder begins
/// (`spares.rs`): the device's begin-ahead thread began it once the command buffer before, which
/// gave the pool back, completed (`WorkCounts::primaries_begun_ahead`), and the encoder begins
/// none of its own (`WorkCounts::encoder_primaries_begun_ahead`). The fills still read correctly.
#[test]
fn a_first_encoder_takes_the_primary_its_spare_pool_began_ahead() {
@@ -155,10 +155,9 @@ fn a_first_encoder_takes_the_primary_its_spare_pool_began_ahead() {
let before = device.work_counts();
let first = fill(&queue, &buffer);
first.commit().unwrap();
// Begun on the completing thread, which a wait for the command buffer would skip:
// read from the counts instead, which count it once its pool is among the spares
// again (the begin runs with the pool out of them), so the next command buffer
// takes that pool.
// Begun on the device's begin-ahead thread after the command buffer completed: read
// from the counts, which count it once its pool is among the spares again (the
// begin runs with the pool out of them), so the next command buffer takes that pool.
let deadline = std::time::Instant::now() + WAIT;
while device.work_counts().primaries_begun_ahead == before.primaries_begun_ahead {
assert!(
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2454;
pub const RUNTIME_VERSION: u32 = 2455;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -3056,6 +3056,7 @@ field metal2vulkan-runtime::WorkCounts.driver_diagnostics_withheld pub driver_di
field metal2vulkan-runtime::WorkCounts.empty_memory_blocks_live pub empty_memory_blocks_live: u64
field metal2vulkan-runtime::WorkCounts.encoder_command_buffers_begun pub encoder_command_buffers_begun: u64
field metal2vulkan-runtime::WorkCounts.encoder_primaries_begun_ahead pub encoder_primaries_begun_ahead: u64
field metal2vulkan-runtime::WorkCounts.encoder_primaries_begun_ahead_missed pub encoder_primaries_begun_ahead_missed: u64
field metal2vulkan-runtime::WorkCounts.encoders_barriered_at_open pub encoders_barriered_at_open: u64
field metal2vulkan-runtime::WorkCounts.encoders_folded pub encoders_folded: u64
field metal2vulkan-runtime::WorkCounts.encoders_last_draw_empty pub encoders_last_draw_empty: u64
Can't render this file because it is too large.