feat(libkernel): implement the unnamed ksem semaphores #9284
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9284"
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 DavidSamir on 2026-10-21T17:26:32Z.
What
Implements the unnamed
ksem_*exports in libkernel, in a newlibkernel/Semaphore/src/Ksem.cpp, following FreeBSD 11sys/kern/uipc_sem.c. They were discovery stubs inlibkernel_systhat threwNotImplemented.Moved to libkernel so libkernel imports reach it on Windows. The PS5 3.20 export lists have
ksem_*in libkernel as well as in libkernel_sys and libkernel_web. On Windows a libkernel import never searches libkernel_sys:WindowsEntryStubBuilder.cpp:175only falls back the other way, from libkernel_sys and libkernel_web to libkernel. With the implementation in libkernel and the libkernel_sys stubs removed, both imports reach it, and the duplicate-export rule holds. On Linux and macOS, ELF lookup is global, so either import already worked. (Review by @pipe1os.)ksem_init(semid_t* idp, u_int value)EINVALforvalue > SEM_VALUE_MAX(0x7fffffff).ENOSPCwhen no descriptor is left, whatever the cause (uipc_sem.c:475-479).EFAULTfor a NULLidp.ENOSPConce 30 semaphores (SEM_MAX,p1003_1b.sem_nsems_max) exist (:300-304,:496-498); that check comes after the id is written, as in FreeBSD.ksem_post(semid_t)EOVERFLOWatSEM_VALUE_MAXksem_wait(semid_t)ksem_trywait(semid_t)EAGAINat 0ksem_timedwait(semid_t, const timespec*)CLOCK_REALTIMEdeadline, givingETIMEDOUT. Atv_nsecoutside 0..999999999 givesEINVALbefore any wait, assys_ksem_timedwaitdoes.ksem_getvalue(semid_t, int*)EFAULTfor a NULL out pointerksem_destroy(semid_t)EBUSYwhile a thread waitsAn id that isn't a live ksem gives
EINVAL, asksem_getmapsfget's failure.semid_tisintptr_t(sys/_semaphore.h).The id is a descriptor, as in FreeBSD:
kqueuereserves one, and the semaphore lives in a table keyed by that descriptor.EqueueDescriptorClosed) gains a small observer list. It is already called fromclose, fromdup2replacing a descriptor, and from sockets.Ksem.cppregisters throughRegisterDescriptorCloseObserver_nid_no_patchto drop the entry when its descriptor is closed or replaced.ksem_destroyreleases the id through the guestclose.Duplicating an id throws:
dupof a ksem id, ordup2from one, throws, as the same spot does for a kqueue (Stdio.cpp). This avoids handing back a descriptor that isn't a semaphore, where FreeBSD would share it.dup2onto an id is exact: it closes the semaphore.The named forms (
ksem_open,ksem_close,ksem_unlink) follow in #9293, which depends on this one. A debt line inlibkernel.mdrecords thedupthrow and that a guest signal doesn't interrupt a wait withEINTR.Tested
Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release. These are CPU-side exports, so no GPU is involved.
guest_kernel_sys_ksem(core/libs/tests/GuestKernelSysKsem.cpp) covers:EAGAIN,EOVERFLOWat the maximum, andEFAULTfor NULL pointers;timedwaitwith a badtv_nsec(EINVAL), a 150 ms real-time deadline (ETIMEDOUT), and a later post that satisfies a wait;ksem_post, withksem_destroygivingEBUSYwhile it waits;EINVAL;closeof an id, a regular file that reuses the same number getsEINVALfromksem_postandksem_getvalue; afterdup2of a file over an id,ksem_postandksem_trywaitgiveEINVAL;dupof an id anddup2from an id both throw, whiledup2(id, id)keeps the semaphore;ksem_initgivesENOSPCwith the id written but dead; destroying one makes room again.The stale-descriptor file is opened by a guest-relative name, not a host temp path, so the test also runs on Linux (found by @xXPBSXx on #9097).
Results:
NotifyDescriptorCloseObserverscall removed fromEqueueDescriptorClosed, the test fails, because a destroyed id still answers;SEM_MAXcheck removed, it fails at line 166;dupcheck removed, it fails at line 153.guest_kernel_sys, semaphore, kqueue, equeue, dup, descriptor, stdio andguest_filepass, 4 runs out of 5. The other run had one failure that didn't repeat in three more runs of the set or ten runs of the ksem test.tools/check_conventions.pypasses, including the duplicate-export rule.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)Imported from boykopovar/AnyPS5. Originally posted by pipe1os on 2026-10-21T17:37:46Z.
I had
ksem_*written on a local branch when this was opened, so I compared your diff with FreeBSD 11.0uipc_sem.c. All of this is from reading the code; I haven't built this branch.ksem_*inlibkernel.cas well as inlibkernel_sys.candlibkernel_web.c. A game imports them from thelibkernelmodule, and on Windows the import search only looks at the declared module pluslibc.prx(WindowsEntryStubBuilder.cpp:169and:176), so a title never finds an implementation inlibkernel_sys.prx. Putting them in libkernel, and dropping the libkernel_sys placeholders for the duplicate-export rule, makes them reachable.ksem_initwith no descriptor left: FreeBSD returnsENOSPCfor an unnamed semaphore whateverfallocfailed with (uipc_sem.c:475-479). Here it'sEMFILE/ENFILE(Ksem.cpp:110).ksem_allocfails oncensemsreachesp1003_1b.sem_nsems_max(uipc_sem.c:300-304), which defaults toSEM_MAX= 30 (:80-82, set at:1022), andksem_createturns that intoENOSPCfor an unnamed one (:496-498). Here a 31stksem_initsucceeds.dupof an id: the debt entry says it gives a descriptor that isn't a semaphore. kqueue throws in the same spot (Stdio.cpp:763and:793), which keeps exact-or-throw instead of a silent difference.Everything else I checked matches: the
tv_nseccheck before the id lookup,EBUSYwith a waiter,EOVERFLOW, andEINVALfor a dead or foreign id.I also have
ksem_open,ksem_closeandksem_unlinkwith tests (ENAMETOOLONGat 1024 bytes, the id written before the name is checked,O_CREAT | O_EXCL, unlink while open, a linked name counting toward the limit). If it helps with your named follow-up, I can share the branch and you take what's useful. No point in me opening a second PR.Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-21T20:35:38Z.
@pipe1os thank you, all four points check out against the source, and point 1 matters most.
ksem_*fromlibkernelas well, and on WindowsWindowsEntryStubBuilder.cpp:175sendslibkernel_sys/libkernel_webimports on tolibkernelbut not the reverse. I'll move the implementation into libkernel and drop the libkernel_sys placeholders, so both imports reach it (and the duplicate-export rule holds). The same applies to our other libkernel_sys PRs whose exports the 3.20libkernellist also has, and they'll get the same move.ENOSPCfor an unnamedksem_initwhateverfallocfailed with: will followuipc_sem.c:475-479.p1003_1b.sem_nsems_maxlimit (SEM_MAX30) withENOSPC: will add it, with a test for the 31st.dup/dup2of an id: will throw as kqueue does (Stdio.cpp:763/:793) instead of the silent difference, and drop that debt wording.On the named part: #9293 already has
ksem_open/ksem_close/ksem_unlink. I'd gladly compare your tests with it (the id written before the name check, and linked names counting toward the limit), so if you can share the branch, I'll credit what I take.Imported from boykopovar/AnyPS5. Originally posted by pipe1os on 2026-10-21T20:47:38Z.
Here it is: https://github.com/pipe1os/AnyPS5/tree/feat/libkernel-ksem. One commit, all ten in libkernel; the tests are in
core/libs/tests/GuestKsem.cpp(casesanonymous,wait,named,limit). Take whatever's useful.Comparing #9293's
ksem_openwithuipc_sem.c:sys_ksem_openchecksoflagfirst (:633-634), thenksem_createchecks the value (:470), allocates the descriptor and copies it out toidp(:475-487), and only then reads the name (:508,EFAULT/ENAMETOOLONG) and checks the leading/(:512). Soidpalready holds the descriptor number when the name,ENOENTorEEXISTfails. #9293 checks the name beforeoflagand never writesidpon failure.ENFILE(:527-529), notENOSPC. A name that's still linked keeps its semaphore alive, so it counts untilksem_unlink.ksem_access(:550,:412), which needs owner read and write in the mode and otherwise falls back topriv_check_cred. #9293 ignoresmode; I made that case throw, since the result depends on privilege.And you're right about
:175: main forwards libkernel_sys/libkernel_web imports to libkernel now. I was reading an older copy.Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-21T21:15:21Z.
@pipe1os all four points are in
8db8924c7:libkernel/Semaphore/src/Ksem.cppand the libkernel_sys stubs are gone, so libkernel and libkernel_sys imports both reach it on Windows.ksem_initgivesENOSPCwhen no descriptor is left.SEM_MAX30: the 31stksem_initgivesENOSPC. Like FreeBSD, it does that after the id is written. Tested.dupof an id, anddup2from one, throw as kqueue does. The debt wording is gone.dup2onto an id still closes the semaphore exactly.Negative controls for 3 and 4 are in Tested. I've retitled the PR
feat(libkernel), and the move carries into #9293 next. I'd still like your named-ksem tests if you can share the branch.AI-assisted: yes
Imported from boykopovar/AnyPS5. Originally posted by pipe1os on 2026-10-21T21:24:59Z.
It's here: https://github.com/pipe1os/AnyPS5/tree/feat/libkernel-ksem (I linked it in my last comment too, easy to miss). The named cases are
Named()andLimit()incore/libs/tests/GuestKsem.cpp.I also ran
8db8924c7on Windows: Windows 11 Pro 10.0.26300, WinLibs GCC 15.2.0 (ucrt-posix-seh r7), Ninja, Release,BUILD_TESTING=ON. Merged ontomain0c6a5bd593without conflicts, no warnings.guest_kernel_sys_ksempasses, five runs in a row.guest_kernel_sys,guest_dup,guest_kqueue,guest_equeue_event,guest_directory_close,guest_positioned_close,guest_kernel_fcntlandguest_socket_descriptorsstill pass with the close observer and the dup guards.core/libs/prx/libkernel,core/libs/prx/libkernel_sysand the debt file back tomain, it aborts onksem_init_nid_postfix not implemented.uipc_sem.cnow, including the 31stksem_initwriting the id beforeENOSPC.One thing for #9293: the limit here checks
g_ksems.size(), which is one entry per descriptor. For unnamed semaphores that's the same as the semaphore count, butnsemscounts semaphores (ksem_alloc/ksem_drop). So two opens of the same name count once, and a name that's closed but still linked keeps counting.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-21T23:33:57Z.
Review: COMMENTED
Linux run of
b0d85e3c2, since the description only lists Windows.Machine: Linux x86_64, i7-8700 (6 cores / 12 threads), Ubuntu 26.04, GCC 15.2, Release,
BUILD_TESTING=ON, full build. Headb0d85e3c2on its own base (main4ec064d29).guest_kernel_sys_ksempasses.libkernel_sys/Export.Discovery.cppto that base and keeping the test aborts it withksem_init_nid_postfix not implemented, so the test covers the change.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-22T02:06:18Z.
Linux: Ubuntu 24.04.1 LTS (WSL2), GCC 13.3.0, Release; head
b0d85e3c2merged ontomain8c26eac3c.guest_kernel_sys_ksempasses 3/3.SEM_MAXcheck removed (g_ksems.size() < SemMaxreplaced bytrue), it fails at line 166, as listed.dupcheck removed (both throws inStdio.cpp), it fails at line 153, as listed.Run from the PC (Windows host, Linux in WSL2), not from the PR author's machine.
Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-25T10:36:52Z.
Review: CHANGES_REQUESTED
Two things stop this from merging on current
main:core/libs/prx/libkernel_sys/Export.Discovery.cppconflicts: main moved the neighbouringksem_*stubs, so the removal hunk no longer applies. Please rebase ontomain.public_headers(core/libs/tests/test_public_headers.py) checks it. The sevenksem_*definitions inlibkernel/Semaphore/src/Ksem.cpp(lines 111-173) have no declaration inlibkernel/include/Api.hpp, so the audit reportsexpected exactly one header declaration; found 0. Please add them there (next tosem_*,Api.hpp:467), reachable from the libkernel umbrella.extern "C"declarations of exports that Api.hpp already declares:close_nid_postfixinKsem.cpp:20(Api.hpp:302) and the ksem/close/dup/dup2/open/__errordeclarations inGuestKernelSysKsem.cpp:16-27; includeprx/libkernel/include/Api.hppinstead. A second declaration in a.cppcounts as a second declaration of the export.RegisterDescriptorCloseObserver_nid_no_patch(Ksem.cpp:21,Equeue.cpp:770) is_nid_no_patchand exempt from the audit, but declare it in a header too rather than twice by hand.After the rebase, please rerun
public_headers,guest_kernel_sys_ksemandguest_kernel_sys. The rest checked out against FreeBSDuipc_sem.c(init/post/wait/timedwait/getvalue/destroy errors,SEM_MAX, id-as-descriptor with the close observer), and the tests fail without the change.