rt: a release waits for the submission that carried its own commits, never a later one

What: Work::settled(n), once every command buffer committed up to n is
submitted, answers the progress value of the last submission that carried
one of them, or 0 where each was seen complete. It answered the progress of
the last submission made at the moment it was asked. The answer comes from a
record of each command buffer's place in the commit order and its
submission's value, added as the submission closes and dropped as the submit
thread sees it complete, so it holds at most the command buffers the queues
hold at once. The pool notes a release's mark (and an import's or export's
free's) under its lock, so the marks rise along its FIFO: no entry behind one
that holds is over, and the block-maker thread, taking each ripe head in
turn, hands on every entry whose wait is over in one round.

Why: the block-maker checks only the FIFO's head, and the head's Commits(n)
became Progress(the newest submission at the check). On a GPU that never
idles each entry bound itself to a submission committed after it, and left
one submit-to-complete latency after the one before it: the backlog grew at
the program's release rate and drained only when the GPU idled. The consumer
measured it on an RTX 3090 (walk m3-max-63277: releases_waiting 129,428 then
400,454 a minute later, live textures 65,729 then 201,339, until
vkCreateImageView failed), and its repro on the runtime's API failed on an
RTX 2080 (m3-max-63291: 2,986 of 3,000 released textures held under three
1 GiB fills in flight). It is neither vendor- nor ICB-specific: a GPU that
idles each frame drains the FIFO at each idle. A release still waits for
every command buffer committed before it, and only for those; nothing is
capped or freed early. The same holds for imported and exported blocks'
frees (the `owned` FIFO) and idle allocations' frees.

Tests:
- rt (argument_tier): a texture released under a command buffer held at an
  event wait; the event is set and that command buffer completes; a second
  command buffer, committed after, is held between its close and its submit
  by its scheduled handler. The release's mark must answer a completed
  submission, and the texture must go while the second is held. The order is
  forced, with no timing in it.
- harness: own row releases_under_work, the standing check for a busy GPU.
  200 iterations each make 8 Private 64x64 textures and a view of each,
  commit a command buffer that writes 1 GiB, release them, and wait for the
  command buffer two before, so three are in flight. releases_waiting, live
  textures and texture block bytes are read with that work in flight at
  iterations 100 and 200, and none may grow by more than eight iterations'
  worth. A harness test runs the row on the cfg's device.

How verified (tree of c4d09750ef on fb466b4519; development since then
changed only the validation crate and docs/VALIDATION.md):
- Before, at fb466b4519 with only the tests (probe 628da990ea / fd2050cfa8,
  lavapipe, m3-max-63330 and m3-max-63336): the rt test fails with "the mark
  answers Some(2), with 1 completed".
