feat(libkernel): support EV_CLEAR on a kqueue watched by another kqueue #9575
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/9575"
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-22T02:48:48Z.
What
keventthrew forEVFILT_READwithEV_CLEARon a kqueue descriptor, that is, one kqueue watching another. In FreeBSD 11:knote_enqueuecallskqueue_wakeup, which runsKNOTEon the watched kqueue'skq_sel.si_note. Sofilt_kqueue(sys/kern/kern_event.c:364,kn_data = kq_count) is evaluated again every time the watched kqueue queues a note.EV_CLEAR:kqueue_scanclears the watching note when it is retrieved, so it fires again only after the next such activation.kqueue_registerevaluates the filter once, so a watched kqueue that already holds notes fires immediately.How:
Equeue.hpp/Equeue.cpp:KernelEqueuePrivatecounts activations, meaning an event becoming enabled and triggered. They come from a poll result, a timer expiring,TriggerEvent,AddEventof a triggered event, a pending event re-queued after retrieval, andEditEvent(the pathNOTE_TRIGGERandEV_ENABLEtake).Activations()reads the count.EditEventcounts through a scope guard, so this change leaves itsNotifyOneline alone.Kqueue.cpp:EV_CLEARon a kqueue no longer throws.filter.data/owner, so the shared event structure is unchanged.dataset to the queued count. The reset after retrieval clears it.kevent on a kqueuedebt line: the "EV_CLEARthrows" sentence now describes this. Activations are seen when the watching queue polls, so one that is undone before that poll is missed.Tested
Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release. This is CPU-side, so no GPU is involved.
guest_kqueue(core/libs/tests/GuestKqueue.cpp) changes:EV_CLEARthrow now adds and deletes the note successfully.ClearedKqueue():data1 andEV_CLEAR;data2;Results:
guest_kqueueand 28 other equeue, kqueue, select, poll, event-flag and AMPR tests pass: 4 solo runs and 4 parallel (-j4) runs.Requirethat reports its line:EditEventactivation count, it fails at the first poll afterNOTE_TRIGGER.tools/check_conventions.py: 0 errors. Its one warning is a debt entry that was already over 1000 characters onmain.tools/pr_overlap.py --branchplusgit merge-tree. This merges cleanly with #7492 (which changes the same functions'NotifyOnecalls), #7605, #7049 and #9284. #7653 and #7088 already conflict withmain.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 jotitadev on 2026-10-22T03:39:03Z.
Review: COMMENTED
First run on Linux (the PR is tested on Windows only). Ubuntu 26.04, x86_64, Intel i7-8700, GCC 15.2.0, Release,
BUILD_TESTING=ON, head bd82db6ca merged--no-commitonto currentorigin/main(6ef5a1c4c).ctest -R guest_kqueuewith the PR: passes.Equeue.cpp,Equeue.hppandKqueue.cpptoorigin/main, keep the new test): the test aborts with the real assertSo the EV_CLEAR path and the activation counter are exercised by
ClearedKqueue()on Linux too, and the test genuinely fails without them.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T03:51:13Z.
Review: CHANGES_REQUESTED
The activation snapshot is not atomic, which can permanently lose a kqueue wakeup.
PollClearedKqueuefirst callsCountTriggeredEvents()and thenActivations(), and each call acquires/releases the watched queue's mutex independently. If another thread triggers an event after the count returns 0 but before the activation count is read, this poll stores the new generation innote.seenwhile leavingnote.activefalse. The next poll sees the same generation and never reports the queued event.AddKqueueKnotehas the same split-read window while initializingpendingandseen.Please expose one locked snapshot operation that returns both the triggered count and activation generation, and use it in both places (with timer/filter polling performed under the same lock). Add a concurrency regression test that forces or reliably exercises activation between snapshot components; the current sequential
ClearedKqueue()test cannot cover this race.Please also resolve the unverified overlap warnings before approval: #7653 shares
Equeue.cpp,Kqueue.cpp,GuestKqueue.cppand the debt entry, and #7088 sharesEqueue.hpp,Kqueue.cpp,GuestKqueue.cppand the debt entry. The body discusses #7653/#7088 as conflicting with main but does not record author coordination or a required ordering. #6044 also has an uncomparableGuestKqueue.cpppath because its broad test move exceeds the diff limit; preserve this new test at the moved path if that reorganization lands first. If any of these require sequencing, agree the order with the authors and declare the prerequisite inDepends on.The hosted eligibility, intake, labels, report and conventions checks pass. The Linux, Windows and relinker product jobs are skipped, so I did not treat them as executed. The author-reported Windows test matrix and the independent Linux run in the discussion are useful evidence, but neither exercises the interleaving above.
Imported from boykopovar/AnyPS5. Originally posted by harisibrar1 on 2026-10-22T06:01:37Z.
Review: COMMENTED
Checked against main
4a17c7175and FreeBSD releng/11.4sys/kern/kern_event.c:kqueue_scancallsfilt_kqueueagain before it reports a note (kern_event.c:1782-1792, 1798).PollClearedKqueue(Kqueue.cpp:204-215) only refreshespendingwhen the activation count has moved, so a note that was polled but not collected keepsactiveand its olddata. Example: outer has an EV_CLEAR user note U, added before the EV_CLEAR watch on inner. Trigger inner note 7 (EV_CLEAR) and U, runkevent(outer, n=1)(returns U), then drain inner. The nextkevent(outer)reports the watch with data 1, where FreeBSD reports nothing becausekq_countis 0. With two inner notes and one drained, it reports data 2 where FreeBSD reports 1. One possible fix: setactive = truewhen the count moves, then on every poll clearactiveifpending == 0, else setdata = pending.kqueue_registerre-evaluates the filter on EV_ADD or EV_ENABLE of an existing enabled knote and queues it if ready (kern_event.c:1435-1438, 1468-1478).ModifyKnotere-armsPollEdgewatches for this (Kqueue.cpp:389) but notPollClearedKqueuenotes. So after the first report, a re-EV_ADD(orEV_DISABLE+EV_ENABLE) of the watch while inner still holds note 7 returns 0 here and 1 on FreeBSD. Settingactive = truethere for an enabledPollClearedKqueuenote, together with the check above, should match FreeBSD.ClearedKqueue(), or into the "kevent on a kqueue" debt line if you would rather leave them for later?Poll(inner)does not empty inner. The test is still valid, but the description's "draining the watched kqueue" step does not really drain it.Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.
Imported from boykopovar/AnyPS5. Originally posted by DavidSamir on 2026-10-22T08:28:08Z.
Thank you both, these were real. New commits, no force-push:
6deae6e09b:KernelEqueuePrivate::SnapshotTriggered()replaces the separateCountTriggeredEvents()+Activations()reads. It returns the triggered count and the activation generation under one lock, after the same timer and filter polling.PollClearedKqueueand the registration inAddKqueueKnoteboth use it.kqueue_scanrerunsfilt_kqueue. An activation makes the watch active; an active watch drops when the count is 0 and otherwise reports the current count.EV_ADDof an existing watch, andEV_ENABLE, re-arm it inModifyKnote, askqueue_registerre-evaluates.ClearedKqueueRechecksTheWatchedCount(): your examples.n=1takes an earlierEV_CLEARuser note) reports nothing once the watched queue is drained.data == 1.EV_ADD, andEV_DISABLE+EV_ENABLE, while the watched queue still holds a note report it again.EV_CLEAR, so the drain really drains. You're right that the originalClearedKqueue()notes don't; that check is unchanged and its description was loose.ClearedKqueueKeepsConcurrentActivations(), a separate CTest entryguest_kqueue_cleared_race(timeout 60):Negative controls, all on Windows:
Kqueue.cpp/Equeue.*failClearedKqueueRechecksTheWatchedCount.guest_kqueuebut failguest_kqueue_cleared_race8/8 (between 4 and 18 s).guest_kqueue_cleared_racepasses in about 11.4 s.c842a3762emerges currentmain.Re-run on the merge (Windows 11, WinLibs GCC 15.2):
guest_kqueue,guest_kqueue_cleared_raceand the other equeue, kevent and event-flag tests pass, andcheck_conventions.pyreports 0 errors (its one warning is a debt entry already over the limit onmain).One note for anyone reproducing:
StandardInput()(onmain) assumes nothing is readable on fd 0, so runguest_kqueuewith stdin from/dev/nullor a terminal. A stdin pipe that has data makes it abort early, which is unrelated to this change.On the overlaps (#7653, #7088, and #6044's move of
GuestKqueue.cpp), I'm asking those authors for an order and will record it in the checklist.AI-assisted: yes
Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T09:01:41Z.
Review: COMMENTED
Re-ran on Linux at c842a3762 (follow-up to my run at bd82db6ca). Ubuntu 26.04, x86_64 i7-8700 (6 cores / 12 threads), GCC 15.2.0, Release, head merged
--no-commitontoorigin/main7e2ba73e4.guest_kqueueandguest_kqueue_cleared_racepass; the race test 10/10 more runs (about 20 s each).Equeue.cpp,Equeue.hppandKqueue.cppfrom bd82db6ca (before 6deae6e09), tests from the head:guest_kqueueaborts (the newClearedKqueueRechecksTheWatchedCount).guest_kqueue_cleared_racepasses 5/5 as registered, and 3/3 more withtaskset -c 0,1/taskset -c 0-3. It only catches the lost wakeup when pinned to one CPU:taskset -c 0 guest_kqueue_tests cleared-raceaborts 3/3 with the old files and passes 5/5 with the head's.So on a multi-core Linux machine the race test doesn't distinguish the fix as registered. If you want it to, pinning the test to one CPU (or making the trigger thread run between the count and the activation read) would do it; I didn't try the latter.
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-22T09:29:56Z.
Thank you @jotitadev, that's exactly the gap.
7ef0ff5420makesguest_kqueue_cleared_racepin itself to its first allowed CPU on Linux (sched_setaffinity, before the trigger threads start, so they inherit it), as in yourtaskset -c 0run.I left Windows unpinned on purpose. There, the split reads fail the race test 8/8 unpinned, but pinned to one CPU they passed 6/6, so pinning would hide the race. On Windows the fix passes in about 11.4 s, and
guest_kqueuestill passes.If you have a moment, could you rerun your control on Linux at this head (
Equeue.*andKqueue.cppfrom bd82db6ca, tests from the head, notaskset)? I'd expectguest_kqueue_cleared_raceto abort now.AI-assisted: yes
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T10:52:25Z.
Review: CHANGES_REQUESTED
Re-reviewed head
7ef0ff542027fba77853362820b763b452641c02. The two earlier functional findings appear addressed: count and activation generation are read in one lock-held snapshot, and the cleared watch is polled against the current watched count on each pass, including re-add/enable. The new Linux race test pins the test and its trigger thread to one allowed CPU, matching the independent reviewer’s negative-control setup. I found no remaining code defect in this pass. The exactguest_kqueue_teststarget builds locally. CTest starts bothguest_kqueueandguest_kqueue_cleared_race, but each aborts inHostCpubefore assertions because this Xeon E5-1620 v2 lacks LZCNT, BMI1/2, MOVBE, AVX2 and FMA. The Windows runs and split-snapshot negative control described in the comments are author-reported; the independent Linux reviewer has tested earlier heads and demonstrated that the split-read control only fails when pinned. Current eligibility, conventions, labels and report pass; product/relinker jobs are skipped. Please resolve the remaining overlap coordination before merge. #7653 edits the sameKernelEqueuePrivate::EditEventfunction (timer expiry accounting versus this PR's activation snapshot accounting); the changes look composable but need an agreed carry-forward/order. #7088 adds regular-file handling inKqueue.cppand tests inGuestKqueue.cpp; the compared functions are separate, but the overlap bot cannot compare these files against its conflicted base and the debt line is shared. #6044 relocatesGuestKqueue.cppand its registration. I found no author agreement in the latest public threads. Please coordinate with these authors, retain the new tests andguest_kqueue_cleared_raceregistration at the relocated path if #6044 lands first, and declare a dependency only if the agreed sequence requires one. The PR is 4 ahead / 11 behind currentmain(clean merge). Please refresh it to satisfy the current-main branch rule. One documentation/conventions correction: the current-base convention run reports adebt-lengthwarning atdocs/dev/debt/libkernel.md:203(1,095 characters). The same entry is 960 characters on currentmain; this PR expanded it past the 1,000-character threshold. Please shorten the entry and correct the Tested text that describes the warning as pre-existing on main.I’ve noticed that holding this PR because of #5239 isn’t necessary. It’s fine for PRs to keep coming in; they’ll be handled in due course. Please disregard my earlier request to hold or defer it.
Imported from boykopovar/AnyPS5. Originally posted by harisibrar1 on 2026-10-22T12:54:59Z.
Review: APPROVED
Rechecked at 7ef0ff542:
PollClearedKqueuenow rechecks the watched count on every poll and drops the watch at 0 (Kqueue.cpp:204-217), andModifyKnotere-arms it onEV_ADD/EV_ENABLE(Kqueue.cpp:392-394). Traced againstkqueue_scanandkqueue_register: the drained case reports nothing, the one-drained case reports data 1, and re-add/enable report 1 (0 once the watched queue is empty), all as on FreeBSD.SnapshotTriggeredlock (Equeue.cpp:297-306) also closes the window @MarcZX10 found, andClearedKqueueRechecksTheWatchedCountcovers our examples with notes that really drain.debt-lengthwarning.Reviewed with AI assistance (Claude Code); the checks above were run locally on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T14:12:35Z.
Review: CHANGES_REQUESTED
Re-reviewed exact head
7ef0ff542027fba77853362820b763b452641c02. The snapshot/generation pair is now read under one lock, the cleared watch rechecks the current watched count, and the re-arm paths coverEV_ADD/EV_ENABLE; the independent FreeBSD-semantics review confirms these changes address the earlier functional findings. I found no new implementation defect in those paths.There are still repository-rule and integration blockers:
core/libs/prx/libkernel/CMakeLists.txtregistersguest_kqueue_cleared_racewithTIMEOUT 60.CONTRIBUTING.mdrequires tests to finish within 30 seconds and says to shrink/split a slow test instead of raising its timeout. The reported Windows run is about 11.4 seconds, but the current test does 5,000 thread creations and 20,000 registered notes, and the independent Linux report measured about 20 seconds per run on its machine. Please reduce or restructure the race test so it retains a useful negative control with adequate CI headroom, and keep its timeout at or below 30 seconds. Please provide an exact-head Linux run for the newly pinned one-CPU path as well; earlier independent Linux runs were on the preceding head.kevent on a kqueuedebt entry is 1,095 characters on this head; the corresponding current-main entry is 960.tools/check_conventions.py --base upstream/main --head HEADreports a newdebt-lengthwarning at line 203. Please shorten the entry below the 1,000-character limit and retain the gap/console-verification facts.d6eafa54d0464258574fd2f71889754d05a5bc93, 54 commits behind currentupstream/main8b3e39832af85f404c6195418d11b3e1ebd1924d. Please update it and rerun the focused matrix.GuestKqueue.cppand its registration. Please record how both behavior changes andguest_kqueue_cleared_racewill be preserved through the chosen order.Checks I ran on this exact head:
git diff --checkpasses; theGuestKqueue.cppsource passes GCC 12.2 C++20-Wall -Wextra -Werror -fsyntax-only;tools/check_test_registration.py --scriptsreports 171 registered scripts. Conventions reports 0 errors and the new 1,095-character debt warning. The prior exact-head local test target built, but CTest aborted duringHostCpuinitialization before assertions because this host lacks LZCNT/BMI/MOVBE/AVX2/FMA. The author reports Windows suites/negative controls; independent Linux runs cover earlier heads and show why the one-CPU control matters. Hosted product jobs are skipped.I withdraw my earlier generic intake/queue objection. Given your contribution-count eligibility,
Unblocks: noneis not an intake blocker here.Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-25T17:20:44Z.
Review: CHANGES_REQUESTED
The implementation looks right to me: the lock-held
SnapshotTriggered(), the per-poll recheck of the watched count and the re-arm onEV_ADD/EV_ENABLEmatchkqueue_scan/filt_kqueue, and the new tests fail without the change. What blocks the merge:core/libs/prx/libkernel/CMakeLists.txt:1518:guest_kqueue_cleared_racehasTIMEOUT 60, and CONTRIBUTING asks for tests that finish within 30 seconds (shrink or split a slow test instead of raising the timeout). It takes about 20 s on an i7-8700 (5000 thread creations, 20000 registered notes,GuestKqueue.cpp:590-598). Please reduce it while keeping a negative control that still fails with the split reads, and set the timeout to 30 or less.docs/dev/debt/libkernel.md:203: thekevent on a kqueueentry grows from 960 to 1095 characters and triggers thedebt-lengthwarning (limit 1000). Please shorten it, keeping theEV_CLEARand "not measured on a console" facts. The Tested section calls that warning pre-existing onmain; it is new with this entry, so please correct it.mainincore/libs/tests/GuestKqueue.cppanddocs/dev/debt/libkernel.md. Please rebase and rerunguest_kqueueandguest_kqueue_cleared_race. #7653 is already merged, so itsEditEventchange is onmainnow. #7088 is still open and touches the sameKqueue.cpp/GuestKqueue.cpphunks and the debt entry, so check the merge once it lands.Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-27T03:03:47Z.
Review: COMMENTED
The rerun you asked for, on
7ef0ff542: the race test as registered now catches the split reads on Linux. On currentmain, one of the newguest_kqueuechecks fails because of an ordering change that landed onmain.Machine: Linux x86_64, i7-8700 (6 cores / 12 threads), Ubuntu 26.04, GCC 15.2, Release,
BUILD_TESTING=ON, full build. Head7ef0ff542merged--no-commitontomainabed03546. I resolved the two conflicts the same way @blawesom did:main(argc, argv)with thecleared-racedispatch plusmain'sStandardInputReplacement(), andmain's debt file.guest_kqueue_cleared_race: passes 3/3 in 20.0, 21.3 and 19.6 s, against the 60 sTIMEOUT.Control, with 6deae6e09's changes to
Equeue.cpp,Equeue.hppandKqueue.cppreverted (the split reads) and the head's tests kept, run through ctest with notaskset:guest_kqueue_cleared_raceaborts 3/3, after about 5.7 s each. So the self-pinning does what mytaskset -c 0run did.guest_kqueueaborts 3/3 on the merge, and passes on plainmain. The last log line is theprocdesc-directoryopen, but that isn't where it stops. WithRequireprinting its line, it aborts at this check inClearedKqueueRechecksTheWatchedCount(line 550 on the head):The poll returns the watched kqueue (
ident6 =inner,EVFILT_READ) instead of user event 1. #9780 (3383d303a, "move every knote kevent reports behind the waiting ones") is now onmain: user event 1 was reported a few lines earlier, so it now waits behind the watched-kqueue note. The check expects the old order. Polling with room for both events and checking each one byidentwould avoid depending on the order.Written with AI assistance (Claude Code). I ran the builds and tests above on my machine.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T06:21:38Z.
Review: CHANGES_REQUESTED
Re-checked — changes requested
The current head
638996829b1a6c9b3800d7aac89a8409af6cbe49includes the order-independent poll fix for #9780: the test now collects both events and matches them by identifier. The race test timeout is 30 seconds, and the current head has an independent maintainer approval. These changes resolve the earlier event-order and timeout concerns.Two integration items remain. I previously asked to coordinate the overlapping
GuestKqueue.cppwork with #12503; both PRs remain open, neither checklist records the agreed order, and I found no author agreement. The pairwise merge preview is clean, but the repository requires the order for overlapping work to be explicit. Please record the agreed sequence in the dependent PR’s checklist. Also, currentmainhas advanced past this branch’s base and changedCMakeLists.txtand the libkernel debt file; please merge current main and rerun the focusedguest_kqueueand cleared-race tests on the integrated head.The author/reviewers report Linux and Windows runs on earlier merged-main heads; I did not run the kqueue tests locally. This request is limited to coordination and current-main integration.
Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-29T08:33:12Z.
Review: CHANGES_REQUESTED
Re-reviewed exact head
638996829b1a6c9b3800d7aac89a8409af6cbe49against currentupstream/main4c7d275bef89d309313d16bc2bc05d37a1b50be2. The original #12503 overlap-order request remains open. The latest head also changes two unrelated submodule gitlinks: SPIRV-Headers and SPIRV-Tools. Both point to the same commits asmain, so please restore those gitlinks in this kqueue PR (or split and justify the dependency update separately). The current-main merge preview is clean andgit diff --checkpasses. I did not run the kqueue tests locally.