fix(libkernel): avoid cancellation wakeups during thread exit #10856

Merged
Felipebmaitan merged 5 commits from upstream-pr/10856 into main 2026-10-28 09:52:08 +00:00
Felipebmaitan commented 2026-10-25 05:36:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Felipebmaitan on 2026-10-25T05:36:24Z.


What

scePthreadCancel repeatedly notifies a registered wait until the target unregisters it. A thread already exiting can enter that wait from a cleanup handler or a thread-specific destructor, while ThreadCancel::Requested() excludes it from cancellation. If the callback needs progress from the requester, waiting for acknowledgement prevents that progress.

Record the wait pointer and a terminal-exit marker together under cancelLock. A cancellation request still becomes pending, but returns without notifying a wait registered during exit. Ordinary notification or timeout completes that wait, and EndWait clears both fields before reacquiring the application lock. Non-exiting waits, including disabled-to-enabled cancellation transitions, retain main's behavior. No exported signatures change.

The 24 independent regressions gate the actual production ThreadCancel::Wait template during explicit-exit cleanup, explicit-exit TSD destruction, or TSD destruction after the entry returns naturally. Three SCE or POSIX cancellation requests must return before the target gate is released or an ordinary notification is sent. A failed observation exits unsuccessfully without releasing the gate, so recovery cannot manufacture a pass. Each lifecycle trigger covers timed/untimed waits, both request APIs, and normal/coarse backends. Completion preserves the exit result and cleanup-before-TSD ordering. The natural-return mode pushes no cleanup handler, requires zero cleanup calls and one destructor, and preserves the entry's return value; it specifically covers finishThread setting the exit marker.

The component debt records remaining non-exit acknowledgement dependencies, nested-registration loss, allocation-failure cleanup, and skipped unwinding. This is a host progress repair, with no new PS5 measurement. The gates do not inject an exception handler or establish general signal/cancellation safety.

Overlap: #7565 adds hostMxcsr at the same header insertion point; any merge must retain both it and cancelWaitExiting. #7135 and #8916 touch adjacent debt text; preserve their entries too. None is a semantic prerequisite. The overlap tool also lists older PRs whose shared files could not be compared because they conflict with main; no exhaustive composition validation or merge-order agreement is claimed. These textual overlaps still need coordination before merge.

Tested

Windows 11 Pro, AMD Ryzen 7 9800X3D, WinLibs MinGW-w64 GCC 15.2.0 r7 UCRT/POSIX, Release, BUILD_TESTING=ON, bundled dependencies. Full CMake configuration; selected libc/libkernel and test targets built from source with --parallel 2 in this branch's own build directory.

  • Original PR base: e7e3e9c1984c293f06bff08428b8c89b7b932ac2. Current main inspected for this follow-up: b986c11a344eb094eec31cbc3977fe2ae8f6eb30. The PR remains cleanly mergeable; no current-main composition run is claimed.
  • Negative artifact 64ad39e457b3ba7ecf86a2c17a26b4849d03bcc0 contains only the new test and its registrations, with main's production code. All 16/16 new cases fail at the cancellation-return gate before release (ctest exit 8); the five existing cancellation/semaphore controls pass 5/5.
  • Repaired implementation 84340f6d6391eb4e60d61a864f35a261ec1477e0: focused runtime selection passes 39/39, including all 16 new cases, with no skips. Original production head f68eb887c91aaf20767ef327f367b9f21b264383 only adds a debt clarification; git diff --exit-code 84340f6d6391 f68eb887c91a -- core is empty.
  • Final registered public-header retry passes 65/65, including all 64 compile batches. The first current attempt timed out in the audit at 30.04 seconds, leaving 64 batches Not Run. A separate direct audit then verified 12,175 exports in 34.87 seconds. The registered retry's audit passed in 12.86 seconds; no timeout was increased and no exclusion was added.
  • Two independent GPT-6.1-Sol/xhigh macro and micro reviews of the original production head f68eb887c91a found no scoped blocking defect. Their static/source and log review is separate from the runtime executions above.
  • Review follow-up f75e51c5d417080a228b6c8a5782577eba0b78eb adds eight natural-return cases and changes only the fixture and CMake registrations. The production Pthread sources and headers are unchanged from f68eb887c91a. All 47/47 focused Windows runtime cases pass with no skips (10.16 seconds), including all 24 teardown gates. No public-header rerun was needed for this test-only follow-up; the 65/65 result above belongs to the original artifact.
  • Bounded main-function negative control: substitute the exact BeginWait and scePthreadCancel definitions from current main b986c11a344e into this PR fixture. The new natural-return cases fail 8/8 at the cancellation-return observation, before gate release or normal notification; five existing cancel/semaphore controls pass 5/5. The relevant wait templates, Requested, EndWait, and finishThread match that main head. This is selected-path evidence, not a build of the whole current-main tree.
  • Lifecycle-specific negative control: remove only CurrentGuestState().exiting = true from finishThread in the repaired production source. The eight natural-return cases fail 8/8 at the same observation, while the 16 explicit-exit cases still pass 16/16. Both controls terminate unsuccessfully within the two-second observation bound; no CTest timeout, gate release, or cleanup recovery supplies the result. Production source was restored byte-for-byte and rebuilt before the 47/47 run.
  • Conventions, whitespace and branch-overlap checks completed. The working tree is clean. No Linux/macOS, console, original-module, title, GPU, hosted runtime, full repository suite, or combined-PR execution is claimed. No performance claim.
