XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
gpu/xnu-cpu-metal: add upstream patches (metal2vulkan, mesa) and apply them in fetch-sources.sh
Heyang Zhoub5618ddd8de0
diff --git a/gpu/xnu-cpu-metal/patches/mesa/0001-arm64e-gallivm-jit-pac.patch b/gpu/xnu-cpu-metal/patches/mesa/0001-arm64e-gallivm-jit-pac.patchnew file mode 100644index 0000000..1fa01b7--- /dev/null+++ b/gpu/xnu-cpu-metal/patches/mesa/0001-arm64e-gallivm-jit-pac.patch@@ -0,0 +1,130 @@+Upstream: Mesa 26.3.1 (https://archive.mesa3d.org/mesa-26.3.1.tar.xz)+Upstream-License: MIT+Patch-License: MIT (provided under the same license as upstream)+Subject: arm64e macOS PAC compatibility for gallivm JIT function pointers++--- a/src/gallium/auxiliary/gallivm/lp_bld_const.c++++ b/src/gallium/auxiliary/gallivm/lp_bld_const.c+@@ -475,6 +475,9 @@+ LLVMTypeRef function_type,+ const char *name)+ {++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ ptr = __builtin_ptrauth_strip((void *)ptr, 0);++#endif+ return LLVMBuildBitCast(gallivm->builder,+ lp_build_const_int_pointer(gallivm, ptr),+ LLVMPointerType(function_type, 0),+--- a/src/gallium/auxiliary/gallivm/lp_bld_conv.c++++ b/src/gallium/auxiliary/gallivm/lp_bld_conv.c+@@ -217,7 +217,11 @@+ unsigned i;++ LLVMTypeRef func_type = LLVMFunctionType(i16t, &f32t, 1, 0);+- LLVMValueRef func = lp_build_const_int_pointer(gallivm, func_to_pointer((func_pointer)_mesa_float_to_half));++ void *f2h_ptr = func_to_pointer((func_pointer)_mesa_float_to_half);++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ f2h_ptr = __builtin_ptrauth_strip(f2h_ptr, 0);++#endif++ LLVMValueRef func = lp_build_const_int_pointer(gallivm, f2h_ptr);+ func = LLVMBuildBitCast(builder, func, LLVMPointerType(func_type, 0), "_mesa_float_to_half");++ for (i = 0; i < length; ++i) {+--- a/src/gallium/auxiliary/gallivm/lp_bld_format_aos.c++++ b/src/gallium/auxiliary/gallivm/lp_bld_format_aos.c+@@ -847,8 +847,11 @@+ if (gallivm->cache)+ gallivm->cache->dont_cache = true;+ /* make const pointer for the C fetch_rgba_8unorm function */+- function = lp_build_const_int_pointer(gallivm,+- func_to_pointer((func_pointer) unpack->fetch_rgba_8unorm));++ void *fetch_ptr = func_to_pointer((func_pointer) unpack->fetch_rgba_8unorm);++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ fetch_ptr = __builtin_ptrauth_strip(fetch_ptr, 0);++#endif++ function = lp_build_const_int_pointer(gallivm, fetch_ptr);+ /* cast the callee pointer to the function's type */+ function = LLVMBuildBitCast(builder, function, LLVMPointerType(function_type, 0), "cast callee");++--- a/src/gallium/auxiliary/gallivm/lp_bld_init.c++++ b/src/gallium/auxiliary/gallivm/lp_bld_init.c+@@ -388,6 +388,9 @@+ void+ gallivm_add_global_mapping(struct gallivm_state *gallivm, LLVMValueRef sym, void* addr)+ {++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ addr = __builtin_ptrauth_strip(addr, 0);++#endif+ LLVMAddGlobalMapping(gallivm->engine, sym, addr);+ }++@@ -522,6 +525,10 @@++ code = LLVMGetPointerToGlobal(gallivm->engine, func);+ assert(code);++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ code = __builtin_ptrauth_sign_unauthenticated(++ __builtin_ptrauth_strip(code, 0), 0, 0);++#endif+ jit_func = pointer_to_func(code);++ if (gallivm_debug & GALLIVM_DEBUG_PERF) {+--- a/src/gallium/auxiliary/gallivm/lp_bld_init_orc.cpp++++ b/src/gallium/auxiliary/gallivm/lp_bld_init_orc.cpp+@@ -682,6 +682,9 @@+ void+ gallivm_add_global_mapping(struct gallivm_state *gallivm, LLVMValueRef sym, void* addr)+ {++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ addr = __builtin_ptrauth_strip(addr, 0);++#endif+ LPJit::add_mapping_to_jd(sym, addr, gallivm->_per_module_jd);+ }++@@ -742,8 +745,14 @@+ objcache = (LPObjectCacheORC *)gallivm->cache->jit_obj_cache;+ }++- return pointer_to_func(+- LPJit::lookup_in_jd(func_name, gallivm->_per_module_jd, objcache));++ void *code = LPJit::lookup_in_jd(func_name, gallivm->_per_module_jd, objcache);++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ if (code) {++ code = __builtin_ptrauth_sign_unauthenticated(++ __builtin_ptrauth_strip(code, 0), 0, 0);++ }++#endif++ return pointer_to_func(code);+ }++ void+--- a/src/gallium/drivers/llvmpipe/lp_texture_handle.c++++ b/src/gallium/drivers/llvmpipe/lp_texture_handle.c+@@ -294,9 +294,16 @@++ matrix->screen = screen;+++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ /* Loaded and invoked by LLVM JIT trampolines via plain blr. */++ matrix->compile_sample_function = __builtin_ptrauth_strip((void *)get_sample_function, 0);++ matrix->compile_fetch_function = __builtin_ptrauth_strip((void *)get_fetch_function, 0);++ matrix->compile_size_function = __builtin_ptrauth_strip((void *)get_size_function, 0);++#else+ matrix->compile_sample_function = get_sample_function;+ matrix->compile_fetch_function = get_fetch_function;+ matrix->compile_size_function = get_size_function;++#endif++ lp_function_cache_init(&matrix->caches[LP_FUNCTION_CACHE_SAMPLE], sample_function_cache_key_table_create(NULL));+ lp_function_cache_init(&matrix->caches[LP_FUNCTION_CACHE_FETCH], sample_function_cache_key_table_create(NULL));+@@ -384,6 +391,10 @@+ gallivm_compile_module(gallivm);++ void *function_ptr = func_to_pointer(gallivm_jit_function(gallivm, function, func_name));++#if defined(__has_feature) && __has_feature(ptrauth_calls)++ /* Texture/image sample helper tables are invoked by LLVM JIT via plain blr. */++ function_ptr = __builtin_ptrauth_strip(function_ptr, 0);++#endif++ if (needs_caching)+ lp_disk_cache_insert_shader(matrix->screen, gallivm->cache, cache_key);diff --git a/gpu/xnu-cpu-metal/patches/metal2vulkan/0001-relax-cpu-device-watchdog-timeout.patch b/gpu/xnu-cpu-metal/patches/metal2vulkan/0001-relax-cpu-device-watchdog-timeout.patchnew file mode 100644index 0000000..1ff31a8--- /dev/null+++ b/gpu/xnu-cpu-metal/patches/metal2vulkan/0001-relax-cpu-device-watchdog-timeout.patch@@ -0,0 +1,59 @@+Upstream: steelbrain/metal2vulkan (d9236a8a11d3b90a1aa27b54e2d74d3891c4d2e5)+Upstream-License: GPL-2.0-or-later OR LGPL-3.0-or-later+Patch-License: GPL-2.0-or-later OR LGPL-3.0-or-later (provided under the same license as upstream)+Subject: Relax watchdog and stall timeouts for CPU software rasterizer devices (DeviceKind::Cpu)++diff --git a/crates/metal2vulkan-runtime/src/command_buffer/stall.rs b/crates/metal2vulkan-runtime/src/command_buffer/stall.rs+index 2410046..671722f 100644+--- a/crates/metal2vulkan-runtime/src/command_buffer/stall.rs++++ b/crates/metal2vulkan-runtime/src/command_buffer/stall.rs+@@ -170,24 +170,45 @@ pub(super) enum Verdict {+ }++ /// How long the clock runs before a probe on `device`: [`STALL`], or what a device test set+-/// (`device/line.rs`'s hooks).++/// (`device/line.rs`'s hooks). CPU software rasterizers (e.g. lavapipe) can legitimately take++/// tens of seconds on heavy frames, so relax their stall bound to 1 hour unless overridden.+ pub(super) fn stall_after(device: &Device) -> Duration {+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]+ if let Some(after) = *crate::device::lock(&device.line().hooks.stall_after) {+ return after;+ }+- let _ = device;++ if device.properties().kind == crate::DeviceKind::Cpu {++ if let Some(ms) = std::env::var("XNU_CPU_METAL_WATCHDOG_MS")++ .ok()++ .and_then(|s| s.parse::<u64>().ok())++ .filter(|&v| v > 0)++ {++ return Duration::from_millis(ms);++ }++ return Duration::from_secs(3600);++ }+ STALL+ }++ /// How long a queue's front may go without its timeline advancing on `device`: [`WATCHDOG`], or+-/// what a device test set (`device/line.rs`'s hooks).++/// what a device test set (`device/line.rs`'s hooks). CPU software rasterizers (e.g. lavapipe)++/// must not be declared `GpuHang` / `AccessRevoked` simply because software rasterization + JIT++/// is slow under heavy load.+ pub(super) fn watchdog_after(device: &Device) -> Duration {+ #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]+ if let Some(after) = *crate::device::lock(&device.line().hooks.watchdog_after) {+ return after;+ }+- let _ = device;++ if device.properties().kind == crate::DeviceKind::Cpu {++ if let Some(ms) = std::env::var("XNU_CPU_METAL_WATCHDOG_MS")++ .ok()++ .and_then(|s| s.parse::<u64>().ok())++ .filter(|&v| v > 0)++ {++ return Duration::from_millis(ms);++ }++ return Duration::from_secs(3600);++ }+ WATCHDOG+ }+diff --git a/gpu/xnu-cpu-metal/patches/metal2vulkan/0002-skip-host-deallocator-on-parked-device.patch b/gpu/xnu-cpu-metal/patches/metal2vulkan/0002-skip-host-deallocator-on-parked-device.patchnew file mode 100644index 0000000..bade054--- /dev/null+++ b/gpu/xnu-cpu-metal/patches/metal2vulkan/0002-skip-host-deallocator-on-parked-device.patch@@ -0,0 +1,38 @@+Upstream: steelbrain/metal2vulkan (d9236a8a11d3b90a1aa27b54e2d74d3891c4d2e5)+Upstream-License: GPL-2.0-or-later OR LGPL-3.0-or-later+Patch-License: GPL-2.0-or-later OR LGPL-3.0-or-later (provided under the same license as upstream)+Subject: Skip host memory deallocators and keep-alive drops when VkDevice is parked++diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs+index 4292631..4b235c7 100644+--- a/crates/metal2vulkan-runtime/src/buffer.rs++++ b/crates/metal2vulkan-runtime/src/buffer.rs+@@ -2122,6 +2122,15 @@ impl Drop for Imported {+ Some(AfterImport { after, delayed, .. }) => (Some(after), delayed),+ None => (None, None),+ };++ // If the VkDevice was parked (e.g. watchdog/device-lost), vkFreeMemory will be skipped++ // because the driver may still be reading these imported host pages; never run caller++ // deallocators or drop keep-alives that could unmap the pages out from under the driver.++ if crate::release::parked(self.device.shared().vk().handle()) {++ if let Some(after) = after {++ std::mem::forget(after);++ }++ return;++ }+ // SAFETY: no pending command buffer uses them: an import's own go as the import goes+ // (`HostImport::drop`), a releasable import's as the last command buffer whose blit read+ // them completed, and no other read reached them (`host_residency.rs`).+@@ -2230,6 +2239,12 @@ impl Drop for HostPages {+ };+ drop(busy);+ let import = &self.import;++ // If the VkDevice is parked, its driver may still be reading these host pages; keep them++ // mapped instead of invoking the caller's deallocator (which would munmap under the driver).++ if crate::release::parked(import.device.shared().vk().handle()) {++ release.keep();++ return;++ }+ match release.keep_alive() {+ // The caller's keep-alive keeps the pages mapped until the import is freed: the+ // deallocator runs now, at Metal's moment. Where another buffer lies in the import,diff --git a/gpu/xnu-cpu-metal/scripts/fetch-sources.sh b/gpu/xnu-cpu-metal/scripts/fetch-sources.shindex 6614ac0..eef9aa1 100755--- a/gpu/xnu-cpu-metal/scripts/fetch-sources.sh+++ b/gpu/xnu-cpu-metal/scripts/fetch-sources.sh@@ -1,16 +1,42 @@#!/usr/bin/env bash-# Fetch the upstream sources the plugin builds against into src/ (never committed: see ../README.md).+# Fetch the upstream sources the plugin builds against into src/ (never committed: see ../README.md),+# then apply our local patches from patches/<project>/*.patch idempotently.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT/src"+git_at() { # git_at DIR URL REV[ -d "$1/.git" ] || git clone -q "$2" "$1"+ git -C "$1" checkout -q -- . 2>/dev/null || truegit -C "$1" fetch -q --depth 1 origin "$3" 2>/dev/null || git -C "$1" fetch -q origingit -C "$1" checkout -q "$3"}++apply_patches() { # apply_patches DIR PATCH_SUBDIR+ local dir="$1" pdir="$ROOT/patches/$2"+ [ -d "$pdir" ] || return 0+ shopt -s nullglob+ local patches=("$pdir"/*.patch)+ shopt -u nullglob+ [ ${#patches[@]} -gt 0 ] || return 0+ for p in "${patches[@]}"; do+ if patch -d "$dir" -p1 --dry-run -R -s -f < "$p" >/dev/null 2>&1; then+ echo "patch already applied: $(basename "$p") -> $2"+ else+ echo "applying patch: $(basename "$p") -> $2"+ patch -d "$dir" -p1 -s -f < "$p"+ fi+ done+}+git_at metal2vulkan https://github.com/steelbrain/metal2vulkan.git d9236a8a11d3b90a1aa27b54e2d74d3891c4d2e5 # v0.2.0, GPL-2.0-or-later / LGPL-3.0-or-latergit_at Vulkan-Loader https://github.com/KhronosGroup/Vulkan-Loader.git fa218055ff4948b159f31d43f800c808a13d51df # vulkan-sdk-1.4.363.0, Apache-2.0git_at llvm-project https://github.com/llvm/llvm-project.git ca7933e47d3a3451d81e72ac174dcb5aa28b59d1 # llvmorg-22.1.8 (arm64e llvmpipe JIT)mkdir -p "$ROOT/build"[ -f "$ROOT/build/mesa-26.3.1.tar.xz" ] || curl -sSLo "$ROOT/build/mesa-26.3.1.tar.xz" https://archive.mesa3d.org/mesa-26.3.1.tar.xz[ -d mesa ] || { mkdir mesa && tar -C mesa --strip-components=1 -xf "$ROOT/build/mesa-26.3.1.tar.xz"; } # MIT (lavapipe)++apply_patches metal2vulkan metal2vulkan+apply_patches Vulkan-Loader Vulkan-Loader+apply_patches mesa mesa+echo "sources ready in $ROOT/src"