Skip to content

fix(libkernel): stop losing _umtx_op umutex wakeups to a userland unlock - #24070

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
jpirz:fix-umtx-lost-wakeup
Nov 27, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
jpirz:fix-umtx-lost-wakeup

Conversation

@jpirz

@jpirz jpirz commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What

_umtx_op's umutex operations could lose a wakeup when the owner unlocks in userland, as libthr-style locks do while UMUTEX_CONTESTED is clear:

  • UMTX_OP_MUTEX_LOCK and UMTX_OP_MUTEX_WAIT read the owner word, found it owned, and only then tried to set UMUTEX_CONTESTED. When the owner released the mutex with a userland CAS between the two steps, MarkContested found the word unowned and stopped, and the caller slept anyway on a free mutex whose word had no UMUTEX_CONTESTED, so no unlock entered the kernel to wake it. The call returned ETIMEDOUT at its timeout, or slept forever without one.
  • UMTX_OP_MUTEX_UNLOCK and UMTX_OP_MUTEX_WAKE counted the waiters, released the bucket lock, and only then updated the owner word and woke a waiter. A locker that queued in between was not counted, so the unlock could store UMUTEX_UNOWNED with two threads waiting; the woken one took the mutex without UMUTEX_CONTESTED and its userland unlock never woke the other.

The _umtx_op technical debt entry says contention and wakeups follow FreeBSD 11's kern_umtx.c: do_lock_normal sleeps only when its CAS that sets the contested bit succeeds on the owner value it saw, and otherwise drops the queue lock and retries; do_unlock_normal and do_wake_umutex count, update the owner word and signal under umtxq_busy, which a locker also holds while it queues and sets the bit.

Now MarkContested reports whether the word still names an owning thread; UMUTEX_RB_OWNERDEAD and UMUTEX_RB_NOTRECOV do not. When it does not, the wait predicate returns without sleeping and MutexLock retries the acquire (for MUTEX_WAIT, the check for a free word) in a new hold of the bucket lock, so a guest word that keeps changing never keeps the shared bucket locked with signal delivery deferred. A thread sleeps only once UMUTEX_CONTESTED is set on a word a thread owns. MUTEX_UNLOCK and MUTEX_WAKE count, store or CAS the owner word and wake one waiter in one hold of the bucket lock, inside the signal deferral; WakeAddress takes the lock itself around the same wake loop. The code has no platform branches, so Linux, Windows and macOS all change. The measured behaviours in the _umtx_op debt entry (relocking an owned mutex, EINVAL for priority protection, the owner id) are unchanged, and the debt entry needs no change. One gap stays as it was: with two or more waiters, MUTEX_WAKE stores UMUTEX_UNOWNED without UMUTEX_CONTESTED, which do_wake_umutex does not appear to do, so a libthr-style wait/wake loop with four threads can still time out on main and on this branch alike. That is a separate change.

The change is built on #19453's robust umutex code and keeps all of it. TryAcquireMutex still takes UMUTEX_RB_OWNERDEAD over with EOWNERDEAD and refuses UMUTEX_RB_NOTRECOV with ENOTRECOVERABLE, and MUTEX_WAIT and MUTEX_WAKE still treat both as free. Because no thread owns either value, MarkContested reports both as unowned, so a locker or waiter that sees one appear after its acquire check retries and takes it over, refuses it or returns, instead of sleeping on a word no unlock will enter the kernel for; do_lock_normal does not sleep on them either. MUTEX_UNLOCK stores #19453's unlocked value (UMUTEX_RB_OWNERDEAD when the robust list releases it at thread exit, UMUTEX_RB_NOTRECOV for UMUTEX_NONCONSISTENT, otherwise UMUTEX_UNOWNED, with UMUTEX_CONTESTED added for a second waiter) in the same hold of the bucket lock in which it counts the waiters and wakes one, so the thread-exit release closes the same window.

Tested

