feat(libkernel_sys): implement pthread_suspend_np #12130

Open
2Swagger wants to merge 16 commits from upstream-pr/12130 into main
2Swagger commented 2026-10-27 22:31:26 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by 2Swagger on 2026-10-27T22:31:26Z.


What

Implements pthread_suspend_np in libkernel_sys, following FreeBSD 11.4 libthr (thr_suspend_np.c): EINVAL for a null thread, ESRCH for a finished one, EDEADLK for the caller, otherwise 0 once the target is suspended. It builds on the create-suspended and resume side from #9573, so pthread_resume_np, pthread_resume_all_np and pthread_multi_np resume it unchanged.

A running thread is only ever stopped at a safe point, where it holds no host lock, so suspending a thread can't stall the emulator itself (the kind of freeze #10666 describes for exception delivery):

  • In guest code: on Windows the target is frozen with SuspendThread and stays frozen until resumed; on Linux a SIGUSR2 handler parks it when the interrupted address is in the main executable or a *.guest.prx (code ranges collected with dl_iterate_phdr outside the handler).
  • In a libkernel wait: on Windows an APC queued into the alertable wait parks it; on Linux the signal handler parks it inside the TimedWait delivery scope, and a new TimedWait::SuspendSafeWait scope marks the Linux mutex waits in Mutex.cpp the same way.
  • When a guest sleep returns: sceKernelUsleep, nanosleep, usleep and sceKernelSleep (all through CancellableSleep) park a thread with a pending suspend.
  • Anywhere else (host code): the caller samples the target again until it reaches one of these points, yielding between attempts and sleeping 1 ms every 256 so that the caller itself stays suspendable.

Parked threads wait on a per-thread epoch word (a raw futex on Linux, so the signal handler stays async-signal-safe), and threads created suspended now park through the same function. A start flag closes the race between pthread_create and the first suspend.

docs/dev/debt/libkernel_sys.md gets an entry for the gaps: a thread that spends nearly all its time in host calls is suspended late (with scePthreadRename called back to back: median 160-205 ms and worst 1.3 s per suspend on Windows 11, median under 0.1 ms and worst 3 ms on Linux), a thread blocked in a host call outside the libkernel waits is suspended only after the call returns while FreeBSD suspends it at once, and sceKernelRaiseException on a suspended thread throws, as for one created suspended. pthread_suspend_all_np, pthread_single_np and the sce forms still throw.

