From 5b260257e0af736bafbbd226f543c3cc31b3a685 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 26 Nov 2026 00:54:46 -0800 Subject: [PATCH] Runtime and replay player: count each dispatch barrier in one source, and print the device's buffer alignment What: Metrics::dispatch_hazard_barriers is now the sum of nine sources, each such barrier in exactly one: dispatch_after_write_barriers and dispatch_write_after_read_barriers (the dispatch's own dependencies), then dispatch_encoder_end_barriers, dispatch_pass_end_barriers, dispatch_indirect_barriers, dispatch_unbound_barriers, dispatch_arena_piece_barriers, dispatch_heap_barriers and dispatch_other_barriers. The replay player prints the nine on each frame line's executed counters and in the report's totals. The tally's bit mask is a u128 (69 metrics). The rule for a barrier with several causes: it counts under the dispatch's own dependency where it has one, first a write (it reads or writes a resource a command since the last barrier wrote), then a write after a read (it writes one that was only read), both by the resource's own id; otherwise under the first source in this order: an encoder that wrote ended; a render pass moved nothing home (or copied a resolve into a buffer); an indirect dispatch after a write since the last barrier that reached argument reads, whatever buffer was written; an access outside every resource (a read after a write, a write after any access, or the barrier such a write owes); a Private-arena piece after the first; a conflict through a heap's one id alone (an exported surface's buffer and planes, which share one id, count here too); anything else (a memory barrier call, a release to another API, a concurrent encoder after commands that touched anything). An owed barrier keeps the first of its causes in that order. In a concurrent encoder the dependency is read only where a barrier is owed, as Metal orders nothing else there. Two buffers of one heap over the same bytes count under the heap: at buffer level they are two resources. How: a heap's resources are marked in the hazard sets by the heap's id, as before, and also by their own ids in a second table of the sets that places no barrier and only tells a dependency on the resource from a conflict through the heap's id. Building::owe takes its cause and no longer starts the sets again; the command that pays the owed barrier does, after reading them: Building::command clears them after paying, and dispatch_hazards takes its command buffer without paying (current_command) and pays the owed barrier itself, counted by every cause it has. Where barriers go is unchanged: each path that paid an owed barrier records the one barrier it recorded before, and the sets start again at the same barriers. Rider: Device::buffer_alignment (no Metal counterpart) returns the alignment Vulkan's memory requirements gave the runtime's buffers, which the pool read at the device's making. The replay player's device line prints it (`device NAME runtime rt buffer alignment N`), and the device test prints it and checks it is a power of two. The runtime prints no line of its own at a device's making, so a consumer's log shows it only by reading this accessor. Why: the planner's reading of the dispatch-hazard barriers: whether the sources that are not the guest's own dependencies reach a quarter of a frame's barriers on any stream. The buffer alignment goes into every lab log because the ring and the zero address assume a multiple of 16 with no query behind it. Tests: every_device_counts_each_dispatch_barrier_in_one_source checks the write after a read, two encoders' ends (the second's dispatch reading the write before it counts as that dependency), a render pass's end that moved nothing home, an indirect dispatch after a write of another buffer, a read outside every resource and a memory barrier in a concurrent encoder, each in its one source with the sources summing to the dispatch barriers; every_device_places_barriers_at_hazards_only checks the dependent and concurrent encoders' in the write dependency and none for independent dispatches; every_device_orders_a_heap_s_resources_as_one checks the heap's source, and the write dependency for one buffer of a heap used twice; the arena test checks its pieces' barriers in the arena source; the hazard sets' unit tests check the own-id table. The signatures table is blessed (9 fields, 1 method). Verified: nothing yet in this commit; the gate (fmt, clippy in three configurations, Rustdoc, the runtime suite on lavapipe and the validation suite) runs on it next. --- crates/metal2vulkan-runtime/README.md | 6 +- crates/metal2vulkan-runtime/src/command.rs | 95 ++++++-- crates/metal2vulkan-runtime/src/counters.rs | 132 +++++++++-- crates/metal2vulkan-runtime/src/device.rs | 8 + crates/metal2vulkan-runtime/src/encoder.rs | 114 +++++++-- crates/metal2vulkan-runtime/src/hazard.rs | 79 +++++-- crates/metal2vulkan-runtime/src/memory.rs | 6 + .../metal2vulkan-runtime/src/tests/compute.rs | 220 +++++++++++++++++- .../metal2vulkan-runtime/src/tests/device.rs | 8 + .../metal2vulkan-runtime/src/tests/hazard.rs | 72 +++++- .../src/tests/private_arena.rs | 4 + .../src/bin/command-replay.rs | 24 +- .../src/replay/new_runtime/mod.rs | 30 +++ crates/metal2vulkan/tests/api_signatures.tsv | 10 + docs/REPLAY-STREAM.md | 13 +- 15 files changed, 704 insertions(+), 117 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 726605c77..1be184117 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -184,8 +184,10 @@ and a call that needs a runtime thread after `Device::quiesce` (`Error::Quiesced `Device::counters` returns a handle that stays readable after the device is gone. `metrics()` are cumulative counts (submissions, passes, barriers, each counted in one cause: a pass's start, a -pass's move home, a blit, a dispatch's hazard, a segment's end, an upload or another, bytes -copied, pipelines created, blocks made, +pass's move home, a blit, a dispatch's hazard, a segment's end, an upload or another, and a +dispatch's in one source: its own dependency on a write or on a read, an encoder's end, a render +pass's end, an indirect dispatch after a write, an access outside every resource, a Private-arena +piece, a heap's one id or another; bytes copied, pipelines created, blocks made, first-use waits, kernels lowered, kernels read from the cache directory, upload waits, pushes, and the draws and dispatches whose push bytes the command buffer already held), and times in nanoseconds, in total and longest: among them each `vkQueueSubmit2` call's time inside the diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index 8a261f307..3bdfe5b99 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -196,6 +196,39 @@ impl CbState { } } +/// Why a barrier is owed before the next command ([`Building::owe`]), in the order a dispatch's +/// barrier that has several causes is counted by: an owed barrier a dispatch pays is counted in +/// its source's bucket where the dispatch has no dependency of its own on the sets +/// ([`Metrics::dispatch_hazard_barriers`](crate::Metrics::dispatch_hazard_barriers)). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Owed { + /// An encoder that wrote ended. + EncoderEnd, + /// A render pass ended with no attachment to move home ([`Building::owe_pass`]). + PassEnd, + /// A dispatch wrote through an address outside its resources. + Unbound, + /// A dispatch over a Private arena records a piece after its first. + ArenaPiece, + /// A memory barrier was asked for, a block was released to another API, or a concurrent + /// encoder began after commands that touched anything. + Other, +} + +impl Owed { + /// The bucket a dispatch's barrier that pays it is counted in, where the dispatch has no + /// dependency of its own. + pub(crate) fn metric(self) -> Metric { + match self { + Owed::EncoderEnd => Metric::DispatchEncoderEndBarriers, + Owed::PassEnd => Metric::DispatchPassEndBarriers, + Owed::Unbound => Metric::DispatchUnboundBarriers, + Owed::ArenaPiece => Metric::DispatchArenaPieceBarriers, + Owed::Other => Metric::DispatchOtherBarriers, + } + } +} + /// What a command buffer records until its commit; an open encoder holds it. pub(crate) struct Building { pub(crate) device: Device, @@ -207,10 +240,11 @@ pub(crate) struct Building { /// Its pair of timestamp queries, from its first record; None before it and where it runs /// untimed. stamps: Option, - /// A barrier owed before the next command: an encoder that wrote ended, a memory barrier was - /// asked for, a dispatch wrote through an address outside its resources, a render pass - /// ended, or a block was released to another API. The segment's own end barrier pays it too. - owed: bool, + /// A barrier owed before the next command, by the first of its causes in [`Owed`]'s order: an + /// encoder that wrote ended, a memory barrier was asked for, a dispatch wrote through an + /// address outside its resources, a render pass ended, or a block was released to another + /// API. The segment's own end barrier pays it too. + owed: Option, /// The barrier owed orders a render pass ([`Building::owe_pass`]) or a release /// ([`Building::release_command`]) before what follows it: it reaches every later command /// ([`Reach::Commands`]), whatever the command that pays it names. @@ -440,7 +474,7 @@ impl CommandBuffer { }, started: false, stamps: None, - owed: false, + owed: None, owed_all: false, args_unordered: false, bound: None, @@ -1086,7 +1120,7 @@ impl Building { self.host_written |= back.iter().any(|copy| copy.shared); } // Its end barrier pays what is owed and starts the hazard sets again. - self.owed = false; + self.owed = None; self.owed_all = false; self.args_unordered = false; if let Some(recorder) = &mut self.gpu.recorder { @@ -1138,22 +1172,37 @@ impl Building { /// The current segment's command buffer, with the barrier owed recorded first, reaching what /// the caller records next (`reach`): a dispatch's, counted as its barrier - /// ([`Metrics::dispatch_hazard_barriers`](crate::Metrics::dispatch_hazard_barriers)). Commands - /// after a signal go in a new segment. + /// ([`Metrics::dispatch_hazard_barriers`](crate::Metrics::dispatch_hazard_barriers)) in its + /// cause's bucket ([`Owed::metric`]), after which the hazard sets start again. Commands after a + /// signal go in a new segment. pub(crate) fn command(&mut self, reach: Reach) -> Result { let command = self.current()?; - if self.owed { - self.barrier(command, reach, Metric::DispatchHazardBarriers); + if let Some(owed) = self.owed { + self.barrier(command, reach, owed.metric()); + self.hazards().clear(); } Ok(command) } + /// The current segment's command buffer, with what is owed left for the caller to pay + /// ([`owed`](Self::owed)): a dispatch's, which counts its barrier by all of its causes. + /// Commands after a signal go in a new segment. + pub(crate) fn current_command(&mut self) -> Result { + self.current() + } + + /// The barrier owed before the next command, by the first of its causes; `None` where none + /// is. + pub(crate) fn owed(&self) -> Option { + self.owed + } + /// The current segment's command buffer, for commands that record a barrier of their own /// first that orders every earlier command before every later one and makes their writes /// visible to them (a blit's): it pays what is owed, and the hazard sets start again. pub(crate) fn ordered_command(&mut self) -> Result { let command = self.current()?; - self.owed = false; + self.owed = None; self.owed_all = false; self.args_unordered = false; self.hazards().clear(); @@ -1178,13 +1227,13 @@ impl Building { pub(crate) fn barrier(&mut self, command: vk::CommandBuffer, reach: Reach, cause: Metric) { // One owed after a render pass or a release reaches every later command, whatever the // caller names. - let reach = match self.owed && self.owed_all { + let reach = match self.owed.is_some() && self.owed_all { true => Reach::Commands, false => reach, }; record::barrier(&self.device.core().device, command, reach); self.tally.count(cause); - self.owed = false; + self.owed = None; self.owed_all = false; if reach.reaches_indirect() { self.args_unordered = false; @@ -1304,13 +1353,12 @@ impl Building { .hazards } - /// Owes a barrier before the next command, and starts the hazard sets again: it orders - /// everything before it. - pub(crate) fn owe(&mut self) { - self.owed = true; - if let Some(recorder) = &mut self.gpu.recorder { - recorder.hazards.clear(); - } + /// Owes a barrier before the next command, for `cause`, kept with the first of the causes + /// owed in [`Owed`]'s order. The hazard sets start again where it is paid, which orders + /// everything before it: the command that pays it reads them first, to count it by what that + /// command depends on. + pub(crate) fn owe(&mut self, cause: Owed) { + self.owed = Some(self.owed.map_or(cause, |owed| owed.min(cause))); } /// A render pass ended with no attachment to move home: the barrier that orders it before @@ -1318,7 +1366,7 @@ impl Building { /// command, or paid by the segment's end barrier where none follows. A command buffer that /// ends with a pass records one barrier after it, its end's. pub(crate) fn owe_pass(&mut self) { - self.owe(); + self.owe(Owed::PassEnd); self.owed_all = true; } @@ -1332,7 +1380,8 @@ impl Building { /// follows. pub(crate) fn release_command(&mut self) -> Result { let command = self.current()?; - self.owe_pass(); + self.owe(Owed::Other); + self.owed_all = true; Ok(command) } @@ -1353,7 +1402,7 @@ impl Building { .as_ref() .is_some_and(|recorder| recorder.hazards.touched()) { - self.owe(); + self.owe(Owed::Other); } } diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index ec94cb13d..4d8891e85 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -221,8 +221,24 @@ pub(crate) enum Metric { PassHomeBarriers, /// [`Metrics::blit_barriers`]. BlitBarriers, - /// [`Metrics::dispatch_hazard_barriers`]. - DispatchHazardBarriers, + /// [`Metrics::dispatch_after_write_barriers`]. + DispatchAfterWriteBarriers, + /// [`Metrics::dispatch_write_after_read_barriers`]. + DispatchWriteAfterReadBarriers, + /// [`Metrics::dispatch_encoder_end_barriers`]. + DispatchEncoderEndBarriers, + /// [`Metrics::dispatch_pass_end_barriers`]. + DispatchPassEndBarriers, + /// [`Metrics::dispatch_indirect_barriers`]. + DispatchIndirectBarriers, + /// [`Metrics::dispatch_unbound_barriers`]. + DispatchUnboundBarriers, + /// [`Metrics::dispatch_arena_piece_barriers`]. + DispatchArenaPieceBarriers, + /// [`Metrics::dispatch_heap_barriers`]. + DispatchHeapBarriers, + /// [`Metrics::dispatch_other_barriers`]. + DispatchOtherBarriers, /// [`Metrics::segment_end_barriers`]. SegmentEndBarriers, /// [`Metrics::upload_barriers`]. @@ -345,7 +361,15 @@ const METRIC_ORDER: [Metric; METRICS] = [ Metric::PassStartBarriers, Metric::PassHomeBarriers, Metric::BlitBarriers, - Metric::DispatchHazardBarriers, + Metric::DispatchAfterWriteBarriers, + Metric::DispatchWriteAfterReadBarriers, + Metric::DispatchEncoderEndBarriers, + Metric::DispatchPassEndBarriers, + Metric::DispatchIndirectBarriers, + Metric::DispatchUnboundBarriers, + Metric::DispatchArenaPieceBarriers, + Metric::DispatchHeapBarriers, + Metric::DispatchOtherBarriers, Metric::SegmentEndBarriers, Metric::UploadBarriers, Metric::OtherBarriers, @@ -418,11 +442,11 @@ const _: () = { pub(crate) struct Tally { counts: [u64; METRICS], /// The metrics counted since the tally was last added, a bit each at its index. - counted: u64, + counted: u128, } // Each metric has its bit in a tally's `counted`. -const _: () = assert!(METRICS <= u64::BITS as usize); +const _: () = assert!(METRICS <= u128::BITS as usize); impl Default for Tally { fn default() -> Self { @@ -703,7 +727,15 @@ struct Atomics { pass_start_barriers: AtomicU64, pass_home_barriers: AtomicU64, blit_barriers: AtomicU64, - dispatch_hazard_barriers: AtomicU64, + dispatch_after_write_barriers: AtomicU64, + dispatch_write_after_read_barriers: AtomicU64, + dispatch_encoder_end_barriers: AtomicU64, + dispatch_pass_end_barriers: AtomicU64, + dispatch_indirect_barriers: AtomicU64, + dispatch_unbound_barriers: AtomicU64, + dispatch_arena_piece_barriers: AtomicU64, + dispatch_heap_barriers: AtomicU64, + dispatch_other_barriers: AtomicU64, segment_end_barriers: AtomicU64, upload_barriers: AtomicU64, other_barriers: AtomicU64, @@ -967,7 +999,15 @@ impl Counters { Metric::PassStartBarriers => &a.pass_start_barriers, Metric::PassHomeBarriers => &a.pass_home_barriers, Metric::BlitBarriers => &a.blit_barriers, - Metric::DispatchHazardBarriers => &a.dispatch_hazard_barriers, + Metric::DispatchAfterWriteBarriers => &a.dispatch_after_write_barriers, + Metric::DispatchWriteAfterReadBarriers => &a.dispatch_write_after_read_barriers, + Metric::DispatchEncoderEndBarriers => &a.dispatch_encoder_end_barriers, + Metric::DispatchPassEndBarriers => &a.dispatch_pass_end_barriers, + Metric::DispatchIndirectBarriers => &a.dispatch_indirect_barriers, + Metric::DispatchUnboundBarriers => &a.dispatch_unbound_barriers, + Metric::DispatchArenaPieceBarriers => &a.dispatch_arena_piece_barriers, + Metric::DispatchHeapBarriers => &a.dispatch_heap_barriers, + Metric::DispatchOtherBarriers => &a.dispatch_other_barriers, Metric::SegmentEndBarriers => &a.segment_end_barriers, Metric::UploadBarriers => &a.upload_barriers, Metric::OtherBarriers => &a.other_barriers, @@ -1802,18 +1842,33 @@ impl Counters { }; let stage = |stage: Stage| (a.stages[stage as usize].each_ref()).map(|n| n.load(Relaxed)); let stage_nanos = |stage: Stage| a.stage_nanos[stage as usize].load(Relaxed); - // Each barrier counts in one cause; their sum is every barrier. - let causes = [ - &a.pass_start_barriers, - &a.pass_home_barriers, - &a.blit_barriers, - &a.dispatch_hazard_barriers, - &a.segment_end_barriers, - &a.upload_barriers, - &a.other_barriers, + // A dispatch's barrier counts in one source, and each barrier in one cause; their sums + // are every dispatch's barriers and every barrier. + let sources = [ + &a.dispatch_after_write_barriers, + &a.dispatch_write_after_read_barriers, + &a.dispatch_encoder_end_barriers, + &a.dispatch_pass_end_barriers, + &a.dispatch_indirect_barriers, + &a.dispatch_unbound_barriers, + &a.dispatch_arena_piece_barriers, + &a.dispatch_heap_barriers, + &a.dispatch_other_barriers, ] .map(|n| n.load(Relaxed)); - let [pass_start, pass_home, blit, dispatch_hazard, segment_end, upload, other] = causes; + let dispatch_hazard = sources.iter().sum(); + let causes = [ + a.pass_start_barriers.load(Relaxed), + a.pass_home_barriers.load(Relaxed), + a.blit_barriers.load(Relaxed), + dispatch_hazard, + a.segment_end_barriers.load(Relaxed), + a.upload_barriers.load(Relaxed), + a.other_barriers.load(Relaxed), + ]; + let [pass_start, pass_home, blit, _, segment_end, upload, other] = causes; + let [on_write, on_read, encoder_end, pass_end, indirect, unbound, arena, heap, rest] = + sources; Metrics { submissions: a.submissions.load(Relaxed), submit_infos: a.submit_infos.load(Relaxed), @@ -1855,6 +1910,15 @@ impl Counters { pass_home_barriers: pass_home, blit_barriers: blit, dispatch_hazard_barriers: dispatch_hazard, + dispatch_after_write_barriers: on_write, + dispatch_write_after_read_barriers: on_read, + dispatch_encoder_end_barriers: encoder_end, + dispatch_pass_end_barriers: pass_end, + dispatch_indirect_barriers: indirect, + dispatch_unbound_barriers: unbound, + dispatch_arena_piece_barriers: arena, + dispatch_heap_barriers: heap, + dispatch_other_barriers: rest, segment_end_barriers: segment_end, upload_barriers: upload, other_barriers: other, @@ -2328,8 +2392,40 @@ pub struct Metrics { /// Of [`barriers`](Self::barriers), those a dispatch records before it: at a hazard with an /// earlier dispatch of its encoder, or paying one an earlier command owed (an encoder that /// wrote, a memory barrier call, a write through an address outside a dispatch's resources, a - /// render pass that moved nothing home, a release to another API). + /// render pass that moved nothing home, a release to another API). Each counts in one of the + /// nine sources below, whose sum this is: where it has several, in the dependency on a write + /// or on a read where the dispatch has one at its resources' level, and otherwise in the first + /// of the other seven, in their order. pub dispatch_hazard_barriers: u64, + /// Of [`dispatch_hazard_barriers`](Self::dispatch_hazard_barriers), those where the dispatch + /// reads or writes a resource of its own (not through a heap's or a surface's one id) that a + /// command since the last barrier wrote. + pub dispatch_after_write_barriers: u64, + /// Of those, the ones where the dispatch writes such a resource that a command since the last + /// barrier read, and none wrote. + pub dispatch_write_after_read_barriers: u64, + /// Of those, the ones owed by an encoder that wrote anything, paid by the next encoder's first + /// dispatch, which has neither dependency. + pub dispatch_encoder_end_barriers: u64, + /// Of those, the ones owed by a render pass that moved nothing home, or that copied a resolve + /// into a buffer, paid by a dispatch with neither dependency. + pub dispatch_pass_end_barriers: u64, + /// Of those, the ones before an indirect dispatch after a write since the last barrier that + /// reached indirect argument reads, whatever buffer was written. + pub dispatch_indirect_barriers: u64, + /// Of those, the ones for an access through an address outside every resource: a read after + /// a write, a write after any access, or the barrier such a write owes the next dispatch. + pub dispatch_unbound_barriers: u64, + /// Of those, the ones before each piece of a dispatch split for its Private-arena slots but + /// the first in a block taken new: the piece reuses slots an earlier command may have used. + pub dispatch_arena_piece_barriers: u64, + /// Of those, the ones at a conflict through the one id of a heap's resources (or an exported + /// surface's buffer and planes), which Metal tracks as one resource. + pub dispatch_heap_barriers: u64, + /// Of those, the rest: owed by a memory barrier call, a release to another API, or a + /// concurrent encoder after commands that touched resources, and paid by a dispatch with + /// neither dependency. + pub dispatch_other_barriers: u64, /// Of [`barriers`](Self::barriers), the one that ends each segment with commands of a command /// buffer, paying what is owed. pub segment_end_barriers: u64, diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index 61ae4af4f..f7ffe7505 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -994,6 +994,14 @@ impl Device { &self.shared.core.consumer_features } + /// No Metal counterpart: the alignment of the device's buffers of the runtime's usage, which + /// Vulkan's memory requirements give (`vkGetDeviceBufferMemoryRequirements`) and the device + /// read once at its making: Vulkan holds it the same for every such buffer, and every block's + /// first byte is a multiple of it. + pub fn buffer_alignment(&self) -> u64 { + self.shared.core.pool.alignment() + } + /// No Metal counterpart: the memory types the device's buffers are allocated from, as the /// floor chose them on the device. pub fn memory_types(&self) -> floor::MemoryTypes { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 41df2626d..5255c1a1e 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -4,14 +4,14 @@ use crate::alias::Placement; use crate::arena; use crate::buffer::{Buffer, BufferInner, BufferObject}; use crate::coherence::Range; -use crate::command::{Building, CommandBuffer}; +use crate::command::{Building, CommandBuffer, Owed}; use crate::counters::Metric; use crate::device::Core; use crate::error::{Error, Gap, Limit, PartialThreadgroupsSite, Refusal, StageInKind}; use crate::fence::Fence; use crate::floor; use crate::function_table::VisibleFunctionTable; -use crate::hazard::Access; +use crate::hazard::{Access, Dependency}; use crate::indirect::IndirectCommandBuffer; use crate::kept::{Handle, Lent, Uncounted}; use crate::memory::BlockId; @@ -932,7 +932,7 @@ impl ComputeCommandEncoder { /// `memoryBarrierWithScope:` and `memoryBarrierWithResources:count:`: one global memory /// barrier either way, before the next dispatch. pub fn memory_barrier(&mut self) { - self.building().owe(); + self.building().owe(Owed::Other); } /// `updateFence:`: encoders that wait on `fence` after this one, of any queue, see what this @@ -1061,7 +1061,7 @@ impl ComputeCommandEncoder { fn end(&mut self) { if let Some(mut building) = self.building.take() { if self.wrote { - building.owe(); + building.owe(Owed::EncoderEnd); } self.command_buffer.close_encoder(building); } @@ -1397,7 +1397,7 @@ impl ComputeCommandEncoder { // reached before. if let Some((_, fresh)) = arena { if !(first && fresh) { - building.owe(); + building.owe(Owed::ArenaPiece); } building.count(Metric::PrivateArenaPieces); } @@ -1938,14 +1938,17 @@ pub(crate) struct Accesses<'a> { impl Accesses<'_> { /// Each resource the dispatch of a kernel of `interface` touches, with its access, by its id /// in the hazard sets ([`Buffer::tracked_id`], [`Texture::tracked_id`]: a heap's resources - /// take the heap's). + /// take the heap's) and its own as bytes ([`Buffer::id`], [`Texture::hazard_id`]), the two + /// equal but for a resource that takes a shared id. pub(crate) fn each<'b>( &'b self, interface: &'b Interface, - ) -> impl Iterator + 'b { + ) -> impl Iterator + 'b { let slots = interface.buffers.iter().filter_map(move |&(slot, access)| { match self.slots.get(slot as usize) { - Some(Slot::Buffer { buffer, .. }) => Some((buffer.tracked_id(), access)), + Some(Slot::Buffer { buffer, .. }) => { + Some(([buffer.tracked_id(), buffer.id()], access)) + } _ => None, } }); @@ -1954,16 +1957,16 @@ impl Accesses<'_> { .iter() .filter_map(move |&(slot, access)| { let texture = self.textures.get(slot as usize)?.as_ref()?; - Some((texture.tracked_id(), access)) + Some(([texture.tracked_id(), texture.hazard_id()], access)) }); slots .chain(textures) .chain( self.declared .iter() - .map(move |&(ids, access, ..)| (ids[1], access)), + .map(move |&([own, tracked], access, ..)| ([tracked, own], access)), ) - .chain(self.indirect.map(|(ids, _)| (ids[1], Access::Read))) + .chain((self.indirect).map(|([own, tracked], _)| ([tracked, own], Access::Read))) } /// Each resource the dispatch of a kernel of `interface` reaches, as the copies over buffers @@ -2024,9 +2027,32 @@ impl Accesses<'_> { } } +/// What a dispatch depends on in the hazard sets, where Metal orders it after what they hold. +#[derive(Default)] +struct Depends { + /// It reads or writes a resource written, by the resource's own id. + write: bool, + /// It writes a resource only read, by the resource's own id. + read: bool, + /// It conflicts through a shared id alone ([`HeapId`](crate::hazard::HeapId)): a heap's + /// resources, or an exported surface's, whose own ids find no dependency. + shared: bool, +} + +impl Depends { + fn any(&self) -> bool { + self.write || self.read || self.shared + } +} + impl Building { /// Places a dispatch's barrier where it needs one, and adds what it touches to the sets. /// True where the dispatch writes. + /// + /// The barrier, one whatever its causes, is counted in one bucket of + /// [`Metrics::dispatch_hazard_barriers`](crate::Metrics::dispatch_hazard_barriers): the + /// dispatch's own dependency on a write or on a read where it has one, and otherwise the first + /// of its other causes in the buckets' order. fn dispatch_hazards( &mut self, serial: bool, @@ -2035,24 +2061,64 @@ impl Building { ) -> Result { let indirect = accesses.indirect.is_some(); let reach = Reach::Dispatches { indirect }; - let command = self.command(reach)?; - let hazards = self.hazards(); - let conflict = serial - && (accesses - .each(interface) - .any(|(id, access)| hazards.conflicts(id, access)) - || (interface.reads_unbound && hazards.wrote()) - || (interface.writes_unbound && hazards.touched())); + let command = self.current_command()?; + let owed = self.owed(); // 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, Metric::DispatchHazardBarriers); + let args = indirect && self.args_unordered(); + let hazards = self.hazards(); + // Metal orders the dispatch after what the sets hold in a serial encoder, and after what + // an owed barrier orders in either kind. + let ordered = serial || owed.is_some(); + let mut depends = Depends::default(); + for ([tracked, own], access) in accesses.each(interface).filter(|_| ordered) { + let Some(on) = hazards.dependency(tracked, access) else { + continue; + }; + let on = match own == tracked { + true => Some(on), + false => hazards.own_dependency(own, access), + }; + match on { + Some(Dependency::Write) => depends.write = true, + Some(Dependency::Read) => depends.read = true, + None => depends.shared = true, + } + } + let unbound = ordered + && ((interface.reads_unbound && hazards.wrote()) + || (interface.writes_unbound && hazards.touched())); + let conflict = serial && (depends.any() || unbound); + if owed.is_some() || conflict || args { + let cause = if depends.write { + Metric::DispatchAfterWriteBarriers + } else if depends.read { + Metric::DispatchWriteAfterReadBarriers + } else if owed == Some(Owed::EncoderEnd) { + Metric::DispatchEncoderEndBarriers + } else if owed == Some(Owed::PassEnd) { + Metric::DispatchPassEndBarriers + } else if args { + Metric::DispatchIndirectBarriers + } else if unbound || owed == Some(Owed::Unbound) { + Metric::DispatchUnboundBarriers + } else if owed == Some(Owed::ArenaPiece) { + Metric::DispatchArenaPieceBarriers + } else if depends.shared { + Metric::DispatchHeapBarriers + } else { + Metric::DispatchOtherBarriers + }; + self.barrier(command, reach, cause); self.hazards().clear(); } let hazards = self.hazards(); let mut wrote = false; - for (id, access) in accesses.each(interface) { - hazards.mark(id, access); + for ([tracked, own], access) in accesses.each(interface) { + hazards.mark(tracked, access); + if own != tracked { + hazards.mark_own(own, access); + } wrote |= access.writes(); } if interface.reads_unbound { @@ -2063,7 +2129,7 @@ impl Building { wrote = true; if serial { // Such a write conflicts with everything after it. - self.owe(); + self.owe(Owed::Unbound); } } if wrote { diff --git a/crates/metal2vulkan-runtime/src/hazard.rs b/crates/metal2vulkan-runtime/src/hazard.rs index be567a35f..bab097f5f 100644 --- a/crates/metal2vulkan-runtime/src/hazard.rs +++ b/crates/metal2vulkan-runtime/src/hazard.rs @@ -40,11 +40,24 @@ impl Access { } } +/// What an access depends on in the sets ([`Hazards::dependency`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Dependency { + /// A write of the resource: the access reads or writes what was written. + Write, + /// Only a read of it: the access writes what was read. + Read, +} + /// The sets. pub(crate) struct Hazards { /// Per resource id, the generations it was last read and last written in; a mark of an older /// generation is in neither set. marks: Vec<[u32; 2]>, + /// The same marks by a resource's own id, of each resource that takes a shared id in + /// `marks` (a heap's, [`HeapId`]): they place no barrier, and only tell a dependency on the + /// resource itself from a conflict through the shared id alone, for the barrier's count. + own: Vec<[u32; 2]>, /// The current generation, from 1. generation: u32, /// Since the last barrier: something was written, through a resource or through an address @@ -58,6 +71,7 @@ impl Default for Hazards { fn default() -> Hazards { Hazards { marks: Vec::new(), + own: Vec::new(), generation: 1, wrote: false, touched: false, @@ -66,34 +80,34 @@ impl Default for Hazards { } impl Hazards { - /// Whether `access` of resource `id` conflicts with the sets: it reads or writes a resource - /// in the written set, or writes one in the read set. - pub(crate) fn conflicts(&self, id: u32, access: Access) -> bool { - match self.marks.get(id as usize) { - Some(&[read, written]) => { - written == self.generation || (access.writes() && read == self.generation) - } - None => false, - } + /// What `access` of resource `id` depends on in the sets, where it conflicts with them: it + /// reads or writes a resource in the written set (`Write`), or writes one in the read set + /// alone (`Read`). + pub(crate) fn dependency(&self, id: u32, access: Access) -> Option { + depends(&self.marks, self.generation, id, access) + } + + /// [`dependency`](Self::dependency) by the own id of a resource that takes a shared id, from + /// its [`mark_own`](Self::mark_own) marks. + pub(crate) fn own_dependency(&self, id: u32, access: Access) -> Option { + depends(&self.own, self.generation, id, access) } /// Adds `access` of resource `id` to the sets. pub(crate) fn mark(&mut self, id: u32, access: Access) { - let index = id as usize; - if index >= self.marks.len() { - self.marks.resize(index + 1, [0, 0]); - } - let mark = &mut self.marks[index]; - if access.reads() { - mark[0] = self.generation; - } + set(&mut self.marks, self.generation, id, access); if access.writes() { - mark[1] = self.generation; self.wrote = true; } self.touched = true; } + /// Adds `access` by the own id of a resource that takes a shared id, which [`mark`](Self::mark) + /// adds by the shared one. + pub(crate) fn mark_own(&mut self, id: u32, access: Access) { + set(&mut self.own, self.generation, id, access); + } + /// A write through an address outside every resource. pub(crate) fn mark_wild_write(&mut self) { self.wrote = true; @@ -119,6 +133,7 @@ impl Hazards { pub(crate) fn clear(&mut self) { if self.generation == u32::MAX { self.marks.fill([0, 0]); + self.own.fill([0, 0]); self.generation = 0; } self.generation += 1; @@ -127,6 +142,34 @@ impl Hazards { } } +/// What `access` of resource `id` depends on in `marks` at `generation`: a write of it, or a read +/// of it alone where the access writes. +fn depends(marks: &[[u32; 2]], generation: u32, id: u32, access: Access) -> Option { + let &[read, written] = marks.get(id as usize)?; + if written == generation { + Some(Dependency::Write) + } else if access.writes() && read == generation { + Some(Dependency::Read) + } else { + None + } +} + +/// Marks `access` of resource `id` in `marks` at `generation`. +fn set(marks: &mut Vec<[u32; 2]>, generation: u32, id: u32, access: Access) { + let index = id as usize; + if index >= marks.len() { + marks.resize(index + 1, [0, 0]); + } + let mark = &mut marks[index]; + if access.reads() { + mark[0] = generation; + } + if access.writes() { + mark[1] = generation; + } +} + /// Resource ids: small and dense, so the sets' table stays short; an id is reused once its /// resource is gone. A reused id can only add a barrier, never lose one. pub(crate) struct Ids { diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index cbb952d87..d79b33cf7 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -919,6 +919,12 @@ impl Carve { } impl Pool { + /// The alignment of a buffer of the pool's usage, which Vulkan's memory requirements gave at + /// the device's making ([`buffer_alignment`]). + pub(crate) fn alignment(&self) -> u64 { + self.alignment + } + /// The pool of a device whose `bufferImageGranularity` is `granularity`, and whose buffers of /// the pool's usage have the alignment `alignment`. pub(crate) fn new( diff --git a/crates/metal2vulkan-runtime/src/tests/compute.rs b/crates/metal2vulkan-runtime/src/tests/compute.rs index 3798f8533..74e82eff8 100644 --- a/crates/metal2vulkan-runtime/src/tests/compute.rs +++ b/crates/metal2vulkan-runtime/src/tests/compute.rs @@ -16,7 +16,8 @@ pub(crate) mod on_device { use crate::tests::kernels; use crate::{ Buffer, CommandBuffer, ComputeCommandEncoder, ComputePipelineState, Device, DispatchType, - Error, Gap, HeapRange, Limit, MemoryClass, Refusal, RefusalBasis, + Error, Gap, HeapRange, Limit, LoadAction, MemoryClass, PixelFormat, Refusal, RefusalBasis, + RenderPassDescriptor, StoreAction, TextureDescriptor, TextureType, TextureUsage, }; use metal2vulkan::pipeline::{Axis, SpecKey}; @@ -148,6 +149,53 @@ pub(crate) mod on_device { assert_eq!(command_buffer.error(), None, "{name}"); } + /// The dispatches' barriers by source grown from `before` to `after`, in their order: after + /// a write, a write after a read, an encoder's end, a render pass's end, an indirect + /// dispatch, an access outside every resource, a Private-arena piece, a heap's one id and + /// another (`Metrics::dispatch_after_write_barriers` and the rest). Their sum is the + /// dispatches' barriers grown (`Metrics::dispatch_hazard_barriers`). + fn sources(after: &crate::Metrics, before: &crate::Metrics) -> [u64; 9] { + let of = |m: &crate::Metrics| { + [ + m.dispatch_after_write_barriers, + m.dispatch_write_after_read_barriers, + m.dispatch_encoder_end_barriers, + m.dispatch_pass_end_barriers, + m.dispatch_indirect_barriers, + m.dispatch_unbound_barriers, + m.dispatch_arena_piece_barriers, + m.dispatch_heap_barriers, + m.dispatch_other_barriers, + ] + }; + let (grown, was) = (of(after), of(before)); + let grown: [u64; 9] = std::array::from_fn(|at| grown[at] - was[at]); + assert_eq!( + grown.iter().sum::(), + after.dispatch_hazard_barriers - before.dispatch_hazard_barriers, + "the sources {grown:?} sum to the dispatches' barriers" + ); + grown + } + + /// `n` barriers in source `at` of [`sources`], and none in the others. + fn only(at: usize, n: u64) -> [u64; 9] { + std::array::from_fn(|source| if source == at { n } else { 0 }) + } + + /// Binds `state` and `buffers` at slots from 0, and dispatches 4 threadgroups of 16. + fn dispatch( + encoder: &mut ComputeCommandEncoder, + state: &ComputePipelineState, + buffers: &[&Buffer], + ) { + encoder.set_compute_pipeline_state(state).expect("a state"); + for (slot, buffer) in buffers.iter().enumerate() { + (encoder.set_buffer(Some(buffer), 0, slot as u32)).expect("a buffer"); + } + (encoder.dispatch_threadgroups([4, 1, 1], [16, 1, 1])).expect("a dispatch"); + } + /// A dispatch reads bound buffers and `set_bytes` data by address and writes a bound buffer. #[test] fn every_device_dispatches_over_bound_buffers_and_set_bytes() { @@ -380,6 +428,9 @@ pub(crate) mod on_device { ] }; assert_eq!(causes(&after, &before), [count - 1, 1], "{name}: dependent"); + // Each after the write of the dispatch before it. + let split = sources(&after, &before); + assert_eq!(split, only(0, count - 1), "{name}: dependent, by source"); let chained = |start: u32| (0..count).fold(start, |x, _| x * 2 + 1); let expected: Vec = (0..WORDS as u32).map(chained).collect(); assert_eq!(words(&x), expected, "{name}: dependent"); @@ -406,6 +457,11 @@ pub(crate) mod on_device { let after = device.counters().metrics(); assert_eq!(after.barriers - before.barriers, 1, "{name}: independent"); assert_eq!(causes(&after, &before), [0, 1], "{name}: independent"); + assert_eq!( + sources(&after, &before), + [0; 9], + "{name}: independent, by source" + ); let expected: Vec = (0..WORDS as u32).map(|x| x * 2 + 1).collect(); for buffer in &buffers { assert_eq!(words(buffer), expected, "{name}: independent"); @@ -436,12 +492,15 @@ pub(crate) mod on_device { count, "{name}: concurrent" ); - // Each memory barrier is owed, and paid by the dispatch after it. + // Each memory barrier is owed, and paid by the dispatch after it, which reads the + // write before it: counted as that dependency. assert_eq!( causes(&after, &before), [count - 1, 1], "{name}: concurrent" ); + let split = sources(&after, &before); + assert_eq!(split, only(0, count - 1), "{name}: concurrent, by source"); let expected: Vec = (0..WORDS as u32).map(chained).collect(); assert_eq!(words(&x), expected, "{name}: concurrent"); }); @@ -450,8 +509,10 @@ pub(crate) mod on_device { /// A heap's resources are one resource in the hazard sets, as Metal tracks a heap's: in a /// serial encoder, a dispatch that uses a heap's buffer after one that wrote another of the /// heap gets a barrier, the two over the same bytes or apart, and the second sees the first's - /// writes; two heaps' buffers get none. A buffer past its heap's end is refused, and the - /// device's map of heaps stays bounded as heaps come and go. + /// writes; two heaps' buffers get none. The barrier counts in the heap's source, and one + /// after a write of the same buffer of the heap in the dependency on a write. A buffer past + /// its heap's end is refused, and the device's map of heaps stays bounded as heaps come and + /// go. #[test] fn every_device_orders_a_heap_s_resources_as_one() { each_device("compute_heap_ids", |name, _, device| { @@ -468,8 +529,8 @@ pub(crate) mod on_device { .unwrap_or_else(|error| panic!("{name}: {error}")) }; // Two dispatches of `step`, each over one buffer: the barriers they take, the - // segment's end among them. - let barriers = |buffers: [&Buffer; 2]| -> u64 { + // segment's end among them, and the dispatches' by source. + let barriers = |buffers: [&Buffer; 2]| -> (u64, [u64; 9]) { let before = device.counters().metrics(); let command_buffer = queue.command_buffer().expect("a command buffer"); let mut encoder = command_buffer @@ -484,22 +545,38 @@ pub(crate) mod on_device { } encoder.end_encoding(); run(name, &command_buffer); - device.counters().metrics().barriers - before.barriers + let after = device.counters().metrics(); + (after.barriers - before.barriers, sources(&after, &before)) }; let (a, b) = (placed(heap(0, 1024), 0), placed(heap(0, 1024), 0)); let apart = placed(heap(0, 1024), 512); let other = placed(heap(4096, 1024), 0); // Over the same bytes: the second step reads the first's words. + let heap_source = (2, only(7, 1)); write_words(&a, |index| index); - assert_eq!(barriers([&a, &b]), 2, "{name}: one heap, the same bytes"); + assert_eq!( + barriers([&a, &b]), + heap_source, + "{name}: one heap, the same bytes" + ); let twice: Vec = (0..WORDS as u32).map(|x| (x * 2 + 1) * 2 + 1).collect(); assert_eq!(words(&b), twice, "{name}: one heap, the same bytes"); // Apart in one heap: still one resource. - assert_eq!(barriers([&a, &apart]), 2, "{name}: one heap, apart"); + assert_eq!( + barriers([&a, &apart]), + heap_source, + "{name}: one heap, apart" + ); + // One buffer of a heap twice: the dependency on its write. + assert_eq!( + barriers([&a, &a]), + (2, only(0, 1)), + "{name}: one heap's buffer" + ); // Two heaps of one block: two resources. - assert_eq!(barriers([&apart, &other]), 1, "{name}: two heaps"); + assert_eq!(barriers([&apart, &other]), (1, [0; 9]), "{name}: two heaps"); match device.new_heap_buffer(heap(0, 1024), 1000, 256) { Err(Error::Refused(refusal)) => assert_eq!( @@ -526,6 +603,129 @@ pub(crate) mod on_device { }); } + /// Each of the dispatches' barriers counts in one source, the sources summing to + /// `Metrics::dispatch_hazard_barriers`: a write of a buffer the dispatch before only read; an + /// encoder's end before a dispatch of another buffer, and before one of the buffer the + /// encoder before wrote, which counts as that dependency; a render pass's end that moved + /// nothing home; an indirect dispatch after a write of another buffer; a read outside every + /// resource after a write; and a memory barrier in a concurrent encoder before a dispatch of + /// another buffer. A barrier with several causes counts once. + #[test] + fn every_device_counts_each_dispatch_barrier_in_one_source() { + each_device("compute_barrier_sources", |name, _, device| { + let mut arena = Arena::new(&device); + let (add, step) = (add(&device), step(&device)); + let fields = vec![region(), address(0, Place::Push(32))]; + let mut wild = interface(vec![(0, Access::ReadWrite)], fields, 40); + wild.reads_unbound = true; + let wild = (ComputePipelineState::for_test(&device, &kernels::STEP, wild)) + .expect("the step kernel, reading outside its resources"); + let queue = device.new_command_queue(4).expect("a queue"); + let counters = device.counters(); + // The sources the commands `record` encodes into one command buffer add, and every + // barrier they and the segment's end add. + let grown = |record: &dyn Fn(&CommandBuffer)| -> ([u64; 9], u64) { + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + record(&command_buffer); + run(name, &command_buffer); + let after = counters.metrics(); + (sources(&after, &before), after.barriers - before.barriers) + }; + let serial = |command_buffer: &CommandBuffer| { + (command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder") + }; + let [a, b, c, d, o, x, y, args] = std::array::from_fn(|_| arena.buffer()); + for buffer in [&a, &b, &c, &d, &o, &x, &y] { + write_words(buffer, |index| index); + } + write_words(&args, |index| u32::from(index < 3)); + + // A write of a buffer the dispatch before only read, and the segment's end. + let split = grown(&|command_buffer| { + let mut encoder = serial(command_buffer); + dispatch(&mut encoder, &add, &[&a, &b, &o]); + dispatch(&mut encoder, &add, &[&c, &d, &a]); + encoder.end_encoding(); + }); + assert_eq!(split, (only(1, 1), 2), "{name}: a write after a read"); + + // Three encoders that write: the second's dispatch pays the first's end, the third's + // the second's and reads the second's write. + let split = grown(&|command_buffer| { + for buffer in [&x, &y, &y] { + let mut encoder = serial(command_buffer); + dispatch(&mut encoder, &step, &[buffer]); + encoder.end_encoding(); + } + }); + let mut ends = only(2, 1); + ends[0] = 1; + assert_eq!(split, (ends, 3), "{name}: encoders' ends"); + + // A render pass whose attachment renders at home owes its barrier to the dispatch + // after it: its start's barrier, the dispatch's and the segment's end. + let mut described = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 4, 4); + described.usage = TextureUsage::RENDER_TARGET; + let target = device.new_texture_for_views(&described).expect("a texture"); + let mut pass = RenderPassDescriptor::default(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + let homes = counters.metrics().pass_home_barriers; + let split = grown(&|command_buffer| { + (command_buffer.render_command_encoder(&pass)) + .unwrap_or_else(|error| panic!("{name}: {error}")) + .end_encoding(); + let mut encoder = serial(command_buffer); + dispatch(&mut encoder, &step, &[&y]); + encoder.end_encoding(); + }); + let moved = counters.metrics().pass_home_barriers - homes; + assert_eq!(moved, 0, "{name}: the pass moves nothing home"); + assert_eq!(split.0, only(3, 1), "{name}: a render pass's end"); + + // An indirect dispatch over another buffer after a write. + let split = grown(&|command_buffer| { + let mut encoder = serial(command_buffer); + dispatch(&mut encoder, &step, &[&x]); + encoder.set_buffer(Some(&y), 0, 0).expect("a buffer"); + (encoder.dispatch_threadgroups_with_indirect_buffer(&args, 0, [16, 1, 1])) + .expect("an indirect dispatch"); + encoder.end_encoding(); + }); + assert_eq!(split, (only(4, 1), 2), "{name}: an indirect dispatch"); + + // A read outside every resource after a write of another buffer. + let split = grown(&|command_buffer| { + let mut encoder = serial(command_buffer); + dispatch(&mut encoder, &step, &[&x]); + dispatch(&mut encoder, &wild, &[&y]); + encoder.end_encoding(); + }); + assert_eq!( + split, + (only(5, 1), 2), + "{name}: a read outside every resource" + ); + + // A memory barrier in a concurrent encoder, before a dispatch of another buffer. + let split = grown(&|command_buffer| { + let mut encoder = (command_buffer + .compute_command_encoder(DispatchType::Concurrent)) + .expect("an encoder"); + dispatch(&mut encoder, &step, &[&x]); + encoder.memory_barrier(); + dispatch(&mut encoder, &step, &[&y]); + encoder.end_encoding(); + }); + assert_eq!(split, (only(8, 1), 2), "{name}: a memory barrier"); + drop((target, add, step, wild)); + }); + } + /// What an encoder's commands count reaches the device's counters once, at the encoder's /// end: 2,000 dispatches that each read the one before's writes move none of them while the /// encoder is open, and its end adds the pass, the 1,999 barriers between them, the push and diff --git a/crates/metal2vulkan-runtime/src/tests/device.rs b/crates/metal2vulkan-runtime/src/tests/device.rs index 16c2c436b..8d9a1eb60 100644 --- a/crates/metal2vulkan-runtime/src/tests/device.rs +++ b/crates/metal2vulkan-runtime/src/tests/device.rs @@ -147,6 +147,14 @@ fn every_device_of_the_cfgs_kind_opens_presents_and_tears_down_to_zero() { ); } println!("{name}: memory types chosen {memory_types:?}"); + // The buffers' alignment, a power of two (Vulkan's memory requirements), printed for the + // leg's log. + let alignment = device.buffer_alignment(); + assert!( + alignment.is_power_of_two(), + "{name}: buffer alignment {alignment}" + ); + println!("{name}: buffer alignment {alignment}"); assert_eq!( device.has_unified_memory(), matches!( diff --git a/crates/metal2vulkan-runtime/src/tests/hazard.rs b/crates/metal2vulkan-runtime/src/tests/hazard.rs index 7caa919a7..15dc48d80 100644 --- a/crates/metal2vulkan-runtime/src/tests/hazard.rs +++ b/crates/metal2vulkan-runtime/src/tests/hazard.rs @@ -1,22 +1,37 @@ -//! The hazard sets: which accesses conflict, and that a barrier starts them again. +//! The hazard sets: which accesses conflict, on what (a write, or a read alone), what a resource's +//! own id finds beside its shared one, and that a barrier starts them again. -use crate::hazard::{Access, Hazards}; +use crate::hazard::{Access, Dependency, Hazards}; #[test] fn a_read_or_write_after_a_write_conflicts_and_a_write_after_a_read_too() { let mut sets = Hazards::default(); sets.mark(3, Access::Write); for access in [Access::Read, Access::Write, Access::ReadWrite] { - assert!(sets.conflicts(3, access), "{access:?} after a write"); + let found = sets.dependency(3, access); + assert_eq!(found, Some(Dependency::Write), "{access:?} after a write"); } - assert!(!sets.conflicts(4, Access::ReadWrite), "another resource"); + assert_eq!( + sets.dependency(4, Access::ReadWrite), + None, + "another resource" + ); let mut sets = Hazards::default(); sets.mark(7, Access::Read); - assert!(!sets.conflicts(7, Access::Read), "a read after a read"); - assert!(sets.conflicts(7, Access::Write), "a write after a read"); - assert!( - sets.conflicts(7, Access::ReadWrite), + assert_eq!( + sets.dependency(7, Access::Read), + None, + "a read after a read" + ); + assert_eq!( + sets.dependency(7, Access::Write), + Some(Dependency::Read), + "a write after a read" + ); + assert_eq!( + sets.dependency(7, Access::ReadWrite), + Some(Dependency::Read), "a read-write after a read" ); } @@ -30,13 +45,50 @@ fn a_barrier_starts_the_sets_again() { sets.clear(); assert!(!sets.wrote() && !sets.touched()); for (id, access) in [(0, Access::ReadWrite), (9, Access::Write)] { - assert!( - !sets.conflicts(id, access), + assert_eq!( + sets.dependency(id, access), + None, "{id} {access:?} after the barrier" ); } } +#[test] +fn own_ids_place_nothing_and_tell_a_resource_from_its_heap() { + // Two buffers of heap 5, with own ids 1 and 2: the first written. + let mut sets = Hazards::default(); + sets.mark(5, Access::Write); + sets.mark_own(1, Access::Write); + for (id, found) in [(1, Some(Dependency::Write)), (2, None)] { + let shared = sets.dependency(5, Access::Read); + assert_eq!( + shared, + Some(Dependency::Write), + "own id {id}, by the heap's" + ); + assert_eq!(sets.own_dependency(id, Access::Read), found, "own id {id}"); + } + // The own marks are in no set of their own ids. + assert_eq!( + sets.dependency(1, Access::ReadWrite), + None, + "own id 1 as an id" + ); + sets.mark_own(2, Access::Read); + let read = sets.own_dependency(2, Access::Write); + assert_eq!( + read, + Some(Dependency::Read), + "a write after a read, by its own id" + ); + sets.clear(); + assert_eq!( + sets.own_dependency(1, Access::Read), + None, + "after the barrier" + ); +} + #[test] fn accesses_outside_every_resource_count_as_touched_and_writes_as_written() { let mut sets = Hazards::default(); diff --git a/crates/metal2vulkan-runtime/src/tests/private_arena.rs b/crates/metal2vulkan-runtime/src/tests/private_arena.rs index ad47f3df7..2604d1761 100644 --- a/crates/metal2vulkan-runtime/src/tests/private_arena.rs +++ b/crates/metal2vulkan-runtime/src/tests/private_arena.rs @@ -230,6 +230,10 @@ entry: assert!(taken <= 1, "{what}: {taken} blocks"); let ordered = 2 * pieces - taken; assert_eq!(barriers, one + ordered, "{what}: barriers"); + // Each counted in its source, the arena's pieces. + let pieced = + after.dispatch_arena_piece_barriers - before.dispatch_arena_piece_barriers; + assert_eq!(pieced, ordered, "{what}: barriers before arena pieces"); println!( "{what}: {pieces} pieces a dispatch, {taken} block taken, {ordered} \ barriers before arena pieces" diff --git a/crates/metal2vulkan-validation/src/bin/command-replay.rs b/crates/metal2vulkan-validation/src/bin/command-replay.rs index 11b84b42f..69f597092 100644 --- a/crates/metal2vulkan-validation/src/bin/command-replay.rs +++ b/crates/metal2vulkan-validation/src/bin/command-replay.rs @@ -29,7 +29,8 @@ //! header lacks `FLAG_COMPLETION_BYTES_RECORDED`, the line `recorded before the recorder's //! completion fix: the stream may differ from what the program did` by itself, then `range ...` //! (the recording range, where it came from, and whether the play ends there), then `device NAME -//! runtime rt`, each frame's `frame` and `end` lines as the frame ends +//! runtime rt buffer alignment N` (the device's buffer alignment, `Device::buffer_alignment`), each +//! frame's `frame` and `end` lines as the frame ends //! (flushed, so a play that never ends leaves the frames it finished), `addresses ...` (the //! written words that look like addresses, which play as recorded but those a noted buffer's range //! holds, which move, the address arguments and those moved, and the objects whose ID differs from @@ -601,8 +602,10 @@ fn play(options: &BTreeMap) -> i32 { }; let cache = PathBuf::from(&options["shader-cache"]); let mut backend = match open_rt(device_type, cache) { - Ok((backend, name)) => { - report.line(&format!("device {name} runtime rt")); + Ok((backend, name, alignment)) => { + report.line(&format!( + "device {name} runtime rt buffer alignment {alignment}" + )); let backend = match device_copies { true => backend.reading_device_copies(), false => backend, @@ -720,9 +723,10 @@ fn state_options( } /// The runtime's backend on the first physical device of `device_type` that opens (a GPU: -/// discrete, then integrated, then virtual), its compiled kernels kept in `cache`, and its name. -/// A GPU opens only while the hang tripwire is absent. -fn open_rt(device_type: DeviceType, cache: PathBuf) -> Result<(NewRuntime, String), String> { +/// discrete, then integrated, then virtual), its compiled kernels kept in `cache`, its name and +/// its buffers' alignment (`Device::buffer_alignment`). A GPU opens only while the hang tripwire is +/// absent. +fn open_rt(device_type: DeviceType, cache: PathBuf) -> Result<(NewRuntime, String, u64), String> { use ash::vk::PhysicalDeviceType as Kind; if device_type == DeviceType::Gpu { metal2vulkan_validation::gpu::tripwire::refuse_if_tripped()?; @@ -756,10 +760,12 @@ fn open_rt(device_type: DeviceType, cache: PathBuf) -> Result<(NewRuntime, Strin for (_, name, physical) in candidates { let mut options = metal2vulkan_runtime::DeviceOptions::default(); options.pipeline_cache_dir = Some(cache.clone()); - let opened = metal2vulkan_runtime::Device::new(&physical, options) - .and_then(|device| NewRuntime::new(device, device_type)); + let opened = metal2vulkan_runtime::Device::new(&physical, options).and_then(|device| { + let alignment = device.buffer_alignment(); + NewRuntime::new(device, device_type).map(|backend| (backend, alignment)) + }); match opened { - Ok(backend) => return Ok((backend, name)), + Ok((backend, alignment)) => return Ok((backend, name, alignment)), Err(why) => refused.push(format!("{name}: {why}")), } } diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index fc3468725..4b02413b9 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -3107,6 +3107,36 @@ impl Backend for NewRuntime { ("pass_home_barriers", metrics.pass_home_barriers), ("blit_barriers", metrics.blit_barriers), ("dispatch_hazard_barriers", metrics.dispatch_hazard_barriers), + ( + "dispatch_after_write_barriers", + metrics.dispatch_after_write_barriers, + ), + ( + "dispatch_write_after_read_barriers", + metrics.dispatch_write_after_read_barriers, + ), + ( + "dispatch_encoder_end_barriers", + metrics.dispatch_encoder_end_barriers, + ), + ( + "dispatch_pass_end_barriers", + metrics.dispatch_pass_end_barriers, + ), + ( + "dispatch_indirect_barriers", + metrics.dispatch_indirect_barriers, + ), + ( + "dispatch_unbound_barriers", + metrics.dispatch_unbound_barriers, + ), + ( + "dispatch_arena_piece_barriers", + metrics.dispatch_arena_piece_barriers, + ), + ("dispatch_heap_barriers", metrics.dispatch_heap_barriers), + ("dispatch_other_barriers", metrics.dispatch_other_barriers), ("segment_end_barriers", metrics.segment_end_barriers), ("upload_barriers", metrics.upload_barriers), ("other_barriers", metrics.other_barriers), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 956881720..b33d68187 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1414,7 +1414,16 @@ field metal2vulkan-runtime::Metrics.consumer_allocation_nanos pub consumer_alloc field metal2vulkan-runtime::Metrics.consumer_allocations pub consumer_allocations: u64 field metal2vulkan-runtime::Metrics.creations_before_seed pub creations_before_seed: u64 field metal2vulkan-runtime::Metrics.d3d11_plane_submissions pub d3d11_plane_submissions: u64 +field metal2vulkan-runtime::Metrics.dispatch_after_write_barriers pub dispatch_after_write_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_arena_piece_barriers pub dispatch_arena_piece_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_encoder_end_barriers pub dispatch_encoder_end_barriers: u64 field metal2vulkan-runtime::Metrics.dispatch_hazard_barriers pub dispatch_hazard_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_heap_barriers pub dispatch_heap_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_indirect_barriers pub dispatch_indirect_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_other_barriers pub dispatch_other_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_pass_end_barriers pub dispatch_pass_end_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_unbound_barriers pub dispatch_unbound_barriers: u64 +field metal2vulkan-runtime::Metrics.dispatch_write_after_read_barriers pub dispatch_write_after_read_barriers: u64 field metal2vulkan-runtime::Metrics.dispatches_without_effects pub dispatches_without_effects: u64 field metal2vulkan-runtime::Metrics.emulated_simdgroup_dispatches pub emulated_simdgroup_dispatches: u64 field metal2vulkan-runtime::Metrics.event_holds pub event_holds: [u64; STAGE_BUCKETS] @@ -5968,6 +5977,7 @@ method metal2vulkan-runtime::Counters::variant_makes pub fn variant_makes(&self, method metal2vulkan-runtime::DepthStencilState::descriptor pub fn descriptor(&self) -> &DepthStencilDescriptor method metal2vulkan-runtime::DepthStencilState::precision_note pub fn precision_note(&self) -> Option method metal2vulkan-runtime::Device::argument_buffers_support pub fn argument_buffers_support(&self) -> ArgumentBuffersTier +method metal2vulkan-runtime::Device::buffer_alignment pub fn buffer_alignment(&self) -> u64 method metal2vulkan-runtime::Device::counters pub fn counters(&self) -> Counters method metal2vulkan-runtime::Device::dma_buf_granule #[cfg(unix)] pub fn dma_buf_granule(&self) -> Option method metal2vulkan-runtime::Device::extensions pub fn extensions(&self) -> &[CString] diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 7ca357895..486ac6c78 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -734,8 +734,14 @@ records as text, and and the rest. The barriers are counted in their causes too, which sum to `barriers`: `pass_start_barriers`, `pass_home_barriers`, `blit_barriers`, `dispatch_hazard_barriers`, `segment_end_barriers`, `upload_barriers` and `other_barriers` (`Metrics::pass_start_barriers` - and the rest). They differ between commits, and between plays of one commit where what the - runtime records depends on timing. Only the stream's counts are compared between plays. + and the rest), and a dispatch's barriers in their sources too, which sum to + `dispatch_hazard_barriers`: `dispatch_after_write_barriers`, + `dispatch_write_after_read_barriers`, `dispatch_encoder_end_barriers`, + `dispatch_pass_end_barriers`, `dispatch_indirect_barriers`, `dispatch_unbound_barriers`, + `dispatch_arena_piece_barriers`, `dispatch_heap_barriers` and `dispatch_other_barriers` + (`Metrics::dispatch_after_write_barriers` and the rest). They differ between commits, and + between plays of one commit where what the runtime records depends on timing. Only the + stream's counts are compared between plays. Its own readbacks are not counted. The backend reads a Private buffer, which has no CPU mapping, through a blit copy of it into a Shared buffer of the play's own, on a queue of the @@ -993,7 +999,8 @@ stream may differ from what the program did` where the stream's header lacks bit 6), then `range last-frame F (SOURCE); the play ends there`, `range last-frame F (SOURCE); --past-range yes plays past it` or `range whole (SOURCE)`, where `SOURCE` is `the stream's sidecar`, `the player's table, stream LABEL` or `no sidecar and no table row`, then -`device NAME runtime rt`, then on a device that keeps a +`device NAME runtime rt buffer alignment N` (the alignment Vulkan's memory requirements give the +runtime's buffers, `Device::buffer_alignment`), then on a device that keeps a device copy of each Managed buffer, `managed digests: ...` (above), then `addresses address_looking_words=N misaligned_address_words=N noted_words=N address_arguments=N relocated_words=N differing_ids=N: written words play as recorded, the noted ones moved; NOTES`