Skip to content

ev/io_uring: arm boot/real timers natively - #516

Merged
lalinsky merged 2 commits into
mainfrom
clock-iouring-native
Jun 24, 2026
Merged

lalinsky merged 2 commits into
mainfrom
clock-iouring-native

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Follows the per-clock timer heaps work (#515). With those, boot/real timers fire correctly on every backend via a capped poll-timeout fallback. This makes io_uring arm them natively so they're exact rather than bounded by the cap.

What

  • New native_wall_timers backend capability. When set, checkTimers stops folding boot/real deadlines into the poll timeout (no 10s cap) and instead hands the per-clock heap minimums to backend.syncWallTimers(boot, real).
  • io_uring arms one IORING_OP_TIMEOUT SQE per active wall clock with IORING_TIMEOUT_ABS | BOOTTIME/REALTIME. The kernel re-evaluates these across suspend and clock steps, so boot/real fire exactly. A fired timeout (-ETIME) makes poll report a timeout so the loop re-runs checkTimers; re-arming on a changed deadline cancels the old SQE first.
  • All gated by the comptime capability — other backends keep the capped fallback untouched.

SQ-full handling

Mirrors the existing waker: if armWall can't get an SQE, it sets wall_needs_rearm and poll uses a zero timeout so the enter2 drains the SQ and the next scan re-arms. Per-timer armed state lives in wall_armed[idx]; the bool is only the "don't block" gate (an OR over the two timers), so a partial failure stays flagged and the already-armed timer is left untouched. Bounded to one non-blocking cycle, never a blocking wait or a spin.

Kernel requirement

No extra gate: the ring already requires ≥6.1 (DEFER_TASKRUN), and the BOOTTIME/REALTIME timeout flags are ≥5.15, so they're always available where this backend runs.

Testing

  • io_uring (native) and epoll (fallback): full suite 492/492 on each.
  • The boot/real/deadline sleep + timer tests now exercise the native SQE path on io_uring.

Not covered

The "exact across suspend/clock-step" behavior relies on the kernel's hrtimer semantics and isn't unit-tested (suspend isn't reproducible in a unit test). epoll/kqueue/IOCP native arming remain future work.

…llback

Add a native_wall_timers backend capability. When set, checkTimers stops
folding boot/real deadlines into the poll timeout (no 10s cap) and instead
hands the per-clock heap minimums to the backend via syncWallTimers.

io_uring arms one IORING_OP_TIMEOUT SQE per active wall clock with
IORING_TIMEOUT_ABS | BOOTTIME/REALTIME (both >= 5.15; the ring already
requires 6.1+ for DEFER_TASKRUN). The kernel re-evaluates these across
suspend and clock steps, so boot/real timers fire exactly rather than
within the cap. A fired timeout (-ETIME) makes poll report a timeout so
the loop re-runs checkTimers; re-arming on a changed deadline cancels the
old SQE first. Other backends keep the capped fallback unchanged.

Tested on io_uring (native) and epoll (fallback): full suite green on both.
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The io_uring backend now arms wall-clock timers natively via absolute-deadline IORING_OP_TIMEOUT SQEs instead of folding them into poll timeouts. A new BackendCapabilities.native_wall_timers flag gates the feature. The backend encodes special user_data schemes to track wall-timer generations, exposes syncWallTimer(clock, deadline) to arm/disarm per-clock timers, and updates poll() to dispatch wall-timer CQEs and propagate wall_fired to the loop. Loop.checkTimers now delegates boot and real clock deadlines to the backend when the capability is enabled, with poll-timeout fallback when arming fails.

Changes

Native wall-clock timer support

Layer / File(s) Summary
Capability definition and special user_data encoding
src/ev/completion.zig, src/ev/backends/io_uring.zig
BackendCapabilities adds native_wall_timers: bool = false. io_uring introduces UD_SPECIAL + SpecialKind + generation helpers to replace fixed sentinels and enable wall-timer generation tracking.
Backend state, capability flag, and SQE updates
src/ev/backends/io_uring.zig
io_uring sets native_wall_timers = true, adds wall_armed deadlines, wall_generation counters, and wall_ts kernel_timespec storage, and updates waker/cancel SQE user_data to use the encoded special scheme.
Wall timer arm/disarm interface
src/ev/backends/io_uring.zig
syncWallTimer(clock, deadline) submits absolute IORING_OP_TIMEOUT SQEs, removes prior timeouts before re-arming, bumps wall generation, and returns false when unable to allocate SQEs.
CQE handling and timer completion propagation
src/ev/backends/io_uring.zig
poll() processes special-encoded CQEs: drains waker, skips cancel/remove, and on wall-timer CQEs sets wall_fired when res == -ETIME, generation matches, and the timer is armed. Return value changes to wall_fired instead of a constant.
Loop integration with timer delegation
src/ev/loop.zig
checkTimers initializes per-clock deadline tracking, records earliest absolute deadlines for native-wall clocks during heap scan without updating next_timeout, then calls backend.syncWallTimer() for boot/real domains. Falls back to poll-timeout folding if the backend cannot arm.
Test updates
src/ev/test/timer.zig
Boot and real clock timer test names drop the "fallback path" qualifier.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • lalinsky/zio#515: The per-wall-clock timer-heap implementation and deadline-selection logic this PR extends directly.
  • lalinsky/zio#503: Overlaps at the io_uring waker signaling and user_data-encoded CQE plumbing layer.
  • lalinsky/zio#181: Earlier Loop.checkTimers changes and the fired state that drives how the loop computes wait timeouts—same code path this PR builds on.

Poem

An SQE for the boot clock, one for the real,
No more folding wall time into poll's next meal.
syncWallTimer submits, wall_fired returns true,
checkTimers offloads—the kernel knows what to do.
⏰ The deadline lives in the kernel now. 🦾

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main change: io_uring backend now arms boot/real wall-clock timers natively using IORING_OP_TIMEOUT operations instead of relying on poll timeout fallbacks.
Description check ✅ Passed The description is directly related to the changeset, explaining the what, why, and implementation details of native wall timer arming, SQ-full handling, kernel requirements, and testing outcomes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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 clock-iouring-native

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.

@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: 2

🤖 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 18-19: The USER_DATA_WALL_BOOT and USER_DATA_WALL_REAL constants
use fixed sentinel values that cannot distinguish between different timeout
instances, causing old timeout completions to interfere with current timeouts
and incorrectly clear wall_armed. Modify the user_data encoding to include a
generation counter alongside the clock tag by using the low 2 bits for the clock
identifier and the remaining bits for a generation counter. Increment the
generation counter when re-arming a timeout (around line 796), use the previous
generation value when canceling a timeout (around line 779), and add a
generation validation check before treating a timeout completion as current (in
the verification logic around lines 866-870) to ensure the arriving CQE matches
the currently armed timeout generation.
- Around line 809-811: The issue is that drainPending() continues to consume SQ
space even when internal SQEs need to be armed (wall timer or waker), causing a
cycle where critical re-arms fail repeatedly. Skip calling drainPending()
whenever wall_needs_rearm or waker_needs_rearm is set, so that SQ space is
reserved for the critical internal operations to get their SQEs on the next
poll. Apply this fix at all locations where drainPending() is called in the poll
function, including the areas around line 844-847 and 899-903 in addition to the
current location on line 811.
🪄 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: 2c4812f8-df3c-4ed5-ba93-4d2c87b03bf9

📥 Commits

Reviewing files that changed from the base of the PR and between 48c4fc5 and 6ed13e2.

📒 Files selected for processing (4)
  • src/ev/backends/io_uring.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/test/timer.zig

Comment thread src/ev/backends/io_uring.zig Resolved
Comment thread src/ev/backends/io_uring.zig Resolved
Two issues from the #516 review:

- Generation race in the wall-timer user_data. Reusing a fixed sentinel
  per (re)arm meant a stale timeout CQE arriving after a re-arm could clear
  the current wall_armed and leak a duplicate SQE. user_data now uses the
  low bit to tell internal ops from *Completion pointers (which are aligned)
  and packs a kind + generation; a stale generation is ignored on the CQE.

- drainPending starved the wall re-arm. The wall_needs_rearm / zero-timeout
  hack couldn't make progress because drainPending refills the SQ before the
  next checkTimers re-arms. Replaced with a fold fallback: syncWallTimer is
  now per-clock and returns whether it armed; on false the loop folds that
  clock's capped remaining into the poll timeout, so it re-evaluates within
  the cap regardless of SQ pressure.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/ev/backends/io_uring.zig (1)

779-820: 🎯 Functional Correctness | 🔴 Critical

The IORING_TIMEOUT_BOOTTIME and IORING_TIMEOUT_REALTIME constants are not defined in Zig's standard library and must be manually declared in this project.

The arm/disarm + generation flow is sound, and prep_timeout_remove is confirmed available in std.os.linux.io_uring_sqe. However, the code at lines 786 and 789 references linux.IORING_TIMEOUT_BOOTTIME and linux.IORING_TIMEOUT_REALTIME, which the Zig stdlib does not provide. These constants (and IORING_TIMEOUT_ABS at line 815) need to be manually defined locally in your project—typically as:

pub const IORING_TIMEOUT_BOOTTIME: u32 = 4;
pub const IORING_TIMEOUT_REALTIME: u32 = 8;
pub const IORING_TIMEOUT_ABS: u32 = 1;

Ensure these definitions exist in your linux namespace or wherever you're importing them from, or the code will not compile.

🤖 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 779 - 820, The syncWallTimer
function references three io_uring timeout constants (IORING_TIMEOUT_BOOTTIME,
IORING_TIMEOUT_REALTIME, and IORING_TIMEOUT_ABS) at lines 786, 789, and 815 that
are not provided by Zig's standard library. You need to define these constants
in your project's linux namespace with the values IORING_TIMEOUT_BOOTTIME as 4,
IORING_TIMEOUT_REALTIME as 8, and IORING_TIMEOUT_ABS as 1, then ensure the linux
namespace in syncWallTimer can access these definitions. Add these constant
definitions to whichever file or module provides the linux namespace that the
io_uring backend is using.
🤖 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.

Outside diff comments:
In `@src/ev/backends/io_uring.zig`:
- Around line 779-820: The syncWallTimer function references three io_uring
timeout constants (IORING_TIMEOUT_BOOTTIME, IORING_TIMEOUT_REALTIME, and
IORING_TIMEOUT_ABS) at lines 786, 789, and 815 that are not provided by Zig's
standard library. You need to define these constants in your project's linux
namespace with the values IORING_TIMEOUT_BOOTTIME as 4, IORING_TIMEOUT_REALTIME
as 8, and IORING_TIMEOUT_ABS as 1, then ensure the linux namespace in
syncWallTimer can access these definitions. Add these constant definitions to
whichever file or module provides the linux namespace that the io_uring backend
is using.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0ff7a481-42f5-4f34-bd7a-8b65fcb328dc

📥 Commits

Reviewing files that changed from the base of the PR and between 6ed13e2 and 696f809.

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

@lalinsky
lalinsky merged commit b382f5b into main Jun 24, 2026
28 checks passed
@lalinsky
lalinsky deleted the clock-iouring-native branch June 24, 2026 05:03
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.

1 participant