fix(libkernel): defer raises while a thread holds the address-wait lock on Windows #4888

Closed
rebelittle wants to merge 1 commit from upstream-pr/4888 into main
rebelittle commented 2026-10-13 01:59:58 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rebelittle on 2026-10-13T01:59:58Z.


What

On Windows, sceKernelRaiseException redirects the target thread to the guest handler wherever it was stopped, unless the thread is in an alertable wait (APC) or inside winpthreads or NtContinue (retry). A thread stopped inside sceKernelSyncOnAddressWake, sceKernelSyncOnAddressWait or _umtx_op while it held the address-wait lock ran the handler with the lock held, so a handler that waits, as Unity's garbage collector does while it stops the world, blocked every other thread that waits on or wakes an address (#1488). After #1562, LeandroLP23's reproducer in #1488 still blocked 35 of 300 rounds, all inside sceKernelSyncOnAddressWake.

The lock is now a RaiseDeferral::Mutex, a std::mutex that counts the deferring locks the calling guest thread holds (PthreadPrivate::hostLocks, bound per thread like waitCount). A raise that finds the count above zero increments the thread's pendingException instead of redirecting it, and the thread runs the handler when it releases its last such lock, as libthr defers signals while a thread holds its internal locks. The count is raised before the lock is taken and lowered after it is released, so a raise never lands while the lock is held, and a raise that comes after the count drops to zero takes the existing path. The handler gets the context of the release point, as a delivery in an alertable wait does.

This avoids the directions tried in #1488: retrying until the thread is back in guest code (breaks the host-blocked phase and can spin), deferring through a thread that samples the target (popcoder565 measured about 75 checks per delivery and a 300-round run of 120 s), and hijacking the guest return address (the System V ABI host functions have no Windows unwind entries, as gunerky found).

Only this lock defers for now. Every blocked round in #1488 stopped in it, and _umtx_op, which the libthr-style locks of bundled modules use, goes through it. Other host locks can become a RaiseDeferral::Mutex the same way; TimedWait::Condition's queue lock is left alone because libSceVideoOut builds its own copy of TimedWait.cpp. Linux is unchanged: its delivery runs in the target's SIGUSR1 handler, which would have to check the count and raise again on release. The Windows sceKernelRaiseException entry in docs/dev/debt/libkernel.md now names the deferred lock.

Tested

