fix(shader): fence the LDS lock's critical section on MoltenVK #12188

Merged
Gonic0 merged 1 commit from upstream-pr/12188 into main 2026-10-28 09:51:01 +00:00
Gonic0 commented 2026-10-28 02:38:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Gonic0 on 2026-10-28T02:38:22Z.


What

On MoltenVK, contended 64-bit LDS atomics lose updates. agc_driver_lds_atomics64, agc_driver_lds_mixed_width_atomics and agc_driver_lds_lock_budget fail on main on an Apple M5 Pro: "lane 0 contended ds_add_rtn_u64 total is 0xc6ef372fe94f82a0, expected 0x8564cc6e78ec4100", and "lane 0 read 0x0000100ffffffff0, expected 0x00001ffffffff000 after 4096 ds_add_u64 and 4096 ds_add_u32 on one slot".

LockedLdsUpdate takes the workgroup lock with an acquire OpAtomicCompareExchange and releases it with a release OpAtomicExchange. Between the two, the 64-bit update is plain loads and stores of the two dwords. In the MoltenVK shader dump, SPIRV-Cross emits both lock atomics as memory_order_relaxed with no fence, so nothing orders those loads and stores against the lock:

uint _1359 = atomic_exchange_explicit((threadgroup atomic_uint*)&lds_dwords[2244u], 0u, memory_order_relaxed);

With this change the driver sets the new SpirvTarget::ldsLockFences on MoltenVK only (LdsLockFencesRequired in SubgroupBarrier.hpp). The lock then emits a workgroup-scope acquire OpMemoryBarrier at the start of its critical section and a release one before the exchange. SPIRV-Cross turns each into a threadgroup fence with no execution barrier, inside the elected lane's branch:

atomic_thread_fence(mem_flags::mem_threadgroup, memory_order_seq_cst, thread_scope_threadgroup);

The two fences are emitted outside the insideLdsLock window, so the existing suppression of fences inside the lock does not remove them. Other drivers emit the same SPIR-V as before: #6976 removed fences from inside the lock because AMD's Windows driver compiles a workgroup-scope OpMemoryBarrier there to s_barrier, which hangs the waves that spin on the lock. The flag is part of the cache key, agc_shader_replay takes --lds-lock-fences, and the new debt entry "LDS lock ordering on MoltenVK" in docs/dev/debt/shader.md records the workaround.

A release OpAtomicStore in place of the exchange also makes the tests pass, but its MSL is still a relaxed atomic_store_explicit with no fence, so it only works because of how Metal compiles it today.

Tests:

  • CheckLockFences in SpirvLdsAtomicLock.cpp recompiles ds_add_u64 alone and ds_add_u32 together with ds_add_u64 with ldsLockFences set. In every critical section it requires exactly two workgroup-scope barriers on workgroup memory: an acquire before the first LDS access and a release after the last one. It also checks that the 32-bit OpAtomicIAdd stays inside the lock, and that a program with only ds_add_u32 still gets no lock. The existing checks still require no barrier inside the lock when the flag is unset.
  • verifyLdsLockFenceDrivers in SubgroupBarrier.cpp checks that only VK_DRIVER_ID_MOLTENVK needs the fences.
  • ShaderDiskCache.cpp checks that the flag changes the cache key.

Overlap: tools/pr_overlap.py reports line conflicts only where other PRs add a line to the same list: #10547 (CacheKey.hpp), #10652, #11265 and #11483 (the agc_shader_replay flags). None of them changes the LDS lock. #10858 also edits SubgroupBarrier.hpp and its test; the hunks are in other functions, and git merge-tree merges the two branches without conflicts.

Tested

Apple M5 Pro, macOS 27.2, Apple clang 21.0.0, MoltenVK from Vulkan SDK 1.4.363, x86-64 Release under Rosetta 2, with ANYPS5_NO_SHADER_CACHE=1.

main alone does not build libkernel or the driver on macOS. The tree is main cccdaa2734 plus only the open PRs it needs to build: #10552, #11447, #10669, #11554, #11437, #7631, #7804, and Exception.cpp from #4630. It also includes #11705: without it, every execution test that submits through AgcDriver::Submit stops on macOS at "deferred destruction found two different device resolvers", with or without this change. #7631, #7804 and #4630 conflict with main; I resolved them locally. This commit is on top. Rebased onto 3850cc86f5, which changes none of the files touched here.

The 26 tests matching lds|subgroup_barrier|shader_disk_cache in ctest, 3 runs each:

fail on every run pass on every run
without this commit agc_driver_lds_atomics64, agc_driver_lds_mixed_width_atomics, agc_driver_lds_lock_budget, agc_driver_lds_subword_store_branch, agc_driver_lds_tree_reduction the other 21
this commit agc_driver_lds_subword_store_branch, agc_driver_lds_tree_reduction the other 24

The two remaining failures are the MoltenVK wave LDS ordering problem that #10858 addresses, and are the same with and without this commit.

Mutations of this commit, each failing the test that covers it:

