diff --git a/crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m b/crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m new file mode 100644 index 000000000..81680b8cc --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m @@ -0,0 +1,204 @@ +// Where a kernel's loads and stores land when a buffer is bound at an offset that is not a +// multiple of its argument type's alignment, with Metal's API validation off (with it on, each +// such bind is reported and the work still runs). +// +// clang -fobjc-arc -O1 -fmodules -o misaligned_buffer_binds misaligned_buffer_binds.m \ +// -framework Foundation -framework Metal +// ./misaligned_buffer_binds +// +// For element types of alignment 2, 4, 8 and 16 (ushort, uint, uint2, uint4), each bound at +// offsets 0 (control), 1, 2, 3, 4 and 8 where the offset is not a multiple of the alignment: once +// with the source misaligned (a load) and once with the destination misaligned (a store), from +// random words. Two kernels per type: a thread-indexed copy (dst[t] = src[t], 64 threads) and a +// constant-indexed one (dst[0] = src[3], dst[2] = src[1]). For each case it prints the effective +// base offsets b (0 to 31) at which every copied element is found (a load) or the whole +// destination equals the expected bytes (a store); "none" with the changed byte span where no b +// matches. Then pointers stored in a buffer (as a program writes a table's addresses itself): a +// `device uint *` at a buffer's gpuAddress + 0, 1, 2 and 3, and a `device uint4 *` at + 0, 4 and +// 8, each read (dst[t] = p.a[t]) and written (p.b[t] = src[t]) through. +// +// On an Apple M3 Max under macOS 27.0.1 every case matched one b: the address rounded down to the +// smaller of the element's alignment and 4 (a ushort at +1 at +0 and at +3 at +2; a uint at +1, +2 +// or +3 at +0; a uint2 or uint4 at +1, +2 or +3 at +0 and at +4 or +8 exactly there), loads, +// stores and stored pointers alike. +#import +#import +#include + +static NSString *const kSource = @ + "#include \n" + "using namespace metal;\n" + "#define K(n, T) \\\n" + "kernel void copy_##n(device const T *src [[buffer(0)]], device T *dst [[buffer(1)]], uint t [[thread_position_in_grid]]) { dst[t] = src[t]; } \\\n" + "kernel void konst_##n(device const T *src [[buffer(0)]], device T *dst [[buffer(1)]], uint t [[thread_position_in_grid]]) { if (t == 0) { dst[0] = src[3]; dst[2] = src[1]; } }\n" + "K(u16, ushort)\n" + "K(u32, uint)\n" + "K(u64, uint2)\n" + "K(u128, uint4)\n" + "#define P(n, T) \\\n" + "struct ptrs_##n { device T *a; device T *b; }; \\\n" + "kernel void ptr_##n(device const ptrs_##n &p [[buffer(0)]], device T *dst [[buffer(1)]], device const T *src [[buffer(2)]], uint t [[thread_position_in_grid]]) { dst[t] = p.a[t]; p.b[t] = src[t]; }\n" + "P(u32, uint)\n" + "P(u128, uint4)\n"; + +enum { N = 64, LEN = 8192, MAXB = 32 }; + +static uint64_t g_state = 0x9E3779B97F4A7C15ull; +static void fill(uint8_t *p, size_t n) { + for (size_t i = 0; i < n; i++) { + g_state ^= g_state << 13; + g_state ^= g_state >> 7; + g_state ^= g_state << 17; + p[i] = (uint8_t)(g_state >> 24); + } +} + +typedef struct { unsigned d, s; } Pair; + +int main(void) { + @autoreleasepool { + id dev = MTLCreateSystemDefaultDevice(); + if (!dev) { printf("no device\n"); return 1; } + printf("device: %s\n", dev.name.UTF8String); + NSError *err = nil; + id lib = [dev newLibraryWithSource:kSource options:nil error:&err]; + if (!lib) { printf("library: %s\n", err.localizedDescription.UTF8String); return 1; } + id q = [dev newCommandQueue]; + struct { const char *name; unsigned size; } types[] = {{"u16", 2}, {"u32", 4}, {"u64", 8}, {"u128", 16}}; + unsigned offsets[] = {0, 1, 2, 3, 4, 8}; + int failures = 0; + for (unsigned ti = 0; ti < 4; ti++) { + unsigned size = types[ti].size; + for (int k = 0; k < 2; k++) { + NSString *fn = [NSString stringWithFormat:@"%s_%s", k ? "konst" : "copy", types[ti].name]; + id pso = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:fn] error:&err]; + if (!pso) { printf("%s: %s\n", fn.UTF8String, err.localizedDescription.UTF8String); return 1; } + Pair pairs[N]; + unsigned np = 0; + if (k == 0) { for (unsigned t = 0; t < N; t++) pairs[np++] = (Pair){t, t}; } + else { pairs[np++] = (Pair){0, 3}; pairs[np++] = (Pair){2, 1}; } + for (unsigned oi = 0; oi < 6; oi++) { + unsigned o = offsets[oi]; + if (o != 0 && o % size == 0) continue; + for (int store = 0; store < 2; store++) { + id sb = [dev newBufferWithLength:LEN options:MTLResourceStorageModeShared]; + id db = [dev newBufferWithLength:LEN options:MTLResourceStorageModeShared]; + uint8_t s0[LEN], d0[LEN]; + fill(s0, LEN); + fill(d0, LEN); + memcpy(sb.contents, s0, LEN); + memcpy(db.contents, d0, LEN); + id cb = [q commandBuffer]; + id e = [cb computeCommandEncoder]; + [e setComputePipelineState:pso]; + [e setBuffer:sb offset:(store ? 0 : o) atIndex:0]; + [e setBuffer:db offset:(store ? o : 0) atIndex:1]; + [e dispatchThreads:MTLSizeMake(N, 1, 1) threadsPerThreadgroup:MTLSizeMake(N, 1, 1)]; + [e endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + const uint8_t *d1 = db.contents; + printf("%-10s %-5s offset %u: ", fn.UTF8String, store ? "store" : "load", o); + if (cb.status != MTLCommandBufferStatusCompleted) { + printf("command buffer status %ld: %s\n", (long)cb.status, cb.error.localizedDescription.UTF8String); + failures++; + continue; + } + int found = 0; + printf("b ="); + for (unsigned b = 0; b < MAXB; b++) { + int ok = 1; + if (!store) { + for (unsigned i = 0; i < np && ok; i++) + ok = memcmp(d1 + pairs[i].d * size, s0 + b + pairs[i].s * size, size) == 0; + } else { + uint8_t want[LEN]; + memcpy(want, d0, LEN); + for (unsigned i = 0; i < np; i++) + memcpy(want + b + pairs[i].d * size, s0 + pairs[i].s * size, size); + ok = memcmp(want, d1, LEN) == 0; + } + if (ok) { printf(" %u", b); found++; } + } + if (!found) { + long lo = -1, hi = -1, n = 0; + for (long i = 0; i < LEN; i++) + if (d1[i] != d0[i]) { if (lo < 0) lo = i; hi = i; n++; } + printf(" none; changed bytes %ld, from %ld to %ld", n, lo, hi); + failures++; + } + printf("%s\n", (found && (store ? 1 : 1)) ? (found == 1 ? "" : " (several)") : ""); + } + } + } + } + struct { const char *name; unsigned size; unsigned offs[4]; unsigned n; } pt[] = { + {"u32", 4, {0, 1, 2, 3}, 4}, {"u128", 16, {0, 4, 8, 0}, 3}}; + for (unsigned ti = 0; ti < 2; ti++) { + unsigned size = pt[ti].size; + NSString *fn = [NSString stringWithFormat:@"ptr_%s", pt[ti].name]; + id pso = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:fn] error:&err]; + if (!pso) { printf("%s: %s\n", fn.UTF8String, err.localizedDescription.UTF8String); return 1; } + for (unsigned oi = 0; oi < pt[ti].n; oi++) { + unsigned o = pt[ti].offs[oi]; + id ab = [dev newBufferWithLength:LEN options:MTLResourceStorageModeShared]; + id bb = [dev newBufferWithLength:LEN options:MTLResourceStorageModeShared]; + id db = [dev newBufferWithLength:LEN options:MTLResourceStorageModeShared]; + id sb = [dev newBufferWithLength:LEN options:MTLResourceStorageModeShared]; + id pb = [dev newBufferWithLength:16 options:MTLResourceStorageModeShared]; + uint8_t a0[LEN], b0[LEN], d0[LEN], s0[LEN]; + fill(a0, LEN); fill(b0, LEN); fill(d0, LEN); fill(s0, LEN); + memcpy(ab.contents, a0, LEN); memcpy(bb.contents, b0, LEN); + memcpy(db.contents, d0, LEN); memcpy(sb.contents, s0, LEN); + uint64_t addrs[2] = {ab.gpuAddress + o, bb.gpuAddress + o}; + memcpy(pb.contents, addrs, 16); + id cb = [q commandBuffer]; + id e = [cb computeCommandEncoder]; + [e setComputePipelineState:pso]; + [e setBuffer:pb offset:0 atIndex:0]; + [e setBuffer:db offset:0 atIndex:1]; + [e setBuffer:sb offset:0 atIndex:2]; + [e useResource:ab usage:MTLResourceUsageRead]; + [e useResource:bb usage:MTLResourceUsageRead | MTLResourceUsageWrite]; + [e dispatchThreads:MTLSizeMake(N, 1, 1) threadsPerThreadgroup:MTLSizeMake(N, 1, 1)]; + [e endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + if (cb.status != MTLCommandBufferStatusCompleted) { + printf("%-10s gpuAddress + %u: command buffer status %ld: %s\n", fn.UTF8String, o, (long)cb.status, cb.error.localizedDescription.UTF8String); + failures++; + continue; + } + const uint8_t *d1 = db.contents, *b1 = bb.contents; + for (int store = 0; store < 2; store++) { + printf("%-10s %-5s gpuAddress + %u: b =", fn.UTF8String, store ? "store" : "load", o); + int found = 0; + for (unsigned b = 0; b < MAXB; b++) { + int ok = 1; + if (!store) { + for (unsigned t = 0; t < N && ok; t++) + ok = memcmp(d1 + t * size, a0 + b + t * size, size) == 0; + } else { + uint8_t want[LEN]; + memcpy(want, b0, LEN); + for (unsigned t = 0; t < N; t++) memcpy(want + b + t * size, s0 + t * size, size); + ok = memcmp(want, b1, LEN) == 0; + } + if (ok) { printf(" %u", b); found++; } + } + if (!found) { + const uint8_t *x1 = store ? b1 : d1, *x0 = store ? b0 : d0; + long lo = -1, hi = -1, n = 0; + for (long i = 0; i < LEN; i++) + if (x1[i] != x0[i]) { if (lo < 0) lo = i; hi = i; n++; } + printf(" none; changed bytes %ld, from %ld to %ld", n, lo, hi); + failures++; + } + printf("\n"); + } + } + } + printf("cases without a matching b: %d\n", failures); + } + return 0; +} diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 12cdaa0fb..700ca9f9b 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -445,6 +445,10 @@ that touch blocks first. before indirect argument reads gets one that does, in either kind of encoder. A segment records nothing else that touches memory; the barrier at a segment's end takes every command and the host. +- A buffer bound where its address, its `gpuAddress` plus the offset, is not a multiple of its + kernel argument's alignment (`air.arg_type_align_size`, at most 16) is pushed rounded down to + that alignment, where Metal's API validation refuses the bind; `docs/API.md` section 10 says + where that differs from Metal without validation. - Parameters: fields in the push window, `[0, 256)` on every device, are pushed: the dispatch region and up to 28 buffer addresses, each kernel pushing only the bytes it reads. Fields past it go to a 16-byte aligned block in the parameter ring, whose address is a field in the window: a diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 90230106b..4dba77376 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -432,9 +432,6 @@ impl ComputeCommandEncoder { /// [`Limit::ThreadgroupMemory`]; [`Gap::PartialSimdgroups`] for a threadgroup that is not /// whole SIMD groups of a kernel whose tier needs them and that has no emulated module; /// [`Error::Quiesced`] where the device was quiesced before that module was lowered; - /// [`Refusal::MisalignedBuffer`] where a bound buffer's address plus its offset is not a - /// multiple of its argument's alignment, as Metal's API validation refuses the bind: the - /// dispatch is not recorded, and the encoder and its command buffer stay usable; /// [`Limit::MemoryAllocations`] where the parameter ring needs a block past the device's /// allocation count; [`Error::Vulkan`] where the pipeline's compile, the ring or recording /// fails. @@ -728,7 +725,7 @@ impl ComputeCommandEncoder { kernel, &inner.numbered.ids, ®ion(base, threads, ragged)?, - )?; + ); self.record(vk_pipeline, Launch::Direct(count))?; } } @@ -736,7 +733,7 @@ impl ComputeCommandEncoder { Ok(()) } (None, Grid::Indirect(buffer, offset)) => { - self.fill_parameters(kernel, &inner.numbered.ids, ®ion([0; 3], [0; 3], false)?)?; + self.fill_parameters(kernel, &inner.numbered.ids, ®ion([0; 3], [0; 3], false)?); self.record(vk_pipeline, Launch::Indirect(buffer, offset)) } (None, Grid::Direct { .. }) => Ok(()), @@ -765,14 +762,9 @@ impl ComputeCommandEncoder { /// samplers `sampler_ids`. The block's address is written by [`Building::record_dispatch`] /// once the block is in the ring. /// - /// Err: [`Refusal::MisalignedBuffer`] where a buffer's address is not a multiple of the - /// alignment the module takes it to have. - fn fill_parameters( - &mut self, - kernel: &Kernel, - sampler_ids: &[u32], - region: &[u8; 32], - ) -> Result<(), Error> { + /// A buffer's address that is not a multiple of the alignment the module takes it to have + /// goes rounded down to that alignment, where Metal's API validation refuses the bind offset. + fn fill_parameters(&mut self, kernel: &Kernel, sampler_ids: &[u32], region: &[u8; 32]) { let interface: &Interface = &kernel.interface; let parameters = &mut self.parameters; parameters.push.clear(); @@ -794,14 +786,7 @@ impl ComputeCommandEncoder { } Some(Slot::Bytes(address)) => *address, Some(Slot::Empty) | None => 0, - }; - if address & mask != 0 { - return Err(Error::Refused(Refusal::MisalignedBuffer { - index: slot, - address, - align: mask + 1, - })); - } + } & !mask; bytes[at..at + 8].copy_from_slice(&address.to_le_bytes()); } FieldValue::TextureId(slot) => { @@ -835,7 +820,6 @@ impl ComputeCommandEncoder { } } parameters.block_address = (interface.block_len > 0).then_some(interface.block_address); - Ok(()) } } diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 1e613e313..93b90e923 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -175,23 +175,6 @@ pub enum Refusal { /// The indices given. given: usize, }, - /// A dispatch whose buffer at `index` sits at an address, its buffer's `gpuAddress` plus the - /// bind offset, that is not a multiple of the alignment of the kernel's argument there - /// (`air.arg_type_align_size`, at most 16; `RuntimeFact::AddressAlignment`). The kernel reaches - /// such an argument from its address as it is. - /// - /// Basis: metal-measured (an Apple M3 Max: API validation fails a bind offset that is not a - /// multiple of the argument type's alignment: "must be a multiple of 4 but was set to 2" for a - /// `uint *` argument, "of 16 but was set to 8" for a `float4 *`, "of 2 but was set to 1" for a - /// `ushort *`; `probes/vector_access_placement.m` in the conformance crate). - MisalignedBuffer { - /// The buffer argument index. - index: u32, - /// The buffer's address plus the bind offset. - address: u64, - /// The argument's alignment: 2, 4, 8 or 16. - align: u64, - }, /// `setBufferOffset` at an index where no buffer is bound. /// /// Basis: ours (there is no buffer whose offset to change). @@ -650,14 +633,6 @@ impl fmt::Display for Refusal { f, "{given} sampler indices were given for the {numbered} samplers the state numbers" ), - Refusal::MisalignedBuffer { - index, - address, - align, - } => write!( - f, - "the buffer at index {index} sits at {address:#x}, not a multiple of the {align} bytes its argument takes" - ), Refusal::ThreadgroupSize { size, max } => write!( f, "a threadgroup of {size:?} threads is empty or past the state's {max}" diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 060529ae5..c7c2ff84f 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -343,9 +343,9 @@ pub(crate) enum Place { #[derive(Clone, Copy)] pub(crate) enum FieldValue { /// A `u64`: the address of the buffer bound at the slot plus its offset, the address of the - /// slot's `set_bytes` copy, or 0 where nothing is bound. `mask` is the alignment the module - /// takes that address to have, less 1 (`RuntimeFact::AddressAlignment`), 0 where it takes - /// none. + /// slot's `set_bytes` copy, or 0 where nothing is bound, rounded down to a multiple of the + /// alignment the module takes that address to have. `mask` is that alignment less 1 + /// (`RuntimeFact::AddressAlignment`), 0 where it takes none. BufferAddress { slot: u32, mask: u64 }, /// A `u64`: the `gpuResourceID` of the texture bound at the slot, 0 where none is. TextureId(u32), @@ -622,7 +622,7 @@ fn interface( for dependency in &pipeline.dependencies { match dependency.fact { RuntimeFact::LocalSizeConstraint { multiple } => multiples.push(multiple), - // The slot's address is a multiple of its argument's alignment. + // The slot's address, rounded down to a multiple of its argument's alignment. RuntimeFact::AddressAlignment { slot: SlotRef { diff --git a/crates/metal2vulkan-rt/src/tests/compute.rs b/crates/metal2vulkan-rt/src/tests/compute.rs index 0eeb8862d..2457f3b8b 100644 --- a/crates/metal2vulkan-rt/src/tests/compute.rs +++ b/crates/metal2vulkan-rt/src/tests/compute.rs @@ -139,6 +139,77 @@ mod on_device { }); } + /// The binder pushes a bound buffer's address rounded down to a multiple of the alignment the + /// kernel takes it to have (`FieldValue::BufferAddress`'s mask, `RuntimeFact::AddressAlignment` + /// in a translated kernel), where Metal's API validation refuses the bind offset. At each + /// alignment, 2, 4, 8 and 16, a buffer bound 1, 3, 4, 8, 12 or 15 bytes past a multiple of 16 + /// (each offset that is not a multiple of the alignment and rounds down to a word: 15 binds) + /// is stepped from its address rounded down to the alignment, and no other word changes. An + /// 8- or 16-byte alignment's bind 4, 8 or 12 bytes past a multiple of 16 is a word apart from + /// its rounded address, so a bind not rounded steps other words on every device. + #[test] + fn every_device_rounds_a_bound_address_down_to_its_alignment() { + each_device("compute_rounded_address", |name, _, device| { + let mut arena = Arena::new(&device); + let queue = device.new_command_queue(4).expect("a queue"); + let mut runs = 0; + for align in [2u64, 4, 8, 16] { + let fields = vec![ + region(), + Field { + place: Place::Push(32), + value: FieldValue::BufferAddress { + slot: 0, + mask: align - 1, + }, + }, + ]; + let buffers = vec![(0, Access::ReadWrite)]; + let state = ComputePipelineState::for_test( + &device, + &kernels::STEP, + interface(buffers, fields, 40), + ) + .expect("the step kernel"); + for at in [1u64, 3, 4, 8, 12, 15] { + let rounded = (32 + at) & !(align - 1); + if at % align == 0 || rounded % 4 != 0 { + continue; + } + let x = arena.buffer(); + assert_eq!(x.gpu_address() % 16, 0, "{name}: the buffer's address"); + write_words(&x, |index| index); + 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"); + encoder.set_buffer(Some(&x), 32 + at, 0).expect("a buffer"); + encoder + .dispatch_threadgroups([1, 1, 1], [16, 1, 1]) + .expect("a dispatch"); + encoder.end_encoding(); + run(name, &command_buffer); + let stepped = rounded as u32 / 4..rounded as u32 / 4 + 16; + let expected: Vec = (0..WORDS as u32) + .map(|index| match stepped.contains(&index) { + true => index * 2 + 1, + false => index, + }) + .collect(); + assert_eq!( + words(&x), + expected, + "{name}: alignment {align}, bound at 32 + {at}" + ); + runs += 1; + } + } + assert_eq!(runs, 15, "{name}: the binds"); + println!("{name}: {runs} binds off their alignment, each run at the rounded address"); + }); + } + /// A serial encoder places a barrier at each hazard and none between independent dispatches; /// a concurrent encoder places one only on request. The values show the order held. #[test] diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 9e03c2946..65813c572 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -19,7 +19,7 @@ mod on_device { use crate::{ host_time, BlockId, Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DeviceOptions, DispatchType, Error, FunctionDescriptor, Gauges, Instance, Library, Limit, - MemoryClass, PrecisionNote, Refusal, StageSource, MAX_BUFFER_LENGTH, + MemoryClass, PrecisionNote, StageSource, MAX_BUFFER_LENGTH, }; use metal2vulkan::pipeline::{RuntimeFact, StageEntries}; use metal2vulkan::Budget; @@ -1162,66 +1162,14 @@ mod on_device { } /// `vwp_vec16` takes its `float4 *` arguments' addresses to be multiples of 16 and `vwp_words` - /// its `uint *` arguments' multiples of 4 (`RuntimeFact::AddressAlignment`), so a dispatch with - /// the first argument bound off that alignment (4 past a multiple of 16; 2 past one of 4) is - /// refused (`Refusal::MisalignedBuffer`), as Metal's API validation refuses the bind ("must be - /// a multiple of 16 but was set to 4", "must be a multiple of 4 but was set to 2"), and the - /// same buffer bound at the next multiple runs. + /// its `uint *` arguments' multiples of 4 (`RuntimeFact::AddressAlignment`). Each argument + /// bound off that alignment (`vwp_words`'s 1 and 3 bytes past each word phase, `vwp_vec16`'s + /// 4 and 12 bytes past its multiples of 16) runs at the address rounded down to it, where + /// Metal's API validation refuses the bind: all four buffers hold Metal's words for the binds + /// at the rounded addresses (`vector_word_phases`' answer), and the command buffer completes + /// without error. #[test] - fn an_argument_bound_off_its_alignment_is_refused() { - use metal2vulkan_devtools::vector_word_phases::{FIXTURE, THREADS, VEC16, WORDS}; - let (Some(vec16), Some(words)) = - (descriptor_of(FIXTURE, VEC16), descriptor_of(FIXTURE, WORDS)) - else { - return; - }; - each_device("compute_address_alignment", |name, _, device| { - let (vec16, words) = (state(name, &device, &vec16), state(name, &device, &words)); - let mut buffers = Buffers::new(&device, 64 * 1024); - let (a, b) = (buffers.buffer(16384), buffers.buffer(16384)); - assert_eq!(a.gpu_address() % 16, 0, "{name}: the buffer's address"); - let queue = device.new_command_queue(4).expect("a queue"); - for (kernel, align, at) in [ - (&vec16, 16, 4), - (&vec16, 16, 16), - (&words, 4, 2), - (&words, 4, 4), - ] { - 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(kernel).expect("a state"); - encoder.set_buffer(Some(&a), at, 0).expect("a buffer"); - encoder.set_buffer(Some(&b), 0, 1).expect("a buffer"); - let r = encoder.dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1]); - match r { - Err(Error::Refused(Refusal::MisalignedBuffer { - index: 0, - address, - align: refused, - })) if at % align != 0 => { - assert_eq!((address, refused), (a.gpu_address() + at, align), "{name}") - } - Ok(()) if at % align == 0 => {} - r => panic!("{name}: align {align}, offset {at}: {r:?}"), - } - encoder.end_encoding(); - command_buffer.commit().expect("a commit"); - finished(name, &command_buffer); - assert_eq!(command_buffer.error(), None, "{name}: offset {at}"); - } - println!("{name}: refused off each argument's alignment, ran on it"); - }); - } - - /// A dispatch refused for a misaligned argument (`Refusal::MisalignedBuffer`) records - /// nothing: in the same encoder, with the arguments bound again at their alignment, the next - /// dispatches record and run, the command buffer commits and completes without error, and - /// every buffer holds Metal's words for those dispatches alone (`vector_word_phases`'s - /// answer). The device's gauges read zero at its drop (`each_device`). - #[test] - fn a_misaligned_dispatch_refused_leaves_its_encoder_and_command_buffer_usable() { + fn an_argument_bound_off_its_alignment_runs_at_the_address_rounded_down() { use metal2vulkan_devtools::vector_word_phases::{ answer, inputs, vec16_offsets, FIXTURE, OFFSETS, THREADS, VEC16, WORDS, }; @@ -1230,7 +1178,7 @@ mod on_device { else { return; }; - each_device("compute_misaligned_then_aligned", |name, _, device| { + each_device("compute_rounded_binds", |name, _, device| { let before = inputs(); let (phased, aligned) = ( state(name, &device, &phased), @@ -1241,70 +1189,61 @@ mod on_device { .into_iter() .map(|bytes| (buffers.buffer(bytes.len() as u64), bytes)) .collect(); - for (buffer, bytes) in &held { - write(buffer, 0, bytes); - } - let offset = OFFSETS[0]; - let (a_at, b_at) = vec16_offsets(offset); + assert!( + held.iter() + .all(|(buffer, _)| buffer.gpu_address() % 16 == 0), + "{name}: the buffers' addresses" + ); 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"); - // `vwp_vec16`'s first `float4 *` 4 bytes past its alignment. - encoder - .set_compute_pipeline_state(&aligned) - .expect("a state"); - encoder - .set_buffer(Some(&held[2].0), a_at + 4, 0) - .expect("a buffer"); - encoder - .set_buffer(Some(&held[3].0), b_at, 1) - .expect("a buffer"); - match encoder.dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1]) { - Err(Error::Refused(Refusal::MisalignedBuffer { - index: 0, - align: 16, - .. - })) => {} - r => panic!("{name}: a misaligned dispatch: {r:?}"), - } - for (state, binds) in [ - (&phased, [(0, offset), (1, offset)]), - (&aligned, [(2, a_at), (3, b_at)]), - ] { - encoder.set_compute_pipeline_state(state).expect("a state"); - for (index, (buffer, at)) in binds.into_iter().enumerate() { + for offset in OFFSETS { + for (buffer, bytes) in &held { + write(buffer, 0, bytes); + } + let (a_at, b_at) = vec16_offsets(offset); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + for (state, binds) in [ + (&phased, [(0, offset + 1), (1, offset + 3)]), + (&aligned, [(2, a_at + 4), (3, b_at + 12)]), + ] { + encoder.set_compute_pipeline_state(state).expect("a state"); + for (index, (buffer, at)) in binds.into_iter().enumerate() { + encoder + .set_buffer(Some(&held[buffer].0), at, index as u32) + .expect("a buffer"); + } encoder - .set_buffer(Some(&held[buffer].0), at, index as u32) - .expect("a buffer"); + .dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1]) + .unwrap_or_else(|error| panic!("{name}: offset {offset}: {error}")); + } + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}: offset {offset}"); + let want = answer(offset); + for ((buffer, bytes), (which, want)) in held.iter().zip([ + ("src", &want.src), + ("dst", &want.dst), + ("a", &want.a), + ("b", &want.b), + ]) { + let got = words(buffer, 0, bytes.len() / 4); + let want: Vec = want + .as_chunks::<4>() + .0 + .iter() + .map(|w| u32::from_le_bytes(*w)) + .collect(); + let first = got.iter().zip(&want).position(|(x, y)| x != y); + assert_eq!( + first, None, + "{name}: offset {offset}: {which} differs from Metal's words at the rounded binds" + ); } - encoder - .dispatch_threadgroups([1, 1, 1], [THREADS, 1, 1]) - .unwrap_or_else(|error| panic!("{name}: after the refusal: {error}")); } - encoder.end_encoding(); - command_buffer.commit().expect("a commit"); - finished(name, &command_buffer); - assert_eq!(command_buffer.error(), None, "{name}"); - let want = answer(offset); - for ((buffer, bytes), (which, want)) in held.iter().zip([ - ("src", &want.src), - ("dst", &want.dst), - ("a", &want.a), - ("b", &want.b), - ]) { - let got = words(buffer, 0, bytes.len() / 4); - let want: Vec = want - .as_chunks::<4>() - .0 - .iter() - .map(|w| u32::from_le_bytes(*w)) - .collect(); - let first = got.iter().zip(&want).position(|(x, y)| x != y); - assert_eq!(first, None, "{name}: {which} differs from Metal's words"); - } - println!("{name}: refused, then ran in the same encoder and command buffer"); + println!("{name}: each argument bound off its alignment ran at the rounded address"); }); } diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index a014f2d95..66f5b30f2 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -206,7 +206,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::TexelRows { .. } => Mechanism::Variant, // Keyed by the slots bound to a texture buffer of more texels than one view holds. RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, - // The binder tests the slot's address against the alignment before the work. + // The binder rounds the slot's address down to a multiple of the alignment. RuntimeFact::AddressAlignment { .. } => Mechanism::PlanTimeCheck, // The function marks the `ExecutionStatus` buffer its `ExecutionStatus` fact binds; the // consumer reads the bit after the command buffer. diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 6b6c6e78e..663a566e0 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -877,8 +877,9 @@ pub enum RuntimeFact { /// bind offset, is a multiple of `align` (2, 4, 8 or 16): its argument's alignment /// (`air.arg_type_align_size`, at most 16). Metal's API validation refuses a bind offset that /// is not a multiple of it ("must be a multiple of 4 but was set to 2" for a `uint *` argument, - /// `probes/vector_access_placement.m` in the conformance crate), and the binder refuses such a - /// binding before the work runs. Where `align` is at least 4 the function reaches the slot from + /// `probes/vector_access_placement.m` in the conformance crate), and the binder rounds such an + /// address down to a multiple of it before the work runs. Where `align` is at least 4 the + /// function reaches the slot from /// that address as it is: no access rounds it to a word, and an 8- or 16-byte access at an /// offset proven a multiple of its size is one `uvec2` or `uvec4`. AddressAlignment { slot: SlotRef, align: u32 }, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index b627cd198..b5e70a8a0 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -13390,7 +13390,6 @@ variant metal2vulkan-rt::Refusal::IndicesInUse IndicesInUse { class: IndexClass, variant metal2vulkan-rt::Refusal::IndicesNotGranted IndicesNotGranted { class: IndexClass, index: u32 } variant metal2vulkan-rt::Refusal::IndirectOffset IndirectOffset { offset: u64, length: u64 } variant metal2vulkan-rt::Refusal::ManagedBlockNotShared ManagedBlockNotShared { block: BlockId } -variant metal2vulkan-rt::Refusal::MisalignedBuffer MisalignedBuffer { index: u32, address: u64, align: u64 } variant metal2vulkan-rt::Refusal::ModifiedRange ModifiedRange { start: u64, length: u64, buffer_length: u64 } variant metal2vulkan-rt::Refusal::NoBufferAtIndex NoBufferAtIndex { index: u32 } variant metal2vulkan-rt::Refusal::NoCommandBuffers NoCommandBuffers diff --git a/docs/API.md b/docs/API.md index d3b021439..ad64ba3a2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -117,8 +117,9 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: address plus its 32-bit byte offset, sign-extended, which is exact as the new runtime makes no buffer longer than 2 GiB (`MAX_BUFFER_LENGTH`), and an access of 8 or 16 bytes at an offset proven a multiple of its size is one `uvec2` or `uvec4`. The function states - `RuntimeFact::AddressAlignment` with that alignment (at most 16), and a binder refuses a binding - whose address is not a multiple of it, as Metal's API validation refuses the bind offset. A + `RuntimeFact::AddressAlignment` with that alignment (at most 16), and a binder rounds a bound + address down to a multiple of it, where Metal's API validation refuses the bind offset (an + accepted difference, section 10). A slot whose argument states an alignment below 4, or none, is reached the same way where each of its accesses is one 1- or 2-byte unit no wider than that alignment (an `i8` access of a `uchar` buffer, an `i16` one of a `ushort` buffer) on a device with that width's storage access. Any @@ -6403,6 +6404,18 @@ each item named states the rule in full. an argument the kernel writes may read those bytes as they were before its own writes, where the device reads read-only memory through another path (RADV reads a uniform address of it with a scalar load). The attribute states that no other argument reaches that memory. +- **A buffer bound off its argument's alignment is reached at the address rounded down to that + alignment** (the alignment the kernel's AIR states for the argument, `air.arg_type_align_size`, + at most 16; `RuntimeFact::AddressAlignment`): the new runtime's binder rounds the bound address, + the buffer's `gpuAddress` plus the offset, before the dispatch runs. Metal's API validation + refuses such a bind offset ("must be a multiple of 4 but was set to 2" for a `uint *` argument). + Without validation an Apple M3 Max (macOS 27.0.1) reaches each element at its address rounded + down to the smaller of the element's alignment and 4, for loads, stores and pointers stored in a + buffer alike (`crates/metal2vulkan-conformance/probes/misaligned_buffer_binds.m`). The two agree + for arguments of alignment 2 and 4, and for 8- and 16-byte ones bound 1 to 3 bytes off a + multiple of 4; an 8- or 16-byte argument bound at a multiple of 4 that is not a multiple of its + alignment is reached at the address rounded down to 8 or 16, where the M3 reaches it exactly + there. - **An imageblock's length rounds its cell as an M4 does** (`ComputePipelineState::imageblock_memory_length_for_dimensions`), never less than what a dispatch counts against the device's threadgroup memory. diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 4eb54501f..98246a518 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 | 7 | 7 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 33 | 33 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 32 | 32 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 10 | 10 | 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 | 7 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 10 | 8 | 0 | 0 | 15 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 9 | 8 | 0 | 0 | 15 | 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 | 10 | 0 | 0 | 0 | @@ -627,7 +627,6 @@ Columns: | `TextureArgumentIndex` | A texture argument index past Metal's 128 entries (`setTexture`) | every device (a public call's own check of its arguments) | `metal-documented`: the texture argument table has 128 entries per stage on Apple GPUs | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_texture)` | `-` | | `SamplerArgumentIndex` | A sampler argument index past Metal's 16 entries (`setSamplerState`) | every device (a public call's own check of its arguments) | `metal-documented`: the sampler argument table has 16 entries per stage | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)` | `-` | | `SamplerIds` | A consumer's answer to `Device::new_compute_pipeline_state`'s numbered samplers with another count of indices | every device (a public call's own check of its arguments) | `ours`: each numbered sampler takes one index | 1: `crates/metal2vulkan-rt/src/pipeline.rs (number)` | `-` | -| `MisalignedBuffer` | A dispatch whose buffer at `index` sits at an address, its buffer's `gpuAddress` plus the bind offset, that is not a multiple of the alignment of... | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: API validation fails a bind offset that is not a multiple of the argument type's alignment: "must be a multiple of 4 but was set to 2" for a `uint *` argument, "of 16 but was set to 8" for a `float4 *`, "of 2 but was set to 1" for a `ushort *`; `probes/vector_access_placement.m` in the conformance crate | 1: `crates/metal2vulkan-rt/src/encoder.rs (fill_parameters)` | `-` | | `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` | `-` | | `ThreadgroupSize` | A threadgroup of no threads, or of more than the pipeline state's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` | `-` | | `IndirectOffset` | An indirect dispatch's argument offset that is not a multiple of 4, or that leaves fewer than 12 bytes (three 32-bit counts) in the buffer | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads three 32-bit counts at a 4-byte aligned offset inside the buffer | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` | `-` | @@ -1178,7 +1177,6 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::TextureArgumentIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_texture)` - `rt:Refusal::SamplerArgumentIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)` - `rt:Refusal::SamplerIds`: `crates/metal2vulkan-rt/src/pipeline.rs (number)` -- `rt:Refusal::MisalignedBuffer`: `crates/metal2vulkan-rt/src/encoder.rs (fill_parameters)` - `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` - `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` - `rt:Refusal::IndirectOffset`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`