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 on Vulkan draws the window server right: CoreAnimation's shader variants, its pipeline library
yehorkaa41cbc4f6101d
diff --git a/drivers/gpu/hakios.gpu.cpp b/drivers/gpu/hakios.gpu.cppindex 0751dc7..633b419 100644--- a/drivers/gpu/hakios.gpu.cpp+++ b/drivers/gpu/hakios.gpu.cpp@@ -38,6 +38,7 @@#include <kern/clock.h>#include <mach/mach_time.h>#include <mach/vm_param.h>+extern "C" void flush_dcache64(addr64_t addr, unsigned count, int phys);#include <sys/systm.h>#include "MiniIOSurface.h"@@ -358,7 +359,7 @@ struct gpu_buffer {IOMemoryDescriptor * memory; /* NULL: this handle is free */uint8_t * kernel; /* where it is in the kernel */MiniIOSurface * surface; /* whose memory it is, when not its own */- IOMemoryMap * user; /* the kernel's view of it, when it is the client's own pages */+ bool client; /* the client's own pages (no kernel view: out of the cache by their physical addresses) */uint64_t address; /* the GPU's for it */uint64_t size;uint32_t flags;@@ -378,7 +379,7 @@ struct gpu_buffer {struct gpu_left {IOMemoryDescriptor * memory;MiniIOSurface * surface;- IOMemoryMap * user;+ bool client;uint64_t address, size;uint32_t fence, flags;};@@ -487,7 +488,7 @@ HakiosGPUUserClient::freeBuffer(struct gpu_buffer * slot)slot->memory = NULL;slot->surface = NULL;- slot->user = NULL;+ slot->client = false;fBufferCount--;fBufferBytes -= b->size;@@ -501,7 +502,7 @@ HakiosGPUUserClient::freeBuffer(struct gpu_buffer * slot)left->memory = b->memory;left->surface = b->surface;- left->user = b->user;+ left->client = b->client;left->address = b->address;left->size = b->size;left->fence = b->fence;@@ -518,16 +519,13 @@ HakiosGPUUserClient::freeBuffer(struct gpu_buffer * slot)if (said++ < 8) {IOLog("HakiosGPU: the GPU is not done with what it was given: a buffer of %llu bytes stays its own\n", b->size);}- } else if (b->surface == NULL && b->user == NULL && hakios_gpu_ready() &&+ } else if (b->surface == NULL && !b->client && hakios_gpu_ready() &&keep(b->memory, b->kernel, b->address, b->size, b->flags)) {b->memory = NULL; /* (now the kept one's) */} else if (hakios_gpu_ready()) {hakios_gpu_unmap(b->address, b->size);hakios_gpu_address_free(b->address, b->size);}- if (b->user != NULL && !busy) {- b->user->release(); /* (the pages are unwired as the descriptor goes) */- }if (b->memory != NULL) {b->memory->release();}@@ -548,16 +546,13 @@ HakiosGPUUserClient::reap(void)i++;continue;}- if (left->surface == NULL && left->user == NULL && hakios_gpu_ready() &&+ if (left->surface == NULL && !left->client && hakios_gpu_ready() &&keep(left->memory, NULL, left->address, left->size, left->flags)) {left->memory = NULL;} else if (hakios_gpu_ready()) {hakios_gpu_unmap(left->address, left->size);hakios_gpu_address_free(left->address, left->size);}- if (left->user != NULL) {- left->user->release();- }if (left->memory != NULL) {left->memory->release();}@@ -664,7 +659,7 @@ HakiosGPUUserClient::newBuffer(IOMemoryDescriptor * memory, uint64_t from, uint6b->seen = false;b->fence = 0;b->surface = NULL;- b->user = NULL;+ b->client = false;fBufferCount++;fBufferBytes += size;return b;@@ -884,42 +879,64 @@ HakiosGPUUserClient::surfaceBuffer(struct hakios_surface * request)IOReturnHakiosGPUUserClient::userBuffer(struct hakios_user_memory * request){- IOMemoryDescriptor * memory;- IOMemoryMap * map;+ IOMemoryDescriptor * memory = NULL;struct gpu_buffer * b;uint64_t began = mach_absolute_time();if ((request->address & PAGE_MASK) || (request->size & PAGE_MASK) || request->size == 0 ||request->size > GPU_BUFFER_MAX) {+ static uint32_t said;++ if (said++ < 8) {+ IOLog("HakiosGPU: pages at %#llx (%llu bytes) of the client's: not whole pages of %u bytes\n",+ request->address, request->size, (unsigned) PAGE_SIZE);+ }return kIOReturnBadArgument;}- memory = IOMemoryDescriptor::withAddressRange(request->address, request->size, kIODirectionInOut, fTask);- if (memory == NULL) {- return kIOReturnNoMemory;+ /* pages the client may only read (a window server's view of another program's backing store): the GPU reads them only */+ IOReturn prepared = kIOReturnNoMemory;+ for (int pass = 0; pass < 2 && prepared != kIOReturnSuccess; pass++) {+ memory = IOMemoryDescriptor::withAddressRange(request->address, request->size,+ pass == 0 ? kIODirectionInOut : kIODirectionOut, fTask);+ if (memory == NULL) {+ IOLog("HakiosGPU: pages at %#llx (%llu bytes) of the client's: no descriptor\n", request->address, request->size);+ return kIOReturnNoMemory;+ }+ prepared = memory->prepare();+ if (prepared != kIOReturnSuccess) {+ memory->release();+ memory = NULL;+ } else if (pass == 1) {+ request->flags |= MSM_BO_GPU_READONLY;+ }}- if (memory->prepare() != kIOReturnSuccess) {- memory->release();+ if (memory == NULL) {+ static uint32_t said;++ if (said++ < 8) {+ IOLog("HakiosGPU: pages at %#llx (%llu bytes) of the client's cannot be wired: %#x\n",+ request->address, request->size, prepared);+ }return kIOReturnVMError;}- map = memory->createMappingInTask(kernel_task, 0, kIOMapAnywhere);- if (map == NULL) {- memory->complete();- memory->release();- return kIOReturnNoMemory;- }IOLockLock(gGPULock);b = newBuffer(memory, 0, request->size, request->flags, &request->handle);if (b != NULL) {- b->memory = memory;- b->kernel = (uint8_t *) map->getVirtualAddress();- b->user = map;+ b->memory = memory; /* (its pages unwired as it goes: IOGeneralMemoryDescriptor::free) */+ b->kernel = NULL;+ b->client = true;b->seen = true;gGPUStat.surfaces++;}gGPUStat.taking += mach_absolute_time() - began;IOLockUnlock(gGPULock);if (b == NULL) {- map->release();+ static uint32_t said;++ if (said++ < 8) {+ IOLog("HakiosGPU: pages at %#llx (%llu bytes) of the client's: no room for them in the GPU\n",+ request->address, request->size);+ }memory->complete();memory->release();return kIOReturnNoMemory;@@ -1003,8 +1020,23 @@ HakiosGPUUserClient::submit(struct msm_gem_submit * request)}b->seed = seed;b->pushed = began;- } else if (b->user == NULL && (!b->seen || !gGPUCached)) {- continue; /* (the client's own pages are ordinary memory: every time) */+ } else if (b->client) {+ /* the client's own pages are ordinary memory: out of the cache every time, by their physical addresses */+ for (uint64_t offset = 0; offset < b->size;) {+ IOByteCount length = 0;+ addr64_t phys = b->memory->getPhysicalSegment(offset, &length, kIOMemoryMapperNone);++ if (phys == 0 || length == 0) {+ break;+ }+ length = MIN(length, b->size - offset);+ flush_dcache64(phys, (unsigned) length, TRUE);+ offset += length;+ }+ gGPUStat.flushed += b->size;+ continue;+ } else if (!b->seen || !gGPUCached) {+ continue;}hakios_gpu_to_memory(b->kernel, b->size);gGPUStat.flushed += b->size;diff --git a/tools/m2v/adrenometal-ios16.patch b/tools/m2v/adrenometal-ios16.patchindex b1f20af..07bd9e3 100644--- a/tools/m2v/adrenometal-ios16.patch+++ b/tools/m2v/adrenometal-ios16.patch@@ -1,5 +1,17 @@+diff --git a/NativeBridgeMetalFrontend.h b/NativeBridgeMetalFrontend.h+index 25ed8e5..1f45ee7 100644+--- a/NativeBridgeMetalFrontend.h++++ b/NativeBridgeMetalFrontend.h+@@ -32,5 +32,7 @@ bool native_bridge_metal_work_stats(uint64_t out[10]);+ size_t native_bridge_metal_benchmark(id device, const char *metallib, unsigned pairs, char *out, size_t size);+ // Lets go of every held IOSurface import whose surface only the import still retains (also done at each command buffer's completion).+ void native_bridge_metal_trim_surface_imports(void);++// (hakios) Core Animation's uber shader variants: set by the plug-in (see the frontend's variantFunction()).++extern const void *(*native_bridge_metal_variant_hook)(const char *name, const char *label, const char *pipeline, int vertex, size_t *length);+ }+ #endifdiff --git a/NativeBridgeMetalFrontend.mm b/NativeBridgeMetalFrontend.mm-index aec500d..5c23640 100644+index aec500d..b6ee810 100644--- a/NativeBridgeMetalFrontend.mm+++ b/NativeBridgeMetalFrontend.mm@@ -994,6 +994,17 @@ static void holdImport(uint64_t identity,uint64_t address,uint64_t bytes,NBBuffe@@ -28,7 +40,63 @@ index aec500d..5c23640 100644NmbBuffer *handle=nmb_buffer_new_no_copy_releasing(gDevice,base,bytes,MTLResourceStorageModeShared,releaseSurface,(void *)CFRetain(surface));if(!handle){CFRelease(surface);NBLOG(@"native-metal: surface import refused: %@",lastError());return nil;}gSurfaceImportsMade++;buffer=[NBBuffer new];buffer.handle=handle;buffer.options=MTLResourceStorageModeShared;buffer.importedSurface=surface;-@@ -4550,7 +4562,7 @@ extern "C" id native_bridge_metal_open(const char *loader,const char *cache,uint+@@ -1442,8 +1454,41 @@ static std::string quartzCoreCallers();+ // no runtime handle: it is stitched from its bitcode (functionBitcode) and refused as a pipeline's own function.+ static NBFunction *ciKernelFunction(NBLibrary *library,NSString *name);+ static bool forEachLibraryEntry(NBLibrary *library,const std::function<bool(const std::string &,int)> &visit);++// (hakios) The module of the variant of a Core Animation uber shader a pipeline is made of (its function's name, the function's++// label, the pipeline's label, vertex or not), from the plug-in that knows QuartzCore's pipeline library; null: the function itself.++extern "C" const void *(*native_bridge_metal_variant_hook)(const char *,const char *,const char *,int,size_t *);++const void *(*native_bridge_metal_variant_hook)(const char *,const char *,const char *,int,size_t *);++static id<MTLFunction> variantFunction(id<MTLFunction> f,NSString *pipeline,bool vertex) {++ if(!f || ![f.name hasPrefix:@"fixed_"])return f;++ size_t length=0;++ NSString *label=[f respondsToSelector:@selector(label)]?[(id)f label]:nil;++ const void *air=native_bridge_metal_variant_hook(f.name.UTF8String,label.UTF8String,pipeline.UTF8String,vertex,&length);++ if(!air || !length)return f;++ static NSMutableDictionary *libraries;static std::mutex lock;++ id library;++ {std::lock_guard<std::mutex> hold(lock);++ if(!libraries)libraries=[NSMutableDictionary dictionary];++ NSNumber *key=@((uintptr_t)air);++ library=libraries[key];++ if(!library){library=native_bridge_metal_library_with_air(air,length);if(library)libraries[key]=library;}}++ if(!library)return f;++ NSString *name=[[library functionNames] containsObject:f.name]?f.name:[[library functionNames] firstObject];++ MTLFunctionConstantValues *values=[f isKindOfClass:[NBFunction class]]?((NBFunction *)f).constantValues:nil;++ NSError *error=nil;++ id<MTLFunction> chosen=values?[library newFunctionWithName:name constantValues:values error:&error]:[library newFunctionWithName:name];++ if(!chosen && values)chosen=[library newFunctionWithName:name];++ return chosen?:f;++}+++ @implementation NBLibrary+ - (void)dealloc {DetailSpan timing(9,(uintptr_t)_handle);nmb_library_release(_handle);}++// (hakios) iOS 16's pipeline library builder (MTLPipelineLibrary over pipelines.desc) asks with Metal's function cache, which holds++// nothing of this device's: the same as without it.++- (id<MTLFunction>)newFunctionWithName:(NSString *)name constantValues:(MTLFunctionConstantValues *)values functionCache:(id)cache++ error:(NSError **)error {++ (void)cache;++ return values?[self newFunctionWithName:name constantValues:values error:error]:[self newFunctionWithName:name];++}+ - (id<MTLFunction>)newFunctionWithName:(NSString *)name constantValues:(MTLFunctionConstantValues *)values error:(NSError **)error {+ return [self nb_newFunctionWithName:name constantValues:values zeroRest:NO error:error];+ }+@@ -4367,6 +4412,13 @@ static bool pipelineArchives(NSArray *list,std::vector<NmbBinaryArchive *> &arch+ - (id<MTLRenderPipelineState>)newRenderPipelineStateWithDescriptor:(MTLRenderPipelineDescriptor *)d options:(MTLPipelineOption)options+ reflection:(MTLAutoreleasedRenderPipelineReflection *)reflection error:(NSError **)error {+ if(reflection)*reflection=nil;++ // (hakios) Core Animation's uber shaders: the variant of the pipeline (native_bridge_metal_variant_hook) in place of the function++ if(native_bridge_metal_variant_hook && ([d.vertexFunction.name hasPrefix:@"fixed_"] || [d.fragmentFunction.name hasPrefix:@"fixed_"])) {++ id<MTLFunction> vertex=variantFunction(d.vertexFunction,d.label,true),fragment=variantFunction(d.fragmentFunction,d.label,false);++ if(vertex!=d.vertexFunction || fragment!=d.fragmentFunction) {++ d=[d copy];d.vertexFunction=vertex;d.fragmentFunction=fragment;++ }++ }+ auto *p=new NBRenderDescriptor();+ if(!renderDescriptor(d,p,error)) {+ static std::atomic<int> told{0};+@@ -4550,7 +4602,7 @@ extern "C" id native_bridge_metal_open(const char *loader,const char *cache,uint#if defined(__arm64e__)if(!base){NBLOG(@"native-metal: no _MTLDevice");return nil;}#elsediff --git a/tools/m2v/metal2vulkan-hakios.patch b/tools/m2v/metal2vulkan-hakios.patchnew file mode 100644index 0000000..3797eb7--- /dev/null+++ b/tools/m2v/metal2vulkan-hakios.patch@@ -0,0 +1,35 @@+diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs+index e07a3208..f677399f 100644+--- a/crates/metal2vulkan-runtime/src/host_memory.rs++++ b/crates/metal2vulkan-runtime/src/host_memory.rs+@@ -547,7 +547,20 @@ pub(super) fn host_page() -> Option<u64> {+ }++ /// The refusal of host memory this device cannot import exactly.++#[track_caller]+ pub(super) fn not_importable() -> Error {++ // (hakios) where it was refused, once per site: the refusal itself names no reason++ {++ use std::sync::Mutex;++ static SAID: Mutex<Vec<String>> = Mutex::new(Vec::new());++ let at = std::panic::Location::caller().to_string();++ if let Ok(mut said) = SAID.lock() {++ if !said.contains(&at) && said.len() < 32 {++ eprintln!("metal2vulkan: host memory refused at {at} (error)");++ said.push(at);++ }++ }++ }+ Error::Unsupported(Unsupported::not_representable(Feature::HostMemory))+ }++@@ -562,7 +575,9 @@ pub(super) fn refused(error: &Error) -> bool {+ /// driver that refuses the memory is a device gap, anything else a Vulkan failure. Refusing+ /// drivers answer `VK_ERROR_INVALID_EXTERNAL_HANDLE`, but RADV of Mesa 26.0.8 answers+ /// `VK_ERROR_UNKNOWN` for the shared memory 26.2.4 refuses with it, so that is a refusal too.++#[track_caller]+ pub(super) fn import_refused(error: vk::Result) -> Error {++ eprintln!("metal2vulkan: the driver refused an import: {error:?} (error)");+ match error {+ vk::Result::ERROR_INVALID_EXTERNAL_HANDLE | vk::Result::ERROR_UNKNOWN => not_importable(),+ other => vulkan(other),diff --git a/tools/mesa/turnip-darwin.patch b/tools/mesa/turnip-darwin.patchindex 66f8b41..58963d1 100644--- a/tools/mesa/turnip-darwin.patch+++ b/tools/mesa/turnip-darwin.patch@@ -248,7 +248,7 @@ index 27916d0..569b1d6 100644TU_RMV(bo_destroy, dev, bo);diff --git a/src/freedreno/vulkan/tu_knl_drm_msm.cc b/src/freedreno/vulkan/tu_knl_drm_msm.cc-index 08831e7..8da1a57 100644+index 08831e7..d2a7d07 100644--- a/src/freedreno/vulkan/tu_knl_drm_msm.cc+++ b/src/freedreno/vulkan/tu_knl_drm_msm.cc@@ -191,7 +191,12 @@ tu_drm_is_memory_type_supported(int fd, uint32_t flags)@@ -293,13 +293,20 @@ index 08831e7..8da1a57 100644if (real_size < 0 || (uint64_t) real_size < size)return vk_error(dev, VK_ERROR_INVALID_EXTERNAL_HANDLE);-@@ -699,8 +717,13 @@ msm_bo_init_dmabuf(struct tu_device *dev,+@@ -699,8 +717,20 @@ msm_bo_init_dmabuf(struct tu_device *dev,msm_vma_lock(dev);uint32_t gem_handle;+#ifdef __APPLE__+ int ret = prime_fd < 0 ? hakios_drm_user_memory(dev->fd, tu_darwin_host_pointer, size, &gem_handle)+ : drmPrimeFDToHandle(dev->fd, prime_fd, &gem_handle);++ if (ret) {++ static int said;++ if (said++ < 8)++ mesa_loge("import of %s %p (%llu bytes) refused: %s", prime_fd < 0 ? "host pages" : "IOSurface",++ prime_fd < 0 ? tu_darwin_host_pointer : (const void *) (uintptr_t) prime_fd,++ (unsigned long long) size, strerror(errno));++ }+#elseint ret = drmPrimeFDToHandle(dev->fd, prime_fd,&gem_handle);@@ -307,7 +314,7 @@ index 08831e7..8da1a57 100644if (ret) {msm_vma_unlock(dev);u_rwlock_wrunlock(&dev->dma_bo_lock);-@@ -735,6 +758,12 @@ msm_bo_init_dmabuf(struct tu_device *dev,+@@ -735,6 +765,12 @@ msm_bo_init_dmabuf(struct tu_device *dev,static VkResultmsm_bo_map(struct tu_device *dev, struct tu_bo *bo, void *placed_addr){@@ -320,7 +327,7 @@ index 08831e7..8da1a57 100644uint64_t offset = tu_gem_info(dev, bo->gem_handle, MSM_INFO_GET_OFFSET);if (!offset)return vk_error(dev, VK_ERROR_OUT_OF_DEVICE_MEMORY);-@@ -743,6 +772,7 @@ msm_bo_map(struct tu_device *dev, struct tu_bo *bo, void *placed_addr)+@@ -743,6 +779,7 @@ msm_bo_map(struct tu_device *dev, struct tu_bo *bo, void *placed_addr)void *map = mmap(placed_addr, bo->size, PROT_READ | PROT_WRITE,MAP_SHARED | (placed_addr != NULL ? MAP_FIXED : 0),dev->fd, offset);diff --git a/tools/mk-m2v.sh b/tools/mk-m2v.shindex b206622..f3fe06c 100755--- a/tools/mk-m2v.sh+++ b/tools/mk-m2v.sh@@ -32,7 +32,7 @@ fetch() { # repository, revision, directory, patches...}fetch https://github.com/UniXNU/AdrenoMetal.git $AM_PIN AdrenoMetal $ROOT/tools/m2v/adrenometal-ios16.patchA=$B/AdrenoMetal-fetch https://github.com/steelbrain/metal2vulkan.git $M2V_PIN metal2vulkan $A/bridge/patches/00*.patch+fetch https://github.com/steelbrain/metal2vulkan.git $M2V_PIN metal2vulkan $A/bridge/patches/00*.patch $ROOT/tools/m2v/metal2vulkan-hakios.patchS=$B/metal2vulkan# the bridge: the runtime behind a C interface, as UniXNU's scripts/build-adreno-metal-bridge.py builds itdiff --git a/userland/src/HakiosMetalCA.m b/userland/src/HakiosMetalCA.mindex 6480464..552de6b 100644--- a/userland/src/HakiosMetalCA.m+++ b/userland/src/HakiosMetalCA.m@@ -110,6 +110,7 @@/* --- printing ----------------------------------------------------------------------------------------------- */static void hm_print(const char *fmt, ...) __attribute__((format(printf, 1, 2)));+static int hm_print_fd = -1; /* where hm_print writes: stderr, the console, or (metal_m2v=1) a copy of stderr kept aside *//* To stderr, as one write: a launchd job's stderr is the console (userland/mkjobs.py sets StandardErrorPath) and its* stdout is nowhere, so the window server's lines -- the client this plug-in is for -- reached no log while they went@@ -135,7 +136,7 @@ hm_print(const char *fmt, ...)/* An application's stderr is /dev/null (a launchd job's is the log); there the line goes to the console instead, as* libhakios.sb.dylib's does in the programs it is given to, so that what this plug-in says inside Maps is read too */{- static int fd = -1;+ int fd = hm_print_fd;if (fd < 0) {struct stat err, null;@@ -147,6 +148,7 @@ hm_print(const char *fmt, ...)if (console >= 0) fd = console;}}+ hm_print_fd = fd;(void)!write(fd, line, strlen(line));}}@@ -1595,6 +1597,47 @@ hm_bitcode_for(id function, NSString *pipeline, BOOL vertex)return variant != nil ? variant : own;}+/* The same choice for UniXNU's Metal on Vulkan (metal_m2v=1), whose functions are its own objects: by the function's name,+ * its label and the pipeline's (native_bridge_metal_variant_hook, NativeBridgeMetalFrontend.mm: variantFunction()). */+static const void *+hm_m2v_variant(const char *name, const char *label, const char *pipeline, int vertex, size_t *length)+{+ static unsigned said;+ NSString *chosen = nil;+ NSData *variant = nil;++ if (name == NULL || strncmp(name, "fixed_", 6) != 0) {+ return NULL;+ }+ hm_ca_load();+ NSString *flabel = label ? @(label) : nil, *plabel = pipeline ? @(pipeline) : nil;+ if (flabel != nil && (variant = hm_ca_variants[flabel]) != nil) {+ chosen = flabel;+ } else if (plabel != nil && hm_ca_pipelines[plabel] != nil) {+ NSArray *pair = hm_ca_pipelines[plabel];++ chosen = vertex ? pair[0] : ([pair count] > 1 ? pair[1] : nil);+ variant = chosen != nil ? hm_ca_variants[chosen] : nil;+ } else if (plabel != nil && [plabel hasPrefix:@"com.apple.coreanimation.draw."]) {+ NSString *spec = [plabel substringFromIndex:[@"com.apple.coreanimation.draw." length]];+ NSRange under = [spec rangeOfString:@"_"];+ NSString *frag = under.location != NSNotFound ?+ [@"com.apple.coreanimation.frag." stringByAppendingString:[spec substringFromIndex:NSMaxRange(under)]] : nil;++ chosen = frag == nil ? nil : (vertex ? hm_ca_frag_vert[frag] : frag);+ variant = chosen != nil ? hm_ca_variants[chosen] : nil;+ }+ if (said++ < 20) {+ hm_print("metal2vulkan: CoreAnimation's %s (label %s, pipeline %s): %s%s\n", name, label ? label : "none",+ pipeline ? pipeline : "none", variant ? "the variant " : "no variant", variant ? [chosen UTF8String] : "");+ }+ if (variant == nil) {+ return NULL;+ }+ *length = [variant length];+ return [variant bytes]; /* (the dictionary keeps it for good) */+}+static voidhm_dump_function(const char *label, id function, const char *key, const hakios_metal_constant *constants, unsigned count){@@ -1964,6 +2007,10 @@ extern id native_bridge_metal_open(const char *loader, const char *cache, uint64extern uint64_t native_bridge_metal_first_problem(char *out, size_t size) __attribute__((weak_import));extern size_t native_bridge_metal_status(char *out, size_t size) __attribute__((weak_import));extern size_t native_bridge_metal_formats(char *out, size_t size) __attribute__((weak_import));+extern const void *(*native_bridge_metal_variant_hook)(const char *, const char *, const char *, int, size_t *) __attribute__((weak_import));+static const void *hm_m2v_variant(const char *name, const char *label, const char *pipeline, int vertex, size_t *length);++static char hm_m2v_last_stderr[400]; /* the last line of Turnip's or the runtime's that said error, refused or warning */static voidhm_m2v_missing(const char *class, const char *selector)@@ -2015,12 +2062,59 @@ hm_boot_arg_set(const char *what)hm_print("metal2vulkan: TU_DEBUG=%s\n", value);}}+ /* Turnip's and the runtime's own messages (stderr) into this log: the first 200 lines */+ {+ static int pipe_fds[2];++ hm_print("metal2vulkan: stderr into this log\n"); /* (hm_print_fd decided first: then kept aside from fd 2) */+ if (hm_print_fd == 2) {+ hm_print_fd = dup(2);+ }+ if (pipe(pipe_fds) == 0 && dup2(pipe_fds[1], 2) >= 0) {+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{+ FILE *in = fdopen(pipe_fds[0], "r");+ char line[400];+ int lines = 0;++ while (in != NULL && fgets(line, sizeof(line), in) != NULL) {+ if (lines++ < 40 || strstr(line, "metal2vulkan:") != NULL || strstr(line, "TU: ") != NULL) {+ hm_print("stderr: %s", line);+ }+ if (strcasestr(line, "error") || strcasestr(line, "refus") || strcasestr(line, "warn")) {+ strlcpy(hm_m2v_last_stderr, line, sizeof(hm_m2v_last_stderr));+ }+ }+ });+ }+ }+ if (&native_bridge_metal_variant_hook != NULL) {+ native_bridge_metal_variant_hook = hm_m2v_variant;+ }mkdir("/private/var/db/m2v", 0700);id device = native_bridge_metal_open("/redwood/lib/libvulkan_freedreno.dylib",access("/private/var/db/m2v", W_OK) == 0 ? "/private/var/db/m2v" : "/private/var/tmp/m2v", 0, hm_m2v_missing);if (device != nil) {hm_print("device: %s (metal2vulkan over Turnip, class %s)\n", [[device name] UTF8String],object_getClassName(device));+ /* QuartzCore's pipeline library opened as for hakios-metal's device (this class's method, onto the+ * metal2vulkan device's class: it calls _MTLDevice's own, both devices' base): its pipelines then+ * carry the labels whose variants hm_m2v_variant() finds. Its cache wants the device's target, which+ * the frontend leaves to _MTLDevice (NULL): the name without spaces, as Metal names a device's. */+ {+ Class nb = object_getClass(device);+ SEL open = @selector(newPipelineLibraryWithFilePath:error:);+ Method ours = class_getInstanceMethod([self class], open);+ static struct MTLTargetDeviceArch target;+ static char name[64];++ snprintf(name, sizeof(name), "%s", [[[device name] stringByReplacingOccurrencesOfString:@" " withString:@""] UTF8String]);+ target.name = name;+ if (ours != NULL) {+ class_replaceMethod(nb, open, method_getImplementation(ours), method_getTypeEncoding(ours));+ }+ class_replaceMethod(nb, @selector(targetDeviceInfo),+ imp_implementationWithBlock(^const struct MTLTargetDeviceArch *(id me) { (void)me; return ⌖ }), "^v16@0:8");+ }/* what it did, every 5 s: commits, passes, draws, refusals; the textures and the surfaces imported */dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{for (;;) {@@ -2029,6 +2123,9 @@ hm_boot_arg_set(const char *what)native_bridge_metal_status(status, sizeof(status));native_bridge_metal_formats(formats, sizeof(formats));hm_print("metal2vulkan: %s | %s\n", status, formats);+ if (hm_m2v_last_stderr[0] != 0) {+ hm_print("metal2vulkan: last stderr: %s", hm_m2v_last_stderr);+ }}});return [device retain]; /* (self not released: before -init, _MTLDevice's -dealloc reads what -init never set) */diff --git a/userland/src/m2v_test.m b/userland/src/m2v_test.mindex 296309f..beaec62 100644--- a/userland/src/m2v_test.m+++ b/userland/src/m2v_test.m@@ -7,6 +7,8 @@*/#import <Foundation/Foundation.h>#import <Metal/Metal.h>+#import <IOSurface/IOSurfaceRef.h>+#include <mach/mach.h>#include <signal.h>#include <stdio.h>#include <dlfcn.h>@@ -163,6 +165,81 @@ main(void)}printf("m2v_test: 100 full-screen clears, each committed and waited for: %.3f ms on average, %.3f at best\n",sum / 100, best);- return status(good != width * height);+ int failed = good != width * height;++ /* what the window server reads: an IOSurface written by the CPU, and pages of a program's own (no-copy), as textures */+ const NSUInteger side = 256;+ MTLTextureDescriptor *small = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm+ width:side height:side mipmapped:NO];+ small.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;+ small.storageMode = MTLStorageModeShared;+ id<MTLTexture> into = [device newTextureWithDescriptor:small];+ uint32_t *back = malloc(side * side * 4);+ uint32_t (^copied)(id<MTLTexture>, uint32_t) = ^uint32_t(id<MTLTexture> from, uint32_t want) {+ memset(back, 0, side * side * 4);+ id<MTLCommandBuffer> c = [queue commandBuffer];+ id<MTLBlitCommandEncoder> b = [c blitCommandEncoder];+ [b copyFromTexture:from sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0)+ sourceSize:MTLSizeMake(side, side, 1) toTexture:into destinationSlice:0 destinationLevel:0+ destinationOrigin:MTLOriginMake(0, 0, 0)];+ [b endEncoding];+ [c commit];+ [c waitUntilCompleted];+ [into getBytes:back bytesPerRow:side * 4 fromRegion:MTLRegionMake2D(0, 0, side, side) mipmapLevel:0];+ uint32_t right = 0;+ for (NSUInteger i = 0; i < side * side; i++)+ right += back[i] == want;+ printf("m2v_test: status %ld, first pixel %#x, last %#x\n", (long)c.status, back[0], back[side * side - 1]);+ return right;+ };++ NSDictionary *props = @{ (id)kIOSurfaceWidth: @(side), (id)kIOSurfaceHeight: @(side), (id)kIOSurfaceBytesPerElement: @4,+ (id)kIOSurfacePixelFormat: @((uint32_t)'BGRA') };+ IOSurfaceRef surface = IOSurfaceCreate((__bridge CFDictionaryRef)props);+ IOSurfaceLock(surface, 0, NULL);+ size_t row = IOSurfaceGetBytesPerRow(surface);+ for (NSUInteger y = 0; y < side; y++)+ for (NSUInteger x = 0; x < side; x++)+ ((uint32_t *)((uint8_t *)IOSurfaceGetBaseAddress(surface) + y * row))[x] = 0xff00ff00;+ IOSurfaceUnlock(surface, 0, NULL);+ id<MTLTexture> onSurface = [device newTextureWithDescriptor:small iosurface:surface plane:0];+ right = onSurface ? copied(onSurface, 0xff00ff00) : 0;+ printf("m2v_test: IOSurface written by the CPU, copied by the GPU: %lu of %lu pixels green%s\n", (unsigned long)right,+ (unsigned long)(side * side), right == side * side ? "" : " -- WRONG");+ failed |= right != side * side;++ vm_address_t pages = 0;+ vm_allocate(mach_task_self(), &pages, side * side * 4, VM_FLAGS_ANYWHERE);+ for (NSUInteger i = 0; i < side * side; i++)+ ((uint32_t *)pages)[i] = 0xffff0000;+ id<MTLBuffer> noCopy = [device newBufferWithBytesNoCopy:(void *)pages length:side * side * 4+ options:MTLResourceStorageModeShared deallocator:nil];+ id<MTLTexture> onPages = [noCopy newTextureWithDescriptor:small offset:0 bytesPerRow:side * 4];+ right = onPages ? copied(onPages, 0xffff0000) : 0;+ printf("m2v_test: own pages (no-copy buffer %s, texture %s) copied by the GPU: %lu of %lu pixels red%s\n",+ noCopy ? "made" : "REFUSED", onPages ? "made" : "REFUSED", right, (unsigned long)(side * side),+ right == side * side ? "" : " -- WRONG");+ failed |= right != side * side;++ /* and the other way: the GPU clears the IOSurface, the CPU reads it */+ MTLRenderPassDescriptor *toSurface = [MTLRenderPassDescriptor renderPassDescriptor];+ toSurface.colorAttachments[0].texture = onSurface;+ toSurface.colorAttachments[0].loadAction = MTLLoadActionClear;+ toSurface.colorAttachments[0].storeAction = MTLStoreActionStore;+ toSurface.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 1, 1);+ cb = [queue commandBuffer];+ [[cb renderCommandEncoderWithDescriptor:toSurface] endEncoding];+ [cb commit];+ [cb waitUntilCompleted];+ IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL);+ right = 0;+ for (NSUInteger y = 0; y < side; y++)+ for (NSUInteger x = 0; x < side; x++)+ right += ((uint32_t *)((uint8_t *)IOSurfaceGetBaseAddress(surface) + y * row))[x] == 0xff0000ff;+ printf("m2v_test: IOSurface cleared by the GPU, read by the CPU: %lu of %lu pixels blue (first %#x)%s\n", right,+ (unsigned long)(side * side), *(uint32_t *)IOSurfaceGetBaseAddress(surface), right == side * side ? "" : " -- WRONG");+ IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);+ failed |= right != side * side;+ return status(failed);}}