Submit a commit's work without waiting for the scheduler's lock

A commit no longer blocks on the scheduler's lock while another thread's pass holds it across its
vkQueueSubmit calls: it leaves its batches in a commit inbox that the pass under way takes in, in
commit order. A batch's first work rides in the batch's own vkQueueSubmit, a batch with nothing to
end submits no command buffer, and the runtime counts its queue submissions and live memory blocks
per commit.

Gain: on an Intel Iris Xe host (ANV on i915), the consumer's guest A/B measured a Finder window drag
at 22.1 -> 34.4 frames/s and Safari at 39.1 -> 42.7 frames/s.

Verified on the original branch: the runtime lanes on 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:22 +03:00
1 parent 4b564766ec
commit 8963e1871b
22 files changed
+1516 -229

No files matched your search

@@ -1267,10 +1267,12 @@ impl CommandBuffer {
/// program that models what Metal does as it submits takes that point here.
///
/// - **The thread.** The committing thread, inside `commit`, where the commit submits the
/// last batch itself (its every wait met, and nothing earlier of its queue held); else the
/// thread that submits it later: the device's scheduler thread (after an event's value
/// rose, a host step, a check), or the thread of another `commit` that submits it in its
/// pass. It runs with no lock of the runtime's held, after the submission's call returned.
/// last batch itself (its every wait met, nothing earlier of its queue held, and no other
/// thread submitting for the device as it commits); else the thread that submits it later:
/// the device's scheduler thread (after an event's value rose, a host step, a check, or a
/// commit that found it submitting), or the thread of another `commit` that submits it in
/// its pass (one that released it, or that was submitting as this commit was made). It
/// runs with no lock of the runtime's held, after the submission's call returned.
/// - **Before.** Its handlers run, in the order added, before the status reads `Scheduled`,
/// before [`wait_until_scheduled`](Self::wait_until_scheduled) returns, before its
/// scheduled handlers run, and before it can complete. The GPU may run the work meanwhile:
@@ -2515,6 +2517,7 @@ impl CommandBufferShared {
let fence = unsafe { shared.fences.take(raw) }.ok()?;
// SAFETY: a submission of no batch with an unsignaled fence in no pending submission;
// the `VkQueue` is used under its lock.
shared.counts.queue_submitted(0);
let submitted =
shared.submit_logged(queue, Some(fence), &self.relayed, |vk_queue| unsafe {
raw.queue_submit(vk_queue, &[], fence)
@@ -14,8 +14,15 @@
//! without holding back the work.
//!
//! 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, so a signal after a wait with nothing between
//! needs both in one.
//! orders only its own `VkSubmitInfo`'s commands, and a signal follows commands, not waits
//! (`vkQueueSubmit`'s synchronization scopes), so a signal after a wait needs both in one, with
//! the end's barrier, a command, between. Where it has no wait, no image to move back and no
//! timestamp to write either (an empty command buffer's batch, one of signals alone), its end
//! records nothing and the `VkSubmitInfo` holds no `VkCommandBuffer`: none of its commands wrote
//! anything, every batch before it made its own writes visible to the host before its signals,
//! and its signals follow every command submitted before them. ANV on i915 lists every
//! `VkDeviceMemory` of the device, and its own buffer objects, in each kernel submission of
//! commands, and two objects in one of none (Mesa 26.2.4, `i915/anv_batch_chain.c`).
//!
//! **The caller's images** ([`Device::new_texture_with_vk_image`]). A batch whose encoders use a
//! wrapped image that is not at rest in `GENERAL` moves it there before its first encoder and back
@@ -31,7 +38,12 @@
//! of the batch, whether a use names the resource or not (a command may reach a texture through its
//! resource ID, a buffer through its address), and the batch holds what it worked on until it
//! completes. On a device of several `VkQueue`s every batch on another one waits for it until it
//! completed.
//! completed. It is a `VkSubmitInfo` of its own, first in the batch's `vkQueueSubmit`, waiting for
//! what the work waits for but a binary semaphore: MoltenVK 1.4.1 runs each `VkSubmitInfo` as a
//! Metal command buffer of its own (`MVKQueue::submit`), and lost a copy into a new image
//! recorded in the same one as the image's move (EVs STL-p4a-mvk4, STL-p4b-mvk4); Mesa's drivers
//! merge it with the work, as it signals nothing (`vk_queue_submits_merge`), so it costs no
//! kernel submission of its own. A failed `vkQueueSubmit` made none of it, or lost the device.
//!
//! [`Device::new_texture_with_vk_image`]: crate::Device::new_texture_with_vk_image
//!
@@ -312,15 +324,6 @@ impl CommandBufferShared {
}
work.extend(&state.recorded[start + offset].raws);
}
let finale_barriers: Vec<Barrier> = exit_barrier
.into_iter()
.chain([Barrier::to_host()])
.collect();
let stamps = Stamps {
start: start_stamp.take(),
end: slot.filter(|_| last),
};
let finale = [self.record_barriers(&mut state, &finale_barriers, &exits, stamps)?];
// The new resources' first work, before every command (`texture/first_move.rs`), given
// back if the submission is not made. A move of an image bound to host pages goes only
// with a batch whose encoders name its key, and so hold its pages.
@@ -332,9 +335,8 @@ impl CommandBufferShared {
.is_some_and(|ended| ended.keys.contains(&key))
})
});
// The first work goes in a `vkQueueSubmit` of its own just before the batch's, under the
// queue's lock: MoltenVK lost a copy into a new image submitted with the image's move.
// Host calls' staged copies go at the batch's start.
// The first work goes in a `VkSubmitInfo` of its own just before the batch's, in its
// `vkQueueSubmit` (the module docs). Host calls' staged copies go at the batch's start.
let lead = match first_work.has_first() {
true => Some(self.record_raw(&mut state, |_, buffer| {
// SAFETY: the command buffer is recording, outside a render pass; it is
@@ -348,13 +350,12 @@ impl CommandBufferShared {
if first_work.has_staged() {
let staged = self.record_raw(&mut state, |_, buffer| {
// SAFETY: the command buffer is recording, outside a render pass; every image's
// move is in the first work's submission or one before.
// move is in the first work's `VkSubmitInfo` or a submission before.
unsafe { first_work.record_staged(raw, buffer) };
Ok(())
})?;
work.insert(0, staged);
}
let mut wait_semaphores = Vec::new();
let mut wait_values = Vec::new();
let mut wait_stages = Vec::new();
@@ -436,6 +437,31 @@ impl CommandBufferShared {
order_values.append(&mut wait_values);
order_stages.append(&mut wait_stages);
}
// The end, where the batch has something to end. A batch with no work, no wait, no image
// to move back and no timestamp records none: none of its commands wrote anything, every
// batch before it on any `VkQueue` made its own writes visible to the host before its
// signals, and its signals follow every command submitted before them. A wait needs it:
// a wait orders the commands of its batch, and a signal follows those, not the wait.
let stamps = Stamps {
start: start_stamp.take(),
end: slot.filter(|_| last),
};
let ends = !single
|| !order_semaphores.is_empty()
|| exit_barrier.is_some()
|| !exits.is_empty()
|| stamps.start.is_some()
|| stamps.end.is_some();
let finale: Vec<vk::CommandBuffer> = match ends {
true => {
let finale_barriers: Vec<Barrier> = exit_barrier
.into_iter()
.chain([Barrier::to_host()])
.collect();
vec![self.record_barriers(&mut state, &finale_barriers, &exits, stamps)?]
}
false => Vec::new(),
};
let signal_semaphores: Vec<vk::Semaphore> = kept
.iter()
.map(|(event, _, _)| event.semaphore())
@@ -489,7 +515,15 @@ impl CommandBufferShared {
.wait_dst_stage_mask(&lead_stages)
.command_buffers(&lead_buffers)
.push_next(&mut lead_timeline);
let (mut lead_made, mut closing) = (false, None);
// The first work's `VkSubmitInfo` leads the batch's, in one `vkQueueSubmit`.
let submits: Vec<vk::SubmitInfo<'_>> = (!lead_buffers.is_empty())
.then_some(lead_info)
.into_iter()
.chain(infos.iter().copied())
.collect();
let buffers = (submits.iter())
.map(|info| info.command_buffer_count as usize)
.sum();
// From here its heap set versions may be pending: nothing writes them any more, and its
// first batch takes the ticket a texture that goes from now on waits for
// (`heap_sets.rs`). One committed and not yet submitted holds no gone texture.
@@ -505,31 +539,9 @@ impl CommandBufferShared {
// transition is of a live image of the caller's in the layout it is in (its contract,
// `new_texture_with_vk_image`); the fence is unsignaled and in no pending submission;
// the `VkQueue` is used under its lock.
// The first work's submission, with no fence, is the batch's lead: where the batch's
// fails after it was made, a submission of no work signals a fence of its own once the
// first work completed (the device's fences, inside the scheduler's section).
let submitted = shared.submit_logged(queue, fence, &self.relayed, |vk_queue| unsafe {
if !lead_buffers.is_empty() {
raw.queue_submit(
vk_queue,
std::slice::from_ref(&lead_info),
vk::Fence::null(),
)?;
lead_made = true;
}
let made = raw.queue_submit(vk_queue, infos, fence.unwrap_or(vk::Fence::null()));
if made.is_err() && lead_made {
if let Ok(ending) = shared.fences.take(raw) {
match raw.queue_submit(vk_queue, &[], ending) {
Ok(()) => closing = Some(ending),
// SAFETY: the failed submission is not pending.
Err(_) => {
release::object(raw, ending);
}
}
}
}
made
shared.counts.queue_submitted(buffers);
raw.queue_submit(vk_queue, &submits, fence.unwrap_or(vk::Fence::null()))
});
exit_guard::called(Call::QueueSubmit);
if let Err(error) = submitted {
@@ -538,32 +550,16 @@ impl CommandBufferShared {
// not kept: Vulkan leaves a fence's state after a failed submission unsaid.
unsafe { release::object(raw, fence) };
}
// The first work went: what it holds goes once it completed. Where nothing ends its
// submission that a wait could see, the device is taken as lost.
if lead_made {
// The first work's command buffer is of this command buffer's pool, which goes
// as the command buffer fails: where the device is lost, once the driver's own
// completion of the first work ran (`Device::drain_queues`).
let ended = match closing {
Some(ending) => {
// SAFETY: the fence was submitted just now; inside the section.
let waited = unsafe { raw.wait_for_fences(&[ending], true, u64::MAX) };
exit_guard::called(Call::WaitForFences);
// SAFETY: signaled or the device lost: not pending.
unsafe { release::object(raw, ending) };
waited.is_ok()
}
None => {
device.mark_lost();
false
}
};
if !ended {
device.drain_queues();
}
drop(first_work.submitted(None));
// A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or
// loses the device: the first work goes back, still to be done, as `first_work`
// drops. Where the device is lost, its command buffers, of this command buffer's pool
// that goes as the command buffer fails, go once the driver's own completion of what
// the call ran did (`Device::drain_queues`).
let error = submission_error(device, error);
if matches!(error, CommandBufferError::DeviceLost) {
device.drain_queues();
}
return Err(submission_error(device, error));
return Err(error);
}
if last {
state.times.kernel_end = gpu_time::host_nanos();
@@ -432,6 +432,7 @@ impl super::DeviceShared {
if let (Some(fence), Some(_busy)) = (fence, exit_guard::enter()) {
let raw = self.vk();
flights.push(fence, by);
self.counts.queue_submitted(0);
// SAFETY: a submission of no work with an unsignaled fence in no pending
// submission; the queue is used under its lock.
let submitted = unsafe { raw.queue_submit(vk_queue, &[], fence) };
@@ -188,6 +188,7 @@ impl Device {
.push_next(&mut timeline);
// SAFETY: the queue is used under the staging lock alone; the command buffer is
// executable; every value waited for was signalled (the host saw it).
shared.counts.queue_submitted(buffers.len());
let submitted = unsafe {
staging.word.restore();
raw.queue_submit(queue, &[submit], made.fence)
@@ -5,7 +5,8 @@
//! with the barrier that makes such writes visible. Each first does the new resources' first GPU
//! work that waits (`texture/first_move.rs`), after the batches on other `VkQueue`s that did such
//! work: no new resource waits for one, so making one waits for no GPU work. That work goes in a
//! submission of its own just before the work's.
//! `VkSubmitInfo` of its own just before the work's, in its `vkQueueSubmit`, as a batch's does
//! (`command_buffer/submit.rs`): one kernel submission on Mesa's drivers.
//!
//! The one submission no one waits for is a no-copy buffer's sparse binding of its dma-bufs
//! (`dma_buf.rs`), on the same queue and timeline: it would wait behind the queue's work in
@@ -24,22 +25,12 @@ use std::time::Duration;
/// How long one wait for an internal submission lasts before it is repeated.
const WAIT_SLICE: Duration = Duration::from_millis(100);
/// What a failed internal submission that held first work submitted.
enum Made {
/// Nothing: the first work's submission failed.
Nothing,
/// The first work's, and a submission of no work that signals the work's fence and timeline
/// value in place of the work's, which failed.
Closed,
/// The first work's alone: the submission of no work failed too.
Unclosed,
}
/// The command pool, command buffers and fence of internal submissions, made on first use.
pub(super) struct Internal {
pool: vk::CommandPool,
buffer: vk::CommandBuffer,
/// The command buffer of a submission's first work, submitted on its own just before it.
/// The command buffer of a submission's first work, in a `VkSubmitInfo` of its own just
/// before the work's.
first: vk::CommandBuffer,
fence: vk::Fence,
/// The timeline each submission signals, and the value the last one signalled: a batch on
@@ -149,9 +140,10 @@ impl Device {
let waits = firsts.waits(0, |point| {
shared.queues[point.queue].completed_value() >= point.value
});
// The first work goes in a command buffer of its own, submitted just before the work's,
// under the same lock: MoltenVK lost a copy into a new image recorded in the same
// submission as the image's move (EVs STL-p4a-mvk4, STL-p4b-mvk4).
// The first work goes in a command buffer and a `VkSubmitInfo` of its own, just before
// the work's, in its `vkQueueSubmit`: MoltenVK runs each `VkSubmitInfo` as a Metal
// command buffer of its own, and lost a copy into a new image recorded in the same one as
// the image's move (EVs STL-p4a-mvk4, STL-p4b-mvk4).
let lead = taken.has_first();
if lead {
// SAFETY: as below, for the first work's command buffer.
@@ -166,7 +158,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)?;
// Host calls' staged copies, after the first work's submission, before the work.
// 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.
unsafe { taken.record_staged(raw, objects.buffer) };
@@ -209,48 +201,26 @@ impl Device {
.wait_dst_stage_mask(&wait_stages)
.command_buffers(&first_buffers)
.push_next(&mut lead_timeline);
// Where the work's submission fails after the first work's was made: a submission of no
// work signals what the work's would have, so that what the first work holds, and its
// place in the order, go only once it completed.
let mut closing_timeline =
vk::TimelineSemaphoreSubmitInfo::default().signal_semaphore_values(&signal_values);
let closing = vk::SubmitInfo::default()
.signal_semaphores(&signal_semaphores)
.push_next(&mut closing_timeline);
let submits: Vec<vk::SubmitInfo<'_>> = lead
.then_some(lead_submit)
.into_iter()
.chain([submit])
.collect();
// SAFETY: the queue is used under its lock; the command buffers are executable; every
// signal of the timeline is above its value. Where the queue's failures are relayed, a
// failure of this submission loses the device (`relay.rs`).
let made = shared.use_queue(0, By::Runtime, |queue| unsafe {
if lead {
raw.queue_submit(queue, &[lead_submit], vk::Fence::null())
.map_err(|error| (error, Made::Nothing))?;
}
match raw.queue_submit(queue, &[submit], objects.fence) {
Ok(()) => Ok(()),
Err(error) if lead => Err((
error,
match raw.queue_submit(queue, &[closing], objects.fence) {
Ok(()) => Made::Closed,
Err(_) => Made::Unclosed,
},
)),
Err(error) => Err((error, Made::Nothing)),
}
let buffers = submits
.iter()
.map(|info| info.command_buffer_count as usize);
shared.counts.queue_submitted(buffers.sum());
raw.queue_submit(queue, &submits, objects.fence)
});
let failed = match made {
Ok(()) => None,
// Nothing was submitted: the work goes back as `taken` drops.
Err((error, Made::Nothing)) => return Err(self.failed(error)),
Err((error, Made::Closed)) => Some(error),
// Nothing ends the first work's submission that a wait could see: the device is
// taken as lost, so that its command buffer is used no more, and what the work holds
// goes, as where a wait for a submission fails (below).
Err((error, Made::Unclosed)) => {
self.mark_lost();
drop(taken.submitted(None));
return Err(vulkan(error));
}
};
// A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or loses
// the device: the work goes back as `taken` drops.
if let Err(error) = made {
return Err(self.failed(error));
}
objects.signalled = value;
shared.counts.internal_submission();
// What it works on, held until it completed.
@@ -262,7 +232,7 @@ impl Device {
} {
Ok(()) => {
firsts.internal_completed(value);
return failed.map_or(Ok(()), |error| Err(self.failed(error)));
return Ok(());
}
Err(vk::Result::TIMEOUT) => continue,
Err(error) => return Err(self.failed(error)),
@@ -308,6 +278,7 @@ impl Device {
// and in its memory at its alignment, of a type it takes (`dma_buf.rs`); the queue's
// family binds sparse memory, and the queue is used under its lock; the signal is above
// the timeline's value (the internal lock is held).
shared.counts.queue_submitted(0);
let bound = shared.use_queue(0, By::Runtime, |queue| unsafe {
raw.queue_bind_sparse(queue, &[info], vk::Fence::null())
});
+41
View File
@@ -380,6 +380,34 @@ impl<T> Pool<T> {
pub(super) fn blocks(&self) -> usize {
self.blocks.iter().flatten().count()
}
/// Its live blocks, by kind, into `census`: those whose payload `imported` names count as
/// imports, whatever else they are.
fn count_into(&self, census: &mut Census, imported: impl Fn(&T) -> bool) {
for block in self.blocks.iter().flatten() {
let count = match (imported(&block.payload), block.dedicated) {
(true, _) => &mut census.imported,
(false, true) => &mut census.dedicated,
(false, false) if block.ranges.is_empty() => &mut census.empty,
(false, false) => &mut census.pooled,
};
*count += 1;
}
}
}
/// A device's live `VkDeviceMemory` blocks, by kind ([`Memory::census`]): each one buffer
/// object the driver lists in every submission where it lists every allocation (ANV on i915).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Census {
/// Pooled blocks with a placement in them.
pub(super) pooled: u64,
/// Pooled blocks with none, kept for the next placement ([`Pool::release`]).
pub(super) empty: u64,
/// Dedicated blocks: a placement larger than half a block, or one placed apart.
pub(super) dedicated: u64,
/// The caller's host memory imported ([`Memory::import_host`]), a block each.
pub(super) imported: u64,
}
/// A host pointer the runtime may send between threads: the mapping of a block it owns.
@@ -408,6 +436,8 @@ pub(super) struct Block {
/// Its buffer of addresses, from the first placement that needs an address (the module
/// docs).
addresses: Option<BlockAddresses>,
/// It is the caller's host memory, imported ([`Memory::import_host`]).
imported: bool,
}
/// A buffer over the first `Block::size` bytes of a block, with every usage of an addressed
@@ -675,6 +705,15 @@ impl Memory {
self.allocated
}
/// Its live blocks, by kind.
pub(super) fn census(&self) -> Census {
let mut census = Census::default();
for pool in &self.pools {
pool.count_into(&mut census, |block| block.imported);
}
census
}
/// Whether one of the memory types `allowed` names is of `class`.
pub(super) fn has_type(&self, allowed: u32, class: MemoryClass) -> bool {
self.class_types(allowed, class) != 0
@@ -970,6 +1009,7 @@ impl Memory {
size,
mapped: Some(Mapped(pointer)),
addresses: None,
imported: true,
};
let index = self
.pool(Holds::Buffers, type_index)
@@ -1164,6 +1204,7 @@ impl BlockMaker {
size,
mapped,
addresses,
imported: false,
})
}
}
@@ -0,0 +1,146 @@
//! The scheduler's lock with an inbox, as a pure structure: a commit that finds another thread
//! making a pass leaves its batches to it and returns, instead of waiting for the pass's
//! submissions.
//!
//! A pass takes the lock, takes in what was committed, and submits what is ready, one
//! `vkQueueSubmit` after another (about 80 us each on ANV with i915, whose execbuffer lists every
//! memory object of the device). A commit made while one runs waited for all of it.
//!
//! - **Inline where the lock is free.** A commit tries the lock: where it gets it, it takes in
//! what the inbox holds and then its own commit, and makes the pass itself, as before.
//! - **Handed to the pass under way.** Where the lock is taken, it puts its commit in the inbox
//! and returns: the thread making the pass takes it in at its next one, which it makes as soon
//! as it let go of the lock (below). The inbox keeps commit order, and every pass takes it in
//! before anything else is committed: so the order sees commits in commit order, and the
//! batches go to the `VkQueue`s, and are planned, in the order a pass picks them, as before.
//! - **Nothing left behind.** The threads making a pass or trying for one are counted
//! (`passers`). Each, once done and counted out, looks at the inbox again after a sequentially
//! consistent fence, and makes another pass for what it holds unless another passer is still
//! counted, which looks again in turn. A commit puts its own in before the same fence and
//! look: whichever of the two fences comes first, the later look sees the other's write, so
//! a commit is either seen by a passer's look or finds no passer, and passes itself. The lock's
//! other holders (a wake, a decode count, the thread's look for work) make no pass and are not
//! counted: a commit that finds only one of them waits for its short hold, and then passes.
//! - **Who runs the after-work.** A pass's thread lets go, outside the lock, of what its passes
//! submitted (the holds, the submission handlers) in submission order, as the scheduler does
//! for its own: a commit handed off runs its submission handlers on that thread.
use crate::device::lock;
use std::sync::atomic::{fence, AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, TryLockError};
/// A state `S` that passes work on under its lock, and the commits `C` waiting to be taken in.
pub(crate) struct Inbox<S, C> {
state: Mutex<S>,
/// Commits not yet taken in, in commit order.
commits: Mutex<Vec<C>>,
/// `commits` holds one (read without its lock; written under it).
posted: AtomicBool,
/// The threads making a pass or trying the lock for one.
passers: AtomicUsize,
}
impl<S, C> Inbox<S, C> {
pub(crate) fn new(state: S) -> Inbox<S, C> {
Inbox {
state: Mutex::new(state),
commits: Mutex::new(Vec::new()),
posted: AtomicBool::new(false),
passers: AtomicUsize::new(0),
}
}
/// The state's lock, for what makes no pass: a read, a mark for the thread, a wait on it.
pub(crate) fn state(&self) -> &Mutex<S> {
&self.state
}
/// Whether a commit waits in the inbox, not yet taken in.
pub(crate) fn holds_commits(&self) -> bool {
self.posted.load(Ordering::SeqCst)
}
/// Commit `commit`: where the lock is free, make the pass on this thread, `pass` taking in
/// what the inbox held and `commit` after it, in commit order; where another thread holds it,
/// leave `commit` to that thread's pass. Then look at the inbox again ([`look_again`]). Whether
/// `commit` was left to another thread.
///
/// [`look_again`]: Self::look_again
pub(crate) fn commit(&self, commit: C, mut pass: impl FnMut(&mut S, Vec<C>)) -> bool {
self.passers.fetch_add(1, Ordering::SeqCst);
let state = match self.state.try_lock() {
Ok(state) => Some(state),
Err(TryLockError::Poisoned(poisoned)) => Some(poisoned.into_inner()),
Err(TryLockError::WouldBlock) => None,
};
let left = match state {
Some(mut state) => {
let mut commits = self.take();
commits.push(commit);
pass(&mut state, commits);
false
}
None => {
let mut commits = lock(&self.commits);
commits.push(commit);
self.posted.store(true, Ordering::SeqCst);
true
}
};
self.passers.fetch_sub(1, Ordering::SeqCst);
let passed = self.look_again(&mut pass);
left && !passed
}
/// A pass by a thread that waits for the lock (the scheduler's own), `pass` taking in what the
/// inbox holds; then look at the inbox again ([`look_again`](Self::look_again)).
pub(crate) fn pass(&self, mut pass: impl FnMut(&mut S, Vec<C>)) {
self.passers.fetch_add(1, Ordering::SeqCst);
let mut state = lock(&self.state);
let commits = self.take();
pass(&mut state, commits);
drop(state);
self.passers.fetch_sub(1, Ordering::SeqCst);
self.look_again(&mut pass);
}
/// After a passer is counted out: while the inbox holds a commit and no other passer is
/// counted, take the lock and pass for it (waiting only for a holder that makes no pass).
/// Whether this made a pass.
fn look_again(&self, pass: &mut impl FnMut(&mut S, Vec<C>)) -> bool {
let mut passed = false;
loop {
fence(Ordering::SeqCst);
if !self.posted.load(Ordering::SeqCst) || self.passers.load(Ordering::SeqCst) > 0 {
return passed;
}
self.passers.fetch_add(1, Ordering::SeqCst);
let mut state = match self.state.try_lock() {
Ok(state) => state,
Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
// Another passer took it since: it looks again once done.
Err(TryLockError::WouldBlock) if self.passers.load(Ordering::SeqCst) > 1 => {
self.passers.fetch_sub(1, Ordering::SeqCst);
continue;
}
// A short hold that makes no pass.
Err(TryLockError::WouldBlock) => lock(&self.state),
};
let commits = self.take();
pass(&mut state, commits);
drop(state);
passed = true;
self.passers.fetch_sub(1, Ordering::SeqCst);
}
}
/// The commits in the inbox, in commit order, taken out; called under the state's lock.
fn take(&self) -> Vec<C> {
if !self.posted.load(Ordering::SeqCst) {
return Vec::new();
}
let mut commits = lock(&self.commits);
self.posted.store(false, Ordering::SeqCst);
commits.drain(..).collect()
}
}
+151 -73
View File
@@ -2,10 +2,15 @@
//! batches to the device's `VkQueue`s.
//!
//! - **Submitted by the commit**. `commit` makes the thread's pass itself, on the committing
//! thread, under the scheduler's lock: the batches ready then go to the `VkQueue` before it
//! returns, in the same order, with no wake of the thread on their path. The thread runs what
//! that pass leaves (a host step, a submission check, a wait for an event the host raises later),
//! as before.
//! thread, under the scheduler's lock, where it finds the lock free: the batches ready then go
//! to the `VkQueue` before it returns, in the same order, with no wake of the thread on their
//! path. The thread runs what that pass leaves (a host step, a submission check, a wait for an
//! event the host raises later), as before.
//! - **Handed to the pass under way** ([`Inbox`]). Where another thread holds the lock for a pass
//! (this one, or another commit), `commit` leaves its batches in the inbox and returns at once:
//! that thread takes them in, in commit order, as soon as it lets go of the lock, and submits
//! what is ready in a pass of its own, as the commit would once it had the lock. The order sees
//! every commit in commit order, and every batch is planned as it is submitted, as before.
//!
//! - **The order** ([`Order`]). Each logical queue's batches wait in commit order; the head
//! committed first among those ready goes next. A batch is ready once every event it waits for
@@ -30,9 +35,10 @@
//! submission.
//! - **Submission handlers** (a runtime extension). The thread that submitted a command buffer's
//! last batch runs its submission handlers, in submission order among the command buffers its
//! pass submitted, once it let go of the lock and before it lets go of the command buffers: in
//! `commit`, before it returns; on this thread, before its next pass, which they hold back. The
//! command buffer's transition to `Scheduled` waits for them.
//! passes submitted, once it let go of the lock and before it lets go of the command buffers: in
//! `commit`, before it returns (a commit handed to another thread's pass has them run there); on
//! this thread, before its next pass, which they hold back. The command buffer's transition to
//! `Scheduled` waits for them.
//! - **Host steps**. A batch that executes commands the GPU may write
//! (`CommandBufferShared::needs_host_step`) is held, once otherwise ready, until every
//! `VkQueue` completed what was submitted to it by then (its gate, a snapshot of the queues'
@@ -56,14 +62,15 @@
//! lock: it may be the last reference, and the command buffer's device may go with it, whose
//! drop stops this thread.
//!
//! Locks are taken in one order: the scheduler's state, then a command buffer's, then an event's
//! or a `VkQueue`'s, then the handler threads' state, then the completion thread's list. No call
//! made under the scheduler's lock takes it again.
//! Locks are taken in one order: the scheduler's state, then its inbox's, then a command buffer's,
//! then an event's or a `VkQueue`'s, then the handler threads' state, then the completion thread's
//! list. No call made under the scheduler's lock takes it again.
//!
//! [`EventTimeline`]: super::event_timeline::EventTimeline
//! [`Point`]: super::tracker::Point
pub(super) mod binary;
pub(super) mod inbox;
pub(super) mod order;
use super::command_buffer::gate::Hold;
@@ -78,6 +85,7 @@ use super::resource::ResourceKey;
use super::tracker::{self, Footprint, Tracker};
use ash::vk;
use binary::{BinarySignals, Needs};
use inbox::Inbox;
use order::{Behind, Order};
use std::collections::BTreeMap;
use std::sync::atomic::{fence, AtomicBool, Ordering};
@@ -95,7 +103,8 @@ pub(crate) struct Scheduler {
}
struct SchedulerShared {
state: Mutex<State>,
/// The state, under the lock a pass holds, with the commits a pass under way takes in.
inbox: Inbox<State, Committed>,
wake: Condvar,
/// A batch waits at its gate for work to complete: the completion thread wakes the thread
/// as batches complete.
@@ -122,6 +131,13 @@ pub(crate) struct State {
untracked_decodes: usize,
}
/// A commit not yet taken into the order: the command buffer, its logical queue, its batches.
struct Committed {
buffer: Hold<CommandBufferShared>,
queue: u64,
batches: Vec<BatchSync>,
}
/// A committed batch not yet submitted.
struct Held {
buffer: Hold<CommandBufferShared>,
@@ -171,7 +187,7 @@ impl Scheduler {
/// one.
pub(crate) fn start(queues: usize) -> Result<Scheduler, Error> {
let shared = Arc::new(SchedulerShared {
state: Mutex::new(State {
inbox: Inbox::new(State {
order: Order::default(),
tracker: Tracker::default(),
values: vec![0; queues],
@@ -201,50 +217,38 @@ impl Scheduler {
/// Hold the batches of `buffer`, committed now on logical queue `queue`: what each batch
/// waits for and signals, in order. Then submit, on the committing thread, every batch that
/// is ready now, as the thread's pass would: a commit whose batches wait for nothing reaches
/// the `VkQueue` before `commit` returns, without the thread's wake on its path. A host step or
/// a submission check found ready, and the process's exit, are left to the thread, which this
/// wakes for them.
/// the `VkQueue` before `commit` returns, without the thread's wake on its path. Where another
/// thread is making a pass, leave the batches to it and return at once (the module docs). A
/// host step or a submission check found ready, and the process's exit, are left to the
/// thread, which this wakes for them.
pub(crate) fn commit(
&self,
buffer: &Arc<CommandBufferShared>,
queue: u64,
batches: Vec<BatchSync>,
) {
let count = batches.len();
let mut state = lock(&self.shared.state);
let binary = &mut state.binary;
let held: Vec<Held> = batches
.into_iter()
.enumerate()
.map(|(index, batch)| Held {
buffer: buffer.hold(),
index,
last: index + 1 == count,
binary_needs: binary.commit(&batch.binary_waits, &batch.binary_signals),
waits: batch.waits,
binary_signals: batch.binary_signals,
segments: batch.segments,
gate: None,
checked: batch.checked,
})
.collect();
state.order.push(queue, held);
let (mut spent, mut settled) = (Spent::default(), Vec::new());
let (mut steps, mut checks) = (Vec::new(), Vec::new());
let mut handlers = Vec::new();
let exiting = submit_ready(
&mut state,
(&mut spent, &mut settled),
(&mut steps, &mut checks),
&mut handlers,
&self.shared.gated,
)
.is_err();
// The pass was the thread's but for what it runs without the lock: the thread looks
// again only for that, or for the exit (or for what woke it before, which this pass saw).
let thread = exiting || !steps.is_empty() || !checks.is_empty();
state.dirty = thread;
drop(state);
let shared = &*self.shared;
let committed = Committed {
buffer: buffer.hold(),
queue,
batches,
};
let mut passed = Passed::default();
let left = (shared.inbox).commit(committed, |state, commits| {
pass(state, commits, &mut passed, &shared.gated, false);
});
if left {
buffer.device().shared().counts.commit_handed_off();
}
let thread = passed.for_thread();
let Passed {
spent,
settled,
steps,
checks,
handlers,
..
} = passed;
settle(settled);
// On the committing thread, before `commit` returns.
run_submission_handlers(handlers);
@@ -254,7 +258,7 @@ impl Scheduler {
drop(steps);
drop(checks);
if thread {
self.shared.wake.notify_all();
shared.wake.notify_all();
}
}
@@ -265,16 +269,17 @@ impl Scheduler {
let shared = Arc::downgrade(&self.shared);
move || {
if let Some(shared) = shared.upgrade() {
lock(&shared.state).dirty = true;
lock(shared.inbox.state()).dirty = true;
shared.wake.notify_all();
}
}
}
/// Whether every batch committed so far was submitted: none is held for an event, a binary
/// semaphore, a host step or a check (`texture/storage_form.rs`).
/// semaphore, a host step or a check, or waits in the inbox (`texture/storage_form.rs`).
pub(crate) fn holds_none(&self) -> bool {
lock(&self.shared.state).order.is_empty()
let inbox = &self.shared.inbox;
lock(inbox.state()).order.is_empty() && !inbox.holds_commits()
}
/// A CPU decode into the decoded twin of the resource `key` was queued: every batch whose
@@ -282,7 +287,7 @@ impl Scheduler {
/// says so of every one queued; where it is not `tracked` (its uses not recorded), every
/// batch. A batch already submitted is not waited for.
pub(crate) fn decode_queued(&self, key: ResourceKey, tracked: bool) {
let mut state = lock(&self.shared.state);
let mut state = lock(self.shared.inbox.state());
*state.decodes.entry(key).or_default() += 1;
if !tracked {
state.untracked_decodes += 1;
@@ -292,7 +297,7 @@ impl Scheduler {
/// One CPU decode into the decoded twin of `key` (`tracked` as it was queued) finished: the
/// batches waiting for its decodes go once none is left.
pub(crate) fn decode_finished(&self, key: ResourceKey, tracked: bool) {
let mut state = lock(&self.shared.state);
let mut state = lock(self.shared.inbox.state());
if let Some(count) = state.decodes.get_mut(&key) {
*count -= 1;
if *count == 0 {
@@ -316,7 +321,7 @@ impl Scheduler {
/// Look for work again: an event's value rose.
pub(crate) fn wake(&self) {
lock(&self.shared.state).dirty = true;
lock(self.shared.inbox.state()).dirty = true;
self.shared.wake.notify_all();
}
@@ -334,7 +339,7 @@ impl Scheduler {
/// 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) {
lock(&self.shared.state).stopping = true;
lock(self.shared.inbox.state()).stopping = true;
self.shared.wake.notify_all();
let mut thread = lock(&self.thread);
let own = thread
@@ -352,7 +357,7 @@ impl Scheduler {
/// ([`exit_guard`]): what is held then stays held, as Metal's pending work stays pending.
fn run(shared: &SchedulerShared) {
loop {
let mut state = lock(&shared.state);
let mut state = lock(shared.inbox.state());
while !state.dirty && !state.stopping {
state = shared
.wake
@@ -363,20 +368,21 @@ fn run(shared: &SchedulerShared) {
if state.stopping {
return;
}
state.dirty = false;
let (mut spent, mut settled) = (Spent::default(), Vec::new());
let mut steps = Vec::new();
let mut checks = Vec::new();
let mut handlers = Vec::new();
let exiting = submit_ready(
&mut state,
(&mut spent, &mut settled),
(&mut steps, &mut checks),
&mut handlers,
&shared.gated,
)
.is_err();
// The pass takes the lock again, counted as a passer from before (`inbox.rs`): a commit
// that finds it taken leaves its batches to this thread.
drop(state);
let mut passed = Passed::default();
(shared.inbox).pass(|state, commits| {
pass(state, commits, &mut passed, &shared.gated, true);
});
let Passed {
spent,
settled,
steps,
checks,
handlers,
exiting,
} = passed;
settle(settled);
// On this thread, before its next pass; none once the process is exiting, as the thread
// then runs nothing more (their command buffers stay `Committed`).
@@ -415,7 +421,79 @@ fn run(shared: &SchedulerShared) {
}
}
drop(steps);
lock(&shared.state).dirty = true;
lock(shared.inbox.state()).dirty = true;
}
}
/// What passes leave for their thread to do without the lock ([`submit_ready`]'s outputs), and
/// whether the process is exiting.
#[derive(Default)]
struct Passed {
spent: Spent,
settled: Settled,
steps: Steps,
checks: Steps,
handlers: Handlers,
exiting: bool,
}
impl Passed {
/// Whether the thread has work the passes found for it: a host step, a check, the exit.
fn for_thread(&self) -> bool {
self.exiting || !self.steps.is_empty() || !self.checks.is_empty()
}
}
/// A pass: take `commits` into the order, in commit order, then submit what is ready
/// ([`submit_ready`]) into `passed`. A pass on a thread other than the scheduler's (`own` false)
/// was the thread's but for what it runs without the lock: the thread looks again only for that,
/// or for the exit, and the caller wakes it (what woke it before, this pass saw).
fn pass(
state: &mut State,
commits: Vec<Committed>,
passed: &mut Passed,
gated: &AtomicBool,
own: bool,
) {
for Committed {
buffer,
queue,
batches,
} in commits
{
let count = batches.len();
let binary = &mut state.binary;
let held: Vec<Held> = batches
.into_iter()
.enumerate()
.map(|(index, batch)| Held {
buffer: buffer.hold(),
index,
last: index + 1 == count,
binary_needs: binary.commit(&batch.binary_waits, &batch.binary_signals),
waits: batch.waits,
binary_signals: batch.binary_signals,
segments: batch.segments,
gate: None,
checked: batch.checked,
})
.collect();
state.order.push(queue, held);
// The commit's own hold goes without the lock: its batches hold the command buffer now.
passed.spent.buffers.push(buffer);
}
state.dirty = false;
let exiting = submit_ready(
state,
(&mut passed.spent, &mut passed.settled),
(&mut passed.steps, &mut passed.checks),
&mut passed.handlers,
gated,
)
.is_err();
passed.exiting |= exiting;
if !own {
state.dirty = passed.for_thread();
}
}
@@ -355,6 +355,7 @@ pub(crate) fn bind_batch(
// submitted; the queue binds sparse memory (the device's support) and is used under its
// lock. Where the queue's failures are relayed, one of the bind's loses the device
// (`device/relay.rs`).
shared.counts.queue_submitted(0);
let bound = shared.use_queue(queue, By::Runtime, |vk_queue| unsafe {
shared
.vk()
@@ -0,0 +1,149 @@
//! `scheduler/inbox.rs`: a commit that finds a pass under way on another thread returns at once
//! and its commit goes next, in commit order; one that finds the lock held for no pass passes
//! itself; and commits from many threads racing passes and short holds are all passed, each
//! thread's in its order, with no pass made for them at the end.
use crate::device::lock;
use crate::scheduler::inbox::Inbox;
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
/// The longest a step of these tests may take: a commit that waits for the pass under way
/// instead of returning fails the test after it, rather than hanging it.
const WAIT: Duration = Duration::from_secs(30);
/// The state: the commits in the order the passes took them in.
type Log = Inbox<Vec<u32>, u32>;
/// A pass that only takes the commits in.
fn take_in(log: &mut Vec<u32>, commits: Vec<u32>) {
log.extend(commits);
}
#[test]
fn a_commit_finding_a_pass_under_way_returns_at_once_and_goes_next_in_commit_order() {
let inbox = Arc::new(Log::new(Vec::new()));
let (entered, in_pass) = mpsc::channel();
let (release, released) = mpsc::channel::<()>();
let passer = {
let inbox = Arc::clone(&inbox);
thread::spawn(move || {
let mut passes = 0;
inbox.commit(0, |log, commits| {
take_in(log, commits);
passes += 1;
// The first pass stays under way, the lock held, until the test lets it end.
if passes == 1 {
entered.send(()).unwrap();
released.recv_timeout(WAIT).unwrap();
}
})
})
};
in_pass.recv_timeout(WAIT).unwrap();
let (done, returned) = mpsc::channel();
let committer = {
let inbox = Arc::clone(&inbox);
thread::spawn(move || {
for commit in 1..=3 {
done.send(inbox.commit(commit, take_in)).unwrap();
}
})
};
for commit in 1..=3 {
let left = returned.recv_timeout(WAIT).unwrap_or_else(|_| {
panic!("commit {commit} waited for the pass under way instead of returning")
});
assert!(left, "commit {commit} was left to the pass under way");
}
committer.join().unwrap();
assert!(inbox.holds_commits());
release.send(()).unwrap();
assert!(
!passer.join().unwrap(),
"the passer's own commit was its own"
);
// The passer took them in once its pass ended, in commit order, with no pass asked for.
assert_eq!(*lock(inbox.state()), [0, 1, 2, 3]);
assert!(!inbox.holds_commits());
}
#[test]
fn a_commit_finding_the_lock_held_for_no_pass_passes_itself() {
let inbox = Arc::new(Log::new(Vec::new()));
let held = lock(inbox.state());
let committer = {
let inbox = Arc::clone(&inbox);
thread::spawn(move || inbox.commit(7, take_in))
};
// It found the lock taken and posted: no passer is counted, so it waits for the lock.
let until = Instant::now() + WAIT;
while !inbox.holds_commits() {
assert!(Instant::now() < until, "the commit never posted");
thread::yield_now();
}
drop(held);
assert!(!committer.join().unwrap(), "it passed its commit itself");
assert_eq!(*lock(inbox.state()), [7]);
assert!(!inbox.holds_commits());
}
#[test]
fn commits_racing_passes_and_short_holds_are_all_passed_each_thread_s_in_its_order() {
const THREADS: u32 = 4;
const COMMITS: u32 = 2000;
let inbox = Arc::new(Log::new(Vec::new()));
// A pass that holds the lock a while, so that commits find it under way.
let slow = |log: &mut Vec<u32>, commits: Vec<u32>| {
for _ in 0..200 {
std::hint::spin_loop();
}
log.extend(commits);
};
let committers: Vec<_> = (0..THREADS)
.map(|index| {
let inbox = Arc::clone(&inbox);
thread::spawn(move || {
(0..COMMITS)
.filter(|&commit| inbox.commit(index * COMMITS + commit, slow))
.count()
})
})
.collect();
// The scheduler's thread: passes of its own.
let scheduler = {
let inbox = Arc::clone(&inbox);
thread::spawn(move || {
for _ in 0..COMMITS {
inbox.pass(slow);
thread::yield_now();
}
})
};
// A wake, a decode count: short holds that make no pass.
let marker = {
let inbox = Arc::clone(&inbox);
thread::spawn(move || {
for _ in 0..COMMITS {
drop(lock(inbox.state()));
thread::yield_now();
}
})
};
let left: usize = committers.into_iter().map(|c| c.join().unwrap()).sum();
scheduler.join().unwrap();
marker.join().unwrap();
// No pass made for them at the end: every commit was passed by then.
assert!(!inbox.holds_commits(), "{left} left to other threads");
let log = lock(inbox.state());
assert_eq!(log.len(), (THREADS * COMMITS) as usize, "each once");
for index in 0..THREADS {
let own: Vec<u32> = (log.iter().copied())
.filter(|commit| commit / COMMITS == index)
.collect();
let ordered: Vec<u32> = (index * COMMITS..(index + 1) * COMMITS).collect();
assert_eq!(own, ordered, "thread {index}'s commits in its order");
}
}
@@ -62,6 +62,7 @@ mod host_memory;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod host_step_neutrals;
mod image_plan;
mod inbox;
mod indirect_command_buffer;
mod interop;
mod keeper;
@@ -38,12 +38,14 @@
//! moved only by a batch whose commands name its key (and so hold its pages), or by none until
//! then: an unnamed read of it meanwhile reads a linear image in `UNDEFINED`, which keeps its
//! bytes on every device the lanes run on (`runtime_lane::no_copy_textures`). The work goes in
//! a `vkQueueSubmit` of its own just before the submission's, under the queue's lock, waiting
//! for what that one waits for but a binary semaphore.
//! a `VkSubmitInfo` of its own just before the submission's, first in its `vkQueueSubmit`,
//! waiting for what that one waits for but a binary semaphore: MoltenVK runs each
//! `VkSubmitInfo` as a Metal command buffer of its own, and Mesa's drivers merge it with the
//! submission's into one kernel submission (`command_buffer/submit.rs`).
//! - **Staged copies**. `replace_region` of a texture whose `VkImage` is its own for good (in
//! memory of its own, or a heap's own pages) and takes no host copies stages the bytes
//! ([`TexelCopy`], [`FirstMoves::register_texels`]): the next submission copies them in at
//! the start of its work, after the first work's submission, each copy after the writes before
//! the start of its work, after the first work's `VkSubmitInfo`, each copy after the writes before
//! it, and holds the image and the staging buffer until it completed.
//! - **Bounded**. Past [`STAGED_BYTES`] bytes, or [`STAGED_COPIES`] copies, staged for the next
//! submission (staged bytes' copies into buffers, a `Managed` buffer's uploads, and staged texel
@@ -1223,10 +1225,10 @@ impl Taken<'_> {
}
/// Record the host calls' staged copies it took into `command_buffer`, each after every
/// write before it (the first work, which a submission of its own made before; the copy
/// before), then the barrier that makes them visible to every command after and to the
/// write before it (the first work, which a `VkSubmitInfo` of its own submitted before; the
/// copy before), then the barrier that makes them visible to every command after and to the
/// host. Apart from [`record`](Self::record)'s work: MoltenVK lost a copy into a new image
/// submitted with the image's move.
/// recorded in the same Metal command buffer as the image's move.
///
/// # Safety
///
+51 -1
View File
@@ -61,6 +61,9 @@ pub(crate) struct Counters {
visibility_queries_begun: AtomicU64,
indirect_draws_recorded: AtomicU64,
internal_submissions: AtomicU64,
queue_submissions: AtomicU64,
command_buffers_submitted: AtomicU64,
commits_handed_off: AtomicU64,
images_started_on_the_host: AtomicU64,
host_texel_copies: AtomicU64,
staging_submissions: AtomicU64,
@@ -325,6 +328,19 @@ impl Counters {
self.internal_submissions.fetch_add(1, Ordering::Relaxed);
}
/// A `vkQueueSubmit` or `vkQueueBindSparse` call was made with `command_buffers`
/// `VkCommandBuffer`s among its `VkSubmitInfo`s.
pub(crate) fn queue_submitted(&self, command_buffers: usize) {
self.queue_submissions.fetch_add(1, Ordering::Relaxed);
(self.command_buffers_submitted).fetch_add(command_buffers as u64, 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) {
self.commits_handed_off.fetch_add(1, Ordering::Relaxed);
}
/// A submission on the staging queue was made (`device/staging.rs`).
pub(crate) fn staging_submission(&self) {
self.staging_submissions.fetch_add(1, Ordering::Relaxed);
@@ -651,6 +667,16 @@ pub struct WorkCounts {
/// blocks, pooled or dedicated, freed since or not): none for host memory it imports. A
/// detach allocates none for the bytes it detaches (`detach.rs`).
pub device_memory_allocated: u64,
/// The runtime's live pooled `VkDeviceMemory` blocks with a placement in them (`memory.rs`):
/// with the blocks below and every dma-buf import, the allocations ANV on i915 lists in each
/// of its kernel submissions, beside its own buffer objects.
pub memory_blocks_live: u64,
/// Its live pooled blocks with no placement, kept for the next.
pub empty_memory_blocks_live: u64,
/// Its live dedicated blocks: a placement larger than half a block, or one placed apart.
pub dedicated_memory_blocks_live: u64,
/// Its live imports of the caller's host memory, a block each (`Memory::import_host`).
pub host_imports_live: u64,
/// Stand-ins made for textures over detached bytes (`texture/stand_in.rs`): one per distinct
/// image plan among the textures detached at once.
pub stand_ins_made: u64,
@@ -697,6 +723,19 @@ pub struct WorkCounts {
/// Internal submissions made (`device/submit.rs`), each one a host call waits for: a host
/// copy through the GPU, a clear of a live buffer, a neutral's making.
pub internal_submissions: u64,
/// `vkQueueSubmit` and `vkQueueBindSparse` calls the runtime made on the device's queues once
/// it was made: every batch's, its new resources' first work's apart (`texture/first_move.rs`),
/// internal and staging submissions, sparse binds, and fences submitted with no work. Each is a
/// submission of its own to the driver; Mesa's drivers merge the `VkSubmitInfo`s of one call
/// where no signal lies between a command and a later one, and no further (`vk_queue.c`).
pub queue_submissions: u64,
/// The `VkCommandBuffer`s those calls submitted.
pub command_buffers_submitted: 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
/// (`scheduler/inbox.rs`). Each other commit made the pass itself.
pub commits_handed_off: u64,
/// New `Shared` and `Managed` textures' images moved to `GENERAL` and zeroed on the host, with
/// no submission (`texture/host_copy.rs`).
pub images_started_on_the_host: u64,
@@ -819,6 +858,10 @@ impl Device {
#[doc(hidden)]
pub fn work_counts(&self) -> WorkCounts {
let counters = &self.shared().counts;
let (allocated, census) = {
let memory = lock(&self.shared().memory);
(memory.allocated(), memory.census())
};
WorkCounts {
command_pools_made: counters.command_pools_made.load(Ordering::Relaxed),
live_tables_uploaded: counters.live_tables_uploaded.load(Ordering::Relaxed),
@@ -862,7 +905,11 @@ impl Device {
driver_diagnostics_withheld: counters
.driver_diagnostics_withheld
.load(Ordering::Relaxed),
device_memory_allocated: lock(&self.shared().memory).allocated(),
device_memory_allocated: allocated,
memory_blocks_live: census.pooled,
empty_memory_blocks_live: census.empty,
dedicated_memory_blocks_live: census.dedicated,
host_imports_live: census.imported,
stand_ins_made: counters.stand_ins_made.load(Ordering::Relaxed),
stand_in_bytes: counters.stand_in_bytes.load(Ordering::Relaxed),
stale_detached_reaches: counters.stale_detached_reaches.load(Ordering::Relaxed),
@@ -887,6 +934,9 @@ impl Device {
visibility_queries_begun: counters.visibility_queries_begun.load(Ordering::Relaxed),
indirect_draws_recorded: counters.indirect_draws_recorded.load(Ordering::Relaxed),
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),
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),
staging_submissions: counters.staging_submissions.load(Ordering::Relaxed),
@@ -1 +1 @@
d7084c1ace13c1348b31d6ce3b82c902314751f958ecfbc3b6fa6df3aa1fd199
ef76f9e62dc4fd20b499dfb0cb4388fcf847afae64e61fd8ccb6fdbef3a564cf
@@ -521,6 +521,8 @@ mod submission_checks;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod submission_handlers;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod submit_costs;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod sum_regroup;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod surface_aliases;
@@ -81,7 +81,7 @@ const LIVE_BUFFERS: usize = 256;
const BUFFER_BYTES: u64 = 16 * 1024;
/// The working set's sampled textures, `RGBA8Unorm`, [`TEXTURE_SIDE`] texels a side.
const LIVE_TEXTURES: usize = 128;
const TEXTURE_SIDE: u64 = 64;
pub(super) const TEXTURE_SIDE: u64 = 64;
/// The render targets the passes draw into, [`TARGET_SIDE`] texels a side.
const TARGETS: usize = 4;
const TARGET_SIDE: u64 = 256;
@@ -97,7 +97,7 @@ const DRAWS: usize = 3;
const POINTER_WALKER: &str = "walk-a-device-pointer-chain-through-a-loop-phi";
/// The process's CPU time so far, every thread's, in microseconds.
fn process_cpu_us() -> f64 {
pub(super) fn process_cpu_us() -> f64 {
let mut now = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
@@ -109,12 +109,12 @@ fn process_cpu_us() -> f64 {
}
/// Microseconds since `at`.
fn since(at: Instant) -> f64 {
pub(super) fn since(at: Instant) -> f64 {
at.elapsed().as_secs_f64() * 1e6
}
/// The 10th, 50th and 90th percentiles of `values`.
fn percentiles(mut values: Vec<f64>) -> [f64; 3] {
pub(super) fn percentiles(mut values: Vec<f64>) -> [f64; 3] {
values.sort_by(f64::total_cmp);
let at = |p: usize| values[(values.len() * p / 100).min(values.len() - 1)];
[at(10), at(50), at(90)]
@@ -130,7 +130,7 @@ struct Sample {
/// The shapes of one command buffer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Shape {
pub(super) enum Shape {
Empty,
Blit,
Draw,
@@ -142,13 +142,13 @@ enum Shape {
}
/// The device, its queue, and what the shapes use.
struct Workload {
device: Device,
queue: CommandQueue,
pub(super) struct Workload {
pub(super) device: Device,
pub(super) queue: CommandQueue,
pipeline: RenderPipelineState,
sampler: SamplerState,
buffers: Vec<Buffer>,
textures: Vec<Texture>,
pub(super) textures: Vec<Texture>,
targets: Vec<Texture>,
/// A `BGRA8Unorm` view of an `RGBA8Unorm` texture without `PixelFormatView` usage (a shadow
/// of its texels, 10.6), and an `RGBA8Unorm` one (the same image); each holds the texture.
@@ -171,7 +171,7 @@ struct Walk {
const RECT: [f32; 4] = [-0.5, -0.5, 0.5, 0.5];
impl Workload {
fn new(device: Device) -> Workload {
pub(super) fn new(device: Device) -> Workload {
let queue = device.new_command_queue().unwrap();
let ll =
Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/public/engine/tob_renders.ll");
@@ -230,13 +230,13 @@ impl Workload {
}
/// The next index into a working-set list of `len` members.
fn take(&mut self, len: usize) -> usize {
pub(super) fn take(&mut self, len: usize) -> usize {
self.next = self.next.wrapping_add(7);
self.next % len
}
/// Encode `shape` into a new command buffer: the command buffer.
fn encode(&mut self, shape: Shape) -> CommandBuffer {
pub(super) fn encode(&mut self, shape: Shape) -> CommandBuffer {
let command_buffer = self.queue.command_buffer().unwrap();
match shape {
Shape::Empty => {}
@@ -358,7 +358,7 @@ impl Workload {
/// Release two buffers and a texture of the working set and make them again, and make two
/// views of another of its textures, which the frame's passes sample through: a
/// `BGRA8Unorm` one (a shadow, 10.6) and one of the texture's own format.
fn churn(&mut self, frame: usize) {
pub(super) fn churn(&mut self, frame: usize) {
for at in [frame % LIVE_BUFFERS, (frame * 31 + 5) % LIVE_BUFFERS] {
self.buffers[at] = buffer(&self.device);
}
@@ -384,7 +384,7 @@ fn buffer(device: &Device) -> Buffer {
}
/// A `Private` square `RGBA8Unorm` texture of `usage`, `side` texels a side.
fn texture(device: &Device, side: u64, usage: TextureUsage) -> Texture {
pub(super) fn texture(device: &Device, side: u64, usage: TextureUsage) -> Texture {
let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, side, side, false);
d.usage = usage;
d.resource_options = ResourceOptions::private();
@@ -3,9 +3,19 @@
//! of its live buffers, to a bound, through the device's work counts (`Device::work_counts`, not
//! part of the API). Deterministic: they count, and time nothing.
//!
//! - **Command pools.** A command buffer that encoded nothing records its submission's barriers
//! into the spare command pool the one before gave back; before, it made one in the
//! scheduler's section, where no spare is taken.
//! - **Command pools.** A command buffer that encoded nothing takes, for any barrier its
//! submission records, the spare command pool the one before gave back; before, it made one in
//! the scheduler's section, where no spare is taken.
//! - **Empty submissions.** A command buffer that encoded nothing and waits for nothing is one
//! `vkQueueSubmit` of no `VkCommandBuffer`: its signals alone. Before, it carried one of the
//! barrier to the host, and ANV on i915 lists every `VkDeviceMemory` of the device in a kernel
//! submission of commands (47 objects at 32 host imports on an Iris Xe), where it lists two in
//! one of none.
//! - **First work rides along.** A new texture's first work (`texture/first_move.rs`) is a
//! `VkSubmitInfo` of the next submission's own `vkQueueSubmit`, a commit's or an internal one's
//! (handing its `VkImage` out): one call each, which Mesa's drivers run as one kernel submission.
//! Before, it was a `vkQueueSubmit` of its own, a second kernel submission listing every buffer
//! object of the device on ANV over i915.
//! - **Fences.** Command buffers that each end in one submission complete at their fences where
//! the driver reads their objects after their values (MoltenVK): the completion thread waits
//! for no timeline value; before, it waited for one each, which MoltenVK wakes through a shared
@@ -29,8 +39,9 @@
use super::degrade_notices::on_device;
use super::{bound_buffers, encode_case, pipeline_state, public_case, CaseResources, WAIT};
use metal2vulkan::error::RuntimeDriverDefect;
use metal2vulkan::metal::{PixelFormat, TextureUsage};
use metal2vulkan_runtime::{
Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ResourceOptions,
Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, ResourceOptions, TextureDescriptor,
};
/// A kernel whose root table searches the device's live buffers: its pointer walk reaches
@@ -70,6 +81,64 @@ fn empty_command_buffers_take_the_spare_command_pool() {
});
}
/// Empty command buffers one after another submit no `VkCommandBuffer`: each is one
/// `vkQueueSubmit` of its signals alone (the module docs).
#[test]
fn empty_command_buffers_submit_no_command_buffer() {
on_device(|device, _| {
let queue = device.new_command_queue().unwrap();
// The first takes any first work the device's creation left.
finish(&queue.command_buffer().unwrap());
let before = device.work_counts();
for _ in 0..8 {
finish(&queue.command_buffer().unwrap());
}
let after = device.work_counts();
assert_eq!(after.queue_submissions - before.queue_submissions, 8);
assert_eq!(
after.command_buffers_submitted,
before.command_buffers_submitted
);
});
}
/// A commit after a new `Private` texture was made, and the internal submission that hands
/// another's `VkImage` out, are one `vkQueueSubmit` each, the texture's first work in it: the
/// empty command buffer's submission carries the first work's `VkCommandBuffer` alone (the module
/// docs).
#[test]
fn a_new_texture_s_first_work_rides_in_the_next_submission() {
on_device(|device, _| {
let queue = device.new_command_queue().unwrap();
finish(&queue.command_buffer().unwrap());
let texture = || {
let mut descriptor =
TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 64, 64, false);
descriptor.usage = TextureUsage::SHADER_READ;
descriptor.resource_options = ResourceOptions::private();
device.new_texture(&descriptor).unwrap()
};
let before = device.work_counts();
let committed = texture();
finish(&queue.command_buffer().unwrap());
let after = device.work_counts();
assert_eq!(after.queue_submissions - before.queue_submissions, 1);
assert_eq!(
after.command_buffers_submitted - before.command_buffers_submitted,
1
);
let handed = texture();
let before = device.work_counts();
// SAFETY: the image is only read for its handle; the texture lives past the read.
let image = unsafe { handed.vk_image() };
assert!(image.is_some(), "a texture of its own image");
let after = device.work_counts();
assert_eq!(after.internal_submissions - before.internal_submissions, 1);
assert_eq!(after.queue_submissions - before.queue_submissions, 1);
drop((committed, handed));
});
}
/// Rounds of 32 command buffers encoded, then committed, together, each a fill of its own
/// buffer, released as they complete: the runtime keeps every command pool given back while the
/// device lives and reuses it, so across the rounds the command pools made stay bounded by the peak
@@ -3,7 +3,7 @@
//!
//! Each shape makes [`Shape::count`] textures of one descriptor, then commits a command buffer of
//! one 16-byte buffer fill and waits for it. The submission records the textures' first work
//! (`texture/first_move.rs`) in a `vkQueueSubmit` of its own before the fill's: Metal's pattern
//! (`texture/first_move.rs`) in a `VkSubmitInfo` of its own before the fill's: Metal's pattern
//! where Metal compresses a `Private` texture, cleared or copied, a clear of its other levels and
//! of the other `Private` ones, and zeros copied into a `Shared` one, or written by the host as it
//! is made where the device copies texels from the host. Each sample is the host's time to make the
@@ -10,6 +10,10 @@
//! (`indirect_host_steps.rs`), behind fills of a ballast: its batch waits at its gate for A's
//! earlier work to complete, and for its host step, while B commits.
//! - **Held for its submission check.** A's fill has a check that waits until B committed.
//!
//! And within one queue, commits from two threads while one's submission waits for the `VkQueue`
//! (the test holds it): the other's commits return at once, left to the submitting thread
//! (`scheduler/inbox.rs`), and every command buffer runs in commit order.
use super::degrade_notices::{assert_made_once, on_device};
use super::indirect_host_steps::{expected, Setup, HOST_STEPS};
@@ -19,6 +23,7 @@ use metal2vulkan_runtime::{
Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions, Submission,
SubmissionCheck,
};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -168,3 +173,123 @@ fn a_copy_committed_while_a_write_waits_for_its_check_holds_it() {
);
});
}
/// Command buffer `number` (from 1) of `queue`: a copy of `tracked`'s 4 bytes into `seen` at
/// `4 * (number - 1)`, then a fill of `tracked` with `number`. Its copy holds the number of the
/// command buffer that ran before it, 0 for the first.
fn numbered(queue: &CommandQueue, tracked: &Buffer, seen: &Buffer, number: u8) -> CommandBuffer {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
let at = 4 * u64::from(number - 1);
blit.copy_from_buffer_to_buffer(tracked, 0, seen, at, 4)
.unwrap();
blit.fill_buffer(tracked, 0..4, number).unwrap();
blit.end_encoding().unwrap();
command_buffer
}
/// Two threads each commit [`EACH`] command buffers of one queue while the test holds its
/// `VkQueue`: the first commit to take the scheduler's lock submits, its `vkQueueSubmit` waiting
/// for the `VkQueue`, and every commit of the other thread returns at once, left to it. Once the
/// `VkQueue` is free, the command buffers run in commit order: each that returned before another
/// started runs before it, as each one's copy of the number the one before it wrote shows.
#[test]
fn commits_made_while_another_thread_submits_return_at_once_and_run_in_commit_order() {
const EACH: u8 = 4;
on_device(|device, _| {
let queue = device.new_command_queue().unwrap();
let tracked = buffer_with(device, &[0; 4]).unwrap();
let seen = buffer_with(device, &[0xff; 4 * 2 * EACH as usize]).unwrap();
// Made and encoded first: the threads only commit them.
let lines: Vec<Vec<(u8, CommandBuffer)>> = (0..2)
.map(|line| {
(1..=EACH)
.map(|k| line * EACH + k)
.map(|number| (number, numbered(&queue, &tracked, &seen, number)))
.collect()
})
.collect();
let handed_off = || device.work_counts().commits_handed_off;
let before = handed_off();
let (held, holding) = mpsc::channel();
let (release, released) = mpsc::channel::<()>();
let holder = {
let queue = queue.clone();
std::thread::spawn(move || {
// SAFETY: the closure keeps no handle and calls nothing of the runtime's; it waits
// only for this test's release.
unsafe {
queue.with_vk_queue(|_, _| {
held.send(()).unwrap();
let _ = released.recv_timeout(WAIT);
})
}
})
};
holding.recv_timeout(WAIT).unwrap();
// Each commit's start and return on one clock.
let clock = Arc::new(AtomicU64::new(0));
let (returned, returns) = mpsc::channel();
let committers: Vec<_> = lines
.into_iter()
.map(|line| {
let (clock, returned) = (Arc::clone(&clock), returned.clone());
std::thread::spawn(move || {
let mut times = Vec::new();
for (number, command_buffer) in &line {
let start = clock.fetch_add(1, Ordering::SeqCst);
command_buffer.commit().unwrap();
let end = clock.fetch_add(1, Ordering::SeqCst);
times.push((*number, start, end));
returned.send(()).unwrap();
}
(line, times)
})
})
.collect();
drop(returned);
for commit in 1..=EACH {
returns.recv_timeout(WAIT).unwrap_or_else(|_| {
panic!(
"commit {commit} of the thread not submitting waited for the other's \
submission"
)
});
}
assert!(
handed_off() - before >= u64::from(EACH),
"the other thread's commits were left to the submitting one"
);
release.send(()).unwrap();
holder.join().unwrap();
let (mut command_buffers, mut times) = (Vec::new(), Vec::new());
for committer in committers {
let (line, line_times) = committer.join().unwrap();
command_buffers.extend(line.into_iter().map(|(_, command_buffer)| command_buffer));
times.extend(line_times);
}
completed(&command_buffers.iter().collect::<Vec<_>>());
// The order they ran in: each copy names the one before it.
let before_of = read_buffer(&seen, 0, seen.length()).unwrap();
let mut ran = vec![0u8];
while ran.len() <= 2 * EACH as usize {
let last = *ran.last().unwrap();
let next: Vec<u8> = (1..=2 * EACH)
.filter(|&number| before_of[4 * usize::from(number - 1)] == last)
.collect();
assert_eq!(next.len(), 1, "one ran after {last}: {before_of:?}");
ran.push(next[0]);
}
let place = |number: u8| ran.iter().position(|&n| n == number).unwrap();
for &(first, _, returned) in &times {
for &(later, started, _) in &times {
if returned < started {
assert!(
place(first) < place(later),
"{first} returned before {later} was committed, so runs first: {ran:?}"
);
}
}
}
});
}
@@ -4,9 +4,10 @@
//!
//! A submission handler runs once the command buffer's last batch reached its `VkQueue`, on the
//! thread that submitted it, before the command buffer is `Scheduled`: inside `commit` where the
//! commit submits it (its waits met, nothing earlier of its queue held), on the scheduler thread
//! where an event the host raised releases it, and inside another `commit` whose GPU signal
//! releases it. Never for a command buffer that fails before its last batch is submitted.
//! commit submits it (its waits met, nothing earlier of its queue held, no other thread
//! submitting), on the scheduler thread where an event the host raised releases it, and inside
//! another `commit` whose GPU signal releases it, or that was submitting as it was committed.
//! Never for a command buffer that fails before its last batch is submitted.
//!
//! Metal's answers (EV SUB-sched1-m4: an M4, macOS 27.0.1): `commit` returns before the command
//! buffer is scheduled, on Metal's own thread; its status reads `Scheduled` just before its first
@@ -0,0 +1,448 @@
//! What a compositor's command buffers cost the driver's submission path on the device the cfg
//! selects, without the validation layer: report only, in release builds, to weigh the runtime's
//! submissions before and after a change to them.
//!
//! The workload is `commit_costs`'s guest window server's (its working set, its blits, passes and
//! pointer walk), with the caller's host memory beside it: [`IMPORTS`] no-copy buffers over pages
//! of the process's own, which uploads copy into textures of the working set, and of which
//! [`IMPORTS_A_FRAME`] are released and made again over fresh pages before each frame. Printed as
//! `SUBMIT-COST` lines:
//!
//! - **One command buffer at a time** (`serial`), each shape [`SERIAL`] times after [`WARM`]
//! untimed: an empty command buffer, a blit encoder, a render pass, a pointer walk, an upload
//! out of a host import, and a render pass committed after a texture of the working set was made
//! again (its new resource's first work rides with the commit, `texture/first_move.rs`).
//! - **Frames** (`frames`): [`FRAMES`] frames of [`PER_FRAME`] command buffers committed in a row
//! and waited for at the frame's end: passes and blits alternating, a pointer walk, two uploads
//! and an empty command buffer, after `commit_costs`'s churn of the working set and the imports'.
//! - **Frames beside a busy scheduler thread** (`busy scheduler`): the frames again, while a
//! thread of the test's keeps the device's scheduler thread submitting, as a consumer's events
//! do: a command buffer of a queue of its own that waits for an event, committed, then released
//! by the host's signal of the event, which wakes the scheduler's thread to submit it, every
//! [`SIDE_PACE`]. The committing thread's time off the CPU in `commit` (its wall time less its
//! CPU time: waits for a lock, and for the CPU), per commit and per frame, the commits a frame
//! that were off it over [`WAITED_US`], and the commits a frame of either thread handed off to
//! another's pass (`WorkCounts::commits_handed_off`).
//!
//! For the first two: the runtime's `vkQueueSubmit` and `vkQueueBindSparse` calls and the `VkCommandBuffer`s
//! they submitted per command buffer (`WorkCounts::queue_submissions`,
//! `command_buffers_submitted`), the committing thread's CPU time in `commit` (which submits
//! what is ready then, `scheduler`), and the process's CPU time per command buffer. Where the i915
//! counter (`scripts/i915-execbuffers/counter.c`) is preloaded: the kernel's execbuffers per
//! command buffer, the buffer objects each lists, by origin (host imports, the runtime's 64-MiB
//! blocks, the rest: ANV's own and the runtime's other blocks), and the microseconds each spent
//! in the ioctl. And the runtime's live `VkDeviceMemory` blocks by kind once the frames ran.
//!
//! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`.
use super::commit_costs::{
percentiles, process_cpu_us, since, texture, Shape, Workload, TEXTURE_SIDE,
};
use super::host_memory::{no_copy, Mapping};
use super::{validated_device_with, Messages, ScratchCache, WAIT};
use crate::gpu::TEST_DEVICE;
use metal2vulkan::metal::TextureUsage;
use metal2vulkan_runtime::{
BlitOption, Buffer, CommandBuffer, CommandBufferStatus, Device, EventRef, Origin,
ResourceOptions, Size, WorkCounts,
};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
/// The host imports live at once.
const IMPORTS: usize = 32;
/// The bytes of each: a 256-KiB guest surface.
const IMPORT_BYTES: usize = 256 << 10;
/// The imports released and made again before each frame.
const IMPORTS_A_FRAME: usize = 2;
/// Command buffers of each serial shape run untimed first.
const WARM: usize = 20;
/// Command buffers of each serial shape measured.
const SERIAL: usize = 200;
/// Frames measured.
const FRAMES: usize = 60;
/// Command buffers a frame.
const PER_FRAME: usize = 24;
/// The pause between the batches the side thread has the scheduler's thread submit.
const SIDE_PACE: Duration = Duration::from_micros(100);
/// A commit off the CPU for longer than this, in microseconds, waited.
const WAITED_US: f64 = 20.0;
/// What one command buffer of the lane does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
/// One of `commit_costs`'s shapes.
Shape(Shape),
/// A blit of a 64x64 texel square out of a host import into a texture of the working set.
Upload,
/// A render pass, committed after a texture of the working set was made again.
Fresh,
}
/// The counts of the i915 counter (`scripts/i915-execbuffers/counter.c`), as it exports them.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
struct Execbuffers {
execbuffers: u64,
objects: u64,
nanos: u64,
userptr: u64,
prime: u64,
block64: u64,
created_other: u64,
unknown: u64,
max_objects: u64,
min_objects: u64,
}
impl Execbuffers {
/// The counter's counts so far, where it is loaded.
fn read() -> Option<Execbuffers> {
// SAFETY: a lookup of a symbol by its name among the process's loaded objects.
let found = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"m2v_i915_shim_counts".as_ptr()) };
if found.is_null() {
return None;
}
// SAFETY: the counter exports the symbol as a function of this signature.
let read = unsafe {
std::mem::transmute::<*mut libc::c_void, extern "C" fn(*mut Execbuffers)>(found)
};
let mut counts = Execbuffers::default();
read(&mut counts);
Some(counts)
}
/// What was counted from `before` to `self`, per `commits` command buffers, printed.
fn since(&self, before: &Execbuffers, commits: usize) -> String {
let execbuffers = self.execbuffers - before.execbuffers;
let each = |count: u64| count as f64 / execbuffers.max(1) as f64;
format!(
"; {:.2} execbuffers per command buffer, {:.1} objects each (host imports {:.1}, \
64-MiB blocks {:.1}, dma-bufs {:.1}, other {:.1}), {:.1} us each in the ioctl",
execbuffers as f64 / commits as f64,
each(self.objects - before.objects),
each(self.userptr - before.userptr),
each(self.block64 - before.block64),
each(self.prime - before.prime),
each((self.created_other - before.created_other) + (self.unknown - before.unknown)),
(self.nanos - before.nanos) as f64 / 1e3 / execbuffers.max(1) as f64,
)
}
}
/// The calling thread's CPU time so far, in microseconds.
fn thread_cpu_us() -> f64 {
let mut now = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
// SAFETY: `now` is a valid timespec for the call to fill.
let read = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut now) };
assert_eq!(read, 0, "the thread's CPU clock");
now.tv_sec as f64 * 1e6 + now.tv_nsec as f64 / 1e3
}
/// A no-copy buffer over pages of its own, which its deallocator unmaps.
fn import(work: &Workload) -> Buffer {
let pages = Mapping::anonymous(IMPORT_BYTES);
pages.fill(0x5a);
let pointer = pages.pointer();
// SAFETY: the pages are this process's, mapped read and write, and unmapped only by the
// deallocator, once the runtime let go of them.
unsafe {
no_copy(
&work.device,
pointer,
IMPORT_BYTES,
ResourceOptions::shared(),
Some(Box::new(move |_, _| drop(pages))),
)
}
.unwrap()
}
/// The workload and its host imports.
struct Lane {
work: Workload,
imports: Vec<Buffer>,
next: usize,
}
impl Lane {
/// Encode `kind` into a new command buffer: the command buffer.
fn encode(&mut self, kind: Kind) -> CommandBuffer {
match kind {
Kind::Shape(shape) => self.work.encode(shape),
Kind::Upload => {
self.next = (self.next + 5) % IMPORTS;
let to = self.work.take(self.work.textures.len());
let command_buffer = self.work.queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.copy_from_buffer_to_texture(
&self.imports[self.next],
0,
TEXTURE_SIDE * 4,
TEXTURE_SIDE * TEXTURE_SIDE * 4,
Size::new(TEXTURE_SIDE, TEXTURE_SIDE, 1),
&self.work.textures[to],
0,
0,
Origin::new(0, 0, 0),
BlitOption::None,
)
.unwrap();
blit.end_encoding().unwrap();
command_buffer
}
Kind::Fresh => {
let at = self.work.take(self.work.textures.len());
let rt = TextureUsage::RENDER_TARGET.union(TextureUsage::SHADER_READ);
self.work.textures[at] = texture(&self.work.device, TEXTURE_SIDE, rt);
self.work.encode(Shape::Draw)
}
}
}
/// Release [`IMPORTS_A_FRAME`] imports and make them again over fresh pages.
fn churn_imports(&mut self, frame: usize) {
for at in 0..IMPORTS_A_FRAME {
let at = (frame * IMPORTS_A_FRAME + at) % IMPORTS;
self.imports[at] = import(&self.work);
}
}
}
/// What a run of `commits` command buffers cost, from the counts before it.
struct Run {
counts: WorkCounts,
execbuffers: Option<Execbuffers>,
process: f64,
}
impl Run {
fn start(lane: &Lane) -> Run {
Run {
counts: lane.work.device.work_counts(),
execbuffers: Execbuffers::read(),
process: process_cpu_us(),
}
}
/// Print what the run cost as `what`: `commits` command buffers, whose `commit` calls took
/// `commit_cpu` microseconds of the committing thread's time each.
fn print(&self, lane: &Lane, what: &str, commits: usize, commit_cpu: Vec<f64>) {
let process = (process_cpu_us() - self.process) / commits as f64;
let after = lane.work.device.work_counts();
let per = |after: u64, before: u64| (after - before) as f64 / commits as f64;
let [_, cpu, cpu_90] = percentiles(commit_cpu);
let execbuffers = Execbuffers::read()
.zip(self.execbuffers)
.map(|(after, before)| after.since(&before, commits))
.unwrap_or_default();
eprintln!(
"SUBMIT-COST {}: {what}: {:.2} vkQueueSubmit calls and {:.2} VkCommandBuffers per \
command buffer; commit cpu {cpu:.1} (p90 {cpu_90:.1}) us; process cpu {process:.1} us \
per command buffer{execbuffers}",
lane.work.device.name(),
per(after.queue_submissions, self.counts.queue_submissions),
per(
after.command_buffers_submitted,
self.counts.command_buffers_submitted
),
);
}
}
/// Commit `command_buffer`: the committing thread's CPU time in the call, in microseconds.
fn commit(command_buffer: &CommandBuffer) -> f64 {
timed_commit(command_buffer).0
}
/// Commit `command_buffer`: the committing thread's CPU time in the call and the call's wall
/// time, in microseconds.
fn timed_commit(command_buffer: &CommandBuffer) -> (f64, f64) {
let (wall, start) = (Instant::now(), thread_cpu_us());
command_buffer.commit().unwrap();
(thread_cpu_us() - start, since(wall))
}
/// One frame: each commit's CPU and wall time in `commit`, and the frame's wall time, in
/// microseconds.
struct Frame {
commits: Vec<(f64, f64)>,
wall: f64,
}
/// [`FRAMES`] frames of the lane (the module docs).
fn frames(lane: &mut Lane) -> Vec<Frame> {
(0..FRAMES)
.map(|frame| {
lane.work.churn(frame);
lane.churn_imports(frame);
let begin = Instant::now();
let mut last = None;
let mut commits = Vec::new();
for at in 0..PER_FRAME {
let kind = match at {
0 => Kind::Shape(Shape::DrawShadowedView),
1 => Kind::Shape(Shape::Walk),
2 => Kind::Shape(Shape::DrawOwnFormatView),
3 | 9 => Kind::Upload,
5 => Kind::Shape(Shape::Empty),
_ if at % 2 == 0 => Kind::Shape(Shape::Draw),
_ => Kind::Shape(Shape::Blit),
};
let command_buffer = lane.encode(kind);
commits.push(timed_commit(&command_buffer));
last = Some(command_buffer);
}
let last = last.expect("a frame's command buffers");
last.wait_until_completed_for(WAIT).unwrap();
assert_eq!(last.status(), CommandBufferStatus::Completed);
Frame {
commits,
wall: since(begin),
}
})
.collect()
}
/// The committing thread's time off the CPU in `commit` over `frames`, printed as `what`, with
/// the commits of any thread `handed_off` to another's pass meanwhile.
fn print_off_cpu(lane: &Lane, what: &str, frames: &[Frame], handed_off: u64) {
let commits = frames.iter().flat_map(|frame| &frame.commits);
let off = |&(cpu, wall): &(f64, f64)| (wall - cpu).max(0.0);
let [_, wall, wall_90] = percentiles(commits.clone().map(|commit| commit.1).collect());
let [_, each, each_90] = percentiles(commits.clone().map(off).collect());
let per_frame = frames
.iter()
.map(|frame| frame.commits.iter().map(off).sum::<f64>());
let [_, frame, frame_90] = percentiles(per_frame.collect());
let waited = commits.filter(|&commit| off(commit) > WAITED_US).count();
eprintln!(
"SUBMIT-COST {}: {what}: commit wall {wall:.1} (p90 {wall_90:.1}) us, off cpu {each:.1} \
(p90 {each_90:.1}) us; off cpu a frame {frame:.0} (p90 {frame_90:.0}) us, {:.2} commits \
a frame off it over {WAITED_US} us; {:.2} commits a frame handed off",
lane.work.device.name(),
waited as f64 / frames.len() as f64,
handed_off as f64 / frames.len() as f64,
);
}
/// The commits handed off to another thread's pass so far (`WorkCounts::commits_handed_off`).
fn handed_off(lane: &Lane) -> u64 {
lane.work.device.work_counts().commits_handed_off
}
/// Keep the device's scheduler thread busy until `stop` (the module docs): the batches it had
/// it submit.
fn side_load(device: &Device, stop: &AtomicBool) -> u64 {
let queue = device.new_command_queue().unwrap();
let event = device.new_shared_event().unwrap();
let target = device.new_buffer(4096, ResourceOptions::private()).unwrap();
let mut flight = VecDeque::new();
let mut value = 0;
while !stop.load(Ordering::Relaxed) {
value += 1;
let command_buffer = queue.command_buffer().unwrap();
(command_buffer.encode_wait_for_event(EventRef::from(&event), value)).unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(&target, 0..4096, value as u8).unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
// Held for the event: the host's signal wakes the scheduler's thread to submit it.
event.set_signaled_value(value);
command_buffer.wait_until_scheduled().unwrap();
flight.push_back(command_buffer);
if flight.len() > 4 {
let oldest = flight.pop_front().unwrap();
oldest.wait_until_completed_for(WAIT).unwrap();
}
std::thread::sleep(SIDE_PACE);
}
for command_buffer in flight {
command_buffer.wait_until_completed_for(WAIT).unwrap();
}
value
}
/// The submission path's costs, printed (the module docs).
#[test]
#[ignore = "a measurement, not a check: run by name with --run-ignored all"]
fn submit_costs() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.layers.clear();
// A consumer's device keeps no execution record.
options.record_executions = false;
})
.unwrap();
let work = Workload::new(device);
let imports = (0..IMPORTS).map(|_| import(&work)).collect();
let mut lane = Lane {
work,
imports,
next: 0,
};
let kinds = [
Kind::Shape(Shape::Empty),
Kind::Shape(Shape::Blit),
Kind::Shape(Shape::Draw),
Kind::Shape(Shape::Walk),
Kind::Upload,
Kind::Fresh,
];
for kind in kinds {
let run_one = |lane: &mut Lane| {
let command_buffer = lane.encode(kind);
let cpu = commit(&command_buffer);
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
cpu
};
for _ in 0..WARM {
run_one(&mut lane);
}
let run = Run::start(&lane);
let cpu: Vec<f64> = (0..SERIAL).map(|_| run_one(&mut lane)).collect();
run.print(&lane, &format!("serial {kind:?}"), SERIAL, cpu);
}
let run = Run::start(&lane);
let before = handed_off(&lane);
let plain = frames(&mut lane);
let cpu = plain.iter().flat_map(|frame| &frame.commits);
run.print(
&lane,
"frames",
FRAMES * PER_FRAME,
cpu.map(|c| c.0).collect(),
);
print_off_cpu(&lane, "frames", &plain, handed_off(&lane) - before);
let [low, wall, high] = percentiles(plain.iter().map(|frame| frame.wall).collect());
let counts = lane.work.device.work_counts();
eprintln!(
"SUBMIT-COST {}: frames: frame {wall:.0} (p10 {low:.0}, p90 {high:.0}) us; live memory \
blocks: {} pooled, {} pooled empty, {} dedicated, {} host imports",
lane.work.device.name(),
counts.memory_blocks_live,
counts.empty_memory_blocks_live,
counts.dedicated_memory_blocks_live,
counts.host_imports_live,
);
let before = handed_off(&lane);
let stop = AtomicBool::new(false);
let device = lane.work.device.clone();
let (busy, released) = std::thread::scope(|scope| {
let side = scope.spawn(|| side_load(&device, &stop));
let busy = frames(&mut lane);
stop.store(true, Ordering::Relaxed);
(busy, side.join().unwrap())
});
let what = format!(
"busy scheduler, {:.1} batches a frame released to its thread",
released as f64 / FRAMES as f64
);
print_off_cpu(&lane, &what, &busy, handed_off(&lane) - before);
}
+202
View File
@@ -0,0 +1,202 @@
// A counter of the i915 kernel submissions a process makes, loaded with LD_PRELOAD: each
// DRM_IOCTL_I915_GEM_EXECBUFFER2, the buffer objects it lists (by how each was made: created with
// its size, a userptr import, a dma-buf import) and the time the ioctl took, by thread. It reads
// the ioctls' arguments and results and changes nothing. ANV on i915 lists every VkDeviceMemory
// of the device, and its own buffer objects, in every execbuffer (Mesa 26.2.4,
// src/intel/vulkan/i915/anv_batch_chain.c, setup_execbuf_for_cmd_buffers), and the kernel's cost
// of each is per object.
//
// gcc -O2 -Wall -shared -fPIC -o counter.so counter.c
// LD_PRELOAD=$PWD/counter.so M2V_I915_SHIM_OUT=counts.txt <program>
//
// At exit it appends its totals, the objects' origins and sizes, and the execbuffers per thread to
// M2V_I915_SHIM_OUT (stderr without it). A program reads the totals so far through the exported
// m2v_i915_shim_counts (the validation lane runtime_lane::submit_costs does).
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <drm/drm.h>
#include <drm/i915_drm.h>
enum origin { O_NONE = 0, O_CREATE, O_CREATE_EXT, O_USERPTR, O_PRIME, O_COUNT };
static const char *origin_names[] = {"unknown", "create", "create_ext", "userptr", "prime"};
#define MAX_HANDLES (1u << 20)
#define MAX_FDS 8
struct bo { uint64_t size; uint8_t origin; };
static struct bo *tables[MAX_FDS];
static int fds[MAX_FDS];
static int nfds;
struct m2v_shim_counts {
uint64_t execbuffers, objects, nanos, userptr, prime, block64, created_other, unknown,
max_objects, min_objects;
};
static struct m2v_shim_counts counts = {.min_objects = UINT64_MAX};
// (origin, size) histogram of objects listed by execbuffers.
#define HIST 4096
struct hist { uint64_t size; uint8_t origin; uint64_t seen; };
static struct hist hist[HIST];
static int nhist;
// Objects-per-execbuffer histogram.
static uint64_t per_eb[2048];
// Execbuffers per thread.
struct tidc { pid_t tid; uint64_t n; uint64_t nanos; char comm[32]; };
static struct tidc tids[64];
static int ntids;
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static int (*real_ioctl)(int, unsigned long, ...);
static struct bo *table_for(int fd, int make) {
for (int i = 0; i < nfds; i++)
if (fds[i] == fd) return tables[i];
if (!make || nfds == MAX_FDS) return NULL;
tables[nfds] = calloc(MAX_HANDLES, sizeof(struct bo));
fds[nfds] = fd;
return tables[nfds++];
}
static uint64_t now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ull + ts.tv_nsec;
}
static void note(int fd, uint32_t handle, uint64_t size, uint8_t origin) {
pthread_mutex_lock(&mu);
struct bo *t = table_for(fd, 1);
if (t && handle < MAX_HANDLES) { t[handle].size = size; t[handle].origin = origin; }
pthread_mutex_unlock(&mu);
}
static void hist_add(uint64_t size, uint8_t origin) {
for (int i = 0; i < nhist; i++)
if (hist[i].size == size && hist[i].origin == origin) { hist[i].seen++; return; }
if (nhist < HIST) { hist[nhist].size = size; hist[nhist].origin = origin; hist[nhist].seen = 1; nhist++; }
}
void m2v_i915_shim_counts(struct m2v_shim_counts *out) {
pthread_mutex_lock(&mu);
*out = counts;
pthread_mutex_unlock(&mu);
}
int ioctl(int fd, unsigned long request, ...) {
va_list ap;
va_start(ap, request);
void *arg = va_arg(ap, void *);
va_end(ap);
if (!real_ioctl) real_ioctl = (int (*)(int, unsigned long, ...))dlsym(RTLD_NEXT, "ioctl");
if (request == DRM_IOCTL_I915_GEM_EXECBUFFER2 || request == DRM_IOCTL_I915_GEM_EXECBUFFER2_WR) {
struct drm_i915_gem_execbuffer2 *eb = arg;
uint64_t t0 = now_ns();
int r = real_ioctl(fd, request, arg);
uint64_t dt = now_ns() - t0;
pid_t tid = (pid_t)syscall(SYS_gettid);
pthread_mutex_lock(&mu);
struct bo *t = table_for(fd, 1);
uint32_t n = eb->buffer_count;
counts.execbuffers++;
counts.objects += n;
counts.nanos += dt;
if (n > counts.max_objects) counts.max_objects = n;
if (n < counts.min_objects) counts.min_objects = n;
per_eb[n < 2047 ? n : 2047]++;
struct drm_i915_gem_exec_object2 *objs = (void *)(uintptr_t)eb->buffers_ptr;
for (uint32_t i = 0; i < n; i++) {
uint32_t h = objs[i].handle;
struct bo b = (t && h < MAX_HANDLES) ? t[h] : (struct bo){0, O_NONE};
switch (b.origin) {
case O_USERPTR: counts.userptr++; break;
case O_PRIME: counts.prime++; break;
case O_CREATE: case O_CREATE_EXT:
if (b.size == (64ull << 20)) counts.block64++; else counts.created_other++;
break;
default: counts.unknown++;
}
hist_add(b.size, b.origin);
}
int found = 0;
for (int i = 0; i < ntids; i++)
if (tids[i].tid == tid) { tids[i].n++; tids[i].nanos += dt; found = 1; break; }
if (!found && ntids < 64) {
tids[ntids].tid = tid; tids[ntids].n = 1; tids[ntids].nanos = dt;
char path[64];
snprintf(path, sizeof path, "/proc/self/task/%d/comm", tid);
FILE *f = fopen(path, "r");
if (f) { if (fgets(tids[ntids].comm, sizeof tids[ntids].comm, f)) tids[ntids].comm[strcspn(tids[ntids].comm, "\n")] = 0; fclose(f); }
ntids++;
}
pthread_mutex_unlock(&mu);
return r;
}
int r = real_ioctl(fd, request, arg);
if (r != 0) return r;
switch (request) {
case DRM_IOCTL_I915_GEM_CREATE: {
struct drm_i915_gem_create *c = arg;
note(fd, c->handle, c->size, O_CREATE);
break;
}
case DRM_IOCTL_I915_GEM_CREATE_EXT: {
struct drm_i915_gem_create_ext *c = arg;
note(fd, c->handle, c->size, O_CREATE_EXT);
break;
}
case DRM_IOCTL_I915_GEM_USERPTR: {
struct drm_i915_gem_userptr *u = arg;
note(fd, u->handle, u->user_size, O_USERPTR);
break;
}
case DRM_IOCTL_PRIME_FD_TO_HANDLE: {
struct drm_prime_handle *p = arg;
note(fd, p->handle, 0, O_PRIME);
break;
}
case DRM_IOCTL_GEM_CLOSE: {
struct drm_gem_close *c = arg;
pthread_mutex_lock(&mu);
struct bo *t = table_for(fd, 0);
if (t && c->handle < MAX_HANDLES) t[c->handle] = (struct bo){0, O_NONE};
pthread_mutex_unlock(&mu);
break;
}
}
return r;
}
static int by_seen(const void *a, const void *b) {
const struct hist *x = a, *y = b;
return x->seen < y->seen ? 1 : x->seen > y->seen ? -1 : 0;
}
__attribute__((destructor)) static void report(void) {
if (!counts.execbuffers) return;
const char *out = getenv("M2V_I915_SHIM_OUT");
FILE *f = out ? fopen(out, "a") : stderr;
if (!f) f = stderr;
fprintf(f, "I915-SHIM pid %d: %llu execbuffers, %llu objects (%.1f each, min %llu max %llu), %.1f us each in the ioctl\n",
getpid(), (unsigned long long)counts.execbuffers, (unsigned long long)counts.objects,
(double)counts.objects / counts.execbuffers, (unsigned long long)counts.min_objects,
(unsigned long long)counts.max_objects, counts.nanos / 1e3 / counts.execbuffers);
qsort(hist, nhist, sizeof hist[0], by_seen);
for (int i = 0; i < nhist && i < 60; i++)
fprintf(f, "I915-SHIM %-10s size %10llu: %.2f per execbuffer\n", origin_names[hist[i].origin],
(unsigned long long)hist[i].size, (double)hist[i].seen / counts.execbuffers);
for (int i = 0; i < ntids; i++)
fprintf(f, "I915-SHIM thread %d %s: %llu execbuffers, %.1f us each\n", tids[i].tid, tids[i].comm,
(unsigned long long)tids[i].n, tids[i].nanos / 1e3 / tids[i].n);
for (int i = 0; i < 2048; i++)
if (per_eb[i]) fprintf(f, "I915-SHIM %d objects: %llu execbuffers\n", i, (unsigned long long)per_eb[i]);
if (f != stderr) fclose(f);
}