diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index efc8b2aee..bb36e1aa3 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -216,7 +216,11 @@ so a block released meanwhile goes back to the pool only then. Placement is the is the slack past a buffer's length: the runtime writes no byte of a block outside the ranges of the buffers placed in it (a zero fill, a Managed buffer's copy-in and its device copy's zeroing each cover exactly the buffer's bytes), so what lies between and after them is as the consumer -left it. +left it. Vulkan reads an indirect dispatch's arguments only at a multiple of 4 of the block, and an +indexed draw's indices only at a multiple of their size; a Metal buffer starts at an aligned +address, where Metal's offset rules keep both so. A dispatch or draw whose arguments or indices a +consumer's placement puts at a byte that misses that multiple is refused +(`Refusal::ArgumentPlace`). ### The consumer's mappings diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 9b2fc0a30..fc780ce67 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -658,7 +658,8 @@ impl ComputeCommandEncoder { /// /// Err: as [`dispatch_threadgroups`](Self::dispatch_threadgroups); [`Refusal::OtherDevice`]; /// [`Refusal::IndirectOffset`] for an offset not a multiple of 4 or without 12 bytes after - /// it in the buffer. + /// it in the buffer; [`Refusal::ArgumentPlace`] for arguments at a byte of the buffer's block + /// that is not a multiple of 4, as a buffer placed at such a byte has. pub fn dispatch_threadgroups_with_indirect_buffer( &mut self, buffer: &Buffer, @@ -678,6 +679,13 @@ impl ComputeCommandEncoder { length: buffer.length(), })); } + let place = buffer.device_range().1 + offset; + if !place.is_multiple_of(4) { + return Err(Error::Refused(Refusal::ArgumentPlace { + place, + alignment: 4, + })); + } self.dispatch(Grid::Indirect(buffer, offset), threads_per_threadgroup) } diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 3489427cf..03734b382 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -617,6 +617,21 @@ pub enum Refusal { /// The buffer's length. length: u64, }, + /// An indirect dispatch's arguments, or an indexed draw's indices, at a byte of the block + /// the buffer lies in (its device copy's, for a Managed buffer with one) that is not a + /// multiple of 4, or of the index size: a buffer the consumer placed at such a byte, read at + /// an offset Metal takes. + /// + /// Basis: ours (`vkCmdDispatchIndirect` reads its arguments at a multiple of 4 in the + /// `VkBuffer`, and `vkCmdBindIndexBuffer` takes indices at a multiple of their size in the + /// memory; a Metal buffer starts at an aligned address, so Metal's offset rule alone keeps + /// both aligned there). + ArgumentPlace { + /// The byte of the block the arguments or indices start at. + place: u64, + /// The multiple Vulkan reads them at: 4, or the index size. + alignment: u64, + }, /// A viewport with a field that is NaN or infinite (but its origin's x, which draws nothing). /// /// Basis: metal-measured (an Apple M4, macOS 27.0.1: Metal's validation stops a NaN or @@ -1337,6 +1352,10 @@ impl fmt::Display for Refusal { f, "indices at offset {offset} of a {length}-byte buffer are misaligned or past its end" ), + Refusal::ArgumentPlace { place, alignment } => write!( + f, + "arguments at byte {place} of their block are not at a multiple of {alignment}" + ), Refusal::ViewportNotFinite => f.write_str("a viewport field is NaN or infinite"), Refusal::StencilAttachment => { f.write_str("a draw tests the stencil in a pass without a stencil attachment") diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index fba1fbcf6..8c606dc22 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -742,7 +742,9 @@ impl RenderCommandEncoder { /// Metal's. A draw of no indices or no instances records nothing. /// /// Err: as [`draw_primitives`](Self::draw_primitives); [`Refusal::OtherDevice`] for another - /// device's index buffer; [`Refusal::IndexBufferOffset`]. + /// device's index buffer; [`Refusal::IndexBufferOffset`]; [`Refusal::ArgumentPlace`] for + /// indices at a byte of the buffer's block that is not a multiple of the index size, as a + /// buffer placed at such a byte has. pub fn draw_indexed_primitives( &mut self, primitive_type: PrimitiveType, @@ -816,13 +818,15 @@ impl RenderCommandEncoder { })); } let (reached, at) = buffer.device_range(); + let place = at + offset; + if !place.is_multiple_of(size) { + return Err(Error::Refused(Refusal::ArgumentPlace { + place, + alignment: size, + })); + } let ty = metal2vulkan::metal::state::index_type(index_type); - Some(( - buffer, - reached, - at + offset, - vk::IndexType::from_raw(ty.as_raw()), - )) + Some((buffer, reached, place, vk::IndexType::from_raw(ty.as_raw()))) } }; // The vertex buffers the vertex descriptor reads. diff --git a/crates/metal2vulkan-rt/src/tests/compute.rs b/crates/metal2vulkan-rt/src/tests/compute.rs index 26462f8d6..4f19c3f7f 100644 --- a/crates/metal2vulkan-rt/src/tests/compute.rs +++ b/crates/metal2vulkan-rt/src/tests/compute.rs @@ -1,6 +1,7 @@ //! Compute encoders, under a device cfg on every device of the cfg's kind: dispatches over bound //! buffers and `set_bytes`, parameters past the push window -//! through the ring, indirect dispatch, barriers only at hazards in a serial encoder and only on +//! through the ring, indirect dispatch, indirect arguments read only at a multiple of 4 of their +//! block, barriers only at hazards in a serial encoder and only on //! request in a concurrent one, end barriers that reach the host only after Shared writes and //! signals, a dispatch of a kernel without effects that records nothing, and Metal's refusals. @@ -518,6 +519,55 @@ pub(crate) mod on_device { }); } + /// Vulkan reads indirect arguments only at a multiple of 4 of the `VkBuffer`: in a buffer the + /// consumer placed 2 bytes into its block, arguments at offsets Metal takes are refused + /// (`Refusal::ArgumentPlace`), and arguments in a buffer placed at byte 4100, a multiple of 4 + /// no Metal buffer starts at, are read where they lie. + #[test] + fn every_device_reads_indirect_arguments_only_at_a_multiple_of_4_of_their_block() { + each_device("compute_indirect_place", |name, _, device| { + let mut arena = Arena::new(&device); + let (a, b, o) = (arena.buffer(), arena.buffer(), arena.buffer()); + write_words(&a, |index| index); + write_words(&b, |index| 1000 * index); + let block = (device.take_block(MemoryClass::Shared, 8192)).expect("a Shared block"); + let placed = |at| (device.new_buffer(block.id, at, 256, Some(0))).expect("a buffer"); + let (off, on) = (placed(2), placed(4100)); + write_words(&on, |index| match index { + 4 => 4, + 5 | 6 => 1, + _ => 0, + }); + let state = add(&device); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + encoder.set_compute_pipeline_state(&state).expect("a state"); + for (slot, buffer) in [&a, &b, &o].into_iter().enumerate() { + encoder + .set_buffer(Some(buffer), 0, slot as u32) + .expect("a buffer"); + } + for offset in [0, 16] { + match encoder.dispatch_threadgroups_with_indirect_buffer(&off, offset, [16, 1, 1]) { + Err(Error::Refused(Refusal::ArgumentPlace { place, alignment })) => { + assert_eq!((place, alignment), (2 + offset, 4), "{name}: at {offset}"); + } + other => panic!("{name}: arguments at {offset}: {other:?}"), + } + } + encoder + .dispatch_threadgroups_with_indirect_buffer(&on, 16, [16, 1, 1]) + .expect("an indirect dispatch"); + encoder.end_encoding(); + run(name, &command_buffer); + let expected: Vec = (0..WORDS as u32).map(|index| 1001 * index).collect(); + assert_eq!(words(&o), expected, "{name}"); + }); + } + /// A dispatch of a kernel that writes no memory (`Interface::has_effects` false, from the /// translator's `PipelineInterface::writes_memory`) records nothing: given the step kernel's /// words under such an interface, a direct and an indirect dispatch leave its buffer as it was, diff --git a/crates/metal2vulkan-rt/src/tests/draw.rs b/crates/metal2vulkan-rt/src/tests/draw.rs index 0cef306b1..c3d763003 100644 --- a/crates/metal2vulkan-rt/src/tests/draw.rs +++ b/crates/metal2vulkan-rt/src/tests/draw.rs @@ -25,6 +25,8 @@ //! for every vertex and instance, from a base instance of 1. //! - a draw whose vertex buffer is bound off its argument's alignment is refused before //! anything is recorded, and the same buffers bound aligned draw. +//! - 32-bit indices at byte 2 of their block are refused before anything is recorded, and +//! 16-bit indices there draw. //! - what Metal refuses is refused, and what a draw does not build is a gap: no pipeline state, //! a pipeline state of other formats than the pass's, points, a depth test, a stencil test //! without a stencil attachment, a misaligned index offset, a non-finite viewport and a @@ -156,10 +158,15 @@ mod on_device { /// A buffer of `bytes`. fn of(&mut self, device: &Device, bytes: &[u8]) -> Buffer { + self.at(device, bytes, 0) + } + + /// A buffer of `bytes`, `skew` bytes past the place [`of`](Self::of) would take. + fn at(&mut self, device: &Device, bytes: &[u8], skew: u64) -> Buffer { let len = bytes.len() as u64; - let buffer = - (device.new_buffer(self.block.id, self.next, len, Some(0))).expect("a buffer"); - self.next += len.next_multiple_of(256); + let at = self.next + skew; + let buffer = (device.new_buffer(self.block.id, at, len, Some(0))).expect("a buffer"); + self.next += (skew + len).next_multiple_of(256); let contents = buffer.contents().expect("a Shared buffer"); // SAFETY: the range lies in the buffer, which is alive, and no GPU work uses it. unsafe { @@ -876,6 +883,76 @@ mod on_device { }); } + /// Vulkan binds indices only at a multiple of their size in the memory: in a buffer the + /// consumer placed 2 bytes into its block, 32-bit indices at offset 0, which Metal takes, are + /// refused before anything is recorded (`Refusal::ArgumentPlace`), and 16-bit indices there + /// draw the top half's triangle from where they lie; the pass is its two barriers and the + /// segment's end. + #[test] + fn every_device_takes_indices_only_at_a_multiple_of_their_size_in_their_block() { + let Some(library) = examples() else { + return; + }; + let d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + each_device("draw_index_place", |name, _, device| { + let state = state(name, &device, &d); + let mut buffers = Buffers::new(&device); + let (positions, colors) = vertices(&device, &mut buffers); + let indices = buffers.at(&device, &[0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0], 2); + let color = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET, + ); + let queue = device.new_command_queue(4).expect("a queue"); + let first = queue.command_buffer().expect("a command buffer"); + (first.record_for_test(&[], |_, _| {})).expect("a command buffer's commands"); + run(name, &first); + let counters = device.counters(); + settled(&device); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + draw(encoder.set_render_pipeline_state(&state)); + draw(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + draw(encoder.set_vertex_buffer(Some(&colors), 0, 1)); + let indexed = |index_type| IndexBuffer { + buffer: &indices, + offset: 0, + index_type, + }; + let triangle = PrimitiveType::Triangle; + match encoder.draw_indexed_primitives(triangle, 3, indexed(IndexType::UInt32), 1, 0, 0) + { + Err(Error::Refused(Refusal::ArgumentPlace { place, alignment })) => { + assert_eq!((place, alignment), (2, 4), "{name}: 32-bit indices"); + } + other => panic!("{name}: 32-bit indices at byte 2: {other:?}"), + } + draw(encoder.draw_indexed_primitives(triangle, 3, indexed(IndexType::UInt16), 1, 0, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.barriers - before.barriers, + after.passes - before.passes, + ), + (1, 3, 1), + "{name}: submissions, barriers, passes" + ); + let want = texels(|_, y| match y { + 0..4 => GREEN, + _ => BLACK, + }); + assert_eq!(read(&color, 4), want, "{name}: the texels"); + println!("{name}: 32-bit indices at byte 2 refused before recording; 16-bit ones drew"); + }); + } + /// What Metal refuses is refused, and what a draw does not build is a gap. #[test] fn every_device_refuses_the_draws_it_does_not_build() { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index b1adc30b6..437c9e5aa 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13688,6 +13688,7 @@ variant metal2vulkan-rt::PrecisionNote::UnmeasuredGroupSpeculation UnmeasuredGro variant metal2vulkan-rt::PrecisionNote::UnorderedFetchWithinDraw UnorderedFetchWithinDraw variant metal2vulkan-rt::PrecisionNote::VertexSimdgroupGrouping VertexSimdgroupGrouping variant metal2vulkan-rt::PrecisionNote::ViewBaseTexelOffset ViewBaseTexelOffset +variant metal2vulkan-rt::Refusal::ArgumentPlace ArgumentPlace { place: u64, alignment: u64 } variant metal2vulkan-rt::Refusal::AttachmentFormat AttachmentFormat { pixel_format: PixelFormat } variant metal2vulkan-rt::Refusal::AttachmentPlace AttachmentPlace { level: u32, slice: u32 } variant metal2vulkan-rt::Refusal::AttachmentUsage AttachmentUsage { pixel_format: PixelFormat } diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 40fc06bee..452dc361e 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,7 +37,7 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 54 | 54 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 55 | 55 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 20 | 20 | 0 | 0 | 0 | 0 | 0 | @@ -55,7 +55,7 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 23 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 24 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 7 | 3 | 0 | 0 | 0 | | The new runtime's `Gap` | 0 | 0 | 0 | 0 | 20 | 0 | 0 | 0 | @@ -668,6 +668,7 @@ Columns: | `AttachmentFormat` | A render pass color attachment of a depth or stencil pixel format, or a stencil attachment of a format without stencil | every device (a public call's own check of its arguments) | `metal-documented`: a color attachment takes a color-renderable format and a stencil attachment a format with stencil; Metal's validation stops the descriptor | 2: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` | `-` | | `VertexBufferOffset` | A draw whose vertex descriptor reads a vertex buffer at an offset at or past the buffer's length | every device (a public call's own check of its arguments) | `metal-documented`: a buffer's offset lies inside it; Metal's validation stops the bind | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | | `IndexBufferOffset` | An indexed draw whose index buffer offset is not a multiple of the index size, or whose indices leave the buffer | every device (a public call's own check of its arguments) | `metal-documented`: the offset is a multiple of the index size and the indices lie in the buffer; Metal's validation stops the draw | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | +| `ArgumentPlace` | An indirect dispatch's arguments, or an indexed draw's indices, at a byte of the block the buffer lies in (its device copy's, for a Managed buffer... | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads its arguments at a multiple of 4 in the `VkBuffer`, and `vkCmdBindIndexBuffer` takes indices at a multiple of their size in the memory; a Metal buffer starts at an aligned address, so Metal's offset rule alone keeps both aligned there | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`, `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | | `ViewportNotFinite` | A viewport with a field that is NaN or infinite (but its origin's x, which draws nothing) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops a NaN or infinite origin; the other fields are taken by the same rule | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)` | `-` | | `StencilAttachment` | A draw under a depth-stencil state that tests the stencil, in a pass without a stencil attachment | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M4, macOS 27.0.1: Metal's validation stops the draw; plain Metal tests it against a hidden stencil of 0 that the runtime does not keep | 1: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` | `-` | @@ -1253,6 +1254,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::AttachmentFormat`: `crates/metal2vulkan-rt/src/pass.rs (check, 2 sites)` - `rt:Refusal::VertexBufferOffset`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` - `rt:Refusal::IndexBufferOffset`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` +- `rt:Refusal::ArgumentPlace`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` - `rt:Refusal::ViewportNotFinite`: `crates/metal2vulkan-rt/src/render_encoder.rs (set_viewport)` - `rt:Refusal::StencilAttachment`: `crates/metal2vulkan-rt/src/render_encoder.rs (draw)` - `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (round)`