diff --git a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs index 1066b7b6b..256983401 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs @@ -52,7 +52,12 @@ //! (`State::fail_part`): every other encoder runs, the event signals fire, the scheduled and //! completed handlers run, and the command buffer completes with status `Error` and //! `CommandBufferError::Injected` of the first failure's code (a `commit_failed`'s before any -//! check's). A check that panics fails its submission with code 1 (`Internal`). +//! check's). A check that panics fails its submission with code 1 (`Internal`). The commit of +//! a command buffer with a check encodes again apart the encoders whose commands a shared +//! `VkCommandBuffer` of a group of compute and blit encoders holds where they lie in more than +//! one submission (`encoder_fold.rs`'s **Failed**), so a failed submission's encoders run +//! nothing alone; where it cannot encode them again so, a failed submission whose commands +//! such a `VkCommandBuffer` holds fails every submission whose commands it holds. //! - **Behind a hang** (`hang.rs`). A command buffer committed with an event wait while a hang //! of its queue (a draw of primitive type 9) was in flight is held for this pass too, with or //! without a check: its first batch's pass, once its waits are met and the batches before it @@ -195,20 +200,25 @@ pub(crate) fn submission_start( } impl State { + /// Metal's submissions of its ended encoders ([`metal_submissions`]). + pub(super) fn metal_submissions(&self) -> Vec<(EncoderKind, Range)> { + metal_submissions(self.ended.iter().map(|record| { + ( + record.kind, + record.event_waits_before, + record.event_signals_before, + ) + })) + } + /// Metal's submissions of its ended encoders, for its check, as it commits; nothing without /// a check, or a decision of its first batch's submission behind a hang (`hang.rs`). pub(super) fn plan_checks(&mut self) { if self.check.is_none() && self.behind_hang.is_none() { return; } - let encoders = self.ended.iter().map(|record| { - ( - record.kind, - record.event_waits_before, - record.event_signals_before, - ) - }); - let planned = metal_submissions(encoders) + let planned = self + .metal_submissions() .into_iter() .map(|(kind, encoders)| Planned { kind, @@ -260,7 +270,10 @@ impl State { /// The check of submission `at` (`encoders`) failed it with `code`, before batch `index` /// is submitted: its encoders' parts from that batch on run nothing (`fail_part`), and the - /// command buffer fails with the code unless it failed already. + /// command buffer fails with the code unless it failed already. Where one of them lies in a + /// group of encoders recorded into one `VkCommandBuffer` that holds commands of other + /// submissions too, which the commit could not split (`State::split_failure`), every + /// submission whose commands it holds runs nothing with it (`widened`). fn fail_submission(&mut self, index: usize, at: usize, encoders: &Range, code: u64) { if let Some(planned) = self .checks @@ -269,6 +282,7 @@ impl State { { planned.failed = true; } + let encoders = self.widened(encoders); let from = self.batch_range(index).start; let State { recorded, @@ -287,6 +301,32 @@ impl State { } } + /// `encoders`, Metal's submission a check failed, with every submission whose commands the + /// shared `VkCommandBuffer` of a group one of its encoders' commands lie in holds + /// (`State::in_tail`): that `VkCommandBuffer` runs whole or not at all, and each such + /// submission whole, so no unit of command predication runs in part. + fn widened(&self, encoders: &Range) -> Range { + let mut groups: Vec> = + (self.ended.get(encoders.clone()).into_iter().flatten()) + .filter_map(|record| record.group.clone()) + .collect(); + groups.dedup(); + let tail: Vec = (groups.into_iter()) + .map(|group| self.in_tail(group)) + .filter(|tail| tail.iter().any(|encoder| encoders.contains(encoder))) + .flatten() + .collect(); + if tail.iter().all(|encoder| encoders.contains(encoder)) { + return encoders.clone(); + } + (self.metal_submissions().into_iter()) + .map(|(_, submission)| submission) + .filter(|submission| tail.iter().any(|encoder| submission.contains(encoder))) + .fold(encoders.clone(), |failed, submission| { + failed.start.min(submission.start)..failed.end.max(submission.end) + }) + } + /// Its first batch's submission, batch `index`, found a hang of its queue in flight /// (`hang.rs`): from that batch on every encoder runs nothing, and it completes with no /// error, its event signals firing, as one committed during the hang with no event wait diff --git a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs index 0320b2200..3c36234df 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/first_submission.rs @@ -66,7 +66,6 @@ //! though the command buffer failed already and keeps that first code (move14: the consumer's //! review; Metal runs it over the new pages). -use super::checks::metal_submissions; use super::rebound_use::{ReboundAt, ReboundUse, Recording}; use super::{write_fields, CommandBufferShared, Resident, State}; use crate::error::{internal, CommandBufferError, Error}; @@ -424,14 +423,7 @@ impl State { if verdicts.is_empty() { return Vec::new(); } - let encoders = self.ended.iter().map(|record| { - ( - record.kind, - record.event_waits_before, - record.event_signals_before, - ) - }); - metal_submissions(encoders) + self.metal_submissions() .into_iter() .filter_map(|(_, encoders)| { let mut failure = None; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs index b596d98c4..d4904f437 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -11,6 +11,7 @@ use crate::tracker::Summary; use crate::used_resources::EncoderKind; use crate::work_counts::Counters; use std::collections::BTreeSet; +use std::ops::Range; impl State { /// The group the compute or blit encoder opening now joins, asking `joining`, where its @@ -44,6 +45,7 @@ impl State { let FoldEnd { joining, fold, + in_tail, encoder, summary, log, @@ -58,6 +60,9 @@ impl State { let mut unkept = Vec::new(); if let Some(mut fold) = fold { fold.members.end = encoder + 1; + if let Some(record) = self.ended.get_mut(encoder) { + record.in_tail = in_tail; + } fold.stashed.extend(log.take()); let goes_on = self.tail == Some(fold.tail); if let (Some((joining, summary)), true) = (&leads, goes_on) { @@ -71,6 +76,10 @@ impl State { } match (leads, self.tail) { (Some((joining, summary)), Some(tail)) => { + // The tail is its last `VkCommandBuffer`. + if let Some(record) = self.ended.get_mut(encoder) { + record.in_tail = true; + } let (leader, batches) = (self.recorded.len() - 1, self.batches.all().len()); let stashed = log.into_iter().collect(); self.fold = Some(Box::new(Fold::begun( @@ -150,11 +159,17 @@ impl State { /// split, each encoder of it that runs to be encoded again from its log, kept now, into /// `VkCommandBuffer`s of its own before the first submission (`reencode.rs`), and the group's /// shared one never submitted; where one of them cannot be encoded again - /// ([`encodes_again_apart`](Self::encodes_again_apart), or its log is gone), the failure fails - /// that whole group instead (a failure that fails those encoders alone, with no error, where - /// the commit has none). With the failure, the encoders that run of each group split, the - /// units to encode again. The logs held for the commit that no split takes stay held, for the - /// command buffer's release to give back to the device's spares + /// ([`encodes_again`](Self::encodes_again)), the failure fails that whole group instead (a + /// failure that fails those encoders alone, with no error, where the commit has none). A + /// command buffer with a submission check (`checks.rs`) splits so each group whose shared + /// `VkCommandBuffer` holds commands of more than one of Metal's submissions + /// ([`in_tail`](Self::in_tail)), those commands' encoders encoded again apart, so a check + /// fails one submission's encoders alone; one of them that cannot be encoded again exactly + /// (no log, or work of a segment's, whose encoding again records it otherwise) leaves the group + /// whole, and a check that fails one of those submissions fails each of them + /// (`State::fail_submission`). With the failure, the encoders that run of each group split, + /// the units to encode again. The logs held for the commit that no split takes stay held, + /// for the command buffer's release to give back to the device's spares /// ([`unsplit_logs`](Self::unsplit_logs)). pub(super) fn split_failure( &mut self, @@ -162,13 +177,21 @@ impl State { ) -> (Option, Vec>) { let mut units = Vec::new(); let left_out = self.left_out_from; - if failure.is_none() && left_out.is_none() { + let checked = self.check.is_some(); + if failure.is_none() && left_out.is_none() && !checked { return (failure, units); } let groups: BTreeSet<(usize, usize)> = (self.ended.iter()) .filter_map(|record| record.group.as_ref()) .map(|group| (group.start, group.end)) .collect(); + // Each ended encoder's submission among Metal's, where a check is set. + let mut submission = Vec::new(); + if checked && !groups.is_empty() { + for (at, (_, encoders)) in self.metal_submissions().into_iter().enumerate() { + submission.extend(encoders.map(|_| at)); + } + } let mut whole = BTreeSet::new(); for (start, end) in groups { let runs = |encoder: &usize| { @@ -176,39 +199,31 @@ impl State { && left_out.is_none_or(|first| *encoder < first) }; let running: Vec = (start..end).filter(runs).collect(); - if running.is_empty() || running.len() == end - start { + if running.is_empty() { continue; } - let logged = running.iter().all(|&encoder| { - self.encodes_again_apart(encoder) - && (self.ended[encoder].replay.is_some() - || self.held_logs.iter().any(|held| held.encoder == encoder)) - }); - if !logged { - whole.extend(running); - continue; - } - for &encoder in &running { - let Some(at) = (self.held_logs.iter()).position(|held| held.encoder == encoder) - else { - continue; - }; - let Stashed { - log, executions, .. - } = self.held_logs.swap_remove(at); - if let Some(log) = self.keep_replay(encoder, Some(log), executions.clone()) { - self.held_logs.push(Stashed { - encoder, - log, - executions, - }); + if running.len() < end - start { + match running.iter().all(|&encoder| self.encodes_again(encoder)) { + true => units.push(self.split_apart(start..end, running)), + false => whole.extend(running), } + continue; } - // Encoded again apart, its encoders share no `VkCommandBuffer` any more. - for record in &mut self.ended[start..end] { - record.group = None; + // Nothing fails it: where a check may fail one of the submissions whose commands its + // shared `VkCommandBuffer` holds and not another, those commands' encoders are + // encoded again apart, where each is so exactly, its work no segment's. + let tail = self.in_tail(start..end); + let first = tail.first().and_then(|&encoder| submission.get(encoder)); + let last = tail.last().and_then(|&encoder| submission.get(encoder)); + let exact = |encoder: &usize| { + self.encodes_again(*encoder) + && (self.recorded.iter()) + .filter(|part| part.encoder == *encoder) + .all(|part| part.segments.is_empty()) + }; + if checked && first != last && tail.iter().all(exact) { + units.push(self.split_apart(start..end, tail)); } - units.push(running); } if whole.is_empty() { return (failure, units); @@ -228,6 +243,55 @@ impl State { (Some(failure), units) } + /// `encoders` of `group`, a group recorded into one `VkCommandBuffer`, to be encoded again + /// apart, their logs kept: the group's encoders share no `VkCommandBuffer` any more, the + /// others' commands lying in `VkCommandBuffer`s of their own. The unit to encode again. + fn split_apart(&mut self, group: Range, encoders: Vec) -> Vec { + self.keep_held_logs(&encoders); + for record in &mut self.ended[group] { + record.group = None; + } + encoders + } + + /// The encoders of `group`, a group recorded into one `VkCommandBuffer`, whose commands lie + /// there, some or all (`EncoderRecord::in_tail`): its first, and each later one a command of + /// which recorded there. + pub(super) fn in_tail(&self, group: Range) -> Vec { + group + .filter(|&encoder| self.ended.get(encoder).is_some_and(|record| record.in_tail)) + .collect() + } + + /// Whether ended encoder `encoder`, of a group recorded into one `VkCommandBuffer`, may be + /// encoded again apart: it does as its command buffer's command predication holds it + /// ([`encodes_again_apart`](Self::encodes_again_apart)), and its log is kept, or held for the + /// commit. + pub(super) fn encodes_again(&self, encoder: usize) -> bool { + self.encodes_again_apart(encoder) + && (self.ended[encoder].replay.is_some() + || self.held_logs.iter().any(|held| held.encoder == encoder)) + } + + /// Keep the logs held for the commit of `encoders`, each its own, for an encoding again. + pub(super) fn keep_held_logs(&mut self, encoders: &[usize]) { + for &encoder in encoders { + let Some(at) = (self.held_logs.iter()).position(|held| held.encoder == encoder) else { + continue; + }; + let Stashed { + log, executions, .. + } = self.held_logs.swap_remove(at); + if let Some(log) = self.keep_replay(encoder, Some(log), executions.clone()) { + self.held_logs.push(Stashed { + encoder, + log, + executions, + }); + } + } + } + /// Whether ended encoder `encoder`, of a group recorded into one `VkCommandBuffer`, encodes /// again apart as the command buffer's command predication holds it: every one where it used /// none; a compute encoder whose unit nothing reached into or out of (`Predication::alone`); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 10fe086c8..4a1340a71 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -1217,6 +1217,7 @@ impl State { unlogged: None, refused: None, group: None, + in_tail: false, }); self.ended.len() - 1 } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 8da7d906f..6320baff7 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -62,6 +62,11 @@ //! `VkCommandBuffer` (`encoder_fold.rs`) are encoded again together: a rebind that moves one //! encodes each again, into `VkCommandBuffer`s of its own, and puts them in their places //! together, or puts none where one of them kept no log, is refused or does not fit its place. +//! A group one of whose encoders kept no log, or cannot be encoded again apart in its command +//! buffer's command predication, is split where each such encoder lies in one of Metal's +//! submissions that holds one of them the rebind moved, which runs nothing anyway +//! (`State::split_rebound`): the group's other encoders are encoded again apart, as a split at +//! the commit's are (below). //! - **Split at the commit.** A commit whose failure fails some of a group's encoders and not the //! others, or after a command-predication record left out the work of some of them //! (`encoder_fold.rs`'s **Failed**), marks the command buffer as a rebind does, and its @@ -92,6 +97,7 @@ use crate::texture::faces::with_faces_as_of; use crate::used_resources::EncoderKind; use crate::work_counts::Counters; use std::collections::BTreeSet; +use std::ops::Range; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -157,6 +163,13 @@ impl CommandBufferShared { } } let submitting = device.shared().rebinds.submitting(); + // Its open encoders, logged or not, a command of which named a buffer that + // lies elsewhere now. + let rebound: BTreeSet = (state.ended.iter().enumerate()) + .filter(|(at, _)| open.contains(at) && !splitting.contains(at)) + .filter(|(_, record)| submitting.rebound(&record.taken)) + .map(|(at, _)| at) + .collect(); let moved: Vec<(usize, Arc)> = (state.ended.iter().enumerate()) .filter(|(at, _)| open.contains(at) && !splitting.contains(at)) .filter_map(|(at, record)| { @@ -167,12 +180,12 @@ impl CommandBufferShared { } return None; }; - let moved = submitting.rebound(&record.taken) || reset; + let moved = rebound.contains(&at) || reset; moved.then(|| (at, Arc::clone(replay))) }) .collect(); - let together = state.encoded_together(moved, &device.shared().counts); - units.extend(together.into_iter().map(|unit| (false, unit))); + let counts = &device.shared().counts; + units.extend(state.encoded_together(moved, &rebound, counts)); units } } @@ -493,22 +506,25 @@ impl State { } /// The units the rebind's turn encodes again of `moved`, the ended encoders it moved, with - /// their logs, in order: each encoder alone, but an encoder of a group of compute and blit - /// encoders recorded into one `VkCommandBuffer` with every encoder of its group - /// (`encoder_fold.rs`), whose shared recording none may leave alone. A group one of whose - /// encoders kept no log, or cannot be encoded again apart in its command buffer's command - /// predication (`State::encodes_again_apart`), is encoded again by none: its moved encoders - /// keep their first recording, the refusal noted and counted. + /// their logs, in order, each with whether it splits a group: each encoder alone, but an + /// encoder of a group of compute and blit encoders recorded into one `VkCommandBuffer` with + /// every encoder of its group (`encoder_fold.rs`), whose shared recording none may leave + /// alone. A group one of whose encoders kept no log, or cannot be encoded again apart in its + /// command buffer's command predication (`State::encodes_again_apart`), is split where each + /// such encoder lies in one of Metal's submissions that runs nothing anyway + /// ([`split_rebound`](Self::split_rebound)); else it is encoded again by none: its moved + /// encoders keep their first recording, the refusal noted and counted. pub(super) fn encoded_together( &mut self, moved: Vec<(usize, Arc)>, + rebound: &BTreeSet, counts: &Counters, - ) -> Vec)>> { + ) -> Vec<(bool, Vec<(usize, Arc)>)> { let mut units = Vec::new(); let mut reached = 0; for (at, replay) in moved { let Some(group) = self.ended[at].group.clone() else { - units.push(vec![(at, replay)]); + units.push((false, vec![(at, replay)])); continue; }; if group.start < reached { @@ -522,21 +538,63 @@ impl State { }) .collect(); let apart = (group.clone()).all(|member| self.encodes_again_apart(member)); - match logs.filter(|_| apart) { - Some(unit) => units.push(unit), - None => { - for record in &mut self.ended[group] { - if record.replay.is_some() { - counts.reencode_refused(); - } - record.refused.get_or_insert_with(|| TOGETHER.to_owned()); - } + if let Some(unit) = logs.filter(|_| apart) { + units.push((false, unit)); + continue; + } + if let Some(unit) = self.split_rebound(group.clone(), rebound) { + units.push((true, unit)); + continue; + } + for record in &mut self.ended[group] { + if record.replay.is_some() { + counts.reencode_refused(); } + record.refused.get_or_insert_with(|| TOGETHER.to_owned()); } } units } + /// `group`, a group of compute and blit encoders recorded into one `VkCommandBuffer` some of + /// whose encoders cannot be encoded again ([`State::encodes_again`]), split by a rebind: where + /// each of those lies in one of Metal's submissions (`checks::metal_submissions`) that holds + /// one of them that named a buffer the rebinds moved (`rebound`), which the first submission + /// finds rebound and runs nothing of (`first_submission.rs`), the group's encoders outside + /// those submissions, with their logs, kept now, to encode again apart; their submissions + /// run, as Metal's do, and the shared `VkCommandBuffer` is never submitted. `None` where one + /// of those encoders runs, or none of the group does. + fn split_rebound( + &mut self, + group: Range, + rebound: &BTreeSet, + ) -> Option)>> { + let stuck: Vec = (group.clone()) + .filter(|&member| !self.encodes_again(member)) + .collect(); + let failing: Vec> = (self.metal_submissions().into_iter()) + .map(|(_, encoders)| encoders) + .filter(|encoders| { + (stuck.iter()).any(|member| encoders.contains(member) && rebound.contains(member)) + }) + .collect(); + let fails = |member: &usize| failing.iter().any(|encoders| encoders.contains(member)); + let running: Vec = group.clone().filter(|member| !fails(member)).collect(); + if running.is_empty() || !stuck.iter().all(fails) { + return None; + } + self.keep_held_logs(&running); + let unit = (running.iter()) + .map(|&member| Some((member, Arc::clone(self.ended[member].replay.as_ref()?)))) + .collect::>>()?; + // Encoded again apart, or running nothing, its encoders share no `VkCommandBuffer` any + // more. + for record in &mut self.ended[group] { + record.group = None; + } + Some(unit) + } + /// The parts of ended encoder `at`, in order. fn parts_of(&self, at: usize) -> Vec { (self.recorded.iter().enumerate()) diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index dcdabf00b..ae5b50614 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -417,6 +417,9 @@ pub(super) struct EncoderCore { /// The group it joined, recording on into its tail, which its group's first part holds /// (`encoder_fold.rs`); `None` where it began a `VkCommandBuffer` of its own. fold: Option>, + /// Whether a command of the encoder's recorded into the tail of the group it joined: its + /// work runs or not with that `VkCommandBuffer` (`encoder_fold.rs`'s **Failed**). + in_tail: bool, /// What the program's memory barriers in the encoder owe its later commands /// ([`memory_barrier`](Self::memory_barrier)). owed: Owed, @@ -752,6 +755,7 @@ impl EncoderCore { barriered, joining, fold, + in_tail: false, owed: Owed::default(), ended: Vec::new(), piece_ends: Vec::new(), @@ -920,6 +924,7 @@ impl EncoderCore { barriered: None, joining: None, fold: None, + in_tail: false, owed: Owed::default(), ended: Vec::new(), piece_ends: Vec::new(), @@ -1372,6 +1377,9 @@ impl EncoderCore { } } self.recorded = true; + if (self.fold.as_ref()).is_some_and(|fold| fold.tail == self.raw) { + self.in_tail = true; + } Some(self.raw) } @@ -3226,6 +3234,7 @@ impl EncoderCore { barriered, joining, fold, + in_tail, mut ended, mut segments, left_out, @@ -3438,6 +3447,7 @@ impl EncoderCore { let end = FoldEnd { joining: joining.filter(|_| !shared.encoder_trail), fold, + in_tail, encoder, summary: fold_summary, log: held_log.map(|log| (log, executed)), diff --git a/crates/metal2vulkan-runtime/src/encoder_fold.rs b/crates/metal2vulkan-runtime/src/encoder_fold.rs index 2262a9c74..fea5c9323 100644 --- a/crates/metal2vulkan-runtime/src/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/encoder_fold.rs @@ -49,7 +49,11 @@ //! - **Encoded again** (`command_buffer/reencode.rs`). A rebind that moves a buffer one encoder of //! a group named encodes every encoder of the group again, each into `VkCommandBuffer`s of its //! own, or none: the shared one is never submitted. A group with a member that cannot be encoded -//! again is not encoded again, and its moved members are refused. +//! again is split where each such member lies in one of Metal's submissions +//! (`checks::metal_submissions`: a blit encoder's and a compute encoder's are two) that holds +//! one of them the rebind moved, which the first submission finds rebound and runs nothing of: +//! the group's encoders outside those submissions are encoded again apart and run, as Metal +//! runs them. Else it is not encoded again, and its moved members are refused. //! - **Failed.** A failure of the command buffer that fails some of a group's encoders and not //! the others (`CommandBuffer::commit_failed`'s first failed encoder or set inside a group, a //! recording failure or a fault at a folded encoder), and a command-predication record that @@ -62,7 +66,13 @@ //! encoder whose unit of command predication laid a loop or left work out, so a command of its //! encoded again would run outside its block: `Predication::alone`; a blit encoder belongs to no //! unit; or a call answers otherwise when encoded again), the failure fails the whole group -//! (docs/API.md, "A command buffer committed as failed"). +//! (docs/API.md, "A command buffer committed as failed"). A command buffer with a submission +//! check (`command_buffer/checks.rs`), which fails one of Metal's submissions as it is +//! submitted, splits so at the commit each group whose shared `VkCommandBuffer` holds commands +//! of more than one of them, those commands' encoders encoded again apart, so a check fails its +//! own submission's encoders alone (an encoder that went on in `VkCommandBuffer`s of its own +//! before any command of its recorded there is failed by its own parts); one that cannot be +//! split so stays whole, and a check that fails one of those submissions fails each of them. //! - **Logs.** A group's members' logs are held from the group's close for the commit, which //! keeps them for every member where one member keeps its own for a rebind, and keeps those of //! a group its failure splits; the rest stay held until the command buffer's release, which @@ -381,6 +391,8 @@ pub(crate) struct FoldEnd { pub(crate) joining: Option, /// The group it joined, where it joined one. pub(crate) fold: Option>, + /// Whether a command of its recorded into that group's tail. + pub(crate) in_tail: bool, /// Its place among its command buffer's ended encoders. pub(crate) encoder: usize, /// What its one part used, where that part leaves nothing that needs a `VkCommandBuffer` diff --git a/crates/metal2vulkan-runtime/src/used_resources.rs b/crates/metal2vulkan-runtime/src/used_resources.rs index 45c21339f..42b87e989 100644 --- a/crates/metal2vulkan-runtime/src/used_resources.rs +++ b/crates/metal2vulkan-runtime/src/used_resources.rs @@ -139,6 +139,10 @@ pub(super) struct EncoderRecord { /// own, where it is one of more (`encoder_fold.rs`): a failure fails them together, and a /// rebind encodes them again together. pub(super) group: Option>, + /// Whether its commands lie in that `VkCommandBuffer`, some or all: the group's first + /// encoder's do, and a later one's where a command of its recorded there before it went on + /// in `VkCommandBuffer`s of its own, or ended. + pub(super) in_tail: bool, } /// What owns the memory under a key, held without keeping it. diff --git a/crates/metal2vulkan-validation/src/runtime_lane/submission_checks.rs b/crates/metal2vulkan-validation/src/runtime_lane/submission_checks.rs index 7815c0639..0d9ebddb3 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/submission_checks.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/submission_checks.rs @@ -12,6 +12,11 @@ //! sees each of Metal's submissions once. //! - **Attached again behind a wait.** The same shapes committed while detached, attached again //! before the signal: everything runs, and the command buffer completes. +//! - **A shared recording the commit cannot split.** A blit encoder and a compute encoder +//! recorded into one `VkCommandBuffer`, the compute encoder's dispatch there and its execution +//! of an indirect command buffer in a segment of its own, which an encoding again records +//! otherwise: a check that fails the blit's submission fails the compute encoder's too, so +//! nothing of either runs. //! - **Reached through an indirect command alone.** A buffer an indirect command binds, which //! no encoder makes resident, is the submission's from the commit on; detached behind a wait, //! that submission fails. @@ -32,8 +37,8 @@ use super::degrade_notices::on_device; use super::degrade_notices::on_device_with; use super::failed_commits::{Shape, HELD, KERNEL, SHAPES}; use super::{ - at_plan, bound_buffers, buffer_with, compute_descriptor, pipeline_state, public_case, - read_buffer, CaseResources, PublicCase, WAIT, + at_plan, bound_buffers, buffer_with, compute_descriptor, encode_case, pipeline_state, + public_case, read_buffer, CaseResources, PublicCase, WAIT, }; use crate::air_library::AirLibrary; use crate::candidate::engine::ComputeOutput; @@ -43,10 +48,11 @@ use metal2vulkan::metal::IndirectCommandType; use metal2vulkan::pipeline::LinkedFunctions; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, ComputePipelineState, Device, - EncoderKind, Event, EventRef, IndirectCommandBufferDescriptor, ObjectId, PipelineOptions, - ResourceOptions, SharedEvent, Size, Submission, SubmissionCheck, VkEventSignal, + EncoderKind, Event, EventRef, IndirectCommandBuffer, IndirectCommandBufferDescriptor, ObjectId, + PipelineOptions, ResourceOptions, SharedEvent, Size, Submission, SubmissionCheck, + VkEventSignal, }; -use std::collections::{BTreeSet, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::num::NonZeroU64; use std::ops::Range; use std::sync::atomic::{AtomicBool, Ordering}; @@ -250,6 +256,138 @@ fn icb_state(device: &Device, kernel: &PublicCase) -> ComputePipelineState { .unwrap() } +/// An indirect command buffer of one command, [`KERNEL`]'s dispatch by `pipeline` (an +/// [`icb_state`]) over `buffers`. +fn icb_of( + device: &Device, + kernel: &PublicCase, + pipeline: &ComputePipelineState, + buffers: &BTreeMap, +) -> IndirectCommandBuffer { + let compute = &kernel.compute; + let size = |[x, y, z]: [u32; 3]| Size::new(x.into(), y.into(), z.into()); + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH + .union(IndirectCommandType::CONCURRENT_DISPATCH_THREADS); + descriptor.max_kernel_buffer_bind_count = 31; + let icb = device + .new_indirect_command_buffer(&descriptor, 1, ResourceOptions::shared()) + .unwrap(); + let command = icb.indirect_compute_command_at(0).unwrap(); + command.set_compute_pipeline_state(pipeline).unwrap(); + for (&slot, buffer) in buffers { + command.set_kernel_buffer(Some(buffer), 0, slot).unwrap(); + } + for (&slot, &threadgroup) in &compute.threadgroup_lengths { + command + .set_threadgroup_memory_length(threadgroup, slot) + .unwrap(); + } + match compute.dispatch { + Dispatch::Threads { + threads, + threads_per_group, + } => command.concurrent_dispatch_threads(size(threads), size(threads_per_group)), + Dispatch::Threadgroups { + groups, + threads_per_group, + } => command.concurrent_dispatch_threadgroups(size(groups), size(threads_per_group)), + other => panic!("{other:?} is no dispatch of a command"), + } + .unwrap(); + icb +} + +/// A blit encoder's fill, then a compute encoder that dispatches [`KERNEL`], its pipeline made +/// first so the dispatch records at once, and executes an indirect command buffer's dispatch of +/// it into an output of its own, which a segment records. The dispatch records into the blit's +/// `VkCommandBuffer` (`encoder_fold.rs`), and the execution's segment is no work the commit +/// encodes again exactly (`State::split_failure`): a check that fails the blit's submission fails +/// the compute encoder's with it, where Metal runs that one (docs/FAST-PATHS.md, the known gap), +/// so none of the three lands. Failing the blit's alone would leave out the dispatch with the +/// shared recording and run the execution: a compute encoder run in part. +#[test] +fn a_check_failing_one_submission_a_shared_recording_holds_fails_each_it_holds() { + let kernel = public_case(KERNEL).unwrap(); + on_device_with(at_plan, |device, _| { + let pipeline = pipeline_state(device, &kernel).unwrap(); + let indirect = icb_state(device, &kernel); + let ComputeOutput::Buffer { + binding, + offset, + length, + } = kernel.compute.output + else { + panic!("{KERNEL}: the case's output is no buffer"); + }; + let queue = device.new_command_queue().unwrap(); + let case = || { + let resources = CaseResources::new(device, &kernel).unwrap(); + let bound = bound_buffers(device, &kernel.compute, &resources).unwrap(); + (resources, bound) + }; + // The dispatch's pipeline made, by a command buffer of its own run to its end. + let (warm, warm_bound) = case(); + let command_buffer = queue.command_buffer().unwrap(); + let mut compute = command_buffer.compute_command_encoder().unwrap(); + encode_case(&mut compute, &pipeline, &kernel.compute, &warm_bound, &warm).unwrap(); + compute.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let (direct, direct_bound) = case(); + let (_executed, executed_bound) = case(); + let initial = read_buffer(&direct_bound[&binding], offset, length).unwrap(); + assert_ne!(initial, kernel.metal_output, "{KERNEL}: no output to see"); + let icb = icb_of(device, &kernel, &indirect, &executed_bound); + let words = buffer_with(device, &[0; 4]).unwrap(); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&words, 0..4, 0x11).unwrap(); + blit.end_encoding().unwrap(); + let mut compute = command_buffer.compute_command_encoder().unwrap(); + encode_case( + &mut compute, + &pipeline, + &kernel.compute, + &direct_bound, + &direct, + ) + .unwrap(); + compute.execute_commands_in_buffer(&icb, 0..1).unwrap(); + compute.end_encoding().unwrap(); + let check: SubmissionCheck = Arc::new(|submission: &Submission<'_>| { + (submission.kind() == EncoderKind::Blit).then(|| NonZeroU64::new(DETACHED).unwrap()) + }); + command_buffer.set_submission_check(check).unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + let counts = device.work_counts(); + assert_eq!( + counts.encoders_folded - before.encoders_folded, + 1, + "the compute encoder recorded into the blit's VkCommandBuffer" + ); + assert_eq!( + counts.encoders_reencoded, before.encoders_reencoded, + "the commit encoded nothing again" + ); + assert_eq!(command_buffer.status(), CommandBufferStatus::Error); + assert_eq!( + command_buffer.error(), + Some(CommandBufferError::Injected(DETACHED)) + ); + assert_eq!( + read_buffer(&words, 0, 4).unwrap(), + [0; 4], + "the blit's fill" + ); + let ran = |bound: &BTreeMap| read_buffer(&bound[&binding], offset, length); + assert_eq!(ran(&direct_bound).unwrap(), initial, "the dispatch"); + assert_eq!(ran(&executed_bound).unwrap(), initial, "the execution"); + }); +} + /// A buffer an indirect command binds as [`KERNEL`]'s output, which no encoder makes resident, /// is the submission's from the commit on (`ended_encoders` lists it then, not before). Between /// two blits, behind a wait: detached before the signal, that submission fails alone and the @@ -268,44 +406,13 @@ fn a_buffer_reached_only_through_an_indirect_command_fails_its_submission() { else { panic!("{KERNEL}: the case's output is no buffer"); }; - let size = |[x, y, z]: [u32; 3]| Size::new(x.into(), y.into(), z.into()); for detached in [true, false] { let resources = CaseResources::new(device, &kernel).unwrap(); let buffers = bound_buffers(device, compute, &resources).unwrap(); let output = buffers[&binding].clone(); let initial = read_buffer(&output, offset, length).unwrap(); assert_ne!(initial, kernel.metal_output, "{KERNEL}: no output to see"); - let mut descriptor = IndirectCommandBufferDescriptor::new(); - descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH - .union(IndirectCommandType::CONCURRENT_DISPATCH_THREADS); - descriptor.max_kernel_buffer_bind_count = 31; - let icb = device - .new_indirect_command_buffer(&descriptor, 1, ResourceOptions::shared()) - .unwrap(); - let command = icb.indirect_compute_command_at(0).unwrap(); - command.set_compute_pipeline_state(&pipeline).unwrap(); - for (&slot, buffer) in &buffers { - command.set_kernel_buffer(Some(buffer), 0, slot).unwrap(); - } - for (&slot, &threadgroup) in &compute.threadgroup_lengths { - command - .set_threadgroup_memory_length(threadgroup, slot) - .unwrap(); - } - match compute.dispatch { - Dispatch::Threads { - threads, - threads_per_group, - } => command.concurrent_dispatch_threads(size(threads), size(threads_per_group)), - Dispatch::Threadgroups { - groups, - threads_per_group, - } => { - command.concurrent_dispatch_threadgroups(size(groups), size(threads_per_group)) - } - other => panic!("{other:?} is no dispatch of a command"), - } - .unwrap(); + let icb = icb_of(device, &kernel, &pipeline, &buffers); let queue = device.new_command_queue().unwrap(); let gate = device.new_shared_event().unwrap(); diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c4117b278..1701a3dcb 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2296; +pub const RUNTIME_VERSION: u32 = 2297; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index 136645083..fbf34b3e0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5450,7 +5450,11 @@ each item named states the rule in full. leave work out (an unbalanced record), it cannot be recorded again outside its blocks, and such a failure fails the whole group instead, where Metal runs the group's encoders before `n` and those the set leaves out. So does a group one of whose calls answers otherwise when recorded - again. + again. A command buffer with a submission check (`CommandBuffer::set_submission_check`) has + the encoders whose commands such a group's shared `VkCommandBuffer` holds recorded again apart + at the commit where they lie in more than one of Metal's submissions, so a check fails its own + submission's encoders alone; where they cannot be recorded again so, a check that fails one of + those submissions fails each of them, where Metal runs the others. **GPU hangs and faults** (a draw of private primitive type 9, `DrawPrimitiveType::Nine`) diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index facbc1a22..54ad6a3fb 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -1236,7 +1236,17 @@ driver's. Each is open work. encoders of one dispatch type it lies in, `predication.rs`) called `encode_start_while` or `encode_start_do_while`, or left a record unbalanced, that encoder cannot be recorded again outside the unit's blocks, so the group runs nothing, where Metal runs its encoders the failure - does not name. A blit encoder belongs to no unit and is always recorded again. + does not name. A blit encoder belongs to no unit and is always recorded again. So does a + submission check (`CommandBuffer::set_submission_check`) that fails one of Metal's submissions + of such a group (a blit encoder's and a compute encoder's are two): the commit of a command + buffer with a check records the encoders whose commands the group's shared `VkCommandBuffer` + holds again apart where they lie in more than one submission, and where it cannot (one keeps no + log, or its work runs in a segment), a check that fails one of those submissions fails each of + them, where Metal runs the others. A rebind that moves a buffer such a group named, + where its encoder that cannot be recorded again lies in a submission that still runs, records + none of the group again, and its moved encoders fail `EncodedUseRebound` where Metal runs them + over the new pages; where every such encoder's submission fails rebound anyway, the group's + other encoders are recorded again apart and run. - **A copied rebind under a texture in place, where the device's check did not pass fresh pages and its own linear image lies at another pitch, is refused** (`NotImplemented(RebindTextures)`). A rebind whose pages the gate refuses, or whose bytes moved in their page, copies them, and the