Tested

  • New guest_pthread_suspend: error codes; a thread created suspended stays parked; a spinner in guest code, a thread looping on sceKernelUsleep(200), and a thread that renames itself under its name lock while the caller reads that name during each suspend (40 suspend/resume rounds each, checking the target makes no progress while suspended and continues after resume); a thread blocked on a mutex stays suspended after the mutex is released and takes it only after resume; a cancel sent to a suspended thread takes effect only after resume; a spinner is suspended and resumed 40 times while another thread keeps creating and joining threads; a host thread that became a guest thread through scePthreadSelf (as a title's main thread does) is suspended and resumed 40 times; such a thread makes a 2 ms host call and exits while it is being suspended, 200 times (also run 20 times under AddressSanitizer on Linux, no reports). About 3 s per run.
  • Head b09a13358, merged onto main fd9b3f62d. Windows 11 (WinLibs GCC 15.2.0, Release): guest_pthread_suspend, guest_pthread_create_suspended, guest_exception_handler, guest_raise_exception, guest_raise_nested_sleep, guest_mutex_raise_exception, guest_raise_in_host_code, guest_raise_leaves_host_code and public_headers with its compile batches pass, 73 of 73. Linux (Ubuntu 24.04 under WSL2, GCC 13.3.0, Release): the same set as registered there, 69 of 69.
  • guest_pthread_suspend and guest_pthread_create_suspended passed 20 consecutive runs each on both platforms with the code of b09a13358 (ctest --repeat until-fail:20), and 200 each at 039d7c7ad, before the 256-segment check. The check itself is defensive: no practical test loads 257 executable guest segments.
  • Conventions and test registration pass. Not tested on a console or a title.

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: #10817
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5042095260 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12130). Originally posted by [2Swagger](https://github.com/2Swagger) on 2026-10-27T22:31:26Z. --- ### What Implements `pthread_suspend_np` in libkernel_sys, following FreeBSD 11.4 libthr ([`thr_suspend_np.c`](https://github.com/freebsd/freebsd-src/blob/8c639945/lib/libthr/thread/thr_suspend_np.c)): `EINVAL` for a null thread, `ESRCH` for a finished one, `EDEADLK` for the caller, otherwise 0 once the target is suspended. It builds on the create-suspended and resume side from #9573, so `pthread_resume_np`, `pthread_resume_all_np` and `pthread_multi_np` resume it unchanged. A running thread is only ever stopped at a safe point, where it holds no host lock, so suspending a thread can't stall the emulator itself (the kind of freeze #10666 describes for exception delivery): - **In guest code:** on Windows the target is frozen with `SuspendThread` and stays frozen until resumed; on Linux a `SIGUSR2` handler parks it when the interrupted address is in the main executable or a `*.guest.prx` (code ranges collected with `dl_iterate_phdr` outside the handler). - **In a libkernel wait:** on Windows an APC queued into the alertable wait parks it; on Linux the signal handler parks it inside the `TimedWait` delivery scope, and a new `TimedWait::SuspendSafeWait` scope marks the Linux mutex waits in `Mutex.cpp` the same way. - **When a guest sleep returns:** `sceKernelUsleep`, `nanosleep`, `usleep` and `sceKernelSleep` (all through `CancellableSleep`) park a thread with a pending suspend. - **Anywhere else (host code):** the caller samples the target again until it reaches one of these points, yielding between attempts and sleeping 1 ms every 256 so that the caller itself stays suspendable. Parked threads wait on a per-thread epoch word (a raw futex on Linux, so the signal handler stays async-signal-safe), and threads created suspended now park through the same function. A start flag closes the race between `pthread_create` and the first suspend. `docs/dev/debt/libkernel_sys.md` gets an entry for the gaps: a thread that spends nearly all its time in host calls is suspended late (with `scePthreadRename` called back to back: median 160-205 ms and worst 1.3 s per suspend on Windows 11, median under 0.1 ms and worst 3 ms on Linux), a thread blocked in a host call outside the libkernel waits is suspended only after the call returns while FreeBSD suspends it at once, and `sceKernelRaiseException` on a suspended thread throws, as for one created suspended. `pthread_suspend_all_np`, `pthread_single_np` and the sce forms still throw. ### Tested - New `guest_pthread_suspend`: error codes; a thread created suspended stays parked; a spinner in guest code, a thread looping on `sceKernelUsleep(200)`, and a thread that renames itself under its name lock while the caller reads that name during each suspend (40 suspend/resume rounds each, checking the target makes no progress while suspended and continues after resume); a thread blocked on a mutex stays suspended after the mutex is released and takes it only after resume; a cancel sent to a suspended thread takes effect only after resume; a spinner is suspended and resumed 40 times while another thread keeps creating and joining threads; a host thread that became a guest thread through `scePthreadSelf` (as a title's main thread does) is suspended and resumed 40 times; such a thread makes a 2 ms host call and exits while it is being suspended, 200 times (also run 20 times under AddressSanitizer on Linux, no reports). About 3 s per run. - Head b09a13358, merged onto `main` fd9b3f62d. Windows 11 (WinLibs GCC 15.2.0, Release): `guest_pthread_suspend`, `guest_pthread_create_suspended`, `guest_exception_handler`, `guest_raise_exception`, `guest_raise_nested_sleep`, `guest_mutex_raise_exception`, `guest_raise_in_host_code`, `guest_raise_leaves_host_code` and `public_headers` with its compile batches pass, 73 of 73. Linux (Ubuntu 24.04 under WSL2, GCC 13.3.0, Release): the same set as registered there, 69 of 69. - `guest_pthread_suspend` and `guest_pthread_create_suspended` passed 20 consecutive runs each on both platforms with the code of b09a13358 (`ctest --repeat until-fail:20`), and 200 each at 039d7c7ad, before the 256-segment check. The check itself is defensive: no practical test loads 257 executable guest segments. - Conventions and test registration pass. Not tested on a console or a title. ### 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: #10817 - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-11-17 08:52:23 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-17T08:52:23Z.

Review: COMMENTED


Reviewed — no blocking findings

Nothing blocks this; the points below are optional. The review read the diff of all 12 changed files at head 56e24d1b14647cdd7111772e2d7686827c521837, but no build or test was run and the full file text was not read.

What I ran

  • Head 56e24d1b14647cdd7111772e2d7686827c521837, base main. No merged-preview check.
  • Read the change description, commit list, manifest, exclusion list and diff.patch.
  • Read the house rules sections for readable reviews, the standard response format and accuracy and evidence.
  • Read head context with the repository reader:
Commands
python3 repo_read.py cat core/libs/prx/libkernel/System/src/Exception.cpp 1640 1672
python3 repo_read.py cat core/libs/prx/libkernel/Time/TimedWait.cpp 336 352
python3 repo_read.py cat core/libs/prx/libkernel/Time/TimedWait.cpp 484 494
python3 repo_read.py search SIGUSR2
python3 repo_read.py search DeliverDeferred
python3 repo_read.py search SleepNanos

Results

Check Result Note
Diff of 12 files passed Read from diff.patch
Full file text not run Nothing read from files/
Build and tests not run Builds are out of scope for this review
Author's test runs not applicable Reported in the description, not reproduced

Findings

Blocking

None.

Non-blocking

  • core/libs/prx/libkernel/System/src/Exception.cpp:1656 (Windows only): the throw is reached only when the compare-exchange on pendingException fails and the stored value is 0 or less. A new raise on a suspended thread takes the first branch and returns 0 without throwing. The Linux branch has no suspended check at all. So the claim that sceKernelRaiseException on a suspended thread throws does not match the code as read, unless pendingException can hold a negative value, which I did not check. See the debt entry at docs/dev/debt/libkernel_sys.md:391, which says it throws without a platform qualifier.
  • core/libs/prx/libkernel/System/src/Exception.cpp:40-44: the new __linux__ block adds <link.h> and <string_view>, which the existing __linux__ block below already includes. Harmless, but a duplicate.

Sources

Not verified

  • Full text of all 12 files, read only as diff. No file under files/ was read.
  • The Windows park path (SuspendThread, GetThreadContext, the APC park, the osParked handoff with ResumeThread): read as diff only, and the race reasoning was not checked against a run.
  • Linux SIGUSR2: the only production host use in the head is Exception.cpp, but I did not check whether guest signal delivery uses a host SIGUSR2 anywhere else. The head search matched a test in libSceAgcDriver and a guest signal number in GuestSignalList.cpp.
  • Whether ParkCurrentGuestThread_nid_no_patch is visible from Time.cpp (the include list was not read).
  • Console behaviour is unmeasured, as the description says. The author's Windows and Linux test runs were not reproduced here.

To get this to a good state

Nothing is required.

Optional, once:

  • Make the debt entry and the sceKernelRaiseException check agree: state the throw is Windows-only and for the negative-pending case, or move the check ahead of the compare-exchange.
  • Remove the duplicate <link.h> and <string_view> includes in Exception.cpp.
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5935457610 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12130#pullrequestreview-5935457610). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-17T08:52:23Z. **Review:** COMMENTED --- # Reviewed — no blocking findings Nothing blocks this; the points below are optional. The review read the diff of all 12 changed files at head `56e24d1b14647cdd7111772e2d7686827c521837`, but no build or test was run and the full file text was not read. ## What I ran - Head `56e24d1b14647cdd7111772e2d7686827c521837`, base `main`. No merged-preview check. - Read the change description, commit list, manifest, exclusion list and `diff.patch`. - Read the house rules sections for readable reviews, the standard response format and accuracy and evidence. - Read head context with the repository reader: <details> <summary>Commands</summary> ``` python3 repo_read.py cat core/libs/prx/libkernel/System/src/Exception.cpp 1640 1672 python3 repo_read.py cat core/libs/prx/libkernel/Time/TimedWait.cpp 336 352 python3 repo_read.py cat core/libs/prx/libkernel/Time/TimedWait.cpp 484 494 python3 repo_read.py search SIGUSR2 python3 repo_read.py search DeliverDeferred python3 repo_read.py search SleepNanos ``` </details> ## Results | Check | Result | Note | |---|---|---| | Diff of 12 files | passed | Read from `diff.patch` | | Full file text | not run | Nothing read from `files/` | | Build and tests | not run | Builds are out of scope for this review | | Author's test runs | not applicable | Reported in the description, not reproduced | ## Findings **Blocking** None. **Non-blocking** - `core/libs/prx/libkernel/System/src/Exception.cpp:1656` (Windows only): the throw is reached only when the compare-exchange on `pendingException` fails and the stored value is 0 or less. A new raise on a suspended thread takes the first branch and returns 0 without throwing. The Linux branch has no suspended check at all. So the claim that `sceKernelRaiseException` on a suspended thread throws does not match the code as read, unless `pendingException` can hold a negative value, which I did not check. See the debt entry at `docs/dev/debt/libkernel_sys.md:391`, which says it throws without a platform qualifier. - `core/libs/prx/libkernel/System/src/Exception.cpp:40-44`: the new `__linux__` block adds `<link.h>` and `<string_view>`, which the existing `__linux__` block below already includes. Harmless, but a duplicate. ## Sources - Exception check, head: https://github.com/boykopovar/AnyPS5/blob/56e24d1b14647cdd7111772e2d7686827c521837/core/libs/prx/libkernel/System/src/Exception.cpp#L1653-L1660 - Debt entry, head: https://github.com/boykopovar/AnyPS5/blob/56e24d1b14647cdd7111772e2d7686827c521837/docs/dev/debt/libkernel_sys.md#L391 ## Not verified - Full text of all 12 files, read only as diff. No file under `files/` was read. - The Windows park path (`SuspendThread`, `GetThreadContext`, the APC park, the `osParked` handoff with `ResumeThread`): read as diff only, and the race reasoning was not checked against a run. - Linux `SIGUSR2`: the only production host use in the head is `Exception.cpp`, but I did not check whether guest signal delivery uses a host `SIGUSR2` anywhere else. The head search matched a test in `libSceAgcDriver` and a guest signal number in `GuestSignalList.cpp`. - Whether `ParkCurrentGuestThread_nid_no_patch` is visible from `Time.cpp` (the include list was not read). - Console behaviour is unmeasured, as the description says. The author's Windows and Linux test runs were not reproduced here. ## To get this to a good state Nothing is required. Optional, once: - Make the debt entry and the `sceKernelRaiseException` check agree: state the throw is Windows-only and for the negative-pending case, or move the check ahead of the compare-exchange. - Remove the duplicate `<link.h>` and `<string_view>` includes in `Exception.cpp`.
ligmaSec commented 2026-12-03 16:20:31 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T16:20:31Z.

Review: COMMENTED


This head conflicts in the fault-delivery code in Exception.cpp and overlaps #21464 on the exported pthread_suspend_np implementation. Please coordinate those entry points and preserve the current signal-delivery setup when rebasing the narrower change.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6173792474 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12130#pullrequestreview-6173792474). Originally posted by [ligmaSec](https://github.com/ligmaSec) on 2026-12-03T16:20:31Z. **Review:** COMMENTED --- This head conflicts in the fault-delivery code in `Exception.cpp` and overlaps #21464 on the exported `pthread_suspend_np` implementation. Please coordinate those entry points and preserve the current signal-delivery setup when rebasing the narrower change. AI-assisted: yes.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/12130:upstream-pr/12130'
git switch 'upstream-pr/12130'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/12130'
git switch 'upstream-pr/12130'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/12130'
git switch 'upstream-pr/12130'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/12130'
git switch 'main'
git merge --squash 'upstream-pr/12130'
git switch 'main'
git merge --ff-only 'upstream-pr/12130'
git switch 'main'
git merge 'upstream-pr/12130'
git push origin 'main'
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!12130
No description provided.