From 652fbca7f1e0a05fc75f4ecc74e323376c5fb031 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 07:37:51 -0800 Subject: [PATCH] metal2vulkan-rt: one global barrier ends each segment, upload and fill A segment no longer starts with a barrier. Each segment with commands ends with one global VkMemoryBarrier2 from every write to every later command and the host (read and write), with no per-buffer barrier; the upload of zero fills and a block's fill each end with one to every later command. A barrier's second scope reaches every later submission on the queue, so the start barrier was redundant. The segment-end barrier goes on every segment with commands, not only on one that wrote: a read-only segment still owes the execution dependency before a later command buffer writes what it read. Metrics::barriers counts the queues' work only; a block's fill, made apart from any command buffer, is not counted, so the count stays deterministic. The states test now expects 2 barriers for 2 segments. Verified: not yet compiled; the lint and legs follow. --- crates/metal2vulkan-rt/README.md | 11 ++-- crates/metal2vulkan-rt/src/command.rs | 4 +- crates/metal2vulkan-rt/src/counters.rs | 4 +- crates/metal2vulkan-rt/src/fill.rs | 2 + crates/metal2vulkan-rt/src/record.rs | 56 +++++++++++++-------- crates/metal2vulkan-rt/src/submit.rs | 15 +++--- crates/metal2vulkan-rt/src/tests/command.rs | 4 +- 7 files changed, 59 insertions(+), 37 deletions(-) diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index ec0faa401..f135a7cc8 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -80,8 +80,8 @@ in its memory. `contents` the block's mapping plus the offset, or `None` in a Private block. `zeroed` zeroes the range, as `newBufferWithLength:options:` does: through the mapping for Shared, before the call returns; in Private by a GPU fill of exactly the range, recorded into the upload, which goes - ahead of every command buffer committed after the call (each command buffer's commands start - with a barrier after every earlier submission) and holds the block until it completes. A buffer + ahead of every command buffer committed after the call and ends with a barrier that makes the + fills visible to every later command, and holds the block until it completes. A buffer placed in a heap passes false, since Metal does not zero heap memory. A length of 0 and a range past the block are refused, as Metal answers nil for both. @@ -107,9 +107,10 @@ after a quiesce. `CommandQueue::command_buffer` waits, as Metal does, while `max` of the queue's command buffers are made and not yet completed. - A `CommandBuffer` records at once, with no replay log. Event waits and signals split it into - segments, one `VkCommandBuffer` each where it has commands; their commands start with a barrier - after every earlier submission and end with a barrier that makes their writes visible to the - host. `enqueue` takes the command buffer's place in its queue; `commit` hands it to the submit + segments, one `VkCommandBuffer` each where it has commands. Each ends with one global memory + barrier: its writes are visible to every later command and to the host, and later commands run + after its own, as Metal orders a queue's command buffers. No segment starts with a barrier. + `enqueue` takes the command buffer's place in its queue; `commit` hands it to the submit thread and returns. A committed command buffer holds no device handle. - The submit thread passes whatever is ready to one `vkQueueSubmit2`, in the device's commit order, ahead of it the upload of zero fills, and the last submit info signals the progress diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index 1014dd521..b7b5aa13a 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -416,8 +416,7 @@ impl Building { } } - /// The current segment's command buffer, begun with its barrier. Commands after a signal go - /// in a new segment. + /// The current segment's command buffer. Commands after a signal go in a new segment. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] fn command(&mut self) -> Result { if !self.last().signals.is_empty() { @@ -433,7 +432,6 @@ impl Building { }; let recorder = self.gpu.recorder.insert(recorder); let command = recorder.next(&core.device)?; - record::begin_barrier(&core.device, command, &core.counters); self.last().command = Some(command); Ok(command) } diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 83e287655..721763159 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -133,7 +133,9 @@ pub struct Metrics { pub submissions: u64, /// Encoders recorded: compute, and later blit and render. pub passes: u64, - /// Pipeline-barrier commands recorded. + /// Pipeline-barrier commands recorded into command buffers' work: one at the end of each + /// segment with commands and of each upload, and one before a dispatch at a hazard. A block's + /// zero fill, made apart from any command buffer, is not counted. pub barriers: u64, /// Bytes the runtime copied for a call: `replace_region` and `get_bytes` staging, and the /// counted copy at commit where a device offers no linear image. diff --git a/crates/metal2vulkan-rt/src/fill.rs b/crates/metal2vulkan-rt/src/fill.rs index 2362e2029..76768b519 100644 --- a/crates/metal2vulkan-rt/src/fill.rs +++ b/crates/metal2vulkan-rt/src/fill.rs @@ -5,6 +5,7 @@ use crate::counters::{Counters, Gauge, Metric}; use crate::device::{lock, Core}; use crate::error::Error; +use crate::record::{barrier, Reach}; use ash::vk; use std::sync::{Mutex, PoisonError}; @@ -157,6 +158,7 @@ impl Filler { .begin_command_buffer(command, &begin) .map_err(Error::vulkan("vkBeginCommandBuffer"))?; record(device, command, objects.zeros, buffer, offset, end); + barrier(device, command, Reach::Commands); device .end_command_buffer(command) .map_err(Error::vulkan("vkEndCommandBuffer"))?; diff --git a/crates/metal2vulkan-rt/src/record.rs b/crates/metal2vulkan-rt/src/record.rs index 137de6898..786a2e51f 100644 --- a/crates/metal2vulkan-rt/src/record.rs +++ b/crates/metal2vulkan-rt/src/record.rs @@ -43,40 +43,56 @@ impl Recorder { } } -#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -/// Records the barrier every segment of a Metal command buffer begins with: every write earlier in -/// submission order (earlier command buffers, earlier segments, zero fills) is made visible to -/// every command after it. -pub(crate) fn begin_barrier(device: &ash::Device, buffer: vk::CommandBuffer, counters: &Counters) { +/// What a barrier makes earlier writes visible to. +#[derive(Clone, Copy)] +pub(crate) enum Reach { + /// Every later command, in this submission and every later one on the queue. + Commands, + /// Every later command, and the host once it has waited for the work. + Host, +} + +/// Records one global memory barrier: every write earlier in submission order is made visible +/// to what `reach` names, and every later command waits for every earlier one. It is the only +/// barrier the runtime records for buffers: none names a buffer or a range. The caller counts it +/// where it is part of the queues' work. +pub(crate) fn barrier(device: &ash::Device, buffer: vk::CommandBuffer, reach: Reach) { + let (stages, accesses) = match reach { + Reach::Commands => ( + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE, + ), + Reach::Host => ( + vk::PipelineStageFlags2::ALL_COMMANDS | vk::PipelineStageFlags2::HOST, + vk::AccessFlags2::MEMORY_READ + | vk::AccessFlags2::MEMORY_WRITE + | vk::AccessFlags2::HOST_READ + | vk::AccessFlags2::HOST_WRITE, + ), + }; let barrier = [vk::MemoryBarrier2::default() .src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) .src_access_mask(vk::AccessFlags2::MEMORY_WRITE) - .dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .dst_access_mask(vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE)]; + .dst_stage_mask(stages) + .dst_access_mask(accesses)]; let dependency = vk::DependencyInfo::default().memory_barriers(&barrier); // SAFETY: the buffer is recording. unsafe { device.cmd_pipeline_barrier2(buffer, &dependency) }; - counters.count(Metric::Barriers); } -/// Ends a segment's command buffer, after the barrier that makes its writes visible to the host: -/// Shared memory reads the GPU's writes once the command buffer completes or the host sees an -/// event it signals. +/// Ends a segment's command buffer after its one barrier, which reaches the host: Shared memory +/// reads the GPU's writes once the command buffer completes or the host sees an event it signals, +/// and a later command buffer's commands run after this one's, as Metal orders the command +/// buffers of a queue. A segment begins with no barrier: the one ending each earlier segment, +/// upload and fill covers it. pub(crate) fn end( device: &ash::Device, buffer: vk::CommandBuffer, counters: &Counters, ) -> Result<(), Error> { - let barrier = [vk::MemoryBarrier2::default() - .src_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) - .src_access_mask(vk::AccessFlags2::MEMORY_WRITE) - .dst_stage_mask(vk::PipelineStageFlags2::HOST) - .dst_access_mask(vk::AccessFlags2::HOST_READ)]; - let dependency = vk::DependencyInfo::default().memory_barriers(&barrier); - // SAFETY: the buffer is recording. - unsafe { device.cmd_pipeline_barrier2(buffer, &dependency) }; + barrier(device, buffer, Reach::Host); counters.count(Metric::Barriers); - // SAFETY: as above. + // SAFETY: the buffer is recording. unsafe { device.end_command_buffer(buffer) }.map_err(Error::vulkan("vkEndCommandBuffer")) } diff --git a/crates/metal2vulkan-rt/src/submit.rs b/crates/metal2vulkan-rt/src/submit.rs index e5fe909be..0ebad6962 100644 --- a/crates/metal2vulkan-rt/src/submit.rs +++ b/crates/metal2vulkan-rt/src/submit.rs @@ -10,7 +10,7 @@ use crate::event::EventInner; use crate::fill; use crate::memory::Block; use crate::queue::QueueInner; -use crate::record::Recorder; +use crate::record::{self, Reach, Recorder}; use ash::vk; use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; @@ -458,11 +458,14 @@ fn submit(core: &Core, batch: Batch) { watch, } = batch; let device = &core.device; - // SAFETY: the upload's command buffer was recording under the work lock, which `stage` took - // it out under. - let mut ok = upload - .as_ref() - .is_none_or(|upload| unsafe { device.end_command_buffer(upload.command) }.is_ok()); + // The upload's fills are visible to every command after it. + let mut ok = upload.as_ref().is_none_or(|upload| { + record::barrier(device, upload.command, Reach::Commands); + core.counters.count(Metric::Barriers); + // SAFETY: the upload's command buffer was recording under the work lock, which `stage` + // took it out under. + unsafe { device.end_command_buffer(upload.command) }.is_ok() + }); if let Some(upload) = &upload { segments.insert( 0, diff --git a/crates/metal2vulkan-rt/src/tests/command.rs b/crates/metal2vulkan-rt/src/tests/command.rs index a4400b431..009f0c1ee 100644 --- a/crates/metal2vulkan-rt/src/tests/command.rs +++ b/crates/metal2vulkan-rt/src/tests/command.rs @@ -192,8 +192,8 @@ mod on_device { assert!(at("second scheduled Scheduled") < at("second completed Completed None")); assert!(at("first completed Completed None") < at("second completed Completed None")); let after = device.counters().metrics(); - // Each segment with commands has two barriers: one at its start, one at its end. - assert_eq!(after.barriers - before.barriers, 4, "{name}"); + // Each segment with commands has one barrier, at its end. + assert_eq!(after.barriers - before.barriers, 2, "{name}"); assert!(after.submissions > before.submissions, "{name}"); // After commit, Metal refuses.