#!/usr/bin/env dub
/+ dub.sdl:
name "io_uring_napi"
dependency "sparkles:event-horizon-sys" path="../../../../.."
platforms "linux"
targetPath "build"
+/
/**
* `io_uring` — NAPI busy-poll registration (`IORING_REGISTER_NAPI`, Linux 6.9).
*
* NAPI busy-polling lets a ring spin on the network stack's NAPI receive path
* for a bounded window instead of sleeping until an interrupt fires — trading
* CPU cycles for lower receive latency on networked completions. It is
* configured per-ring (not per-NIC) via `io_uring_register(IORING_REGISTER_NAPI)`,
* which `during` exposes as `Uring.registerNapi`.
*
* This example builds an `io_uring_napi` config (a busy-poll timeout in
* microseconds plus the `prefer_busy_poll` flag), registers it, prints the
* parameters on success, then tears it back down with `unregisterNapi`.
*
* Companion to the io_uring chronology:
* see docs/research/async-io/io-uring/timeline.md
* § "6.9 — NAPI busy-poll, ftruncate (May 2024)".
*
* Run with: `dub run --single napi.d`
*
* Portability: NAPI busy-poll arrived in 6.9 and can additionally be gated by
* the running kernel's network configuration. If `io_uring` is unavailable, or
* `registerNapi` reports `-EINVAL`/`-EOPNOTSUPP`/`-ENOSYS`, the program prints a
* `SKIP:` line and exits 0 so it stays green in CI regardless of the host.
*/
module (module) napi_exampleio_uring — NAPI busy-poll registration (IORING_REGISTER_NAPI, Linux 6.9).
NAPI busy-polling lets a ring spin on the network stack's NAPI receive path
for a bounded window instead of sleeping until an interrupt fires — trading
CPU cycles for lower receive latency on networked completions. It is
configured per-ring (not per-NIC) via io_uring_register(IORING_REGISTER_NAPI),
which during exposes as Uring.registerNapi.
This example builds an io_uring_napi config (a busy-poll timeout in
microseconds plus the prefer_busy_poll flag), registers it, prints the
parameters on success, then tears it back down with unregisterNapi.
Companion to the io_uring chronology:
see docs/research/async-io/io-uring/timeline.md
§ "6.9 — NAPI busy-poll, ftruncate (May 2024)".
Run with: dub run --single napi.d
Portability
NAPI busy-poll arrived in 6.9 and can additionally be gated by
the running kernel's network configuration. If io_uring is unavailable, or
registerNapi reports -EINVAL/-EOPNOTSUPP/-ENOSYS, the program prints a
SKIP: line and exits 0 so it stays green in CI regardless of the host.
napi_example;
import (package) sparklessparkles.(package) sparkles.event_horizonevent_horizon.(package) sparkles.event_horizon.syssys.(module) sparkles.event_horizon.sys.uringSimple idiomatic dlang wrapper around linux io_uring
(see: https://kernel.dk/io_uring.pdf) asynchronous API.
Vendored from
tchaloupka/during
by Tomáš Chaloupka: release 0.6.0, commit 3cd81909a4204b94da7de9f7b9d8e707a7360e74, which
is also upstream's latest, so no untagged fixes are left behind. The three modules
during, during.io_uring and during.openat2 are
sparkles.event_horizon.sys.uring`` and its io_uring and openat2 submodules; all
three compile to nothing outside Linux. Upstream's own test suite (tests/, run by
silly) is not vendored: this package's suite tests what Sparkles changes or relies on.
Changed from upstream:
the module names;
openat2 is version (linux) like the other two;
the io_uring_* system-call wrappers call druntime's
core.sys.linux.unistd.syscall (c_long syscall(c_long, ...)) instead of declaring
their own int syscall(int, ...): compiled into one LDC module set with druntime's,
the two prototypes clash;
Uring.submitAndWait(want, args) with nothing to submit waits with args: upstream
dropped them there, so a wait with a deadline blocked until a completion arrived.
prepCancel64 (liburing's io_uring_prep_cancel64) cancels by a raw user_data
value: prepCancel cancels by the address of a variable, which cannot name a request
tagged with setUserDataRaw.
prepCmdGetsockname notes Linux 6.19, where the kernel added the command, not 6.7.
eight RegisterOpCode members note the release that added them, from the kernel's
history: CLOCK and CLONE_BUFFERS 6.12, SEND_MSG_RING and RESIZE_RINGS 6.13,
ZCRX_IFQ 6.15, QUERY 6.18, ZCRX_CTRL 6.19 and BPF_FILTER 7.0;
the query interface (linux/io_uring/query.h, Linux 6.18), which upstream does not
bind: io_uring_query and the io_uring_query_* structs.
Why vendored: Sparkles' io_uring backend (sparkles:event-horizon) stands on this
binding and worked around two of its defects in its own code instead of fixing them
here; owning the copy fixes them at the source and lets new kernel operations land
as the kernel ships them. As a dub package it also put during and, through its
unittest configuration, silly (which Sparkles does not use) into the
dub.selections.json of every package that reaches the loop and into the Nix dub
locks. It is the raw kernel interface, with no event loop, so it belongs to the
loop-free system-call layer.
uring;
import (package) corecore.(package) core.syssys.(package) core.sys.linuxlinux.(module) core.sys.linux.errnoD header file for GNU/Linux
errno : (alias constant) napi_example.EINVAL = int core.stdc.errno.EINVAL = 22EINVAL, (alias constant) napi_example.EOPNOTSUPP = int core.stdc.errno.EOPNOTSUPP = 95EOPNOTSUPP, (alias constant) napi_example.ENOSYS = int core.stdc.errno.ENOSYS = 38ENOSYS;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) napi_example.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to writef(fmt, args, '\n').
writefln, stderr;
int int D main()main()
{
(struct) sparkles.event_horizon.sys.uring.UringMain entry point to work with io_uring.
It hides SubmissionQueue and CompletionQueue behind standard range interface.
We put in SubmissionEntry entries and take out CompletionEntry entries.
Use predefined prepXX methods to fill required fields of SubmissionEntry before put or during putWith.
Note
prepXX functions doesn't touch previous entry state, just fills in operation properties. This is because for
less error prone interface it is cleared automatically when prepared using putWith. So when using on own SubmissionEntry
(outside submission queue), that would be added to the submission queue using put, be sure its cleared if it's
reused for multiple operations.
Uring (local variable) sparkles.event_horizon.sys.uring.Uring ioio;
const (local variable) const(int) setupRetsetupRet = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.setup(ref sparkles.event_horizon.sys.uring.Uring uring, uint entries = 128u, sparkles.event_horizon.sys.uring.io_uring.SetupFlags flags = SetupFlags.NONE) nothrow @nogc @safeSetup new instance of io_uring into provided Uring structure.
setup(8);
if ((local variable) const(int) setupRetsetupRet < 0)
{
void std.stdio.writefln!(char, const(int))(in char[] fmt, const(int) __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("SKIP: io_uring_setup failed (errno %d) — io_uring unavailable on this host", -(local variable) const(int) setupRetsetupRet);
return 0;
}
// NAPI busy-poll config: spin the NAPI receive path for up to 50us before
// falling back to interrupt-driven wakeups, and prefer busy polling.
(struct) sparkles.event_horizon.sys.uring.io_uring.io_uring_napiArgument for IORING_REGISTER_NAPI / IORING_UNREGISTER_NAPI. Configures NAPI busy-poll
behaviour for the ring. busy_poll_to is the busy-poll timeout in microseconds.
The struct has a backward-compatible layout: zero-initialised callers leave opcode and
op_param at 0, selecting the original register/unregister behaviour. Linux 6.18+ users
can write IO_URING_NAPI_STATIC_* into opcode to manage the static NAPI tracking list.
Note
Available from Linux 6.9 (extended in 6.18 with opcode/op_param)
io_uring_napi (local variable) sparkles.event_horizon.sys.uring.io_uring.io_uring_napi napinapi;
(local variable) sparkles.event_horizon.sys.uring.io_uring.io_uring_napi napinapi.(field) uint sparkles.event_horizon.sys.uring.io_uring.io_uring_napi.busy_poll_tobusy-poll timeout in microseconds
busy_poll_to = 50; // busy-poll timeout, microseconds
(local variable) sparkles.event_horizon.sys.uring.io_uring.io_uring_napi napinapi.(field) ubyte sparkles.event_horizon.sys.uring.io_uring.io_uring_napi.prefer_busy_pollboolean: prefer busy polling over interrupts
prefer_busy_poll = 1; // prefer busy poll over interrupts
const (local variable) const(int) regRetregRet = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.Uring.registerNapi(ref scope sparkles.event_horizon.sys.uring.io_uring.io_uring_napi napi) nothrow @nogc @trustedEnable NAPI busy-polling on the ring. napi`.busy_poll_to` is the busy-poll timeout in
microseconds, napi.prefer_busy_poll selects busy poll over interrupt-driven receive.
On return, napi is filled with the previous configuration.
Note
Available from Linux 6.9
registerNapi((local variable) sparkles.event_horizon.sys.uring.io_uring.io_uring_napi napinapi);
if ((local variable) const(int) regRetregRet == -(constant) int core.stdc.errno.EINVAL = 22EINVAL || (local variable) const(int) regRetregRet == -(constant) int core.stdc.errno.EOPNOTSUPP = 95EOPNOTSUPP || (local variable) const(int) regRetregRet == -(constant) int core.stdc.errno.ENOSYS = 38ENOSYS)
{
// Kernel < 6.9, or NAPI busy-poll not available in this environment.
// This is an expected outcome on hosts without NAPI support.
void std.stdio.writefln!(char, const(int))(in char[] fmt, const(int) __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("SKIP: IORING_REGISTER_NAPI unsupported here (errno %d) — needs Linux 6.9+ with NAPI busy-poll", -(local variable) const(int) regRetregRet);
return 0;
}
if ((local variable) const(int) regRetregRet < 0)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("registerNapi failed unexpectedly: errno %d", -(local variable) const(int) regRetregRet);
return 1;
}
// On success the kernel writes the *previous* config back into `napi`, but
// the values we just registered are the ones that matter for the demo.
void std.stdio.writefln!(char, int, int)(in char[] fmt, int __param_1, int __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("ok: registered NAPI busy-poll (busy_poll_to=%dus, prefer_busy_poll=%d)",
50, 1);
// Tear the registration back down. `unregisterNapi` fills its argument with
// the configuration that was in effect; we don't need it, so pass a fresh one.
(struct) sparkles.event_horizon.sys.uring.io_uring.io_uring_napiArgument for IORING_REGISTER_NAPI / IORING_UNREGISTER_NAPI. Configures NAPI busy-poll
behaviour for the ring. busy_poll_to is the busy-poll timeout in microseconds.
The struct has a backward-compatible layout: zero-initialised callers leave opcode and
op_param at 0, selecting the original register/unregister behaviour. Linux 6.18+ users
can write IO_URING_NAPI_STATIC_* into opcode to manage the static NAPI tracking list.
Note
Available from Linux 6.9 (extended in 6.18 with opcode/op_param)
io_uring_napi (local variable) sparkles.event_horizon.sys.uring.io_uring.io_uring_napi prevprev;
const (local variable) const(int) unregRetunregRet = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.Uring.unregisterNapi(ref scope sparkles.event_horizon.sys.uring.io_uring.io_uring_napi napi) nothrow @nogc @trustedDisable NAPI busy-polling on the ring. On return, napi is filled with the
configuration that was in effect.
Note
Available from Linux 6.9
unregisterNapi((local variable) sparkles.event_horizon.sys.uring.io_uring.io_uring_napi prevprev);
if ((local variable) const(int) unregRetunregRet < 0)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("unregisterNapi failed: errno %d", -(local variable) const(int) unregRetunregRet);
return 1;
}
return 0;
}