Ubuntu 24.04 x86-64 container, gcc 13, Release build with BUILD_TESTING=ON, on c14fbcd. Linux only; Windows and macOS not tested.

  • New check in guest_umtx_op (MutexLockAndWaitDoNotLoseAWakeupToAUserlandUnlock): two threads lock and unlock a umutex with userland CAS only, entering the kernel only to unlock when UMUTEX_CONTESTED is set, while the main thread calls MUTEX_LOCK and MUTEX_UNLOCK, then MUTEX_WAIT, for 200 ms each with the file's 10 s failsafe. The window lies between two loads inside the kernel's wait predicate with no hook between them, so the check is a bounded stress loop rather than a scripted interleaving.
  • Fail before (SyncOnAddress.cpp from c14fbcd, new test kept): 3 of 3 ctest -R '^guest_umtx_op$' runs ended Subprocess aborted after about 11.7 s (the call times out at the failsafe with ETIMEDOUT).
  • Pass after: 8 of 8 runs of guest_umtx_op, which also holds feat(libkernel): robust umutexes and UMTX_OP_ROBUST_LISTS in _umtx_op #19453's robust checks, passed, about 2.6 s each. The other 26 tests whose names contain umtx, robust or mutex (among them guest_kernel_mutex_contention_robust_bounds and the guest_pthread_mutex_* tests) passed 3 of 3 runs.
  • Tests the change reaches, selected as CI selects them (tools/select_tests.py, 5986 of 6824), run with -j3 --timeout 120: 5959 passed or skipped, 27 failed. 25 are socket tests (guest_net_*, guest_sce_net*, guest_socket_*, guest_tcp, guest_rudp_local_info, guest_kernel_sock_names, guest_kernel_socket_creation_bounds) that abort because the container has no IPv6. agc_driver_pm4_order_signal (a held submission started 0.11 ms after the wait instead of at once, on llvmpipe) and patched_self_imports (libScePosixForWebKit.prx imports three names it also exports) fail 3 of 3 runs alone with this change reverted as well.
  • The unlock-side window was found by reading the code; the check does not reproduce it.

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: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

https://claude.ai/code/session_014t2HhdnDYm3ps2BQNLaF2H

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 17ad128a8a:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_umtx_op_tests built cleanly.
  • CTest (guest_umtx_op):
    1/1 Test #5750: guest_umtx_op ....................   Passed    2.46 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #5750: guest_umtx_op ....................Subprocess aborted***Exception:  11.81 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified MarkContested return value and retry loop in MutexLock: when the lock is released in userland before marking contested, retry is set and MutexLock spins back to retry acquisition or marking instead of sleeping on an unowned/uncontested mutex.
    • Verified atomic update in MutexUnlock: owner store and WakeWaiters are executed atomically inside DeferringDelivery under the bucket mutex, eliminating the race where a newly queued waiter was missed when counting waiters.
    • Verified atomic update in MutexWake: WaiterCount check, compare_exchange_strong and WakeWaiters run under bucket.mutex, ensuring contested bit clearing accurately reflects remaining waiter count.
    • Verified WaiterCount signature and callers: updated to accept const WaiterBucket& and correctly passed bucket references under existing lock guards.
    • Verified test coverage in GuestUmtxOp.cpp: MutexLockAndWaitDoNotLoseAWakeupToAUserlandUnlock exercises both UMTX_OP_MUTEX_LOCK and UMTX_OP_MUTEX_WAIT under heavy userland CAS contention without deadlocking or losing wakeups.

Looks Good To Me

@MarcZX10 MarcZX10 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.

Reviewed — looks good

The change addresses the described umutex lost-wakeup races, and the changed code and test support approval at head 17ad128a8a585eab03485a325f332cd42c771f3a.

What I ran

No commands or tests were run. I read the prepared diff and both changed files at the pinned head.

Results

Check Result Note
Changed code review passed Both changed files read
Tests in this review not run Test results in the description are author-reported

Findings

Blocking

None.

Non-blocking

None.

Not verified

I did not run tests or verify the author-reported test results. I did not review platform behavior on Windows or macOS. The description says its stress test does not reproduce the unlock-side race.

To get this to a good state

Nothing is required.

@Kal0s-design

Copy link
Copy Markdown

Negative control and repeated runs for this, since a lost wakeup is timing dependent and the earlier Linux check is a single pass. Linux x86-64, GCC, head 17ad128a8a merged onto main fd7fe562ed (clean merge), running guest_umtx_op_tests directly.

tree plain, 50 runs TSan, 10 runs
main + only this PR's GuestUmtxOp.cpp 0 of 50 pass (aborts) 0 of 10 pass
main + this PR 50 of 50 pass every run completes, 1 report per run

So the new check fails on main every time here, not just now and then, and passes every time with the change.

The one TSan report with the PR is a data race at GuestUmtxOp.cpp:709 in ConditionWaitReleasesTheMutexAndWakes, inside the test. It is not from this change: a TSan run of main from yesterday already had the same report in the same function (line 677 then, the new lines in this file account for the shift). TSan reports nothing in SyncOnAddress.cpp.

