rt: a barrier between dispatches reaches indirect argument reads only before an indirect dispatch

The barrier between two dispatches took the indirect-argument stage (DRAW_INDIRECT,
INDIRECT_COMMAND_READ) in its second scope, so that a dispatch after it could read its
arguments from a buffer written before it. On NVIDIA that keeps it as costly as the barrier
that takes every command (m3-max-42161: the 2080's frame and dispatch_chain rows equal with and
without the narrowing), while the harness lane's barrier of compute shader accesses alone took
the 2080's frame row from 22.2 to 8.5 us a command buffer.

The barrier now takes indirect argument reads only where the dispatch it precedes is indirect,
known at the dispatch (Reach::Dispatches { indirect }), and for a barrier an encoder owes, at
the dispatch that records it. A barrier that leaves them out does not order a write before it
against a later indirect dispatch, so the command buffer keeps whether a dispatch wrote since the
last barrier that reached them (cleared by one that did and at the segment's end); an indirect
dispatch after such a write gets a barrier that reaches its argument read, in a serial or a
concurrent encoder.

Test: a dispatch writes the arguments, a direct dispatch reads them (a barrier for shader
accesses), an indirect dispatch that conflicts with neither reads them: three barriers (the two,
and the segment's end), and the indirect dispatch's output is right.
This commit is contained in:
Anees Iqbal committed 2026-11-17 12:57:25 -08:00
1 parent 7edbf84c8f
commit 8d160c12ac
5 files changed
+149 -22

No files matched your search

+5 -2
View File
@@ -235,8 +235,11 @@ that touch blocks first.
- An encoder that wrote anything owes one barrier at its end. The next command records it, or the
segment's own end barrier pays it, so a command buffer of one writing encoder has one barrier.
- A barrier within a segment orders dispatches after dispatches: compute shader writes before it,
compute shader reads and writes and indirect argument reads after it. A segment records nothing
else that touches memory; the barrier at a segment's end takes every command and the host.
compute shader reads and writes after it, and indirect argument reads only where the dispatch
after it is indirect. An indirect dispatch after a write that no barrier since has ordered
before indirect argument reads gets one that does, in either kind of encoder. A segment records
nothing else that touches memory; the barrier at a segment's end takes every command and the
host.
- Parameters: fields in the push window, `[0, 256)` on every device, are pushed: the dispatch
region and up to 28 buffer addresses, each kernel pushing only the bytes it reads. Fields past it
go to a 16-byte aligned block in the parameter ring, whose address is a field in the window: a
+31 -4
View File
@@ -124,6 +124,10 @@ pub(crate) struct Building {
/// asked for, or a dispatch wrote through an address outside its resources. The segment's
/// own end barrier pays it too.
owed: bool,
/// A dispatch wrote since the last barrier that reached indirect argument reads: a barrier
/// between dispatches leaves them out unless the dispatch after it is indirect, so an
/// indirect dispatch after such a write needs one that reaches them.
args_unordered: bool,
/// The pipeline bound in the current segment's command buffer.
bound: Option<vk::Pipeline>,
}
@@ -195,6 +199,7 @@ impl CommandBuffer {
stamps,
started: false,
owed: false,
args_unordered: false,
bound: None,
}),
ended: None,
@@ -527,6 +532,7 @@ impl Building {
Some(command) => {
// Its end barrier pays what is owed and starts the hazard sets again.
self.owed = false;
self.args_unordered = false;
if let Some(recorder) = &mut self.gpu.recorder {
recorder.hazards.clear();
}
@@ -574,14 +580,35 @@ impl Building {
None => self.begin()?,
};
if self.owed {
let core = self.device.core();
record::barrier(&core.device, command, reach);
core.counters.count(Metric::Barriers);
self.owed = false;
self.barrier(command, reach);
}
Ok(command)
}
/// Records a barrier into `command`, the current segment's, reaching what the caller records
/// next (`reach`), and pays what is owed. The caller starts the hazard sets again where it
/// has not.
pub(crate) fn barrier(&mut self, command: vk::CommandBuffer, reach: Reach) {
let core = self.device.core();
record::barrier(&core.device, command, reach);
core.counters.count(Metric::Barriers);
self.owed = false;
if reach.reaches_indirect() {
self.args_unordered = false;
}
}
/// A dispatch wrote: an indirect dispatch after it needs a barrier that reaches its
/// argument read.
pub(crate) fn wrote(&mut self) {
self.args_unordered = true;
}
/// Whether a dispatch wrote since the last barrier that reached indirect argument reads.
pub(crate) fn args_unordered(&self) -> bool {
self.args_unordered
}
/// The hazard sets, once the command buffer records: they live with its recorder.
pub(crate) fn hazards(&mut self) -> &mut Hazards {
&mut self
+21 -12
View File
@@ -120,7 +120,9 @@ enum Launch<'a> {
/// mode, as serial dispatch is serial order in Metal. An encoder that wrote anything owes one
/// barrier at its end, which the next command, or the segment's own end, records. A barrier
/// between dispatches orders the dispatches after it after the dispatches before it, and reaches
/// nothing else, as nothing else in the command buffer touches memory.
/// nothing else, as nothing else in the command buffer touches memory; it orders indirect
/// argument reads only where the dispatch after it is indirect, and an indirect dispatch after a
/// write no barrier since has ordered before them gets one that does.
///
/// Parameters: a dispatch's parameter block (bound addresses plus offsets, `set_bytes` addresses
/// and grid values) is pushed as push constants up to 128 bytes; a longer one is written into the
@@ -762,21 +764,23 @@ impl Building {
interface: &crate::pipeline::Interface,
accesses: &Accesses<'_>,
) -> Result<bool, Error> {
let command = self.command(Reach::Dispatches)?;
let core = Arc::clone(self.device.core());
let indirect = accesses.indirect.is_some();
let reach = Reach::Dispatches { indirect };
let command = self.command(reach)?;
let hazards = self.hazards();
if serial {
let conflict = accesses
let conflict = serial
&& (accesses
.each(&interface.buffers)
.any(|(id, access)| hazards.conflicts(id, access))
|| (interface.reads_unbound && hazards.wrote())
|| (interface.writes_unbound && hazards.touched());
if conflict {
record::barrier(&core.device, command, Reach::Dispatches);
core.counters.count(Metric::Barriers);
hazards.clear();
}
|| (interface.writes_unbound && hazards.touched()));
// In either kind of encoder: the barriers since a write may have left indirect argument
// reads out.
if conflict || (indirect && self.args_unordered()) {
self.barrier(command, reach);
self.hazards().clear();
}
let hazards = self.hazards();
let mut wrote = false;
for (id, access) in accesses.each(&interface.buffers) {
hazards.mark(id, access);
@@ -793,6 +797,9 @@ impl Building {
self.owe();
}
}
if wrote {
self.wrote();
}
Ok(wrote)
}
@@ -813,7 +820,9 @@ impl Building {
}
let push = &parameters.push[..];
debug_assert!(push.len() <= PUSH_BYTES as usize);
let command = self.command(Reach::Dispatches)?;
let command = self.command(Reach::Dispatches {
indirect: matches!(launch, Launch::Indirect(..)),
})?;
// SAFETY: the command buffer is recording outside any render pass; the pipeline and the
// layout are the device's, and the push range of the layout spans every stage's first 128
// bytes.
+20 -3
View File
@@ -50,23 +50,40 @@ impl Recorder {
#[derive(Clone, Copy)]
pub(crate) enum Reach {
/// Within a segment: the dispatches after it after the dispatches before it, their shader
/// reads and writes and their indirect argument reads seeing the earlier shader writes. A
/// reads and writes seeing the earlier shader writes, and where `indirect` (the dispatch that
/// follows it reads its arguments from a buffer), their indirect argument reads too. A
/// segment records nothing else that reads or writes memory, so it orders the segment's
/// commands as [`Reach::Commands`] would.
Dispatches,
Dispatches { indirect: bool },
/// Every later command, in this submission and every later one on the queue.
Commands,
/// Every later command, and the host once it has waited for the work.
Host,
}
impl Reach {
/// Whether the barrier orders indirect argument reads after the writes before it.
pub(crate) fn reaches_indirect(self) -> bool {
match self {
Reach::Dispatches { indirect } => indirect,
Reach::Commands | Reach::Host => true,
}
}
}
/// Records one global memory barrier: the writes earlier in submission order are made visible
/// to what `reach` names, and the commands it names wait for the earlier ones. It is the only
/// barrier the runtime records for buffers: none names a buffer or a range. The caller counts it
/// where it is part of the queues' work.
pub(crate) fn barrier(device: &ash::Device, buffer: vk::CommandBuffer, reach: Reach) {
let (source, written, stages, accesses) = match reach {
Reach::Dispatches => (
Reach::Dispatches { indirect: false } => (
vk::PipelineStageFlags2::COMPUTE_SHADER,
vk::AccessFlags2::SHADER_WRITE,
vk::PipelineStageFlags2::COMPUTE_SHADER,
vk::AccessFlags2::SHADER_READ | vk::AccessFlags2::SHADER_WRITE,
),
Reach::Dispatches { indirect: true } => (
vk::PipelineStageFlags2::COMPUTE_SHADER,
vk::AccessFlags2::SHADER_WRITE,
vk::PipelineStageFlags2::COMPUTE_SHADER | vk::PipelineStageFlags2::DRAW_INDIRECT,
+72 -1
View File
@@ -10,7 +10,8 @@ mod on_device {
use crate::tests::command::on_device::{each_device, finished, Arena};
use crate::tests::kernels;
use crate::{
Buffer, CommandBuffer, ComputePipelineState, Device, DispatchType, Error, Gap, Refusal,
Buffer, CommandBuffer, ComputeCommandEncoder, ComputePipelineState, Device, DispatchType,
Error, Gap, Refusal,
};
/// Words in each test buffer: 256 bytes.
@@ -313,6 +314,76 @@ mod on_device {
});
}
/// An indirect dispatch after a write that no barrier since has ordered before indirect
/// argument reads gets a barrier that does: a dispatch writes the arguments, a direct
/// dispatch that reads them follows (its barrier reaches shader accesses alone), and the
/// indirect dispatch, which conflicts with neither, reads them.
#[test]
fn every_device_orders_an_indirect_dispatch_after_the_write_of_its_arguments() {
each_device("compute_indirect_after_write", |name, _, device| {
let mut arena = Arena::new(&device);
let (a, b, arguments, c, o) = (
arena.buffer(),
arena.buffer(),
arena.buffer(),
arena.buffer(),
arena.buffer(),
);
write_words(&a, |index| if index == 4 { 3 } else { index * 10 });
write_words(&b, |index| match index {
4..=6 => 1,
_ => 0,
});
for buffer in [&arguments, &c, &o] {
write_words(buffer, |_| 0);
}
let state = add(&device);
let queue = device.new_command_queue(4).expect("a queue");
let before = device.counters().metrics();
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = command_buffer
.compute_command_encoder(DispatchType::Serial)
.expect("an encoder");
encoder.set_compute_pipeline_state(&state).expect("a state");
let bind = |encoder: &mut ComputeCommandEncoder, buffers: [&Buffer; 3]| {
for (slot, buffer) in buffers.into_iter().enumerate() {
encoder
.set_buffer(Some(buffer), 0, slot as u32)
.expect("a buffer");
}
};
// The arguments, a + b: (4, 1, 1) threadgroups at words 4 to 6.
bind(&mut encoder, [&a, &b, &arguments]);
encoder
.dispatch_threadgroups([4, 1, 1], [16, 1, 1])
.expect("a dispatch");
// A direct dispatch that reads them, after a barrier for shader accesses alone.
bind(&mut encoder, [&arguments, &b, &c]);
encoder
.dispatch_threadgroups([4, 1, 1], [16, 1, 1])
.expect("a dispatch");
// The indirect dispatch: a barrier that reaches its argument read.
bind(&mut encoder, [&a, &b, &o]);
encoder
.dispatch_threadgroups_with_indirect_buffer(&arguments, 16, [16, 1, 1])
.expect("an indirect dispatch");
encoder.end_encoding();
run(name, &command_buffer);
let after = device.counters().metrics();
// The direct dispatch's, the indirect dispatch's, and the segment's end.
assert_eq!(after.barriers - before.barriers, 3, "{name}");
let sum = |index: u32| {
if index == 4 {
4
} else {
index * 10 + u32::from((4..=6).contains(&index))
}
};
let expected: Vec<u32> = (0..WORDS as u32).map(sum).collect();
assert_eq!(words(&o), expected, "{name}");
});
}
/// What Metal refuses in an encoder, and the limits the device sets.
#[test]
fn every_device_refuses_what_metal_refuses_in_an_encoder() {