Skip to content

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

Closed
rebelittle wants to merge 1 commit into
boykopovar:mainfrom
rebelittle:fix/windows-raise-host-lock
Closed

rebelittle wants to merge 1 commit into
boykopovar:mainfrom
rebelittle:fix/windows-raise-host-lock

Conversation

@rebelittle

Copy link
Copy Markdown
Contributor

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 c276873:

  • 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

…ck on Windows

On Windows, sceKernelRaiseException redirected a thread that was inside
sceKernelSyncOnAddressWake, sceKernelSyncOnAddressWait or _umtx_op while
it held the address-wait lock, so the guest handler ran with the lock
held. A handler that waits, as Unity's garbage collector does, then
blocked every other thread that waits on or wakes an address (boykopovar#1488).

The lock is now a RaiseDeferral::Mutex, which counts the locks a guest
thread holds. A raise that finds the count above zero is recorded instead
of redirecting the thread, and the thread runs the handler when it
releases its last such lock, as libthr defers signals while a thread holds
its internal locks. A new phase of guest_raise_exception raises at a
thread that wakes an address in a loop and holds the handler while
another thread wakes a different address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@xXPBSXx

xXPBSXx commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

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

gunerky commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

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 CnRJay left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants