From 7f50ad492eb9ffa7f2d9bd83a64c0fb1152e344d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 22 Oct 2026 21:48:05 +0300 Subject: [PATCH] Run a predicated loop's copies again until the loop ends Content: the tree of `development` at 61cb931693, unchanged. --- .../src/command_buffer/mod.rs | 57 +++- .../src/command_buffer/rerun.rs | 268 ++++++++++++++++++ crates/metal2vulkan-runtime/src/compute.rs | 14 +- crates/metal2vulkan-runtime/src/deferred.rs | 80 +++++- crates/metal2vulkan-runtime/src/encoder.rs | 75 ++++- crates/metal2vulkan-runtime/src/error.rs | 20 +- .../metal2vulkan-runtime/src/predication.rs | 113 +++++++- crates/metal2vulkan-runtime/src/queue.rs | 63 +++- .../metal2vulkan-runtime/src/scheduler/mod.rs | 26 +- .../src/tests/command_buffer.rs | 1 + .../metal2vulkan-runtime/src/work_counts.rs | 11 + .../src/metal/platform/predication_tests.rs | 101 ++++++- .../src/runtime_lane/predication.rs | 260 +++++++++++++---- docs/API.md | 19 +- docs/REFUSALS.md | 14 +- docs/RUNTIME-PORTING.md | 2 +- 16 files changed, 994 insertions(+), 130 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/command_buffer/rerun.rs diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index d488ef664..1a9febbb3 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -41,6 +41,7 @@ pub(super) mod kept_barriers; pub(super) mod own; pub(super) mod rebound_use; mod reencode; +pub(super) mod rerun; mod storage_form; mod submit; @@ -1193,6 +1194,11 @@ impl State { self.ended.len() } + /// The encoders, or parts of them, ended so far. + pub(super) fn parts(&self) -> usize { + self.recorded.len() + } + /// A compute encoder of `dispatch_type` opened: it joins the unit of command predication of /// the compute encoder that ended just before it, of its dispatch type with no event wait or /// signal between and no fence update in it, taking the bodies of the loops it left open, or @@ -1676,7 +1682,7 @@ impl CommandBuffer { pub(super) fn new(queue: &CommandQueue, slot: Slot) -> CommandBuffer { CommandBuffer(Arc::new(CommandBufferShared { device: queue.device().clone(), - queue: queue.clone(), + queue: queue.kept(), state: Mutex::new(State { status: CommandBufferStatus::NotEnqueued, error: None, @@ -2494,11 +2500,14 @@ impl CommandBuffer { return Err(error); } }; - // The first segment a host step records, which the device announces. + // The first segment a host step records, which the device announces (a loop's check + // records nothing). let announced = segments .iter() .zip(&prepared) - .find(|((_, host), prepared)| *host && !prepared.for_good) + .find(|((work, host), prepared)| { + *host && !prepared.for_good && !matches!(work, Deferred::Loop(_)) + }) .map(|((work, _), _)| work.clone()); // A host step may record commands after the commit (a segment not recorded for good): // until the command buffer completes, the buffers they use keep their pages. @@ -3115,17 +3124,24 @@ impl CommandBufferShared { /// What the host step of batch `index` waits for ([`needs_host_step`](Self::needs_host_step)): /// the work submitted before it, where the GPU may write what a segment or an indirect - /// sparse update of it reads; and the pipelines its segments record, while one is being made. + /// sparse update of it reads, its own `VkQueue`'s alone where those are loops' checks; and the + /// pipelines its segments record, while one is being made, and what a loop's check runs again. pub(crate) fn step_waits(&self, index: usize) -> StepWaits { let state = lock(&self.state); let recorded = &state.recorded[state.batch_range(index)]; let segments = || recorded.iter().flat_map(|encoder| &encoder.segments); + let sparse = recorded + .iter() + .flat_map(|encoder| &encoder.sparse) + .any(SparseUpdate::needs_step); + // A loop's check reads only what its laying, on its own `VkQueue`, wrote (`rerun.rs`). + let checks_alone = !sparse + && segments() + .filter(|segment| segment.steps_after_the_gpu()) + .all(|segment| matches!(segment.work, Deferred::Loop(_))); StepWaits { - gpu: segments().any(Segment::steps_after_the_gpu) - || recorded - .iter() - .flat_map(|encoder| &encoder.sparse) - .any(SparseUpdate::needs_step), + gpu: segments().any(Segment::steps_after_the_gpu) || sparse, + queue_alone: checks_alone.then(|| self.queue.vk_queue()), pipelines: segments().any(Segment::steps_after_pipelines), } } @@ -3157,18 +3173,25 @@ impl CommandBufferShared { /// batch that shares a resource with it waits for it. `None` while some of it is not known: a /// segment its host step records (or records again) for what the GPU may write, one its /// submission records (a scrub), or a resource state encoder's update, whose uses its - /// submission adds. + /// submission adds. A loop's check adds what its laying's parts use, which it may run again. pub(crate) fn footprint(&self, index: usize) -> Option> { let state = lock(&self.state); - let recorded = &state.recorded[state.batch_range(index)]; + let range = state.batch_range(index); + let recorded = &state.recorded[range.clone()]; let mut summaries = Vec::new(); let mut known = Vec::new(); - for encoder in recorded { + for (at, encoder) in recorded.iter().enumerate() { if !encoder.sparse.is_empty() { return None; } summaries.push(&encoder.summary); for segment in &encoder.segments { + // A loop's check may run its laying again: what the laying's parts use (`rerun.rs`). + if let Deferred::Loop(check) = &segment.work { + let laying = state.recorded.get(check.from()..range.start + at); + summaries.extend(laying.into_iter().flatten().map(|part| &part.summary)); + continue; + } match &segment.recorded { // One recorded again on the GPU alone uses what its recording does; one a // route outgrew, what its host step finds. @@ -3238,12 +3261,14 @@ impl CommandBufferShared { // announces: a recording on the GPU alone made again announces nothing // (`gpu_execute::Rerecord`), unless a route outgrew it (`Deferred::outgrown`), which the // step records from the records; nor does work recorded again for the CPU's writes since - // the commit alone (`Deferred::rewritten`), or for its pipelines alone. + // the commit alone (`Deferred::rewritten`), or for its pipelines alone; nor a loop's check, + // which records nothing. let announced = steps .iter() .find(|(_, work, inputs)| { work.gpu_written() && (!matches!(inputs, Some(StepInputs::Rerecord(_))) || work.outgrown()) + && !matches!(inputs, Some(StepInputs::Loop)) }) .map(|(_, work, _)| work.clone()); let buffer = CommandBuffer(Arc::clone(self)); @@ -3279,8 +3304,14 @@ impl CommandBufferShared { } } drop(state); + // A loop's check that runs its laying again holds the batch: the segments after it + // read what the laying leaves, and step once it ends (`rerun.rs`). + let holds = work.holds(); // Dropped without the lock: what it holds may be a state's last handle. drop((work, inputs)); + if holds { + break; + } } drop(buffer); if let Some(announced) = announced { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs new file mode 100644 index 000000000..4c2fd7b93 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs @@ -0,0 +1,268 @@ +//! The check after a predicated loop laid down as copies (`predication.rs`): where the step past +//! its last copy halted its unit (the loop would run another pass), the check runs the loop's +//! laying again, from the halted loop's copy on (the halt word, `bind::PredicationOp::WhileFirst`), +//! until the loop ends, as Metal runs a loop on; then the command buffer goes on. Metal never ends +//! a loop that runs without bound (an M3 Max with macOS 27.0.1 ran an endless While and DoWhile for +//! 180 s, each, with no error), and neither does the check. +//! +//! - **The laying** is its own run of `VkCommandBuffer`s, begun to be submitted again: the +//! encoder cut its command buffer at the outermost loop's start (`EncoderCore::cut_reusable`) +//! and ends it at the check (`EncoderCore::end_laying`), the textures it shadows copied back at +//! each end, behind a barrier from everything before it at its start and one to every later +//! command and to the host at its end. A run again so repeats nothing encoded before the loop (a +//! render pass's load and store actions, a blit, an event's signal or wait) and copies in again +//! what it shadows; every dispatch in it is gated, and every step holds until the halted loop's +//! copy starts. +//! - **The check** is a host step (`Deferred::Loop`), its segment the first of the batch after the +//! laying: once the work before it completed, it reads the unit's halt word. 0: the batch goes. +//! Else a thread of its own ([`run_again`]) submits the laying again to the command buffer's +//! `VkQueue` with a fence of the device's, logged for the command buffer's relayed failures +//! (`device/relay.rs`), waits for it, and reads the word again, until it is 0; then it wakes the +//! scheduler. Meanwhile the batch waits as for a pipeline's making +//! (`Segment::steps_after_pipelines`), and the scheduler goes on with every other line; a batch +//! committed later on another queue that conflicts with the laying's uses waits behind it +//! (`CommandBufferShared::footprint`), as behind any host step. The batch's other segments step +//! once the check ends: they read what the laying leaves. +//! - **Let go.** The thread stops at the process's exit, a lost device or a failed submission or +//! wait (each failing the command buffer as its submission would), and once the program holds +//! no handle of the command buffer's queue (`CommandQueue::let_go`): Metal would run the loop +//! until the process ends, but nothing of the program can then commit to the queue or wait for +//! it, and the device would stay held. The command buffer then fails +//! (`CommandBufferError::PredicatedLoopLetGo`), its later batches unsubmitted, and lets go of +//! its device. Each run again is counted (`WorkCounts::predicated_loop_runs_again`). + +use super::gate::Hold; +use super::{recording_error, submission_error, CommandBuffer, CommandBufferShared}; +use crate::device::lock; +use crate::encoder::RecordedSegment; +use crate::error::{internal, CommandBufferError, Error}; +use crate::exit_guard::{self, Call}; +use crate::retained::Retained; +use crate::tracker::EncoderUses; +use crate::upload::Upload; +use ash::vk; +use metal2vulkan::bind::ReplayFaults; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// How long one wait for a run again's fence lasts before the thread looks for an exit. +const WAIT_SLICE: Duration = Duration::from_millis(100); + +/// The check after a loop's laying (the module docs). +pub(crate) struct LoopCheck { + /// The unit's skip counter: its halt word lies 4 bytes past it. + counter: Upload, + /// The laying's `VkCommandBuffer`s as encoded, in order. + raws: Vec, + /// The command buffer's parts before the laying's first: the laying lies in the parts from + /// there to the check's. + from: usize, + rounds: Mutex, +} + +/// Where a check stands. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Rounds { + /// Its host step has not read the halt word yet. + Unchecked, + /// Its thread runs the laying again. + Running, + /// The loop ended, or the check stopped. + Ended, +} + +/// How one run again ended. +enum Round { + /// The loop would run on. + Again, + /// The loop ended. + Ended, + /// The command buffer fails so. + Failed(CommandBufferError), + /// The process is exiting: the thread does nothing more. + Exiting, +} + +impl LoopCheck { + /// The check of the laying in `raws`, after `from` of the command buffer's parts, of the loop + /// of the unit of skip counter `counter`. + pub(crate) fn new(counter: Upload, raws: Vec, from: usize) -> LoopCheck { + LoopCheck { + counter, + raws, + from, + rounds: Mutex::new(Rounds::Unchecked), + } + } + + /// The command buffer's parts before the laying's first. + pub(crate) fn from(&self) -> usize { + self.from + } + + /// Whether its thread runs the laying again: its batch waits. + pub(crate) fn running(&self) -> bool { + *lock(&self.rounds) == Rounds::Running + } + + /// Whether the unit is halted: its halt word is not 0. Read once the work that writes it + /// completed. + fn halted(&self) -> bool { + self.counter.read::<8>()[4..] != [0; 4] + } + + /// Its host step, once the laying completed: nothing to record; where the loop halted its + /// unit, its thread starts running the laying again. Refused where the thread cannot start. + pub(crate) fn step( + self: &Arc, + command_buffer: &CommandBuffer, + ) -> Result { + if !self.halted() { + *lock(&self.rounds) = Rounds::Ended; + return Ok(nothing()); + } + *lock(&self.rounds) = Rounds::Running; + let check = Arc::clone(self); + let buffer = command_buffer.0.hold(); + let spawned = std::thread::Builder::new() + .name("metal2vulkan-loop".to_owned()) + .spawn(move || run_again(&check, buffer)); + if spawned.is_err() { + *lock(&self.rounds) = Rounds::Ended; + return Err(internal( + "a predicated loop's check could not start its thread", + )); + } + Ok(nothing()) + } + + /// Submit the laying again on `buffer`'s `VkQueue`, wait for it, and read the halt word. + fn run_once(&self, buffer: &CommandBufferShared) -> Round { + let device = &buffer.device; + if device.is_lost() { + return Round::Failed(CommandBufferError::DeviceLost); + } + let Some(busy) = exit_guard::enter() else { + return Round::Exiting; + }; + let shared = device.shared(); + let raw = shared.vk(); + let mut reals = Vec::with_capacity(self.raws.len()); + for &handle in &self.raws { + // SAFETY: each ended, its command buffer committed and its batch submitted, which + // replayed it; inside a section. + match unsafe { crate::recorder::resolve(raw, handle) } { + Ok(real) => reals.push(real), + Err(error) => { + return Round::Failed(recording_error(device, crate::error::vulkan(error))) + } + } + } + // SAFETY: the device's fences, inside a section. + let fence = match unsafe { shared.fences.take(raw) } { + Ok(fence) => fence, + Err(error) => return Round::Failed(submission_error(device, error)), + }; + let queue = buffer.queue.vk_queue(); + let submits = [vk::SubmitInfo::default().command_buffers(&reals)]; + shared.counts.queue_submitted(1, reals.len()); + // SAFETY: the `VkQueue` is used under its lock; each command buffer was begun to be + // submitted again, ended, and is in no pending submission: the laying's batch completed + // before the check's step, and each run again before the next; the fence is unsignaled + // and in no pending submission. + let submitted = shared.submit_logged( + (queue, None), + Some(fence), + &buffer.relayed, + |vk_queue| unsafe { raw.queue_submit(vk_queue, &submits, fence) }, + ); + exit_guard::called(Call::QueueSubmit); + if let Err(error) = submitted { + // SAFETY: a fence no submission took. + unsafe { crate::release::object(raw, fence) }; + return Round::Failed(submission_error(device, error)); + } + drop(busy); + loop { + let Some(_busy) = exit_guard::enter() else { + return Round::Exiting; + }; + // SAFETY: the device's fence, submitted above. + let waited = + unsafe { raw.wait_for_fences(&[fence], true, WAIT_SLICE.as_nanos() as u64) }; + exit_guard::called(Call::WaitForFences); + match waited { + Ok(()) => break, + Err(vk::Result::TIMEOUT) => continue, + // The fence stays in the relay's log, as a failed batch's does, never released. + Err(error) => return Round::Failed(submission_error(device, error)), + } + } + let Some(_busy) = exit_guard::enter() else { + return Round::Exiting; + }; + // Out of the relay's log before it goes back: its submission completed. + if let Some(flights) = shared.flights(queue) { + flights.let_go(fence); + } + // SAFETY: the fence is signaled and its submission completed. + let reset = unsafe { raw.reset_fences(&[fence]) }; + exit_guard::called(Call::ResetFences); + let mut fences = vec![fence]; + match reset { + // SAFETY: unsignaled and in no pending submission; inside a section. + Ok(()) => unsafe { shared.fences.give(raw, &mut fences) }, + Err(_) => { + // SAFETY: in no pending submission. + unsafe { crate::release::object(raw, fence) }; + } + } + shared.counts.predicated_loop_ran_again(); + // A failure the driver relayed for the run fails the command buffer at its completion. + if buffer.relayed.failure().is_some() { + return Round::Ended; + } + match self.halted() { + true => Round::Again, + false => Round::Ended, + } + } +} + +/// A recording of nothing: a check records no command. +fn nothing() -> RecordedSegment { + RecordedSegment { + raws: Vec::new(), + summary: EncoderUses::new(true).finish(), + retained: Retained::default(), + executions: Vec::new(), + keys: Default::default(), + taken: Default::default(), + resident_misses: 0, + faults: ReplayFaults::default(), + } +} + +/// The check's thread (the module docs): run the laying again until the loop ends, or the check +/// stops; then the scheduler takes the batch again. +fn run_again(check: &LoopCheck, buffer: Hold) { + let waker = buffer.device.shared().scheduler.waker(); + let failure = loop { + if buffer.queue.let_go() { + break Some(CommandBufferError::PredicatedLoopLetGo); + } + match check.run_once(&buffer) { + Round::Again => continue, + Round::Ended => break None, + Round::Failed(error) => break Some(error), + // What it holds stays held to the process's end, as the scheduler's does. + Round::Exiting => return std::mem::forget(buffer), + } + }; + if let Some(error) = failure { + lock(&buffer.state).step_failure.get_or_insert(error); + } + *lock(&check.rounds) = Rounds::Ended; + waker(); + drop(buffer); +} diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index cb2951997..452fbeab3 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -236,6 +236,13 @@ impl CommandBuffer { // It joins its command buffer's unit of command predication, carrying on the loops open // across its start, or starts the next. let carried = self.state().enter_predication(dispatch_type); + let mut core = core; + // The laying of a loop open across its start goes on in a command buffer of its own, which + // the loop's check may submit again (`predication.rs`). + if !carried.is_empty() && self.state().predication.laying() { + let raw = core.cut_reusable()?; + self.state().predication.laid_into(raw); + } Ok(ComputeCommandEncoder { core, dispatch_type, @@ -2071,7 +2078,12 @@ fn record( .and_then(|kept| kept.made.get()) .or_else(|| planned.made_for(commands)) .filter(|_| !apart_samplers(&device, &objects)); - let (pipelines, pending) = match (own.filter(|_| !core.encodes_again()), kept_made) { + // Inside a predicated loop's laying, it waits for them too: the laying stays one run of + // command buffers its check may submit again (`command_buffer/rerun.rs`); but where its + // variant records in one of its own. + let laying = core.command_buffer().state().predication.laying(); + let waits = core.encodes_again() || (laying && !apart_samplers(&device, &objects)); + let (pipelines, pending) = match (own.filter(|_| !waits), kept_made) { (Some(_), Some(made)) => { if let Some(kept) = &kept { drop(kept.made.set(made.clone())); diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index cc032644c..4811d138a 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -4,6 +4,7 @@ //! the device announces for the step. The command buffer handles every kind alike //! (`command_buffer`). +use super::command_buffer::rerun::LoopCheck; use super::command_buffer::CommandBuffer; use super::device::lock; use super::encoder::RecordedSegment; @@ -37,6 +38,9 @@ pub(super) enum Deferred { RenderPass(Arc), /// A compute encoder's dispatch whose pipelines were being made (`pending_dispatch.rs`). Pending(Arc), + /// The check after a predicated loop's laying, which runs it again while the loop would run + /// on (`command_buffer/rerun.rs`): it records nothing, and its batch waits for it. + Loop(Arc), } /// What `commit` left a segment for its host step. @@ -56,6 +60,8 @@ pub(super) enum StepInputs { /// execution; its step names states among those alive then, and compiles only what `commit` /// could not settle (`DeferredPass::settle`). RenderPass, + /// A loop's check: nothing past the check itself. + Loop, /// An execution `commit` recorded on the GPU alone with no barrier between its commands, which /// its batch's submission records again with them where a route encoded since may set a /// barrier in a record (`gpu_execute::Rerecord`); no work on the GPU is waited for. @@ -95,7 +101,10 @@ impl Deferred { /// at the dispatch, and its writes are its encoder's to copy back. pub(super) fn leaves_shadows(&self) -> bool { match self { - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => true, + Deferred::Execute(_) + | Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Loop(_) => true, Deferred::RenderPass(_) | Deferred::Pending(_) => false, } } @@ -113,7 +122,7 @@ impl Deferred { Deferred::Execute(execute) => { execute.icb.gpu_written() || execute.indirect() || execute.predicated() } - Deferred::Dispatch(_) => true, + Deferred::Dispatch(_) | Deferred::Loop(_) => true, Deferred::SparseScrub(_) | Deferred::Pending(_) => false, Deferred::RenderPass(pass) => pass.gpu_written(), } @@ -256,6 +265,14 @@ impl Deferred { pipelines: false, }) } + // Its host step reads the unit's halt word once the laying completed. + Deferred::Loop(_) => Ok(Prepared { + recorded: None, + for_good: false, + inputs: StepInputs::Loop, + retained: None, + pipelines: false, + }), // Recorded now where its pipelines are made; else by a host step once they are, // which makes again one whose making failed. Deferred::Pending(dispatch) => { @@ -304,7 +321,10 @@ impl Deferred { Deferred::RenderPass(pass) => Ok(pass .record_on_gpu(command_buffer)? .map(|recorded| (recorded, StepInputs::RenderPass))), - Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Pending(_) => Ok(None), + Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Pending(_) + | Deferred::Loop(_) => Ok(None), } } @@ -335,7 +355,10 @@ impl Deferred { StepInputs::Rerecord(rerecord) => { return rerecord.record(command_buffer, execute); } - StepInputs::Dispatch | StepInputs::None | StepInputs::RenderPass => { + StepInputs::Dispatch + | StepInputs::None + | StepInputs::RenderPass + | StepInputs::Loop => { return Err(internal("an execution's host step without its states")); } }; @@ -347,6 +370,7 @@ impl Deferred { Deferred::SparseScrub(_) => Err(internal("a sparse scrub's host step")), Deferred::RenderPass(pass) => pass.record(command_buffer, true), Deferred::Pending(dispatch) => dispatch.record(command_buffer), + Deferred::Loop(check) => check.step(command_buffer), } } @@ -359,7 +383,10 @@ impl Deferred { match self { Deferred::RenderPass(pass) => pass.outgrown(), Deferred::Execute(execute) => execute.outgrown(), - Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Pending(_) => false, + Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Pending(_) + | Deferred::Loop(_) => false, } } @@ -371,7 +398,23 @@ impl Deferred { match self { Deferred::Execute(execute) => execute.rewritten(), Deferred::RenderPass(pass) => pass.rewritten(), - Deferred::Dispatch(_) | Deferred::SparseScrub(_) | Deferred::Pending(_) => false, + Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Pending(_) + | Deferred::Loop(_) => false, + } + } + + /// Whether its batch waits for it after its host step: a loop's check while it runs the + /// laying again (`command_buffer/rerun.rs`), which wakes the scheduler as it ends. + pub(super) fn holds(&self) -> bool { + match self { + Deferred::Loop(check) => check.running(), + Deferred::Execute(_) + | Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::RenderPass(_) + | Deferred::Pending(_) => false, } } @@ -380,19 +423,26 @@ impl Deferred { match self { Deferred::RenderPass(pass) => pass.making(), Deferred::Pending(dispatch) => dispatch.making(), - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => false, + Deferred::Execute(_) + | Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Loop(_) => false, } } /// What its recording uses, on `device`, where that is known before it records /// (`DeferredPass::known_summary`): a render pass's that executes no render commands. `None` /// for the rest, whose uses their recording finds: an execution's or an indirect dispatch's - /// from the records and arguments it reads, a scrub's at its submission. + /// from the records and arguments it reads, a scrub's at its submission; a loop's check's are + /// its laying's (`CommandBufferShared::footprint`). pub(super) fn known_summary(&self, device: &Device) -> Option> { match self { Deferred::RenderPass(pass) => pass.known_summary(device), Deferred::Pending(dispatch) => Some(dispatch.known_summary()), - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => None, + Deferred::Execute(_) + | Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Loop(_) => None, } } @@ -401,7 +451,10 @@ impl Deferred { match self { Deferred::RenderPass(pass) => pass.when_made(waker), Deferred::Pending(dispatch) => dispatch.when_made(waker), - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => {} + Deferred::Execute(_) + | Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Loop(_) => {} } } @@ -411,7 +464,10 @@ impl Deferred { match self { Deferred::RenderPass(pass) => pass.hasten(urgency), Deferred::Pending(dispatch) => dispatch.hasten(urgency), - Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => {} + Deferred::Execute(_) + | Deferred::Dispatch(_) + | Deferred::SparseScrub(_) + | Deferred::Loop(_) => {} } } @@ -420,7 +476,7 @@ impl Deferred { match self { Deferred::Execute(execute) => indirect_execute::degrade_host_replay(device, execute), Deferred::Dispatch(dispatch) => dispatch.degrade(device), - Deferred::SparseScrub(_) | Deferred::Pending(_) => {} + Deferred::SparseScrub(_) | Deferred::Pending(_) | Deferred::Loop(_) => {} Deferred::RenderPass(pass) => pass.degrade(device), } } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index b040a3044..e9f278081 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -128,12 +128,14 @@ impl Segment { /// the CPU wrote since (`Deferred::rewritten`); or `commit`'s recording on the /// GPU alone must be made again ([`rerecords`](Self::rerecords)); or `commit` recorded it on /// the GPU for good, and a route encoded since may write more than it decided on, or gives an - /// execution's check something to see (`Deferred::outgrown`). + /// execution's check something to see (`Deferred::outgrown`); or its step left work its batch + /// waits for (`Deferred::holds`). pub(super) fn needs_step(&self) -> bool { (!self.stepped && (self.host || self.pipelines || self.work.gpu_written() || self.work.rewritten())) || self.rerecords() || self.work.outgrown() + || self.work.holds() } /// Whether `commit` recorded it on the GPU alone with no barrier between its commands and its @@ -149,9 +151,10 @@ impl Segment { (!self.stepped && (self.host || self.work.gpu_written())) || self.work.outgrown() } - /// Whether its host step waits for a pipeline still being made. + /// Whether its host step waits for a pipeline still being made, or its batch for what its + /// step left (`Deferred::holds`), which wakes the scheduler as it ends. pub(super) fn steps_after_pipelines(&self) -> bool { - !self.stepped && self.work.making() + (!self.stepped && self.work.making()) || self.work.holds() } /// Whether it is a dispatch whose pipelines were being made (`pending_dispatch.rs`): an @@ -1556,22 +1559,80 @@ impl EncoderCore { let next = { let command_buffer = &self.open.command_buffer; let mut state = command_buffer.state(); + // Work left apart inside a predicated loop's laying keeps it from running again alone + // (`predication.rs`). + state.predication.break_laying(); command_buffer.allocate_raw(&mut state)? }; - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + self.begin(next, vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)?; + Ok(Continuation(next)) + } + + /// End the `VkCommandBuffer` the encoder records into and go on in a new one, begun to be + /// submitted again, for a predicated loop's laying (`predication.rs`), which its check may + /// run again: the textures it shadows copied back first, so the laying copies in again what + /// it reads, and a barrier from everything before at its start. Its handle. Refused where the + /// current one does not end, or none can be made, which abandons the command buffer. + pub(super) fn cut_reusable(&mut self) -> Result { + let copies = self.shadows.leave(); + self.shadow_copies(&copies); + self.barrier(Barrier::everything()); + let next = { + let command_buffer = &self.open.command_buffer; + let mut state = command_buffer.state(); + command_buffer.allocate_raw(&mut state) + }; + let ended = next.and_then(|next| { + // SAFETY: as in `barrier`. + unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?; + Ok(next) + }); + let next = match ended { + Ok(next) => next, + Err(error) => { + self.open.command_buffer.state().abandoned = true; + return Err(error); + } + }; + self.ended.push(self.raw); + self.raw = next; + if let Err(error) = self.begin(next, vk::CommandBufferUsageFlags::empty()) { + self.open.command_buffer.state().abandoned = true; + return Err(error); + } + self.barrier(Barrier::everything()); + Ok(next) + } + + /// End a predicated loop's laying (`predication.rs`) with its check, `work`: the textures it + /// shadows copied back, a barrier from everything before to every later command and to the + /// host, which reads the unit's halt word; the encoder goes on after the check. + pub(super) fn end_laying(&mut self, work: Deferred) -> Result<(), Error> { + let copies = self.shadows.leave(); + self.shadow_copies(&copies); + self.barrier(Barrier::to_all()); + self.defer(work) + } + + /// Begin `raw`, a `VkCommandBuffer` the command buffer's pool just handed out, with `flags`. + fn begin( + &self, + raw: vk::CommandBuffer, + flags: vk::CommandBufferUsageFlags, + ) -> Result<(), Error> { + let begin = vk::CommandBufferBeginInfo::default().flags(flags); // SAFETY: the command buffer was just allocated from the pool; only this encoder // records it. unsafe { self.device() .shared() .vk() - .begin_command_buffer(next, &begin) + .begin_command_buffer(raw, &begin) } .map_err(vulkan)?; let counts = &self.device().shared().counts; counts.encoder_command_buffer_begun(Begun::Continuation); - Ok(Continuation(next)) + Ok(()) } /// [`defer`](Self::defer) `work`, the encoder going on in `next`: refused only where the diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 7af6657fd..e87659946 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1764,11 +1764,21 @@ pub enum CommandBufferError { DetachedBacking, /// A command-predication loop (`ComputeCommandEncoder::encode_start_while`, /// `encode_start_do_while`) would have run past the copies of its commands the runtime laid - /// down (at most 64, or 16 inside another loop, fewer for a long body). Metal runs a loop on - /// without bound; the runtime ran those copies, then nothing more of the loop's unit, and then - /// the rest of the command buffer, so its results are not Metal's. Set before the command - /// buffer's completed handlers run. + /// down (at most 64, or 16 inside another loop, fewer for a long body), and its commands hold + /// work the runtime records apart (an indirect dispatch or an indirect command buffer's + /// execution a host step records, or a dispatch whose variant records in a command buffer of + /// its own), so its copies cannot run again alone, as the runtime runs any other loop on. + /// Metal runs a loop on without bound; the runtime ran those copies, then nothing more of the + /// loop's unit, and then the rest of the command buffer, so its results are not Metal's. Set + /// before the command buffer's completed handlers run. PredicatedLoopPastCopies, + /// A command-predication loop of the command buffer would still run on (Metal runs a loop + /// without bound, as the runtime runs its laying again) when the program held no handle of + /// the command buffer's queue any more: the runtime stopped running it, nothing of the + /// command buffer after the loop ran, and the command buffer let go of its device. Metal runs + /// such a loop until the process ends. Set before the command buffer's completed handlers + /// run. + PredicatedLoopLetGo, /// A unit of command predication (`ComputeCommandEncoder::encode_start_if` and the others) /// ended with a block open that no misused record killed, where the unit's commands skipped /// as the GPU reached its end (a failed If or While, a held If's Else, a block inside one that @@ -2007,6 +2017,7 @@ impl CommandBufferError { | CommandBufferError::HostStepObject(_) | CommandBufferError::EncodedUseRebound | CommandBufferError::PredicatedLoopPastCopies + | CommandBufferError::PredicatedLoopLetGo | CommandBufferError::PredicationOpenAtUnitEnd { .. } | CommandBufferError::DefaultRasterSampleCount | CommandBufferError::CallRefused(_) => 1, @@ -2053,6 +2064,7 @@ impl CommandBufferError { | CommandBufferError::HostStepObject(_) | CommandBufferError::EncodedUseRebound | CommandBufferError::PredicatedLoopPastCopies + | CommandBufferError::PredicatedLoopLetGo | CommandBufferError::CallRefused(_) => FailureOrigin::Runtime, } } diff --git a/crates/metal2vulkan-runtime/src/predication.rs b/crates/metal2vulkan-runtime/src/predication.rs index 26d33c0e2..a87c6a0ab 100644 --- a/crates/metal2vulkan-runtime/src/predication.rs +++ b/crates/metal2vulkan-runtime/src/predication.rs @@ -114,15 +114,26 @@ //! copies share a flag the first failing test sets, after which every copy skips; the first //! copy's start takes the flag as clear (`PredicationOp::WhileFirst`, `PredicationOp::DoFirst`). //! A step past the copies halts the unit where the loop would run another: it sets the unit's -//! halt word (beside its counter) to the loop's id, every later step of the unit then leaves -//! its words and runs nothing (a host step's command too), and the command buffer fails at its -//! completion, before its completed handlers run -//! (`CommandBufferError::PredicatedLoopPastCopies`), where Metal runs on. A loop inside -//! another's copy is laid down again in each, with an id of its own. A killed loop gets no -//! copies. +//! halt word (beside its counter) to the loop's id, and every later step of the unit then leaves +//! its words and runs nothing (a host step's command too). A loop inside another's copy is laid +//! down again in each, with an id of its own. A killed loop gets no copies. +//! - **A loop's laying runs again** until the loop ends, as Metal runs a loop on without bound +//! (`command_buffer/rerun.rs`): the outermost loop's laying goes in command buffers of its own, +//! cut at its start (and at each later encoder of its unit it spans) and ended by its check, a +//! host step that reads the halt word once the laying completed and, while it is set, submits +//! the laying again; the halted loop's first copy's start clears it, so the loop goes on where +//! it stopped, and nothing encoded before the loop runs again. A dispatch inside a laying whose +//! pipelines are being made waits for them, so the laying stays one run. A laying that holds +//! work recorded apart (an indirect dispatch or an indirect command buffer's execution a host +//! step records, or a dispatch whose variant records in a command buffer of its own) cannot run +//! again alone: its loop past its copies fails the command buffer at its completion, before its +//! completed handlers run (`CommandBufferError::PredicatedLoopPastCopies`), where Metal runs +//! on. use super::buffer::Buffer; +use super::command_buffer::rerun::LoopCheck; use super::compute::{ComputeCommandEncoder, EncoderState}; +use super::deferred::Deferred; use super::degradation::Degradation; use super::encoder::EncoderCore; use super::error::{internal, Error, RuntimeGap}; @@ -140,6 +151,7 @@ use metal2vulkan::bind::{ }; use metal2vulkan::metal::{BarrierScope, DispatchType}; use std::ops::Range; +use std::sync::Arc; /// A command buffer's command predication (the module docs): its current unit, the gated runs of /// its records, and the check words of the units that ended with a live block open. @@ -167,11 +179,30 @@ pub(super) struct Predication { halts: Vec, /// The loops laid down so far: the next one's id ([`PredicationStep::id`]) is one more. loops: u32, + /// The laying of the unit's outermost open loop, from its start (the module docs). + laying: Option, /// The steps and gated dispatches recorded so far: what a loop's copies lay down is counted /// from it ([`copies_of`]). laid: u64, } +/// The laying of a unit's outermost loop: the `VkCommandBuffer`s its encoders recorded it into, +/// each begun to be submitted again, from the one begun at the loop's start; whether a segment +/// left among them (work a host step or the commit records apart) keeps it from running again +/// alone; and the command buffer's parts recorded before its first, after which its own lie. +pub(super) struct Laying { + raws: Vec, + broken: bool, + from: usize, +} + +impl Laying { + /// Its `VkCommandBuffer`s, in order, and the parts before its first. + pub(super) fn into_parts(self) -> (Vec, usize) { + (self.raws, self.from) + } +} + /// The copies of a loop no other loop holds, at most. const FIRST_COPIES: u64 = 64; @@ -576,6 +607,8 @@ impl Predication { /// The current unit ends: one with a live block open keeps its check word for the completion, /// with the index of the record that opened its outermost open block. fn end_unit(&mut self) { + // A loop open where its unit ends is closed by no End: its laying is checked by none. + self.laying = None; if let Some(unit) = self.unit.take() { if let (true, Some(check), Some(outermost)) = (unit.live_open(), unit.check, unit.stack.first()) @@ -877,6 +910,45 @@ impl Predication { Ok((answer, Some(record))) } + /// The outermost loop's laying begins, in `raw`, after `from` parts of the command buffer. + pub(super) fn lay_from(&mut self, raw: vk::CommandBuffer, from: usize) { + self.laying = Some(Laying { + raws: vec![raw], + broken: false, + from, + }); + } + + /// Whether the outermost open loop's laying goes on. + pub(super) fn laying(&self) -> bool { + self.laying.is_some() + } + + /// The laying goes on in `raw`, begun to be submitted again. + pub(super) fn laid_into(&mut self, raw: vk::CommandBuffer) { + if let Some(laying) = &mut self.laying { + laying.raws.push(raw); + } + } + + /// The encoder left a segment inside the laying: it cannot run again alone. + pub(super) fn break_laying(&mut self) { + if let Some(laying) = &mut self.laying { + laying.broken = true; + } + } + + /// The outermost loop closed: its laying, where it may run again alone and the loop was laid + /// down as copies, with the unit's counter, whose halt word its check reads. + fn end_laying(&mut self, copied: bool) -> Option<(Laying, Upload)> { + let laying = self.laying.take()?; + if laying.broken || !copied { + return None; + } + let counter = self.unit.as_ref()?.counter.clone()?; + Some((laying, counter)) + } + /// How many loops the unit has open. fn loops_open(&self) -> usize { self.unit.as_ref().map_or(0, |unit| { @@ -1513,6 +1585,16 @@ impl ComputeCommandEncoder { test: Option<&Test>, event: impl FnOnce() -> Event, ) -> Result<(), Error> { + // The outermost loop's laying goes in command buffers of its own, from here to its check + // (the module docs). + if self.predication(|predication, _, _| Ok(predication.loops_open() == 0))? { + let raw = self.core().cut_reusable()?; + let from = self.core().command_buffer().state().parts(); + self.predication(|predication, _, _| { + predication.lay_from(raw, from); + Ok(()) + })?; + } let (resume, record) = self.predication(|predication, uploads, device| { predication.start_loop(uploads, device, test) })?; @@ -1547,6 +1629,7 @@ impl ComputeCommandEncoder { self.captures().open.pop(); } self.capture(event); + self.end_laying(false)?; return Ok(end.answer); }; let record = end @@ -1557,9 +1640,27 @@ impl ComputeCommandEncoder { .ok_or_else(|| internal("a live loop's End without its body"))?; self.capture(event); self.lay_copies(kernel, (&looping, test.as_ref()), &body)?; + self.end_laying(true)?; Ok(end.answer) } + /// A loop closed, laid down as copies where `copied`: where it was the outermost one and its + /// laying may run again alone, the laying ends with its check (the module docs). + fn end_laying(&mut self, copied: bool) -> Result<(), Error> { + let ended = self.predication(|predication, _, _| { + Ok(match predication.loops_open() { + 0 => predication.end_laying(copied), + _ => None, + }) + })?; + let Some((laying, counter)) = ended else { + return Ok(()); + }; + let (raws, from) = laying.into_parts(); + let check = LoopCheck::new(counter, raws, from); + self.core().end_laying(Deferred::Loop(Arc::new(check))) + } + /// Lay down the further copies of `looping` (with a DoWhile's `test`), each its start, its /// `body` replayed with the encoder's state each command ran with, and its end; then the step /// that finds whether it would run past them. The encoder's state is then as before. diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs index 9681859f7..39f7ef92a 100644 --- a/crates/metal2vulkan-runtime/src/queue.rs +++ b/crates/metal2vulkan-runtime/src/queue.rs @@ -45,8 +45,27 @@ use std::time::Instant; const DEFAULT_MAX_COMMAND_BUFFER_COUNT: usize = 64; /// A Metal command queue (`MTLCommandQueue`). Cheap to clone (a retain); `Send + Sync`. -#[derive(Clone)] -pub struct CommandQueue(Arc); +pub struct CommandQueue(Arc, Handle); + +/// Whether a [`CommandQueue`] is one of the program's handles, which its queue counts +/// ([`QueueShared::handles`]): every one the queue's making or a clone hands out, but the one +/// each of its command buffers keeps (`CommandQueue::kept`). +struct Handle(bool); + +impl Clone for CommandQueue { + fn clone(&self) -> CommandQueue { + self.0.handles.fetch_add(1, Ordering::Relaxed); + CommandQueue(Arc::clone(&self.0), Handle(true)) + } +} + +impl Drop for CommandQueue { + fn drop(&mut self) { + if self.1 .0 { + self.0.handles.fetch_sub(1, Ordering::Release); + } + } +} impl std::fmt::Debug for CommandQueue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -78,6 +97,9 @@ struct QueueShared { /// Its command buffers Metal's GPU hangs at that are in flight, and those committed with an /// event wait meanwhile (`command_buffer/hang.rs`). hangs: Arc, + /// The program's handles of it ([`Handle`]): a predicated loop that would run on without + /// bound stops once none is left (`command_buffer/rerun.rs`). + handles: AtomicUsize, } /// A queue's slots: one per uncompleted command buffer, at most `max`. @@ -242,17 +264,21 @@ impl Device { self.take_device_sampler(); self.make_texture_pool(); self.keep_room(); - CommandQueue(Arc::new(QueueShared { - device: self.clone(), - id, - vk_queue, - label: Mutex::new(None), - slots: Slots::new(count, Arc::clone(&self.shared().uncommitted)), - latest_gpu_end: Mutex::new(0), - memoryless_backings: Mutex::new(BackingPool::default()), - kept_images: KeptImages::default(), - hangs: Arc::default(), - })) + CommandQueue( + Arc::new(QueueShared { + device: self.clone(), + id, + vk_queue, + label: Mutex::new(None), + slots: Slots::new(count, Arc::clone(&self.shared().uncommitted)), + latest_gpu_end: Mutex::new(0), + memoryless_backings: Mutex::new(BackingPool::default()), + kept_images: KeptImages::default(), + hangs: Arc::default(), + handles: AtomicUsize::new(1), + }), + Handle(true), + ) } } @@ -265,6 +291,17 @@ impl Drop for QueueShared { } impl CommandQueue { + /// The queue a command buffer of it keeps: not one of the program's handles ([`Handle`]), + /// though a clone of it is. + pub(super) fn kept(&self) -> CommandQueue { + CommandQueue(Arc::clone(&self.0), Handle(false)) + } + + /// Whether the program holds no handle of the queue any more ([`Handle`]). + pub(super) fn let_go(&self) -> bool { + self.0.handles.load(Ordering::Acquire) == 0 + } + /// `device`. pub fn device(&self) -> &Device { &self.0.device diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index ec980a7f4..c6828eda7 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -50,7 +50,10 @@ //! values): only then are the records the work before it wrote known. The thread then records //! the batch's segments (`CommandBufferShared::host_step`) without its lock, each step a //! section of the exit guard, and submits the batch in its order. Meanwhile it submits other -//! ready batches; the completion turns wake it as batches complete while a gate is pending. +//! ready batches; the completion turns wake it as batches complete while a gate is pending. A +//! batch whose step is a predicated loop's check alone waits for its own `VkQueue`'s work +//! alone; while the check's thread runs the loop's laying again, the batch waits as for a +//! making, which the thread's end wakes the thread for (`command_buffer/rerun.rs`). //! - **Submission checks** (`command_buffer/checks.rs`). A batch of a command buffer with a check //! is held, once otherwise ready and its host step recorded, until the checks of Metal's //! submissions in it ran (`CommandBufferShared::run_checks`), which the thread runs as it runs @@ -467,6 +470,9 @@ struct Held { pub(crate) struct StepWaits { /// The work submitted before it to complete (its gate): 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. + pub(crate) queue_alone: Option, /// A pipeline it records, still being made. pub(crate) pipelines: bool, } @@ -1450,16 +1456,22 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left, awaits: continue; } let gate = held.gate.get_or_insert_with(|| values.clone()); - awaits.gate(gate); + match waits.queue_alone { + Some(queue) => awaits.gate_on(queue, gate[queue], gate.len()), + None => awaits.gate(gate), + } fence(Ordering::SeqCst); let device = held.buffer.device(); let shared = device.shared(); let reached = device.is_lost() - || shared - .queues - .iter() - .zip(gate.iter()) - .all(|(queue, &value)| queue.completed_value() >= value); + || match waits.queue_alone { + Some(queue) => shared.queues[queue].completed_value() >= gate[queue], + None => shared + .queues + .iter() + .zip(gate.iter()) + .all(|(queue, &value)| queue.completed_value() >= value), + }; if reached { left.push(Kind::Step, (held.buffer.hold(), held.index)); } else { diff --git a/crates/metal2vulkan-runtime/src/tests/command_buffer.rs b/crates/metal2vulkan-runtime/src/tests/command_buffer.rs index 85f2d8380..d9f5ed887 100644 --- a/crates/metal2vulkan-runtime/src/tests/command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/tests/command_buffer.rs @@ -262,6 +262,7 @@ fn a_command_buffer_error_names_whose_failure_it_is() { (E::Internal(VkResultCode(-13)), Runtime, 1), (E::IndexPoolOverflow, Runtime, 8), (E::PredicatedLoopPastCopies, Runtime, 1), + (E::PredicatedLoopLetGo, Runtime, 1), (E::PredicationOpenAtUnitEnd { record: 3 }, Metal, 1), (E::SparseHeapSplit, Runtime, 1), ( diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 778e8ddb6..8c71a6a22 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -55,6 +55,7 @@ pub(crate) struct Counters { pipeline_layouts_shared: AtomicU64, variant_pipelines_made: AtomicU64, flights_followed: AtomicU64, + predicated_loop_runs_again: AtomicU64, variants_taken_back: AtomicU64, unlisted_argument_sampler_buffers: AtomicU64, host_step_sampler_sets_made: AtomicU64, @@ -749,6 +750,12 @@ impl Counters { self.flights_followed.fetch_add(1, Ordering::Relaxed); } + /// A predicated loop's check ran its laying again (`command_buffer/rerun.rs`). + pub(crate) fn predicated_loop_ran_again(&self) { + self.predicated_loop_runs_again + .fetch_add(1, Ordering::Relaxed); + } + /// A graphics pipeline library of `part` was made (`pipeline/libraries.rs`). pub(crate) fn pipeline_library_made(&self, part: crate::pipeline::libraries::Part) { self.pipeline_libraries_made.fetch_add(1, Ordering::Relaxed); @@ -2444,6 +2451,9 @@ pub struct WorkCounts { /// Of those, the makings that waited for a twin's making in the air, of the same functions /// and specialization, to land before their own (`pipeline/flight.rs`). pub flights_followed: u64, + /// The runs again of predicated loops' layings that a check submitted, the loop still running + /// past its copies (`command_buffer/rerun.rs`). + pub predicated_loop_runs_again: u64, /// Variants made again that took back a released variant's objects and `VkPipeline`s. pub variants_taken_back: u64, /// Command buffers committed whose commands' plans could not list every sampler state live @@ -3898,6 +3908,7 @@ impl Device { pipeline_layouts_shared: counters.pipeline_layouts_shared.load(Ordering::Relaxed), variant_pipelines_made: counters.variant_pipelines_made.load(Ordering::Relaxed), flights_followed: counters.flights_followed.load(Ordering::Relaxed), + predicated_loop_runs_again: counters.predicated_loop_runs_again.load(Ordering::Relaxed), variants_taken_back: counters.variants_taken_back.load(Ordering::Relaxed), unlisted_argument_sampler_buffers: counters .unlisted_argument_sampler_buffers diff --git a/crates/metal2vulkan-validation/src/metal/platform/predication_tests.rs b/crates/metal2vulkan-validation/src/metal/platform/predication_tests.rs index fb53dc6cd..3acc873ab 100644 --- a/crates/metal2vulkan-validation/src/metal/platform/predication_tests.rs +++ b/crates/metal2vulkan-validation/src/metal/platform/predication_tests.rs @@ -17,10 +17,12 @@ use objc2::rc::Retained; use objc2::runtime::ProtocolObject; use objc2_foundation::{NSRange, NSString}; use objc2_metal::{ - MTLBarrierScope, MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, - MTLCommandQueue, MTLComputeCommandEncoder, MTLComputePipelineState, MTLDevice, MTLDispatchType, - MTLFence, MTLHeap, MTLHeapDescriptor, MTLHeapType, MTLLibrary, MTLResourceOptions, - MTLResourceUsage, MTLSize, MTLStorageMode, + MTLBarrierScope, MTLBlitCommandEncoder, MTLBuffer, MTLClearColor, MTLCommandBuffer, + MTLCommandEncoder, MTLCommandQueue, MTLComputeCommandEncoder, MTLComputePipelineState, + MTLDevice, MTLDispatchType, MTLFence, MTLHeap, MTLHeapDescriptor, MTLHeapType, MTLLibrary, + MTLLoadAction, MTLOrigin, MTLPixelFormat, MTLRenderPassDescriptor, MTLResourceOptions, + MTLResourceUsage, MTLSize, MTLStorageMode, MTLStoreAction, MTLTextureDescriptor, + MTLTextureUsage, }; type Buffer = Retained>; @@ -499,3 +501,94 @@ fn metal_runs_a_block_left_open_where_its_commands_run() { assert_eq!(got.once().as_deref(), Some(ran), "{script}"); } } + +/// A loop past the copies the runtime lays down, after a render pass that clears a texture and +/// blits in its command buffer, on Metal (the runtime lane's +/// `a_loop_run_again_repeats_nothing_before_it`, the same commands): the pass clears the texture +/// red, a blit copies green into it, another 5 into log word 3, and `while (log[3] != 105) +/// { mark 3; mark 4 }` runs 100 passes; the texture reads green. +#[test] +fn metal_runs_a_loop_after_a_cleared_pass_and_blits_once() { + let probe = Probe::new(); + write(&probe.log, &[0; LOG_WORDS]); + let device = probe.queue.device(); + let descriptor = MTLTextureDescriptor::new(); + descriptor.setPixelFormat(MTLPixelFormat::RGBA8Unorm); + // SAFETY: a 1 x 1 texture. + unsafe { + descriptor.setWidth(1); + descriptor.setHeight(1); + } + descriptor.setStorageMode(MTLStorageMode::Shared); + descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); + let texture = device + .newTextureWithDescriptor(&descriptor) + .expect("a texture"); + let green = shared(&device, &[u32::from_le_bytes([0, 255, 0, 255])]); + let five = shared(&device, &[5]); + let out = shared(&device, &[0]); + let command_buffer: CommandBuffer = probe.queue.commandBuffer().expect("a command buffer"); + let pass = MTLRenderPassDescriptor::renderPassDescriptor(); + // SAFETY: attachment 0 of the pass's array. + let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) }; + color.setTexture(Some(&texture)); + color.setLoadAction(MTLLoadAction::Clear); + color.setStoreAction(MTLStoreAction::Store); + color.setClearColor(MTLClearColor { + red: 1.0, + green: 0.0, + blue: 0.0, + alpha: 1.0, + }); + command_buffer + .renderCommandEncoderWithDescriptor(&pass) + .expect("a render encoder") + .endEncoding(); + let origin = MTLOrigin { x: 0, y: 0, z: 0 }; + let blit = command_buffer.blitCommandEncoder().expect("a blit encoder"); + // SAFETY: a texel of the texture and words of Shared buffers that outlive the command buffer, + // which the test waits for. + unsafe { + blit.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin( + &green, 0, 4, 4, one(), &texture, 0, 0, origin, + ); + blit.copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size( + &five, 0, &probe.log, 12, 4, + ); + } + blit.endEncoding(); + let encoder = command_buffer + .computeCommandEncoder() + .expect("a compute encoder"); + let e = &*encoder; + let log = &*probe.log; + // SAFETY: the private selectors take these arguments (`v@:@QQI` and `B@:`), on a live compute + // encoder; the log outlives the command buffer. + unsafe { + let _: () = msg_send![e, encodeStartWhile: log, offset: 12usize, comparison: 1usize, referenceValue: 105u32]; + for tag in [3, 4] { + probe.bind(&encoder, tag); + encoder.dispatchThreads_threadsPerThreadgroup(one(), one()); + } + let end: bool = msg_send![e, encodeEndWhile]; + assert!(end); + } + encoder.endEncoding(); + let blit = command_buffer.blitCommandEncoder().expect("a blit encoder"); + // SAFETY: as above. + unsafe { + blit.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage( + &texture, 0, 0, origin, one(), &out, 0, 4, 4, + ); + } + blit.endEncoding(); + commit_and_wait(&command_buffer, "Metal loop after a cleared pass and blits") + .expect("the command buffer completes"); + let contents = probe.log.contents().cast::(); + // SAFETY: the Shared log's words, read once the command buffer's work ended. + let counts = unsafe { std::slice::from_raw_parts(contents.as_ptr(), LOG_WORDS) }; + assert_eq!(counts[3..5], [105, 100]); + // SAFETY: the Shared buffer's word, read once the command buffer's work ended. + let texel = unsafe { out.contents().cast::().read() }; + assert_eq!(texel.to_le_bytes(), [0, 255, 0, 255]); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/predication.rs b/crates/metal2vulkan-validation/src/runtime_lane/predication.rs index 9b8989015..d3c64278c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/predication.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/predication.rs @@ -16,8 +16,10 @@ //! an indirect range; inside a holding one each runs once; setters inside a skipped block take //! effect; //! - loops run as Metal's ran, each pass with the encoder's state each command was encoded with, -//! nested, around Ifs and every dispatch form, across their unit's encoders, and a loop that -//! would run past the copies the runtime lays down fails its command buffer; +//! nested, around Ifs and every dispatch form, across their unit's encoders, and past the +//! copies the runtime lays down, whose laying its check runs again, repeating nothing encoded +//! before the loop (a render pass's clear, a blit); a loop without bound stops once the program +//! holds no handle of its queue; //! - a live block open where its unit ends fails the command buffer where its commands skip there, //! as Metal's GPU recovery does, and is harmless where they run; //! - a word past its buffer reads as Metal reads it: zero within the 256 bytes Metal rounds a lone @@ -33,14 +35,17 @@ use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; use metal2vulkan::bind::PredicationStepForm; use metal2vulkan::device::VkFeature; -use metal2vulkan::metal::{BarrierScope, DispatchType, IndirectCommandType, ResourceUsage}; +use metal2vulkan::metal::{ + BarrierScope, DispatchType, IndirectCommandType, PixelFormat, ResourceUsage, TextureUsage, +}; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use metal2vulkan_devtools::llvm_assemble_text; use metal2vulkan_runtime::{ - Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, ComputeCommandEncoder, - ComputePipelineState, Degradation, Device, Error, EventRef, HeapDescriptor, HeapType, - IndirectCommandBuffer, IndirectCommandBufferDescriptor, Invalid, MetalLevel, PipelineOptions, - Problem, ResourceOptions, RuntimeGap, Size, + BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferError, CommandBufferStatus, + ComputeCommandEncoder, ComputePipelineState, Degradation, Device, Error, EventRef, + HeapDescriptor, HeapType, IndirectCommandBuffer, IndirectCommandBufferDescriptor, Invalid, + LoadAction, MetalLevel, Origin, PipelineOptions, Problem, RenderPassDescriptor, + ResourceOptions, RuntimeGap, Size, StoreAction, TextureDescriptor, }; /// The kernels: `prd_mark` adds 1 to word `t[0]` of `log`; `prd_put` writes `v[0]` into word 0 @@ -491,7 +496,21 @@ pub(crate) fn loop_cases() -> Vec { "1", )); } - let fixed: [FixedLoopCase; 21] = [ + let fixed: [FixedLoopCase; 25] = [ + // Past the copies laid down, the laying run again: 128 passes, a DoWhile of 65, and inner + // loops of 17 and 40 passes in a While of 2, with marks after. + ("w128 T0 V T1", &[(0, 128), (1, 1)], "1"), + ("D T0 z65 T1", &[(0, 65), (1, 1)], "1"), + ( + "w2 T0 Q1 w17@1 T1 T2 V V T3", + &[(0, 2), (1, 17), (2, 34), (3, 1)], + "11", + ), + ( + "w2 T0 Q1 w40@1 T1 T2 V V T3", + &[(0, 2), (1, 40), (2, 80), (3, 1)], + "11", + ), ("% w7 T0 V", &[(0, 7)], "1"), ( "w3 T0 Q1 w4@1 T1 Q2 D T2 T3 z5@2 V V", @@ -1435,13 +1454,17 @@ fn loops_run_as_metal_ran() { } /// The loops Metal ran ([`loop_cases`]) run its passes, answer what its Ends answered and -/// complete, but those that run past the copies the runtime lays down, which fail their command -/// buffers (`CommandBufferError::PredicatedLoopPastCopies`), where Metal runs on, and one whose -/// unbalanced End would drop the unit's ungated dispatches, refused +/// complete, those that run past the copies the runtime lays down among them (their laying run +/// again, counted), but one whose unbalanced End would drop the unit's ungated dispatches, refused /// (`RuntimeGap::PredicationDropsUngatedWork`). #[test] fn loop_streams_run_as_metal_ran() { - const PAST_COPIES: [&str; 7] = [ + // Past the copies laid down: 2 x 2 x ... six deep, its laying cut at 64, 16, 16 and 1 copies. + const PAST_COPIES: [&str; 11] = [ + "w128 T0 V T1", + "D T0 z65 T1", + "w2 T0 Q1 w17@1 T1 T2 V V T3", + "w2 T0 Q1 w40@1 T1 T2 V V T3", "w2@1 T1 Q2 w2@2 T2 Q3 w2@3 T3 Q4 w2@4 T4 Q5 w2@5 T5 Q6 w2@6 T6 T50 V V V V V V", "D T1 Q2 D T2 Q3 D T3 Q4 D T4 T50 z2@4 z2@3 z2@2 z2@1", "w65 T0 T1 V T2", @@ -1455,6 +1478,7 @@ fn loop_streams_run_as_metal_ran() { on_device(|device| { let streams = Streams::new(device); let mut wrong = Vec::new(); + let mut ran_again = device.work_counts().predicated_loop_runs_again; for (script, want, answers) in loop_cases() { let got = run_counted(&streams, &script); if script == DROPS_UNGATED { @@ -1468,16 +1492,11 @@ fn loop_streams_run_as_metal_ran() { wrong.push(format!("{script}: refused {error:?}")); continue; } - if PAST_COPIES.contains(&script.as_str()) { - let failed = ( - CommandBufferStatus::Error, - Some(CommandBufferError::PredicatedLoopPastCopies), - ); - if (got.status, got.error) != failed { - wrong.push(format!("{script}: {:?} {:?}", got.status, got.error)); - } - continue; + let again = device.work_counts().predicated_loop_runs_again; + if PAST_COPIES.contains(&script.as_str()) && again == ran_again { + wrong.push(format!("{script}: its laying ran no time again")); } + ran_again = again; let mut counts = vec![0; LOG_WORDS]; for &(tag, n) in &want { counts[tag] = n; @@ -1529,37 +1548,44 @@ fn every_dispatch_form_runs_in_each_pass() { }); } -/// A loop that would run past the copies the runtime lays down (64, or 16 inside another loop) -/// runs them, halts its unit (the unit's later commands run nothing) and fails its command buffer -/// (`CommandBufferError::PredicatedLoopPastCopies`), where Metal runs it on; one that ends within -/// them completes. +/// A loop that runs past the copies the runtime lays down (64, or 16 inside another loop) runs on +/// as Metal's runs: its check runs its laying again until it ends, as many times as the passes past +/// the copies need (counted), and its command buffer completes with every pass Metal ran (a While +/// of 65, 128 and 1000, a DoWhile of 65, an inner While of 17 and 40 in a While of 2 that resets +/// the inner count each pass). #[test] -fn a_loop_past_its_copies_fails_its_command_buffer() { +fn a_loop_past_its_copies_runs_on() { on_device(|device| { - let past = ( - CommandBufferStatus::Error, - Some(CommandBufferError::PredicatedLoopPastCopies), - ); - let got = looped(device, false, |encoder, marks| { - encoder - .encode_start_while(Some(&marks.log), 0, NOT_EQUAL, 65) - .unwrap(); - marks.mark(encoder, 0); - assert_eq!(encoder.encode_end_while(), Ok(true)); - marks.mark(encoder, 1); - }); - assert_eq!((got.0, got.1), past, "a While of 65"); - assert_eq!(got.2[..2], [64, 0], "a While of 65"); + let ok = (CommandBufferStatus::Completed, None); + let again = || device.work_counts().predicated_loop_runs_again; + for (n, runs) in [(65u32, 1u64), (128, 1), (1000, 15)] { + let before = again(); + let got = looped(device, false, |encoder, marks| { + encoder + .encode_start_while(Some(&marks.log), 0, NOT_EQUAL, n) + .unwrap(); + marks.mark(encoder, 0); + assert_eq!(encoder.encode_end_while(), Ok(true)); + marks.mark(encoder, 1); + }); + assert_eq!((got.0, got.1), ok, "a While of {n}"); + assert_eq!(got.2[..2], [n, 1], "a While of {n}"); + assert_eq!(again() - before, runs, "a While of {n}: its runs again"); + } + let before = again(); let got = looped(device, false, |encoder, marks| { encoder.encode_start_do_while().unwrap(); marks.mark(encoder, 0); let end = encoder.encode_end_do_while(Some(&marks.log), 0, LESS, 65); assert_eq!(end, Ok(true)); + marks.mark(encoder, 1); }); - assert_eq!((got.0, got.1), past, "a DoWhile of 65"); - assert_eq!(got.2[0], 64, "a DoWhile of 65"); + assert_eq!((got.0, got.1), ok, "a DoWhile of 65"); + assert_eq!(got.2[..2], [65, 1], "a DoWhile of 65"); + assert_eq!(again() - before, 1, "a DoWhile of 65: its runs again"); let zero = kernel(device, "prd_put", false); - for (inner, status) in [(16, (CommandBufferStatus::Completed, None)), (17, past)] { + for (inner, runs) in [(16u32, 0u64), (17, 2), (40, 4)] { + let before = again(); let got = looped(device, false, |encoder, marks| { let log = Some(&marks.log); encoder.encode_start_while(log, 0, NOT_EQUAL, 2).unwrap(); @@ -1572,19 +1598,155 @@ fn a_loop_past_its_copies_fails_its_command_buffer() { marks.mark(encoder, 2); assert_eq!(encoder.encode_end_while(), Ok(true)); assert_eq!(encoder.encode_end_while(), Ok(true)); + marks.mark(encoder, 3); }); - assert_eq!((got.0, got.1), status, "an inner While of {inner}"); - // The inner loop past its copies halts the unit in the outer loop's first pass. - let passes = if inner > 16 { 1 } else { 2 }; + assert_eq!((got.0, got.1), ok, "an inner While of {inner}"); + let want = [2, inner, 2 * inner, 1]; + assert_eq!(got.2[..4], want, "an inner While of {inner}"); assert_eq!( - got.2[..3], - [passes, 16, passes * 16], - "an inner While of {inner}" + again() - before, + runs, + "an inner While of {inner}: its runs again" ); } }); } +/// What a loop's check runs again is the loop's laying alone: a render pass that clears a texture, +/// a blit into it and a blit into the log, encoded before the loop in its command buffer, run +/// once, as Metal runs them. The loop (`while (log[3] != 105) { mark 3; mark 4 }`, from the blit's +/// 5) runs 100 passes, its laying once again; a run again of the blit would run more passes, and +/// one of the clear would leave the texture red. +#[test] +fn a_loop_run_again_repeats_nothing_before_it() { + on_device(|device| { + let marks = Marks::new(device); + let queue = device.new_command_queue().unwrap(); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 1, 1, false); + descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let texture = device.new_texture(&descriptor).unwrap(); + let green = buffer_with(device, &[0, 255, 0, 255]).unwrap(); + let five = buffer_with(device, &bytes(&[5])).unwrap(); + let out = buffer_with(device, &[0; 4]).unwrap(); + let before = device.work_counts().predicated_loop_runs_again; + let command_buffer = queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(texture.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + color.clear_color = ClearColor::new(1.0, 0.0, 0.0, 1.0); + command_buffer + .render_command_encoder(&pass) + .unwrap() + .end_encoding() + .unwrap(); + let (origin, size) = (Origin::new(0, 0, 0), Size::new(1, 1, 1)); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_texture( + &green, + 0, + 4, + 4, + size, + &texture, + 0, + 0, + origin, + BlitOption::None, + ) + .unwrap(); + blit.copy_from_buffer_to_buffer(&five, 0, &marks.log, 12, 4) + .unwrap(); + blit.end_encoding().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .encode_start_while(Some(&marks.log), 12, NOT_EQUAL, 105) + .unwrap(); + marks.mark(&mut encoder, 3); + marks.mark(&mut encoder, 4); + assert_eq!(encoder.encode_end_while(), Ok(true)); + encoder.end_encoding().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_texture_to_buffer( + &texture, + 0, + 0, + origin, + size, + &out, + 0, + 4, + 4, + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + complete(&command_buffer); + assert_eq!(marks.counts()[3..5], [105, 100]); + assert_eq!(read_buffer(&out, 0, 4).unwrap(), [0, 255, 0, 255]); + let again = device.work_counts().predicated_loop_runs_again - before; + assert_eq!(again, 1, "the laying ran once again"); + }); +} + +/// A loop without bound (`while (log[1] != 1) mark 0`, log[1] staying 0) runs on, its laying run +/// again and again, as Metal's runs (an M3 Max with macOS 27.0.1 ran one 180 s with no error), +/// while the program holds a handle of its queue (one of two let go changes nothing); once it +/// holds none, the check stops and the command buffer fails +/// (`CommandBufferError::PredicatedLoopLetGo`), nothing after the loop run, its runs again +/// stopped. +#[test] +fn a_loop_without_bound_stops_once_its_queue_is_let_go() { + on_device(|device| { + let marks = Marks::new(device); + let queue = device.new_command_queue().unwrap(); + let held = queue.clone(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .encode_start_while(Some(&marks.log), 4, NOT_EQUAL, 1) + .unwrap(); + marks.mark(&mut encoder, 0); + assert_eq!(encoder.encode_end_while(), Ok(true)); + marks.mark(&mut encoder, 2); + encoder.end_encoding().unwrap(); + let again = || device.work_counts().predicated_loop_runs_again; + let before = again(); + command_buffer.commit().unwrap(); + let ran = |more: u64| { + let start = std::time::Instant::now(); + while again() < before + more { + assert!( + start.elapsed() < WAIT, + "its laying ran {} times again", + again() - before + ); + std::thread::yield_now(); + } + }; + ran(3); + drop(queue); + ran(6); + let running = !matches!( + command_buffer.status(), + CommandBufferStatus::Completed | CommandBufferStatus::Error + ); + assert!(running, "{:?}", command_buffer.status()); + drop(held); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Error); + assert_eq!( + command_buffer.error(), + Some(CommandBufferError::PredicatedLoopLetGo) + ); + let stopped = again(); + std::thread::sleep(std::time::Duration::from_millis(50)); + assert_eq!(again(), stopped, "its runs again stopped"); + assert_eq!(marks.counts()[2], 0, "nothing after the loop ran"); + }); +} + /// The shapes of [`a_runs_first_indirect_dispatch_of_another_type_ends_the_process_at_26_7`]: /// each the consumer's name for it, its script, and the tag of the dispatch at which macOS 26.7 /// ends the process (`None`: it runs on). diff --git a/docs/API.md b/docs/API.md index 9c8b31ab1..a7e738f07 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2953,12 +2953,19 @@ each item named states the rule in full. while and do-while loops) runs Metal's blocks and loops on every device, with or without buffer device addresses, its unbalanced records answering `NO` and dropping their ranges, and its live blocks left open where a unit ends failing the command buffer as Metal's GPU recovery - does (`PredicationOpenAtUnitEnd`). Loops nest to any depth. A loop is laid down as 64 copies - (16 inside another loop, fewer where they would lay down more than 16384 steps and gated - dispatches, and at least one); one that runs past them runs nothing more of its unit and fails - its command buffer (`PredicatedLoopPastCopies`), where Metal runs on. A condition word past its buffer reads as - Metal reads it (the heap's bytes, or zero), and as zero where Metal reads memory unrelated to the - buffer (`predication-word-past-buffer`). Refused where Metal runs on (`RuntimeGap`): an + does (`PredicationOpenAtUnitEnd`). Loops nest to any depth and run as many passes as Metal's. + A loop is laid down as 64 copies (16 inside another loop, fewer where they would lay down more + than 16384 steps and gated dispatches, and at least one); where it runs past them, a check + submits its copies again, from where it stopped, until it ends, each time a round trip to the + host, holding the batches after it on its queue (and those on other queues that use what the + loop uses), and nothing encoded before the loop runs again. A loop without bound runs on, as + Metal's does, until the program holds no handle of its queue: then its command buffer fails + (`PredicatedLoopLetGo`). A loop whose commands hold work the runtime records apart (an + indirect dispatch or an indirect command buffer's execution a host step records) cannot be + submitted again alone: past its copies it runs nothing more of its unit and fails its command + buffer (`PredicatedLoopPastCopies`), where Metal runs on. A condition word past its buffer reads + as Metal reads it (the heap's bytes, or zero), and as zero where Metal reads memory unrelated to + the buffer (`predication-word-past-buffer`). Refused where Metal runs on (`RuntimeGap`): an unbalanced record that is its unit's first after dispatches of the unit (`PredicationDropsUngatedWork`). - **A GPU-written indirect command naming a placed ID runs that ID's live holder**, the state made diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 8f8fb5bbc..07ae736fd 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -14,7 +14,7 @@ Columns: - `none`: no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets; - `?`: not assessed yet. -Generated at `8639f4209`. +Generated at `e21cc1069`. ## Totals @@ -134,7 +134,7 @@ Generated at `8639f4209`. | `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | devices short of a Vulkan feature the site names; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/binding_view.rs:167`, `crates/metal2vulkan-runtime/src/texture.rs:994` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured | | `MipmapGeneration` | `generateMipmapsForTexture:` where the device's filter is not shown to give Metal's answer | devices without VkFeature::ShaderInt64; devices without a format's usage; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/blit_texture.rs:1818`, `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37` (+5) | `app`: generateMipmapsForTexture: where the device's filter is not Metal's | | `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/host_memory.rs:430`, `crates/metal2vulkan-runtime/src/host_memory.rs:470` (+3) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory | -| `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2832` | `rare`: GPU times on a queue without timestamps | +| `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2841` | `rare`: GPU times on a queue without timestamps | | `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | devices without VkFeature::OcclusionQueryPrecise | 1: `crates/metal2vulkan-runtime/src/visibility.rs:452` | `rare`: counting occlusion queries on a device without precise queries | | `ViewFormatReinterpretation` | A texture view whose format has other components, or components of other widths, than its texture's (`RGBA8Unorm` as `R32Uint`), on a device whose... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/view_plan.rs:570` | `app`: a view of another component layout on a portability subset (MoltenVK) | | `SeparateMultisampledDepthStencil` | A render pass whose depth and stencil attachments are separate multisampled textures that it loads or may store, on a device without maintenance8,... | - | via a helper: 7: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:188`, `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:294` (+5) | `rare`: separate multisampled depth and stencil textures | @@ -171,7 +171,7 @@ Generated at `8639f4209`. | `HeapTextureMemory` | A heap texture whose image the heap's memory type does not take | every device (runtime piece not built) | 5: `crates/metal2vulkan-runtime/src/texture/heap.rs:1508`, `crates/metal2vulkan-runtime/src/texture/heap.rs:1515` (+3) | `app`: a heap texture the heap's memory type does not take | | `FunctionTablePastMaxBufferLength` | A visible-function table of more entries than one buffer of the device's `max_buffer_length` holds words for, or than its size word holds | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/function_table.rs:622` | `none`: a function table past one buffer | | `IndirectCommandBufferPastMaxBufferLength` | An indirect command buffer of more commands than one buffer of the device's `max_buffer_length` holds the records of | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:522` | `none`: an ICB past one buffer | -| `IndirectRenderCommands` | What indirect command buffers lack of their render commands | every device (runtime piece not built) | 17: `crates/metal2vulkan-runtime/src/compute.rs:1115`, `crates/metal2vulkan-runtime/src/compute.rs:1196` (+15) | `rare`: indirect render commands' remaining pieces | +| `IndirectRenderCommands` | What indirect command buffers lack of their render commands | every device (runtime piece not built) | 17: `crates/metal2vulkan-runtime/src/compute.rs:1122`, `crates/metal2vulkan-runtime/src/compute.rs:1203` (+15) | `rare`: indirect render commands' remaining pieces | | `IndirectImageblockSize` | An indirect compute command's imageblock side past 65535, which Metal keeps | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:3363` | `none`: an imageblock side past 65535 | | `CommandReplay` | The device replay of indirect command buffers | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/binding.rs:720`, `crates/metal2vulkan-runtime/src/binding.rs:723` | `rare`: the device replay of indirect command buffers | | `RenderAttachments` | Render attachments and their binding forms | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/binding.rs:1871` | `rare`: render attachment forms not built | @@ -225,7 +225,7 @@ Generated at `8639f4209`. | `DetachedTexelAccess` | `Texture::replace_region` or `get_bytes` of a texture whose bytes (a no-copy buffer's or heap's) are detached (`detach_backing`) | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/texture.rs:4922` | `none`: CPU texel access while a runtime extension detached the bytes | | `SurfaceDepthStencil` | A use of a texture of a depth or stencil format (`Depth16Unorm`, `Depth32Float`, `Depth32Float_Stencil8`, `Stencil8`, `X32_Stencil8`) over a plane... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/blit_texture.rs:269`, `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:57` | `rare`: a blit of the stencil of a Depth32Float_Stencil8 texture over a plane of an IOSurface with planes, or a pass on an X32_Stencil8 one's view as Depth32Float_Stencil8 | | `ExtendedRangeResolve` | The multisample resolve (`MultisampleResolve`, `StoreAndMultisampleResolve`) of a color attachment of an extended-range format (`BGRA10_XR`,... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/resolve.rs:604` | `rare`: a multisample resolve of a BGRA10_XR, BGR10_XR or sRGB twin attachment (EDR content drawn multisampled) | -| `PredicationDropsUngatedWork` | An unbalanced command-predication record (`ComputeCommandEncoder::encode_end_if` and the other ends, or `encode_start_else`, with no block open;... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:729` | `none`: an unbalanced Apple-private command-predication record as its unit's first, after dispatches of the unit | +| `PredicationDropsUngatedWork` | An unbalanced command-predication record (`ComputeCommandEncoder::encode_end_if` and the other ends, or `encode_start_else`, with no block open;... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/predication.rs:762` | `none`: an unbalanced Apple-private command-predication record as its unit's first, after dispatches of the unit | | `MultisampledBufferCopy` | A blit copy between a buffer and a multisampled texture (`copyFromBuffer:...toTexture:` into, or `copyFromTexture:...toBuffer:` out of, a texture... | every device (runtime piece not built) | 2: `crates/metal2vulkan-runtime/src/blit_texture.rs:527`, `crates/metal2vulkan-runtime/src/blit_texture.rs:674` | `rare`: a buffer<->multisampled-texture copy on a device without sample-rate shading, an integer multisample attachment at the count, or the copy format's storage; and, where maintenance8's depth/colour copies are missing or wrong, what the sample-rate draws cannot move: a 16-bit depth, or a depth or stencil texture they cannot sample or render to (emulated elsewhere; the consumer's Maps pans and screensaver make the copy) | | `MultisampledBufferLayout` | A blit copy between a buffer and a multisampled texture (as for `MultisampledBufferCopy`) in one of two buffer layouts that plain Metal copies by... | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/sample_interleave.rs:1020` | `rare`: a buffer<->multisampled-texture copy at a bytesPerRow of 0 from an offset that is a multiple of 16, or of pixels of 32 bytes or more at a pitch below a row or off the pixel: Metal copies these by rules not yet reduced, and its API validation rejects them | | `ColorAttachmentGroups` | What a render pass the device draws in color groups does not build | every device (runtime piece not built) | 1: `crates/metal2vulkan-runtime/src/render/color_groups.rs:106` | `app`: in a render pass of more color attachments than the device draws at once (five or more on a device of four), or one at an index past them: a pipeline state of other colors, a tile state, an execution of render commands, a draw reading another group's attachment | @@ -395,7 +395,7 @@ Each refusal's sites, with the function that builds it. - `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs:167 (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs:994 (may_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1102 (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2587 (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3396 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3743 (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs:307 (select)` - `feature::MipmapGeneration`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1818 (mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37 (pick_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:262 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:270 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:275 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:304 (plan_mipmaps)`; `crates/metal2vulkan/src/bind/mipmap_filter.rs:973 (mipmap_filter_module)` - `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs:430 (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:470 (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:689 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:694 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:712 (new)` -- `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2832 (gpu_times)` +- `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2841 (gpu_times)` - `feature::CountingVisibility`: `crates/metal2vulkan-runtime/src/visibility.rs:452 (check_mode)` - `feature::ViewFormatReinterpretation`: `crates/metal2vulkan-runtime/src/view_plan.rs:570 (reinterpretation_refused)` - `feature::SeparateMultisampledDepthStencil`: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:188 (sampled_candidate)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:294 (by_draws)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:336 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:376 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:777 (plan)`; `crates/metal2vulkan-runtime/src/nan_clear.rs:658 (nan_write)`; `crates/metal2vulkan-runtime/src/texture/signed_depth.rs:191 (sample_strip)` @@ -427,7 +427,7 @@ Each refusal's sites, with the function that builds it. - `gap::HeapTextureMemory`: `crates/metal2vulkan-runtime/src/texture/heap.rs:1508 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:1515 (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2057 (host_heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:2289 (memory_shadow)`; `crates/metal2vulkan-runtime/src/texture/heap.rs:552 (memory_refusal)` - `gap::FunctionTablePastMaxBufferLength`: `crates/metal2vulkan-runtime/src/function_table.rs:622 (past_limit)` - `gap::IndirectCommandBufferPastMaxBufferLength`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:522 (new_indirect_command_buffer)` -- `gap::IndirectRenderCommands`: `crates/metal2vulkan-runtime/src/compute.rs:1115 (execute_range)`; `crates/metal2vulkan-runtime/src/compute.rs:1196 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/depth_stencil.rs:85 (gpu_resource_id)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:4356 (render_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:517 (new_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1632 (compile_error)`; `crates/metal2vulkan-runtime/src/render.rs:7140 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:7611 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:8016 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:8484 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/executions.rs:1104 (back_memoryless)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2008 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2051 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2900 (record_forms)`; `crates/metal2vulkan-runtime/src/render/executions.rs:380 (execute_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:439 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:454 (execute_indirect_range)` +- `gap::IndirectRenderCommands`: `crates/metal2vulkan-runtime/src/compute.rs:1122 (execute_range)`; `crates/metal2vulkan-runtime/src/compute.rs:1203 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/depth_stencil.rs:85 (gpu_resource_id)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:4356 (render_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:517 (new_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs:1632 (compile_error)`; `crates/metal2vulkan-runtime/src/render.rs:7140 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:7611 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:8016 (draw_resident)`; `crates/metal2vulkan-runtime/src/render.rs:8484 (draw_resident)`; `crates/metal2vulkan-runtime/src/render/executions.rs:1104 (back_memoryless)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2008 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2051 (record)`; `crates/metal2vulkan-runtime/src/render/executions.rs:2900 (record_forms)`; `crates/metal2vulkan-runtime/src/render/executions.rs:380 (execute_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:439 (execute_indirect_range)`; `crates/metal2vulkan-runtime/src/render/executions.rs:454 (execute_indirect_range)` - `gap::IndirectImageblockSize`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs:3363 (set_imageblock_size)` - `gap::CommandReplay`: `crates/metal2vulkan-runtime/src/binding.rs:720 (bind_into)`; `crates/metal2vulkan-runtime/src/binding.rs:723 (bind_into)` - `gap::RenderAttachments`: `crates/metal2vulkan-runtime/src/binding.rs:1871 (unexpected)` @@ -481,7 +481,7 @@ Each refusal's sites, with the function that builds it. - `gap::DetachedTexelAccess`: `crates/metal2vulkan-runtime/src/texture.rs:4922 (refuse_detached_texels)` - `gap::SurfaceDepthStencil`: `crates/metal2vulkan-runtime/src/blit_texture.rs:269 (unit)`; `crates/metal2vulkan-runtime/src/texture/surface_depth.rs:57 (surface_depth_twin)` - `gap::ExtendedRangeResolve`: `crates/metal2vulkan-runtime/src/resolve.rs:604 (color)` -- `gap::PredicationDropsUngatedWork`: `crates/metal2vulkan-runtime/src/predication.rs:729 (unbalanced)` +- `gap::PredicationDropsUngatedWork`: `crates/metal2vulkan-runtime/src/predication.rs:762 (unbalanced)` - `gap::MultisampledBufferCopy`: `crates/metal2vulkan-runtime/src/blit_texture.rs:527 (copy_from_buffer_to_texture)`; `crates/metal2vulkan-runtime/src/blit_texture.rs:674 (copy_from_texture_to_buffer)` - `gap::MultisampledBufferLayout`: `crates/metal2vulkan-runtime/src/sample_interleave.rs:1020 (plan)` - `gap::ColorAttachmentGroups`: `crates/metal2vulkan-runtime/src/render/color_groups.rs:106 (gap)` diff --git a/docs/RUNTIME-PORTING.md b/docs/RUNTIME-PORTING.md index d0270d462..2c513029c 100644 --- a/docs/RUNTIME-PORTING.md +++ b/docs/RUNTIME-PORTING.md @@ -161,7 +161,7 @@ narrow refusal that the call's rustdoc describes. | `DispatchThreadgroupsIndirect` | `dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:…` | `ComputeCommandEncoder::dispatch_threadgroups_indirect`; at the Metal level `MacOS26_7`, a compute encoder run's first indirect dispatch in an encoder of another dispatch type is refused `Invalid` (`IndirectDispatchOfAnotherType`), where that Metal ends the process | | `DispatchThreads` | `dispatchThreads:threadsPerThreadgroup:` | `ComputeCommandEncoder::dispatch_threads` | | `DispatchThreadsIndirect` | `dispatchThreadsWithIndirectBuffer:indirectBufferOffset:` (SPI) | `ComputeCommandEncoder::dispatch_threads_indirect` (a host step reads the arguments); refused at `MacOS26_7` as `dispatch_threadgroups_indirect` is | -| `EncodeStartDoWhile` | `encodeStartDoWhile` (SPI) | `ComputeCommandEncoder::encode_start_do_while`, as Metal runs it, its body in its unit's later encoders included, nested to any depth, laid down as 64 copies of the loop's commands (16 inside another loop, fewer past 16384 steps and gated dispatches, at least one); a loop past its copies runs nothing more of its unit and fails the command buffer (`PredicatedLoopPastCopies`) where Metal runs on *(partial)* | +| `EncodeStartDoWhile` | `encodeStartDoWhile` (SPI) | `ComputeCommandEncoder::encode_start_do_while`, as Metal runs it, its body in its unit's later encoders included, nested to any depth, laid down as 64 copies of the loop's commands (16 inside another loop, fewer past 16384 steps and gated dispatches, at least one), submitted again from where the loop stopped until it ends; a loop without bound runs until the program lets go of its queue (`PredicatedLoopLetGo`); a loop whose commands hold an indirect dispatch or an indirect command buffer's execution a host step records fails the command buffer past its copies (`PredicatedLoopPastCopies`) where Metal runs on *(partial)* | | `EncodeStartElse` | `encodeStartElse` (SPI) | `ComputeCommandEncoder::encode_start_else`, as Metal runs it; with no block open an unbalanced record, dropping its range of the unit's work as Metal's does; refused where that range holds dispatches from before the unit's first record (`NotImplemented(PredicationDropsUngatedWork)`) *(partial)* | | `EncodeStartIf` | `encodeStartIf:offset:comparison:referenceValue:` (SPI) | `ComputeCommandEncoder::encode_start_if`, as Metal runs it, on a counter the runtime's step kernel moves; a live block open where its unit ends fails the command buffer where its commands skip there, as Metal's GPU recovery does (`PredicationOpenAtUnitEnd`); a word past its buffer reads as Metal reads it (the heap's bytes, or zero; zero announced where Metal reads unrelated memory); refused: a nil buffer with no block open where `encode_start_else` refuses *(partial)* | | `EncodeStartWhile` | `encodeStartWhile:offset:comparison:referenceValue:` (SPI) | `ComputeCommandEncoder::encode_start_while`, as Metal runs it, laid down as `encode_start_do_while`'s loops are; refused as `encode_start_if` refuses *(partial)* |