Windows 10 22H2 (19045), WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON, based on main c27687313:

  • New phase of guest_raise_exception: a guest thread calls sceKernelSyncOnAddressWake in a loop; for 100 rounds the test raises at it, holds the handler, and requires a wake on another address from another thread to return within 500 ms. Without the change the test aborts with waking round 4: a wake on another address blocked while the handler held the thread (round 6 in a second run); with it, 3 of 3 runs pass in 15.7 to 15.8 s (15.1 s without the phase).
  • Stress, in a temporary local build that was not committed: 2 × 5000 rounds, 0 blocked; raise-to-handler mean 20 µs, maximum 64 µs and 102 µs, none over 1 ms; the deferred path was taken in 3257 and 3242 of the 5000 rounds.
  • Full ctest on an NVIDIA RTX 3090 (driver 610.47, ANYPS5_GPU=3090): 1022 tests, 1015 passed, 7 skipped (the video out tests without a display or Vulkan device, and agc_driver_stencil_ref_export, as this driver lacks VK_EXT_shader_stencil_export), 0 failed.
  • tools/check_conventions.py, tools/check_test_registration.py and tools/pr_overlap.py --branch pass.

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 in TechnicalDebt
  • 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
  • Unblocks: none
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4837287285 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4888). Originally posted by [rebelittle](https://github.com/rebelittle) on 2026-10-13T01:59:58Z. --- ### What On Windows, `sceKernelRaiseException` redirects the target thread to the guest handler wherever it was stopped, unless the thread is in an alertable wait (APC) or inside winpthreads or `NtContinue` (retry). A thread stopped inside `sceKernelSyncOnAddressWake`, `sceKernelSyncOnAddressWait` or `_umtx_op` while it held the address-wait lock ran the handler with the lock held, so a handler that waits, as Unity's garbage collector does while it stops the world, blocked every other thread that waits on or wakes an address (#1488). After #1562, LeandroLP23's reproducer in #1488 still blocked 35 of 300 rounds, all inside `sceKernelSyncOnAddressWake`. The lock is now a `RaiseDeferral::Mutex`, a `std::mutex` that counts the deferring locks the calling guest thread holds (`PthreadPrivate::hostLocks`, bound per thread like `waitCount`). A raise that finds the count above zero increments the thread's `pendingException` instead of redirecting it, and the thread runs the handler when it releases its last such lock, as libthr defers signals while a thread holds its internal locks. The count is raised before the lock is taken and lowered after it is released, so a raise never lands while the lock is held, and a raise that comes after the count drops to zero takes the existing path. The handler gets the context of the release point, as a delivery in an alertable wait does. This avoids the directions tried in #1488: retrying until the thread is back in guest code (breaks the host-blocked phase and can spin), deferring through a thread that samples the target (popcoder565 measured about 75 checks per delivery and a 300-round run of 120 s), and hijacking the guest return address (the System V ABI host functions have no Windows unwind entries, as gunerky found). Only this lock defers for now. Every blocked round in #1488 stopped in it, and `_umtx_op`, which the libthr-style locks of bundled modules use, goes through it. Other host locks can become a `RaiseDeferral::Mutex` the same way; `TimedWait::Condition`'s queue lock is left alone because libSceVideoOut builds its own copy of `TimedWait.cpp`. Linux is unchanged: its delivery runs in the target's SIGUSR1 handler, which would have to check the count and raise again on release. The Windows `sceKernelRaiseException` entry in `docs/dev/debt/libkernel.md` now names the deferred lock. ### Tested Windows 10 22H2 (19045), WinLibs GCC 15.2.0 r7, Release, `BUILD_TESTING=ON`, based on `main` c27687313: - New phase of `guest_raise_exception`: a guest thread calls `sceKernelSyncOnAddressWake` in a loop; for 100 rounds the test raises at it, holds the handler, and requires a wake on another address from another thread to return within 500 ms. Without the change the test aborts with `waking round 4: a wake on another address blocked while the handler held the thread` (round 6 in a second run); with it, 3 of 3 runs pass in 15.7 to 15.8 s (15.1 s without the phase). - Stress, in a temporary local build that was not committed: 2 × 5000 rounds, 0 blocked; raise-to-handler mean 20 µs, maximum 64 µs and 102 µs, none over 1 ms; the deferred path was taken in 3257 and 3242 of the 5000 rounds. - Full `ctest` on an NVIDIA RTX 3090 (driver 610.47, `ANYPS5_GPU=3090`): 1022 tests, 1015 passed, 7 skipped (the video out tests without a display or Vulkan device, and `agc_driver_stencil_ref_export`, as this driver lacks `VK_EXT_shader_stencil_export`), 0 failed. - `tools/check_conventions.py`, `tools/check_test_registration.py` and `tools/pr_overlap.py --branch` pass. ### 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 in [TechnicalDebt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/TechnicalDebt.md#silent-stubs) - [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] Unblocks: none - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
xXPBSXx commented 2026-10-13 08:20:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-13T08:20:54Z.


Windows test of this PR.

Environment: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, BUILD_TESTING=ON, -j2, libusb-cmake from a local checkout. Built from main c2565f014 with this PR and ten other open PRs (#4972, #4967, #4966, #4945, #4938, #4936, #4933, #4898, #4896, #4888) merged together; the merges had no conflict.

Result: guest_raise_exception (1 of 1, 15.8 s) pass.

Not checked: whether the test fails without the change in the library code; the PR was not tested alone, only in the combined merge; no title run; Linux not tested.

AI-assisted (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6141389797 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4888#issuecomment-6141389797). Originally posted by [xXPBSXx](https://github.com/xXPBSXx) on 2026-10-13T08:20:54Z. --- Windows test of this PR. Environment: Windows 10 (19045), MinGW-w64 GCC 15.2.0 (WinLibs r7), Release, `BUILD_TESTING=ON`, `-j2`, `libusb-cmake` from a local checkout. Built from `main` `c2565f014` with this PR and ten other open PRs (#4972, #4967, #4966, #4945, #4938, #4936, #4933, #4898, #4896, #4888) merged together; the merges had no conflict. Result: guest_raise_exception (1 of 1, 15.8 s) pass. Not checked: whether the test fails without the change in the library code; the PR was not tested alone, only in the combined merge; no title run; Linux not tested. AI-assisted (Claude Code).
gunerky commented 2026-10-13 09:16:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gunerky on 2026-10-13T09:16:24Z.


Independent Windows validation of this PR alone.

Tested main 20890629f22cfa11d6cf4170826ac8eb86dffa9d plus the seven-file patch from PR head c0eedaac6ff1284025534138960b6ba2fba1b84b, with no other open PR applied. Windows 11 Pro x64 (26300), WinLibs GCC 15.2.0 r7, Release flags. Fresh manual focused builds of libc/libkernel; the comparison used actual NID-patched libraries.

Using my independently written #1488 measurement, three sets of 100 rounds per variant:

Build Rounds Independent-address wake blocked during the handler hold
main 300 63
main + this PR 300 0

Here “blocked” means the separate wake did not finish during a 150 ms observation while the target's handler waited atomically for release. All 63 main wakes returned after release; with the PR all 300 progressed while the handler was held. Every round delivered on the matching target thread and recovered; no missing delivery or incomplete child. Empty-handler, guest-loop, finished-target and long host-wait controls also completed. The deliberately long non-alertable host wait still delayed delivery in both builds.

Separate instrumentation-only controls paused the actual Wake/Wait lock at acquisition/release boundaries. 100 normal boundary cases passed. Four parallel raisers queued 64 requests per paused target: 80 further Wake/Wait children delivered exactly 5,120/5,120 on the target thread. Three deliberately unsafe local variants (ignored count, delivery before physical unlock, dropped pending requests) were caught with their intended diagnostics. This instrumentation was separate from the unmodified comparison above.

13 existing runtime test executables per variant passed (26/26 focused local CTest runs), including raise/exception, address sync, mutex/rwlock, cancellation and thread lifecycle checks. No repository timeout was increased. This was a focused manual build/test collection, not a full CMake build, libs, full repository CTest or hosted CI.

These results support the scoped address-wait-lock fix. They do not establish safety under other host locks or full asynchronous context preservation. Not tested: later main revisions, Linux/macOS, PS5 or games. AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6142323176 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4888#issuecomment-6142323176). Originally posted by [gunerky](https://github.com/gunerky) on 2026-10-13T09:16:24Z. --- Independent Windows validation of this PR alone. Tested `main` `20890629f22cfa11d6cf4170826ac8eb86dffa9d` plus the seven-file patch from PR head `c0eedaac6ff1284025534138960b6ba2fba1b84b`, with no other open PR applied. Windows 11 Pro x64 (26300), WinLibs GCC 15.2.0 r7, Release flags. Fresh manual focused builds of libc/libkernel; the comparison used actual NID-patched libraries. Using my independently written #1488 measurement, three sets of 100 rounds per variant: | Build | Rounds | Independent-address wake blocked during the handler hold | |---|---:|---:| | main | 300 | 63 | | main + this PR | 300 | 0 | Here “blocked” means the separate wake did not finish during a 150 ms observation while the target's handler waited atomically for release. All 63 main wakes returned after release; with the PR all 300 progressed while the handler was held. Every round delivered on the matching target thread and recovered; no missing delivery or incomplete child. Empty-handler, guest-loop, finished-target and long host-wait controls also completed. The deliberately long non-alertable host wait still delayed delivery in both builds. Separate instrumentation-only controls paused the actual Wake/Wait lock at acquisition/release boundaries. 100 normal boundary cases passed. Four parallel raisers queued 64 requests per paused target: 80 further Wake/Wait children delivered exactly 5,120/5,120 on the target thread. Three deliberately unsafe local variants (ignored count, delivery before physical unlock, dropped pending requests) were caught with their intended diagnostics. This instrumentation was separate from the unmodified comparison above. 13 existing runtime test executables per variant passed (26/26 focused local CTest runs), including raise/exception, address sync, mutex/rwlock, cancellation and thread lifecycle checks. No repository timeout was increased. This was a focused manual build/test collection, not a full CMake build, `libs`, full repository CTest or hosted CI. These results support the scoped address-wait-lock fix. They do not establish safety under other host locks or full asynchronous context preservation. Not tested: later main revisions, Linux/macOS, PS5 or games. AI-assisted: yes.
CnRJay commented 2026-10-14 01:18:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-14T01:18:41Z.

Review: COMMENTED


gunerky's numbers (63/300 blocked → 0/300) show it works for the #1488 pattern. My concern is where the deferred handler runs. Leave() delivers from inside RaiseDeferral::Mutex::unlock(), and the address-wait lock is also unlocked by the condition wait itself:

  • SyncOnAddress.cpp waits with waiter.condition.Wait(lock, ...) / WaitUntil(lock, ...). In TimedWait::Condition::Wait (Windows, non-coarse), the order is enqueue(), then lock.unlock(), then waitSignal(waiter). With this PR, lock.unlock() can now run the guest handler after the waiter is enqueued and before it waits. If the handler returns normally that's merely early. If it doesn't return (a handler that longjmps, or switches context, as GC and crash handlers sometimes do), the Waiter stays enqueued on the condition with its stack frame gone, and the next NotifyOne on that address writes into freed stack.
  • Under APS5_COARSE_TIMED_WAITS, coarse.wait(lock) is std::condition_variable_any. libstdc++'s condition_variable_any::wait holds its internal mutex while it calls lock.unlock(). The handler then runs with that internal mutex held, so every NotifyOne/NotifyAll on that condition from another thread blocks until the handler returns. That is the same "handler runs while holding a lock others need" problem, moved one level down. A stop-the-world handler waiting for those threads would deadlock.
  • More generally, unlock() is called from lock_guard / unique_lock destructors in code that doesn't expect arbitrary guest code to run there (or to unwind out of it).

Delivering at a point the driver controls avoids all three. For example:

  • keep Mutex::unlock() free of delivery, and make the condition waits use the raw std::mutex (unlock and relock without touching the count);
  • deliver pending exceptions on the way out of sceKernelSyncOnAddressWait/Wake and _umtx_op, after the last lock is released and before returning to the guest. That is where libthr's deferred-signal check sits (_thr_ast on the way out of its critical sections), not inside the unlock primitive.

A test where the handler longjmps out while the target is in sceKernelSyncOnAddressWait, followed by a wake on the same address, would catch the dangling-waiter case.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5511957957 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4888#pullrequestreview-5511957957). Originally posted by [CnRJay](https://github.com/CnRJay) on 2026-10-14T01:18:41Z. **Review:** COMMENTED --- gunerky's numbers (63/300 blocked → 0/300) show it works for the #1488 pattern. My concern is **where** the deferred handler runs. `Leave()` delivers from inside `RaiseDeferral::Mutex::unlock()`, and the address-wait lock is also unlocked by the condition wait itself: - `SyncOnAddress.cpp` waits with `waiter.condition.Wait(lock, ...)` / `WaitUntil(lock, ...)`. In `TimedWait::Condition::Wait` (Windows, non-coarse), the order is `enqueue()`, then `lock.unlock()`, then `waitSignal(waiter)`. With this PR, `lock.unlock()` can now run the guest handler **after the waiter is enqueued and before it waits**. If the handler returns normally that's merely early. If it doesn't return (a handler that `longjmp`s, or switches context, as GC and crash handlers sometimes do), the `Waiter` stays enqueued on the condition with its stack frame gone, and the next `NotifyOne` on that address writes into freed stack. - Under `APS5_COARSE_TIMED_WAITS`, `coarse.wait(lock)` is `std::condition_variable_any`. libstdc++'s `condition_variable_any::wait` holds its internal mutex while it calls `lock.unlock()`. The handler then runs with that internal mutex held, so every `NotifyOne`/`NotifyAll` on that condition from another thread blocks until the handler returns. That is the same "handler runs while holding a lock others need" problem, moved one level down. A stop-the-world handler waiting for those threads would deadlock. - More generally, `unlock()` is called from `lock_guard` / `unique_lock` destructors in code that doesn't expect arbitrary guest code to run there (or to unwind out of it). Delivering at a point the driver controls avoids all three. For example: - keep `Mutex::unlock()` free of delivery, and make the condition waits use the raw `std::mutex` (unlock and relock without touching the count); - deliver pending exceptions on the way out of `sceKernelSyncOnAddressWait/Wake` and `_umtx_op`, after the last lock is released and before returning to the guest. That is where libthr's deferred-signal check sits (`_thr_ast` on the way out of its critical sections), not inside the unlock primitive. A test where the handler `longjmp`s out while the target is in `sceKernelSyncOnAddressWait`, followed by a wake on the same address, would catch the dangling-waiter case.
oneandonlydean commented 2026-10-14 02:33:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-14T02:33:59Z.


Closing: no title is known to reach this. With the queue at 700+ open PRs, please hold off on new PRs that don't name a title needing the change until it's down. If a title stops on this on current main, reopen with the title ID and the log line.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6159599865 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/4888#issuecomment-6159599865). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-14T02:33:59Z. --- Closing: no title is known to reach this. With the queue at 700+ open PRs, please hold off on new PRs that don't name a title needing the change until it's down. If a title stops on this on current main, reopen with the title ID and the log line.

Pull request closed

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!4888
No description provided.