Begin two command buffers per render pass instead of four

Keep a batch's barrier command buffers and submit them again rather than beginning new ones, cut a
pass end's allocations and work where nothing needs them, count the command buffers the runtime
begins, and count a frame's instructions per step in frames of their own, outside the timed ones.

Gain: two command buffers begun per pass instead of four (ANV memsets each one twice), and a pass
end's allocations from 52 to 36.

Verified on the original branch: the runtime lanes on RADV, ANV and lavapipe. This squashed commit
was not re-tested on its own.
This commit is contained in:
Anees Iqbal committed 2026-10-14 12:15:32 +03:00
1 parent 2ccf403815
commit 4600bc606d
16 files changed
+720 -68

No files matched your search

@@ -939,7 +939,7 @@ impl BlitCommandEncoder {
written: Vec<(vk::ImageAspectFlags, Written)>,
) -> Result<(), Error> {
FreshUnwritten::wrote(self.core().device(), texture, &written)?;
let written = written.into_iter().map(|(_, texels)| texels).collect();
let written = || written.into_iter().map(|(_, texels)| texels).collect();
match Scrub::of(texture, written) {
Some(scrub) => self.core().defer(Deferred::SparseScrub(Arc::new(scrub))),
None => Ok(()),
+73 -2
View File
@@ -335,7 +335,24 @@ impl DrawnArea {
/// not bounded, or the pass's sample count has no measured tile size.
pub(super) fn tiles(&self, layout: &PassLayout) -> Option<DrawnTiles> {
let tile = layout.tile.tile.filter(|_| !self.whole)?;
let [per_row, rows] = [0, 1].map(|axis| layout.extent[axis].div_ceil(tile[axis]));
self.tiles_of(tile, layout.extent)
}
/// The tiles of `tile` pixels a side of a render area of `extent` the rectangles reach:
/// `None` where that is every one ([`tiles`](Self::tiles)).
fn tiles_of(&self, tile: [u32; 2], extent: [u32; 2]) -> Option<DrawnTiles> {
let [per_row, rows] = [0, 1].map(|axis| extent[axis].div_ceil(tile[axis]));
// A rectangle that reaches every tile on its own (a draw over the whole render area, as
// most are): every tile, with no grid made.
let every = |&[x0, y0, x1, y1]: &[u32; 4]| {
x0 < tile[0]
&& y0 < tile[1]
&& x1.div_ceil(tile[0]) >= per_row
&& y1.div_ceil(tile[1]) >= rows
};
if per_row == 0 || rows == 0 || self.rects.iter().any(every) {
return None;
}
let mut tiles = DrawnTiles {
tile,
per_row,
@@ -677,7 +694,8 @@ fn rect([width, height]: [u32; 2]) -> vk::Rect2D {
#[cfg(test)]
mod tests {
use super::dont_care_clear;
use super::{dont_care_clear, DrawnArea};
use ash::vk;
use metal2vulkan::metal::format::{ClearRoute, ExtendedRange};
use metal2vulkan::metal::PixelFormat;
@@ -720,4 +738,57 @@ mod tests {
assert_eq!(form.clear_texel([0.0; 4], rule), [0; 4], "{rule:?}");
}
}
/// The tiles a pass's rectangles reach are the tiles each overlaps, whether one of them
/// reaches every tile (no grid made) or none does: checked tile by tile.
#[test]
fn drawn_tiles_are_the_tiles_the_rectangles_overlap() {
let rect = |x: i32, y: i32, w: u32, h: u32| vk::Rect2D {
offset: vk::Offset2D { x, y },
extent: vk::Extent2D {
width: w,
height: h,
},
};
let tile = [32u32, 16];
let extent = [100u32, 70];
let cases = [
vec![rect(0, 0, 100, 70)],
vec![rect(31, 15, 69, 55)],
vec![rect(32, 0, 68, 70)],
vec![rect(0, 16, 100, 54)],
vec![rect(0, 0, 96, 64)],
vec![rect(0, 0, 97, 65)],
vec![rect(5, 5, 10, 10), rect(0, 0, 100, 70)],
vec![rect(0, 0, 50, 70), rect(50, 0, 50, 70)],
vec![rect(40, 20, 10, 10)],
vec![],
];
for (case, rects) in cases.iter().enumerate() {
let mut area = DrawnArea::default();
area.add(rects);
let [per_row, rows] = [0, 1].map(|axis| extent[axis].div_ceil(tile[axis]));
let reached = |tx: u32, ty: u32| {
area.rects.iter().any(|&[x0, y0, x1, y1]| {
x0 < (tx + 1) * tile[0]
&& tx * tile[0] < x1
&& y0 < (ty + 1) * tile[1]
&& ty * tile[1] < y1
})
};
let every = (0..rows).all(|ty| (0..per_row).all(|tx| reached(tx, ty)));
match area.tiles_of(tile, extent) {
None => assert!(every, "case {case}"),
Some(tiles) => {
assert!(!every, "case {case}");
for ty in 0..rows {
for tx in 0..per_row {
let reach = reached(tx, ty);
assert_eq!(tiles.contains(tx, ty), reach, "case {case}: {tx}, {ty}");
}
}
}
}
}
}
}
@@ -0,0 +1,164 @@
//! A batch's barrier command buffers, recorded once and submitted again.
//!
//! Every batch with encoders submits a command buffer of barriers alone before its first encoder
//! (`Barrier::after_completed`, with the barrier the tracker planned for that encoder) and one
//! after its last (`Barrier::to_host`), and one before each later encoder the tracker planned a
//! barrier for (`submit.rs`): batch after batch, the same few lists of barriers. 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`), for each of a
//! window server frame's 67 or more batches.
//!
//! - **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
//! submission's command buffers into one batch buffer only where none has that flag
//! (`anv_cmd_buffer_is_chainable`), and submits the rest one execbuffer each. The batch that
//! takes one marks it with its own timeline value before it is submitted: a batch whose
//! submission fails leaves that value to the queue's next batch, so the command buffer waits
//! for that one instead.
//! - **Where.** On every `VkQueue` but one whose command buffers end at a fence
//! (`fences::ends_at_fence`): MoltenVK reads a command buffer after its timeline signal and
//! refuses one submitted again before its completed handler ran. A barrier command buffer that
//! writes timestamps or moves the caller's images is recorded by its batch, as before.
//! - **Bounded.** At most [`LISTS`] lists of barriers per `VkQueue`, each with at most [`KEPT`]
//! command buffers, as many as its batches in flight at once needed: past them a batch records
//! its own into its command buffer's pool. They live in a command pool of the queue's family,
//! made at the first, and go with the device once its queues are idle.
//! - **Inside the scheduler's section**: every call is in the exit guard's table.
use crate::error::{vulkan, Error};
use crate::exit_guard::{self, Call};
use crate::release;
use crate::tracker::Barrier;
use crate::Device;
use ash::vk;
use std::collections::VecDeque;
/// The most lists of barriers a `VkQueue` keeps command buffers of.
pub(crate) const LISTS: usize = 8;
/// The most command buffers a `VkQueue` keeps of one list of barriers.
pub(crate) const KEPT: usize = 128;
/// The scheduler's kept barrier command buffers, by `VkQueue` (`scheduler::State::kept`).
#[derive(Default)]
pub(crate) struct KeptBarriers {
queues: Vec<QueueKept>,
}
/// One `VkQueue`'s.
#[derive(Default)]
struct QueueKept {
/// The pool they are made from; null until the first.
pool: vk::CommandPool,
lists: Vec<KeptList>,
}
/// The command buffers of one list of barriers, in the order of the batches that last took them.
struct KeptList {
barriers: Vec<Barrier>,
buffers: VecDeque<Kept>,
}
/// A kept command buffer, and the timeline value of the batch that last took it.
struct Kept {
raw: vk::CommandBuffer,
after: u64,
}
impl KeptBarriers {
/// A command buffer of `device`'s `VkQueue` `queue` holding only `barriers` (each recorded
/// as [`Barrier::record`] records it), for the batch that signals `at` on that queue's
/// timeline: a kept one whose last batch completed, else one recorded now and kept. `None`
/// past the bounds (the module docs), where the batch records its own.
pub(crate) fn take(
&mut self,
device: &Device,
queue: usize,
barriers: &[Barrier],
at: u64,
) -> Result<Option<vk::CommandBuffer>, Error> {
let shared = device.shared();
let completed = shared.queues[queue].completed_value();
if self.queues.len() <= queue {
self.queues.resize_with(queue + 1, QueueKept::default);
}
let kept = &mut self.queues[queue];
let index = match kept.lists.iter().position(|list| list.barriers == barriers) {
Some(index) => index,
None if kept.lists.len() < LISTS => {
kept.lists.push(KeptList {
barriers: barriers.to_vec(),
buffers: VecDeque::new(),
});
kept.lists.len() - 1
}
None => return Ok(None),
};
let list = &mut kept.lists[index];
// The batches that took them did so in their timeline values' order: the first is the
// one that may have completed.
if list.buffers.front().is_some_and(|k| k.after <= completed) {
if let Some(mut taken) = list.buffers.pop_front() {
taken.after = at;
let raw = taken.raw;
list.buffers.push_back(taken);
return Ok(Some(raw));
}
}
if list.buffers.len() >= KEPT {
return Ok(None);
}
let raw = shared.vk();
if kept.pool == vk::CommandPool::null() {
let info = vk::CommandPoolCreateInfo::default()
.queue_family_index(shared.queue_family_of(queue));
// SAFETY: the device is live and `info` valid.
let pool = unsafe { raw.create_command_pool(&info, None) };
exit_guard::called(Call::CreateCommandPool);
kept.pool = pool.map_err(vulkan)?;
}
let info = vk::CommandBufferAllocateInfo::default()
.command_pool(kept.pool)
.level(vk::CommandBufferLevel::PRIMARY)
.command_buffer_count(1);
let buffer = device.allocate_command_buffers(&info)?[0];
// Submitted again, one batch at a time: neither one-time nor simultaneous.
let begin = vk::CommandBufferBeginInfo::default();
// SAFETY: the command buffer was just allocated from the scheduler's pool, under its
// lock, and only this call records it.
unsafe {
let begun = raw.begin_command_buffer(buffer, &begin);
exit_guard::called(Call::BeginCommandBuffer);
begun.map_err(vulkan)?;
shared.counts.command_buffer_begun();
for barrier in barriers {
barrier.record(raw, buffer);
exit_guard::called(Call::CmdPipelineBarrier);
}
let ended = raw.end_command_buffer(buffer);
exit_guard::called(Call::EndCommandBuffer);
ended.map_err(vulkan)?;
}
shared.counts.barrier_buffer_kept();
let list = &mut self.queues[queue].lists[index];
list.buffers.push_back(Kept {
raw: buffer,
after: at,
});
Ok(Some(buffer))
}
/// Release the pools, with every kept command buffer, as the device is torn down after its
/// queues are idle.
pub(crate) fn release(&mut self, raw: &ash::Device) {
for kept in self.queues.drain(..) {
if kept.pool != vk::CommandPool::null() {
// SAFETY: the device's queues are idle: no kept command buffer is pending.
unsafe { release::object(raw, kept.pool) };
}
}
}
}
@@ -30,6 +30,7 @@ pub(super) mod completion;
pub(super) mod fences;
mod first_submission;
pub(super) mod gate;
pub(super) mod kept_barriers;
pub(super) mod own;
mod reencode;
mod storage_form;
@@ -13,6 +13,11 @@
//! `VkQueue`, this part waits for it, so the event's semaphore is signaled in index order
//! without holding back the work.
//!
//! Each barrier goes in a command buffer of barriers alone, which the scheduler records once per
//! list of barriers and submits again once the batch that last carried it completed
//! ([`kept_barriers`](super::kept_barriers)); one that also writes timestamps or moves the caller's
//! images is recorded by its batch.
//!
//! A batch with no work is one `VkSubmitInfo` of every wait, the end and the signals: a wait
//! orders only its own `VkSubmitInfo`'s commands, and a signal follows commands, not waits
//! (`vkQueueSubmit`'s synchronization scopes), so a signal after a wait needs both in one, with
@@ -71,6 +76,7 @@
//! thread, once the scheduler's lock is free; its transition to `Scheduled` waits for them.
use super::completion::Submitted;
use super::kept_barriers::KeptBarriers;
use super::{lock, recording_error, submission_error, CommandBufferShared, State};
use crate::deferred::Deferred;
use crate::encoder::RecordedSegment;
@@ -320,7 +326,8 @@ impl CommandBufferShared {
start: start_stamp.take(),
end: None,
};
work.push(self.record_barriers(&mut state, &globals, &[], stamps)?);
let kept = &mut scheduler.kept;
work.push(self.barrier_buffer(&mut state, kept, at, &globals, &[], stamps)?);
}
work.extend(&state.recorded[start + offset].raws);
}
@@ -458,7 +465,8 @@ impl CommandBufferShared {
.into_iter()
.chain([Barrier::to_host()])
.collect();
vec![self.record_barriers(&mut state, &finale_barriers, &exits, stamps)?]
let kept = &mut scheduler.kept;
vec![self.barrier_buffer(&mut state, kept, at, &finale_barriers, &exits, stamps)?]
}
false => Vec::new(),
};
@@ -660,6 +668,7 @@ impl CommandBufferShared {
let begun = unsafe { raw.begin_command_buffer(buffer, &begin) };
exit_guard::called(Call::BeginCommandBuffer);
begun.map_err(|error| submission_error(device, error))?;
device.shared().counts.command_buffer_begun();
record(state, buffer).map_err(|error| recording_error(device, error))?;
// SAFETY: as above.
let ended = unsafe { raw.end_command_buffer(buffer) };
@@ -704,6 +713,34 @@ impl CommandBufferShared {
Ok(())
}
/// A command buffer holding only `barriers`, in order, then `transitions` of the caller's
/// images, between the `stamps` it writes, for the batch that signals `at`: where it holds
/// barriers alone, one the scheduler keeps (`kept_barriers.rs`) on a queue whose command
/// buffers end at their timeline's value (`fences::ends_at_fence`), and else, or past the
/// kept ones' bounds, one recorded into this command buffer's pool
/// ([`record_barriers`](Self::record_barriers)).
fn barrier_buffer(
&self,
state: &mut State,
kept: &mut KeptBarriers,
at: Point,
barriers: &[Barrier],
transitions: &[Transition],
stamps: Stamps,
) -> Result<vk::CommandBuffer, CommandBufferError> {
let device = &self.device;
let alone = transitions.is_empty() && stamps.start.is_none() && stamps.end.is_none();
if alone && !super::fences::ends_at_fence(device, at.queue) {
let taken = kept
.take(device, at.queue, barriers, at.value)
.map_err(|error| recording_error(device, error))?;
if let Some(buffer) = taken {
return Ok(buffer);
}
}
self.record_barriers(state, barriers, transitions, stamps)
}
/// A command buffer of this command buffer's pool holding only `barriers`, in order, then
/// `transitions` of the caller's images, from all commands before to all commands after,
/// between the `stamps` it writes.
@@ -727,6 +764,7 @@ impl CommandBufferShared {
let begun = raw.begin_command_buffer(buffer, &begin);
exit_guard::called(Call::BeginCommandBuffer);
begun.map_err(|error| submission_error(device, error))?;
device.shared().counts.command_buffer_begun();
if let Some((queries, first)) = stamps.start {
raw.cmd_reset_query_pool(buffer, queries, first, 2);
exit_guard::called(Call::CmdResetQueryPool);
+14 -2
View File
@@ -3175,7 +3175,7 @@ impl Device {
})
.map(|color| {
(
format!("color attachment {index}"),
StoredAttachment::Color(index),
color.target.texture.pixel_format(),
color.store,
)
@@ -3205,7 +3205,7 @@ impl Device {
.filter(|aspect| !metals(&pick, aspect.load, aspect.store))
.map(|aspect| {
(
format!("the {name} attachment"),
StoredAttachment::Aspect(name),
ds.target.texture.pixel_format(),
aspect.store,
)
@@ -3221,6 +3221,10 @@ impl Device {
}
};
self.degrade(Degradation::DontCareStore, || {
let which = match which {
StoredAttachment::Color(index) => format!("color attachment {index}"),
StoredAttachment::Aspect(name) => format!("the {name} attachment"),
};
(
format!("{which} of a render pass, a {format:?} texture"),
format!("it is stored with `{store:?}`, {how}"),
@@ -3244,6 +3248,14 @@ impl Device {
}
}
/// The attachment a `DontCare` store's notice names (`Device::degrade_pass`), named only where
/// the notice is made: a color attachment by index, or the depth or the stencil aspect.
#[derive(Clone, Copy)]
enum StoredAttachment {
Color(usize),
Aspect(&'static str),
}
/// A pass recorded as one render pass instance in which the runtime recorded nothing a driver
/// restarts its Metal pass for (`Device::degrade_pass`, `DriverFact::DontCareStoreIsMetals`):
/// no execution of render commands, no barrier between draws, no tessellated draw, no views,
@@ -470,6 +470,8 @@ impl Drop for DeviceShared {
// with its state.
self.timing.release(self.vk());
}
// Nor a kept barrier command buffer: the queues are idle.
self.scheduler.release_kept(self.vk());
// No command buffer is left to give back a spare, or to hold one.
self.spares.release(self);
if let Some(internal) = lock(&self.internal).take() {
@@ -165,6 +165,7 @@ impl Device {
// SAFETY: the command buffer is not pending (every submission is waited for below) and
// the staging lock is held; beginning it resets it (the pool resets command buffers).
unsafe { raw.begin_command_buffer(made.buffer, &begin) }.map_err(vulkan)?;
shared.counts.command_buffer_begun();
record(raw, made.buffer);
// SAFETY: as above.
unsafe { raw.end_command_buffer(made.buffer) }.map_err(vulkan)?;
@@ -148,6 +148,7 @@ impl Device {
if lead {
// SAFETY: as below, for the first work's command buffer.
unsafe { raw.begin_command_buffer(objects.first, &begin) }.map_err(vulkan)?;
shared.counts.command_buffer_begun();
// SAFETY: recording, outside a render pass, for the queue family; it is submitted
// just before the work's submission, which is waited for before anything that uses
// the resources is submitted after it.
@@ -158,6 +159,7 @@ impl Device {
// SAFETY: the command buffer is not pending (every submission is waited for below) and
// the internal lock is held; beginning it resets it (the pool resets command buffers).
unsafe { raw.begin_command_buffer(objects.buffer, &begin) }.map_err(vulkan)?;
shared.counts.command_buffer_begun();
// Host calls' staged copies, after the first work's `VkSubmitInfo`, before the work.
// SAFETY: recording, outside a render pass; every image's move is in the first work's
// submission or one before.
+17 -1
View File
@@ -252,6 +252,11 @@ impl EncoderCore {
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
// SAFETY: the command buffer was just allocated from the pool, under the state lock.
unsafe { device.begin_command_buffer(raw, &begin) }.map_err(vulkan)?;
command_buffer
.device()
.shared()
.counts
.command_buffer_begun();
state.encoder_open = true;
drop(state);
command_buffer
@@ -323,6 +328,11 @@ impl EncoderCore {
// SAFETY: the command buffer was just allocated from the pool, and only this core
// records it.
unsafe { device.begin_command_buffer(raw, &begin) }.map_err(vulkan)?;
command_buffer
.device()
.shared()
.counts
.command_buffer_begun();
Ok(EncoderCore {
open: OpenGuard {
command_buffer: command_buffer.clone(),
@@ -777,6 +787,7 @@ impl EncoderCore {
.begin_command_buffer(next, &begin)
}
.map_err(vulkan)?;
self.device().shared().counts.command_buffer_begun();
Ok(Continuation(next))
}
@@ -937,7 +948,12 @@ impl EncoderCore {
sparse: Vec::new(),
});
}
state.retained.extend(retained);
// The command buffer's first encoder hands over its list as it is.
if state.retained.is_empty() {
state.retained = retained;
} else {
state.retained.extend(retained);
}
state.executions.extend(executions);
if !holds.is_empty() {
state.holds.push(holds);
+35 -28
View File
@@ -1381,6 +1381,7 @@ impl CommandBuffer {
.begin_command_buffer(draws, &begin)
}
.map_err(vulkan)?;
self.device().shared().counts.command_buffer_begun();
Ok(draws)
}
}
@@ -3274,12 +3275,16 @@ impl RenderCommandEncoder {
.iter()
.map(|instance| instance.shape.clone())
.collect();
// The sample planes' steps before each instance and after the last.
let planes = PlanesCommands::plan(
&device,
&layout,
&sample_planes::steps(&layout, &shapes.iter().collect::<Vec<_>>()),
)?;
// The sample planes' steps before each instance and after the last: none in a pass
// without planes.
let planes = match layout.colors.iter().flatten().any(|c| c.planes.is_some()) {
true => PlanesCommands::plan(
&device,
&layout,
&sample_planes::steps(&layout, &shapes.iter().collect::<Vec<_>>()),
)?,
false => None,
};
if resolve_after {
shapes.push(resolving.clone());
}
@@ -3681,7 +3686,7 @@ impl RenderCommandEncoder {
// (`render/extended_shadow.rs`).
let (shadow_fills, fill_uses) = extended.settings(&device, &layout, instances.len())?;
uses.extend(fill_uses);
core.retain(extended.textures());
let extended_textures = extended.textures();
// The copies of each color an instance renders through a stand-in of another format:
// from the attachment before it, and back after it but where it is the pass's last and
// the color's store discards it. Never the pass's first instance clearing that color
@@ -3734,7 +3739,6 @@ impl RenderCommandEncoder {
.filter(|r| r.copies)
.map(|r| r.target.texture.clone())
.collect();
core.retain(stand_ins);
for instance in &instances {
let pieces = instance.pieces.iter().filter_map(|piece| match *piece {
Piece::Draws(draws) => Some(draws),
@@ -3852,6 +3856,8 @@ impl RenderCommandEncoder {
};
// The passes of the runs an execution may split an instance into (`render/executions.rs`).
let mut run_objects = Vec::new();
// The steps of a pass recorded now, or the pass that records later.
let (mut recorded_steps, mut deferred) = (None, None);
// A pass of a draw whose pipeline is being made records later too, once it is made
// (`render/pending.rs`).
if executions.is_empty() && pending.is_empty() {
@@ -3890,7 +3896,7 @@ impl RenderCommandEncoder {
}
},
);
core.retain(steps);
recorded_steps = Some(steps);
} else {
// The pass records later, as a segment of its own: its visibility results are reset
// before it here, as query commands run in submission order.
@@ -3958,7 +3964,7 @@ impl RenderCommandEncoder {
texels_shadowed,
));
// The steps' objects, held with the pass until the command buffer completes.
core.retain(Arc::clone(&pass));
deferred = Some(Arc::clone(&pass));
core.defer(Deferred::RenderPass(pass))?;
}
if let Some(resolves) = exact_resolves {
@@ -3976,9 +3982,6 @@ impl RenderCommandEncoder {
for (_, merge) in &merged {
merge.record_merge(&mut core);
}
if !merged.is_empty() {
core.retain(merged);
}
if let Some(copies) = resolve_copies {
copies.record(&mut core);
}
@@ -4079,21 +4082,25 @@ impl RenderCommandEncoder {
.chain(stood_in)
.chain(planes_images)
.collect();
core.retain(targets);
core.retain(tile_scratch);
core.retain(layout.visibility);
core.retain(passes);
core.retain(objects);
core.retain(run_objects);
if let Some(shadow) = shadow {
core.retain(shadow.held());
}
if let Some(stand_in) = depth_stand_in {
core.retain(stand_in.held());
}
if let Some(imageblock) = imageblock {
core.retain(imageblock.held());
}
// What the pass's commands use, held until the command buffer completes as one object,
// which lets go of them in this order: the command buffer lets go of what it holds from
// the last retained back.
core.retain((
imageblock.as_ref().map(PassImageblock::held),
depth_stand_in.as_ref().map(DepthStandIn::held),
shadow.as_ref().map(ShadowStencil::held),
run_objects,
objects,
passes,
layout.visibility,
tile_scratch,
targets,
merged,
deferred,
recorded_steps,
stand_ins,
extended_textures,
));
// What it made resident joins its command buffer's (`residency.rs`), and is its own
// (`CommandBuffer::ended_encoders`).
let log = log.filter(|_| captured.is_none());
@@ -74,6 +74,7 @@ pub(super) mod inbox;
pub(super) mod order;
use super::command_buffer::gate::Hold;
use super::command_buffer::kept_barriers::KeptBarriers;
use super::command_buffer::CommandBufferShared;
use super::device::lock;
use super::error::{Error, MemoryKind};
@@ -129,6 +130,9 @@ pub(crate) struct State {
/// How many of `decodes` are of untracked textures, whose uses no footprint names: every
/// batch waits while one is left.
untracked_decodes: usize,
/// The batches' barrier command buffers, recorded once and submitted again
/// (`command_buffer/kept_barriers.rs`).
pub(crate) kept: KeptBarriers,
}
/// A commit not yet taken into the order: the command buffer, its logical queue, its batches.
@@ -196,6 +200,7 @@ impl Scheduler {
stopping: false,
decodes: BTreeMap::new(),
untracked_decodes: 0,
kept: KeptBarriers::default(),
}),
wake: Condvar::new(),
gated: AtomicBool::new(false),
@@ -336,6 +341,12 @@ impl Scheduler {
}
}
/// Release the kept barrier command buffers (`command_buffer/kept_barriers.rs`): the device is
/// being torn down, its queues idle.
pub(crate) fn release_kept(&self, raw: &ash::Device) {
lock(self.shared.inbox.state()).kept.release(raw);
}
/// Ask the thread to end, and wait for it unless this is the thread. The device is being
/// dropped, so nothing is held: every held command buffer holds its device.
pub(crate) fn stop(&self) {
@@ -284,15 +284,15 @@ pub(crate) struct Scrub {
}
impl Scrub {
/// The scrub of `written` of `texture`, or `None` for a texture that is not a sparse texture
/// the runtime zeroes.
pub(crate) fn of(texture: &Texture, written: Vec<Written>) -> Option<Scrub> {
/// The scrub of `written` of `texture` (made only for one), or `None` for a texture that is
/// not a sparse texture the runtime zeroes.
pub(crate) fn of(texture: &Texture, written: impl FnOnce() -> Vec<Written>) -> Option<Scrub> {
texture
.sparse_image()
.filter(|image| image.zeroed)
.map(|_| Scrub {
texture: texture.clone(),
written,
written: written(),
})
}
@@ -309,13 +309,14 @@ impl Scrub {
targets
.into_iter()
.filter_map(|target| {
let written = Written {
level: target.level,
layers: target.layer..target.layer + target.layers,
origin: [0; 3],
size: [extent[0], extent[1], 1],
};
Scrub::of(&target.texture, vec![written])
Scrub::of(&target.texture, || {
vec![Written {
level: target.level,
layers: target.layer..target.layer + target.layers,
origin: [0; 3],
size: [extent[0], extent[1], 1],
}]
})
})
.collect()
}
@@ -63,6 +63,8 @@ pub(crate) struct Counters {
internal_submissions: AtomicU64,
queue_submissions: AtomicU64,
command_buffers_submitted: AtomicU64,
command_buffers_begun: AtomicU64,
barrier_buffers_kept: AtomicU64,
commits_handed_off: AtomicU64,
images_started_on_the_host: AtomicU64,
host_texel_copies: AtomicU64,
@@ -335,6 +337,17 @@ impl Counters {
(self.command_buffers_submitted).fetch_add(command_buffers as u64, Ordering::Relaxed);
}
/// A `VkCommandBuffer` was begun (`vkBeginCommandBuffer`).
pub(crate) fn command_buffer_begun(&self) {
self.command_buffers_begun.fetch_add(1, Ordering::Relaxed);
}
/// A batch's barrier command buffer was recorded to be kept and submitted again
/// (`command_buffer/kept_barriers.rs`).
pub(crate) fn barrier_buffer_kept(&self) {
self.barrier_buffers_kept.fetch_add(1, Ordering::Relaxed);
}
/// A commit found another thread making the scheduler's pass and left its batches to it
/// (`scheduler/inbox.rs`).
pub(crate) fn commit_handed_off(&self) {
@@ -731,6 +744,15 @@ pub struct WorkCounts {
pub queue_submissions: u64,
/// The `VkCommandBuffer`s those calls submitted.
pub command_buffers_submitted: u64,
/// `VkCommandBuffer`s the runtime began once the device was made: each encoder's, a render
/// encoder's draws' secondary ones, segments', a batch's barrier and first-work ones, internal
/// and staging submissions'. A driver may clear a command buffer's state as it begins one
/// (ANV, Mesa 26.2.4: `anv_cmd_state_init` at each begin after a reset).
pub command_buffers_begun: u64,
/// Barrier command buffers of batches recorded once, kept, and submitted again by later
/// batches once the batch that last took one completed (`command_buffer/kept_barriers.rs`):
/// each is among `command_buffers_begun` once.
pub barrier_buffers_kept: u64,
/// Commits that found another thread submitting for the device's scheduler (a pass of the
/// scheduler's thread, or another commit's) and returned at once, their batches left to that
/// thread, which submits them in commit order as soon as its pass ends
@@ -936,6 +958,8 @@ impl Device {
internal_submissions: counters.internal_submissions.load(Ordering::Relaxed),
queue_submissions: counters.queue_submissions.load(Ordering::Relaxed),
command_buffers_submitted: counters.command_buffers_submitted.load(Ordering::Relaxed),
command_buffers_begun: counters.command_buffers_begun.load(Ordering::Relaxed),
barrier_buffers_kept: counters.barrier_buffers_kept.load(Ordering::Relaxed),
commits_handed_off: counters.commits_handed_off.load(Ordering::Relaxed),
images_started_on_the_host: counters.images_started_on_the_host.load(Ordering::Relaxed),
host_texel_copies: counters.host_texel_copies.load(Ordering::Relaxed),
@@ -1 +1 @@
f59e80962721fc15d92450bad3cb465473ad43b38e85da71f4780ab84680a988
9c9267a50f955648659d21e048d2dc1ad9b022603552bbbcdfa0b8ccfffdc494
@@ -26,8 +26,14 @@
//! pass's opening (`render_command_encoder`), of a draw (its state changes and its draw call), of
//! a pass's end (`end_encoding`) and of a commit; where the lib test binary counts its
//! allocations (a build without `--cfg m2v_system_alloc`), the encoding thread's allocations of
//! each; the notices the sink took per frame; and a frame's share of the device's work counts
//! (`Device::work_counts`) the draw and commit paths keep.
//! each; where the kernel lets a thread count its own (Linux), the user-space instructions the
//! encoding thread retired in each, on average and their 50th percentile, and in a frame's steps
//! together (steady where the times are not, so a change shows run to run), counted in
//! [`COUNTED`] frames of their own after the timed ones: each read of the counter is a system
//! call, which a timed frame's CPU time would hold; the notices the sink took per frame; and a
//! frame's share of the device's work counts
//! (`Device::work_counts`) the draw and commit paths keep, the command buffers begun and submitted
//! among them.
//!
//! `frame_costs` measures the plain device then the announced one, each in turn on one device of
//! its own; `frame_costs_plain` and `frame_costs_announced` measure one alone, in a process of its
@@ -39,15 +45,21 @@
//! its time), and in one without it for the allocations.
//!
//! One check runs by default where the allocations are counted:
//! `a_frame_s_draws_allocate_within_their_bound` holds a frame's draws to [`DRAW_ALLOCATIONS`]
//! on the encoding thread, a draw's state changes and its draw call together, on average. It
//! counts, and times nothing.
//! `a_frame_s_draws_and_pass_ends_allocate_within_their_bounds` holds a frame's draws to
//! [`DRAW_ALLOCATIONS`] on the encoding thread, a draw's state changes and its draw call
//! together, and its passes' ends to [`PASS_END_ALLOCATIONS`], each on average. Another
//! runs by default on every device,
//! `a_frame_s_passes_and_commits_begin_their_command_buffers_within_their_bound`: each pass, from
//! its opening through its end, begins at most [`PASS_BEGINS`] command buffers, and each commit
//! none but the barrier command buffers it records to keep, on a device that keeps them
//! (`Device::work_counts`). They count, and time nothing.
use super::{buffer_with, loader, open_device, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::gpu::TEST_DEVICE;
use crate::worker::alloc;
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
use metal2vulkan::metal::{
BlendFactor, DataType, IndexType, PixelFormat, PrimitiveType, SamplerMinMagFilter, TextureType,
@@ -65,9 +77,10 @@ use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// The untimed and the timed frames of a run.
/// The untimed and the timed frames of a run, and the frames whose instructions it counts.
const WARM: usize = 20;
const TIMED: usize = 100;
const COUNTED: usize = 20;
/// The command buffers of a frame, each one pass.
const BUFFERS: usize = 67;
/// The draws of a pass.
@@ -88,6 +101,15 @@ const SHAPE_BYTES: usize = 64;
/// encoder its pipeline state's routing, and the format table its entries.
#[cfg(not(m2v_system_alloc))]
const DRAW_ALLOCATIONS: f64 = 72.0;
/// The most allocations a frame's pass end (`end_encoding`) makes on the encoding thread on
/// average, once every pipeline is made. Measured: 35.6 on RADV (Radeon 780M) and ANV (Iris Xe),
/// 37.6 on lavapipe; 52.1 on RADV before a pass end retained what its commands use as one object
/// and stopped making the lists it found empty.
#[cfg(not(m2v_system_alloc))]
const PASS_END_ALLOCATIONS: f64 = 40.0;
/// The most command buffers a pass begins, from its opening through its end, once every pipeline
/// is made: its primary and its draws' secondary.
const PASS_BEGINS: u64 = 2;
/// The pipelines of one raster sample count: the rectangle's, the mask's and the panel's.
struct Pipelines {
@@ -348,26 +370,52 @@ impl Workload {
/// Encode and commit one frame, then wait for its last command buffer: what each step cost.
fn frame(&self) -> Frame {
self.frame_reading(Reads::default())
}
/// [`frame`](Self::frame), reading `reads` around each step too (so its times are not the
/// plain frame's).
fn frame_reading(&self, reads: Reads) -> Frame {
let mut frame = Frame::default();
let mut last: Option<CommandBuffer> = None;
let counts = || reads.work_counts.then(|| self.device.work_counts());
let cpu = thread_cpu();
let start = Instant::now();
let mut begun = [Begun::default(); 4];
for pass in 0..BUFFERS {
let command_buffer = self.queue.command_buffer().unwrap();
let descriptor = self.pass(pass);
let (mut encoder, open) =
step(|| command_buffer.render_command_encoder(&descriptor).unwrap());
let before = counts();
let (mut encoder, open) = step(reads.instructions, || {
command_buffer.render_command_encoder(&descriptor).unwrap()
});
frame.open.push(open);
for draw in 0..DRAWS {
let ((), drawn) = step(|| self.draw(&mut encoder, pass, draw));
frame.draws.push(drawn);
if let Some(before) = &before {
begun[0].add(Begun::since(&self.device, before));
}
let ((), ended) = step(|| encoder.end_encoding().unwrap());
for draw in 0..DRAWS {
let before = counts();
let ((), drawn) = step(reads.instructions, || self.draw(&mut encoder, pass, draw));
frame.draws.push(drawn);
if let Some(before) = &before {
begun[1].add(Begun::since(&self.device, before));
}
}
let before = counts();
let ((), ended) = step(reads.instructions, || encoder.end_encoding().unwrap());
frame.end.push(ended);
let ((), committed) = step(|| command_buffer.commit().unwrap());
if let Some(before) = &before {
begun[2].add(Begun::since(&self.device, before));
}
let before = counts();
let ((), committed) = step(reads.instructions, || command_buffer.commit().unwrap());
frame.commit.push(committed);
if let Some(before) = &before {
begun[3].add(Begun::since(&self.device, before));
}
last = Some(command_buffer);
}
frame.begun = begun;
frame.wall = start.elapsed();
frame.cpu = thread_cpu().saturating_sub(cpu);
let last = last.unwrap();
@@ -377,21 +425,163 @@ impl Workload {
}
}
/// One step's wall time, and the encoding thread's allocations in it where they are counted.
/// One step's wall time, and the encoding thread's allocations and user-space instructions in it
/// where they are counted.
#[derive(Clone, Copy)]
struct Step {
wall: Duration,
allocations: Option<u64>,
instructions: Option<u64>,
}
/// Run `body` as one step.
fn step<R>(body: impl FnOnce() -> R) -> (R, Step) {
/// Run `body` as one step, counting its instructions where `counted`.
fn step<R>(counted: bool, body: impl FnOnce() -> R) -> (R, Step) {
let allocations = alloc::thread_allocations();
let instructions = counted.then(instructions::read).flatten();
let start = Instant::now();
let result = body();
let wall = start.elapsed();
let instructions = instructions.map(|before| instructions::read().unwrap() - before);
let allocations = allocations.map(|before| alloc::thread_allocations().unwrap() - before);
(result, Step { wall, allocations })
(
result,
Step {
wall,
allocations,
instructions,
},
)
}
/// The calling thread's count of the instructions it retired in user space, where the kernel lets
/// a thread count its own (Linux's `perf_event_open`, `kernel.perf_event_paranoid` at most 2):
/// steady where a step's time is not, so a change to the encode path shows in it run to run. On a
/// hybrid CPU (Intel's P and E cores) it counts on the P cores alone (`cpu_core`), where a run is
/// pinned (`taskset`).
#[cfg(target_os = "linux")]
mod instructions {
use std::cell::Cell;
/// `struct perf_event_attr` as its first published size (`PERF_ATTR_SIZE_VER0`).
#[repr(C)]
struct Attr {
kind: u32,
size: u32,
config: u64,
sample_period: u64,
sample_type: u64,
read_format: u64,
flags: u64,
wakeup_events: u32,
bp_type: u32,
config1: u64,
}
/// `PERF_TYPE_HARDWARE`, `PERF_COUNT_HW_INSTRUCTIONS`, and the `exclude_kernel` and
/// `exclude_hv` flags.
const HARDWARE: u32 = 0;
const INSTRUCTIONS: u64 = 1;
const EXCLUDE_KERNEL_HV: u64 = (1 << 5) | (1 << 6);
thread_local! {
/// The thread's counter: its descriptor, or -1 where none opened; opened at its first read.
static COUNTER: Cell<Option<i32>> = const { Cell::new(None) };
}
/// The counter's descriptor for the calling thread, opened at its first call.
fn counter() -> i32 {
COUNTER.with(|cell| {
if let Some(fd) = cell.get() {
return fd;
}
// A hybrid CPU's P cores' PMU, in the config's upper half; none elsewhere.
let pmu = std::fs::read_to_string("/sys/bus/event_source/devices/cpu_core/type")
.ok()
.and_then(|text| text.trim().parse::<u64>().ok())
.unwrap_or(0);
let attr = Attr {
kind: HARDWARE,
size: std::mem::size_of::<Attr>() as u32,
config: INSTRUCTIONS | (pmu << 32),
sample_period: 0,
sample_type: 0,
read_format: 0,
flags: EXCLUDE_KERNEL_HV,
wakeup_events: 0,
bp_type: 0,
config1: 0,
};
// SAFETY: `attr` is a valid `perf_event_attr` of its stated size, live for the call;
// the calling thread (0), any CPU (-1), no group (-1), no flags.
let fd = unsafe {
libc::syscall(
libc::SYS_perf_event_open,
&attr as *const Attr,
0,
-1,
-1,
0,
)
};
let fd = i32::try_from(fd).unwrap_or(-1);
cell.set(Some(fd));
fd
})
}
/// The instructions the calling thread retired in user space since its counter opened.
pub(super) fn read() -> Option<u64> {
let fd = counter();
if fd < 0 {
return None;
}
let mut count = 0u64;
// SAFETY: `count` is 8 writable bytes, the size of the counter's value.
let read = unsafe { libc::read(fd, (&mut count as *mut u64).cast(), 8) };
(read == 8).then_some(count)
}
}
/// Elsewhere none is counted.
#[cfg(not(target_os = "linux"))]
mod instructions {
pub(super) fn read() -> Option<u64> {
None
}
}
/// What a frame reads around each step beside its wall time ([`Workload::frame_reading`]): none
/// in a timed frame, as each read costs the encoding thread.
#[derive(Clone, Copy, Default)]
struct Reads {
/// The device's work counts: the command buffers each step began ([`Frame::begun`]).
work_counts: bool,
/// The encoding thread's user-space instructions in each ([`Step::instructions`]).
instructions: bool,
}
/// The command buffers the device began, and of those the barrier command buffers it recorded to
/// keep, in a step a frame that read the work counts ran ([`Workload::frame_reading`]).
#[derive(Clone, Copy, Default)]
struct Begun {
all: u64,
kept: u64,
}
impl Begun {
/// What `device` began since `before`, its work counts then.
fn since(device: &Device, before: &WorkCounts) -> Begun {
let now = device.work_counts();
Begun {
all: now.command_buffers_begun - before.command_buffers_begun,
kept: now.barrier_buffers_kept - before.barrier_buffers_kept,
}
}
fn add(&mut self, other: Begun) {
self.all += other.all;
self.kept += other.kept;
}
}
/// A frame's steps of one kind ([`Frame`]'s `open`, `draws`, `end` or `commit`).
@@ -406,6 +596,10 @@ struct Frame {
commit: Vec<Step>,
wall: Duration,
cpu: Duration,
/// The command buffers its passes' openings, their draws, their ends and its commits began,
/// in that order, where it read the work counts ([`Workload::frame_reading`]); none
/// elsewhere.
begun: [Begun; 4],
}
/// The calling thread's CPU time so far.
@@ -476,6 +670,11 @@ fn measure(runs: &[bool]) {
let frames: Vec<Frame> = (0..TIMED).map(|_| work.frame()).collect();
let counts = work.device.work_counts();
let notices: u64 = heard.lock().unwrap().values().map(|(n, _)| n).sum();
let reads = Reads {
instructions: true,
..Reads::default()
};
let counted: Vec<Frame> = (0..COUNTED).map(|_| work.frame_reading(reads)).collect();
let ms = |d: Duration| d.as_secs_f64() * 1e3;
let [cpu, cpu_high] = percentiles(frames.iter().map(|f| ms(f.cpu)).collect());
let [wall, wall_high] = percentiles(frames.iter().map(|f| ms(f.wall)).collect());
@@ -501,8 +700,38 @@ fn measure(runs: &[bool]) {
Some(total) => format!("{:.2} allocations each", total as f64 / all.len() as f64),
None => "allocations not counted".to_owned(),
};
let read: Vec<Step> = counted.iter().flat_map(|f| of(f).iter().copied()).collect();
let instructions = match read.iter().map(|s| s.instructions).sum::<Option<u64>>() {
Some(total) => {
let [p50, _] = percentiles(
read.iter()
.filter_map(|s| s.instructions)
.map(|n| n as f64)
.collect(),
);
format!(
"{:.0} user-space instructions each (p50 {p50:.0})",
total as f64 / read.len() as f64
)
}
None => "instructions not counted".to_owned(),
};
eprintln!(
"FRAME-COST {name} {label}: {step}: {p50:.2} us (p90 {p90:.2}); {allocations}"
"FRAME-COST {name} {label}: {step}: {p50:.2} us (p90 {p90:.2}); {allocations}; \
{instructions}"
);
}
let instructions: Option<u64> = counted
.iter()
.flat_map(|f| f.open.iter().chain(&f.draws).chain(&f.end).chain(&f.commit))
.map(|s| s.instructions)
.sum();
if let Some(total) = instructions {
eprintln!(
"FRAME-COST {name} {label}: the encoding thread's user-space instructions in a \
frame's steps, over {COUNTED} frames of their own: {:.0} a frame, {:.0} a pass",
total as f64 / COUNTED as f64,
total as f64 / (COUNTED * BUFFERS) as f64,
);
}
let per_frame = |count: fn(&WorkCounts) -> u64| {
@@ -522,6 +751,17 @@ fn measure(runs: &[bool]) {
per_frame(|c| c.timeline_waits),
per_frame(|c| c.addressable_buffers_made),
);
eprintln!(
"FRAME-COST {name} {label}: a frame's command buffers: {:.1} begun ({:.2} a pass), \
{:.1} of them barrier command buffers recorded to keep; {:.1} submitted ({:.2} a \
pass) in {:.1} vkQueueSubmit calls",
per_frame(|c| c.command_buffers_begun),
per_frame(|c| c.command_buffers_begun) / BUFFERS as f64,
per_frame(|c| c.barrier_buffers_kept),
per_frame(|c| c.command_buffers_submitted),
per_frame(|c| c.command_buffers_submitted) / BUFFERS as f64,
per_frame(|c| c.queue_submissions),
);
if announced {
for (kind, (count, _)) in heard.lock().unwrap().iter() {
eprintln!(
@@ -554,10 +794,13 @@ fn frame_costs_announced() {
/// A frame's draws allocate at most [`DRAW_ALLOCATIONS`] each on average on the encoding thread,
/// once every pipeline is made: what the draw path keeps of what it found before (each texture's
/// storage view formats, the pipeline state's routing into the pass's colors, the settles of its
/// latest bind shapes, the format table) is not made again at each draw.
/// latest bind shapes, the format table) is not made again at each draw. Its passes' ends
/// allocate at most [`PASS_END_ALLOCATIONS`] each: a pass end retains what its commands use as one
/// object, and makes no tile grid where a draw reaches every tile, no sample planes' steps in a
/// pass without planes, and no scrub's list for a texture that is not sparse.
#[cfg(not(m2v_system_alloc))]
#[test]
fn a_frame_s_draws_allocate_within_their_bound() {
fn a_frame_s_draws_and_pass_ends_allocate_within_their_bounds() {
let cache = ScratchCache::new().unwrap();
let heard = Heard::default();
let work = Workload::new(device(&cache, false, &heard));
@@ -576,4 +819,63 @@ fn a_frame_s_draws_allocate_within_their_bound() {
each <= DRAW_ALLOCATIONS,
"{each:.2} allocations a draw, more than {DRAW_ALLOCATIONS}"
);
let allocations: u64 = frame.end.iter().map(|s| s.allocations.unwrap()).sum();
let each = allocations as f64 / frame.end.len() as f64;
eprintln!(
"FRAME-COST {}: {each:.2} allocations a pass end, at most {PASS_END_ALLOCATIONS} kept",
work.device.name()
);
assert!(
each <= PASS_END_ALLOCATIONS,
"{each:.2} allocations a pass end, more than {PASS_END_ALLOCATIONS}"
);
}
/// A frame's passes each begin at most [`PASS_BEGINS`] command buffers on the encoding thread,
/// from the opening through the end, once every pipeline is made; and its commits begin none but
/// the barrier command buffers they record to keep (`command_buffer/kept_barriers.rs`), where the
/// device keeps them: every device whose driver reads no command buffer after its timeline's
/// signal (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`), where a commit records
/// its batch's two barrier command buffers, before its pass and after it.
#[test]
fn a_frame_s_passes_and_commits_begin_their_command_buffers_within_their_bound() {
let cache = ScratchCache::new().unwrap();
let heard = Heard::default();
let work = Workload::new(device(&cache, false, &heard));
// Every pipeline made, and every pool piece done, before the frame that counts.
for _ in 0..WARM {
work.frame();
}
let frame = work.frame_reading(Reads {
work_counts: true,
..Reads::default()
});
let [open, draws, end, commit] = frame.begun;
let passes = BUFFERS as u64;
let late_reads = (work.device.properties().driver_defects)
.contains(&RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal);
eprintln!(
"FRAME-COST {}: command buffers begun a pass: {:.2} opening, {:.2} drawing, {:.2} ending, \
{:.2} committing ({:.2} of them barrier command buffers recorded to keep), the bound \
{PASS_BEGINS} a pass; the driver reads command buffers after their signal: {late_reads}",
work.device.name(),
open.all as f64 / passes as f64,
draws.all as f64 / passes as f64,
end.all as f64 / passes as f64,
commit.all as f64 / passes as f64,
commit.kept as f64 / passes as f64,
);
let pass = open.all + draws.all + end.all;
assert!(
pass <= PASS_BEGINS * passes,
"{pass} command buffers begun by {passes} passes, more than {PASS_BEGINS} each"
);
let own = commit.all - commit.kept;
match late_reads {
true => assert_eq!(own, 2 * passes, "a commit's two barrier command buffers"),
false => assert_eq!(
own, 0,
"{own} command buffers begun by {passes} commits, not kept"
),
}
}