feat(libkernel): implement CPU_LEVEL_ROOT and CPU_LEVEL_CPUSET cpuset affinity #19612

Merged
Mohabbadi11 merged 1 commit from upstream-pr/19612 into main 2026-11-21 20:01:09 +00:00
Mohabbadi11 commented 2026-11-13 16:00:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Mohabbadi11 on 2026-11-13T16:00:59Z.


What

Support CPU_LEVEL_ROOT and CPU_LEVEL_CPUSET hierarchy levels in cpuset_getaffinity and cpuset_setaffinity following FreeBSD 11.4 semantics:

  • In cpuset_getaffinity: level ROOT (1) returns the hardware root available CPU mask (0xffff), level CPUSET (2) returns the process container cpuset mask, and level WHICH (3) returns the thread affinity or the union of live guest threads for the process.
  • In cpuset_setaffinity: level ROOT returns EPERM following unprivileged sandbox semantics. Level CPUSET atomically updates the process cpuset mask, clipping explicit thread affinities and failing with EDEADLK if disjoint from any explicit thread. Level WHICH updates thread or process thread affinity without altering the process cpuset container mask.
  • Unified boundary enforcement: all affinity setters (cpuset_setaffinity, pthread_setaffinity_np, scePthreadSetaffinity, and scePthreadCreate with explicit attributes) atomically validate and enforce that thread affinity cannot exceed the enclosing process cpuset under the registry lock, eliminating TOCTOU concurrency races.
  • Explicit thread affinities and pins are inherited by child threads and preserved when the process cpuset expands.
  • Update technical debt documentation in docs/dev/debt/libkernel.md.

Tested

