Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.
C
Metal: a command queue and the objects a renderer asks for, as logged stubs; the next wall is a metallib URL
shimokueb757ba7a654
diff --git a/docs/metal-plan.md b/docs/metal-plan.mdindex 7e4d468..dd4f192 100644--- a/docs/metal-plan.md+++ b/docs/metal-plan.md@@ -54,8 +54,22 @@ Run in a loop of rebuild-image, boot, read the log; each pass gave the next requwindow server restarts and fails the same way (launchd: "service has crashed N times in a row"). That is what a Metaldevice that exists and cannot do anything does to the system, and the reason `metal=1` is off by default.-So the road from here is step 3 onwards, and the first thing the window server needs is a **command queue** (step 5), with-buffers and textures under it; none of that can be tried without the GPU.+4. **A command queue** is now made (`HakiosMetalQueue`, a subclass of `_MTLCommandQueue`; it queues nothing). Metal then+ sends it `-setCompletionQueue:`, which is not in `MTLCommandQueue` but in the private protocol `MTLCommandQueueSPI`: found+ by taking every protocol of the process whose name begins with `MTLCommandQueue`. The window server then asks for+ `-setGPUPriority:` and `-newDepthStencilStateWithDescriptor:`.+5. **The objects a device hands out** are stub classes made from a table in `HakiosMetal.m` (depth-stencil state, sampler+ state, texture, render and compute pipeline states, event, fence): a subclass of Metal's private base where the system has+ one, the protocol family declared, every other message logged once and answered with zero. Textures and events have no+ private base class on this system (NSObject is used).+6. **The next wall**, with those in place: CoreAnimation's Metal renderer stops with+ `Assertion failed: (metallib_url != nil), function MetalContext, file ogl-metal.mm, line 3308.` It needs the URL of a+ `.metallib` (the system has `AppleMetalGLRenderer.bundle/default.metallib`, 274 shader modules, which the AIR work translates)+ and will then ask the device for a library from it, which is where the shader compiler (part A) is first needed for real.+ Where CoreAnimation takes that URL from is not known yet; the log shows the device was asked for nothing before it.++So the road from here is the library (step 4 of the order below: `newLibraryWithURL:` / `…Data:` through the AIR compiler), then+buffers and textures with real memory, and the command encoders; none of that can be tried without the GPU.## Frame skipsdiff --git a/userland/src/HakiosMetal.m b/userland/src/HakiosMetal.mindex f57157d..4297390 100644--- a/userland/src/HakiosMetal.m+++ b/userland/src/HakiosMetal.m@@ -60,8 +60,63 @@ deviceRegistryID(__unused id self, __unused SEL _cmd)return gPort;}+/* the largest buffer: what the GPU memory could hold, not a promise (nothing allocates a buffer yet) */+static uint64_t+deviceMaxBufferLength(__unused id self, __unused SEL _cmd)+{+ return 256ull << 20;+}++/*+ * The command queue: the first thing the window server wants after the device (the second run's log: "[Metal] Failed to create+ * MTLCommandQueue", then the process ends). Made as a subclass of Metal's private _MTLCommandQueue, at the same time as the device's+ * class, with the same stub for what it does not answer. It queues nothing and executes nothing: a command buffer asked of it is+ * nil, and the log says so, which is the next step's list.+ */+static Class gQueueClass;+static id gDevice;++static id+queueDevice(__unused id self, __unused SEL _cmd)+{+ return gDevice;+}++static id+queueLabel(__unused id self, __unused SEL _cmd)+{+ return @"HakiosMetalQueue";+}++static void+queueSetGPUPriority(__unused id self, __unused SEL _cmd, __unused unsigned long priority)+{+}++static id+deviceNewQueue(id self, __unused SEL _cmd)+{+ id (*plain)(id, SEL) = (id (*)(id, SEL))objc_msgSend;+ id queue;++ gDevice = self;+ if (gQueueClass == Nil) {+ say(@"newCommandQueue: no queue class (this system has no _MTLCommandQueue): nil");+ return nil;+ }+ queue = plain(plain((id)gQueueClass, sel_registerName("alloc")), sel_registerName("init"));+ say([NSString stringWithFormat:@"newCommandQueue: a queue that queues nothing (%@)", queue ? @"made" : @"_MTLCommandQueue's init gave nil"]);+ return queue;+}++static id+deviceNewQueueMax(id self, SEL _cmd, __unused unsigned long maxBuffers)+{+ return deviceNewQueue(self, _cmd);+}+/* the protocols the class declares (the ones Metal checks for), for the signatures below */-static Protocol * gProtocols[4];+static Protocol * gProtocols[16];static unsigned gProtocolCount;/*@@ -108,7 +163,10 @@ deviceForward(id self, SEL _cmd, id invocation)}if (![seen containsObject:name]) {[seen addObject:name];- say([NSString stringWithFormat:@"asked and not implemented: -%@ (returns %lu bytes; answered with zero)", name, (unsigned long)length]);+ const char * encoding = ((const char * (*)(id, SEL))objc_msgSend)(signature, sel_registerName("methodReturnType"));++ say([NSString stringWithFormat:@"asked and not implemented: -%@ (returns %lu bytes, type %s; answered with zero)", name,+ (unsigned long)length, encoding ? encoding : "?"]);}}if (length != 0) {@@ -119,6 +177,138 @@ deviceForward(id self, SEL _cmd, id invocation)}}+/*+ * The objects a device hands out. Every one is a class of ours made at load time, a subclass of Metal's private base where this+ * system has one (and of NSObject where it does not), declaring the protocol Metal checks and any private protocol of the same+ * name family, answering the rest through the same logged zero stub as the device. None of them does anything: a state object+ * holds nothing, a buffer has memory and a length and nothing else. They exist so that the next question reaches the log, which is+ * the work list of this plug-in (docs/metal-plan.md).+ */+static const struct stubSpec {+ const char * selector; /* the device's method that makes it */+ const char * cls; /* our class */+ const char * base; /* Metal's private base class, if the system has it */+ const char * protocol; /* the public protocol, and the family of private ones beginning with it */+} gStubSpecs[] = {+ { "newDepthStencilStateWithDescriptor:", "HakiosMetalDepthStencilState", "_MTLDepthStencilState", "MTLDepthStencilState" },+ { "newSamplerStateWithDescriptor:", "HakiosMetalSamplerState", "_MTLSamplerState", "MTLSamplerState" },+ { "newTextureWithDescriptor:", "HakiosMetalTexture", "_MTLTexture", "MTLTexture" },+ { "newRenderPipelineStateWithDescriptor:error:", "HakiosMetalRenderPipelineState", "_MTLRenderPipelineState", "MTLRenderPipelineState" },+ { "newComputePipelineStateWithFunction:error:", "HakiosMetalComputePipelineState", "_MTLComputePipelineState", "MTLComputePipelineState" },+ { "newEventWithOptions:", "HakiosMetalEvent", "_MTLEvent", "MTLEvent" },+ { "newFence", "HakiosMetalFence", "_MTLFence", "MTLFence" },+};+#define STUB_COUNT (sizeof(gStubSpecs) / sizeof(gStubSpecs[0]))+static Class gStubClass[STUB_COUNT];++/* a device method that makes one of the objects above: the class is found by the selector it was called by */+static id+stubFactory(__unused id self, SEL _cmd)+{+ id (*plain)(id, SEL) = (id (*)(id, SEL))objc_msgSend;+ const char * called = sel_getName(_cmd);++ for (unsigned i = 0; i < STUB_COUNT; i++) {+ if (strcmp(gStubSpecs[i].selector, called) == 0) {+ id object;++ if (gStubClass[i] == Nil) {+ return nil;+ }+ object = plain(plain((id)gStubClass[i], sel_registerName("alloc")), sel_registerName("init"));+ say([NSString stringWithFormat:@"%s: a %s that holds nothing (%@)", called, gStubSpecs[i].cls, object ? @"made" : @"init gave nil"]);+ return object;+ }+ }+ return nil;+}++/* Declares `protocol` and every private protocol whose name begins with it on `cls`, and keeps them for the stub's signatures. */+static void+declareProtocolFamily(Class cls, const char * protocolName)+{+ unsigned int count = 0;+ Protocol * __unsafe_unretained * all = objc_copyProtocolList(&count);++ for (unsigned int i = 0; i < count; i++) {+ if (strncmp(protocol_getName(all[i]), protocolName, strlen(protocolName)) == 0) {+ class_addProtocol(cls, all[i]);+ if (gProtocolCount < sizeof(gProtocols) / sizeof(gProtocols[0])) {+ gProtocols[gProtocolCount++] = all[i];+ }+ }+ }+ free(all);+}++static void+registerStubClasses(Class device)+{+ for (unsigned i = 0; i < STUB_COUNT; i++) {+ Class base = objc_getClass(gStubSpecs[i].base);+ Class cls = objc_allocateClassPair(base != Nil ? base : objc_getClass("NSObject"), gStubSpecs[i].cls, 0);++ if (cls == Nil) {+ say([NSString stringWithFormat:@"could not make the class %s", gStubSpecs[i].cls]);+ continue;+ }+ declareProtocolFamily(cls, gStubSpecs[i].protocol);+ class_addMethod(cls, sel_registerName("methodSignatureForSelector:"), (IMP)deviceSignature, "@@::");+ class_addMethod(cls, sel_registerName("forwardInvocation:"), (IMP)deviceForward, "v@:@");+ objc_registerClassPair(cls);+ gStubClass[i] = cls;+ class_addMethod(device, sel_registerName(gStubSpecs[i].selector), (IMP)stubFactory, "@@:@");+ say([NSString stringWithFormat:@"%s is a %s (a subclass of %s)", gStubSpecs[i].selector, gStubSpecs[i].cls,+ base != Nil ? gStubSpecs[i].base : "NSObject: this system has no such class"]);+ }+}++static void+registerQueueClass(void)+{+ Class base = objc_getClass("_MTLCommandQueue");+ Protocol * protocol = @protocol(MTLCommandQueue);++ if (base == Nil) {+ say(@"this system has no _MTLCommandQueue: no queue class is registered");+ return;+ }+ gQueueClass = objc_allocateClassPair(base, "HakiosMetalQueue", 0);+ if (gQueueClass == Nil) {+ say(@"could not make the class HakiosMetalQueue");+ return;+ }+ class_addProtocol(gQueueClass, protocol);+ if (gProtocolCount < sizeof(gProtocols) / sizeof(gProtocols[0])) {+ gProtocols[gProtocolCount++] = protocol;+ }+ /*+ * The third run: -setCompletionQueue: is not in MTLCommandQueue but in a private protocol of Metal's own (as MTLDeviceSPI is+ * for the device), and the window server sends it. Every protocol of this process whose name begins with MTLCommandQueue is+ * taken, so that the stub answers what any of them declares; their names go to the log, which is how the next one is found.+ */+ unsigned int count = 0;+ Protocol * __unsafe_unretained * all = objc_copyProtocolList(&count);++ for (unsigned int i = 0; i < count; i++) {+ const char * name = protocol_getName(all[i]);++ if (strncmp(name, "MTLCommandQueue", 15) == 0 && all[i] != protocol && gProtocolCount < sizeof(gProtocols) / sizeof(gProtocols[0])) {+ class_addProtocol(gQueueClass, all[i]);+ gProtocols[gProtocolCount++] = all[i];+ say([NSString stringWithFormat:@"the queue also declares the protocol %s", name]);+ }+ }+ free(all);+ class_addMethod(gQueueClass, sel_registerName("device"), (IMP)queueDevice, "@@:");+ class_addMethod(gQueueClass, sel_registerName("label"), (IMP)queueLabel, "@@:");+ class_addMethod(gQueueClass, sel_registerName("setGPUPriority:"), (IMP)queueSetGPUPriority, "v@:Q");+ class_addMethod(gQueueClass, sel_registerName("methodSignatureForSelector:"), (IMP)deviceSignature, "@@::");+ class_addMethod(gQueueClass, sel_registerName("forwardInvocation:"), (IMP)deviceForward, "v@:@");+ objc_registerClassPair(gQueueClass);+ say(@"the class HakiosMetalQueue is registered (a subclass of _MTLCommandQueue)");+}+__attribute__((constructor)) static voidregisterDevice(void){@@ -162,8 +352,13 @@ registerDevice(void)class_addMethod(device, @selector(initWithAcceleratorPort:), (IMP)deviceInit, "@@:I");class_addMethod(device, @selector(name), (IMP)deviceName, "@@:");class_addMethod(device, @selector(registryID), (IMP)deviceRegistryID, "Q@:");+ class_addMethod(device, sel_registerName("maxBufferLength"), (IMP)deviceMaxBufferLength, "Q@:");+ class_addMethod(device, sel_registerName("newCommandQueue"), (IMP)deviceNewQueue, "@@:");+ class_addMethod(device, sel_registerName("newCommandQueueWithMaxCommandBufferCount:"), (IMP)deviceNewQueueMax, "@@:Q");class_addMethod(device, sel_registerName("methodSignatureForSelector:"), (IMP)deviceSignature, "@@::");class_addMethod(device, sel_registerName("forwardInvocation:"), (IMP)deviceForward, "v@:@");objc_registerClassPair(device);say(@"the class HakiosMetalDevice is registered (a subclass of _MTLDevice)");+ registerQueueClass();+ registerStubClasses(device);}