cmake --build build --parallel 2 --target guest_pthread_cancel_inactive_wait_tests guest_pthread_cancel_tests guest_pthread_cancel_recovery_tests guest_sem_canceled_wake_tests guest_sleep_cancel_tests guest_once_tests guest_pthread_join_detach_tests guest_pthread_join_self_tests guest_pthread_key_tests guest_pthread_destructor_lifetime_tests guest_cond_timedwait_tests guest_cond_recursive_mutex_tests guest_cond_unowned_mutex_tests guest_signal_tests guest_signal_set_tests
ctest --test-dir build -R '^(guest_pthread_cancel.*|guest_sem_canceled_wake(_coarse)?|guest_sleep_cancel.*|guest_once|guest_pthread_join_detach|guest_pthread_join_self|guest_pthread_key|guest_pthread_destructor_lifetime|guest_cond_timedwait.*|guest_cond_recursive_mutex|guest_cond_unowned_mutex|guest_signals|guest_signal_sets)$' -V --parallel 2
ctest --test-dir build -R '^public_headers(_compile_[0-9]+)?$' --output-on-failure --parallel 2
python tools/check_conventions.py --base origin/main
git diff --check origin/main...HEAD
python tools/pr_overlap.py --branch feat/guest-signal-cancellation --repo boykopovar/AnyPS5 --jobs 2

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: #11872 (agreed merge order; no new runtime dependency)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5002147687 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10856). Originally posted by [Felipebmaitan](https://github.com/Felipebmaitan) on 2026-10-25T05:36:24Z. --- ### What `scePthreadCancel` repeatedly notifies a registered wait until the target unregisters it. A thread already exiting can enter that wait from a cleanup handler or a thread-specific destructor, while `ThreadCancel::Requested()` excludes it from cancellation. If the callback needs progress from the requester, waiting for acknowledgement prevents that progress. Record the wait pointer and a terminal-exit marker together under `cancelLock`. A cancellation request still becomes pending, but returns without notifying a wait registered during exit. Ordinary notification or timeout completes that wait, and `EndWait` clears both fields before reacquiring the application lock. Non-exiting waits, including disabled-to-enabled cancellation transitions, retain main's behavior. No exported signatures change. The 24 independent regressions gate the actual production `ThreadCancel::Wait` template during explicit-exit cleanup, explicit-exit TSD destruction, or TSD destruction after the entry returns naturally. Three SCE or POSIX cancellation requests must return before the target gate is released or an ordinary notification is sent. A failed observation exits unsuccessfully without releasing the gate, so recovery cannot manufacture a pass. Each lifecycle trigger covers timed/untimed waits, both request APIs, and normal/coarse backends. Completion preserves the exit result and cleanup-before-TSD ordering. The natural-return mode pushes no cleanup handler, requires zero cleanup calls and one destructor, and preserves the entry's return value; it specifically covers `finishThread` setting the exit marker. The component debt records remaining non-exit acknowledgement dependencies, nested-registration loss, allocation-failure cleanup, and skipped unwinding. This is a host progress repair, with no new PS5 measurement. The gates do not inject an exception handler or establish general signal/cancellation safety. Overlap: #7565 adds `hostMxcsr` at the same header insertion point; any merge must retain both it and `cancelWaitExiting`. #7135 and #8916 touch adjacent debt text; preserve their entries too. None is a semantic prerequisite. The overlap tool also lists older PRs whose shared files could not be compared because they conflict with main; no exhaustive composition validation or merge-order agreement is claimed. These textual overlaps still need coordination before merge. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> Windows 11 Pro, AMD Ryzen 7 9800X3D, WinLibs MinGW-w64 GCC 15.2.0 r7 UCRT/POSIX, Release, `BUILD_TESTING=ON`, bundled dependencies. Full CMake configuration; selected libc/libkernel and test targets built from source with `--parallel 2` in this branch's own build directory. - Original PR base: `e7e3e9c1984c293f06bff08428b8c89b7b932ac2`. Current main inspected for this follow-up: `b986c11a344eb094eec31cbc3977fe2ae8f6eb30`. The PR remains cleanly mergeable; no current-main composition run is claimed. - Negative artifact `64ad39e457b3ba7ecf86a2c17a26b4849d03bcc0` contains only the new test and its registrations, with main's production code. All **16/16** new cases fail at the cancellation-return gate before release (`ctest` exit 8); the five existing cancellation/semaphore controls pass **5/5**. - Repaired implementation `84340f6d6391eb4e60d61a864f35a261ec1477e0`: focused runtime selection passes **39/39**, including all 16 new cases, with no skips. Original production head `f68eb887c91aaf20767ef327f367b9f21b264383` only adds a debt clarification; `git diff --exit-code 84340f6d6391 f68eb887c91a -- core` is empty. - Final registered public-header retry passes **65/65**, including all 64 compile batches. The first current attempt timed out in the audit at 30.04 seconds, leaving 64 batches Not Run. A separate direct audit then verified 12,175 exports in 34.87 seconds. The registered retry's audit passed in 12.86 seconds; no timeout was increased and no exclusion was added. - Two independent GPT-6.1-Sol/xhigh macro and micro reviews of the original production head `f68eb887c91a` found no scoped blocking defect. Their static/source and log review is separate from the runtime executions above. - Review follow-up `f75e51c5d417080a228b6c8a5782577eba0b78eb` adds eight natural-return cases and changes only the fixture and CMake registrations. The production Pthread sources and headers are unchanged from `f68eb887c91a`. All **47/47** focused Windows runtime cases pass with no skips (10.16 seconds), including all 24 teardown gates. No public-header rerun was needed for this test-only follow-up; the 65/65 result above belongs to the original artifact. - Bounded main-function negative control: substitute the exact `BeginWait` and `scePthreadCancel` definitions from current main `b986c11a344e` into this PR fixture. The new natural-return cases fail **8/8** at the cancellation-return observation, before gate release or normal notification; five existing cancel/semaphore controls pass **5/5**. The relevant wait templates, `Requested`, `EndWait`, and `finishThread` match that main head. This is selected-path evidence, not a build of the whole current-main tree. - Lifecycle-specific negative control: remove only `CurrentGuestState().exiting = true` from `finishThread` in the repaired production source. The eight natural-return cases fail **8/8** at the same observation, while the 16 explicit-exit cases still pass **16/16**. Both controls terminate unsuccessfully within the two-second observation bound; no CTest timeout, gate release, or cleanup recovery supplies the result. Production source was restored byte-for-byte and rebuilt before the 47/47 run. - Conventions, whitespace and branch-overlap checks completed. The working tree is clean. No Linux/macOS, console, original-module, title, GPU, hosted runtime, full repository suite, or combined-PR execution is claimed. No performance claim. ```powershell cmake --build build --parallel 2 --target guest_pthread_cancel_inactive_wait_tests guest_pthread_cancel_tests guest_pthread_cancel_recovery_tests guest_sem_canceled_wake_tests guest_sleep_cancel_tests guest_once_tests guest_pthread_join_detach_tests guest_pthread_join_self_tests guest_pthread_key_tests guest_pthread_destructor_lifetime_tests guest_cond_timedwait_tests guest_cond_recursive_mutex_tests guest_cond_unowned_mutex_tests guest_signal_tests guest_signal_set_tests ctest --test-dir build -R '^(guest_pthread_cancel.*|guest_sem_canceled_wake(_coarse)?|guest_sleep_cancel.*|guest_once|guest_pthread_join_detach|guest_pthread_join_self|guest_pthread_key|guest_pthread_destructor_lifetime|guest_cond_timedwait.*|guest_cond_recursive_mutex|guest_cond_unowned_mutex|guest_signals|guest_signal_sets)$' -V --parallel 2 ctest --test-dir build -R '^public_headers(_compile_[0-9]+)?$' --output-on-failure --parallel 2 python tools/check_conventions.py --base origin/main git diff --check origin/main...HEAD python tools/pr_overlap.py --branch feat/guest-signal-cancellation --repo boykopovar/AnyPS5 --jobs 2 ``` ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [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: #11872 (agreed merge order; no new runtime dependency) <!-- #PR, or none --> - [x] Fixes: none <!-- issue it closes as Fixes #N, or none --> - [x] Unblocks: none <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none --> - [x] GPUs tested: n/a <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a --> - [x] AI-assisted: yes <!-- yes / no -->
MarcZX10 commented 2026-10-25 05:39:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T05:39:47Z.

