Skip to content

XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)

C

gpu/xnu-cpu-metal: Round 19 clean fixes (2-plane YCbCr wallpaper, combined texture+sampler SPI, 16B alignment)

Heyang Zhou5aef0b442875
diff --git a/gpu/xnu-cpu-metal/REPORT.md b/gpu/xnu-cpu-metal/REPORT.md
index fd79da6..6bf5647 100644
--- a/gpu/xnu-cpu-metal/REPORT.md
+++ b/gpu/xnu-cpu-metal/REPORT.md
@@ -591,3 +591,19 @@ dist/XnuCpuMetal.bundle/
### 验证结果
- **托管 macOS `WindowServer` on Venus**:替换新 bundle 并重启 `WindowServer` 后,`vmmap` 确认仅加载 `libvulkan_virtio.dylib`(无 `libvulkan_lvp.dylib`),帧缓冲 `/var/tmp/xnu-fb.raw` 点亮 **`1,023,982 / 1,024,000`** 像素,完整渲染出 macOS 27 登录界面(金门大桥日落壁纸、`Sun 22 Nov`、`xnu` 头像、`Enter Password` 输入框、右上角 Wi-Fi 图标)。
- **宿主机全套回归**:`lavapipe (arm64e)` 与 `MoltenVK (arm64)` 的 `test_round17_direct_driver`、`test-bundle.sh`、`test-render-ci.sh`、`test_round10`、`test_carenderer`、`test_round13`、`test_round14_vfx` 全部 PASS。
+
+---
+
+## Round 19 (clean): YCbCr 2-plane 壁纸、`setFragmentTexture:samplerState:` SPI 与 16 字节对齐修复
+
+### 修复内容
+1. **2-plane 10-bit YCbCr IOSurface 桌面壁纸(`MTLPixelFormatYCBCR10_420_2P = 505` / `RGB10_420_2P = 543` over `'x420'`)**:
+ - `xnu-m2v-bridge` 新增 `xm2v_pixel_format_is_ycbcr` 与 `xm2v_buffer_new_texture_with_iosurface_ycbcr`(封装 `metal2vulkan-runtime` 的 `Buffer::new_texture_with_iosurface_plane` + `IoSurfaceYCbCr` + `IOSurfaceYCbCrMatrix`)。
+ - `XcmTexture` 支持 YCbCr 2-plane IOSurface 拷贝进 Shared `Xm2vBuffer` 并按 `IOSurfaceGetSeed` 刷新。
+ - `XcmRenderEncoder` 补齐 `CoreAnimation` 采样 YCbCr 纹理所需的合并绑定 SPI:`setFragmentTexture:atTextureIndex:samplerState:atSamplerIndex:`(含 `lodMinClamp:lodMaxClamp:` 及 vertex 变体)。
+2. **线性 / IOSurface 纹理对齐修正(`64 -> 16`,匹配 Apple Silicon)**:
+ - `xcmDev_minLinearAlign`、`xcmDev_minTileAlign` 与 `xcmDev_align16`(用于 `iosurfaceTextureAlignmentBytes` / `linearTextureAlignmentBytes` / `deviceLinearTextureAlignmentBytes` 等)统一由 `64` 改为 **`16`**,解决 `CoreImage` 拒收 16 字节对齐中间 IOSurface 导致 `iconservicesagent` 在 `CIBlurProcessor` → `MPSImageGaussianBlur` 持续 `SIGABRT` 的问题(托管 macOS 实测崩溃数由累计 134 次降至 0 次新增;Dock 剩余 8 个 `NaturalStack` 空白格定位为 Venus 下 `VK_EXT_fragment_shader_interlock` `vkCreateGraphicsPipelines` 返回 `-3`,`newBufferWithBytesNoCopy:` 真零拷贝别名留待 Round 20)。
+
+### 验证结果
+- 新增 `test/test_round19.mm`(3/3 PASS):16 字节对齐查询、`'x420'` `YCBCR10_420_2P (505)` 采样得 `(1.000, 1.000, 1.000, 1.000)`、`CIGaussianBlur` 18 组非 64 字节对齐宽度/半径组合全部 PASS。
+- 宿主机 `lavapipe (arm64e)` 与 `MoltenVK 1.4.2 (arm64)` 全套回归全部 PASS。
diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
index 4a3926c..931690c 100644
--- a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
@@ -289,6 +289,7 @@ static NSData *xcmCodeGenRequest(uint32_t type, const std::vector<uint8_t> &requ
NSUInteger _iosurfacePlane;
uint32_t _iosurfaceSeed;
BOOL _iosurfaceSyncedIn;
+ BOOL _iosurfaceIsYCbCrBacking;
XcmBuffer *_buffer;
NSUInteger _bufferOffset;
NSUInteger _bufferBytesPerRow;
@@ -433,10 +434,18 @@ static bool xcmIOSurfacePlaneLayout(IOSurfaceRef surf, NSUInteger plane, NSUInte
uint32_t seed = IOSurfaceGetSeed(_iosurface);
if (_iosurfaceSyncedIn && seed == _iosurfaceSeed) return;
if (IOSurfaceLock(_iosurface, kIOSurfaceLockReadOnly, nullptr) == kIOReturnSuccess) {
- void *base = nullptr;
- size_t bpr = 0;
- if (xcmIOSurfacePlaneLayout(_iosurface, _iosurfacePlane, _width, _height, _pixelFormat, &base, &bpr)) {
- xm2v_texture_replace_region(_handle, 0, 0, 0, _width, _height, 1, 0, 0, base, bpr, 0);
+ if (_iosurfaceIsYCbCrBacking && _buffer && _buffer->_handle) {
+ void *src = IOSurfaceGetBaseAddress(_iosurface);
+ size_t allocSz = IOSurfaceGetAllocSize(_iosurface);
+ void *dst = xm2v_buffer_contents(_buffer->_handle);
+ size_t copySz = allocSz < (size_t)_buffer->_length ? allocSz : (size_t)_buffer->_length;
+ if (src && dst && copySz > 0) memcpy(dst, src, copySz);
+ } else {
+ void *base = nullptr;
+ size_t bpr = 0;
+ if (xcmIOSurfacePlaneLayout(_iosurface, _iosurfacePlane, _width, _height, _pixelFormat, &base, &bpr)) {
+ xm2v_texture_replace_region(_handle, 0, 0, 0, _width, _height, 1, 0, 0, base, bpr, 0);
+ }
}
IOSurfaceUnlock(_iosurface, kIOSurfaceLockReadOnly, nullptr);
_iosurfaceSeed = seed;
@@ -1638,6 +1647,30 @@ static void xcmSharedEventNotified(void *context, uint64_t value) {
for (NSUInteger i = 0; i < range.length; i++)
[self setFragmentSamplerState:samplers[i] atIndex:range.location + i];
}
+- (void)setFragmentTexture:(id<MTLTexture>)texture atTextureIndex:(NSUInteger)texIdx
+ samplerState:(id<MTLSamplerState>)sampler atSamplerIndex:(NSUInteger)sampIdx {
+ [self setFragmentTexture:texture atIndex:texIdx];
+ [self setFragmentSamplerState:sampler atIndex:sampIdx];
+}
+- (void)setFragmentTexture:(id<MTLTexture>)texture atTextureIndex:(NSUInteger)texIdx
+ samplerState:(id<MTLSamplerState>)sampler lodMinClamp:(float)lodMin lodMaxClamp:(float)lodMax
+ atSamplerIndex:(NSUInteger)sampIdx {
+ (void)lodMin; (void)lodMax;
+ [self setFragmentTexture:texture atIndex:texIdx];
+ [self setFragmentSamplerState:sampler atIndex:sampIdx];
+}
+- (void)setVertexTexture:(id<MTLTexture>)texture atTextureIndex:(NSUInteger)texIdx
+ samplerState:(id<MTLSamplerState>)sampler atSamplerIndex:(NSUInteger)sampIdx {
+ [self setVertexTexture:texture atIndex:texIdx];
+ [self setVertexSamplerState:sampler atIndex:sampIdx];
+}
+- (void)setVertexTexture:(id<MTLTexture>)texture atTextureIndex:(NSUInteger)texIdx
+ samplerState:(id<MTLSamplerState>)sampler lodMinClamp:(float)lodMin lodMaxClamp:(float)lodMax
+ atSamplerIndex:(NSUInteger)sampIdx {
+ (void)lodMin; (void)lodMax;
+ [self setVertexTexture:texture atIndex:texIdx];
+ [self setVertexSamplerState:sampler atIndex:sampIdx];
+}
- (void)setVertexBufferOffset:(NSUInteger)offset atIndex:(NSUInteger)index {
id b = _vbufs[@(index)]; if (b) [self setVertexBuffer:b offset:offset atIndex:index];
}
@@ -2251,9 +2284,9 @@ static NSUInteger xcmDev_maxTex3D(id, SEL) { return 2048; }
static NSUInteger xcmDev_maxTexLayers(id, SEL) { return 2048; }
static NSUInteger xcmDev_maxColorAtt(id, SEL) { return 8; }
static NSUInteger xcmDev_maxTGMem(id, SEL) { return 32768; }
-static NSUInteger xcmDev_minLinearAlign(id, SEL, MTLPixelFormat) { return 64; }
-static NSUInteger xcmDev_minTileAlign(id, SEL, MTLPixelFormat) { return 64; }
-static NSUInteger xcmDev_align64(id, SEL) { return 64; }
+static NSUInteger xcmDev_minLinearAlign(id, SEL, MTLPixelFormat) { return 16; }
+static NSUInteger xcmDev_minTileAlign(id, SEL, MTLPixelFormat) { return 16; }
+static NSUInteger xcmDev_align16(id, SEL) { return 16; }
static NSUInteger xcmDev_rwTexTier(id, SEL) { return MTLReadWriteTextureTier2; }
static BOOL xcmDev_yes(id, SEL) { return YES; }
static BOOL xcmDev_supportsSampleCount(id, SEL, NSUInteger c) { return c == 1; }
@@ -2393,6 +2426,79 @@ static id xcmDev_newTexture(id self, SEL, MTLTextureDescriptor *desc) {
static id xcmDev_newTextureIOSurface(id self, SEL, MTLTextureDescriptor *desc, IOSurfaceRef surface, NSUInteger plane) {
if (xcmTraceOn()) fprintf(stderr, "XCM enter newTextureIOSurface desc=%p surf=%p plane=%lu\n", (__bridge void *)desc, surface, (unsigned long)plane);
if (!gXm2vDevice || !desc) return nil;
+ // Two-plane YCbCr IOSurface formats (YCBCR8_420_2P, YCBCR10_420_2P, etc.) are created over
+ // a shared backing buffer via metal2vulkan-runtime's IoSurfacePlane + IoSurfaceYCbCr path.
+ if (surface && xm2v_pixel_format_is_ycbcr((uint64_t)desc.pixelFormat)) {
+ if (IOSurfaceLock(surface, kIOSurfaceLockReadOnly, nullptr) == kIOReturnSuccess) {
+ void *rootBase = IOSurfaceGetBaseAddress(surface);
+ size_t allocSz = IOSurfaceGetAllocSize(surface);
+ size_t planeCount = IOSurfaceGetPlaneCount(surface);
+ uint32_t surfFmt = IOSurfaceGetPixelFormat(surface);
+ uint64_t surfW = IOSurfaceGetWidth(surface);
+ uint64_t surfH = IOSurfaceGetHeight(surface);
+ bool planar = (planeCount > 1);
+ void *lumaBase = (planeCount > 0 && plane < planeCount) ? IOSurfaceGetBaseAddressOfPlane(surface, plane) : rootBase;
+ uint64_t lumaBpr = (planeCount > 0 && plane < planeCount) ? IOSurfaceGetBytesPerRowOfPlane(surface, plane) : IOSurfaceGetBytesPerRow(surface);
+ uint64_t lumaOff = (rootBase && lumaBase && (uintptr_t)lumaBase >= (uintptr_t)rootBase)
+ ? (uint64_t)((uint8_t *)lumaBase - (uint8_t *)rootBase) : 0;
+ uint64_t chromaOff = 0, chromaBpr = 0;
+ if (planeCount > 1) {
+ void *chromaBase = IOSurfaceGetBaseAddressOfPlane(surface, 1);
+ chromaBpr = IOSurfaceGetBytesPerRowOfPlane(surface, 1);
+ if (rootBase && chromaBase && (uintptr_t)chromaBase >= (uintptr_t)rootBase) {
+ chromaOff = (uint64_t)((uint8_t *)chromaBase - (uint8_t *)rootBase);
+ }
+ }
+ char matBuf[64] = {};
+ CFTypeRef matRef = IOSurfaceCopyValue(surface, CFSTR("IOSurfaceYCbCrMatrix"));
+ if (matRef) {
+ if (CFGetTypeID(matRef) == CFStringGetTypeID()) {
+ CFStringGetCString((CFStringRef)matRef, matBuf, sizeof(matBuf), kCFStringEncodingUTF8);
+ }
+ CFRelease(matRef);
+ }
+ uint32_t seed = IOSurfaceGetSeed(surface);
+ Xm2vBuffer *bh = (rootBase && allocSz > 0)
+ ? xm2v_buffer_new(gXm2vDevice, allocSz, MTLResourceStorageModeShared, rootBase)
+ : nullptr;
+ IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, nullptr);
+ if (bh) {
+ XcmBuffer *backingBuf = [[XcmBuffer alloc] initWithHandle:bh device:self options:MTLResourceStorageModeShared];
+ MTLTextureDescriptor *copy = [desc copy];
+ copy.storageMode = MTLStorageModeShared;
+ Xm2vTextureDesc td;
+ xcmFillTextureDesc(copy, td);
+ Xm2vTexture *t = xm2v_buffer_new_texture_with_iosurface_ycbcr(
+ bh, &td, lumaOff, lumaBpr, planar, surfFmt, plane, surfW, surfH,
+ chromaOff, chromaBpr, matBuf[0] ? matBuf : nullptr);
+ if (t) {
+ XcmTexture *tex = [[XcmTexture alloc] initWithHandle:t device:self descriptor:copy];
+ if (tex) {
+ CFRetain(surface);
+ tex->_buffer = backingBuf;
+ tex->_iosurface = surface;
+ tex->_iosurfacePlane = plane;
+ tex->_iosurfaceSeed = seed;
+ tex->_iosurfaceSyncedIn = YES;
+ tex->_iosurfaceIsYCbCrBacking = YES;
+ }
+ return tex;
+ } else {
+ static int sYcbcrFailLogs = 0;
+ if (sYcbcrFailLogs < 10) {
+ sYcbcrFailLogs++;
+ os_log_error(OS_LOG_DEFAULT,
+ "XnuCpuMetal: newTextureIOSurface YCbCr failed (sid=0x%x surfFmt=0x%x plane=%lu descFmt=%lu %lux%lu luma=(%llu,%llu) chroma=(%llu,%llu) mat=%{public}s): %{public}s",
+ IOSurfaceGetID(surface), surfFmt, (unsigned long)plane,
+ (unsigned long)desc.pixelFormat, (unsigned long)desc.width, (unsigned long)desc.height,
+ (unsigned long long)lumaOff, (unsigned long long)lumaBpr,
+ (unsigned long long)chromaOff, (unsigned long long)chromaBpr,
+ matBuf[0] ? matBuf : "(none)", xm2v_last_error() ?: "?");
+ }
+ }
+ }
+ }
+ }
// Force Shared storage internally so replaceRegion/getBytes sync with IOSurface directly.
MTLTextureDescriptor *copy = [desc copy];
copy.storageMode = MTLStorageModeShared;
@@ -3106,11 +3212,11 @@ static Class createBackendDeviceClass(void) {
{"maxThreadgroupMemoryLength", (IMP)xcmDev_maxTGMem, "Q16@0:8"},
{"minimumLinearTextureAlignmentForPixelFormat:", (IMP)xcmDev_minLinearAlign, "Q24@0:8Q16"},
{"minimumTextureBufferAlignmentForPixelFormat:", (IMP)xcmDev_minTileAlign, "Q24@0:8Q16"},
- {"linearTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
- {"iosurfaceTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
- {"iosurfaceReadOnlyTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
- {"deviceLinearTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
- {"deviceLinearReadOnlyTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
+ {"linearTextureAlignmentBytes", (IMP)xcmDev_align16, "Q16@0:8"},
+ {"iosurfaceTextureAlignmentBytes", (IMP)xcmDev_align16, "Q16@0:8"},
+ {"iosurfaceReadOnlyTextureAlignmentBytes", (IMP)xcmDev_align16, "Q16@0:8"},
+ {"deviceLinearTextureAlignmentBytes", (IMP)xcmDev_align16, "Q16@0:8"},
+ {"deviceLinearReadOnlyTextureAlignmentBytes", (IMP)xcmDev_align16, "Q16@0:8"},
{"readWriteTextureSupport", (IMP)xcmDev_rwTexTier, "Q16@0:8"},
{"argumentBuffersSupport", (IMP)xcmDev_argBufTier, "Q16@0:8"},
{"supportsSharedStorageTextures", (IMP)xcmDev_yes, "B16@0:8"},
diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
index 029a8f0..314aa4a 100644
--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
@@ -172,6 +172,20 @@ uint64_t xm2v_buffer_gpu_address(const Xm2vBuffer *buf);
void xm2v_buffer_did_modify_range(const Xm2vBuffer *buf, uint64_t location, uint64_t length);
Xm2vTexture *xm2v_buffer_new_texture(Xm2vBuffer *buf, const Xm2vTextureDesc *desc, uint64_t offset, uint64_t bytes_per_row);
Xm2vTexture *xm2v_buffer_new_linear_texture(Xm2vBuffer *buf, const Xm2vTextureDesc *desc, uint64_t offset, uint64_t bytes_per_row, uint64_t bytes_per_image);
+bool xm2v_pixel_format_is_ycbcr(uint64_t pixel_format);
+Xm2vTexture *xm2v_buffer_new_texture_with_iosurface_ycbcr(
+ Xm2vBuffer *buf,
+ const Xm2vTextureDesc *desc,
+ uint64_t luma_offset,
+ uint64_t luma_bytes_per_row,
+ bool planar,
+ uint32_t surface_pixel_format,
+ uint64_t surface_plane,
+ uint64_t surface_width,
+ uint64_t surface_height,
+ uint64_t chroma_offset,
+ uint64_t chroma_bytes_per_row,
+ const char *ycbcr_matrix);
/* Textures */
Xm2vTexture *xm2v_texture_new(Xm2vDevice *dev, const Xm2vTextureDesc *desc);
diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
index d1f3d7a..d793b4f 100644
--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
@@ -18,10 +18,11 @@ use metal2vulkan_runtime::{
ArgumentEncoder, BlitCommandEncoder, BlitOption, Buffer, ClearColor, CommandBuffer,
CommandBufferStatus, CommandQueue, ComputeCommandEncoder, ComputePipelineState, Deallocator,
DepthStencilState, Device, DeviceOptions, Event, EventRef, Fence, Function,
- FunctionDescriptor, HostMemory, Library, LoadAction, Origin, PipelineOptions, Region,
- RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions, ResourceRef,
- SamplerState, ScissorRect, ShaderCacheOptions, SharedEvent, SharedEventHandle,
- SharedEventListener, Size, StoreAction, Texture, TextureDescriptor, Viewport,
+ FunctionDescriptor, HostMemory, IoSurfacePlane, IoSurfaceYCbCr, Library, LoadAction, Origin,
+ PipelineOptions, Region, RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState,
+ ResourceOptions, ResourceRef, SamplerState, ScissorRect, ShaderCacheOptions, SharedEvent,
+ SharedEventHandle, SharedEventListener, Size, StoreAction, SurfaceYCbCrMatrix, Texture,
+ TextureDescriptor, Viewport,
};
use std::cell::RefCell;
use std::ffi::{c_char, c_void, CStr};
@@ -525,6 +526,59 @@ pub extern "C" fn xm2v_buffer_new_linear_texture(
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_pixel_format_is_ycbcr(pixel_format: u64) -> bool {
+ guard(false, || {
+ let pf: PixelFormat = raw_enum(pixel_format, "PixelFormat")?;
+ Ok(metal2vulkan::metal::format::ycbcr(pf))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_new_texture_with_iosurface_ycbcr(
+ buf: *mut Buffer,
+ desc: *const Xm2vTextureDesc,
+ luma_offset: u64,
+ luma_bytes_per_row: u64,
+ planar: bool,
+ surface_pixel_format: u32,
+ surface_plane: u64,
+ surface_width: u64,
+ surface_height: u64,
+ chroma_offset: u64,
+ chroma_bytes_per_row: u64,
+ ycbcr_matrix: *const c_char,
+) -> *mut Texture {
+ guard(std::ptr::null_mut(), || {
+ let buf = get(buf)?;
+ let td = build_texture_descriptor(get(desc)?)?;
+ let mut facts = IoSurfaceYCbCr::new(
+ surface_pixel_format,
+ surface_plane,
+ [surface_width, surface_height],
+ chroma_offset,
+ chroma_bytes_per_row,
+ );
+ if !ycbcr_matrix.is_null() {
+ if let Ok(s) = unsafe { CStr::from_ptr(ycbcr_matrix) }.to_str() {
+ if !s.is_empty() {
+ facts = facts.with_matrix(SurfaceYCbCrMatrix::from_attachment(s));
+ }
+ }
+ }
+ let plane = IoSurfacePlane::new(luma_offset, luma_bytes_per_row, planar).with_ycbcr(facts);
+ let tex = buf
+ .new_texture_with_iosurface_plane(&td, plane)
+ .map_err(|e| {
+ format!(
+ "buffer.new_texture_with_iosurface_plane(fmt={:?} ostype=0x{surface_pixel_format:08x} plane={surface_plane} luma=({luma_offset},{luma_bytes_per_row}) chroma=({chroma_offset},{chroma_bytes_per_row})): {e:?}",
+ td.pixel_format
+ )
+ })?;
+ Ok(boxed(tex))
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_buffer_release(buf: *mut Buffer) {
release(buf);
diff --git a/gpu/xnu-cpu-metal/test/test_round19.mm b/gpu/xnu-cpu-metal/test/test_round19.mm
new file mode 100644
index 0000000..9c68a3d
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_round19.mm
@@ -0,0 +1,216 @@
+// Round 19 regression test (non-fallback fixes):
+// 1. MTLDevice linear/IOSurface texture alignment queries return 16 (matching Apple Silicon).
+// 2. 2-plane 10-bit YCbCr IOSurface ('x420') -> MTLPixelFormatYCBCR10_420_2P (505) texture creation + shader sampling.
+// 3. CoreImage CIGaussianBlur across non-64-byte-aligned widths & radii (reproduces iconservicesagent MPSImageGaussianBlur crash when alignment != 16).
+
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <CoreGraphics/CoreGraphics.h>
+#import <CoreImage/CoreImage.h>
+#import <IOSurface/IOSurface.h>
+#import <objc/message.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+
+@interface NSObject (XnuCpuMetalPlugin)
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static id<MTLDevice> loadBundleDevice(const char *bundlePath) {
+ NSBundle *b = [NSBundle bundleWithPath:[NSString stringWithUTF8String:bundlePath]];
+ if (!b || ![b load]) {
+ fprintf(stderr, "FAIL: cannot load bundle %s\n", bundlePath);
+ return nil;
+ }
+ Class cls = [b principalClass];
+ if (!cls) {
+ fprintf(stderr, "FAIL: no principalClass\n");
+ return nil;
+ }
+ id<MTLDevice> dev = [[cls alloc] initWithAcceleratorPort:0];
+ if (!dev) {
+ fprintf(stderr, "FAIL: initWithAcceleratorPort:0 returned nil\n");
+ return nil;
+ }
+ return dev;
+}
+
+static int testAlignmentQueries(id<MTLDevice> dev) {
+ NSUInteger a1 = [dev minimumLinearTextureAlignmentForPixelFormat:MTLPixelFormatBGRA8Unorm];
+ NSUInteger a2 = [dev minimumLinearTextureAlignmentForPixelFormat:MTLPixelFormatRGBA16Float];
+ NSUInteger a3 = [dev minimumTextureBufferAlignmentForPixelFormat:MTLPixelFormatBGRA8Unorm];
+ SEL selIso = NSSelectorFromString(@"iosurfaceTextureAlignmentBytes");
+ SEL selLin = NSSelectorFromString(@"linearTextureAlignmentBytes");
+ NSUInteger isoA = [dev respondsToSelector:selIso]
+ ? ((NSUInteger(*)(id, SEL))objc_msgSend)(dev, selIso) : 0;
+ NSUInteger linA = [dev respondsToSelector:selLin]
+ ? ((NSUInteger(*)(id, SEL))objc_msgSend)(dev, selLin) : 0;
+ printf("[1/3] Alignments: minLinear(BGRA8)=%lu minLinear(RGBA16F)=%lu minTexBuf=%lu iosurface=%lu linear=%lu\n",
+ (unsigned long)a1, (unsigned long)a2, (unsigned long)a3, (unsigned long)isoA, (unsigned long)linA);
+ if (a1 != 16 || a2 != 16 || a3 != 16 || isoA != 16 || linA != 16) {
+ fprintf(stderr, "FAIL [1/3]: expected 16-byte alignment (Apple Silicon), got %lu/%lu/%lu/%lu/%lu\n",
+ (unsigned long)a1, (unsigned long)a2, (unsigned long)a3, (unsigned long)isoA, (unsigned long)linA);
+ return 1;
+ }
+ printf("PASS [1/3]: all linear/IOSurface texture alignments == 16\n");
+ return 0;
+}
+
+static int testYCbCrIOSurface(id<MTLDevice> dev) {
+ const int W = 64, H = 64;
+ NSDictionary *plane0 = @{
+ (id)kIOSurfacePlaneWidth: @(W),
+ (id)kIOSurfacePlaneHeight: @(H),
+ (id)kIOSurfacePlaneBytesPerElement: @(2),
+ (id)kIOSurfacePlaneBytesPerRow: @(W * 2),
+ (id)kIOSurfacePlaneSize: @(W * 2 * H),
+ (id)kIOSurfacePlaneOffset: @(0),
+ };
+ NSDictionary *plane1 = @{
+ (id)kIOSurfacePlaneWidth: @(W / 2),
+ (id)kIOSurfacePlaneHeight: @(H / 2),
+ (id)kIOSurfacePlaneBytesPerElement: @(4),
+ (id)kIOSurfacePlaneBytesPerRow: @((W / 2) * 4),
+ (id)kIOSurfacePlaneSize: @((W / 2) * 4 * (H / 2)),
+ (id)kIOSurfacePlaneOffset: @(W * 2 * H),
+ };
+ NSDictionary *props = @{
+ (id)kIOSurfaceWidth: @(W),
+ (id)kIOSurfaceHeight: @(H),
+ (id)kIOSurfacePixelFormat: @((uint32_t)'x420'),
+ (id)kIOSurfaceAllocSize: @(W * 2 * H + (W / 2) * 4 * (H / 2)),
+ (id)kIOSurfacePlaneInfo: @[plane0, plane1],
+ };
+ IOSurfaceRef surf = IOSurfaceCreate((__bridge CFDictionaryRef)props);
+ if (!surf) {
+ fprintf(stderr, "FAIL [2/3]: IOSurfaceCreate('x420') returned NULL\n");
+ return 1;
+ }
+ IOSurfaceSetValue(surf, CFSTR("IOSurfaceYCbCrMatrix"), CFSTR("ITU_R_709_2"));
+
+ IOSurfaceLock(surf, 0, NULL);
+ uint16_t *yPlane = (uint16_t *)IOSurfaceGetBaseAddressOfPlane(surf, 0);
+ size_t yBpr = IOSurfaceGetBytesPerRowOfPlane(surf, 0) / 2;
+ for (int y = 0; y < H; y++)
+ for (int x = 0; x < W; x++)
+ yPlane[y * yBpr + x] = (uint16_t)(940 << 6); // 10-bit video-range white Y
+ uint16_t *uvPlane = (uint16_t *)IOSurfaceGetBaseAddressOfPlane(surf, 1);
+ size_t uvBpr = IOSurfaceGetBytesPerRowOfPlane(surf, 1) / 2;
+ for (int y = 0; y < H / 2; y++)
+ for (int x = 0; x < W / 2; x++) {
+ uvPlane[y * uvBpr + x * 2 + 0] = (uint16_t)(512 << 6); // neutral Cb
+ uvPlane[y * uvBpr + x * 2 + 1] = (uint16_t)(512 << 6); // neutral Cr
+ }
+ IOSurfaceUnlock(surf, 0, NULL);
+
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:(MTLPixelFormat)505
+ width:W
+ height:H
+ mipmapped:NO];
+ td.usage = MTLTextureUsageShaderRead;
+ id<MTLTexture> tex = [dev newTextureWithDescriptor:td iosurface:surf plane:0];
+ if (!tex) {
+ fprintf(stderr, "FAIL [2/3]: newTextureWithDescriptor:505 iosurface:'x420' returned nil\n");
+ CFRelease(surf);
+ return 1;
+ }
+
+ NSString *src = @"#include <metal_stdlib>\n"
+ "using namespace metal;\n"
+ "kernel void sample_ycbcr(texture2d<float, access::sample> t [[texture(0)]],\n"
+ " device float4 *out [[buffer(0)]],\n"
+ " uint gid [[thread_position_in_grid]]) {\n"
+ " constexpr sampler s(filter::linear);\n"
+ " if (gid == 0) out[0] = t.sample(s, float2(0.5, 0.5));\n"
+ "}\n";
+ NSError *err = nil;
+ id<MTLLibrary> lib = [dev newLibraryWithSource:src options:nil error:&err];
+ id<MTLFunction> fn = [lib newFunctionWithName:@"sample_ycbcr"];
+ id<MTLComputePipelineState> pso = [dev newComputePipelineStateWithFunction:fn error:&err];
+ if (!pso) {
+ fprintf(stderr, "FAIL [2/3]: compute PSO failed: %s\n", err.localizedDescription.UTF8String);
+ CFRelease(surf);
+ return 1;
+ }
+
+ id<MTLBuffer> outBuf = [dev newBufferWithLength:sizeof(float) * 4 options:MTLResourceStorageModeShared];
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
+ [enc setComputePipelineState:pso];
+ [enc setTexture:tex atIndex:0];
+ [enc setBuffer:outBuf offset:0 atIndex:0];
+ [enc dispatchThreads:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
+ [enc endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+
+ float *rgba = (float *)outBuf.contents;
+ printf("[2/3] Sampled YCBCR10_420_2P (505) white -> rgba=(%.3f, %.3f, %.3f, %.3f)\n",
+ rgba[0], rgba[1], rgba[2], rgba[3]);
+ CFRelease(surf);
+ if (fabsf(rgba[0] - 1.0f) > 0.03f || fabsf(rgba[1] - 1.0f) > 0.03f ||
+ fabsf(rgba[2] - 1.0f) > 0.03f || fabsf(rgba[3] - 1.0f) > 0.03f) {
+ fprintf(stderr, "FAIL [2/3]: expected ~(1, 1, 1, 1)\n");
+ return 1;
+ }
+ printf("PASS [2/3]: 2-plane YCBCR10_420_2P IOSurface sampled accurately\n");
+ return 0;
+}
+
+static int testCIGaussianBlurNon64Aligned(id<MTLDevice> dev) {
+ CIContext *ctx = [CIContext contextWithMTLDevice:dev];
+ const int widths[] = {124, 126, 128, 130, 136, 140};
+ const float radii[] = {6.0f, 10.0f, 15.0f};
+ int cases = 0;
+ for (int w : widths) {
+ for (float r : radii) {
+ CIImage *base = [[CIImage imageWithColor:[CIColor colorWithRed:0.8 green:0.4 blue:0.15 alpha:1.0]]
+ imageByCroppingToRect:CGRectMake(20, 20, w - 40, w - 40)];
+ CIFilter *blur = [CIFilter filterWithName:@"CIGaussianBlur"];
+ [blur setValue:base forKey:kCIInputImageKey];
+ [blur setValue:@(r) forKey:kCIInputRadiusKey];
+ CIImage *out = [blur.outputImage imageByCroppingToRect:CGRectMake(0, 0, w, w)];
+ uint8_t *buf = (uint8_t *)calloc((size_t)w * (size_t)w * 4, 1);
+ [ctx render:out
+ toBitmap:buf
+ rowBytes:(size_t)w * 4
+ bounds:CGRectMake(0, 0, w, w)
+ format:kCIFormatRGBA8
+ colorSpace:CGColorSpaceCreateDeviceRGB()];
+ int cx = w / 2, cy = w / 2;
+ uint8_t *p = buf + ((size_t)cy * (size_t)w + (size_t)cx) * 4;
+ bool ok = (p[0] > 50 && p[3] > 50);
+ free(buf);
+ if (!ok) {
+ fprintf(stderr, "FAIL [3/3]: CIGaussianBlur w=%d r=%.0f center=(%u,%u,%u,%u)\n",
+ w, r, p[0], p[1], p[2], p[3]);
+ return 1;
+ }
+ cases++;
+ }
+ }
+ printf("PASS [3/3]: CoreImage CIGaussianBlur passed all %d non-64-aligned width/radius combinations\n", cases);
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ @autoreleasepool {
+ const char *bundlePath = (argc > 1) ? argv[1] : getenv("XNU_CPU_METAL_BUNDLE");
+ if (!bundlePath) {
+ fprintf(stderr, "Usage: %s <path/to/XnuCpuMetal.bundle>\n", argv[0]);
+ return 2;
+ }
+ id<MTLDevice> dev = loadBundleDevice(bundlePath);
+ if (!dev) return 1;
+ printf("Device: %s\n", dev.name.UTF8String);
+ int rc = 0;
+ rc |= testAlignmentQueries(dev);
+ rc |= testYCbCrIOSurface(dev);
+ rc |= testCIGaussianBlurNon64Aligned(dev);
+ if (rc == 0) printf("ALL ROUND 19 TESTS PASSED!\n");
+ return rc;
+ }
+}