From 04bc130a4cc5f002a0bbfd4d38446e99cbbfab1f Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 25 Oct 2026 13:40:25 +0200 Subject: [PATCH] Make the indirect buffer and bind counts plain Metal makes, and refuse only what its process does not survive The steps this packet landed as, in order: - Measure the slots past the records before anything is taken, and read the taken calls at commit - Bless the public signature table after the bind-count refusal's variant - Take runtime version 1605 and re-derive the generated documents at the rebase tip Content: the tree of `development` at 7f47d5fffe, unchanged. --- .../probes/icb_refusals_that_metal_takes.m | 896 ++++++++++++++++++ .../src/indirect_command_buffer.rs | 307 +++--- .../src/tests/indirect_command_buffer.rs | 48 +- .../runtime_lane/indirect_command_buffers.rs | 108 ++- crates/metal2vulkan/tests/api_signatures.tsv | 1 - docs/REFUSALS.md | 16 +- 6 files changed, 1212 insertions(+), 164 deletions(-) create mode 100644 crates/metal2vulkan-conformance/probes/icb_refusals_that_metal_takes.m diff --git a/crates/metal2vulkan-conformance/probes/icb_refusals_that_metal_takes.m b/crates/metal2vulkan-conformance/probes/icb_refusals_that_metal_takes.m new file mode 100644 index 000000000..2e139784a --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/icb_refusals_that_metal_takes.m @@ -0,0 +1,896 @@ +// Plain Metal's own answer, with the API validation layer OFF, for the four indirect-command-buffer +// refusals the runtime raises where a measurement said plain Metal takes the input: +// `NoCommandTypes`, `BindCount`, `PipelineWithoutSupport` and `CommandType`. Three of the four +// cover an accepted shape and an aborting one at once, so each group sweeps BOTH sides of the line +// rather than one shape of it. +// +// Build (no GPU needed to build): +// +// clang -fobjc-arc -fmodules -framework Metal -framework Foundation \ +// -o icb_refusals_that_metal_takes icb_refusals_that_metal_takes.m +// +// Run ONE SHAPE PER PROCESS, WITHOUT MTL_DEBUG_LAYER (the layer is not passive: it asserts, and it +// has been measured to change what a shader reads). A shape whose process Metal ends prints no +// `DONE`, and its exit status is the signal: that is the reading. +// +// ./icb_refusals_that_metal_takes +// ./icb_refusals_that_metal_takes --list +// +// Every shape prints `DEVICE / RELEASE ` first, then `SHAPE`, then `READ ` +// lines, then `DONE `. Each offending shape has a legal neighbour beside it whose readings +// must differ, so a run where everything reads the same has measured nothing. + +#import +#import +#include +#include + +static id gDevice = nil; +static id gQueue = nil; + +static void head(void) { + printf("DEVICE %s\n", gDevice.name.UTF8String); + printf("RELEASE macOS %s\n", + [NSProcessInfo processInfo].operatingSystemVersionString.UTF8String); + fflush(stdout); +} + +static void readv(const char *key, const char *fmt, ...) { + printf("READ %s ", key); + va_list ap; + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + printf("\n"); + fflush(stdout); +} + +static void done(const char *shape) { + printf("DONE %s\n", shape); + fflush(stdout); +} + +static void commit_and_read(id cb, const char *key) { + [cb commit]; + [cb waitUntilCompleted]; + readv(key, "status %ld error %s", (long)cb.status, + cb.error ? cb.error.localizedDescription.UTF8String : "(none)"); +} + +// --------------------------------------------------------------------------------------------- +// The shaders: one draw, one mesh pipeline and one marking kernel. + +static NSString *const kShaders = @"\ +#include \n\ +using namespace metal;\n\ +struct VOut { float4 position [[position]]; };\n\ +vertex VOut vmain(uint vid [[vertex_id]], const device float2 *pts [[buffer(0)]]) {\n\ + VOut o; o.position = float4(pts[vid], 0.0, 1.0); return o;\n\ +}\n\ +fragment float4 fmain() { return float4(0.75, 0.5, 0.25, 1.0); }\n\ +using MeshT = mesh;\n\ +[[mesh]] void mmain(MeshT m, uint tid [[thread_index_in_threadgroup]]) {\n\ + if (tid != 0) { return; }\n\ + VOut v; v.position = float4(0.0, 0.0, 0.0, 1.0);\n\ + m.set_vertex(0, v); m.set_vertex(1, v); m.set_vertex(2, v);\n\ + m.set_index(0, 0); m.set_index(1, 1); m.set_index(2, 2);\n\ + m.set_primitive_count(1);\n\ +}\n\ +kernel void mark(device uint *out [[buffer(0)]], uint gid [[thread_position_in_grid]]) {\n\ + out[gid] = 0xC0DE0000u | gid;\n\ +}\n\ +"; + +static id library(void) { + NSError *err = nil; + id lib = [gDevice newLibraryWithSource:kShaders + options:[[MTLCompileOptions alloc] init] + error:&err]; + if (lib == nil) { readv("library", "nil error %s", err.localizedDescription.UTF8String); } + return lib; +} + +static id draw_pipeline(id lib, BOOL icb_support) { + MTLRenderPipelineDescriptor *pd = [[MTLRenderPipelineDescriptor alloc] init]; + pd.vertexFunction = [lib newFunctionWithName:@"vmain"]; + pd.fragmentFunction = [lib newFunctionWithName:@"fmain"]; + pd.colorAttachments[0].pixelFormat = MTLPixelFormatR32Float; + pd.supportIndirectCommandBuffers = icb_support; + NSError *err = nil; + id ps = [gDevice newRenderPipelineStateWithDescriptor:pd error:&err]; + if (ps == nil) { readv("pipeline", "nil error %s", err.localizedDescription.UTF8String); } + return ps; +} + +static id mesh_pipeline(id lib, BOOL icb_support) { + MTLMeshRenderPipelineDescriptor *pd = [[MTLMeshRenderPipelineDescriptor alloc] init]; + pd.meshFunction = [lib newFunctionWithName:@"mmain"]; + pd.fragmentFunction = [lib newFunctionWithName:@"fmain"]; + pd.colorAttachments[0].pixelFormat = MTLPixelFormatR32Float; + pd.supportIndirectCommandBuffers = icb_support; + NSError *err = nil; + id ps = + [gDevice newRenderPipelineStateWithMeshDescriptor:pd options:MTLPipelineOptionNone + reflection:nil error:&err]; + if (ps == nil) { readv("mesh-pipeline", "nil error %s", err.localizedDescription.UTF8String); } + return ps; +} + +static id mark_pipeline(id lib, BOOL icb_support) { + MTLComputePipelineDescriptor *cd = [[MTLComputePipelineDescriptor alloc] init]; + cd.computeFunction = [lib newFunctionWithName:@"mark"]; + cd.supportIndirectCommandBuffers = icb_support; + NSError *err = nil; + id ps = + [gDevice newComputePipelineStateWithDescriptor:cd options:MTLPipelineOptionNone + reflection:nil error:&err]; + if (ps == nil) { + readv("compute-pipeline", "nil error %s", err.localizedDescription.UTF8String); + } + return ps; +} + +// The four corners of the whole target, as a triangle strip's vertices. +static id quad_points(void) { + const float pts[8] = {-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f}; + return [gDevice newBufferWithBytes:pts length:sizeof(pts) + options:MTLResourceStorageModeShared]; +} + +static id color_target(void) { + MTLTextureDescriptor *d = [[MTLTextureDescriptor alloc] init]; + d.textureType = MTLTextureType2D; + d.pixelFormat = MTLPixelFormatR32Float; + d.width = 64; + d.height = 64; + d.storageMode = MTLStorageModeShared; + d.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + return [gDevice newTextureWithDescriptor:d]; +} + +static void clear_color(id t, float value) { + MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor]; + rp.colorAttachments[0].texture = t; + rp.colorAttachments[0].loadAction = MTLLoadActionClear; + rp.colorAttachments[0].clearColor = MTLClearColorMake(value, 0, 0, 1); + rp.colorAttachments[0].storeAction = MTLStoreActionStore; + id cb = [gQueue commandBuffer]; + [[cb renderCommandEncoderWithDescriptor:rp] endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; +} + +static void read_texels(id t, const char *key) { + size_t row = t.width * 4; + void *bytes = malloc(row); + [t getBytes:bytes bytesPerRow:row fromRegion:MTLRegionMake2D(0, 0, t.width, 1) mipmapLevel:0]; + const float *f = (const float *)bytes; + readv(key, "texels 0-3: %.5f %.5f %.5f %.5f", f[0], f[1], f[2], f[3]); + free(bytes); +} + +// --------------------------------------------------------------------------------------------- +// A 0xEE guard next to a destination, so an invisible overrun becomes a reading: the destination +// at offset 0 of a placement heap and the guard at the next 256-aligned offset past it. + +static const NSUInteger kGuardBytes = 1024; + +typedef struct { + id heap; + id target; + id guard; +} Guarded; + +static Guarded guarded_buffer(NSUInteger length) { + Guarded g = {nil, nil, nil}; + NSUInteger at = (length + 255) & ~(NSUInteger)255; + MTLHeapDescriptor *hd = [[MTLHeapDescriptor alloc] init]; + hd.type = MTLHeapTypePlacement; + hd.size = at + kGuardBytes + 4096; + hd.storageMode = MTLStorageModeShared; + g.heap = [gDevice newHeapWithDescriptor:hd]; + if (g.heap == nil) { return g; } + g.target = [g.heap newBufferWithLength:length options:MTLResourceStorageModeShared offset:0]; + g.guard = [g.heap newBufferWithLength:kGuardBytes options:MTLResourceStorageModeShared + offset:at]; + if (g.guard) { memset(g.guard.contents, 0xEE, kGuardBytes); } + readv("guard", "target %lu bytes at 0, guard %lu bytes at %lu", (unsigned long)length, + (unsigned long)kGuardBytes, (unsigned long)at); + return g; +} + +static void read_guard(Guarded g, const char *key) { + if (g.guard == nil) { readv(key, "no guard"); return; } + const unsigned char *p = (const unsigned char *)g.guard.contents; + NSUInteger bad = 0, first = 0; + for (NSUInteger i = 0; i < kGuardBytes; i++) { + if (p[i] != 0xEE) { + if (bad == 0) { first = i; } + bad++; + } + } + readv(key, "bytes-not-0xEE %lu first-at %lu", (unsigned long)bad, + bad ? (unsigned long)first : 0ul); +} + +// --------------------------------------------------------------------------------------------- +// `BindCount`: a descriptor's buffer and threadgroup-length counts. The reading is Metal's own +// `allocatedSize` of the buffer, which tells apart a count Metal reserved storage for from one it +// ignored: the kernel count moves a COMPUTE buffer's layout and is ignored by a RENDER buffer's, +// so the same count on a render buffer is the control that says "ignored", not "accepted". + +// The count a shape's word names. The word may be followed by more of the shape's name, so each +// spelling is matched as a PREFIX: `keep-2p31-at-40` passes "2p31-at-40" here, and reading that +// with `atoll` alone would silently measure a count of 2. +static NSUInteger count_of(const char *word) { + if (strncmp(word, "2p32m1", 6) == 0) { return 0xFFFFFFFFull; } + if (strncmp(word, "2p31", 4) == 0) { return 1ull << 31; } + if (strncmp(word, "2p26", 4) == 0) { return 1ull << 26; } + if (strncmp(word, "2p25", 4) == 0) { return 1ull << 25; } + if (strncmp(word, "2p24", 4) == 0) { return 1ull << 24; } + if (strncmp(word, "2p20", 4) == 0) { return 1ull << 20; } + return (NSUInteger)atoll(word); +} + +static int group_bind(const char *shape) { + // bind--on-- + const char *rest = shape + 5; + const char *field_end = strchr(rest, '-'); + if (field_end == NULL) { return 3; } + char field[16] = {0}; + strncpy(field, rest, (size_t)(field_end - rest) < 15 ? (size_t)(field_end - rest) : 15); + if (strncmp(field_end, "-on-", 4) != 0) { return 3; } + const char *kind = field_end + 4; + const char *kind_end = strchr(kind, '-'); + if (kind_end == NULL) { return 3; } + BOOL compute = strncmp(kind, "compute", 7) == 0; + NSUInteger count = count_of(kind_end + 1); + + MTLIndirectCommandBufferDescriptor *d = [[MTLIndirectCommandBufferDescriptor alloc] init]; + d.commandTypes = compute ? MTLIndirectCommandTypeConcurrentDispatch + : MTLIndirectCommandTypeDraw; + d.inheritPipelineState = NO; + d.inheritBuffers = NO; + if (strcmp(field, "kernel") == 0) { d.maxKernelBufferBindCount = count; } + else if (strcmp(field, "vertex") == 0) { d.maxVertexBufferBindCount = count; } + else if (strcmp(field, "fragment") == 0) { d.maxFragmentBufferBindCount = count; } + else if (strcmp(field, "object") == 0) { d.maxObjectBufferBindCount = count; } + else if (strcmp(field, "mesh") == 0) { d.maxMeshBufferBindCount = count; } + else if (strcmp(field, "tglen") == 0) { d.maxKernelThreadgroupMemoryBindCount = count; } + else { return 3; } + readv("descriptor", "commandTypes %s max%sBufferBindCount %llu maxCommandCount 8", + compute ? "ConcurrentDispatch" : "Draw", field, (unsigned long long)count); + + NSUInteger before = gDevice.currentAllocatedSize; + id b = + [gDevice newIndirectCommandBufferWithDescriptor:d maxCommandCount:8 + options:MTLResourceStorageModeShared]; + NSUInteger after = gDevice.currentAllocatedSize; + readv("made", "%s", b ? "yes" : "nil"); + readv("device-allocated", "before %lu after %lu delta %ld", (unsigned long)before, + (unsigned long)after, (long)after - (long)before); + if (b) { + readv("buffer", "size %lu allocatedSize %lu", (unsigned long)b.size, + (unsigned long)b.allocatedSize); + } + done(shape); + return 0; +} + +// --- Does a bind at an absurd index actually land? A compute buffer of `count` kernel buffers, +// the marking kernel bound at index 0 and the same buffer bound again at high indices, then +// command 0 dispatched: the marker proves the command ran and index 0's bind was kept, and the +// guard proves no high-index setter wrote outside its own storage. + +static int group_keep(const char *shape) { + // keep--at- + NSUInteger count = count_of(shape + 5); + const char *at = strstr(shape, "-at-"); + if (at == NULL) { return 3; } + NSUInteger index = count_of(at + 4); + id lib = library(); + if (lib == nil) { return 2; } + id ps = mark_pipeline(lib, YES); + if (ps == nil) { return 2; } + + MTLIndirectCommandBufferDescriptor *d = [[MTLIndirectCommandBufferDescriptor alloc] init]; + d.commandTypes = MTLIndirectCommandTypeConcurrentDispatch; + d.maxKernelBufferBindCount = count; + readv("descriptor", "maxKernelBufferBindCount %llu, bind also at index %llu", + (unsigned long long)count, (unsigned long long)index); + id b = + [gDevice newIndirectCommandBufferWithDescriptor:d maxCommandCount:2 + options:MTLResourceStorageModeShared]; + readv("made", "%s allocatedSize %lu", b ? "yes" : "nil", + b ? (unsigned long)b.allocatedSize : 0ul); + if (b == nil) { return 2; } + + Guarded g = guarded_buffer(256); + if (g.target == nil) { readv("heap", "nil"); return 2; } + memset(g.target.contents, 0, 256); + + id cmd = [b indirectComputeCommandAtIndex:0]; + [cmd setComputePipelineState:ps]; + [cmd setKernelBuffer:g.target offset:0 atIndex:0]; + readv("bind-0", "setKernelBuffer:atIndex:0 returned"); + [cmd setKernelBuffer:g.target offset:0 atIndex:index]; + readv("bind-high", "setKernelBuffer:atIndex:%llu returned", (unsigned long long)index); + [cmd concurrentDispatchThreadgroups:MTLSizeMake(1, 1, 1) + threadsPerThreadgroup:MTLSizeMake(8, 1, 1)]; + readv("dispatch", "concurrentDispatchThreadgroups: returned"); + + id cb = [gQueue commandBuffer]; + id enc = [cb computeCommandEncoder]; + [enc useResource:g.target usage:MTLResourceUsageRead | MTLResourceUsageWrite]; + [enc executeCommandsInBuffer:b withRange:NSMakeRange(0, 1)]; + [enc endEncoding]; + commit_and_read(cb, "command-buffer"); + const uint32_t *w = (const uint32_t *)g.target.contents; + readv("marker", "words 0-3: %08x %08x %08x %08x", w[0], w[1], w[2], w[3]); + read_guard(g, "guard-after"); + done(shape); + return 0; +} + +// --------------------------------------------------------------------------------------------- +// `NoCommandTypes`: each call the refusal covers, on a buffer of no command types, with the same +// call on a buffer of the matching command type beside it. + +static id icb(MTLIndirectCommandType types, BOOL inherit, + NSUInteger count) { + MTLIndirectCommandBufferDescriptor *d = [[MTLIndirectCommandBufferDescriptor alloc] init]; + d.commandTypes = types; + d.inheritPipelineState = inherit; + d.inheritBuffers = NO; + d.maxVertexBufferBindCount = 4; + d.maxFragmentBufferBindCount = 4; + d.maxKernelBufferBindCount = 4; + d.maxObjectBufferBindCount = 4; + d.maxMeshBufferBindCount = 4; + return [gDevice newIndirectCommandBufferWithDescriptor:d maxCommandCount:count + options:MTLResourceStorageModeShared]; +} + +// Execute `buffer`'s commands 0..count in a render pass over a 64 by 64 target, with `resident` +// resident, and read the target's first texels back. +static void execute_render(id buffer, NSUInteger count, + NSArray> *resident) { + id target = color_target(); + clear_color(target, -1.0f); + MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor]; + rp.colorAttachments[0].texture = target; + rp.colorAttachments[0].loadAction = MTLLoadActionLoad; + rp.colorAttachments[0].storeAction = MTLStoreActionStore; + id cb = [gQueue commandBuffer]; + id enc = [cb renderCommandEncoderWithDescriptor:rp]; + for (id r in resident) { + [enc useResource:r usage:MTLResourceUsageRead + stages:MTLRenderStageVertex | MTLRenderStageFragment]; + } + [enc executeCommandsInBuffer:buffer withRange:NSMakeRange(0, count)]; + [enc endEncoding]; + commit_and_read(cb, "command-buffer"); + read_texels(target, "target-after"); +} + +static int group_types(const char *shape) { + // types-- + const char *rest = shape + 6; + const char *dash = strchr(rest, '-'); + if (dash == NULL) { return 3; } + char kind[8] = {0}; + strncpy(kind, rest, (size_t)(dash - rest) < 7 ? (size_t)(dash - rest) : 7); + const char *call = dash + 1; + MTLIndirectCommandType types = 0; + if (strcmp(kind, "draw") == 0) { types = MTLIndirectCommandTypeDraw; } + else if (strcmp(kind, "disp") == 0) { types = MTLIndirectCommandTypeConcurrentDispatch; } + else if (strcmp(kind, "none") != 0) { return 3; } + + id b = icb(types, NO, 4); + readv("buffer", "commandTypes 0x%lx made %s size %lu allocatedSize %lu", + (unsigned long)types, b ? "yes" : "nil", b ? (unsigned long)b.size : 0ul, + b ? (unsigned long)b.allocatedSize : 0ul); + if (b == nil) { return 2; } + + if (strcmp(call, "make") == 0) { done(shape); return 0; } + + if (strcmp(call, "rangereset") == 0 || strcmp(call, "rangereset0") == 0) { + NSUInteger length = strcmp(call, "rangereset0") == 0 ? 0 : 4; + readv("reset", "resetWithRange: location 0 length %lu, about to call", + (unsigned long)length); + [b resetWithRange:NSMakeRange(0, length)]; + readv("reset", "resetWithRange: returned"); + done(shape); + return 0; + } + + if (strcmp(call, "getter-render") == 0) { + id cmd = [b indirectRenderCommandAtIndex:0]; + readv("getter", "indirectRenderCommandAtIndex:0 -> %s", cmd ? "an object" : "nil"); + done(shape); + return 0; + } + if (strcmp(call, "getter-compute") == 0) { + id cmd = [b indirectComputeCommandAtIndex:0]; + readv("getter", "indirectComputeCommandAtIndex:0 -> %s", cmd ? "an object" : "nil"); + done(shape); + return 0; + } + + if (strcmp(call, "exec") == 0) { + execute_render(b, 4, @[]); + done(shape); + return 0; + } + // Every call this buffer takes, then an execution and a commit: a setter that returns can + // still fail at commit, so the taken calls are read at commit too and not at the call alone. + if (strcmp(call, "taken-exec") == 0) { + id scratch = [gDevice newBufferWithLength:256 + options:MTLResourceStorageModeShared]; + id c = [b indirectComputeCommandAtIndex:0]; + [c setKernelBuffer:scratch offset:0 atIndex:0]; + [c setKernelBuffer:scratch offset:0 attributeStride:16 atIndex:1]; + [c setThreadgroupMemoryLength:256 atIndex:0]; + [c setStageInRegion:MTLRegionMake2D(0, 0, 8, 8)]; + [c setImageblockWidth:8 height:8]; + [c setBarrier]; + [c clearBarrier]; + id r = [b indirectRenderCommandAtIndex:0]; + [r setFragmentBuffer:scratch offset:0 atIndex:0]; + [r setBarrier]; + [r clearBarrier]; + [r reset]; + [b resetWithRange:NSMakeRange(0, 0)]; + readv("setters", "every call this buffer takes returned"); + execute_render(b, 4, @[scratch]); + done(shape); + return 0; + } + if (strcmp(call, "optimize") == 0) { + id cb = [gQueue commandBuffer]; + id blit = [cb blitCommandEncoder]; + [blit optimizeIndirectCommandBuffer:b withRange:NSMakeRange(0, 4)]; + [blit endEncoding]; + commit_and_read(cb, "command-buffer"); + done(shape); + return 0; + } + if (strncmp(call, "copy-", 5) == 0) { + // copy-to-draw, copy-from-draw, copy-to-none + BOOL to_draw = strcmp(call, "copy-to-draw") == 0; + BOOL from_draw = strcmp(call, "copy-from-draw") == 0; + MTLIndirectCommandType other = (to_draw || from_draw) ? MTLIndirectCommandTypeDraw : 0; + id o = icb(other, NO, 4); + if (o == nil) { readv("other", "nil"); return 2; } + id src = from_draw ? o : b; + id dst = from_draw ? b : o; + readv("copy", "source commandTypes 0x%lx destination commandTypes 0x%lx", + (unsigned long)(from_draw ? other : types), + (unsigned long)(from_draw ? types : other)); + id cb = [gQueue commandBuffer]; + id blit = [cb blitCommandEncoder]; + [blit copyIndirectCommandBuffer:src sourceRange:NSMakeRange(0, 4) destination:dst + destinationIndex:0]; + [blit endEncoding]; + commit_and_read(cb, "command-buffer"); + done(shape); + return 0; + } + if (strcmp(call, "argenc") == 0) { + MTLArgumentDescriptor *ad = [MTLArgumentDescriptor argumentDescriptor]; + ad.dataType = MTLDataTypeIndirectCommandBuffer; + ad.index = 0; + ad.access = MTLBindingAccessReadOnly; + id ae = [gDevice newArgumentEncoderWithArguments:@[ad]]; + id arg = [gDevice newBufferWithLength:ae.encodedLength + options:MTLResourceStorageModeShared]; + memset(arg.contents, 0, ae.encodedLength); + [ae setArgumentBuffer:arg offset:0]; + [ae setIndirectCommandBuffer:b atIndex:0]; + const unsigned char *p = (const unsigned char *)arg.contents; + char line[64]; + size_t at = 0; + for (size_t i = 0; i < 8; i++) { + at += (size_t)snprintf(line + at, sizeof(line) - at, "%02x", p[i]); + } + readv("argument-buffer", "%s (the ID Metal wrote)", line); + done(shape); + return 0; + } + + // The per-command setters. Each is reached through the getter first, which is its own reading. + id lib = library(); + if (lib == nil) { return 2; } + id scratch = [gDevice newBufferWithLength:256 + options:MTLResourceStorageModeShared]; + if (strncmp(call, "r-", 2) == 0) { + id cmd = [b indirectRenderCommandAtIndex:0]; + readv("getter", "indirectRenderCommandAtIndex:0 -> %s", cmd ? "an object" : "nil"); + const char *which = call + 2; + if (strcmp(which, "pipeline") == 0) { + id ps = draw_pipeline(lib, YES); + if (ps == nil) { return 2; } + [cmd setRenderPipelineState:ps]; + readv("setter", "setRenderPipelineState: returned"); + } else if (strcmp(which, "vbuf") == 0) { + [cmd setVertexBuffer:scratch offset:0 atIndex:0]; + readv("setter", "setVertexBuffer:offset:atIndex: returned"); + } else if (strcmp(which, "draw") == 0) { + [cmd drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 + instanceCount:1 baseInstance:0]; + readv("setter", "drawPrimitives: returned"); + } else if (strcmp(which, "fbuf") == 0) { + [cmd setFragmentBuffer:scratch offset:0 atIndex:0]; + readv("setter", "setFragmentBuffer:offset:atIndex: returned"); + } else if (strcmp(which, "obuf") == 0) { + [cmd setObjectBuffer:scratch offset:0 atIndex:0]; + readv("setter", "setObjectBuffer:offset:atIndex: returned"); + } else if (strcmp(which, "mbuf") == 0) { + [cmd setMeshBuffer:scratch offset:0 atIndex:0]; + readv("setter", "setMeshBuffer:offset:atIndex: returned"); + } else if (strcmp(which, "idraw") == 0) { + [cmd drawIndexedPrimitives:MTLPrimitiveTypeTriangleStrip indexCount:4 + indexType:MTLIndexTypeUInt32 indexBuffer:scratch indexBufferOffset:0 + instanceCount:1 baseVertex:0 baseInstance:0]; + readv("setter", "drawIndexedPrimitives: returned"); + } else if (strcmp(which, "mdraw") == 0) { + [cmd drawMeshThreadgroups:MTLSizeMake(1, 1, 1) + threadsPerObjectThreadgroup:MTLSizeMake(1, 1, 1) + threadsPerMeshThreadgroup:MTLSizeMake(1, 1, 1)]; + readv("setter", "drawMeshThreadgroups: returned"); + } else if (strcmp(which, "barrier") == 0) { + [cmd setBarrier]; + readv("setter", "setBarrier returned"); + } else if (strcmp(which, "clearbarrier") == 0) { + [cmd clearBarrier]; + readv("setter", "clearBarrier returned"); + } else if (strcmp(which, "objtglen") == 0) { + [cmd setObjectThreadgroupMemoryLength:256 atIndex:0]; + readv("setter", "setObjectThreadgroupMemoryLength:atIndex: returned"); + } else if (strcmp(which, "reset") == 0) { + [cmd reset]; + readv("setter", "the command's reset returned"); + } else { + return 3; + } + done(shape); + return 0; + } + if (strncmp(call, "c-", 2) == 0) { + id cmd = [b indirectComputeCommandAtIndex:0]; + readv("getter", "indirectComputeCommandAtIndex:0 -> %s", cmd ? "an object" : "nil"); + const char *which = call + 2; + if (strcmp(which, "pipeline") == 0) { + id ps = mark_pipeline(lib, YES); + if (ps == nil) { return 2; } + [cmd setComputePipelineState:ps]; + readv("setter", "setComputePipelineState: returned"); + } else if (strcmp(which, "kbuf") == 0) { + [cmd setKernelBuffer:scratch offset:0 atIndex:0]; + readv("setter", "setKernelBuffer:offset:atIndex: returned"); + } else if (strcmp(which, "dispatch") == 0) { + [cmd concurrentDispatchThreadgroups:MTLSizeMake(1, 1, 1) + threadsPerThreadgroup:MTLSizeMake(1, 1, 1)]; + readv("setter", "concurrentDispatchThreadgroups: returned"); + } else if (strcmp(which, "tglen") == 0) { + [cmd setThreadgroupMemoryLength:256 atIndex:0]; + readv("setter", "setThreadgroupMemoryLength:atIndex: returned"); + } else if (strcmp(which, "barrier") == 0) { + [cmd setBarrier]; + readv("setter", "setBarrier returned"); + } else if (strcmp(which, "clearbarrier") == 0) { + [cmd clearBarrier]; + readv("setter", "clearBarrier returned"); + } else if (strcmp(which, "dthreads") == 0) { + [cmd concurrentDispatchThreads:MTLSizeMake(8, 1, 1) + threadsPerThreadgroup:MTLSizeMake(8, 1, 1)]; + readv("setter", "concurrentDispatchThreads: returned"); + } else if (strcmp(which, "stagein") == 0) { + [cmd setStageInRegion:MTLRegionMake2D(0, 0, 8, 8)]; + readv("setter", "setStageInRegion: returned"); + } else if (strcmp(which, "imageblock") == 0) { + [cmd setImageblockWidth:8 height:8]; + readv("setter", "setImageblockWidth:height: returned"); + } else if (strcmp(which, "kbufstride") == 0) { + [cmd setKernelBuffer:scratch offset:0 attributeStride:16 atIndex:0]; + readv("setter", "setKernelBuffer:offset:attributeStride:atIndex: returned"); + } else if (strcmp(which, "reset") == 0) { + [cmd reset]; + readv("setter", "the command's reset returned"); + } else { + return 3; + } + done(shape); + return 0; + } + return 3; +} + +// --------------------------------------------------------------------------------------------- +// `PipelineWithoutSupport`: a pipeline state made without `supportIndirectCommandBuffers`, set on +// a command. The legs tell the setter apart from the execution, and ask whether a command buffer +// submitted after the fault still completes. + +static int group_support(const char *shape) { + // support--- + BOOL support = strncmp(shape + 8, "yes", 3) == 0; + const char *rest = strchr(shape + 8, '-'); + if (rest == NULL) { return 3; } + rest++; + BOOL compute = strncmp(rest, "compute", 7) == 0; + const char *leg = strchr(rest, '-'); + if (leg == NULL) { return 3; } + leg++; + readv("pipeline", "supportIndirectCommandBuffers %d kind %s leg %s", (int)support, + compute ? "compute" : "render", leg); + + id lib = library(); + if (lib == nil) { return 2; } + + if (compute) { + id ps = mark_pipeline(lib, support); + if (ps == nil) { return 2; } + id b = icb(MTLIndirectCommandTypeConcurrentDispatch, NO, 4); + if (b == nil) { readv("buffer", "nil"); return 2; } + Guarded g = guarded_buffer(256); + if (g.target == nil) { readv("heap", "nil"); return 2; } + memset(g.target.contents, 0, 256); + id cmd = [b indirectComputeCommandAtIndex:0]; + [cmd setComputePipelineState:ps]; + readv("setter", "setComputePipelineState: returned"); + [cmd setKernelBuffer:g.target offset:0 atIndex:0]; + [cmd concurrentDispatchThreadgroups:MTLSizeMake(1, 1, 1) + threadsPerThreadgroup:MTLSizeMake(8, 1, 1)]; + readv("dispatch", "concurrentDispatchThreadgroups: returned"); + if (strcmp(leg, "setter") == 0) { done(shape); return 0; } + id cb = [gQueue commandBuffer]; + id enc = [cb computeCommandEncoder]; + [enc useResource:g.target usage:MTLResourceUsageRead | MTLResourceUsageWrite]; + [enc executeCommandsInBuffer:b withRange:NSMakeRange(0, 1)]; + [enc endEncoding]; + commit_and_read(cb, "command-buffer"); + const uint32_t *w = (const uint32_t *)g.target.contents; + readv("marker", "words 0-3: %08x %08x %08x %08x", w[0], w[1], w[2], w[3]); + read_guard(g, "guard-after"); + if (strcmp(leg, "again") == 0) { + // A second, plainly valid command buffer after the fault: does the queue still work? + id out = [gDevice newBufferWithLength:256 + options:MTLResourceStorageModeShared]; + memset(out.contents, 0, 256); + id plain = mark_pipeline(lib, NO); + id cb2 = [gQueue commandBuffer]; + id e2 = [cb2 computeCommandEncoder]; + [e2 setComputePipelineState:plain]; + [e2 setBuffer:out offset:0 atIndex:0]; + [e2 dispatchThreadgroups:MTLSizeMake(1, 1, 1) + threadsPerThreadgroup:MTLSizeMake(8, 1, 1)]; + [e2 endEncoding]; + commit_and_read(cb2, "second-command-buffer"); + const uint32_t *v = (const uint32_t *)out.contents; + readv("second-marker", "words 0-3: %08x %08x %08x %08x", v[0], v[1], v[2], v[3]); + } + done(shape); + return 0; + } + + id ps = draw_pipeline(lib, support); + if (ps == nil) { return 2; } + id pts = quad_points(); + id b = icb(MTLIndirectCommandTypeDraw, NO, 4); + if (b == nil) { readv("buffer", "nil"); return 2; } + id cmd = [b indirectRenderCommandAtIndex:0]; + [cmd setRenderPipelineState:ps]; + readv("setter", "setRenderPipelineState: returned"); + [cmd setVertexBuffer:pts offset:0 atIndex:0]; + [cmd drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 + instanceCount:1 baseInstance:0]; + readv("draw", "drawPrimitives: returned"); + if (strcmp(leg, "setter") == 0) { done(shape); return 0; } + execute_render(b, 1, @[pts]); + if (strcmp(leg, "again") == 0) { + id t = color_target(); + clear_color(t, -1.0f); + MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor]; + rp.colorAttachments[0].texture = t; + rp.colorAttachments[0].loadAction = MTLLoadActionLoad; + rp.colorAttachments[0].storeAction = MTLStoreActionStore; + id plain = draw_pipeline(lib, NO); + id cb = [gQueue commandBuffer]; + id enc = [cb renderCommandEncoderWithDescriptor:rp]; + [enc setRenderPipelineState:plain]; + [enc setVertexBuffer:pts offset:0 atIndex:0]; + [enc drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4]; + [enc endEncoding]; + commit_and_read(cb, "second-command-buffer"); + read_texels(t, "second-target-after"); + } + done(shape); + return 0; +} + +// --------------------------------------------------------------------------------------------- +// `CommandType`: a draw of a kind the buffer's command types lack. The index buffer sits in a +// placement heap with a 0xEE guard next to it, so an indexed draw that paints nothing but reads or +// writes past its index buffer is still a reading. Two controls: the same indexed draw on a buffer +// of `DrawIndexed`, which must paint; and a draw of primitives on the same `Draw` buffer, which +// must paint. A run where all three read the same has measured nothing. + +static int group_kind(const char *shape) { + // kind--on- + const char *which = shape + 5; + const char *on = strstr(which, "-on-"); + if (on == NULL) { return 3; } + char drawn[16] = {0}; + strncpy(drawn, which, (size_t)(on - which) < 15 ? (size_t)(on - which) : 15); + const char *buffer_kind = on + 4; + + MTLIndirectCommandType types; + if (strcmp(buffer_kind, "draw") == 0) { types = MTLIndirectCommandTypeDraw; } + else if (strcmp(buffer_kind, "indexed") == 0) { types = MTLIndirectCommandTypeDrawIndexed; } + else if (strcmp(buffer_kind, "patches") == 0) { types = MTLIndirectCommandTypeDrawPatches; } + else if (strcmp(buffer_kind, "mesh") == 0) { + types = MTLIndirectCommandTypeDrawMeshThreadgroups; + } else { return 3; } + BOOL mesh_state = strcmp(drawn, "mesh") == 0 || strcmp(buffer_kind, "mesh") == 0; + + id lib = library(); + if (lib == nil) { return 2; } + id ps = mesh_state ? mesh_pipeline(lib, YES) : draw_pipeline(lib, YES); + if (ps == nil) { return 2; } + id pts = quad_points(); + id b = icb(types, NO, 4); + readv("buffer", "commandTypes 0x%lx made %s", (unsigned long)types, b ? "yes" : "nil"); + if (b == nil) { return 2; } + + // 64 bytes of indices -- 16 of them -- with a guard right after. + Guarded g = guarded_buffer(64); + if (g.target == nil) { readv("heap", "nil"); return 2; } + { + uint32_t *w = (uint32_t *)g.target.contents; + for (NSUInteger i = 0; i < 16; i++) { w[i] = (uint32_t)(i & 3); } + } + + id cmd = [b indirectRenderCommandAtIndex:0]; + readv("getter", "indirectRenderCommandAtIndex:0 -> %s", cmd ? "an object" : "nil"); + [cmd setRenderPipelineState:ps]; + readv("setter", "setRenderPipelineState: returned"); + if (strcmp(drawn, "indexed") == 0) { + [cmd setVertexBuffer:pts offset:0 atIndex:0]; + [cmd drawIndexedPrimitives:MTLPrimitiveTypeTriangleStrip indexCount:4 + indexType:MTLIndexTypeUInt32 indexBuffer:g.target indexBufferOffset:0 + instanceCount:1 baseVertex:0 baseInstance:0]; + readv("draw", "drawIndexedPrimitives: returned"); + } else if (strcmp(drawn, "patch") == 0) { + id factors = [gDevice newBufferWithLength:64 + options:MTLResourceStorageModeShared]; + [cmd drawPatches:4 patchStart:0 patchCount:1 patchIndexBuffer:nil +patchIndexBufferOffset:0 instanceCount:1 baseInstance:0 + tessellationFactorBuffer:factors tessellationFactorBufferOffset:0 +tessellationFactorBufferInstanceStride:0]; + readv("draw", "drawPatches: returned"); + } else if (strcmp(drawn, "mesh") == 0) { + [cmd drawMeshThreadgroups:MTLSizeMake(1, 1, 1) + threadsPerObjectThreadgroup:MTLSizeMake(1, 1, 1) + threadsPerMeshThreadgroup:MTLSizeMake(1, 1, 1)]; + readv("draw", "drawMeshThreadgroups: returned"); + } else if (strcmp(drawn, "draw") == 0) { + [cmd setVertexBuffer:pts offset:0 atIndex:0]; + [cmd drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4 + instanceCount:1 baseInstance:0]; + readv("draw", "drawPrimitives: returned"); + } else { + return 3; + } + execute_render(b, 1, @[pts, g.target]); + read_guard(g, "guard-after"); + done(shape); + return 0; +} + +// --------------------------------------------------------------------------------------------- + +static const char *const kShapes[] = { + // BindCount: the count on the buffer kind whose layout it moves, and on the kind that ignores + // it (the control that says "ignored", not "accepted"). + "bind-kernel-on-compute-4", "bind-kernel-on-compute-31", "bind-kernel-on-compute-32", + "bind-kernel-on-compute-33", "bind-kernel-on-compute-1024", + "bind-kernel-on-compute-65535", "bind-kernel-on-compute-65536", + "bind-kernel-on-compute-65537", "bind-kernel-on-compute-70000", + "bind-kernel-on-compute-2p20", "bind-kernel-on-compute-2p24", + "bind-kernel-on-compute-2p25", "bind-kernel-on-compute-2p26", + "bind-kernel-on-compute-2p31", "bind-kernel-on-compute-2p32m1", + "bind-kernel-on-draw-4", "bind-kernel-on-draw-65536", "bind-kernel-on-draw-2p31", + "bind-vertex-on-draw-4", "bind-vertex-on-draw-1024", "bind-vertex-on-draw-65536", + "bind-vertex-on-draw-65537", "bind-vertex-on-draw-2p31", "bind-vertex-on-draw-2p32m1", + "bind-fragment-on-draw-65536", "bind-fragment-on-draw-2p31", + "bind-object-on-draw-65536", "bind-mesh-on-draw-65536", + "bind-tglen-on-compute-31", "bind-tglen-on-compute-32", "bind-tglen-on-compute-1024", + "bind-tglen-on-compute-65536", "bind-tglen-on-compute-65537", + "bind-tglen-on-compute-2p31", "bind-tglen-on-compute-2p32m1", + // Does a bind past the record's 32 slots, and past the count, land at all? + "keep-1024-at-0", "keep-1024-at-40", "keep-1024-at-1000", "keep-1024-at-2000", + "keep-70000-at-40", "keep-70000-at-69999", "keep-65537-at-65536", + "keep-2p20-at-1048575", "keep-2p31-at-40", "keep-2p31-at-2p31", + // NoCommandTypes: the getter, each setter, the CPU reset, the execution, the optimize, the + // copies and the argument-buffer encoding, on a buffer of no command types and on one of the + // matching type. + "types-none-make", "types-draw-make", "types-disp-make", + "types-none-getter-render", "types-draw-getter-render", + "types-none-getter-compute", "types-disp-getter-compute", + "types-none-r-pipeline", "types-draw-r-pipeline", + "types-none-r-vbuf", "types-draw-r-vbuf", + "types-none-r-draw", "types-draw-r-draw", + "types-none-r-reset", "types-draw-r-reset", + "types-none-r-fbuf", "types-draw-r-fbuf", + "types-none-r-obuf", "types-draw-r-obuf", + "types-none-r-mbuf", "types-draw-r-mbuf", + "types-none-r-idraw", "types-draw-r-idraw", + "types-none-r-mdraw", "types-draw-r-mdraw", + "types-none-r-barrier", "types-draw-r-barrier", + "types-none-r-clearbarrier", "types-draw-r-clearbarrier", + "types-none-r-objtglen", "types-draw-r-objtglen", + "types-none-c-pipeline", "types-disp-c-pipeline", + "types-none-c-kbuf", "types-disp-c-kbuf", + "types-none-c-dispatch", "types-disp-c-dispatch", + "types-none-c-tglen", "types-disp-c-tglen", + "types-none-c-barrier", "types-disp-c-barrier", + "types-none-c-reset", "types-disp-c-reset", + "types-none-c-clearbarrier", "types-disp-c-clearbarrier", + "types-none-c-dthreads", "types-disp-c-dthreads", + "types-none-c-stagein", "types-disp-c-stagein", + "types-none-c-imageblock", "types-disp-c-imageblock", + "types-none-c-kbufstride", "types-disp-c-kbufstride", + "types-none-rangereset", "types-draw-rangereset", + "types-none-rangereset0", "types-draw-rangereset0", + "types-none-exec", "types-draw-exec", + "types-none-taken-exec", "types-draw-taken-exec", + "types-none-optimize", "types-draw-optimize", + "types-none-copy-to-draw", "types-none-copy-from-draw", "types-none-copy-to-none", + "types-draw-copy-to-draw", + "types-none-argenc", "types-draw-argenc", + // PipelineWithoutSupport: the setter apart from the execution, render and compute, and whether + // the next command buffer still completes. + "support-yes-render-setter", "support-no-render-setter", + "support-yes-render-exec", "support-no-render-exec", + "support-yes-render-again", "support-no-render-again", + "support-yes-compute-setter", "support-no-compute-setter", + "support-yes-compute-exec", "support-no-compute-exec", + "support-yes-compute-again", "support-no-compute-again", + // CommandType: a draw of a kind the buffer's types lack, with both controls. + "kind-draw-on-draw", "kind-indexed-on-indexed", "kind-indexed-on-draw", + "kind-indexed-on-patches", "kind-patch-on-draw", "kind-patch-on-patches", + "kind-mesh-on-mesh", "kind-mesh-on-draw", "kind-draw-on-mesh", +}; + +int main(int argc, const char *argv[]) { + if (argc == 2 && strcmp(argv[1], "--list") == 0) { + for (size_t i = 0; i < sizeof(kShapes) / sizeof(kShapes[0]); i++) { + printf("%s\n", kShapes[i]); + } + return 0; + } + if (argc != 2) { + fprintf(stderr, "usage: %s |--list\n", argv[0]); + return 2; + } + const char *shape = argv[1]; + @autoreleasepool { + gDevice = MTLCreateSystemDefaultDevice(); + if (gDevice == nil) { + fprintf(stderr, "no Metal device\n"); + return 2; + } + gQueue = [gDevice newCommandQueue]; + head(); + printf("SHAPE %s\n", shape); + fflush(stdout); + + if (strncmp(shape, "bind-", 5) == 0) { return group_bind(shape); } + if (strncmp(shape, "keep-", 5) == 0) { return group_keep(shape); } + if (strncmp(shape, "types-", 6) == 0) { return group_types(shape); } + if (strncmp(shape, "support-", 8) == 0) { return group_support(shape); } + if (strncmp(shape, "kind-", 5) == 0) { return group_kind(shape); } + fprintf(stderr, "no such shape: %s\n", shape); + return 2; + } +} diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index ad7ca752b..34372df3d 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -57,11 +57,11 @@ //! as they stand when the execution's batch is submitted, or for records the GPU may write, once //! the work before it completed ([`indirect_execute`](super::indirect_execute)); it refuses a //! buffer of render commands, which a render encoder's runs (`render/executions.rs`). -//! - **Creation.** The records of every command must fit one buffer of the device's -//! `max_buffer_length`; a larger buffer is refused, naming the limit. The record format holds -//! every render command type, mesh draws among them, whose object and mesh buffers a command sets -//! as its vertex and fragment buffers; a buffer of either mesh kind holds both mesh draws, as -//! Metal's does. +//! - **Creation.** The records of every command, and the slots past them, must each fit one buffer +//! of the device's `max_buffer_length`; a larger buffer is refused, naming the limit. The record +//! format holds every render command type, mesh draws among them, whose object and mesh buffers a +//! command sets as its vertex and fragment buffers; a buffer of either mesh kind holds both mesh +//! draws, as Metal's does. use super::address::{AddressPlacement, Place, RecordsId}; use super::buffer::{Buffer, Modes}; @@ -108,16 +108,6 @@ use std::sync::{Arc, Mutex, Weak}; /// The threadgroup lengths a fresh descriptor binds, as Metal's answers. const DEFAULT_THREADGROUP_LENGTHS: u32 = 31; -/// The most kernel, vertex or fragment buffers, or threadgroup lengths, a descriptor may bind. -/// Metal's validation stops more than 31, but plain Metal makes a buffer of more, whose commands -/// keep a buffer set at any index below the count and whose functions bind none past 30 (32, 33 and -/// 64 kernel buffers, 32 threadgroup lengths, 32 and 33 vertex and 33 fragment buffers, each set at -/// its last index and run). Its storage grew with the count to 65536 kernel buffers (1024 vertex -/// and fragment buffers and threadgroup lengths, as kernel buffers grow), but a buffer of 2^31 -/// was made as small as one of few, and 2^32 - 1 ended its process: past 65536 its storage is not -/// defined. -const MOST_BINDS: u32 = 65536; - /// `count` bindings, of which the record holds `capacity`: the ones a command's record holds. fn held(count: u32, capacity: u32) -> u32 { count.min(capacity) @@ -286,10 +276,12 @@ impl IndirectCommandBufferDescriptor { && self.inherit_blend_color } - /// The record format's descriptor and inheritance of this descriptor, or what refuses it - /// for `call`. - fn records(&self, call: &'static str) -> Result<(CommandDescriptor, Inheritance), Error> { - let problem = |problem| invalid(call, Problem::IndirectCommandBuffer(problem)); + /// The record format's descriptor and inheritance of this descriptor. Every buffer, vertex, + /// fragment, object, mesh and threadgroup-length count is taken: the record holds the first + /// 32 slots of a stage and the first 31 lengths, the rest lie past them ([`Overflow`]), and a + /// count whose slots the runtime cannot lay out in one buffer is refused where they are made + /// (`new_indirect_command_buffer`, `IndirectCommandBufferPastMaxBufferLength`). + fn records(&self) -> (CommandDescriptor, Inheritance) { let types = self.command_types; // No command types make a buffer of compute records no command reaches (the buffer's // calls refuse them, `check_command_types`). @@ -309,20 +301,7 @@ impl IndirectCommandBufferDescriptor { buffers: source(self.inherit_buffers), }; if !mixed && types.intersects(RENDER_TYPES) { - for count in [ - self.max_vertex_buffer_bind_count, - self.max_fragment_buffer_bind_count, - self.max_object_buffer_bind_count, - self.max_mesh_buffer_bind_count, - ] { - if count > MOST_BINDS { - return Err(problem(IndirectCommandBufferProblem::BindCount { - count, - limit: MOST_BINDS, - })); - } - } - return Ok(( + return ( CommandDescriptor::Render { draws: RenderDraws { primitives: types.contains(IndirectCommandType::DRAW), @@ -352,18 +331,7 @@ impl IndirectCommandBufferDescriptor { support_dynamic_attribute_stride: self.support_dynamic_attribute_stride, }, inheritance, - )); - } - for count in [ - self.max_kernel_buffer_bind_count, - self.max_kernel_threadgroup_memory_bind_count, - ] { - if count > MOST_BINDS { - return Err(problem(IndirectCommandBufferProblem::BindCount { - count, - limit: MOST_BINDS, - })); - } + ); } let dispatch = match ( types.contains(IndirectCommandType::CONCURRENT_DISPATCH), @@ -373,7 +341,7 @@ impl IndirectCommandBufferDescriptor { (true, false) => ComputeDispatch::Threadgroups, _ => ComputeDispatch::Threads, }; - Ok(( + ( CommandDescriptor::Compute { dispatch, max_buffer_bind_count: held(self.max_kernel_buffer_bind_count, RECORD_BUFFERS), @@ -384,7 +352,7 @@ impl IndirectCommandBufferDescriptor { support_dynamic_attribute_stride: self.support_dynamic_attribute_stride, }, inheritance, - )) + ) } } @@ -396,36 +364,32 @@ impl IndirectCommandBufferDescriptor { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IndirectCommandBufferProblem { - /// A command, a CPU reset, a read-back or an argument buffer's encoding of a buffer of no - /// command types, or its blit copy to or from a buffer of command types. Plain Metal makes - /// such a buffer, where its validation stops it, and executes, resets, optimizes and copies - /// it to another such as nothing, as the runtime does, but its process ends at a command's - /// first setter and at its CPU reset. + /// A call on a buffer of no command types that plain Metal's process does not survive: a + /// command's pipeline-state setter, its vertex-buffer setter, its draw, a compute command's + /// dispatch or `reset`, and a CPU reset of a range of commands. Plain Metal makes such a + /// buffer, where its validation stops it, and gives its commands, executes, resets, optimizes + /// and copies it as nothing, as the runtime does; the read-back is refused too, as a runtime + /// extension with no Metal call to measure. /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal ends the process, SIGBUS, at - /// a command's `setRenderPipelineState:` and at `resetWithRange:`, where a buffer of `Draw` - /// takes both; but it encodes such a buffer into an argument buffer to the same bytes a `Draw` - /// one encodes to, and completes its blit copy into a `Draw` buffer, its execution in a pass - /// and its optimize with no error, so those refusals reach past Metal. The read-back is the - /// runtime's own extension and has no Metal call to measure). + /// Basis: metal-measured (an Apple M3 Max, macOS 27.0.1, build 26A434, the validation layer + /// off, one shape per process, three processes a shape, each beside the same call on a buffer + /// of the matching command type, `probes/icb_refusals_that_metal_takes.m`. Plain Metal ends + /// the process — SIGBUS, SIGSEGV in some processes of the same shape — at + /// `setRenderPipelineState:`, `setVertexBuffer:offset:atIndex:`, `drawPrimitives:`, + /// `drawIndexedPrimitives:`, `setComputePipelineState:`, `concurrentDispatchThreadgroups:`, + /// `concurrentDispatchThreads:`, a compute command's `reset`, and `resetWithRange:` of a + /// non-empty range, where the buffer of the matching type takes each. It **takes**, and the + /// runtime takes with it, `indirectRenderCommandAtIndex:` and + /// `indirectComputeCommandAtIndex:` — an object, not nil — a render command's `reset`, + /// `setFragmentBuffer:`, `setBarrier` and `clearBarrier`, `setKernelBuffer:` plain and with an + /// attribute stride, `setThreadgroupMemoryLength:atIndex:`, `setStageInRegion:`, + /// `setImageblockWidth:height:`, `resetWithRange:` of an empty range, the execution in a pass + /// which paints nothing, `optimizeIndirectCommandBuffer:`, the blit copy in either direction, + /// and the argument-buffer encoding, to the same ID bytes a `Draw` buffer encodes to. The + /// argument-buffer encoding and the blit copy are still refused, in `argument_encoder.rs` and + /// `blit_indirect.rs`, and reach past Metal there. The read-back is a runtime extension and + /// has no Metal call to measure). NoCommandTypes, - /// A descriptor with more kernel, vertex, fragment, object or mesh buffers, or kernel - /// threadgroup lengths, than 65536, past which plain Metal's storage is not defined (a buffer - /// of 2^31 kernel buffers was made as small as one of few). - /// Metal's validation stops more than 31, but plain Metal makes a buffer of up to 65536, as - /// the runtime does. - /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal makes the buffer at 4, at - /// 65536, at 2^31 and at 2^32 - 1 kernel buffers alike, each taking the same 16 KiB of the - /// device's allocated size, where `maxCommandCount` moves that figure — 16 KiB at one command - /// against 64 KiB at 64 — so the storage is undefined rather than refused and the refusal - /// reaches past Metal). - BindCount { - /// The count the descriptor asks for. - count: u32, - /// The most the runtime binds. - limit: u32, - }, /// A range of commands not inside the buffer: for `reset_with_range`, one that starts at or /// past its size (an empty one too, but the empty one at the size) or ends past it; for the /// read-back, one that ends past it. @@ -447,14 +411,23 @@ pub enum IndirectCommandBufferProblem { /// at `setRenderPipelineState:` on a command of a buffer whose `inheritPipelineState` is set, /// where the same setter on a buffer that does not inherit it runs the draw). InheritedPipelineState, - /// A pipeline state made without `supportIndirectCommandBuffers`: plain Metal takes the setter - /// and the draw, and its GPU faults where the command runs. + /// A pipeline state made without `supportIndirectCommandBuffers`, set on a command. A compute + /// state ends plain Metal's process at the setter; a render state is taken, and its command + /// faults Metal's GPU where it runs. /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal's `setRenderPipelineState:` - /// and `drawPrimitives:` on the command both return rather than ending the process, and the - /// command buffer fails at execution, "Caused GPU Address Fault Error", where the same pipeline - /// with the flag set draws: so the refusal stands on undefined behaviour and not on a refusal - /// of Metal's, and reaches past it). + /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1, build 26A434, the validation layer off, + /// one shape per process, three processes a shape, + /// `probes/icb_refusals_that_metal_takes.m`. The two kinds do not answer alike. + /// `setComputePipelineState:` with a state made without the flag ends the process, SIGSEGV, + /// where the same call with the flag set dispatches and the kernel's marker words read back: + /// that arm is a refusal of Metal's own. `setRenderPipelineState:` and `drawPrimitives:` both + /// return, and the command buffer then fails at execution with status 5 and `Caused GPU + /// Address Fault Error 0000000b:kIOGPUCommandBufferCallbackErrorPageFault`, leaving the target + /// at its clear value, where the same pipeline with the flag set paints; a plainly valid + /// command buffer submitted after the fault completes and paints, so the fault does not poison + /// the queue. That arm stands on undefined behaviour — a GPU address fault is not an answer — + /// and so reaches past Metal, and the refusal is kept there deliberately: a typed `Invalid` at + /// the setter is the useful answer where Metal's own is a page fault at execution). PipelineWithoutSupport, /// A draw of a kind (`DRAW_INDEXED`, `DRAW_PATCHES` or `DRAW_INDEXED_PATCHES`, a probe) whose /// record the buffer's records cannot hold: an indexed draw on a buffer of draws of primitives @@ -466,11 +439,19 @@ pub enum IndirectCommandBufferProblem { /// not enabled on this indirect command buffer"), but plain Metal runs one their records hold, /// as the runtime does. /// - /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1: plain Metal ends the process, SIGBUS, at - /// a patch draw on a buffer of `DRAW` alone, at a mesh pipeline's `setRenderPipelineState:` on - /// such a buffer, and at a draw of primitives on a buffer of `DRAW_MESH_THREADGROUPS` alone; - /// but an indexed draw on a buffer of `DRAW` alone completes with no error and paints nothing, - /// where the same draw on a buffer of `DRAW_INDEXED` paints, so that kind reaches past Metal). + /// Basis: metal-takes (an Apple M3 Max, macOS 27.0.1, build 26A434, the validation layer off, + /// one shape per process, `probes/icb_refusals_that_metal_takes.m`. Plain Metal ends the + /// process, SIGBUS, at a patch draw on a buffer of `DRAW` alone, at a mesh pipeline's + /// `setRenderPipelineState:` on such a buffer, and at a draw of primitives on a buffer of + /// `DRAW_MESH_THREADGROUPS` alone, three processes each. One cell reaches past Metal, and one + /// only: an indexed draw on a buffer of `DRAW` alone completes with no error and paints + /// nothing, three processes, with both controls live beside it — a draw of primitives on the + /// same buffer paints 0.75, and the same indexed draw on a buffer of `DRAW_INDEXED` and on one + /// of `DRAW_PATCHES` paints 0.75 — and with no byte of a 0xEE guard at the next 256-aligned + /// placement-heap offset past the index buffer touched. Taking it needs the execution to run + /// nothing for such a record, which is `Asked::of` in `render/executions.rs`, where + /// `Asked::Nothing` already stands for a draw that runs nothing: that side is not built, so + /// the setter stays refused rather than taken and then painted). CommandType(IndirectCommandType), /// A compute command of a buffer whose commands are render ones, or a setter plain Metal does /// not ignore on a render command of a buffer whose commands are dispatches. Plain Metal ends @@ -517,15 +498,34 @@ impl Device { /// `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:`: a buffer of /// `max_count` reset commands of `descriptor`, `max_count` 0 included. /// - /// Refused `Invalid`: what plain Metal makes no defined storage of (more than 65536 kernel, - /// vertex or fragment buffers or threadgroup lengths, `Memoryless` storage). Plain Metal - /// makes what its validation stops of the rest, and so does the runtime: no command types (a - /// buffer that executes as nothing and whose commands are refused), render types beside - /// compute types (a buffer of compute commands), more than 31 buffers or lengths. A placement - /// at 16384 or more is refused `Invalid` (`Problem::ResourceId`): Metal writes past its table - /// of IDs there. Refused `NotImplemented`: records past one buffer of the device's - /// `max_buffer_length` (`IndirectCommandBufferPastMaxBufferLength`). The device's memory can - /// refuse it too (`OutOfMemory`), and so can the IDs, once every ID below 2^31 is held. + /// Refused `Invalid`: `Memoryless` storage. Plain Metal makes what its validation stops of + /// the rest, and so does the runtime: no command types (a buffer that executes as nothing and + /// whose commands' pipeline, vertex-buffer and draw setters are refused), render types beside + /// compute types (a buffer of compute commands), more than 31 buffers or lengths of a stage. A + /// placement at 16384 or more is refused `Invalid` (`Problem::ResourceId`): Metal writes past + /// its table of IDs there. Refused `NotImplemented`: records, or slots past the records, that + /// one buffer of the device's `max_buffer_length` cannot hold + /// (`IndirectCommandBufferPastMaxBufferLength`). The device's memory can refuse it too + /// (`OutOfMemory`), and so can the IDs, once every ID below 2^31 is held. + /// + /// Every buffer and threadgroup-length count is taken, however large: plain Metal lays out + /// the slots the count asks for and the runtime does the same. Measured on an Apple M3 Max + /// under macOS 27.0.1 (`probes/icb_refusals_that_metal_takes.m`, one shape per process, the + /// validation layer off), on a buffer of 8 commands, reading Metal's own `allocatedSize`: a + /// compute buffer's `maxKernelBufferBindCount` grows it from 16 KiB at 4, 31, 32 and 33 to 80 + /// KiB at 1024, 4.01 MiB at 65535, 65536 and 65537, 4.28 MiB at 70000, 64 MiB at 2^20, 1 GiB + /// at 2^24 and 2 GiB at 2^25, and a render buffer's `maxVertexBufferBindCount` and + /// `maxFragmentBufferBindCount` grow it the same way; a bind at index 69999 of a buffer of + /// 70000 returns, and the command still dispatches with the buffer bound at index 0 and no + /// byte of a 0xEE guard beside it touched. The same count on a buffer whose layout ignores it + /// (a kernel count on a render buffer) leaves `allocatedSize` at 16 KiB at 4, at 65536 and at + /// 2^31 alike, and a threadgroup-length count leaves it at 16 KiB at every value from 31 to + /// 2^32 - 1: a reading of such a count measures Metal ignoring it, not Metal taking it. + /// Past where Metal lays the slots out its storage is not defined: at 2^26 kernel buffers of 8 + /// commands and at 2^32 - 1 its creation ends the process, and at 2^31 it makes a 16-KiB + /// buffer whose `setKernelBuffer:atIndex:` at index 2^31 then ends the process. The runtime + /// lays out every slot it answers for, so what will not fit is the `NotImplemented` gap above + /// rather than a claim that Metal refuses it. pub fn new_indirect_command_buffer( &self, descriptor: &IndirectCommandBufferDescriptor, @@ -538,7 +538,7 @@ impl Device { if modes.storage == StorageMode::Memoryless { return Err(invalid(CALL, Problem::StorageMode)); } - let (records, inheritance) = descriptor.records(CALL)?; + let (records, inheritance) = descriptor.records(); // A device that claims Apple10 would draw a command with its own render states where the // buffer does not inherit them: not built. if !descriptor.inherits_render_states() && self.supports_family(GpuFamily::Apple10.raw()) { @@ -557,6 +557,14 @@ impl Device { if length > max_buffer_length { return Err(past_length()); } + // The slots past the records, measured before anything is taken: a descriptor may count + // buffers of a stage no buffer of the device can lay out, and the refusal names that + // limit rather than whatever the steps below run out of first. + let layout = OverflowLayout::of(descriptor); + let overflow_bytes = layout.map(|layout| layout.bytes(size)); + if overflow_bytes.is_some_and(|bytes| bytes > max_buffer_length) { + return Err(past_length()); + } // The records are host-visible whatever the storage mode asked for: the CPU initializes // them, and reads them back. let backing = Modes { @@ -585,12 +593,8 @@ impl Device { Place::Records(held.id), )?; // The slots past the record's, of their own buffer, as long as Metal's storage grows. - let overflow = match OverflowLayout::of(descriptor) { - Some(layout) => { - let bytes = layout.bytes(size); - if bytes > max_buffer_length { - return Err(past_length()); - } + let overflow = match (layout, overflow_bytes) { + (Some(layout), Some(bytes)) => { let storage = self.zeroed_buffer( CALL, bytes.max(SLOT_BYTES), @@ -607,7 +611,7 @@ impl Device { commands: size, }) } - None => None, + _ => None, }; let options = ResourceOptions::new(modes.storage, modes.cache, storage.hazard_tracking_mode()); @@ -1150,9 +1154,12 @@ impl OverflowLayout { self.slot_bytes() + self.lengths_bytes() } - /// The bytes an overflow of `commands` commands holds. + /// The bytes an overflow of `commands` commands holds, saturated: a descriptor may ask for + /// up to 2^32 - 1 slots of a stage of each of up to 2^32 - 1 commands, whose product is past + /// `u64`, and a wrap would walk past the check that refuses what one buffer cannot hold + /// (`new_indirect_command_buffer`). fn bytes(&self, commands: u32) -> u64 { - u64::from(commands) * self.command_bytes() + u64::from(commands).saturating_mul(self.command_bytes()) } } @@ -1602,12 +1609,14 @@ impl IndirectCommandBuffer { /// Command `index` for `call`, of a buffer whose commands are render ones where `render`: /// refused (`Invalid`) for a buffer of the other kind's commands (but a render command of a - /// buffer of dispatches alone) and a buffer of no command types, and - /// `NotImplemented(IndirectCommandPastSize)` for an index at or past the size. A `Private` - /// buffer's commands are the CPU's as a `Shared` one's are, as plain Metal encodes, reads back - /// and runs them. + /// buffer of dispatches alone), and `NotImplemented(IndirectCommandPastSize)` for an index at + /// or past the size. A buffer of no command types gives a command, as plain Metal gives one + /// (an M3 Max, macOS 27.0.1: `indirectRenderCommandAtIndex:0` and + /// `indirectComputeCommandAtIndex:0` both answered an object, three processes each); the + /// command's own calls carry the refusal, each where plain Metal's process ends + /// (`NoCommandTypes`). A `Private` buffer's commands are the CPU's as a `Shared` one's are, as + /// plain Metal encodes, reads back and runs them. fn command_at(&self, call: &'static str, index: u64, render: bool) -> Result { - self.check_command_types(call)?; self.check_kind(call, render)?; if index >= u64::from(self.0.size) { return Err(Error::NotImplemented(RuntimeGap::IndirectCommandPastSize { @@ -1642,9 +1651,9 @@ impl IndirectCommandBuffer { } /// Refuse, for `call`, a buffer of no command types (`Invalid`, - /// `IndirectCommandBufferProblem::NoCommandTypes`): plain Metal makes one, and executes, - /// resets, optimizes and copies it as nothing, but its process ends at a command's first setter - /// and at its CPU reset; what else it does with one was not measured. + /// `IndirectCommandBufferProblem::NoCommandTypes`): plain Metal makes one, gives its commands, + /// and executes, resets, optimizes and copies it as nothing, but its process ends at the calls + /// the refusal's own doc lists. Only those calls, and the read-back, call this. pub(super) fn check_command_types(&self, call: &'static str) -> Result<(), Error> { if self.has_no_command_types() { return Err(problem(call, IndirectCommandBufferProblem::NoCommandTypes)); @@ -2020,10 +2029,16 @@ impl IndirectCommandBuffer { /// `resetWithRange:`: reset commands `range`, as a fresh buffer's. Refused (`Invalid`) unless /// the range starts below the size and ends at or before it, an empty range included, as /// Metal's validation refuses it, but for the empty range at the size, which resets nothing - /// as plain Metal's does; a `Private` buffer's are reset too. + /// as plain Metal's does; a `Private` buffer's are reset too. On a buffer of no command types + /// a range of commands is refused (`NoCommandTypes`), where plain Metal's process ends, and + /// an empty range resets nothing, as plain Metal's returns (an Apple M3 Max, macOS 27.0.1: + /// `resetWithRange:` of location 0 length 4 ended the process and of location 0 length 0 + /// returned, three processes each, where both returned on a buffer of `Draw`). pub fn reset_with_range(&self, range: Range) -> Result<(), Error> { - self.check_command_types("reset_with_range")?; let range = self.inside(&range)?; + if !range.is_empty() { + self.check_command_types("reset_with_range")?; + } self.reset_commands(range) } @@ -3447,6 +3462,7 @@ impl IndirectComputeCommand { /// state of another device. pub fn set_compute_pipeline_state(&self, state: &ComputePipelineState) -> Result<(), Error> { const CALL: &str = "set_compute_pipeline_state"; + self.icb.check_command_types(CALL)?; if !state.device().same(self.icb.device()) { return Err(invalid(CALL, Problem::ForeignObject)); } @@ -3548,10 +3564,13 @@ impl IndirectComputeCommand { threadgroups: Size, threads_per_threadgroup: Size, ) -> Result<(), Error> { - self.set_dispatch(Action::DispatchThreadgroups { - grid: low_bits(threadgroups), - local_size: low_bits(threads_per_threadgroup), - }) + self.set_dispatch( + "concurrent_dispatch_threadgroups", + Action::DispatchThreadgroups { + grid: low_bits(threadgroups), + local_size: low_bits(threads_per_threadgroup), + }, + ) } /// `concurrentDispatchThreads:threadsPerThreadgroup:`: the command dispatches `threads` in @@ -3563,15 +3582,20 @@ impl IndirectComputeCommand { threads: Size, threads_per_threadgroup: Size, ) -> Result<(), Error> { - self.set_dispatch(Action::DispatchThreads { - grid: low_bits(threads), - local_size: low_bits(threads_per_threadgroup), - }) + self.set_dispatch( + "concurrent_dispatch_threads", + Action::DispatchThreads { + grid: low_bits(threads), + local_size: low_bits(threads_per_threadgroup), + }, + ) } /// Set the record's dispatch `action`, which every compute buffer's records hold - /// (`CommandDescriptor::holds`). - fn set_dispatch(&self, action: Action) -> Result<(), Error> { + /// (`CommandDescriptor::holds`). Refused for `call` on a buffer of no command types + /// (`NoCommandTypes`), where plain Metal's process ends. + fn set_dispatch(&self, call: &'static str, action: Action) -> Result<(), Error> { + self.icb.check_command_types(call)?; self.edit(RecordField::Action(action), None) } @@ -3641,6 +3665,7 @@ impl IndirectComputeCommand { /// too, as plain Metal's reads back after `reset` (the size set before it, measured by the /// integration consumer on an M3 without API validation). pub fn reset(&self) -> Result<(), Error> { + self.icb.check_command_types("reset")?; self.icb.reset_command(self.index, |record, _| { let retained = record.bindings.pipeline.or(record.retained_pipeline); *record = CommandRecord { @@ -3658,19 +3683,29 @@ impl IndirectComputeCommand { /// the GPU may have written the records may not be what an execution committed earlier /// runs ([`IndirectCommandBuffer::gpu_written`]). pub fn command_type(&self) -> Result { + self.check_getter("command_type")?; self.icb .read_record(self.index, |view| command_type(&view.action())) } + /// Refuse, for `call`, a getter of a command of a buffer of no command types + /// (`NoCommandTypes`): the getters are a runtime extension standing for Metal's private + /// getters, and such a buffer has no Metal call to measure them against. + fn check_getter(&self, call: &'static str) -> Result<(), Error> { + self.icb.check_command_types(call) + } + /// `hasBarrier`, Apple's private getter: the command's /// [`barrier`](EncodedComputeCommand::barrier), read alone. pub fn has_barrier(&self) -> Result { + self.check_getter("has_barrier")?; self.icb.read_record(self.index, |view| view.barrier()) } /// `dispatchThreadgroupsArguments` and `dispatchThreadsArguments`, Apple's private getters: /// the command's [`dispatch`](EncodedComputeCommand::dispatch), read alone. pub fn dispatch(&self) -> Result, Error> { + self.check_getter("dispatch")?; self.icb .read_record(self.index, |view| dispatch_of(&view.action())) } @@ -3682,6 +3717,7 @@ impl IndirectComputeCommand { /// [`EncodedComputeCommand::kernel_buffer_address`] and /// [`EncodedComputeCommand::kernel_attribute_stride`] do. pub fn kernel_buffer(&self, index: u64) -> Result, Error> { + self.check_getter("kernel_buffer")?; let count = self.descriptor().max_kernel_buffer_bind_count; self.icb .read_buffer(self.index, BufferStage::Kernel, count, index) @@ -3700,12 +3736,14 @@ impl IndirectComputeCommand { /// them (an M3 Max: 100000 places past command 0's of 3), Metal's getter ends the process, /// and the runtime's answers. pub fn threadgroup_memory_length(&self, index: u64) -> Result, Error> { + self.check_getter("threadgroup_memory_length")?; self.icb.length(self.index, index as u32).map(Some) } /// `getStageInRegion`, Apple's private getter: the command's /// [`stage_in_region`](EncodedComputeCommand::stage_in_region), read alone. pub fn stage_in_region(&self) -> Result { + self.check_getter("stage_in_region")?; let [x, y, z, width, height, depth] = self .icb .read_record(self.index, |view| view.stage_in_region())? @@ -3720,6 +3758,7 @@ impl IndirectComputeCommand { /// [`imageblock_width`](EncodedComputeCommand::imageblock_width) and /// [`imageblock_height`](EncodedComputeCommand::imageblock_height), read alone. pub fn imageblock_size(&self) -> Result<(u64, u64), Error> { + self.check_getter("imageblock_size")?; let [width, height] = self .icb .read_record(self.index, |view| view.imageblock_size())?; @@ -3729,12 +3768,14 @@ impl IndirectComputeCommand { /// The command's [`pipeline`](EncodedComputeCommand::pipeline), read alone: the state set on /// it, none when unset, reset, or when no state of the ID it names lives. pub fn pipeline_state(&self) -> Result, Error> { + self.check_getter("pipeline_state")?; Ok(self.icb.compute_pipeline_now(self.index)?.0) } /// The command's [`pipeline_id`](EncodedComputeCommand::pipeline_id), read alone: the ID of /// the state its record names, none where it names none. pub fn pipeline_id(&self) -> Result, Error> { + self.check_getter("pipeline_id")?; self.icb.read_record(self.index, |view| { view.pipeline().map(|id| ResourceId(id.get())) }) @@ -3744,6 +3785,7 @@ impl IndirectComputeCommand { /// [`pipeline_unique_identifier`](EncodedComputeCommand::pipeline_unique_identifier), read /// alone, whose kind the device announces as `commands` announces it. pub fn pipeline_unique_identifier(&self) -> Result, Error> { + self.check_getter("pipeline_unique_identifier")?; let (_, identifier) = self.icb.compute_pipeline_now(self.index)?; self.icb.announce_identifier(identifier); Ok(identifier) @@ -4039,6 +4081,7 @@ impl IndirectRenderCommand { /// one's on a buffer of no mesh draw), where Metal's process ends. pub fn set_render_pipeline_state(&self, state: &RenderPipelineState) -> Result<(), Error> { const CALL: &str = "set_render_pipeline_state"; + self.icb.check_command_types(CALL)?; if !state.device().same(self.icb.device()) { return Err(invalid(CALL, Problem::ForeignObject)); } @@ -4101,6 +4144,7 @@ impl IndirectRenderCommand { offset: u64, index: u32, ) -> Result<(), Error> { + self.icb.check_command_types("set_vertex_buffer")?; if self.of_compute() { return Ok(()); } @@ -4129,6 +4173,7 @@ impl IndirectRenderCommand { index: u32, ) -> Result<(), Error> { const CALL: &str = "set_vertex_buffer_with_stride"; + self.icb.check_command_types(CALL)?; let dynamic = self.descriptor().support_dynamic_attribute_stride; let stride = (dynamic && stride != u64::MAX).then_some(stride); self.set_buffer(CALL, BufferStage::Vertex, buffer, offset, stride, index) @@ -4197,6 +4242,7 @@ impl IndirectRenderCommand { kind: IndirectCommandType, action: &Action, ) -> Result<(), Error> { + self.icb.check_command_types(call)?; if self.of_compute() { return Err(problem(call, IndirectCommandBufferProblem::CommandKind)); } @@ -4233,6 +4279,7 @@ impl IndirectRenderCommand { base_instance: u64, ) -> Result<(), Error> { const CALL: &str = "draw_primitives"; + self.icb.check_command_types(CALL)?; if self.of_compute() { return Ok(()); } @@ -4642,9 +4689,12 @@ impl IndirectRenderCommand { self.edit("clear_barrier", RecordField::Barrier(false), None) } - /// `reset`: the command as a fresh buffer's. + /// `reset`: the command as a fresh buffer's. Refused (`CommandKind`) for a command of a + /// buffer of dispatches, where Metal's process ends (SIGSEGV), but taken on a buffer of no + /// command types, where plain Metal's returns (an M3 Max, macOS 27.0.1, three processes, + /// beside a compute command's `reset` on the same buffer, which ends the process). pub fn reset(&self) -> Result<(), Error> { - if self.of_compute() { + if self.of_compute() && !self.icb.has_no_command_types() { return Err(problem("reset", IndirectCommandBufferProblem::CommandKind)); } self.icb.reset_command(self.index, |record, pipeline| { @@ -4750,6 +4800,7 @@ impl IndirectRenderCommand { /// Refuse, for `call`, a getter of a command of a buffer of dispatches (`CommandKind`, /// `of_compute`), whose answers were not measured. fn check_getter(&self, call: &'static str) -> Result<(), Error> { + self.icb.check_command_types(call)?; match self.of_compute() { true => Err(problem(call, IndirectCommandBufferProblem::CommandKind)), false => Ok(()), diff --git a/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer.rs index 1ebe25c54..2da10a898 100644 --- a/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer.rs @@ -53,13 +53,13 @@ fn a_descriptor_has_metal_s_defaults() { } /// `allocatedSize` is Metal's: rows measured on an M4, at a page's last count and the next where it -/// turns. Each row: the command types, whether the pipeline and the buffers are inherited, dynamic +/// turns, and rows measured on an M3 Max for the buffer counts past 31. Each row: the command types, whether the pipeline and the buffers are inherited, dynamic /// strides, the vertex, fragment, kernel, object and mesh buffer counts, the count of commands, and /// Metal's answer. Every kind answers one page for no commands. #[test] fn a_buffer_answers_metal_s_allocated_size() { type Row = (u32, bool, bool, bool, [u32; 5], u32, u64); - let rows: [Row; 47] = [ + let rows: [Row; 68] = [ (32, false, false, true, [0, 0, 5, 0, 0], 1000, 802816), (64, true, false, false, [0, 0, 31, 0, 0], 1000, 966656), (96, false, true, true, [0, 0, 5, 0, 0], 511, 376832), @@ -109,6 +109,50 @@ fn a_buffer_answers_metal_s_allocated_size() { (160, true, false, true, [3, 4, 5, 6, 7], 21, 16384), (160, true, false, true, [3, 4, 5, 6, 7], 22, 32768), (160, true, false, true, [3, 4, 5, 6, 7], 1000, 770048), + // The buffer counts past the 31 Metal's validation allows, measured on an Apple M3 Max + // under macOS 27.0.1 at 8 commands (`probes/icb_refusals_that_metal_takes.m`): Metal lays + // out the slots the count asks for, so `allocatedSize` grows with it, on past the 65536 + // a refusal once stopped at. A kernel count moves a compute buffer's layout alone and a + // vertex or fragment count a render buffer's; the other kind's rows below read one page + // whatever the count, which is what makes these live readings. + (32, false, false, false, [0, 0, 4, 0, 0], 8, 16384), + (32, false, false, false, [0, 0, 31, 0, 0], 8, 16384), + (32, false, false, false, [0, 0, 32, 0, 0], 8, 16384), + (32, false, false, false, [0, 0, 33, 0, 0], 8, 16384), + (32, false, false, false, [0, 0, 1024, 0, 0], 8, 81920), + (32, false, false, false, [0, 0, 65535, 0, 0], 8, 4210688), + (32, false, false, false, [0, 0, 65536, 0, 0], 8, 4210688), + (32, false, false, false, [0, 0, 65537, 0, 0], 8, 4210688), + (32, false, false, false, [0, 0, 70000, 0, 0], 8, 4489216), + (32, false, false, false, [0, 0, 1 << 20, 0, 0], 8, 67125248), + ( + 32, + false, + false, + false, + [0, 0, 1 << 24, 0, 0], + 8, + 1073758208, + ), + ( + 32, + false, + false, + false, + [0, 0, 1 << 25, 0, 0], + 8, + 2147500032, + ), + (32, false, false, false, [0, 0, 70000, 0, 0], 2, 1130496), + (1, false, false, false, [4, 0, 0, 0, 0], 8, 16384), + (1, false, false, false, [1024, 0, 0, 0, 0], 8, 81920), + (1, false, false, false, [65536, 0, 0, 0, 0], 8, 4210688), + (1, false, false, false, [65537, 0, 0, 0, 0], 8, 4210688), + (1, false, false, false, [0, 65536, 0, 0, 0], 8, 4210688), + // A count the buffer's own layout ignores: one page, whatever it asks for. + (1, false, false, false, [0, 0, 65536, 0, 0], 8, 16384), + (1, false, false, false, [0, 0, 0, 65536, 0], 8, 16384), + (1, false, false, false, [0, 0, 0, 0, 65536], 8, 16384), ]; for ( types, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/indirect_command_buffers.rs b/crates/metal2vulkan-validation/src/runtime_lane/indirect_command_buffers.rs index 991232a7f..c687d5c47 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/indirect_command_buffers.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/indirect_command_buffers.rs @@ -301,23 +301,65 @@ fn creation_refuses_what_metal_refuses() { .unwrap_err() }; let shared = ResourceOptions::shared(); - // No command types: made, but its commands, reset and read-back are refused (plain - // Metal's process ends at a command's first setter and at a reset). + // No command types: made, and both getters give a command, as plain Metal gives one; the + // calls plain Metal's process does not survive are refused on the command itself, and the + // ones it takes are taken (`IndirectCommandBufferProblem::NoCommandTypes`, measured on an + // M3 Max under macOS 27.0.1, three processes a call). let none = icb(device, &IndirectCommandBufferDescriptor::new(), 4); assert_eq!(none.size(), 4); let no_types = |call| icb_problem(call, IndirectCommandBufferProblem::NoCommandTypes); + let dispatches = none.indirect_compute_command_at(0).unwrap(); + let draws = none.indirect_render_command_at(0).unwrap(); + let state = template_state(device, true); assert_eq!( - none.indirect_compute_command_at(0).unwrap_err(), - no_types("indirect_compute_command_at") + dispatches.set_compute_pipeline_state(&state).unwrap_err(), + no_types("set_compute_pipeline_state") ); assert_eq!( - none.indirect_render_command_at(0).unwrap_err(), - no_types("indirect_render_command_at") + dispatches + .concurrent_dispatch_threadgroups(Size::new(1, 1, 1), Size::new(1, 1, 1)) + .unwrap_err(), + no_types("concurrent_dispatch_threadgroups") ); + assert_eq!( + dispatches + .concurrent_dispatch_threads(Size::new(1, 1, 1), Size::new(1, 1, 1)) + .unwrap_err(), + no_types("concurrent_dispatch_threads") + ); + assert_eq!(dispatches.reset().unwrap_err(), no_types("reset")); + assert_eq!( + dispatches.command_type().unwrap_err(), + no_types("command_type") + ); + assert_eq!( + draws.set_vertex_buffer(None, 0, 0).unwrap_err(), + no_types("set_vertex_buffer") + ); + assert_eq!( + draws + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap_err(), + no_types("draw_primitives") + ); + assert_eq!(draws.draw().unwrap_err(), no_types("draw")); + // Taken, as plain Metal takes them: a kernel buffer, a threadgroup length, either + // barrier, a fragment buffer and a render command's reset, each kept nowhere an + // execution of this buffer reads (it runs nothing). + dispatches.set_kernel_buffer(None, 0, 0).unwrap(); + dispatches.set_threadgroup_memory_length(16, 0).unwrap(); + dispatches.set_barrier().unwrap(); + dispatches.clear_barrier().unwrap(); + draws.set_fragment_buffer(None, 0, 0).unwrap(); + draws.set_barrier().unwrap(); + draws.reset().unwrap(); + // A CPU reset of commands ends plain Metal's process; an empty range returns. assert_eq!( none.reset_with_range(0..1).unwrap_err(), no_types("reset_with_range") ); + none.reset_with_range(0..0).unwrap(); + none.reset_with_range(2..2).unwrap(); assert_eq!(none.commands(0..1).unwrap_err(), no_types("commands")); // Draws of any kind beside dispatches make a buffer of compute commands, as plain // Metal's. @@ -337,13 +379,21 @@ fn creation_refuses_what_metal_refuses() { .set_threadgroup_memory_length(16, 1) .unwrap(); assert_eq!(command(&compute, 0).threadgroup_memory_lengths, [0, 16]); + // Such a buffer gives a render command, as plain Metal gives one, and the setters + // plain Metal does not ignore on it are refused (`CommandKind`, where Metal's process + // ends); a draw of primitives does nothing, as plain Metal's does. + let drawn = compute.indirect_render_command_at(0).unwrap(); + let kind = |call| icb_problem(call, IndirectCommandBufferProblem::CommandKind); assert_eq!( - compute.indirect_render_command_at(0).unwrap_err(), - icb_problem( - "indirect_render_command_at", - IndirectCommandBufferProblem::CommandKind - ) + drawn + .set_render_pipeline_state(&render_template_state(device, true)) + .unwrap_err(), + kind("set_render_pipeline_state") ); + assert_eq!(drawn.reset().unwrap_err(), kind("reset")); + drawn + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); } assert_eq!(icb(device, &render_descriptor(), 4).size(), 4); // Indexed, patch and indexed patch draws, and mesh draws, alone or beside draws of @@ -365,8 +415,11 @@ fn creation_refuses_what_metal_refuses() { draws.command_types = held; assert_eq!(icb(device, &draws, 4).size(), 4); } - // Up to 65536 buffers of a stage, or threadgroup lengths, as plain Metal makes them; past - // that its storage is not defined. + // Every buffer count and threadgroup-length count a descriptor asks for is taken, as + // plain Metal takes it: Metal's own `allocatedSize` grows with the count it lays slots + // out for (an M3 Max, macOS 27.0.1: 16 KiB at 4, 31, 32 and 33 kernel buffers of 8 + // commands, 80 KiB at 1024, 4.01 MiB at 65535, 65536 and 65537, 4.28 MiB at 70000, and on + // to 2 GiB at 2^25), and the runtime lays out the same slots. let counts = |count: u32| { let mut buffers = compute_descriptor(); buffers.max_kernel_buffer_bind_count = count; @@ -378,8 +431,10 @@ fn creation_refuses_what_metal_refuses() { fragment.max_fragment_buffer_bind_count = count; [buffers, lengths, vertex, fragment] }; - for descriptor in counts(65536) { - assert_eq!(icb(device, &descriptor, 2).size(), 2); + for count in [65536, 65537, 70000] { + for descriptor in counts(count) { + assert_eq!(icb(device, &descriptor, 2).size(), 2); + } } // A buffer set past what a record holds is kept beside the records and read back with // the record's slots, every slot the descriptor counts; a length past the record is kept @@ -404,16 +459,21 @@ fn creation_refuses_what_metal_refuses() { let lengths = command(&long, 0).threadgroup_memory_lengths; assert_eq!(lengths.len(), 31); assert_eq!(lengths[30], 16); - for descriptor in counts(65537) { + // A threadgroup-length count takes storage of neither side, so even 2^32 - 1 is made, as + // plain Metal makes it (16 KiB at every value from 31 to 2^32 - 1). Buffer slots that one + // buffer of the device's `max_buffer_length` cannot hold are the gap naming the limit: + // plain Metal makes such a buffer and lays out no slots in it (16 KiB at 2^31 kernel + // buffers, whose `setKernelBuffer:atIndex:` at index 2^31 then ends the process), and the + // runtime lays out every slot it answers for. + let [buffers_max, lengths_max, vertex_max, fragment_max] = counts(u32::MAX); + assert_eq!(icb(device, &lengths_max, 2).size(), 2); + for descriptor in [buffers_max, vertex_max, fragment_max] { assert_eq!( - refused(&descriptor, 4, shared), - icb_problem( - CALL, - IndirectCommandBufferProblem::BindCount { - count: 65537, - limit: 65536 - } - ) + refused(&descriptor, 2, shared), + Error::NotImplemented(RuntimeGap::IndirectCommandBufferPastMaxBufferLength { + count: 2, + max_buffer_length: device.properties().max_buffer_length, + }) ); } let memoryless = ResourceOptions::new( diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 2ed5fd614..5a4dc2e4c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -11447,7 +11447,6 @@ variant metal2vulkan-runtime::IdPlacement::At At(ResourceId) variant metal2vulkan-runtime::IdPlacement::Outside Outside variant metal2vulkan-runtime::IndirectCommand::Compute Compute(EncodedComputeCommand) variant metal2vulkan-runtime::IndirectCommand::Render Render(EncodedRenderCommand) -variant metal2vulkan-runtime::IndirectCommandBufferProblem::BindCount BindCount { count: u32, limit: u32 } variant metal2vulkan-runtime::IndirectCommandBufferProblem::CommandKind CommandKind variant metal2vulkan-runtime::IndirectCommandBufferProblem::CommandType CommandType(IndirectCommandType) variant metal2vulkan-runtime::IndirectCommandBufferProblem::InheritedPipelineState InheritedPipelineState diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index e65ac98ac..287041d16 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -35,7 +35,7 @@ Columns: | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | | What a call did wrong | 66 | 66 | 0 | 0 | 0 | 0 | 0 | -| What a call did wrong, in detail | 165 | 150 | 0 | 0 | 0 | 0 | 0 | +| What a call did wrong, in detail | 164 | 149 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -49,7 +49,7 @@ Columns: | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | | What a call did wrong | 22 | 3 | 5 | 0 | 10 | 9 | 17 | 0 | -| What a call did wrong, in detail | 56 | 27 | 25 | 0 | 31 | 26 | 0 | 0 | +| What a call did wrong, in detail | 57 | 27 | 23 | 0 | 31 | 26 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -365,7 +365,7 @@ Columns: | `ReservationHangs` | An indirect command buffer ID of `limit` (2^31) to 2^32 - 1 in a reservation (`Device::reserve_resource_ids`) | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: Metal's call never returns, its pool spinning | 1: `crates/metal2vulkan-runtime/src/resource_ids.rs (reserve_resource_ids)` | `-` | | `OutsidePlacement` | [`IdPlacement::Outside`](crate::IdPlacement::Outside) for anything but a texture `Device::new_texture` makes | every device (a public call's own check of its arguments) | `ours`: a runtime extension's misuse: Metal has no such placement | 4: `crates/metal2vulkan-runtime/src/resource_ids.rs (check_sampler_placement)`, `crates/metal2vulkan-runtime/src/resource_ids.rs (check_texture_placement)` (+2) | `-` | | `FunctionTable` | A visible-function table call, or a table or buffer binding a dispatch reads as the other, Metal stops | every device (a public call's own check of its arguments) | `delegated`: FunctionTableProblem, section 9 | 3: `crates/metal2vulkan-runtime/src/argument_table.rs (check_function_tables)`, `crates/metal2vulkan-runtime/src/function_table.rs (not_one_stage)` (+1) | `-` | -| `IndirectCommandBuffer` | An indirect command buffer call plain Metal itself refuses, ending its process or failing the call | every device (a public call's own check of its arguments) | `delegated`: IndirectCommandBufferProblem, section 9 | 2: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (problem)`, `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (records)` | `-` | +| `IndirectCommandBuffer` | An indirect command buffer call plain Metal itself refuses, ending its process or failing the call | every device (a public call's own check of its arguments) | `delegated`: IndirectCommandBufferProblem, section 9 | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (problem)` | `-` | | `RateMap` | A rasterization-rate map's descriptor Metal stops (`new_rasterization_rate_map`) | every device (a public call's own check of its arguments) | `delegated`: RateMapProblem, section 9 | 6: `crates/metal2vulkan-runtime/src/rate_map.rs (map_physical_to_screen_coordinates, 2 sites)`, `crates/metal2vulkan-runtime/src/rate_map.rs (map_screen_to_physical_coordinates, 2 sites)` (+2) | `-` | | `ArgumentEncoder` | An argument encoder call Metal stops, raises for, or answers nil for | every device (a public call's own check of its arguments) | `delegated`: ArgumentEncoderProblem, section 9 | 2: `crates/metal2vulkan-runtime/src/argument_encoder.rs (new_argument_encoder_for_buffer_at_index)`, `crates/metal2vulkan-runtime/src/argument_encoder.rs (problem)` | `-` | | `IndirectDispatchRange` | An indirect dispatch's `bytes` of arguments at `offset` that run past the bytes the runtime holds at Metal's address in its buffer of `length`... | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max under macOS 27.0.1: an indirect dispatch whose 12 bytes of arguments run past its buffer of 8 bytes runs and counts right; Metal's API validation alone refuses it. Arguments inside the buffer's allocation are taken now, so what the refusal still reaches past Metal for is the slice past the bytes the runtime holds there | 1: `crates/metal2vulkan-runtime/src/indirect_dispatch.rs (arguments_offset)` | `-` | @@ -513,12 +513,11 @@ Columns: | `FunctionTableProblem::HandleOfAnotherState` | `set_function` with a handle of another pipeline state than the table's (Metal's validation | every device (a public call's own check of its arguments) | `unknown`: Metal's validation stops the handle, and plain Metal's own answer was not measured | 1: `crates/metal2vulkan-runtime/src/function_table.rs (set)` | `-` | | `FunctionTableProblem::TableAtBufferIndex` | A command whose function writes a buffer, or reads an intersection function table, at `index`, where a visible-function table is bound | every device (a public call's own check of its arguments) | `unknown`: plain Metal's answer was not measured, and ray tracing's tables are out of scope | 1: `crates/metal2vulkan-runtime/src/argument_table.rs (check_function_tables)` | `-` | | `FunctionTableProblem::StageWithoutFunction` | A render pipeline state's `function_handle` or `new_visible_function_table` for `stage`, which is not one stage | every device (a public call's own check of its arguments) | `metal-measured`: an M4, macOS 27.0.1: plain Metal answers the handle nil and the table of more than one stage nil, and faults on a table of no stage | 1: `crates/metal2vulkan-runtime/src/function_table.rs (not_one_stage)` | `-` | -| `IndirectCommandBufferProblem::NoCommandTypes` | A command, a CPU reset, a read-back or an argument buffer's encoding of a buffer of no command types, or its blit copy to or from a buffer of... | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1: plain Metal ends the process, SIGBUS, at a command's `setRenderPipelineState:` and at `resetWithRange:`, where a buffer of `Draw` takes both; but it encodes such a buffer into an argument buffer to the same bytes a `Draw` one encodes to, and completes its blit copy into a `Draw` buffer, its execution in a pass and its optimize with no error, so those refusals reach past Metal. The read-back is the runtime's own extension and has no Metal call to measure | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_command_types)` | `-` | -| `IndirectCommandBufferProblem::BindCount` | A descriptor with more kernel, vertex, fragment, object or mesh buffers, or kernel threadgroup lengths, than 65536, past which plain Metal's... | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1: plain Metal makes the buffer at 4, at 65536, at 2^31 and at 2^32 - 1 kernel buffers alike, each taking the same 16 KiB of the device's allocated size, where `maxCommandCount` moves that figure — 16 KiB at one command against 64 KiB at 64 — so the storage is undefined rather than refused and the refusal reaches past Metal | 2: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (records, 2 sites)` | `-` | +| `IndirectCommandBufferProblem::NoCommandTypes` | A call on a buffer of no command types that plain Metal's process does not survive | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1, build 26A434, the validation layer off, one shape per process, three processes a shape, each beside the same call on a buffer of the matching command type, `probes/icb_refusals_that_metal_takes.m`. Plain Metal ends the process — SIGBUS, SIGSEGV in some processes of the same shape — at `setRenderPipelineState:`, `setVertexBuffer:offset:atIndex:`, `drawPrimitives:`, `drawIndexedPrimitives:`, `setComputePipelineState:`, `concurrentDispatchThreadgroups:`, `concurrentDispatchThreads:`, a compute command's `reset`, and `resetWithRange:` of a non-empty range, where the buffer of the matching type takes each. It **takes**, and the runtime takes with it, `indirectRenderCommandAtIndex:` and `indirectComputeCommandAtIndex:` — an object, not nil — a render command's `reset`, `setFragmentBuffer:`, `setBarrier` and `clearBarrier`, `setKernelBuffer:` plain and with an attribute stride, `setThreadgroupMemoryLength:atIndex:`, `setStageInRegion:`, `setImageblockWidth:height:`, `resetWithRange:` of an empty range, the execution in a pass which paints nothing, `optimizeIndirectCommandBuffer:`, the blit copy in either direction, and the argument-buffer encoding, to the same ID bytes a `Draw` buffer encodes to. The argument-buffer encoding and the blit copy are still refused, in `argument_encoder.rs` and `blit_indirect.rs`, and reach past Metal there. The read-back is a runtime extension and has no Metal call to measure | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_command_types)` | `-` | | `IndirectCommandBufferProblem::Range` | A range of commands not inside the buffer | every device (a public call's own check of its arguments) | `unknown`: plain Metal's answer for a reset or read-back range that is not inside the buffer is unmeasured | 2: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (command_range)`, `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (inside)` | `-` | | `IndirectCommandBufferProblem::InheritedPipelineState` | A pipeline state set on a command of a buffer that inherits it (this ends Metal's process) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal ends the process, SIGBUS, at `setRenderPipelineState:` on a command of a buffer whose `inheritPipelineState` is set, where the same setter on a buffer that does not inherit it runs the draw | 2: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_compute_pipeline_state)`, `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_render_pipeline_state)` | `-` | -| `IndirectCommandBufferProblem::PipelineWithoutSupport` | A pipeline state made without `supportIndirectCommandBuffers` | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1: plain Metal's `setRenderPipelineState:` and `drawPrimitives:` on the command both return rather than ending the process, and the command buffer fails at execution, "Caused GPU Address Fault Error", where the same pipeline with the flag set draws: so the refusal stands on undefined behaviour and not on a refusal of Metal's, and reaches past it | 3: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_compute_pipeline_state)`, `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_render_pipeline_state, 2 sites)` | `-` | -| `IndirectCommandBufferProblem::CommandType` | A draw of a kind (`DRAW_INDEXED`, `DRAW_PATCHES` or `DRAW_INDEXED_PATCHES`, a probe) whose record the buffer's records cannot hold | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1: plain Metal ends the process, SIGBUS, at a patch draw on a buffer of `DRAW` alone, at a mesh pipeline's `setRenderPipelineState:` on such a buffer, and at a draw of primitives on a buffer of `DRAW_MESH_THREADGROUPS` alone; but an indexed draw on a buffer of `DRAW` alone completes with no error and paints nothing, where the same draw on a buffer of `DRAW_INDEXED` paints, so that kind reaches past Metal | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_draw)` | `-` | +| `IndirectCommandBufferProblem::PipelineWithoutSupport` | A pipeline state made without `supportIndirectCommandBuffers`, set on a command | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1, build 26A434, the validation layer off, one shape per process, three processes a shape, `probes/icb_refusals_that_metal_takes.m`. The two kinds do not answer alike. `setComputePipelineState:` with a state made without the flag ends the process, SIGSEGV, where the same call with the flag set dispatches and the kernel's marker words read back: that arm is a refusal of Metal's own. `setRenderPipelineState:` and `drawPrimitives:` both return, and the command buffer then fails at execution with status 5 and `Caused GPU Address Fault Error 0000000b:kIOGPUCommandBufferCallbackErrorPageFault`, leaving the target at its clear value, where the same pipeline with the flag set paints; a plainly valid command buffer submitted after the fault completes and paints, so the fault does not poison the queue. That arm stands on undefined behaviour — a GPU address fault is not an answer — and so reaches past Metal, and the refusal is kept there deliberately: a typed `Invalid` at the setter is the useful answer where Metal's own is a page fault at execution | 3: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_compute_pipeline_state)`, `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_render_pipeline_state, 2 sites)` | `-` | +| `IndirectCommandBufferProblem::CommandType` | A draw of a kind (`DRAW_INDEXED`, `DRAW_PATCHES` or `DRAW_INDEXED_PATCHES`, a probe) whose record the buffer's records cannot hold | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max, macOS 27.0.1, build 26A434, the validation layer off, one shape per process, `probes/icb_refusals_that_metal_takes.m`. Plain Metal ends the process, SIGBUS, at a patch draw on a buffer of `DRAW` alone, at a mesh pipeline's `setRenderPipelineState:` on such a buffer, and at a draw of primitives on a buffer of `DRAW_MESH_THREADGROUPS` alone, three processes each. One cell reaches past Metal, and one only: an indexed draw on a buffer of `DRAW` alone completes with no error and paints nothing, three processes, with both controls live beside it — a draw of primitives on the same buffer paints 0.75, and the same indexed draw on a buffer of `DRAW_INDEXED` and on one of `DRAW_PATCHES` paints 0.75 — and with no byte of a 0xEE guard at the next 256-aligned placement-heap offset past the index buffer touched. Taking it needs the execution to run nothing for such a record, which is `Asked::of` in `render/executions.rs`, where `Asked::Nothing` already stands for a draw that runs nothing: that side is not built, so the setter stays refused rather than taken and then painted | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_draw)` | `-` | | `IndirectCommandBufferProblem::CommandKind` | A compute command of a buffer whose commands are render ones, or a setter plain Metal does not ignore on a render command of a buffer whose... | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: plain Metal's process ends — SIGBUS, SIGBUS and SIGSEGV — at `indirectComputeCommandAtIndex:` on a buffer of draws and at a render command's setters and reset on one of dispatches, the API validation layer off | 7: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_draw)`, `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_getter)` (+5) | `-` | | `IndirectCommandBufferProblem::RenderState` | A render state set on a render command (`set_depth_stencil_state`, `set_depth_bias`, `set_depth_clip_mode`, `set_cull_mode`,... | every device (a public call's own check of its arguments) | `metal-measured`: an M4, macOS 27.0.1: plain Metal raises `APINotSupported` at each setter and its process ends, whether the buffer inherits the state or not | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (render_state)` | `-` | | `IndirectCommandBufferProblem::ObjectThreadgroupMemory` | An object threadgroup length set on a render command of a buffer whose command types hold no mesh draw (`set_object_threadgroup_memory_length`) | every device (a public call's own check of its arguments) | `metal-measured`: an M4: Metal's process ends at `set_object_threadgroup_memory_length` on a buffer of no mesh draw, with and without its validation | 1: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_object_threadgroup_memory_length)` | `-` | @@ -836,7 +835,7 @@ Each refusal's sites, with the function that builds it. - `invalid::ReservationHangs`: `crates/metal2vulkan-runtime/src/resource_ids.rs (reserve_resource_ids)` - `invalid::OutsidePlacement`: `crates/metal2vulkan-runtime/src/resource_ids.rs (check_sampler_placement)`; `crates/metal2vulkan-runtime/src/resource_ids.rs (check_texture_placement)`; `crates/metal2vulkan-runtime/src/resource_ids.rs (pipeline_placement)`; `crates/metal2vulkan-runtime/src/resource_ids.rs (records_placement)` - `invalid::FunctionTable`: `crates/metal2vulkan-runtime/src/argument_table.rs (check_function_tables)`; `crates/metal2vulkan-runtime/src/function_table.rs (not_one_stage)`; `crates/metal2vulkan-runtime/src/function_table.rs (set)` -- `invalid::IndirectCommandBuffer`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (problem)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (records)` +- `invalid::IndirectCommandBuffer`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (problem)` - `invalid::RateMap`: `crates/metal2vulkan-runtime/src/rate_map.rs (map_physical_to_screen_coordinates, 2 sites)`; `crates/metal2vulkan-runtime/src/rate_map.rs (map_screen_to_physical_coordinates, 2 sites)`; `crates/metal2vulkan-runtime/src/rate_map.rs (reset)`; `crates/metal2vulkan-runtime/src/rate_map.rs (validate)` - `invalid::ArgumentEncoder`: `crates/metal2vulkan-runtime/src/argument_encoder.rs (new_argument_encoder_for_buffer_at_index)`; `crates/metal2vulkan-runtime/src/argument_encoder.rs (problem)` - `invalid::IndirectDispatchRange`: `crates/metal2vulkan-runtime/src/indirect_dispatch.rs (arguments_offset)` @@ -965,7 +964,6 @@ Each refusal's sites, with the function that builds it. - `subproblem::FunctionTableProblem::TableAtBufferIndex`: `crates/metal2vulkan-runtime/src/argument_table.rs (check_function_tables)` - `subproblem::FunctionTableProblem::StageWithoutFunction`: `crates/metal2vulkan-runtime/src/function_table.rs (not_one_stage)` - `subproblem::IndirectCommandBufferProblem::NoCommandTypes`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_command_types)` -- `subproblem::IndirectCommandBufferProblem::BindCount`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (records, 2 sites)` - `subproblem::IndirectCommandBufferProblem::Range`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (command_range)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (inside)` - `subproblem::IndirectCommandBufferProblem::InheritedPipelineState`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_render_pipeline_state)` - `subproblem::IndirectCommandBufferProblem::PipelineWithoutSupport`: `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_render_pipeline_state, 2 sites)`