feat(libkernel): answer sceKernelAddReadEvent and sceKernelAddWriteEvent on regular files #8584

Closed
aarushkha wants to merge 1 commit from upstream-pr/8584 into main
aarushkha commented 2026-10-20 17:25:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by aarushkha on 2026-10-20T17:25:57Z.


What

sceKernelAddReadEvent and sceKernelAddWriteEvent threw for a regular file: they only accepted guest sockets and the read end of a pipe. They now follow FreeBSD 11.4's vnode filters filt_vfsread and filt_vfswrite:

  • A read event reports the file's size less the descriptor's offset in data (negative past the end) and fires while that is not 0.
  • A write event always fires, with data 0.

FreeBSD activates these knotes when the vnode changes. No host call reports every file change, so WaitForDescriptors re-polls an equeue that holds a regular-file event every millisecond (a new KernelFilter::repoll flag), instead of handing the file to poll/WSAPoll. A write made through another descriptor is therefore seen up to 1 ms late. A size argument above 1, directories and other vnode types still throw, as recorded in docs/dev/debt/libkernel.md. Whether the console's own file systems answer these filters as vfs_kqfilter does was not measured.

kevent on regular files is left to #7088, which implements the same FreeBSD filters there. This PR only touches the equeue path (Equeue.cpp), which #7088 does not change. If #7088 lands first, its file classification could replace RegularFile here.

#8523 edits the same lines of WaitForDescriptors, so whichever merges second needs a small rebase.

Tested