- After, lavapipe suites of metal2vulkan-runtime and metal2vulkan-harness
  under m2v_cpu_icd (m3-max-63335): 605 passed. The rt test passes ("2
  releases gone under a later submission"), and so does the harness row
  (releases_waiting 41 -> 32, textures 21 -> 16).
- Lint (m3-max-63334): fmt; clippy -D warnings plain, under m2v_gpu and
  under m2v_cpu_icd; workspace Rustdoc -D warnings.
- The harness row also passed before the fix on lavapipe (m3-max-63336:
  releases_waiting 64 -> 32), so lavapipe does not exercise the busy GPU this
  row is for. Its before/after on a GPU is a separate run.
This commit is contained in:
Anees Iqbal committed 2026-11-21 05:47:13 -08:00
1 parent cf87db0fb7
commit ce998742d7
8 files changed
+294 -18

No files matched your search

+14 -1
View File
@@ -259,10 +259,19 @@ pub enum OwnRow {
/// surface caches), in rounds that take turns; the medians of each kind, in microseconds,
/// are its times.
ExportSubmitCost,
/// Textures released while the GPU runs throughout: 200 iterations, each making 8 `Private`
/// 64 by 64 textures at indices, with a view of each, committing a command buffer that writes
/// 1 GiB (four fills of a 256 MiB `Private` buffer), releasing the textures and views, then
/// waiting for the command buffer committed two before it, so that three are in flight. The
/// releases waiting, the live textures and the texture blocks' bytes, read after the 100th
/// and the 200th iteration with that work in flight, are each to grow by no more than eight
/// iterations' worth between the two reads: a release that waits for work committed after it
/// grows them, and fails the row.
ReleasesUnderWork,
}
/// The rows of one runtime's own.
pub const OWN_ROWS: [Own; 3] = [
pub const OWN_ROWS: [Own; 4] = [
Own {
name: "idle_frees",
row: OwnRow::IdleFrees,
@@ -275,6 +284,10 @@ pub const OWN_ROWS: [Own; 3] = [
name: "export_submit_cost",
row: OwnRow::ExportSubmitCost,
},
Own {
name: "releases_under_work",
row: OwnRow::ReleasesUnderWork,
},
];
/// The kernel of a compute pipeline state row's warm-up
+4 -1
View File
@@ -150,7 +150,10 @@
//! began 25 ms or more past its allocation's idle age fails the row, and they record no time.
//! `export_submit_cost` records a submission's median time with no export and with 64 live
//! (`none` and `exports_64`), which the matrix judges as it judges a time of one runtime: as a
//! cross-GPU outlier against the leg's base.
//! cross-GPU outlier against the leg's base. `releases_under_work` holds its check alone, and
//! records no time: what textures released while three command buffers keep the GPU running
//! leave waiting, read with that work in flight, is to stay flat from its 100th iteration to its
//! 200th.
use std::ptr::NonNull;
+144
View File
@@ -17,6 +17,10 @@
//! barrier, on the presenting queue, waited for by a fence before the next, in rounds that take
//! turns with no export and with 64 live; its times are the medians of the rounds' medians, in
//! microseconds. A device that exports no handle reports so and times nothing.
//!
//! The releases row reads the runtime's gauges with its work in flight, never at an idle device:
//! a release that waits for more than the work committed before it is freed only as the GPU idles,
//! so a read at idle would not see it wait.
use super::error;
use crate::authored::OwnRow;
@@ -24,6 +28,7 @@ use crate::run::OwnReport;
use crate::Result;
use ash::vk;
use metal2vulkan_runtime as rt;
use std::collections::VecDeque;
use std::thread;
use std::time::{Duration, Instant};
@@ -62,6 +67,25 @@ const SUBMITS: usize = 200;
/// The rounds of the export row.
const ROUNDS: usize = 3;
/// The iterations of the releases row, and those after which it reads the gauges.
const ITERATIONS: u32 = 200;
const READ_AFTER: [u32; 2] = [100, 200];
/// The command buffers the releases row keeps in flight.
const IN_FLIGHT: usize = 3;
/// The textures each iteration of the releases row makes, each with a view, and their side.
const TEXTURES: u32 = 8;
const SIDE: u32 = 64;
/// The bytes of the buffer the releases row's command buffers write, and the fills of it each
/// makes: 1 GiB written a command buffer.
const FILL_LEN: u64 = 256 << 20;
const FILLS: u32 = 4;
/// The iterations' worth a gauge of the releases row may grow from its first read to its second.
const FLAT_ITERATIONS: u64 = 8;
/// `row` on a device of its own on `physical`.
pub(super) fn run(physical: &rt::PhysicalDevice, row: OwnRow) -> Result<OwnReport> {
let device = rt::Device::new(physical, rt::DeviceOptions::default()).map_err(error)?;
@@ -69,9 +93,129 @@ pub(super) fn run(physical: &rt::PhysicalDevice, row: OwnRow) -> Result<OwnRepor
OwnRow::IdleFrees => idle_frees(&device, false),
OwnRow::IdleFreesUnderCommits => idle_frees(&device, true),
OwnRow::ExportSubmitCost => export_submit_cost(&device),
OwnRow::ReleasesUnderWork => releases_under_work(&device),
}
}
/// The releases row ([`OwnRow::ReleasesUnderWork`]).
fn releases_under_work(device: &rt::Device) -> Result<OwnReport> {
let counters = device.counters();
let class = rt::IndexClass::Texture;
let range = class.range();
(device.grant_indices(class, range.start, range.end - range.start)).map_err(error)?;
let block = (device.take_block(rt::MemoryClass::Private, FILL_LEN)).map_err(error)?;
let buffer = (device.new_buffer(block.id, 0, FILL_LEN, None)).map_err(error)?;
let queue = device.new_command_queue(IN_FLIGHT as u32).map_err(error)?;
let mut descriptor = rt::TextureDescriptor::new(
rt::TextureType::Type2D,
rt::PixelFormat::RGBA8Unorm,
SIDE,
SIDE,
);
descriptor.usage = rt::TextureUsage::SHADER_READ;
descriptor.storage_mode = rt::StorageMode::Private;
let mut indices = range;
let mut index = || indices.next().ok_or("the texture indices ran out");
// The command buffer at the front, waited for, is to have completed.
let completed = |command_buffer: rt::CommandBuffer| -> Result<()> {
command_buffer.wait_until_completed().map_err(error)?;
match command_buffer.status() {
rt::CommandBufferStatus::Completed => Ok(()),
status => Err(format!("a command buffer ended {status:?}").into()),
}
};
let mut in_flight = VecDeque::with_capacity(IN_FLIGHT);
// The live textures and the texture blocks' bytes one iteration's textures and views add.
let mut each = None;
let mut reads = Vec::new();
for iteration in 1..=ITERATIONS {
let before = counters.gauges();
let mut made = Vec::with_capacity(2 * TEXTURES as usize);
for _ in 0..TEXTURES {
let texture = (device.new_texture(&descriptor, Some(index()?))).map_err(error)?;
let format = rt::PixelFormat::RGBA8Unorm;
let view = texture.new_texture_view(
format,
rt::TextureType::Type2D,
0..1,
0..1,
Some(index()?),
);
made.push(view.map_err(error)?);
made.push(texture);
}
// Read at the first iteration, before anything is released.
each.get_or_insert_with(|| {
let after = counters.gauges();
(
after.textures - before.textures,
after.texture_block_bytes - before.texture_block_bytes,
)
});
let command_buffer = queue.command_buffer().map_err(error)?;
let mut encoder = command_buffer.blit_command_encoder().map_err(error)?;
for _ in 0..FILLS {
(encoder.fill_buffer(&buffer, 0..FILL_LEN, iteration as u8)).map_err(error)?;
}
encoder.end_encoding();
command_buffer.commit().map_err(error)?;
in_flight.push_back(command_buffer);
// Released under the work in flight, the command buffer just committed among it.
drop(made);
if in_flight.len() == IN_FLIGHT {
completed(in_flight.pop_front().ok_or("a command buffer in flight")?)?;
}
if READ_AFTER.contains(&iteration) {
reads.push(counters.gauges());
}
}
for command_buffer in in_flight {
completed(command_buffer)?;
}
drop((buffer, block));
let (textures, bytes) = each.ok_or("no iteration ran")?;
let [first, second] = [&reads[0], &reads[1]];
// Each texture and view leaves its image or views and its index.
let gauges = [
(
"releases_waiting",
first.releases_waiting,
second.releases_waiting,
2 * textures,
),
("textures", first.textures, second.textures, textures),
(
"texture_block_bytes",
first.texture_block_bytes,
second.texture_block_bytes,
bytes,
),
];
let shown = (gauges.iter())
.map(|(gauge, first, second, _)| format!("{gauge} {first} -> {second}"))
.collect::<Vec<_>>()
.join(", ");
let [at, then] = READ_AFTER;
let line = format!(
"{shown} from iteration {at} to {then}, {IN_FLIGHT} command buffers writing 1 GiB each in flight"
);
let grown: Vec<&str> = (gauges.iter())
.filter(|(_, first, second, each)| *second > first + each * FLAT_ITERATIONS)
.map(|(gauge, ..)| *gauge)
.collect();
if !grown.is_empty() {
return Err(format!(
"{} grew by more than {FLAT_ITERATIONS} iterations' worth under the work: {line}",
grown.join(", ")
)
.into());
}
Ok(OwnReport {
lines: vec![line],
times: Vec::new(),
})
}
/// The idle row (the module's docs): four Shared blocks, each taken in a unit made ahead of need,
/// given back [`APART`], or with `commits` two, while a command buffer is committed every
/// [`COMMIT_EVERY`], the first [`FIRST_AFTER`] in and the second once the first's free ended.
+17 -3
View File
@@ -1,8 +1,10 @@
//! The runtime's buffers through the harness, on the device the cfg names
//! (docs/VALIDATION.md): a range given back is the next one taken, buffers alive at once lie
//! apart, and a buffer longer than a pooled block takes a block of its own.
//! The runtime through the harness, on the device the cfg names (docs/VALIDATION.md): a range
//! given back is the next one taken, buffers alive at once lie apart, and a buffer longer than a
//! pooled block takes a block of its own; and what textures released under work in flight leave
//! waiting stays flat (`releases_under_work`).
#![cfg(any(m2v_gpu, m2v_cpu_icd))]
use metal2vulkan_harness::authored::OwnRow;
use metal2vulkan_harness::{rt, Buffer, Device, Storage};
#[test]
@@ -27,3 +29,15 @@ fn a_range_given_back_is_the_next_taken_and_live_buffers_lie_apart() {
drop(long);
drop((second, third, private));
}
/// The runtime's row `releases_under_work` passes its check: textures released while three
/// command buffers keep the GPU running leave no more waiting at the 200th iteration than at the
/// 100th, give or take eight iterations' worth.
#[test]
fn releases_under_work_in_flight_stay_flat() {
let device = rt::system_default(None).unwrap();
let report = (device.own_row(OwnRow::ReleasesUnderWork))
.expect("a row of the runtime's own")
.unwrap_or_else(|why| panic!("{why}"));
println!("releases_under_work: {}", report.lines.join("; "));
}
+5 -1
View File
@@ -1142,7 +1142,11 @@ made, with no lock, and never rewritten for layouts.
holds its index: a texture's index, elements, views and image, a texture view's views, and a
sampler state's index and device samplers go once every command buffer committed before the release
has retired, at once where none is in flight, so that work reads them as they were
(`Gauges::releases_waiting` counts what waits). Metal leaves that read undefined: a program that
(`Gauges::releases_waiting` counts what waits). Work committed after the release holds none of
them: the harness's own row `releases_under_work` holds what waits, the live textures and the
texture blocks' bytes flat from its 100th iteration to its 200th, each releasing 16 textures and
views while three command buffers that write 1 GiB each keep the GPU running, read with that
work in flight. Metal leaves that read undefined: a program that
released textures a frame in flight still sampled finished every run with no command buffer
error on two Macs, with the answer it gave with the textures held on a Radeon Pro 5300M, and one
a few channel levels off it, differing from run to run, on an Apple M3 Max. The runtime gives
+25 -8
View File
@@ -85,19 +85,21 @@ pub(crate) const SPARSE: u64 = 16;
/// committed before it, which may reach it with no handle of it, by address (a heap's buffers
/// through an argument buffer) or through set 1 (a heap's textures and sampler states by their
/// resource IDs). Such a reader may read another block's bytes by then, as on a Mac, but never
/// memory or an object the device freed. Nothing is kept past the work in flight.
/// memory or an object the device freed. Nothing is kept past the work in flight, and no command
/// buffer committed after the release is waited for.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Wait {
/// Every command buffer committed up to this place in the commit order is to be submitted.
Commits(u64),
/// Then the submission of this progress value is to complete.
/// Then the submission of this progress value is to complete: the last that carried one of
/// them, or none (0).
Progress(u64),
}
impl Wait {
/// Whether the work it waits for completed, on the block-maker thread without the pool's
/// lock: a wait for commits moves on to the progress value of the last submission once each
/// of them is submitted (`Work::settled`).
/// lock: a wait for commits moves on, once each of them is submitted, to the progress value
/// of the last submission that carried one of them (`Work::settled`).
fn over(&mut self, core: &Core) -> bool {
if let Wait::Commits(commits) = *self {
match core.work.settled(commits) {
@@ -950,8 +952,7 @@ impl Pool {
/// on the reaper thread. Where none is in flight, it goes at once, an index on this thread,
/// so it is vacated before the program's release returns. Releases keep their order.
pub(crate) fn release(&self, core: &Core, object: Free) {
let wait = self.noted();
let now = matches!(wait, Wait::Progress(0));
let now = matches!(self.noted(), Wait::Progress(0));
if now && matches!(object, Free::TextureIndex(..) | Free::SamplerIndex(..)) {
return crate::reaper::free(core, object);
}
@@ -960,6 +961,10 @@ impl Pool {
drop(state);
return core.reaper.give(Job::Free(object));
}
// Noted under the lock, the marks rise along the queue, and a later mark waits for no
// less: the entries whose waits are over are its first, which the block-maker thread
// hands on in one round.
let wait = self.noted();
state.held.push_back((object, wait));
self.counters.rise(Gauge::ReleasesWaiting);
self.changed.notify_all();
@@ -992,6 +997,13 @@ impl Pool {
}
}
/// For the device tests: the last commit's place in the commit order, which a release made
/// now notes while work is in flight.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn commits(&self) -> u64 {
self.commits.load(Ordering::SeqCst)
}
/// For the device tests: whether the class holds a wholly free unit ([`State::whole`]), so
/// the block-maker thread makes nothing for it.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
@@ -1310,8 +1322,11 @@ impl Pool {
/// Takes back an imported or exported block, for the block-maker thread to free, and then to
/// run an import's release.
pub(crate) fn give_back_own(&self, memory: Memory, release: Option<Release>) {
// Noted under the lock, as a release's ([`release`](Self::release)).
let mut state = self.lock();
let wait = self.noted();
self.lock().owned.push_back(((memory, release), wait));
state.owned.push_back(((memory, release), wait));
drop(state);
self.changed.notify_all();
}
@@ -1764,7 +1779,9 @@ pub(crate) fn run(core: Arc<Core>) {
}
/// The oldest entry of a queue of memory given back, taken out where its [`Wait`] is over; where
/// it is not, it stays first, and `held` is set. The pool's lock is dropped for the check.
/// it is not, it stays first, and `held` is set. The pool's lock is dropped for the check. The
/// waits are noted in order, and a later one waits for no less, so no entry behind one that holds
/// is over: the thread, taking one after another, hands on each that is in one round.
fn ripe<'a, T>(
core: &'a Core,
mut state: MutexGuard<'a, State>,
+21 -4
View File
@@ -198,6 +198,11 @@ pub(crate) struct WorkState {
next_place: u64,
/// The progress value of the last submission.
progress: u64,
/// The command buffers whose last segment a submission not seen complete when the submit
/// thread last looked carried, in the order submitted: each one's place in the commit order
/// and that submission's progress value ([`Work::settled`]). At most the command buffers
/// the queues hold at once.
carried: VecDeque<(u64, u64)>,
/// The progress value of the last submission that took an upload, 0 before the first.
uploaded: u64,
/// The upload recording: zero fills, copies and new textures' moves to a home layout, the
@@ -521,6 +526,7 @@ impl Work {
next_seq: 0,
next_place: 0,
progress: 0,
carried: VecDeque::new(),
uploaded: 0,
upload: None,
sealed: VecDeque::new(),
@@ -1181,9 +1187,11 @@ impl Work {
self.lock().progress
}
/// The progress value of the last submission once every command buffer committed up to place
/// `commits` in the commit order is submitted, or ended before it was; None while one waits
/// in its queue's FIFO or in a group not yet submitted (`crate::memory::Wait`).
/// Once every command buffer committed up to place `commits` in the commit order is
/// submitted, or ended before it was: the progress value of the last submission that carried
/// the last segment of one of them, which no later commit moves, or 0 where each was seen
/// complete. None while one waits in its queue's FIFO or in a group not yet submitted
/// (`crate::memory::Wait`).
pub(crate) fn settled(&self, commits: u64) -> Option<u64> {
let state = self.lock();
let waits = |pending: &Pending| pending.seq <= commits;
@@ -1191,7 +1199,12 @@ impl Work {
let staged = (state.fifos.iter()).filter_map(|fifo| fifo.group.as_ref());
let held = queued.filter_map(|entry| entry.pending.as_ref()).any(waits)
|| (staged.flat_map(|group| &group.finished)).any(|(_, pending, _)| waits(pending));
(!held).then_some(state.progress)
// The values rise along the list: the last of them that carried one is the highest.
(!held).then(|| {
(state.carried.iter().rev())
.find(|&&(seq, _)| seq <= commits)
.map_or(0, |&(_, value)| value)
})
}
}
@@ -1473,6 +1486,9 @@ impl WorkState {
/// Forgets the submissions seen complete by `completed`, and the FIFOs left with nothing.
fn settle(&mut self, completed: u64) {
while (self.carried.front()).is_some_and(|&(_, value)| value <= completed) {
self.carried.pop_front();
}
self.fifos.retain_mut(|fifo| {
while (fifo.in_flight.front()).is_some_and(|&value| value <= completed) {
fifo.in_flight.pop_front();
@@ -1718,6 +1734,7 @@ impl WorkState {
pending.gpu.fences.submitted(value);
}
}
(self.carried).extend((batch.finished.iter()).map(|(_, pending, _)| (pending.seq, value)));
let through = batch.leads.last().copied().unwrap_or(0);
let uploads = self.take_uploads(core, released, value, through);
Some((value, uploads, batch))
@@ -598,6 +598,70 @@ mod on_device {
});
}
/// A release waits for no command buffer committed after it (`crate::memory::Wait`): a
/// texture at an index is released under a command buffer that waits on an event, which is
/// then set, and that command buffer completes. A second command buffer, committed after,
/// is held between its close and its submission by its scheduled handler, so the last
/// submission made is the second's and cannot complete. The release's mark then answers a
/// submission already complete, the first's, and the texture goes while the second is held.
/// The order is forced: the first goes only once the event is set, the second is committed
/// only once the first completed, and both checks run while the second's handler waits.
#[test]
fn every_device_frees_a_release_whose_own_commits_completed_under_a_later_submission() {
use crate::tests::command::on_device::{shared_event, within, PATIENCE};
each_device("argument_tier_release_before_later", |name, _, device| {
let (counters, core) = (device.counters(), device.core());
let _grant = (device.grant_indices(IndexClass::Texture, 1, 1))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 2, 2);
d.usage = TextureUsage::SHADER_READ;
let texture =
(device.new_texture(&d, Some(1))).unwrap_or_else(|error| panic!("{name}: {error}"));
let event = shared_event(&device);
let queue = device.new_command_queue(2).expect("a queue");
let first = queue.command_buffer().expect("a command buffer");
(first.encode_wait_for_event(event.as_event(), 1)).expect("a wait");
first.commit().expect("a commit");
let mark = core.pool.commits();
let live = counters.gauges().textures;
drop(texture);
let waiting = counters.gauges().releases_waiting;
assert!(waiting >= 1, "{name}: {waiting} releases waiting");
assert_eq!(
core.work.settled(mark),
None,
"{name}: the mark before its commit went"
);
event.set_signaled_value(1);
finished(name, &first);
// The second's scheduled handler holds the submit thread past its close until `go`
// drops.
let (entered, inside) = std::sync::mpsc::channel::<()>();
let (go, held) = std::sync::mpsc::channel::<()>();
let second = queue.command_buffer().expect("a command buffer");
(second.encode_wait_for_event(event.as_event(), 1)).expect("a wait");
(second.add_scheduled_handler(move |_| {
let _ = entered.send(());
let _ = held.recv();
}))
.expect("a scheduled handler");
second.commit().expect("a commit");
(inside.recv_timeout(PATIENCE)).expect("the second's scheduled handler");
let (answer, completed) = (core.work.settled(mark), core.done.completed());
assert!(
answer.is_some_and(|progress| progress <= completed),
"{name}: the mark answers {answer:?}, with {completed} completed"
);
within("the release under the later submission", || {
let gauges = counters.gauges();
gauges.releases_waiting == 0 && gauges.textures < live
});
drop(go);
finished(name, &second);
println!("{name}: {waiting} releases gone under a later submission");
});
}
/// A slot pointer converted to an integer: thread `i` stores the address of element `i` of
/// buffer 0, bound 16 bytes past its buffer's start, and increments the element through the
/// same pointer (`ab_slot_address`). The address is the buffer's `gpuAddress` plus 16 plus