mutation failing test
no fences emitted agc_spirv_lds_atomic_lock: "ds_add_u64 with LDS lock fences emitted 0 memory barriers inside the workgroup lock, expected 2"
release fence moved before the update agc_spirv_lds_atomic_lock: "ds_add_u64 with LDS lock fences accesses LDS outside the fences inside the workgroup lock"
flag left out of the cache key agc_shader_disk_cache
LdsLockFencesRequired false for MoltenVK agc_subgroup_barrier: "driver 14: expected LDS lock fences only on MoltenVK"

The GPU tests do not tell the two fences apart: in an earlier run with acquire-release semantics on both, each fence alone also passed them. The commit keeps both, because the lock needs an acquire after taking it and a release before giving it back.

In the MoltenVK dumps of the two GPU tests, each of the 5 lock shaders has exactly two of these fences per compare-exchange, and no threadgroup_barrier between them. The 2 lock shaders that the run without this commit also reaches have the same number of threadgroup_barriers in both runs.

The same 26 tests with VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, ANYPS5_NO_SHADER_CACHE=1 and ANYPS5_REQUIRE_VULKAN=1 (ctest -V): 21 pass without this commit and 24 with it, the same failures as above. Neither log reports a VUID- error or "was not found but was requested by env var VK_INSTANCE_LAYERS".

