fix(libkernel): defer raises while a thread holds the address-wait lock on Windows #4888
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/4888"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by rebelittle on 2026-10-13T01:59:58Z.
What
On Windows,
sceKernelRaiseExceptionredirects the target thread to the guest handler wherever it was stopped, unless the thread is in an alertable wait (APC) or inside winpthreads orNtContinue(retry). A thread stopped insidesceKernelSyncOnAddressWake,sceKernelSyncOnAddressWaitor_umtx_opwhile 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 insidesceKernelSyncOnAddressWake.The lock is now a
RaiseDeferral::Mutex, astd::mutexthat counts the deferring locks the calling guest thread holds (PthreadPrivate::hostLocks, bound per thread likewaitCount). A raise that finds the count above zero increments the thread'spendingExceptioninstead 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 aRaiseDeferral::Mutexthe same way;TimedWait::Condition's queue lock is left alone because libSceVideoOut builds its own copy ofTimedWait.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 WindowssceKernelRaiseExceptionentry indocs/dev/debt/libkernel.mdnow names the deferred lock.Tested
Windows 10 22H2 (19045), WinLibs GCC 15.2.0 r7, Release,
BUILD_TESTING=ON, based onmainc27687313:guest_raise_exception: a guest thread callssceKernelSyncOnAddressWakein 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 withwaking 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).cteston 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, andagc_driver_stencil_ref_export, as this driver lacksVK_EXT_shader_stencil_export), 0 failed.tools/check_conventions.py,tools/check_test_registration.pyandtools/pr_overlap.py --branchpass.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed in TechnicalDebt.mdfiles or images added to the repository (attach them to this PR)🤖 Generated with Claude Code
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-cmakefrom a local checkout. Built frommainc2565f014with 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).
Imported from boykopovar/AnyPS5. Originally posted by gunerky on 2026-10-13T09:16:24Z.
Independent Windows validation of this PR alone.
Tested
main20890629f22cfa11d6cf4170826ac8eb86dffa9dplus the seven-file patch from PR headc0eedaac6ff1284025534138960b6ba2fba1b84b, 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:
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.
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 insideRaiseDeferral::Mutex::unlock(), and the address-wait lock is also unlocked by the condition wait itself:SyncOnAddress.cppwaits withwaiter.condition.Wait(lock, ...)/WaitUntil(lock, ...). InTimedWait::Condition::Wait(Windows, non-coarse), the order isenqueue(), thenlock.unlock(), thenwaitSignal(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 thatlongjmps, or switches context, as GC and crash handlers sometimes do), theWaiterstays enqueued on the condition with its stack frame gone, and the nextNotifyOneon that address writes into freed stack.APS5_COARSE_TIMED_WAITS,coarse.wait(lock)isstd::condition_variable_any. libstdc++'scondition_variable_any::waitholds its internal mutex while it callslock.unlock(). The handler then runs with that internal mutex held, so everyNotifyOne/NotifyAllon 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.unlock()is called fromlock_guard/unique_lockdestructors 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:
Mutex::unlock()free of delivery, and make the condition waits use the rawstd::mutex(unlock and relock without touching the count);sceKernelSyncOnAddressWait/Wakeand_umtx_op, after the last lock is released and before returning to the guest. That is where libthr's deferred-signal check sits (_thr_aston the way out of its critical sections), not inside the unlock primitive.A test where the handler
longjmps out while the target is insceKernelSyncOnAddressWait, followed by a wake on the same address, would catch the dangling-waiter case.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.
Pull request closed