API reference
An io_uring completion loop for Zig: one ring, one tick, and a user_data type you define.
io_uring is the architecture here, not a driver choice. Every operation is a submission that completes later, and the loop's job is the part std does not do: when to submit, when to enter, and what runs when.
The tag is yours. Loop(Tag) takes any 64-bit type — a packed struct of
op/slot/generation, a *Node, a bare u64 — and never interprets it. The
caller decides what a completion is; the loop only decides when.
const std = @import("std");
const uring = @import("uring");
const Tag = packed struct(u64) { op: u8, slot: u16, gen: u16, spare: u24 };
var cqes: [64]std.os.linux.io_uring_cqe = undefined;
var loop: uring.Loop(Tag) = try .init(.{ .cqes = &cqes });
defer loop.deinit();
_ = try loop.recv(.{ .op = 1, .slot = 7, .gen = 1 }, fd, .{ .buffer = buf }, 0);
try loop.tick(&app, App.onCompletion, .{ .until = loop.now() + 10 * std.time.ns_per_ms });
The loop never closes a descriptor, never frees a byte, and never rearms an operation. Those are the caller's calls, which is what lets one loop serve a proxy, a database, and a test.
Coverage
Every operation std.os.linux.IoUring encodes has a wrapper here, and the
wrapper takes the caller's tag in place of a raw user_data: accept
(single, multishot, direct), connect, bind, listen, socket (plain, direct,
direct-alloc), send, sendmsg, send_zc (plain and fixed), recv, recvmsg,
recv_multishot, read, read_fixed, write, writev, write_fixed, close,
close_direct, fsync, fallocate, statx, splice, openat (plain and direct),
renameat, unlinkat, mkdirat, symlinkat, linkat, waitid, epoll_ctl, timeout,
link_timeout, timeout_remove, poll_add, poll_remove, poll_update, cancel,
shutdown, nop, provide_buffers, remove_buffers, and URING_CMD on a socket
(cmd_sock, setsockopt, getsockopt).
Ring covers what the kernel lets a ring register: files (plain, sparse,
alloc-range, update, unregister), buffers, eventfd (plain and async), NAPI,
and the probe (Ring.supports asks it about an op).
Provided buffers are BufferGroup plus recvMultishot, bufferGet, and
bufferPut.
Not encoded, because std does not encode them: msg_ring, futex_wait,
futex_wake, futex_waitv, tee, madvise, openat2,
timeout_update, and a generic URING_CMD for non-socket commands.
Registration that std does not expose either: personalities,
restrictions, iowq worker limits, sync_cancel, clamp, pbuf_status,
and files_update2. Those need an SQE or a registration built by hand; the
sqe() escape hatch is where that goes.
type fn
Loop
src
pub const Loop = @import("loop.zig").Loop
Fields
ring: Ring
cqes: []linux.io_uring_cqe
deferred: []Tag
deferred_head: usize = 0
deferred_len: usize = 0
deferred_stopped: bool = false
sq_floor: u16
now_ns: i64 = 0
stopped: bool = false
stats: Stats = .zero
Constants
Functions
The tag as the ring sees it. @bitCast for everything that is
exactly 64 bits, @ptrToInt for a pointer.
The loop's view of one kernel completion. For a caller that copies
the completion queue itself instead of going through tick, which
is the only other place that decodes a tag from a CQE.
The monotonic timestamp of this tick, in nanoseconds. It is read once per tick, after the enter, so it is also the moment the kernel finished the work the tick waited on. Every timestamp a handler takes from here agrees within one tick.
Ask the loop to finish. run honors this at its next tick
boundary, and the batch it is in still drains: a completion that
arrived is work that happened. A caller that drives tick itself
reads stopped and decides, which is what lets a shutdown keep
serving its last connections.
Idempotent on purpose: two completions in one batch can each decide the loop is done, and that is not a bug in the caller.
Post tag for dispatch on the next tick, as though it completed.
A post from inside a handler runs one tick later, never in the
middle of the current batch.
Dispatch tag on the next tick, as though a completion had
arrived for it: the handler sees res zero, no flags, and
Cqe.deferred set. Nothing is submitted, and the kernel is not
involved; this is the loop's one synthetic completion.
A nextTick from inside a handler runs one tick later, so work
that arrived while dispatching cannot extend the current pass. The
queue is the caller's slice from Options.deferred, and a full
queue returns error.DeferredFull rather than dropping the tag.
pub fn stopDeferred(self: *Self) void
src
End this pass's deferred dispatch, leaving the rest of the queue in place and in order. A handler that cannot take any more deferred work this pass calls this instead of deferring the remainder again: deferring moves them behind whatever arrived during the pass, which starves them under a steady arrival rate. The next pass resumes at the same head.
It takes effect after the current handler returns, and the tag that handler was given has already been popped: a caller must finish its work, then stop. Stopping instead of working consumes that tag undriven.
pub fn tickStarting(
self: *Self,
ctx: anytype,
comptime before_dispatch: anytype,
comptime handler: anytype,
wait: Wait,
) !Tick
src
tick, with a function called once per pass after the enter and
before the first handler, receiving the pass's settled facts.
more
A caller whose handlers read a cached clock needs exactly this
point: refreshing after tick returns is too late, because every
handler has already run on the previous pass's sample, and
refreshing before the tick is too early, because it would stamp an
idle worker's first post-wake work with the park-start time.
before_dispatch is fn (ctx: anytype, loop: *Self, done: Tick) void, known at comptime; pass null for none.
tick until stop. The waiting mode is comptime, so a run that
never blocks pays no branch for it.
more
Wait.until is one absolute deadline for the whole run, not a
timeout per tick: the value is fixed when run is called, so
.{ .until = now + 50ms } means "run for 50 ms" and spins after
that. A deadline that moves, such as a connection's idle timeout,
means calling tick in the caller's own loop with a deadline
computed from the loop's clock each pass.
A blank SQE with this tag: the escape hatch for an operation the loop does not wrap. The caller sets the opcode and its arguments, and the loop submits it at the end of the tick.
pub fn acceptMultishot(
self: *Self,
tag: Tag,
fd: linux.fd_t,
addr: ?*posix.sockaddr,
addrlen: ?*posix.socklen_t,
flags: u32,
) !*linux.io_uring_sqe
src
A multishot accept. Every completion keeps IORING_CQE_F_MORE set
until the operation ends, so one accept answers many connections.
Close a descriptor on the ring. The caller still owns the lifetime question: the kernel borrows buffers until the operation completes, so a slot can only be reused after this completion lands.
Cancel a request by its tag. A cancel finds only requests the kernel already holds, so the queued submissions go out first: without that, cancelling an operation armed moments ago returns ENOENT and the target runs on.
pub fn timeout(
self: *Self,
tag: Tag,
deadline: *const linux.kernel_timespec,
count: u32,
flags: u32,
) !*linux.io_uring_sqe
src
One IORING_OP_TIMEOUT, for a caller that wants the kernel to own
the clock. The loop's own deadlines ride the enter and need no
operation; this exists for a deadline that outlives one tick or
must fire while the loop is busy.
pub fn splice(
self: *Self,
tag: Tag,
fd_in: linux.fd_t,
off_in: u64,
fd_out: linux.fd_t,
off_out: u64,
len: usize,
) !*linux.io_uring_sqe
src
Both ends registered: IOSQE_FIXED_FILE on each, and the offsets
are ignored (io_uring splices at the file positions).
pub fn readFixed(
self: *Self,
tag: Tag,
fd: linux.fd_t,
buffer: *posix.iovec,
offset: u64,
buffer_index: u16,
) !*linux.io_uring_sqe
src
buffer must have been registered with ring.registerBuffers, and
buffer_index is its index there.
pub fn writeFixed(
self: *Self,
tag: Tag,
fd: linux.fd_t,
buffer: *posix.iovec,
offset: u64,
buffer_index: u16,
) !*linux.io_uring_sqe
src
pub fn accept(
self: *Self,
tag: Tag,
fd: linux.fd_t,
addr: ?*posix.sockaddr,
addrlen: ?*posix.socklen_t,
flags: u32,
) !*linux.io_uring_sqe
src
A single accept. acceptMultishot above is the one that keeps
producing completions from one SQE.
pub fn acceptDirect(
self: *Self,
tag: Tag,
fd: linux.fd_t,
addr: ?*posix.sockaddr,
addrlen: ?*posix.socklen_t,
flags: u32,
file_index: u32,
) !*linux.io_uring_sqe
src
Accept into registered file slot file_index (see
ring.registerFiles), or IORING_FILE_INDEX_ALLOC to let the
kernel pick.
pub fn acceptMultishotDirect(
self: *Self,
tag: Tag,
fd: linux.fd_t,
addr: ?*posix.sockaddr,
addrlen: ?*posix.socklen_t,
flags: u32,
) !*linux.io_uring_sqe
src
pub fn sendZc(
self: *Self,
tag: Tag,
fd: linux.fd_t,
buffer: []const u8,
send_flags: u32,
zc_flags: u16,
) !*linux.io_uring_sqe
src
Zerocopy send. Produces two completions: the result, then a
notification (IORING_CQE_F_NOTIF) that the buffer is free.
pub fn sendZcFixed(
self: *Self,
tag: Tag,
fd: linux.fd_t,
buffer: []const u8,
send_flags: u32,
zc_flags: u16,
buffer_index: u16,
) !*linux.io_uring_sqe
src
pub fn openatDirect(
self: *Self,
tag: Tag,
dir_fd: linux.fd_t,
path: [*:0]const u8,
flags: linux.O,
mode: posix.mode_t,
file_index: u32,
) !*linux.io_uring_sqe
src
Open into registered file slot file_index.
pub fn closeDirect(self: *Self, tag: Tag, file_index: u32) !*linux.io_uring_sqe
src
Close registered file slot file_index.
pub fn timeoutRemove(
self: *Self,
tag: Tag,
target: Tag,
flags: u32,
) !*linux.io_uring_sqe
src
Cancel a timeout armed with timeout by its tag.
pub fn linkTimeout(
self: *Self,
tag: Tag,
deadline: *const linux.kernel_timespec,
flags: u32,
) !*linux.io_uring_sqe
src
A timeout linked to the SQE before it, so it fires only if that operation has not completed.
pub fn pollRemove(self: *Self, tag: Tag, target: Tag) !*linux.io_uring_sqe
src
pub fn pollUpdate(
self: *Self,
tag: Tag,
old: Tag,
new: Tag,
poll_mask: u32,
flags: u32,
) !*linux.io_uring_sqe
src
pub fn socketDirect(
self: *Self,
tag: Tag,
domain: u32,
socket_type: u32,
protocol: u32,
flags: u32,
file_index: u32,
) !*linux.io_uring_sqe
src
Socket into registered file slot file_index.
pub fn socketDirectAlloc(
self: *Self,
tag: Tag,
domain: u32,
socket_type: u32,
protocol: u32,
flags: u32,
) !*linux.io_uring_sqe
src
Socket into a slot the kernel picks (IORING_FILE_INDEX_ALLOC).
The completion's res is the index.
pub fn cmdSock(
self: *Self,
tag: Tag,
cmd_op: linux.IO_URING_SOCKET_OP,
fd: linux.fd_t,
level: u32,
optname: u32,
optval: u64,
optlen: u32,
) !*linux.io_uring_sqe
src
IORING_OP_URING_CMD on a socket: the only uring_cmd std encodes.
pub fn setsockopt(
self: *Self,
tag: Tag,
fd: linux.fd_t,
level: u32,
optname: u32,
opt: []const u8,
) !*linux.io_uring_sqe
src
pub fn getsockopt(
self: *Self,
tag: Tag,
fd: linux.fd_t,
level: u32,
optname: u32,
opt: []u8,
) !*linux.io_uring_sqe
src
pub fn recvMultishot(
self: *Self,
tag: Tag,
group: *BufferGroup,
fd: linux.fd_t,
flags: u32,
) !*linux.io_uring_sqe
src
Multishot receive over a provided-buffer group: one SQE, one
IORING_CQE_F_BUFFER completion per buffer the kernel fills, until
the operation ends. Return the buffer with bufferPut.
The bytes a provided-buffer completion filled, by its buffer id.
Give the buffer back to the kernel. Incremental consumption
(IORING_CQE_F_BUF_MORE) is handled by the ring: the kernel keeps
writing at the same offset until the buffer is whole.
pub fn provideBuffers(
self: *Self,
tag: Tag,
buffers: [*]u8,
buffer_size: usize,
buffers_count: usize,
group_id: usize,
buffer_id: usize,
) !*linux.io_uring_sqe
src
Give a buffer group to the kernel the old way, one
IORING_OP_PROVIDE_BUFFERS per call. BufferGroup uses the
registered ring instead; this exists for the op itself.
pub fn removeBuffers(
self: *Self,
tag: Tag,
buffers_count: usize,
group_id: usize,
) !*linux.io_uring_sqe
src
Take back buffers provided with provideBuffers.
Types
struct
Options
src
Fields
entries: u16 = 256
Submission queue depth. Must be a power of two.
setup: Ring.Setup = Ring.default_setup
Ring setup. The default is deferred completions with a single
issuer; a mask the kernel refuses fails at init.
cqes: []linux.io_uring_cqe
Where completions land before dispatch. Sized by the caller: the loop allocates nothing and holds nothing back. Bigger batches mean fewer enters and more work per tick.
deferred: []Tag = &.{}
The deferred queue: one slot per tag waiting for nextTick. A
zero-length slice disables nextTick.
sq_floor: u16 = 8
Flush the submission queue once this many slots are left. A
prep that finds the queue full retries once and then fails
with error.SubmissionQueueFull, so the loop publishes early
rather than at the edge.
struct
Cqe
src
Fields
tag: Tag
res: i32
The kernel's result: bytes moved, a descriptor, or a negative errno. Decoding it is the caller's business, because only the caller knows which operation it armed.
flags: u32
deferred: bool = false
True when the loop synthesized this with nextTick: no kernel
operation finished, and res is zero.
Functions
The errno in res, or .SUCCESS. An io_uring result uses the
syscall convention, so this is the std decoder and not a
second copy of it.
The operation that produced this completion is still armed and will produce more: a multishot accept or receive.
The selected buffer group's id, for a receive that used buffer selection.
union
Wait
src
pub const Wait = union(enum)
How long one tick may spend waiting for work.
Fields
poll poll
Enter on every pass, even when completions are already visible, and never wait. Under DEFER_TASKRUN only an enter runs the kernel's deferred completions, so a caller whose completion queue never empties needs this or starves them.
no_wait no_wait
Copy what is ready, enter only when nothing is, and never block. The cheap pass for a caller with no such starvation.
once once
Block until a completion arrives.
until: i64
Block until a completion arrives or at_ns passes on the
monotonic clock, whichever comes first.
struct
Tick
src
One tick: wait, reap, dispatch, defer, submit.
more
handler is fn (ctx: anytype, loop: *Self, cqe: Cqe) !void, known
at comptime, so each completion is a direct call with no function
pointer and no erased context. An error from it is returned from
the tick, and the loop keeps no restart policy: the caller decides.
What one tick did, for a caller whose policy depends on it: a
busy-poll gate needs the gap, and the DEFER_TASKRUN rule needs to
know the kernel ran its deferred completions.
Fields
cqes: u32
Completions from the kernel this tick.
deferred: u32
Deferred tags this tick.
entered: bool
The tick made a GETEVENTS enter. Under DEFER_TASKRUN this is the only way the kernel runs deferred completions.
waited: bool
That enter blocked for a completion or a deadline.
start_ns: i64
When the tick started, before the enter.
now_ns: i64
When the kernel's work became visible: after the enter, or the
tick's start when it did not enter. now_ns - start_ns is what
the tick spent entering and dispatching.
module
Ring
src
The ring, and the one syscall std cannot make for us.
more
std.os.linux.IoUring encodes every SQE this library submits and owns both
queues. What it cannot do is wait with a deadline: linux.io_uring_enter
hardcodes the extended-argument size, so no io_uring_getevents_arg fits
through it and a kernel timeout needs an IORING_OP_TIMEOUT SQE plus a
cancel to move it. This file adds that enter, and the submit bookkeeping
around it. It re-implements no SQE: prep_* on the standard SQE is the one
encoding, and it overwrites the whole 64 bytes, so a reused slot carries no
stale IOSQE_ bit into the next operation.
One thread owns a ring, submits on it, and enters it. DEFER_TASKRUN makes
that a kernel requirement, not a convention.
Fields
Constants
pub const RecvBuffer = linux.IoUring.RecvBuffer
src
pub const ReadBuffer = linux.IoUring.ReadBuffer
src
pub const default_setup: Setup = …
src
value
.{
.single_issuer = true,
.defer_taskrun = true,
}What this loop wants by default: completions deferred to the submit-side enter, one issuer. The kernel requires the pair, and it is the configuration the loop's timings were measured with.
pub const EnterError = …
src
value
error{
/// The kernel ran out of memory or resources. Wait for completions and retry.
SystemResources,
FileDescriptorInvalid,
FileDescriptorInBadState,
/// Too many requests in flight. Wait for completions and retry.
CompletionQueueOvercommitted,
SubmissionQueueEntryInvalid,
BufferInvalid,
RingShuttingDown,
OpcodeNotSupported,
/// GETEVENTS came from a thread that does not own the ring.
InvalidThread,
/// Interrupted before `min_complete`. Nothing is lost; CQEs stay queued.
SignalInterrupt,
/// An errno the enter has no case for.
Unexpected,
}value
error{
/// The kernel has no IORING_FEAT_EXT_ARG, so `enter` cannot take a
/// deadline. 5.11 or newer.
KernelTooOld,
}Functions
SQEs prepped but not published yet.
The room left in the submission queue.
pub fn registerFiles(self: *Ring, fds: []const linux.fd_t) !void
src
Register fds so operations can name them by index with
IOSQE_FIXED_FILE instead of paying an fd-table lookup per operation.
The result of assigning a file is unusable: the kernel has taken the
reference, and the caller's fd must close it when it is done.
pub fn registerFilesUpdate(self: *Ring, offset: u32, fds: []const linux.fd_t) !void
src
Replace fds.len slots starting at offset.
pub fn registerFilesSparse(self: *Ring, fd_count: u32) !void
src
Reserve fd_count slots without naming any file: the indexes can be
filled later by operations that create a file (*Direct) or by
registerFilesUpdate.
pub fn registerFileAllocRange(self: *Ring, offset: u32, len: u32) !void
src
Bind slot offset for len slots to the kernel's file-index allocator,
so IORING_FILE_INDEX_ALLOC lands in that range.
pub fn unregisterFiles(self: *Ring) !void
src
pub fn registerBuffers(self: *Ring, buffers: []const posix.iovec) !void
src
Register buffers for readFixed/writeFixed/sendZcFixed.
pub fn unregisterBuffers(self: *Ring) !void
src
pub fn registerEventfd(self: *Ring, fd: linux.fd_t) !void
src
The ring posts a completion on fd (an eventfd) each time one arrives, so
a thread that is not entering the ring can still be woken by it.
pub fn registerEventfdAsync(self: *Ring, fd: linux.fd_t) !void
src
As registerEventfd, but the wakeup happens before the CQE is posted.
pub fn unregisterEventfd(self: *Ring) !void
src
pub fn registerNapi(self: *Ring, napi: *linux.io_uring_napi) !void
src
NAPI busy polling for the given NAPI ids.
pub fn unregisterNapi(self: *Ring) !void
src
What this kernel's ring supports. Ask before choosing an op or a flag if the deployment target's kernel is not known.
True when the ring can do op on this kernel.
A blank SQE whose user_data is the caller's. The escape hatch: every
operation the loop does not wrap is still one prep_* away.
Publish the queued SQEs. Never blocks and never waits for a completion.
It always enters, even with nothing obvious to publish: SQE prep can happen
through inner without the ring noticing, so a conditional submit would
strand those operations. std's submit is the contract.
Run the completions the kernel deferred without waiting for one. Under DEFER_TASKRUN these run only inside an enter, so an empty completion queue is not proof that there is no work.
A signal cannot interrupt anything here: the enter asks for no completion
and waits for nothing, so SignalInterrupt is absorbed rather than handed
to every caller. wait still reports it.
Block until min_complete completions arrive, the deadline passes, or a
signal interrupts. timeout_ns is relative to the call; null waits
without a deadline.
Move the ready completions into buf. Never blocks: with wait_nr zero,
the standard call enters only to flush an overflowing completion queue.
Types
struct
Setup
src
Ring setup, in place of the raw io_uring_setup flag word.
The kernel's flags are a bitmask of unrelated booleans plus three values
that are meaningless without their bit, so a u32 lets a caller pass
IORING_SETUP_SQ_AFF without a CPU or CQSIZE without a size. Here each
bit has a name and the values sit beside it.
Fields
iopoll: bool = false
Complete each operation by polling the device: O_DIRECT block and char devices, not sockets or pipes.
sqpoll: bool = false
A kernel thread submits SQEs. The ring must then be shared only for completion reads; submitting from userspace races it.
sq_aff: bool = false
Pin the SQPOLL thread to sq_thread_cpu.
clamp: bool = false
Let the kernel clamp entries to what it can allocate instead of
failing the setup.
r_disabled: bool = false
Start disabled: Ring.enable turns it on later, which lets a process
set up a ring before it has the privileges to submit.
submit_all: bool = false
Submit every SQE in the batch even after one fails, instead of stopping at the first error.
coop_taskrun: bool = false
Deferred completions run in the submitting task. Cheaper than the default task work, and it cannot be combined with a ring shared across threads.
taskrun_flag: bool = false
Set IORING_SQ_TASKRUN on the SQ ring when task work is pending.
sqe128: bool = false
128-byte SQEs, for operations that carry more than 64 bytes.
cqe32: bool = false
32-byte CQEs, for the flags of CQE32 operations.
single_issuer: bool = false
One thread may submit. Required by defer_taskrun.
defer_taskrun: bool = false
Deferred completions run only inside the submit-side enter, so the
completions cannot arrive as interrupts. Requires single_issuer.
no_mmap: bool = false
The ring's memory is not mmap'd by the kernel; the caller maps it.
registered_fd_only: bool = false
Only registered files may be used.
no_sqarray: bool = false
The SQ array (the indirection from submission order to SQE slots) is not allocated; SQEs are consumed in order.
cq_entries: u32 = 0
CQSIZE: completion queue entries, when they must differ from the
submission queue's. Zero keeps the kernel's default.
sq_thread_cpu: u32 = 0
SQ_AFF: the CPU for the SQPOLL thread.
sq_thread_idle: u32 = 1000
SQPOLL: how long the thread idles before sleeping, in milliseconds.
wq_fd: ?linux.fd_t = null
ATTACH_WQ: share the io-wq worker pool of an existing ring.
Functions
The flag word io_uring_setup wants, with CQSIZE and ATTACH_WQ
derived from the values beside them.
The bits of a flag word, for a caller that has one.
more
Lossy on purpose: CQSIZE and ATTACH_WQ exist only to say that a
value is present, and a word does not carry the value. Those two bits
come back false here, because a Setup with the bit and no value is
not expressible. Set cq_entries or wq_fd to restore them.