Skip to content

fix(libkernel): wake every thread waiting on an equeue or kqueue when an event fires - #7492

Merged
oneandonlydean merged 2 commits into
boykopovar:mainfrom
Lindamea1:fix/equeue-wake-all-waiters
Nov 13, 2026
Merged

oneandonlydean merged 2 commits into
boykopovar:mainfrom
Lindamea1:fix/equeue-wake-all-waiters

Conversation

@Lindamea1

@Lindamea1 Lindamea1 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

What

sceKernelWaitEqueue and kevent sleep on the queue's condition variable in KernelEqueuePrivate::WaitForEventsUntil, and AddEvent, TriggerEvent and EditEvent woke only one of the sleeping threads (m_cond.NotifyOne()). With two or more threads blocked on one equeue or kqueue:

  • a level-triggered event (sceKernelAddUserEvent and sceKernelTriggerUserEvent, or an EVFILT_USER knote without EV_CLEAR triggered with NOTE_TRIGGER) released one waiter. The others slept until their timeout, or for good with a null timeout, while a poll (timo 0) of the same queue at that moment returned the event.
  • a timer added while they waited (sceKernelAddTimerEvent, or EVFILT_TIMER with EV_ADD) reached only the thread woken to recompute its wait. The others returned at their own timeout, or not at all with a null timeout.

On main, with two waiters using a 5 s timeout and the event fired 50 ms after they start, the second waiter returns at 5000 ms in all three cases (user event, timer, kqueue user event), while the first returns at 50 ms, or at 100 ms for the 50 ms timer.

FreeBSD 11.4 wakes every thread asleep on a kqueue when a knote becomes active. knote_enqueue calls kqueue_wakeup, which calls wakeup(kq), and wakeup makes every thread sleeping on the queue runnable through sleepq_broadcast; kern_event.c never calls wakeup_one. Each woken thread goes back to retry in kqueue_scan. A knote without EV_CLEAR or EV_DISPATCH is put back at the tail after it is reported, so every waiter returns it; an EV_CLEAR knote is taken by one waiter and the others find kq_count at 0 and sleep again. A NOTE_TRIGGER change enqueues the knote in kqueue_register, and a timer expiry through filt_timerexpire. Not measured on a console.

The three calls now use m_cond.NotifyAll(), as Close already does. WaitForEventsUntil collects again after every wake and goes back to sleep when it finds nothing, so an EV_CLEAR event still reaches one waiter and a queue with a single waiter behaves as before. A queue with socket or pipe events waits in WaitForDescriptors instead, and WakePollers already wakes every poller there. On Windows the non-coarse TimedWait::Condition::NotifyAll walks the waiter list, the path Close already takes. I don't know of a title that blocks two threads on one queue; VideoOut, AGC, AMPR and libSceHttp2 completions reach waiters through TriggerEvent.

New checks:

  • VerifyEventWakesEveryWaiter in GuestEqueueEvents.cpp: two threads wait with a 5 s timeout, the main thread triggers a level user event (TriggerEvent), and both waiters must return within 2 s. The same follows on the emptied queue by adding a 50 ms timer (AddEvent).
  • UserEventWakesEveryWaiter in GuestKqueue.cpp: the same with two kevent waiters and a NOTE_TRIGGER change (EditEvent).

Tested

Gentoo Linux, kernel 7.2.8, GCC 16.2.1, glibc 2.43, Release, BUILD_TESTING=ON, rebased onto main cf2c667.