Review: APPROVED


Reviewed exact head f68eb887c91aaf20767ef327f367b9f21b264383 against current main e7e3e9c1984c293f06bff08428b8c89b7b932ac2. The exit marker is set before cleanup handlers and TSD destructors run; BeginWait publishes the wait pointer and whether it belongs to exit under cancelLock, and scePthreadCancel checks both under that same lock before notifying. This closes the requester-waits-for-exiting-callback deadlock while preserving repeated notification for ordinary registered waits. The POSIX entry delegates to the same implementation. The new tests gate the actual wait template in cleanup and destructor paths across SCE/POSIX APIs, timed/untimed waits, and normal/coarse backends, and require the cancel requester to return before the gate is released. The author reports 16/16 new negative-control failures on main, 39/39 focused runtime tests on the fix, and a successful 65/65 public-header retry; I did not rerun the Windows runtime suite locally. I independently ran the current-main conventions checker and git diff --check on the exact head; both pass. GitHub policy checks pass; hosted product jobs are skipped. I found no blocking issue in this change.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5641739512 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10856#pullrequestreview-5641739512). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T05:39:47Z. **Review:** APPROVED --- Reviewed exact head `f68eb887c91aaf20767ef327f367b9f21b264383` against current main `e7e3e9c1984c293f06bff08428b8c89b7b932ac2`. The exit marker is set before cleanup handlers and TSD destructors run; `BeginWait` publishes the wait pointer and whether it belongs to exit under `cancelLock`, and `scePthreadCancel` checks both under that same lock before notifying. This closes the requester-waits-for-exiting-callback deadlock while preserving repeated notification for ordinary registered waits. The POSIX entry delegates to the same implementation. The new tests gate the actual wait template in cleanup and destructor paths across SCE/POSIX APIs, timed/untimed waits, and normal/coarse backends, and require the cancel requester to return before the gate is released. The author reports 16/16 new negative-control failures on main, 39/39 focused runtime tests on the fix, and a successful 65/65 public-header retry; I did not rerun the Windows runtime suite locally. I independently ran the current-main conventions checker and `git diff --check` on the exact head; both pass. GitHub policy checks pass; hosted product jobs are skipped. I found no blocking issue in this change.
ahmadmuj commented 2026-10-25 11:56:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ahmadmuj on 2026-10-25T11:56:56Z.

