Use uring to keep several positional reads or writes outstanding on regular
files from a storage worker. Open files with the standard library. Create a
queue with uring.New(depth) and close it explicitly. The executable
example shows a write and its completion.
This read uses a queue with no other outstanding requests.
buffer := make([]byte, 4096)
if _, err := queue.SubmitReadAt(file, buffer, offset); err != nil {
return err
}
completion, err := queue.Wait()
if err != nil {
return err
}
if completion.Err != nil {
return completion.Err
}
consume(buffer[:completion.N])
Submit returns a nonzero request ID after Linux accepts the submission. The
completion may arrive in any order relative to other requests. With multiple
requests outstanding, use each completion’s ID to select the request and its
buffer before handling the byte count or error. Wait returns a
queue error separately from Completion.Err, which preserves the operation’s
Linux errno and any error releasing the file reference. A successful short
transfer reports the actual byte count. Zero bytes can indicate end of file.
Write completion reports transfer progress. When the workload needs
durability, wait for the relevant writes and then sync the file.
Positional reads and writes use a nonnegative byte offset independent of
the file’s current position. Writes use Linux RWF_NOAPPEND to honor the
requested offset when the file was opened with O_APPEND. Regular files retain their
underlying filesystem’s I/O restrictions, including alignment for direct I/O.
When O_DIRECT uses a Go heap buffer or another private mapping, wait for
the I/O to complete before a fork that duplicates the address space. Workers
that must fork during direct I/O can use an aligned MAP_SHARED buffer and
keep its mapping alive through completion. Linux open(2), O_DIRECT
The queue duplicates the file descriptor, so the caller may close the original
file after submission. The queue closes its duplicate when Wait consumes the
completion, when Close drains it, or when submission fails after duplication.
Closing the duplicate releases all POSIX record locks the process holds on
that inode, even while the original file remains open. A lock acquired with
file.OFDLocks survives that close while the caller keeps the original file
open. See byte-range advisory locking.
Keep each buffer and its backing storage valid and exclusively available to the request until its completion is returned or Close finishes draining. For memory outside the Go heap, keep its owner open too. A failed single-request submission returns zero and releases any file and buffer acquired for that attempt.
Queue depth is between 1 and 32768 and includes unread completions for I/O,
sync, timeout, and poll requests. Submit at capacity returns uring.ErrQueueFull.
Wait on an empty queue returns uring.ErrNoPending. The zero value returns
os.ErrInvalid. Operations on a
closed queue return os.ErrClosed.
Calls from multiple goroutines serialize, with cancellation able to submit while Wait or Close is blocked. Close drains outstanding operations and discards their unread results. If waiting for the drain fails, Close retains the remaining resources and can be retried. Once drained, the queue rejects new I/O. If unmapping fails, retry Close to release the remaining mappings. Use Wait to collect operation errors before closing. Close and Wait can block for as long as the underlying I/O takes.
A journal writer can pass a record’s header and payload as separate buffers
to SubmitWritevAt(file, buffers, offset). SubmitReadvAt reads into
successive buffers in the same order. Both take up to 1024 buffers with a
combined length from 1 through 2,147,483,647 bytes. Empty elements are
allowed. Linux may transfer fewer bytes than requested. The completion’s
byte count covers the prefix across all buffers, including when it ends
partway through a buffer. The queue captures the slice headers on submission.
Keep the backing storage exclusively available to the request through
completion, including any external mappings.
Once the writes you need have completed successfully, call
SubmitSync(file, uring.SyncAll) for data and file metadata, or
SubmitSync(file, uring.SyncData) for data and the metadata needed to
retrieve it. Sync uses one ordinary queue slot and returns a completion
with a zero byte count. Check its Err for the kernel’s outcome. Sync
operates on the whole file and leaves synchronization of its directory
entry to the caller. Requests submitted independently can execute in
any order. See the journal write and sync example.
A journal worker can submit a write and its dependent sync together with
queue.SubmitLinked(uring.WritevAt(file, record, offset), uring.Sync(file, uring.SyncData)).
Linux executes the soft-linked operations in order. A failed operation or
short I/O transfer breaks the chain. It keeps its own byte count or error, and the
remaining operations report ECANCELED. Earlier writes may have taken
effect. Collect both the write and sync outcomes before reporting the
record durable. See the linked journal example.
An I/O operation with a successor can request at most Linux’s MAX_RW_COUNT
bytes, or 2,147,479,552 bytes on a system with 4 KiB pages. Split larger
transfers across operations. The queue rejects an oversized predecessor with
os.ErrInvalid before submitting the chain. This ensures that Linux checks
the full requested byte count when deciding whether to start the next operation.
Each operation occupies an ordinary queue slot and has its own ID and completion. Keep its buffers and any external mapping available until its terminal completion is consumed. The returned IDs follow submission order. Read completions in kernel order and match them by ID. A link timeout has its own completion and can finish before its target’s completion is read. Unrelated requests can complete between the linked operations.
An argument or staging error submits nothing. If Linux accepts only a prefix, the call returns that prefix’s IDs and a submission error. Linux can execute the accepted requests with the links it received. Collect their completions before deciding whether any remaining work can be resubmitted.
Use SubmitTimeout(delay, uring.Monotonic) for a one-shot timeout request.
SubmitTimeoutAt uses a uring.TimeoutInstant in a named Linux clock domain.
Monotonic excludes suspend time. Boottime includes it. Realtime absolute
deadlines use Unix seconds and follow wall-clock changes. In time namespaces
with offsets, upstream Linux 7.0 interprets absolute Monotonic and Boottime
deadlines in the initial namespace. Kernels with the time-namespace fix
interpret them in the submitting task’s namespace. Relative delays work
under either behavior. Linux time-namespace fix
Expiry produces a completion with Err matching ETIME. SubmitCancel(id) can
stop a pending standalone timeout.
Place uring.LinkTimeout(delay, clock) or uring.LinkTimeoutAt(instant)
immediately after the operation you want to bound in SubmitLinked. Linux
arms it for that operation and reports ECANCELED for the timer when the
operation finishes first. Disarming the timer after a successful operation
allows the next link to run. If the timer expires, Linux attempts to cancel the
target. The timer reports ETIME or the cancellation race’s errno. Collect
the target’s result before reusing its buffer. A standalone TimeoutAfter
or TimeoutAt in a chain reports expiry as a failure and breaks subsequent
links.
Use queue.WaitTimeout(delay) to limit how long a consumer waits for a
completion after it acquires the queue’s completion lock. A zero duration
checks for an available completion. Expiry returns ETIME as the method
error and leaves pending requests and their resources with the queue. A
submitted timer’s expiry appears in Completion.Err. Draining on Close can
wait for pending timers, so cancel long-lived timers when finishing early.
A storage worker that reuses a set of files and page buffers can install
them once with queue.RegisterFiles(files) and queue.RegisterBuffers(buffers).
SubmitReadFixedAt(fileSlot, bufferSlot, length, offset) and
SubmitWriteFixedAt(fileSlot, bufferSlot, length, offset) use the first
length bytes of the selected buffer at the given file offset. Slot numbers
start at zero. The registered slice lengths determine the maximum transfer
sizes. Wait returns the same completion type as ordinary submissions. See
the fixed write example.
The file table owns separate kernel references. A caller may close a file after registration. Register and update temporarily duplicate the supplied files, and closing those duplicates has the POSIX record-lock effect described above. The queue keeps Go buffers pinned while registered. Exclusive access begins at each submission and ends when its completion is consumed. The caller coordinates access to overlapping buffers.
For an external mapping, keep both the mapping and its backing pages stable
throughout registration, including between requests. For example,
region.Advise(mmap.DontNeed) on a private anonymous mapping can leave the
slice at the same address while later accesses use new pages. Fixed I/O still
uses the pages Linux pinned at registration. Before discarding pages, resizing,
or remapping, drain fixed completions and clear every affected slot or unregister
the buffer table. Register the current view before the next fixed submission.
Closing the queue also ends the registration.
Each queue has one table of each kind. A nil entry installs or clears an empty
slot. A read or write on an empty file slot reports EBADF in its completion.
UpdateFiles and UpdateBuffers replace consecutive slots. Check the
returned count even when the error is nil. Linux can stop after a prefix with
no error. On a short buffer update the remaining slots stay in place. A file
update may clear the first failing slot as part of replacing it. The update
and unregister methods return EBUSY while a fixed completion is outstanding.
Drain those completions before replacing or unregistering a table. Close
drains both forms of I/O and releases the tables.
Linux and the runner’s seccomp policy must allow io_uring_setup and
io_uring_enter. Fixed I/O also requires io_uring_register, the probed
fixed read and write opcodes, and enough locked-memory allowance for the
buffer table. See verification for
the isolated profile.
When a worker no longer needs a submitted operation, call
queue.SubmitCancel(targetID) with the nonzero ID from that queue. The
queue probes the Linux cancellation opcode on first use. This requires
io_uring_register as well as the ordinary submission syscalls.
A rejected submission returns zero and an error, with no completion to collect.
The queue reserves one slot for cancellation even when all I/O slots are
occupied. It returns uring.ErrQueueFull if the previous cancellation
completion is still unread. Use the returned cancellation ID and the original
target ID to dispatch their separate results from Wait. A successful
cancellation has a nil Completion.Err. Linux can report ENOENT when the
target has completed or is unknown, or EALREADY when the operation is
already running. Keep the target’s resources available until its own
completion is consumed or Close finishes draining. A canceled target can
report ECANCELED in its completion. See the cancellation example.
Use queue.SubmitPoll(reader, uring.Readable) to wait for a file such as
a pipe to become readable while handling the result through the completion
queue. Linux runs the initial readiness check on a worker, so a slow file
poll callback can proceed independently of submission. Match the result by ID
and check Completion.Err, then call
Completion.PollEvents() to get the Linux event mask. Completion.N holds
that mask for poll requests. Linux also reports error and hangup conditions
regardless of the interest mask. A successful readiness result leaves the
source’s data available for ordinary I/O. Its readiness may change before
that I/O starts. Executable poll example.
Each poll is one-shot and occupies one ordinary slot until consumed. It
retains an independent file reference through completion, with the same
POSIX record-lock effect as file I/O. Resubmit to wait for another readiness
result. WaitTimeout bounds the consumer wait and leaves the request
pending on expiry. Use SubmitCancel before draining a pending poll for
shutdown, or submit uring.Poll(reader, uring.Readable) followed by
uring.LinkTimeout(delay, uring.Monotonic) to bound the request itself.
Closing the original file leaves the request active.
Create an eventfd counter with eventfd.New(0, eventfd.Default)
and pass it to queue.RegisterEventFD(counter) before submitting work. The
counter can wake a goroutine through ReadValue or join an existing epoll
loop through counter.Register(poller, epoll.Readable). Bound counter I/O
with its own deadline. Executable notification example.
Read the counter before draining ready completions with WaitTimeout(0).
Handle each result by request ID and stop draining on ETIME or
uring.ErrNoPending. A notification is a hint to check the completion queue.
Linux can coalesce notifications and the count can differ from the number of
completions. Reading the counter leaves completions queued, and collecting a
completion leaves the count available until read.
RegisterEventFD and UnregisterEventFD require io_uring_register. One
counter can be registered per queue. Linux returns EBUSY for a second
registration and ENXIO when asked to remove an absent registration.
Unregistering or closing the queue releases its kernel reference and leaves
the counter handle and its epoll registrations under their respective owners.
Closing the counter handle leaves the queue registration installed. Signals
already posted or in flight can still be observed after unregistering.
The queue supports READ, WRITE, READV, WRITEV, FSYNC, READ_FIXED,
WRITE_FIXED, POLL_ADD, TIMEOUT, LINK_TIMEOUT, and ASYNC_CANCEL from
the IORING_OP_* enumeration. Polls and timers produce one terminal
completion each. The remaining opcodes are outside the current queue API.
Linux 7.0 opcode enumeration.
| Area | Remaining opcodes without the IORING_OP_ prefix |
|---|---|
| Poll, timeout, and epoll | POLL_REMOVE, TIMEOUT_REMOVE, EPOLL_CTL, EPOLL_WAIT |
| File and directory operations | SYNC_FILE_RANGE, FALLOCATE, OPENAT, OPENAT2, CLOSE, STATX, FADVISE, MADVISE, SPLICE, TEE, RENAMEAT, UNLINKAT, MKDIRAT, SYMLINKAT, LINKAT, FSETXATTR, SETXATTR, FGETXATTR, GETXATTR, FTRUNCATE, PIPE |
| Fixed, selected, and multishot buffers | FILES_UPDATE, PROVIDE_BUFFERS, REMOVE_BUFFERS, READ_MULTISHOT, FIXED_FD_INSTALL, READV_FIXED, WRITEV_FIXED |
| Socket operations | SENDMSG, RECVMSG, ACCEPT, CONNECT, SEND, RECV, SHUTDOWN, SOCKET, SEND_ZC, SENDMSG_ZC, BIND, LISTEN, RECV_ZC |
| Ring communication, device commands, and waits | NOP, NOP128, MSG_RING, URING_CMD, URING_CMD128, WAITID, FUTEX_WAIT, FUTEX_WAKE, FUTEX_WAITV |
SubmitCancel handles cancellation by request ID. Fixed file updates use
the registration syscall. Poll updates, multishot requests, and async-only
eventfd notifications remain outside the current API.