runtime: a command buffer's end stamp follows its tail; the runtime's own command buffers are counted and timed

What:
- A Metal command buffer's end timestamp is now the last command of its last segment, written
  after close()'s tail: the copies back of the images its commands wrote and the end barrier,
  with the present moves (record::end takes the stamp). Before, finish() wrote it ahead of
  close(), so the tail ran outside the command buffer's GPU span. gpu_end_time's doc, the type's
  doc, times.rs's module doc and the runtime README say where it sits now.
- The runtime's own command buffers take a stamp pair each from the same pools: every upload
  (leading a submission or going alone) and every Managed copy-in. The start is written as the
  buffer begins (times::begin_own) and the end as its last command (times::end_own). The pairs
  are read on the completion thread as the buffers retire (times::retire_own), as a Metal command
  buffer's are.
- Two new Metrics:
  - runtime_command_buffers: those buffers passed to vkQueueSubmit2, counted before the calls;
  - runtime_command_buffer_gpu_nanos: the sum of their spans.
  A pair read as not available counts in stamps_not_available, and a buffer that found no pair
  counts in untimed_command_buffers; neither adds time. A buffer that never went gives back its
  pair unreset; one in flight at a loss has its pair reset and not read (a new lost flag on the
  completion thread's retiree).
- The api_signatures table holds the two fields.

Tests (device cfg):
- layouts.rs's intercept now keeps each submitted command buffer's barriers, copies to a buffer
  and timestamp writes in order. a_command_buffer_s_end_timestamp_follows_its_tail writes a
  texture over a Shared buffer in an image of its own by a blit and checks the command buffer's
  tail: the copy back between its barriers, the end barrier, then the end stamp, last. In every
  submitted command buffer, uploads included, an end stamp is the last command.
- every_device_counts_and_times_its_own_command_buffers: the first commit carries one upload and,
  where Managed buffers keep a device copy, one copy-in, so it counts 2 (1 on unified memory).
  A get_bytes flush counts 1 more. On lavapipe both add GPU time and every pair is read.

Why: the planner's order. On the RTX 2080 the driver reports the GPU busy 97% of a benchmark
while rt's spans cover 51-53%. This puts the tail inside the Metal span and measures the rest
apart.

How verified: the lane's runtime gate (fmt, clippy plain, m2v_gpu, m2v_cpu_icd and Windows,
Rustdoc, signatures, the runtime suite on lavapipe under the validation layer).
This commit is contained in:
Anees Iqbal committed 2026-11-20 11:51:41 -08:00
1 parent 419d9ab85d
commit c20543ded9
11 files changed
+435 -58

No files matched your search