Review: APPROVED


Reviewed head f68eb887c91a merged onto main a5a780eaaa7f (PR base e7e3e9c1984c). Linux: WSL2 Ubuntu 24.04, GCC 13.3, Release, BUILD_TESTING=ON. I think this is the first Linux run.

What I ran:

  • Merged tree: 37/37 of the focused cancel/sem/sleep/join/key/cond set pass, all 16 new cases included. The 16 new cases also pass --repeat until-fail:50.
  • Same tree with main's Thread.cpp and Pthread.hpp: all 16 new cases fail at the cancelReturned Await (line 25; a temporary print confirmed the gate Await passes first). The 13 controls pass.
  • tools/check_conventions.py --base origin/main passes on the merged tree.

One note on the Linux red. Off Windows Coarse() is always true, so NotifyAll is condition_variable_any::notify_all. While the gate parks inside the CV's unlock, the waiter holds the CV's internal mutex, so on Linux main's cancel blocks inside NotifyAll instead of spinning. To check the spin itself I ran a throwaway probe without the gate: the exiting thread waits in ThreadCancel::Wait (cleanup handler or TSD destructor) for a flag that the main thread sets only after 3 cancels return.

  • main: the cancels took 0.5-1.7 s and woke the exiting waiter 57k-170k times. 1 of 6 runs did not return within 2 s.
  • PR: under 4 ms, 0 wakeups, 6/6.