Not tested on Linux or Windows. There the flag stays unset, and the SPIR-V is the same as on main.

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: Apple M5 Pro, MoltenVK (Vulkan SDK 1.4.363), macOS 27.2
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5044269325 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12188). Originally posted by [Gonic0](https://github.com/Gonic0) on 2026-10-28T02:38:22Z. --- ### What On MoltenVK, contended 64-bit LDS atomics lose updates. `agc_driver_lds_atomics64`, `agc_driver_lds_mixed_width_atomics` and `agc_driver_lds_lock_budget` fail on `main` on an Apple M5 Pro: "lane 0 contended ds_add_rtn_u64 total is 0xc6ef372fe94f82a0, expected 0x8564cc6e78ec4100", and "lane 0 read 0x0000100ffffffff0, expected 0x00001ffffffff000 after 4096 ds_add_u64 and 4096 ds_add_u32 on one slot". `LockedLdsUpdate` takes the workgroup lock with an acquire `OpAtomicCompareExchange` and releases it with a release `OpAtomicExchange`. Between the two, the 64-bit update is plain loads and stores of the two dwords. In the MoltenVK shader dump, SPIRV-Cross emits both lock atomics as `memory_order_relaxed` with no fence, so nothing orders those loads and stores against the lock: ``` uint _1359 = atomic_exchange_explicit((threadgroup atomic_uint*)&lds_dwords[2244u], 0u, memory_order_relaxed); ``` With this change the driver sets the new `SpirvTarget::ldsLockFences` on MoltenVK only (`LdsLockFencesRequired` in `SubgroupBarrier.hpp`). The lock then emits a workgroup-scope acquire `OpMemoryBarrier` at the start of its critical section and a release one before the exchange. SPIRV-Cross turns each into a threadgroup fence with no execution barrier, inside the elected lane's branch: ``` atomic_thread_fence(mem_flags::mem_threadgroup, memory_order_seq_cst, thread_scope_threadgroup); ``` The two fences are emitted outside the `insideLdsLock` window, so the existing suppression of fences inside the lock does not remove them. Other drivers emit the same SPIR-V as before: #6976 removed fences from inside the lock because AMD's Windows driver compiles a workgroup-scope `OpMemoryBarrier` there to `s_barrier`, which hangs the waves that spin on the lock. The flag is part of the cache key, `agc_shader_replay` takes `--lds-lock-fences`, and the new debt entry "LDS lock ordering on MoltenVK" in `docs/dev/debt/shader.md` records the workaround. A release `OpAtomicStore` in place of the exchange also makes the tests pass, but its MSL is still a relaxed `atomic_store_explicit` with no fence, so it only works because of how Metal compiles it today. Tests: - `CheckLockFences` in `SpirvLdsAtomicLock.cpp` recompiles `ds_add_u64` alone and `ds_add_u32` together with `ds_add_u64` with `ldsLockFences` set. In every critical section it requires exactly two workgroup-scope barriers on workgroup memory: an acquire before the first LDS access and a release after the last one. It also checks that the 32-bit `OpAtomicIAdd` stays inside the lock, and that a program with only `ds_add_u32` still gets no lock. The existing checks still require no barrier inside the lock when the flag is unset. - `verifyLdsLockFenceDrivers` in `SubgroupBarrier.cpp` checks that only `VK_DRIVER_ID_MOLTENVK` needs the fences. - `ShaderDiskCache.cpp` checks that the flag changes the cache key. Overlap: `tools/pr_overlap.py` reports line conflicts only where other PRs add a line to the same list: #10547 (`CacheKey.hpp`), #10652, #11265 and #11483 (the `agc_shader_replay` flags). None of them changes the LDS lock. #10858 also edits `SubgroupBarrier.hpp` and its test; the hunks are in other functions, and `git merge-tree` merges the two branches without conflicts. ### Tested Apple M5 Pro, macOS 27.2, Apple clang 21.0.0, MoltenVK from Vulkan SDK 1.4.363, x86-64 Release under Rosetta 2, with `ANYPS5_NO_SHADER_CACHE=1`. `main` alone does not build libkernel or the driver on macOS. The tree is `main` `cccdaa2734` plus only the open PRs it needs to build: #10552, #11447, #10669, #11554, #11437, #7631, #7804, and `Exception.cpp` from #4630. It also includes #11705: without it, every execution test that submits through `AgcDriver::Submit` stops on macOS at "deferred destruction found two different device resolvers", with or without this change. #7631, #7804 and #4630 conflict with `main`; I resolved them locally. This commit is on top. Rebased onto `3850cc86f5`, which changes none of the files touched here. The 26 tests matching `lds|subgroup_barrier|shader_disk_cache` in `ctest`, 3 runs each: | | fail on every run | pass on every run | |---|---|---| | without this commit | `agc_driver_lds_atomics64`, `agc_driver_lds_mixed_width_atomics`, `agc_driver_lds_lock_budget`, `agc_driver_lds_subword_store_branch`, `agc_driver_lds_tree_reduction` | the other 21 | | this commit | `agc_driver_lds_subword_store_branch`, `agc_driver_lds_tree_reduction` | the other 24 | The two remaining failures are the MoltenVK wave LDS ordering problem that #10858 addresses, and are the same with and without this commit. Mutations of this commit, each failing the test that covers it: | mutation | failing test | |---|---| | no fences emitted | `agc_spirv_lds_atomic_lock`: "ds_add_u64 with LDS lock fences emitted 0 memory barriers inside the workgroup lock, expected 2" | | release fence moved before the update | `agc_spirv_lds_atomic_lock`: "ds_add_u64 with LDS lock fences accesses LDS outside the fences inside the workgroup lock" | | flag left out of the cache key | `agc_shader_disk_cache` | | `LdsLockFencesRequired` false for MoltenVK | `agc_subgroup_barrier`: "driver 14: expected LDS lock fences only on MoltenVK" | The GPU tests do not tell the two fences apart: in an earlier run with acquire-release semantics on both, each fence alone also passed them. The commit keeps both, because the lock needs an acquire after taking it and a release before giving it back. In the MoltenVK dumps of the two GPU tests, each of the 5 lock shaders has exactly two of these fences per compare-exchange, and no `threadgroup_barrier` between them. The 2 lock shaders that the run without this commit also reaches have the same number of `threadgroup_barrier`s in both runs. The same 26 tests with `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`, `ANYPS5_NO_SHADER_CACHE=1` and `ANYPS5_REQUIRE_VULKAN=1` (`ctest -V`): 21 pass without this commit and 24 with it, the same failures as above. Neither log reports a `VUID-` error or "was not found but was requested by env var VK_INSTANCE_LAYERS". Not tested on Linux or Windows. There the flag stays unset, and the SPIR-V is the same as on `main`. ### 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: Apple M5 Pro, MoltenVK (Vulkan SDK 1.4.363), macOS 27.2 - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-10-28 03:13:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-28T03:13:40Z.

Review: APPROVED


I reviewed exact head 2f25ab919feee34f8663c50369b56071478fa5b7. The workaround is scoped to MoltenVK, where the report demonstrates the relaxed Metal lock atomics do not order plain LDS accesses. The added barriers are memory-only (no workgroup execution rendezvous), bracket the elected lane’s locked update, and are enabled only after lock acquisition. The target flag is propagated into emission and the shader cache key; tests cover fence scope/order, the mixed 32/64-bit lock path, no-lock programs, driver selection, and cache separation. The reported M5 Pro A/B runs reproduce the lost updates on main and pass the focused 26-test group on the change across three runs; mutation checks exercise each policy/configuration guard. I verified the current-main merge preview is clean, conventions pass, and git diff --check is clean. Hosted policy checks, relinker matrix including ASan, and Windows build pass; Linux full build and specialized platform jobs are skipped by workflow filters. I did not independently reproduce the Apple hardware run, but the detailed controlled evidence and scoped implementation support approval.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5677338015 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12188#pullrequestreview-5677338015). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-28T03:13:40Z. **Review:** APPROVED --- I reviewed exact head `2f25ab919feee34f8663c50369b56071478fa5b7`. The workaround is scoped to MoltenVK, where the report demonstrates the relaxed Metal lock atomics do not order plain LDS accesses. The added barriers are memory-only (no workgroup execution rendezvous), bracket the elected lane’s locked update, and are enabled only after lock acquisition. The target flag is propagated into emission and the shader cache key; tests cover fence scope/order, the mixed 32/64-bit lock path, no-lock programs, driver selection, and cache separation. The reported M5 Pro A/B runs reproduce the lost updates on main and pass the focused 26-test group on the change across three runs; mutation checks exercise each policy/configuration guard. I verified the current-main merge preview is clean, conventions pass, and `git diff --check` is clean. Hosted policy checks, relinker matrix including ASan, and Windows build pass; Linux full build and specialized platform jobs are skipped by workflow filters. I did not independently reproduce the Apple hardware run, but the detailed controlled evidence and scoped implementation support approval.
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!12188
No description provided.