fix(agc): destroy buffers and memory on MoltenVK only while the graphics queue is idle #10062

Merged
imellag merged 1 commit from upstream-pr/10062 into main 2026-10-26 01:28:45 +00:00
imellag commented 2026-10-23 07:44:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by imellag on 2026-10-23T07:44:10Z.


What

On MoltenVK, buffers and device memory that the AGC driver releases are now destroyed only while the graphics queue is idle. This works around KhronosGroup/MoltenVK#2876 (open; MoltenVK 1.4.2 and main), which loses the device on Stray (PPSA02100) about 40 to 100 s into the game.

MoltenVK adds every VkBuffer created with SHADER_DEVICE_ADDRESS usage to a device-wide list at vkCreateBuffer, and MVKDevice::encodeGPUAddressableBuffers passes the whole list to useResources in every command buffer that binds a shader using device addresses. Its command buffers do not retain resources. So:

  • destroying a buffer that no pending command uses, which is legal Vulkan, loses the device (kIOGPUCommandBufferCallbackErrorInvalidResource; under MTL_DEBUG_LAYER=1, The following Metal object is being destroyed while still required to be alive by the command buffer);
  • waiting for the fences of the work that used the buffer is not enough: every command buffer submitted while the buffer still exists references it too. I first tried keeping released objects until the next submission's fence, and Metal still asserted on a buffer destroyed after that fence;
  • freeing the memory before the buffer leaves a live buffer without an MTLBuffer, and Metal validation asserts resource (at index: N) should not be nil in useResources.

The only safe moment is when no command buffer that was encoded while the buffer existed is pending: the queue is idle. The change:

  • Graphics/src/DeferredDestruction.cpp: on MoltenVK the graphics context gets a device resolver that returns queuing versions of vkDestroyBuffer and vkFreeMemory and forwards every other name. Everything that destroys through the context (the buffer pool, Buffer, DeviceBuffer, guest buffer memory imports, unit shadows) is covered without touching those call sites.
  • Recorder::Submit and CommandBatch::Submit drain the queue before their vkQueueSubmit, under the GPU mutex that every graphics-queue submission holds, once 512 objects wait or the oldest has waited 100 ms: vkQueueWaitIdle, then the buffers, then the memory. vkQueueWaitIdle also waits for MoltenVK's asynchronous encoding, so nothing can still read the list.
  • The device teardown destroys what is left before vkDestroyDevice.
  • VK_DRIVER_ID_MOLTENVK only; other drivers keep destroying at once. APS5_NO_DEFERRED_DESTRUCTION=1 turns it off (row in docs/dev/ENVIRONMENT.md). The debt entry states the cost: each drain stalls the CPU until the GPU is idle, and memory released under pressure only returns at the next drain. It also says to remove this once a MoltenVK release fixes #2876.

