// oracle_errors: the errors and refusals Metal gives for common failures, with the whole NSError // (domain, code, userInfo, the underlying error and the encoders' execution status). // oracle_errors DEVICE [CASE [ARG]] every case but timeout (or the one named), each in a child // Cases: // purgeable a buffer and a texture set purgeable Empty, then used by a command buffer // creates oversized creates: a buffer past maxBufferLength, a 32768 x 32768 texture, a // heap past the working set // bounds [STEP] each create of a length or size Metal bounds, at its bound and past it, each // step in a child of its own (L is maxBufferLength, P the page size): a buffer // of a length (len.L, len.L+1, len.L+P), over the caller's bytes (nocopy.1M, // nocopy.L, nocopy.L+P, nocopy.L+1, and nocopy.P+1, a length off the page); a // Private heap (heap.L, heap.L+1, heap.L+P); a buffer and a texture of a 1 MiB // Private Placement heap at its end and past it (place.buf.end, place.buf.past, // place.buf.long, place.tex.end, place.tex.past); the tiled texture SPI over the // caller's bytes (tiled.1M, tiled.L, tiled.L+P); last, a buffer of bytes past // the bound (bytes.L+P), which commits them where it is made (bytes.L is not // asked: it would). The caller's bytes are a sparse file's pages. Each line says // made or nil and the process's footprint after the create, and the parent says // how a step's process ended. // residency GIB GIB 1 GiB Private buffers made and all filled in one command buffer // timeout SEC one kernel that runs about SEC seconds (the GPU's watchdog may end it); run it // only on a GPU that does not drive a display // Build: see README.md. #import "oracle_common.h" #include #include #include #include #include #include extern char **environ; static id D; static id Q; static const char *gArgv0; static const char *gDeviceArg; static void print_error(const char *indent, NSError *e) { if (!e) { printf("%serror nil\n", indent); return; } printf("%sdomain %s code %ld\n", indent, e.domain.UTF8String, (long)e.code); for (NSString *k in e.userInfo) { id v = e.userInfo[k]; if ([v isKindOfClass:[NSError class]]) { printf("%s %s:\n", indent, k.UTF8String); char deeper[32]; snprintf(deeper, sizeof deeper, "%s ", indent); print_error(deeper, v); } else if ([v isKindOfClass:[NSArray class]]) { printf("%s %s: [%lu]\n", indent, k.UTF8String, (unsigned long)[v count]); for (id x in v) { if ([x conformsToProtocol:@protocol(MTLCommandBufferEncoderInfo)]) { id info = x; printf("%s encoder '%s' status %ld signposts %lu\n", indent, info.label.UTF8String, (long)info.errorState, (unsigned long)info.debugSignposts.count); } else { printf("%s %s\n", indent, [x description].UTF8String); } } } else { printf("%s %s: %s\n", indent, k.UTF8String, [v description].UTF8String); } } } static id new_cb(void) { MTLCommandBufferDescriptor *cd = [MTLCommandBufferDescriptor new]; cd.errorOptions = MTLCommandBufferErrorOptionEncoderExecutionStatus; return [Q commandBufferWithDescriptor:cd]; } static void finish(const char *what, id cb) { double t0 = oracle_now_ms(); [cb commit]; [cb waitUntilCompleted]; printf(" %s: status %ld after %.1f ms (GPU %.1f ms)\n", what, (long)cb.status, oracle_now_ms() - t0, (cb.GPUEndTime - cb.GPUStartTime) * 1e3); print_error(" ", cb.error); } static void case_purgeable(void) { printf("case purgeable\n"); id b = [D newBufferWithLength:1 << 20 options:MTLResourceStorageModePrivate]; MTLPurgeableState old = [b setPurgeableState:MTLPurgeableStateVolatile]; MTLPurgeableState was = [b setPurgeableState:MTLPurgeableStateEmpty]; MTLPurgeableState now = [b setPurgeableState:MTLPurgeableStateKeepCurrent]; printf(" buffer purgeable states: %lu -> %lu -> now %lu\n", (unsigned long)old, (unsigned long)was, (unsigned long)now); id out = [D newBufferWithLength:1 << 20 options:MTLResourceStorageModeShared]; id cb = new_cb(); id e = [cb blitCommandEncoder]; e.label = @"copy from emptied buffer"; [e copyFromBuffer:b sourceOffset:0 toBuffer:out destinationOffset:0 size:1 << 20]; [e endEncoding]; finish("copy from an emptied buffer", cb); MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:256 height:256 mipmapped:NO]; td.storageMode = MTLStorageModePrivate; td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; id t = [D newTextureWithDescriptor:td]; [t setPurgeableState:MTLPurgeableStateVolatile]; [t setPurgeableState:MTLPurgeableStateEmpty]; MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor]; rp.colorAttachments[0].texture = t; rp.colorAttachments[0].loadAction = MTLLoadActionLoad; rp.colorAttachments[0].storeAction = MTLStoreActionStore; cb = new_cb(); id r = [cb renderCommandEncoderWithDescriptor:rp]; r.label = @"pass on emptied texture"; [r endEncoding]; finish("render pass on an emptied texture", cb); } static void case_creates(void) { printf("case creates (maxBufferLength %lu)\n", (unsigned long)D.maxBufferLength); printf(" buffer of maxBufferLength + 4096: "); fflush(stdout); id b = [D newBufferWithLength:D.maxBufferLength + 4096 options:MTLResourceStorageModePrivate]; printf("%s\n", b ? "made" : "nil"); b = nil; MTLHeapDescriptor *hd = [MTLHeapDescriptor new]; hd.size = D.recommendedMaxWorkingSetSize * 4; hd.storageMode = MTLStorageModePrivate; printf(" Private heap of 4x recommendedMaxWorkingSetSize (%llu): ", (unsigned long long)hd.size); fflush(stdout); id h = [D newHeapWithDescriptor:hd]; printf("%s\n", h ? "made" : "nil"); h = nil; MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:32768 height:32768 mipmapped:NO]; td.storageMode = MTLStorageModePrivate; printf(" 32768x32768 RGBA8 texture: "); fflush(stdout); id t = [D newTextureWithDescriptor:td]; printf("%s\n", t ? "made" : "nil"); } static const char *const kBoundsSteps[] = { "len.L", "len.L+1", "len.L+P", "nocopy.1M", "nocopy.L", "nocopy.L+P", "nocopy.L+1", "nocopy.P+1", "heap.L", "heap.L+1", "heap.L+P", "place.buf.end", "place.buf.past", "place.buf.long", "place.tex.end", "place.tex.past", "tiled.1M", "tiled.L", "tiled.L+P", "bytes.L+P", }; // The length a step's suffix names: L, L+1, L+P, P+1 or 1M. static uint64_t bounds_length(const char *suffix, uint64_t L, uint64_t P) { if (!strcmp(suffix, "L")) return L; if (!strcmp(suffix, "L+1")) return L + 1; if (!strcmp(suffix, "L+P")) return L + P; if (!strcmp(suffix, "P+1")) return P + 1; if (!strcmp(suffix, "1M")) return 1 << 20; fprintf(stderr, "no length %s\n", suffix); exit(2); } // `length` bytes of a sparse file of their own, whole pages, mapped shared: they read zero, and // the process's footprint does not count them, so a create that wires or reads them stays inside // a small job's memory limit. static void *bounds_bytes(uint64_t length, uint64_t P) { const uint64_t size = (length + P - 1) & ~(P - 1); const char *dir = getenv("TMPDIR"); char path[1024]; snprintf(path, sizeof path, "%s/oracle_errors.bounds.XXXXXX", dir ? dir : "/tmp"); const int fd = mkstemp(path); if (fd < 0 || unlink(path) != 0 || ftruncate(fd, (off_t)size) != 0) { printf(" no file of %llu bytes at %s\n", (unsigned long long)size, path); exit(1); } void *p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); if (p == MAP_FAILED) { printf(" mmap of %llu bytes failed\n", (unsigned long long)size); exit(1); } return p; } static void bounds_say(const char *step, uint64_t length, id object, double t0) { printf(" %s (%llu): %s", step, (unsigned long long)length, object ? "made" : "nil"); if ([object conformsToProtocol:@protocol(MTLBuffer)]) printf(", length %lu", (unsigned long)[(id)object length]); else if ([object conformsToProtocol:@protocol(MTLHeap)]) printf(", size %lu", (unsigned long)[(id)object size]); struct rusage_info_v2 ri = {0}; proc_pid_rusage(getpid(), RUSAGE_INFO_V2, (rusage_info_t *)&ri); printf(" (%.1f ms, footprint %llu)\n", oracle_now_ms() - t0, (unsigned long long)ri.ri_phys_footprint); } // A Private Placement heap of 1 MiB. static id bounds_placement_heap(void) { MTLHeapDescriptor *hd = [MTLHeapDescriptor new]; hd.size = 1 << 20; hd.storageMode = MTLStorageModePrivate; hd.type = MTLHeapTypePlacement; id h = [D newHeapWithDescriptor:hd]; if (!h) { printf(" no Placement heap of 1 MiB\n"); exit(1); } return h; } static void case_bounds(const char *step) { const uint64_t L = D.maxBufferLength, P = (uint64_t)getpagesize(); if (step == NULL) { const char *layer = getenv("MTL_DEBUG_LAYER"); printf("case bounds (maxBufferLength %llu, page %llu, MTL_DEBUG_LAYER %s)\n", (unsigned long long)L, (unsigned long long)P, layer ? layer : "unset"); for (size_t i = 0; i < sizeof kBoundsSteps / sizeof kBoundsSteps[0]; i++) { char *args[] = {(char *)gArgv0, (char *)gDeviceArg, "--case", "bounds", (char *)kBoundsSteps[i], NULL}; pid_t pid; if (posix_spawn(&pid, gArgv0, NULL, NULL, args, environ)) exit(1); int st; waitpid(pid, &st, 0); if (WIFSIGNALED(st)) printf(" => step %s died on signal %d\n", kBoundsSteps[i], WTERMSIG(st)); else if (WEXITSTATUS(st)) printf(" => step %s exited %d\n", kBoundsSteps[i], WEXITSTATUS(st)); } return; } printf(" step %s\n", step); fflush(stdout); const double t0 = oracle_now_ms(); if (!strncmp(step, "len.", 4)) { const uint64_t length = bounds_length(step + 4, L, P); bounds_say(step, length, [D newBufferWithLength:length options:MTLResourceStorageModePrivate], t0); } else if (!strncmp(step, "bytes.", 6)) { const uint64_t length = bounds_length(step + 6, L, P); void *bytes = bounds_bytes(length, P); bounds_say(step, length, [D newBufferWithBytes:bytes length:length options:MTLResourceStorageModeShared], t0); } else if (!strncmp(step, "nocopy.", 7)) { const uint64_t length = bounds_length(step + 7, L, P); void *bytes = bounds_bytes(length, P); bounds_say(step, length, [D newBufferWithBytesNoCopy:bytes length:length options:MTLResourceStorageModeShared deallocator:nil], t0); } else if (!strncmp(step, "heap.", 5)) { const uint64_t size = bounds_length(step + 5, L, P); MTLHeapDescriptor *hd = [MTLHeapDescriptor new]; hd.size = size; hd.storageMode = MTLStorageModePrivate; bounds_say(step, size, [D newHeapWithDescriptor:hd], t0); } else if (!strncmp(step, "place.buf.", 10)) { // At the heap's last 64 KiB (end), 128 KiB there (past), and 1 MiB + 64 KiB at 0 (long). id h = bounds_placement_heap(); const uint64_t H = h.size, K = 64 << 10; const char *how = step + 10; const uint64_t offset = !strcmp(how, "long") ? 0 : H - K; const uint64_t length = !strcmp(how, "end") ? K : !strcmp(how, "past") ? 2 * K : H + K; printf(" heap of %llu, a buffer of %llu at %llu\n", (unsigned long long)H, (unsigned long long)length, (unsigned long long)offset); bounds_say(step, length, [h newBufferWithLength:length options:MTLResourceStorageModePrivate offset:offset], t0); } else if (!strncmp(step, "place.tex.", 10)) { // A 128 x 128 RGBA8 texture at the last offset of its alignment that holds it (end), and // one alignment on (past). id h = bounds_placement_heap(); MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:128 height:128 mipmapped:NO]; td.storageMode = MTLStorageModePrivate; const MTLSizeAndAlign sa = [D heapTextureSizeAndAlignWithDescriptor:td]; const uint64_t H = h.size, align = sa.align ? sa.align : 1; uint64_t offset = (H - sa.size) / align * align; if (!strcmp(step + 10, "past")) offset += align; printf(" heap of %llu, a texture of %lu (align %lu) at %llu\n", (unsigned long long)H, (unsigned long)sa.size, (unsigned long)sa.align, (unsigned long long)offset); bounds_say(step, sa.size, [h newTextureWithDescriptor:td offset:offset], t0); } else if (!strncmp(step, "tiled.", 6)) { const SEL sel = NSSelectorFromString(@"newTiledTextureWithBytesNoCopy:length:deallocator:descriptor:" @"offset:bytesPerRow:"); if (![D respondsToSelector:sel]) { printf(" %s: the device does not respond\n", step); return; } const uint64_t length = bounds_length(step + 6, L, P); void *bytes = bounds_bytes(length, P); MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:64 height:64 mipmapped:NO]; td.storageMode = MTLStorageModeShared; id t = ((id(*)(id, SEL, void *, NSUInteger, id, MTLTextureDescriptor *, NSUInteger, NSUInteger))objc_msgSend)(D, sel, bytes, (NSUInteger)length, nil, td, 0, 256); bounds_say(step, length, t, t0); } else { fprintf(stderr, "no step %s\n", step); exit(2); } } static void case_residency(int gib) { printf("case residency: %d x 1 GiB Private buffers, all filled in one command buffer\n", gib); NSMutableArray *bufs = [NSMutableArray array]; for (int i = 0; i < gib; i++) { id b = [D newBufferWithLength:1ull << 30 options:MTLResourceStorageModePrivate]; if (!b) { printf(" buffer %d: nil\n", i); break; } [bufs addObject:b]; } printf(" made %lu, currentAllocatedSize %lu\n", (unsigned long)bufs.count, (unsigned long)D.currentAllocatedSize); id cb = new_cb(); id e = [cb blitCommandEncoder]; e.label = @"fill all"; for (id b in bufs) [e fillBuffer:b range:NSMakeRange(0, b.length) value:1]; [e endEncoding]; finish("fill every buffer", cb); } static void case_timeout(double seconds) { printf("case timeout: one kernel of about %.1f s\n", seconds); id lib = oracle_library(D, gArgv0, "oracle"); NSError *err = nil; id p = [D newComputePipelineStateWithFunction:[lib newFunctionWithName:@"progress"] error:&err]; id ctr = [D newBufferWithLength:64 options:MTLResourceStorageModeShared]; id sink = [D newBufferWithLength:64 options:MTLResourceStorageModeShared]; // Calibrate: 100 steps of `spin`. uint32_t steps = 100, spin = 20000; double gpu = 0; for (int k = 0; k < 5; k++) { id cb = [Q commandBuffer]; id e = [cb computeCommandEncoder]; [e setComputePipelineState:p]; [e setBuffer:ctr offset:0 atIndex:0]; [e setBytes:&steps length:4 atIndex:1]; [e setBytes:&spin length:4 atIndex:2]; [e setBuffer:sink offset:0 atIndex:3]; [e dispatchThreads:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)]; [e endEncoding]; oracle_commit_wait(cb, NULL, &gpu); if (gpu > 50) break; spin *= 4; } steps = (uint32_t)(100 * seconds * 1000 / gpu); printf(" calibration: 100 steps of %u = %.1f ms; %u steps\n", spin, gpu, steps); memset(ctr.contents, 0, 64); id cb = new_cb(); id e = [cb computeCommandEncoder]; e.label = @"long kernel"; [e setComputePipelineState:p]; [e setBuffer:ctr offset:0 atIndex:0]; [e setBytes:&steps length:4 atIndex:1]; [e setBytes:&spin length:4 atIndex:2]; [e setBuffer:sink offset:0 atIndex:3]; [e dispatchThreads:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)]; [e endEncoding]; finish("long kernel", cb); printf(" the kernel reached step %u of %u\n", ((uint32_t *)ctr.contents)[0], steps); cb = new_cb(); id b = [cb blitCommandEncoder]; [b fillBuffer:sink range:NSMakeRange(0, 64) value:3]; [b endEncoding]; finish("a tiny buffer on the same queue after it", cb); } int main(int argc, char **argv) { setvbuf(stdout, NULL, _IOLBF, 0); gArgv0 = argv[0]; gDeviceArg = argc > 1 ? argv[1] : NULL; if (argc < 2) { fprintf(stderr, "usage: %s DEVICE [CASE [ARG]]\n", argv[0]); return 2; } D = oracle_device(argv[1]); if (argc > 2 && !strcmp(argv[2], "--case")) { Q = [D newCommandQueue]; const char *c = argv[3]; if (!strcmp(c, "purgeable")) case_purgeable(); else if (!strcmp(c, "creates")) case_creates(); else if (!strcmp(c, "bounds")) case_bounds(argc > 4 ? argv[4] : NULL); else if (!strcmp(c, "residency")) case_residency(argc > 4 && argv[4] ? atoi(argv[4]) : 6); else if (!strcmp(c, "timeout")) case_timeout(argc > 4 && argv[4] ? atof(argv[4]) : 10); else return 2; return 0; } oracle_header("oracle_errors", D); D = nil; static const char *const all[][2] = { {"purgeable", NULL}, {"creates", NULL}, {"bounds", NULL}, {"residency", "6"}, {"timeout", "10"}, }; for (size_t i = 0; i < sizeof all / sizeof all[0]; i++) { if (argc > 2 ? strcmp(argv[2], all[i][0]) : !strcmp(all[i][0], "timeout")) continue; const char *arg = argc > 3 ? argv[3] : all[i][1]; char *args[] = {argv[0], argv[1], "--case", (char *)all[i][0], (char *)arg, NULL}; pid_t pid; if (posix_spawn(&pid, argv[0], NULL, NULL, args, environ)) return 1; int st; waitpid(pid, &st, 0); if (WIFSIGNALED(st)) printf(" => case %s died on signal %d\n", all[i][0], WTERMSIG(st)); else if (WEXITSTATUS(st)) printf(" => case %s exited %d\n", all[i][0], WEXITSTATUS(st)); } return 0; }