Windows 10 Pro (10.0.19045), WinLibs GCC 15.2.0 posix UCRT r7, Release, full build with -DBUILD_TESTING=ON, on main 83751168dd.

  • guest_socket_events has a new RegularFileEvents case: a read event with the offset mid-file (data 8) and at the end (times out), woken when a second descriptor appends 3 bytes (data 3); a write event (data 0); a size of 64 throws; after close the event is gone (ENOENT) and a new add fails with EBADF.
  • With the change, guest_socket_events, guest_kqueue and guest_equeue_events passed 3 of 3 runs each. select_tests, guest_select, guest_kernel_errors, guest_http2, guest_ampr_markers, guest_video_out_hdr and video_out_flip_decode (every other test program that uses equeues or kqueues) pass. The VideoOut flip tests that need a display were skipped, as on CI.
  • With only the new test on main's Equeue.cpp, guest_socket_events aborts (0xc0000409).
  • Not tested: Linux and macOS, and a title.

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

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4939689861 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8584). Originally posted by [aarushkha](https://github.com/aarushkha) on 2026-10-20T17:25:57Z. --- ### What `sceKernelAddReadEvent` and `sceKernelAddWriteEvent` threw for a regular file: they only accepted guest sockets and the read end of a pipe. They now follow FreeBSD 11.4's vnode filters [`filt_vfsread` and `filt_vfswrite`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/sys/kern/vfs_subr.c#L5122-L5168): - A read event reports the file's size less the descriptor's offset in `data` (negative past the end) and fires while that is not 0. - A write event always fires, with `data` 0. FreeBSD activates these knotes when the vnode changes. No host call reports every file change, so `WaitForDescriptors` re-polls an equeue that holds a regular-file event every millisecond (a new `KernelFilter::repoll` flag), instead of handing the file to `poll`/`WSAPoll`. A write made through another descriptor is therefore seen up to 1 ms late. A size argument above 1, directories and other vnode types still throw, as recorded in `docs/dev/debt/libkernel.md`. Whether the console's own file systems answer these filters as `vfs_kqfilter` does was not measured. `kevent` on regular files is left to #7088, which implements the same FreeBSD filters there. This PR only touches the equeue path (`Equeue.cpp`), which #7088 does not change. If #7088 lands first, its file classification could replace `RegularFile` here. #8523 edits the same lines of `WaitForDescriptors`, so whichever merges second needs a small rebase. ### Tested Windows 10 Pro (10.0.19045), WinLibs GCC 15.2.0 posix UCRT r7, Release, full build with `-DBUILD_TESTING=ON`, on `main` `83751168dd`. - `guest_socket_events` has a new `RegularFileEvents` case: a read event with the offset mid-file (`data` 8) and at the end (times out), woken when a second descriptor appends 3 bytes (`data` 3); a write event (`data` 0); a size of 64 throws; after `close` the event is gone (`ENOENT`) and a new add fails with `EBADF`. - With the change, `guest_socket_events`, `guest_kqueue` and `guest_equeue_events` passed 3 of 3 runs each. `select_tests`, `guest_select`, `guest_kernel_errors`, `guest_http2`, `guest_ampr_markers`, `guest_video_out_hdr` and `video_out_flip_decode` (every other test program that uses equeues or kqueues) pass. The VideoOut flip tests that need a display were skipped, as on CI. - With only the new test on `main`'s `Equeue.cpp`, `guest_socket_events` aborts (`0xc0000409`). - Not tested: Linux and macOS, and a title. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes 🤖 Generated with [Claude Code](https://claude.com/claude-code)
github-actions[bot] commented 2026-10-20 17:26:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-20T17:26:17Z.


Thank you for your contribution! Authors with no pull requests merged into main can have 1 open pull request at a time, authors with at least 1 merged can have 20, and from 20 merged there is no limit. This PR has been automatically closed and labeled "open PR limit" because that limit was reached. This is not a judgment of the quality of your changes: reopen it once one of your open pull requests is merged or closed.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6296947636 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8584#issuecomment-6296947636). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-20T17:26:17Z. --- Thank you for your contribution! Authors with no pull requests merged into `main` can have 1 open pull request at a time, authors with at least 1 merged can have 20, and from 20 merged there is no limit. This PR has been automatically closed and labeled "open PR limit" because that limit was reached. This is not a judgment of the quality of your changes: reopen it once one of your open pull requests is merged or closed.
oneandonlydean commented 2026-10-20 17:34:46 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-20T17:34:46Z.


Thanks, the filters match FreeBSD's filt_vfsread/filt_vfswrite, and the repoll doesn't shorten the caller's own timeout. There's one problem on Windows: a lock-order inversion between the new poll and close.

  • The waiter holds the equeue's m_mutex in WaitForEventsUntil → PollEvents → UnreadFileBytes → sceKernelLseek. On Windows, NativeLseek (File/src/Open.cpp, around line 50) takes File::LockPositionedTransfer(fd).
  • sceKernelClose (Open.cpp, around line 293) and close_nid_postfix (Stdio.cpp, around line 695) hold LockPositionedTransfer(d) and then call EqueueDescriptorClosed(d) → RemoveDescriptorEvents, which locks m_mutex.

So closing a regular file while another thread waits on an equeue with a read event on it can deadlock both threads. The 1 ms repoll re-enters that order a thousand times a second. A long read or write on the same descriptor also blocks every equeue operation for its duration, because the poll waits for the positioned lock while holding m_mutex. Linux's NativeLseek takes no lock, so neither a Linux run nor a run without a concurrent close shows it.

Could you avoid calling into the File layer while holding m_mutex? For example, poll the file events after releasing it, or query the size and offset without the positioned lock. Or have the close paths call EqueueDescriptorClosed before they take LockPositionedTransfer. A test where one thread waits at end of file while another closes the descriptor (it should return, not hang) would cover it.

Separately, this conflicts with #8523 in WaitForDescriptors, as you noted.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6297114448 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8584#issuecomment-6297114448). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-20T17:34:46Z. --- Thanks, the filters match FreeBSD's `filt_vfsread`/`filt_vfswrite`, and the repoll doesn't shorten the caller's own timeout. There's one problem on Windows: a lock-order inversion between the new poll and `close`. - The waiter holds the equeue's `m_mutex` in `WaitForEventsUntil` → `PollEvents` → `UnreadFileBytes` → `sceKernelLseek`. On Windows, `NativeLseek` (`File/src/Open.cpp`, around line 50) takes `File::LockPositionedTransfer(fd)`. - `sceKernelClose` (`Open.cpp`, around line 293) and `close_nid_postfix` (`Stdio.cpp`, around line 695) hold `LockPositionedTransfer(d)` and then call `EqueueDescriptorClosed(d)` → `RemoveDescriptorEvents`, which locks `m_mutex`. So closing a regular file while another thread waits on an equeue with a read event on it can deadlock both threads. The 1 ms repoll re-enters that order a thousand times a second. A long read or write on the same descriptor also blocks every equeue operation for its duration, because the poll waits for the positioned lock while holding `m_mutex`. Linux's `NativeLseek` takes no lock, so neither a Linux run nor a run without a concurrent close shows it. Could you avoid calling into the File layer while holding `m_mutex`? For example, poll the file events after releasing it, or query the size and offset without the positioned lock. Or have the close paths call `EqueueDescriptorClosed` before they take `LockPositionedTransfer`. A test where one thread waits at end of file while another closes the descriptor (it should return, not hang) would cover it. Separately, this conflicts with #8523 in `WaitForDescriptors`, as you noted.
aarushkha commented 2026-10-20 18:01:02 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by aarushkha on 2026-10-20T18:01:02Z.


@oneandonlydean Thanks for the review. Both problems are fixed on the branch:

  1. Lock-order deadlock with close (ca3277fe49): sceKernelClose and close_nid_postfix now call EqueueDescriptorClosed before they take LockPositionedTransfer, as dup2 already did. CloseWhileWaitingOnFile in GuestSocketEvents.cpp covers it: a thread keeps waiting on the equeue while another thread opens a file at end of file, adds a read event and closes it, 2000 times. Without the fix it hit ctest's 20 s timeout 3 of 3 times on Windows. With it, it passes in about 0.6 s (10 of 10 runs).

  2. File calls under m_mutex (2d0dbf0fc8): the file read event no longer calls into the File layer while holding m_mutex. Before PollEvents, MeasureFiles copies the read events to measure, releases m_mutex, runs sceKernelFstat and sceKernelLseek, then stores the results under m_mutex. So a long read or write on the descriptor only delays the waiting thread, not other equeue operations. Each file read event keeps its result in its own state object held through filter.owner. A descriptor closed and reused during the measurement gets a new object, so the old file's size is never reported for it. Write events don't touch the file.

With fix 2, the close reorder from fix 1 isn't needed to avoid the deadlock any more. I kept it because it does no harm, but I can drop it if you'd prefer a smaller diff.

Tested on Windows 10 (WinLibs GCC 15.2): guest_socket_events, guest_equeue_events, guest_kqueue, guest_positioned_race, guest_positioned_close, guest_dup, guest_directory_close, guest_file_vector, guest_aio, guest_aio_bad_descriptors, guest_filesystem, guest_posix_filesystem, guest_socket_descriptors, guest_sendfile, file_position and file_streams all pass. check_conventions.py --base origin/main passes. There is no automated test for the long-transfer case, since I couldn't hold a transfer in progress for a set time without making the test unreliable.

The conflict with #8523 in WaitForDescriptors is still there. I'll rebase onto whichever of the two lands first. This PR was closed by the open-PR limit, so I'll reopen it once #8554 is merged or closed.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6297624720 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8584#issuecomment-6297624720). Originally posted by [aarushkha](https://github.com/aarushkha) on 2026-10-20T18:01:02Z. --- @oneandonlydean Thanks for the review. Both problems are fixed on the branch: 1. **Lock-order deadlock with `close`** (ca3277fe49): `sceKernelClose` and `close_nid_postfix` now call `EqueueDescriptorClosed` before they take `LockPositionedTransfer`, as `dup2` already did. `CloseWhileWaitingOnFile` in `GuestSocketEvents.cpp` covers it: a thread keeps waiting on the equeue while another thread opens a file at end of file, adds a read event and closes it, 2000 times. Without the fix it hit ctest's 20 s timeout 3 of 3 times on Windows. With it, it passes in about 0.6 s (10 of 10 runs). 2. **File calls under `m_mutex`** (2d0dbf0fc8): the file read event no longer calls into the File layer while holding `m_mutex`. Before `PollEvents`, `MeasureFiles` copies the read events to measure, releases `m_mutex`, runs `sceKernelFstat` and `sceKernelLseek`, then stores the results under `m_mutex`. So a long read or write on the descriptor only delays the waiting thread, not other equeue operations. Each file read event keeps its result in its own state object held through `filter.owner`. A descriptor closed and reused during the measurement gets a new object, so the old file's size is never reported for it. Write events don't touch the file. With fix 2, the close reorder from fix 1 isn't needed to avoid the deadlock any more. I kept it because it does no harm, but I can drop it if you'd prefer a smaller diff. Tested on Windows 10 (WinLibs GCC 15.2): `guest_socket_events`, `guest_equeue_events`, `guest_kqueue`, `guest_positioned_race`, `guest_positioned_close`, `guest_dup`, `guest_directory_close`, `guest_file_vector`, `guest_aio`, `guest_aio_bad_descriptors`, `guest_filesystem`, `guest_posix_filesystem`, `guest_socket_descriptors`, `guest_sendfile`, `file_position` and `file_streams` all pass. `check_conventions.py --base origin/main` passes. There is no automated test for the long-transfer case, since I couldn't hold a transfer in progress for a set time without making the test unreliable. The conflict with #8523 in `WaitForDescriptors` is still there. I'll rebase onto whichever of the two lands first. This PR was closed by the open-PR limit, so I'll reopen it once #8554 is merged or closed.
aarushkha commented 2026-10-21 09:31:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by aarushkha on 2026-10-21T09:31:36Z.


#8554 is merged, so this is under the open PR limit now. GitHub won't let me reopen a PR the bot closed. Could a maintainer reopen it? The branch already has both review fixes (ca3277fe49, 2d0dbf0fc8).

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6312714444 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8584#issuecomment-6312714444). Originally posted by [aarushkha](https://github.com/aarushkha) on 2026-10-21T09:31:36Z. --- #8554 is merged, so this is under the open PR limit now. GitHub won't let me reopen a PR the bot closed. Could a maintainer reopen it? The branch already has both review fixes (ca3277fe49, 2d0dbf0fc8).
aarushkha commented 2026-10-21 12:14:48 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by aarushkha on 2026-10-21T12:14:48Z.


Since this can't be reopened, I opened a copy as #9099: the same change with both review fixes (MeasureFiles outside m_mutex, and EqueueDescriptorClosed before the position lock in the close paths), rebased on current main and retested. Review can continue there.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6315645860 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8584#issuecomment-6315645860). Originally posted by [aarushkha](https://github.com/aarushkha) on 2026-10-21T12:14:48Z. --- Since this can't be reopened, I opened a copy as #9099: the same change with both review fixes (`MeasureFiles` outside `m_mutex`, and `EqueueDescriptorClosed` before the position lock in the close paths), rebased on current `main` and retested. Review can continue there.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!8584
No description provided.