Tested

  • New agc_deferred_destruction test: destroys and frees are queued, other names pass through, a drain below both bounds does nothing, a drain past the age bound or at 512 objects waits for the queue and then destroys buffers before memory, a failed queue wait throws and keeps the objects, teardown destroys the rest without a queue wait, and destroys after teardown or on another device run at once. With the queueing disabled (defer always returning false) it fails 6 of its checks.
  • Linux, paired run in the same container (Ubuntu 24.04 x86-64, GCC 14.2, Release, lavapipe from Mesa 25.2.8, validation layer 1.3.275, ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, ctest -V). lavapipe is not MoltenVK, so this checks that other drivers are unchanged:
    main ef0d8ae3b5 this PR 4bee82086f
    agc_buffer_pool (and its two small-device variants), agc_command_batch_failure, agc_driver_graphics, agc_driver_pooled_buffer_range pass pass
    agc_deferred_destruction not on main pass
    was not found but was requested / VUID- 0 / 0 0 / 0
  • macOS 27.0.1, Apple M4 Pro, MoltenVK 1.4.2 (Vulkan SDK 1.4.363.0), on a local stack with the macOS host support PRs (main does not build on macOS yet): agc_deferred_destruction and agc_buffer_pool pass. Stray, pressing cross into the game, MTL_DEBUG_LAYER=1:
    • Without this change, the device is lost or MoltenVK segfaults in MVKMetalComputeCommandEncoderState::prepareComputeDispatch within 40 to 100 s; Metal names a 12-byte buffer destroyed from Buffer::Buffer when the pool rebinds reused memory. With only the per-fence deferral described above, it names buffers and imported guest memory destroyed on the release thread after their own batch's fence.
    • With it, and a MoltenVK carrying two one-line local fixes (#2885, and skipping buffers that are not yet bound, see below), Stray runs the whole 300 s with MoltenVK's default asynchronous submissions: past the first checkpoint, 76 light draws, no Metal assertion, no device loss, no MoltenVK segfault.
    • With the stock SDK MoltenVK it stops at 36 s on KhronosGroup/MoltenVK#2885 (a 2D-array view of a 3D image recreated each render pass), which only MoltenVK can fix. So this PR alone does not make Stray run on stock MoltenVK, but it removes the failures that AnyPS5 can avoid.
    • MoltenVK also passes a buffer that is created but not yet bound to memory (getMTLBuffer() is nil) to useResources: vkCreateBuffer adds it to the list before vkBindBufferMemory. AnyPS5 creates buffers on threads without the GPU mutex, so this cannot be closed from here; the local MoltenVK fix skips nil buffers in encodeGPUAddressableBuffers. I will report it on #2876.
  • Not measured: the frame-time cost of the drains. Stray on macOS is not yet stable enough for a trace_digest.py pair (a separate UE4 asset-loading failure after the first checkpoint, timing-dependent, is being investigated).

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: lavapipe (Mesa 25.2.8, Ubuntu 24.04 x86-64); Apple M4 Pro, MoltenVK 1.4.2, macOS 27.0.1
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4979542598 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10062). Originally posted by [imellag](https://github.com/imellag) on 2026-10-23T07:44:10Z. --- ### What On MoltenVK, buffers and device memory that the AGC driver releases are now destroyed only while the graphics queue is idle. This works around [KhronosGroup/MoltenVK#2876](https://github.com/KhronosGroup/MoltenVK/issues/2876) (open; MoltenVK 1.4.2 and `main`), which loses the device on Stray (PPSA02100) about 40 to 100 s into the game. MoltenVK adds every `VkBuffer` created with `SHADER_DEVICE_ADDRESS` usage to a device-wide list at `vkCreateBuffer`, and `MVKDevice::encodeGPUAddressableBuffers` passes the whole list to `useResources` in every command buffer that binds a shader using device addresses. Its command buffers do not retain resources. So: - destroying a buffer that no pending command uses, which is legal Vulkan, loses the device (`kIOGPUCommandBufferCallbackErrorInvalidResource`; under `MTL_DEBUG_LAYER=1`, `The following Metal object is being destroyed while still required to be alive by the command buffer`); - waiting for the fences of the work that used the buffer is not enough: every command buffer submitted while the buffer still exists references it too. I first tried keeping released objects until the next submission's fence, and Metal still asserted on a buffer destroyed after that fence; - freeing the memory before the buffer leaves a live buffer without an `MTLBuffer`, and Metal validation asserts `resource (at index: N) should not be nil` in `useResources`. The only safe moment is when no command buffer that was encoded while the buffer existed is pending: the queue is idle. The change: - `Graphics/src/DeferredDestruction.cpp`: on MoltenVK the graphics context gets a device resolver that returns queuing versions of `vkDestroyBuffer` and `vkFreeMemory` and forwards every other name. Everything that destroys through the context (the buffer pool, `Buffer`, `DeviceBuffer`, guest buffer memory imports, unit shadows) is covered without touching those call sites. - `Recorder::Submit` and `CommandBatch::Submit` drain the queue before their `vkQueueSubmit`, under the GPU mutex that every graphics-queue submission holds, once 512 objects wait or the oldest has waited 100 ms: `vkQueueWaitIdle`, then the buffers, then the memory. `vkQueueWaitIdle` also waits for MoltenVK's asynchronous encoding, so nothing can still read the list. - The device teardown destroys what is left before `vkDestroyDevice`. - `VK_DRIVER_ID_MOLTENVK` only; other drivers keep destroying at once. `APS5_NO_DEFERRED_DESTRUCTION=1` turns it off (row in `docs/dev/ENVIRONMENT.md`). The debt entry states the cost: each drain stalls the CPU until the GPU is idle, and memory released under pressure only returns at the next drain. It also says to remove this once a MoltenVK release fixes #2876. ### Tested - New `agc_deferred_destruction` test: destroys and frees are queued, other names pass through, a drain below both bounds does nothing, a drain past the age bound or at 512 objects waits for the queue and then destroys buffers before memory, a failed queue wait throws and keeps the objects, teardown destroys the rest without a queue wait, and destroys after teardown or on another device run at once. With the queueing disabled (`defer` always returning false) it fails 6 of its checks. - Linux, paired run in the same container (Ubuntu 24.04 x86-64, GCC 14.2, Release, lavapipe from Mesa 25.2.8, validation layer 1.3.275, `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`, `ctest -V`). lavapipe is not MoltenVK, so this checks that other drivers are unchanged: | | `main` `ef0d8ae3b5` | this PR `4bee82086f` | |---|---|---| | `agc_buffer_pool` (and its two small-device variants), `agc_command_batch_failure`, `agc_driver_graphics`, `agc_driver_pooled_buffer_range` | pass | pass | | `agc_deferred_destruction` | not on `main` | pass | | `was not found but was requested` / `VUID-` | 0 / 0 | 0 / 0 | - macOS 27.0.1, Apple M4 Pro, MoltenVK 1.4.2 (Vulkan SDK 1.4.363.0), on a local stack with the macOS host support PRs (`main` does not build on macOS yet): `agc_deferred_destruction` and `agc_buffer_pool` pass. Stray, pressing cross into the game, `MTL_DEBUG_LAYER=1`: - Without this change, the device is lost or MoltenVK segfaults in `MVKMetalComputeCommandEncoderState::prepareComputeDispatch` within 40 to 100 s; Metal names a 12-byte buffer destroyed from `Buffer::Buffer` when the pool rebinds reused memory. With only the per-fence deferral described above, it names buffers and imported guest memory destroyed on the release thread after their own batch's fence. - With it, and a MoltenVK carrying two one-line local fixes (#2885, and skipping buffers that are not yet bound, see below), Stray runs the whole 300 s with MoltenVK's default asynchronous submissions: past the first checkpoint, 76 light draws, no Metal assertion, no device loss, no MoltenVK segfault. - With the stock SDK MoltenVK it stops at 36 s on [KhronosGroup/MoltenVK#2885](https://github.com/KhronosGroup/MoltenVK/issues/2885) (a 2D-array view of a 3D image recreated each render pass), which only MoltenVK can fix. So this PR alone does not make Stray run on stock MoltenVK, but it removes the failures that AnyPS5 can avoid. - MoltenVK also passes a buffer that is created but not yet bound to memory (`getMTLBuffer()` is nil) to `useResources`: `vkCreateBuffer` adds it to the list before `vkBindBufferMemory`. AnyPS5 creates buffers on threads without the GPU mutex, so this cannot be closed from here; the local MoltenVK fix skips nil buffers in `encodeGPUAddressableBuffers`. I will report it on #2876. - Not measured: the frame-time cost of the drains. Stray on macOS is not yet stable enough for a `trace_digest.py` pair (a separate UE4 asset-loading failure after the first checkpoint, timing-dependent, is being investigated). ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: lavapipe (Mesa 25.2.8, Ubuntu 24.04 x86-64); Apple M4 Pro, MoltenVK 1.4.2, macOS 27.0.1 - [x] AI-assisted: yes
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!10062
No description provided.