Not run on Windows, macOS or a console by me. @wachi35676 (Windows 11 and Ubuntu 24.04) and @screamm (Windows 11, stacked with #7509 and #7090) ran the head before this rebase, fd2eb35, which has the same change; see their comments.

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

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 7121 core/libs/tests/GuestKqueue.cpp
PR 9293 core/libs/prx/libkernel/Equeue/Equeue.cpp
PR 9297 core/libs/prx/libkernel/Equeue/Equeue.cpp
PR 9302 core/libs/prx/libkernel/Equeue/Equeue.cpp

@wachi35676

Copy link
Copy Markdown
Contributor

Windows run (this was syntax-checked only there): Windows 11, MinGW GCC 15.2, with this PR merged onto main 9f25d0bf5, plus Ubuntu 24.04/GCC 13.3.

  • Tests: with only the two test files from this PR, guest_equeue_events and guest_kqueue abort on main on both platforms. With the PR they pass 10/10 each with the default Windows waits, and 10/10 each with APS5_COARSE_TIMED_WAITS=1 (the condition_variable_any path). The socket/equeue set passes serially (Windows 38/38, Linux 26/26).

  • Extra probe, not in the PR: eight sceKernelWaitEqueue waiters (3 s timeout) on one level user event, triggered after 20 ms, 100 rounds:

    • main: 100 of 100 rounds had a waiter return at its timeout (worst 3055 ms).
    • this PR: 0 of 100 (worst 35 ms on Windows in both modes, 21 ms on Linux).

    With an EV_CLEAR event (sceKernelAddUserEventEdge), 4 waiters and 20 rounds, exactly one waiter got the event each round on both platforms, so NotifyAll doesn't double-deliver.

  • fix(libkernel): bound equeue pending events #7509: it merges cleanly with this PR, and the combination passes guest_equeue_events/guest_kqueue 5/5.

  • Heads-up for Windows reruns: under parallel load, guest_kqueue on main itself can abort in PipeRead (GuestKqueue.cpp:246). In my runs kevent returned the read event 13 µs–35 ms into a wait, while the writer was still in its 50 ms sleep. That happens before UserEventWakesEveryWaiter runs, so a failure there is unrelated to this change.

AI-assisted: yes (Claude Code); results above were run on this machine.

@screamm

screamm commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

Windows run of head fd2eb3521, merged onto main 0d078f75d together with #7509 (c170bba42) and #7090 (17d9e0a51); the three merge cleanly in that order, so this is the stack, not #7492 alone.

  • Host: Windows 11 Pro 26220, Ryzen 7 5700X, RTX 4070 (driver 596.21), WinLibs MinGW-w64 GCC 15.2.0 r7, Ninja, Release, BUILD_TESTING=ON.
  • Build: the full build and libs pass. No warning in Equeue.cpp, GuestEqueueEvents.cpp or GuestKqueue.cpp.
  • On a quiet host guest_equeue_events, guest_kqueue and guest_socket_events pass 3/3 (equeue 0.7-0.9 s, kqueue 3.0-3.1 s), and 35 equeue/kqueue/socket/poll/select/rudp tests pass 3x, 105/105. With --repeat until-fail:15 under load from other builds, guest_equeue_events and guest_kqueue pass 15/15 each (equeue 0.77-2.27 s, kqueue 3.17-4.74 s).
  • One guest_kqueue abort in a first batch (while I was copying files): it aborted in PipeRead, which runs before the new test. Afterwards 20/20 on the stack, 20/20 on main and 28/28 with 8 parallel copies. @wachi35676 reports the same PipeRead abort on main under load, so I treat it as that flake.
  • Negative control: NotifyAll back to NotifyOne in AddEvent, TriggerEvent and EditEvent (everything else kept) makes both guest_equeue_events and guest_kqueue abort after 8.6 s (the second waiter returns at its 5 s timeout). Restored, both pass.
  • Non-GPU suite (ctest -j8 --timeout 120 -E '^agc_driver_|^video_out_flip'): 936 tests, 929 pass, 2 skipped, 5 load timeouts (conventions_function_bodies, configure_seed, hardware_oracle_compare, guest_none_relocations, tls_function_coverage_register_address_loads) that all pass when rerun serially.
  • tools/check_conventions.py --base origin/main and git diff origin/main --check pass on the stack.
  • FreeBSD 11.4 kern_event.c: kqueue_wakeup clears KQ_SLEEP and calls wakeup(kq), which wakes every sleeper, and the file has no wakeup_one; this matches the description. An EV_CLEAR knote is dequeued by the first scanner, so the other waiters find nothing and sleep again, as here.

Titles: sceKernelWaitEqueue is imported by 17 local titles. I ran PPSA99169 (RetroArch), PPSA01153 (OliSe Player) and PPSA74126 (Stremio Plus) for 60 s each, the stack against the same build with Equeue.cpp, Equeue.hpp and Udp.cpp from main. No stop line in any run; frames 5494 / 3457 / 3387 before and 5914 / 3486 / 3487 after, with the same last fps (about 119 / 60 / 60). With a local diagnostic libkernel (reverted) that logs the first time a second thread blocks on one equeue, PPSA74126, PPSA99082 and PPSA99169 (app.exe only, not its picker child) had none in 45 s. So I found no local title that blocks two threads on one queue, as the description says; the change has no visible effect on them.

Not checked: Linux, macOS, APS5_COARSE_TIMED_WAITS=1, a console, the other 14 importers.

Written with Claude Code assistance (validation by a subagent, reviewed in this session).

@blawesom

Copy link
Copy Markdown
Contributor

Support triage — rebase note: the only rebase conflict against current main (d34da5d69) is core/libs/tests/GuestKqueue.cpp, which has seen several new test calls land recently (LowWaterMarks, DisableAndDispatch). The production change in Equeue/Equeue.cpp itself applies cleanly. A rebase keeping main's test-runner calls alongside this PR's should be mechanical.

… an event fires

AddEvent, TriggerEvent and EditEvent woke one of the threads blocked in
sceKernelWaitEqueue or kevent on the queue. With two or more waiters, a
level-triggered event (sceKernelAddUserEvent, or EVFILT_USER without
EV_CLEAR) released only one of them; the others slept until their
timeout, or for good without one, while a poll of the same queue
reported the event. A timer added while several threads waited reached
only the thread woken to recompute its wait; the others slept until
their own timeout, or for good without one.

FreeBSD 11.4 kern_event.c activates a knote through knote_enqueue,
which calls kqueue_wakeup and wakeup(kq), and wakeup makes every thread
sleeping on the queue runnable (kern_synch.c). Each woken thread scans
again: a level knote goes back on the queue after it is reported, so
every waiter returns it, while an EV_CLEAR knote is taken by one waiter
and the others sleep again. Notify every waiter, as Close already does;
WaitForEventsUntil already collects again and goes back to sleep when
it finds nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Lindamea1
Lindamea1 force-pushed the fix/equeue-wake-all-waiters branch from fd2eb35 to 2feb074 Compare October 21, 2026 18:36
@Lindamea1

Copy link
Copy Markdown
Contributor Author

Thanks. Rebased onto main cf2c66706. The only conflict was in the test list of main() in GuestKqueue.cpp, where main added WatchKqueue() after UserEvents() at the same spot as this PR's UserEventWakesEveryWaiter(); both calls are kept. Equeue.cpp and the new tests are unchanged.

On the rebased branch both tests pass, 15 times in a row, and abort again at the < 2 s check with only Equeue.cpp from main. The full ctest run has no new failures: the 6 tests that fail on this machine fail the same way with Equeue.cpp from main. The description is updated.

AI-assisted: yes (Claude Code).

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 21, 2026

@ahmadmuj ahmadmuj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed head 2feb074210, merged onto current main 0119103fa9 (clean). Linux (WSL2 Ubuntu 24.04), GCC 13.3, Release. Main has had 24 commits under Equeue/ since this branch's base cf2c66706, so I mostly wanted to know if the fix still holds up on top of them.

What I ran:

  • guest_equeue_events and guest_kqueue on the merged tree: 10/10 each (--repeat until-fail:10).
  • Control, main's Equeue.cpp with this PR's tests: both abort (equeue after 5.5 s, kqueue after 7.3 s, vs 0.6 s / 5.0 s green), which fits the second waiter sitting out its 5 s limit.

Checked on the merged tree:

  • The three sites here plus Close are still the only m_cond notifies. DeleteEvent and RemoveDescriptorEvents only wake pollers, and they don't make anything ready, so nothing's missing. The kqueue NOTE_TRIGGER path ends up in EditEvent.
  • No double delivery with NotifyAll: in CollectTriggered and CollectOncePerWait, EV_CLEAR/EV_DISPATCH/EV_ONESHOT get cleared or erased by whichever waiter collects first, and the others loop back to sleep. AMPR's pendingEvents hands the next queued completion to the second waiter, not the same one again.
  • Timer case: sceKernelAddTimerEvent is EV_CLEAR with a periodic interval, so the second waiter gets the next expiry, not the same one. That matches the 100 ms / 150 ms in the description.
  • FreeBSD 11.4 kern_event.c: kqueue_wakeup calls wakeup(kq), wakeup goes through sleepq_broadcast, there's no wakeup_one anywhere in the file, and non-EV_CLEAR/EV_DISPATCH knotes get re-queued at the tail in kqueue_scan. Your links point at those lines.

Looks right to me.

Not checked: Windows (wachi35676 and screamm covered it on older bases), titles.

@blawesom

Copy link
Copy Markdown
Contributor

Static review plus an independent Linux run (CachyOS, kernel 7.2.10, GCC 16.2.1, Ninja, Release, BUILD_TESTING=ON, Ryzen 7 9800X3D). No findings.

What I checked

  • Three NotifyOne() → NotifyAll() flips in KernelEqueuePrivate::AddEvent / TriggerEvent / EditEvent fix a genuine lost-wake: with N waiters blocked on m_cond, only one would return per event, leaving the rest to spin on their timeout despite a matching trigger. The change is scoped precisely to the three notify sites that represent real queue-state changes; no perf-sensitive hot path is affected beyond the extra wakeup.
  • RequireBothWaitersWake is a real regression test: two threads blocked concurrently, 50ms settle, trigger once, assert both completions arrive within 2s. Covers user-event trigger and timer-add paths in GuestEqueueEvents.cpp, plus the kqueue EvfiltUser/NoteTrigger equivalent in GuestKqueue.cpp. Without the fix this test would deadlock one waiter into its 5s timeout — say so in the message, visible in CI on regression.

Focused test runs

tree guest_equeue_event guest_kqueue
this head 2feb074210 Passed Passed (3.81s)

Both 2/2 Passed on the PR head. Not an AGC/shader/VideoOut change — no paired VVL run required.

@Lindamea1

Copy link
Copy Markdown
Contributor Author

Thanks for the run.

On the failure message: the < 2 s check uses the files' Require, which calls std::abort() without printing anything, so in CI a regression shows as guest_equeue_events or guest_kqueue aborting, with no message about the wait times. The control run in the Tested section shows the cause: with Equeue.cpp from main, the second waiter returns at its 5 s timeout, and both tests abort at that check, after 5.42 s and 6.66 s. I kept the plain Require the neighbouring checks use; if a maintainer wants the check to print both wait times before it aborts, I'll add that.

AI-assisted: yes (Claude Code).

@blawesom

blawesom commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Go with the printing variant, but as the helper upgrade rather than per-check: GuestNetProtocol.cpp already defines the precedent — Require(bool, std::source_location = std::source_location::current()) that prints the line before std::abort(). The same one-line change in GuestEqueueEvents.cpp and GuestKqueue.cpp covers every check in both files, not just the two new ones. With that (or without it — the file-local convention is a silent abort everywhere, so the plain Require is defensible), this is approved from my side: the fix is a precise lost-wake correction, the test reproduces the 5 s-timeout signature, and the rebased head passes 15 consecutive rounds.

@oneandonlydean
oneandonlydean merged commit daad982 into boykopovar:main Nov 13, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

libkernel needs rebase Conflicts with main, rebase needed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants