Skip to content

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

C

gpu/xnu-cpu-metal: Rounds 8-14 WindowServer/Safari/Chrome/VFX fixes, tests, and REPORT

Heyang Zhoue9e27e6c8a29
diff --git a/gpu/xnu-cpu-metal/REPORT.md b/gpu/xnu-cpu-metal/REPORT.md
index 2c78c5a..93eba6f 100644
--- a/gpu/xnu-cpu-metal/REPORT.md
+++ b/gpu/xnu-cpu-metal/REPORT.md
@@ -323,8 +323,171 @@ dist/XnuCpuMetal.bundle/
- **不改 `metal2vulkan-runtime` 64 MiB 内存 slab(`BLOCK_BYTES`)**:`metal2vulkan` 属 GPL/LGPL 上游(构建时拉取、不入库);我们在自研桥接层收紧了 `ShaderCacheOptions` 内存/磁盘上限。
- **不做 commit 去阻塞 / 无管线 draw 跳过**:插件此前已异步 `commit` 且已跳过 `!_hasPipeline` 的 draw。
-### 托管 macOS 内实测(xnulinux 托管 XNU,1 CPU,`tools/hosted/tests/gpu7.sh`)
-- `ictool Stats.icon --scale 2`,同一图标、输出 md5 全部一致(`da2d8998…`):
- - 旧 bundle(Round 6):21.81s / 20.23s,峰值 RSS 1.11–1.15 GB
- - 新 bundle(Round 7):首次 19.53s(填缓存)→ 8.48s → **4.97s**,峰值 RSS 1.09–1.14 GB
-- 托管系统里峰值内存基本不变(宿主机上报的 RSS 下降没有复现);耗时随 Mesa 磁盘缓存命中逐次下降。
+---
+
+## Round 8: WindowServer / SkyLight Metal 设备筛选分析与合成器适配
+
+### SkyLight 静态反汇编证据(macOS 27.0.1 dyld cache `SkyLight.framework`)
+1. **`__WSSystemCanCompositeWithMetal_block_invoke` (`SkyLight @ 0x19365f508`)**:
+ - `+0x088`: `BL MTLCopyAllDevicesWithObserver(&observer, handler)`(observer block 在 `+0x1e0` 检查 `MTLDeviceWasAddedNotification`)。
+ - `+0x090`: `BL objc_msgSend("count")`;`+0x094`: `cbz x0, +0x0a4`。
+ - **此处本身没有任何设备属性过滤**——只要 `[devices count] == 0`,就记录 `"Metal device initially absent."`(`+0x0c8`),在 `dispatch_semaphore_wait` 上等 30 秒,超时后记录 `"No suitable Metal devices present after %llu seconds."`(`+0x168`)并 `abort()`。
+ - **托管系统 WindowServer 触发该错误的直接根因**:commit `04d3386` 的插件在 `confstr(_CS_DARWIN_USER_CACHE_DIR)` 失败时回退到共享路径 `/tmp/xnu-cpu-metal-m2v`;先前以 `root` (uid=0) 运行时 `metal2vulkan` `ShaderCache` 以 `0700` 创建了该目录,随后 `WindowServer` 以 `_windowserver` (uid=88) 启动时 `ShaderCache::open` 报 `PermissionDenied` → `xm2v_device_open` 返回 `NULL` → `initWithAcceleratorPort:` 返回 `nil` → `MTLCopyAllDevicesWithObserver` 返回空数组 (`count == 0`)。
+2. **通过 `WSSystemCanCompositeWithMetal` 后 SkyLight 紧接着检查的接口**:
+ - `__WSGetDefaultMetalAccelerator_block_invoke` (`0x19366a14c`):`MTLCopyAllDevices` → `firstObject` → `acceleratorPort`(必须非 0)。
+ - `CompositorMetal::new_compositor` (`0x193663944`):`acceleratorPort`、`isRemovable` (`NO`)、`supportPriorityBand` (`NO`)、`MPSSupportsMTLDevice` (`YES`)、`registryID`、`compilerPropagatesThreadPriority:`、队列 `setCompletionQueue:` / `setSubmissionQueue:` / `setGPUPriority:`。
+ - `SLSCreateDefaultMetalDevice` (`0x19387fc08`):`acceleratorPort`、`isLowPower`。
+
+### 插件修改(`XnuCpuMetalPlugin.mm`、`XnuCpuMetalShim.h`)
+1. **Per-UID 真实可写探测的缓存目录回退**:按 `XNU_CPU_METAL_CACHE_DIR` → `_CS_DARWIN_USER_CACHE_DIR` → `_CS_DARWIN_USER_TEMP_DIR` → `NSTemporaryDirectory()` → `/var/tmp/xnu-cpu-metal-<uid>` → `/tmp/xnu-cpu-metal-<uid>` 逐级用实际 `open(O_CREAT|O_WRONLY)` 探测可写性,杜绝 uid=0 与 uid=88 (`_windowserver`) 互锁;打开失败时同步写入 `os_log_error`。
+2. **对齐 DroidVM WindowServer 设备属性与 IOSurface 策略**:
+ - `isHeadless = NO`、`isLowPower = NO`(原为 `YES`/`YES`),保持 `isRemovable = NO`、`hasUnifiedMemory = YES`、`isBuiltIn = YES`。
+ - 启动时设置 `CFPreferencesSetAppValue(CFSTR("CAEnableIOSurfaceCompression"), kCFBooleanFalse, kCFPreferencesCurrentApplication)`,确保 QuartzCore/WindowServer 分配线性未压缩 IOSurface。
+3. **补齐 WindowServer 合成器接口**:
+ - `XnuCpuMetalShim.h` 新增设备 `compilerPropagatesThreadPriority:` 与队列 `setCompletionQueue:` / `setSubmissionQueue:`(消除 `CompositorMetal::new_compositor` 的 stub 警告)。
+ - `XcmTexture` 多平面 IOSurface 同步增加 `plane < planeCount` 越界保护,并将 `_iosurface` / `_iosurfacePlane` 传递到 `newTextureViewWithPixelFormat:` 视图纹理(支持对 IOSurface 的 sRGB/格式视图渲染回写)。
+
+### 宿主机验证结果(通用 `arm64 + arm64e` `XnuCpuMetal.bundle`)
+- `test_ws_full`:`isHeadless=0, isLowPower=0, isRemovable=0, hasUnified=1, MPSSupportsMTLDevice=1`;2-plane YCbCr `420v` IOSurface (`R8Unorm` + `RG8Unorm`) 读写 PASS;`MPSImageGaussianBlur` + `setCompletionQueue:`/`setSubmissionQueue:` PASS(`status=4, center=(229,229,229,229)`)。
+- 全量回归全部 PASS:`test-bundle.sh arm64/arm64e` (`bad=0, completedHandler=1`)、`test-render-ci.sh arm64/arm64e` (`CIGaussianBlur maxErr=1, meanErr=0.0161`)、`ictool Stats.icon` (`maxErr=51`)、`MenuBarIcon.icon` scale 1 & 2 (`maxErr=42/38`)、`mbui_offscreen` (`maxErr=2`)、`gpui_offscreen` (`maxErr=1`),全部零 `stubbed`。
+
+---
+
+## Round 9: Vulkan-Loader secure-mode ICD 自包含加载 + `&BGA`/`&RhA`/`&b3a` 压缩 IOSurface 线性处理
+
+### 修改内容
+1. **彻底消除 `VK_ICD_FILENAMES` 环境变量依赖与构建目录 `sysconfdir` 硬编码**:
+ - `scripts/build-vkloader-arm64e.sh` 改为同时构建 `arm64` 与 `arm64e` 两个 slice,并传入 `-DSYSCONFDIR=/Library/GPUBundles/XnuCpuMetal.bundle/Contents/Resources`。
+ - `scripts/build-bundle-universal.sh` 将双架构 `libvulkan.1.dylib` 合并进 bundle,并在 bundle 内放入 `Contents/Resources/vulkan/icd.d/lvp_icd.aarch64.json`(`library_path: "../../../Frameworks/libvulkan_lvp.dylib"`)。在 `WindowServer` 等高权限/secure 模式下,Vulkan-Loader 自动搜索 `<SYSCONFDIR>/vulkan/icd.d` 并加载 bundle 内的 lavapipe,无需环境变量也无需在 `/usr/local/share/vulkan/icd.d` 写外部清单。
+ - `strings` 验证 `libvulkan.1.dylib` 中零 `/Users/admin` 硬编码路径,仅含 `/Library/GPUBundles/XnuCpuMetal.bundle/Contents/Resources`。
+2. **`&BGA` / `&RhA` / `&b3a` / `b3a8` 压缩 IOSurface 格式的线性处理**(`XnuCpuMetalPlugin.mm`):
+ - 新增 `xcmPixelFormatBpp`(含 `BGRA10_XR` 8 Bpp)与 `xcmIOSurfacePlaneLayout`,在 `syncFromIOSurfaceIfNeeded` / `syncToIOSurface` 中统一将 `&` 开头的无损压缩 IOSurface 按线性未压缩行读取/回写;针对 `b3a8`/`&b3a` 双平面 `IOSurfaceGetBytesPerRowOfPlane == 0` 情形按 64B 对齐自动计算双平面偏移与 stride(并做 `allocSize` 越界保护)。
+ - `XcmTexture` 的 `replaceRegion:` 与 `getBytes:` 同步补齐 IOSurface 双向同步。
+
+### 验证结果
+- 端到端 `&BGA` (1280×720, `bpr=5120`)、`&RhA` (`RGBA16Float`)、`&b3a` (`BGR10_XR`) 渲染 + 采样 + Blit + IOSurface 线性回读测试 (`test_compressed_full`):**全部 PASS**(线性 BGRA 精确匹配 `(204,153,51,255)`)。
+- 全量 `arm64` + `arm64e` 回归(`test-bundle.sh`、`test-render-ci.sh`):**全部 PASS**(`vecadd bad=0, completedHandler=1`;Render Pass PASS;CoreImage `CIGaussianBlur maxErr=1, meanErr=0.0161`)。
+
+---
+
+## Round 10: Buffer-Backed Linear Textures + `MTLSharedEvent`/`MTLFence` + 内存态 `CAEnableIOSurfaceCompression`
+
+### 根因分析(QuartzCore macOS 27.0.1 dyld cache 静态反汇编)
+1. **`nil linear texture from buffer`**:`CA::OGL::MetalContext::copy_image_to_texture` 将客户端共享内存 backing store 通过 `newBufferWithBytesNoCopy:length:options:deallocator:` 包装为 `MTLBuffer` 后,调用 SPI `-[MTLBuffer newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:]`。此前 `XcmBuffer` 未实现该 SPI(被 `resolveStub` 桩返回 `0`),且 `newTextureWithDescriptor:offset:bytesPerRow:` 忽略 `offset`/`bytesPerRow` 新建了独立纹理。
+2. **`timed out fence` + `Command buffer failed (Error code = 0x1)`**:`XcmBackendDevice` 缺失 `newSharedEvent` / `newSharedEventWithOptions:` / `newSharedEventWithHandle:`,`XcmCommandBuffer` 的 `encodeSignalEvent:`/`encodeWaitForEvent:` 仅处理 `XcmEvent` 未处理 `MTLSharedEvent`,三类 Encoder 缺失 `updateFence:`/`waitForFence:`,且 `XcmCommandBuffer.error` 硬编码 `"Command buffer failed"` 未透出底层 `metal2vulkan` 失败原因。
+3. **非持久化 `CAEnableIOSurfaceCompression`**:`CFPreferencesSetAppValue` 会把偏好落盘到各 App 的 plist。反汇编 `__CADeviceUseCompression_block_invoke` 确认 QuartzCore 调用 `CFPreferencesGetAppBooleanValue`,改用 `[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"CAEnableIOSurfaceCompression": @NO}]` 仅在内存 `NSRegistrationDomain` 生效,绝不落盘。
+
+### 修改内容
+- **`src/xnu-m2v-bridge/include/xnu_m2v.h` & `src/lib.rs`**:
+ - 导出 `xm2v_buffer_new_no_copy_dealloc`(支持 `Deallocator` 回调)、`xm2v_buffer_new_texture`、`xm2v_buffer_new_linear_texture`(直接对接 `metal2vulkan_runtime::Buffer::new_texture` / `new_linear_texture`,原生别名共享内存并在需要时自动走 `shadowed-texture` 双向同步)。
+ - 导出完整 `Xm2vSharedEvent` / `Xm2vSharedEventHandle` C ABI(`new`、`new_with_handle`、`signaled_value`、`set_signaled_value`、`wait_until`、`notify`、`new_handle`)及 `xm2v_command_buffer_encode_{signal,signal_scheduled,wait}_shared_event`。
+ - 导出 Compute/Render/Blit Encoder 的 `update_fence` / `wait_fence` 与 `xm2v_command_buffer_error`(透出 `cb.error()` / `cb.refusal()` / `cb.error_description()`)。
+- **`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm` & `XnuCpuMetalShim.h`**:
+ - 实现 `-[XcmBuffer newTextureWithDescriptor:offset:bytesPerRow:]` 与 `-[XcmBuffer newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:]`,在 `XcmTexture` 上维护并透传 `buffer` / `bufferOffset` / `bufferBytesPerRow`;`newBufferWithBytesNoCopy:` 完整透传 `deallocator`。
+ - 新增 `XcmSharedEvent`(声明遵循 `MTLSharedEvent`/`MTLEvent`,参考类 `IOGPUMetalSharedEvent`)与 `XcmSharedEventHandle`,支持 `MTLSharedEventListener` 在其 `dispatchQueue` 异步回调;补齐 `XcmCommandBuffer` 事件编码与 `os_log_error` 详细错误日志、三类 Encoder 的 `MTLFence` 编码。
+ - 将 `CFPreferencesSetAppValue` 替换为纯内存 `NSUserDefaults registerDefaults:`。
+
+### 宿主机验证结果(通用 `arm64 + arm64e` `XnuCpuMetal.bundle`)
+- **`test_round10`(`arm64` & `arm64e` 双架构全部 PASS)**:
+ - `CAEnableIOSurfaceCompression` 通过 `CFPreferencesGetAppBooleanValue` 读到 `valid=1, val=0` 且无任何 plist 落盘。
+ - WindowServer 日志全部 4 种线性纹理规格(`84x103 bpr=192 o=0`、`234x18 bpr=960 o=0x100`、`256x1 bpr=2048 o=0`、`1x1 bpr=64 o=0x100 bpi=4`)均成功创建并校验 `buffer`/`bufferOffset`/`bufferBytesPerRow` 与 `deallocator` 调用;CPU 原地覆写共享内存(`0xff112233` → `0xff44cc88`)不重建纹理,GPU Shader 连续两帧渲染结果精确一致。
+ - `MTLSharedEvent` GPU signal → `MTLSharedEventListener` 回调及时触发、CPU `setSignaledValue:` 解除 GPU `encodeWaitForEvent:` 阻塞、`newSharedEventHandle`/`newSharedEventWithHandle:` 别名与 `MTLFence` 均 PASS。
+- **全量回归(`arm64` & `arm64e`)**:`test-bundle.sh`、`test-render-ci.sh`(Render Pass + `CIGaussianBlur maxErr=1, meanErr=0.0161`)、`test_compressed_full`(`&BGA`/`&RhA`/`&b3a`)全部 PASS。
+
+---
+
+## Round 11: 修复 QuartzCore `VfxXg/Xgc` 合成全黑(`minConstantBufferAlignmentBytes` 环缓冲归零 + `isFramebufferReadSupported`)
+
+### 根因定位(宿主机 `CARenderer rendererWithMTLTexture:options:` 复现 + `QuartzCore` 反汇编)
+用 `CARenderer` 对比本插件与 Apple M5 Max 原生 Metal,在 `rounded_only` 与 `rounded_shadow` 场景中稳定复现全黑/大面积 `(0,0,0,0)`,并定位到两个耦合的设备能力缺口:
+1. **`minConstantBufferAlignmentBytes` 返回 `0` 导致 `MetalBufferPool` 环缓冲偏移归零覆写**:
+ - 反汇编 `CA::OGL::MetalBufferPool::encode_vertex_arg`(`+0x3c..+0x58`)确认其用 `align = max(req_align, pool->min_alignment)` 计算对齐偏移 `aligned = (cur + align - 1) & (-align)`。
+ - 当 `VfxXg/Xgc` 编码 0 字节占位参数(`req_align = 0`)且 `_MTLDevice` limits 中 `minConstantBufferAlignmentBytes == 0` 时,`align = 0`,`aligned = (cur - 1) & 0 = 0`,导致 `pool->current_offset` 在同一个 RenderPass 中被重置为 `0`,后续 draw 直接从偏移 `0` 覆写同一个 256 KiB 缓冲,摧毁前面所有 draw 的顶点、索引和颜色常量。
+2. **`isFramebufferReadSupported` 返回 `NO` 导致 `VfxXg/Xgc` 混合输出 `(0,0,0,0)`**:
+ - `VfxXg/Xgc`(`fixed_vert_lph_gen` + `fixed_frag_lph_cpf`)是 QuartzCore 的通用 uber-shader,其管线固定为 `blend=0` 并依赖 `[[color(0)]]` 可编程混合(`fc_framebuffer_fetch = Bool 01`)。此前插件未返回 `isFramebufferReadSupported = YES`,导致 QuartzCore 以 `fc_framebuffer_fetch = Bool 00` 且 `blend=0` 编译 `Xgc`,所有半透明/圆角/阴影/窗口合成 draw 均输出 `(0,0,0,0)`。开启后 `metal2vulkan-runtime` 通过 lavapipe 的 `rasterizationOrderColorAttachmentAccess` 精确执行 framebuffer fetch。
+
+### 修改内容(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)
+- 在 `fillBaseLimits` 补齐缺失的对齐字段:`minConstantBufferAlignmentBytes = 4`、`minBufferNoCopyAlignmentBytes = 4096`、`linearTextureArrayAlignmentBytes = 16`、`linearTextureArrayAlignmentSlice = 128`、`maxComputeThreadgroupMemoryAlignmentBytes = 16`、`linearTextureAlignmentBytes = 64`。
+- 在 `XcmBackendDevice` 补齐 `isFramebufferReadSupported = YES`、`supportsProgrammableBlending = YES`、`supportsUnalignedVertexFetch = YES`,并在 `supportsFamily:` 放行 `Apple1..2` / `Mac1..2` / `Common1..3`。
+- 在 `XNU_CPU_METAL_TRACE=1` 下新增每次 `renderCommandEncoderWithDescriptor:`(`c0`、load/store/clear、depth/stencil)、`newRenderPSO`(`blend` 参数与 `writeMask`)、`drawPrimitives`/`drawIndexedPrimitives`(图元类型、顶点数、绑定的 `vb`/`fb`/`ft`/`fs` 掩码、`fbytes`、`viewport`、`scissor`)及 `cb-done` 状态日志。
+
+### 宿主机验证结果(通用 `arm64 + arm64e` `XnuCpuMetal.bundle`)
+- **`CARenderer` 对比 Apple M5 Max(`build/test_carenderer.mm`,`arm64` & `arm64e` 双架构全部 PASS,覆盖 `VfxXg/Xgc` 路径)**:
+ - `color`(纯红 backgroundColor):`maxErr=0, meanErr=0.000`
+ - `image`(四象限 CGImage):`maxErr=0, meanErr=0.000`
+ - `two_layers`(双层叠加):`maxErr=0, meanErr=0.000`
+ - `rounded_only`(圆角 layer,触发 `VfxXg/Xgc`):`maxErr=1, meanErr=0.000`
+ - `rounded_shadow`(圆角 + 阴影,多 pass 模糊 + `VfxXg/Xgc`):`maxErr=3, meanErr=0.092`
+- **全量回归(`arm64` & `arm64e`)**:`test_round10`、`test-bundle.sh`、`test-render-ci.sh`、`test_compressed_full` 全部 PASS。
+
+---
+
+## Round 12: `XcmCommandBuffer` / Encoder 并发资源生命周期与线程安全加固(`iconservicesagent` 崩溃排查)
+
+### 审计发现与修复(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)
+1. **Encoder 资源过早释放(违反 `retainedReferences = YES`)**:
+ - 此前 `XcmRenderEncoder`、`XcmComputeEncoder`、`XcmBlitEncoder` 在 `endEncoding` 时立刻清空 `_retained`,且 `renderCommandEncoderWithDescriptor:` 未强引用非 IOSurface 的 color/depth/stencil attachment 纹理,导致调用方在 `endEncoding` + `commit` 后立即释放 `XcmBuffer`(含 `_fallbackDeallocator`)或 `XcmTexture` 时,对象可能在 GPU(`llvmpipe` 光栅化线程)仍在执行期间提前 `dealloc`。
+ - 修复:在 `XcmCommandBuffer` 新增 `_retainedResources` 与 `retainResource:`(`@synchronized(self)` 保护),将三类 Encoder 绑定资源、RenderPass attachment 纹理与 Event 全部挂到 `XcmCommandBuffer`,仅在 `wait_until_completed` + IOSurface 同步 + handlers 完成后于锁外 `_releaseRetainedResourcesOnce` 释放。
+2. **`XcmCommandBuffer` 并发竞争与 Handler 顺序保证**:
+ - `addScheduledHandler:`、`addCompletedHandler:`、`markDirtyIOSurfaceTexture:`、`commit`(`_committed` 防重入)全部加 `@synchronized(self)` 保护。
+ - `_fireHandlersOnce` 在锁内快照清空回调列表,**锁外**执行用户回调避免死锁,同时用 `dispatch_group_t`(带同线程重入检测)保证任意并发调用 `waitUntilCompleted` 的线程在所有 completed handler 执行完之前绝不提前返回。
+3. **`XcmTexture` IOSurface 并发同步与类型校验**:
+ - `syncFromIOSurfaceIfNeeded`(先 `xcmFlushIOSurfaceWriter` 再取 `@synchronized(self)`,保持严格锁序 `XcmCommandBuffer -> XcmTexture`)与 `syncToIOSurface` 加 `@synchronized(self)` 保护;`gIOSurfaceLastWriter` 超过 256 项时自动清理失效 `__weak` 项。
+ - 三类 Encoder 对 buffer/texture/sampler/depthStencil/pipeline 参数补齐 `isKindOfClass:` 校验,避免非法对象强转解引用 `_handle`。
+
+### 验证结果(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)
+- **新增多线程并发压测**(`build/test_stress_mt.mm`,`arm64` & `arm64e`,`LP_NUM_THREADS=2` 与 `LP_NUM_THREADS=0`):
+ - Phase 1(8 线程 × 60 = 480 次并发 `commit` + IOSurface + `addCompletedHandler:` + 交替 `waitUntilCompleted` + 立即释放):`submitted=480 handlers=480 failures=0`
+ - Phase 2(4 线程 × 15 = 60 次并发 `CARenderer` 含圆角阴影):`caDone=60 failures=0`
+ - Phase 3(4 线程 × 40 = 160 次 `newBufferWithBytesNoCopy:` + `munmap` deallocator + `commit` 后立即释放):`noCopyDone=160 deallocCount=160 failures=0`
+ - Phase 4(40 轮双线程并发 `waitUntilCompleted` 与 `completedHandler` 完成顺序及单次触发校验):`failures=0`
+ - 4 进程并发 `ictool MenuBarIcon.icon`:全部退出 0 且输出一致(`114801` 字节)。
+- **全量回归(`arm64` & `arm64e`)**:
+ - `test_carenderer`(5 项对比 Apple M5 Max)、`test_round10`(4/4 PASS)、`test-bundle.sh`(`bad=0`)、`test-render-ci.sh`(`CIGaussianBlur maxErr=1, meanErr=0.0161`)全部 PASS。
+
+---
+
+## Round 13: Safari 打开时 `WindowServer` `GpuHang` → `AccessRevoked` → `llvmpipe_draw_vbo` UAF `SIGSEGV` 与 0 长度 NoCopy 修复
+
+### 根因
+1. **CPU 设备套用了 20.2s 硬件 GPU watchdog**:`metal2vulkan-runtime/src/command_buffer/stall.rs` 对所有设备硬编码 `WATCHDOG = 20.2s`、`STALL = 10s`。Safari 启动时 CPU 光栅化 + LLVM JIT 负载骤增,单批超过 20.2s 即被判 `GpuHang` 并 park `VkDevice`;累计 2 次后触发 `revocation.rs`(`REVOKING = 2`)永久吊销队列,后续提交全部 `AccessRevoked`。
+2. **Parked 设备仍执行 host memory deallocator 导致 `llvmpipe_draw_vbo` 顶点 fetch UAF**:`VkDevice` 被 park 后 `release::object` 跳过 `vkFreeMemory`,但 `metal2vulkan-runtime/src/buffer.rs` 的 `Imported::drop` 与 `HostPages::drop` 仍会执行调用方的 `deallocator`(`munmap`),且 `XcmCommandBuffer` 仍释放 `_retainedResources`,导致 `lavapipe` 后台线程执行 `llvmpipe_draw_vbo` 读取已取消映射的页边界(`0x...c000`)而 `SIGSEGV`。同时 `XcmCommandBuffer` 的 `wait_until_completed` 存在 60s 硬超时。
+3. **`newBufferWithBytesNoCopy(ptr=0, len=0)` 语义偏差**:实测宿主机 Apple M5 Max 上 `newBufferWithBytesNoCopy(NULL, 0)`、`newBufferWithLength(0)`、`newBufferWithBytes(NULL, 0)` 均直接返回 `nil` 且不调用 `deallocator`;原插件会报错并回退到 `xm2v_buffer_new(..., 0, ...)`。
+
+### 修复
+1. `src/metal2vulkan/crates/metal2vulkan-runtime/src/command_buffer/stall.rs`:对 `DeviceKind::Cpu` 将 `watchdog_after` 与 `stall_after` 放宽至 `3600s`(支持 `XNU_CPU_METAL_WATCHDOG_MS` 覆盖用于测试)。
+2. `src/metal2vulkan/crates/metal2vulkan-runtime/src/buffer.rs`:`Imported::drop` 与 `HostPages::drop` 在 `release::parked(vk_device)` 时跳过 deallocator / keep_alive 释放(与 `vkFreeMemory` 一致地保持映射),彻底杜绝 parked 设备的 `munmap` UAF。
+3. `src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`:
+ - `XcmCommandBuffer` `wait_until_completed` 改为无限等待(`timeout_ms = 0`);若遇到 `GpuHang`/`DeviceLost` 则将 `_retainedResources` 存入静态 park 列表不提前释放。
+ - `xcmDev_newBufferNoCopy`、`xcmDev_newBufferLen`、`xcmDev_newBufferBytes` 对 `ptr == nullptr || length == 0` 直接返回 `nil` 且不触发 `deallocator`。
+
+### 验证(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)
+- `build/test_round13.mm`(`arm64` & `arm64e`,`LP_NUM_THREADS=0`):
+ - `PASS [1]`:`newBufferWithBytesNoCopy(NULL, 0)` / `newBufferWithLength(0)` / `newBufferWithBytes(NULL, 0)` 全返回 `nil` 且 `dealloc=0`。
+ - `PASS [2]`:单 CB 26 次重负载 draw 连续运行 **25.02s**(超过原 20.2s watchdog)正常完成,`0 GpuHang / 0 AccessRevoked`,`dealloced=1/1`;3 连重负载 CB(9.75s)全过。
+ - `PASS [hang_uaf]`(`XNU_CPU_METAL_WATCHDOG_MS=1000` 强制触发 `GpuHang` 并 park 设备):`arm64` 与 `arm64e` 均在 `llvmpipe_draw_vbo` 继续读 `mmap` 顶点缓冲期间零 `SIGSEGV`(`dealloced=0`)。
+- 全量回归:`test_carenderer_arm64e`、`test_round10_arm64e`、`test_stress_mt_arm64e`(Phase 1-4 `failures=0`)、`test-bundle.sh arm64e` 全部 PASS。
+
+---
+
+## Round 14: 锁屏 `loginwindow` → `AvatarKit` / `VFX` `MTLDevice` Selector 差集补齐
+
+### 根因与审计
+- 锁屏时 `loginwindow` 的 `AVTView` 进入 `VFX`,调用 `-[XcmBackendDevice isDepth24Stencil8PixelFormatSupported]` 抛出 `NSInvalidArgumentException` 导致 `loginwindow` 退出、会话重启。
+- 对照宿主机 macOS 27 `AGXG17CDevice`(Apple M5 Max)全量扫描 `@protocol(MTLDevice)`、`@protocol(MTLDeviceSPI)` 以及 7 个框架(`VFX`、`AvatarKit`、`SceneKit`、`CoreRE`、`QuartzCore`、`RenderBox`、`CoreImage`)共 **25,589 条 `__objc_selrefs`**,发现:
+ - `@protocol(MTLDevice)` 缺失 3 项:`isDepth24Stencil8PixelFormatSupported`、`sparseTileSizeWithTextureType:pixelFormat:sampleCount:`、`sparseTileSizeWithTextureType:pixelFormat:sampleCount:sparsePageSize:`(3 项均被 `VFX` / `SceneKit` 引用)。
+ - `@protocol(MTLDeviceSPI)` 缺失 23 项(含 `newBufferWithDescriptor:`、`newVisibleFunctionTableWithDescriptor:`、`newTextureWithBytesNoCopy:length:descriptor:deallocator:`、`supportsSampleCount:`、`singleFPConfig`/`doubleFPConfig`/`halfFPConfig`、`metalAssertionsEnabled`/`setMetalAssertionsEnabled:`、`tileSizeWithSparsePageSize:...`、`newRenderPipelineStateWithTileDescriptor:*` 等)。
+ - 另发现 VFX 初始化查询 `maxViewportCount` 返回了 `0`(应为 `16`),`maxArgumentBufferSamplerCount` 为 `0`(应为 `16`)。
+
+### 修复(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)
+- 在 `XcmBackendDevice` 补齐上述全部 26 个 `MTLDevice` + `MTLDeviceSPI` 方法(`isDepth24Stencil8PixelFormatSupported` 按 Apple Silicon 实测返回 `NO`;`newBufferWithDescriptor:` 标 `NS_RETURNS_RETAINED` 并完整转发至 `newBuffer*`),并补齐 `maxViewportCount = 16`、`maxArgumentBufferSamplerCount = 16`、`supportsBaseVertexInstanceDrawing` / `supportsDepthClipMode` / `supportsTextureCubeArray` / `supportsNonUniformThreadgroupSize = YES`。
+
+### 验证(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)
+- 新增 `build/test_round14_vfx.mm`(`arm64` & `arm64e` 均 6/6 PASS):
+ 1. `isDepth24Stencil8PixelFormatSupported == NO`
+ 2. `@protocol(MTLDevice)` + `@protocol(MTLDeviceSPI)` 对照 Apple M5 Max **0 缺失**
+ 3. `Depth32Float_Stencil8` 纹理创建 + 深度/模板 RenderPass 完成
+ 4. `SCNRenderer rendererWithDevice:dev options:nil` 正常初始化
+ 5. `VFXRenderer rendererWithDevice:dev options:nil` 与 `AVTView initWithFrame:options:` 正常初始化(0 `unrecognized selector`)
+ 6. 7 个框架(`VFX`/`AvatarKit`/`SceneKit`/`CoreRE`/`QuartzCore`/`RenderBox`/`CoreImage`)25,589 条 `__objc_selrefs` **0 缺失**
+- 全量回归:`test_carenderer_arm64e`、`test_round10_arm64e`、`test_round13_arm64e`、`test-bundle.sh arm64e` 全部 PASS。
diff --git a/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh b/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh
index 7d467c4..0319f88 100755
--- a/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh
+++ b/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh
@@ -18,7 +18,7 @@ lipo -create \
-output "$BUNDLE/Contents/Frameworks/libxnu_m2v.dylib"
lipo -create \
- "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib" \
+ "$ROOT/build/vkloader-arm64-install/lib/libvulkan.1.dylib" \
"$ROOT/build/vkloader-arm64e-install/lib/libvulkan.1.dylib" \
-output "$BUNDLE/Contents/Frameworks/libvulkan.1.dylib"
@@ -27,7 +27,7 @@ lipo -create \
"$ROOT/dist/lavapipe-arm64e/lib/libvulkan_lvp.dylib" \
-output "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib"
-# 2. Relocatable ICD JSON
+# 2. Relocatable ICD JSON (both top-level for host env-var runs and vulkan/icd.d/ for secure-mode SYSCONFDIR)
cat > "$BUNDLE/Contents/Resources/lvp_icd.aarch64.json" <<'EOF'
{
"ICD": {
@@ -38,6 +38,17 @@ cat > "$BUNDLE/Contents/Resources/lvp_icd.aarch64.json" <<'EOF'
"file_format_version": "1.0.1"
}
EOF
+mkdir -p "$BUNDLE/Contents/Resources/vulkan/icd.d"
+cat > "$BUNDLE/Contents/Resources/vulkan/icd.d/lvp_icd.aarch64.json" <<'EOF'
+{
+ "ICD": {
+ "api_version": "1.4.363",
+ "library_arch": "64",
+ "library_path": "../../../Frameworks/libvulkan_lvp.dylib"
+ },
+ "file_format_version": "1.0.1"
+}
+EOF
# 3. Compile XnuCpuMetal MH_BUNDLE for both arm64 and arm64e, then lipo
for ARCH in arm64 arm64e; do
diff --git a/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh
index f40dd88..5e6332b 100755
--- a/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh
+++ b/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh
@@ -2,24 +2,32 @@
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
-BUILD_DIR="$ROOT/build/vkloader-arm64e"
-PREFIX="$ROOT/build/vkloader-arm64e-install"
VK_HDR_DIR="$ROOT/build/vk-deps/vulkan-headers/1.4.363.0"
+BUNDLE_SYSCONFDIR="/Library/GPUBundles/XnuCpuMetal.bundle/Contents/Resources"
export PATH="$ROOT/build/pyvenv/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
-cmake -G Ninja -S "$ROOT/src/Vulkan-Loader" -B "$BUILD_DIR" \
- -DCMAKE_BUILD_TYPE=Release \
- -DCMAKE_C_COMPILER=/usr/bin/clang \
- -DCMAKE_CXX_COMPILER=/usr/bin/clang++ \
- -DCMAKE_OSX_ARCHITECTURES=arm64e \
- -DCMAKE_INSTALL_PREFIX="$PREFIX" \
- -DVULKAN_HEADERS_INSTALL_DIR="$VK_HDR_DIR" \
- -DBUILD_TESTS=OFF
+build_arch() {
+ local ARCH="$1"
+ local BUILD_DIR="$ROOT/build/vkloader-${ARCH}"
+ local PREFIX="$ROOT/build/vkloader-${ARCH}-install"
+ rm -rf "$BUILD_DIR"
+ cmake -G Ninja -S "$ROOT/src/Vulkan-Loader" -B "$BUILD_DIR" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_C_COMPILER=/usr/bin/clang \
+ -DCMAKE_CXX_COMPILER=/usr/bin/clang++ \
+ -DCMAKE_OSX_ARCHITECTURES="$ARCH" \
+ -DCMAKE_INSTALL_PREFIX="$PREFIX" \
+ -DSYSCONFDIR="$BUNDLE_SYSCONFDIR" \
+ -DVULKAN_HEADERS_INSTALL_DIR="$VK_HDR_DIR" \
+ -DBUILD_TESTS=OFF
+ ninja -C "$BUILD_DIR" -j"$(sysctl -n hw.ncpu)"
+ ninja -C "$BUILD_DIR" install
+ install_name_tool -id "@rpath/libvulkan.1.dylib" "$PREFIX/lib/libvulkan.1.dylib"
+ codesign -s - --force "$PREFIX/lib/libvulkan.1.dylib" 2>/dev/null || true
+ file "$PREFIX/lib/libvulkan.1.dylib"
+ otool -L "$PREFIX/lib/libvulkan.1.dylib"
+}
-ninja -C "$BUILD_DIR" -j"$(sysctl -n hw.ncpu)"
-ninja -C "$BUILD_DIR" install
-install_name_tool -id "@rpath/libvulkan.1.dylib" "$PREFIX/lib/libvulkan.1.dylib"
-codesign -s - --force "$PREFIX/lib/libvulkan.1.dylib" 2>/dev/null || true
-file "$PREFIX/lib/libvulkan.1.dylib"
-otool -L "$PREFIX/lib/libvulkan.1.dylib"
+build_arch arm64
+build_arch arm64e
diff --git a/gpu/xnu-cpu-metal/scripts/test-bundle.sh b/gpu/xnu-cpu-metal/scripts/test-bundle.sh
index f7ed986..1efb420 100755
--- a/gpu/xnu-cpu-metal/scripts/test-bundle.sh
+++ b/gpu/xnu-cpu-metal/scripts/test-bundle.sh
@@ -5,6 +5,12 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SDK="$(xcrun --show-sdk-path)"
ARCH="${1:-arm64}"
+mkdir -p "$ROOT/build"
+if [ ! -f "$ROOT/build/vecadd.metallib" ]; then
+ xcrun -sdk macosx metal -c "$ROOT/test/vecadd.metal" -o "$ROOT/build/vecadd.air"
+ xcrun -sdk macosx metallib "$ROOT/build/vecadd.air" -o "$ROOT/build/vecadd.metallib"
+fi
+
/usr/bin/clang++ -arch "$ARCH" -O2 -fobjc-arc -isysroot "$SDK" \
"$ROOT/test/test_bundle.mm" \
-framework Foundation -framework Metal \
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 9ecb07f..044ccfd 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
@@ -10,6 +10,8 @@
#import <objc/runtime.h>
#import <objc/message.h>
#include <dlfcn.h>
+#include <fcntl.h>
+#include <os/log.h>
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
#include <mach-o/loader.h>
@@ -210,6 +212,8 @@ static NSData *xcmCodeGenRequest(uint32_t type, const std::vector<uint8_t> &requ
MTLResourceOptions _options;
uint64_t _length;
MTLPurgeableState _purgeable;
+ void (^_fallbackDeallocator)(void *, NSUInteger);
+ void *_fallbackPtr;
}
- (instancetype)initWithHandle:(Xm2vBuffer *)h device:(id)dev options:(MTLResourceOptions)opts;
@end
@@ -227,6 +231,11 @@ static NSData *xcmCodeGenRequest(uint32_t type, const std::vector<uint8_t> &requ
}
- (void)dealloc {
if (_handle) { xm2v_buffer_release(_handle); _handle = nullptr; }
+ if (_fallbackDeallocator) {
+ void (^d)(void *, NSUInteger) = _fallbackDeallocator;
+ _fallbackDeallocator = nil;
+ d(_fallbackPtr, (NSUInteger)_length);
+ }
}
- (id<MTLDevice>)device { return _device; }
- (void *)contents { return _handle ? xm2v_buffer_contents(_handle) : nullptr; }
@@ -245,10 +254,6 @@ static NSData *xcmCodeGenRequest(uint32_t type, const std::vector<uint8_t> &requ
if (state != MTLPurgeableStateKeepCurrent) _purgeable = state;
return prev;
}
-- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)desc offset:(NSUInteger)offset bytesPerRow:(NSUInteger)bytesPerRow {
- (void)offset; (void)bytesPerRow;
- return [_device newTextureWithDescriptor:desc];
-}
@end
/* ======================== Texture (with IOSurface bidirectional sync) ======================== */
@@ -267,6 +272,9 @@ static NSData *xcmCodeGenRequest(uint32_t type, const std::vector<uint8_t> &requ
NSUInteger _iosurfacePlane;
uint32_t _iosurfaceSeed;
BOOL _iosurfaceSyncedIn;
+ XcmBuffer *_buffer;
+ NSUInteger _bufferOffset;
+ NSUInteger _bufferBytesPerRow;
}
- (instancetype)initWithHandle:(Xm2vTexture *)h device:(id)dev descriptor:(MTLTextureDescriptor *)desc;
- (void)syncFromIOSurfaceIfNeeded;
@@ -304,6 +312,13 @@ static void xcmRecordIOSurfaceWriter(IOSurfaceRef surf, id cmdBuf) {
uint32_t sid = IOSurfaceGetID(surf);
if (!sid) return;
std::lock_guard<std::mutex> lk(gIOSurfaceWriterLock);
+ if (gIOSurfaceLastWriter.size() > 256) {
+ for (auto it = gIOSurfaceLastWriter.begin(); it != gIOSurfaceLastWriter.end(); ) {
+ id w = it->second;
+ if (!w) it = gIOSurfaceLastWriter.erase(it);
+ else ++it;
+ }
+ }
gIOSurfaceLastWriter[sid] = cmdBuf;
}
@@ -323,48 +338,117 @@ static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
}
}
+static NSUInteger xcmPixelFormatBpp(MTLPixelFormat fmt) {
+ switch (fmt) {
+ case MTLPixelFormatA8Unorm: case MTLPixelFormatR8Unorm: case MTLPixelFormatR8Snorm:
+ case MTLPixelFormatR8Uint: case MTLPixelFormatR8Sint: case MTLPixelFormatStencil8:
+ return 1;
+ case MTLPixelFormatR16Unorm: case MTLPixelFormatR16Snorm: case MTLPixelFormatR16Uint:
+ case MTLPixelFormatR16Sint: case MTLPixelFormatR16Float: case MTLPixelFormatRG8Unorm:
+ case MTLPixelFormatRG8Snorm: case MTLPixelFormatRG8Uint: case MTLPixelFormatRG8Sint:
+ case MTLPixelFormatDepth16Unorm:
+ return 2;
+ case MTLPixelFormatRGBA16Unorm: case MTLPixelFormatRGBA16Snorm: case MTLPixelFormatRGBA16Uint:
+ case MTLPixelFormatRGBA16Sint: case MTLPixelFormatRGBA16Float:
+ case MTLPixelFormatRG32Uint: case MTLPixelFormatRG32Sint: case MTLPixelFormatRG32Float:
+ case MTLPixelFormatDepth32Float_Stencil8:
+ case MTLPixelFormatBGRA10_XR: case MTLPixelFormatBGRA10_XR_sRGB:
+ return 8;
+ case MTLPixelFormatRGBA32Uint: case MTLPixelFormatRGBA32Sint: case MTLPixelFormatRGBA32Float:
+ return 16;
+ default:
+ return 4;
+ }
+}
+
+// Resolve linear base pointer and bytes-per-row for an IOSurface plane (while locked),
+// treating '&'-prefixed lossless-compressed formats (&BGA, &b3a, &RhA, &R10, etc.) as linear
+// uncompressed rows and computing 64-byte aligned planes for 2-plane b3a8/&b3a when bpr==0.
+static bool xcmIOSurfacePlaneLayout(IOSurfaceRef surf, NSUInteger plane, NSUInteger width, NSUInteger height,
+ MTLPixelFormat fmt, void **outBase, size_t *outBpr) {
+ if (!surf || !width || !height) return false;
+ void *rootBase = IOSurfaceGetBaseAddress(surf);
+ size_t allocSz = IOSurfaceGetAllocSize(surf);
+ size_t planeCount = IOSurfaceGetPlaneCount(surf);
+ bool usePlane = (planeCount > 0 && plane < planeCount);
+ void *base = usePlane ? IOSurfaceGetBaseAddressOfPlane(surf, plane) : rootBase;
+ size_t bpr = usePlane ? IOSurfaceGetBytesPerRowOfPlane(surf, plane) : IOSurfaceGetBytesPerRow(surf);
+
+ if (bpr == 0) {
+ uint32_t pf = IOSurfaceGetPixelFormat(surf);
+ // 2-plane RGB10A8_2P_XR10 ('b3a8' or compressed '&b3a') reporting 0 plane row bytes.
+ if ((pf == 0x62336138u || pf == 0x26623361u) && plane < 2 && rootBase) {
+ size_t sw = IOSurfaceGetWidth(surf), sh = IOSurfaceGetHeight(surf);
+ size_t row0 = (sw * 4 + 63) & ~(size_t)63;
+ size_t row1 = (sw + 63) & ~(size_t)63;
+ if (sw && sh && row0 * sh + row1 * sh <= allocSz) {
+ base = (uint8_t *)rootBase + (plane == 0 ? 0 : row0 * sh);
+ bpr = (plane == 0) ? row0 : row1;
+ }
+ }
+ if (bpr == 0) {
+ if (!base) base = rootBase;
+ bpr = IOSurfaceGetBytesPerRow(surf);
+ }
+ if (bpr == 0) {
+ bpr = ((size_t)width * xcmPixelFormatBpp(fmt) + 63) & ~(size_t)63;
+ }
+ }
+ if (!base || bpr == 0) return false;
+ if (rootBase && allocSz > 0) {
+ uintptr_t r = (uintptr_t)rootBase, b = (uintptr_t)base;
+ if (b < r || (b - r) + bpr * (size_t)height > allocSz) {
+ // Clamp to unaligned width*bpp if padded bpr slightly exceeds allocSz on last row.
+ size_t minBpr = (size_t)width * xcmPixelFormatBpp(fmt);
+ if (b < r || (b - r) + minBpr * (size_t)height > allocSz) return false;
+ }
+ }
+ *outBase = base;
+ *outBpr = bpr;
+ return true;
+}
+
- (void)syncFromIOSurfaceIfNeeded {
if (!_iosurface || !_handle) return;
xcmFlushIOSurfaceWriter(_iosurface);
- uint32_t seed = IOSurfaceGetSeed(_iosurface);
- if (_iosurfaceSyncedIn && seed == _iosurfaceSeed) return;
- if (IOSurfaceLock(_iosurface, kIOSurfaceLockReadOnly, nullptr) == kIOReturnSuccess) {
- size_t planeCount = IOSurfaceGetPlaneCount(_iosurface);
- void *base = (planeCount > 0) ? IOSurfaceGetBaseAddressOfPlane(_iosurface, _iosurfacePlane)
- : IOSurfaceGetBaseAddress(_iosurface);
- size_t bpr = (planeCount > 0) ? IOSurfaceGetBytesPerRowOfPlane(_iosurface, _iosurfacePlane)
- : IOSurfaceGetBytesPerRow(_iosurface);
- if (base && bpr > 0) {
- xm2v_texture_replace_region(_handle, 0, 0, 0, _width, _height, 1, 0, 0, base, bpr, 0);
+ @synchronized(self) {
+ if (!_iosurface || !_handle) return;
+ 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);
+ }
+ IOSurfaceUnlock(_iosurface, kIOSurfaceLockReadOnly, nullptr);
+ _iosurfaceSeed = seed;
+ _iosurfaceSyncedIn = YES;
}
- IOSurfaceUnlock(_iosurface, kIOSurfaceLockReadOnly, nullptr);
- _iosurfaceSeed = seed;
- _iosurfaceSyncedIn = YES;
}
}
- (void)syncToIOSurface {
- if (!_iosurface || !_handle) return;
- if (IOSurfaceLock(_iosurface, 0, nullptr) == kIOReturnSuccess) {
- size_t planeCount = IOSurfaceGetPlaneCount(_iosurface);
- void *base = (planeCount > 0) ? IOSurfaceGetBaseAddressOfPlane(_iosurface, _iosurfacePlane)
- : IOSurfaceGetBaseAddress(_iosurface);
- size_t bpr = (planeCount > 0) ? IOSurfaceGetBytesPerRowOfPlane(_iosurface, _iosurfacePlane)
- : IOSurfaceGetBytesPerRow(_iosurface);
- if (base && bpr > 0) {
- bool ok = xm2v_texture_get_bytes(_handle, base, bpr, 0, 0, 0, 0, _width, _height, 1, 0, 0);
- if (xcmTraceOn() || !ok) {
- const uint8_t *p = (const uint8_t *)base;
- size_t nz = 0;
- for (size_t i = 0; i < bpr * _height; i++) if (p[i]) nz++;
- fprintf(stderr, "XCM syncToIOSurface(%p surf=%p fmt=%lu %lux%lu bpr=%zu) ok=%d nz=%zu/%zu err=%s\n",
- (__bridge void *)self, _iosurface, (unsigned long)_pixelFormat,
- (unsigned long)_width, (unsigned long)_height, bpr, ok, nz, bpr * _height,
- ok ? "ok" : xm2v_last_error());
+ @synchronized(self) {
+ if (!_iosurface || !_handle) return;
+ if (IOSurfaceLock(_iosurface, 0, nullptr) == kIOReturnSuccess) {
+ void *base = nullptr;
+ size_t bpr = 0;
+ if (xcmIOSurfacePlaneLayout(_iosurface, _iosurfacePlane, _width, _height, _pixelFormat, &base, &bpr)) {
+ bool ok = xm2v_texture_get_bytes(_handle, base, bpr, 0, 0, 0, 0, _width, _height, 1, 0, 0);
+ if (xcmTraceOn() || !ok) {
+ const uint8_t *p = (const uint8_t *)base;
+ size_t nz = 0;
+ for (size_t i = 0; i < bpr * _height; i++) if (p[i]) nz++;
+ fprintf(stderr, "XCM syncToIOSurface(%p surf=%p fmt=%lu %lux%lu bpr=%zu) ok=%d nz=%zu/%zu err=%s\n",
+ (__bridge void *)self, _iosurface, (unsigned long)_pixelFormat,
+ (unsigned long)_width, (unsigned long)_height, bpr, ok, nz, bpr * _height,
+ ok ? "ok" : xm2v_last_error());
+ }
}
+ IOSurfaceUnlock(_iosurface, 0, nullptr);
+ _iosurfaceSeed = IOSurfaceGetSeed(_iosurface);
+ _iosurfaceSyncedIn = YES;
}
- IOSurfaceUnlock(_iosurface, 0, nullptr);
- _iosurfaceSeed = IOSurfaceGetSeed(_iosurface);
- _iosurfaceSyncedIn = YES;
}
}
- (id<MTLDevice>)device { return _device; }
@@ -386,30 +470,14 @@ static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
- (BOOL)isDrawable { return NO; }
- (NSUInteger)protectionOptions { return 0; }
- (NSUInteger)allocatedSize {
- NSUInteger bpp = 4;
- switch (_pixelFormat) {
- case MTLPixelFormatA8Unorm: case MTLPixelFormatR8Unorm: case MTLPixelFormatR8Snorm:
- case MTLPixelFormatR8Uint: case MTLPixelFormatR8Sint: case MTLPixelFormatStencil8:
- bpp = 1; break;
- case MTLPixelFormatR16Unorm: case MTLPixelFormatR16Snorm: case MTLPixelFormatR16Uint:
- case MTLPixelFormatR16Sint: case MTLPixelFormatR16Float: case MTLPixelFormatRG8Unorm:
- case MTLPixelFormatRG8Snorm: case MTLPixelFormatRG8Uint: case MTLPixelFormatRG8Sint:
- case MTLPixelFormatDepth16Unorm:
- bpp = 2; break;
- case MTLPixelFormatRGBA16Unorm: case MTLPixelFormatRGBA16Snorm: case MTLPixelFormatRGBA16Uint:
- case MTLPixelFormatRGBA16Sint: case MTLPixelFormatRGBA16Float:
- case MTLPixelFormatRG32Uint: case MTLPixelFormatRG32Sint: case MTLPixelFormatRG32Float:
- case MTLPixelFormatDepth32Float_Stencil8:
- bpp = 8; break;
- case MTLPixelFormatRGBA32Uint: case MTLPixelFormatRGBA32Sint: case MTLPixelFormatRGBA32Float:
- bpp = 16; break;
- default: bpp = 4; break;
- }
+ NSUInteger bpp = xcmPixelFormatBpp(_pixelFormat);
NSUInteger sz = MAX(1ul, _width) * MAX(1ul, _height) * MAX(1ul, _depth) * MAX(1ul, _arrayLength) * MAX(1ul, _sampleCount) * bpp;
return (sz + 255ul) & ~255ul;
}
- (id<MTLTexture>)parentTexture { return nil; }
-- (id<MTLBuffer>)buffer { return nil; }
+- (id<MTLBuffer>)buffer { return (id<MTLBuffer>)_buffer; }
+- (NSUInteger)bufferOffset { return _bufferOffset; }
+- (NSUInteger)bufferBytesPerRow { return _bufferBytesPerRow; }
- (IOSurfaceRef)iosurface { return _iosurface; }
- (NSUInteger)iosurfacePlane { return _iosurfacePlane; }
- (MTLPurgeableState)setPurgeableState:(MTLPurgeableState)state {
@@ -424,6 +492,7 @@ static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
region.origin.x, region.origin.y, region.origin.z,
region.size.width, region.size.height, region.size.depth,
level, slice, pixelBytes, bytesPerRow, bytesPerImage);
+ if (_iosurface && level == 0 && slice == 0) [self syncToIOSurface];
}
}
- (void)replaceRegion:(MTLRegion)region mipmapLevel:(NSUInteger)level
@@ -433,6 +502,7 @@ static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
- (void)getBytes:(void *)pixelBytes bytesPerRow:(NSUInteger)bytesPerRow bytesPerImage:(NSUInteger)bytesPerImage
fromRegion:(MTLRegion)region mipmapLevel:(NSUInteger)level slice:(NSUInteger)slice {
if (_handle) {
+ if (_iosurface && level == 0 && slice == 0) [self syncFromIOSurfaceIfNeeded];
xm2v_texture_get_bytes(_handle, pixelBytes, bytesPerRow, bytesPerImage,
region.origin.x, region.origin.y, region.origin.z,
region.size.width, region.size.height, region.size.depth,
@@ -463,7 +533,20 @@ static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
desc.arrayLength = sliceRange.length;
desc.usage = _usage;
desc.resourceOptions = _options;
- return (id<MTLTexture>)[[XcmTexture alloc] initWithHandle:vh device:_device descriptor:desc];
+ XcmTexture *view = [[XcmTexture alloc] initWithHandle:vh device:_device descriptor:desc];
+ if (view && _iosurface && levelRange.location == 0 && sliceRange.location == 0) {
+ CFRetain(_iosurface);
+ view->_iosurface = _iosurface;
+ view->_iosurfacePlane = _iosurfacePlane;
+ view->_iosurfaceSeed = _iosurfaceSeed;
+ view->_iosurfaceSyncedIn = _iosurfaceSyncedIn;
+ }
+ if (view && _buffer && levelRange.location == 0 && sliceRange.location == 0) {
+ view->_buffer = _buffer;
+ view->_bufferOffset = _bufferOffset;
+ view->_bufferBytesPerRow = _bufferBytesPerRow;
+ }
+ return (id<MTLTexture>)view;
}
- (id<MTLTexture>)newTextureViewWithPixelFormat:(MTLPixelFormat)pixelFormat {
return [self newTextureViewWithPixelFormat:pixelFormat textureType:_textureType
@@ -490,6 +573,64 @@ static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
}
@end
+static void xcmFillTextureDesc(MTLTextureDescriptor *desc, Xm2vTextureDesc &td) {
+ td = {};
+ td.texture_type = (uint64_t)desc.textureType;
+ td.pixel_format = (uint64_t)desc.pixelFormat;
+ td.width = desc.width;
+ td.height = desc.height;
+ td.depth = desc.depth;
+ td.mipmap_level_count = desc.mipmapLevelCount;
+ td.sample_count = desc.sampleCount;
+ td.array_length = desc.arrayLength;
+ td.resource_options = (uint64_t)desc.resourceOptions;
+ td.usage = (uint64_t)desc.usage;
+}
+
+@implementation XcmBuffer (LinearTextures)
+- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)desc offset:(NSUInteger)offset bytesPerRow:(NSUInteger)bytesPerRow {
+ if (!_handle || !desc) return nil;
+ Xm2vTextureDesc td;
+ xcmFillTextureDesc(desc, td);
+ Xm2vTexture *t = xm2v_buffer_new_texture(_handle, &td, offset, bytesPerRow);
+ if (!t) {
+ const char *err = xm2v_last_error();
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: buffer newTexture failed (fmt=%lu %lux%lu off=%lu bpr=%lu len=%llu): %{public}s",
+ (unsigned long)desc.pixelFormat, (unsigned long)desc.width, (unsigned long)desc.height,
+ (unsigned long)offset, (unsigned long)bytesPerRow, (unsigned long long)_length, err ?: "?");
+ return nil;
+ }
+ XcmTexture *tex = [[XcmTexture alloc] initWithHandle:t device:_device descriptor:desc];
+ if (tex) {
+ tex->_buffer = self;
+ tex->_bufferOffset = offset;
+ tex->_bufferBytesPerRow = bytesPerRow;
+ }
+ return (id<MTLTexture>)tex;
+}
+- (id<MTLTexture>)newLinearTextureWithDescriptor:(MTLTextureDescriptor *)desc offset:(NSUInteger)offset bytesPerRow:(NSUInteger)bytesPerRow bytesPerImage:(NSUInteger)bytesPerImage {
+ if (!_handle || !desc) return nil;
+ Xm2vTextureDesc td;
+ xcmFillTextureDesc(desc, td);
+ Xm2vTexture *t = xm2v_buffer_new_linear_texture(_handle, &td, offset, bytesPerRow, bytesPerImage);
+ if (!t) {
+ const char *err = xm2v_last_error();
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: buffer newLinearTexture failed (fmt=%lu %lux%lu off=%lu bpr=%lu bpi=%lu len=%llu): %{public}s",
+ (unsigned long)desc.pixelFormat, (unsigned long)desc.width, (unsigned long)desc.height,
+ (unsigned long)offset, (unsigned long)bytesPerRow, (unsigned long)bytesPerImage,
+ (unsigned long long)_length, err ?: "?");
+ return nil;
+ }
+ XcmTexture *tex = [[XcmTexture alloc] initWithHandle:t device:_device descriptor:desc];
+ if (tex) {
+ tex->_buffer = self;
+ tex->_bufferOffset = offset;
+ tex->_bufferBytesPerRow = bytesPerRow;
+ }
+ return (id<MTLTexture>)tex;
+}
+@end
+
/* ======================== Function & Library ======================== */
@class XcmLibrary;
@@ -854,6 +995,10 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
@public
Xm2vRenderPipeline *_handle;
id _device;
+ NSString *_vName;
+ NSString *_fName;
+ BOOL _blendEnabled;
+ uint64_t _writeMask;
}
- (instancetype)initWithHandle:(Xm2vRenderPipeline *)h device:(id)dev;
@end
@@ -1008,6 +1153,69 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
- (id<MTLDevice>)device { return _device; }
@end
+@interface XcmSharedEventHandle : NSObject {
+@public
+ Xm2vSharedEventHandle *_handle;
+ NSString *_label;
+}
+- (instancetype)initWithHandle:(Xm2vSharedEventHandle *)h label:(NSString *)label;
+@end
+
+@implementation XcmSharedEventHandle
+- (instancetype)initWithHandle:(Xm2vSharedEventHandle *)h label:(NSString *)label {
+ if ((self = [super init])) { _handle = h; _label = [label copy]; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_shared_event_handle_release(_handle); _handle = nullptr; } }
+- (NSString *)label { return _label; }
+@end
+
+@interface XcmSharedEvent : XcmObject {
+@public
+ Xm2vSharedEvent *_handle;
+}
+- (instancetype)initWithHandle:(Xm2vSharedEvent *)h;
+@end
+
+static void xcmSharedEventNotified(void *context, uint64_t value) {
+ NSArray *job = (__bridge_transfer NSArray *)context;
+ id<MTLSharedEvent> event = job[0];
+ dispatch_queue_t queue = job[1];
+ MTLSharedEventNotificationBlock block = job[2];
+ dispatch_async(queue, ^{ block(event, value); });
+}
+
+@implementation XcmSharedEvent
+- (instancetype)initWithHandle:(Xm2vSharedEvent *)h {
+ if ((self = [super init])) { _handle = h; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_shared_event_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return nil; }
+- (uint64_t)signaledValue { return _handle ? xm2v_shared_event_signaled_value(_handle) : 0; }
+- (void)setSignaledValue:(uint64_t)value {
+ if (_handle) xm2v_shared_event_set_signaled_value(_handle, value);
+}
+- (BOOL)waitUntilSignaledValue:(uint64_t)value timeoutMS:(uint64_t)milliseconds {
+ return _handle ? (xm2v_shared_event_wait_until(_handle, value, milliseconds) ? YES : NO) : NO;
+}
+- (void)notifyListener:(MTLSharedEventListener *)listener atValue:(uint64_t)value block:(MTLSharedEventNotificationBlock)block {
+ if (!_handle || !block) return;
+ dispatch_queue_t queue = listener.dispatchQueue ?: dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
+ NSArray *job = @[self, queue, [block copy]];
+ void *ctx = (__bridge_retained void *)job;
+ if (!xm2v_shared_event_notify(_handle, value, xcmSharedEventNotified, ctx)) {
+ (void)(__bridge_transfer NSArray *)ctx;
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: shared event notifyListener failed: %{public}s", xm2v_last_error() ?: "?");
+ }
+}
+- (MTLSharedEventHandle *)newSharedEventHandle {
+ if (!_handle) return nil;
+ Xm2vSharedEventHandle *h = xm2v_shared_event_new_handle(_handle);
+ return h ? (MTLSharedEventHandle *)[[XcmSharedEventHandle alloc] initWithHandle:h label:self.label] : nil;
+}
+@end
+
@interface XcmFence : XcmObject {
@public
Xm2vFence *_handle;
@@ -1096,12 +1304,18 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
NSMutableArray<MTLCommandBufferHandler> *_scheduledHandlers;
NSMutableArray<MTLCommandBufferHandler> *_completedHandlers;
NSMutableArray<XcmTexture *> *_dirtyIOSurfaceTextures;
+ NSMutableArray *_retainedResources;
+ dispatch_group_t _handlersGroup;
+ pthread_t _handlersThread;
+ BOOL _committed;
BOOL _handlersFired;
BOOL _iosurfaceFlushed;
+ BOOL _retainedReleased;
NSUInteger _protectionOptions;
}
- (instancetype)initWithHandle:(Xm2vCommandBuffer *)h device:(id)dev queue:(id)q;
- (void)markDirtyIOSurfaceTexture:(XcmTexture *)tex;
+- (void)retainResource:(id)obj;
@end
/* ======================== Encoders ======================== */
@@ -1132,15 +1346,18 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
- (id<MTLDevice>)device { return _device; }
- (void)setComputePipelineState:(id<MTLComputePipelineState>)state {
- if (!_handle || !state) return;
- [_retained addObject:state];
+ if (!_handle || !state || ![(id)state isKindOfClass:[XcmComputePipeline class]]) return;
+ [_cmdBuf retainResource:state];
xm2v_compute_encoder_set_pipeline(_handle, ((XcmComputePipeline *)state)->_handle);
}
- (void)setBuffer:(id<MTLBuffer>)buffer offset:(NSUInteger)offset atIndex:(NSUInteger)index {
if (!_handle) return;
if (index < 31) _boundBuffers[index] = buffer;
- if (buffer) [_retained addObject:buffer];
- Xm2vBuffer *bh = buffer ? ((XcmBuffer *)buffer)->_handle : nullptr;
+ Xm2vBuffer *bh = nullptr;
+ if (buffer && [(id)buffer isKindOfClass:[XcmBuffer class]]) {
+ [_cmdBuf retainResource:buffer];
+ bh = ((XcmBuffer *)buffer)->_handle;
+ }
xm2v_compute_encoder_set_buffer(_handle, bh, offset, (uint32_t)index);
}
- (void)setBuffers:(const id<MTLBuffer> *)buffers offsets:(const NSUInteger *)offsets withRange:(NSRange)range {
@@ -1156,14 +1373,15 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
- (void)setTexture:(id<MTLTexture>)texture atIndex:(NSUInteger)index {
if (!_handle) return;
+ Xm2vTexture *th = nullptr;
if (texture && [texture isKindOfClass:[XcmTexture class]]) {
XcmTexture *xt = (XcmTexture *)texture;
- [_retained addObject:xt];
+ [_cmdBuf retainResource:xt];
[xt syncFromIOSurfaceIfNeeded];
if (xt->_iosurface && (xt->_usage & MTLTextureUsageShaderWrite))
[_cmdBuf markDirtyIOSurfaceTexture:xt];
+ th = xt->_handle;
}
- Xm2vTexture *th = texture ? ((XcmTexture *)texture)->_handle : nullptr;
xm2v_compute_encoder_set_texture(_handle, th, (uint32_t)index);
}
- (void)setTextures:(const id<MTLTexture> *)textures withRange:(NSRange)range {
@@ -1172,8 +1390,11 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
- (void)setSamplerState:(id<MTLSamplerState>)sampler atIndex:(NSUInteger)index {
if (!_handle) return;
- if (sampler) [_retained addObject:sampler];
- Xm2vSampler *sh = sampler ? ((XcmSampler *)sampler)->_handle : nullptr;
+ Xm2vSampler *sh = nullptr;
+ if (sampler && [(id)sampler isKindOfClass:[XcmSampler class]]) {
+ [_cmdBuf retainResource:sampler];
+ sh = ((XcmSampler *)sampler)->_handle;
+ }
xm2v_compute_encoder_set_sampler(_handle, sh, (uint32_t)index);
}
- (void)setSamplerStates:(const id<MTLSamplerState> *)samplers withRange:(NSRange)range {
@@ -1185,7 +1406,7 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
- (void)useResource:(id<MTLResource>)resource usage:(MTLResourceUsage)usage {
if (!_handle || !resource) return;
- [_retained addObject:resource];
+ [_cmdBuf retainResource:resource];
if ([resource isKindOfClass:[XcmBuffer class]]) {
xm2v_compute_encoder_use_buffer(_handle, ((XcmBuffer *)resource)->_handle, (uint64_t)usage);
} else if ([resource isKindOfClass:[XcmTexture class]]) {
@@ -1215,6 +1436,16 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
threadsPerThreadgroup.width, threadsPerThreadgroup.height, threadsPerThreadgroup.depth);
}
}
+- (void)updateFence:(id<MTLFence>)fence {
+ if (!_handle || !fence || ![(id)fence isKindOfClass:[XcmFence class]]) return;
+ [_cmdBuf retainResource:fence];
+ xm2v_compute_encoder_update_fence(_handle, ((XcmFence *)fence)->_handle);
+}
+- (void)waitForFence:(id<MTLFence>)fence {
+ if (!_handle || !fence || ![(id)fence isKindOfClass:[XcmFence class]]) return;
+ [_cmdBuf retainResource:fence];
+ xm2v_compute_encoder_wait_fence(_handle, ((XcmFence *)fence)->_handle);
+}
- (void)endEncoding {
if (_handle) { xm2v_compute_encoder_end(_handle); _handle = nullptr; }
[_retained removeAllObjects];
@@ -1232,6 +1463,14 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
NSMutableArray *_retained;
NSMutableDictionary *_vbufs, *_fbufs; // slot -> bound buffer (for set*BufferOffset:atIndex:)
BOOL _hasPipeline;
+ XcmRenderPipeline *_curPso;
+ uint32_t _tVbufMask, _tFbufMask, _tFtexMask, _tFsampMask;
+ NSUInteger _tFbytesLen;
+ uint32_t _tFbytesSlot;
+ uint8_t _tFbytesHead[16];
+ BOOL _tHasVp, _tHasScissor;
+ MTLViewport _tVp;
+ MTLScissorRect _tScissor;
}
- (instancetype)initWithHandle:(Xm2vRenderEncoder *)h device:(id)dev commandBuffer:(XcmCommandBuffer *)cb;
@end
@@ -1247,27 +1486,36 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
if (!_handle) return;
if (!pipelineState || ![pipelineState isKindOfClass:[XcmRenderPipeline class]] || !((XcmRenderPipeline *)pipelineState)->_handle) {
_hasPipeline = NO;
+ _curPso = nil;
return;
}
_hasPipeline = YES;
- [_retained addObject:pipelineState];
- bool ok = xm2v_render_encoder_set_pipeline(_handle, ((XcmRenderPipeline *)pipelineState)->_handle);
+ _curPso = (XcmRenderPipeline *)pipelineState;
+ [_cmdBuf retainResource:pipelineState];
+ bool ok = xm2v_render_encoder_set_pipeline(_handle, _curPso->_handle);
if (!ok) fprintf(stderr, "XCM setRenderPipelineState FAILED: %s\n", xm2v_last_error());
}
- (void)setDepthStencilState:(id<MTLDepthStencilState>)depthStencilState {
if (!_handle) return;
- if (depthStencilState) [_retained addObject:depthStencilState];
- Xm2vDepthStencil *h = depthStencilState ? ((XcmDepthStencil *)depthStencilState)->_handle : nullptr;
+ Xm2vDepthStencil *h = nullptr;
+ if (depthStencilState && [(id)depthStencilState isKindOfClass:[XcmDepthStencil class]]) {
+ [_cmdBuf retainResource:depthStencilState];
+ h = ((XcmDepthStencil *)depthStencilState)->_handle;
+ }
+ if (xcmTraceOn()) fprintf(stderr, "XCM setDepthStencil(%p)\n", (void *)h);
xm2v_render_encoder_set_depth_stencil(_handle, h);
}
- (void)setViewport:(MTLViewport)vp {
+ if (xcmTraceOn()) { _tHasVp = YES; _tVp = vp; }
if (_handle) xm2v_render_encoder_set_viewport(_handle, vp.originX, vp.originY, vp.width, vp.height, vp.znear, vp.zfar);
}
- (void)setScissorRect:(MTLScissorRect)r {
+ if (xcmTraceOn()) { _tHasScissor = YES; _tScissor = r; }
if (_handle) xm2v_render_encoder_set_scissor(_handle, r.x, r.y, r.width, r.height);
}
- (void)setCullMode:(MTLCullMode)cullMode {
- if (_handle) xm2v_render_encoder_set_cull_mode(_handle, (uint64_t)cullMode);
+ if (_handle) if (xcmTraceOn()) fprintf(stderr, "XCM setCullMode(%lu)\n", (unsigned long)cullMode);
+ xm2v_render_encoder_set_cull_mode(_handle, (uint64_t)cullMode);
}
- (void)setFrontFacingWinding:(MTLWinding)winding {
if (_handle) xm2v_render_encoder_set_front_facing_winding(_handle, (uint64_t)winding);
@@ -1276,42 +1524,71 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
if (!_handle) return;
if (!_vbufs) _vbufs = [NSMutableDictionary dictionary];
if (buffer) _vbufs[@(index)] = buffer; else [_vbufs removeObjectForKey:@(index)];
- if (buffer) [_retained addObject:buffer];
- xm2v_render_encoder_set_vertex_buffer(_handle, buffer ? ((XcmBuffer *)buffer)->_handle : nullptr, offset, (uint32_t)index);
+ Xm2vBuffer *bh = nullptr;
+ if (buffer && [(id)buffer isKindOfClass:[XcmBuffer class]]) {
+ [_cmdBuf retainResource:buffer];
+ bh = ((XcmBuffer *)buffer)->_handle;
+ }
+ if (xcmTraceOn() && index < 32) { if (bh) _tVbufMask |= (1u << index); else _tVbufMask &= ~(1u << index); }
+ xm2v_render_encoder_set_vertex_buffer(_handle, bh, offset, (uint32_t)index);
}
- (void)setVertexBytes:(const void *)bytes length:(NSUInteger)length atIndex:(NSUInteger)index {
+ if (xcmTraceOn() && index < 32) _tVbufMask |= (1u << index);
if (_handle) xm2v_render_encoder_set_vertex_bytes(_handle, bytes, length, (uint32_t)index);
}
- (void)setVertexTexture:(id<MTLTexture>)texture atIndex:(NSUInteger)index {
if (!_handle) return;
+ Xm2vTexture *th = nullptr;
if (texture && [texture isKindOfClass:[XcmTexture class]]) {
- [_retained addObject:texture];
+ [_cmdBuf retainResource:texture];
[(XcmTexture *)texture syncFromIOSurfaceIfNeeded];
+ th = ((XcmTexture *)texture)->_handle;
}
- xm2v_render_encoder_set_vertex_texture(_handle, texture ? ((XcmTexture *)texture)->_handle : nullptr, (uint32_t)index);
+ xm2v_render_encoder_set_vertex_texture(_handle, th, (uint32_t)index);
}
- (void)setVertexSamplerState:(id<MTLSamplerState>)sampler atIndex:(NSUInteger)index {
if (!_handle) return;
- if (sampler) [_retained addObject:sampler];
- xm2v_render_encoder_set_vertex_sampler(_handle, sampler ? ((XcmSampler *)sampler)->_handle : nullptr, (uint32_t)index);
+ Xm2vSampler *sh = nullptr;
+ if (sampler && [(id)sampler isKindOfClass:[XcmSampler class]]) {
+ [_cmdBuf retainResource:sampler];
+ sh = ((XcmSampler *)sampler)->_handle;
+ }
+ xm2v_render_encoder_set_vertex_sampler(_handle, sh, (uint32_t)index);
}
- (void)setFragmentBuffer:(id<MTLBuffer>)buffer offset:(NSUInteger)offset atIndex:(NSUInteger)index {
if (!_handle) return;
if (!_fbufs) _fbufs = [NSMutableDictionary dictionary];
if (buffer) _fbufs[@(index)] = buffer; else [_fbufs removeObjectForKey:@(index)];
- if (buffer) [_retained addObject:buffer];
- xm2v_render_encoder_set_fragment_buffer(_handle, buffer ? ((XcmBuffer *)buffer)->_handle : nullptr, offset, (uint32_t)index);
+ Xm2vBuffer *bh = nullptr;
+ if (buffer && [(id)buffer isKindOfClass:[XcmBuffer class]]) {
+ [_cmdBuf retainResource:buffer];
+ bh = ((XcmBuffer *)buffer)->_handle;
+ }
+ if (xcmTraceOn() && index < 32) { if (bh) _tFbufMask |= (1u << index); else _tFbufMask &= ~(1u << index); }
+ if (!xm2v_render_encoder_set_fragment_buffer(_handle, bh, offset, (uint32_t)index))
+ fprintf(stderr, "XCM setFragmentBuffer(%lu) FAILED: %s\n", (unsigned long)index, xm2v_last_error());
}
- (void)setFragmentBytes:(const void *)bytes length:(NSUInteger)length atIndex:(NSUInteger)index {
+ if (xcmTraceOn()) {
+ if (index < 32) _tFbufMask |= (1u << index);
+ _tFbytesSlot = (uint32_t)index;
+ _tFbytesLen = length;
+ memset(_tFbytesHead, 0, sizeof(_tFbytesHead));
+ if (bytes && length) memcpy(_tFbytesHead, bytes, length < 16 ? length : 16);
+ }
if (_handle) xm2v_render_encoder_set_fragment_bytes(_handle, bytes, length, (uint32_t)index);
}
- (void)setFragmentTexture:(id<MTLTexture>)texture atIndex:(NSUInteger)index {
if (!_handle) return;
+ Xm2vTexture *th = nullptr;
if (texture && [texture isKindOfClass:[XcmTexture class]]) {
- [_retained addObject:texture];
+ [_cmdBuf retainResource:texture];
[(XcmTexture *)texture syncFromIOSurfaceIfNeeded];
+ th = ((XcmTexture *)texture)->_handle;
}
- xm2v_render_encoder_set_fragment_texture(_handle, texture ? ((XcmTexture *)texture)->_handle : nullptr, (uint32_t)index);
+ if (xcmTraceOn() && index < 32) { if (th) _tFtexMask |= (1u << index); else _tFtexMask &= ~(1u << index); }
+ if (!xm2v_render_encoder_set_fragment_texture(_handle, th, (uint32_t)index))
+ fprintf(stderr, "XCM setFragmentTexture(%lu) FAILED: %s\n", (unsigned long)index, xm2v_last_error());
}
- (void)setFragmentTextures:(const id<MTLTexture> *)textures withRange:(NSRange)range {
for (NSUInteger i = 0; i < range.length; i++)
@@ -1319,8 +1596,13 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
- (void)setFragmentSamplerState:(id<MTLSamplerState>)sampler atIndex:(NSUInteger)index {
if (!_handle) return;
- if (sampler) [_retained addObject:sampler];
- xm2v_render_encoder_set_fragment_sampler(_handle, sampler ? ((XcmSampler *)sampler)->_handle : nullptr, (uint32_t)index);
+ Xm2vSampler *sh = nullptr;
+ if (sampler && [(id)sampler isKindOfClass:[XcmSampler class]]) {
+ [_cmdBuf retainResource:sampler];
+ sh = ((XcmSampler *)sampler)->_handle;
+ }
+ if (xcmTraceOn() && index < 32) { if (sh) _tFsampMask |= (1u << index); else _tFsampMask &= ~(1u << index); }
+ xm2v_render_encoder_set_fragment_sampler(_handle, sh, (uint32_t)index);
}
- (void)setFragmentSamplerStates:(const id<MTLSamplerState> *)samplers withRange:(NSRange)range {
for (NSUInteger i = 0; i < range.length; i++)
@@ -1362,7 +1644,7 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
- (void)setVisibilityResultMode:(MTLVisibilityResultMode)mode offset:(NSUInteger)offset { (void)mode; (void)offset; }
- (void)useResource:(id<MTLResource>)r usage:(MTLResourceUsage)u stages:(MTLRenderStages)st {
if (!_handle || !r) return;
- [_retained addObject:r];
+ [_cmdBuf retainResource:r];
if ([r isKindOfClass:[XcmBuffer class]]) {
xm2v_render_encoder_use_buffer(_handle, ((XcmBuffer *)r)->_handle, (uint64_t)u, (uint64_t)st);
} else if ([r isKindOfClass:[XcmTexture class]]) {
@@ -1392,10 +1674,34 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
- (void)memoryBarrierWithResources:(const id<MTLResource> *)resources count:(NSUInteger)count afterStages:(MTLRenderStages)after beforeStages:(MTLRenderStages)before {
(void)resources; (void)count; (void)after; (void)before;
}
+- (void)_traceDraw:(const char *)kind prim:(MTLPrimitiveType)prim start:(NSUInteger)start count:(NSUInteger)count inst:(NSUInteger)inst {
+ if (!xcmTraceOn()) return;
+ char fbHex[40] = "-";
+ if (_tFbytesLen > 0) {
+ size_t n = _tFbytesLen < 16 ? _tFbytesLen : 16;
+ char *p = fbHex;
+ for (size_t i = 0; i < n; i++) p += snprintf(p, 4, "%02x", _tFbytesHead[i]);
+ }
+ fprintf(stderr, "XCM %s(prim=%lu start=%lu cnt=%lu inst=%lu pso=%s/%s blend=%d mask=0x%llx vb=0x%x fb=0x%x ft=0x%x fs=0x%x fbytes[%u]=%lu:%s vp=%.0f,%.0f,%.0fx%.0f sc=%lu,%lu,%lux%lu)\n",
+ kind, (unsigned long)prim, (unsigned long)start, (unsigned long)count, (unsigned long)inst,
+ _curPso && _curPso->_vName ? _curPso->_vName.UTF8String : "?",
+ _curPso && _curPso->_fName ? _curPso->_fName.UTF8String : "?",
+ _curPso ? (int)_curPso->_blendEnabled : -1,
+ _curPso ? (unsigned long long)_curPso->_writeMask : 0ull,
+ _tVbufMask, _tFbufMask, _tFtexMask, _tFsampMask,
+ _tFbytesSlot, (unsigned long)_tFbytesLen, fbHex,
+ _tHasVp ? _tVp.originX : -1.0, _tHasVp ? _tVp.originY : -1.0,
+ _tHasVp ? _tVp.width : 0.0, _tHasVp ? _tVp.height : 0.0,
+ _tHasScissor ? (unsigned long)_tScissor.x : 0ul,
+ _tHasScissor ? (unsigned long)_tScissor.y : 0ul,
+ _tHasScissor ? (unsigned long)_tScissor.width : 0ul,
+ _tHasScissor ? (unsigned long)_tScissor.height : 0ul);
+}
- (void)drawPrimitives:(MTLPrimitiveType)primitiveType vertexStart:(NSUInteger)vertexStart
vertexCount:(NSUInteger)vertexCount instanceCount:(NSUInteger)instanceCount
baseInstance:(NSUInteger)baseInstance {
if (_handle && _hasPipeline) {
+ [self _traceDraw:"draw" prim:primitiveType start:vertexStart count:vertexCount inst:instanceCount];
bool ok = xm2v_render_encoder_draw_primitives(_handle, (uint64_t)primitiveType, vertexStart, vertexCount, instanceCount, baseInstance);
if (!ok) fprintf(stderr, "XCM drawPrimitives FAILED: %s\n", xm2v_last_error());
}
@@ -1407,8 +1713,9 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
indexType:(MTLIndexType)indexType indexBuffer:(id<MTLBuffer>)indexBuffer
indexBufferOffset:(NSUInteger)indexBufferOffset instanceCount:(NSUInteger)instanceCount
baseVertex:(NSInteger)baseVertex baseInstance:(NSUInteger)baseInstance {
- if (!_handle || !_hasPipeline || !indexBuffer) return;
- [_retained addObject:indexBuffer];
+ if (!_handle || !_hasPipeline || !indexBuffer || ![(id)indexBuffer isKindOfClass:[XcmBuffer class]]) return;
+ [self _traceDraw:"drawIdx" prim:primitiveType start:indexBufferOffset count:indexCount inst:instanceCount];
+ [_cmdBuf retainResource:indexBuffer];
bool ok = xm2v_render_encoder_draw_indexed_primitives(_handle, (uint64_t)primitiveType, indexCount, (uint64_t)indexType,
((XcmBuffer *)indexBuffer)->_handle, indexBufferOffset, instanceCount, baseVertex, baseInstance);
if (!ok) fprintf(stderr, "XCM drawIndexedPrimitives FAILED: %s\n", xm2v_last_error());
@@ -1431,8 +1738,22 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
vertexCount:(NSUInteger)vertexCount instanceCount:(NSUInteger)instanceCount {
[self drawPrimitives:primitiveType vertexStart:vertexStart vertexCount:vertexCount instanceCount:instanceCount baseInstance:0];
}
+- (void)updateFence:(id<MTLFence>)fence afterStages:(MTLRenderStages)stages {
+ if (!_handle || !fence || ![(id)fence isKindOfClass:[XcmFence class]]) return;
+ [_cmdBuf retainResource:fence];
+ xm2v_render_encoder_update_fence(_handle, ((XcmFence *)fence)->_handle, (uint64_t)stages);
+}
+- (void)waitForFence:(id<MTLFence>)fence beforeStages:(MTLRenderStages)stages {
+ if (!_handle || !fence || ![(id)fence isKindOfClass:[XcmFence class]]) return;
+ [_cmdBuf retainResource:fence];
+ xm2v_render_encoder_wait_fence(_handle, ((XcmFence *)fence)->_handle, (uint64_t)stages);
+}
- (void)endEncoding {
- if (_handle) { xm2v_render_encoder_end(_handle); _handle = nullptr; }
+ if (_handle) {
+ bool ok = xm2v_render_encoder_end(_handle);
+ if (!ok) fprintf(stderr, "XCM render endEncoding FAILED: %s\n", xm2v_last_error());
+ _handle = nullptr;
+ }
[_retained removeAllObjects];
}
- (void)pushDebugGroup:(NSString *)string { (void)string; }
@@ -1459,17 +1780,17 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
- (id<MTLDevice>)device { return _device; }
- (void)copyFromBuffer:(id<MTLBuffer>)src sourceOffset:(NSUInteger)srcOff
toBuffer:(id<MTLBuffer>)dst destinationOffset:(NSUInteger)dstOff size:(NSUInteger)size {
- if (!_handle || !src || !dst) return;
- [_retained addObject:src]; [_retained addObject:dst];
+ if (!_handle || !src || !dst || ![(id)src isKindOfClass:[XcmBuffer class]] || ![(id)dst isKindOfClass:[XcmBuffer class]]) return;
+ [_cmdBuf retainResource:src]; [_cmdBuf retainResource:dst];
xm2v_blit_encoder_copy_buffer_to_buffer(_handle, ((XcmBuffer *)src)->_handle, srcOff, ((XcmBuffer *)dst)->_handle, dstOff, size);
}
- (void)copyFromBuffer:(id<MTLBuffer>)src sourceOffset:(NSUInteger)srcOff
sourceBytesPerRow:(NSUInteger)bpr sourceBytesPerImage:(NSUInteger)bpi
sourceSize:(MTLSize)sz toTexture:(id<MTLTexture>)dst
destinationSlice:(NSUInteger)slice destinationLevel:(NSUInteger)level destinationOrigin:(MTLOrigin)origin {
- if (!_handle || !src || !dst) return;
- [_retained addObject:src]; [_retained addObject:dst];
- if ([dst isKindOfClass:[XcmTexture class]] && ((XcmTexture *)dst)->_iosurface)
+ if (!_handle || !src || !dst || ![(id)src isKindOfClass:[XcmBuffer class]] || ![(id)dst isKindOfClass:[XcmTexture class]]) return;
+ [_cmdBuf retainResource:src]; [_cmdBuf retainResource:dst];
+ if (((XcmTexture *)dst)->_iosurface)
[_cmdBuf markDirtyIOSurfaceTexture:(XcmTexture *)dst];
xm2v_blit_encoder_copy_buffer_to_texture(_handle, ((XcmBuffer *)src)->_handle, srcOff, bpr, bpi,
sz.width, sz.height, sz.depth, ((XcmTexture *)dst)->_handle, slice, level, origin.x, origin.y, origin.z);
@@ -1477,41 +1798,51 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
- (void)copyFromTexture:(id<MTLTexture>)src sourceSlice:(NSUInteger)slice sourceLevel:(NSUInteger)level
sourceOrigin:(MTLOrigin)origin sourceSize:(MTLSize)sz toBuffer:(id<MTLBuffer>)dst
destinationOffset:(NSUInteger)dstOff destinationBytesPerRow:(NSUInteger)bpr destinationBytesPerImage:(NSUInteger)bpi {
- if (!_handle || !src || !dst) return;
- [_retained addObject:src]; [_retained addObject:dst];
- if ([src isKindOfClass:[XcmTexture class]]) [(XcmTexture *)src syncFromIOSurfaceIfNeeded];
+ if (!_handle || !src || !dst || ![(id)src isKindOfClass:[XcmTexture class]] || ![(id)dst isKindOfClass:[XcmBuffer class]]) return;
+ [_cmdBuf retainResource:src]; [_cmdBuf retainResource:dst];
+ [(XcmTexture *)src syncFromIOSurfaceIfNeeded];
xm2v_blit_encoder_copy_texture_to_buffer(_handle, ((XcmTexture *)src)->_handle, slice, level,
origin.x, origin.y, origin.z, sz.width, sz.height, sz.depth, ((XcmBuffer *)dst)->_handle, dstOff, bpr, bpi);
}
- (void)copyFromTexture:(id<MTLTexture>)src sourceSlice:(NSUInteger)ss sourceLevel:(NSUInteger)sl
sourceOrigin:(MTLOrigin)so sourceSize:(MTLSize)sz toTexture:(id<MTLTexture>)dst
destinationSlice:(NSUInteger)ds destinationLevel:(NSUInteger)dl destinationOrigin:(MTLOrigin)do_ {
- if (!_handle || !src || !dst) return;
- [_retained addObject:src]; [_retained addObject:dst];
- if ([src isKindOfClass:[XcmTexture class]]) [(XcmTexture *)src syncFromIOSurfaceIfNeeded];
- if ([dst isKindOfClass:[XcmTexture class]] && ((XcmTexture *)dst)->_iosurface)
+ if (!_handle || !src || !dst || ![(id)src isKindOfClass:[XcmTexture class]] || ![(id)dst isKindOfClass:[XcmTexture class]]) return;
+ [_cmdBuf retainResource:src]; [_cmdBuf retainResource:dst];
+ [(XcmTexture *)src syncFromIOSurfaceIfNeeded];
+ if (((XcmTexture *)dst)->_iosurface)
[_cmdBuf markDirtyIOSurfaceTexture:(XcmTexture *)dst];
xm2v_blit_encoder_copy_texture_to_texture(_handle, ((XcmTexture *)src)->_handle, ss, sl,
so.x, so.y, so.z, sz.width, sz.height, sz.depth, ((XcmTexture *)dst)->_handle, ds, dl, do_.x, do_.y, do_.z);
}
- (void)fillBuffer:(id<MTLBuffer>)buffer range:(NSRange)range value:(uint8_t)value {
- if (!_handle || !buffer) return;
- [_retained addObject:buffer];
+ if (!_handle || !buffer || ![(id)buffer isKindOfClass:[XcmBuffer class]]) return;
+ [_cmdBuf retainResource:buffer];
xm2v_blit_encoder_fill_buffer(_handle, ((XcmBuffer *)buffer)->_handle, range.location, range.length, value);
}
- (void)generateMipmapsForTexture:(id<MTLTexture>)texture {
- if (!_handle || !texture) return;
- [_retained addObject:texture];
+ if (!_handle || !texture || ![(id)texture isKindOfClass:[XcmTexture class]]) return;
+ [_cmdBuf retainResource:texture];
xm2v_blit_encoder_generate_mipmaps(_handle, ((XcmTexture *)texture)->_handle);
}
- (void)synchronizeResource:(id<MTLResource>)resource {
if (!_handle || !resource) return;
- [_retained addObject:resource];
+ [_cmdBuf retainResource:resource];
if ([resource isKindOfClass:[XcmBuffer class]])
xm2v_blit_encoder_synchronize_buffer(_handle, ((XcmBuffer *)resource)->_handle);
else if ([resource isKindOfClass:[XcmTexture class]])
xm2v_blit_encoder_synchronize_texture(_handle, ((XcmTexture *)resource)->_handle);
}
+- (void)updateFence:(id<MTLFence>)fence {
+ if (!_handle || !fence || ![(id)fence isKindOfClass:[XcmFence class]]) return;
+ [_cmdBuf retainResource:fence];
+ xm2v_blit_encoder_update_fence(_handle, ((XcmFence *)fence)->_handle);
+}
+- (void)waitForFence:(id<MTLFence>)fence {
+ if (!_handle || !fence || ![(id)fence isKindOfClass:[XcmFence class]]) return;
+ [_cmdBuf retainResource:fence];
+ xm2v_blit_encoder_wait_fence(_handle, ((XcmFence *)fence)->_handle);
+}
- (void)endEncoding {
if (_handle) { xm2v_blit_encoder_end(_handle); _handle = nullptr; }
[_retained removeAllObjects];
@@ -1532,15 +1863,28 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
_scheduledHandlers = [NSMutableArray array];
_completedHandlers = [NSMutableArray array];
_dirtyIOSurfaceTextures = [NSMutableArray array];
+ _retainedResources = [NSMutableArray array];
+ _handlersGroup = dispatch_group_create();
}
return self;
}
- (void)dealloc { if (_handle) { xm2v_command_buffer_release(_handle); _handle = nullptr; } }
+- (void)retainResource:(id)obj {
+ if (!obj) return;
+ @synchronized(self) {
+ if (!_retainedReleased) [_retainedResources addObject:obj];
+ }
+}
- (void)markDirtyIOSurfaceTexture:(XcmTexture *)tex {
- if (tex && tex->_iosurface && ![_dirtyIOSurfaceTextures containsObject:tex]) {
- [_dirtyIOSurfaceTextures addObject:tex];
- xcmRecordIOSurfaceWriter(tex->_iosurface, self);
+ if (!tex || !tex->_iosurface) return;
+ BOOL added = NO;
+ @synchronized(self) {
+ if (!_iosurfaceFlushed && ![_dirtyIOSurfaceTextures containsObject:tex]) {
+ [_dirtyIOSurfaceTextures addObject:tex];
+ added = YES;
+ }
}
+ if (added) xcmRecordIOSurfaceWriter(tex->_iosurface, self);
}
- (id<MTLDevice>)device { return _device; }
- (id<MTLCommandQueue>)commandQueue { return _queue; }
@@ -1555,16 +1899,28 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
return _handle ? (MTLCommandBufferStatus)xm2v_command_buffer_status(_handle) : MTLCommandBufferStatusError;
}
- (NSError *)error {
- if (self.status == MTLCommandBufferStatusError)
+ if (self.status == MTLCommandBufferStatusError) {
+ char buf[512] = {};
+ if (_handle && xm2v_command_buffer_error(_handle, buf, sizeof(buf)) > 0) {
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: command buffer error (cb=%p): %{public}s", (__bridge void *)self, buf);
+ return xcmError(MTLCommandBufferErrorDomain, MTLCommandBufferErrorInternal, buf);
+ }
return xcmError(MTLCommandBufferErrorDomain, MTLCommandBufferErrorInternal, "Command buffer failed");
+ }
return nil;
}
- (void)enqueue {}
- (void)addScheduledHandler:(MTLCommandBufferHandler)block {
- if (block) [_scheduledHandlers addObject:[block copy]];
+ if (!block) return;
+ @synchronized(self) {
+ if (!_handlersFired) [_scheduledHandlers addObject:[block copy]];
+ }
}
- (void)addCompletedHandler:(MTLCommandBufferHandler)block {
- if (block) [_completedHandlers addObject:[block copy]];
+ if (!block) return;
+ @synchronized(self) {
+ if (!_handlersFired) [_completedHandlers addObject:[block copy]];
+ }
}
- (void)_flushIOSurfacesOnce {
@synchronized(self) {
@@ -1575,37 +1931,101 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
}
- (void)_fireHandlersOnce {
+ NSArray<MTLCommandBufferHandler> *sched = nil;
+ NSArray<MTLCommandBufferHandler> *comp = nil;
+ BOOL shouldRun = NO;
@synchronized(self) {
- if (_handlersFired) return;
- _handlersFired = YES;
- NSArray<MTLCommandBufferHandler> *sched = [_scheduledHandlers copy];
- NSArray<MTLCommandBufferHandler> *comp = [_completedHandlers copy];
- [_scheduledHandlers removeAllObjects];
- [_completedHandlers removeAllObjects];
+ if (!_handlersFired) {
+ _handlersFired = YES;
+ sched = [_scheduledHandlers copy];
+ comp = [_completedHandlers copy];
+ [_scheduledHandlers removeAllObjects];
+ [_completedHandlers removeAllObjects];
+ if (sched.count || comp.count) {
+ shouldRun = YES;
+ _handlersThread = pthread_self();
+ dispatch_group_enter(_handlersGroup);
+ }
+ }
+ }
+ if (shouldRun) {
for (MTLCommandBufferHandler h in sched) h((id<MTLCommandBuffer>)self);
for (MTLCommandBufferHandler h in comp) h((id<MTLCommandBuffer>)self);
+ @synchronized(self) {
+ _handlersThread = nullptr;
+ }
+ dispatch_group_leave(_handlersGroup);
+ } else {
+ BOOL isSameThread = NO;
+ @synchronized(self) {
+ isSameThread = (_handlersThread != nullptr && pthread_equal(_handlersThread, pthread_self()) != 0);
+ }
+ if (!isSameThread) {
+ dispatch_group_wait(_handlersGroup, DISPATCH_TIME_FOREVER);
+ }
+ }
+}
+- (void)_releaseRetainedResourcesOnce {
+ NSArray *toRelease = nil;
+ @synchronized(self) {
+ if (_retainedReleased) return;
+ _retainedReleased = YES;
+ toRelease = [_retainedResources copy];
+ [_retainedResources removeAllObjects];
+ }
+ if (toRelease.count && _handle &&
+ (MTLCommandBufferStatus)xm2v_command_buffer_status(_handle) == MTLCommandBufferStatusError) {
+ char ebuf[256] = {};
+ if (xm2v_command_buffer_error(_handle, ebuf, sizeof(ebuf)) > 0 &&
+ (strstr(ebuf, "GpuHang") || strstr(ebuf, "DeviceLost"))) {
+ // Driver may still be executing in-flight draws on a parked device; keep resources alive
+ // rather than running fallback deallocators or freeing backing memory under lavapipe.
+ static NSMutableArray *gParkedResources;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ gParkedResources = [NSMutableArray array]; });
+ @synchronized(gParkedResources) { [gParkedResources addObjectsFromArray:toRelease]; }
+ return;
+ }
}
+ (void)toRelease;
}
- (void)commit {
- if (xcmTraceOn()) fprintf(stderr, "XCM commit cb=%p sched=%lu comp=%lu dirty=%lu\n",
- (__bridge void *)self, (unsigned long)_scheduledHandlers.count,
- (unsigned long)_completedHandlers.count, (unsigned long)_dirtyIOSurfaceTextures.count);
+ BOOL needsWait = NO;
+ NSUInteger nSched = 0, nComp = 0, nDirty = 0, nRet = 0;
+ @synchronized(self) {
+ if (_committed) return;
+ _committed = YES;
+ nSched = _scheduledHandlers.count;
+ nComp = _completedHandlers.count;
+ nDirty = _dirtyIOSurfaceTextures.count;
+ nRet = _retainedResources.count;
+ needsWait = (nSched || nComp || nDirty || nRet);
+ }
+ if (xcmTraceOn()) fprintf(stderr, "XCM commit cb=%p sched=%lu comp=%lu dirty=%lu ret=%lu\n",
+ (__bridge void *)self, (unsigned long)nSched,
+ (unsigned long)nComp, (unsigned long)nDirty, (unsigned long)nRet);
if (_handle) {
bool ok = xm2v_command_buffer_commit(_handle);
if (!ok) fprintf(stderr, "XCM commit FAILED cb=%p err=%s\n", (__bridge void *)self, xm2v_last_error());
}
- if (_scheduledHandlers.count || _completedHandlers.count || _dirtyIOSurfaceTextures.count) {
+ if (needsWait) {
static dispatch_queue_t waitQ;
static dispatch_once_t once;
dispatch_once(&once, ^{ waitQ = dispatch_queue_create("xcm.cb.wait", DISPATCH_QUEUE_CONCURRENT); });
dispatch_async(waitQ, ^{
if (_handle) {
- bool wok = xm2v_command_buffer_wait_until_completed(_handle, 60000);
- if (!wok) fprintf(stderr, "XCM wait FAILED cb=%p status=%u err=%s\n",
- (__bridge void *)self, xm2v_command_buffer_status(_handle), xm2v_last_error());
+ bool wok = xm2v_command_buffer_wait_until_completed(_handle, 0);
+ uint32_t st = xm2v_command_buffer_status(_handle);
+ if (!wok || xcmTraceOn()) {
+ char ebuf[256] = {};
+ if (!wok) xm2v_command_buffer_error(_handle, ebuf, sizeof(ebuf));
+ fprintf(stderr, "XCM cb-done cb=%p wok=%d status=%u err=%s\n",
+ (__bridge void *)self, wok, st, ebuf[0] ? ebuf : (wok ? "ok" : xm2v_last_error()));
+ }
}
[self _flushIOSurfacesOnce];
[self _fireHandlersOnce];
+ [self _releaseRetainedResourcesOnce];
});
}
}
@@ -1616,9 +2036,10 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
[self waitUntilCompleted];
}
- (void)waitUntilCompleted {
- if (_handle) xm2v_command_buffer_wait_until_completed(_handle, 60000);
+ if (_handle) xm2v_command_buffer_wait_until_completed(_handle, 0);
[self _flushIOSurfacesOnce];
[self _fireHandlersOnce];
+ [self _releaseRetainedResourcesOnce];
}
- (id<MTLComputeCommandEncoder>)computeCommandEncoder {
if (!_handle) return nil;
@@ -1638,6 +2059,7 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
MTLRenderPassColorAttachmentDescriptor *ca = desc.colorAttachments[i];
if (ca && ca.texture && [ca.texture isKindOfClass:[XcmTexture class]]) {
XcmTexture *xt = (XcmTexture *)ca.texture;
+ [self retainResource:xt];
if (ca.loadAction == MTLLoadActionLoad) [xt syncFromIOSurfaceIfNeeded];
if (xt->_iosurface && ca.storeAction != MTLStoreActionDontCare)
[self markDirtyIOSurfaceTexture:xt];
@@ -1653,19 +2075,30 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
}
}
if (desc.depthAttachment.texture && [desc.depthAttachment.texture isKindOfClass:[XcmTexture class]]) {
+ [self retainResource:desc.depthAttachment.texture];
rd.depth_texture = ((XcmTexture *)desc.depthAttachment.texture)->_handle;
rd.depth_load_action = (uint64_t)desc.depthAttachment.loadAction;
rd.depth_store_action = (uint64_t)desc.depthAttachment.storeAction;
rd.clear_depth = desc.depthAttachment.clearDepth;
}
if (desc.stencilAttachment.texture && [desc.stencilAttachment.texture isKindOfClass:[XcmTexture class]]) {
+ [self retainResource:desc.stencilAttachment.texture];
rd.stencil_texture = ((XcmTexture *)desc.stencilAttachment.texture)->_handle;
rd.stencil_load_action = (uint64_t)desc.stencilAttachment.loadAction;
rd.stencil_store_action = (uint64_t)desc.stencilAttachment.storeAction;
rd.clear_stencil = desc.stencilAttachment.clearStencil;
}
Xm2vRenderEncoder *eh = xm2v_render_encoder_new(_handle, &rd);
- if (xcmTraceOn()) fprintf(stderr, "XCM renderEncoder -> %p\n", (void *)eh);
+ if (xcmTraceOn()) {
+ MTLRenderPassColorAttachmentDescriptor *ca0 = desc.colorAttachments[0];
+ id t0 = ca0 ? ca0.texture : nil;
+ fprintf(stderr, "XCM renderEncoder -> %p c0=%p(%lux%lu load=%lu store=%lu clear=%.2f,%.2f,%.2f,%.2f) d=%p s=%p\n",
+ (void *)eh, (__bridge void *)t0,
+ t0 ? (unsigned long)[t0 width] : 0ul, t0 ? (unsigned long)[t0 height] : 0ul,
+ ca0 ? (unsigned long)ca0.loadAction : 0ul, ca0 ? (unsigned long)ca0.storeAction : 0ul,
+ ca0 ? ca0.clearColor.red : 0.0, ca0 ? ca0.clearColor.green : 0.0,
+ ca0 ? ca0.clearColor.blue : 0.0, ca0 ? ca0.clearColor.alpha : 0.0, (__bridge void *)desc.depthAttachment.texture, (__bridge void *)desc.stencilAttachment.texture);
+ }
return eh ? (id<MTLRenderCommandEncoder>)[[XcmRenderEncoder alloc] initWithHandle:eh device:_device commandBuffer:self] : nil;
}
- (id<MTLBlitCommandEncoder>)blitCommandEncoder {
@@ -1674,12 +2107,35 @@ static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
return eh ? (id<MTLBlitCommandEncoder>)[[XcmBlitEncoder alloc] initWithHandle:eh device:_device commandBuffer:self] : nil;
}
- (void)encodeSignalEvent:(id<MTLEvent>)event value:(uint64_t)value {
- if (_handle && [event isKindOfClass:[XcmEvent class]])
- xm2v_command_buffer_encode_signal_event(_handle, ((XcmEvent *)event)->_handle, value);
+ if (!_handle || !event) return;
+ [self retainResource:event];
+ if ([event isKindOfClass:[XcmSharedEvent class]]) {
+ if (!xm2v_command_buffer_encode_signal_shared_event(_handle, ((XcmSharedEvent *)event)->_handle, value))
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: encodeSignalEvent(shared) failed: %{public}s", xm2v_last_error() ?: "?");
+ } else if ([event isKindOfClass:[XcmEvent class]]) {
+ if (!xm2v_command_buffer_encode_signal_event(_handle, ((XcmEvent *)event)->_handle, value))
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: encodeSignalEvent failed: %{public}s", xm2v_last_error() ?: "?");
+ }
+}
+- (void)encodeSignalEventScheduled:(id<MTLEvent>)event value:(uint64_t)value {
+ if (!_handle || !event) return;
+ [self retainResource:event];
+ if ([event isKindOfClass:[XcmSharedEvent class]]) {
+ xm2v_command_buffer_encode_signal_shared_event_scheduled(_handle, ((XcmSharedEvent *)event)->_handle, value);
+ } else if ([event isKindOfClass:[XcmEvent class]]) {
+ xm2v_command_buffer_encode_signal_event_scheduled(_handle, ((XcmEvent *)event)->_handle, value);
+ }
}
- (void)encodeWaitForEvent:(id<MTLEvent>)event value:(uint64_t)value {
- if (_handle && [event isKindOfClass:[XcmEvent class]])
- xm2v_command_buffer_encode_wait_event(_handle, ((XcmEvent *)event)->_handle, value);
+ if (!_handle || !event) return;
+ [self retainResource:event];
+ if ([event isKindOfClass:[XcmSharedEvent class]]) {
+ if (!xm2v_command_buffer_encode_wait_shared_event(_handle, ((XcmSharedEvent *)event)->_handle, value))
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: encodeWaitForEvent(shared) failed: %{public}s", xm2v_last_error() ?: "?");
+ } else if ([event isKindOfClass:[XcmEvent class]]) {
+ if (!xm2v_command_buffer_encode_wait_event(_handle, ((XcmEvent *)event)->_handle, value))
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: encodeWaitForEvent failed: %{public}s", xm2v_last_error() ?: "?");
+ }
}
- (void)pushDebugGroup:(NSString *)string { (void)string; }
- (void)popDebugGroup {}
@@ -1738,8 +2194,8 @@ static NSString *xcmDev_name(id, SEL) {
return @"XnuCpuMetal (lavapipe)";
}
static uint64_t xcmDev_registryID(id, SEL) { return gRegistryID; }
-static BOOL xcmDev_isLowPower(id, SEL) { return YES; }
-static BOOL xcmDev_isHeadless(id, SEL) { return YES; }
+static BOOL xcmDev_isLowPower(id, SEL) { return NO; }
+static BOOL xcmDev_isHeadless(id, SEL) { return NO; }
static BOOL xcmDev_isRemovable(id, SEL) { return NO; }
static BOOL xcmDev_hasUnifiedMemory(id, SEL) { return YES; }
static NSUInteger xcmDev_maxBufferLength(id, SEL) {
@@ -1763,7 +2219,17 @@ static BOOL xcmDev_yes(id, SEL) { return YES; }
static BOOL xcmDev_supportsSampleCount(id, SEL, NSUInteger c) { return c == 1; }
static BOOL xcmDev_supportsFeatureSet(id, SEL, NSUInteger) { return YES; }
static BOOL xcmDev_supportsFamily(id, SEL, MTLGPUFamily family) {
- return gXm2vDevice ? xm2v_device_supports_family(gXm2vDevice, (int64_t)family) : NO;
+ if (gXm2vDevice && xm2v_device_supports_family(gXm2vDevice, (int64_t)family)) return YES;
+ // Report Apple1/Apple2, Mac1/Mac2, Common1..3 so QuartzCore enables framebuffer fetch (programmable blending)
+ // and standard macOS/Apple GPU paths that lavapipe + metal2vulkan support.
+ switch ((int64_t)family) {
+ case 1001: case 1002: // MTLGPUFamilyApple1..Apple2
+ case 2001: case 2002: // MTLGPUFamilyMac1..Mac2
+ case 3001: case 3002: case 3003: // MTLGPUFamilyCommon1..Common3
+ return YES;
+ default:
+ return NO;
+ }
}
static id xcmDev_newCommandQueue(id self, SEL) NS_RETURNS_RETAINED;
@@ -1790,6 +2256,9 @@ static id xcmDev_newRenderPSOOpts(id self, SEL, MTLRenderPipelineDescriptor *, M
static id xcmDev_newSampler(id self, SEL, MTLSamplerDescriptor *) NS_RETURNS_RETAINED;
static id xcmDev_newDepthStencil(id self, SEL, MTLDepthStencilDescriptor *) NS_RETURNS_RETAINED;
static id xcmDev_newEvent(id self, SEL) NS_RETURNS_RETAINED;
+static id xcmDev_newSharedEvent(id self, SEL) NS_RETURNS_RETAINED;
+static id xcmDev_newSharedEventOpts(id self, SEL, NSUInteger) NS_RETURNS_RETAINED;
+static id xcmDev_newSharedEventWithHandle(id self, SEL, MTLSharedEventHandle *) NS_RETURNS_RETAINED;
static id xcmDev_newFence(id self, SEL) NS_RETURNS_RETAINED;
static id xcmDev_newHeap(id self, SEL, MTLHeapDescriptor *) NS_RETURNS_RETAINED;
@@ -1802,22 +2271,41 @@ static id xcmDev_newCommandQueueMax(id self, SEL, NSUInteger) {
return xcmDev_newCommandQueue(self, nullptr);
}
static id xcmDev_newBufferLen(id self, SEL, NSUInteger length, MTLResourceOptions opts) {
- if (!gXm2vDevice) return nil;
+ if (!gXm2vDevice || length == 0) return nil;
Xm2vBuffer *b = xm2v_buffer_new(gXm2vDevice, length, opts, nullptr);
if (xcmTraceOn()) fprintf(stderr, "XCM newBufferLen(%lu, 0x%lx) -> %p\n", (unsigned long)length, (unsigned long)opts, (void *)b);
return b ? [[XcmBuffer alloc] initWithHandle:b device:self options:opts] : nil;
}
static id xcmDev_newBufferBytes(id self, SEL, const void *pointer, NSUInteger length, MTLResourceOptions opts) {
- if (!gXm2vDevice) return nil;
+ if (!gXm2vDevice || !pointer || length == 0) return nil;
Xm2vBuffer *b = xm2v_buffer_new(gXm2vDevice, length, opts, pointer);
return b ? [[XcmBuffer alloc] initWithHandle:b device:self options:opts] : nil;
}
+static void xcmBufferDeallocCallback(void *ptr, uint64_t length, void *ctx) {
+ if (!ctx) return;
+ void (^block)(void *, NSUInteger) = (__bridge_transfer void (^)(void *, NSUInteger))ctx;
+ block(ptr, (NSUInteger)length);
+}
static id xcmDev_newBufferNoCopy(id self, SEL, void *pointer, NSUInteger length, MTLResourceOptions opts, void (^deallocator)(void *, NSUInteger)) {
- (void)deallocator;
- if (!gXm2vDevice) return nil;
- Xm2vBuffer *b = xm2v_buffer_new_no_copy(gXm2vDevice, pointer, length, opts);
- if (!b) b = xm2v_buffer_new(gXm2vDevice, length, opts, pointer);
- return b ? [[XcmBuffer alloc] initWithHandle:b device:self options:opts] : nil;
+ // Match real macOS Metal: NULL pointer or 0 length returns nil without invoking deallocator.
+ if (!gXm2vDevice || !pointer || length == 0) return nil;
+ void *ctx = deallocator ? (__bridge_retained void *)[deallocator copy] : nullptr;
+ Xm2vBuffer *b = xm2v_buffer_new_no_copy_dealloc(gXm2vDevice, pointer, length, opts,
+ ctx ? xcmBufferDeallocCallback : nullptr, ctx);
+ if (!b) {
+ if (ctx) (void)(__bridge_transfer id)ctx;
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: newBufferWithBytesNoCopy failed (ptr=%p len=%lu opts=0x%lx), falling back to copy: %{public}s",
+ pointer, (unsigned long)length, (unsigned long)opts, xm2v_last_error() ?: "?");
+ b = xm2v_buffer_new(gXm2vDevice, length, opts, pointer);
+ if (!b) return nil;
+ XcmBuffer *buf = [[XcmBuffer alloc] initWithHandle:b device:self options:opts];
+ if (buf && deallocator) {
+ buf->_fallbackDeallocator = [deallocator copy];
+ buf->_fallbackPtr = pointer;
+ }
+ return buf;
+ }
+ return [[XcmBuffer alloc] initWithHandle:b device:self options:opts];
}
static id xcmDev_newTexture(id self, SEL, MTLTextureDescriptor *desc) {
if (!gXm2vDevice || !desc) return nil;
@@ -1862,6 +2350,22 @@ static id xcmDev_newTextureIOSurfaceSlice(id self, SEL, MTLTextureDescriptor *de
(void)slice;
return xcmDev_newTextureIOSurface(self, nullptr, desc, surface, plane);
}
+static id xcmDev_newLibraryFromNSData(id self, NSData *nsdata, const char *origin, NSError **error) {
+ if (!gXm2vDevice || !nsdata || nsdata.length == 0) {
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: newLibrary empty (origin=%{public}s data=%p len=%lu)",
+ origin ?: "?", (__bridge void *)nsdata, (unsigned long)nsdata.length);
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "empty library data");
+ return nil;
+ }
+ Xm2vLibrary *lib = xm2v_library_new_with_data(gXm2vDevice, nsdata.bytes, nsdata.length);
+ if (!lib) {
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: xm2v_library_new_with_data failed (origin=%{public}s len=%lu): %{public}s",
+ origin ?: "?", (unsigned long)nsdata.length, xm2v_last_error() ?: "?");
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Library load failed");
+ return nil;
+ }
+ return [[XcmLibrary alloc] initWithHandle:lib device:self data:nsdata];
+}
static id xcmDev_newLibraryWithData(id self, SEL, dispatch_data_t data, NSError **error) {
if (!gXm2vDevice || !data) {
if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Null library data");
@@ -1870,20 +2374,39 @@ static id xcmDev_newLibraryWithData(id self, SEL, dispatch_data_t data, NSError
const void *buf = nullptr;
size_t len = 0;
dispatch_data_t contig = dispatch_data_create_map(data, &buf, &len);
- NSData *nsCopy = (buf && len) ? [NSData dataWithBytes:buf length:len] : nil;
- Xm2vLibrary *lib = xm2v_library_new_with_data(gXm2vDevice, buf, len);
- (void)contig;
- if (!lib) {
- if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Library load failed");
- return nil;
+ NSData *nsdata = nil;
+ if (contig && buf && len > 0) {
+ // dispatch_data_t is toll-free bridged to NSData; avoid copying 187 MB default.metallib into dirty heap.
+ nsdata = (NSData *)contig;
+ } else {
+ size_t total = dispatch_data_get_size(data);
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: newLibraryWithData map returned empty (data=%p cls=%{public}s total=%zu buf=%p len=%zu)",
+ (__bridge void *)data, object_getClassName((id)data), total, buf, len);
+ if (total > 0) {
+ NSMutableData *flat = [NSMutableData dataWithCapacity:total];
+ if (flat) {
+ dispatch_data_apply(data, ^bool(dispatch_data_t, size_t, const void *ptr, size_t sz) {
+ [flat appendBytes:ptr length:sz];
+ return true;
+ });
+ nsdata = flat;
+ }
+ }
}
- return [[XcmLibrary alloc] initWithHandle:lib device:self data:nsCopy];
+ return xcmDev_newLibraryFromNSData(self, nsdata, "dispatch_data", error);
}
static id xcmDev_newLibraryWithURL(id self, SEL, NSURL *url, NSError **error) {
- NSData *nsdata = [NSData dataWithContentsOfURL:url options:0 error:error];
- if (!nsdata) return nil;
- dispatch_data_t d = dispatch_data_create(nsdata.bytes, nsdata.length, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
- return xcmDev_newLibraryWithData(self, nullptr, d, error);
+ if (!url) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorFileNotFound, "Nil library URL");
+ return nil;
+ }
+ NSData *nsdata = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:error];
+ if (!nsdata) {
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: newLibraryWithURL read failed (url=%{public}s): %{public}s",
+ url.path.UTF8String ?: "?", (error && *error) ? (*error).localizedDescription.UTF8String : "?");
+ return nil;
+ }
+ return xcmDev_newLibraryFromNSData(self, nsdata, url.path.UTF8String ?: "url", error);
}
static id xcmDev_newLibraryWithFile(id self, SEL, NSString *filepath, NSError **error) {
return xcmDev_newLibraryWithURL(self, nullptr, [NSURL fileURLWithPath:filepath], error);
@@ -1964,8 +2487,7 @@ static id xcmDev_newLibraryWithSource(id self, SEL, NSString *source, MTLCompile
userInfo:@{NSLocalizedDescriptionKey: failure ?: @"Metal source compilation failed"}];
return nil;
}
- dispatch_data_t data = dispatch_data_create(metallib.bytes, metallib.length, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
- id<MTLLibrary> lib = xcmDev_newLibraryWithData(self, nullptr, data, error);
+ id<MTLLibrary> lib = xcmDev_newLibraryFromNSData(self, metallib, "source", error);
if (lib && warnings.length && error)
*error = [NSError errorWithDomain:MTLLibraryErrorDomain code:MTLLibraryErrorCompileWarning
userInfo:@{NSLocalizedDescriptionKey: warnings}];
@@ -2024,8 +2546,7 @@ static id xcmDev_newLibraryWithStitched(id self, SEL, MTLStitchedLibraryDescript
userInfo:@{NSLocalizedDescriptionKey: failure ?: @"Stitched library compilation failed"}];
return nil;
}
- dispatch_data_t data = dispatch_data_create(metallib.bytes, metallib.length, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
- return xcmDev_newLibraryWithData(self, nullptr, data, error);
+ return xcmDev_newLibraryFromNSData(self, metallib, "stitched", error);
}
static id xcmDev_newLibraryWithStitchedArchive(id self, SEL, MTLStitchedLibraryDescriptor *d, id, NSError **error) {
return xcmDev_newLibraryWithStitched(self, nullptr, d, error);
@@ -2250,11 +2771,16 @@ static id xcmDev_newRenderPSO(id self, SEL, MTLRenderPipelineDescriptor *desc, N
break;
}
if (xcmTraceOn() || !pso) {
- fprintf(stderr, "XCM newRenderPSO(v=%s,f=%s, vl=%zu+%zu, fl=%zu+%zu, fLinkedObj=%p) -> %p err=%s\n",
+ const auto &c0 = rd.color_attachments[0];
+ fprintf(stderr, "XCM newRenderPSO(v=%s,f=%s, fmt0=%llu blend=%d[op=%llu/%llu rgb=%llu,%llu a=%llu,%llu] mask=0x%llx, vl=%zu+%zu, fl=%zu+%zu) -> %p err=%s\n",
desc.vertexFunction.name.UTF8String ?: "?",
desc.fragmentFunction.name.UTF8String ?: "-",
+ (unsigned long long)c0.pixel_format, (int)c0.blending_enabled,
+ (unsigned long long)c0.rgb_blend_op, (unsigned long long)c0.alpha_blend_op,
+ (unsigned long long)c0.src_rgb_blend, (unsigned long long)c0.dst_rgb_blend,
+ (unsigned long long)c0.src_alpha_blend, (unsigned long long)c0.dst_alpha_blend,
+ (unsigned long long)c0.write_mask,
vPub.size(), vPriv.size(), fPub.size(), fPriv.size(),
- (__bridge void *)desc.fragmentLinkedFunctions,
(void *)pso, pso ? "ok" : xm2v_last_error());
if (!pso && !vattrs.empty()) {
fprintf(stderr, " vattrs(%zu):", vattrs.size());
@@ -2280,7 +2806,14 @@ static id xcmDev_newRenderPSO(id self, SEL, MTLRenderPipelineDescriptor *desc, N
if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Render PSO failed");
return nil;
}
- return [[XcmRenderPipeline alloc] initWithHandle:pso device:self];
+ XcmRenderPipeline *rp = [[XcmRenderPipeline alloc] initWithHandle:pso device:self];
+ if (rp) {
+ rp->_vName = [desc.vertexFunction.name copy];
+ rp->_fName = [desc.fragmentFunction.name copy];
+ rp->_blendEnabled = rd.color_attachments[0].blending_enabled ? YES : NO;
+ rp->_writeMask = rd.color_attachments[0].write_mask;
+ }
+ return rp;
}
static id xcmDev_newRenderPSOOpts(id self, SEL, MTLRenderPipelineDescriptor *desc, MTLPipelineOption, MTLRenderPipelineReflection **refl, NSError **error) {
if (refl) *refl = nil;
@@ -2328,6 +2861,22 @@ static id xcmDev_newEvent(id self, SEL) {
Xm2vEvent *ev = xm2v_event_new(gXm2vDevice);
return ev ? [[XcmEvent alloc] initWithHandle:ev device:self] : nil;
}
+static id xcmDev_newSharedEvent(id self, SEL) {
+ (void)self;
+ if (!gXm2vDevice) return nil;
+ Xm2vSharedEvent *ev = xm2v_shared_event_new(gXm2vDevice);
+ return ev ? [[XcmSharedEvent alloc] initWithHandle:ev] : nil;
+}
+static id xcmDev_newSharedEventOpts(id self, SEL, NSUInteger options) {
+ (void)options;
+ return xcmDev_newSharedEvent(self, nullptr);
+}
+static id xcmDev_newSharedEventWithHandle(id self, SEL, MTLSharedEventHandle *handle) {
+ (void)self;
+ if (!gXm2vDevice || !handle || ![(id)handle isKindOfClass:[XcmSharedEventHandle class]]) return nil;
+ Xm2vSharedEvent *ev = xm2v_shared_event_new_with_handle(gXm2vDevice, ((XcmSharedEventHandle *)handle)->_handle);
+ return ev ? [[XcmSharedEvent alloc] initWithHandle:ev] : nil;
+}
static id xcmDev_newFence(id self, SEL) {
if (!gXm2vDevice) return nil;
Xm2vFence *f = xm2v_fence_new(gXm2vDevice);
@@ -2372,6 +2921,54 @@ static id xcmDev_targetDeviceArchitecture(id, SEL) {
}
static MTLArgumentBuffersTier xcmDev_argBufTier(id, SEL) { return MTLArgumentBuffersTier2; }
+static BOOL xcmDev_no(id, SEL) { return NO; }
+static void xcmDev_noop(id, SEL) {}
+static void xcmDev_noopBool(id, SEL, BOOL) {}
+static void xcmDev_noopReserve(id, SEL, NSUInteger, NSUInteger *, NSUInteger) {}
+static NSUInteger xcmDev_zeroU(id, SEL) { return 0; }
+static NSUInteger xcmDev_zeroU1(id, SEL, NSUInteger) { return 0; }
+static NSUInteger xcmDev_singleFPConfig(id, SEL) { return 0x54; }
+static NSUInteger xcmDev_halfFPConfig(id, SEL) { return 0xe; }
+static NSUInteger xcmDev_maxViewportCount(id, SEL) { return 16; }
+static NSUInteger xcmDev_maxArgBufSamplers(id, SEL) { return 16; }
+static MTLSize xcmDev_sparseTileSize(id, SEL, MTLTextureType, MTLPixelFormat, NSUInteger) { return MTLSizeMake(0, 0, 0); }
+static MTLSize xcmDev_sparseTileSizePage(id, SEL, MTLTextureType, MTLPixelFormat, NSUInteger, NSInteger) { return MTLSizeMake(0, 0, 0); }
+static MTLSize xcmDev_tileSizeSparse(id, SEL, NSInteger, MTLTextureType, MTLPixelFormat, NSUInteger) { return MTLSizeMake(0, 0, 0); }
+static id xcmDev_nil1(id, SEL, id) { return nil; }
+static id xcmDev_nilPtr1(id, SEL, void *) { return nil; }
+static id xcmDev_nil2(id, SEL, id, BOOL) { return nil; }
+static id xcmDev_nilResGrp(id, SEL, const id *, NSUInteger) { return nil; }
+static id xcmDev_nilICB(id, SEL, id, NSUInteger, MTLResourceOptions) { return nil; }
+static id xcmDev_nilTexNoCopy(id, SEL, void *, NSUInteger, id, id) { return nil; }
+static BOOL xcmDev_noMapSample(id, SEL, void *, NSUInteger, NSUInteger) { return NO; }
+static id xcmDev_newTilePSO(id, SEL, id, NSError **error) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorUnsupported, "Tile render pipelines not supported on CPU device");
+ return nil;
+}
+static void xcmDev_newTilePSOAsync(id self, SEL, id desc, void (^handler)(id, NSError *)) {
+ NSError *err = nil;
+ id pso = xcmDev_newTilePSO(self, nullptr, desc, &err);
+ if (handler) handler(pso, err);
+}
+static id xcmDev_newBufferWithDescriptor(id self, SEL, id desc) NS_RETURNS_RETAINED;
+static id xcmDev_newBufferWithDescriptor(id self, SEL, id desc) {
+ if (!gXm2vDevice || !desc) return nil;
+ NSUInteger len = [desc respondsToSelector:@selector(length)] ? ((NSUInteger (*)(id, SEL))objc_msgSend)(desc, @selector(length)) : 0;
+ if (len == 0) return nil;
+ MTLResourceOptions opts = [desc respondsToSelector:@selector(resourceOptions)]
+ ? ((MTLResourceOptions (*)(id, SEL))objc_msgSend)(desc, @selector(resourceOptions)) : MTLResourceStorageModeShared;
+ void *contents = [desc respondsToSelector:@selector(contents)] ? ((void *(*)(id, SEL))objc_msgSend)(desc, @selector(contents)) : nullptr;
+ BOOL noCopy = [desc respondsToSelector:@selector(noCopy)] ? ((BOOL (*)(id, SEL))objc_msgSend)(desc, @selector(noCopy)) : NO;
+ if (contents && noCopy) {
+ typedef void (^XcmBufDealloc)(void *, NSUInteger);
+ XcmBufDealloc dealloc = nil;
+ if ([desc respondsToSelector:@selector(deallocator)])
+ dealloc = ((XcmBufDealloc (*)(id, SEL))objc_msgSend)(desc, @selector(deallocator));
+ return xcmDev_newBufferNoCopy(self, nullptr, contents, len, opts, dealloc);
+ }
+ if (contents) return xcmDev_newBufferBytes(self, nullptr, contents, len, opts);
+ return xcmDev_newBufferLen(self, nullptr, len, opts);
+}
static Class createBackendDeviceClass(void) {
static Class cls = nil;
@@ -2401,6 +2998,8 @@ static Class createBackendDeviceClass(void) {
{"maxTextureDepth3D", (IMP)xcmDev_maxTex3D, "Q16@0:8"},
{"maxTextureLayers", (IMP)xcmDev_maxTexLayers, "Q16@0:8"},
{"maxColorAttachments", (IMP)xcmDev_maxColorAtt, "Q16@0:8"},
+ {"maxViewportCount", (IMP)xcmDev_maxViewportCount, "Q16@0:8"},
+ {"maxArgumentBufferSamplerCount", (IMP)xcmDev_maxArgBufSamplers, "Q16@0:8"},
{"maxThreadgroupMemoryLength", (IMP)xcmDev_maxTGMem, "Q16@0:8"},
{"minimumLinearTextureAlignmentForPixelFormat:", (IMP)xcmDev_minLinearAlign, "Q24@0:8Q16"},
{"minimumTextureBufferAlignmentForPixelFormat:", (IMP)xcmDev_minTileAlign, "Q24@0:8Q16"},
@@ -2416,9 +3015,42 @@ static Class createBackendDeviceClass(void) {
{"supportsLinearTextureFromSharedBuffer", (IMP)xcmDev_yes, "B16@0:8"},
{"supportsTextureSwizzle", (IMP)xcmDev_yes, "B16@0:8"},
{"supportsNonPrivateDepthStencilTextures", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsUnalignedVertexFetch", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsBaseVertexInstanceDrawing", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsDepthClipMode", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsTextureCubeArray", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsNonUniformThreadgroupSize", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsProgrammableBlending", (IMP)xcmDev_yes, "B16@0:8"},
+ {"isFramebufferReadSupported", (IMP)xcmDev_yes, "B16@0:8"},
+ {"isDepth24Stencil8PixelFormatSupported", (IMP)xcmDev_no, "B16@0:8"},
+ {"sparseTileSizeWithTextureType:pixelFormat:sampleCount:", (IMP)xcmDev_sparseTileSize, "{?=QQQ}40@0:8Q16Q24Q32"},
+ {"sparseTileSizeWithTextureType:pixelFormat:sampleCount:sparsePageSize:", (IMP)xcmDev_sparseTileSizePage, "{?=QQQ}48@0:8Q16Q24Q32q40"},
+ {"tileSizeWithSparsePageSize:textureType:pixelFormat:sampleCount:", (IMP)xcmDev_tileSizeSparse, "{?=QQQ}48@0:8q16Q24Q32Q40"},
{"supportsTextureSampleCount:", (IMP)xcmDev_supportsSampleCount, "B24@0:8Q16"},
+ {"supportsSampleCount:", (IMP)xcmDev_supportsSampleCount, "B24@0:8Q16"},
{"supportsFeatureSet:", (IMP)xcmDev_supportsFeatureSet, "B24@0:8Q16"},
{"supportsFamily:", (IMP)xcmDev_supportsFamily, "B24@0:8q16"},
+ {"singleFPConfig", (IMP)xcmDev_singleFPConfig, "Q16@0:8"},
+ {"doubleFPConfig", (IMP)xcmDev_zeroU, "Q16@0:8"},
+ {"halfFPConfig", (IMP)xcmDev_halfFPConfig, "Q16@0:8"},
+ {"metalAssertionsEnabled", (IMP)xcmDev_no, "B16@0:8"},
+ {"setMetalAssertionsEnabled:", (IMP)xcmDev_noopBool, "v20@0:8B16"},
+ {"copyIOSurfaceSharedTextureProperties:", (IMP)xcmDev_nil1, "@24@0:8@16"},
+ {"mapShaderSampleBufferWithBuffer:capacity:size:", (IMP)xcmDev_noMapSample, "B40@0:8^{?=III}16Q24Q32"},
+ {"unmapShaderSampleBuffer", (IMP)xcmDev_noop, "v16@0:8"},
+ {"newBufferWithDescriptor:", (IMP)xcmDev_newBufferWithDescriptor, "@24@0:8@16"},
+ {"newBufferWithIOSurface:", (IMP)xcmDev_nilPtr1, "@24@0:8^{__IOSurface=}16"},
+ {"newIndirectCommandBufferWithDescriptor:maxCount:options:", (IMP)xcmDev_nilICB, "@40@0:8@16Q24Q32"},
+ {"newIndirectComputeCommandEncoderWithBuffer:", (IMP)xcmDev_nil1, "@24@0:8@16"},
+ {"newIndirectRenderCommandEncoderWithBuffer:", (IMP)xcmDev_nil1, "@24@0:8@16"},
+ {"newRenderPipelineStateWithTileDescriptor:error:", (IMP)xcmDev_newTilePSO, "@32@0:8@16^@24"},
+ {"newRenderPipelineStateWithTileDescriptor:completionHandler:", (IMP)xcmDev_newTilePSOAsync, "v32@0:8@16@?24"},
+ {"newResourceGroupFromResources:count:", (IMP)xcmDev_nilResGrp, "@32@0:8r^@16Q24"},
+ {"newTextureLayoutWithDescriptor:isHeapOrBufferBacked:", (IMP)xcmDev_nil2, "@28@0:8@16B24"},
+ {"newTextureWithBytesNoCopy:length:descriptor:deallocator:", (IMP)xcmDev_nilTexNoCopy, "@48@0:8^v16Q24@32@?40"},
+ {"newVisibleFunctionTableWithDescriptor:", (IMP)xcmDev_nil1, "@24@0:8@16"},
+ {"reserveResourceIndicesForResourceType:indices:indexCount:", (IMP)xcmDev_noopReserve, "v40@0:8Q16^Q24Q32"},
+ {"resourcePatchingTypeForResourceType:", (IMP)xcmDev_zeroU1, "Q24@0:8Q16"},
{"newCommandQueue", (IMP)xcmDev_newCommandQueue, "@16@0:8"},
{"newCommandQueueWithMaxCommandBufferCount:", (IMP)xcmDev_newCommandQueueMax, "@24@0:8Q16"},
{"newBufferWithLength:options:", (IMP)xcmDev_newBufferLen, "@32@0:8Q16Q24"},
@@ -2446,6 +3078,9 @@ static Class createBackendDeviceClass(void) {
{"newSamplerStateWithDescriptor:", (IMP)xcmDev_newSampler, "@24@0:8@16"},
{"newDepthStencilStateWithDescriptor:", (IMP)xcmDev_newDepthStencil, "@24@0:8@16"},
{"newEvent", (IMP)xcmDev_newEvent, "@16@0:8"},
+ {"newSharedEvent", (IMP)xcmDev_newSharedEvent, "@16@0:8"},
+ {"newSharedEventWithOptions:", (IMP)xcmDev_newSharedEventOpts, "@24@0:8Q16"},
+ {"newSharedEventWithHandle:", (IMP)xcmDev_newSharedEventWithHandle, "@24@0:8@16"},
{"newFence", (IMP)xcmDev_newFence, "@16@0:8"},
{"newHeapWithDescriptor:", (IMP)xcmDev_newHeap, "@24@0:8@16"},
{"heapTextureSizeAndAlignWithDescriptor:", (IMP)xcmDev_heapTexSizeAndAlign, "{?=QQ}24@0:8@16"},
@@ -2511,7 +3146,12 @@ static void fillBaseLimits(id device) {
{"maxInterpolants", 32},
{"maxViewports", 16},
{"maxCustomSamplePositions", 0},
- {"linearTextureAlignmentBytes", 256},
+ {"linearTextureAlignmentBytes", 64},
+ {"linearTextureArrayAlignmentBytes", 16},
+ {"linearTextureArrayAlignmentSlice", 128},
+ {"minConstantBufferAlignmentBytes", 4},
+ {"minBufferNoCopyAlignmentBytes", 4096},
+ {"maxComputeThreadgroupMemoryAlignmentBytes", 16},
};
for (const auto &lv : kLimits) {
SEL s = sel_registerName(lv.sel);
@@ -2553,7 +3193,10 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
if (gSingletonDevice) return gSingletonDevice;
gXm2vDevice = xm2v_device_open(loader, icd_json, cache_dir);
if (!gXm2vDevice) {
- fprintf(stderr, "XnuCpuMetal: xm2v_device_open failed: %s\n", xm2v_last_error());
+ const char *err = xm2v_last_error();
+ fprintf(stderr, "XnuCpuMetal: xm2v_device_open failed (cache=%s): %s\n", cache_dir ?: "(null)", err ?: "?");
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: xm2v_device_open failed (prog=%{public}s uid=%u cache=%{public}s): %{public}s",
+ getprogname(), (unsigned)getuid(), cache_dir ?: "(null)", err ?: "?");
return nil;
}
if (port) {
@@ -2605,11 +3248,22 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
const char *envIcd = getenv("XNU_CPU_METAL_ICD");
if (envIcd && envIcd[0]) icdJson = envIcd;
+ // IOSurfaces read/written by this CPU Metal device must be linear uncompressed rows (WindowServer/QuartzCore).
+ // Use in-memory NSRegistrationDomain (never persisted to any app's plist on disk).
+ [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"CAEnableIOSurfaceCompression": @NO}];
+
char cacheDir[512] = {};
auto tryCacheDir = [&](const char *path) -> bool {
if (!path || !path[0]) return false;
mkdir(path, 0700);
- if (access(path, W_OK | X_OK) == 0) {
+ // Verify actual file-creation permission (matches metal2vulkan ShaderCache write probe;
+ // prevents WindowServer uid=88 from failing on root-owned or sandboxed directories).
+ char probe[560];
+ snprintf(probe, sizeof(probe), "%s/.xcm_probe_%d", path, (int)getpid());
+ int fd = open(probe, O_CREAT | O_WRONLY | O_TRUNC, 0600);
+ if (fd >= 0) {
+ close(fd);
+ unlink(probe);
strlcpy(cacheDir, path, sizeof(cacheDir));
return true;
}
@@ -2623,6 +3277,17 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
strlcat(darwinCache, "xnu-cpu-metal-m2v", sizeof(darwinCache));
ok = tryCacheDir(darwinCache);
}
+ if (!ok && confstr(_CS_DARWIN_USER_TEMP_DIR, darwinCache, sizeof(darwinCache) - 32) > 0) {
+ strlcat(darwinCache, "xnu-cpu-metal-m2v", sizeof(darwinCache));
+ ok = tryCacheDir(darwinCache);
+ }
+ if (!ok) {
+ NSString *tmp = NSTemporaryDirectory();
+ if (tmp.length > 0) {
+ snprintf(darwinCache, sizeof(darwinCache), "%s/xnu-cpu-metal-%u", tmp.fileSystemRepresentation, (unsigned)getuid());
+ ok = tryCacheDir(darwinCache);
+ }
+ }
if (!ok) {
char fallback[128];
snprintf(fallback, sizeof(fallback), "/var/tmp/xnu-cpu-metal-%u", (unsigned)getuid());
diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h
index c5ba26c..03432a2 100644
--- a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h
+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h
@@ -43,6 +43,7 @@ static Class referenceClass(Class cls) {
{"XcmBlitEncoder", "IOGPUMetalBlitCommandEncoder"},
{"XcmFence", "IOGPUMetalFence"},
{"XcmEvent", "IOGPUMetalEvent"},
+ {"XcmSharedEvent", "IOGPUMetalSharedEvent"},
{"XcmHeap", "IOGPUMetalHeap"},
{"XcmLibrary", "_MTLLibrary"},
{"XcmFunction", "_MTLFunction"},
@@ -165,6 +166,7 @@ static void install(id device, io_service_t port) {
{"currentAllocatedSize", (IMP)zero, "Q16@0:8", false},
{"gpuCoreCount", (IMP)gpuCoreCount, "Q16@0:8", false},
{"featureProfile", (IMP)zero, "Q16@0:8", false},
+ {"compilerPropagatesThreadPriority:", (IMP)nothingWith, "v20@0:8B16", false},
};
Class cls = object_getClass(device);
addMethods(cls, deviceMethods, sizeof deviceMethods / sizeof *deviceMethods);
@@ -176,6 +178,8 @@ static void install(id device, io_service_t port) {
{"setGPUPriority:", (IMP)setGPUPriority, "B24@0:8Q16", false},
{"setGPUPriority:offset:", (IMP)setGPUPriorityOffset, "B32@0:8Q16Q24", false},
{"_setGPUPriority:backgroundPriority:", (IMP)setBothGPUPriorities, "B32@0:8Q16Q24", false},
+ {"setCompletionQueue:", (IMP)nothingWith, "v24@0:8@16", false},
+ {"setSubmissionQueue:", (IMP)nothingWith, "v24@0:8@16", false},
};
if (Class q = objc_getClass("XcmQueue"))
addMethods(q, queueMethods, sizeof queueMethods / sizeof *queueMethods);
@@ -200,7 +204,7 @@ static void install(id device, io_service_t port) {
{"XcmComputePipeline", "MTLComputePipelineState"},
{"XcmRenderPipeline", "MTLRenderPipelineState"},
{"XcmSampler", "MTLSamplerState"}, {"XcmDepthStencil", "MTLDepthStencilState"},
- {"XcmEvent", "MTLEvent"}, {"XcmFence", "MTLFence"},
+ {"XcmEvent", "MTLEvent"}, {"XcmSharedEvent", "MTLEvent"}, {"XcmSharedEvent", "MTLSharedEvent"}, {"XcmFence", "MTLFence"},
{"XcmHeap", "MTLHeap"},
{"XcmQueue", "MTLCommandQueue"}, {"XcmCommandBuffer", "MTLCommandBuffer"},
{"XcmComputeEncoder", "MTLComputeCommandEncoder"},
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 f384f25..81bff2c 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
@@ -24,9 +24,14 @@ typedef struct Xm2vComputeEncoder Xm2vComputeEncoder;
typedef struct Xm2vRenderEncoder Xm2vRenderEncoder;
typedef struct Xm2vBlitEncoder Xm2vBlitEncoder;
typedef struct Xm2vEvent Xm2vEvent;
+typedef struct Xm2vSharedEvent Xm2vSharedEvent;
+typedef struct Xm2vSharedEventHandle Xm2vSharedEventHandle;
typedef struct Xm2vFence Xm2vFence;
typedef struct Xm2vArgumentEncoder Xm2vArgumentEncoder;
+typedef void (*Xm2vDeallocatorFn)(void *ptr, uint64_t length, void *ctx);
+typedef void (*Xm2vSharedEventNotifyFn)(void *ctx, uint64_t value);
+
typedef struct Xm2vTextureDesc {
uint64_t texture_type;
uint64_t pixel_format;
@@ -156,11 +161,15 @@ bool xm2v_device_supports_family(const Xm2vDevice *dev, int64_t family);
/* Buffers */
Xm2vBuffer *xm2v_buffer_new(Xm2vDevice *dev, uint64_t length, uint64_t resource_options, const void *bytes);
Xm2vBuffer *xm2v_buffer_new_no_copy(Xm2vDevice *dev, void *ptr, uint64_t length, uint64_t resource_options);
+Xm2vBuffer *xm2v_buffer_new_no_copy_dealloc(Xm2vDevice *dev, void *ptr, uint64_t length, uint64_t resource_options,
+ Xm2vDeallocatorFn dealloc_fn, void *dealloc_ctx);
void xm2v_buffer_release(Xm2vBuffer *buf);
void *xm2v_buffer_contents(const Xm2vBuffer *buf);
uint64_t xm2v_buffer_length(const Xm2vBuffer *buf);
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);
/* Textures */
Xm2vTexture *xm2v_texture_new(Xm2vDevice *dev, const Xm2vTextureDesc *desc);
@@ -252,8 +261,13 @@ void xm2v_command_buffer_release(Xm2vCommandBuffer *cb);
bool xm2v_command_buffer_commit(Xm2vCommandBuffer *cb);
bool xm2v_command_buffer_wait_until_completed(Xm2vCommandBuffer *cb, uint64_t timeout_ms);
uint32_t xm2v_command_buffer_status(const Xm2vCommandBuffer *cb);
+size_t xm2v_command_buffer_error(const Xm2vCommandBuffer *cb, char *out, size_t size);
bool xm2v_command_buffer_encode_signal_event(Xm2vCommandBuffer *cb, Xm2vEvent *ev, uint64_t value);
+bool xm2v_command_buffer_encode_signal_event_scheduled(Xm2vCommandBuffer *cb, Xm2vEvent *ev, uint64_t value);
bool xm2v_command_buffer_encode_wait_event(Xm2vCommandBuffer *cb, Xm2vEvent *ev, uint64_t value);
+bool xm2v_command_buffer_encode_signal_shared_event(Xm2vCommandBuffer *cb, Xm2vSharedEvent *ev, uint64_t value);
+bool xm2v_command_buffer_encode_signal_shared_event_scheduled(Xm2vCommandBuffer *cb, Xm2vSharedEvent *ev, uint64_t value);
+bool xm2v_command_buffer_encode_wait_shared_event(Xm2vCommandBuffer *cb, Xm2vSharedEvent *ev, uint64_t value);
/* Compute Encoder */
Xm2vComputeEncoder *xm2v_compute_encoder_new(Xm2vCommandBuffer *cb);
@@ -271,6 +285,8 @@ bool xm2v_compute_encoder_dispatch_threadgroups(Xm2vComputeEncoder *enc,
bool xm2v_compute_encoder_dispatch_threads(Xm2vComputeEncoder *enc,
uint64_t gx, uint64_t gy, uint64_t gz,
uint64_t tx, uint64_t ty, uint64_t tz);
+bool xm2v_compute_encoder_update_fence(Xm2vComputeEncoder *enc, Xm2vFence *fence);
+bool xm2v_compute_encoder_wait_fence(Xm2vComputeEncoder *enc, Xm2vFence *fence);
bool xm2v_compute_encoder_end(Xm2vComputeEncoder *enc);
/* Render Encoder */
@@ -298,6 +314,8 @@ bool xm2v_render_encoder_draw_primitives(Xm2vRenderEncoder *enc, uint64_t prim,
bool xm2v_render_encoder_draw_indexed_primitives(Xm2vRenderEncoder *enc, uint64_t prim, uint64_t index_count, uint64_t index_type,
Xm2vBuffer *index_buf, uint64_t index_offset, uint64_t instance_count,
int64_t base_vertex, uint64_t base_instance);
+bool xm2v_render_encoder_update_fence(Xm2vRenderEncoder *enc, Xm2vFence *fence, uint64_t after_stages);
+bool xm2v_render_encoder_wait_fence(Xm2vRenderEncoder *enc, Xm2vFence *fence, uint64_t before_stages);
bool xm2v_render_encoder_end(Xm2vRenderEncoder *enc);
/* Blit Encoder */
@@ -323,11 +341,22 @@ bool xm2v_blit_encoder_fill_buffer(Xm2vBlitEncoder *enc, Xm2vBuffer *buf, uint64
bool xm2v_blit_encoder_generate_mipmaps(Xm2vBlitEncoder *enc, Xm2vTexture *tex);
bool xm2v_blit_encoder_synchronize_buffer(Xm2vBlitEncoder *enc, Xm2vBuffer *buf);
bool xm2v_blit_encoder_synchronize_texture(Xm2vBlitEncoder *enc, Xm2vTexture *tex);
+bool xm2v_blit_encoder_update_fence(Xm2vBlitEncoder *enc, Xm2vFence *fence);
+bool xm2v_blit_encoder_wait_fence(Xm2vBlitEncoder *enc, Xm2vFence *fence);
bool xm2v_blit_encoder_end(Xm2vBlitEncoder *enc);
/* Events & Fences */
Xm2vEvent *xm2v_event_new(Xm2vDevice *dev);
void xm2v_event_release(Xm2vEvent *ev);
+Xm2vSharedEvent *xm2v_shared_event_new(Xm2vDevice *dev);
+Xm2vSharedEvent *xm2v_shared_event_new_with_handle(Xm2vDevice *dev, const Xm2vSharedEventHandle *handle);
+void xm2v_shared_event_release(Xm2vSharedEvent *ev);
+uint64_t xm2v_shared_event_signaled_value(const Xm2vSharedEvent *ev);
+void xm2v_shared_event_set_signaled_value(const Xm2vSharedEvent *ev, uint64_t value);
+bool xm2v_shared_event_wait_until(const Xm2vSharedEvent *ev, uint64_t value, uint64_t timeout_ms);
+bool xm2v_shared_event_notify(const Xm2vSharedEvent *ev, uint64_t value, Xm2vSharedEventNotifyFn cb, void *ctx);
+Xm2vSharedEventHandle *xm2v_shared_event_new_handle(const Xm2vSharedEvent *ev);
+void xm2v_shared_event_handle_release(Xm2vSharedEventHandle *h);
Xm2vFence *xm2v_fence_new(Xm2vDevice *dev);
void xm2v_fence_release(Xm2vFence *f);
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 14130e3..03f80a2 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
@@ -16,17 +16,18 @@ use metal2vulkan::pipeline::{
};
use metal2vulkan_runtime::{
ArgumentEncoder, BlitCommandEncoder, BlitOption, Buffer, ClearColor, CommandBuffer,
- CommandBufferStatus, CommandQueue, ComputeCommandEncoder, ComputePipelineState,
+ 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, Size, StoreAction, Texture, TextureDescriptor,
- Viewport,
+ SamplerState, ScissorRect, ShaderCacheOptions, SharedEvent, SharedEventHandle,
+ SharedEventListener, Size, StoreAction, Texture, TextureDescriptor, Viewport,
};
use std::cell::RefCell;
use std::ffi::{c_char, c_void, CStr};
use std::path::PathBuf;
use std::ptr::NonNull;
+use std::sync::OnceLock;
use std::time::Duration;
thread_local! {
@@ -409,24 +410,103 @@ pub extern "C" fn xm2v_buffer_new(
})
}
+pub type Xm2vDeallocatorFn = extern "C" fn(*mut c_void, u64, *mut c_void);
+pub type Xm2vSharedEventNotifyFn = extern "C" fn(*mut c_void, u64);
+
+fn build_texture_descriptor(d: &Xm2vTextureDesc) -> Result<TextureDescriptor, String> {
+ let pixel_format: PixelFormat = raw_enum(d.pixel_format, "PixelFormat")?;
+ let texture_type: TextureType = raw_enum(d.texture_type, "TextureType")?;
+ let mut td = TextureDescriptor::texture_2d(
+ pixel_format,
+ d.width.max(1),
+ d.height.max(1),
+ d.mipmap_level_count > 1,
+ );
+ td.texture_type = texture_type;
+ td.depth = d.depth.max(1);
+ td.mipmap_level_count = d.mipmap_level_count.max(1);
+ td.sample_count = d.sample_count.max(1);
+ td.array_length = d.array_length.max(1);
+ td.resource_options = raw_opts(d.resource_options)?;
+ td.usage = raw_enum::<TextureUsage>(d.usage, "TextureUsage")?;
+ Ok(td)
+}
+
#[no_mangle]
pub extern "C" fn xm2v_buffer_new_no_copy(
dev: *mut Device,
ptr: *mut c_void,
length: u64,
resource_options: u64,
+) -> *mut Buffer {
+ xm2v_buffer_new_no_copy_dealloc(dev, ptr, length, resource_options, None, std::ptr::null_mut())
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_new_no_copy_dealloc(
+ dev: *mut Device,
+ ptr: *mut c_void,
+ length: u64,
+ resource_options: u64,
+ dealloc_fn: Option<Xm2vDeallocatorFn>,
+ dealloc_ctx: *mut c_void,
) -> *mut Buffer {
guard(std::ptr::null_mut(), || {
let dev = get(dev)?;
let opts = raw_opts(resource_options)?;
let nn = NonNull::new(ptr.cast::<u8>()).ok_or_else(|| "null ptr".to_string())?;
let hm = unsafe { HostMemory::new(nn) };
- let buf = unsafe { dev.new_buffer_with_bytes_no_copy(hm, length, opts, None) }
+ let dealloc: Option<Deallocator> = dealloc_fn.map(|f| {
+ let ctx_addr = dealloc_ctx as usize;
+ Box::new(move |p: NonNull<u8>, len: u64| {
+ f(p.as_ptr().cast::<c_void>(), len, ctx_addr as *mut c_void);
+ }) as Deallocator
+ });
+ let buf = unsafe { dev.new_buffer_with_bytes_no_copy(hm, length, opts, dealloc) }
.map_err(|e| format!("new_buffer_no_copy: {e:?}"))?;
Ok(boxed(buf))
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_new_texture(
+ buf: *mut Buffer,
+ desc: *const Xm2vTextureDesc,
+ offset: u64,
+ bytes_per_row: u64,
+) -> *mut Texture {
+ guard(std::ptr::null_mut(), || {
+ let buf = get(buf)?;
+ let td = build_texture_descriptor(get(desc)?)?;
+ let tex = buf
+ .new_texture(&td, offset, bytes_per_row)
+ .map_err(|e| format!("buffer.new_texture(off={offset}, bpr={bytes_per_row}): {e:?}"))?;
+ Ok(boxed(tex))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_new_linear_texture(
+ buf: *mut Buffer,
+ desc: *const Xm2vTextureDesc,
+ offset: u64,
+ bytes_per_row: u64,
+ bytes_per_image: u64,
+) -> *mut Texture {
+ guard(std::ptr::null_mut(), || {
+ let buf = get(buf)?;
+ let td = build_texture_descriptor(get(desc)?)?;
+ let tex = buf
+ .new_linear_texture(&td, offset, bytes_per_row, bytes_per_image)
+ .map_err(|e| {
+ format!(
+ "buffer.new_linear_texture(off={offset}, bpr={bytes_per_row}, bpi={bytes_per_image}): {e:?}"
+ )
+ })?;
+ Ok(boxed(tex))
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_buffer_release(buf: *mut Buffer) {
release(buf);
@@ -469,22 +549,7 @@ pub extern "C" fn xm2v_texture_new(
) -> *mut Texture {
guard(std::ptr::null_mut(), || {
let dev = get(dev)?;
- let d = get(desc)?;
- let pixel_format: PixelFormat = raw_enum(d.pixel_format, "PixelFormat")?;
- let texture_type: TextureType = raw_enum(d.texture_type, "TextureType")?;
- let mut td = TextureDescriptor::texture_2d(
- pixel_format,
- d.width.max(1),
- d.height.max(1),
- d.mipmap_level_count > 1,
- );
- td.texture_type = texture_type;
- td.depth = d.depth.max(1);
- td.mipmap_level_count = d.mipmap_level_count.max(1);
- td.sample_count = d.sample_count.max(1);
- td.array_length = d.array_length.max(1);
- td.resource_options = raw_opts(d.resource_options)?;
- td.usage = raw_enum::<TextureUsage>(d.usage, "TextureUsage")?;
+ let td = build_texture_descriptor(get(desc)?)?;
let tex = dev
.new_texture(&td)
.map_err(|e| format!("new_texture: {e:?}"))?;
@@ -1360,6 +1425,33 @@ pub extern "C" fn xm2v_command_buffer_status(cb: *const CommandBuffer) -> u32 {
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_error(
+ cb: *const CommandBuffer,
+ out: *mut c_char,
+ size: usize,
+) -> usize {
+ guard(0, || {
+ let cb = get(cb)?;
+ let mut parts: Vec<String> = Vec::new();
+ if let Some(err) = cb.error() {
+ parts.push(format!("{err:?}"));
+ }
+ if let Some(refusal) = cb.refusal() {
+ parts.push(format!("refusal={refusal:?}"));
+ }
+ if let Some(desc) = cb.error_description() {
+ if !desc.is_empty() {
+ parts.push(desc);
+ }
+ }
+ if parts.is_empty() {
+ return Ok(0);
+ }
+ Ok(copy_str(&parts.join(": "), out, size))
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_command_buffer_encode_signal_event(
cb: *mut CommandBuffer,
@@ -1374,6 +1466,20 @@ pub extern "C" fn xm2v_command_buffer_encode_signal_event(
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_encode_signal_event_scheduled(
+ cb: *mut CommandBuffer,
+ ev: *mut Event,
+ value: u64,
+) -> bool {
+ guard(false, || {
+ get(cb)?
+ .encode_signal_event(EventRef::Event(get(ev)?), value)
+ .map_err(|e| format!("encode_signal_event_scheduled: {e:?}"))?;
+ Ok(true)
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_command_buffer_encode_wait_event(
cb: *mut CommandBuffer,
@@ -1388,6 +1494,48 @@ pub extern "C" fn xm2v_command_buffer_encode_wait_event(
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_encode_signal_shared_event(
+ cb: *mut CommandBuffer,
+ ev: *mut SharedEvent,
+ value: u64,
+) -> bool {
+ guard(false, || {
+ get(cb)?
+ .encode_signal_event(EventRef::Shared(get(ev)?), value)
+ .map_err(|e| format!("encode_signal_shared_event: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_encode_signal_shared_event_scheduled(
+ cb: *mut CommandBuffer,
+ ev: *mut SharedEvent,
+ value: u64,
+) -> bool {
+ guard(false, || {
+ get(cb)?
+ .encode_signal_event_scheduled(get(ev)?, value)
+ .map_err(|e| format!("encode_signal_shared_event_scheduled: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_encode_wait_shared_event(
+ cb: *mut CommandBuffer,
+ ev: *mut SharedEvent,
+ value: u64,
+) -> bool {
+ guard(false, || {
+ get(cb)?
+ .encode_wait_for_event(EventRef::Shared(get(ev)?), value)
+ .map_err(|e| format!("encode_wait_shared_event: {e:?}"))?;
+ Ok(true)
+ })
+}
+
/* ---- Compute Encoder ---- */
#[no_mangle]
@@ -1559,6 +1707,32 @@ pub extern "C" fn xm2v_compute_encoder_dispatch_threads(
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_update_fence(
+ enc: *mut ComputeCommandEncoder,
+ fence: *mut Fence,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .update_fence(get(fence)?)
+ .map_err(|e| format!("compute update_fence: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_wait_fence(
+ enc: *mut ComputeCommandEncoder,
+ fence: *mut Fence,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .wait_for_fence(get(fence)?)
+ .map_err(|e| format!("compute wait_for_fence: {e:?}"))?;
+ Ok(true)
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_compute_encoder_end(enc: *mut ComputeCommandEncoder) -> bool {
guard(false, || {
@@ -1954,6 +2128,36 @@ pub extern "C" fn xm2v_render_encoder_draw_indexed_primitives(
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_update_fence(
+ enc: *mut RenderCommandEncoder,
+ fence: *mut Fence,
+ after_stages: u64,
+) -> bool {
+ guard(false, || {
+ let stages = raw_enum::<RenderStages>(after_stages, "RenderStages")?;
+ get_mut(enc)?
+ .update_fence(get(fence)?, stages)
+ .map_err(|e| format!("render update_fence: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_wait_fence(
+ enc: *mut RenderCommandEncoder,
+ fence: *mut Fence,
+ before_stages: u64,
+) -> bool {
+ guard(false, || {
+ let stages = raw_enum::<RenderStages>(before_stages, "RenderStages")?;
+ get_mut(enc)?
+ .wait_for_fence(get(fence)?, stages)
+ .map_err(|e| format!("render wait_for_fence: {e:?}"))?;
+ Ok(true)
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_render_encoder_end(enc: *mut RenderCommandEncoder) -> bool {
guard(false, || {
@@ -2157,6 +2361,32 @@ pub extern "C" fn xm2v_blit_encoder_synchronize_texture(
})
}
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_update_fence(
+ enc: *mut BlitCommandEncoder,
+ fence: *mut Fence,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .update_fence(get(fence)?)
+ .map_err(|e| format!("blit update_fence: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_wait_fence(
+ enc: *mut BlitCommandEncoder,
+ fence: *mut Fence,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .wait_for_fence(get(fence)?)
+ .map_err(|e| format!("blit wait_for_fence: {e:?}"))?;
+ Ok(true)
+ })
+}
+
#[no_mangle]
pub extern "C" fn xm2v_blit_encoder_end(enc: *mut BlitCommandEncoder) -> bool {
guard(false, || {
@@ -2169,6 +2399,8 @@ pub extern "C" fn xm2v_blit_encoder_end(enc: *mut BlitCommandEncoder) -> bool {
/* ---- Events & Fences ---- */
+static SHARED_EVENT_LISTENER: OnceLock<SharedEventListener> = OnceLock::new();
+
#[no_mangle]
pub extern "C" fn xm2v_event_new(dev: *mut Device) -> *mut Event {
guard(std::ptr::null_mut(), || {
@@ -2184,6 +2416,98 @@ pub extern "C" fn xm2v_event_release(ev: *mut Event) {
release(ev);
}
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_new(dev: *mut Device) -> *mut SharedEvent {
+ guard(std::ptr::null_mut(), || {
+ let ev = get(dev)?
+ .new_shared_event()
+ .map_err(|e| format!("new_shared_event: {e:?}"))?;
+ Ok(boxed(ev))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_new_with_handle(
+ dev: *mut Device,
+ handle: *const SharedEventHandle,
+) -> *mut SharedEvent {
+ guard(std::ptr::null_mut(), || {
+ let ev = get(dev)?
+ .new_shared_event_with_handle(get(handle)?)
+ .map_err(|e| format!("new_shared_event_with_handle: {e:?}"))?;
+ Ok(boxed(ev))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_release(ev: *mut SharedEvent) {
+ release(ev);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_signaled_value(ev: *const SharedEvent) -> u64 {
+ guard(0, || Ok(get(ev)?.signaled_value()))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_set_signaled_value(ev: *const SharedEvent, value: u64) {
+ let _ = guard((), || {
+ get(ev)?.set_signaled_value(value);
+ Ok(())
+ });
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_wait_until(
+ ev: *const SharedEvent,
+ value: u64,
+ timeout_ms: u64,
+) -> bool {
+ guard(false, || {
+ let dur = if timeout_ms == u64::MAX {
+ Duration::MAX
+ } else {
+ Duration::from_millis(timeout_ms)
+ };
+ Ok(get(ev)?.wait_until_signaled_value(value, dur))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_notify(
+ ev: *const SharedEvent,
+ value: u64,
+ cb: Option<Xm2vSharedEventNotifyFn>,
+ ctx: *mut c_void,
+) -> bool {
+ guard(false, || {
+ let ev = get(ev)?;
+ let cb = cb.ok_or_else(|| "null notify callback".to_string())?;
+ let listener = SHARED_EVENT_LISTENER.get_or_init(SharedEventListener::new);
+ let ctx_addr = ctx as usize;
+ ev.notify_listener(
+ listener,
+ value,
+ Box::new(move |_event, signaled| {
+ cb(ctx_addr as *mut c_void, signaled);
+ }),
+ );
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_new_handle(ev: *const SharedEvent) -> *mut SharedEventHandle {
+ guard(std::ptr::null_mut(), || {
+ Ok(boxed(get(ev)?.new_shared_event_handle()))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_shared_event_handle_release(h: *mut SharedEventHandle) {
+ release(h);
+}
+
#[no_mangle]
pub extern "C" fn xm2v_fence_new(dev: *mut Device) -> *mut Fence {
guard(std::ptr::null_mut(), || Ok(boxed(get(dev)?.new_fence())))
diff --git a/gpu/xnu-cpu-metal/test/test_bundle.mm b/gpu/xnu-cpu-metal/test/test_bundle.mm
new file mode 100644
index 0000000..befa543
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_bundle.mm
@@ -0,0 +1,108 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <objc/runtime.h>
+#include <stdio.h>
+#include <math.h>
+
+@interface NSObject (XnuCpuMetalPlugin)
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+int main(int argc, const char **argv) {
+ @autoreleasepool {
+ if (argc < 3) {
+ fprintf(stderr, "Usage: %s <XnuCpuMetal.bundle> <vecadd.metallib>\n", argv[0]);
+ return 2;
+ }
+ NSString *bundlePath = [NSString stringWithUTF8String:argv[1]];
+ NSString *metallibPath = [NSString stringWithUTF8String:argv[2]];
+
+ NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
+ NSError *loadErr = nil;
+ if (!bundle || ![bundle loadAndReturnError:&loadErr]) {
+ fprintf(stderr, "Failed to load bundle %s: %s\n",
+ bundlePath.UTF8String, loadErr.localizedDescription.UTF8String ?: "unknown");
+ return 1;
+ }
+
+ Class principal = [bundle principalClass];
+ Class iogpuBase = objc_getClass("IOGPUMetalDevice");
+ printf("Bundle loaded: principalClass=%s, isSubclassOf(IOGPUMetalDevice)=%s\n",
+ principal ? class_getName(principal) : "(nil)",
+ (principal && iogpuBase && [principal isSubclassOfClass:iogpuBase]) ? "YES" : "NO");
+
+ if (!principal || !iogpuBase || ![principal isSubclassOfClass:iogpuBase]) {
+ fprintf(stderr, "Principal class check failed!\n");
+ return 1;
+ }
+
+ id<MTLDevice> dev = [[principal alloc] initWithAcceleratorPort:0];
+ if (!dev) {
+ fprintf(stderr, "initWithAcceleratorPort: returned nil!\n");
+ return 1;
+ }
+ printf("Device: %s (registryID=0x%llx, lowPower=%d, headless=%d, unified=%d, conformsMTLDevice=%d)\n",
+ dev.name.UTF8String, (unsigned long long)dev.registryID,
+ dev.isLowPower, dev.isHeadless, dev.hasUnifiedMemory,
+ [dev conformsToProtocol:@protocol(MTLDevice)]);
+
+ NSError *err = nil;
+ id<MTLLibrary> lib = [dev newLibraryWithURL:[NSURL fileURLWithPath:metallibPath] error:&err];
+ if (!lib) {
+ fprintf(stderr, "newLibraryWithURL failed: %s\n", err.localizedDescription.UTF8String);
+ return 1;
+ }
+ printf("Library functions: %s\n", [[lib.functionNames componentsJoinedByString:@", "] UTF8String]);
+
+ id<MTLFunction> fn = [lib newFunctionWithName:@"vecadd"];
+ if (!fn) {
+ fprintf(stderr, "newFunctionWithName(vecadd) returned nil\n");
+ return 1;
+ }
+
+ id<MTLComputePipelineState> pso = [dev newComputePipelineStateWithFunction:fn error:&err];
+ if (!pso) {
+ fprintf(stderr, "newComputePipelineStateWithFunction failed: %s\n", err.localizedDescription.UTF8String);
+ return 1;
+ }
+
+ const uint32_t N = 1024;
+ float a[1024], b[1024];
+ for (uint32_t i = 0; i < N; i++) {
+ a[i] = (float)i * 3.0f;
+ b[i] = (float)(N - i) * 0.25f;
+ }
+ id<MTLBuffer> bufA = [dev newBufferWithBytes:a length:sizeof(a) options:MTLResourceStorageModeShared];
+ id<MTLBuffer> bufB = [dev newBufferWithBytes:b length:sizeof(b) options:MTLResourceStorageModeShared];
+ id<MTLBuffer> bufC = [dev newBufferWithLength:sizeof(a) options:MTLResourceStorageModeShared];
+
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ __block BOOL completedHandlerRan = NO;
+ [cb addCompletedHandler:^(id<MTLCommandBuffer> _Nonnull c) {
+ (void)c;
+ completedHandlerRan = YES;
+ }];
+
+ id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
+ [enc setComputePipelineState:pso];
+ [enc setBuffer:bufA offset:0 atIndex:0];
+ [enc setBuffer:bufB offset:0 atIndex:1];
+ [enc setBuffer:bufC offset:0 atIndex:2];
+ [enc dispatchThreads:MTLSizeMake(N, 1, 1) threadsPerThreadgroup:MTLSizeMake(64, 1, 1)];
+ [enc endEncoding];
+
+ [cb commit];
+ [cb waitUntilCompleted];
+
+ const float *c = (const float *)bufC.contents;
+ uint32_t bad = 0;
+ for (uint32_t i = 0; i < N; i++) {
+ float exp = a[i] + b[i];
+ if (fabsf(c[i] - exp) > 1e-5f) bad++;
+ }
+ printf("Bundle ObjC MTLDevice vecadd N=%u: status=%lu, completedHandler=%d, bad=%u (c[0]=%.2f, c[10]=%.2f, c[1023]=%.2f)\n",
+ N, (unsigned long)cb.status, completedHandlerRan, bad, c[0], c[10], c[1023]);
+ return (bad == 0 && completedHandlerRan) ? 0 : 1;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/test_carenderer.mm b/gpu/xnu-cpu-metal/test/test_carenderer.mm
new file mode 100644
index 0000000..6e9eb4e
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_carenderer.mm
@@ -0,0 +1,170 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <QuartzCore/QuartzCore.h>
+#import <CoreGraphics/CoreGraphics.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <vector>
+
+@interface XcmBundleDeviceStub : NSObject
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static id<MTLDevice> loadBundleDevice(const char *bundlePath) {
+ NSBundle *b = [NSBundle bundleWithPath:[NSString stringWithUTF8String:bundlePath]];
+ if (!b || ![b load]) return nil;
+ return (id<MTLDevice>)[(XcmBundleDeviceStub *)[b.principalClass alloc] initWithAcceleratorPort:0u];
+}
+
+static CGImageRef makeQuadrantImage(int w, int h) {
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ CGContextRef cg = CGBitmapContextCreate(NULL, w, h, 8, 0, cs,
+ kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
+ CGFloat rgb[4][3] = {{1,0,0}, {0,1,0}, {0,0,1}, {1,1,0}};
+ for (int i = 0; i < 4; i++) {
+ CGContextSetRGBFillColor(cg, rgb[i][0], rgb[i][1], rgb[i][2], 1);
+ CGContextFillRect(cg, CGRectMake((i % 2) * (w / 2), (i / 2) * (h / 2), w / 2, h / 2));
+ }
+ CGImageRef img = CGBitmapContextCreateImage(cg);
+ CGContextRelease(cg);
+ CGColorSpaceRelease(cs);
+ return img;
+}
+
+static std::vector<uint8_t> renderCase(id<MTLDevice> dev, const char *mode, int W, int H) {
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:W height:H mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ id<MTLTexture> tex = [dev newTextureWithDescriptor:td];
+
+ CALayer *root = [CALayer layer];
+ root.bounds = CGRectMake(0, 0, W, H);
+ root.position = CGPointMake(W / 2.0, H / 2.0);
+ root.geometryFlipped = NO;
+
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ if (!strcmp(mode, "color")) {
+ CGFloat comps[4] = {1.0, 0.0, 0.0, 1.0};
+ CGColorRef red = CGColorCreate(cs, comps);
+ root.backgroundColor = red;
+ CGColorRelease(red);
+ } else if (!strcmp(mode, "image")) {
+ CGImageRef img = makeQuadrantImage(W, H);
+ root.contents = (__bridge id)img;
+ CGImageRelease(img);
+ } else if (!strcmp(mode, "two_layers")) {
+ CGFloat bgc[4] = {0.2, 0.8, 0.2, 1.0};
+ CGColorRef bg = CGColorCreate(cs, bgc);
+ root.backgroundColor = bg;
+ CGColorRelease(bg);
+ CALayer *child = [CALayer layer];
+ child.frame = CGRectMake(32, 32, W - 64, H - 64);
+ CGFloat cc[4] = {0.2, 0.5, 0.9, 1.0};
+ CGColorRef blue = CGColorCreate(cs, cc);
+ child.backgroundColor = blue;
+ CGColorRelease(blue);
+ [root addSublayer:child];
+ } else if (!strcmp(mode, "rounded_only")) {
+ CGFloat bgc[4] = {0.9, 0.9, 0.95, 1.0};
+ CGColorRef bg = CGColorCreate(cs, bgc);
+ root.backgroundColor = bg;
+ CGColorRelease(bg);
+ CALayer *child = [CALayer layer];
+ child.frame = CGRectMake(32, 32, W - 64, H - 64);
+ CGFloat cc[4] = {0.2, 0.5, 0.9, 1.0};
+ CGColorRef blue = CGColorCreate(cs, cc);
+ child.backgroundColor = blue;
+ CGColorRelease(blue);
+ child.cornerRadius = 24.0;
+ [root addSublayer:child];
+ } else if (!strcmp(mode, "rounded_shadow")) {
+ CGFloat bgc[4] = {0.9, 0.9, 0.95, 1.0};
+ CGColorRef bg = CGColorCreate(cs, bgc);
+ root.backgroundColor = bg;
+ CGColorRelease(bg);
+
+ CALayer *child = [CALayer layer];
+ child.frame = CGRectMake(32, 32, W - 64, H - 64);
+ CGFloat cc[4] = {0.2, 0.5, 0.9, 1.0};
+ CGColorRef blue = CGColorCreate(cs, cc);
+ child.backgroundColor = blue;
+ CGColorRelease(blue);
+ child.cornerRadius = 24.0;
+ child.shadowOpacity = 0.8f;
+ child.shadowRadius = 8.0;
+ child.shadowOffset = CGSizeMake(0, 4);
+ [root addSublayer:child];
+ }
+ CGColorSpaceRelease(cs);
+
+ fprintf(stderr, "TEST %s dev=%s tex=%p\n", mode, dev.name.UTF8String, (__bridge void *)tex);
+ CARenderer *renderer = [CARenderer rendererWithMTLTexture:tex options:nil];
+ renderer.layer = root;
+ renderer.bounds = CGRectMake(0, 0, W, H);
+ [CATransaction flush];
+ [renderer beginFrameAtTime:CACurrentMediaTime() timeStamp:NULL];
+ [renderer addUpdateRect:renderer.bounds];
+ [renderer render];
+ [renderer endFrame];
+
+ // Flush GPU queue to ensure CARenderer's internal CB completed
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ [cb commit];
+ [cb waitUntilCompleted];
+ usleep(300000);
+
+ std::vector<uint8_t> px(W * H * 4, 0);
+ [tex getBytes:px.data() bytesPerRow:W * 4 fromRegion:MTLRegionMake2D(0, 0, W, H) mipmapLevel:0];
+ return px;
+}
+
+static void printSummary(const char *tag, const char *mode, const std::vector<uint8_t> &px, int W, int H) {
+ size_t nz = 0, nzRGB = 0;
+ for (int i = 0; i < W * H; i++) {
+ if (px[i*4+0] || px[i*4+1] || px[i*4+2]) nzRGB++;
+ for (int c = 0; c < 4; c++) if (px[i*4+c]) nz++;
+ }
+ auto at = [&](int x, int y) {
+ const uint8_t *p = &px[(y * W + x) * 4];
+ printf("(%d,%d)=BGRA(%3u,%3u,%3u,%3u)", x, y, p[0], p[1], p[2], p[3]);
+ };
+ printf("[%s %-14s] nz=%zu/%zu nzRGB=%zu/%d ", tag, mode, nz, px.size(), nzRGB, W * H);
+ at(W/4, H/4); printf(" ");
+ at(3*W/4, H/4); printf(" ");
+ at(W/2, H/2); printf(" "); at(0, 0); printf("\n");
+}
+
+int main(int argc, char **argv) {
+ setvbuf(stdout, nullptr, _IONBF, 0);
+ @autoreleasepool {
+ const char *bundlePath = (argc > 1) ? argv[1] : "dist/XnuCpuMetal.bundle";
+ id<MTLDevice> cpuDev = loadBundleDevice(bundlePath);
+ id<MTLDevice> gpuDev = MTLCreateSystemDefaultDevice();
+ if (!cpuDev || !gpuDev) { fprintf(stderr, "FAIL: devices %p %p\n", (__bridge void *)cpuDev, (__bridge void *)gpuDev); return 1; }
+ printf("CPU: %s\nGPU: %s\n", cpuDev.name.UTF8String, gpuDev.name.UTF8String);
+
+ const int W = 128, H = 128;
+ const char *modes[] = {"color", "image", "two_layers", "rounded_only", "rounded_shadow"};
+ int failures = 0;
+ for (const char *m : modes) {
+ auto ref = renderCase(gpuDev, m, W, H);
+ auto got = renderCase(cpuDev, m, W, H);
+ printSummary("GPU", m, ref, W, H);
+ printSummary("CPU", m, got, W, H);
+ int maxErr = 0;
+ double sumErr = 0;
+ for (size_t i = 0; i < ref.size(); i++) {
+ int d = abs((int)ref[i] - (int)got[i]);
+ if (d > maxErr) maxErr = d;
+ sumErr += d;
+ }
+ double meanErr = sumErr / ref.size();
+ printf(" DIFF %-14s: maxErr=%d meanErr=%.3f\n", m, maxErr, meanErr);
+ if (maxErr > 8 || meanErr > 2.0) failures++;
+ }
+ return failures ? 1 : 0;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/test_render_ci.mm b/gpu/xnu-cpu-metal/test/test_render_ci.mm
new file mode 100644
index 0000000..6490211
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_render_ci.mm
@@ -0,0 +1,236 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <CoreImage/CoreImage.h>
+#import <objc/runtime.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <math.h>
+#include <stdlib.h>
+
+@interface NSObject (XnuCpuMetalPlugin)
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static int run_render_pass_test(id<MTLDevice> dev, NSString *triMetallibPath) {
+ printf("\n=== [Test A] Render Pass (clear blue + orange triangle -> 64x64 RGBA8) ===\n");
+ NSError *err = nil;
+ id<MTLLibrary> lib = [dev newLibraryWithURL:[NSURL fileURLWithPath:triMetallibPath] error:&err];
+ if (!lib) {
+ fprintf(stderr, "Render: newLibraryWithURL failed: %s\n", err.localizedDescription.UTF8String);
+ return 1;
+ }
+ id<MTLFunction> vfn = [lib newFunctionWithName:@"tri_vertex"];
+ id<MTLFunction> ffn = [lib newFunctionWithName:@"tri_fragment"];
+ if (!vfn || !ffn) {
+ fprintf(stderr, "Render: missing vertex/fragment function\n");
+ return 1;
+ }
+
+ MTLRenderPipelineDescriptor *rpd = [[MTLRenderPipelineDescriptor alloc] init];
+ rpd.vertexFunction = vfn;
+ rpd.fragmentFunction = ffn;
+ rpd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
+ id<MTLRenderPipelineState> pso = [dev newRenderPipelineStateWithDescriptor:rpd error:&err];
+ if (!pso) {
+ fprintf(stderr, "Render: newRenderPipelineState failed: %s\n", err.localizedDescription.UTF8String);
+ return 1;
+ }
+
+ const NSUInteger W = 64, H = 64;
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
+ width:W height:H mipmapped:NO];
+ td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ td.storageMode = MTLStorageModePrivate;
+ id<MTLTexture> target = [dev newTextureWithDescriptor:td];
+ id<MTLBuffer> readback = [dev newBufferWithLength:W * H * 4 options:MTLResourceStorageModeShared];
+ if (!target || !readback) {
+ fprintf(stderr, "Render: texture or readback buffer alloc failed\n");
+ return 1;
+ }
+
+ MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
+ pass.colorAttachments[0].texture = target;
+ pass.colorAttachments[0].loadAction = MTLLoadActionClear;
+ pass.colorAttachments[0].storeAction = MTLStoreActionStore;
+ pass.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 1.0, 1.0);
+
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ id<MTLRenderCommandEncoder> renc = [cb renderCommandEncoderWithDescriptor:pass];
+ [renc setRenderPipelineState:pso];
+ [renc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
+ [renc endEncoding];
+
+ id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
+ [blit copyFromTexture:target sourceSlice:0 sourceLevel:0
+ sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(W, H, 1)
+ toBuffer:readback destinationOffset:0 destinationBytesPerRow:W * 4 destinationBytesPerImage:W * H * 4];
+ [blit endEncoding];
+
+ [cb commit];
+ [cb waitUntilCompleted];
+
+ const uint8_t *px = (const uint8_t *)readback.contents;
+ const uint8_t *center = px + (32 * W + 32) * 4;
+ const uint8_t *corner = px + (2 * W + 2) * 4;
+ int triPixels = 0, bluePixels = 0, otherPixels = 0;
+ for (NSUInteger i = 0; i < W * H; i++) {
+ const uint8_t *p = px + i * 4;
+ if (p[0] > 240 && p[1] >= 45 && p[1] <= 57 && p[2] < 10 && p[3] == 255) triPixels++;
+ else if (p[0] == 0 && p[1] == 0 && p[2] == 255 && p[3] == 255) bluePixels++;
+ else otherPixels++;
+ }
+ printf("Render pass status=%lu: center=(%u,%u,%u,%u) corner=(%u,%u,%u,%u) triPx=%d bluePx=%d otherPx=%d\n",
+ (unsigned long)cb.status,
+ center[0], center[1], center[2], center[3],
+ corner[0], corner[1], corner[2], corner[3],
+ triPixels, bluePixels, otherPixels);
+
+ bool ok = (cb.status == MTLCommandBufferStatusCompleted) &&
+ (center[0] > 240 && center[2] < 10) &&
+ (corner[0] == 0 && corner[2] == 255) &&
+ (triPixels > 800 && bluePixels > 2000 && otherPixels == 0);
+ printf("Render pass verdict: %s\n", ok ? "PASS" : "FAIL");
+ return ok ? 0 : 1;
+}
+
+static bool render_ci_blur(id<MTLDevice> dev, const uint8_t *srcBytes, size_t W, size_t H, uint8_t *outBytes) {
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ NSData *srcData = [NSData dataWithBytes:srcBytes length:W * H * 4];
+ CIImage *input = [CIImage imageWithBitmapData:srcData
+ bytesPerRow:W * 4
+ size:CGSizeMake(W, H)
+ format:kCIFormatRGBA8
+ colorSpace:cs];
+ CIFilter *blur = [CIFilter filterWithName:@"CIGaussianBlur"];
+ [blur setValue:input forKey:kCIInputImageKey];
+ [blur setValue:@(4.0) forKey:kCIInputRadiusKey];
+ CIImage *output = blur.outputImage;
+
+ NSDictionary *opts = @{
+ kCIContextWorkingFormat: @(kCIFormatRGBAh),
+ kCIContextCacheIntermediates: @NO,
+ };
+ CIContext *ctx = [CIContext contextWithMTLDevice:dev options:opts];
+ if (!ctx || !output) {
+ CGColorSpaceRelease(cs);
+ return false;
+ }
+
+ memset(outBytes, 0x55, W * H * 4);
+ NSError *err = nil;
+ CIRenderDestination *dest = [[CIRenderDestination alloc] initWithBitmapData:outBytes
+ width:W
+ height:H
+ bytesPerRow:W * 4
+ format:kCIFormatRGBA8];
+ dest.colorSpace = cs;
+ CIRenderTask *task = [ctx startTaskToRender:output
+ fromRect:CGRectMake(0, 0, W, H)
+ toDestination:dest
+ atPoint:CGPointZero
+ error:&err];
+ bool ok = false;
+ if (!task) {
+ fprintf(stderr, "CoreImage(%s) startTaskToRender failed: %s\n",
+ dev.name.UTF8String, err.localizedDescription.UTF8String ?: "(nil)");
+ } else {
+ CIRenderInfo *info = [task waitUntilCompletedAndReturnError:&err];
+ if (!info) {
+ fprintf(stderr, "CoreImage(%s) waitUntilCompleted failed: %s\n",
+ dev.name.UTF8String, err.localizedDescription.UTF8String ?: "(nil)");
+ } else {
+ ok = true;
+ }
+ }
+ CGColorSpaceRelease(cs);
+ return ok;
+}
+
+static int run_coreimage_blur_test(id<MTLDevice> cpuDev) {
+ printf("\n=== [Test B] CoreImage CIContext(mtlDevice:) + CIGaussianBlur (CPU Metal vs Native GPU) ===\n");
+ const size_t W = 64, H = 64;
+ uint8_t srcBytes[W * H * 4];
+ memset(srcBytes, 0, sizeof(srcBytes));
+ // White 16x16 square in center [24..40), alpha=255 everywhere
+ for (size_t y = 0; y < H; y++) {
+ for (size_t x = 0; x < W; x++) {
+ uint8_t *p = srcBytes + (y * W + x) * 4;
+ bool inside = (x >= 24 && x < 40 && y >= 24 && y < 40);
+ p[0] = inside ? 255 : 0;
+ p[1] = inside ? 255 : 0;
+ p[2] = inside ? 255 : 0;
+ p[3] = 255;
+ }
+ }
+
+ uint8_t cpuOut[W * H * 4];
+ uint8_t gpuOut[W * H * 4];
+
+ if (!render_ci_blur(cpuDev, srcBytes, W, H, cpuOut)) {
+ printf("CoreImage CIGaussianBlur verdict: FAIL (CPU Metal render failed)\n");
+ return 1;
+ }
+
+ id<MTLDevice> nativeDev = MTLCreateSystemDefaultDevice();
+ if (!nativeDev || !render_ci_blur(nativeDev, srcBytes, W, H, gpuOut)) {
+ printf("CoreImage CIGaussianBlur verdict: FAIL (Native GPU reference render failed)\n");
+ return 1;
+ }
+
+ int maxErr = 0;
+ double sumErr = 0.0;
+ size_t nonZeroDiff = 0;
+ for (size_t i = 0; i < W * H * 4; i++) {
+ int d = abs((int)cpuOut[i] - (int)gpuOut[i]);
+ if (d > maxErr) maxErr = d;
+ if (d > 0) nonZeroDiff++;
+ sumErr += (double)d;
+ }
+ double meanErr = sumErr / (double)(W * H * 4);
+
+ const uint8_t *cc = cpuOut + (32 * W + 32) * 4;
+ const uint8_t *ce = cpuOut + (22 * W + 32) * 4;
+ const uint8_t *co = cpuOut + (2 * W + 2) * 4;
+ const uint8_t *gc = gpuOut + (32 * W + 32) * 4;
+ const uint8_t *ge = gpuOut + (22 * W + 32) * 4;
+ const uint8_t *go = gpuOut + (2 * W + 2) * 4;
+
+ printf("CPU Metal (%s): center=(%u,%u,%u,%u) edge_2px_out=(%u,%u,%u,%u) corner=(%u,%u,%u,%u)\n",
+ cpuDev.name.UTF8String,
+ cc[0], cc[1], cc[2], cc[3], ce[0], ce[1], ce[2], ce[3], co[0], co[1], co[2], co[3]);
+ printf("Native GPU (%s): center=(%u,%u,%u,%u) edge_2px_out=(%u,%u,%u,%u) corner=(%u,%u,%u,%u)\n",
+ nativeDev.name.UTF8String,
+ gc[0], gc[1], gc[2], gc[3], ge[0], ge[1], ge[2], ge[3], go[0], go[1], go[2], go[3]);
+ printf("Pixel diff (64x64x4=%zu channels): maxErr=%d, meanErr=%.4f, nonZeroDiff=%zu\n",
+ W * H * 4, maxErr, meanErr, nonZeroDiff);
+
+ bool ok = (cc[0] > 180) && (ce[0] > 20 && ce[0] < cc[0]) && (co[0] < 10) && (maxErr <= 20) && (meanErr < 4.0);
+ printf("CoreImage CIGaussianBlur verdict: %s\n", ok ? "PASS" : "FAIL");
+ return ok ? 0 : 1;
+}
+
+int main(int argc, const char **argv) {
+ @autoreleasepool {
+ if (argc < 3) {
+ fprintf(stderr, "Usage: %s <XnuCpuMetal.bundle> <tri.metallib>\n", argv[0]);
+ return 2;
+ }
+ NSBundle *bundle = [NSBundle bundleWithPath:[NSString stringWithUTF8String:argv[1]]];
+ NSError *loadErr = nil;
+ if (!bundle || ![bundle loadAndReturnError:&loadErr]) {
+ fprintf(stderr, "Failed to load bundle: %s\n", loadErr.localizedDescription.UTF8String);
+ return 1;
+ }
+ id<MTLDevice> dev = [[[bundle principalClass] alloc] initWithAcceleratorPort:0];
+ if (!dev) {
+ fprintf(stderr, "initWithAcceleratorPort returned nil\n");
+ return 1;
+ }
+ printf("Loaded device: %s\n", dev.name.UTF8String);
+ int rc1 = run_render_pass_test(dev, [NSString stringWithUTF8String:argv[2]]);
+ int rc2 = run_coreimage_blur_test(dev);
+ return (rc1 == 0 && rc2 == 0) ? 0 : 1;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/test_round10.mm b/gpu/xnu-cpu-metal/test/test_round10.mm
new file mode 100644
index 0000000..e1314f2
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_round10.mm
@@ -0,0 +1,299 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <IOSurface/IOSurface.h>
+#include <dlfcn.h>
+#include <objc/message.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <execinfo.h>
+#include <signal.h>
+static void crash_h(int sig){ void *bt[32]; int n=backtrace(bt,32); fprintf(stderr,"CRASH sig=%d\n",sig); backtrace_symbols_fd(bt,n,2); _exit(128+sig); }
+
+
+@protocol XcmLinearBufferSPI <MTLBuffer>
+- (id<MTLTexture>)newLinearTextureWithDescriptor:(MTLTextureDescriptor *)desc
+ offset:(NSUInteger)offset
+ bytesPerRow:(NSUInteger)bytesPerRow
+ bytesPerImage:(NSUInteger)bytesPerImage;
+@end
+
+@interface XcmBundleDeviceStub : NSObject
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static id<MTLDevice> loadBundleDevice(const char *bundlePath) {
+ NSBundle *b = [NSBundle bundleWithPath:[NSString stringWithUTF8String:bundlePath]];
+ if (!b) { fprintf(stderr, "FAIL: bundle not found at %s\n", bundlePath); return nil; }
+ NSError *err = nil;
+ if (![b loadAndReturnError:&err]) {
+ fprintf(stderr, "FAIL: bundle load: %s\n", err.localizedDescription.UTF8String);
+ return nil;
+ }
+ Class cls = b.principalClass;
+ id dev = [(XcmBundleDeviceStub *)[cls alloc] initWithAcceleratorPort:0u];
+ return (id<MTLDevice>)dev;
+}
+
+static void *allocPages(size_t len) {
+ void *p = mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
+ return (p == MAP_FAILED) ? nullptr : p;
+}
+
+int main(int argc, char **argv) {
+ signal(SIGSEGV, crash_h); signal(SIGBUS, crash_h); setvbuf(stdout, nullptr, _IONBF, 0);
+ @autoreleasepool {
+ const char *bundlePath = (argc > 1) ? argv[1] : "dist/XnuCpuMetal.bundle";
+ id<MTLDevice> dev = loadBundleDevice(bundlePath);
+ if (!dev) { fprintf(stderr, "FAIL: device open returned nil\n"); return 1; }
+ printf("Loaded device: %s\n", dev.name.UTF8String);
+
+ // ---- Test 1: CAEnableIOSurfaceCompression in-memory only (no plist on disk) ----
+ {
+ Boolean valid = false;
+ Boolean val = CFPreferencesGetAppBooleanValue(
+ CFSTR("CAEnableIOSurfaceCompression"), kCFPreferencesCurrentApplication, &valid);
+ if (!valid || val) {
+ fprintf(stderr, "FAIL: CAEnableIOSurfaceCompression valid=%d val=%d (expected 1, 0)\n",
+ (int)valid, (int)val);
+ return 2;
+ }
+ NSString *plistPath = [NSHomeDirectory() stringByAppendingPathComponent:
+ @"Library/Preferences/test_round10.plist"];
+ struct stat st;
+ if (stat(plistPath.fileSystemRepresentation, &st) == 0) {
+ fprintf(stderr, "FAIL: unexpected plist created on disk at %s\n", plistPath.UTF8String);
+ return 3;
+ }
+ printf("PASS [1/4]: CAEnableIOSurfaceCompression=NO in-memory only (no plist on disk)\n");
+ }
+
+ // ---- Test 2: WindowServer 4 buffer-backed linear texture shapes + live CPU mutation ----
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ if (!q) { fprintf(stderr, "FAIL: newCommandQueue nil\n"); return 4; }
+
+ {
+ struct Shape {
+ const char *name;
+ size_t bufLen;
+ NSUInteger offset;
+ NSUInteger w, h, bpr, bpi;
+ MTLPixelFormat fmt;
+ } shapes[] = {
+ {"84x103_rg8_o0", 0x5000, 0x0000, 84, 103, 192, 19752, MTLPixelFormatRG8Unorm},
+ {"234x18_bgra_o100", 0x5000, 0x0100, 234, 18, 960, 17256, MTLPixelFormatBGRA8Unorm},
+ {"256x1_rgba16f_o0", 0x1000, 0x0000, 256, 1, 2048, 2048, MTLPixelFormatRGBA16Float},
+ {"1x1_bgra_o100", 0x1000, 0x0100, 1, 1, 64, 4, MTLPixelFormatBGRA8Unorm},
+ };
+ for (const auto &s : shapes) {
+ void *mem = allocPages(s.bufLen);
+ if (!mem) { fprintf(stderr, "FAIL: mmap %s\n", s.name); return 5; }
+ memset(mem, 0x5A, s.bufLen);
+ __block BOOL deallocCalled = NO;
+ @autoreleasepool {
+ id<MTLBuffer> buf = [dev newBufferWithBytesNoCopy:mem
+ length:s.bufLen
+ options:MTLResourceStorageModeShared
+ deallocator:^(void *ptr, NSUInteger len) {
+ deallocCalled = YES;
+ munmap(ptr, len);
+ }];
+ if (!buf) { fprintf(stderr, "FAIL: no-copy buffer nil for %s\n", s.name); return 6; }
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:s.fmt
+ width:s.w
+ height:s.h
+ mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageShaderRead;
+ id<MTLTexture> tex = [(id<XcmLinearBufferSPI>)buf
+ newLinearTextureWithDescriptor:td offset:s.offset bytesPerRow:s.bpr bytesPerImage:s.bpi];
+ if (!tex) { fprintf(stderr, "FAIL: newLinearTexture returned nil for %s\n", s.name); return 7; }
+ if (tex.buffer != buf || tex.bufferOffset != s.offset || tex.bufferBytesPerRow != s.bpr) {
+ fprintf(stderr, "FAIL: metadata mismatch for %s (buf=%p/%p off=%lu/%lu bpr=%lu/%lu)\n",
+ s.name, (__bridge void *)tex.buffer, (__bridge void *)buf,
+ (unsigned long)tex.bufferOffset, (unsigned long)s.offset,
+ (unsigned long)tex.bufferBytesPerRow, (unsigned long)s.bpr);
+ return 8;
+ }
+ // Also test standard MTLBuffer newTextureWithDescriptor:offset:bytesPerRow:
+ id<MTLTexture> tex2 = [buf newTextureWithDescriptor:td offset:s.offset bytesPerRow:s.bpr];
+ if (!tex2) { fprintf(stderr, "FAIL: newTextureWithDescriptor returned nil for %s\n", s.name); return 9; }
+ }
+ if (!deallocCalled) {
+ fprintf(stderr, "FAIL: no-copy buffer deallocator not called for %s\n", s.name);
+ return 10;
+ }
+ }
+
+ // Live CPU mutation test with shader sampling -> IOSurface render target
+ const NSUInteger W = 234, H = 18, BPR = 960, OFF = 0x100, BLEN = 0x5000;
+ void *mem = allocPages(BLEN);
+ id<MTLBuffer> buf = [dev newBufferWithBytesNoCopy:mem length:BLEN options:MTLResourceStorageModeShared
+ deallocator:^(void *ptr, NSUInteger len) { munmap(ptr, len); }];
+ MTLTextureDescriptor *srcDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:W height:H mipmapped:NO];
+ srcDesc.storageMode = MTLStorageModeShared;
+ srcDesc.usage = MTLTextureUsageShaderRead;
+ id<MTLTexture> srcTex = [(id<XcmLinearBufferSPI>)buf
+ newLinearTextureWithDescriptor:srcDesc offset:OFF bytesPerRow:BPR bytesPerImage:BPR * H];
+
+ MTLTextureDescriptor *dstDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:16 height:16 mipmapped:NO];
+ dstDesc.storageMode = MTLStorageModeShared;
+ dstDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ id<MTLTexture> dstTex = [dev newTextureWithDescriptor:dstDesc];
+
+ NSString *msl =
+ @"#include <metal_stdlib>\n"
+ "using namespace metal;\n"
+ "struct VOut { float4 pos [[position]]; float2 uv; };\n"
+ "vertex VOut vs(uint vid [[vertex_id]]) {\n"
+ " float2 p[3] = { float2(-1,-1), float2(3,-1), float2(-1,3) };\n"
+ " VOut o; o.pos = float4(p[vid], 0, 1); o.uv = float2(0.5, 0.5); return o;\n"
+ "}\n"
+ "fragment half4 fs(VOut in [[stage_in]], texture2d<half> t [[texture(0)]]) {\n"
+ " constexpr sampler s(filter::nearest);\n"
+ " return t.sample(s, in.uv);\n"
+ "}\n";
+ NSError *err = nil;
+ id<MTLLibrary> lib = [dev newLibraryWithSource:msl options:nil error:&err];
+ if (!lib) { fprintf(stderr, "FAIL: shader compile: %s\n", err.localizedDescription.UTF8String); return 11; }
+ MTLRenderPipelineDescriptor *rpd = [[MTLRenderPipelineDescriptor alloc] init];
+ rpd.vertexFunction = [lib newFunctionWithName:@"vs"];
+ rpd.fragmentFunction = [lib newFunctionWithName:@"fs"];
+ rpd.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
+ id<MTLRenderPipelineState> pso = [dev newRenderPipelineStateWithDescriptor:rpd error:&err];
+ if (!pso) { fprintf(stderr, "FAIL: PSO: %s\n", err.localizedDescription.UTF8String); return 12; }
+
+ auto fillAndRender = [&](uint32_t bgraPixel) -> uint32_t {
+ uint8_t *base = (uint8_t *)mem + OFF;
+ for (NSUInteger y = 0; y < H; y++) {
+ uint32_t *row = (uint32_t *)(base + y * BPR);
+ for (NSUInteger x = 0; x < W; x++) row[x] = bgraPixel;
+ }
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = dstTex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ rp.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 0);
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setRenderPipelineState:pso];
+ [enc setFragmentTexture:srcTex atIndex:0];
+ [enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
+ [enc endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) {
+ fprintf(stderr, "FAIL: render CB status=%lu err=%s\n",
+ (unsigned long)cb.status, cb.error.localizedDescription.UTF8String);
+ return 0;
+ }
+ uint32_t outPx = 0;
+ [dstTex getBytes:&outPx bytesPerRow:16 * 4 fromRegion:MTLRegionMake2D(8, 8, 1, 1) mipmapLevel:0];
+ return outPx;
+ };
+
+ uint32_t p1 = fillAndRender(0xFF112233u);
+ uint32_t p2 = fillAndRender(0xFF44CC88u);
+ if (p1 != 0xFF112233u || p2 != 0xFF44CC88u) {
+ fprintf(stderr, "FAIL: live buffer mutation mismatch: frame1=0x%08x (exp 0xFF112233) frame2=0x%08x (exp 0xFF44CC88)\n", p1, p2);
+ return 13;
+ }
+ printf("PASS [2/4]: All 4 WindowServer linear texture shapes + live CPU mutation (0x%08x -> 0x%08x) + deallocator\n", p1, p2);
+ }
+
+ // ---- Test 3: MTLSharedEvent + MTLSharedEventListener + Handle ----
+ {
+ id<MTLSharedEvent> ev = [dev newSharedEvent];
+ if (!ev) { fprintf(stderr, "FAIL: newSharedEvent returned nil\n"); return 14; }
+ if (![ev conformsToProtocol:@protocol(MTLSharedEvent)]) {
+ fprintf(stderr, "FAIL: event does not conform to MTLSharedEvent\n"); return 15;
+ }
+ if (ev.signaledValue != 0) {
+ fprintf(stderr, "FAIL: initial signaledValue=%llu\n", ev.signaledValue); return 16;
+ }
+ dispatch_queue_t notifyQ = dispatch_queue_create("test.shared.event", DISPATCH_QUEUE_SERIAL);
+ MTLSharedEventListener *listener = [[MTLSharedEventListener alloc] initWithDispatchQueue:notifyQ];
+ dispatch_semaphore_t sem = dispatch_semaphore_create(0);
+ __block uint64_t seenVal = 0;
+ [ev notifyListener:listener atValue:1 block:^(id<MTLSharedEvent> e, uint64_t val) {
+ (void)e;
+ seenVal = val;
+ dispatch_semaphore_signal(sem);
+ }];
+
+ id<MTLCommandBuffer> cb1 = [q commandBuffer];
+ [cb1 encodeSignalEvent:ev value:1];
+ [cb1 commit];
+ [cb1 waitUntilCompleted];
+ if (cb1.status != MTLCommandBufferStatusCompleted) {
+ fprintf(stderr, "FAIL: cb1 status=%lu err=%s\n",
+ (unsigned long)cb1.status, cb1.error.localizedDescription.UTF8String);
+ return 17;
+ }
+ if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC)) != 0 || seenVal < 1) {
+ fprintf(stderr, "FAIL: MTLSharedEventListener did not fire (seenVal=%llu)\n", seenVal);
+ return 18;
+ }
+ if (![ev waitUntilSignaledValue:1 timeoutMS:1000]) {
+ fprintf(stderr, "FAIL: waitUntilSignaledValue(1) returned NO\n"); return 19;
+ }
+
+ // Wait on value 2 -> signal value 3, unblocked from CPU via setSignaledValue:2
+ id<MTLCommandBuffer> cb2 = [q commandBuffer];
+ [cb2 encodeWaitForEvent:ev value:2];
+ [cb2 encodeSignalEvent:ev value:3];
+ [cb2 commit];
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_MSEC),
+ dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
+ ev.signaledValue = 2;
+ });
+ [cb2 waitUntilCompleted];
+ if (cb2.status != MTLCommandBufferStatusCompleted || ev.signaledValue != 3) {
+ fprintf(stderr, "FAIL: cb2 status=%lu val=%llu\n", (unsigned long)cb2.status, ev.signaledValue);
+ return 20;
+ }
+
+ // Handle round-trip
+ MTLSharedEventHandle *h = [ev newSharedEventHandle];
+ id<MTLSharedEvent> evAlias = h ? [dev newSharedEventWithHandle:h] : nil;
+ if (!evAlias || evAlias.signaledValue != 3) {
+ fprintf(stderr, "FAIL: shared event handle alias failed (evAlias=%p val=%llu)\n",
+ (__bridge void *)evAlias, evAlias ? evAlias.signaledValue : 0);
+ return 21;
+ }
+ printf("PASS [3/4]: MTLSharedEvent + MTLSharedEventListener + CPU wait/signal + Handle alias\n");
+ }
+
+ // ---- Test 4: MTLFence across Blit -> Compute encoders ----
+ {
+ id<MTLFence> fence = [dev newFence];
+ id<MTLBuffer> b1 = [dev newBufferWithLength:256 options:MTLResourceStorageModeShared];
+ id<MTLBuffer> b2 = [dev newBufferWithLength:256 options:MTLResourceStorageModeShared];
+ memset(b1.contents, 0xAB, 256);
+ memset(b2.contents, 0x00, 256);
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
+ [blit copyFromBuffer:b1 sourceOffset:0 toBuffer:b2 destinationOffset:0 size:256];
+ [blit updateFence:fence];
+ [blit endEncoding];
+ id<MTLBlitCommandEncoder> blit2 = [cb blitCommandEncoder];
+ [blit2 waitForFence:fence];
+ [blit2 endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted || ((uint8_t *)b2.contents)[0] != 0xAB) {
+ fprintf(stderr, "FAIL: MTLFence blit test failed (status=%lu byte0=0x%02x)\n",
+ (unsigned long)cb.status, ((uint8_t *)b2.contents)[0]);
+ return 22;
+ }
+ printf("PASS [4/4]: MTLFence updateFence/waitForFence\n");
+ }
+
+ printf("ALL ROUND 10 TESTS PASSED!\n");
+ return 0;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/test_round13.mm b/gpu/xnu-cpu-metal/test/test_round13.mm
new file mode 100644
index 0000000..bcfe28b
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_round13.mm
@@ -0,0 +1,199 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#include <atomic>
+#include <execinfo.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <time.h>
+
+@interface XcmBundleDeviceStub : NSObject
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static void crashHandler(int sig) {
+ void *bt[32];
+ int n = backtrace(bt, 32);
+ fprintf(stderr, "\n=== CRASH sig=%d ===\n", sig);
+ backtrace_symbols_fd(bt, n, 2);
+ _exit(128 + sig);
+}
+
+static double nowSec() {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return ts.tv_sec + ts.tv_nsec * 1e-9;
+}
+
+static id<MTLDevice> loadBundleDevice(const char *bundlePath) {
+ NSBundle *b = [NSBundle bundleWithPath:[NSString stringWithUTF8String:bundlePath]];
+ if (!b || ![b load]) return nil;
+ return (id<MTLDevice>)[(XcmBundleDeviceStub *)[b.principalClass alloc] initWithAcceleratorPort:0u];
+}
+
+int main(int argc, char **argv) {
+ signal(SIGSEGV, crashHandler);
+ signal(SIGBUS, crashHandler);
+ signal(SIGABRT, crashHandler);
+ setvbuf(stdout, nullptr, _IONBF, 0);
+
+ @autoreleasepool {
+ const char *bundlePath = (argc > 1) ? argv[1] : "dist/XnuCpuMetal.bundle";
+ const char *mode = (argc > 2) ? argv[2] : "normal";
+ id<MTLDevice> dev = loadBundleDevice(bundlePath);
+ if (!dev) { fprintf(stderr, "FAIL: device nil\n"); return 1; }
+ printf("Round 13 test (%s): %s, LP_NUM_THREADS=%s, XNU_CPU_METAL_WATCHDOG_MS=%s\n",
+ mode, dev.name.UTF8String,
+ getenv("LP_NUM_THREADS") ?: "(default)",
+ getenv("XNU_CPU_METAL_WATCHDOG_MS") ?: "(default=3600s)");
+
+ // Test 1: Zero-length / NULL buffer semantics (must match Apple Metal: return nil, no deallocator call)
+ __block int zeroDealloc = 0;
+ id<MTLBuffer> z1 = [dev newBufferWithBytesNoCopy:nullptr length:0 options:0 deallocator:^(void *, NSUInteger) {
+ zeroDealloc++;
+ }];
+ id<MTLBuffer> z2 = [dev newBufferWithLength:0 options:0];
+ id<MTLBuffer> z3 = [dev newBufferWithBytes:nullptr length:0 options:0];
+ if (z1 != nil || z2 != nil || z3 != nil || zeroDealloc != 0) {
+ fprintf(stderr, "FAIL [1]: zero-length buffers z1=%p z2=%p z3=%p dealloc=%d\n",
+ (__bridge void *)z1, (__bridge void *)z2, (__bridge void *)z3, zeroDealloc);
+ return 2;
+ }
+ printf("PASS [1]: newBufferWithBytesNoCopy(NULL,0) / newBufferWithLength(0) / newBufferWithBytes(NULL,0) all return nil without calling deallocator\n");
+
+ // Heavy vertex+fragment shader that reads from a vertex buffer and does heavy ALU work
+ // so we can reliably control single-CB duration on llvmpipe.
+ NSString *msl =
+ @"#include <metal_stdlib>\n"
+ "using namespace metal;\n"
+ "struct VIn { float4 pos; float4 col; };\n"
+ "struct VOut { float4 pos [[position]]; float4 col; };\n"
+ "vertex VOut vs(uint vid [[vertex_id]], device const VIn *verts [[buffer(0)]]) {\n"
+ " VOut o; o.pos = verts[vid].pos; o.col = verts[vid].col; return o;\n"
+ "}\n"
+ "fragment float4 fs(VOut in [[stage_in]], constant uint &iters [[buffer(0)]]) {\n"
+ " float4 acc = in.col;\n"
+ " for (uint i = 0; i < iters; i++) {\n"
+ " acc = sin(acc * 1.0001f + float4(0.1f, 0.2f, 0.3f, 0.4f));\n"
+ " }\n"
+ " return float4(abs(acc.rgb), 1.0f);\n"
+ "}\n";
+ NSError *err = nil;
+ id<MTLLibrary> lib = [dev newLibraryWithSource:msl options:nil error:&err];
+ if (!lib) { fprintf(stderr, "FAIL: lib: %s\n", err.localizedDescription.UTF8String); return 3; }
+ MTLRenderPipelineDescriptor *rpd = [[MTLRenderPipelineDescriptor alloc] init];
+ rpd.vertexFunction = [lib newFunctionWithName:@"vs"];
+ rpd.fragmentFunction = [lib newFunctionWithName:@"fs"];
+ rpd.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
+ id<MTLRenderPipelineState> pso = [dev newRenderPipelineStateWithDescriptor:rpd error:&err];
+ if (!pso) { fprintf(stderr, "FAIL: pso: %s\n", err.localizedDescription.UTF8String); return 4; }
+
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:512 height:512 mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ id<MTLTexture> tex = [dev newTextureWithDescriptor:td];
+
+ // Build mmap-backed NoCopy vertex buffer with 6000 vertices (2000 full-screen triangles)
+ // placed right up to a page boundary so any UAF after munmap hits SIGSEGV immediately.
+ struct VIn { float pos[4]; float col[4]; };
+ const int numVerts = 600;
+ size_t vbytes = numVerts * sizeof(VIn);
+ size_t pg = 16384;
+ size_t allocSz = (vbytes + pg - 1) & ~(pg - 1);
+
+ auto makeVBuf = ^id<MTLBuffer>(std::atomic<int> *deallocCounter) {
+ void *mem = mmap(nullptr, allocSz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
+ if (mem == MAP_FAILED) return nil;
+ VIn *v = (VIn *)mem;
+ float tri[3][2] = { {-1.0f, -1.0f}, {1.0f, -1.0f}, {0.0f, 1.0f} };
+ for (int i = 0; i < numVerts; i++) {
+ v[i].pos[0] = tri[i % 3][0]; v[i].pos[1] = tri[i % 3][1]; v[i].pos[2] = 0; v[i].pos[3] = 1;
+ v[i].col[0] = 0.3f; v[i].col[1] = 0.6f; v[i].col[2] = 0.9f; v[i].col[3] = 1.0f;
+ }
+ return [dev newBufferWithBytesNoCopy:mem length:allocSz options:MTLResourceStorageModeShared
+ deallocator:^(void *ptr, NSUInteger len) {
+ munmap(ptr, len);
+ if (deallocCounter) deallocCounter->fetch_add(1);
+ }];
+ };
+
+ if (strcmp(mode, "hang_uaf") == 0) {
+ // Test 2 (forced watchdog mode): XNU_CPU_METAL_WATCHDOG_MS=1000 while draw runs ~3s.
+ // Must NOT SIGSEGV when watchdog fires and parks device!
+ static std::atomic<int> dealloced{0};
+ double t0 = nowSec();
+ @autoreleasepool {
+ id<MTLBuffer> vb = makeVBuf(&dealloced);
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = tex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setRenderPipelineState:pso];
+ [enc setVertexBuffer:vb offset:0 atIndex:0];
+ uint32_t iters = 80;
+ [enc setFragmentBytes:&iters length:sizeof(iters) atIndex:0];
+ for (int d = 0; d < 20; d++) {
+ [enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:numVerts];
+ }
+ [enc endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+ printf("hang_uaf cb done in %.2fs: status=%lu err=%s dealloced=%d\n",
+ nowSec() - t0, (unsigned long)cb.status,
+ cb.error ? cb.error.localizedDescription.UTF8String : "none",
+ dealloced.load());
+ }
+ // Wait 3s while lavapipe finishes executing the parked draw — must NOT SIGSEGV!
+ sleep(3);
+ printf("PASS [hang_uaf]: survived parked-device watchdog without SIGSEGV (dealloced=%d)\n", dealloced.load());
+ return 0;
+ }
+
+ // Test 2 (normal CPU mode): continuous heavy draws + slow CB (>21s? or configurable via argv[3])
+ // Default: run a single heavy batch + follow-up batches to verify no GpuHang / AccessRevoked.
+ uint32_t iters = (argc > 3) ? (uint32_t)atoi(argv[3]) : 40;
+ int drawsPerCb = (argc > 4) ? atoi(argv[4]) : 8;
+ int numCbs = (argc > 5) ? atoi(argv[5]) : 4;
+ static std::atomic<int> normDealloc{0};
+ double t0 = nowSec();
+ for (int c = 0; c < numCbs; c++) {
+ @autoreleasepool {
+ id<MTLBuffer> vb = makeVBuf(&normDealloc);
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = tex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setRenderPipelineState:pso];
+ [enc setVertexBuffer:vb offset:0 atIndex:0];
+ [enc setFragmentBytes:&iters length:sizeof(iters) atIndex:0];
+ for (int d = 0; d < drawsPerCb; d++) {
+ [enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:numVerts];
+ }
+ [enc endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) {
+ fprintf(stderr, "FAIL [2]: cb %d status=%lu err=%s\n", c, (unsigned long)cb.status,
+ cb.error ? cb.error.localizedDescription.UTF8String : "none");
+ return 5;
+ }
+ }
+ }
+ usleep(200000);
+ printf("PASS [2]: %d heavy CBs (%d draws/CB, iters=%u) completed in %.2fs with 0 GpuHang/AccessRevoked, dealloced=%d/%d\n",
+ numCbs, drawsPerCb, iters, nowSec() - t0, normDealloc.load(), numCbs);
+ if (normDealloc.load() != numCbs) {
+ fprintf(stderr, "FAIL [2]: dealloced=%d != %d\n", normDealloc.load(), numCbs);
+ return 6;
+ }
+ return 0;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/test_round14_vfx.mm b/gpu/xnu-cpu-metal/test/test_round14_vfx.mm
new file mode 100644
index 0000000..ec6c53c
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_round14_vfx.mm
@@ -0,0 +1,213 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <IOKit/IOKitLib.h>
+#import <AppKit/AppKit.h>
+#import <SceneKit/SceneKit.h>
+#import <objc/runtime.h>
+#import <objc/message.h>
+#include <dlfcn.h>
+#include <execinfo.h>
+#include <mach-o/dyld.h>
+#include <mach-o/getsect.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <set>
+#include <string>
+
+static void crashHandler(int sig) {
+ void *bt[40];
+ int n = backtrace(bt, 40);
+ fprintf(stderr, "\n=== CRASH sig=%d ===\n", sig);
+ backtrace_symbols_fd(bt, n, 2);
+ _exit(128 + sig);
+}
+
+@interface XcmBundleDeviceStub : NSObject
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static void collectProtocolSels(Protocol *p, std::set<std::string> &out, std::set<Protocol *> &seen) {
+ if (!p || seen.count(p)) return;
+ seen.insert(p);
+ for (int req = 0; req <= 1; req++) {
+ unsigned cnt = 0;
+ struct objc_method_description *mds = protocol_copyMethodDescriptionList(p, req != 0, YES, &cnt);
+ for (unsigned i = 0; i < cnt; i++) {
+ if (mds[i].name) out.insert(sel_getName(mds[i].name));
+ }
+ free(mds);
+ }
+ unsigned pcnt = 0;
+ Protocol * __unsafe_unretained *plist = protocol_copyProtocolList(p, &pcnt);
+ for (unsigned i = 0; i < pcnt; i++) collectProtocolSels(plist[i], out, seen);
+ free(plist);
+}
+
+int main(int argc, char **argv) {
+ signal(SIGSEGV, crashHandler);
+ signal(SIGBUS, crashHandler);
+ signal(SIGABRT, crashHandler);
+ setvbuf(stdout, nullptr, _IONBF, 0);
+ @autoreleasepool {
+ const char *bundlePath = (argc > 1) ? argv[1] : "dist/XnuCpuMetal.bundle";
+ id<MTLDevice> native = MTLCreateSystemDefaultDevice();
+ NSBundle *b = [NSBundle bundleWithPath:[NSString stringWithUTF8String:bundlePath]];
+ if (!b || ![b load]) { fprintf(stderr, "FAIL: load bundle\n"); return 1; }
+ // Pass a real IOAccelerator service port so XcmBackendDevice gets a valid IORegistry registryID
+ // (matching hosted macOS; VFX looks up devices by registryID in its global resource manager table).
+ io_service_t accelPort = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("IOAccelerator"));
+ id<MTLDevice> dev = (id<MTLDevice>)[(XcmBundleDeviceStub *)[b.principalClass alloc] initWithAcceleratorPort:accelPort];
+ if (accelPort) IOObjectRelease(accelPort);
+ if (!dev) { fprintf(stderr, "FAIL: device nil\n"); return 2; }
+ printf("Round 14 test: %s\n", dev.name.UTF8String);
+
+ // [1] Check isDepth24Stencil8PixelFormatSupported == NO (matches Apple Silicon)
+ if ([dev isDepth24Stencil8PixelFormatSupported] != NO) {
+ fprintf(stderr, "FAIL [1]: isDepth24Stencil8PixelFormatSupported expected NO\n");
+ return 3;
+ }
+ printf("PASS [1]: isDepth24Stencil8PixelFormatSupported == NO\n");
+
+ // [2] Protocol completeness vs Apple Silicon native device (MTLDevice + MTLDeviceSPI)
+ std::set<std::string> allSels;
+ std::set<Protocol *> seen;
+ collectProtocolSels(@protocol(MTLDevice), allSels, seen);
+ collectProtocolSels(objc_getProtocol("MTLDeviceSPI"), allSels, seen);
+ int missingProto = 0;
+ for (const auto &s : allSels) {
+ SEL sel = sel_registerName(s.c_str());
+ if ([native respondsToSelector:sel] && ![dev respondsToSelector:sel]) {
+ fprintf(stderr, "FAIL [2]: missing protocol selector: %s\n", s.c_str());
+ missingProto++;
+ }
+ }
+ if (missingProto) return 4;
+ printf("PASS [2]: 0 missing selectors across MTLDevice + MTLDeviceSPI\n");
+
+ // [3] Depth32Float_Stencil8 render pass verification (VFX fallback depth format)
+ {
+ MTLTextureDescriptor *ctd = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:64 height:64 mipmapped:NO];
+ ctd.storageMode = MTLStorageModeShared;
+ ctd.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ id<MTLTexture> colorTex = [dev newTextureWithDescriptor:ctd];
+
+ MTLTextureDescriptor *dtd = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatDepth32Float_Stencil8
+ width:64 height:64 mipmapped:NO];
+ dtd.storageMode = MTLStorageModePrivate;
+ dtd.usage = MTLTextureUsageRenderTarget;
+ id<MTLTexture> depthTex = [dev newTextureWithDescriptor:dtd];
+ if (!colorTex || !depthTex) { fprintf(stderr, "FAIL [3]: Depth32Float_Stencil8 texture nil\n"); return 5; }
+
+ MTLDepthStencilDescriptor *dsd = [[MTLDepthStencilDescriptor alloc] init];
+ dsd.depthCompareFunction = MTLCompareFunctionLess;
+ dsd.depthWriteEnabled = YES;
+ id<MTLDepthStencilState> ds = [dev newDepthStencilStateWithDescriptor:dsd];
+ if (!ds) { fprintf(stderr, "FAIL [3]: depthStencilState nil\n"); return 5; }
+
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = colorTex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ rp.colorAttachments[0].clearColor = MTLClearColorMake(0.2, 0.4, 0.6, 1.0);
+ rp.depthAttachment.texture = depthTex;
+ rp.depthAttachment.loadAction = MTLLoadActionClear;
+ rp.depthAttachment.storeAction = MTLStoreActionDontCare;
+ rp.depthAttachment.clearDepth = 1.0;
+ rp.stencilAttachment.texture = depthTex;
+ rp.stencilAttachment.loadAction = MTLLoadActionClear;
+ rp.stencilAttachment.storeAction = MTLStoreActionDontCare;
+ rp.stencilAttachment.clearStencil = 0;
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setDepthStencilState:ds];
+ [enc endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) {
+ fprintf(stderr, "FAIL [3]: Depth32Float_Stencil8 render pass status=%lu\n", (unsigned long)cb.status);
+ return 5;
+ }
+ printf("PASS [3]: Depth32Float_Stencil8 texture + depth/stencil render pass completed\n");
+ }
+
+ // [4] SceneKit SCNRenderer with our CPU Metal device (exercises SceneKit + VFX Metal device queries)
+ {
+ SCNRenderer *scn = [SCNRenderer rendererWithDevice:dev options:nil];
+ if (!scn) { fprintf(stderr, "FAIL [4]: SCNRenderer nil\n"); return 6; }
+ SCNScene *scene = [SCNScene scene];
+ SCNNode *boxNode = [SCNNode nodeWithGeometry:[SCNBox boxWithWidth:1 height:1 length:1 chamferRadius:0.1]];
+ [scene.rootNode addChildNode:boxNode];
+ scn.scene = scene;
+ printf("PASS [4]: SCNRenderer initialized with XcmBackendDevice (0 unrecognized selectors)\n");
+ }
+
+ // [5] VFX + AvatarKit AVTView initialization with our CPU Metal device
+ {
+ // Register dev in Metal.framework's device list (exact same registration IOKit performs
+ // in hosted macOS; VFX looks up devices in MTLCopyAllDevices by registryID).
+ void (*mtlAddDevice)(id<MTLDevice>) = (void (*)(id<MTLDevice>))dlsym(RTLD_DEFAULT, "MTLAddDevice");
+ if (mtlAddDevice) mtlAddDevice(dev);
+
+ void *vfxH = dlopen("/System/Library/PrivateFrameworks/VFX.framework/VFX", RTLD_NOW);
+ void *avtH = dlopen("/System/Library/PrivateFrameworks/AvatarKit.framework/AvatarKit", RTLD_NOW);
+ printf("dlopen VFX=%p AvatarKit=%p (MTLAddDevice=%p)\n", vfxH, avtH, (void *)mtlAddDevice);
+
+ // Try VFXRenderer if present
+ Class vfxRendererCls = objc_getClass("VFXRenderer");
+ if (vfxRendererCls && [vfxRendererCls respondsToSelector:@selector(rendererWithDevice:options:)]) {
+ id r = ((id (*)(id, SEL, id, id))objc_msgSend)(vfxRendererCls, @selector(rendererWithDevice:options:), dev, nil);
+ printf(" VFXRenderer with XcmBackendDevice -> %p\n", (__bridge void *)r);
+ if (!r) { fprintf(stderr, "FAIL [5]: VFXRenderer returned nil\n"); return 6; }
+ }
+
+ // Try AVTView initWithFrame:options: (exact loginwindow lock-screen path!)
+ Class avtViewCls = objc_getClass("AVTView");
+ if (avtViewCls) {
+ NSDictionary *opts = @{@"AVTViewMetalDeviceKey": dev, @"SCNPreferredDeviceKey": dev};
+ id view = [[avtViewCls alloc] initWithFrame:NSMakeRect(0, 0, 128, 128) options:opts];
+ printf(" AVTView initWithFrame:options: -> %p\n", (__bridge void *)view);
+ if (!view) { fprintf(stderr, "FAIL [5]: AVTView returned nil\n"); return 6; }
+ }
+ printf("PASS [5]: VFX + AvatarKit AVTView init completed with 0 unrecognized selectors\n");
+ }
+
+ // [6] Verify 0 missing __objc_selrefs across VFX, AvatarKit, SceneKit, CoreRE, QuartzCore, RenderBox, CoreImage
+ {
+ dlopen("/System/Library/PrivateFrameworks/CoreRE.framework/CoreRE", RTLD_LAZY);
+ dlopen("/System/Library/Frameworks/QuartzCore.framework/QuartzCore", RTLD_LAZY);
+ dlopen("/System/Library/PrivateFrameworks/RenderBox.framework/RenderBox", RTLD_LAZY);
+ dlopen("/System/Library/Frameworks/CoreImage.framework/CoreImage", RTLD_LAZY);
+ int missFw = 0;
+ for (uint32_t i = 0; i < _dyld_image_count(); i++) {
+ const char *name = _dyld_get_image_name(i);
+ if (!name) continue;
+ if (!strstr(name, "/VFX") && !strstr(name, "/AvatarKit") && !strstr(name, "/SceneKit") &&
+ !strstr(name, "/CoreRE") && !strstr(name, "/QuartzCore") && !strstr(name, "/RenderBox") &&
+ !strstr(name, "/CoreImage")) continue;
+ const struct mach_header_64 *mh = (const struct mach_header_64 *)_dyld_get_image_header(i);
+ const char *segs[] = {"__DATA_CONST", "__DATA", "__AUTH_CONST"};
+ for (auto seg : segs) {
+ unsigned long sz = 0;
+ const SEL *sels = (const SEL *)getsectiondata(mh, seg, "__objc_selrefs", &sz);
+ if (!sels || !sz) continue;
+ size_t n = sz / sizeof(SEL);
+ for (size_t k = 0; k < n; k++) {
+ SEL sel = sels[k];
+ if (sel && [native respondsToSelector:sel] && ![dev respondsToSelector:sel]) {
+ fprintf(stderr, "FAIL [6]: missing framework selref %s in %s\n", sel_getName(sel), name);
+ missFw++;
+ }
+ }
+ }
+ }
+ if (missFw) return 7;
+ printf("PASS [6]: 0 missing __objc_selrefs across all 7 frameworks\n");
+ }
+
+ return 0;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/test_stress_mt.mm b/gpu/xnu-cpu-metal/test/test_stress_mt.mm
new file mode 100644
index 0000000..d0ee2d6
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_stress_mt.mm
@@ -0,0 +1,281 @@
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <IOSurface/IOSurface.h>
+#import <QuartzCore/QuartzCore.h>
+#import <CoreGraphics/CoreGraphics.h>
+#include <atomic>
+#include <execinfo.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+
+@interface XcmBundleDeviceStub : NSObject
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static void crashHandler(int sig) {
+ void *bt[32];
+ int n = backtrace(bt, 32);
+ fprintf(stderr, "\n=== CRASH sig=%d ===\n", sig);
+ backtrace_symbols_fd(bt, n, 2);
+ _exit(128 + sig);
+}
+
+static id<MTLDevice> loadBundleDevice(const char *bundlePath) {
+ NSBundle *b = [NSBundle bundleWithPath:[NSString stringWithUTF8String:bundlePath]];
+ if (!b || ![b load]) return nil;
+ return (id<MTLDevice>)[(XcmBundleDeviceStub *)[b.principalClass alloc] initWithAcceleratorPort:0u];
+}
+
+int main(int argc, char **argv) {
+ signal(SIGSEGV, crashHandler);
+ signal(SIGBUS, crashHandler);
+ signal(SIGABRT, crashHandler);
+ setvbuf(stdout, nullptr, _IONBF, 0);
+
+ @autoreleasepool {
+ const char *bundlePath = (argc > 1) ? argv[1] : "dist/XnuCpuMetal.bundle";
+ int numThreads = (argc > 2) ? atoi(argv[2]) : 8;
+ int itersPerThread = (argc > 3) ? atoi(argv[3]) : 80;
+
+ id<MTLDevice> dev = loadBundleDevice(bundlePath);
+ if (!dev) { fprintf(stderr, "FAIL: device nil\n"); return 1; }
+ printf("Stress test: %s, threads=%d, iters=%d, LP_NUM_THREADS=%s\n",
+ dev.name.UTF8String, numThreads, itersPerThread, getenv("LP_NUM_THREADS") ?: "(default)");
+
+ NSString *msl =
+ @"#include <metal_stdlib>\n"
+ "using namespace metal;\n"
+ "struct VOut { float4 pos [[position]]; float4 col; };\n"
+ "vertex VOut vs(uint vid [[vertex_id]], constant float4 *tint [[buffer(0)]]) {\n"
+ " float2 p[3] = { float2(-0.8,-0.8), float2(0.8,-0.8), float2(0.0,0.8) };\n"
+ " VOut o; o.pos = float4(p[vid % 3], 0, 1); o.col = tint[0]; return o;\n"
+ "}\n"
+ "fragment half4 fs(VOut in [[stage_in]]) { return half4(in.col); }\n";
+ NSError *err = nil;
+ id<MTLLibrary> lib = [dev newLibraryWithSource:msl options:nil error:&err];
+ if (!lib) { fprintf(stderr, "FAIL: lib: %s\n", err.localizedDescription.UTF8String); return 2; }
+ MTLRenderPipelineDescriptor *rpd = [[MTLRenderPipelineDescriptor alloc] init];
+ rpd.vertexFunction = [lib newFunctionWithName:@"vs"];
+ rpd.fragmentFunction = [lib newFunctionWithName:@"fs"];
+ rpd.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
+ id<MTLRenderPipelineState> pso = [dev newRenderPipelineStateWithDescriptor:rpd error:&err];
+ if (!pso) { fprintf(stderr, "FAIL: pso: %s\n", err.localizedDescription.UTF8String); return 3; }
+
+ // Shared queue + per-thread queues
+ id<MTLCommandQueue> sharedQ = [dev newCommandQueue];
+ dispatch_group_t grp = dispatch_group_create();
+ dispatch_queue_t concQ = dispatch_queue_create("stress.mt", DISPATCH_QUEUE_CONCURRENT);
+ static std::atomic<int> completedCount{0};
+ static std::atomic<int> handlerCount{0};
+ static std::atomic<int> failures{0};
+
+ // Phase 1: Heavy concurrent commit + completedHandler + waitUntilCompleted + immediate release
+ for (int t = 0; t < numThreads; t++) {
+ dispatch_group_async(grp, concQ, ^{
+ id<MTLCommandQueue> q = (t % 2 == 0) ? sharedQ : [dev newCommandQueue];
+ for (int i = 0; i < itersPerThread; i++) {
+ @autoreleasepool {
+ int sz = 64 + ((t * 17 + i * 13) % 192);
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:sz height:sz mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ id<MTLTexture> tex = nil;
+ IOSurfaceRef surf = nullptr;
+ if (i % 3 == 0) {
+ NSDictionary *props = @{
+ (id)kIOSurfaceWidth: @(sz),
+ (id)kIOSurfaceHeight: @(sz),
+ (id)kIOSurfaceBytesPerElement: @4,
+ (id)kIOSurfacePixelFormat: @(0x42475241u),
+ };
+ surf = IOSurfaceCreate((__bridge CFDictionaryRef)props);
+ tex = [dev newTextureWithDescriptor:td iosurface:surf plane:0];
+ } else {
+ tex = [dev newTextureWithDescriptor:td];
+ }
+
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ [cb addScheduledHandler:^(id<MTLCommandBuffer> c) { (void)c; }];
+ [cb addCompletedHandler:^(id<MTLCommandBuffer> c) {
+ if (c.status != MTLCommandBufferStatusCompleted) failures.fetch_add(1);
+ handlerCount.fetch_add(1);
+ }];
+
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = tex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ rp.colorAttachments[0].clearColor = MTLClearColorMake(0.1, 0.2, 0.3, 1.0);
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setRenderPipelineState:pso];
+ float tint[4] = {1.0f, 0.5f, 0.25f, 1.0f};
+ [enc setVertexBytes:tint length:sizeof(tint) atIndex:0];
+ [enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:30];
+ [enc endEncoding];
+
+ [cb commit];
+ if (i % 2 == 0) {
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) failures.fetch_add(1);
+ }
+ // Immediately let cb, tex, surf drop out of autoreleasepool!
+ if (surf) CFRelease(surf);
+ completedCount.fetch_add(1);
+ }
+ }
+ });
+ }
+ dispatch_group_wait(grp, DISPATCH_TIME_FOREVER);
+ // Drain any non-waited CBs
+ usleep(300000);
+ printf("Phase 1 done: submitted=%d handlers=%d failures=%d\n",
+ completedCount.load(), handlerCount.load(), failures.load());
+
+ // Phase 2: Concurrent CARenderer across 4 threads (mimics iconservicesagent rendering icons concurrently)
+ static std::atomic<int> caDone{0};
+ for (int t = 0; t < 4; t++) {
+ dispatch_group_async(grp, concQ, ^{
+ for (int i = 0; i < 15; i++) {
+ @autoreleasepool {
+ int W = 128, H = 128;
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:W height:H mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
+ id<MTLTexture> tex = [dev newTextureWithDescriptor:td];
+
+ CALayer *root = [CALayer layer];
+ root.bounds = CGRectMake(0, 0, W, H);
+ root.position = CGPointMake(W / 2.0, H / 2.0);
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
+ CGFloat bgc[4] = {0.9, 0.9, 0.95, 1.0};
+ CGColorRef bg = CGColorCreate(cs, bgc);
+ root.backgroundColor = bg;
+ CGColorRelease(bg);
+ CALayer *child = [CALayer layer];
+ child.frame = CGRectMake(24, 24, W - 48, H - 48);
+ CGFloat cc[4] = {(t % 2) ? 0.9 : 0.2, 0.4, 0.8, 1.0};
+ CGColorRef fg = CGColorCreate(cs, cc);
+ child.backgroundColor = fg;
+ CGColorRelease(fg);
+ child.cornerRadius = 20.0;
+ child.shadowOpacity = 0.6f;
+ child.shadowRadius = 6.0;
+ [root addSublayer:child];
+ CGColorSpaceRelease(cs);
+
+ CARenderer *r = [CARenderer rendererWithMTLTexture:tex options:nil];
+ r.layer = root;
+ r.bounds = CGRectMake(0, 0, W, H);
+ [CATransaction flush];
+ [r beginFrameAtTime:CACurrentMediaTime() timeStamp:NULL];
+ [r addUpdateRect:r.bounds];
+ [r render];
+ [r endFrame];
+ caDone.fetch_add(1);
+ }
+ }
+ });
+ }
+ dispatch_group_wait(grp, DISPATCH_TIME_FOREVER);
+ usleep(300000);
+ printf("Phase 2 done: caDone=%d failures=%d\n", caDone.load(), failures.load());
+
+ // Phase 3: newBufferWithBytesNoCopy + munmap deallocator + immediate release after commit
+ static std::atomic<int> noCopyDone{0};
+ static std::atomic<int> deallocCount{0};
+ for (int t = 0; t < 4; t++) {
+ dispatch_group_async(grp, concQ, ^{
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ for (int i = 0; i < 40; i++) {
+ @autoreleasepool {
+ size_t pg = 16384;
+ void *mem = mmap(nullptr, pg, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
+ if (mem == MAP_FAILED) { failures.fetch_add(1); continue; }
+ float *fp = (float *)mem;
+ fp[0] = 0.25f; fp[1] = 0.75f; fp[2] = 0.5f; fp[3] = 1.0f;
+ id<MTLBuffer> buf = [dev newBufferWithBytesNoCopy:mem length:pg options:MTLResourceStorageModeShared deallocator:^(void *ptr, NSUInteger len) {
+ munmap(ptr, len);
+ deallocCount.fetch_add(1);
+ }];
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:64 height:64 mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageRenderTarget;
+ id<MTLTexture> tex = [dev newTextureWithDescriptor:td];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = tex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setRenderPipelineState:pso];
+ [enc setVertexBuffer:buf offset:0 atIndex:0];
+ [enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:30];
+ [enc endEncoding];
+ [cb commit];
+ if (i % 2 == 0) [cb waitUntilCompleted];
+ // Drop buf, tex, cb immediately!
+ noCopyDone.fetch_add(1);
+ }
+ }
+ });
+ }
+ dispatch_group_wait(grp, DISPATCH_TIME_FOREVER);
+ usleep(400000);
+ printf("Phase 3 done: noCopyDone=%d deallocCount=%d failures=%d\n",
+ noCopyDone.load(), deallocCount.load(), failures.load());
+ if (deallocCount.load() != noCopyDone.load()) {
+ fprintf(stderr, "FAIL: deallocCount (%d) != noCopyDone (%d)\n", deallocCount.load(), noCopyDone.load());
+ failures.fetch_add(1);
+ }
+
+ // Phase 4: Handler ordering invariant under concurrent waitUntilCompleted
+ for (int i = 0; i < 40; i++) {
+ @autoreleasepool {
+ MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:32 height:32 mipmapped:NO];
+ td.storageMode = MTLStorageModeShared;
+ td.usage = MTLTextureUsageRenderTarget;
+ id<MTLTexture> tex = [dev newTextureWithDescriptor:td];
+ id<MTLCommandBuffer> cb = [sharedQ commandBuffer];
+ std::atomic<int> hDone{0};
+ std::atomic<int> hCalls{0};
+ std::atomic<int> *pDone = &hDone;
+ std::atomic<int> *pCalls = &hCalls;
+ [cb addCompletedHandler:^(id<MTLCommandBuffer> c) {
+ (void)c;
+ usleep(500);
+ pCalls->fetch_add(1);
+ pDone->store(1);
+ }];
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = tex;
+ rp.colorAttachments[0].loadAction = MTLLoadActionClear;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ id<MTLRenderCommandEncoder> enc = [cb renderCommandEncoderWithDescriptor:rp];
+ [enc setRenderPipelineState:pso];
+ float tint[4] = {1, 0, 0, 1};
+ [enc setVertexBytes:tint length:sizeof(tint) atIndex:0];
+ [enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
+ [enc endEncoding];
+ [cb commit];
+ dispatch_group_t g2 = dispatch_group_create();
+ dispatch_group_async(g2, concQ, ^{
+ [cb waitUntilCompleted];
+ if (pDone->load() != 1) failures.fetch_add(1);
+ });
+ [cb waitUntilCompleted];
+ if (pDone->load() != 1) failures.fetch_add(1);
+ dispatch_group_wait(g2, DISPATCH_TIME_FOREVER);
+ if (pCalls->load() != 1) failures.fetch_add(1);
+ }
+ }
+ printf("Phase 4 done: failures=%d\n", failures.load());
+ return failures.load() ? 1 : 0;
+ }
+}
diff --git a/gpu/xnu-cpu-metal/test/tri.metal b/gpu/xnu-cpu-metal/test/tri.metal
new file mode 100644
index 0000000..1e3036e
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/tri.metal
@@ -0,0 +1,23 @@
+#include <metal_stdlib>
+using namespace metal;
+
+struct VOut {
+ float4 pos [[position]];
+ float4 color;
+};
+
+vertex VOut tri_vertex(uint vid [[vertex_id]]) {
+ const float2 pos[3] = {
+ float2(-0.8, -0.8),
+ float2( 0.8, -0.8),
+ float2( 0.0, 0.8),
+ };
+ VOut o;
+ o.pos = float4(pos[vid], 0.0, 1.0);
+ o.color = float4(1.0, 0.2, 0.0, 1.0); // bright orange-red
+ return o;
+}
+
+fragment float4 tri_fragment(VOut in [[stage_in]]) {
+ return in.color;
+}
diff --git a/gpu/xnu-cpu-metal/test/vecadd.metal b/gpu/xnu-cpu-metal/test/vecadd.metal
new file mode 100644
index 0000000..caab01d
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/vecadd.metal
@@ -0,0 +1,11 @@
+#include <metal_stdlib>
+using namespace metal;
+
+kernel void vecadd(
+ device const float *a [[buffer(0)]],
+ device const float *b [[buffer(1)]],
+ device float *c [[buffer(2)]],
+ uint id [[thread_position_in_grid]])
+{
+ c[id] = a[id] + b[id];
+}