+17 -6
View File
@@ -190,7 +190,9 @@ the host had set nor a submitted signal promised, by the length of each hold (`e
the same buckets); the groups a queue held behind three submissions in flight that went once a
completion left fewer running (`held_starts`), and the GPU's time behind them, from the latest
end of the command buffers submitted before each to the start of its first, on their timestamps
(`held_start_gap_nanos`);
(`held_start_gap_nanos`); the command buffers of the runtime's own it submitted, the uploads and
the Managed buffers' copy-ins (`runtime_command_buffers`), and the GPU's time they ran, on
timestamps of their own (`runtime_command_buffer_gpu_nanos`);
the copies of textures over a buffer that no linear image holds are split by cause
(`over_copies_pitch` and the rest, in Textures below);
`gauges()` are live counts per kind of resource, every one zero after teardown, and
@@ -1673,8 +1675,10 @@ made, with no lock, and never rewritten for layouts.
once it is scheduled, the `kernel_end_time` of its queue's command buffer before it where that
is later, as Metal schedules a queue's command buffers in order; `kernel_end_time` is the time
it was scheduled. `gpu_start_time` and `gpu_end_time` are two
timestamp queries, one written where its first commands begin and one where its last segment
ends, read once it completes with no wait, and placed on the host clock by the device's last
timestamp queries, one written where its first commands begin and one as the last command of
its last segment, after the copies back of the images its commands wrote and its end barrier,
so the two span all the GPU work done for it, read once it completes with no wait, and placed
on the host clock by the device's last
calibration: one `vkGetCalibratedTimestampsEXT` call reading the GPU's clock and the host's
together, made as the device starts and again at a completion once 100 ms have passed since
the last, never for each command buffer. Neither is ever later than the host time the
@@ -1698,7 +1702,12 @@ made, with no lock, and never rewritten for layouts.
is made (`hostQueryReset`), and a pair as its command buffer retires, those of the two its
submissions wrote, so no command buffer the GPU runs resets a query. A command buffer with no
commands, or whose last segment has none, records a `VkCommandBuffer` for its timestamps. One
that ends with an error has GPU times of 0.
that ends with an error has GPU times of 0. The runtime's own command buffers, which no Metal
command buffer is (the uploads that lead a submission or go alone, and the Managed buffers'
copy-ins), take a pair each from the same pools, written as their first command and their
last, and read as they retire: `Metrics::runtime_command_buffers` counts them and
`Metrics::runtime_command_buffer_gpu_nanos` sums their spans, which no Metal command buffer's
GPU times hold.
- `Event` and `SharedEvent` are timeline semaphores whose values are Metal's values. A host set
(`SharedEvent::set_signaled_value`) raises a floor and never signals the semaphore. A wait
submits no semaphore wait: it is held until the floor meets it or a signal of its value is
@@ -1820,7 +1829,8 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
compute and blit work before its first render pass: one with no render pass reports
`gpu_start_time` equal to its `gpu_end_time`, a length of zero, and one that dispatches before
its first render pass reports a start after those dispatches. Its `gpu_end_time` is its
work's end. Measured on an M3 Max with Mesa 26.3.1, in Vulkan alone, around a 16 ms dispatch:
work's end. An upload or a copy-in holds no render pass, so there its span, in
`Metrics::runtime_command_buffer_gpu_nanos`, is 0. Measured on an M3 Max with Mesa 26.3.1, in Vulkan alone, around a 16 ms dispatch:
two timestamps read one value with a pipeline barrier or a buffer fill between them too, 43-56
µs apart with an empty render pass after the dispatch, and the end one came 51-213 µs before
the host's calibration after its fence wait. Vulkan allows it: a timestamp may be latched at
@@ -1837,7 +1847,8 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
- On lavapipe a command buffer's completion waits for all the device's later work, of every
queue: the driver's read of query results waits for the whole device to idle
(`lvp_GetQueryPoolResults`, with or without `VK_QUERY_RESULT_WAIT_BIT`), and the completion
thread reads each command buffer's two timestamps before its completed handlers run. A short
thread reads each command buffer's two timestamps before its completed handlers run, and each
upload's and copy-in's as it retires. A short
command buffer committed beside another queue's long one completes once the long one ends.
Measured with Vulkan alone on Mesa 26.2.6: a read of a completed submission's timestamps
returned 500.4 ms later, once a later batch that waited on the host could run. It delays and
+16 -4
View File
@@ -42,6 +42,7 @@ use crate::memory::Block;
use crate::over::{self, Back, ManagedOvers};
use crate::record::{self, Reach, Recorder};
use crate::texture::{Image, OverCopy};
use crate::times;
use ash::vk;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Weak};
@@ -187,18 +188,24 @@ pub(crate) struct CopyIn {
pub(crate) command: vk::CommandBuffer,
pub(crate) modified: Vec<Modified>,
pub(crate) images: Vec<Arc<Image>>,
/// Its pair of timestamp queries, its start written first and its end last
/// ([`times::begin_own`]); None where it runs untimed.
pub(crate) stamps: Option<times::Pair>,
}
impl CopyIn {
/// Gives its recorder back and drops what it holds: once what took it retired, or where it
/// never went.
pub(crate) fn retire(self, core: &Core) {
/// Gives its recorder back and drops what it holds, and its pair of timestamp queries, read
/// where its submission completed (`end`, [`times::retire_own`]): once what took it retired,
/// or ended at a loss, or where it never went.
pub(crate) fn retire(self, core: &Core, end: times::OwnEnd) {
let CopyIn {
recorder,
modified,
images,
stamps,
..
} = self;
times::retire_own(core, stamps, end);
core.recorders.give_back(core, recorder);
drop((modified, images));
}
@@ -209,7 +216,8 @@ impl CopyIn {
/// first, then one `vkCmdCopyBuffer` for each buffer from the consumer's block into its device
/// copy, then the copies in those textures take, or a barrier that makes the copies visible to
/// every later command. It begins with no barrier of its own: the one ending each earlier command
/// buffer on the queue puts every earlier command first (`record::end`).
/// buffer on the queue puts every earlier command first (`record::end`). Its timestamps are its
/// first command and its last ([`times::begin_own`]).
///
/// Err: [`Error::Vulkan`] where a command pool or buffer cannot be made or ended.
pub(crate) fn copy_in(core: &Core, named: &[Modified]) -> Result<CopyIn, Error> {
@@ -222,6 +230,7 @@ pub(crate) fn copy_in(core: &Core, named: &[Modified]) -> Result<CopyIn, Error>
return Err(error);
}
};
let stamps = times::begin_own(core, command);
let backs = backs(named);
let into = copies_in(named);
let back_copies: Vec<OverCopy> = backs.iter().map(|(_, copy, _)| *copy).collect();
@@ -254,8 +263,10 @@ pub(crate) fn copy_in(core: &Core, named: &[Modified]) -> Result<CopyIn, Error>
false => over::record_side(device, command, &into_copies, true, &core.counters),
}
}
times::end_own(device, command, stamps);
// SAFETY: the command buffer is recording, and only this thread has it.
if let Err(result) = unsafe { device.end_command_buffer(command) } {
times::retire_own(core, stamps, times::OwnEnd::Unsent);
core.recorders.give_back(core, recorder);
return Err(Error::Vulkan {
call: "vkEndCommandBuffer",
@@ -269,6 +280,7 @@ pub(crate) fn copy_in(core: &Core, named: &[Modified]) -> Result<CopyIn, Error>
command,
modified: named.to_vec(),
images,
stamps,
})
}
+36 -26
View File
@@ -33,10 +33,12 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
/// part waits for can be signalled by the part before it. Each segment's commands end with one
/// barrier that makes their writes visible to every later command and to the host.
///
/// Its GPU times come from two timestamps, written where its first commands begin and where its
/// last segment ends, and read once it completes. Their pair of queries comes from the device's
/// timestamp pools at its first record and goes back as they are read, or as it drops. A command
/// buffer with no commands, or whose last segment has none, records a `VkCommandBuffer` for them.
/// Its GPU times come from two timestamps, written where its first commands begin and as the last
/// command of its last segment, after the copies back of the images its commands wrote and its end
/// barrier, so they span all the GPU work done for it; read once it completes. Their pair of
/// queries comes from the device's timestamp pools at its first record and goes back as they are
/// read, or as it drops. A command buffer with no commands, or whose last segment has none,
/// records a `VkCommandBuffer` for them.
/// Where every pair is taken and the device makes no new pool, it runs untimed, its GPU times 0
/// ([`Metrics::untimed_command_buffers`](crate::Metrics::untimed_command_buffers)).
///
@@ -778,11 +780,16 @@ impl CommandBuffer {
}
/// `GPUEndTime`, in nanoseconds of [`host_time`](crate::host_time) where Metal gives seconds:
/// the timestamp written where its last segment ended, placed on the host clock through the
/// device's calibrated timestamps as [`gpu_start_time`](Self::gpu_start_time) is, and never
/// later than the completion the runtime observed; their difference is the two timestamps'
/// own span. 0 until it completes, and for one that ended with an error; its start time for
/// one that writes no timestamp.
/// the timestamp written as the last command of its last segment, after the copies back of
/// the images its commands wrote to their buffers and its end barrier (with the moves of the
/// drawables it presents), so that from [`gpu_start_time`](Self::gpu_start_time) it spans all
/// the GPU work done for it. Placed on the host clock through the device's calibrated
/// timestamps as [`gpu_start_time`](Self::gpu_start_time) is, and never later than the
/// completion the runtime observed; their difference is the two timestamps' own span. The
/// uploads and copy-ins the runtime submits ahead of it are not in it
/// ([`Metrics::runtime_command_buffer_gpu_nanos`](crate::Metrics::runtime_command_buffer_gpu_nanos)).
/// 0 until it completes, and for one that ended with an error; its start time for one that
/// writes no timestamp.
pub fn gpu_end_time(&self) -> u64 {
self.state().times.gpu_end
}
@@ -845,9 +852,11 @@ impl Building {
&mut segments[last]
}
/// At commit: records the end timestamp into the last segment, beginning a command buffer for
/// it where the segment has none, and ends it; nothing where the command buffer has nothing
/// for the GPU, and no timestamp where it runs untimed.
/// At commit: ends the last segment with the end timestamp as its last command, after the
/// copies back of the images its commands wrote and its end barrier (`close`), so the
/// command buffer's two timestamps span all the GPU work done for it; a command buffer begun
/// for it where the segment has none. Nothing where the command buffer has nothing for the
/// GPU, and no timestamp where it runs untimed.
/// A command buffer that presents drawables records the moves of their images to the present
/// layout in its last segment's end barrier, a command buffer begun for them where the
/// segment has none, and the segment signals their semaphores.
@@ -855,23 +864,19 @@ impl Building {
if self.nothing_for_gpu() {
return Ok(());
}
let last = self.last().command;
let command = match last {
Some(command) => command,
None if self.started && self.stamps.is_none() && self.presents.is_empty() => {
return self.close(&[]);
if self.last().command.is_none() {
if self.started && self.stamps.is_none() && self.presents.is_empty() {
return self.close(&[], None);
}
None => self.begin()?,
};
if let Some(pair) = self.stamps {
times::write_end(&self.device.core().device, command, pair.pool, pair.first);
self.begin()?;
}
let moves: Vec<vk::ImageMemoryBarrier2<'static>> = (self.presents.iter())
.map(|(drawable, _)| drawable.present_barrier())
.collect();
let ready: Vec<vk::Semaphore> = self.presents.iter().map(|&(_, ready)| ready).collect();
self.last().binary = ready;
self.close(&moves)
let end = self.stamps;
self.close(&moves, end)
}
/// Nothing for the GPU: no segment holds commands, a wait or a signal, and no drawable is
@@ -907,8 +912,13 @@ impl Building {
Ok(command)
}
/// Ends the last segment's commands, if it has any, `moves` in its end barrier.
fn close(&mut self, moves: &[vk::ImageMemoryBarrier2<'_>]) -> Result<(), Error> {
/// Ends the last segment's commands, if it has any, `moves` in its end barrier and `end`, the
/// command buffer's end timestamp where it is the last segment, after that barrier.
fn close(
&mut self,
moves: &[vk::ImageMemoryBarrier2<'_>],
end: Option<Pair>,
) -> Result<(), Error> {
let core = Arc::clone(self.device.core());
match self.last().command {
Some(command) => {
@@ -934,7 +944,7 @@ impl Building {
// completes, and may read after an event the segment signals.
let host = self.host_written || !self.last().signals.is_empty();
self.host_written = false;
record::end(&core.device, command, host, moves, &core.counters)
record::end(&core.device, command, host, moves, end, &core.counters)
}
None => Ok(()),
}
@@ -942,7 +952,7 @@ impl Building {
/// Starts a new segment after the last one.
fn split(&mut self) -> Result<(), Error> {
self.close(&[])?;
self.close(&[], None)?;
self.gpu.segments.push(Segment::default());
Ok(())
}
+18 -6
View File
@@ -9,7 +9,7 @@ use crate::device::{lock, Core};
use crate::error::Error;
use crate::event::{self, EventInner, Listener};
use crate::submit::{Ended, Finished, Upload};
use crate::times::{self, Calibration};
use crate::times::{self, Calibration, OwnEnd};
use ash::vk;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -68,6 +68,8 @@ struct Retiree {
value: u64,
/// Of a held group's submission ([`Sent::held`]).
held: bool,
/// In flight at a loss ([`Retiree::lost`]): nothing of it is read.
lost: bool,
item: Item,
}
@@ -226,6 +228,7 @@ impl Done {
state.flight.push_back(Retiree {
value,
held,
lost: false,
item: Item::Upload(upload),
});
}
@@ -233,6 +236,7 @@ impl Done {
state.flight.push_back(Retiree {
value,
held,
lost: false,
item: Item::CopyIn(copy_in),
});
}
@@ -242,6 +246,7 @@ impl Done {
state.flight.push_back(Retiree {
value,
held,
lost: false,
item: Item::Command {
cb,
gpu,
@@ -274,6 +279,7 @@ impl Done {
let retiree = Retiree {
value,
held: false,
lost: false,
item: Item::Command {
cb,
gpu,
@@ -322,8 +328,13 @@ pub(crate) fn lose(core: &Core) {
}
impl Retiree {
/// Retires it, a command buffer with its GPU times where it completed.
fn retire(self, core: &Core, times: Option<(u64, u64)>) {
/// Retires it, a command buffer with its GPU times where it completed; an upload or a copy-in
/// with its timestamps read where it completed (`times::retire_own`).
fn retire(self, core: &Core, gpu_times: Option<(u64, u64)>) {
let end = match self.lost {
true => OwnEnd::Lost,
false => OwnEnd::Completed,
};
match self.item {
Item::Command {
cb,
@@ -331,9 +342,9 @@ impl Retiree {
handlers,
error,
written,
} => command::retire(core, cb, gpu, handlers, error, times, written),
Item::Upload(upload) => upload.retire(core),
Item::CopyIn(copy_in) => copy_in.retire(core),
} => command::retire(core, cb, gpu, handlers, error, gpu_times, written),
Item::Upload(upload) => upload.retire(core, end),
Item::CopyIn(copy_in) => copy_in.retire(core, end),
}
}
@@ -353,6 +364,7 @@ impl Retiree {
/// In flight at a loss.
fn lost(mut self) -> Retiree {
self.lost = true;
if let Item::Command { error, .. } = &mut self.item {
error.get_or_insert(CommandBufferError::DeviceLost { in_flight: true });
}
+40 -2
View File
@@ -531,6 +531,8 @@ struct Atomics {
untimed_command_buffers: AtomicU64,
sampler_element_writes: AtomicU64,
stamps_not_available: AtomicU64,
runtime_command_buffers: AtomicU64,
runtime_command_buffer_gpu_nanos: AtomicU64,
waits_behind_counter: AtomicU64,
external_acquires: AtomicU64,
external_releases: AtomicU64,
@@ -800,6 +802,22 @@ impl Counters {
self.atomics.held_start_gap_nanos.fetch_add(nanos, Relaxed);
}
/// `count` more of the runtime's own command buffers passed to `vkQueueSubmit2`
/// ([`Metrics::runtime_command_buffers`]).
pub(crate) fn runtime_command_buffers(&self, count: u64) {
self.atomics
.runtime_command_buffers
.fetch_add(count, Relaxed);
}
/// One of the runtime's own command buffers ran `nanos` nanoseconds of the GPU's between its
/// two timestamps ([`Metrics::runtime_command_buffer_gpu_nanos`]).
pub(crate) fn runtime_command_buffer_ran(&self, nanos: u64) {
self.atomics
.runtime_command_buffer_gpu_nanos
.fetch_add(nanos, Relaxed);
}
/// An allocation of `bytes` made for blocks ([`Metrics::block_bytes_made`]).
pub(crate) fn allocated(&self, bytes: u64) {
self.atomics.block_bytes_made.fetch_add(bytes, Relaxed);
@@ -1393,6 +1411,8 @@ impl Counters {
untimed_command_buffers: a.untimed_command_buffers.load(Relaxed),
sampler_element_writes: a.sampler_element_writes.load(Relaxed),
stamps_not_available: a.stamps_not_available.load(Relaxed),
runtime_command_buffers: a.runtime_command_buffers.load(Relaxed),
runtime_command_buffer_gpu_nanos: a.runtime_command_buffer_gpu_nanos.load(Relaxed),
waits_behind_counter: a.waits_behind_counter.load(Relaxed),
external_acquires: a.external_acquires.load(Relaxed),
external_releases: a.external_releases.load(Relaxed),
@@ -2040,7 +2060,9 @@ pub struct Metrics {
/// Command buffers that ran untimed, their GPU start and end times 0
/// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time)): at their first
/// record, every pair of the device's timestamp pools was taken and the device made no new
/// pool ([`Gauges::timestamp_pools`]).
/// pool ([`Gauges::timestamp_pools`]). The runtime's own command buffers that found no pair
/// as they began count here too, and their time in
/// [`runtime_command_buffer_gpu_nanos`](Self::runtime_command_buffer_gpu_nanos) is lost.
pub untimed_command_buffers: u64,
/// Elements of set 1's sampler arrays written (`vkUpdateDescriptorSets`): a sampler state's or
/// a constexpr sampler's placement and its going write only the elements whose sampler
@@ -2052,8 +2074,24 @@ pub struct Metrics {
/// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time)). A driver whose
/// timestamps become available only after the signal it orders them before counts every such
/// command buffer here; a submission the device cancelled at a reset, which signals having run
/// nothing, counts too.
/// nothing, counts too. The runtime's own command buffers whose pair reads so count here too,
/// and add no time to
/// [`runtime_command_buffer_gpu_nanos`](Self::runtime_command_buffer_gpu_nanos).
pub stamps_not_available: u64,
/// The runtime's own command buffers passed to `vkQueueSubmit2`, none of them a Metal command
/// buffer: the uploads, each leading a submission or going alone (zero fills, moves home and
/// the zeroing of new textures, staging copies, acquires of another API's writes, and copies
/// between a texture over a buffer and its image of its own), and the Managed buffers'
/// copy-ins ([`managed_bytes_captured`](Self::managed_bytes_captured)). Counted before the
/// call, as [`submissions`](Self::submissions) is.
pub runtime_command_buffers: u64,
/// The GPU's nanoseconds those command buffers ran, in total: each one's span from a
/// timestamp written as its commands begin to one written after its last, in
/// `timestampPeriod`s, counted on the completion thread as it retires. It is no Metal command
/// buffer's [`gpu_run`](Self::gpu_run). One whose pair reads as not available
/// ([`stamps_not_available`](Self::stamps_not_available)), or that took no pair
/// ([`untimed_command_buffers`](Self::untimed_command_buffers)), adds nothing.
pub runtime_command_buffer_gpu_nanos: u64,
/// Rounds of the completion thread in which the progress semaphore's counter read a value
/// that a host wait on it with a timeout of 0 then reported not reached, so nothing retired in
/// that round. A command buffer retires only once a host wait has seen its submission's
+8 -2
View File
@@ -6,6 +6,7 @@ use crate::device::{lock, Core};
use crate::error::Error;
use crate::hazard::Hazards;
use crate::reaper::{Free, Job};
use crate::times::{self, Pair};
use ash::vk;
use std::sync::Mutex;
@@ -131,13 +132,15 @@ pub(crate) fn memory_barrier(reach: Reach) -> vk::MemoryBarrier2<'static> {
/// wrote Shared memory, or signals an event) the barrier also reaches the host, so Shared memory
/// reads the GPU's writes once the command buffer completes or the host sees the event. The
/// barrier also makes the image moves `images`: a presenting command buffer's drawables' moves to
/// the present layout. A segment begins with no barrier: the one ending each earlier segment,
/// upload and fill covers it.
/// the present layout. Where `stamp` is given (the command buffer's last segment), its end
/// timestamp is the last command, after the barrier. A segment begins with no barrier: the one
/// ending each earlier segment, upload and fill covers it.
pub(crate) fn end(
device: &ash::Device,
buffer: vk::CommandBuffer,
host: bool,
images: &[vk::ImageMemoryBarrier2<'_>],
stamp: Option<Pair>,
counters: &Counters,
) -> Result<(), Error> {
let barrier = [memory_barrier(match host {
@@ -155,6 +158,9 @@ pub(crate) fn end(
if host {
counters.reach_host();
}
if let Some(pair) = stamp {
times::write_end(device, buffer, pair.pool, pair.first);
}
// SAFETY: the buffer is recording.
unsafe { device.end_command_buffer(buffer) }.map_err(Error::vulkan("vkEndCommandBuffer"))
}
+20 -8
View File
@@ -289,6 +289,9 @@ pub(crate) struct Upload {
/// first, which a fill of an upload before it in the same submission may meet
/// ([`order_fills`]).
leading: Option<Vec<Filled>>,
/// Its pair of timestamp queries, its start written as it began and its end as it ends
/// ([`times::begin_own`]); None where it runs untimed.
stamps: Option<times::Pair>,
}
/// A zero fill's buffer and its range of bytes.
@@ -342,6 +345,7 @@ impl Upload {
prune_at: HOMES_PRUNE,
filled: Vec::new(),
leading: None,
stamps: times::begin_own(core, command),
}),
Err(error) => {
core.recorders.give_back(core, recorder);
@@ -1852,7 +1856,7 @@ pub(crate) fn run(core: Arc<Core>) {
let uploads = state.drop_uploads();
drop(state);
for upload in uploads {
upload.retire(&core);
upload.retire(&core, times::OwnEnd::Unsent);
}
core.done.end_all(&core, ended);
state = work.lock();
@@ -1868,10 +1872,10 @@ pub(crate) fn run(core: Arc<Core>) {
let captured = state.changes.clear();
drop(state);
for upload in uploads {
upload.retire(&core);
upload.retire(&core, times::OwnEnd::Unsent);
}
for copy_in in captured {
copy_in.retire(&core);
copy_in.retire(&core, times::OwnEnd::Unsent);
}
core.done.end_all(&core, ended);
// The last command buffers this thread ends went to the completion thread first, so
@@ -2077,7 +2081,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
match upload.entries {
0 => {
if let Some(earlier) = empty.replace(upload) {
earlier.retire(core);
earlier.retire(core, times::OwnEnd::Unsent);
}
}
_ => kept.push(upload),
@@ -2089,7 +2093,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
Ok(upload) => kept.push(upload),
Err(_) => ok = false,
},
(false, Some(upload)) => upload.retire(core),
(false, Some(upload)) => upload.retire(core, times::OwnEnd::Unsent),
(false, None) => {}
}
let mut uploads = kept;
@@ -2098,6 +2102,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
// submission completes: one barrier, at the end of the last.
if let Some((last, earlier)) = uploads.split_last_mut() {
for upload in earlier {
times::end_own(device, upload.command, upload.stamps);
// SAFETY: the upload's command buffer was recording under the work lock, which
// `close` took it out under.
ok &= unsafe { device.end_command_buffer(upload.command) }.is_ok();
@@ -2115,6 +2120,7 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
(last.held).extend(backs.into_iter().map(|(_, _, image)| Held::Texture(image)));
record::barrier(device, last.command, Reach::Host);
core.counters.count(Metric::Barriers);
times::end_own(device, last.command, last.stamps);
// SAFETY: as above.
ok &= unsafe { device.end_command_buffer(last.command) }.is_ok();
}
@@ -2176,6 +2182,10 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
);
}
}
// The runtime's own command buffers of the submission, the uploads ahead of its command
// buffers and each copy-in ahead of the one that takes it: counted before the calls, as
// each call is.
(core.counters).runtime_command_buffers((uploads.len() + copy_ins.len()) as u64);
for part in &parts {
let merged = infos(part);
let infos: Vec<vk::SubmitInfo2<'_>> = merged
@@ -2261,9 +2271,11 @@ fn submit(core: &Core, value: u64, uploads: Vec<Upload>, batch: Batch) {
}
impl Upload {
/// Recycles the upload's recorder and gives up what it holds: once its submission completed,
/// or where it never went.
pub(crate) fn retire(self, core: &Core) {
/// Recycles the upload's recorder and gives up what it holds, and its pair of timestamp
/// queries, read where its submission completed (`end`, [`times::retire_own`]): once its
/// submission completed, or ended at a loss, or where it never went.
pub(crate) fn retire(self, core: &Core, end: times::OwnEnd) {
times::retire_own(core, self.stamps, end);
core.recorders.give_back(core, self.recorder);
}
}
@@ -6,6 +6,9 @@
//! driver's. Its barrier commands are counted too. The core commands that name a layout and that rt does not record get no entry, so
//! that a call of one panics (ash's stub for a command it did not load) and the test learns of it.
//!
//! Each command buffer's barriers, copies to a buffer and timestamp writes are kept in the order
//! recorded, for every command buffer submitted ([`submitted`]).
//!
//! The same commands keep each image's moves in the order the queue runs them ([`moves`]): each
//! command buffer's steps, as recorded, are taken in the order `vkQueueSubmit2` hands the command
//! buffers to the queue. An image made while recording moves home once: a barrier of its first
@@ -78,6 +81,16 @@ enum Step {
/// A copy from a buffer: [`Moves::copies_in`] counts its steps.
const COPY_IN: &str = "a copy from a buffer";
/// A command of a command buffer, as [`submitted`] keeps it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Ordered {
Barrier,
/// `vkCmdCopyImageToBuffer`.
CopyToBuffer,
/// `vkCmdWriteTimestamp2` of this query.
Stamp(u32),
}
/// One device's images' moves, in the order its queue ran its submitted command buffers.
#[derive(Clone, Default, Debug)]
pub(crate) struct Moves {
@@ -108,6 +121,7 @@ struct Driver {
cmd_blit_image: vk::PFN_vkCmdBlitImage,
cmd_clear_color_image: vk::PFN_vkCmdClearColorImage,
cmd_begin_rendering: vk::PFN_vkCmdBeginRendering,
cmd_write_timestamp2: vk::PFN_vkCmdWriteTimestamp2,
}
#[derive(Default)]
@@ -130,6 +144,10 @@ struct Record {
homed: HashMap<(vk::Device, vk::Image), bool>,
/// Each device's moves.
moves: HashMap<vk::Device, Moves>,
/// Each command buffer's commands since its begin, in the order recorded.
order: HashMap<vk::CommandBuffer, Vec<Ordered>>,
/// Each device's submitted command buffers' commands, in the order submitted.
submitted: HashMap<vk::Device, Vec<Vec<Ordered>>>,
}
static RECORD: LazyLock<Mutex<Record>> = LazyLock::new(Mutex::default);
@@ -161,6 +179,16 @@ pub(crate) fn moves(device: vk::Device) -> Moves {
record().moves.get(&device).cloned().unwrap_or_default()
}
/// The commands of each command buffer `device` submitted so far, in the order submitted.
pub(crate) fn submitted(device: vk::Device) -> Vec<Vec<Ordered>> {
record().submitted.get(&device).cloned().unwrap_or_default()
}
/// Notes `command` of `command_buffer`, in the order recorded.
fn ordered(command_buffer: vk::CommandBuffer, command: Ordered) {
(record().order.entry(command_buffer).or_default()).push(command);
}
/// Notes `steps` of `command_buffer`, in the order recorded.
fn step(command_buffer: vk::CommandBuffer, steps: impl IntoIterator<Item = (vk::Image, Step)>) {
(record().steps.entry(command_buffer).or_default()).extend(steps);
@@ -283,6 +311,9 @@ pub(crate) unsafe fn recorded(instance: &ash::Instance, device: ash::Device) ->
cmd_begin_rendering: std::mem::transmute::<*const c_void, vk::PFN_vkCmdBeginRendering>(
load(c"vkCmdBeginRendering"),
),
cmd_write_timestamp2: std::mem::transmute::<*const c_void, vk::PFN_vkCmdWriteTimestamp2>(
load(c"vkCmdWriteTimestamp2"),
),
}
};
record().drivers.insert(handle, driver);
@@ -302,6 +333,7 @@ pub(crate) unsafe fn recorded(instance: &ash::Instance, device: ash::Device) ->
b"vkCmdBlitImage" => cmd_blit_image as *const c_void,
b"vkCmdClearColorImage" => cmd_clear_color_image as *const c_void,
b"vkCmdBeginRendering" => cmd_begin_rendering as *const c_void,
b"vkCmdWriteTimestamp2" => cmd_write_timestamp2 as *const c_void,
_ => return None,
};
Some(function)
@@ -386,7 +418,10 @@ unsafe extern "system" fn begin_command_buffer(
) -> vk::Result {
let (_, driver) = driver_of(command_buffer);
// Steps of a recording never submitted are not the queue's.
record().steps.remove(&command_buffer);
let mut record = record();
record.steps.remove(&command_buffer);
record.order.remove(&command_buffer);
drop(record);
// SAFETY: the caller's arguments, passed on.
unsafe { (driver.begin_command_buffer)(command_buffer, info) }
}
@@ -442,6 +477,8 @@ unsafe extern "system" fn queue_submit2(
};
for info in infos {
take(&mut record, device, info.command_buffer);
let order = (record.order.remove(&info.command_buffer)).unwrap_or_default();
record.submitted.entry(device).or_default().push(order);
}
}
record.drivers[&device]
@@ -508,6 +545,7 @@ unsafe extern "system" fn cmd_pipeline_barrier2(
) {
let (device, driver) = driver_of(command_buffer);
*record().barriers.entry(device).or_default() += 1;
ordered(command_buffer, Ordered::Barrier);
// SAFETY: the caller's dependency info and its image barriers.
let barriers = unsafe {
let info = &*info;
@@ -611,12 +649,25 @@ unsafe extern "system" fn cmd_copy_image_to_buffer(
let (device, driver) = driver_of(command_buffer);
note(device, [("a copy to a buffer", image, layout)]);
step(command_buffer, [(image, Step::Use("a copy to a buffer"))]);
ordered(command_buffer, Ordered::CopyToBuffer);
// SAFETY: the caller's arguments, passed on.
unsafe {
(driver.cmd_copy_image_to_buffer)(command_buffer, image, layout, buffer, count, regions)
}
}
unsafe extern "system" fn cmd_write_timestamp2(
command_buffer: vk::CommandBuffer,
stage: vk::PipelineStageFlags2,
pool: vk::QueryPool,
query: u32,
) {
let (_, driver) = driver_of(command_buffer);
ordered(command_buffer, Ordered::Stamp(query));
// SAFETY: the caller's arguments, passed on.
unsafe { (driver.cmd_write_timestamp2)(command_buffer, stage, pool, query) }
}
unsafe extern "system" fn cmd_blit_image(
command_buffer: vk::CommandBuffer,
source: vk::Image,
@@ -709,7 +760,7 @@ unsafe extern "system" fn cmd_begin_rendering(
}
mod on_device {
use super::{barriers, forget, named, Recording};
use super::{barriers, forget, named, submitted, Ordered, Recording};
use crate::tests::command::on_device::{each_device, finished};
use crate::texture::TextureObject;
use crate::{
@@ -922,4 +973,80 @@ mod on_device {
);
});
}
/// A command buffer's end timestamp is its last command, after its tail: a blit writes a
/// texture over a Shared buffer in an image of its own (a texel off the linear image's memory
/// alignment), so the command buffer's last segment ends with the copy of that image back to
/// the buffer and its end barrier, and only then the end timestamp (the pair's second query,
/// an odd one), which `vkCmdWriteTimestamp2` orders after every earlier command. In every
/// command buffer the device submits, the uploads among them, an end timestamp is the last
/// command seen. lavapipe makes the texture an image of its own; a device that takes it in
/// place runs no copy back, and the test says so.
#[test]
fn a_command_buffer_s_end_timestamp_follows_its_tail() {
let _recording = Recording::start();
each_device("end stamp", |name, _, device| {
let handle = device.core().device.handle();
let answer = (device.minimum_linear_texture_alignment(PixelFormat::RGBA8Unorm))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let pitch = ROW.next_multiple_of(answer);
let block = (device.take_block(MemoryClass::Shared, AT + LEN))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let buffer = (device.new_buffer(block.id, AT, LEN, Some(0)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let source = (device.new_buffer(block.id, 0, ROW * u64::from(HEIGHT), None))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let first = IndexClass::Texture.range().start;
(device.grant_indices(IndexClass::Texture, first, 1)).expect("a grant");
let mut d =
TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, WIDTH, HEIGHT);
d.usage = TextureUsage::SHADER_READ;
let texture = (buffer.new_texture(&d, Some(first), 4, pitch))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let copied = texture.copied_over().is_some();
if cfg!(m2v_cpu_icd) {
assert!(copied, "{name}: an image of its own");
}
let queue = device.new_command_queue(4).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut blit = command_buffer.blit_command_encoder().expect("an encoder");
let packed = BufferLayout {
offset: 0,
bytes_per_row: ROW,
bytes_per_image: 0,
};
let (size, at) = ([WIDTH, HEIGHT, 1], TexturePlace::default());
(blit.copy_from_buffer(&source, packed, size, &texture, at))
.unwrap_or_else(|error| panic!("{name}: {error}"));
blit.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
let submitted = submitted(handle);
for order in &submitted {
let end = order
.iter()
.position(|c| matches!(c, Ordered::Stamp(q) if q % 2 == 1));
if let Some(at) = end {
assert_eq!(
at + 1,
order.len(),
"{name}: an end stamp not last: {order:?}"
);
}
}
// The tail: the copy back between its two barriers, the end barrier, the end stamp.
let tail = |order: &Vec<Ordered>| match order.as_slice() {
[.., Ordered::CopyToBuffer, Ordered::Barrier, Ordered::Barrier, last] => {
matches!(last, Ordered::Stamp(q) if q % 2 == 1)
}
_ => false,
};
let tails = submitted.iter().filter(|order| tail(order)).count();
println!("end stamp: {name}: image of its own {copied}; {tails} tails: {submitted:?}");
assert_eq!(tails, usize::from(copied), "{name}: {submitted:?}");
drop((command_buffer, queue, texture, source, buffer));
(device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}"));
});
}
}
@@ -20,6 +20,8 @@
//! - a `replace_region` and a new texture made after a commit held at an event wait go in the
//! submission of the next commit, so the held one copies out the bytes from before the call;
//! - two copies into one texture in two uploads of one submission leave the later one's bytes;
//! - the runtime's own command buffers (an upload, a Managed copy-in, an upload gone alone) are
//! counted as they go and timed as they retire;
//!
//! and every gauge reads zero after teardown.
@@ -693,6 +695,91 @@ mod on_device {
});
}
/// The runtime's own command buffers, counted as they go and timed as they retire
/// (`Metrics::runtime_command_buffers`, `Metrics::runtime_command_buffer_gpu_nanos`): the
/// first commit carries one upload, of every call before it (a new texture's move home and
/// its zeroing, and a Managed device copy's zeroing), and, where Managed buffers keep a device
/// copy, the copy-in of the range `didModifyRange:` named: two, or one on a device of unified
/// memory. Then a `get_bytes` of the texture, whose upload goes alone, counts one more. On
/// lavapipe each pair is read, none untimed or read as not available, and each adds GPU time.
#[test]
fn every_device_counts_and_times_its_own_command_buffers() {
use crate::tests::managed::on_device::new_managed;
each_device("own command buffers", |name, _, device| {
let counters = device.counters();
let copies = !device.has_unified_memory();
let timed = cfg!(m2v_cpu_icd);
(device.grant_indices(IndexClass::Texture, 4096, 1)).expect("a grant");
let cpu = (device.take_block(MemoryClass::Shared, 256))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let managed = (new_managed(&device, cpu.id, 0, 256, 0))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let out_block = (device.take_block(MemoryClass::Shared, 256))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let out = (device.new_buffer(out_block.id, 0, 256, None))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let queue = device.new_command_queue(4).expect("a queue");
let own = || {
let metrics = counters.metrics();
(
metrics.runtime_command_buffers,
metrics.runtime_command_buffer_gpu_nanos,
metrics.untimed_command_buffers + metrics.stamps_not_available,
)
};
let before = own();
let side = 16;
let texture = (device.new_texture(&square(side), Some(4096)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let contents = managed.contents().expect("the consumer's bytes");
// SAFETY: the buffer is 256 bytes long, and nothing reads it meanwhile.
unsafe { contents.as_ptr().write_bytes(0xA5, 256) };
(managed.did_modify_range(0, 256)).unwrap_or_else(|error| panic!("{name}: {error}"));
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut blit = command_buffer.blit_command_encoder().expect("an encoder");
(blit.copy_from_buffer_to_buffer(&managed, 0, &out, 0, 256))
.unwrap_or_else(|error| panic!("{name}: {error}"));
blit.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
assert_eq!(read(&out), vec![0xA5; 256], "{name}: the bytes named");
let committed = own();
println!("own command buffers: {name}: copy-in {copies}; {before:?} -> {committed:?}");
assert_eq!(
committed.0 - before.0,
1 + u64::from(copies),
"{name}: the upload and the copy-in"
);
assert!(!timed || committed.1 > before.1, "{name}: their GPU time");
assert!(!timed || committed.2 == before.2, "{name}: every pair read");
let mut bytes = vec![0u8; (side * side * 4) as usize];
(texture.get_bytes(&mut bytes, u64::from(side * 4), 0, whole(side), 0, 0))
.unwrap_or_else(|error| panic!("{name}: {error}"));
assert!(
bytes.iter().all(|&byte| byte == 0),
"{name}: a new texture's zeros"
);
// A command buffer submitted after the upload retires after it.
let after = queue.command_buffer().expect("a command buffer");
let mut blit = after.blit_command_encoder().expect("an encoder");
(blit.fill_buffer(&out, 0..256, 0)).unwrap_or_else(|error| panic!("{name}: {error}"));
blit.end_encoding();
after.commit().expect("a commit");
finished(name, &after);
let flushed = own();
println!("own command buffers: {name}: the flush {committed:?} -> {flushed:?}");
assert_eq!(flushed.0 - committed.0, 1, "{name}: the upload alone");
assert!(!timed || flushed.1 > committed.1, "{name}: its GPU time");
assert!(!timed || flushed.2 == before.2, "{name}: every pair read");
drop((command_buffer, after, queue, texture, managed, out));
(device.release_block(out_block)).unwrap_or_else(|error| panic!("{name}: {error}"));
(device.release_block(cpu)).unwrap_or_else(|error| panic!("{name}: {error}"));
});
}
/// Writes `byte` over the whole of `texture`, `side` texels square, through the upload.
fn replace(name: &str, texture: &Texture, side: u32, byte: u8) {
let len = u64::from(side * side * 4);
+62 -2
View File
@@ -3,7 +3,12 @@
//!
//! Each command buffer takes a pair of timestamp queries from the device's pools ([`StampPools`])
//! as it records its first commands. Its first command buffer writes the first where its commands
//! begin; its last segment writes the second where it ends. One that finds no pair runs untimed.
//! begin; its last segment writes the second as its last command, after the copies back of the
//! images its commands wrote and its end barrier, so the pair spans all the GPU work done for it.
//! One that finds no pair runs untimed. The runtime's own command buffers, which no Metal command
//! buffer is (the uploads and the Managed buffers' copy-ins), take a pair each too, written first
//! and last ([`begin_own`], [`end_own`]), and their spans are summed as they retire
//! (`Metrics::runtime_command_buffer_gpu_nanos`).
//! The GPU times are the two timestamps placed on the host clock by the device's last calibration
//! (`VK_EXT_calibrated_timestamps`, one reading of the GPU's clock and the host's together): one
//! as the device starts, then one at a completion once [`CALIBRATION_PERIOD`] has passed since
@@ -356,7 +361,9 @@ pub(crate) fn write_start(
}
}
/// Records the end timestamp: written once every earlier command of the queue has completed.
/// Records the end timestamp: written once every earlier command of the queue has completed
/// (`vkCmdWriteTimestamp2`'s first synchronization scope is every command earlier in submission
/// order, at its stage, and in a first scope the bottom-of-pipe stage is every stage).
pub(crate) fn write_end(
device: &ash::Device,
command: vk::CommandBuffer,
@@ -374,3 +381,56 @@ pub(crate) fn write_end(
)
};
}
/// Takes the pair of one of the runtime's own command buffers, which no Metal command buffer is
/// (an upload or a Managed buffer's copy-in), and writes its start into `command`, which has just
/// begun recording: None, counted (`Metrics::untimed_command_buffers`), where every pair is taken
/// and the device makes no new pool.
pub(crate) fn begin_own(core: &Core, command: vk::CommandBuffer) -> Option<Pair> {
let pair = core.stamps.take(&core.device, &core.counters);
match pair {
Some(pair) => write_start(&core.device, command, pair.pool, pair.first),
None => core.counters.count(Metric::UntimedCommandBuffers),
}
pair
}
/// Writes the end of `pair` ([`begin_own`]) into `command`: its last command, after its last
/// barrier, so the pair spans every command of it.
pub(crate) fn end_own(device: &ash::Device, command: vk::CommandBuffer, pair: Option<Pair>) {
if let Some(pair) = pair {
write_end(device, command, pair.pool, pair.first);
}
}
/// How one of the runtime's own command buffers retires.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum OwnEnd {
/// It never went to `vkQueueSubmit2`: its queries are still reset.
Unsent,
/// Its submission completed.
Completed,
/// Its submission was in flight at a loss, the device now idle: nothing of it is read.
Lost,
}
/// Gives back `pair` ([`begin_own`]) as its command buffer retires (`end`). Where it completed,
/// its span is added to `Metrics::runtime_command_buffer_gpu_nanos` where both timestamps read,
/// and one that reads as not available is counted ([`Pair::times`]); where it was submitted, both
/// queries are reset first ([`reset`]).
pub(crate) fn retire_own(core: &Core, pair: Option<Pair>, end: OwnEnd) {
let Some(pair) = pair else {
return;
};
if end == OwnEnd::Completed {
// SAFETY: the pair's pool is the device's, and only this retirement resets its two
// queries, after this read.
if let Some((start, stop)) = unsafe { pair.times(&core.device, &core.counters) } {
(core.counters).runtime_command_buffer_ran(core.ticks.span(start, stop));
}
}
if end != OwnEnd::Unsent {
reset(&core.device, pair.pool, pair.first, 2);
}
core.stamps.give_back(pair);
}
@@ -2290,6 +2290,8 @@ field metal2vulkan-runtime::Metrics.render_records_stale pub render_records_stal
field metal2vulkan-runtime::Metrics.resolves pub resolves: u64
field metal2vulkan-runtime::Metrics.ring_block_allocations pub ring_block_allocations: SiteAllocations
field metal2vulkan-runtime::Metrics.ring_writes pub ring_writes: u64
field metal2vulkan-runtime::Metrics.runtime_command_buffer_gpu_nanos pub runtime_command_buffer_gpu_nanos: u64
field metal2vulkan-runtime::Metrics.runtime_command_buffers pub runtime_command_buffers: u64
field metal2vulkan-runtime::Metrics.sampler_element_writes pub sampler_element_writes: u64
field metal2vulkan-runtime::Metrics.scheduled_to_gpu_start pub scheduled_to_gpu_start: [u64; STAGE_BUCKETS]
field metal2vulkan-runtime::Metrics.shared_long_reuses pub shared_long_reuses: u64
Can't render this file because it is too large.