#!/usr/bin/env dub
/+ dub.sdl:
name "io_uring_sq_rewind"
dependency "sparkles:event-horizon-sys" path="../../../../.."
platforms "linux"
targetPath "build"
+/
/**
* `io_uring` — SQ rewind (`IORING_SETUP_SQ_REWIND`, Linux 7.0).
*
* Normally the submission-queue tail only moves forward, and once the kernel has
* been told (via the shared `tail` index) about a batch of SQEs it owns them —
* any it can't process in one `io_uring_enter` would simply be lost to the
* application. `IORING_SETUP_SQ_REWIND` changes that: when the kernel stops a
* batch part-way (e.g. it hit a malformed SQE), it *rewinds its head* back over
* the SQEs it did not consume, so the application can re-submit them. This makes
* partial submits recoverable and enables speculative batching where a program
* prepares entries optimistically and re-drives whatever the kernel didn't take.
*
* The flag requires `IORING_SETUP_NO_SQARRAY` (head/tail index the SQE array
* directly, so there is a well-defined tail to rewind) and is incompatible with
* `SQPOLL` (a kernel poll thread could consume an SQE out from under a rewind).
*
* What this program demonstrates (when the kernel supports the flag):
* 1. queue three NOPs, deliberately corrupting the *middle* one (bogus opcode);
* 2. `submit()` — the kernel processes SQE #1, chokes on the malformed #2, and
* stops the batch early, rewinding its head over the un-consumed #2 and #3;
* 3. drain the completion(s) from that partial submit;
* 4. `submit()` again with no fresh `putWith` — on a rewind ring the trailing
* good NOP (#3) survived and is re-sent, and we assert its `user_data`
* round-trips. On a non-rewind ring SQE #3 would have been dropped, so this
* observably exercises the rewind machinery rather than a plain NOP.
*
* Companion to the io_uring chronology:
* see docs/research/async-io/io-uring/timeline.md § "7.0 — SQ rewind".
*
* Run with: `dub run --single sq-rewind.d`
*
* Portability: this box runs Linux 6.18, which predates `SQ_REWIND` (Linux 7.0),
* so `io_uring_setup` is expected to reject the flag with `-EINVAL`; we print a
* `SKIP:` line and exit 0. The same SKIP path covers hosts with no `io_uring`
* at all (too old, or blocked by a seccomp/container policy).
*/
module (module) io_uring_sq_rewindio_uring — SQ rewind (IORING_SETUP_SQ_REWIND, Linux 7.0).
Normally the submission-queue tail only moves forward, and once the kernel has
been told (via the shared tail index) about a batch of SQEs it owns them —
any it can't process in one io_uring_enter would simply be lost to the
application. IORING_SETUP_SQ_REWIND changes that: when the kernel stops a
batch part-way (e.g. it hit a malformed SQE), it rewinds its head back over
the SQEs it did not consume, so the application can re-submit them. This makes
partial submits recoverable and enables speculative batching where a program
prepares entries optimistically and re-drives whatever the kernel didn't take.
The flag requires IORING_SETUP_NO_SQARRAY (head/tail index the SQE array
directly, so there is a well-defined tail to rewind) and is incompatible with
SQPOLL (a kernel poll thread could consume an SQE out from under a rewind).
What this program demonstrates (when the kernel supports the flag):
queue three NOPs, deliberately corrupting the middle one (bogus opcode);
submit() — the kernel processes SQE #1, chokes on the malformed #2, and
stops the batch early, rewinding its head over the un-consumed #2 and #3;
drain the completion(s) from that partial submit;
submit() again with no fresh putWith — on a rewind ring the trailing
good NOP (#3) survived and is re-sent, and we assert its user_data
round-trips. On a non-rewind ring SQE #3 would have been dropped, so this
observably exercises the rewind machinery rather than a plain NOP.
Companion to the io_uring chronology:
see docs/research/async-io/io-uring/timeline.md § "7.0 — SQ rewind".
Run with: dub run --single sq-rewind.d
Portability
this box runs Linux 6.18, which predates SQ_REWIND (Linux 7.0),
so io_uring_setup is expected to reject the flag with -EINVAL; we print a
SKIP: line and exit 0. The same SKIP path covers hosts with no io_uring
at all (too old, or blocked by a seccomp/container policy).
io_uring_sq_rewind;
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) 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) io_uring_sq_rewind.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()
{
import (package) corecore.(package) core.stdcstdc.(module) core.stdc.errnoD header file for C99.
pubs.opengroup.org/onlinepubs/009695399/basedefs/errno.h.html, errno.h
Source
core/stdc/errno.d
errno : (alias constant) EINVAL = int core.stdc.errno.EINVAL = 22EINVAL, (alias constant) EOPNOTSUPP = int core.stdc.errno.EOPNOTSUPP = 95EOPNOTSUPP, (alias constant) ENOSYS = int core.stdc.errno.ENOSYS = 38ENOSYS, (alias constant) EPERM = int core.stdc.errno.EPERM = 1EPERM;
(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;
// SQ_REWIND requires NO_SQARRAY (the direct head/tail layout that gives a
// rewindable tail) and is mutually exclusive with SQPOLL.
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, (enum) sparkles.event_horizon.sys.uring.io_uring.SetupFlagsio_uring_setup() flags
SetupFlags.(enum value) sparkles.event_horizon.sys.uring.io_uring.SetupFlags.NO_SQARRAY = 65536uIORING_SETUP_NO_SQARRAY (from Linux 6.6)
Skip the indirect SQ array — head/tail now index the SQE array directly. Saves a small
mmap region. Default for newly-created rings on recent kernels.
NO_SQARRAY | (enum) sparkles.event_horizon.sys.uring.io_uring.SetupFlagsio_uring_setup() flags
SetupFlags.(enum value) sparkles.event_horizon.sys.uring.io_uring.SetupFlags.SQ_REWIND = 1048576uIORING_SETUP_SQ_REWIND (from Linux 6.18)
Requires NO_SQARRAY and is incompatible with SQPOLL. Lets the application rewind
the SQ tail to retry SQEs that have not yet been processed.
SQ_REWIND);
if ((local variable) const(int) setupRetsetupRet < 0)
{
const (local variable) const(int) ee = -(local variable) const(int) setupRetsetupRet;
// -EINVAL / -EOPNOTSUPP / -ENOSYS: the kernel doesn't know this flag
// (e.g. < 7.0, like this 6.18 box). -EPERM: policy-blocked.
if ((local variable) const(int) ee == (constant) int core.stdc.errno.EINVAL = 22EINVAL || (local variable) const(int) ee == (constant) int core.stdc.errno.EOPNOTSUPP = 95EOPNOTSUPP || (local variable) const(int) ee == (constant) int core.stdc.errno.ENOSYS = 38ENOSYS || (local variable) const(int) ee == (constant) int core.stdc.errno.EPERM = 1EPERM)
{
void std.stdio.writefln!(char, const(int))(in char[] fmt, const(int) __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("SKIP: IORING_SETUP_SQ_REWIND unsupported (errno %d) — needs Linux 7.0+", (local variable) const(int) ee);
return 0;
}
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("io_uring_setup(NO_SQARRAY|SQ_REWIND) failed unexpectedly: errno %d", (local variable) const(int) ee);
return 1;
}
// Three NOPs; the middle one is sabotaged with a bogus opcode so the kernel
// refuses it and halts the batch there. The trailing good NOP (user_data 3)
// is the one whose survival proves the rewind behaviour.
enum ulong (constant) ulong io_uring_sq_rewind.main.goodHead = 1LUgoodHead = 1, (constant) ulong io_uring_sq_rewind.main.badMiddle = 2LUbadMiddle = 2, (constant) ulong io_uring_sq_rewind.main.goodTail = 3LUgoodTail = 3;
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.putWith!((ref SubmissionEntry e) { e.prepNop(); e.user_data = goodHead; })();
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.putWith!((ref SubmissionEntry e) {
e.prepNop();
e.opcode = cast(Operation) 0xFF; // not a real op — kernel rejects it
e.user_data = badMiddle;
})();
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.putWith!((ref SubmissionEntry e) { e.prepNop(); e.user_data = goodTail; })();
// First submit: the kernel takes the leading good NOP, then stops at the
// malformed one. It must report a partial count (>0, <3) and rewind its head
// over the SQEs it did not consume.
const (local variable) const(int) firstfirst = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.Uring.submit() nothrow @nogc @safeSubmits qued SubmissionEntry to be processed by kernel.
submit();
if ((local variable) const(int) firstfirst < 0)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("first submit failed: errno %d", -(local variable) const(int) firstfirst);
return 1;
}
if (!((local variable) const(int) firstfirst > 0 && (local variable) const(int) firstfirst < 3))
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("expected a partial submit (1 or 2), got %d", (local variable) const(int) firstfirst);
return 1;
}
// Drain everything that completed from the partial submit (bounded: the
// kernel produced exactly `first` CQEs and they are already imminent).
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.Uring.wait(uint want = 1u) nothrow @nogcSimmilar to submit but with this method we just wait for required number
of CompletionEntries.
wait(1);
while (!(local variable) sparkles.event_horizon.sys.uring.Uring ioio.bool sparkles.event_horizon.sys.uring.Uring.empty() const pure nothrow @nogc @safeCheck if there is some CompletionEntry to process.
empty)
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.void sparkles.event_horizon.sys.uring.Uring.popFront() pure nothrow @nogc @safeMove to next CompletionEntry
popFront();
// Second submit with NO new SQE queued. On a SQ_REWIND ring the un-consumed
// trailing NOP was rewound and re-presented, so this sends exactly one SQE.
// Without rewind support `submit()` would have nothing left to send here.
const (local variable) const(int) secondsecond = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.Uring.submit() nothrow @nogc @safeSubmits qued SubmissionEntry to be processed by kernel.
submit();
if ((local variable) const(int) secondsecond < 0)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("re-submit of rewound SQE failed: errno %d", -(local variable) const(int) secondsecond);
return 1;
}
if ((local variable) const(int) secondsecond != 1)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("rewound SQE was lost: re-submit sent %d entries, expected 1", (local variable) const(int) secondsecond);
return 1;
}
// The survivor completes; its cookie confirms it is exactly the SQE the
// kernel rewound rather than something freshly minted.
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.int sparkles.event_horizon.sys.uring.Uring.wait(uint want = 1u) nothrow @nogcSimmilar to submit but with this method we just wait for required number
of CompletionEntries.
wait(1);
const (local variable) const(int) resres = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.sparkles.event_horizon.sys.uring.io_uring.CompletionEntry sparkles.event_horizon.sys.uring.Uring.front() pure nothrow @nogc return ref @safeGet first CompletionEntry from cq ring
front.(field) int sparkles.event_horizon.sys.uring.io_uring.CompletionEntry.resresult code for this event
res;
const (local variable) const(ulong) echoedechoed = (local variable) sparkles.event_horizon.sys.uring.Uring ioio.sparkles.event_horizon.sys.uring.io_uring.CompletionEntry sparkles.event_horizon.sys.uring.Uring.front() pure nothrow @nogc return ref @safeGet first CompletionEntry from cq ring
front.(field) ulong sparkles.event_horizon.sys.uring.io_uring.CompletionEntry.user_datasqe->data submission passed back
user_data;
(local variable) sparkles.event_horizon.sys.uring.Uring ioio.void sparkles.event_horizon.sys.uring.Uring.popFront() pure nothrow @nogc @safeMove to next CompletionEntry
popFront();
if ((local variable) const(int) resres < 0)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("rewound NOP completed with error: errno %d", -(local variable) const(int) resres);
return 1;
}
if ((local variable) const(ulong) echoedechoed != (constant) ulong io_uring_sq_rewind.main.goodTail = 3LUgoodTail)
{
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwritefln("rewound SQE mismatch: expected user_data %d, got %d", (constant) ulong io_uring_sq_rewind.main.goodTail = 3LUgoodTail, (local variable) const(ulong) echoedechoed);
return 1;
}
void std.stdio.writefln!(char, const(int), const(ulong))(in char[] fmt, const(int) __param_1, const(ulong) __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("ok: SQ_REWIND recovered the trailing SQE after a partial submit "
~ "(first sent %d, leftover user_data %d re-submitted and completed)", (local variable) const(int) firstfirst, (local variable) const(ulong) echoedechoed);
return 0;
}