diff --git a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs index 8b55bc21a..4228c4e5a 100644 --- a/crates/metal2vulkan-validation/src/candidate/runtime_case.rs +++ b/crates/metal2vulkan-validation/src/candidate/runtime_case.rs @@ -200,7 +200,9 @@ pub(crate) fn report_each_message() { /// What the validation layer reported that fails a run: every error, and every warning of the /// validation type (the rule the executor's own context applies); and, apart, the runtime's /// degrade notices (`DebugMessage::degradation`), which fail nothing. Bounded so a flood cannot -/// grow without limit. +/// grow without limit. While a test holds the layer's hazard reports +/// ([`Messages::hold_hazards`]), each distinct one is kept once and its repeats counted, for the +/// test's claim to judge. /// /// Four layer gaps pass, on the layer releases whose source was read with their cause in place: /// the layer's synchronization validation forgetting a semaphore chain once the host waited on a @@ -253,6 +255,9 @@ struct Reported { /// put back (`Messages::restore_notices`): a device announces a kind once, so a later making /// or use of it announces nothing again. taken: BTreeMap, + /// The layer's hazard reports held apart from `failing` while a test holds them + /// (`Messages::hold_hazards`): each distinct report once, with the times it came. + held: Option>, } impl Default for Reported { @@ -266,6 +271,7 @@ impl Default for Reported { unsupported_sets: false, unsupported_set_messages: 0, taken: BTreeMap::new(), + held: None, layers: layer_claim::LayerFacts::default(), test: std::thread::current() .name() @@ -306,6 +312,10 @@ impl Drop for Reported { /// a run ([`Messages::sink`]). pub const QUEUE_LIMITS_REACHED: &str = "metal2vulkan-queue-limits-reached"; +/// The start of every id name the validation layer's synchronization validation reports a hazard +/// by (`SYNC-HAZARD-WRITE-AFTER-WRITE`, ...). +pub const HAZARD: &str = "SYNC-HAZARD-"; + /// The `specVersion` of the validation layer the runtime's loader offers, read once. static LAYER_VERSION: OnceLock> = OnceLock::new(); @@ -356,12 +366,15 @@ impl Messages { /// The failing messages reported so far, removed, with the loader's own messages about a /// layer it could not provide that no device of this list explained, and without its reports - /// of driver manifests it ignored, each printed (`layer_claim`). + /// of driver manifests it ignored, each printed (`layer_claim`). Hazard reports still held + /// ([`Messages::hold_hazards`]) are among them, each once, and holding ends. pub fn take(&self) -> Vec { let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); let mut unexplained = reported.layers.release(); let mut failing = reported.failing.split_off(0); unexplained.append(&mut failing); + let held = reported.held.take().unwrap_or_default(); + unexplained.extend(held.into_iter().map(|(message, _)| message)); let ignored = layer_claim::IgnoredDrivers::of_messages(&unexplained); unexplained.retain(|message| { let host = ignored.explains(&message.id_name, &message.text); @@ -378,6 +391,34 @@ impl Messages { unexplained } + /// Hold the layer's synchronization hazard reports (id names [`HAZARD`]`*`) apart from the + /// failing messages from here on, until [`Messages::take_held_hazards`] or + /// [`Messages::take`]: each distinct report (its id name and text) once, a repeat only + /// counted, so a claim that judges a report by those alone reads every report the layer + /// made, however often it repeats one (`runtime_lane::apart_writes`). Past `Messages::MAX` + /// distinct reports, a new one is a failing message as before. + pub fn hold_hazards(&self) { + let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); + reported.held.get_or_insert_with(Vec::new); + } + + /// The hazard reports held since [`Messages::hold_hazards`], each with the times it came, + /// removed; holding ends. + pub fn take_held_hazards(&self) -> Vec<(DebugMessage, usize)> { + let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); + reported.held.take().unwrap_or_default() + } + + /// Whether a device reporting here announced `kind`: a notice of it taken + /// ([`Messages::taken_kinds`]) or still to be taken. + pub fn announced(&self, kind: Degradation) -> bool { + let reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); + reported.taken.contains_key(&kind) + || (reported.notices.iter()) + .filter_map(|message| message.degradation.as_ref()) + .any(|notice| notice.degradation == kind) + } + /// The degrade notices delivered so far, removed. pub fn take_notices(&self) -> Vec { let mut reported = self.0.lock().unwrap_or_else(|p| p.into_inner()); @@ -672,6 +713,22 @@ impl Messages { message.text.replace('\n', " ") ); } + // A hazard report while a test holds them (`Messages::hold_hazards`): a repeat of + // one held is counted, a new one held, while there is room. + let hold = message.id_name.starts_with(HAZARD) + && match reported.held.as_mut() { + None => false, + Some(held) => { + let repeat = (held.iter_mut()).find(|(kept, _)| { + kept.id_name == message.id_name && kept.text == message.text + }); + if let Some((_, times)) = repeat { + *times += 1; + return; + } + held.len() < Self::MAX + } + }; if ECHO.load(Ordering::Relaxed) { use std::io::Write as _; let _ = writeln!( @@ -690,8 +747,13 @@ impl Messages { message.text.replace('\n', " ") ); } - if reported.failing.len() < Self::MAX { - reported.failing.push(message); + match reported.held.as_mut() { + Some(held) if hold => held.push((message, 1)), + _ => { + if reported.failing.len() < Self::MAX { + reported.failing.push(message); + } + } } }) } diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index f82c73483..f3f23d9a2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -867,6 +867,8 @@ mod srgb_storage; mod stage_in_regions; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod stage_in_strides; +#[cfg(test)] +mod stage_races; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod staging_batches; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -1397,8 +1399,10 @@ fn dynamic_input_assembly(device: &Device) -> bool { /// at submission by default: `syncval_submit_time_validation` (default on) through 1.4.357, /// which 1.4.363 deprecates for `syncval_full_validation` (default on) and reports, when asked /// for, as a settings warning, while an older layer reports the newer setting as unrecognized; -/// so the lane asks for neither and takes the default every release has. With the shaders' -/// accesses through descriptors +/// so the lane asks for neither and takes the default every release has. Every report is made +/// (`enable_message_limit` off, as the executor's devices have it: by default the layer reports +/// each message ID ten times per instance, so a hazard past a test's tenth of its kind would +/// go unread). With the shaders' accesses through descriptors /// (`syncval_shader_accesses_heuristic`: the layer's default, off, sees no shader access at /// all, only transfers, attachments and fixed-function reads). Even so, the layer sees no /// access through a descriptor array of more than one element (the runtime's set 1, the heap @@ -1493,16 +1497,20 @@ impl LaneChecks { /// The validation layer's settings the checks take. pub fn layer_settings(self) -> Vec { - let synchronization = [c"validate_sync", c"syncval_shader_accesses_heuristic"]; - let load_after_store = [c"syncval_load_op_after_store_op_validation"]; - let on = |names: &[&std::ffi::CStr]| -> Vec { + let synchronization = [ + (c"enable_message_limit", false), + (c"validate_sync", true), + (c"syncval_shader_accesses_heuristic", true), + ]; + let load_after_store = [(c"syncval_load_op_after_store_op_validation", true)]; + let on = |names: &[(&std::ffi::CStr, bool)]| -> Vec { names .iter() - .map(|name| { + .map(|(name, value)| { LayerSetting::new( VALIDATION_LAYER.to_owned(), (*name).to_owned(), - LayerSettingValue::Bool(true), + LayerSettingValue::Bool(*value), ) }) .collect() @@ -1934,7 +1942,7 @@ mod lane_checks { let mut options = DeviceOptions::default(); options.layers.push(VALIDATION_LAYER.to_owned()); options.layer_settings = vec![ - setting(c"enable_message_limit", LayerSettingValue::Bool(false)), + setting(c"enable_message_limit", LayerSettingValue::Bool(true)), setting(c"validate_sync", LayerSettingValue::Bool(false)), ]; checks.apply(&mut options); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/apart_writes.rs b/crates/metal2vulkan-validation/src/runtime_lane/apart_writes.rs index 829ec59cc..a3d8c4c85 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/apart_writes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/apart_writes.rs @@ -1,28 +1,73 @@ -//! The validation layer's write-after-write hazards between two of a test's own dispatches whose -//! bytes the test placed apart: a lane claim that lets those pass, and nothing wider. +//! The validation layer's write-after-write hazards that leave no two writes of one byte: between +//! two of a test's own writes whose bytes the test placed apart, between the two draws of one +//! index bounds pass, at most one of which draws, and between the chunk draws of an emulated patch +//! draw, at most one of which draws. A lane claim that lets those pass, and nothing wider. //! -//! The layer's synchronization validation takes a dispatch's storage buffer as written over the -//! whole range its descriptor binds. The runtime binds a buffer slot over the bytes the translation -//! proves the kernel reaches, from the device's offset alignment down and in 16-byte granules, 16 -//! bytes at least (`bind::descriptor_range`), and its hazard tracking orders a serial encoder's -//! dispatches by those proven bytes alone (the slot's window, `bind::plan`'s `buffer_use`). So two -//! dispatches that write words 4 bytes apart in one 16-byte block get no barrier between them, -//! and the layer reports a `WRITE_AFTER_WRITE`. No order of the two can change a byte: Vulkan's -//! memory model has a data race only between "operations that access overlapping sets of memory -//! locations", and "a memory operation must not affect memory at a memory location not within its -//! set of memory locations" (the Memory Model appendix). The lane's positive control -//! `sync_coverage::disjoint_words_of_one_block_are_a_hazard_to_the_layer_alone` shows the -//! report beside the bytes, word by word. +//! **Apart writes.** The layer's synchronization validation takes a shader's storage buffer as +//! written over the whole range its descriptor binds. The runtime binds a buffer slot over the +//! bytes the translation proves the function reaches, from the device's offset alignment down and +//! in 16-byte granules, 16 bytes at least (`bind::descriptor_range`), and its hazard tracking +//! orders a serial encoder's dispatches by those proven bytes alone (the slot's window, +//! `bind::plan`'s `buffer_use`). So two dispatches that write words 4 bytes apart in one 16-byte +//! block get no barrier between them, and the layer reports a `WRITE_AFTER_WRITE`; so do a fill +//! and a dispatch beside it in one block, and two draws of one render encoder, which Metal leaves +//! unordered (docs/API.md's accepted differences), writing their own bytes of one buffer bound +//! wider. No order of two such writes can change a byte: Vulkan's memory model has a data race +//! only between "operations that access overlapping sets of memory locations", and "a memory +//! operation must not affect memory at a memory location not within its set of memory locations" +//! (the Memory Model appendix). The lane's positive control +//! `sync_coverage::disjoint_words_of_one_block_are_a_hazard_to_the_layer_alone` shows the report +//! beside the bytes, word by word. //! -//! A test whose dispatches write such words notes each write as it places it ([`DispatchWrites`]: -//! every dispatch write of a buffer it notes), and states its claim with +//! **The index bounds pass's two draws.** Where Metal has one indexed indirect draw, the runtime's +//! index bounds pass (the runtime's `index_bounds.rs`, announced as `indirect-index-bounds-pass`) +//! records two `vkCmdDrawIndexedIndirect` in the pass, exactly one of which draws the primitives +//! (neither, where the index pool cannot hold them). The layer reads no indirect draw's counts, +//! so it takes both as writing their storage buffers' bound ranges, and reports a +//! `WRITE_AFTER_WRITE` between them as the second is recorded. A draw of no index or no instance +//! makes no write: "primitives are assembled using ... indexCount vertices", "drawn instanceCount +//! times" (`vkCmdDrawIndexed`), so no shader runs. Of the pair at most one accesses memory, and a +//! data race takes two. +//! +//! **An emulated patch draw's chunk draws.** On a device without `tessellationShader` the runtime +//! draws a Metal patch draw as `K` chunk draws (the runtime's `render/tessellation_scan.rs`, +//! announced as `emulated-tessellation-draws`), each a `vkCmdDrawIndirect` of `2^30` of the draw's +//! triangles, whose command the draw's scan writes; `K` covers every triangle the draw's records +//! can hold, every record of the pool for an indirect draw. A chunk past the draw's triangles +//! draws no vertex: the scan writes its `vertexCount` 0, and "primitives are assembled using ... +//! vertexCount consecutive vertex indices" (`vkCmdDraw`, whose parameters a `vkCmdDrawIndirect` +//! command holds). A test keeps each patch draw's triangles below `2^30`, so only chunk 0 +//! draws: of the chunks at most one accesses memory. The layer reads no indirect draw's counts and +//! reports a `WRITE_AFTER_WRITE` between the chunks as each is recorded. +//! +//! A test notes each write of a buffer it notes as it places it ([`NotedWrites`]: every write of +//! such a buffer, by its kind, [`Writer`]), and states its claim with //! [`layer_reported_nothing_but_apart_writes`] once the work ran. A message passes only when it is -//! a `WRITE_AFTER_WRITE` (not the racing form) between two dispatches ([`DISPATCHES`]) on a -//! `VkBuffer` the test noted two writes or more of, no two of which share a byte; it passes with a -//! `LAYER-APART-WRITES` line. Everything else fails as [`layer_reported_nothing`] fails it: a read -//! after a write, a write after a read, a draw's or a copy's access, a buffer the test did not note -//! or noted one write of, and two noted writes that share a byte (the runtime orders those, so the -//! layer's report of them is a missing barrier). +//! a `WRITE_AFTER_WRITE` (not the racing form) on a `VkBuffer` the test noted, and either: +//! +//! - **apart**: the test noted two writes or more of the buffer, each of a kind one Vulkan command +//! records ([`Writer::split`]), none empty and no two sharing a byte, and each of the two +//! commands is one a kind the test noted on the buffer records ([`Writer::commands`]). It passes +//! with a `LAYER-APART-WRITES` line. +//! - **idle**: both commands are `vkCmdDrawIndexedIndirect`, reported as the later one was +//! recorded (two commands of one `VkCommandBuffer`, which holds one command buffer's work: the +//! command buffer records into pools of its own), every write the test noted of the buffer is a +//! bounded draw's ([`Writer::BoundedDraw`]), no command buffer it noted holds two, and a device +//! reporting to the list announced the pass. It passes with a `LAYER-IDLE-DRAW` line. +//! - **idle chunk**: both commands are `vkCmdDrawIndirect`, reported as the later one was +//! recorded, every write the test noted of the buffer is a patch draw's ([`Writer::PatchDraw`]), +//! those of each command buffer none empty and no two sharing a byte (one each, or each into a +//! buffer of its own placed in one `VkBuffer`: two chunks of one draw then, at most one of which +//! draws, or chunks of two draws whose bytes share nothing), and a device reporting to the list +//! announced the emulation. It passes with a `LAYER-IDLE-CHUNK` line. +//! +//! Everything else fails as [`layer_reported_nothing`] fails it: a read after a write, a write +//! after a read, a command of a kind the test did not note on the buffer (a copy's among them), an +//! image, a buffer the test did not note or noted one write of, two noted writes that share a byte +//! (the runtime orders those, so the layer's report of them is a missing barrier), bounded draws +//! reported at a submission, between command buffers, or of a command buffer that noted two, and +//! patch draws' chunks reported so, of a command buffer whose noted patch draws share a byte, or +//! where the emulation was not announced. //! //! [`layer_reported_nothing`]: super::layer_reported_nothing @@ -32,114 +77,302 @@ use std::ops::Range; use { super::{LayerClaim, Messages}, ash::vk::Handle as _, - metal2vulkan_runtime::{Buffer, DebugMessage}, + metal2vulkan_runtime::{Buffer, DebugMessage, Degradation}, }; /// The id name of the one hazard that may pass. const WRITE_AFTER_WRITE: &str = "SYNC-HAZARD-WRITE-AFTER-WRITE"; -/// Whether the layer's message of id name `id_name` and text `text` is a write after write between -/// two dispatches on a `VkBuffer` of which `writes` (each a raw `VkBuffer` handle and the bytes -/// written in it) holds two writes or more, none empty and no two sharing a byte. -fn apart(writes: &[(u64, Range)], id_name: &str, text: &str) -> bool { - if id_name != WRITE_AFTER_WRITE { - return false; +/// The command the index bounds pass records each of its two draws with. +const BOUNDED_DRAW: &str = "vkCmdDrawIndexedIndirect"; + +/// The command the tessellation emulation records each chunk draw of a patch draw with. +const CHUNK_DRAW: &str = "vkCmdDrawIndirect"; + +/// The Vulkan commands the runtime records a Metal draw with, as the layer names them. +const DRAWS: &[&str] = &[ + "vkCmdDraw", + "vkCmdDrawIndexed", + "vkCmdDrawIndirect", + BOUNDED_DRAW, +]; + +/// The Vulkan commands the runtime records a Metal buffer fill of whole words with +/// (`word_fill.rs`), as the layer names them; a fill recorded as a copy is not among them. +const FILLS: &[&str] = &["vkCmdFillBuffer", "vkCmdUpdateBuffer"]; + +/// The kind of a write a test noted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Writer { + /// A dispatch's kernel. + Dispatch, + /// A draw's shaders. + Draw, + /// A blit encoder's fill. + Fill, + /// The shaders of an indexed indirect draw the index bounds pass bounds: two draws, at most + /// one of which draws. + BoundedDraw, + /// The post-tessellation vertex function of a patch draw of fewer than `2^30` triangles: + /// where the runtime emulates tessellation, its chunk draws, at most one of which draws. + PatchDraw, +} + +impl Writer { + /// The Vulkan commands the runtime records such a write with, as the layer names them. + fn commands(self) -> &'static [&'static str] { + match self { + Writer::Dispatch => DISPATCHES, + Writer::Draw => DRAWS, + Writer::Fill => FILLS, + Writer::BoundedDraw => &[BOUNDED_DRAW], + Writer::PatchDraw => &[CHUNK_DRAW], + } } - let Some(hazard) = parse(id_name, text) else { - return false; - }; - let dispatch = |command: &str| DISPATCHES.contains(&command); - if !(hazard.later_writes - && hazard.earlier_writes - && dispatch(&hazard.later) - && dispatch(&hazard.earlier)) - { - return false; + + /// Whether the runtime may record one such write as several Vulkan commands: then two of them + /// may be one write's, and the apart form does not hold. + fn split(self) -> bool { + matches!(self, Writer::BoundedDraw | Writer::PatchDraw) + } +} + +/// Which of the runtime's draws of one Metal draw as several a device reporting to the list +/// announced: the index bounds pass (`indirect-index-bounds-pass`) and the tessellation +/// emulation (`emulated-tessellation-draws`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Announced { + bounds_pass: bool, + emulated_tessellation: bool, +} + +/// One noted write in its `VkBuffer`: its kind, the raw handle, the bytes there, and the command +/// buffer it was noted in (counted from 0 in the order the test noted them). +#[derive(Clone, Debug, PartialEq, Eq)] +struct Noted { + writer: Writer, + buffer: u64, + bytes: Range, + command_buffer: usize, +} + +/// Why a message passed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Passed { + /// Its two writes are noted apart. + Apart, + /// Its two draws are one bounded draw's. + Idle, + /// Its two draws are chunk draws of patch draws noted apart, or of one. + IdleChunk, +} + +/// Why the layer's message of id name `id_name` and text `text` passes against the writes `noted`, +/// where `announced` says which of the runtime's splits a device announced; `None` where it fails +/// (the module docs). +fn passes(noted: &[Noted], announced: Announced, id_name: &str, text: &str) -> Option { + if id_name != WRITE_AFTER_WRITE { + return None; + } + let hazard = parse(id_name, text)?; + if !(hazard.later_writes && hazard.earlier_writes) { + return None; } let Named::Buffer(buffer) = hazard.memory else { - return false; + return None; }; - let mut bytes: Vec<&Range> = (writes.iter()) - .filter(|(noted, _)| *noted == buffer) - .map(|(_, bytes)| bytes) - .collect(); + let on: Vec<&Noted> = noted.iter().filter(|w| w.buffer == buffer).collect(); + if apart(&on, &hazard.later, &hazard.earlier) { + return Some(Passed::Apart); + } + // Two commands of `command`, reported as the later one was recorded, on a buffer every noted + // write of which is `writer`'s, those of each command buffer one, or where `apart_within`, + // none empty and no two sharing a byte. + let idle = |command: &str, writer: Writer, apart_within: bool| { + text.starts_with(&format!("{command}(): ")) + && hazard.later == command + && hazard.earlier == command + && !on.is_empty() + && on.iter().all(|w| w.writer == writer) + && (on.iter()).all(|w| { + let mates: Vec<&Noted> = (on.iter().copied()) + .filter(|v| v.command_buffer == w.command_buffer) + .collect(); + match apart_within { + true => disjoint(&mates), + false => mates.len() == 1, + } + }) + }; + if announced.bounds_pass && idle(BOUNDED_DRAW, Writer::BoundedDraw, false) { + return Some(Passed::Idle); + } + let chunks = announced.emulated_tessellation && idle(CHUNK_DRAW, Writer::PatchDraw, true); + chunks.then_some(Passed::IdleChunk) +} + +/// Whether the writes `on` of one buffer are two or more, each of a kind one Vulkan command +/// records, none empty and no two sharing a byte, and the commands `later` and `earlier` each one +/// that a kind noted among them records. +fn apart(on: &[&Noted], later: &str, earlier: &str) -> bool { + let noted = |command: &str| on.iter().any(|w| w.writer.commands().contains(&command)); + noted(later) + && noted(earlier) + && on.len() >= 2 + && on.iter().all(|w| !w.writer.split()) + && disjoint(on) +} + +/// Whether the writes `on` are none empty and no two sharing a byte. +fn disjoint(on: &[&Noted]) -> bool { + let mut bytes: Vec<&Range> = on.iter().map(|w| &w.bytes).collect(); bytes.sort_by_key(|bytes| bytes.start); // Sorted by their starts, the writes share no byte when each ends at or before the next starts. - bytes.len() >= 2 - && bytes.iter().all(|bytes| bytes.start < bytes.end) + bytes.iter().all(|bytes| bytes.start < bytes.end) && bytes.windows(2).all(|pair| pair[0].end <= pair[1].start) } -/// The writes a test's dispatches made of the buffers it notes, each as the test placed it: the -/// buffer, and the bytes from its byte 0. +/// The writes a test's commands made of the buffers it notes, each as the test placed it: its +/// kind, the buffer, the bytes from its byte 0, and the command buffer. Made, it holds the +/// layer's hazard reports for its claim ([`Messages::hold_hazards`]), which reads every one. #[cfg(any(m2v_gpu, m2v_cpu_icd))] -#[derive(Default)] -pub(super) struct DispatchWrites(Vec<(Buffer, Range)>); +pub(super) struct NotedWrites { + writes: Vec<(Writer, Buffer, Range, usize)>, + command_buffer: usize, +} #[cfg(any(m2v_gpu, m2v_cpu_icd))] -impl DispatchWrites { - /// Note that a dispatch writes `bytes` of `buffer`. A test notes every dispatch write of a - /// buffer it notes. - pub(super) fn wrote(&mut self, buffer: &Buffer, bytes: Range) { - self.0.push((buffer.clone(), bytes)); +impl NotedWrites { + /// No write noted yet, the layer's hazard reports to `messages` held from here on. + pub(super) fn new(messages: &Messages) -> NotedWrites { + messages.hold_hazards(); + NotedWrites { + writes: Vec::new(), + command_buffer: 0, + } } - /// Each noted write in its `VkBuffer`, as the layer names it: the raw handle, and the bytes - /// there. Asked only once the work ran, so handing the buffers out changes nothing of it. - fn in_vk_buffers(&self) -> Vec<(u64, Range)> { - (self.0.iter()) - .map(|(buffer, bytes)| { + /// Note that a dispatch writes `bytes` of `buffer`. + pub(super) fn dispatched(&mut self, buffer: &Buffer, bytes: Range) { + self.wrote(Writer::Dispatch, buffer, bytes); + } + + /// Note that a draw's shaders write `bytes` of `buffer`. + pub(super) fn drew(&mut self, buffer: &Buffer, bytes: Range) { + self.wrote(Writer::Draw, buffer, bytes); + } + + /// Note that a fill writes `bytes` of `buffer`. + pub(super) fn filled(&mut self, buffer: &Buffer, bytes: Range) { + self.wrote(Writer::Fill, buffer, bytes); + } + + /// Note that an indexed indirect draw the index bounds pass bounds writes `bytes` of `buffer`. + pub(super) fn drew_bounded(&mut self, buffer: &Buffer, bytes: Range) { + self.wrote(Writer::BoundedDraw, buffer, bytes); + } + + /// Note that a patch draw of fewer than `2^30` triangles writes `bytes` of `buffer` from its + /// post-tessellation vertex function. + pub(super) fn drew_patches(&mut self, buffer: &Buffer, bytes: Range) { + self.wrote(Writer::PatchDraw, buffer, bytes); + } + + /// The writes noted from here on are another command buffer's. + pub(super) fn next_command_buffer(&mut self) { + self.command_buffer += 1; + } + + /// Note that a write of `writer`'s kind writes `bytes` of `buffer`. A test notes every write + /// of a buffer it notes. + fn wrote(&mut self, writer: Writer, buffer: &Buffer, bytes: Range) { + (self.writes).push((writer, buffer.clone(), bytes, self.command_buffer)); + } + + /// Each noted write in its `VkBuffer`, as the layer names it. Asked only once the work ran, + /// so handing the buffers out changes nothing of it. + fn in_vk_buffers(&self) -> Vec { + (self.writes.iter()) + .map(|(writer, buffer, bytes, command_buffer)| { // SAFETY: the handle is only compared with the layer's reports, never used. let (raw, at) = unsafe { buffer.vk_buffer() }; - (raw.as_raw(), at + bytes.start..at + bytes.end) + Noted { + writer: *writer, + buffer: raw.as_raw(), + bytes: at + bytes.start..at + bytes.end, + command_buffer: *command_buffer, + } }) .collect() } } /// [`layer_reported_nothing`](super::layer_reported_nothing) of `claim`, but for the layer's write -/// after write between two dispatches on a buffer at bytes `writes` notes apart, each of which -/// passes with a `LAYER-APART-WRITES` line. A list the sink filled fails: what it dropped past -/// [`Messages::MAX`] is unread. +/// after write between two writes at bytes `writes` notes apart, each of which passes with a +/// `LAYER-APART-WRITES` line, between the two draws of one bounded draw `writes` notes alone in +/// its command buffer, each of which passes with a `LAYER-IDLE-DRAW` line, and between chunk draws +/// of patch draws `writes` notes apart in their command buffer, each of which passes with a +/// `LAYER-IDLE-CHUNK` line (the module docs). +/// Each distinct report is judged once and passes or fails with the times it came. A list the +/// sink filled fails: what it dropped past [`Messages::MAX`] is unread. /// /// # Panics /// -/// Where the layer reported anything else, or filled the list. +/// Where the layer reported anything else, or filled a list. #[cfg(any(m2v_gpu, m2v_cpu_icd))] pub(super) fn layer_reported_nothing_but_apart_writes( messages: &Messages, claim: &str, - writes: &DispatchWrites, + writes: &NotedWrites, ) -> LayerClaim { + let held = messages.take_held_hazards(); let reported = messages.take(); assert!( - reported.len() < Messages::MAX, - "{claim}: the message list filled, so what it dropped is unread\n{reported:#?}" + held.len() < Messages::MAX && reported.len() < Messages::MAX, + "{claim}: a message list filled, so what it dropped is unread\n{held:#?}\n{reported:#?}" ); - let noted = match reported.is_empty() { + let noted = match held.is_empty() && reported.is_empty() { true => Vec::new(), false => writes.in_vk_buffers(), }; + let announced = Announced { + bounds_pass: messages.announced(Degradation::IndirectIndexBoundsPass), + emulated_tessellation: messages.announced(Degradation::EmulatedTessellationDraws), + }; let test = std::thread::current().name().unwrap_or_default().to_owned(); - let rest: Vec = (reported.into_iter()) - .filter(|message| { - let passes = apart(¬ed, &message.id_name, &message.text); - if passes { - eprintln!( - "LAYER-APART-WRITES {test}: passed, a write after write between dispatches \ - whose bytes the test placed apart: {} ({}): {}", - message.id_name, - message.id, - message.text.replace('\n', " ") - ); - } - !passes + let all = (held.into_iter()).chain(reported.into_iter().map(|message| (message, 1))); + let rest: Vec<(DebugMessage, usize)> = all + .filter(|(message, times)| { + let (tag, what) = match passes(¬ed, announced, &message.id_name, &message.text) { + None => return true, + Some(Passed::Apart) => ( + "LAYER-APART-WRITES", + "a write after write between writes whose bytes the test placed apart", + ), + Some(Passed::Idle) => ( + "LAYER-IDLE-DRAW", + "a write after write between the two draws of one bounded draw, at most one \ + of which draws", + ), + Some(Passed::IdleChunk) => ( + "LAYER-IDLE-CHUNK", + "a write after write between chunk draws of patch draws the test placed \ + apart, at most one chunk of each drawing", + ), + }; + eprintln!( + "{tag} {test}: passed, {what} ({times} time(s)): {} ({}): {}", + message.id_name, + message.id, + message.text.replace('\n', " ") + ); + false }) .collect(); let stated = messages.state_layer_claim(claim); assert!( rest.is_empty(), - "{claim}: the validation layer reported\n{rest:#?}" + "{claim}: the validation layer reported (each with the times it came)\n{rest:#?}" ); stated } @@ -151,6 +384,9 @@ mod tests { /// The buffer the hazards below name. const BUFFER: u64 = 0x7400_0000_0074; + /// Another buffer. + const OTHER: u64 = 0x5900_0000_0059; + /// The hazard as the layer 1.4.357 reported it at a submission, between the dispatches of two /// command buffers of one batch (`argument_buffers` on lavapipe), naming no shader stage. const AT_SUBMIT_357: &str = "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. \ @@ -187,74 +423,221 @@ mod tests { /// Every wording above. const FORMS: [&str; 3] = [AT_SUBMIT_357, AT_SUBMIT, AT_RECORD]; - /// Two words 4 bytes apart, and two more after them: the four ID words of `argument_buffers`. - fn words(count: u64) -> Vec<(u64, Range)> { + /// A fill's write after a dispatch's, as the layer 1.4.357 reported it at a submission + /// (`memoryless_uses` on lavapipe). + const FILL_AFTER_DISPATCH: &str = "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. \ + vkCmdFillBuffer (from VkCommandBuffer 0x7f3f49c76530 submitted on the current VkQueue \ + 0x7f3f48135d40) writes to VkBuffer 0x740000000074, which was previously written by \ + vkCmdDispatch (from VkCommandBuffer 0x7f3f49c73410 submitted on VkQueue 0x7f3f48135d40). \ + \nNo sufficient synchronization is present to ensure that a write \ + (VK_ACCESS_2_TRANSFER_WRITE_BIT) at VK_PIPELINE_STAGE_2_CLEAR_BIT does not conflict with \ + a prior write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at \ + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT."; + + /// A dispatch's write after a fill's, at a submission with a barrier between them that orders + /// no shader write (`memoryless_uses` on lavapipe). + const DISPATCH_AFTER_FILL: &str = "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. \ + vkCmdDispatch (from VkCommandBuffer 0x7fa965d6d350 submitted on the current VkQueue \ + 0x7fa964135d10) writes to VkBuffer 0x740000000074, which was previously written by \ + vkCmdFillBuffer (from VkCommandBuffer 0x7fa965ce7890 submitted on VkQueue \ + 0x7fa964135d10). The current synchronization allows 0, but to prevent this hazard, it \ + must allow VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT accesses at \ + VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT."; + + /// Two draws of one render encoder, as the layer 1.4.357 reported the later one's recording + /// (`int_attributes` on lavapipe). + const DRAW_AT_RECORD: &str = "vkCmdDraw(): WRITE_AFTER_WRITE hazard detected. Shader stage \ + VK_SHADER_STAGE_VERTEX_BIT writes to VkBuffer 0x740000000074, which was previously \ + written by another vkCmdDraw command. The buffer is referenced by descriptor binding 0 \ + (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) from descriptor set 0 (VkDescriptorSet 0x0), \ + VkPipeline 0x420000000042. No sufficient synchronization is present to ensure that a \ + write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT \ + does not conflict with a prior write of the same type at the same stage."; + + /// A draw of an indirect command buffer's execution after the encoder's own, as the layer + /// 1.4.357 reported it at `vkCmdExecuteCommands` (`render_executions` on lavapipe). + const DRAW_AT_EXECUTE: &str = "vkCmdExecuteCommands(): WRITE_AFTER_WRITE hazard detected. \ + vkCmdDraw (from the secondary VkCommandBuffer 0x7f8f71dd19a0) writes to VkBuffer \ + 0x740000000074, which was previously written by another vkCmdDraw command (from the \ + primary VkCommandBuffer 0x7f8f71ce1090). No sufficient synchronization is present to \ + ensure that a write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at \ + VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT does not conflict with a prior write of the same \ + type at the same stage."; + + /// The index bounds pass's two draws, as the layer 1.4.357 reported the second's recording + /// (`draw_bases` on lavapipe). + const BOUNDED_AT_RECORD: &str = "vkCmdDrawIndexedIndirect(): WRITE_AFTER_WRITE hazard \ + detected. Shader stage VK_SHADER_STAGE_VERTEX_BIT writes to VkBuffer 0x740000000074, \ + which was previously written by another vkCmdDrawIndexedIndirect command. The buffer is \ + referenced by descriptor binding 0 (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) from descriptor \ + set 0 (VkDescriptorSet 0x0), VkPipeline 0x3c000000003c. No sufficient synchronization is \ + present to ensure that a write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at \ + VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT does not conflict with a prior write of the same \ + type at the same stage."; + + /// A noted write of `writer` at `bytes` of `buffer`, in command buffer `command_buffer`. + fn noted(writer: Writer, buffer: u64, bytes: Range, command_buffer: usize) -> Noted { + Noted { + writer, + buffer, + bytes, + command_buffer, + } + } + + /// `count` words of [`BUFFER`] side by side, each written by `writer`: the four ID words of + /// `argument_buffers` for dispatches. + fn words(writer: Writer, count: u64) -> Vec { (0..count) - .map(|word| (BUFFER, 4 * word..4 * word + 4)) + .map(|word| noted(writer, BUFFER, 4 * word..4 * word + 4, 0)) .collect() } + /// Both splits announced. + const BOTH: Announced = Announced { + bounds_pass: true, + emulated_tessellation: true, + }; + + /// The tessellation emulation announced alone. + const CHUNKS_ONLY: Announced = Announced { + bounds_pass: false, + emulated_tessellation: true, + }; + + /// The index bounds pass announced alone. + const BOUNDS_ONLY: Announced = Announced { + bounds_pass: true, + emulated_tessellation: false, + }; + + /// Whether `text` passes against `noted` with both splits announced, and why. + fn judged(noted: &[Noted], text: &str) -> Option { + passes(noted, BOTH, WRITE_AFTER_WRITE, text) + } + #[test] fn dispatches_writing_words_apart_pass_in_either_form() { for text in FORMS { - assert!(apart(&words(2), WRITE_AFTER_WRITE, text), "{text}"); - assert!(apart(&words(4), WRITE_AFTER_WRITE, text), "{text}"); + let two = words(Writer::Dispatch, 2); + assert_eq!(judged(&two, text), Some(Passed::Apart), "{text}"); + let four = words(Writer::Dispatch, 4); + assert_eq!(judged(&four, text), Some(Passed::Apart), "{text}"); // The noted writes of other buffers change nothing. - let mut more = words(2); - more.push((0x5900_0000_0059, 0..4)); - assert!(apart(&more, WRITE_AFTER_WRITE, text), "{text}"); + let mut more = words(Writer::Dispatch, 2); + more.push(noted(Writer::Dispatch, OTHER, 0..4, 0)); + assert_eq!(judged(&more, text), Some(Passed::Apart), "{text}"); // A later dispatch of either other form. for command in ["vkCmdDispatchBase", "vkCmdDispatchIndirect"] { let other = text.replacen("vkCmdDispatch", command, 1); - assert!(apart(&words(2), WRITE_AFTER_WRITE, &other), "{other}"); + assert_eq!(judged(&two, &other), Some(Passed::Apart), "{other}"); } } } + #[test] + fn a_fill_and_a_dispatch_apart_pass_either_way_round() { + let mut beside = vec![noted(Writer::Fill, BUFFER, 0..4, 0)]; + beside.push(noted(Writer::Dispatch, BUFFER, 8..12, 0)); + for text in [FILL_AFTER_DISPATCH, DISPATCH_AFTER_FILL] { + assert_eq!(judged(&beside, text), Some(Passed::Apart), "{text}"); + // A fill recorded as an update. + let update = text.replace("vkCmdFillBuffer", "vkCmdUpdateBuffer"); + assert_eq!(judged(&beside, &update), Some(Passed::Apart), "{update}"); + // Sharing a byte. + let mut over = beside.clone(); + over.push(noted(Writer::Fill, BUFFER, 10..14, 0)); + assert_eq!(judged(&over, text), None, "{text}"); + // A fill the test did not note: two dispatches' writes alone. + let dispatches = words(Writer::Dispatch, 2); + assert_eq!(judged(&dispatches, text), None, "{text}"); + // A copy where a fill was noted. + let copy = text.replace("vkCmdFillBuffer", "vkCmdCopyBuffer"); + assert_eq!(judged(&beside, ©), None, "{copy}"); + } + } + + #[test] + fn draws_writing_their_own_bytes_pass_and_a_shared_byte_fails() { + for text in [DRAW_AT_RECORD, DRAW_AT_EXECUTE] { + let rows = words(Writer::Draw, 8); + assert_eq!(judged(&rows, text), Some(Passed::Apart), "{text}"); + // Each of the runtime's draw commands, at either end. + for command in ["vkCmdDrawIndexed", "vkCmdDrawIndirect", BOUNDED_DRAW] { + let later = (text.replacen("vkCmdDraw(): ", &format!("{command}(): "), 1)) + .replacen("detected. vkCmdDraw ", &format!("detected. {command} "), 1); + assert_eq!(judged(&rows, &later), Some(Passed::Apart), "{later}"); + let earlier = text.replace("another vkCmdDraw ", &format!("another {command} ")); + assert_eq!(judged(&rows, &earlier), Some(Passed::Apart), "{earlier}"); + } + // Two draws of one row. + let mut shared = words(Writer::Draw, 8); + shared.push(noted(Writer::Draw, BUFFER, 12..16, 0)); + assert_eq!(judged(&shared, text), None, "{text}"); + // Draws noted where the layer names a dispatch, and dispatches where it names draws. + let dispatch = text.replacen("vkCmdDraw", "vkCmdDispatch", 1); + assert_eq!(judged(&rows, &dispatch), None, "{dispatch}"); + assert_eq!(judged(&words(Writer::Dispatch, 8), text), None, "{text}"); + } + } + #[test] fn writes_that_share_a_byte_fail() { for text in FORMS { - let one_word = vec![(BUFFER, 0..4), (BUFFER, 0..4)]; - assert!(!apart(&one_word, WRITE_AFTER_WRITE, text), "{text}"); - let overlapping = vec![(BUFFER, 0..4), (BUFFER, 8..12), (BUFFER, 2..6)]; - assert!(!apart(&overlapping, WRITE_AFTER_WRITE, text), "{text}"); - let empty = vec![(BUFFER, 0..4), (BUFFER, 4..4)]; - assert!(!apart(&empty, WRITE_AFTER_WRITE, text), "{text}"); + let one_word = [words(Writer::Dispatch, 1), words(Writer::Dispatch, 1)].concat(); + assert_eq!(judged(&one_word, text), None, "{text}"); + let mut overlapping = words(Writer::Dispatch, 1); + overlapping.push(noted(Writer::Dispatch, BUFFER, 8..12, 0)); + overlapping.push(noted(Writer::Dispatch, BUFFER, 2..6, 0)); + assert_eq!(judged(&overlapping, text), None, "{text}"); + let mut empty = words(Writer::Dispatch, 1); + empty.push(noted(Writer::Dispatch, BUFFER, 4..4, 0)); + assert_eq!(judged(&empty, text), None, "{text}"); } } #[test] fn a_buffer_the_test_did_not_note_twice_fails() { for text in FORMS { - assert!(!apart(&[], WRITE_AFTER_WRITE, text), "{text}"); - assert!(!apart(&words(1), WRITE_AFTER_WRITE, text), "{text}"); - let elsewhere: Vec<_> = (words(2).into_iter()) - .map(|(_, bytes)| (0x5900_0000_0059, bytes)) + assert_eq!(judged(&[], text), None, "{text}"); + assert_eq!(judged(&words(Writer::Dispatch, 1), text), None, "{text}"); + let elsewhere: Vec = (words(Writer::Dispatch, 2).into_iter()) + .map(|w| Noted { buffer: OTHER, ..w }) .collect(); - assert!(!apart(&elsewhere, WRITE_AFTER_WRITE, text), "{text}"); + assert_eq!(judged(&elsewhere, text), None, "{text}"); } } #[test] fn reads_and_racing_writes_fail() { + let two = words(Writer::Dispatch, 2); let read_after_write = AT_RECORD .replace("WRITE_AFTER_WRITE", "READ_AFTER_WRITE") .replace(" writes to ", " reads "); for id_name in ["SYNC-HAZARD-READ-AFTER-WRITE", WRITE_AFTER_WRITE] { - assert!(!apart(&words(2), id_name, &read_after_write), "{id_name}"); + assert_eq!(passes(&two, BOTH, id_name, &read_after_write), None); } let write_after_read = AT_RECORD .replace("WRITE_AFTER_WRITE", "WRITE_AFTER_READ") .replace("previously written by", "previously read by"); for id_name in ["SYNC-HAZARD-WRITE-AFTER-READ", WRITE_AFTER_WRITE] { - assert!(!apart(&words(2), id_name, &write_after_read), "{id_name}"); + assert_eq!(passes(&two, BOTH, id_name, &write_after_read), None); } let racing = AT_RECORD.replace("WRITE_AFTER_WRITE", "WRITE_RACING_WRITE"); - assert!(!apart(&words(2), "SYNC-HAZARD-WRITE-RACING-WRITE", &racing)); + let id_name = "SYNC-HAZARD-WRITE-RACING-WRITE"; + assert_eq!(passes(&two, BOTH, id_name, &racing), None); + // A bounded draw's pair, read rather than written. + let bounded = [noted(Writer::BoundedDraw, BUFFER, 0..32, 0)]; + let read = BOUNDED_AT_RECORD + .replace("WRITE_AFTER_WRITE", "READ_AFTER_WRITE") + .replace(" writes to ", " reads "); + let id_name = "SYNC-HAZARD-READ-AFTER-WRITE"; + assert_eq!(passes(&bounded, BOTH, id_name, &read), None); } #[test] - fn a_draw_or_a_copy_at_either_end_fails() { + fn a_draw_or_a_copy_where_dispatches_were_noted_fails() { + let two = words(Writer::Dispatch, 2); for command in [ "vkCmdDraw", "vkCmdDrawIndexed", @@ -263,30 +646,194 @@ mod tests { ] { // The later command. let later = AT_RECORD.replacen("vkCmdDispatch", command, 1); - assert!(!apart(&words(2), WRITE_AFTER_WRITE, &later), "{later}"); + assert_eq!(judged(&two, &later), None, "{later}"); let later = AT_SUBMIT.replacen("in vkCmdDispatch", &format!("in {command}"), 1); - assert!(!apart(&words(2), WRITE_AFTER_WRITE, &later), "{later}"); + assert_eq!(judged(&two, &later), None, "{later}"); let later = AT_SUBMIT_357.replacen( "detected. vkCmdDispatch", &format!("detected. {command}"), 1, ); - assert!(!apart(&words(2), WRITE_AFTER_WRITE, &later), "{later}"); + assert_eq!(judged(&two, &later), None, "{later}"); // The earlier one. for text in FORMS { let earlier = text.replace("another vkCmdDispatch", &format!("another {command}")); - assert!(!apart(&words(2), WRITE_AFTER_WRITE, &earlier), "{earlier}"); + assert_eq!(judged(&two, &earlier), None, "{earlier}"); } } // A copy's own wording, with no shader stage. let copy = "vkCmdCopyBuffer(): WRITE_AFTER_WRITE hazard detected. vkCmdCopyBuffer writes \ to VkBuffer 0x740000000074, which was previously written by vkCmdDispatch command."; - assert!(!apart(&words(2), WRITE_AFTER_WRITE, copy)); + assert_eq!(judged(&two, copy), None); } #[test] fn an_image_fails() { let image = AT_RECORD.replace("VkBuffer 0x740000000074", "VkImage 0x740000000074"); - assert!(!apart(&words(2), WRITE_AFTER_WRITE, &image)); + assert_eq!(judged(&words(Writer::Dispatch, 2), &image), None); + let image = BOUNDED_AT_RECORD.replace("VkBuffer 0x740000000074", "VkImage 0x740000000074"); + let bounded = [noted(Writer::BoundedDraw, BUFFER, 0..32, 0)]; + assert_eq!(judged(&bounded, &image), None); + } + + /// One bounded draw's whole output, in each of `command_buffers` command buffers. + fn bounded(command_buffers: usize) -> Vec { + (0..command_buffers) + .map(|at| noted(Writer::BoundedDraw, BUFFER, 0..32, at)) + .collect() + } + + #[test] + fn the_two_draws_of_a_bounded_draw_alone_in_its_command_buffer_pass() { + assert_eq!(judged(&bounded(1), BOUNDED_AT_RECORD), Some(Passed::Idle)); + // One such draw in each of several command buffers. + assert_eq!(judged(&bounded(3), BOUNDED_AT_RECORD), Some(Passed::Idle)); + // The noted writes of other buffers change nothing. + let mut more = bounded(1); + more.push(noted(Writer::Draw, OTHER, 0..4, 0)); + more.push(noted(Writer::Draw, OTHER, 0..4, 0)); + assert_eq!(judged(&more, BOUNDED_AT_RECORD), Some(Passed::Idle)); + } + + #[test] + fn bounded_draws_that_share_a_command_buffer_or_a_byte_with_another_write_fail() { + // Two bounded draws of one command buffer writing the same bytes: a real overlap. + let mut two = bounded(1); + two.push(noted(Writer::BoundedDraw, BUFFER, 0..32, 0)); + assert_eq!(judged(&two, BOUNDED_AT_RECORD), None); + // And beside another command buffer's one. + two.push(noted(Writer::BoundedDraw, BUFFER, 0..32, 1)); + assert_eq!(judged(&two, BOUNDED_AT_RECORD), None); + // A plain draw of the same bytes beside the bounded one. + let mut beside = bounded(1); + beside.push(noted(Writer::Draw, BUFFER, 0..4, 0)); + assert_eq!(judged(&beside, BOUNDED_AT_RECORD), None); + // Beside it in another command buffer: the buffer's writes are not all bounded draws'. + let mut other = bounded(1); + other.push(noted(Writer::Draw, BUFFER, 0..4, 1)); + assert_eq!(judged(&other, BOUNDED_AT_RECORD), None); + // No bounded draw noted on the buffer. + assert_eq!(judged(&[], BOUNDED_AT_RECORD), None); + let elsewhere = [noted(Writer::BoundedDraw, OTHER, 0..32, 0)]; + assert_eq!(judged(&elsewhere, BOUNDED_AT_RECORD), None); + } + + #[test] + fn bounded_draws_pass_only_as_recorded_both_bounded_and_announced() { + let one = bounded(1); + // Not announced. + let unannounced = passes(&one, CHUNKS_ONLY, WRITE_AFTER_WRITE, BOUNDED_AT_RECORD); + assert_eq!(unannounced, None); + // At a submission, or at an execution of secondary command buffers: two command buffers. + let submitted = format!( + "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. {BOUNDED_DRAW} (from \ + VkCommandBuffer 0x7f00000001 submitted on the current VkQueue 0x7f00000002) writes \ + to VkBuffer 0x740000000074, which was previously written by another {BOUNDED_DRAW} \ + command (from VkCommandBuffer 0x7f00000003 submitted on VkQueue 0x7f00000002)." + ); + assert_eq!(judged(&one, &submitted), None, "{submitted}"); + let executed = DRAW_AT_EXECUTE.replace("vkCmdDraw ", &format!("{BOUNDED_DRAW} ")); + assert_eq!(judged(&one, &executed), None, "{executed}"); + // Either command another draw. + for command in ["vkCmdDraw", "vkCmdDrawIndexed", "vkCmdDrawIndirect"] { + let later = BOUNDED_AT_RECORD.replacen(BOUNDED_DRAW, command, 1); + assert_eq!(judged(&one, &later), None, "{later}"); + let earlier = BOUNDED_AT_RECORD.replace( + &format!("another {BOUNDED_DRAW}"), + &format!("another {command}"), + ); + assert_eq!(judged(&one, &earlier), None, "{earlier}"); + } + } + + /// Two chunk draws of an emulated patch draw, as the layer reported the later one's recording + /// (`patches::emulated_patch_draws_read_their_factors_as_metal` on lavapipe). + const CHUNK_AT_RECORD: &str = "vkCmdDrawIndirect(): WRITE_AFTER_WRITE hazard detected. Shader \ + stage VK_SHADER_STAGE_VERTEX_BIT writes to VkBuffer 0x740000000074, which was previously \ + written by another vkCmdDrawIndirect command. The buffer is referenced by descriptor \ + binding 0 (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) from descriptor set 0 (VkDescriptorSet \ + 0x0), VkPipeline 0x470000000047. No sufficient synchronization is present to ensure that a \ + write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT does \ + not conflict with a prior write of the same type at the same stage."; + + /// A patch draw's marks, of `MARKS` bytes, at mark buffer `at` of one `VkBuffer`, in command + /// buffer `command_buffer`. + fn patch_draw(at: u64, command_buffer: usize) -> Noted { + const MARKS: u64 = 4225 * 16; + noted( + Writer::PatchDraw, + BUFFER, + at * MARKS..(at + 1) * MARKS, + command_buffer, + ) + } + + #[test] + fn chunks_of_patch_draws_apart_in_their_command_buffer_pass() { + // One patch draw in each of several command buffers, of the same bytes. + let alone = [patch_draw(0, 0), patch_draw(0, 1), patch_draw(0, 2)]; + assert_eq!(judged(&alone, CHUNK_AT_RECORD), Some(Passed::IdleChunk)); + // Several in one command buffer, each into a buffer of its own in the `VkBuffer`. + let own = [patch_draw(0, 0), patch_draw(1, 0), patch_draw(2, 0)]; + assert_eq!(judged(&own, CHUNK_AT_RECORD), Some(Passed::IdleChunk)); + // The noted writes of other buffers change nothing. + let mut more = vec![patch_draw(0, 0)]; + more.push(noted(Writer::Draw, OTHER, 0..4, 0)); + more.push(noted(Writer::Draw, OTHER, 0..4, 0)); + assert_eq!(judged(&more, CHUNK_AT_RECORD), Some(Passed::IdleChunk)); + } + + #[test] + fn patch_draws_that_share_a_byte_in_a_command_buffer_or_with_another_write_fail() { + // Two patch draws of one command buffer writing the same marks: a real overlap. + let shared = [patch_draw(0, 0), patch_draw(0, 0)]; + assert_eq!(judged(&shared, CHUNK_AT_RECORD), None); + // A plain draw beside the patch draw, in its command buffer or another. + for command_buffer in [0, 1] { + let beside = [ + patch_draw(0, 0), + noted(Writer::Draw, BUFFER, 0..4, command_buffer), + ]; + assert_eq!(judged(&beside, CHUNK_AT_RECORD), None); + } + // Patch draws noted apart, but more than one Vulkan command each: not the apart form. + let apart = [patch_draw(0, 0), patch_draw(1, 0)]; + let draws = CHUNK_AT_RECORD.replace("vkCmdDrawIndirect", "vkCmdDraw"); + assert_eq!(judged(&apart, &draws), None, "{draws}"); + // No patch draw noted on the buffer. + assert_eq!(judged(&[], CHUNK_AT_RECORD), None); + let elsewhere = [Noted { + buffer: OTHER, + ..patch_draw(0, 0) + }]; + assert_eq!(judged(&elsewhere, CHUNK_AT_RECORD), None); + } + + #[test] + fn chunks_pass_only_as_recorded_both_chunks_and_announced() { + let one = [patch_draw(0, 0)]; + // Not announced. + let unannounced = passes(&one, BOUNDS_ONLY, WRITE_AFTER_WRITE, CHUNK_AT_RECORD); + assert_eq!(unannounced, None); + // At a submission, or at an execution of secondary command buffers: two command buffers. + let submitted = format!( + "vkQueueSubmit(): WRITE_AFTER_WRITE hazard detected. {CHUNK_DRAW} (from \ + VkCommandBuffer 0x7f00000001 submitted on the current VkQueue 0x7f00000002) writes \ + to VkBuffer 0x740000000074, which was previously written by another {CHUNK_DRAW} \ + command (from VkCommandBuffer 0x7f00000003 submitted on VkQueue 0x7f00000002)." + ); + assert_eq!(judged(&one, &submitted), None, "{submitted}"); + let executed = DRAW_AT_EXECUTE.replace("vkCmdDraw ", &format!("{CHUNK_DRAW} ")); + assert_eq!(judged(&one, &executed), None, "{executed}"); + // Either command another draw. + for command in ["vkCmdDraw", "vkCmdDrawIndexed", BOUNDED_DRAW] { + let later = CHUNK_AT_RECORD.replacen(CHUNK_DRAW, command, 1); + assert_eq!(judged(&one, &later), None, "{later}"); + let earlier = CHUNK_AT_RECORD.replace( + &format!("another {CHUNK_DRAW}"), + &format!("another {command}"), + ); + assert_eq!(judged(&one, &earlier), None, "{earlier}"); + } } } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/argument_buffers.rs b/crates/metal2vulkan-validation/src/runtime_lane/argument_buffers.rs index fc76d9b51..489573c8e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/argument_buffers.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/argument_buffers.rs @@ -13,7 +13,7 @@ //! dispatches share one heap set per pipeline variant, so 2048 dispatches over textures of their //! own each read their own and the process stays small. -use super::apart_writes::{layer_reported_nothing_but_apart_writes, DispatchWrites}; +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::kernel_textures::{absent_read_only, fresh_candidate, refusal}; use super::{ at_plan, bound_buffers, buffer_with, encode_case, layer_reported_nothing, @@ -278,14 +278,14 @@ fn addresses_a_kernel_writes_reach_buffers_as_the_cpus_do() { let mut encoder = command_buffer.compute_command_encoder().unwrap(); encoder.set_compute_pipeline_state(©).unwrap(); encoder.set_buffer(Some(&address), 0, 0).unwrap(); - let mut writes = DispatchWrites::default(); + let mut writes = NotedWrites::new(messages); for word in [0, 4] { encoder.set_buffer_offset(word, 0).unwrap(); let at = u64::from(field.1) + word; encoder.set_buffer(Some(owner), at, 1).unwrap(); let one = Size::new(1, 1, 1); encoder.dispatch_threads(one, one).unwrap(); - writes.wrote(owner, at..at + 4); + writes.dispatched(owner, at..at + 4); } if !one_encoder { encoder.end_encoding().unwrap(); @@ -406,7 +406,7 @@ fn resource_ids_a_kernel_writes_name_resources_as_the_cpus_do() { let mut encoder = command_buffer.compute_command_encoder().unwrap(); encoder.set_compute_pipeline_state(©).unwrap(); encoder.set_buffer(Some(&source), 0, 0).unwrap(); - let mut writes = DispatchWrites::default(); + let mut writes = NotedWrites::new(messages); for ((field, id), at) in ids.iter().zip((0u64..).step_by(8)) { let owner = &buffers[&field.0]; assert_ne!( @@ -420,7 +420,7 @@ fn resource_ids_a_kernel_writes_name_resources_as_the_cpus_do() { encoder.set_buffer(Some(owner), to, 1).unwrap(); let one = Size::new(1, 1, 1); encoder.dispatch_threads(one, one).unwrap(); - writes.wrote(owner, to..to + 4); + writes.dispatched(owner, to..to + 4); } } if !one_encoder { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/draw_bases.rs b/crates/metal2vulkan-validation/src/runtime_lane/draw_bases.rs index afaccb589..afa9eaaee 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/draw_bases.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/draw_bases.rs @@ -14,8 +14,9 @@ //! `MTLDrawIndexedPrimitivesIndirectArguments` of the same values), and as the one command of an //! indirect command buffer of draws executed in the encoder, and stores the M3's answer each way. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::degrade_notices::on_device_with; -use super::{at_plan, buffer_with, read_buffer, WAIT}; +use super::{at_plan, buffer_with, read_buffer, Messages, WAIT}; use crate::air_library::AirLibrary; use crate::case::{AuthoredCase, IndexType as CaseIndexType, OutputSelection, Primitive}; use crate::store::CorpusStore; @@ -80,8 +81,11 @@ fn words(device: &Device, words: &[u32]) -> Buffer { buffer_with(device, &bytes).unwrap() } -/// The output bytes `case`'s draw stores when `issued`. -fn drawn(device: &Device, case: &AuthoredCase, issued: Issued) -> Vec { +/// The output bytes `case`'s draw stores when `issued`. An indexed indirect draw, which the index +/// bounds pass bounds on a device that does not keep it on its range, writes `out` alone in its +/// command buffer, so the layer's report of the pass's two draws passes +/// ([`layer_reported_nothing_but_apart_writes`]). +fn drawn(device: &Device, messages: &Messages, case: &AuthoredCase, issued: Issued) -> Vec { let draw = case.draw.as_ref().expect("a vertex case's draw"); assert_eq!(draw.primitive, Primitive::Point, "{}", case.name); let initial = base64::engine::general_purpose::STANDARD @@ -93,6 +97,7 @@ fn drawn(device: &Device, case: &AuthoredCase, issued: Issued) -> Vec { ) .unwrap(); let out = buffer_with(device, &initial).unwrap(); + let mut writes = NotedWrites::new(messages); let OutputSelection::Buffer { offset, length, .. } = case.output else { panic!("{}: a buffer output", case.name) }; @@ -177,6 +182,7 @@ fn drawn(device: &Device, case: &AuthoredCase, issued: Issued) -> Vec { } // {indexCount, instanceCount, indexStart, baseVertex, baseInstance}. (Issued::Indirect, Some((indices, index_type, offset))) => { + writes.drew_bounded(&out, 0..out.length()); let arguments = words( device, &[ @@ -237,6 +243,8 @@ fn drawn(device: &Device, case: &AuthoredCase, issued: Issued) -> Vec { command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.error(), None, "{} {issued:?}", case.name); + let claim = format!("{} {issued:?}", case.name); + layer_reported_nothing_but_apart_writes(messages, &claim, &writes); drop(held); read_buffer(&out, offset, length).unwrap() } @@ -249,11 +257,11 @@ fn drawn(device: &Device, case: &AuthoredCase, issued: Issued) -> Vec { fn draws_read_metal_s_base_vertex_and_base_instance() { let cases = cases(); assert_eq!(cases.len(), 4, "the fixture's committed cases"); - on_device_with(at_plan, |device, _| { + on_device_with(at_plan, |device, messages| { for (case, metal) in &cases { for issued in [Issued::Direct, Issued::Indirect, Issued::Command] { assert_eq!( - drawn(device, case, issued), + drawn(device, messages, case, issued), *metal, "{} {issued:?} on {}", case.name, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/helper_select.rs b/crates/metal2vulkan-validation/src/runtime_lane/helper_select.rs index e89607969..48231e7f3 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/helper_select.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/helper_select.rs @@ -21,7 +21,8 @@ //! may be lost where the note is not recorded, and none written outside the triangle. //! //! The fence's GPU time is printed for a 1024x1024 pass whose every fragment picks the sum (each -//! invocation, live ones too, runs the call and its fence), 32 draws a command buffer. +//! invocation, live ones too, runs the call and its fence), 32 draws a command buffer, a texture +//! barrier between each two. use super::buffer_with; use super::guarded_effects::{bytes, covered, texture, unpack, words, CORNERS, H, SENTINEL, W}; @@ -30,7 +31,7 @@ use super::WAIT; use crate::air_library::AirLibrary; use metal2vulkan::device::DriverWorkaround; use metal2vulkan::device::OpBits; -use metal2vulkan::metal::{PrimitiveType, TextureUsage}; +use metal2vulkan::metal::{BarrierScope, PrimitiveType, RenderStages, TextureUsage}; use metal2vulkan::pipeline::{PrecisionNote, RenderPipelineDescriptor, StageSource}; use metal2vulkan::vk; use metal2vulkan::Budget; @@ -261,8 +262,9 @@ fn a_write_after_a_helper_pick_is_lost_only_where_noted() { } /// The GPU time of `rch_select_arm` where every fragment picks the sum: a 1024x1024 pass, 32 -/// draws a command buffer, the least of five command buffers printed beside the fences the -/// fragment takes. Every pixel must hold the sum. +/// draws a command buffer, a texture barrier between each two (each draw writes every texel), the +/// least of five command buffers printed beside the fences the fragment takes. Every pixel must +/// hold the sum. #[test] fn a_fenced_pick_s_gpu_time() { let (messages, _cache, lane) = lane(); @@ -299,7 +301,13 @@ fn a_fenced_pick_s_gpu_time() { encoder.set_fragment_texture(Some(&noise), 0).unwrap(); encoder.set_fragment_texture(Some(&coverage), 1).unwrap(); encoder.set_fragment_texture(Some(&written), 2).unwrap(); - for _ in 0..DRAWS { + // Two draws of one encoder that write one texel race, on Metal too, but where a barrier + // between them orders the first's writes before the second's fragments. + for draw in 0..DRAWS { + if draw > 0 { + let fragment = RenderStages::FRAGMENT; + encoder.memory_barrier_with_scope(BarrierScope::TEXTURES, fragment, fragment); + } encoder .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) .unwrap(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/index_fetches.rs b/crates/metal2vulkan-validation/src/runtime_lane/index_fetches.rs index e1f2159ba..08516e1af 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/index_fetches.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/index_fetches.rs @@ -45,6 +45,7 @@ //! buffer, which mark 7 as Metal's read of them does. The padded copy and the index bounds pass //! read the same bytes. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::degrade_notices::{assert_made_once, assert_once}; use super::shared_kinds; use super::{ @@ -118,15 +119,17 @@ impl Opened { } } -/// The device's queue and the fixture's vertex-only pipeline state. +/// The device's queue, the fixture's vertex-only pipeline state, and the list the device reports +/// to. struct Lane { device: Device, queue: CommandQueue, pipeline: RenderPipelineState, + messages: Messages, } impl Lane { - fn new(device: Device) -> Lane { + fn new(device: Device, messages: &Messages) -> Lane { let bitcode = llvm_assemble(&engine_dir().join("ob3_index_buffer.ll")).unwrap(); let library = device.new_library_with_air(&bitcode).unwrap(); let function = library.new_function_with_name("ob3_index_buffer").unwrap(); @@ -140,6 +143,7 @@ impl Lane { queue: device.new_command_queue().unwrap(), device, pipeline, + messages: messages.clone(), } } @@ -149,7 +153,10 @@ impl Lane { self.drawn_positions(indices, offset, indirect, POSITIONS) } - /// [`drawn`](Self::drawn) of `positions` positions. + /// [`drawn`](Self::drawn) of `positions` positions. An indirect draw, which the index bounds + /// pass bounds on a device that does not keep it on its range, writes `seen` alone in its + /// command buffer, so the layer's report of the pass's two draws passes + /// ([`layer_reported_nothing_but_apart_writes`]). fn drawn_positions( &self, indices: &Buffer, @@ -158,6 +165,10 @@ impl Lane { positions: u32, ) -> Result<[u32; 8], Error> { let seen = buffer_with(&self.device, &[0; 32]).unwrap(); + let mut writes = NotedWrites::new(&self.messages); + if indirect { + writes.drew_bounded(&seen, 0..32); + } let arguments: Vec = [positions, 1, 0, BASE_VERTEX as u32, 0] .iter() .flat_map(|word| word.to_le_bytes()) @@ -197,6 +208,8 @@ impl Lane { command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.error(), None); + let claim = format!("a draw from offset {offset}, indirect {indirect}"); + layer_reported_nothing_but_apart_writes(&self.messages, &claim, &writes); drawn?; let bytes = read_buffer(&seen, 0, 32).unwrap(); let mut words = [0u32; 8]; @@ -249,7 +262,7 @@ fn index_positions_past_the_buffer_draw_index_zero_plus_the_base_vertex() { .contains(&DriverFact::RobustIndexFetchReadsZero); let name = device.name().to_owned(); let shared = shared_kinds(&device); - let lane = Lane::new(device); + let lane = Lane::new(device, &messages); let placed = guarded_buffer( &lane.device, &bytes, @@ -374,7 +387,7 @@ fn a_run_of_bounded_indirect_draws_draws_each_draws_metal_vertices() { .unwrap(); let name = device.name().to_owned(); let shared = shared_kinds(&device); - let lane = Lane::new(device); + let lane = Lane::new(device, &messages); let indices = buffer_with(&lane.device, &bytes).unwrap(); let arguments: Vec = RUN .iter() @@ -394,7 +407,10 @@ fn a_run_of_bounded_indirect_draws_draws_each_draws_metal_vertices() { let command_buffer = lane.queue.command_buffer().unwrap(); let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); encoder.set_render_pipeline_state(&lane.pipeline).unwrap(); + // Each draw writes a `seen` of its own, alone in the command buffer. + let mut writes = NotedWrites::new(&messages); for (at, ((offset, _, _), seen)) in RUN.iter().zip(&seen).enumerate() { + writes.drew_bounded(seen, 0..32); encoder.set_vertex_buffer(Some(seen), 0, 0).unwrap(); encoder .draw_indexed_primitives_indirect( @@ -411,6 +427,7 @@ fn a_run_of_bounded_indirect_draws_draws_each_draws_metal_vertices() { command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.error(), None, "on {name}"); + layer_reported_nothing_but_apart_writes(&messages, "the run's draws", &writes); assert_eq!( lane.device.work_counts().bounded_run_draws - before, RUN.len() as u64, @@ -472,7 +489,7 @@ fn an_indirect_draw_past_the_old_index_pool_draws_metals_vertices() { .unwrap(); let name = device.name().to_owned(); let unified = device.properties().has_unified_memory; - let lane = Lane::new(device); + let lane = Lane::new(device, &messages); let own = buffer_with(&lane.device, &bytes).unwrap(); assert_eq!( lane.drawn_positions(&own, 0, true, PAST_OLD_POOL), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/index_pools.rs b/crates/metal2vulkan-validation/src/runtime_lane/index_pools.rs index 5ed845114..68c01939d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/index_pools.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/index_pools.rs @@ -34,6 +34,7 @@ //! other 15 rounds the submission returned before the allocation began and the handler ran //! during it; in all 40 the handler ran 0.07 to 1.44 ms after the later of the two. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::{ at_plan, buffer_with, layer_reported_nothing_at_all, validated_device_with, Messages, ScratchCache, WAIT, @@ -49,6 +50,7 @@ use metal2vulkan_runtime::{ host_time, Buffer, CommandBuffer, CommandQueue, Device, PipelineOptions, RenderPassDescriptor, RenderPipelineState, }; +use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -82,14 +84,18 @@ fn words(words: &[u32]) -> Vec { words.iter().flat_map(|word| word.to_le_bytes()).collect() } -/// The device, opened without the robustness features, the fixture's vertex-only pipeline state -/// and the draw's buffers. +/// The device, opened without the robustness features, the fixture's vertex-only pipeline state, +/// the draw's buffers, and the list the device reports to with the draws' writes: each command +/// buffer's one draw, which the index bounds pass bounds, writes `seen` alone in it, so the +/// layer's report of the pass's two draws passes ([`Lane::claim`]). struct Lane { device: Device, pipeline: RenderPipelineState, seen: Buffer, indices: Buffer, arguments: Buffer, + messages: Messages, + writes: RefCell, } impl Lane { @@ -125,6 +131,8 @@ impl Lane { seen, indices, arguments, + messages: messages.clone(), + writes: RefCell::new(NotedWrites::new(messages)), } } @@ -132,6 +140,13 @@ impl Lane { self.device.new_command_queue().unwrap() } + /// The layer reported nothing of the command buffers so far but the index bounds pass's + /// two draws of each ([`layer_reported_nothing_but_apart_writes`]). + fn claim(&self, claim: &str) { + let writes = self.writes.replace(NotedWrites::new(&self.messages)); + layer_reported_nothing_but_apart_writes(&self.messages, claim, &writes); + } + /// A command buffer of `queue` with the draw, encoded: its pass leased the queue's block. fn encoded(&self, queue: &CommandQueue) -> CommandBuffer { self.encoded_with(queue, &self.arguments) @@ -144,6 +159,10 @@ impl Lane { pass.render_target_height = 1; pass.default_raster_sample_count = 1; let command_buffer = queue.command_buffer().unwrap(); + let mut writes = self.writes.borrow_mut(); + writes.next_command_buffer(); + writes.drew_bounded(&self.seen, 0..32); + drop(writes); let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); encoder.set_render_pipeline_state(&self.pipeline).unwrap(); encoder.set_vertex_buffer(Some(&self.seen), 0, 0).unwrap(); @@ -234,6 +253,7 @@ fn command_buffers_of_one_queue_share_one_pool_block() { 2, "two command buffers held the block at once at most" ); + lane.claim("the rounds' draws"); } layer_reported_nothing_at_all(&messages); } @@ -270,6 +290,7 @@ fn a_second_queue_takes_its_own_pool_block() { assert_eq!(lane.blocks(), (3, 1), "the later queue took the spare"); lane.drawn(&queue); assert_eq!(lane.blocks(), (3, 1), "the first queue's block again"); + lane.claim("the queues' draws"); } layer_reported_nothing_at_all(&messages); } @@ -319,6 +340,7 @@ fn a_pool_block_no_command_buffer_held_goes_after_the_quiet_period() { assert_eq!(lane.blocks(), (3, 1), "a queue that rested took the spare"); lane.drawn(&idle); assert_eq!(lane.blocks(), (4, 1), "the other makes one again"); + lane.claim("the queues' draws"); } layer_reported_nothing_at_all(&messages); } @@ -407,6 +429,7 @@ fn a_completed_handler_waits_for_no_pool_block_made_meanwhile() { assert_eq!(live(&lane), 2, "round {round}: the blocks left"); } eprintln!("{told} of {MAKING_ROUNDS} rounds told"); + lane.claim("the rounds' draws"); } layer_reported_nothing_at_all(&messages); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/int_attributes.rs b/crates/metal2vulkan-validation/src/runtime_lane/int_attributes.rs index b8d836346..6b7d49c22 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/int_attributes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/int_attributes.rs @@ -26,6 +26,7 @@ //! - A 32-bit integer format read into a float attribute refuses the pipeline, //! `InvalidDescriptor(VertexAttribute)`, where Metal refuses it too. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::degrade_notices::{counts, made_render_kinds}; use super::{ buffer_with, half_within, layer_reported_nothing_at_all, read_buffer, validated_device, @@ -189,16 +190,20 @@ fn form(pipeline: &ExecutedPipeline) -> String { } /// The rows each draw of `pipeline` wrote, in a 1x1 pass without attachments: per vertex one -/// draw of `ROWS` points, constant `ROWS` draws of one point bound at each record; and how the -/// first executed pipeline fetched the attribute. +/// draw of `ROWS` points, constant `ROWS` draws of one point bound at each record, each writing +/// its own row of `out`, bound from there on, which the layer takes as written by each +/// ([`layer_reported_nothing_but_apart_writes`]); and how the first executed pipeline fetched the +/// attribute. fn drawn( queue: &CommandQueue, + messages: &Messages, pipeline: &RenderPipelineState, records: &metal2vulkan_runtime::Buffer, constant: bool, ) -> (Vec<[u32; 4]>, String) { let device = queue.device(); let out = buffer_with(device, &[0xCD; 16 * ROWS]).unwrap(); + let mut writes = NotedWrites::new(messages); let mut pass = RenderPassDescriptor::new(); pass.render_target_width = 1; pass.render_target_height = 1; @@ -217,6 +222,7 @@ fn drawn( encoder .draw_primitives(PrimitiveType::Point, 0, 1, 1, 0) .unwrap(); + writes.drew(&out, 16 * r as u64..16 * (r as u64 + 1)); } } else { encoder.set_vertex_buffer(Some(&out), 0, 0).unwrap(); @@ -229,6 +235,7 @@ fn drawn( command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + layer_reported_nothing_but_apart_writes(messages, "the conversion's draws", &writes); let executions = command_buffer.executions(); let form = form(executions[0].pipeline()); let rows = read_buffer(&out, 0, 16 * ROWS as u64) @@ -275,7 +282,7 @@ fn integer_formats_read_into_float_attributes_take_metal_s_values() { let pipeline = conversion(&device, &library, function, format, 16 * i as u32, step) .unwrap_or_else(|e| panic!("{function} {format:?} {step:?}: {e}")); - let (rows, form) = drawn(&queue, &pipeline, &records, constant); + let (rows, form) = drawn(&queue, &messages, &pipeline, &records, constant); println!( "INT-ATTR {}: {function} {format:?} {step:?}: {form}", device.name() diff --git a/crates/metal2vulkan-validation/src/runtime_lane/memoryless_uses.rs b/crates/metal2vulkan-validation/src/runtime_lane/memoryless_uses.rs index dc8158a98..8dc860d97 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/memoryless_uses.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/memoryless_uses.rs @@ -15,10 +15,11 @@ //! rather than to nil, and a texture read only on pixels the draw never covers rather than behind //! a flag that is never set. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::attachment_reads::{corners, floats, function}; use super::degrade_notices::on_device; use super::degrade_notices::on_device_with; -use super::{at_plan, buffer_with, read_buffer, WAIT}; +use super::{at_plan, buffer_with, read_buffer, Messages, WAIT}; use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{ PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureType, TextureUsage, @@ -355,8 +356,9 @@ enum Step { /// The sequence `steps` in one command buffer, each encoder with a mark of its own, then the /// queue's next: each encoder's mark, its own value where it ran and 0 where not, and the event's -/// signaled value. -fn sequence(device: &Device, steps: &[Step]) -> Ran { +/// signaled value. A kernel's mark and a fill's lie apart in one 16-byte block, which the layer +/// takes as the kernel's whole ([`layer_reported_nothing_but_apart_writes`]). +fn sequence(device: &Device, messages: &Messages, steps: &[Step]) -> Ran { let store = kernel(device, "store_const", "store_const.ll"); let writes = kernel(device, "tob_two_ways", "tob_renders.ll"); let texture = memoryless(device, 1); @@ -367,8 +369,14 @@ fn sequence(device: &Device, steps: &[Step]) -> Ran { let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); let one = Size::new(1, 1, 1); + let mut noted = NotedWrites::new(messages); for (at, step) in steps.iter().enumerate() { let at = at as u64; + match step { + Step::Compute | Step::ComputeUses => noted.dispatched(&marks, at * 4..at * 4 + 4), + Step::Blit => noted.filled(&marks, at * 4..at * 4 + 4), + Step::BlitUses | Step::Signal => {} + } match step { Step::Compute | Step::ComputeUses => { let mut compute = command_buffer.compute_command_encoder().unwrap(); @@ -395,7 +403,11 @@ fn sequence(device: &Device, steps: &[Step]) -> Ran { .unwrap(), } } - ran(&queue, &command_buffer, &marks, words, &[&event]) + // The next command buffer's fill of the last mark. + noted.filled(&marks, (words - 1) * 4..words * 4); + let ran = ran(&queue, &command_buffer, &marks, words, &[&event]); + layer_reported_nothing_but_apart_writes(messages, &format!("{steps:?}"), ¬ed); + ran } /// A copy of `texture`'s `side`² texels at its origin into `buffer`, tight rows. @@ -425,7 +437,7 @@ fn copy_out( #[test] fn a_memoryless_use_fails_its_run_of_encoders_on() { use Step::{Blit, BlitUses, Compute, ComputeUses, Signal}; - on_device_with(at_plan, |device, _messages| { + on_device_with(at_plan, |device, messages| { let (stored, filled, last) = (42, word(0x11), word(0x77)); let cases: [(&str, &[Step], &[u32], u64); 7] = [ ("CcC", &[Compute, ComputeUses, Compute], &[0, 0, 0], 0), @@ -442,7 +454,7 @@ fn a_memoryless_use_fails_its_run_of_encoders_on() { ("CSc", &[Compute, Signal, ComputeUses], &[stored, 0, 0], 1), ]; for (name, steps, marks, event) in cases { - let ran = sequence(device, steps); + let ran = sequence(device, messages, steps); assert_eq!((ran.status, ran.error), FAILED, "{name}"); let mut want = marks.to_vec(); want.push(last); @@ -450,7 +462,7 @@ fn a_memoryless_use_fails_its_run_of_encoders_on() { assert_eq!(ran.events, [event], "{name}"); } // Without a use: every encoder runs and the signal fires. - let ran = sequence(device, &[Blit, Signal, Compute]); + let ran = sequence(device, messages, &[Blit, Signal, Compute]); assert_eq!((ran.status, ran.error), COMPLETED); assert_eq!(ran.marks, [filled, 0, stored, last]); assert_eq!(ran.events, [1]); @@ -465,7 +477,7 @@ fn a_memoryless_use_fails_its_run_of_encoders_on() { /// complete. #[test] fn memoryless_compute_and_blit_uses_fail_as_metal_s() { - on_device(|device, _messages| { + on_device(|device, messages| { let store = kernel(device, "store_const", "store_const.ll"); let writes = kernel(device, "tob_two_ways", "tob_renders.ll"); let texture = memoryless(device, 1); @@ -582,7 +594,9 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { } type Compute<'a> = Box; let one = Size::new(1, 1, 1); - let computes: Vec<(&str, Compute, bool)> = vec![ + // Each case, whether it fails its command buffer, and whether its kernel runs a thread, + // which stores into the mark bound at 4. + let computes: Vec<(&str, Compute, bool, bool)> = vec![ ( "read", Box::new(|c| { @@ -592,6 +606,7 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { c.dispatch_threadgroups(one, one).unwrap(); }), true, + true, ), ( "no_threadgroups", @@ -602,6 +617,7 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { c.dispatch_threadgroups(Size::new(0, 1, 1), one).unwrap(); }), true, + false, ), ( "empty_threadgroup", @@ -612,6 +628,7 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { c.dispatch_threadgroups(one, Size::new(0, 0, 0)).unwrap(); }), true, + false, ), ( "use_resource", @@ -620,6 +637,7 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { c.use_resource(texture.as_resource(), usage).unwrap(); }), true, + false, ), ( "unused", @@ -627,6 +645,7 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { c.set_texture(Some(&texture), 0).unwrap(); }), false, + false, ), ( "barrier", @@ -635,10 +654,23 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { c.memory_barrier_with_resources(&resources).unwrap(); }), false, + false, ), ]; - for (name, case, fails) in computes { + for (name, case, fails, stores) in computes { let marks = buffer_with(device, &[0u8; 20]).unwrap(); + // The fills' and the kernels' marks, apart in the blocks the layer takes whole + // ([`layer_reported_nothing_but_apart_writes`]); a case's kernel that runs a thread + // stores into the mark bound at 4 too, and one of no thread stores nothing. + let mut noted = NotedWrites::new(messages); + noted.filled(&marks, 0..4); + noted.dispatched(&marks, 4..8); + if stores { + noted.dispatched(&marks, 4..8); + } + noted.dispatched(&marks, 8..12); + noted.filled(&marks, 12..16); + noted.filled(&marks, 16..20); let command_buffer = queue.command_buffer().unwrap(); fill(&command_buffer, &marks, 0, 0x11); let mut compute = command_buffer.compute_command_encoder().unwrap(); @@ -652,6 +684,7 @@ fn memoryless_compute_and_blit_uses_fail_as_metal_s() { compute.end_encoding().unwrap(); fill(&command_buffer, &marks, 3, 0x44); let ran = ran(&queue, &command_buffer, &marks, 5, &[]); + layer_reported_nothing_but_apart_writes(messages, name, ¬ed); let last = word(0x77); if fails { assert_eq!((ran.status, ran.error), FAILED, "{name}"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/normalized_vertex_fetch.rs b/crates/metal2vulkan-validation/src/runtime_lane/normalized_vertex_fetch.rs index dba62862a..e7ee9a0b2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/normalized_vertex_fetch.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/normalized_vertex_fetch.rs @@ -38,6 +38,7 @@ //! each code and its maximum's reciprocal, not the device's conversion: it records the note on //! every profile where that product misses Metal's at some code, and is not drawn. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::degrade_notices::counts; use super::{ buffer_with, half_within, layer_reported_nothing_at_all, read_buffer, validated_device, @@ -354,9 +355,12 @@ fn descriptor( } /// The rows `descriptor`'s pipeline writes for `elements` records: per vertex one draw of a point -/// per element, per instance one draw of one point per element at its base vertex and instance. +/// per element, per instance one draw of one point per element at its base vertex and instance, +/// each writing its own row of `out`, bound whole, which the layer takes as written by each +/// ([`layer_reported_nothing_but_apart_writes`]). fn drawn( queue: &CommandQueue, + messages: &Messages, descriptor: &RenderPipelineDescriptor, records: &Buffer, elements: usize, @@ -367,6 +371,7 @@ fn drawn( .new_render_pipeline_state(descriptor, &PipelineOptions::default()) .unwrap(); let out = buffer_with(device, &vec![0xCD; ROW * elements]).unwrap(); + let mut writes = NotedWrites::new(messages); let mut pass = RenderPassDescriptor::new(); pass.render_target_width = 1; pass.render_target_height = 1; @@ -383,6 +388,8 @@ fn drawn( encoder .draw_primitives(PrimitiveType::Point, v, 1, 1, v) .unwrap(); + let row = (ROW as u64) * u64::from(v); + writes.drew(&out, row..row + ROW as u64); } } _ => encoder @@ -393,6 +400,7 @@ fn drawn( command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + layer_reported_nothing_but_apart_writes(messages, "the format's draws", &writes); read_buffer(&out, 0, (ROW * elements) as u64) .unwrap() .as_chunks::<16>() @@ -473,7 +481,7 @@ fn every_normalized_code_reads_metal_s_value() { && (conversion || notes.contains(&PrecisionNote::NativeHalfConversion) || notes.contains(&PrecisionNote::NativeHalfQuantize)); - let rows = drawn(&queue, &d, &records, elements, step); + let rows = drawn(&queue, &messages, &d, &records, elements, step); let (mut off, mut most, mut first) = (0usize, 0u64, None); for (v, got) in rows.iter().enumerate() { let want = metal_row(coding, v, half); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pass_start_reads.rs b/crates/metal2vulkan-validation/src/runtime_lane/pass_start_reads.rs index c95177dee..dad4dea7d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pass_start_reads.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pass_start_reads.rs @@ -24,6 +24,7 @@ use super::degrade_notices::{ use super::render_state::{ quiet, validated, validated_checking_synchronization, Pipe, Probe, PASS, WHITE, }; +use super::stage_races::layer_reported_nothing_but_announced_stage_races; use super::{read_buffer, WAIT}; use crate::air_library::AirLibrary; use metal2vulkan::metal::{ @@ -306,7 +307,8 @@ fn a_fragment_stage_touches_what_an_earlier_vertex_stage_of_its_pass_wrote_after /// A buffer a vertex stage of the pass wrote too (the fixture `icb_render_replay_template`, /// rasterizing nothing, writes words 0 and 1) is read in place, announced once -/// (`in-place-vertex-reads`); the depth is the device's. +/// (`in-place-vertex-reads`); the depth is the device's. The layer's report of that race passes +/// as announced (`stage_races.rs`). #[test] fn a_vertex_stage_reads_in_place_what_another_stage_of_its_pass_wrote() { let (messages, _cache, probe) = validated(); @@ -342,6 +344,8 @@ fn a_vertex_stage_reads_in_place_what_another_stage_of_its_pass_wrote() { mark(e, &marker, &words); read(p, e, &words, 0); }); + let claim = "the reader's in-place read of the marker's write"; + layer_reported_nothing_but_announced_stage_races(&messages, claim, &[&words]); let reader = [WHITE.depth(PixelFormat::Depth32Float)]; let first = forced_kinds(&probe, (false, true), &reader, false); assert_made_once(&messages, &IN_PLACE_VERTEX_READS, &first); @@ -430,7 +434,7 @@ fn a_command_s_vertex_stage_reads_the_bytes_from_before_its_pass_s_fragment_writ /// nothing) is announced once (`fragments-before-geometry`). Metal runs the vertex function /// before the pass's fragments (an earlier fragment read a later vertex function's write, and its /// own write outlasted it), so the marker ORs bit 0 into the writer's 0.5; the device's order is -/// printed. +/// printed. The layer's report of that race passes as announced (`stage_races.rs`). #[test] fn a_vertex_stage_s_write_after_a_fragment_s_access_is_announced() { let (messages, _cache, probe) = validated(); @@ -465,6 +469,8 @@ fn a_vertex_stage_s_write_after_a_fragment_s_access_is_announced() { e.set_vertex_buffer(Some(&words), 0, 1).unwrap(); e.draw_primitives(PrimitiveType::Point, 0, 1, 1, 0).unwrap(); }); + let claim = "the writer's write after the marker's access"; + layer_reported_nothing_but_announced_stage_races(&messages, claim, &[&words]); let word = u32::from_le_bytes(read_buffer(&words, 0, 4).unwrap().try_into().unwrap()); assert!( word == OLD || word == WRITTEN, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/patch_indices.rs b/crates/metal2vulkan-validation/src/runtime_lane/patch_indices.rs index 44974978e..3b743e451 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/patch_indices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/patch_indices.rs @@ -19,7 +19,8 @@ //! //! Each test runs on the device's tessellation stages and on the emulation (`patches::Path`). -use super::patches::{on_path, Path}; +use super::apart_writes::NotedWrites; +use super::patches::{on_path_noted, Path}; use super::{buffer_with, read_buffer, WAIT}; use crate::air_library::AirLibrary; use metal2vulkan::metal::{ @@ -344,9 +345,15 @@ impl Lane { self.padded(&bytes, pad) } - /// Record `case` with `pipeline`, its buffers and factors bound, and return what it left in - /// the marks: `Err` for a refused draw, which ends the encoder unrecorded. - fn marks(&self, pipeline: &RenderPipelineState, case: &Case) -> Result<[u32; 4], Error> { + /// Record `case` with `pipeline`, its buffers and factors bound, in a command buffer of its + /// own noted in `writes`, and return what it left in the marks: `Err` for a refused draw, + /// which ends the encoder unrecorded. + fn marks( + &self, + pipeline: &RenderPipelineState, + case: &Case, + writes: &mut NotedWrites, + ) -> Result<[u32; 4], Error> { let points = self.words(&(0..12).collect::>(), 0); let tags = self.words(&(0..16).map(|p| 0xa0 + p).collect::>(), 0); let marks = self.words(&[0; 4], 0); @@ -402,6 +409,10 @@ impl Lane { command_buffer.commit()?; command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + if drawn.is_ok() { + writes.drew_patches(&marks, 0..marks.length()); + } + writes.next_command_buffer(); drawn?; let bytes = read_buffer(&marks, 0, 16).unwrap(); let mut words = [0; 4]; @@ -430,7 +441,7 @@ fn emulated_patch_index_buffers_name_patches_as_metal() { } fn name_patches_as_metal(path: Path) { - on_path(path, |device, name| { + on_path_noted(path, |device, name, writes| { let lane = Lane::new(device); for (case, metal) in cases() { let pipeline = match lane.pipeline(case.index_type()) { @@ -442,7 +453,7 @@ fn name_patches_as_metal(path: Path) { Err(error) => panic!("the pipeline on {name}: {error}"), }; let marks = lane - .marks(&pipeline, &case) + .marks(&pipeline, &case, writes) .unwrap_or_else(|e| panic!("{} on {name}: {e}", case.name)); assert_eq!( marks.map(|w| format!("{w:x}")), @@ -479,7 +490,7 @@ fn emulated_control_point_index_buffers_are_refused_as_metal_refuses_them() { fn refused_as_metal_refuses_them(path: Path) { use TessellationControlPointIndexType as T; - on_path(path, |device, name| { + on_path_noted(path, |device, name, writes| { let lane = Lane::new(device); let short = REVERSED.split_at(5).0; let six = REVERSED.split_at(6).0; @@ -596,7 +607,7 @@ fn refused_as_metal_refuses_them(path: Path) { } Err(error) => panic!("the pipeline on {name}: {error}"), }; - let got = lane.marks(&pipeline, &case); + let got = lane.marks(&pipeline, &case, writes); match expected { Ok(metal) => { let marks = got.unwrap_or_else(|e| panic!("{} on {name}: {e}", case.name)); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/patches.rs b/crates/metal2vulkan-validation/src/runtime_lane/patches.rs index 7837235d5..da8bf483e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/patches.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/patches.rs @@ -15,6 +15,7 @@ //! (`render/tessellation_scan.rs`): the same marks, and the emulation announced once //! ([`EMULATED_TESSELLATION`]). +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::{ buffer_with, layer_reported_nothing_at_all, read_buffer, validated_device_with, Messages, ScratchCache, WAIT, @@ -82,9 +83,26 @@ pub(super) fn on_path_with( adjust: fn(&mut DeviceOptions), path: Path, check: impl FnOnce(Device, &str), +) { + noted_on_path_with(adjust, path, |device, name, _| check(device, name)) +} + +/// [`on_path`], `check` noting the writes of its patch draws, whose marks buffers the layer may +/// report between the chunk draws of an emulated draw +/// ([`layer_reported_nothing_but_apart_writes`]). +pub(super) fn on_path_noted(path: Path, check: impl FnOnce(Device, &str, &mut NotedWrites)) { + noted_on_path_with(|_| {}, path, check) +} + +/// [`on_path_noted`], `adjust` applied to the options of each device it makes. +fn noted_on_path_with( + adjust: fn(&mut DeviceOptions), + path: Path, + check: impl FnOnce(Device, &str, &mut NotedWrites), ) { let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); + let mut writes = NotedWrites::new(&messages); let apple_tessellator; { let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { @@ -96,8 +114,9 @@ pub(super) fn on_path_with( apple_tessellator = description.driver_id == Some(DriverId::MOLTENVK) && description.vendor_id == 0x106B; let name = device.name().to_owned(); - check(device, &name); + check(device, &name, &mut writes); } + layer_reported_nothing_but_apart_writes(&messages, "the patch draws", &writes); let notices = messages.take_notices(); let announced = |kind: Degradation| { notices @@ -327,8 +346,8 @@ impl Lane { Ok(command_buffer) } - /// The cells `case` marked. - fn marked(&self, case: &Case) -> Result, Error> { + /// The cells `case` marked, its draw, in a command buffer of its own, noted in `writes`. + fn marked(&self, case: &Case, writes: &mut NotedWrites) -> Result, Error> { let pipeline = self.pipeline(case.step, case.scale_enabled)?; let marks = self.buffer(&vec![0; MARK_WORDS * 4]); let factors = match case.halves { @@ -361,6 +380,8 @@ impl Lane { ), } })?; + writes.drew_patches(&marks, 0..marks.length()); + writes.next_command_buffer(); Ok(cells(&marks)) } } @@ -976,11 +997,11 @@ fn emulated_patch_draws_read_their_factors_as_metal() { } fn read_their_factors_as_metal(path: Path) { - on_path(path, |device, name| { + on_path_noted(path, |device, name, writes| { let lane = Lane::new(device); let mut answers = Vec::new(); for (case, metal) in cases() { - match lane.marked(&case) { + match lane.marked(&case, writes) { Ok(cells) => { assert_eq!(cells, metal, "{} on {name}: the marked cells", case.name); answers.push(format!("{} Metal's", case.name)); @@ -1013,7 +1034,7 @@ fn emulated_a_scale_infinite_as_a_half_draws_the_maximum_factor() { } fn scale_infinite_draws_the_maximum(path: Path) { - on_path(path, |device, name| { + on_path_noted(path, |device, name, writes| { let lane = Lane::new(device); for scale in [64.0, 65504.0, 70000.0, f32::INFINITY] { let case = Case { @@ -1021,7 +1042,7 @@ fn scale_infinite_draws_the_maximum(path: Path) { scale: Some(scale), ..Case::new("scale_maximum") }; - match lane.marked(&case) { + match lane.marked(&case, writes) { Ok(cells) => { if let Some(unlike) = unlike(&cells, &maximum()) { panic!("scale {scale} on {name}: {unlike}"); @@ -1053,7 +1074,7 @@ fn emulated_an_infinite_inside_factor_draws_the_maximum_inside() { } fn infinite_inside_draws_the_maximum(path: Path) { - on_path(path, |device, name| { + on_path_noted(path, |device, name, writes| { let lane = Lane::new(device); let case = Case { scale_enabled: true, @@ -1061,7 +1082,7 @@ fn infinite_inside_draws_the_maximum(path: Path) { inside: Some(0x7c00), ..Case::new("inside_infinite") }; - match lane.marked(&case) { + match lane.marked(&case, writes) { Ok(cells) => { if let Some(unlike) = unlike(&cells, &cells_of(INSIDE_CELLS)) { panic!("on {name}: {unlike}"); @@ -1090,8 +1111,9 @@ fn invalid(call: &'static str, problem: DrawProblem) -> Result<(), Error> { /// (Metal probes on an M4); a draw with other control points than the function's draws with its /// own, one of no patches or instances draws nothing, as does a draw of primitives with the /// tessellation pipeline, and indirect arguments and a patch index buffer at an offset that is not -/// a multiple of 4 are read from the offset rounded down. Each pass draws only patch 0 of factors -/// 2, so it marks what that patch marks. +/// a multiple of 4 are read from the offset rounded down. Each draw that runs marks a buffer of +/// its own (Metal orders no draw's vertex writes after another's in a pass) and draws only patch 0 +/// of factors 2, so together they mark what that patch marks. #[test] fn patch_draws_answer_as_plain_metal_and_refuse_the_rest() { answer_as_plain_metal(Path::Native); @@ -1104,7 +1126,7 @@ fn emulated_patch_draws_answer_as_plain_metal_and_refuse_the_rest() { } fn answer_as_plain_metal(path: Path) { - on_path(path, |device, name| { + on_path_noted(path, |device, name, writes| { let lane = Lane::new(device); let pipeline = match lane.pipeline(TessellationFactorStepFunction::PerPatch, false) { Ok(pipeline) => pipeline, @@ -1121,8 +1143,17 @@ fn answer_as_plain_metal(path: Path) { let index = lane.buffer(&[0; 8]); let draw = |e: &mut RenderCommandEncoder, points| e.draw_patches(points, 0, 1, None, 0, 1, 0); - let marks = lane.buffer(&vec![0; MARK_WORDS * 4]); - lane.pass(&pipeline, &marks, |e| { + // Each draw that runs marks a buffer of its own: Metal orders no draw's vertex writes after + // another's in a pass, so draws marking one buffer would race. + let mut drawn = Vec::new(); + let mut fresh = |e: &mut RenderCommandEncoder| { + let marks = lane.buffer(&vec![0; MARK_WORDS * 4]); + e.set_vertex_buffer(Some(&marks), 0, 1)?; + drawn.push(marks); + Ok::<_, Error>(()) + }; + let refused = lane.buffer(&vec![0; MARK_WORDS * 4]); + lane.pass(&pipeline, &refused, |e| { let patches = "draw_patches"; let indirect = "draw_patches_indirect"; assert_eq!( @@ -1146,23 +1177,31 @@ fn answer_as_plain_metal(path: Path) { e.set_tessellation_factor_scale(taken); } for points in [0, 3] { + fresh(e)?; assert_eq!(draw(e, points), Ok(())); + fresh(e)?; assert_eq!( e.draw_patches_indirect(points, None, 0, &arguments, 0), Ok(()) ); } + fresh(e)?; assert_eq!(e.draw_patches(1, 0, 1, None, 0, 0, 0), Ok(())); + fresh(e)?; assert_eq!(e.draw_patches(1, 0, 0, None, 0, 1, 0), Ok(())); + fresh(e)?; assert_eq!(e.draw_patches_indirect(1, None, 0, &arguments, 2), Ok(())); assert_eq!( e.draw_patches_indirect(1, None, 0, &arguments, 4), invalid(indirect, DrawProblem::IndirectBufferRange) ); + fresh(e)?; assert_eq!(e.draw_primitives(PrimitiveType::Point, 0, 1, 1, 0), Ok(())); // A patch index buffer's offset off a multiple of 4 (read from 0, patch 0), and a // direct draw's indices past the buffer (Metal probes on an M4). + fresh(e)?; assert_eq!(e.draw_patches(1, 0, 1, Some(&index), 2, 1, 0), Ok(())); + fresh(e)?; assert_eq!( e.draw_patches_indirect(1, Some(&index), 2, &arguments, 0), Ok(()) @@ -1179,11 +1218,21 @@ fn answer_as_plain_metal(path: Path) { ) ); // The factors stayed 2 at offset 0; patch 0 drawn through its index. + fresh(e)?; e.draw_patches(1, 0, 1, Some(&index), 4, 1, 0)?; + fresh(e)?; draw(e, 1) }) .unwrap(); - assert_eq!(cells(&marks), TWOS, "after the refusals on {name}"); + assert!(cells(&refused).is_empty(), "the refused draws on {name}"); + let mut marked: Vec = (drawn.iter()) + .inspect(|marks| writes.drew_patches(marks, 0..marks.length())) + .flat_map(cells) + .collect(); + writes.next_command_buffer(); + marked.sort_unstable(); + marked.dedup(); + assert_eq!(marked, TWOS, "after the refusals on {name}"); let marks = lane.buffer(&vec![0; MARK_WORDS * 4]); lane.pass(&plain, &marks, |e| { e.set_tessellation_factor_buffer(Some(&factors), 0, 0)?; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/predication.rs b/crates/metal2vulkan-validation/src/runtime_lane/predication.rs index 5f90d674f..fa214f661 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/predication.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/predication.rs @@ -27,6 +27,7 @@ //! buffer up to, the heap's bytes past a buffer placed in a heap, and zero, announced, where //! Metal reads memory unrelated to the buffer. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::host_memory::Seen; use super::rebind_reach::{buffer_len, buffer_over, deallocated, pages}; use super::rebinds::rebind; @@ -314,7 +315,12 @@ impl Streams { /// encodes a blit (the next command opens a serial encoder, as one with no encoder open does). /// The tags that ran, each once, and the answers, of a command buffer that completed. pub(crate) fn run(streams: &Streams, script: &str) -> (Vec, String) { - let ran = run_counted(streams, script); + completed(script, run_counted(streams, script), &streams.marks) +} + +/// The tags that ran, each once, and the answers, of `script`'s run `ran` into `marks`, which +/// completed with nothing refused. +fn completed(script: &str, ran: Counted, marks: &Marks) -> (Vec, String) { if let Some(error) = ran.refused { panic!("{script}: refused {error:?}"); } @@ -323,7 +329,7 @@ pub(crate) fn run(streams: &Streams, script: &str) -> (Vec, String) { (CommandBufferStatus::Completed, None), "{script}" ); - (streams.marks.ran(), ran.answers) + (marks.ran(), ran.answers) } /// What a stream's command buffer ran ([`run_counted`]). @@ -335,6 +341,10 @@ struct Counted { answers: String, /// The first record the runtime refused, which recorded nothing. refused: Option, + /// The log word each dispatch the stream encodes writes, once per dispatch token, in order: + /// `prd_mark` adds 1 to word `offset + t`, `prd_put` writes word `offset`, where `offset` is + /// buffer 1's, in words. + written: Vec, } /// [`run`]'s stream, with these for loops that count, as the Metal probe's: `w[@k]` starts a @@ -350,7 +360,28 @@ fn run_counted(streams: &Streams, script: &str) -> Counted { let mut open: Option = None; let mut answers = String::new(); let mut refused = None; + // What a dispatch with the state set writes: whether it is `prd_put`'s, its bytes' value and + // buffer 1's offset in words ([`Counted::written`]). + let (mut puts, mut value, mut offset) = (false, 0u64, 0u64); + let mut written = Vec::new(); for token in script.split_whitespace() { + let tagged = |token: &str| token[1..].parse::().ok(); + match token { + "t" => written.push(if puts { offset } else { offset + value }), + _ if token.starts_with(['T', 'G', 'H', 'b']) => { + (puts, value, offset) = (false, tagged(token).unwrap_or(0), 0); + if !token.starts_with('b') { + written.push(value); + } + } + _ if token.starts_with('Q') => { + (puts, value, offset) = (true, 0, tagged(token).unwrap_or(0)); + written.push(offset); + } + _ if token.starts_with('y') => value = tagged(token).unwrap_or(0), + _ if token.starts_with('o') => offset = tagged(token).unwrap_or(0), + _ => {} + } match token { "|" | "%" => { if let Some(encoder) = open.take() { @@ -469,6 +500,7 @@ fn run_counted(streams: &Streams, script: &str) -> Counted { counts: marks.counts(), answers, refused, + written, } } @@ -619,16 +651,25 @@ pub(crate) fn measured_streams() -> Vec<(&'static str, &'static str, Vec, & } /// Every measured stream runs the marks Metal ran, each once, and its Ends answer what Metal's -/// answered. +/// answered. Each dispatch token writes its own log word, where the stream names each word once +/// ([`layer_reported_nothing_but_apart_writes`]: a concurrent encoder's dispatches, which Metal +/// leaves unordered, writing words of one 16-byte block). #[test] fn streams_run_what_metal_ran() { - on_device(|device| { + on_device_noted(|device, messages| { let streams = Streams::new(device); let measured = measured_streams(); assert!(measured.len() >= 600, "{}", measured.len()); let mut wrong = Vec::new(); for (name, script, ran, answers) in &measured { - let got = run(&streams, script); + let mut writes = NotedWrites::new(messages); + let counted = run_counted(&streams, script); + for word in &counted.written { + writes.dispatched(&streams.marks.log, 4 * word..4 * word + 4); + } + let claim = format!("{name} `{script}`"); + layer_reported_nothing_but_apart_writes(messages, &claim, &writes); + let got = completed(script, counted, &streams.marks); if got != (ran.clone(), answers.to_string()) { wrong.push(format!( "{name} `{script}`: ran {:?} answered {:?}, Metal ran {ran:?} answered \ diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs index 9fa2863c7..0cde055e4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs @@ -38,6 +38,7 @@ //! whose signaller first reads what the frame writes (the buffer its draws write, or a texture //! over the `Private` buffer its color target lies over), reading it as it stood before. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::degrade_notices::{ assert_made_once, forced, made_render_kinds, on_device, on_device_with, shared_in_system_memory, }; @@ -57,6 +58,7 @@ use crate::candidate::runtime_case::render_pipeline_descriptor; use crate::case::indirect_commands::metal_primitive_type; use metal2vulkan::bind::DrawCall; use metal2vulkan::bind::ReplayFaults; +use metal2vulkan::device::VkFeature; use metal2vulkan::metal::TextureUsage; use metal2vulkan::metal::{ IndexType, IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, @@ -213,6 +215,23 @@ pub(super) struct Drawn { pub(super) base: usize, } +impl Drawn { + /// The bytes of `out` the draw writes, from its first word to its last: the layer takes each + /// draw as writing `out` from its window on ([`layer_reported_nothing_but_apart_writes`]). + pub(super) fn bytes(&self) -> std::ops::Range { + let word = |iid: usize, vid: usize| (self.window * WINDOW + 16 * iid + vid) as u64 * 4; + let last = (self.base + self.instances - 1, self.start + self.count - 1); + word(self.base, self.start)..word(last.0, last.1) + 4 + } +} + +/// The bytes of `out`'s window `window`: what a draw over it writes, of fewer than 16 vertices +/// and 4 instances. +pub(super) fn window_bytes(window: usize) -> std::ops::Range { + let start = (window * WINDOW * 4) as u64; + start..start + (WINDOW * 4) as u64 +} + /// `out` after `draws`, zero where none wrote. pub(super) fn expected(draws: &[Drawn]) -> Vec { let mut out = vec![0; WINDOWS * WINDOW]; @@ -339,7 +358,25 @@ fn commands_draw_as_their_records_stand_at_commit() { .command(&icb, 3, 2) .draw_primitives(PrimitiveType::Point, 2, 3, 2, 1) .unwrap(); + // Each draw's own words: the encoder's two over window 3, commands 0 and 3. + let mut writes = NotedWrites::new(messages); + for (window, start, count, instances, base) in [ + (3, 0, 2, 1, 0), + (0, 0, 4, 1, 0), + (2, 2, 3, 2, 1), + (3, 2, 2, 1, 0), + ] { + let drawn = Drawn { + window, + start, + count, + instances, + base, + }; + writes.drew(&setup.out, drawn.bytes()); + } complete(&command_buffer); + layer_reported_nothing_but_apart_writes(messages, "the execution's draws", &writes); let draws = [ Drawn { window: 0, @@ -378,8 +415,9 @@ fn commands_draw_as_their_records_stand_at_commit() { /// (`an_execution_under_a_state_without_support_faults_its_encoder`). #[test] fn inheriting_commands_draw_with_the_encoder_s_state_at_the_call() { - on_device(|device, _| { + on_device(|device, messages| { let setup = Setup::new(device); + let mut writes = NotedWrites::new(messages); let mut inheriting = IndirectCommandBufferDescriptor::new(); inheriting.command_types = IndirectCommandType::DRAW; inheriting.inherit_pipeline_state = true; @@ -429,6 +467,11 @@ fn inheriting_commands_draw_with_the_encoder_s_state_at_the_call() { base: 0, }, ]; + // The command's draw and the encoder's, each its own words. + for drawn in &draws { + writes.drew(&setup.out, drawn.bytes()); + } + layer_reported_nothing_but_apart_writes(messages, "the execution's draws", &writes); assert_eq!(setup.output(), expected(&draws)); }); } @@ -552,10 +595,15 @@ fn both_draws() -> IndirectCommandBufferDescriptor { /// draw). Windows 0 and 1 are the commands', 2 and 3 the encoder's own draws after them. #[test] fn commands_of_private_types_draw_as_the_encoder_s_draws() { - on_device_with(at_plan, |device, _| { + on_device_with(at_plan, |device, messages| { let indices = permuted(device); for (primitive_type, reached) in PRIVATE { let setup = Setup::new(device); + // Each draw writes in a window of its own. + let mut writes = NotedWrites::new(messages); + for window in 0..4 { + writes.drew(&setup.out, window_bytes(window)); + } let icb = icb(device, &both_draws(), 2); setup .command(&icb, 0, 0) @@ -586,6 +634,8 @@ fn commands_of_private_types_draw_as_the_encoder_s_draws() { .unwrap(); encoder.end_encoding().unwrap(); complete(&command_buffer); + let claim = format!("{primitive_type:?}'s draws"); + layer_reported_nothing_but_apart_writes(messages, &claim, &writes); let direct: Vec = (0..reached).collect(); let indexed: Vec = PERMUTED[..reached] .iter() @@ -613,10 +663,12 @@ fn commands_of_private_types_draw_as_the_encoder_s_draws() { /// count faults it (`PageFault`), its encoder and every one after it running nothing, the command /// before it included, and the encoder before running; a direct one of 2 vertices draws nothing, /// and the rest runs. Window 3 is the encoder's before, 0 the command before the draw, 1 the -/// draw's, 2 the encoder's after; each on a queue of its own (a queue's second fault revokes it). +/// draw's, 2 the encoder's after (its first two vertices) and the next encoder's (the two after +/// them); each on a queue of its own (a queue's second fault revokes it). Each draw writes its own +/// bytes of `out` ([`layer_reported_nothing_but_apart_writes`]). #[test] fn a_command_of_type_nine_fails_its_command_buffer_as_the_encoder_s_draw_does() { - on_device_with(at_plan, |device, _| { + on_device_with(at_plan, |device, messages| { let indices = permuted(device); let nine = DrawPrimitiveType::Nine; let cases = [ @@ -639,6 +691,25 @@ fn a_command_of_type_nine_fails_its_command_buffer_as_the_encoder_s_draw_does() ]; for (label, indexed, error) in cases { let setup = Setup::new(device); + let window = |window, start, count| Drawn { + window, + start, + count, + instances: 1, + base: 0, + }; + // The encoders' draws and the command before the draw, each its own words; the + // draw's, which runs nothing, its window. + let mut writes = NotedWrites::new(messages); + for drawn in [ + window(3, 0, 2), + window(0, 0, 4), + window(2, 0, 2), + window(2, 2, 2), + ] { + writes.drew(&setup.out, drawn.bytes()); + } + writes.drew(&setup.out, window_bytes(1)); let icb = icb(device, &both_draws(), 2); setup .command(&icb, 0, 0) @@ -662,7 +733,7 @@ fn a_command_of_type_nine_fails_its_command_buffer_as_the_encoder_s_draw_does() .unwrap(); let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); - let points = |window: usize, execute: bool| { + let points = |window: usize, start: u32, execute: bool| { let mut encoder = command_buffer.render_command_encoder(&pass()).unwrap(); setup.resident(&mut encoder); encoder @@ -678,24 +749,18 @@ fn a_command_of_type_nine_fails_its_command_buffer_as_the_encoder_s_draw_does() } setup.bind(&mut encoder, window); encoder - .draw_primitives(PrimitiveType::Point, 0, 2, 1, 0) + .draw_primitives(PrimitiveType::Point, start, 2, 1, 0) .unwrap(); encoder.end_encoding().unwrap(); }; - points(3, false); - points(2, true); - points(2, false); + points(3, 0, false); + points(2, 0, true); + points(2, 2, false); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); let label = format!("{label} on {}", device.name()); + layer_reported_nothing_but_apart_writes(messages, &label, &writes); assert_eq!(command_buffer.error(), error, "{label}"); - let window = |window, count| Drawn { - window, - start: 0, - count, - instances: 1, - base: 0, - }; let drawn = match error { Some(_) => { assert_eq!( @@ -703,7 +768,7 @@ fn a_command_of_type_nine_fails_its_command_buffer_as_the_encoder_s_draw_does() CommandBufferStatus::Error, "{label}" ); - expected(&[window(3, 2)]) + expected(&[window(3, 0, 2)]) } None => { assert_eq!( @@ -711,7 +776,7 @@ fn a_command_of_type_nine_fails_its_command_buffer_as_the_encoder_s_draw_does() CommandBufferStatus::Completed, "{label}" ); - expected(&[window(3, 2), window(0, 4), window(2, 2)]) + expected(&[window(3, 0, 2), window(0, 0, 4), window(2, 0, 4)]) } }; assert_eq!(setup.output(), drawn, "{label}"); @@ -1145,7 +1210,8 @@ fn a_host_step_waiting_for_a_later_signal_that_reads_its_target_s_buffer_ends() /// completion, so the step compiled nothing; the commit settled the draws' pipeline with no /// buffer of the commands bound. Nor does it count one across the commit (the coordinator's ruling /// of 2026-10-07): the state's creation compiled the variant, and the commit only looked it up. The -/// same commands the CPU wrote, drawn at commit, take the bound form. +/// same commands the CPU wrote, drawn at commit, take the bound form. Each command's draw writes +/// its own words of `out` ([`layer_reported_nothing_but_apart_writes`]). #[test] fn a_host_step_draws_on_what_its_commit_compiled() { on_device(|device, messages| { @@ -1160,6 +1226,21 @@ fn a_host_step_draws_on_what_its_commit_compiled() { instances: 1, base: 0, }; + // Command `i` draws vertices `4i..4i + 4` of window 0. + let note = |out: &Buffer| { + let mut writes = NotedWrites::new(messages); + for index in 0..commands as usize { + let command = Drawn { + window: 0, + start: 4 * index, + count: 4, + instances: 1, + base: 0, + }; + writes.drew(out, command.bytes()); + } + writes + }; let queue = device.new_command_queue().unwrap(); // Whether each command's draw reached its buffers at their device addresses. let large = |command_buffer: &CommandBuffer| { @@ -1178,6 +1259,7 @@ fn a_host_step_draws_on_what_its_commit_compiled() { .draw_primitives(PrimitiveType::Point, 4 * index, 4, 1, 0) .unwrap(); } + let writes = note(&setup.out); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.render_command_encoder(&pass()).unwrap(); setup.resident(&mut encoder); @@ -1186,6 +1268,7 @@ fn a_host_step_draws_on_what_its_commit_compiled() { .unwrap(); encoder.end_encoding().unwrap(); complete(&command_buffer); + layer_reported_nothing_but_apart_writes(messages, "the CPU's records' draws", &writes); assert_eq!(setup.output(), expected(&[drawn()]), "drawn at commit"); assert_eq!(large(&command_buffer), vec![false; commands as usize]); @@ -1197,6 +1280,7 @@ fn a_host_step_draws_on_what_its_commit_compiled() { } let arguments = buffer_with(device, &icb.gpu_resource_id().0.to_le_bytes()).unwrap(); let event = device.new_shared_event().unwrap(); + let writes = note(&setup.out); let command_buffer = queue.command_buffer().unwrap(); command_buffer .encode_wait_for_event(EventRef::from(&event), 1) @@ -1228,6 +1312,7 @@ fn a_host_step_draws_on_what_its_commit_compiled() { ); event.set_signaled_value(1); indirect_host_steps::wait(&command_buffer); + layer_reported_nothing_but_apart_writes(messages, "the kernel's records' draws", &writes); let completed = device.shader_cache_statistics(); assert_eq!( (completed.hits, completed.misses), @@ -1501,11 +1586,22 @@ fn an_indexed_draw_reads_from_its_offset_s_low_32_bits() { /// beside a draw of primitives. An index buffer no encoder made resident draws, as Metal's did /// there (a buffer of its own, which the command buffer's resident set holds); one placed in a heap /// no encoder of the command buffer used misses: that command runs nothing, its neighbour runs, and -/// the execution report counts it. +/// the execution report counts it. Each command's draw writes its own words of `out`, from its +/// first vertex to its last ([`layer_reported_nothing_but_apart_writes`]). #[test] fn indexed_commands_draw_their_indices() { on_device(|device, messages| { let setup = Setup::new(device); + let over = |window, start, count, instances, base| { + let drawn = Drawn { + window, + start, + count, + instances, + base, + }; + drawn.bytes() + }; let mut descriptor = descriptor(); descriptor.command_types = IndirectCommandType::DRAW.union(IndirectCommandType::DRAW_INDEXED); @@ -1546,6 +1642,15 @@ fn indexed_commands_draw_their_indices() { .command(&icb, 2, 2) .draw_primitives(PrimitiveType::Point, 0, 2, 1, 0) .unwrap(); + // Vertices 1, 3 and 5 of instances 1 and 2; 2, 5 and 9 of instance 0; 0 and 1. + let mut writes = NotedWrites::new(messages); + for bytes in [ + over(0, 1, 5, 2, 1), + over(1, 2, 8, 1, 0), + over(2, 0, 2, 1, 0), + ] { + writes.drew(&setup.out, bytes); + } let queue = device.new_command_queue().unwrap(); let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.render_command_encoder(&pass()).unwrap(); @@ -1562,6 +1667,7 @@ fn indexed_commands_draw_their_indices() { encoder.execute_commands_in_buffer(&icb, 0..3).unwrap(); encoder.end_encoding().unwrap(); complete(&command_buffer); + layer_reported_nothing_but_apart_writes(messages, "the indexed commands' draws", &writes); let drawn = expected_vertices(&[ (0, &[5, 1, 3], 1..3), (1, &[5, 2, 9], 0..1), @@ -1586,6 +1692,11 @@ fn indexed_commands_draw_their_indices() { 0, ) .unwrap(); + // Vertices 0 to 2 of window 3, where the command draws; 0 and 1 of window 2. + let mut writes = NotedWrites::new(messages); + for bytes in [over(3, 0, 3, 1, 0), over(2, 0, 2, 1, 0)] { + writes.drew(&setup.out, bytes); + } let command_buffer = queue.command_buffer().unwrap(); let mut encoder = command_buffer.render_command_encoder(&pass()).unwrap(); setup.resident(&mut encoder); @@ -1595,6 +1706,7 @@ fn indexed_commands_draw_their_indices() { command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + layer_reported_nothing_but_apart_writes(messages, "a stray command's draws", &writes); command_buffer.execution_report().unwrap() }; let report = run_stray(&placed(&heap, &stray_words)); @@ -2156,8 +2268,8 @@ fn a_render_execution_s_range_is_refused_where_metal_s_read_is_not_the_copy_s() /// One command of [`indexed_patch_commands_draw_as_metal_s_did`]: the pipeline's index type /// (`None`: no index type), whether it is indexed (with its control-point index buffer's words, /// 16-bit where `half`, the bytes before them and its offset, `None` for a null buffer) or plain, -/// its control points, patch start and count, and its patch index buffer's words and the bytes -/// before them, its offset. +/// its control points, patch start and count, its patch index buffer's words and the bytes +/// before them, its offset, and the bytes of the marks it may write. struct PatchCommand { index_type: TessellationControlPointIndexType, points: Option>, @@ -2166,10 +2278,12 @@ struct PatchCommand { count: u64, patch_indices: Option<&'static [u32]>, patch_pad: u64, + marks: std::ops::Range, } impl PatchCommand { - /// An indexed command of a 32-bit pipeline: two patches through `points` from 0. + /// An indexed command of a 32-bit pipeline: two patches through `points` from 0, which may + /// write every mark. const fn indexed(points: &'static [u32]) -> PatchCommand { PatchCommand { index_type: TessellationControlPointIndexType::UInt32, @@ -2179,6 +2293,7 @@ impl PatchCommand { count: 2, patch_indices: None, patch_pad: 0, + marks: 0..16, } } } @@ -2199,7 +2314,10 @@ const REVERSED: &[u32] = &[9, 10, 11, 6, 7, 8, 3, 4, 5, 0, 1, 2]; /// an M4 alike), and a patch index offset that is not a multiple of 4 reads them from the offset /// rounded down to one. A control-point index buffer of its own that no encoder made resident is /// reached; one placed in a heap no encoder of the command buffer used misses. A device without -/// tessellation shaders refuses the pipeline, reported as its refusal. +/// tessellation shaders refuses the pipeline, reported as its refusal. The side-by-side commands +/// write marks of their own, which the layer takes as one buffer's bound range: the test notes +/// each command's marks, a draw's where the device tessellates and a patch draw's where it +/// emulates ([`layer_reported_nothing_but_apart_writes`]). #[test] fn indexed_patch_commands_draw_as_metal_s_did() { indexed_patch_commands_draw_as_metal_s_did_on(Path::Native); @@ -2213,8 +2331,11 @@ fn emulated_indexed_patch_commands_draw_as_metal_s_did() { fn indexed_patch_commands_draw_as_metal_s_did_on(path: Path) { use TessellationControlPointIndexType as T; - on_device_with(options_of(path), |device, _| { + on_device_with(options_of(path), |device, messages| { let lane = Lane::new(device.clone()); + let tessellates = (device.compile_device().profile().enabled().features) + .contains(&VkFeature::TessellationShader); + let mut writes = NotedWrites::new(messages); let mut states = Vec::new(); for index_type in [T::None, T::UInt16, T::UInt32] { let mut descriptor = lane.descriptor(index_type); @@ -2253,9 +2374,12 @@ fn indexed_patch_commands_draw_as_metal_s_did_on(path: Path) { IndirectCommandType::DRAW_PATCHES.union(IndirectCommandType::DRAW_INDEXED_PATCHES); descriptor.inherit_buffers = true; // Run `commands` in one execution, `resident` saying whether their buffers are made - // resident, their control-point index buffers placed in `heap` where it is given: the - // marks and the execution report. - let run = |commands: &[PatchCommand], resident: bool, heap: Option<&Heap>| { + // resident, their control-point index buffers placed in `heap` where it is given, their + // marks noted in `writes`: the marks and the execution report. + let run = |commands: &[PatchCommand], + resident: bool, + heap: Option<&Heap>, + writes: &mut NotedWrites| { let icb = icb(device, &descriptor, commands.len() as u64); let mut buffers = vec![factors.clone()]; for (index, c) in commands.iter().enumerate() { @@ -2350,6 +2474,13 @@ fn indexed_patch_commands_draw_as_metal_s_did_on(path: Path) { command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + for c in commands { + match tessellates { + true => writes.drew(&marks, c.marks.clone()), + false => writes.drew_patches(&marks, c.marks.clone()), + } + } + writes.next_command_buffer(); let bytes = read_buffer(&marks, 0, 16).unwrap(); let marks: Vec = bytes .as_chunks::<4>() @@ -2449,10 +2580,12 @@ fn indexed_patch_commands_draw_as_metal_s_did_on(path: Path) { points: None, start: 2, count: 1, + marks: 8..12, ..PatchCommand::indexed(REVERSED) }, PatchCommand { count: 1, + marks: 12..16, ..PatchCommand::indexed(REVERSED) }, ], @@ -2475,7 +2608,7 @@ fn indexed_patch_commands_draw_as_metal_s_did_on(path: Path) { ), ]; for (name, commands, expected) in cases { - let (marks, report) = run(&commands, true, None); + let (marks, report) = run(&commands, true, None, &mut writes); assert_eq!(marks, expected, "{name}"); assert!(!report.replay_fault, "{name}"); assert_eq!(report.resident_misses, 0, "{name}"); @@ -2488,19 +2621,21 @@ fn indexed_patch_commands_draw_as_metal_s_did_on(path: Path) { points: Some(Some((&[0, 9, 0, 10, 0, 11, 0, 6, 0, 7, 0, 8], true, 2))), ..PatchCommand::indexed(REVERSED) }; - let (marks, report) = run(&[misaligned], true, None); + let (marks, report) = run(&[misaligned], true, None, &mut writes); assert_eq!(marks, ["a000009a", "0", "0", "a1010b67"]); assert!(!report.replay_fault); assert_eq!(report.resident_misses, 0); // A control-point index buffer of its own that no encoder made resident is reached; one // placed in a heap no encoder used misses. - let (marks, report) = run(&[PatchCommand::indexed(REVERSED)], false, None); + let (marks, report) = run(&[PatchCommand::indexed(REVERSED)], false, None, &mut writes); assert_eq!(marks, ["0", "0", "a1010678", "a00009ab"]); assert_eq!(report.resident_misses, 0); let heap = shared_heap(device); - let (marks, report) = run(&[PatchCommand::indexed(REVERSED)], false, Some(&heap)); + let one = [PatchCommand::indexed(REVERSED)]; + let (marks, report) = run(&one, false, Some(&heap), &mut writes); assert_eq!(marks, ["0"; 4]); assert_eq!(report.resident_misses, 1); + layer_reported_nothing_but_apart_writes(messages, "the patch commands' draws", &writes); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_gpu_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_gpu_executions.rs index 3013d7d9b..48f8e7a7d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_gpu_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_gpu_executions.rs @@ -27,6 +27,7 @@ //! - a record past the descriptor's bind count sets the sticky encoding fault: nothing draws, and //! the execution report says why. +use super::apart_writes::{layer_reported_nothing_but_apart_writes, NotedWrites}; use super::degrade_notices::on_device_with; use super::degrade_notices::{assert_made_once, on_device}; use super::indirect_host_steps::{self, complete, HOST_STEPS}; @@ -439,7 +440,8 @@ fn facts_that_grow_before_the_batch_is_ready_take_the_host_step() { /// `commit` records from the CPU's records: `commit` calls it with each command of the range /// before it returns, where the CPU drew points and the check looks for them; where the CPU drew /// triangles alone, or the check looks for nothing, never. The commands draw the same each time, -/// and no host step runs. +/// and no host step runs. Each command's draw writes its own words of `out` +/// ([`layer_reported_nothing_but_apart_writes`]). #[test] fn commit_checks_the_cpu_s_records_where_the_check_may_see_something() { on_device_with(at_plan, |device, messages| { @@ -451,6 +453,10 @@ fn commit_checks_the_cpu_s_records_where_the_check_may_see_something() { (PrimitiveType::Point, nothing), ] { let setup = Setup::new(device); + let mut writes = NotedWrites::new(messages); + for window in 0..4 { + writes.drew(&setup.out, drawn(window, 0, 3).bytes()); + } let icb = icb(device, &inheriting(1), 4); for index in 0..4 { buffers(&setup, &icb, index, index as usize); @@ -479,6 +485,7 @@ fn commit_checks_the_cpu_s_records_where_the_check_may_see_something() { let at_commit = seen.lock().unwrap().clone(); indirect_host_steps::wait(&command_buffer); let at = format!("{primitive_type:?}, {needs:?}"); + layer_reported_nothing_but_apart_writes(messages, &at, &writes); assert!(!icb.gpu_written(), "{at}"); assert_eq!(read, 4, "{at}: the commit read each record"); let every: Vec = match primitive_type == PrimitiveType::Point && needs == points { @@ -499,12 +506,21 @@ fn commit_checks_the_cpu_s_records_where_the_check_may_see_something() { /// CPU draws 2 more vertices in command 1 after the commit, before the batch is submitted (it waits /// for an event the test signals after the write), the host step records the pass again from the /// records then (each record read again) and command 1 draws 5 vertices; without the write, the -/// commit's recording draws 3. Nothing is announced. +/// commit's recording draws 3. Nothing is announced. Each command's draw writes its own words of +/// `out` ([`layer_reported_nothing_but_apart_writes`]). #[test] fn the_cpu_s_writes_after_the_commit_draw_where_the_batch_waits() { on_device_with(at_plan, |device, messages| { for write in [false, true] { let setup = Setup::new(device); + let count = |window: usize| match (write, window) { + (true, 1) => 5, + _ => 3, + }; + let mut writes = NotedWrites::new(messages); + for window in 0..4 { + writes.drew(&setup.out, drawn(window, 0, count(window)).bytes()); + } let icb = icb(device, &inheriting(1), 4); for index in 0..4 { buffers(&setup, &icb, index, index as usize); @@ -535,13 +551,10 @@ fn the_cpu_s_writes_after_the_commit_draw_where_the_batch_waits() { event.set_signaled_value(1); indirect_host_steps::wait(&command_buffer); }); + layer_reported_nothing_but_apart_writes(messages, &format!("write {write}"), &writes); assert!(!icb.gpu_written(), "write {write}"); let reads = if write { 8 } else { 4 }; assert_eq!(read, reads, "write {write}: the records read"); - let count = |window: usize| match (write, window) { - (true, 1) => 5, - _ => 3, - }; let draws: Vec = (0..4) .map(|window| drawn(window, 0, count(window))) .collect(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/stage_races.rs b/crates/metal2vulkan-validation/src/runtime_lane/stage_races.rs new file mode 100644 index 000000000..1f0a5e972 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/stage_races.rs @@ -0,0 +1,265 @@ +//! The validation layer's hazards between a draw's vertex stage and an earlier draw's fragment +//! stage of one render pass, on a buffer both reach, where the device announced the difference +//! that race is. A lane claim that lets those pass, and nothing wider. +//! +//! Metal runs a pass's vertex functions before its fragments: a probe (an M3 Max, and an M4) read, +//! from a later draw's vertex function, the bytes from before an earlier draw's fragment writes, +//! and an earlier fragment read a later vertex function's write (`pass_start_reads.rs`). Vulkan +//! orders a pass's draws only through the barriers the pass records. Where the runtime keeps no +//! copy of the bytes from before the pass, its device answers the vertex stage's access in its +//! own order, and it announces that: +//! +//! - **`in-place-vertex-reads`**: a vertex stage reads in place bytes a fragment stage of its pass +//! wrote (a vertex stage of the pass wrote them too, so no copy from before the pass holds what +//! the reader reads): the layer reports a `READ_AFTER_WRITE` whose later access is the vertex +//! stage's read. +//! - **`fragments-before-geometry`**: a vertex stage writes bytes a fragment stage of its pass read +//! or wrote: the layer reports a `WRITE_AFTER_READ` or `WRITE_AFTER_WRITE` whose later access is +//! the vertex stage's write and whose earlier one the fragment stage's. +//! +//! A test names each buffer whose such accesses it makes +//! ([`layer_reported_nothing_but_announced_stage_races`]). A message passes only when it is +//! reported as the later draw was recorded (both commands draws of one `VkCommandBuffer`), on a +//! buffer the test named, its later access the vertex stage's, of the kind above whose notice the +//! device announced, and, for a write, its earlier access the fragment stage's. It passes with a +//! `LAYER-STAGE-RACE` line. Everything else fails as +//! [`layer_reported_nothing`] fails it: a racing form, an image, a command that is not a draw, a +//! buffer the test did not name, a later access of another stage, and either kind where its notice +//! was not announced. +//! +//! [`layer_reported_nothing`]: super::layer_reported_nothing + +use crate::parity::sequences::hazards::{parse, Named}; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +use { + super::{LayerClaim, Messages}, + ash::vk::Handle as _, + metal2vulkan_runtime::{Buffer, DebugMessage, Degradation}, +}; + +/// The Vulkan commands the runtime records a Metal draw with, as the layer names them. +const DRAWS: &[&str] = &[ + "vkCmdDraw", + "vkCmdDrawIndexed", + "vkCmdDrawIndirect", + "vkCmdDrawIndexedIndirect", +]; + +/// How the layer names the later access's stage where a shader's access through a descriptor is +/// the later one. +const VERTEX_ACCESS: &str = " hazard detected. Shader stage VK_SHADER_STAGE_VERTEX_BIT "; + +/// How the layer begins naming the earlier access of a write's hazard, and its stage where it is +/// a fragment shader's. +const PRIOR: &str = "does not conflict with a prior "; +const FRAGMENT_STAGE: &str = "at VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT"; + +/// The notice a race of a hazard of id name `id_name` is announced by, where it is one: a vertex +/// stage's read after a write (`in-place-vertex-reads`), or its write after a read or a write +/// (`fragments-before-geometry`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Race { + InPlaceRead, + WriteBeforeFragments, +} + +impl Race { + fn of(id_name: &str) -> Option { + match id_name { + "SYNC-HAZARD-READ-AFTER-WRITE" => Some(Race::InPlaceRead), + "SYNC-HAZARD-WRITE-AFTER-READ" | "SYNC-HAZARD-WRITE-AFTER-WRITE" => { + Some(Race::WriteBeforeFragments) + } + _ => None, + } + } +} + +/// Whether the layer's message of id name `id_name` and text `text` passes against the buffers +/// `named` (their raw handles), where `announced` says whether the device announced each race's +/// notice (the module docs). +fn passes(named: &[u64], announced: impl Fn(Race) -> bool, id_name: &str, text: &str) -> bool { + let Some(race) = Race::of(id_name) else { + return false; + }; + let Some(hazard) = parse(id_name, text) else { + return false; + }; + let Named::Buffer(buffer) = hazard.memory else { + return false; + }; + let recorded = DRAWS + .iter() + .any(|draw| text.starts_with(&format!("{draw}(): "))); + let draws = DRAWS.contains(&hazard.later.as_str()) && DRAWS.contains(&hazard.earlier.as_str()); + // The earlier access, up to the sentence's end: "a prior read (...) at ." + let prior = (text.split_once(PRIOR)).map(|(_, prior)| prior.split('.').next().unwrap_or("")); + let fragment_prior = match race { + Race::InPlaceRead => true, + Race::WriteBeforeFragments => prior.is_some_and(|prior| prior.contains(FRAGMENT_STAGE)), + }; + recorded + && draws + && named.contains(&buffer) + && text.contains(VERTEX_ACCESS) + && fragment_prior + && announced(race) +} + +/// [`layer_reported_nothing`](super::layer_reported_nothing) of `claim`, but for the layer's +/// hazards between a vertex stage and an earlier fragment stage of one pass on one of `buffers` +/// whose notice the device announced, each of which passes with a `LAYER-STAGE-RACE` line (the +/// module docs). +/// +/// # Panics +/// +/// Where the layer reported anything else. +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +pub(super) fn layer_reported_nothing_but_announced_stage_races( + messages: &Messages, + claim: &str, + buffers: &[&Buffer], +) -> LayerClaim { + let reported = messages.take(); + let named: Vec = match reported.is_empty() { + true => Vec::new(), + // SAFETY: the handles are only compared with the layer's reports, never used. + false => (buffers.iter()) + .map(|buffer| unsafe { buffer.vk_buffer() }.0.as_raw()) + .collect(), + }; + let announced = |race| { + messages.announced(match race { + Race::InPlaceRead => Degradation::InPlaceVertexReads, + Race::WriteBeforeFragments => Degradation::FragmentsBeforeGeometry, + }) + }; + let test = std::thread::current().name().unwrap_or_default().to_owned(); + let rest: Vec = reported + .into_iter() + .filter(|message| { + if !passes(&named, announced, &message.id_name, &message.text) { + return true; + } + eprintln!( + "LAYER-STAGE-RACE {test}: passed, a race between a vertex stage and an earlier \ + fragment stage of its pass, announced: {} ({}): {}", + message.id_name, + message.id, + message.text.replace('\n', " ") + ); + false + }) + .collect(); + let stated = messages.state_layer_claim(claim); + assert!( + rest.is_empty(), + "{claim}: the validation layer reported\n{rest:#?}" + ); + stated +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The buffer the hazards below name. + const BUFFER: u64 = 0x4700_0000_0047; + + /// The in-place read as the layer 1.4.366 reported it on lavapipe + /// (`pass_start_reads::a_vertex_stage_reads_in_place_what_another_stage_of_its_pass_wrote`). + const IN_PLACE: &str = "vkCmdDraw(): READ_AFTER_WRITE hazard detected. Shader stage \ + VK_SHADER_STAGE_VERTEX_BIT reads VkBuffer 0x470000000047, which was previously written by \ + another vkCmdDraw command. The buffer is referenced by descriptor binding 0 \ + (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) from descriptor set 0 (VkDescriptorSet 0x0), \ + VkPipeline 0x7e000000007e. The current synchronization allows \ + VK_ACCESS_2_SHADER_READ_BIT|VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT accesses at \ + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT, but to prevent this hazard, it must allow \ + VK_ACCESS_2_UNIFORM_READ_BIT accesses at VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT."; + + /// The vertex stage's write after a fragment's read, as the layer 1.4.366 reported it on + /// lavapipe (`pass_start_reads::a_vertex_stage_s_write_after_a_fragment_s_access_is_announced`). + const WRITE_AFTER_FRAGMENT: &str = "vkCmdDraw(): WRITE_AFTER_READ hazard detected. Shader \ + stage VK_SHADER_STAGE_VERTEX_BIT writes to VkBuffer 0x470000000047, which was previously \ + read by another vkCmdDraw command. The buffer is referenced by descriptor binding 1 \ + (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) from descriptor set 0 (VkDescriptorSet 0x0), \ + VkPipeline 0x460000000046. No sufficient synchronization is present to ensure that a \ + write (VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT) at VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT \ + does not conflict with a prior read (VK_ACCESS_2_SHADER_STORAGE_READ_BIT) at \ + VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT."; + + const RAW: &str = "SYNC-HAZARD-READ-AFTER-WRITE"; + const WAR: &str = "SYNC-HAZARD-WRITE-AFTER-READ"; + + fn every(_: Race) -> bool { + true + } + + #[test] + fn announced_races_on_a_named_buffer_pass() { + assert!(passes(&[BUFFER], every, RAW, IN_PLACE)); + assert!(passes(&[BUFFER], every, WAR, WRITE_AFTER_FRAGMENT)); + } + + #[test] + fn a_race_whose_notice_was_not_announced_fails() { + let only = |announced: Race| move |race: Race| race == announced; + assert!(!passes( + &[BUFFER], + only(Race::WriteBeforeFragments), + RAW, + IN_PLACE + )); + assert!(!passes( + &[BUFFER], + only(Race::InPlaceRead), + WAR, + WRITE_AFTER_FRAGMENT + )); + assert!(!passes(&[BUFFER], |_| false, RAW, IN_PLACE)); + } + + #[test] + fn a_buffer_the_test_did_not_name_fails() { + assert!(!passes(&[], every, RAW, IN_PLACE)); + assert!(!passes( + &[0x5100_0000_0051], + every, + WAR, + WRITE_AFTER_FRAGMENT + )); + } + + #[test] + fn a_later_access_of_another_stage_fails() { + let fragment = + IN_PLACE.replace("VK_SHADER_STAGE_VERTEX_BIT", "VK_SHADER_STAGE_FRAGMENT_BIT"); + assert!(!passes(&[BUFFER], every, RAW, &fragment)); + let later = WRITE_AFTER_FRAGMENT + .replace("VK_SHADER_STAGE_VERTEX_BIT", "VK_SHADER_STAGE_FRAGMENT_BIT"); + assert!(!passes(&[BUFFER], every, WAR, &later)); + // A vertex stage's write after another vertex stage's read is no fragment's race. + let vertex_prior = WRITE_AFTER_FRAGMENT.replace( + "at VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT", + "at VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT", + ); + assert!(!passes(&[BUFFER], every, WAR, &vertex_prior)); + } + + #[test] + fn racing_forms_submissions_copies_and_images_fail() { + let racing = IN_PLACE.replace("READ_AFTER_WRITE", "READ_RACING_WRITE"); + assert!(!passes( + &[BUFFER], + every, + "SYNC-HAZARD-READ-RACING-WRITE", + &racing + )); + let submitted = format!("vkQueueSubmit(): {}", &IN_PLACE["vkCmdDraw(): ".len()..]); + assert!(!passes(&[BUFFER], every, RAW, &submitted)); + let copy = IN_PLACE.replace("another vkCmdDraw command", "vkCmdCopyBuffer"); + assert!(!passes(&[BUFFER], every, RAW, ©)); + let image = IN_PLACE.replace("VkBuffer 0x470000000047", "VkImage 0x470000000047"); + assert!(!passes(&[BUFFER], every, RAW, &image)); + } +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/sync_coverage.rs b/crates/metal2vulkan-validation/src/runtime_lane/sync_coverage.rs index 8a30dbd4a..5dd45046f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/sync_coverage.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/sync_coverage.rs @@ -395,8 +395,8 @@ fn a_shader_write_then_a_shader_read_of_one_untracked_buffer_in_one_concurrent_e } /// A layer false positive, byte by byte: a descriptor's range broader than its command's access -/// (the lanes' `argument_buffers` and `render_executions` reports; `argument_buffers` notes its -/// dispatches' words and lets the layer's writes after writes between them pass, `apart_writes`). +/// (the lane tests that note their dispatches', draws' and fills' bytes let the layer's writes +/// after writes between them pass, `apart_writes`). /// One serial compute encoder /// of tracked buffers dispatches the copy-word kernel three times over one 16-byte `block`: the /// first writes its word 0, the second its word 1, the third reads its word 2. The runtime's diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 0a5ae72df..36ca2c978 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -164,13 +164,14 @@ a layer the loader answers `VK_ERROR_LAYER_NOT_PRESENT` for and says so as the d claim of what the layer reported therefore states what it holds, against the layers the instance enabled and nothing else: where the layer was dropped the claim is not exercised, and the test prints `LANE-LAYER-ABSENT : ...` and a count per message list instead of passing on an empty -list. Four forms state it, and no lane test reads a message list for emptiness any other way: +list. Five forms state it, and no lane test reads a message list for emptiness any other way: | Form | The claim | |---|---| | `layer_reported_nothing_at_all(&messages)` | The widest claim, and the one the lane states oftenest: whatever the layer checked of the work so far, it reported nothing of it | | `layer_reported_nothing(&messages, claim)` | The same, of the narrower `claim` the test names, which leads the failure and the `LANE-LAYER-ABSENT` line | -| `layer_reported_nothing_but_apart_writes(&messages, claim, &writes)` (`runtime_lane::apart_writes`) | The same, but a write after write the layer reports between two dispatches on a buffer passes, with a `LAYER-APART-WRITES` line, where the test noted every dispatch write of that buffer as it placed it (`DispatchWrites`), two or more, and no two share a byte. The layer takes a dispatch's storage buffer as written over its descriptor's whole range, which the runtime binds wider than the bytes the kernel provably writes (from the offset alignment down, in 16-byte granules) and orders by (`sync_coverage::disjoint_words_of_one_block_are_a_hazard_to_the_layer_alone`); no order of writes that share no byte changes one. A read after a write, a write after a read, a draw's or a copy's access, and two noted writes of one byte fail as above | +| `layer_reported_nothing_but_apart_writes(&messages, claim, &writes)` (`runtime_lane::apart_writes`) | The same, but a write after write the layer reports on a buffer whose every write the test noted as it placed it (`NotedWrites`: a dispatch's, a draw's, a fill's, a bounded draw's or a patch draw's) passes in three cases. **Apart** (a `LAYER-APART-WRITES` line): two noted writes or more, each one Vulkan command's, no two sharing a byte. The layer takes a shader's storage buffer as written over its descriptor's whole range, which the runtime binds wider than the bytes the shader provably writes (from the offset alignment down, in 16-byte granules) and orders by (`sync_coverage::disjoint_words_of_one_block_are_a_hazard_to_the_layer_alone`); no order of writes that share no byte changes one. **Idle draw** (`LAYER-IDLE-DRAW`): the two `vkCmdDrawIndexedIndirect` of one draw the index bounds pass bounds, reported as recorded, one such draw noted per command buffer, on a device that announced `indirect-index-bounds-pass`: at most one of the two draws. **Idle chunk** (`LAYER-IDLE-CHUNK`): two `vkCmdDrawIndirect` chunk draws of emulated patch draws, reported as recorded, the patch draws of each command buffer noted apart, on a device that announced `emulated-tessellation-draws`: a test keeps each patch draw below `2^30` triangles and the scan writes a `vertexCount` of 0 past them, so at most one chunk of a draw draws. A read after a write, a write after a read, a copy's access, two noted writes of one byte, and either split form reported otherwise fail as above | +| `layer_reported_nothing_but_announced_stage_races(&messages, claim, &buffers)` (`runtime_lane::stage_races`) | The same, but a hazard between a later draw's vertex stage and an earlier draw's fragment stage of one pass, reported as recorded, on a buffer the test names, passes with a `LAYER-STAGE-RACE` line where the device announced the difference it is: a read after a write under `in-place-vertex-reads`, a write after a read or a write under `fragments-before-geometry`. Metal runs a pass's vertex functions before its fragments; Vulkan orders the draws only through the pass's barriers | | `nothing_reported_without_the_layer(&messages, claim)` | A device the test made without the validation layer, to time something: the claim is the driver's own messages and the runtime's, so the layer's absence takes nothing from it. It fails where such a device did ask for the layer after all | A host whose layer manifest names its library by a bare