fix(libkernel): hand signalled semaphore tokens to queued waiters #9491
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9491"
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 EagleBearerYS on 2026-10-21T23:19:50Z.
Opened again from #5412: title-less conformance fixes of this kind are merged now, for example #7365 and #8411.
What
sceKernelSignalSemaonly adds to the count and wakes the waiters, each of which then has to take the count itself. AsceKernelPollSemaorsceKernelWaitSemathat runs first takes the tokens instead, so a thread that had queued for them can time out or keep waiting. Event flags onmainalready hand their bits to queued waiters when the pattern is set, since #6737.sceKernelSignalSemanow hands its tokens to the queued waiters in the order they queued, passing over one that needs more than is left, and only what remains stays on the count. AsceKernelWaitSemaorsceKernelPollSemathat finds enough tokens still takes them without queueing.sceKernelCancelSemareports and cancels the queued waiters as before. shadPS4's semaphore works the same way. TheAPS5_TRACE_SYNClinesmainadded to these calls are kept; a wait that finds enough tokens prints its begin and end lines too.A semaphore created with
SCE_KERNEL_SEMA_ATTR_TH_PRIO(0x02) queues a waiter by the priority its thread has when it starts to wait: before the first queued waiter with a numerically higher, that is lower, priority, so the signal serves higher-priority threads first and equal ones in arrival order. Attributes 1 and 0 keep arrival order.The second commit records that order in
docs/dev/debt/libkernel.md.0a353f80ef, after MarcZX10's review, adds the priority order and its debt sentence: a priority change while a thread waits does not move it, and the console's order and its rule for a waiter that needs more than is left are unverified.2132238f45, after oneandonlydean's review, makessceKernelWaitSemareturnEACCESfor a semaphore thatsceKernelDeleteSemais deleting before it looks at the free tokens, asmaindoes. Before it, a wait that found enough tokens took them from a semaphore being deleted.No title is claimed.
Overlap: #9566 (DavidSamir) changes the
tcsendbreak … tcsetpgrpentry ofdocs/dev/debt/libkernel.md, right after the semaphore entry this PR adds, and the two conflict in that file only. Neither needs to wait for the other: whichever merges second keeps both entries, and this PR takes the rebase in either order.#10558 (ZSWolt) adds a handle lookup at the top of
sceKernelSignalSema,sceKernelWaitSemaandsceKernelCancelSema, where this PR changes the bodies, and the two conflict inSemaphore.cpp. Agreed order: #10558 first (comment). Once it merges, this PR mergesmainand keeps the token handoff after that lookup.Tested
On GitHub's runners from my fork, merged with
mainata6dcea9279(run), on both Linux and Windows:guest_semaphore_handoff, 20 rounds: a thread waits on an empty semaphore, the main thread signals one token and polls right away. The poll must fail withEBUSY, and the waiting thread must get the token. Withmain'sSemaphore.cppthe test aborts; with the change it andguest_semaphorepass 10 runs in a row.core/libs/prx/libcandcore/libs/prx/libkernelpasses: 115 and 198 on Linux, 142 and 208 on Windows. In the first Windows attemptguest_raise_in_system_calltimed out after 30 s; the rerun of that job passed it with the rest.0a353f80ef(run):guest_semaphore_handoffgains two-waiter cases. A waiter that needs 2, queued before one that needs 1, must be passed over by a signal of 1 and served by the next signal of 2. Two waiters must be served in arrival order with attribute 1, whatever their priorities, and with attribute 0x02 by priority (767 and 256 either way round) or in arrival order when equal. With the previous head, which serves both attributes in arrival order, the test fails 3 of 3 on both runners; with the commitguest_semaphore_handoff,guest_semaphoreandguest_semaphore_tracepass 10 of 10, and the libc and libkernel suites pass.semaphore_trace_testscompilesSemaphore.cppon its own, so it gains stubs for the two pthread calls the priority lookup uses.mainatda54c652e3(d1604d79c9, no conflicts, the PR's own diff unchanged; run):guest_semaphore_handoffpasses 10 runs in a row on both runners. The libc and libkernel suites pass on Linux (116, 198); on Windows libc passes (143) and libkernel'sguest_raise_in_system_calltimed out once. Run alone withguest_semaphore_handoff(run), it passes 20 runs in a row on Windows, and that run's libkernel suite passes (208), as in the first Windows attempt above.mainatfa515def85(406e9bc542; run): the only conflict was indocs/dev/debt/libkernel.md, wheremainadded its kevent measurements entry at the place this PR adds its semaphore entry, and both are kept. The PR's own added and removed lines are unchanged.guest_semaphore_handoff,guest_semaphoreandguest_semaphore_tracepass ×10: 3 run, 3 pass, 0 skip, 0 fail on Linux and on Windows. The libc and libkernel suites pass on both (121 and 205 tests on Linux, 148 and 217 on Windows), run withAPS5_SKIP_TIMING_TESTS=1, which relaxesprecise_wait's median bounds on GitHub's hosted runners.tools/check_conventions.py --base origin/mainpasses.87b2a04b4fanda302f0c516, merges ofmain85f8e11372and518d36eaec(run, run). Both conflicted only indocs/dev/debt/libkernel.md, where this PR adds itssceKernelWaitSemaandsceKernelSignalSemaentry after thesem_timedwaitone: orezraey's #10137 rewrote that entry with a PS5's results, and xXPBSXx's #10105 then added a title's call site to it. Each merge keepsmain's entry and this PR's, and this PR's other changed lines are the same. The first run took the semaphore tests with the tests for every file the first merge changes, 10 runs each. Linux: 828 run, 813 pass, 15 skip (seven AGC tests on lavapipe and eight video-out tests with no display), 0 fail. Windows: 850 run, 755 pass, 95 skip (85 AGC tests, nine video-out tests andguest_job_manager_profiler_gpu, with no Vulkan device or display), 0 fail. The second took the semaphore tests with the tests for the files the second merge changes, 10 runs each. Linux: 25 run, 25 pass, 0 skip, 0 fail. Windows: 24 run, 24 pass, 0 skip, 0 fail. Suites: libc and libkernel pass on Linux (145 and 213) and on Windows (174 and 234). The suites ran withAPS5_SKIP_TIMING_TESTS=1, which relaxesprecise_wait's median bounds on GitHub's hosted runners.2132238f45, after oneandonlydean's review, onaf93ca4e6c, a merge ofmainae0e0a284b(merge run, fix run).Semaphore.cpp(an include next to onemainadded) and indocs/dev/debt/libkernel.md, wheremainadded its kevent entry next to this PR's semaphore entry; both keepmain's lines and this PR's. orezraey's argument checks frommain(b7e5eb7f31) merged without a conflict. This PR's own added and removed lines are the same. Without the new case,guest_semaphore,guest_semaphore_handoffandguest_semaphore_tracepass 10 runs in a row on the merge. Linux: 3 run, 3 pass, 0 skip, 0 fail. Windows: 3 run, 3 pass, 0 skip, 0 fail.2132238f45adds aguest_semaphore_handoffcase: it setsdeletedon a semaphore holding 2 tokens, assceKernelDeleteSemadoes while it waits for its waiters, and checks that a wait for 1 returnsEACCESand leaves both tokens. With the merge's code the test fails 3 of 3 on both runners. With the commit the three tests pass 10 runs in a row. Linux: 3 run, 3 pass, 0 skip, 0 fail. Windows: 3 run, 3 pass, 0 skip, 0 fail.exec_arguments,guest_timed_join_import_libkernel_sysandguest_timed_join_import_libkernel_webfail at their setup in the verify's Windows build (FileNotFoundErrorstarting the title, or copying the libraries they load) with and without the commit, and pass inmain's own Windows job at1829def9bf(job). The suites ran withAPS5_SKIP_TIMING_TESTS=1, which relaxesprecise_wait's median bounds on GitHub's hosted runners.8b1608d2deandc87a1fb54e, after oneandonlydean's second review (run).8b1608d2deremoves the local pthread declarations fromSemaphore.cppandGuestSemaphoreHandoff.cpp, which now includeprx/libkernel/include/Api.hpp; the test keeps the internal semaphore header for the fixture state.c87a1fb54emakes the first handoff loop wait withWaitForQueue(sem, 1)before signalling, in place of thestartedflag and a 50 ms sleep.guest_semaphore_handoff,guest_semaphore,guest_semaphore_trace,guest_pthread_sem,guest_sem_canceled_wakeandguest_sem_canceled_wake_coarsepass 10 runs in a row. Linux: 6 run, 6 pass, 0 skip, 0 fail. Windows: 6 run, 6 pass, 0 skip, 0 fail. The libc and libkernel suites run 161 and 265 tests on Linux and 189 and 287 on Windows, with 0 failed.e6d4929f65, a merge ofmain1db077e876(run). The one conflict was indocs/dev/debt/libkernel.md, wheremainadds kallmek3nny'ssem_setnameentry (#11267) where this PR adds its semaphore entry; the merge keeps both. This PR's own added and removed lines are the same. The same six tests pass 10 runs in a row. Linux: 6 run, 6 pass, 0 skip, 0 fail. Windows: 6 run, 6 pass, 0 skip, 0 fail. The libc and libkernel suites run 191 and 293 tests on Linux and 220 and 316 on Windows, with 0 failed. The suites ran withAPS5_SKIP_TIMING_TESTS=1, which relaxesprecise_wait's median bounds on GitHub's hosted runners.7a6f4ee910, a merge ofmain1b91748340, which brings akkadbakkad89's #13600 (run).sceKernelCreateSemainSemaphore.cpp. #13600 accepts attribute bit 0x100, in place ofmain'sNotImplemented_nid_no_patchfor it, and reads the FIFO mode as(attr & 3u) == 1u.main's lines are kept, and this PR's priority-queue flag reads the low two bits the same way,(attr & 3u) == 2uin place ofattr == 2, so 0x102 still queues by priority. The merge commit's message names that line. This PR's other added and removed lines are the same.guest_semaphore(#13600's case) creates semaphores with 0x100, 0x101 and 0x102 and checks only that they're accepted.guest_semaphore_handoffchecks the queue order with attributes 1 and 2 only. So no test here runs the masked read's priority order with bit 0x100 set.guest_semaphore_handoff,guest_semaphore,guest_semaphore_trace,guest_pthread_sem,guest_sem_canceled_wakeandguest_sem_canceled_wake_coarse.APS5_SKIP_TIMING_TESTS=1, which relaxesprecise_wait's median bounds on GitHub's hosted runners.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)sceKernelSignalSema,sceKernelWaitSemaandsceKernelCancelSema, where this PR changes the bodies; this PR goes after it). No order with #9566, see Overlap; merge order with orezraey's #11195 (the semaphore code and its debt entry): whichever merges second keeps bothImported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-21T23:24:11Z.
Review: CHANGES_REQUESTED
The queue handoff is a useful fix for the signal/poll race, and the reported Linux/Windows library suites pass. I cannot approve the current behavior for the supported priority attribute:
KernelSemaPrivate::isFifois set at creation (attr == 1), but the new queue is always traversed in arrival order. The PR’s debt entry confirmsSCE_KERNEL_SEMA_ATTR_TH_PRIOis not modeled; the unknown ordering therefore silently gets FIFO behavior instead of throwing or implementing the priority contract. Please handle this attribute explicitly (implement its ordering, or fail the unsupported case and record the limitation) and add a focused test for it. Also, the regression currently has one waiter, so it does not exercise the new loop’s multi-waiter behavior, especially passing a waiter whose need exceeds the remaining signal count. Please add a two-waiter case to verify the ordering/skip rule. The current conventions, intake, eligibility, labels and report checks pass; hosted product build jobs are skipped.Imported from boykopovar/AnyPS5. Originally posted by EagleBearerYS on 2026-10-22T00:02:01Z.
Thanks, @MarcZX10.
0a353f80efhandlesSCE_KERNEL_SEMA_ATTR_TH_PRIO(0x02) explicitly: a waiter on such a semaphore is queued by the priority its thread has when it starts to wait, before the first queued waiter with a numerically higher (that is, lower) priority, so the signal serves higher-priority threads first and equal ones in arrival order. Attributes 1 and 0 keep arrival order. The debt entry now says so, and that a priority change while waiting doesn't move a waiter.guest_semaphore_handoffgains the two-waiter cases: a waiter needing 2 queued before one needing 1, where a signal of 1 serves the second and leaves the first queued until 2 more arrive; and the order of two waiters for both attributes, with priorities 767 and 256 either way round and with equal priorities. On GitHub's runners (run) the test fails 3 of 3 with the previous head, and with the commitguest_semaphore_handoff,guest_semaphoreandguest_semaphore_tracepass 10 of 10 on Linux and Windows, with the libc and libkernel suites.semaphore_trace_testsbuildsSemaphore.cppon its own, so it gains stubs for the two pthread calls the lookup uses.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T02:12:33Z.
Review: APPROVED
Re-reviewed the updated head. The FIFO path preserves arrival order, and attribute 0x02 inserts waiters by the priority captured when they enter the queue, with equal priorities retaining arrival order. The regression now covers two waiters, passing over a larger unmet need, both priority orderings and equal-priority FIFO order. The author reports the focused semaphore tests plus libc/libkernel suites passing on Linux and Windows after this update; conventions, intake, eligibility, labels and report checks pass, while hosted product and relinker jobs are skipped. I did not run tests locally. The debt entry clearly states that console ordering and priority changes while waiting remain unverified.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T04:27:31Z.
Review: CHANGES_REQUESTED
The semaphore handoff now covers the original token-stealing race, multi-waiter skip behavior and priority ordering for
SCE_KERNEL_SEMA_ATTR_TH_PRIO, with reported focused and full libc/libkernel runs on Linux and Windows. I independently checked the new #9566 shared debt warning: #9566 edits the terminal process-group clause around line 128, while this PR edits the semaphore clause later in the file; the changes are distinct but both debt edits must survive integration. However, the tested branch is based ona6dcea9279and current upstream main isab347d144d. Please rebase onto current main, rerun the focused semaphore/handoff/trace tests and conventions, and refresh the overlap scan, preserving the #9566 debt change. Hosted product jobs are skipped; I did not run local tests.Imported from boykopovar/AnyPS5. Originally posted by EagleBearerYS on 2026-10-22T06:07:34Z.
Thanks, @MarcZX10. The branch now has
mainatda54c652e3merged in (d1604d79c9), with the PR's own diff unchanged. On GitHub's runners (run)guest_semaphore_handoffpasses 10 runs in a row on both, and conventions pass. Windows' libkernel suite timedguest_raise_in_system_callout once there; run alone it passes 20 times in a row, with that run's whole suite passing (run). #9566's debt entry is kept either way: the two conflict only in that file, and Overlap and Depends on now say neither needs to wait. Tested now says so.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T08:31:20Z.
Review: CHANGES_REQUESTED
Re-reviewed exact head
2132238f4539d6a1b98bade9c0d7a7ddfbdb05efagainst currentupstream/main4c7d275bef89d309313d16bc2bc05d37a1b50be2. Two review items remain in this head:Semaphore.cppstill declaresscePthreadSelfandscePthreadGetpriolocally. Please includeprx/libkernel/include/Api.hppand use its matching declarations, as required by the public-header rule. Keep the private semaphore header for fixture state.waiter.startedand then sleeps 50 ms.startedis set beforeWaitSemaqueues, so a delayed worker can signal before it is queued and make the test nondeterministic. Use the existingWaitForQueue(sem, 1)before signaling.The current-main merge preview is clean;
git diff --checkand conventions pass. I did not rerun the semaphore tests locally.Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T11:24:29Z.
Review: CHANGES_REQUESTED
Re-reviewed exact head
e6d4929f658d8a81a3d823f6805128548980549e. The two findings from my last code review are addressed: the local pthread declarations are gone in favor ofApi.hpp, and the first handoff waits forWaitForQueuerather than a pre-queue flag/sleep. The reported Linux/Windows focused semaphore, trace and libc/libkernel runs on this integrated head are useful.One integration point remains before this can be approved: the checklist correctly says this PR follows #10558, but #10558 is still open and this head does not contain its handle changes.
GuestSemaphoreHandoff.cppstill reaches intosem->mutex,sem->queue,sem->deletedandsem->tokenCount. Please apply the handoff after #10558 lands, adapt those fixture accesses to the resulting handle API, rebase onto currentmain, then rerun the focused semaphore tests and public-header/conventions checks on that final head. Current GitHub mergeability alone does not exercise the declared stacked integration.