FreeBSD 11.4 agrees. _pthread_exit_mask sets cancelling and no_cancel before cleanup handlers and TSD destructors (thr_exit.c L221-L222), and check_cancel returns early on no_cancel (thr_sig.c L281-L283). _pthread_cancel only sets cancel_pending, sends SIGCANCEL and returns; it never waits for the target (thr_cancel.c L55-L75).

Two suggestions, neither blocking:

  1. All 16 cases exit through scePthreadExit. A TSD destructor that waits after the entry returns normally only gets exiting from finishThread (Thread.cpp L701), and no case covers it. I tried it with your gate and Worker doing return &context; without the cleanup push: main fails 3/3, this PR passes 3/3. One more argv mode like that would pin it.
  2. The new field may not be needed. Requested() already ignores exiting threads, so BeginWait can skip the registration: state.current->cancelWait = state.exiting ? nullptr : condition;, and scePthreadCancel keeps main's if (!thread->cancelWait) return SCE_OK;. That also drops the Pthread.hpp line that overlaps #7565. I ran that variant locally: the 16 new cases and 17 neighbouring controls pass (33/33).

Approving on the above. Linux only; no console or title run.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5643107557 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10856#pullrequestreview-5643107557). Originally posted by [ahmadmuj](https://github.com/ahmadmuj) on 2026-10-25T11:56:56Z. **Review:** APPROVED --- Reviewed head `f68eb887c91a` merged onto main `a5a780eaaa7f` (PR base `e7e3e9c1984c`). Linux: WSL2 Ubuntu 24.04, GCC 13.3, Release, `BUILD_TESTING=ON`. I think this is the first Linux run. What I ran: - Merged tree: 37/37 of the focused cancel/sem/sleep/join/key/cond set pass, all 16 new cases included. The 16 new cases also pass `--repeat until-fail:50`. - Same tree with main's `Thread.cpp` and `Pthread.hpp`: all 16 new cases fail at the `cancelReturned` Await (line 25; a temporary print confirmed the gate Await passes first). The 13 controls pass. - `tools/check_conventions.py --base origin/main` passes on the merged tree. One note on the Linux red. Off Windows `Coarse()` is always true, so `NotifyAll` is `condition_variable_any::notify_all`. While the gate parks inside the CV's unlock, the waiter holds the CV's internal mutex, so on Linux main's cancel blocks inside `NotifyAll` instead of spinning. To check the spin itself I ran a throwaway probe without the gate: the exiting thread waits in `ThreadCancel::Wait` (cleanup handler or TSD destructor) for a flag that the main thread sets only after 3 cancels return. - main: the cancels took 0.5-1.7 s and woke the exiting waiter 57k-170k times. 1 of 6 runs did not return within 2 s. - PR: under 4 ms, 0 wakeups, 6/6. FreeBSD 11.4 agrees. `_pthread_exit_mask` sets `cancelling` and `no_cancel` before cleanup handlers and TSD destructors ([thr_exit.c L221-L222](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libthr/thread/thr_exit.c#L221-L222)), and `check_cancel` returns early on `no_cancel` ([thr_sig.c L281-L283](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libthr/thread/thr_sig.c#L281-L283)). `_pthread_cancel` only sets `cancel_pending`, sends SIGCANCEL and returns; it never waits for the target ([thr_cancel.c L55-L75](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/lib/libthr/thread/thr_cancel.c#L55-L75)). Two suggestions, neither blocking: 1. All 16 cases exit through `scePthreadExit`. A TSD destructor that waits after the entry returns normally only gets `exiting` from `finishThread` ([Thread.cpp L701](https://github.com/boykopovar/AnyPS5/blob/f68eb887c91aaf20767ef327f367b9f21b264383/core/libs/prx/libkernel/Pthread/src/Thread.cpp#L701)), and no case covers it. I tried it with your gate and `Worker` doing `return &context;` without the cleanup push: main fails 3/3, this PR passes 3/3. One more argv mode like that would pin it. 2. The new field may not be needed. `Requested()` already ignores exiting threads, so `BeginWait` can skip the registration: `state.current->cancelWait = state.exiting ? nullptr : condition;`, and `scePthreadCancel` keeps main's `if (!thread->cancelWait) return SCE_OK;`. That also drops the `Pthread.hpp` line that overlaps #7565. I ran that variant locally: the 16 new cases and 17 neighbouring controls pass (33/33). Approving on the above. Linux only; no console or title run.
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!10856
No description provided.