feat(libkernel_sys): notify aio completions by signal or kevent and queue aio on sockets #21463
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/21463"
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 frankea on 2026-11-16T06:50:58Z.
What
aio_read,aio_writeandaio_fsyncno longer throw forSIGEV_SIGNAL,SIGEV_THREAD_IDorSIGEV_KEVENTcompletion, or for a request on a socket. These were the twoNotImplemented_nid_no_patchcalls left in the sharedQueue()helper ofcore/libs/prx/libkernel_sys/Aio.cpp. The behaviour follows FreeBSD 11.4:sys/kern/vfs_aio.candsys/kern/sys_socket.c, with the kqueue parts checked againstsys/kern/kern_event.c.#19463 is merged into
main(2026-11-21), and this branch has mergedmainatef7dc4452df. It reuses the queued-signal entries that #19463 added toSignals.cpp(code, value,si_valueat offset 32) instead of adding a second mechanism. The commits of this PR are613be0a396a,660296545c1,4c721b9c105,4c9710db5a6,ada4cc96312,d300f12e04e,82fcbf5e84dand908178b6689, plus merges ofmain.SIGEV_KEVENT(vfs_aio.caio_aqueueL1589-L1605,filt_aioattach/filt_aioL2492-L2539,aio_free_entryL532,aqueue_failL1645-L1650):sigev_notify_kevent_flags(the low 16 bits of thesigeventunion) other thanEV_CLEAR,EV_DISPATCHandEV_ONESHOTfail withEINVAL, afterkernelinfois stored, asaio_aqueuechecks them there.sigev_notify_kqueue(sigev_signo) that is not a kqueue fails withEBADF, askqueue_acquire(L1496) answers, and the error is stored in the aiocb.EVFILT_AIO,udata=sigev_value, and the requested flags withoutEV_FLAG1, whichfilt_aioattachclears.aio_cancel) it fires withEV_EOFanddata= the request's error (0,ECANCELED, an errno), asfilt_aiosets them. The knote keeps that error, so a re-activated knote (anEV_CLEARone after a later change) reports it again, asfilt_aiosetskn_dataon every call. It stays level-triggered untilaio_returnoraio_waitcompletefrees the request, which deletes the knote asaio_free_entrydoes throughknlist_delete.EOPNOTSUPP) deletes its knote, asaqueue_faildoes.EVFILT_AIOknote in that kqueue (the earlier request finished but was not yet returned) replaces that knote with a fresh one bound to the new request (908178b6689). The earlier request's completion andaio_returnthen no longer touch it, and the new request's completion andaio_returnfire and free it. Before, the old knote kept the old request's token, so it re-reported the old completion at once, the new completion did not fire it, andaio_returnof the old request deleted it.Kqueue.cpp: a userEV_ADDof a newEVFILT_AIOknote still fails withEPERM(userEV_FLAG1is stripped bykqueue_keventL1087, thenfilt_aioattachrefuses). A change to an existing aio knote now takes the generic path, askqueue_register(L1234-L1493) does:EV_DELETE,EV_ENABLE/EV_DISABLE,EV_FORCEONESHOTand a newudata. A finished knote is re-activated by such a change, askqueue_registercallsf_eventagain atdone_ev_add.KqueueAddAio_nid_no_patch,KqueueAioDone_nid_no_patchandKqueueAioFree_nid_no_patchinKqueue.cpp, declared inlibkernel/include/Api.hpp.SIGEV_SIGNALandSIGEV_THREAD_ID(vfs_aio.caio_sendsigL469-L485,aio_bio_done_notifyL874-L940):sigev_signowithsi_codeSI_ASYNCIO(0x10004),si_value=sigev_valueandsi_pid0, asksiginfo_set_sigevandaio_sendsigfill it.SIGEV_THREAD_IDtargetssigev_notify_thread_id; an unknown thread sends nothing, assigev_findtdreturnsESRCHand the completion goes on.SendValueSignal_nid_no_patchinSignals.cppfollows #19463'sSendTimerSignalwithout the overrun accounting: an ignored signal is dropped, a signal the target blocks is queued (each completion queues its own entry, asKSI_INSdoes), and the mask is checked again after queueing.aio_returnandaio_waitcompleteremove the request's own completion signal if it is still queued, asaio_free_entry(L534) callssigqueue_take(&job->ksi). Each queued entry carries a ticket, so a request removes only its own entry, not one of another request with the samesigev_value.NotImplemented_nid_no_patch), because guest handlers do not run on the aio threads. ForSIGEV_SIGNALthe target is the submitting thread, where FreeBSD posts to the process; this matches how #19463 picks the arming thread.Sockets (
sys_socket.csoo_aio_queueL774-L808,soaio_process_jobL560-L673,soo_aio_cancelL743-L771):aio_fsyncand a negative offset on a socket fail withEINVAL, asaio_aqueuedoes for a file without a vnode. The socket type no longer counts as a vnode for that check.recvorsendwithMSG_DONTWAIT(MSG_NBIO), andMSG_NOSIGNALon sends.EINTRorEWOULDBLOCKafter progress completes with the progress.EPIPEon a write withoutSO_NOSIGPIPEpostsSIGPIPEwithSI_KERNEL, assoaio_process_job(L620-L624) callskern_psignal(job->userproc, SIGPIPE), through the same helper. That is process-directed, so likeSIGEV_SIGNALit targets the submitting thread, also when the request usesSIGEV_THREAD_IDfor its completion.aio_cancelon a waiting socket request completes it withECANCELED(AIO_CANCELED), or with the bytes already sent andAIO_NOTCANCELEDwhen part was sent, assoo_aio_cancelandaio_cancel_job(L576-L624) count it.aio_cancelon a socket request in the middle of an attempt givesAIO_NOTCANCELEDand marks it, asaio_cancel_jobsetsKAIOCB_CANCELLEDon a job without a cancel function. When that attempt would put the request back, it completes instead: with the bytes already moved, orECANCELEDwhen none moved, assoaio_process_job(L651-L660) does whenaio_set_cancel_functionfails.The libkernel_sys debt entry is rewritten gap first (951 characters): the signal throw, the submitting-thread target, the 10 ms socket poll and the host send that can block (below). It drops the claim that a bad
aio_suspendpointer crashes the host, which is no longer true onmain(aio_suspendcopies its list and timeout in withGuestCopyInand returnsEFAULT).Progress (
python3 tools/progress.py --module libkernel_sys,mainatfb233c99c4):main193/820, this branch 195/820.aio_read,aio_writeandaio_fsyncbecome implemented.aio_cancelbecomes pending in the count: a cancelled request withSIGEV_SIGNALnow reaches the unblocked-signal throw through its completion, so the scanner sees that throw fromaio_cancel. Before this PR such a request could not be created, sinceaio_readthrew. libkernel goes from 716 to 717 through #19463 only.Tested
macOS 27.0.1 on Apple silicon (arm64), Release build with Ninja and AppleClang.
19980cb26f4(merge ofmainef7dc4452df), x86_64 build:guest_kernel_sys_aiopassed 10 of 10;guest_kernel_sys_ktimer,guest_kernel_sys_ktimer_exit_armed,guest_kernel_sys_ktimer_exit_deleted,guest_legacy_signal_maskandguest_kqueuepassed.guest_kqueue_cleared_racepassed when run directly, in 57 s on a host at load average about 180, which is over its 30 s ctest limit; it does not involve aio. With the908178b6689change toKqueue.cppreverted,guest_kernel_sys_aiofails at the first check after the second request on the reused aiocb.82fcbf5e84d:guest_kernel_sys_aiopassed 10 of 10 on Windows 11 (RTX 4090 box, MinGW build) and 3 of 3 on macOS.Earlier runs:
guest_kernel_sys_aiopassed 10 of 10 consecutive runs, about 0.54 s each, after mergingmainfb233c99c4.ctest -Roverguest_kernel_sys_aio,guest_kernel_sys_ktimer,guest_kernel_sys_ktimer_exit_armed,guest_kernel_sys_ktimer_exit_deleted,guest_signals,guest_signal_interrupt,guest_signal_handler_mask,guest_sigtimedwait,guest_kernel_sig_pending,guest_signal_context,guest_equeue_events,guest_kqueueandguest_kqueue_cleared_race: 13 of 13 passed.public_headersand its compile tests: 65 of 65 passed.mainAio.cppand the new test, the test stops withaio completion delivering a signal or a kevent not implemented.New test cases in
core/libs/tests/GuestKernelSysAio.cpp:EV_EOF),dataandudata; level-triggered untilaio_return, then gone (EV_DELETEgivesENOENT); a second request on the same aiocb before the first is returned reports nothing while pending, nothing afteraio_returnof the first, then fires once with its ownudataand is gone after its ownaio_return;EV_ONESHOTandEV_CLEARreport once; a laterEV_ADDchange re-reports a finishedEV_CLEARknote with the newudata; a cancelled request fires withdataECANCELED, and a cancelledEV_CLEARrequest re-reported by a later change still hasdataECANCELED; a userEV_DELETEbefore completion means no event; a forgedEV_ADDofEVFILT_AIOstill givesEPERM;EBADFfor a descriptor that is not a kqueue andEINVALfor a bad flag, both stored in the aiocb; a pipe request leaves no knote.SIGUSR1blocked,sigtimedwaitreturnsSI_ASYNCIO,si_pid0 and the value; two completions queue two entries in order;SIGEV_THREAD_IDto the calling thread; an unknown thread id sends nothing; an ignoredSIGURGis dropped; a cancelled request still signals;aio_returnandaio_waitcompleteleave noSIGUSR1pending (sigpending,sigtimedwaitgivesEAGAIN); two requests with the samesigev_value: aftersigtimedwaittakes the first one's signal,aio_returnof the first leaves the second one's signal queued.AF_UNIXstream pair):aio_fsyncand a negative offset giveEINVAL; a waiting read is cancelled; two queued reads complete in order from one write; a short read completes with 2 bytes; a write withSIGEV_KEVENT; end of file reads 0;EPIPEwithSIGPIPEignored; a 1 MiB write on a blocking socket givesAIO_NOTCANCELEDand completes once drained; on a non-blocking socket it completes with part of the bytes; a read cancelled in the middle of an attempt (held there by a test hook,AioHoldSocketForTest_nid_no_patch) givesAIO_NOTCANCELEDtwice, and after the test drains the data first the request completes withECANCELEDinstead of waiting again;SIGPIPEfrom a write withSIGEV_THREAD_IDto another thread (which blocks the completion signal but notSIGPIPE) is queued for the submitting thread, which blocks it.Mutation check, 10 hand mutations: 8 failed the test (
SIGEV_THREAD_IDtreated as process-directed, the knote not freed byaio_return, the knote not freed afterEOPNOTSUPP, no signal removal inaio_return, removal of any aio entry instead of the request's own, no cancelled check at the requeue (the request never completes), a re-activated knote without its error,SIGPIPEto theSIGEV_THREAD_IDthread). 2 survived on macOS: completing a blocking socket write early, and cancelling a partly sent write asECANCELED. The macOS host blocks insend(..., MSG_DONTWAIT)on a blockingAF_UNIXstream socket when the data does not fit (a standalone C program confirmed it), so a partly sent blocking write never happens there. Linux honoursMSG_DONTWAIT, so these paths need a Linux run. On WindowsMSG_DONTWAITis a poll followed by a blocking send inWaitForTransfer; the debt entry records both hosts.Overlap.
python3 tools/pr_overlap.py --names aio_read aio_write aio_fsyncandgh pr list --searchfor each name,SIGEV_KEVENT,EVFILT_AIOandsigeventfind no open PR that implements aio notification or socket aio. #16191 changes the sameQueue()function;git merge-treemerges it with this branch without conflicts. #20808 changes the same libkernel_sys debt entry in its own fragment (docs-kernel-sys-aio-suspend-debt.md) to replace the staleaio_suspendcrash sentence with theEFAULTbehaviour. The two texts agree: this one drops the sentence. The files merge without conflicts, buttools/debt_fold.py --checkrefuses two fragments that change the same entry, so whichever lands second folds the other's fragment into its own; this fragment applies cleanly on top of #20808's folded entry (checked withdebt_fold.pylocally). #9389 (sigqueue) also changesSignals.cppand is not needed here.Not verified:
22ee655388)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 PrivacyOnion on 2026-11-16T07:03:13Z.
Review: APPROVED
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against
22ee655388:tools/check_conventions.pypassed;git diff --checkclean.guest_kernel_sys_aio_tests,guest_kernel_sys_ktimer_exit_tests,guest_kernel_sys_ktimer_testsbuilt cleanly.guest_kernel_sys_ktimer,guest_kernel_sys_ktimer_exit_armed,guest_kernel_sys_ktimer_exit_deleted,guest_kernel_sys_aio):core/libs/prx/libkernel/Equeue/src/Kqueue.cpp,core/libs/prx/libkernel/System/src/Signals.cpp,core/libs/prx/libkernel/Time/Ktimer.cpp,core/libs/prx/libkernel/include/Api.hpp,core/libs/prx/libkernel_sys/Aio.cppreverted tomain, the new tests do not build/link without the change; restoring it makes them build and pass.Looks Good To Me
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-16T07:37:30Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: remove the dangling thread registry entries and make the socket worker lifetime safe when its queue is removed.
What I ran
Reviewed head
22ee65538880b0d881102b7857b503b2a8f0d8fc; no merged preview or programmatic checks were run. Inspected the prepared diff and repository context withrepo_read.py.Results
Findings
Blocking
core/libs/prx/libkernel/System/src/Signals.cpp:150:RegisterSignalThreadstores a rawThreadSignals*in the global map, and no corresponding unregister or erase path exists. After a guest thread exits, a later timer or AIO completion can find that stale pointer and callSignalBlockedthrough it. This is a use-after-lifetime risk on thread exit. Remove registry entries as threads exit, or use storage whose lifetime safely outlives all senders.core/libs/prx/libkernel_sys/Aio.cpp:257:SocketWorkererases itsSocketQueuenode once the job deque becomes empty. The worker dropsaio.lockwhile polling at lines 251–254; meanwhile, another thread can enqueue on that same queue or cancel its last job, allowing the worker to erase the node after it was reused. The worker then holds an invalid list iterator/reference, causing undefined behavior. Keep queue nodes alive until the worker has reacquired the lock and confirmed they remain empty, coordinating enqueue/cancel with that lifecycle.Non-blocking
None.
Sources
core/libs/prx/libkernel/System/src/Signals.cppandcore/libs/prx/libkernel_sys/Aio.cpp.Not verified
core/libs/prx/libkernel/Equeue/src/Kqueue.cpp,core/libs/prx/libkernel/System/src/Signals.cpp, andcore/libs/prx/libkernel_sys/Aio.cpp. Inspected changed hunks for the remaining files; did not read their full text. The manifest marks all listed changed files as included;files.jsonwas not available through the reader.To get this to a good state
Fix the thread registry and socket queue lifetimes, then rerun the relevant build and tests on the new head.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-18T07:35:19Z.
Review: APPROVED
Reviewed — looks good
Nothing blocks this change based on the source and test coverage reviewed; the reported test runs were supplied by the author and were not run here.
What I ran
Reviewed head
d300f12e04e452d404f46a9ee7eb1751ef649861. No commands or tests were run; the prepared diff and repository reader were the available review inputs.Results
Findings
Blocking
None.
Non-blocking
None.
Not verified
The full changed-file texts were included for 10 of 11 changed files. The deleted
docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.mdwas excluded because it has no added lines. I read targeted runtime ranges and test sections; I did not read every line of every included changed file. Linux, Windows, and console behavior were not run or confirmed here. The test outcomes in the PR description are author-reported.To get this to a good state
Nothing is required.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-18T18:54:32Z.
Review: COMMENTED
Reviewed — comments
The review is incomplete because the full changed-line inventory and targeted source audit were not completed, so approval or a formal change request is not justified.
What I ran
Read the prepared description, commits, manifest, diff excerpt, and changed source excerpts through the pinned-head reader. No build or tests were run; author-reported results were not independently verified.
Results
Findings
Blocking
None verified from the inspected excerpts.
Non-blocking
None.
Not verified
The full diff and remaining changed-file lines were not read, including most of
Aio.cpp, the remaining signal helpers, tests, and build/debt changes. Thus correctness, test coverage, and the claims in the PR description remain unverified. Files listed as changed and included in the review folder:core/libs/CMakeLists.txt,core/libs/prx/libkernel/Equeue/src/Kqueue.cpp,core/libs/prx/libkernel/System/include/TimerSignals.hpp,core/libs/prx/libkernel/System/src/Signals.cpp,core/libs/prx/libkernel/Time/Ktimer.cpp,core/libs/prx/libkernel/include/Api.hpp,core/libs/prx/libkernel_sys/Aio.cpp,core/libs/tests/GuestKernelSysAio.cpp,core/libs/tests/GuestKernelSysKtimer.cpp,core/libs/tests/GuestKernelSysKtimerExit.cpp,docs/dev/debt/changes/feat-aio-sigevent-completion.md, anddocs/dev/debt/changes/feat-libkernel-ktimer-signal.md.docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.mdis deleted and has no new text to inspect.To get this to a good state
Nothing is required.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T18:57:10Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: prevent an existing AIO knote from being rebound to a different request.
What I ran
Reviewed head
6822e196629f93825dfdfe93e63659a5cbae7ddeusing the prepared review artifacts andrepo_read.py; no tests or build commands were run.Results
Findings
Blocking
core/libs/prx/libkernel/Equeue/src/Kqueue.cpp:735: When a new AIO request uses anidentthat already has anEVFILT_AIOknote, this path updates the existing knote but leaves itsAioNote::tokenunchanged. AIO completion and cleanup only act when that token matches the request (Kqueue.cpp:755-763,767-773). Reusing an aiocb address can therefore leave the new request without its completion event and leave the old knote behind afteraio_return. Reject the duplicate registration or safely replace/rebind the note so completion and cleanup match the new request.Non-blocking
None.
Not verified
No tests or build were run. Full changed-file texts read:
core/libs/prx/libkernel/Equeue/src/Kqueue.cppandcore/libs/prx/libkernel_sys/Aio.cpp. The prepared description, commits, manifest, and diff were read; other changed-file texts were not read.docs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.mdis deleted and has no new text. Author-reported test results were not independently verified.To get this to a good state
Fix duplicate AIO knote registration so a request cannot inherit a knote with another request's token, then rerun the AIO tests.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-22T04:34:29Z.
Review: CHANGES_REQUESTED
Reviewed — changes requested
Changes are required before merge: prevent zero-byte socket requests from waiting indefinitely and preserve the pending-signal queue limit for AIO completions.
What I ran
Reviewed head
19980cb26f4fc7395f870a5cb9199ca84c446114againstmain. Read the prepared description, commits, diff, manifest, all included changed files, and targeted socket, signal, and kqueue context throughrepo_read.py. No build or tests were run.Results
Findings
Blocking
core/libs/prx/libkernel_sys/Aio.cpp:223: For a zero-byte socket read,recvreturns 0 only when data is available or the peer has closed; while a live socket has no data,SocketWorkerwaits forPOLLINbefore it callsRunSocketJob. The queued request therefore never completes even though a zero-byte read should complete immediately. The write path has the same readiness gating. Complete zero-byte socket requests without waiting for socket readiness, and add a regression test.core/libs/prx/libkernel/System/src/Signals.cpp:789:QueueValueSignalappends every AIO completion signal without enforcingMaxQueuedPerSignal(1024), unlike the existingMarkPendingpath. Repeated completions to a blocked signal can grow the queue without bound and bypass the established per-signal cap. Enforce the cap and define the completion behavior when it is reached; add a capacity test.Non-blocking
None.
Not verified
No build, tests, Linux run, or console run was performed. The deleted debt fragment was excluded because it has no added lines. The code review covered the included changed files:
Kqueue.cpp,Signals.cpp,Api.hpp,Aio.cpp,GuestKernelSysAio.cpp, andfeat-aio-sigevent-completion.md.To get this to a good state
Handle zero-byte socket requests without readiness polling and enforce the signal queue limit. Add regression coverage for both cases, then rerun the AIO test suite on the new head.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-22T14:15:07Z.
Review: APPROVED
Reviewed — looks good
The reviewed changes implement AIO signal and kqueue completion notifications and socket requests; no verified blocking defect was found in the code read.
What I ran
Reviewed head
7ddbf60a2efb22c67bd96cfce1cd97703ffa6b86againstmain. No commands or tests were run; the test results below are author-reported.Results
Findings
Blocking
None.
Non-blocking
None.
Not verified
The console, Linux behavior for partial socket writes on this head, unblocked signal delivery, and the deleted debt fragment were not verified. The author reports macOS and Windows test runs and identifies the unblocked-signal path as still throwing. Files read:
description.md,commits.md,manifest.json,diff.patch,Kqueue.cpp,Signals.cpp,Api.hpp(diff only),Aio.cpp,GuestKernelSysAio.cpp, andfeat-aio-sigevent-completion.md. Excluded: deleteddocs/dev/debt/changes/docs-kernel-sys-aio-suspend-debt.md;files.jsonwas unavailable in the review folder.To get this to a good state
Nothing is required.