A host step waits for the batches that wrote what it reads, not every queue's work

A batch whose host step records indirect commands the GPU may write waited, once otherwise
ready, until every VkQueue completed what was submitted to it by then. A frame of a GPU-culling
renderer (a kernel encodes the draws and their execution range, then several render passes
execute them through the range) paid one GPU round trip per pass: each pass's step waited for
the passes before it in its command buffer, and for other queues' unrelated work, though it
reads only the records and the range the culling wrote. The range read made it worse: it was
read from a copy recorded right before the execution, in the batch of the previous pass.

Now the gate is taken from the hazard state where it can be (scheduler gate_of):

- CommandBufferShared::step_reads names what a batch's host step reads on the host of what the
  GPU may write, where each segment whose step waits for the GPU is an execution (outside a block
  of command predication) or a render pass of executions whose uses commit bounded: their
  records and ranges (Deferred::host_reads, ExecutionRange::host_reads), with their host
  aliases. Anything else (an indirect dispatch, a loop's check, a staged gather, an indirect
  sparse update) answers None.
- Tracker::last_writes answers, per VkQueue, the value of the last batch that wrote those bytes
  of the writes the state holds; None for an untracked resource. The state forgets only what
  completed, and a write that let an older entry go waited for it, so once each queue reached its
  value every GPU write to those bytes completed and reached the host (every batch ends with the
  barrier to the host). Every such writer is submitted by the time the gate is taken: earlier
  batches of the line went first, an earlier commit's conflicting batch on another line holds the
  head behind it (its footprint holds the step's reads), a later one waits behind it.
- Where either answers None the gate is every queue's last submission, as before.
- The range of executeCommandsInBuffer:indirectBuffer: is read in place where the host maps the
  bytes the GPU writes (Buffer::maps_gpu_bytes: not Private, not a Managed host copy on a
  discrete device, not a copied host buffer), through Buffer::read_mapped, which holds a no-copy
  buffer's pages while it reads 8 bytes so a detach and rebind meanwhile free none of them; a
  detached buffer runs nothing. The read is noted at the call as a command that reads the bytes
  (no GPU work), so the encoder's order, a detach and the hazard state see it as they saw the
  copy's. Other buffers keep the copy.
- WorkCounts::host_step_gates_narrowed counts gates that left out work submitted before them;
  the conformance cost tables report it and never gate it (QUEUE_DEPTH: whether a gate falls
  below a queue's last submission depends on whether the host had seen the writer complete).
- The HostReplayedIndirectCommands notice's cost, its catalogue entry in docs/API.md, the
  scheduler's and indirect_execute's module docs and the execution calls' docs say so.

Tests: tracker a_host_read_waits_for_the_last_writes_of_its_bytes_alone (the writer per queue, no
writer, a covering write on another queue, untracked, a queue past the count, retired). Lane
depth_executions a_frame_s_executions_wait_for_the_culling_alone: a culling command buffer on one
queue, a fill on another queue submitted before the frame, then a frame of two passes that
execute the commands through the range: two host steps, both gates narrowed, both targets hold
each kept chunk's depth. The existing depth_executions test now shares its workload.

No Metal-visible behaviour changes: what the steps read and record is the same; they start
earlier.
This commit is contained in:
Anees Iqbal committed 2026-11-12 04:53:27 -08:00
1 parent 5c3d492b4d
commit 2724757bbf
16 files changed
+545 -150

No files matched your search

+6 -1
View File
@@ -716,7 +716,7 @@ pub fn monotone(name: &str) -> Option<&'static str> {
/// truncated and it reran. The other read the counters behind its own movements and found every one
/// of them process-shared. Neither symptom could be read off a single run, which is the property
/// that makes this class worth naming rather than discovering again.
const SHARED: [(&str, &str); 21] = [
const SHARED: [(&str, &str); 22] = [
// `work_counts.rs`: "every batch, by how far its queue's work ran behind its submission".
// Four buckets of one histogram, and which bucket a batch lands in is decided by how fast the
// GPU drained what was submitted before it, earlier cases included. The sum is the case's own
@@ -742,6 +742,11 @@ const SHARED: [(&str, &str); 21] = [
// them is pending. Whether a registration finds a submission holding the order is a race with
// that submission. Reads 0 on this venue, and is here on its definition.
("registrations_waited", QUEUE_DEPTH),
// Host steps whose gate "left out work submitted before it". A gate the batches that last
// wrote what the step reads set holds no value for a writer the host had already seen
// complete, so whether it falls below the queue's last submission depends on how far the GPU
// had got when it was taken. Here on its definition.
("host_step_gates_narrowed", QUEUE_DEPTH),
// The two halves of a transition's thread that an earlier pass left gated because nothing had
// been seen to move them. Definition-first says otherwise, and consistency matters more than
// the reach: `scheduled_where_submitted` is documented as running "on the scheduler's thread
+58
View File
@@ -559,6 +559,26 @@ impl HostCell {
}
}
/// The `N` bytes at `offset` of the buffer's bytes, as the host reads them now through the
/// pages they lie in, which are held while they are read: a detach and a rebind meanwhile let
/// none of them go under the read (their deallocator waits for them, `HeldBack`). `None` while
/// it is detached. The caller holds `offset + N` inside the buffer's length.
fn read<const N: usize>(&self, offset: u64) -> Option<[u8; N]> {
let pages = self.current()?;
let shape = pages.import.shape;
let start = shape.mapped?.as_ptr().wrapping_add(shape.offset as usize);
let mut bytes = [0u8; N];
// SAFETY: the pages map the buffer's bytes from `start`, and the caller holds the `N`
// bytes at `offset` inside its length; `pages` keeps them mapped until the copy ends. A
// write to them meanwhile races, as a read of `contents` does on Metal.
unsafe {
let at = start.wrapping_add(offset as usize);
std::ptr::copy_nonoverlapping(at, bytes.as_mut_ptr(), N);
}
drop(pages);
Some(bytes)
}
/// The caller's pointer of the pages the buffer was detached from, while it is detached.
fn detached_pointer(&self) -> Option<NonNull<u8>> {
match &*lock(&self.pages) {
@@ -4796,6 +4816,44 @@ impl Buffer {
}
}
/// Whether the host maps the bytes the GPU reads and writes, through which the runtime may
/// read what the GPU wrote once it completed ([`read_mapped`](Buffer::read_mapped)): not a
/// `Private` buffer, nor a `Managed` one's host copy on a device without unified memory
/// ([`HostCopy`]), nor a copy of the caller's pages ([`copied`](Buffer::copied)), whose
/// GPU's bytes are not the pages.
pub(super) fn maps_gpu_bytes(&self) -> bool {
self.storage_mode() != StorageMode::Private && self.mirror().is_none() && !self.copied()
}
/// The `N` bytes at `offset`, as the host reads them now through the buffer's mapping
/// ([`mapped_contents`](Buffer::mapped_contents)): where they lie in host pages (a no-copy
/// buffer's, or for a heap's buffer its heap's), read with those pages held, so a detach and
/// a rebind meanwhile let none of them go under the read. `None` where nothing maps them now
/// (a `Private` buffer, a detached one), or `offset + N` passes the buffer's length.
pub(super) fn read_mapped<const N: usize>(&self, offset: u64) -> Option<[u8; N]> {
if offset.checked_add(N as u64)? > self.length() {
return None;
}
let contents = match &self.s().bytes {
Bytes::Heap(bytes) => return bytes.bytes.read_mapped(bytes.offset + offset),
Bytes::Own(OwnBytes {
mirror: None,
lie: Lie::Host(cell),
..
}) => return cell.read(offset),
Bytes::Own(_) => self.mapped_contents()?,
};
let mut bytes = [0u8; N];
// SAFETY: the mapping holds the buffer's `length` bytes from `contents`, which its own
// memory keeps mapped while the buffer lives, and `offset + N` is at most that. A write
// to them meanwhile races, as a read of `contents` does on Metal.
unsafe {
let at = contents.as_ptr().wrapping_add(offset as usize);
std::ptr::copy_nonoverlapping(at, bytes.as_mut_ptr(), N);
}
Some(bytes)
}
/// The caller's pointer of the pages a detached no-copy buffer lay in last, or for a heap's
/// buffer its offset from its detached heap's: what [`contents`](Buffer::contents) answers
/// while it is detached. `None` for any other buffer.
@@ -4549,6 +4549,36 @@ impl CommandBufferShared {
}
}
/// What the host step of batch `index` reads on the host of what the GPU may write, where its
/// gate may be the batches that last wrote it alone (`scheduler/mod.rs`'s `gate_heads`): each
/// segment whose step waits for the GPU is an execution, or a render pass of executions,
/// whose uses `commit` bounded (`Segment::bound`), and its reads are their records and ranges
/// (`Deferred::host_reads`), with the host aliases of their bytes. `None` where the step waits
/// for more: an indirect sparse update or a staged gather of the batch reads what the GPU may
/// write, or another segment's step waits for the GPU (an indirect dispatch's, a loop's check,
/// an execution inside a block of command predication): its gate is every queue's work.
pub(crate) fn step_reads(&self, index: usize) -> Option<Vec<Use<ResourceKey>>> {
let state = lock(&self.state);
let recorded = &state.recorded[state.batch_range(index)];
let mut sparse = recorded.iter().flat_map(|encoder| &encoder.sparse);
if sparse.any(SparseUpdate::needs_step) {
return None;
}
let mut reads = Vec::new();
for segment in recorded.iter().flat_map(|encoder| &encoder.segments) {
if segment.needs_step() && segment.work.steps_after_the_gpu_now(&self.device) {
return None;
}
if segment.steps_after_the_gpu() {
segment.bound.as_ref()?;
reads.extend(segment.work.host_reads()?);
}
}
drop(state);
let aliases = &self.device.shared().aliases;
Some(aliases.augment(&reads).unwrap_or(reads))
}
/// Raise the makings of the pipelines batch `index`'s host step records, still being made,
/// to a queue's first held batch's (`budget::Urgency::Head`): the scheduler found the batch
/// first in its queue's line, every batch after it there waiting behind it. The makings are
+7 -10
View File
@@ -1371,9 +1371,11 @@ impl ComputeCommandEncoder {
/// end. A location past the size, or a range past `2^32 - 1`, which Metal's GPU faults on, runs
/// nothing, and the command buffer's execution report states `ReplayFaults::RANGE`. The
/// commands run as [`execute_commands_in_buffer`](Self::execute_commands_in_buffer)'s that a
/// function may write do: by a host step once the work before them completed, which the device
/// announces once (`Degradation::HostReplayedIndirectCommands`; the encoder copies the range
/// where it is encoded, behind a barrier from everything before).
/// function may write do: by a host step once the work that wrote them and the range completed,
/// which the device announces once (`Degradation::HostReplayedIndirectCommands`). The step
/// reads the range in place where the host maps the bytes of `range_buffer` the GPU writes (a
/// `Shared` buffer, a `Managed` one on unified memory); else the encoder copies it where it is
/// encoded, behind a barrier from everything before, and the step reads the copy.
///
/// A range plain Metal takes and the runtime has no exact answer for is its own gap, not
/// misuse: 8 bytes that run past `range_buffer`, which Metal reads from whatever follows it
@@ -1441,13 +1443,8 @@ impl ComputeCommandEncoder {
if icb.has_no_command_types() {
return Ok(());
}
let copy = indirect_dispatch::copy_arguments(
&mut this.core,
range_buffer,
offset,
indirect_execute::RANGE_BYTES,
)?;
this.defer_execution(icb, ExecutionRange::Indirect(copy), pipeline, check)?;
let range = indirect_execute::range_from(&mut this.core, range_buffer, offset)?;
this.defer_execution(icb, range, pipeline, check)?;
this.worked();
this.capture(|| Event::ExecuteIndirect(icb.clone(), range_buffer.clone(), offset));
Ok(())
+22 -1
View File
@@ -20,7 +20,7 @@ use super::render::DeferredPass;
use super::resource::ResourceKey;
use super::shadow::GatedCopyIn;
use super::sparse::emulated::Scrub;
use super::tracker::{EncoderUses, Summary};
use super::tracker::{EncoderUses, Summary, Use};
use super::Device;
use super::IndirectCommandBuffer;
use crate::pipeline::budget::Urgency;
@@ -515,6 +515,27 @@ impl Deferred {
}
}
/// What its host step reads on the host of what the GPU may write, where that is all the
/// step waits for of the work before it (`CommandBufferShared::step_reads`): an execution's
/// records and range (`ExecutionRange::host_reads`), outside a block of command predication,
/// whose counter its step reads too; a render pass's executions'. `None` for every other
/// work, whose step waits for all the work submitted before it.
pub(super) fn host_reads(&self) -> Option<Vec<Use<ResourceKey>>> {
match self {
Deferred::Execute(execute) => execute.host_reads(),
Deferred::RenderPass(pass) => Some(pass.host_reads()),
Deferred::Dispatch(_)
| Deferred::SparseScrub(_)
| Deferred::GatedCopyIn(_)
| Deferred::RunMerge(_)
| Deferred::Pending(_)
| Deferred::Loop(_)
| Deferred::GatherStage(_)
| Deferred::ScatterStage(_)
| Deferred::ScatterDrain(_) => None,
}
}
/// Whether a rebind's encoding again of its encoder records it at once in its place, leaving
/// no segment of it (`command_buffer/reencode.rs`): a staged gather, which an encoder encoded
/// again copies through the imports (`host_ram/copy.rs`). The encoding again's parts are the
@@ -704,10 +704,13 @@ degradations! {
/// commands times its states pass 32,768. Every other execution runs on the GPU alone and
/// announces nothing.
HostReplayedIndirectCommands = "host-replayed-indirect-commands", Performance,
"one GPU-to-CPU round trip per execution: its command buffer's work before it, and \
every batch submitted before that on any queue, completes before the CPU records \
its commands from their records, on a thread of the runtime's, and submits the \
rest; meanwhile the device's other batches go, but for a later one that shares a \
"a GPU-to-CPU round trip: the batches that last wrote its records and its range \
complete before the CPU records its commands from their records, on a thread of \
the runtime's, and submits the rest, so a command buffer's executions behind one \
writer wait for it once (where Metal tracks neither, or the step reads more, as \
inside a block of command predication: its command buffer's work before it, and \
every batch submitted before that on any queue); meanwhile the device's other \
batches go, but for a later one that shares a \
resource the execution may reach (one made resident, the records), and the first \
command of a threadgroup size or threadgroup lengths its pipeline state has not \
dispatched makes that VkPipeline then, as does a render command's draw of a state \
@@ -21,8 +21,10 @@
//! records are known only once the work before the execution completed. Its segment starts a part
//! of the encoder, and a batch, of its own. Where every record it may hold is covered, `commit`
//! records it to run on the GPU alone (`gpu_execute.rs`); otherwise the scheduler submits the
//! batch once every batch submitted before it on any queue completed and its host step recorded
//! the segment from the records then (`scheduler`), which the device announces once
//! batch once the batches that last wrote its records and its range completed (every batch
//! submitted before it on any queue, where Metal tracks neither or the step reads more:
//! `scheduler`'s `gate_of`) and its host step recorded the segment from the records then, which
//! the device announces once
//! (`Degradation::HostReplayedIndirectCommands`). So is a segment `commit` recorded from the
//! CPU's records whose buffer such a route met after the commit ([`Unforeseen`]). The step
//! compiles nothing: `commit`, or for such a segment the call that met the buffer (a later
@@ -96,7 +98,7 @@ use super::compute::{
use super::degradation::Degradation;
use super::device::lock;
use super::encoder::{EncoderCore, RecordedSegment};
use super::error::{internal, invalid, Error, RuntimeGap};
use super::error::{invalid, Error, RuntimeGap};
use super::executed_commands::{ExecutedCommand, RecordsRead};
use super::indirect_command_buffer::{
IndirectCommandBuffer, IndirectCommandCheck, IndirectCommandCheckNeeds, Reader,
@@ -110,6 +112,7 @@ use super::tracker::{Access, Barrier, EncoderUses, Summary, Use};
use super::upload::Upload;
use super::write_routes::replay_why;
use super::Device;
use super::{blit, indirect_dispatch};
use ash::vk;
use metal2vulkan::bind::indirect_commands::{Action, BufferBinding, BufferStage, CommandRecord};
use metal2vulkan::bind::{Dispatch, ImageblockSize, ReplayFaults, StageInRegion};
@@ -194,26 +197,54 @@ pub(super) const NOT_READ: u64 = u64::MAX;
pub(super) enum ExecutionRange {
/// `executeCommandsInBuffer:withRange:`'s, inside the buffer's size.
Fixed(Range<u32>),
/// `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:`'s: a copy of the
/// `MTLIndirectCommandBufferExecutionRange` (`location`, then `length`, each a `u32`), made
/// where the execution is encoded behind a barrier from everything before
/// (`indirect_dispatch::copy_arguments`), which the host step reads.
Indirect(Buffer),
/// `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:`'s: the
/// `MTLIndirectCommandBufferExecutionRange` (`location`, then `length`, each a `u32`) at
/// `offset` of `buffer`, which the host step reads ([`range_from`]).
Indirect { buffer: Buffer, offset: u64 },
}
/// The range of an execution `core` encodes from the [`RANGE_BYTES`] at `offset` of `buffer`
/// (`executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:`), which its host step reads
/// ([`ExecutionRange::commands`]). Read there in place where the host maps the bytes the GPU
/// reads and writes (`Buffer::maps_gpu_bytes`), so the step waits for the batches that wrote
/// them alone (`CommandBufferShared::step_reads`): the read is noted where the call lies, as a
/// command that reads them, so the encoder's order, a detach (`detach.rs`) and the hazard state
/// see it as they saw the copy's. Else read from a copy made here behind a barrier from
/// everything before (`indirect_dispatch::copy_arguments`), whose batch the step waits for.
/// Refused as the copy's buffer is.
pub(super) fn range_from(
core: &mut EncoderCore,
buffer: &Buffer,
offset: u64,
) -> Result<ExecutionRange, Error> {
if buffer.maps_gpu_bytes() {
let read = blit::reads(buffer, offset..offset + RANGE_BYTES);
core.command(vk::PipelineStageFlags2::TRANSFER, &[read], |_, _| {});
core.retain(buffer.clone());
let buffer = buffer.clone();
return Ok(ExecutionRange::Indirect { buffer, offset });
}
let copy = indirect_dispatch::copy_arguments(core, buffer, offset, RANGE_BYTES)?;
Ok(ExecutionRange::Indirect {
buffer: copy,
offset: 0,
})
}
impl ExecutionRange {
/// What a host step of an execution of `icb`'s commands over this range reads on the host of
/// what the GPU may write, for the scheduler's order across queues
/// (`CommandBufferShared::footprint`): the records' buffer, and the copy a range read from a
/// buffer is read from, each read in every stage.
/// (`CommandBufferShared::footprint`) and for what the step waits for
/// (`CommandBufferShared::step_reads`): the records' buffer, and the bytes a range read from
/// a buffer is read from, each read in every stage.
pub(super) fn host_reads(&self, icb: &IndirectCommandBuffer) -> Vec<Use<ResourceKey>> {
let read = Access::new(
vk::PipelineStageFlags2::ALL_COMMANDS,
vk::AccessFlags2::MEMORY_READ,
);
let mut reads = vec![whole_use(icb.storage(), read, Access::NONE)];
if let ExecutionRange::Indirect(copy) = self {
reads.push(whole_use(copy, read, Access::NONE));
if let ExecutionRange::Indirect { buffer, offset } = self {
reads.push(blit::reads_by(buffer, *offset..offset + RANGE_BYTES, read));
}
reads
}
@@ -222,38 +253,38 @@ impl ExecutionRange {
/// ([`ExecutionRange::Indirect`]): a host step records its execution, whoever wrote the
/// records.
pub(super) fn indirect(&self) -> bool {
matches!(self, ExecutionRange::Indirect(_))
matches!(self, ExecutionRange::Indirect { .. })
}
/// The commands it runs of a buffer of `size` commands: the range given, or the range the
/// copy holds now as Metal's execution takes it (an M3 Max and an M4, for a compute encoder; a
/// probe, the same chips, for a render encoder): from `location` to `location + length`,
/// The commands it runs of a buffer of `size` commands: the range given, or the range its
/// bytes hold now as Metal's execution takes it (an M3 Max and an M4, for a compute encoder;
/// a probe, the same chips, for a render encoder): from `location` to `location + length`,
/// clamped at the buffer's size, so a location of 2 and a length of 5 in a buffer of 4 run
/// commands 2 and 3, and a length of 0 or a location at the size runs nothing. Where the
/// location lies past the size, or `location + length` passes `2^32 - 1` (Metal's GPU then
/// faults the command buffer, or hangs), it runs nothing and reports `ReplayFaults::RANGE`.
pub(super) fn commands(&self, size: u64) -> Result<(Range<u32>, ReplayFaults), Error> {
let copy = match self {
ExecutionRange::Fixed(range) => return Ok((range.clone(), ReplayFaults::default())),
ExecutionRange::Indirect(copy) => copy,
/// Bytes no mapping holds now (a no-copy buffer detached since the call, `detach.rs`) run
/// nothing.
pub(super) fn commands(&self, size: u64) -> (Range<u32>, ReplayFaults) {
let (buffer, offset) = match self {
ExecutionRange::Fixed(range) => return (range.clone(), ReplayFaults::default()),
ExecutionRange::Indirect { buffer, offset } => (buffer, *offset),
};
// The GPU's writes to the bytes before the host step completed (its gate) and reached
// the host (each batch ends with the barrier to the host); nothing of the command buffer
// after the execution runs before the step.
let Some(bytes) = buffer.read_mapped::<{ RANGE_BYTES as usize }>(offset) else {
return (0..0, ReplayFaults::default());
};
let contents = copy
.mapped_contents()
.ok_or_else(|| internal("an execution range's copy without host bytes"))?;
let mut bytes = [0u8; RANGE_BYTES as usize];
// SAFETY: the copy is a `Shared` buffer of at least `RANGE_BYTES`, mapped; the GPU's
// write to it completed before the host step (its batch ended with the barrier to the
// host), and nothing writes it after.
unsafe { std::ptr::copy_nonoverlapping(contents.as_ptr(), bytes.as_mut_ptr(), 8) };
let [l0, l1, l2, l3, n0, n1, n2, n3] = bytes;
let location = u64::from(u32::from_le_bytes([l0, l1, l2, l3]));
let length = u64::from(u32::from_le_bytes([n0, n1, n2, n3]));
if location > size || location + length > u64::from(u32::MAX) {
return Ok((0..0, ReplayFaults::RANGE));
return (0..0, ReplayFaults::RANGE);
}
let end = (location + length).min(size);
// Both lie within the size, which a buffer's `u32` command count holds.
Ok((location as u32..end as u32, ReplayFaults::default()))
(location as u32..end as u32, ReplayFaults::default())
}
}
@@ -365,7 +396,7 @@ impl Execute {
Some(_) => BufferForms::Large,
None => BufferForms::Bound,
};
let (range, mut faults) = self.range()?;
let (range, mut faults) = self.range();
// The caller's check sees each command the execution will record, before it records any,
// where it may see something; so do the command buffer's executed-commands handlers,
// which hear of the execution once. `commit` reads the rest a chunk at a time
@@ -551,6 +582,15 @@ impl Execute {
Some(bound.finish())
}
/// What its host step reads on the host of what the GPU may write, where that is all the step
/// waits for (`Deferred::host_reads`): its records and its range
/// ([`ExecutionRange::host_reads`]). `None` inside a block of command predication, whose
/// counter the steps before it write and its step reads too (`predication.rs`).
pub(super) fn host_reads(&self) -> Option<Vec<Use<ResourceKey>>> {
let predicated = self.gate.is_some() || self.preprocess_gate.is_some();
(!predicated).then(|| self.range.host_reads(&self.icb))
}
/// Whether it reads its range from a buffer, which the GPU may write
/// ([`ExecutionRange::indirect`]): a host step records it, whoever wrote its records.
pub(super) fn indirect(&self) -> bool {
@@ -612,7 +652,7 @@ impl Execute {
}
/// The commands it runs ([`ExecutionRange::commands`]).
fn range(&self) -> Result<(Range<u32>, ReplayFaults), Error> {
fn range(&self) -> (Range<u32>, ReplayFaults) {
self.range.commands(self.icb.size())
}
@@ -101,7 +101,7 @@ impl Execute {
residency: &Residency,
keeping: Keeping,
) -> Result<RecordedSegment, Error> {
let (range, faults) = self.range()?;
let (range, faults) = self.range();
let Keeping {
mut key,
kept,
@@ -304,7 +304,6 @@ use crate::indirect_command_buffer::{
IndirectCommandBuffer, IndirectCommandCheck, IndirectCommandCheckNeeds, NineDraw, Reader,
WrittenRecords,
};
use crate::indirect_dispatch;
use crate::indirect_execute::{self, unstrided_stride, ExecutionRange};
use crate::kept_commands;
use crate::live_bind::LiveBind;
@@ -497,13 +496,8 @@ impl RenderLowering {
IndirectRule::RangeWrittenByDraw,
)));
}
let copy = indirect_dispatch::copy_arguments(
&mut self.core,
range_buffer,
offset,
indirect_execute::RANGE_BYTES,
)?;
self.defer_execution(icb, ExecutionRange::Indirect(copy), pipeline, check)
let range = indirect_execute::range_from(&mut self.core, range_buffer, offset)?;
self.defer_execution(icb, range, pipeline, check)
}
/// The pipeline state an execution of `icb` here runs with (`Inherited`). Where the
@@ -543,7 +537,7 @@ impl RenderLowering {
{
Some(earlier.len())
}
ExecutionRange::Fixed(_) | ExecutionRange::Indirect(_) => None,
ExecutionRange::Fixed(_) | ExecutionRange::Indirect { .. } => None,
});
if let Some(earlier) = earlier {
degrade_repeated_start(self.core.device(), icb, range, earlier);
@@ -586,7 +580,7 @@ impl RenderLowering {
// read from a buffer runs at most every command of the buffer.
let commands = match &range {
ExecutionRange::Fixed(range) => u64::from(range.end - range.start),
ExecutionRange::Indirect(_) => icb.size(),
ExecutionRange::Indirect { .. } => icb.size(),
};
let (depth, _) = self.layout.aspects();
let metal_depth = depth
@@ -863,10 +857,12 @@ impl RenderCommandEncoder {
/// location, clamped at the buffer's size, so a length of 0 or a location at the size runs
/// nothing and a length past it runs to its end; a location past the size, or a range past
/// `2^32 - 1`, at which Metal's GPU faults the command buffer, runs nothing, and the command
/// buffer's execution report states `ReplayFaults::RANGE`. The encoder copies the range where
/// it is encoded, behind a barrier from everything before, so the range a kernel of an earlier
/// encoder wrote is read; a host step records the pass once the work before it completed, which
/// the device announces once (`Degradation::HostReplayedIndirectCommands`).
/// buffer's execution report states `ReplayFaults::RANGE`. A host step records the pass once
/// the work that wrote its records and the range completed (a kernel of an earlier encoder, a
/// blit), which the device announces once (`Degradation::HostReplayedIndirectCommands`). The
/// step reads the range in place where the host maps the bytes of `range_buffer` the GPU
/// writes (a `Shared` buffer, a `Managed` one on unified memory); else the encoder copies it
/// where it is encoded, behind a barrier from everything before, and the step reads the copy.
///
/// A range plain Metal takes and the runtime has no exact answer for is its own gap, not
/// misuse: 8 bytes that run past `range_buffer`, which Metal reads from whatever follows it
@@ -878,8 +874,8 @@ impl RenderCommandEncoder {
/// [`execute_commands_in_buffer`](Self::execute_commands_in_buffer) refuses but a range (an
/// unset inherited state whatever the range), and a range buffer of another device. A range a draw of the
/// encoder before the call may write is `NotImplemented(IndirectRenderCommands)`: Metal's
/// execution reads that draw's write, where the runtime's copy, made before the pass, would
/// not; as for the index bounds pass, an untracked buffer's writes are not seen. Under an
/// execution reads that draw's write, where the runtime's read, before the pass, would not; as
/// for the index bounds pass, an untracked buffer's writes are not seen. Under an
/// inherited state made without `supportIndirectCommandBuffers`, whatever the range, `{0, 0}`
/// included, the encoder faults as `execute_commands_in_buffer`'s does.
pub fn execute_commands_in_buffer_indirect(
@@ -2077,7 +2073,7 @@ impl RenderExecution {
}
Keeps::Inline(reads) => reads,
};
let (range, faults) = self.range.commands(self.icb.size())?;
let (range, faults) = self.range.commands(self.icb.size());
if !step && self.range.indirect() {
return Err(internal(
"a range read from a buffer recorded before its host step",
@@ -2633,7 +2629,7 @@ impl RenderExecution {
None => {
let commands = match &self.range {
ExecutionRange::Fixed(range) => range.clone(),
ExecutionRange::Indirect(_) => {
ExecutionRange::Indirect { .. } => {
0..u32::try_from(self.icb.size()).unwrap_or(u32::MAX)
}
};
@@ -2922,6 +2918,14 @@ impl DeferredPass {
.any(|execution| execution.icb.gpu_written() || execution.range.indirect())
}
/// What its host step reads on the host of what the GPU may write (`Deferred::host_reads`):
/// each execution's records and range (`ExecutionRange::host_reads`).
pub(crate) fn host_reads(&self) -> Vec<Use<ResourceKey>> {
(self.executions.iter())
.flat_map(|execution| execution.range.host_reads(&execution.icb))
.collect()
}
/// The indirect command buffers its executions run.
pub(crate) fn executed(&self) -> impl Iterator<Item = &IndirectCommandBuffer> {
self.executions.iter().map(|execution| &execution.icb)
@@ -3084,7 +3088,7 @@ impl DeferredPass {
// The first length each buffer (by its resource ID) was executed with from each command.
let mut first: BTreeMap<(u64, u32), usize> = BTreeMap::new();
for execution in &self.executions {
let (range, _) = execution.range.commands(execution.icb.size())?;
let (range, _) = execution.range.commands(execution.icb.size());
if range.is_empty() {
continue;
}
@@ -93,8 +93,10 @@
//! work in flight, whose completion turn is this thread's (`Completion::turn_owed`), is
//! finished before they run.
//! - **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'
//! (`CommandBufferShared::needs_host_step`) is held, once otherwise ready, until the batches
//! that last wrote what its step reads completed (its gate, [`gate_of`]: where every segment
//! whose step waits for the GPU is an execution whose records and range Metal tracks, the
//! values of those batches the hazard state holds; else a snapshot of the queues' submitted
//! values): only then are the records the work before it wrote known. The thread then hands
//! the batch's step to the steps' threads ([`steps`], a step a thread, up to eight at once),
//! one of which records its segments (`CommandBufferShared::host_step`), each step a section of
@@ -695,8 +697,9 @@ struct Held {
binary_signals: Vec<vk::Semaphore>,
/// It holds segments, so it may need a host step.
segments: bool,
/// For its host step: each `VkQueue`'s value of the last batch submitted there once the batch
/// was otherwise ready, which the queue's completed value reaches before the step.
/// For its host step, taken once the batch was otherwise ready ([`gate_of`]): each `VkQueue`'s
/// value of the last batch submitted there that wrote what the step reads, or of the last
/// batch submitted there, which the queue's completed value reaches before the step.
gate: Option<Vec<u64>>,
/// Its command buffer has a submission check, so it may wait for checks to run.
checked: bool,
@@ -736,7 +739,8 @@ impl Held {
/// What a batch's host step waits for (`CommandBufferShared::step_waits`).
pub(crate) struct StepWaits {
/// The work submitted before it to complete (its gate): the GPU may write what it reads.
/// The work submitted before it to complete (its gate, [`gate_of`]: the batches that wrote
/// what it reads where those are known): the GPU may write what it reads.
pub(crate) gpu: bool,
/// The `VkQueue` whose work alone it waits for, where the GPU writes what it reads there alone
/// (a predicated loop's check, `command_buffer/rerun.rs`): every other queue goes on.
@@ -2422,14 +2426,16 @@ fn hasten_heads(order: &mut Order<Held>) {
}
/// Look at each line's head that is otherwise ready (not `behind` an earlier commit either,
/// its gate then covers that commit's work) and needs a host step: its gate is taken (the queues'
/// submitted values, the first time), and once every `VkQueue`'s completed value reached it (or the
/// its gate then covers that commit's work) and needs a host step: its gate is taken the first
/// time ([`gate_of`]: the values of the batches that last wrote what the step reads, or the
/// queues' submitted values), and once every `VkQueue`'s completed value reached it (or the
/// device is lost), its step goes to `left`, unless there already. The gate goes to `awaits`
/// before the completed values are read, as [`Scheduler::completions`] says. Whether a head still
/// waits at its gate.
fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left<Work>, awaits: &Awaits) -> bool {
let State {
order,
tracker,
values,
binary,
wake_by,
@@ -2463,7 +2469,10 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left<Work>, awaits:
left.push(Kind::Step, (held.buffer.hold(), held.index));
continue;
}
let gate = held.gate.get_or_insert_with(|| values.clone());
let gate = (held.gate).get_or_insert_with(|| {
let (buffer, index) = (&held.buffer, held.index);
gate_of(buffer, index, tracker, values)
});
match waits.queue_alone {
Some(queue) => awaits.gate_on(queue, gate[queue], gate.len()),
None => awaits.gate(gate),
@@ -2490,6 +2499,40 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left<Work>, awaits:
waiting
}
/// The gate of `buffer`'s batch `index`, a line's head whose host step waits for the GPU, taken
/// once the batch is otherwise ready ([`gate_heads`]): per `VkQueue`, the value of the last batch
/// submitted there that wrote what the step reads (its executions' records and ranges,
/// `CommandBufferShared::step_reads`), where `tracker` holds every such write
/// (`Tracker::last_writes`), so the step waits for those batches alone, and a command buffer's
/// executions behind one writer wait for it once; else every queue's last submitted value,
/// `values`. A gate that leaves out work submitted before it is counted
/// (`WorkCounts::host_step_gates_narrowed`).
///
/// Every batch that may write what the step reads was submitted by then: an earlier batch of its
/// line went before it, a batch of an earlier commit on another line that may write those bytes
/// holds it behind until submitted (`is_behind`, whose footprints hold the step's reads,
/// `ExecutionRange::host_reads`), and a later commit's that may write them waits behind it.
fn gate_of(
buffer: &Hold<CommandBufferShared>,
index: usize,
tracker: &Tracker<ResourceKey>,
values: &[u64],
) -> Vec<u64> {
let writes =
(buffer.step_reads(index)).and_then(|reads| tracker.last_writes(&reads, values.len()));
let Some(writes) = writes else {
return values.to_vec();
};
if writes
.iter()
.zip(values)
.any(|(write, value)| write < value)
{
buffer.device().shared().counts.host_step_gate_narrowed();
}
writes
}
/// Whether the head of commit sequence number `sequence` waits behind a batch committed before it
/// that keeps its place ([`Order::is_behind`]): one whose binary semaphores' signals are submitted
/// and whose event values are reached, as is every batch before it on its line, and whose footprint
@@ -2429,3 +2429,57 @@ fn draws_check_what_their_encoder_made_resident_against_geometry_writes_once_by_
"merged into one that meets"
);
}
/// A host step's gate (`scheduler/mod.rs`'s `gate_of`): per `VkQueue`, the last batch that wrote
/// the bytes it reads. A batch that wrote other bytes or only read them adds nothing; a write on
/// another queue that covers the older one's bytes names its own queue alone, having waited for
/// the older; a write the host saw complete is forgotten; an untracked read, or a queue past the
/// count, answers none.
#[test]
fn a_host_read_waits_for_the_last_writes_of_its_bytes_alone() {
let mut tracker = Tracker::default();
submit(
&mut tracker,
&[one(&[writes(1, bytes(0..64), shader_write())])],
on(0, 1),
);
submit(
&mut tracker,
&[one(&[writes(2, bytes(0..64), shader_write())])],
on(1, 1),
);
submit(
&mut tracker,
&[one(&[reads(1, bytes(0..64), shader_read())])],
on(0, 2),
);
let read = Access::new(
vk::PipelineStageFlags2::ALL_COMMANDS,
vk::AccessFlags2::MEMORY_READ,
);
let records = reads(1, bytes(0..8), read);
let last = |tracker: &Tracker<Key>, read: &Use<Key>| tracker.last_writes(&[read.clone()], 2);
assert_eq!(last(&tracker, &records), Some(vec![1, 0]), "the writer");
let unwritten = reads(1, bytes(64..72), read);
assert_eq!(last(&tracker, &unwritten), Some(vec![0, 0]), "no writer");
let (_, waits) = submit(
&mut tracker,
&[one(&[writes(1, bytes(0..64), shader_write())])],
on(1, 2),
);
assert_eq!(waits, [wait(on(0, 2), COMPUTE)], "the covering write waits");
assert_eq!(
last(&tracker, &records),
Some(vec![0, 2]),
"the covering writer"
);
let untracked = Use::reads(1, false, bytes(0..8), read);
assert_eq!(last(&tracker, &untracked), None, "untracked");
assert_eq!(
tracker.last_writes(&[records.clone()], 1),
None,
"a queue past the count"
);
tracker.completed(1, 2);
assert_eq!(last(&tracker, &records), Some(vec![0, 0]), "seen complete");
}
@@ -2656,6 +2656,30 @@ impl<K: Copy + Ord + Hash> Tracker<K> {
at.value.saturating_sub(1).saturating_sub(through)
}
/// Per `VkQueue`, of `queues`: the timeline value of the last batch there that wrote what
/// `reads` read, of the writes the state holds (0 where it holds none there). Once each queue
/// completed its value, every write a submitted batch made to those bytes completed and
/// reached the host (each batch ends with [`Barrier::to_host`]): the state forgets only what
/// completed, and a write it let an older one's entry go for waited for that one. `None`
/// where one of `reads` is of a resource Metal does not track, whose writes the state does not
/// hold, or names a queue past `queues`.
pub(super) fn last_writes(&self, reads: &[Use<K>], queues: usize) -> Option<Vec<u64>> {
let mut values = vec![0; queues];
for read in reads {
if !read.tracked {
return None;
}
let entries = self.resources.get(&read.key).into_iter().flatten();
for entry in entries.filter(|entry| entry.range.overlaps(&read.range)) {
for writer in entry.writers.iter() {
let value = values.get_mut(writer.at.queue)?;
*value = (*value).max(writer.at.value);
}
}
}
Some(values)
}
/// The barriers before the `encoders` of the batch submitted next, at `at`, and its waits.
/// The state is unchanged; the plan's lists come from those plans applied before gave back.
pub(super) fn plan<'a>(
+21 -3
View File
@@ -235,6 +235,7 @@ pub(crate) struct Counters {
/// By `HeldFor`, in its order: the looks that found a line's head held for each reason.
heads_held_for: [AtomicU64; HeldFor::COUNT],
heads_waiting_at_their_gate: AtomicU64,
host_step_gates_narrowed: AtomicU64,
heads_awaiting_check_signals: AtomicU64,
batches_held_past_a_look: AtomicU64,
batch_hold_nanos: AtomicU64,
@@ -2740,6 +2741,13 @@ impl Counters {
.fetch_add(1, Ordering::Relaxed);
}
/// A head's host step gate, as it was taken, left out work submitted before it
/// (`scheduler/mod.rs`'s `gate_of`).
pub(crate) fn host_step_gate_narrowed(&self) {
self.host_step_gates_narrowed
.fetch_add(1, Ordering::Relaxed);
}
/// Such a look left a head's submission checks waiting for a submitted GPU signal to land
/// (`scheduler/mod.rs`'s `check_heads`).
pub(crate) fn head_awaiting_check_signals(&self) {
@@ -6068,10 +6076,19 @@ pub struct WorkCounts {
/// behind about one batch of theirs.
pub heads_held_for_unshared_isolation: u64,
/// Times a look left a head that needs a host step waiting at its gate: the step reads what
/// the GPU may write, so it waits until every `VkQueue` completed what was submitted to it
/// when the batch was otherwise ready (a predicated loop's check waits for its own `VkQueue`
/// alone). Of `heads_held_for_host_steps`.
/// the GPU may write, so it waits until the batches that last wrote what it reads completed
/// (`host_step_gates_narrowed`), or else until every `VkQueue` completed what was submitted to
/// it when the batch was otherwise ready (a predicated loop's check waits for its own
/// `VkQueue` alone). Of `heads_held_for_host_steps`.
pub heads_waiting_at_their_gate: u64,
/// Host steps whose gate, as it was taken, left out work submitted before it: each segment
/// whose step waits for the GPU executes indirect commands whose records and range Metal
/// tracks, so the step waits for the batches that last wrote those alone, not for every
/// `VkQueue`'s last submission (the batches after the writer on its queue, and other queues'
/// work that writes neither). A command buffer's executions behind one writer then cost one
/// GPU round trip between them, not one each. Whether a gate leaves work out depends on what
/// was submitted, and seen complete, when it was taken.
pub host_step_gates_narrowed: u64,
/// Times a look left a head's submission checks waiting for a submitted GPU signal to land:
/// Metal checks a submission only once the event values it waits for are reached, so a value
/// only a submitted GPU signal reaches is waited for. Of `heads_held_for_checks`.
@@ -9138,6 +9155,7 @@ impl Device {
heads_waiting_at_their_gate: counters
.heads_waiting_at_their_gate
.load(Ordering::Relaxed),
host_step_gates_narrowed: counters.host_step_gates_narrowed.load(Ordering::Relaxed),
heads_awaiting_check_signals: counters
.heads_awaiting_check_signals
.load(Ordering::Relaxed),
@@ -10,7 +10,9 @@
//! (`execute_commands_in_buffer_indirect`). The depth the pass stores is each visible chunk's quad
//! at its depth, and the clear depth elsewhere: into a 2D texture, into slice 1 of a 2D array,
//! beside a later encoder of the command buffer that makes a shadowed texture resident, and over a
//! rasterization rate map.
//! rasterization rate map. And a frame's two passes that execute the commands after the culling
//! wait for the culling alone: not for another queue's unrelated work submitted before them, nor
//! the second for the first.
use super::degrade_notices::on_device;
use super::rate_maps::descriptor as descriptor_of_rate_map;
@@ -28,9 +30,9 @@ use metal2vulkan::pipeline::{
};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
CommandBufferStatus, ComputePipelineState, DepthStencilState, Device,
IndirectCommandBufferDescriptor, Library, LoadAction, PipelineOptions, Region,
RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture,
Buffer, CommandBuffer, CommandBufferStatus, ComputePipelineState, DepthStencilState, Device,
IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, PipelineOptions,
Region, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture,
TextureDescriptor,
};
@@ -203,18 +205,24 @@ fn shadowed(device: &Device) -> Texture {
truth.new_texture(&descriptor, 0, 48).unwrap()
}
/// The commands a kernel encodes run from the range it wrote, each drawing its chunk's quad with
/// the buffers it set onto the encoder's depth-only state: the depth the pass stores is each kept
/// chunk's, and the clear depth where the kernel kept none, in a 2D texture, in slice 1 of a 2D
/// array, beside a later encoder's shadowed texture, and over a rate map.
#[test]
fn a_kernel_s_depth_only_commands_draw_through_the_range_it_wrote() {
on_device(|device, _| {
/// The fixture's states, the commands, and the buffers the kernel and the records name.
struct Workload {
reset: ComputePipelineState,
encode: ComputePipelineState,
state: RenderPipelineState,
less: DepthStencilState,
icb: IndirectCommandBuffer,
encoder_args: Buffer,
positions: Buffer,
indices: Buffer,
camera: Buffer,
visible: Buffer,
range: Buffer,
}
impl Workload {
fn new(device: &Device) -> Workload {
let library = library(device);
let reset = kernel(device, &library, "dio_reset");
let encode = kernel(device, &library, "dio_encode");
let state = depth_only(device, &library);
let less = less(device);
let mut descriptor = IndirectCommandBufferDescriptor::new();
descriptor.command_types = IndirectCommandType::DRAW_INDEXED;
descriptor.inherit_pipeline_state = true;
@@ -224,12 +232,90 @@ fn a_kernel_s_depth_only_commands_draw_through_the_range_it_wrote() {
.new_indirect_command_buffer(&descriptor, CHUNKS, ResourceOptions::shared())
.unwrap();
let encoder_args = buffer_with(device, &icb.gpu_resource_id().0.to_le_bytes()).unwrap();
let positions = buffer_with(device, &positions()).unwrap();
let indices = buffer_with(device, &indices()).unwrap();
let camera: Vec<u8> = CAMERA.iter().flat_map(|f| f.to_le_bytes()).collect();
let camera = buffer_with(device, &camera).unwrap();
let visible = buffer_with(device, &VISIBLE.to_le_bytes()).unwrap();
let range = buffer_with(device, &[0xFF; 8]).unwrap();
Workload {
reset: kernel(device, &library, "dio_reset"),
encode: kernel(device, &library, "dio_encode"),
state: depth_only(device, &library),
less: less(device),
icb,
encoder_args,
positions: buffer_with(device, &positions()).unwrap(),
indices: buffer_with(device, &indices()).unwrap(),
camera: buffer_with(device, &camera).unwrap(),
visible: buffer_with(device, &VISIBLE.to_le_bytes()).unwrap(),
range: buffer_with(device, &[0xFF; 8]).unwrap(),
}
}
/// The culling, into `command_buffer`: a blit resets the commands, then a kernel resets the
/// range and one encodes the kept chunks' commands, taking each its place in the range.
fn cull(&self, command_buffer: &CommandBuffer) {
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.reset_commands_in_buffer(&self.icb, 0..CHUNKS).unwrap();
blit.end_encoding().unwrap();
let mut writing = command_buffer.compute_command_encoder().unwrap();
writing.set_compute_pipeline_state(&self.reset).unwrap();
writing.set_buffer(Some(&self.range), 0, 0).unwrap();
let one = Size::new(1, 1, 1);
writing.dispatch_threads(one, one).unwrap();
writing.set_compute_pipeline_state(&self.encode).unwrap();
writing.set_buffer(Some(&self.encoder_args), 0, 0).unwrap();
writing.set_buffer(Some(&self.positions), 0, 1).unwrap();
writing.set_buffer(Some(&self.indices), 0, 2).unwrap();
writing.set_buffer(Some(&self.camera), 0, 3).unwrap();
writing.set_buffer(Some(&self.range), 4, 4).unwrap();
writing.set_buffer(Some(&self.visible), 0, 5).unwrap();
writing
.use_resource(self.icb.as_resource(), ResourceUsage::WRITE)
.unwrap();
let chunks = Size::new(CHUNKS, 1, 1);
writing.dispatch_threads(chunks, chunks).unwrap();
writing.end_encoding().unwrap();
}
/// A pass of `pass` into `command_buffer` that executes the commands through the range under
/// the depth-only state.
fn draw(&self, command_buffer: &CommandBuffer, pass: &RenderPassDescriptor) {
let mut encoder = command_buffer.render_command_encoder(pass).unwrap();
encoder.set_render_pipeline_state(&self.state).unwrap();
encoder.set_depth_stencil_state(&self.less).unwrap();
encoder.set_depth_bias(0.0, 2.0, 0.0).unwrap();
for buffer in [&self.positions, &self.indices, &self.camera] {
encoder
.use_resource(
buffer.as_resource(),
ResourceUsage::READ,
RenderStages::VERTEX,
)
.unwrap();
}
encoder
.execute_commands_in_buffer_indirect(&self.icb, &self.range, 0)
.unwrap();
encoder.end_encoding().unwrap();
}
}
/// A pass that clears `target`'s depth at slice `slice` and stores it.
fn depth_pass(target: &Texture, slice: u64) -> RenderPassDescriptor {
let mut pass = RenderPassDescriptor::new();
pass.depth_attachment.texture = Some(target.clone());
pass.depth_attachment.slice = slice;
pass.depth_attachment.load_action = LoadAction::Clear;
pass.depth_attachment.clear_depth = 1.0;
pass.depth_attachment.store_action = StoreAction::Store;
pass
}
/// The commands a kernel encodes run from the range it wrote, each drawing its chunk's quad with
/// the buffers it set onto the encoder's depth-only state: the depth the pass stores is each kept
/// chunk's, and the clear depth where the kernel kept none, in a 2D texture, in slice 1 of a 2D
/// array, beside a later encoder's shadowed texture, and over a rate map.
#[test]
fn a_kernel_s_depth_only_commands_draw_through_the_range_it_wrote() {
on_device(|device, _| {
let work = Workload::new(device);
let queue = device.new_command_queue().unwrap();
let mut runs = Vec::new();
for variant in [
@@ -244,55 +330,14 @@ fn a_kernel_s_depth_only_commands_draw_through_the_range_it_wrote() {
};
let target = target(device, slices);
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.reset_commands_in_buffer(&icb, 0..CHUNKS).unwrap();
blit.end_encoding().unwrap();
let mut writing = command_buffer.compute_command_encoder().unwrap();
writing.set_compute_pipeline_state(&reset).unwrap();
writing.set_buffer(Some(&range), 0, 0).unwrap();
let one = Size::new(1, 1, 1);
writing.dispatch_threads(one, one).unwrap();
writing.set_compute_pipeline_state(&encode).unwrap();
writing.set_buffer(Some(&encoder_args), 0, 0).unwrap();
writing.set_buffer(Some(&positions), 0, 1).unwrap();
writing.set_buffer(Some(&indices), 0, 2).unwrap();
writing.set_buffer(Some(&camera), 0, 3).unwrap();
writing.set_buffer(Some(&range), 4, 4).unwrap();
writing.set_buffer(Some(&visible), 0, 5).unwrap();
writing
.use_resource(icb.as_resource(), ResourceUsage::WRITE)
.unwrap();
let chunks = Size::new(CHUNKS, 1, 1);
writing.dispatch_threads(chunks, chunks).unwrap();
writing.end_encoding().unwrap();
let mut pass = RenderPassDescriptor::new();
pass.depth_attachment.texture = Some(target.clone());
pass.depth_attachment.slice = slice;
pass.depth_attachment.load_action = LoadAction::Clear;
pass.depth_attachment.clear_depth = 1.0;
pass.depth_attachment.store_action = StoreAction::Store;
work.cull(&command_buffer);
let mut pass = depth_pass(&target, slice);
if variant == Variant::RateMap {
let map = descriptor_of_rate_map(SIZE as u32, SIZE as u32, &[(0.5, 0.5)]);
pass.rasterization_rate_map =
Some(device.new_rasterization_rate_map(&map).unwrap());
}
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
encoder.set_render_pipeline_state(&state).unwrap();
encoder.set_depth_stencil_state(&less).unwrap();
encoder.set_depth_bias(0.0, 2.0, 0.0).unwrap();
for buffer in [&positions, &indices, &camera] {
encoder
.use_resource(
buffer.as_resource(),
ResourceUsage::READ,
RenderStages::VERTEX,
)
.unwrap();
}
encoder
.execute_commands_in_buffer_indirect(&icb, &range, 0)
.unwrap();
encoder.end_encoding().unwrap();
work.draw(&command_buffer, &pass);
let later = (variant == Variant::LaterShadow).then(|| shadowed(device));
if let Some(texture) = &later {
let mut after = command_buffer.compute_command_encoder().unwrap();
@@ -324,3 +369,53 @@ fn a_kernel_s_depth_only_commands_draw_through_the_range_it_wrote() {
}
});
}
/// A frame's executions after the culling wait for the culling alone. One queue commits the
/// culling; another commits unrelated work (a fill of a buffer of its own), submitted before the
/// frame is committed; then the first commits the frame: two passes, each into a target of its
/// own, that execute the commands through the range. Each pass's host step waits for the batches
/// that wrote the records and the range, so both gates leave work submitted before them out (the
/// unrelated fill, and for the second the first pass's batch): `host_step_gates_narrowed` counts
/// two, against none where a gate is every queue's last submission. Both targets hold each kept
/// chunk's depth.
#[test]
fn a_frame_s_executions_wait_for_the_culling_alone() {
on_device(|device, _| {
let work = Workload::new(device);
let queue = device.new_command_queue().unwrap();
let other = device.new_command_queue().unwrap();
let culling = queue.command_buffer().unwrap();
work.cull(&culling);
culling.commit().unwrap();
let filled = buffer_with(device, &[0; 1 << 16]).unwrap();
let unrelated = other.command_buffer().unwrap();
let mut fill = unrelated.blit_command_encoder().unwrap();
fill.fill_buffer(&filled, 0..1 << 16, 0x5A).unwrap();
fill.end_encoding().unwrap();
unrelated.commit().unwrap();
unrelated.wait_until_scheduled().unwrap();
let before = device.work_counts();
let targets = [target(device, None), target(device, None)];
let frame = queue.command_buffer().unwrap();
for target in &targets {
work.draw(&frame, &depth_pass(target, 0));
}
frame.commit().unwrap();
frame.wait_until_completed_for(WAIT).unwrap();
let after = device.work_counts();
unrelated.wait_until_completed_for(WAIT).unwrap();
let narrowed = after.host_step_gates_narrowed - before.host_step_gates_narrowed;
let steps = after.host_steps_recorded - before.host_steps_recorded;
let drawn: Vec<Vec<f32>> = targets.iter().map(|target| depths(target, 0)).collect();
let statuses = [culling.status(), unrelated.status(), frame.status()];
eprintln!(
"statuses {statuses:?}, refusal {:?}, steps {steps}, gates narrowed {narrowed}, \
depths {drawn:?}",
frame.refusal()
);
assert_eq!(statuses, [CommandBufferStatus::Completed; 3]);
assert_eq!(frame.refusal(), None);
assert_eq!(drawn, [expected(), expected()]);
assert_eq!((steps, narrowed), (2, 2), "host steps, gates narrowed");
});
}
@@ -2964,6 +2964,7 @@ field metal2vulkan-runtime::WorkCounts.host_step_chunk_copies_put_off pub host_s
field metal2vulkan-runtime::WorkCounts.host_step_chunks_kept pub host_step_chunks_kept: u64
field metal2vulkan-runtime::WorkCounts.host_step_chunks_recorded_again pub host_step_chunks_recorded_again: u64
field metal2vulkan-runtime::WorkCounts.host_step_compare_nanos pub host_step_compare_nanos: u64
field metal2vulkan-runtime::WorkCounts.host_step_gates_narrowed pub host_step_gates_narrowed: u64
field metal2vulkan-runtime::WorkCounts.host_step_nanos pub host_step_nanos: u64
field metal2vulkan-runtime::WorkCounts.host_step_pipelines_made pub host_step_pipelines_made: u64
field metal2vulkan-runtime::WorkCounts.host_step_records_compared pub host_step_records_compared: u64
Can't render this file because it is too large.
+9 -7
View File
@@ -2335,12 +2335,14 @@ bound.
may name past four pass 256 (the states: every live one made with `supportIndirectCommandBuffers`,
or the encoder's where the buffer inherits it), where they run with one and its commands times the
states past twelve pass 512, and where its commands times its states pass 32,768. Every other
execution runs on the GPU alone and announces nothing. Cost: one GPU-to-CPU round trip per
execution: its command buffer's work before it, and every batch submitted before that on any
queue, completes before the CPU records its commands from their records, on a thread of the
runtime's, and submits the rest; meanwhile the device's other batches go, but for a later one
that shares a resource the execution may reach (one made resident, the records), and the first
command of a threadgroup size or threadgroup lengths its pipeline state has not dispatched makes
execution runs on the GPU alone and announces nothing. Cost: a GPU-to-CPU round trip: the
batches that last wrote its records and its range complete before the CPU records its commands
from their records, on a thread of the runtime's, and submits the rest, so a command buffer's
executions behind one writer wait for it once (where Metal tracks neither, or the step reads
more, as inside a block of command predication: its command buffer's work before it, and every
batch submitted before that on any queue); meanwhile the device's other batches go, but for a
later one that shares a resource the execution may reach (one made resident, the records), and
the first command of a threadgroup size or threadgroup lengths its pipeline state has not dispatched makes
that VkPipeline then, as does a render command's draw of a state the CPU set on none of the
commands. The commands run in the large-buffer form (their range-limited buffer slots at device
addresses, with in-shader bounds checks), whose variants the commit compiles for every pipeline
@@ -4876,7 +4878,7 @@ each item named states the rule in full.
as `commit` records them, and `commit` returns what a command refuses; but for a buffer the
command buffer made resident for writing, as a route met after the commit may still write the
records before they run (another queue's command buffer the work waits for through an event,
whose writes Metal runs), the host step records them once the work before it completed, and the
whose writes Metal runs), the host step records them once the work that wrote them completed, and the
command buffer fails at that batch's submission only where they are still refused
(`WorkCounts::commit_refusals_held`).
- **A render execution's range read from a buffer is read before its pass**