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
The window server draws through UniXNU's Metal on Vulkan (metal_m2v=1)
yehorkaa32f59a297de3
diff --git a/tools/m2v/adrenometal-ios16.patch b/tools/m2v/adrenometal-ios16.patchindex 1b1ca43..b1f20af 100644--- a/tools/m2v/adrenometal-ios16.patch+++ b/tools/m2v/adrenometal-ios16.patch@@ -1,8 +1,34 @@diff --git a/NativeBridgeMetalFrontend.mm b/NativeBridgeMetalFrontend.mm-index aec500d..3b42251 100644+index aec500d..5c23640 100644--- a/NativeBridgeMetalFrontend.mm+++ b/NativeBridgeMetalFrontend.mm-@@ -4550,7 +4550,7 @@ extern "C" id native_bridge_metal_open(const char *loader,const char *cache,uint+@@ -994,6 +994,17 @@ static void holdImport(uint64_t identity,uint64_t address,uint64_t bytes,NBBuffe+ pruneHeldImports(false,gone);+ gHeldImports[{identity,address,bytes}]={buffer,buffer.importedSurface};+ }++// (hakios) Turnip there imports a host pointer only as an IOSurface's memory, which its kernel makes a buffer of by the surface's ID:++// the surface mapped at base is told to it (tools/mesa/hakios-drm: hakios_drm_host_surface) before the runtime imports the pages.++static void tellHostSurface(IOSurfaceRef surface,void *base,size_t bytes) {++ static void (*tell)(const void *,uint64_t,uint32_t);++ static std::once_flag once;++ std::call_once(once,[]{++ if(void *turnip=gLoaderPath.empty()?nullptr:dlopen(gLoaderPath.c_str(),RTLD_NOW|RTLD_NOLOAD))++ tell=(void (*)(const void *,uint64_t,uint32_t))dlsym(turnip,"hakios_drm_host_surface");++ });++ if(tell)tell(base,bytes,IOSurfaceGetID(surface));++}+ static NBBuffer *surfaceBuffer(IOSurfaceRef surface,void *base,size_t bytes) {+ struct Key {uint64_t identity,address,bytes;};+ const Key value={IOSurfaceGetID(surface),(uintptr_t)base,bytes};+@@ -1005,6 +1016,7 @@ static NBBuffer *surfaceBuffer(IOSurfaceRef surface,void *base,size_t bytes) {+ NBBuffer *buffer=key?[gSurfaceImports objectForKey:key]:nil;+ if(buffer){if(key)holdImport(value.identity,value.address,value.bytes,buffer,gone);return buffer;}+ // The surface keeps its CPU mapping (the imported pages) until the import is freed.++ tellHostSurface(surface,base,bytes);+ NmbBuffer *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#if defined(__arm64e__)if(!base){NBLOG(@"native-metal: no _MTLDevice");return nil;}#elsediff --git a/tools/mesa/hakios-drm/hakios.drm.c b/tools/mesa/hakios-drm/hakios.drm.cindex 78bb5e8..9bfb780 100644--- a/tools/mesa/hakios-drm/hakios.drm.c+++ b/tools/mesa/hakios-drm/hakios.drm.c@@ -577,3 +577,53 @@ int drmGetDevices2(uint32_t flags, drmDevicePtr devices[], int max_devices) { (vvoid drmFreeDevices(drmDevicePtr devices[], int count) { (void)devices; (void)count; }int drmGetDevice2(int fd, uint32_t flags, drmDevicePtr *device) { (void)fd; (void)flags; *device = NULL; return -ENODEV; }void drmFreeDevice(drmDevicePtr *device) { (void)device; }++/*+ * The IOSurfaces mapped in this process, by address (hakios_drm_host_surface): a host pointer Turnip is asked to import+ * (VK_EXT_external_memory_host) is the memory of one of them, and the kernel makes a buffer of a surface by its ID+ * (drmPrimeFDToHandle). A surface's mapping lasts as long as the surface; a later surface at the same address replaces it.+ */+#define HOST_SURFACES 1024+static struct { uintptr_t base; uint64_t size; uint32_t surface; } host_surfaces[HOST_SURFACES];+static unsigned host_surfaces_next;+static pthread_mutex_t host_surfaces_lock = PTHREAD_MUTEX_INITIALIZER;++__attribute__((visibility("default"))) /* (called by AdrenoMetal's frontend, outside Turnip) */+void+hakios_drm_host_surface(const void *base, uint64_t size, uint32_t surface)+{+ unsigned i, free_slot = HOST_SURFACES;++ pthread_mutex_lock(&host_surfaces_lock);+ for (i = 0; i < HOST_SURFACES; i++) {+ if (host_surfaces[i].base == (uintptr_t)base) {+ break;+ }+ if (host_surfaces[i].base == 0 && free_slot == HOST_SURFACES) {+ free_slot = i;+ }+ }+ if (i == HOST_SURFACES) {+ i = free_slot != HOST_SURFACES ? free_slot : host_surfaces_next++ % HOST_SURFACES;+ }+ host_surfaces[i].base = (uintptr_t)base;+ host_surfaces[i].size = size;+ host_surfaces[i].surface = surface;+ pthread_mutex_unlock(&host_surfaces_lock);+}++uint32_t+hakios_drm_host_surface_at(const void *base, uint64_t size)+{+ uint32_t surface = 0;++ pthread_mutex_lock(&host_surfaces_lock);+ for (unsigned i = 0; i < HOST_SURFACES; i++) {+ if (host_surfaces[i].base == (uintptr_t)base && host_surfaces[i].size >= size) {+ surface = host_surfaces[i].surface;+ break;+ }+ }+ pthread_mutex_unlock(&host_surfaces_lock);+ return surface;+}diff --git a/tools/mesa/hakios-drm/xf86drm.h b/tools/mesa/hakios-drm/xf86drm.hindex d8ca982..09b3735 100644--- a/tools/mesa/hakios-drm/xf86drm.h+++ b/tools/mesa/hakios-drm/xf86drm.h@@ -104,6 +104,10 @@ struct hakios_drm_surface {uint32_t width, height, pixel_format, planes; /* and what they are */};int hakios_drm_surface(int fd, struct hakios_drm_surface *surface);+/* Not libdrm's: which IOSurface's memory is mapped at BASE in this process, told by whoever maps it (AdrenoMetal's frontend,+ * tools/m2v), for Turnip's VK_EXT_external_memory_host, which is given only the address: its ID, 0 if nobody said. */+void hakios_drm_host_surface(const void *base, uint64_t size, uint32_t surface);+uint32_t hakios_drm_host_surface_at(const void *base, uint64_t size);#ifdef __cplusplus}diff --git a/tools/mesa/turnip-darwin.patch b/tools/mesa/turnip-darwin.patchindex 1aedc6e..e2a59e7 100644--- a/tools/mesa/turnip-darwin.patch+++ b/tools/mesa/turnip-darwin.patch@@ -39,10 +39,41 @@ index d0a38c9..4f68424 100644install : true,)diff --git a/src/freedreno/vulkan/tu_device.cc b/src/freedreno/vulkan/tu_device.cc-index 62ebfd0..f1bc5f6 100644+index 62ebfd0..d273d0e 100644--- a/src/freedreno/vulkan/tu_device.cc+++ b/src/freedreno/vulkan/tu_device.cc-@@ -2709,6 +2709,7 @@ tu_CreateDevice(VkPhysicalDevice physicalDevice,+@@ -8,6 +8,9 @@+ */++ #include "tu_device.h"++#if defined(__APPLE__) && defined(TU_HAS_MSM)++#include <xf86drm.h> /* hakios_drm_host_surface_at (src/hakios-drm) */++#endif++ #include "drm-uapi/drm_fourcc.h"+ #include "fdl/freedreno_layout.h"+@@ -269,6 +272,10 @@ get_device_extensions(const struct tu_physical_device *device,+ .EXT_extended_dynamic_state2 = true,+ .EXT_extended_dynamic_state3 = true,+ .EXT_external_memory_dma_buf = true,++#if defined(__APPLE__) && defined(TU_HAS_MSM)++ /* the memory of IOSurfaces, by their address (src/hakios-drm: hakios_drm_host_surface) */++ .EXT_external_memory_host = true,++#endif+ .EXT_filter_cubic = device->info->a6xx.has_tex_filter_cubic,+ .EXT_fragment_density_map = true,+ .EXT_global_priority = true,+@@ -1160,6 +1167,9 @@ tu_get_properties(struct tu_physical_device *pdevice,++ /* VK_EXT_custom_border_color */+ props->maxCustomBorderColorSamplers = TU_BORDER_COLOR_COUNT;++#if defined(__APPLE__) && defined(TU_HAS_MSM)++ props->minImportedHostPointerAlignment = 16384; /* a page of Darwin's */++#endif++ /* VK_KHR_performance_query */+ props->allowCommandBufferQueryCopies = false;+@@ -2709,6 +2719,7 @@ tu_CreateDevice(VkPhysicalDevice physicalDevice,"pthread condattr init");goto fail_timeline_cond;}@@ -50,7 +81,7 @@ index 62ebfd0..f1bc5f6 100644if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {pthread_condattr_destroy(&condattr);result = vk_startup_errorf(physical_device->instance,-@@ -2716,6 +2717,7 @@ tu_CreateDevice(VkPhysicalDevice physicalDevice,+@@ -2716,6 +2727,7 @@ tu_CreateDevice(VkPhysicalDevice physicalDevice,"pthread condattr clock setup");goto fail_timeline_cond;}@@ -58,7 +89,7 @@ index 62ebfd0..f1bc5f6 100644if (pthread_cond_init(&device->timeline_cond, &condattr) != 0) {pthread_condattr_destroy(&condattr);result = vk_startup_errorf(physical_device->instance,-@@ -3015,6 +3017,16 @@ vk_icdGetInstanceProcAddr(VkInstance instance, const char *pName)+@@ -3015,6 +3027,16 @@ vk_icdGetInstanceProcAddr(VkInstance instance, const char *pName)return tu_GetInstanceProcAddr(instance, pName);}@@ -75,6 +106,44 @@ index 62ebfd0..f1bc5f6 100644VKAPI_ATTR VkResult VKAPI_CALLtu_AllocateMemory(VkDevice _device,const VkMemoryAllocateInfo *pAllocateInfo,+@@ -3064,6 +3086,15 @@ tu_AllocateMemory(VkDevice _device,+ /* take ownership and close the fd */+ close(fd_info->fd);+ }++#if defined(__APPLE__) && defined(TU_HAS_MSM)++ } else if (const VkImportMemoryHostPointerInfoEXT *host_info =++ vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT)) {++ /* an IOSurface's memory: the kernel makes a buffer of the surface (as of a dma-buf, whose fd is its ID here) */++ uint32_t surface = hakios_drm_host_surface_at(host_info->pHostPointer, pAllocateInfo->allocationSize);++ result = surface != 0 ? tu_bo_init_dmabuf(device, &mem->bo, pAllocateInfo->allocationSize, (int) surface)++ : vk_errorf(device, VK_ERROR_INVALID_EXTERNAL_HANDLE,++ "host pointer %p is not an IOSurface's", host_info->pHostPointer);++#endif+ } else if (mem->vk.ahardware_buffer) {+ #if DETECT_OS_ANDROID+ const native_handle_t *handle = AHardwareBuffer_getNativeHandle(mem->vk.ahardware_buffer);+@@ -3402,6 +3433,21 @@ tu_GetMemoryFdPropertiesKHR(VkDevice _device,+ return VK_SUCCESS;+ }+++#if defined(__APPLE__) && defined(TU_HAS_MSM)++VKAPI_ATTR VkResult VKAPI_CALL++tu_GetMemoryHostPointerPropertiesEXT(VkDevice _device,++ VkExternalMemoryHandleTypeFlagBits handleType,++ const void *pHostPointer,++ VkMemoryHostPointerPropertiesEXT *pMemoryHostPointerProperties)++{++ VK_FROM_HANDLE(tu_device, device, _device);++ /* only an IOSurface's memory can be imported: any other pointer, no type (its user places the memory as ever) */++ pMemoryHostPointerProperties->memoryTypeBits =++ hakios_drm_host_surface_at(pHostPointer, 1) != 0 ? (1 << device->physical_device->memory.type_count) - 1 : 0;++ return VK_SUCCESS;++}++#endif+++ VKAPI_ATTR void VKAPI_CALL+ tu_GetPhysicalDeviceMultisamplePropertiesEXT(+ VkPhysicalDevice physicalDevice,diff --git a/src/freedreno/vulkan/tu_knl.cc b/src/freedreno/vulkan/tu_knl.ccindex 80e3900..3f00525 100644--- a/src/freedreno/vulkan/tu_knl.cc@@ -176,7 +245,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..7472ea6 100644+index 08831e7..0a75392 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)@@ -192,7 +261,23 @@ index 08831e7..7472ea6 100644if (fd < 0) {return vk_startup_errorf(dev->physical_device->instance, VK_ERROR_INITIALIZATION_FAILED,-@@ -735,6 +740,12 @@ msm_bo_init_dmabuf(struct tu_device *dev,+@@ -680,9 +685,15 @@ msm_bo_init_dmabuf(struct tu_device *dev,+ uint64_t size,+ int prime_fd)+ {++#ifdef __APPLE__++ /* the "fd" is an IOSurface's ID (src/hakios-drm): its size is the kernel's answer */++ struct hakios_drm_surface described = { .surface = (uint32_t) prime_fd };++ off_t real_size = hakios_drm_surface(dev->fd, &described) == 0 ? (off_t) described.size : -1;++#else+ /* lseek() to get the real size */+ off_t real_size = lseek(prime_fd, 0, SEEK_END);+ lseek(prime_fd, 0, SEEK_SET);++#endif+ if (real_size < 0 || (uint64_t) real_size < size)+ return vk_error(dev, VK_ERROR_INVALID_EXTERNAL_HANDLE);++@@ -735,6 +746,12 @@ msm_bo_init_dmabuf(struct tu_device *dev,static VkResultmsm_bo_map(struct tu_device *dev, struct tu_bo *bo, void *placed_addr){@@ -205,7 +290,7 @@ index 08831e7..7472ea6 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 +754,7 @@ msm_bo_map(struct tu_device *dev, struct tu_bo *bo, void *placed_addr)+@@ -743,6 +760,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/userland/build.sh b/userland/build.shindex 6788222..c5d86fe 100755--- a/userland/build.sh+++ b/userland/build.sh@@ -293,8 +293,14 @@ if [ -d $DARWIN/rootfs/usr/lib ]; then# this tree's shader choice), over hakios-metal built with its compiler (make ios MESA=1); the window server# also wants QuartzCore's default.metallib (tools/ca-metallib.py, EXTRA_SHARE=, boot-arg ca_metallib=)echo "build.sh: HakiosMetal for CoreAnimation (src/HakiosMetalCA.m)"+ # M2V=1: with UniXNU's Metal on Vulkan inside, the device boot-arg metal_m2v=1 gives the window server+ M2V_OBJS=+ if [ -n "${M2V:-}" ] && [ -f ../xnu-deps/build/m2v/out/frontend.o ]; then+ M2V_OBJS="../xnu-deps/build/m2v/out/frontend.o ../xnu-deps/build/m2v/out/libadreno_metal_bridge.a -framework CoreFoundation -lc++ -Wl,-dead_strip"+ echo "build.sh: with UniXNU's Metal on Vulkan (metal_m2v=1)"+ fi$DYN -bundle -framework Foundation -framework IOKit -framework IOSurface -framework Metal -lobjc \- -I$HM/include -o obj/HakiosMetal src/HakiosMetalCA.m $METAL_GPU+ -I$HM/include -o obj/HakiosMetal src/HakiosMetalCA.m $METAL_GPU $M2V_OBJSelse$DYN -bundle -framework Foundation -framework Metal -lobjc -I$METAL_SRC -o obj/HakiosMetal $METAL_SRC/HakiosMetal.m \$METAL_SRC/hakios_metallib.c $METAL_GPU@@ -540,6 +546,17 @@ for f in extensions.plist extensions.plist.sig; do[ -f $DARWIN/rootfs/System/Library/xpc/$f ] && cp $DARWIN/rootfs/System/Library/xpc/$f root/xpc/done[ -d root/lib/HakiosAudio.driver ] && ln -s /redwood/lib/HakiosAudio.driver root/hal/HakiosAudio.driver+# Programs and libraries of more than 4 MB (Turnip, UniXNU's Metal on Vulkan: TURNIP=1, M2V=1) live in the system+# image, in /usr/local/redwood, with a link in their place here: the small image is loaded with the kernel, in the+# 64 MB the loader takes for both (with them it grew from 6.6 to 26 MB).+rm -rf big+for f in $(cd root && find lib bin -type f -size +4M 2>/dev/null); do+ mkdir -p big/$(dirname $f)+ mv root/$f big/$f+ ln -s /usr/local/redwood/$f root/$f+ echo "build.sh: $f ($(stat -c %s big/$f) bytes) in the system image, /usr/local/redwood/$f"+done+[ -d big ] && SYSTEM=1 # (the links point into it: it is made again with them)# the image: zlib where it saves room (a small file whole in its attribute, as Apple keeps them); fw/# as it is, which the kernel's drivers use where it lies in memory (drivers/storage/hakios.image.c)python3 ../tools/apfs/mkapfs.py -z --plain fw -o root.apfs redwood=root | tail -1@@ -705,6 +722,8 @@ if [ -f $DARWIN/system.manifest ] && [ -f $CACHE/dyld_shared_cache_arm64 ] &&mkdir -p sysroot/System/Library/Audio/Plug-Ins/HALln -s /redwood/lib/HakiosAudio.driver sysroot/System/Library/Audio/Plug-Ins/HAL/HakiosAudio.driver# the plug-in Metal opens when the accelerator names it (boot-arg metal=1; without it nothing names this bundle)+ rm -rf sysroot/usr/local/redwood+ [ -d big ] && mkdir -p sysroot/usr/local && cp -a big sysroot/usr/local/redwoodmkdir -p sysroot/System/Library/Extensions[ -d root/lib/HakiosMetal.bundle ] && ln -sfn /redwood/lib/HakiosMetal.bundle sysroot/System/Library/Extensions/HakiosMetal.bundle# the OS cryptex: on a device a separate volume grafted at /System/Cryptexes/OS. It holds the dylddiff --git a/userland/src/HakiosMetalCA.m b/userland/src/HakiosMetalCA.mindex 5c1fbe7..6480464 100644--- a/userland/src/HakiosMetalCA.m+++ b/userland/src/HakiosMetalCA.m@@ -1958,6 +1958,28 @@ ca_prof_start(void)});}+/* UniXNU's Metal on Vulkan (NativeBridgeMetalFrontend.h), there when the bundle is linked with it (M2V=1) */+extern id native_bridge_metal_open(const char *loader, const char *cache, uint64_t registryID,+ void (*missing)(const char *, const char *)) __attribute__((weak_import));+extern 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));++static void+hm_m2v_missing(const char *class, const char *selector)+{+ hm_print("metal2vulkan: no -[%s %s]\n", class, selector);+}++static bool+hm_boot_arg_set(const char *what)+{+ char args[1024] = "";+ size_t size = sizeof(args) - 1;++ return sysctlbyname("kern.bootargs", args, &size, NULL, 0) == 0 && strstr(args, what) != NULL;+}+- (instancetype)initWithAcceleratorPort:(io_service_t)port{/* (hakios) the window server alone is shown the device: every other client of this image's Metal (SpringBoard@@ -1977,6 +1999,44 @@ ca_prof_start(void)return nil; /* (not released: before -init, _MTLDevice's -dealloc reads what -init never set) */}}+ /* (hakios) metal_m2v=1: the device is UniXNU's Metal on Vulkan instead (AdrenoMetal's frontend over metal2vulkan+ * over Turnip, tools/mk-m2v.sh; linked in by userland/build.sh M2V=1): its own objects, from the device down */+ if (native_bridge_metal_open != NULL && hm_boot_arg_set("metal_m2v=1")) {+ /* boot-arg tu_debug=FLAGS[,FLAGS]: Turnip's TU_DEBUG in the window server (sysmem, gmem, forcebin, ...) */+ {+ char args[1024] = "", value[64] = "";+ size_t size = sizeof(args) - 1;+ const char *at;++ if (sysctlbyname("kern.bootargs", args, &size, NULL, 0) == 0 && (at = strstr(args, "tu_debug=")) != NULL) {+ strlcpy(value, at + 9, sizeof(value));+ value[strcspn(value, " ")] = 0;+ setenv("TU_DEBUG", value, 1);+ hm_print("metal2vulkan: TU_DEBUG=%s\n", value);+ }+ }+ 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));+ /* 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 (;;) {+ char status[600] = "", formats[300] = "";+ sleep(5);+ native_bridge_metal_status(status, sizeof(status));+ native_bridge_metal_formats(formats, sizeof(formats));+ hm_print("metal2vulkan: %s | %s\n", status, formats);+ }+ });+ return [device retain]; /* (self not released: before -init, _MTLDevice's -dealloc reads what -init never set) */+ }+ char problem[256] = "";+ native_bridge_metal_first_problem(problem, sizeof(problem));+ hm_print("no metal2vulkan device (%s): hakios-metal's instead\n", problem);+ }hm_library_stand_ins();ca_prof_start();/* (hakios) the window server's compiled stages kept on disk (hakios-metal: compileStage's cache), so that a