Ran GuestAvailableCpumask test suite verifying:

  • Invariant root mask querying under narrowed cpuset.
  • Level 2 CPUSET querying, mutation, and clipping of explicit threads.
  • Rejection of unprivileged ROOT modification with EPERM.
  • Disjoint CPUSET updates rejected with EDEADLK preserving system state.
  • Separation of CPU_LEVEL_WHICH on PID from CPU_LEVEL_CPUSET.
  • Child thread explicit affinity inheritance and isolation upon cpuset expansion.
  • Enforcement against affinities outside cpuset returning EINVAL / SCE_KERNEL_ERROR_EINVAL across cpuset_setaffinity, pthread_setaffinity_np, scePthreadSetaffinity, and scePthreadCreate.
  • Multi-threaded parallel concurrency stress test verifying atomic synchronization without TOCTOU races or deadlocks under concurrent CPUSET and affinity mutations.
  • Conventions check passed (python tools/check_conventions.py --base origin/main).

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
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5298704743 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/19612). Originally posted by [Mohabbadi11](https://github.com/Mohabbadi11) on 2026-11-13T16:00:59Z. --- ### What Support CPU_LEVEL_ROOT and CPU_LEVEL_CPUSET hierarchy levels in cpuset_getaffinity and cpuset_setaffinity following FreeBSD 11.4 semantics: - In cpuset_getaffinity: level ROOT (1) returns the hardware root available CPU mask (0xffff), level CPUSET (2) returns the process container cpuset mask, and level WHICH (3) returns the thread affinity or the union of live guest threads for the process. - In cpuset_setaffinity: level ROOT returns EPERM following unprivileged sandbox semantics. Level CPUSET atomically updates the process cpuset mask, clipping explicit thread affinities and failing with EDEADLK if disjoint from any explicit thread. Level WHICH updates thread or process thread affinity without altering the process cpuset container mask. - Unified boundary enforcement: all affinity setters (cpuset_setaffinity, pthread_setaffinity_np, scePthreadSetaffinity, and scePthreadCreate with explicit attributes) atomically validate and enforce that thread affinity cannot exceed the enclosing process cpuset under the registry lock, eliminating TOCTOU concurrency races. - Explicit thread affinities and pins are inherited by child threads and preserved when the process cpuset expands. - Update technical debt documentation in docs/dev/debt/libkernel.md. ### Tested Ran GuestAvailableCpumask test suite verifying: - Invariant root mask querying under narrowed cpuset. - Level 2 CPUSET querying, mutation, and clipping of explicit threads. - Rejection of unprivileged ROOT modification with EPERM. - Disjoint CPUSET updates rejected with EDEADLK preserving system state. - Separation of CPU_LEVEL_WHICH on PID from CPU_LEVEL_CPUSET. - Child thread explicit affinity inheritance and isolation upon cpuset expansion. - Enforcement against affinities outside cpuset returning EINVAL / SCE_KERNEL_ERROR_EINVAL across cpuset_setaffinity, pthread_setaffinity_np, scePthreadSetaffinity, and scePthreadCreate. - Multi-threaded parallel concurrency stress test verifying atomic synchronization without TOCTOU races or deadlocks under concurrent CPUSET and affinity mutations. - Conventions check passed (python tools/check_conventions.py --base origin/main). ### Checklist - [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: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
PrivacyOnion commented 2026-11-13 21:25:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-13T21:25:40Z.

Review: APPROVED


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

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_available_cpumask_tests built cleanly.
  • CTest (guest_available_cpumask):
    1/1 Test #4734: guest_available_cpumask ..........   Passed    0.02 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/Pthread/Posix/Thread.cpp, core/libs/prx/libkernel/Pthread/include/Pthread.hpp, core/libs/prx/libkernel/Pthread/src/Thread.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #4734: guest_available_cpumask ..........Subprocess aborted***Exception:   0.36 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • core/libs/prx/libkernel/Pthread/Posix/Thread.cpp: Verified cpuset_getaffinity_nid_postfix and cpuset_setaffinity_nid_postfix correctly implement LevelRoot (1) and LevelCpuset (2), returning GuestEperm (1) for root modification, GuestEsrch (3) for non-existent thread/process IDs prior to level checks, and GuestEdeadlk (11) for masks disjoint from sceKernelGetAvailableCpumask().
    • core/libs/prx/libkernel/Pthread/src/Thread.cpp: Verified SetLiveGuestProcessCpuset, SetLiveGuestThreadsAffinity, and SetLiveGuestThreadAffinity_nid_no_patch hold registry.lock across both verification and mutation passes, eliminating TOCTOU races and rejecting cpuset updates disjoint from any explicit thread affinity with GuestEdeadlk.
    • core/libs/prx/libkernel/Pthread/src/Thread.cpp: Verified scePthreadSetaffinity, PthreadPrivate::PthreadPrivate, and scePthreadCreate clip masks against registry.processAffinity and fail with SCE_KERNEL_ERROR_EINVAL (via std::invalid_argument in thread construction) only when the intersection is zero, exactly adhering to maintainer review specifications.
    • core/libs/prx/libkernel/Pthread/include/Pthread.hpp and Thread.cpp: Verified explicitAffinity tracking correctly preserves explicitly assigned and inherited thread affinity masks upon process cpuset expansion while allowing non-explicit threads to expand with the container mask.
    • core/libs/tests/GuestAvailableCpumask.cpp: Verified comprehensive test coverage for levels 1-3, error code return ordering for dead threads (GUEST_ESRCH), wide attribute clipping (0xFFFF and ~0ULL), disjoint mask rejections, and concurrent mutator/worker execution without deadlocks or state corruptions.
    • AGENTS.md and docs/dev/debt/libkernel.md: Verified strict compliance with repository rules (zero comments in C++ source/header modifications) and confirmed documentation of unmeasured console behaviors as requested in review discussion.
  • Note: the AI-assisted checkbox can stay.

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5898258732 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/19612#pullrequestreview-5898258732). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-13T21:25:40Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `a9b37605d5`: - **Conventions**: `tools/check_conventions.py` passed; `git diff --check` clean. - **Build**: `guest_available_cpumask_tests` built cleanly. - **CTest** (`guest_available_cpumask`): ``` 1/1 Test #4734: guest_available_cpumask .......... Passed 0.02 sec 100% tests passed, 0 tests failed out of 1 ``` - **Negative control**: with `core/libs/prx/libkernel/Pthread/Posix/Thread.cpp`, `core/libs/prx/libkernel/Pthread/include/Pthread.hpp`, `core/libs/prx/libkernel/Pthread/src/Thread.cpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/1 Test #4734: guest_available_cpumask ..........Subprocess aborted***Exception: 0.36 sec 0% tests passed, 1 tests failed out of 1 ``` Restoring the change makes it pass again. - **Code reading**: - core/libs/prx/libkernel/Pthread/Posix/Thread.cpp: Verified cpuset_getaffinity_nid_postfix and cpuset_setaffinity_nid_postfix correctly implement LevelRoot (1) and LevelCpuset (2), returning GuestEperm (1) for root modification, GuestEsrch (3) for non-existent thread/process IDs prior to level checks, and GuestEdeadlk (11) for masks disjoint from sceKernelGetAvailableCpumask(). - core/libs/prx/libkernel/Pthread/src/Thread.cpp: Verified SetLiveGuestProcessCpuset, SetLiveGuestThreadsAffinity, and SetLiveGuestThreadAffinity_nid_no_patch hold registry.lock across both verification and mutation passes, eliminating TOCTOU races and rejecting cpuset updates disjoint from any explicit thread affinity with GuestEdeadlk. - core/libs/prx/libkernel/Pthread/src/Thread.cpp: Verified scePthreadSetaffinity, PthreadPrivate::PthreadPrivate, and scePthreadCreate clip masks against registry.processAffinity and fail with SCE_KERNEL_ERROR_EINVAL (via std::invalid_argument in thread construction) only when the intersection is zero, exactly adhering to maintainer review specifications. - core/libs/prx/libkernel/Pthread/include/Pthread.hpp and Thread.cpp: Verified explicitAffinity tracking correctly preserves explicitly assigned and inherited thread affinity masks upon process cpuset expansion while allowing non-explicit threads to expand with the container mask. - core/libs/tests/GuestAvailableCpumask.cpp: Verified comprehensive test coverage for levels 1-3, error code return ordering for dead threads (GUEST_ESRCH), wide attribute clipping (0xFFFF and ~0ULL), disjoint mask rejections, and concurrent mutator/worker execution without deadlocks or state corruptions. - AGENTS.md and docs/dev/debt/libkernel.md: Verified strict compliance with repository rules (zero comments in C++ source/header modifications) and confirmed documentation of unmeasured console behaviors as requested in review discussion. - Note: the AI-assisted checkbox can stay. Looks Good To Me
MarcZX10 commented 2026-11-17 08:40:57 +00:00 (Migrated from github.com)

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

Review: COMMENTED


Reviewed — no blocking findings

Nothing blocks this; the points below are optional.

PR #19612 (feat(libkernel): implement CPU_LEVEL_ROOT and CPU_LEVEL_CPUSET cpuset affinity) at head a9b37605d595927b0f550bcd8576b39645282790, base main.

What I ran

  • Read the PR title, body, commit list, manifest and diff.patch from the review folder.
  • Read the diff hunks for all five changed files.
  • Searched the head with repo_read.py search to find the callers of the helpers whose signatures changed (SetLiveGuestThreadAffinity_nid_no_patch, SetLiveGuestThreadsAffinity, SetLiveGuestProcessCpuset, LockRegisteredGuestThread). No caller was left on the old bool or void contract.
  • Read core/libs/prx/libkernel/Pthread/src/Thread.cpp lines 589–616 at head, the constructor that clamps the thread affinity and registers the thread.
  • I did not build the code and did not run the test suite.

Results

Check Result Note
Build not run Not built here
GuestAvailableCpumask tests not run Author-reported only
Conventions check not run Author-reported only
Changed-helper callers passed No stale caller found

Findings

Blocking

None.

Non-blocking

  1. The description overstates restoration. The description says explicit thread affinities are "preserved when the process cpuset expands". The code only narrows them: core/libs/prx/libkernel/Pthread/src/Thread.cpp:686 stores thread->affinity & mask and never widens an explicit thread again. The test at core/libs/tests/GuestAvailableCpumask.cpp:342 asserts that a pinned thread stays at its narrowed mask after the cpuset is restored. The behaviour is consistent with the test. Only the wording is off. "Not widened by a later expansion" would match the code.

  2. The TOCTOU claim holds for thread creation. The constructor clamps the affinity and registers the thread under the same registry.lock (Thread.cpp:591 and Thread.cpp:615), so the description's claim that creation is atomic is correct for that path. The std::invalid_argument it throws is caught in scePthreadCreate. The adopted-thread callers use the default constructor and cannot reach that throw.

Not verified

  • The build and the GuestAvailableCpumask suite, including the concurrency stress test. I only read the test code.
  • The pthread_setaffinity_np path in core/libs/prx/libkernel/Pthread/Posix/Thread.cpp. It is not in the diff, and I did not trace how it reaches the cpuset setter.
  • The full text of the five changed files. I read their diff hunks and one constructor, not the whole files. The copies in files/ were not read.
  • Console behaviour. The debt-file entries say it was not measured, and I did not check that wording against any measurement.
  • Thread-safety of the stress test's settled() check. I reasoned about it from the code and did not run it.

Files read: all five in files.json reviewed (diff hunks), plus head context for Thread.cpp. Files excluded by rule: none.

To get this to a good state

Nothing is required. Optional: reword the description as in finding 1.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5935313846 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/19612#pullrequestreview-5935313846). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-17T08:40:57Z. **Review:** COMMENTED --- # Reviewed — no blocking findings Nothing blocks this; the points below are optional. PR #19612 (`feat(libkernel): implement CPU_LEVEL_ROOT and CPU_LEVEL_CPUSET cpuset affinity`) at head `a9b37605d595927b0f550bcd8576b39645282790`, base `main`. ## What I ran - Read the PR title, body, commit list, manifest and `diff.patch` from the review folder. - Read the diff hunks for all five changed files. - Searched the head with `repo_read.py search` to find the callers of the helpers whose signatures changed (`SetLiveGuestThreadAffinity_nid_no_patch`, `SetLiveGuestThreadsAffinity`, `SetLiveGuestProcessCpuset`, `LockRegisteredGuestThread`). No caller was left on the old `bool` or `void` contract. - Read `core/libs/prx/libkernel/Pthread/src/Thread.cpp` lines 589–616 at head, the constructor that clamps the thread affinity and registers the thread. - I did not build the code and did not run the test suite. ## Results | Check | Result | Note | |---|---|---| | Build | not run | Not built here | | `GuestAvailableCpumask` tests | not run | Author-reported only | | Conventions check | not run | Author-reported only | | Changed-helper callers | passed | No stale caller found | ## Findings ### Blocking None. ### Non-blocking 1. **The description overstates restoration.** The description says explicit thread affinities are "preserved when the process cpuset expands". The code only narrows them: `core/libs/prx/libkernel/Pthread/src/Thread.cpp:686` stores `thread->affinity & mask` and never widens an explicit thread again. The test at `core/libs/tests/GuestAvailableCpumask.cpp:342` asserts that a pinned thread stays at its narrowed mask after the cpuset is restored. The behaviour is consistent with the test. Only the wording is off. "Not widened by a later expansion" would match the code. 2. **The TOCTOU claim holds for thread creation.** The constructor clamps the affinity and registers the thread under the same `registry.lock` (`Thread.cpp:591` and `Thread.cpp:615`), so the description's claim that creation is atomic is correct for that path. The `std::invalid_argument` it throws is caught in `scePthreadCreate`. The adopted-thread callers use the default constructor and cannot reach that throw. ## Not verified - The build and the `GuestAvailableCpumask` suite, including the concurrency stress test. I only read the test code. - The `pthread_setaffinity_np` path in `core/libs/prx/libkernel/Pthread/Posix/Thread.cpp`. It is not in the diff, and I did not trace how it reaches the cpuset setter. - The full text of the five changed files. I read their diff hunks and one constructor, not the whole files. The copies in `files/` were not read. - Console behaviour. The debt-file entries say it was not measured, and I did not check that wording against any measurement. - Thread-safety of the stress test's `settled()` check. I reasoned about it from the code and did not run it. Files read: all five in `files.json` `reviewed` (diff hunks), plus head context for `Thread.cpp`. Files excluded by rule: none. ## To get this to a good state Nothing is required. Optional: reword the description as in finding 1.
MarcZX10 commented 2026-11-21 03:59:16 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-21T03:59:16Z.

Review: APPROVED


Reviewed — looks good

The reviewed change has no verified blocking defects; the source and added test cases support the stated affinity behavior, though the reported test and conventions runs were not independently run here.

What I ran

Reviewed head 2e23eb772398889bd919905c444d85288548c820. Read the prepared description, commit summary, manifest, diff, and all five changed files; targeted source context was read through the pinned reader. No tests or build commands were run.

Results

Check Result Note
Diff and changed source review passed Five changed files read
GuestAvailableCpumask test not run Described by the author; not run here
Conventions check not run Described by the author; not run here

Findings

Blocking

None.

Non-blocking

None.

Not verified

The GuestAvailableCpumask suite and conventions check were not run during this review. Console behavior and the claims based on physical console measurements were not independently confirmed. The description’s test claims are author-reported. files.json was not present in the review bundle; the reader’s file listing shows all five changed files as included, and each was read. No files were excluded from the manifest.

To get this to a good state

Nothing is required.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6002687035 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/19612#pullrequestreview-6002687035). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-21T03:59:16Z. **Review:** APPROVED --- # Reviewed — looks good The reviewed change has no verified blocking defects; the source and added test cases support the stated affinity behavior, though the reported test and conventions runs were not independently run here. ## What I ran Reviewed head `2e23eb772398889bd919905c444d85288548c820`. Read the prepared description, commit summary, manifest, diff, and all five changed files; targeted source context was read through the pinned reader. No tests or build commands were run. ## Results | Check | Result | Note | |---|---|---| | Diff and changed source review | passed | Five changed files read | | GuestAvailableCpumask test | not run | Described by the author; not run here | | Conventions check | not run | Described by the author; not run here | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified The GuestAvailableCpumask suite and conventions check were not run during this review. Console behavior and the claims based on physical console measurements were not independently confirmed. The description’s test claims are author-reported. `files.json` was not present in the review bundle; the reader’s file listing shows all five changed files as included, and each was read. No files were excluded from the manifest. ## To get this to a good state Nothing is required.
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!19612
No description provided.