Not covered: Windows and macOS, and a real libthr-style userland unlock from a title.

AI-assisted: yes

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 25968 core/libs/tests/GuestUmtxOp.cpp L997

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 19454 core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp
core/libs/tests/GuestUmtxOp.cpp

@kiwe147

kiwe147 commented Nov 20, 2026

Copy link
Copy Markdown

Tested head 17ad128a8a, applied with git apply on main 86d2ba2 together with the other eight PRs of one batch (#23921, #23955, #24031, #24072, #24073, #24077, #24081, #24130). All nine applied without conflicts and the whole tree built.

Setup: Windows 11 Pro 10.0.26200, Ryzen 7 9800X3D, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON. GPUs: NVIDIA GeForce RTX 3080 (driver 621.24) and the AMD Radeon iGPU of the CPU (gfx1036, driver 32.0.21036.18). No validation layer. iGPU runs: ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 ANYPS5_GPU="AMD Radeon".

test RTX 3080
guest_umtx_op (with the new MutexLockAndWaitDoNotLoseAWakeupToAUserlandUnlock loop) pass, 2.9 s

Whole batch: the full ctest -j 12 (6496 tests) on the RTX 3080 has 4 failures, and all 4 also fail on main 86d2ba2 (agc_driver_stencil_plane_memory, agc_driver_msaa_dcc_unwatch, agc_storage_write_back_host_retile, and pr_overlap_names, which needs a newer Python than my 3.10). The 2099 agc_/video tests on the iGPU ran twice. The second run fails only agc_driver_stencil_plane_memory and agc_driver_store_over_untracked, both known on main. The first run also failed agc_driver_image_table_packed_guards once; it passes 12 of 12 alone on both GPUs and did not recur.

This is one combined tree, not a run of this PR alone.

AI-assisted: yes (Claude Code)

A thread calling _umtx_op(m, UMTX_OP_MUTEX_LOCK) or UMTX_OP_MUTEX_WAIT
while another thread owns m without UMUTEX_CONTESTED read the owner
word, failed, and only then tried to set UMUTEX_CONTESTED. If the owner
unlocked in userland in between, with CAS(id -> 0) as libthr-style
locks do while the bit is clear, MarkContested found the word unowned
and returned without marking it, and the caller went to sleep anyway.
Nothing enters the kernel to wake it: the call returned ETIMEDOUT at its
timeout, or slept forever without one, while the mutex was free.

MUTEX_UNLOCK and MUTEX_WAKE had a second window: they counted the
waiters under the bucket lock, released it, and only then updated the
owner word and woke one waiter. A locker that queued in between was not
counted, so with one waiter queued MUTEX_UNLOCK stored UMUTEX_UNOWNED
although two threads waited; the woken one took the mutex without
UMUTEX_CONTESTED and its userland unlock never woke the other.

The _umtx_op debt entry says contention and wakeups follow FreeBSD 11's
kern_umtx.c. Its do_lock_normal sleeps only when its CAS that sets the
contested bit succeeds on the owner value it saw and otherwise drops the
queue lock and retries ("the lock changed and we need to retry");
do_unlock_normal and do_wake_umutex count, update the owner word and
signal under umtxq_busy, which a locker also holds while it queues and
sets the bit.

MarkContested now reports whether the word still names an owning
thread. UMUTEX_RB_OWNERDEAD and UMUTEX_RB_NOTRECOV do not: the acquire
takes the first over with EOWNERDEAD and refuses the second with
ENOTRECOVERABLE, MUTEX_WAIT returns on both, and do_lock_normal never
sleeps on either. When the word names no owning thread, the wait
predicate returns without sleeping and MutexLock retries the acquire
(for MUTEX_WAIT, the check for a free word) in a new hold of the bucket
lock, as do_lock_normal does, so a guest word that keeps changing does
not keep the shared bucket locked with signal delivery deferred. A
thread sleeps only once UMUTEX_CONTESTED is set on a word a thread
owns. MUTEX_UNLOCK counts the waiters, stores the unlocked value
(UMUTEX_UNOWNED, or UMUTEX_RB_OWNERDEAD for a robust umutex released at
thread exit and UMUTEX_RB_NOTRECOV for one marked UMUTEX_NONCONSISTENT,
with UMUTEX_CONTESTED added for a second waiter) and wakes one waiter in
one hold of the bucket lock, inside the signal deferral that the wake
already used; MUTEX_WAKE counts, repairs the word and wakes one waiter
the same way. WakeAddress takes that lock itself around the same wake
loop. The code is shared by Linux, Windows and macOS. Relocking an
owned mutex, EINVAL for priority protection, the owner id and the
robust owner values stay as they were.

guest_umtx_op gains a check in which two threads lock and unlock a
umutex with userland CAS only, entering the kernel only to unlock when
UMUTEX_CONTESTED is set, while the main thread calls MUTEX_LOCK and
MUTEX_UNLOCK, then MUTEX_WAIT, for 200 ms each with the 10 s failsafe.
The window lies between two loads inside the wait predicate, so the
check is a bounded stress loop rather than a scripted interleaving.
Before this change a call slept through the failsafe and failed with
ETIMEDOUT while the holders kept taking the word without
UMUTEX_CONTESTED. The unlock-side window, and a robust value appearing
between the acquire and MarkContested, were found by reading the code;
the check does not reproduce them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014t2HhdnDYm3ps2BQNLaF2H
@jpirz
jpirz force-pushed the fix-umtx-lost-wakeup branch from 17ad128 to cf69df9 Compare November 24, 2026 17:16
@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Nov 24, 2026

@MarcZX10 MarcZX10 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.

Reviewed — no blocking findings

The changed synchronization paths keep waiter registration and wakeup decisions under the same bucket lock, and the bounded regression test covers lock and wait retries under concurrent userland unlocks.

What I ran

Reviewed head cf69df9d7d5c7abe2089d31d60186b659e526463 using the prepared diff and repo_read.py targeted source reads. No commands or tests were run in this review. The PR description reports Ubuntu 24.04 x86-64 build and test results; these were not independently run.

Results

Check Result Note
Diff and changed source passed Both changed files read
Build and tests not run Author-reported results only
Negative control not run No test mutation performed

Findings

Blocking

None.

Non-blocking

None.

Not verified

The complete changed-file texts listed as reviewed in the manifest were not read end to end; targeted ranges around changed hunks and their relevant wait/wake helpers were read. The prepared files.json was not available through the reader. The PR description's reported Linux build and test results, the Windows and macOS behavior, and the unlock-side race scenario were not independently verified. The review did not inspect repository-wide callers beyond targeted context.

To get this to a good state

Nothing is required.

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against cf69df9d7d:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_umtx_op_tests built cleanly.
  • CTest (guest_umtx_op):
    1/1 Test #6491: guest_umtx_op ....................   Passed    2.60 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/SyncOnAddress/src/SyncOnAddress.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #6491: guest_umtx_op ....................Subprocess aborted***Exception:  12.10 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified MarkContested return value and retry handling in MutexLock (SyncOnAddress.cpp:648-701) ensuring a retry occurs when the lock is released in userland before marking contested instead of sleeping on an uncontested/free lock
    • Verified atomic owner update and WakeWaiters under bucket.mutex in MutexUnlock (SyncOnAddress.cpp:727-736), preventing uncounted waiters from being orphaned without UMUTEX_CONTESTED
    • Verified MutexWake synchronization with DeferringDelivery and bucket.mutex (SyncOnAddress.cpp:746-758), ensuring consistent WaiterCount inspection and compare_exchange_strong against UMUTEX_CONTESTED
    • Verified updated WaiterCount signature accepting const WaiterBucket& and all call sites in SyncOnAddress.cpp
    • Verified GuestUmtxOp.cpp regression test MutexLockAndWaitDoNotLoseAWakeupToAUserlandUnlock correctly stresses both UMTX_OP_MUTEX_LOCK and UMTX_OP_MUTEX_WAIT under heavy userland CAS contention without leaking resources

Looks Good To Me

@oneandonlydean
oneandonlydean merged commit 678a86a into boykopovar:main Nov 27, 2026
14 of 16 checks passed
superSniper4576154 pushed a commit to superSniper4576154/AnyPS5 that referenced this pull request Dec 6, 2026
…tics and run tools

Local working branch, not for upstream as-is. Holds the open PRs applied for PPSA38500
(boykopovar#27532 boykopovar#27543 boykopovar#27560 boykopovar#27648 boykopovar#27649 boykopovar#27590 boykopovar#27563 boykopovar#27457 boykopovar#21238 boykopovar#21763 boykopovar#24077 boykopovar#24070 boykopovar#26174
boykopovar#24826), the GuestAllocations span/pin fixes, the opt-in fair GPU lock, span-aware table reuse,
APS5_UNTRACKED_COMPARE_MEMO, the APS5_TRACE_TABLE_STEPS diagnostics, and the run/dump scripts.
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.

7 participants