Skip to content

ev/io_uring: replace fragile FUTEX waker with eventfd multishot poll - #503

Merged
lalinsky merged 1 commit into
mainfrom
fix/494-iouring-waker-eventfd
Jun 22, 2026
Merged

lalinsky merged 1 commit into
mainfrom
fix/494-iouring-waker-eventfd

Conversation

@lalinsky

@lalinsky lalinsky commented Jun 22, 2026 •

Copy link
Copy Markdown
Owner

Problem

On the io_uring backend, latency-bound request/response (e.g. a cold QUIC handshake) was ~4x slower than on epoll (#494). The waker was a FUTEX_WAIT SQE woken cross-thread via futex2_wake. Two separate problems compounded:

  1. Arming window. The FUTEX_WAIT was (re)armed only at the end of poll(), so an executor's first/cold poll blocked with no waiter in the ring. A cross-thread loop.wake() in that window (a .new task scheduled to a sleeping home executor, or any cross-runtime wake) was lost until the 10ms fallback.

  2. Unreliable futex wake delivery. Even with the FUTEX_WAIT armed before blocking, futex2_wake did not reliably wake it. An experiment that armed the waiter before enter2 — fully closing problem Make it possible to use std.crypto.tls.Client #1 — still left ~half of cross-thread wakes ~11ms late. So the arming window is not the whole story: the SHARED-futex → FUTEX_WAIT path itself drops wakes. The SHARED-futex "global hash pivot" workaround already in this file is evidence the path is fragile; the precise remaining kernel interaction isn't pinned down.

epoll has neither problem because its eventfd waker is registered persistently in init and uses ordinary poll readiness.

Fix

Rather than chase the futex behavior, replace the waker with an eventfd registered as a permanent multishot poll (IORING_POLL_ADD_MULTI), mirroring the epoll backend:

  • Armed once in init(); the kernel keeps it armed across wakes (F_MORE), so the loop is never deaf and there's no per-wake re-arming.
  • wake() writes the eventfd; drainWaker() does one coalesced read to clear the level-triggered readiness.
  • A rare F_MORE drop (e.g. CQ overflow) is recovered by the single top-of-poll armWaker(), with a non-blocking enter2 fallback if the SQ is full.
  • Removes the 10ms fallback cap and the SHARED-futex kernel-bug workaround — both no longer needed.

Validation

Minimal repro: one task per executor scheduled onto cold executors, measuring scheduled→running latency.

backend max start-latency
io_uring FUTEX, as-is 11–24 ms
io_uring FUTEX, armed before enter2 ~11 ms (≈half of wakes still slow)
epoll ~0.97 ms
io_uring eventfd multishot (this PR) ~0.7 ms

The middle row is the key evidence: closing the arming window alone is not sufficient — the futex path itself is the problem, and the eventfd waker resolves it.

zig build test -Dbackend=io_uring: no new failures vs baseline.

Fixes #494

@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f5a553bc-1de1-435e-949b-1274cbc9e720

📥 Commits

Reviewing files that changed from the base of the PR and between f6b8d99 and f8eae4b.

📒 Files selected for processing (1)
  • src/ev/backends/io_uring.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/ev/backends/io_uring.zig

📝 Walkthrough

Walkthrough

Replaces the FUTEX-based waker in the io_uring backend with an eventfd-backed multishot poll (IORING_POLL_ADD_MULTI). Adds waker_eventfd to backend state; init/deinit create/close it; wake writes to it; armWaker/drainWaker manage the SQE and CQE drain. poll() timeout and CQE dispatch are updated, and the old explicit end-of-loop rearm step is removed.

Changes

io_uring eventfd multishot waker

Layer / File(s) Summary
State field, imports, and constant docs
src/ev/backends/io_uring.zig
Adds posix import for eventfd syscalls, updates USER_DATA_WAKER/USER_DATA_CANCEL comments to describe the multishot poll mechanism, and adds the waker_eventfd field to the backend struct.
Waker init/deinit/wake/armWaker/drainWaker
src/ev/backends/io_uring.zig
init creates the eventfd and calls armWaker; deinit closes it; wake writes to it; armWaker submits a POLL_ADD_MULTI SQE tagged USER_DATA_WAKER; drainWaker reads the eventfd to clear readiness and sets waker_needs_rearm when the F_MORE flag is absent from the CQE.
poll() timeout, CQE dispatch, and rearm removal
src/ev/backends/io_uring.zig
poll() attempts armWaker every call and forces effective_timeout to zero if arming fails, replacing the previous 10ms fallback cap. Zero-completion path drains pending and returns timeout immediately. Waker CQEs now call drainWaker(cqe) directly. The old explicit end-of-loop rearmWaker call is removed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • lalinsky/zio#205: Modifies the same waker drain/rearm path in io_uring.zig, switching to FUTEX_WAIT/WAKE rearming — the exact mechanism this PR replaces.
  • lalinsky/zio#409: Adjusts poll()/CQE draining and rearmWaker/drainPending ordering in io_uring.zig — structurally adjacent to the rearm removal in this PR.

Poem

An eventfd wakes the sleeping ring,
No futex needed — poll_add's the thing.
F_MORE decides: rearm or not,
Zero timeout when the SQE's forgot.
The handshake latency? No longer slow. 🎯

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: replacing the FUTEX-based waker with an eventfd multishot poll approach to fix cross-thread wakeup latency.
Description check ✅ Passed The description provides clear context on the performance problem, root cause analysis, the proposed solution, and validation results directly related to the code changes.
Linked Issues check ✅ Passed The PR directly addresses issue #494 by replacing the FUTEX waker with eventfd multishot poll, matching the diagnosed solution. Validation metrics confirm the fix resolves the 4× latency regression.
Out of Scope Changes check ✅ Passed All changes are tightly scoped to the waker mechanism: eventfd creation/cleanup, multishot poll setup, wake logic, and drain logic. No unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/494-iouring-waker-eventfd

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

The io_uring waker (a FUTEX_WAIT SQE woken cross-thread via futex2_wake) lost cross-thread wakeups, making latency-bound request/response (e.g. a cold QUIC handshake) ~4x slower than epoll (#494). Two problems compounded:

- The FUTEX_WAIT was (re)armed only at the end of poll(), so an executor's first/cold poll blocked with no waiter in the ring and a cross-thread loop.wake() in that window was lost until the 10ms fallback.
- Even when the FUTEX_WAIT was armed before blocking, futex2_wake did not reliably wake it: an experiment arming the waiter before enter2 (closing the window above) still left ~half of cross-thread wakes ~11ms late. The SHARED-futex global-hash workaround already in this file shows the path is fragile; the remaining interaction is not fully pinned down.

Rather than chase the futex behavior, replace the waker with an eventfd registered as a permanent multishot poll (IORING_POLL_ADD_MULTI), mirroring the epoll backend's persistent eventfd registration:

- Armed once in init(); the kernel keeps it armed across wakes (F_MORE), so the loop is never deaf and there is no per-wake re-arming.
- wake() writes the eventfd; drainWaker() does one coalesced read to clear the level-triggered readiness.
- A rare F_MORE drop is recovered by the top-of-poll armWaker(), with a non-blocking enter2 fallback when the SQ is full.
- Removes the 10ms fallback cap and the SHARED-futex kernel-bug workaround.

Fixes #494
@lalinsky
lalinsky force-pushed the fix/494-iouring-waker-eventfd branch from f6b8d99 to f8eae4b Compare June 22, 2026 09:40
@lalinsky lalinsky changed the title ev/io_uring: fix lost cross-thread wakeups with eventfd multishot waker ev/io_uring: replace fragile FUTEX waker with eventfd multishot poll Jun 22, 2026

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/ev/backends/io_uring.zig (1)

187-187: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Consider asserting armWaker() succeeds in init().

The SQ is empty immediately after ring creation, so this should never fail. An assertion makes that invariant explicit and prevents silent breakage if someone adds SQE submissions before this line later:

-    _ = self.armWaker();
+    std.debug.assert(self.armWaker());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ev/backends/io_uring.zig` at line 187, The `armWaker()` call in the
`init()` function is currently discarding its return value with the blank
identifier pattern. Since the submission queue is empty at this point in
initialization, the call should always succeed. Replace the `_ =
self.armWaker();` line with an assertion that verifies `armWaker()` succeeds,
making this invariant explicit and preventing silent failures if SQE submissions
are added before this call in the future.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/ev/backends/io_uring.zig`:
- Around line 206-207: The constant linux.IORING_POLL_ADD_MULTI does not exist
in Zig's standard library, causing a compilation failure. Replace the current
approach of calling prep_poll_add followed by manually setting sqe.len with a
direct call to Zig's built-in prep_poll_multishot() method. Pass the same
parameters (self.waker_eventfd and linux.POLL.IN) to this function instead,
which handles multishot polling in the intended way.

---

Nitpick comments:
In `@src/ev/backends/io_uring.zig`:
- Line 187: The `armWaker()` call in the `init()` function is currently
discarding its return value with the blank identifier pattern. Since the
submission queue is empty at this point in initialization, the call should
always succeed. Replace the `_ = self.armWaker();` line with an assertion that
verifies `armWaker()` succeeds, making this invariant explicit and preventing
silent failures if SQE submissions are added before this call in the future.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8f743413-567d-400b-9726-3b6682624948

📥 Commits

Reviewing files that changed from the base of the PR and between c1f7286 and f6b8d99.

📒 Files selected for processing (1)
  • src/ev/backends/io_uring.zig

Comment on lines +206 to +207
sqe.prep_poll_add(self.waker_eventfd, linux.POLL.IN);
sqe.len = linux.IORING_POLL_ADD_MULTI;

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if IORING_POLL_ADD_MULTI is defined in Zig's std.os.linux
rg -n "IORING_POLL_ADD_MULTI" --type zig

Repository: lalinsky/zio

Length of output: 132


🏁 Script executed:

head -50 src/ev/backends/io_uring.zig

Repository: lalinsky/zio

Length of output: 2742


🏁 Script executed:

rg -n "const linux|`@import`.*linux" src/ev/backends/io_uring.zig --type zig -A 2

Repository: lalinsky/zio

Length of output: 662


🏁 Script executed:

rg -n "IORING_POLL" --type zig

Repository: lalinsky/zio

Length of output: 132


🌐 Web query:

IORING_POLL_ADD_MULTI Zig std.os.linux constant

💡 Result:

The constant IORING_POLL_ADD_MULTI is a Linux kernel flag used to enable multishot mode for io_uring poll operations [1][2]. While it is a fundamental Linux kernel constant defined for the io_uring interface [1][3], it is not typically exposed as a direct constant within Zig's std.os.linux namespace. In Zig, you can utilize this flag by applying it to the length (len) field of the submission queue entry (SQE) [4]. Usage in Zig: When preparing a poll request, you can set the flag manually: const IORING_POLL_ADD_MULTI = 1; // 1U << 0 sqe.len |= IORING_POLL_ADD_MULTI; Alternatively, the standard library often provides higher-level helper functions. Instead of manually manipulating SQE fields, it is recommended to use the provided prep function, which abstracts the multishot configuration [5][4]: // Use the built-in multishot preparation function sqe.prep_poll_multishot(fd, poll_mask); When using multishot mode, the kernel will generate multiple completion queue entries (CQEs) for a single submitted SQE [1][4]. These CQEs will include the IORING_CQE_F_MORE flag to signal that the application should expect further notifications for that request [1][4].

Citations:


IORING_POLL_ADD_MULTI is not defined in Zig's std.os.linux—this will fail to compile.

The constant doesn't exist in the standard library. You need to either define it locally as const IORING_POLL_ADD_MULTI = 1; or better yet, use Zig's built-in prep_poll_multishot() function instead of manually manipulating sqe.len. The latter is the intended approach and cleaner.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ev/backends/io_uring.zig` around lines 206 - 207, The constant
linux.IORING_POLL_ADD_MULTI does not exist in Zig's standard library, causing a
compilation failure. Replace the current approach of calling prep_poll_add
followed by manually setting sqe.len with a direct call to Zig's built-in
prep_poll_multishot() method. Pass the same parameters (self.waker_eventfd and
linux.POLL.IN) to this function instead, which handles multishot polling in the
intended way.

@lalinsky
lalinsky merged commit be93fa4 into main Jun 22, 2026
28 checks passed
@lalinsky
lalinsky deleted the fix/494-iouring-waker-eventfd branch June 22, 2026 10:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

io_uring backend: QUIC handshake ~4x slower than epoll (event loop over-sleeps in latency-bound request/response)

1 participant