Documentation
¶
Overview ¶
Package uring provides the kernel-boundary `io_uring` surface for Linux 6.18+. `uring` assumes the 6.18+ baseline and carries no fallback branches for older kernels. Its core Linux `io_uring` implementation was refactored from `code.hybscloud.com/sox` into this dedicated package. It prepares SQEs, copies CQEs, and carries submission context through `user_data`. The caller drives the ring and routes each completion to its owner.
A typical caller starts the ring, submits an operation, and then treats the completion queue as the source of truth for kernel results. This example has one outstanding read and uses iox.Backoff when no completion is available. The file retains close ownership. The ring owns the registered buffer until Stop; consume its bytes after completion and before reuse or ring teardown. This example exits on unrecoverable errors with log.Fatal. Services must retain and drain pending requests before stopping the ring.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ring, err := uring.New(func(opt *uring.Options) {
opt.Entries = uring.EntriesMedium
opt.NotifySucceed = true
})
if err != nil {
log.Fatal(err)
}
if err := ring.Start(); err != nil {
log.Fatal(err)
}
fd := iofd.FD(file.Fd()) // Borrowed; file owns Close.
buf := ring.RegisteredBuffer(0)
ctx := uring.PackDirect(uring.IORING_OP_READ, 0, 0, 0).WithFD(fd)
if err := ring.Read(ctx, buf); err != nil {
log.Fatal(err)
}
var cqes [1]uring.CQEView // Only one request is outstanding.
var backoff iox.Backoff
for {
n, err := ring.Wait(cqes[:])
if err != nil && !iox.IsWouldBlock(err) {
log.Fatal(err)
}
if n == 0 {
backoff.Wait()
continue
}
backoff.Reset()
break
}
cqe := cqes[0]
if cqe.Op() != uring.IORING_OP_READ || cqe.FD() != fd {
log.Fatalf("unexpected completion: op=%d fd=%d", cqe.Op(), cqe.FD())
}
runtime.KeepAlive(file) // Keep the owner of the borrowed FD live through the read.
completionErr := cqe.Err()
if completionErr == nil {
handle(buf[:int(cqe.Res)])
}
if err := ring.Stop(); err != nil {
log.Fatal(err)
}
if completionErr != nil {
log.Fatal(completionErr)
}
Uring.SubmitAcceptMultishot, Uring.SubmitReceiveMultishot, and Uring.SubmitReceiveBundleMultishot submit raw multishot SQEs and keep the kernel-boundary flow explicit. Uring.AcceptMultishot and Uring.ReceiveMultishot use the same kernel path and return a MultishotSubscription for caller-owned callback dispatch in the same serialized completion loop. If copied CQEs outlive that loop, caller code must pair them with its own route state and reject observations for retired subscriptions. Dispatch cancellation CQEs through the same subscription's HandleCQE or their extended handlers, even after State reports SubscriptionStopped. The original pooled context is retained until both the original terminal CQE and any cancellation CQE have been handled.
sqeCtx := uring.ForFD(listenerFD)
sub, err := ring.AcceptMultishot(sqeCtx, handler)
if err != nil {
return err
}
// Process CQEs in the same serialized completion loop.
for i := range n {
if sub.HandleCQE(cqes[i]) {
continue
}
dispatch(ring, cqes[i])
}
// Cancel when done
// On default single-issuer rings, call Cancel from the OS-thread-pinned
// ring owner and serialize it with submit, Wait, WaitDirect,
// WaitExtended, Stop, and ResizeRings.
if err := sub.Cancel(); err != nil {
return err
}
// Keep dispatching the original terminal CQE and any queued cancellation CQE.
ListenerManager submits the initial SOCKET and returns a ListenerOp. Route setup CQEs to ListenerOp.HandleCQE to invoke callbacks and submit the next stage automatically:
SOCKET -> OnSocketCreated -> BIND -> OnBound -> LISTEN -> OnListening
OnListening establishes readiness to accept. If HandleCQE returns iox.ErrWouldBlock, drive the ring and retry the prepared SQE with ring.SubmitExtended(PackExtended(op.Ext())); never replay the CQE or callback. For manual advancement, use DecodeListenerCQE, PrepareListenerBind, PrepareListenerListen, and SetListenerReady instead. Serialize dispatch, retry and Close. If Close is called while a setup CQE is pending, drain it before the final Close that returns the pooled context.
Extended-mode raw `UserData` is caller-beware storage. Prefer scalar payloads there; if raw overlays or typed context views place Go pointers, interfaces, func values, maps, slices, strings, chans, or structs containing them in those bytes, caller code must keep the live roots outside `UserData`.
SQEContext packs submission metadata into `user_data`.
Direct mode layout (inline context, zero allocation):
┌─────────┬─────────┬──────────────┬────────────────────────────┬────┐ │ Op (8b) │Flags(8b)│ BufGrp (16b) │ FD (30b) │Mode│ └─────────┴─────────┴──────────────┴────────────────────────────┴────┘ Bits 0-7 Bits 8-15 Bits 16-31 Bits 32-61 Bits 62-63
Mode bits (62-63): 00=Direct, 01=Indirect (64B ptr), 10=Extended (128B ptr)
Pack context for submission:
ctx := uring.PackDirect(
uring.IORING_OP_RECV, // Op: operation type
0, // Flags: SQE flags
bufferGroupID, // BufGroup: for buffer selection
clientFD, // FD: target file descriptor
)
If `IOSQE_FIXED_FILE` is set, the FD field stores the registered file index instead of a raw file descriptor.
Or use the fluent builder:
ctx := uring.ForFD(clientFD).WithOp(uring.IORING_OP_RECV).WithBufGroup(groupID)
Handler Patterns ¶
NewMultishotSubscriber adapts functions to MultishotHandler. In this accept handler, registerConnection takes ownership of each socket and closes it after its last use.
handler := uring.NewMultishotSubscriber().
OnStep(func(step uring.MultishotStep) uring.MultishotAction {
if step.Err != nil {
return uring.MultishotStop
}
registerConnection(iofd.NewFD(int(step.CQE.Res)))
return uring.MultishotContinue
}).
OnStop(func(err error, cancelled bool) {
log.Println("stopped", err, cancelled)
})
Custom handlers can embed NoopMultishotHandler and override the methods they need. MultishotContinue keeps a live subscription running. MultishotStop requests cancellation after a non-final step.
Multishot Subscription Lifecycle ¶
Each original CQE with IORING_CQE_F_MORE leaves the multishot request live. Handling its terminal CQE sets SubscriptionStopped and, if callbacks remain enabled, invokes OnMultishotStop. This ends the original request; a queued cancellation still has its own completion obligation.
The subscription owns its submitted ExtSQE through original terminality, cancellation dispatch, and any concurrent cancellation submission. The package returns that context to its pool only after all three obligations end. Caller code must not return the subscription's contexts manually, and must dispatch queued cancellation CQEs even after the original stop callback.
Inspect each result independently of MORE: a live request does not imply byte progress or success. Returning MultishotStop from a non-final callback makes one best-effort cancellation attempt; failed admission leaves the subscription active. Caller code owns any retry through MultishotSubscription.Cancel.
Runtime Boundary ¶
Uring.Multicast and Uring.MulticastZeroCopy require Direct contexts and return the accepted target count, even when submission stops on an error. If retrying, resume at the first unaccepted target. For registered buffers, payload size and target count determine the send opcode. MulticastZeroCopy uses lower zero-copy thresholds. A retry with fewer targets can change the opcode. Check CQEView.Op and CQEView.IsNotification on each completion. Only a data CQE reports the send result. For a short stream send, retry only that target's unsent suffix.
Keep shared bytes immutable until every accepted send releases them. An ordinary send releases them on its data CQE. A zero-copy send releases them on a data CQE without MORE, or after both a data CQE with MORE and its matching notification, in either order. To observe ordinary Multicast successes, enable NotifySucceed and leave IOSQE_CQE_SKIP_SUCCESS clear. The Multicast zero-copy path and both MulticastZeroCopy paths retain success CQEs regardless of NotifySucceed and reject explicit success suppression.
Publishing an SQE admits the request. The caller matches each CQE to its source and interprets the result and flags for that operation. The caller decides when to poll, retry, cancel or advance a protocol. For managed operations, dispatching a CQE lets the helper advance its own state. MultishotSubscription, for example, retains its pooled context through dispatch of the original terminal CQE and any queued cancellation CQE.
Buffer Groups ¶
Buffer groups enable kernel-side buffer selection for receive operations. The kernel selects a published buffer while processing the receive and reports its ID in the CQE. Selection can precede completion; userspace does not select or assign buffers per receive. The package exposes three practical buffer-management paths: registered fixed buffers for fixed-buffer file I/O, provided buffers selected by the kernel, and bundle receives over buffers in publication order. IDs need not remain numerically consecutive after recycling; Uring.BundleIterator retains the actual order. NewBundleIterator requires a caller-maintained consecutive-ID layout.
IncrementalReceiver tracks a separate offset for each buffer ID in an IOU_PBUF_RING_INC group. Dispatch its CQEs once, serially in CQ order. IORING_CQE_F_BUF_MORE retains the selected buffer for further consumption, independently of request completion. A CQE with IORING_CQE_F_BUFFER and without IORING_CQE_F_BUF_MORE returns that buffer, even for a zero or negative result. Finish borrowed payload access before republishing the buffer.
opts := uring.OptionsForBudget(256 * uring.MiB)
opts.NotifySucceed = true // Observe the fixed write's byte count.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ring, err := uring.New(func(opt *uring.Options) {
*opt = opts
})
if err != nil {
return err
}
if err := ring.Start(); err != nil {
return err
}
defer ring.Stop() // The caller drains admitted work before this runs.
cfg, scale := uring.BufferConfigForBudget(256 * uring.MiB)
fmt.Printf("buffer tiers=%+v scale=%d\n", cfg, scale)
Here fd is a caller-owned iofd.FD and the payload fits in registered buffer 0. Keep fd open and the buffer unchanged through the matching write CQE. Check CQEView.Err before using Res as the number of bytes written. A successful write can be short.
buf := ring.RegisteredBuffer(0)
copy(buf, payload)
writeCtx := uring.PackDirect(uring.IORING_OP_WRITE_FIXED, 0, 0, 0).WithFD(fd)
if err := ring.WriteFixed(writeCtx, 0, len(payload)); err != nil {
return err
}
For socket receive with kernel buffer selection, pass nil as the receive buffer and request the desired read-buffer size class. The matching CQE reports which buffer group and buffer ID were consumed.
recvCtx := uring.PackDirect(uring.IORING_OP_RECV, 0, 0, 0)
if err := ring.Receive(recvCtx, &socketFD, nil, uring.WithReadBufferSize(uring.BufferSizeSmall)); err != nil {
return err
}
if cqe.HasBuffer() {
fmt.Printf("kernel selected group=%d id=%d\n", cqe.BufGroup(), cqe.BufID())
}
Bundle receives may consume more than one provided buffer in one CQE. A selected slot can accompany EOF or an error and yields one empty slice. Finish all borrowed reads, then call Recycle exactly once across all copies of the iterator to return the slots to the kernel.
if err := ring.ReceiveBundle(recvCtx, &socketFD, uring.WithReadBufferSize(uring.BufferSizeSmall)); err != nil {
return err
}
if it, ok := ring.BundleIterator(cqe, cqe.BufGroup()); ok {
if it.TotalBytes() > 0 {
for buf := range it.All() {
handle(buf)
}
}
if err := it.Recycle(ring); err != nil {
return err
}
}
Supported Operations ¶
Socket creation:
- TCP: Uring.TCP4Socket, Uring.TCP6Socket, Uring.TCP4SocketDirect, Uring.TCP6SocketDirect
- UDP: Uring.UDP4Socket, Uring.UDP6Socket, Uring.UDP4SocketDirect, Uring.UDP6SocketDirect
- UDPLITE: Uring.UDPLITE4Socket, Uring.UDPLITE6Socket, Uring.UDPLITE4SocketDirect, Uring.UDPLITE6SocketDirect
- SCTP: Uring.SCTP4Socket, Uring.SCTP6Socket, Uring.SCTP4SocketDirect, Uring.SCTP6SocketDirect
- Unix: Uring.UnixSocket, Uring.UnixSocketDirect
- Generic: Uring.SocketRaw, Uring.SocketDirect
Socket operations:
- Uring.Bind, Uring.Listen, Uring.Accept, Uring.AcceptDirect, Uring.Connect, Uring.Shutdown
- Uring.Receive, Uring.Send, Uring.RecvMsg, Uring.SendMsg, Uring.SendMsgHeader
- Uring.ReceiveBundle, Uring.ReceiveZeroCopy
- Uring.Multicast, Uring.MulticastZeroCopy
- Raw multishot submits: Uring.SubmitAcceptMultishot, Uring.SubmitAcceptDirectMultishot, Uring.SubmitReceiveMultishot, Uring.SubmitReceiveBundleMultishot
- Helper-backed multishot subscriptions: Uring.AcceptMultishot, Uring.ReceiveMultishot
File operations:
- Uring.Read, Uring.Write, Uring.ReadV, Uring.WriteV
- Uring.ReadFixed, Uring.WriteFixed, Uring.ReadvFixed, Uring.WritevFixed with registered-buffer ranges
- Uring.OpenAt, Uring.Close, Uring.Sync, Uring.Fallocate, Uring.FTruncate
- Uring.Statx, Uring.RenameAt, Uring.UnlinkAt, Uring.MkdirAt, Uring.SymlinkAt, Uring.LinkAt
- Uring.FGetXattr, Uring.FSetXattr, Uring.GetXattr, Uring.SetXattr
- Uring.Splice, Uring.Tee, Uring.Pipe for zero-copy data transfer
- Uring.SyncFileRange, Uring.FileAdvise
- Uring.Close submits `IORING_OP_CLOSE` for the target file descriptor; it does not tear down the ring itself
Control operations:
- Uring.Timeout, Uring.TimeoutRemove, Uring.TimeoutUpdate, Uring.LinkTimeout
- Uring.AsyncCancel, Uring.AsyncCancelFD, Uring.AsyncCancelOpcode, Uring.AsyncCancelAny, Uring.AsyncCancelAll
- Uring.PollAdd, Uring.PollRemove, Uring.PollUpdate, Uring.PollAddLevel, Uring.PollAddMultishot, Uring.PollAddMultishotLevel
- Uring.EpollWait, Uring.FutexWait, Uring.FutexWake, Uring.FutexWaitV, Uring.Waitid
- Uring.MsgRing, Uring.MsgRingFD
- Uring.FixedFdInstall, Uring.FilesUpdate
- Uring.UringCmd, Uring.UringCmdInline, Uring.UringCmd128
- Uring.Nop, Uring.Nop128
Registration:
- Files: Uring.RegisterFiles, Uring.RegisterFilesSparse, Uring.RegisterFilesUpdate, Uring.UnregisterFiles, Uring.RegisteredFileCount
- Buffers: Uring.RegisterBufRingMMAP, Uring.RegisterBufRingIncremental, Uring.RegisterBufRingWithFlags, BufferRing.Add, BufferRing.Advance, Uring.RegisteredBuffer, Uring.RegisteredBufferCount
- Buffer cloning: Uring.CloneBuffers, Uring.CloneBuffersFromRegistered
- Memory: Uring.RegisterMemRegion
- NAPI: Uring.RegisterNAPI, Uring.UnregisterNAPI, Uring.NAPIAddStaticID, Uring.NAPIDelStaticID
Ring management:
- Uring.Start, Uring.Stop, Uring.Wait, Uring.ResizeRings
- Uring.SQAvailable, Uring.CQPending, Uring.RingFD
- Uring.ExtSQE, Uring.PutExtSQE, Uring.IndirectSQE, Uring.PutIndirectSQE, Uring.SubmitExtended
Capability queries:
Zero-copy receive (ZCRX):
- Uring.QueryZCRX, Uring.RegisterZCRXIfq
- NewZCRXReceiver is wired for rings created with 32-byte CQEs. The current Options surface does not expose `IORING_SETUP_CQE32`, so rings created through the standard New path return ErrNotSupported from this constructor. Until a CQE32 setup path is exposed, the receiver docs describe the boundary contract rather than a runnable public setup recipe.
Performance ¶
The hot submit and reap paths are designed to remain zero-allocation. Run the benchmark tests to measure performance on your system.
Ring Setup ¶
New returns an unstarted ring that may be handed to another goroutine with synchronized, exclusive access. With MultiIssuers=false, call runtime.LockOSThread before Start and keep the owner locked through Stop. Drain outstanding work before Stop. The example locks before New.
Create and start an io_uring instance:
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ring, err := uring.New(func(opt *uring.Options) {
opt.Entries = uring.EntriesMedium // 2048 entries
})
if err != nil {
return err
}
if err := ring.Start(); err != nil {
return err
}
defer ring.Stop()
Memory Barriers ¶
Completion reads acquire the kernel's published tail through Go atomics. Shared consumers claim the CQ copy with CAS and spin.Wait, copy CQEs, and publish the head before admitting the next consumer. Submission and buffer publication also use dwcas.BarrierRelease. User code does not manage these barriers.
Dependencies ¶
- code.hybscloud.com/zcall: Zero-overhead syscalls
- code.hybscloud.com/iox: Non-blocking I/O semantics and error types
- code.hybscloud.com/iofd: File descriptor abstractions
- code.hybscloud.com/iobuf: Buffer pools and aligned memory
- code.hybscloud.com/sock: Socket types and address handling
- code.hybscloud.com/dwcas: Memory barriers for ring synchronization
- code.hybscloud.com/spin: Spin-wait primitives
The TCP broadcast test in the examples package uses code.hybscloud.com/framer to encode and decode length-prefixed messages.
Index ¶
- Constants
- Variables
- func AlignedMemBlock() []byte
- func CastUserData[T any](ext *ExtSQE) *T
- func CompletionError(res int32) error
- func ContextUserData[T any](ctx context.Context) T
- func ContextWithUserData[T any](ctx context.Context, val T) context.Context
- func PrepareListenerBind(ext *ExtSQE, fd iofd.FD)
- func PrepareListenerListen(ext *ExtSQE, fd iofd.FD)
- func PrepareListenerSocket(ext *ExtSQE, domain, sockType, proto int, sa Sockaddr, backlog int, ...) error
- func SetListenerReady(ext *ExtSQE)
- type Addr
- type AttrPI
- type BigBuffer
- type BufferGroupsConfig
- type BufferRing
- type BundleIterator
- func (it BundleIterator) All() iter.Seq[[]byte]
- func (it BundleIterator) AllWithSlotID() iter.Seq2[uint16, []byte]
- func (it BundleIterator) Buffer(index int) []byte
- func (it BundleIterator) Collect() [][]byte
- func (it BundleIterator) CopyTo(dst []byte) int
- func (it BundleIterator) Count() int
- func (it BundleIterator) Recycle(ur *Uring) error
- func (it BundleIterator) SlotID(index int) uint16
- func (it BundleIterator) TotalBytes() int
- type CQEView
- func (c *CQEView) BufGroup() uint16
- func (c *CQEView) BufID() uint16
- func (c *CQEView) BundleBuffers(bufferSize int) (startID uint16, count int)
- func (c *CQEView) BundleCount(bufferSize int) int
- func (c *CQEView) BundleStartID() uint16
- func (c *CQEView) Context() SQEContext
- func (c *CQEView) Err() error
- func (c *CQEView) ExtSQE() *ExtSQE
- func (c *CQEView) Extended() bool
- func (c *CQEView) FD() iofd.FD
- func (c *CQEView) FullSQE() bool
- func (c *CQEView) HasBuffer() bool
- func (c *CQEView) HasBufferMore() bool
- func (c *CQEView) HasMore() bool
- func (c *CQEView) IsNotification() bool
- func (c *CQEView) Op() uint8
- func (c *CQEView) SQE() SQEView
- func (c *CQEView) SocketNonEmpty() bool
- type CloneBuffers
- type ContextPools
- func (p *ContextPools) Capacity() int
- func (p *ContextPools) Extended() *ExtSQE
- func (p *ContextPools) ExtendedAvailable() int
- func (p *ContextPools) Indirect() *IndirectSQE
- func (p *ContextPools) IndirectAvailable() int
- func (p *ContextPools) PutExtended(ext *ExtSQE)
- func (p *ContextPools) PutIndirect(indirect *IndirectSQE)
- func (p *ContextPools) Reset()
- type Ctx0
- type Ctx0V1
- type Ctx0V2
- type Ctx0V3
- type Ctx0V4
- type Ctx0V5
- type Ctx0V6
- type Ctx0V7
- type Ctx1
- type Ctx1V1
- type Ctx1V2
- type Ctx1V3
- type Ctx1V4
- type Ctx1V5
- type Ctx1V6
- type Ctx2
- type Ctx2V1
- type Ctx2V2
- type Ctx2V3
- type Ctx2V4
- type Ctx2V5
- type Ctx3
- type Ctx3V1
- type Ctx3V2
- type Ctx3V3
- type Ctx3V4
- type Ctx4
- type Ctx4V1
- type Ctx4V2
- type Ctx4V3
- type Ctx5
- type Ctx5V1
- type Ctx5V2
- type Ctx6
- type Ctx6V1
- type Ctx7
- type CtxRefs0
- type CtxRefs1
- type CtxRefs2
- type CtxRefs3
- type CtxRefs4
- type CtxRefs5
- type CtxRefs6
- type CtxRefs7
- type DirectCQE
- type EpollEvent
- type ExtCQE
- type ExtSQE
- type Features
- type GiantBuffer
- type GreatBuffer
- type Handler
- type HugeBuffer
- type IncrementalHandler
- type IncrementalReceiver
- type IncrementalSubscriber
- func (s *IncrementalSubscriber) Handler() IncrementalHandler
- func (s *IncrementalSubscriber) OnComplete(fn func()) *IncrementalSubscriber
- func (s *IncrementalSubscriber) OnData(fn func(buf []byte, hasMore bool)) *IncrementalSubscriber
- func (s *IncrementalSubscriber) OnError(fn func(err error)) *IncrementalSubscriber
- type IndirectSQE
- type IoTimespec
- type IoVec
- type LargeBuffer
- type ListenerHandler
- type ListenerManager
- func (m *ListenerManager) ListenTCP4(addr *net.TCPAddr, backlog int, handler ListenerHandler) (*ListenerOp, error)
- func (m *ListenerManager) ListenTCP6(addr *net.TCPAddr, backlog int, handler ListenerHandler) (*ListenerOp, error)
- func (m *ListenerManager) ListenUnix(addr *net.UnixAddr, backlog int, handler ListenerHandler) (*ListenerOp, error)
- func (m *ListenerManager) Pool() *ContextPools
- func (m *ListenerManager) Ring() *Uring
- type ListenerOp
- func (op *ListenerOp) AcceptMultishot(handler MultishotHandler, options ...OpOptionFunc) (*MultishotSubscription, error)
- func (op *ListenerOp) Close()
- func (op *ListenerOp) Ext() *ExtSQE
- func (op *ListenerOp) FD() iofd.FD
- func (op *ListenerOp) HandleCQE(cqe CQEView) (bool, error)
- func (op *ListenerOp) SetFD(fd iofd.FD)
- type ListenerState
- type ListenerStep
- type ListenerSubscriber
- func (s *ListenerSubscriber) Handler() ListenerHandler
- func (s *ListenerSubscriber) OnBound(fn func() bool) *ListenerSubscriber
- func (s *ListenerSubscriber) OnError(fn func(op uint8, err error)) *ListenerSubscriber
- func (s *ListenerSubscriber) OnListening(fn func()) *ListenerSubscriber
- func (s *ListenerSubscriber) OnSocketCreated(fn func(fd iofd.FD) bool) *ListenerSubscriber
- type MediumBuffer
- type MemRegionReg
- type MicroBuffer
- type Msghdr
- type MultishotAction
- type MultishotHandler
- type MultishotStep
- type MultishotSubscriber
- func (s *MultishotSubscriber) Handler() MultishotHandler
- func (s *MultishotSubscriber) OnMultishotStep(step MultishotStep) MultishotAction
- func (s *MultishotSubscriber) OnMultishotStop(err error, cancelled bool)
- func (s *MultishotSubscriber) OnStep(fn func(step MultishotStep) MultishotAction) *MultishotSubscriber
- func (s *MultishotSubscriber) OnStop(fn func(err error, cancelled bool)) *MultishotSubscriber
- type MultishotSubscription
- type NanoBuffer
- type NapiReg
- type NetworkType
- type NoopIncrementalHandler
- type NoopListenerHandler
- type NoopMultishotHandler
- type NoopZCHandler
- type NoopZCRXHandler
- type OpOption
- type OpOptionFunc
- func WithBacklog(n int) OpOptionFunc
- func WithCount(cnt int) OpOptionFunc
- func WithDuration(d time.Duration) OpOptionFunc
- func WithFadvise(advice int) OpOptionFunc
- func WithFileIndex(idx uint32) OpOptionFunc
- func WithFileMode(mode os.FileMode) OpOptionFunc
- func WithFlags(flags uint8) OpOptionFunc
- func WithFsyncDataSync() OpOptionFunc
- func WithIOPrio(ioprio uint16) OpOptionFunc
- func WithIOPrioClass(class, level uint8) OpOptionFunc
- func WithN(n int) OpOptionFunc
- func WithOffset(offset int64) OpOptionFunc
- func WithPersonality(id uint16) OpOptionFunc
- func WithReadBufferSize(n int) OpOptionFunc
- func WithSpliceFlags(flags uint32) OpOptionFunc
- func WithTimeoutAbsolute() OpOptionFunc
- func WithTimeoutBootTime() OpOptionFunc
- func WithTimeoutEtimeSuccess() OpOptionFunc
- func WithTimeoutFlags(flags uint32) OpOptionFunc
- func WithTimeoutMultishot() OpOptionFunc
- func WithTimeoutRealTime() OpOptionFunc
- func WithUringCmdFlags(flags uint32) OpOptionFunc
- func WithWriteBufferSize(n int) OpOptionFunc
- type OpenHow
- type OptionFunc
- type Options
- type PicoBuffer
- type PollCloser
- type PollFd
- type QueryHdr
- type QueryOpcode
- type QuerySCQ
- type QueryZCRX
- type RawSockaddr
- type RawSockaddrAny
- type RawSockaddrInet4
- type RawSockaddrInet6
- type RawSockaddrUnix
- type RegWait
- type RegionDesc
- type RegisterBuffer
- type RegisterBufferPool
- type SQEContext
- func (c SQEContext) BufGroup() uint16
- func (c SQEContext) ExtSQE() *ExtSQE
- func (c SQEContext) FD() int32
- func (c SQEContext) Flags() uint8
- func (c SQEContext) HasBufferSelect() bool
- func (c SQEContext) IndirectSQE() *IndirectSQE
- func (c SQEContext) IsDirect() bool
- func (c SQEContext) IsExtended() bool
- func (c SQEContext) IsIndirect() bool
- func (c SQEContext) Mode() SQEContext
- func (c SQEContext) Op() uint8
- func (c SQEContext) OrFlags(flags uint8) SQEContext
- func (c SQEContext) Raw() uint64
- func (c SQEContext) WithBufGroup(bufGroup uint16) SQEContext
- func (c SQEContext) WithFD(fd iofd.FD) SQEContext
- func (c SQEContext) WithFlags(flags uint8) SQEContext
- func (c SQEContext) WithOp(op uint8) SQEContext
- type SQEView
- func (v SQEView) Addr() uint64
- func (v SQEView) BufGroup() uint16
- func (v SQEView) BufIndex() uint16
- func (v SQEView) FD() iofd.FD
- func (v SQEView) FileIndex() uint32
- func (v SQEView) Flags() uint8
- func (v SQEView) HasAsync() bool
- func (v SQEView) HasBufferSelect() bool
- func (v SQEView) HasCQESkipSuccess() bool
- func (v SQEView) HasFixedFile() bool
- func (v SQEView) HasIODrain() bool
- func (v SQEView) HasIOHardlink() bool
- func (v SQEView) HasIOLink() bool
- func (v SQEView) IoPrio() uint16
- func (v SQEView) Len() uint32
- func (v SQEView) Off() uint64
- func (v SQEView) Opcode() uint8
- func (v SQEView) Personality() uint16
- func (v SQEView) RawFD() int32
- func (v SQEView) SpliceFDIn() int32
- func (v SQEView) UFlags() uint32
- func (v SQEView) UserData() uint64
- func (v SQEView) Valid() bool
- type ScopedExtSQE
- type SendTargets
- type SmallBuffer
- type Sockaddr
- type Socket
- type Statx
- type StatxTimestamp
- type SubscriptionState
- type Timespec
- type TitanBuffer
- type UnderlyingProtocol
- type Uring
- func (ur *Uring) Accept(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) AcceptDirect(sqeCtx SQEContext, fileIndex uint32, options ...OpOptionFunc) error
- func (ur *Uring) AcceptMultishot(sqeCtx SQEContext, handler MultishotHandler, options ...OpOptionFunc) (*MultishotSubscription, error)
- func (ur *Uring) AsyncCancel(sqeCtx SQEContext, targetUserData uint64, options ...OpOptionFunc) error
- func (ur *Uring) AsyncCancelAll(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) AsyncCancelAny(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) AsyncCancelFD(sqeCtx SQEContext, cancelAll bool, options ...OpOptionFunc) error
- func (ur *Uring) AsyncCancelOpcode(sqeCtx SQEContext, opcode uint8, cancelAll bool, options ...OpOptionFunc) error
- func (ur *Uring) Bind(sqeCtx SQEContext, addr Addr, options ...OpOptionFunc) error
- func (ur *Uring) BundleIterator(cqe CQEView, group uint16) (BundleIterator, bool)
- func (ur *Uring) CQPending() int
- func (ur *Uring) CloneBuffers(src *Uring, srcOff, dstOff, count uint32, replace bool) error
- func (ur *Uring) CloneBuffersFromRegistered(src *Uring, srcRegisteredRingIdx uint32, srcOff, dstOff, count uint32, ...) error
- func (ur *Uring) Close(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) Connect(sqeCtx SQEContext, remote Addr, options ...OpOptionFunc) error
- func (ur *Uring) EpollWait(sqeCtx SQEContext, events []EpollEvent, timeout int32, options ...OpOptionFunc) error
- func (ur *Uring) ExtSQE() *ExtSQE
- func (ur *Uring) FGetXattr(sqeCtx SQEContext, name string, value []byte, options ...OpOptionFunc) error
- func (ur *Uring) FSetXattr(sqeCtx SQEContext, name string, value []byte, flags uint32, ...) error
- func (ur *Uring) FTruncate(sqeCtx SQEContext, length int64, options ...OpOptionFunc) error
- func (ur *Uring) Fallocate(sqeCtx SQEContext, mode uint32, offset int64, length int64, ...) error
- func (ur *Uring) FileAdvise(sqeCtx SQEContext, offset int64, length int, advice uint32, ...) error
- func (ur *Uring) FilesUpdate(sqeCtx SQEContext, fds []int32, offset int, options ...OpOptionFunc) error
- func (ur *Uring) FixedFdInstall(sqeCtx SQEContext, fixedIndex int, flags uint32, options ...OpOptionFunc) error
- func (ur *Uring) FutexWait(sqeCtx SQEContext, addr *uint32, val uint64, mask uint64, flags uint32, ...) error
- func (ur *Uring) FutexWaitV(sqeCtx SQEContext, waitv unsafe.Pointer, count uint32, flags uint32, ...) error
- func (ur *Uring) FutexWake(sqeCtx SQEContext, addr *uint32, val uint64, mask uint64, flags uint32, ...) error
- func (ur *Uring) GetXattr(sqeCtx SQEContext, path, name string, value []byte, options ...OpOptionFunc) error
- func (ur *Uring) IndirectSQE() *IndirectSQE
- func (ur *Uring) LinkAt(sqeCtx SQEContext, oldDirfd iofd.FD, oldPath, newPath string, flags uint32, ...) error
- func (ur *Uring) LinkTimeout(sqeCtx SQEContext, d time.Duration, options ...OpOptionFunc) error
- func (ur *Uring) Listen(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) MkdirAt(sqeCtx SQEContext, path string, mode uint32, options ...OpOptionFunc) error
- func (ur *Uring) MsgRing(sqeCtx SQEContext, userData int64, result int32, options ...OpOptionFunc) error
- func (ur *Uring) MsgRingFD(sqeCtx SQEContext, srcFD uint32, dstSlot uint32, userData int64, skipCQE bool, ...) error
- func (ur *Uring) Multicast(sqeCtx SQEContext, targets SendTargets, bufIndex int, p []byte, offset int64, ...) (int, error)
- func (ur *Uring) MulticastZeroCopy(sqeCtx SQEContext, targets SendTargets, bufIndex int, offset int64, n int, ...) (int, error)
- func (ur *Uring) MustExtSQE() *ExtSQE
- func (ur *Uring) NAPIAddStaticID(napiID uint32) error
- func (ur *Uring) NAPIDelStaticID(napiID uint32) error
- func (ur *Uring) NewScopedExtSQE() ScopedExtSQE
- func (ur *Uring) Nop(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) Nop128(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) OpenAt(sqeCtx SQEContext, pathname string, openFlags uint32, mode uint32, ...) error
- func (ur *Uring) Pipe(sqeCtx SQEContext, fds *[2]iofd.FD, pipeFlags uint32, options ...OpOptionFunc) error
- func (ur *Uring) PollAdd(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
- func (ur *Uring) PollAddLevel(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
- func (ur *Uring) PollAddMultishot(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
- func (ur *Uring) PollAddMultishotLevel(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
- func (ur *Uring) PollRemove(sqeCtx SQEContext, targetUserData uint64, options ...OpOptionFunc) error
- func (ur *Uring) PollUpdate(sqeCtx SQEContext, oldUserData, newUserData uint64, newEvents, updateFlags int, ...) error
- func (ur *Uring) PutExtSQE(sqe *ExtSQE)
- func (ur *Uring) PutIndirectSQE(sqe *IndirectSQE)
- func (ur *Uring) QueryOpcodes() (*QueryOpcode, error)
- func (ur *Uring) QuerySCQ() (*QuerySCQ, error)
- func (ur *Uring) QueryZCRX() (*QueryZCRX, error)
- func (ur *Uring) Read(sqeCtx SQEContext, b []byte, options ...OpOptionFunc) error
- func (ur *Uring) ReadFixed(sqeCtx SQEContext, bufIndex int, options ...OpOptionFunc) ([]byte, error)
- func (ur *Uring) ReadV(sqeCtx SQEContext, iovs [][]byte, options ...OpOptionFunc) error
- func (ur *Uring) ReadvFixed(sqeCtx SQEContext, offset int64, bufIndex int, iovs [][]byte, ...) error
- func (ur *Uring) Receive(sqeCtx SQEContext, pollFD PollFd, b []byte, options ...OpOptionFunc) error
- func (ur *Uring) ReceiveBundle(sqeCtx SQEContext, pollFD PollFd, options ...OpOptionFunc) error
- func (ur *Uring) ReceiveFD(sqeCtx SQEContext, fd iofd.FD, b []byte, options ...OpOptionFunc) error
- func (ur *Uring) ReceiveMultishot(sqeCtx SQEContext, handler MultishotHandler, options ...OpOptionFunc) (*MultishotSubscription, error)
- func (ur *Uring) ReceiveZeroCopy(sqeCtx SQEContext, pollFD PollFd, n int, zcrxIfqIdx uint32, ...) error
- func (ur *Uring) RecvMsg(sqeCtx SQEContext, pollFD PollFd, msg *Msghdr, options ...OpOptionFunc) error
- func (ur *Uring) RegisterBufRingIncremental(entries int, groupID uint16) (*BufferRing, error)
- func (ur *Uring) RegisterBufRingMMAP(entries int, groupID uint16) (*BufferRing, error)
- func (ur *Uring) RegisterBufRingWithFlags(entries int, groupID uint16, flags uint16) (*BufferRing, error)
- func (ur *Uring) RegisterFiles(fds []int32) error
- func (ur *Uring) RegisterFilesSparse(count uint32) error
- func (ur *Uring) RegisterFilesUpdate(offset uint32, fds []int32) (int, error)
- func (ur *Uring) RegisterMemRegion(region *RegionDesc, flags uint64) error
- func (ur *Uring) RegisterNAPI(busyPollTimeout uint32, preferBusyPoll bool, strategy uint32) error
- func (ur *Uring) RegisterZCRXIfq(ifIdx, ifRxq uint32, rqEntries uint32, area *ZCRXAreaReg, region *RegionDesc, ...) (ZCRXIfqRegistration, error)
- func (ur *Uring) RegisteredBuffer(index int) []byte
- func (ur *Uring) RegisteredBufferCount() int
- func (ur *Uring) RegisteredFileCount() int
- func (ur *Uring) RenameAt(sqeCtx SQEContext, oldPath, newPath string, flags uint32, ...) error
- func (ur *Uring) ResizeRings(newSQSize, newCQSize uint32) error
- func (ur *Uring) RingFD() iofd.FD
- func (ur *Uring) SCTP4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) SCTP4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) SCTP6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) SCTP6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) SQAvailable() int
- func (ur *Uring) Send(sqeCtx SQEContext, pollFD PollFd, p []byte, options ...OpOptionFunc) error
- func (ur *Uring) SendFD(sqeCtx SQEContext, fd iofd.FD, p []byte, options ...OpOptionFunc) error
- func (ur *Uring) SendMsg(sqeCtx SQEContext, pollFD PollFd, buffers [][]byte, oob []byte, to Addr, ...) error
- func (ur *Uring) SendMsgHeader(sqeCtx SQEContext, fd iofd.FD, msg *Msghdr, options ...OpOptionFunc) error
- func (ur *Uring) SetXattr(sqeCtx SQEContext, path, name string, value []byte, flags uint32, ...) error
- func (ur *Uring) Shutdown(sqeCtx SQEContext, how int, options ...OpOptionFunc) error
- func (ur *Uring) SocketDirect(sqeCtx SQEContext, domain, typ, proto int, fileIndex uint32, ...) error
- func (ur *Uring) SocketRaw(sqeCtx SQEContext, domain, typ, proto int, options ...OpOptionFunc) error
- func (ur *Uring) Splice(sqeCtx SQEContext, fdIn iofd.FD, n int, options ...OpOptionFunc) error
- func (ur *Uring) Start() (err error)
- func (ur *Uring) Statx(sqeCtx SQEContext, path string, flags, mask uint32, stat *Statx, ...) error
- func (ur *Uring) Stop() error
- func (ur *Uring) SubmitAcceptDirectMultishot(sqeCtx SQEContext, fileIndex uint32, options ...OpOptionFunc) error
- func (ur *Uring) SubmitAcceptMultishot(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) SubmitExtended(sqeCtx SQEContext) error
- func (ur *Uring) SubmitReceiveBundleMultishot(sqeCtx SQEContext, pollFD PollFd, options ...OpOptionFunc) error
- func (ur *Uring) SubmitReceiveMultishot(sqeCtx SQEContext, pollFD PollFd, b []byte, options ...OpOptionFunc) error
- func (ur *Uring) SubmitReceiveMultishotFD(sqeCtx SQEContext, fd iofd.FD, b []byte, options ...OpOptionFunc) error
- func (ur *Uring) SymlinkAt(sqeCtx SQEContext, target, linkpath string, options ...OpOptionFunc) error
- func (ur *Uring) Sync(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) SyncFileRange(sqeCtx SQEContext, offset int64, length int, syncFlags uint32, ...) error
- func (ur *Uring) TCP4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) TCP4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) TCP6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) TCP6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) Tee(sqeCtx SQEContext, fdIn iofd.FD, length int, options ...OpOptionFunc) error
- func (ur *Uring) Timeout(sqeCtx SQEContext, d time.Duration, options ...OpOptionFunc) error
- func (ur *Uring) TimeoutRemove(sqeCtx SQEContext, userData uint64, options ...OpOptionFunc) error
- func (ur *Uring) TimeoutUpdate(sqeCtx SQEContext, userData uint64, d time.Duration, absolute bool, ...) error
- func (ur *Uring) UDP4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDP4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDP6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDP6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDPLITE4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDPLITE4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDPLITE6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UDPLITE6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UnixSocket(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UnixSocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
- func (ur *Uring) UnlinkAt(sqeCtx SQEContext, path string, flags uint32, options ...OpOptionFunc) error
- func (ur *Uring) UnregisterFiles() error
- func (ur *Uring) UnregisterNAPI() error
- func (ur *Uring) UringCmd(sqeCtx SQEContext, cmdOp uint32, cmdData []byte, options ...OpOptionFunc) error
- func (ur *Uring) UringCmd128(sqeCtx SQEContext, cmdOp uint32, cmdData []byte, options ...OpOptionFunc) error
- func (ur *Uring) UringCmdInline(sqeCtx SQEContext, cmdOp uint32, cmdData []byte, options ...OpOptionFunc) error
- func (ur *Uring) Wait(cqes []CQEView) (n int, err error)
- func (ur *Uring) WaitDirect(cqes []DirectCQE) (int, error)
- func (ur *Uring) WaitExtended(cqes []ExtCQE) (int, error)
- func (ur *Uring) Waitid(sqeCtx SQEContext, idtype, id int, infop unsafe.Pointer, options int, ...) error
- func (ur *Uring) WithExtSQE(fn func(ext *ExtSQE) error) error
- func (ur *Uring) Write(sqeCtx SQEContext, b []byte, options ...OpOptionFunc) error
- func (ur *Uring) WriteFixed(sqeCtx SQEContext, bufIndex int, n int, options ...OpOptionFunc) error
- func (ur *Uring) WriteV(sqeCtx SQEContext, iovs [][]byte, options ...OpOptionFunc) error
- func (ur *Uring) WritevFixed(sqeCtx SQEContext, offset int64, bufIndex int, iovs [][]byte, ...) error
- func (ur *Uring) ZCRXExport(zcrxID uint32) (iofd.FD, error)
- func (ur *Uring) ZCRXFlushRQ(zcrxID uint32) error
- type VastBuffer
- type ZCHandler
- type ZCRXAreaReg
- type ZCRXBuffer
- type ZCRXConfig
- type ZCRXCqe
- type ZCRXCtrl
- type ZCRXHandler
- type ZCRXIfqReg
- type ZCRXIfqRegistration
- type ZCRXOffsets
- type ZCRXReceiver
- type ZCRXRqe
- type ZCSubscriber
- type ZCTracker
Constants ¶
const ( KiB = 1 << 10 MiB = 1 << 20 GiB = 1 << 30 )
Memory size constants for budget specification.
const ( MachineMemory512MB = 512 * MiB MachineMemory1GB = 1 * GiB MachineMemory2GB = 2 * GiB MachineMemory4GB = 4 * GiB MachineMemory8GB = 8 * GiB MachineMemory16GB = 16 * GiB MachineMemory32GB = 32 * GiB MachineMemory64GB = 64 * GiB MachineMemory96GB = 96 * GiB MachineMemory128GB = 128 * GiB )
Common machine memory sizes for OptionsForSystem.
const ( BufferSizePico = iobuf.BufferSizePico // 32 B BufferSizeNano = iobuf.BufferSizeNano // 128 B BufferSizeMicro = iobuf.BufferSizeMicro // 512 B BufferSizeSmall = iobuf.BufferSizeSmall // 2 KiB BufferSizeMedium = iobuf.BufferSizeMedium // 8 KiB BufferSizeBig = iobuf.BufferSizeBig // 32 KiB BufferSizeLarge = iobuf.BufferSizeLarge // 128 KiB BufferSizeGreat = iobuf.BufferSizeGreat // 512 KiB BufferSizeHuge = iobuf.BufferSizeHuge // 2 MiB BufferSizeVast = iobuf.BufferSizeVast // 8 MiB BufferSizeGiant = iobuf.BufferSizeGiant // 32 MiB BufferSizeTitan = iobuf.BufferSizeTitan // 128 MiB )
Buffer size constants re-exported from iobuf for API compatibility. These follow a power-of-4 progression starting at 32 bytes.
const ( EPERM = uintptr(zcall.EPERM) EINTR = uintptr(zcall.EINTR) EAGAIN = uintptr(zcall.EAGAIN) EWOULDBLOCK = EAGAIN ENOMEM = uintptr(zcall.ENOMEM) EACCES = uintptr(zcall.EACCES) EFAULT = uintptr(zcall.EFAULT) EBUSY = uintptr(zcall.EBUSY) EEXIST = uintptr(zcall.EEXIST) ENAMETOOLONG = uintptr(zcall.ENAMETOOLONG) ENODEV = uintptr(zcall.ENODEV) EINVAL = uintptr(zcall.EINVAL) EPIPE = uintptr(zcall.EPIPE) EMFILE = uintptr(zcall.EMFILE) ENFILE = uintptr(zcall.ENFILE) ENOSYS = uintptr(zcall.ENOSYS) ENOTSUP = uintptr(zcall.ENOTSUP) EINPROGRESS = uintptr(zcall.EINPROGRESS) EALREADY = uintptr(zcall.EALREADY) ENOTSOCK = uintptr(zcall.ENOTSOCK) EDESTADDRREQ = uintptr(zcall.EDESTADDRREQ) EMSGSIZE = uintptr(zcall.EMSGSIZE) EPROTOTYPE = uintptr(zcall.EPROTOTYPE) ENOPROTOOPT = uintptr(zcall.ENOPROTOOPT) EPROTONOSUPPORT = uintptr(zcall.EPROTONOSUPPORT) EOPNOTSUPP = uintptr(zcall.EOPNOTSUPP) EAFNOSUPPORT = uintptr(zcall.EAFNOSUPPORT) EADDRINUSE = uintptr(zcall.EADDRINUSE) EADDRNOTAVAIL = uintptr(zcall.EADDRNOTAVAIL) ENETDOWN = uintptr(zcall.ENETDOWN) ENETUNREACH = uintptr(zcall.ENETUNREACH) ENETRESET = uintptr(zcall.ENETRESET) ECONNABORTED = uintptr(zcall.ECONNABORTED) ECONNRESET = uintptr(zcall.ECONNRESET) ENOBUFS = uintptr(zcall.ENOBUFS) EISCONN = uintptr(zcall.EISCONN) ENOTCONN = uintptr(zcall.ENOTCONN) ESHUTDOWN = uintptr(zcall.ESHUTDOWN) ETIMEDOUT = uintptr(zcall.ETIMEDOUT) ECONNREFUSED = uintptr(zcall.ECONNREFUSED) EHOSTDOWN = uintptr(zcall.EHOSTDOWN) EHOSTUNREACH = uintptr(zcall.EHOSTUNREACH) ECANCELED = uintptr(zcall.ECANCELED) )
Errno constants aliased from zcall for architecture-safe error handling.
const ( EntriesPico = 1 << 3 // 8 entries EntriesNano = 1 << 5 // 32 entries EntriesMicro = 1 << 7 // 128 entries EntriesSmall = 1 << 9 // 512 entries EntriesMedium = 1 << 11 // 2048 entries EntriesLarge = 1 << 13 // 8192 entries EntriesHuge = 1 << 15 // 32768 entries )
Uring entry count constants define submission queue sizes. The values scale by powers of four: 8, 32, 128, 512, 2048, 8192, and 32768.
const ( IORING_SETUP_IOPOLL = zcall.IORING_SETUP_IOPOLL IORING_SETUP_SQPOLL = zcall.IORING_SETUP_SQPOLL IORING_SETUP_SQ_AFF = zcall.IORING_SETUP_SQ_AFF IORING_SETUP_CQSIZE = zcall.IORING_SETUP_CQSIZE IORING_SETUP_CLAMP = zcall.IORING_SETUP_CLAMP IORING_SETUP_ATTACH_WQ = zcall.IORING_SETUP_ATTACH_WQ IORING_SETUP_R_DISABLED = zcall.IORING_SETUP_R_DISABLED IORING_SETUP_SUBMIT_ALL = zcall.IORING_SETUP_SUBMIT_ALL IORING_SETUP_COOP_TASKRUN = zcall.IORING_SETUP_COOP_TASKRUN IORING_SETUP_TASKRUN_FLAG = zcall.IORING_SETUP_TASKRUN_FLAG IORING_SETUP_SQE128 = zcall.IORING_SETUP_SQE128 IORING_SETUP_CQE32 = zcall.IORING_SETUP_CQE32 IORING_SETUP_SINGLE_ISSUER = zcall.IORING_SETUP_SINGLE_ISSUER IORING_SETUP_DEFER_TASKRUN = zcall.IORING_SETUP_DEFER_TASKRUN IORING_SETUP_NO_MMAP = zcall.IORING_SETUP_NO_MMAP IORING_SETUP_REGISTERED_FD_ONLY = zcall.IORING_SETUP_REGISTERED_FD_ONLY IORING_SETUP_NO_SQARRAY = zcall.IORING_SETUP_NO_SQARRAY IORING_SETUP_HYBRID_IOPOLL = zcall.IORING_SETUP_HYBRID_IOPOLL IORING_SETUP_CQE_MIXED = zcall.IORING_SETUP_CQE_MIXED // Allow both 16b and 32b CQEs IORING_SETUP_SQE_MIXED = zcall.IORING_SETUP_SQE_MIXED // Allow both 64b and 128b SQEs )
const ( IORING_ENTER_GETEVENTS = zcall.IORING_ENTER_GETEVENTS IORING_ENTER_SQ_WAKEUP = zcall.IORING_ENTER_SQ_WAKEUP IORING_ENTER_SQ_WAIT = zcall.IORING_ENTER_SQ_WAIT IORING_ENTER_EXT_ARG = zcall.IORING_ENTER_EXT_ARG IORING_ENTER_REGISTERED_RING = zcall.IORING_ENTER_REGISTERED_RING IORING_ENTER_ABS_TIMER = zcall.IORING_ENTER_ABS_TIMER // Absolute timeout IORING_ENTER_EXT_ARG_REG = zcall.IORING_ENTER_EXT_ARG_REG // Use registered wait region IORING_ENTER_NO_IOWAIT = zcall.IORING_ENTER_NO_IOWAIT // Skip I/O-wait accounting; may still block )
const ( IORING_OFF_SQ_RING int64 = 0 IORING_OFF_CQ_RING int64 = 0x8000000 IORING_OFF_SQES int64 = 0x10000000 IORING_OFF_PBUF_RING = 0x80000000 IORING_OFF_PBUF_SHIFT = 16 IORING_OFF_MMAP_MASK = 0xf8000000 )
const ( IORING_SQ_NEED_WAKEUP = 1 << iota IORING_SQ_CQ_OVERFLOW IORING_SQ_TASKRUN )
const ( IOSQE_FIXED_FILE = zcall.IOSQE_FIXED_FILE IOSQE_IO_DRAIN = zcall.IOSQE_IO_DRAIN IOSQE_IO_LINK = zcall.IOSQE_IO_LINK IOSQE_IO_HARDLINK = zcall.IOSQE_IO_HARDLINK IOSQE_ASYNC = zcall.IOSQE_ASYNC IOSQE_BUFFER_SELECT = zcall.IOSQE_BUFFER_SELECT IOSQE_CQE_SKIP_SUCCESS = zcall.IOSQE_CQE_SKIP_SUCCESS )
const ( IORING_POLL_ADD_MULTI = 1 << iota IORING_POLL_UPDATE_EVENTS IORING_POLL_UPDATE_USER_DATA IORING_POLL_ADD_LEVEL )
const ( IORING_ASYNC_CANCEL_ALL = 1 << iota IORING_ASYNC_CANCEL_FD IORING_ASYNC_CANCEL_ANY IORING_ASYNC_CANCEL_FD_FIXED IORING_ASYNC_CANCEL_USERDATA IORING_ASYNC_CANCEL_OP )
const ( IORING_CQE_F_BUFFER = 1 << 0 IORING_CQE_F_MORE = 1 << 1 IORING_CQE_F_SOCK_NONEMPTY = 1 << 2 IORING_CQE_F_NOTIF = 1 << 3 IORING_CQE_F_BUF_MORE = 1 << 4 // Buffer partially consumed (incremental mode) IORING_CQE_F_SKIP = 1 << 5 // Skip CQE (gap filler for ring wrap) IORING_CQE_F_32 = 1 << 15 // 32-byte CQE in mixed mode )
const ( IORING_REGISTER_BUFFERS = zcall.IORING_REGISTER_BUFFERS IORING_UNREGISTER_BUFFERS = zcall.IORING_UNREGISTER_BUFFERS IORING_REGISTER_FILES = zcall.IORING_REGISTER_FILES IORING_UNREGISTER_FILES = zcall.IORING_UNREGISTER_FILES IORING_REGISTER_EVENTFD = zcall.IORING_REGISTER_EVENTFD IORING_UNREGISTER_EVENTFD = zcall.IORING_UNREGISTER_EVENTFD IORING_REGISTER_FILES_UPDATE = zcall.IORING_REGISTER_FILES_UPDATE IORING_REGISTER_EVENTFD_ASYNC = zcall.IORING_REGISTER_EVENTFD_ASYNC IORING_REGISTER_PROBE = zcall.IORING_REGISTER_PROBE IORING_REGISTER_PERSONALITY = zcall.IORING_REGISTER_PERSONALITY IORING_UNREGISTER_PERSONALITY = zcall.IORING_UNREGISTER_PERSONALITY IORING_REGISTER_RESTRICTIONS = zcall.IORING_REGISTER_RESTRICTIONS IORING_REGISTER_ENABLE_RINGS = zcall.IORING_REGISTER_ENABLE_RINGS IORING_REGISTER_FILES2 = zcall.IORING_REGISTER_FILES2 IORING_REGISTER_FILES_UPDATE2 = zcall.IORING_REGISTER_FILES_UPDATE2 IORING_REGISTER_BUFFERS2 = zcall.IORING_REGISTER_BUFFERS2 IORING_REGISTER_BUFFERS_UPDATE = zcall.IORING_REGISTER_BUFFERS_UPDATE IORING_REGISTER_IOWQ_AFF = zcall.IORING_REGISTER_IOWQ_AFF IORING_UNREGISTER_IOWQ_AFF = zcall.IORING_UNREGISTER_IOWQ_AFF IORING_REGISTER_IOWQ_MAX_WORKERS = zcall.IORING_REGISTER_IOWQ_MAX_WORKERS IORING_REGISTER_RING_FDS = zcall.IORING_REGISTER_RING_FDS IORING_UNREGISTER_RING_FDS = zcall.IORING_UNREGISTER_RING_FDS IORING_REGISTER_PBUF_RING = zcall.IORING_REGISTER_PBUF_RING IORING_UNREGISTER_PBUF_RING = zcall.IORING_UNREGISTER_PBUF_RING IORING_REGISTER_SYNC_CANCEL = zcall.IORING_REGISTER_SYNC_CANCEL IORING_REGISTER_FILE_ALLOC_RANGE = zcall.IORING_REGISTER_FILE_ALLOC_RANGE IORING_REGISTER_PBUF_STATUS = zcall.IORING_REGISTER_PBUF_STATUS IORING_REGISTER_NAPI = zcall.IORING_REGISTER_NAPI IORING_UNREGISTER_NAPI = zcall.IORING_UNREGISTER_NAPI IORING_REGISTER_CLOCK = zcall.IORING_REGISTER_CLOCK // Register clock source IORING_REGISTER_CLONE_BUFFERS = zcall.IORING_REGISTER_CLONE_BUFFERS // Clone buffers from another ring IORING_REGISTER_SEND_MSG_RING = zcall.IORING_REGISTER_SEND_MSG_RING // Send MSG_RING without ring IORING_REGISTER_ZCRX_IFQ = zcall.IORING_REGISTER_ZCRX_IFQ // Register ZCRX interface queue IORING_REGISTER_RESIZE_RINGS = zcall.IORING_REGISTER_RESIZE_RINGS // Resize SQ and CQ rings IORING_REGISTER_MEM_REGION = zcall.IORING_REGISTER_MEM_REGION // Memory region setup (6.13+) IORING_REGISTER_QUERY = zcall.IORING_REGISTER_QUERY // Query ring state (6.18+) IORING_REGISTER_ZCRX_CTRL = zcall.IORING_REGISTER_ZCRX_CTRL // ZCRX control operations (6.19+) )
const ( FUTEX2_SIZE_U8 uint32 = 0x00 // 8-bit futex FUTEX2_SIZE_U16 uint32 = 0x01 // 16-bit futex FUTEX2_SIZE_U32 uint32 = 0x02 // 32-bit futex (most common) FUTEX2_SIZE_U64 uint32 = 0x03 // 64-bit futex FUTEX2_NUMA uint32 = 0x04 // NUMA-aware futex FUTEX2_PRIVATE uint32 = 128 // Private futex (process-local, faster) )
Futex2 flags for FutexWait/FutexWake operations. These follow the futex2(2) interface, not the legacy futex(2) v1 flags.
const ( // IORING_MSG_DATA sends data (result + userData) to target ring's CQ. IORING_MSG_DATA uint64 = 0 // IORING_MSG_SEND_FD transfers a fixed file from source to target ring. IORING_MSG_SEND_FD uint64 = 1 )
MSG_RING command types for the addr field.
const ( // IORING_MSG_RING_CQE_SKIP skips posting CQE to target ring. // The source ring still gets a completion. IORING_MSG_RING_CQE_SKIP uint32 = 1 << 0 // IORING_MSG_RING_FLAGS_PASS passes the specified flags to target CQE. IORING_MSG_RING_FLAGS_PASS uint32 = 1 << 1 )
MSG_RING flags for MsgRing operations.
const ( IOU_PBUF_RING_MMAP = 1 // Kernel allocates memory, app uses mmap IOU_PBUF_RING_INC = 2 // Incremental buffer consumption mode )
Buffer ring registration flags.
const ( IORING_ZCRX_AREA_SHIFT = 48 IORING_ZCRX_AREA_MASK = ^((uint64(1) << IORING_ZCRX_AREA_SHIFT) - 1) )
ZCRX area shift and mask for encoding area ID into offsets.
const ( ZCRX_CTRL_FLUSH_RQ = 0 // Flush refill queue ZCRX_CTRL_EXPORT = 1 // Export ZCRX state )
ZCRX control operations.
const ( IO_URING_QUERY_OPCODES = 0 // Query supported opcodes IO_URING_QUERY_ZCRX = 1 // Query ZCRX capabilities IO_URING_QUERY_SCQ = 2 // Query SQ/CQ ring info )
Query operation types for IORING_REGISTER_QUERY.
const ( IO_URING_NAPI_REGISTER_OP = 0 // Register/unregister (backward compatible) IO_URING_NAPI_STATIC_ADD_ID = 1 // Add NAPI ID with static tracking IO_URING_NAPI_STATIC_DEL_ID = 2 // Delete NAPI ID with static tracking )
NAPI operation types.
const ( IO_URING_NAPI_TRACKING_DYNAMIC = 0 // Dynamic tracking (default) IO_URING_NAPI_TRACKING_STATIC = 1 // Static tracking IO_URING_NAPI_TRACKING_INACTIVE = 255 // Inactive/disabled )
NAPI tracking strategies.
const ( SOCKET_URING_OP_SIOCINQ = 0 // Get input queue size SOCKET_URING_OP_SIOCOUTQ = 1 // Get output queue size SOCKET_URING_OP_GETSOCKOPT = 2 // Get socket option SOCKET_URING_OP_SETSOCKOPT = 3 // Set socket option SOCKET_URING_OP_TX_TIMESTAMP = 4 // TX timestamp support SOCKET_URING_OP_GETSOCKNAME = 5 // Get socket name )
Socket uring command operations.
const ( IORING_TIMESTAMP_HW_SHIFT = 16 // CQE flags bit shift for HW timestamp IORING_TIMESTAMP_TYPE_SHIFT = IORING_TIMESTAMP_HW_SHIFT + 1 // CQE flags bit shift for timestamp type IORING_CQE_F_TSTAMP_HW = 1 << IORING_TIMESTAMP_HW_SHIFT // Hardware timestamp flag )
Timestamp constants for SOCKET_URING_OP_TX_TIMESTAMP.
const ( IORING_NOP_INJECT_RESULT = 1 << 0 // Inject result from sqe->result IORING_NOP_FILE = 1 << 1 // NOP with file reference IORING_NOP_FIXED_FILE = 1 << 2 // NOP with fixed file IORING_NOP_FIXED_BUFFER = 1 << 3 // NOP with fixed buffer IORING_NOP_TW = 1 << 4 // NOP via task work IORING_NOP_CQE32 = 1 << 5 // NOP produces 32-byte CQE )
NOP operation flags for IORING_OP_NOP.
const ( IORING_REGISTER_SRC_REGISTERED = 1 << 0 // Source ring is registered IORING_REGISTER_DST_REPLACE = 1 << 1 // Replace destination buffers )
Clone buffers registration flags.
const ( IOPrioClassNone = 0 IOPrioClassRT = 1 // Real-time IOPrioClassBE = 2 // Best-effort IOPrioClassIDLE = 3 // Idle )
I/O priority class constants for WithIOPrioClass.
const ( IORING_OP_NOP uint8 = iota IORING_OP_READV IORING_OP_WRITEV IORING_OP_FSYNC IORING_OP_READ_FIXED IORING_OP_WRITE_FIXED IORING_OP_POLL_ADD IORING_OP_POLL_REMOVE IORING_OP_SYNC_FILE_RANGE IORING_OP_SENDMSG IORING_OP_RECVMSG IORING_OP_TIMEOUT IORING_OP_TIMEOUT_REMOVE IORING_OP_ACCEPT IORING_OP_ASYNC_CANCEL IORING_OP_LINK_TIMEOUT IORING_OP_CONNECT IORING_OP_FALLOCATE IORING_OP_OPENAT IORING_OP_CLOSE IORING_OP_FILES_UPDATE IORING_OP_STATX IORING_OP_READ IORING_OP_WRITE IORING_OP_FADVISE IORING_OP_MADVISE IORING_OP_SEND IORING_OP_RECV IORING_OP_OPENAT2 IORING_OP_EPOLL_CTL IORING_OP_SPLICE IORING_OP_PROVIDE_BUFFERS IORING_OP_REMOVE_BUFFERS IORING_OP_TEE IORING_OP_SHUTDOWN IORING_OP_RENAMEAT IORING_OP_UNLINKAT IORING_OP_MKDIRAT IORING_OP_SYMLINKAT IORING_OP_LINKAT IORING_OP_MSG_RING IORING_OP_FSETXATTR IORING_OP_SETXATTR IORING_OP_FGETXATTR IORING_OP_GETXATTR IORING_OP_SOCKET IORING_OP_URING_CMD IORING_OP_SEND_ZC IORING_OP_SENDMSG_ZC IORING_OP_READ_MULTISHOT IORING_OP_WAITID IORING_OP_FUTEX_WAIT IORING_OP_FUTEX_WAKE IORING_OP_FUTEX_WAITV IORING_OP_FIXED_FD_INSTALL IORING_OP_FTRUNCATE IORING_OP_BIND IORING_OP_LISTEN IORING_OP_RECV_ZC // Zero-copy receive IORING_OP_EPOLL_WAIT // Epoll wait IORING_OP_READV_FIXED // Vectored read with one fixed buffer IORING_OP_WRITEV_FIXED // Vectored write with one fixed buffer IORING_OP_PIPE // Create pipe IORING_OP_NOP128 // 128-byte NOP opcode IORING_OP_URING_CMD128 // 128-byte uring command opcode )
IORING_OP_* values encode io_uring operation types in SQEs and SQEContext.
const ( IORING_URING_CMD_FIXED = 1 << iota IORING_URING_CMD_MULTISHOT IORING_URING_CMD_MASK = IORING_URING_CMD_FIXED | IORING_URING_CMD_MULTISHOT )
URING_CMD operation flags.
const ( IORING_TIMEOUT_ABS = 1 << iota IORING_TIMEOUT_UPDATE IORING_TIMEOUT_BOOTTIME IORING_TIMEOUT_REALTIME IORING_LINK_TIMEOUT_UPDATE IORING_TIMEOUT_ETIME_SUCCESS IORING_TIMEOUT_MULTISHOT IORING_TIMEOUT_CLOCK_MASK = IORING_TIMEOUT_BOOTTIME | IORING_TIMEOUT_REALTIME IORING_TIMEOUT_UPDATE_MASK = IORING_TIMEOUT_UPDATE | IORING_LINK_TIMEOUT_UPDATE )
Timeout operation flags.
const ( IORING_ACCEPT_MULTISHOT = 1 << 0 // Multi-shot accept: one SQE, multiple completions IORING_ACCEPT_DONTWAIT = 1 << 1 // Non-blocking accept IORING_ACCEPT_POLL_FIRST = 1 << 2 // Poll for connection before accepting )
Accept operation flags.
const ( IORING_RECVSEND_POLL_FIRST = 1 << iota // Poll before send/recv IORING_RECV_MULTISHOT // Multi-shot receive IORING_RECVSEND_FIXED_BUF // Use registered buffer IORING_SEND_ZC_REPORT_USAGE // Report zero-copy usage IORING_RECVSEND_BUNDLE // Bundle mode IORING_SEND_VECTORIZED // Vectorized send )
Send/receive operation flags.
const ( DefaultBufferNumPico = 1 << 15 // 32768 × 32 B = 1 MiB DefaultBufferNumNano = 1 << 14 // 16384 × 128 B = 2 MiB DefaultBufferNumMicro = 1 << 13 // 8192 × 512 B = 4 MiB DefaultBufferNumSmall = 1 << 12 // 4096 × 2 KiB = 8 MiB DefaultBufferNumMedium = 1 << 11 // 2048 × 8 KiB = 16 MiB DefaultBufferNumBig = 1 << 10 // 1024 × 32 KiB = 32 MiB DefaultBufferNumLarge = 1 << 9 // 512 × 128 KiB = 64 MiB DefaultBufferNumGreat = 1 << 8 // 256 × 512 KiB = 128 MiB DefaultBufferNumHuge = 1 << 7 // 128 × 2 MiB = 256 MiB DefaultBufferNumVast = 1 << 6 // 64 × 8 MiB = 512 MiB DefaultBufferNumGiant = 1 << 5 // 32 × 32 MiB = 1 GiB DefaultBufferNumTitan = 1 << 4 // 16 × 128 MiB = 2 GiB )
Default buffer counts per tier. Smaller buffers have more instances to handle high-frequency small I/O. Larger buffers have fewer instances due to memory constraints.
const ( SizeofSockaddrAny = sock.SizeofSockaddrAny SizeofSockaddrInet4 = sock.SizeofSockaddrInet4 SizeofSockaddrInet6 = sock.SizeofSockaddrInet6 SizeofSockaddrUnix = sock.SizeofSockaddrUnix )
Raw socket address size constants.
const ( AF_UNIX = sock.AF_UNIX AF_LOCAL = sock.AF_LOCAL AF_INET = sock.AF_INET AF_INET6 = sock.AF_INET6 SOCK_STREAM = sock.SOCK_STREAM SOCK_DGRAM = sock.SOCK_DGRAM SOCK_RAW = sock.SOCK_RAW SOCK_SEQPACKET = sock.SOCK_SEQPACKET SOCK_NONBLOCK = sock.SOCK_NONBLOCK SOCK_CLOEXEC = sock.SOCK_CLOEXEC IPPROTO_IP = sock.IPPROTO_IP IPPROTO_RAW = sock.IPPROTO_RAW IPPROTO_TCP = sock.IPPROTO_TCP IPPROTO_UDP = sock.IPPROTO_UDP IPPROTO_IPV6 = sock.IPPROTO_IPV6 IPPROTO_SCTP = sock.IPPROTO_SCTP MSG_WAITALL = sock.MSG_WAITALL MSG_ZEROCOPY = sock.MSG_ZEROCOPY SHUT_RD = sock.SHUT_RD SHUT_WR = sock.SHUT_WR SHUT_RDWR = sock.SHUT_RDWR PROT_READ = zcall.PROT_READ PROT_WRITE = zcall.PROT_WRITE MAP_SHARED = zcall.MAP_SHARED MAP_POPULATE = zcall.MAP_POPULATE )
Socket, protocol, message, shutdown, and memory-mapping aliases.
const ( EPOLL_CTL_ADD = 1 EPOLL_CTL_DEL = 2 EPOLL_CTL_MOD = 3 EPOLLIN = 0x1 EPOLLOUT = 0x4 EPOLLET = 0x80000000 )
Epoll constants.
const ( NetworkUnix = sock.NetworkUnix NetworkIPv4 = sock.NetworkIPv4 NetworkIPv6 = sock.NetworkIPv6 )
Network family aliases use the target OS's address-family values.
const AT_FDCWD = -100
AT_FDCWD is the special value for current working directory.
const FUTEX_BITSET_MATCH_ANY uint64 = 0xFFFFFFFF
FUTEX_BITSET_MATCH_ANY matches any waker when used as mask in FutexWait.
const (
IORING_CQE_BUFFER_SHIFT = 16
)
const IORING_FILE_INDEX_ALLOC uint32 = 0xFFFFFFFF
IORING_FILE_INDEX_ALLOC is passed as file_index to have io_uring allocate a free direct descriptor slot. The allocated index is returned in cqe->res. Returns -ENFILE if no free slots available.
const IORING_FIXED_FD_NO_CLOEXEC uint32 = 1 << 0
IORING_FIXED_FD_NO_CLOEXEC omits O_CLOEXEC when installing a fixed fd. By default, FixedFdInstall sets O_CLOEXEC on the new regular fd.
const (
IORING_MEM_REGION_REG_WAIT_ARG = 1 // Expose region as registered wait arguments
)
Memory region registration flags.
const (
IORING_MEM_REGION_TYPE_USER = 1 // User-provided memory
)
Memory region types.
const IORING_NOTIF_USAGE_ZC_COPIED = 1 << 31
IORING_NOTIF_USAGE_ZC_COPIED is set in a send usage report if any data was copied or the send never used zero-copy.
const IORING_REGISTER_USE_REGISTERED_RING = zcall.IORING_REGISTER_USE_REGISTERED_RING
IORING_REGISTER_USE_REGISTERED_RING is a flag that can be OR'd with register opcodes to use a registered ring fd instead of a regular fd.
const (
IORING_REG_WAIT_TS = 1 << 0 // Timestamp in wait region
)
Registered wait flags.
const (
IORING_RSRC_REGISTER_SPARSE = 1 << 0 // Sparse registration
)
Resource registration flags.
const (
IORING_RW_ATTR_FLAG_PI = 1 << 0 // PI (Protection Information) attribute
)
RW attribute flags for sqe->attr_type_mask.
const (
IORING_ZCRX_AREA_DMABUF = 1 // Use DMA buffer
)
ZCRX area registration flags.
const (
IO_URING_OP_SUPPORTED = 1 << 0
)
const IPPROTO_UDPLITE = sock.IPPROTO_UDPLITE
IPPROTO_UDPLITE is UDP-Lite protocol number.
const O_LARGEFILE = 0x8000
O_LARGEFILE flag for openat.
const SizeofOpenHow = 24
SizeofOpenHow is the size of OpenHow structure.
const ZCRX_FEATURE_RX_PAGE_SIZE = 1 << 0
ZCRX query feature flags.
const (
ZCRX_REG_IMPORT = 1 // Import mode
)
ZCRX registration flags.
Variables ¶
var ( ErrInvalidParam = iofd.ErrInvalidParam ErrInterrupted = iofd.ErrInterrupted ErrNoMemory = iofd.ErrNoMemory ErrPermission = iofd.ErrPermission )
Common errors reused from iofd for semantic consistency across the ecosystem.
var ( // ErrInProgress indicates the operation is in progress. ErrInProgress = errors.New("uring: operation in progress") // ErrFaultParams indicates a fault in parameters (bad address). ErrFaultParams = errors.New("uring: fault in parameters") // ErrProcessFileLimit indicates the process file descriptor limit was reached. ErrProcessFileLimit = errors.New("uring: process file descriptor limit") // ErrSystemFileLimit indicates the system file descriptor limit was reached. ErrSystemFileLimit = errors.New("uring: system file descriptor limit") // ErrNoDevice indicates no such device. ErrNoDevice = errors.New("uring: no such device") // ErrNotSupported indicates the operation is not supported. ErrNotSupported = errors.New("uring: operation not supported") // ErrBusy indicates the resource is busy. ErrBusy = errors.New("uring: resource busy") // ErrClosed indicates the ring has already been stopped. ErrClosed = errors.New("uring: ring closed") // ErrCQOverflow indicates the CQ overflow condition was observed while the CQ appeared empty. ErrCQOverflow = errors.New("uring: completion queue overflow") // ErrExists indicates the resource already exists. ErrExists = errors.New("uring: already exists") // ErrNameTooLong indicates a pathname exceeds the kernel limit. ErrNameTooLong = errors.New("uring: name too long") // ErrNotFound indicates the resource was not found. ErrNotFound = errors.New("uring: not found") // ErrCanceled indicates the operation was canceled. ErrCanceled = errors.New("uring: operation canceled") // ErrTimedOut indicates the operation timed out. ErrTimedOut = errors.New("uring: operation timed out") // ErrConnectionRefused indicates the connection was refused. ErrConnectionRefused = errors.New("uring: connection refused") // ErrConnectionReset indicates the connection was reset. ErrConnectionReset = errors.New("uring: connection reset") // ErrNotConnected indicates the socket is not connected. ErrNotConnected = errors.New("uring: not connected") // ErrAlreadyConnected indicates the socket is already connected. ErrAlreadyConnected = errors.New("uring: already connected") // ErrAddressInUse indicates the address is already in use. ErrAddressInUse = errors.New("uring: address in use") // ErrNetworkUnreachable indicates the network is unreachable. ErrNetworkUnreachable = errors.New("uring: network unreachable") // ErrHostUnreachable indicates the host is unreachable. ErrHostUnreachable = errors.New("uring: host unreachable") // ErrBrokenPipe indicates the pipe is broken (EPIPE). ErrBrokenPipe = errors.New("uring: broken pipe") // ErrNoBufferSpace indicates no buffer space available (ENOBUFS). ErrNoBufferSpace = errors.New("uring: no buffer space available") )
Error definitions for uring operations.
var ErrNotReady = errors.New("uring: listener not ready")
ErrNotReady indicates the listener is not yet ready for accept.
Functions ¶
func AlignedMemBlock ¶
func AlignedMemBlock() []byte
AlignedMemBlock returns a page-aligned memory block.
func CastUserData ¶
CastUserData returns a borrowed *T over ext.UserData. T must fit within the 64-byte UserData array. Copy needed values before mutation, reuse, or release; never access the overlay after storage release. The GC does not trace UserData. Prefer pointer-free types; callers that store pointer-bearing values must keep their referents reachable outside UserData.
func CompletionError ¶
CompletionError decodes a matched operation result. Nonnegative values return nil. Negative values encode errno, with EAGAIN mapping to iox.ErrWouldBlock. Classify the CQE before calling this function. A Uring.MsgRing target carries the sender's signed value, and a SEND_ZC notification can carry usage flags. Consult the CQE flags separately to determine whether more completions follow.
func ContextUserData ¶
ContextUserData extracts a typed value from context. Returns the zero value of T if not found.
func ContextWithUserData ¶
ContextWithUserData returns a new context with the typed value stored.
func PrepareListenerBind ¶
PrepareListenerBind fills ext's SQE for IORING_OP_BIND using the sockaddr stored from PrepareListenerSocket. fd is the socket from SOCKET completion.
func PrepareListenerListen ¶
PrepareListenerListen fills ext's SQE for IORING_OP_LISTEN. fd is the bound socket, backlog from the stored context.
func PrepareListenerSocket ¶
func PrepareListenerSocket(ext *ExtSQE, domain, sockType, proto int, sa Sockaddr, backlog int, handler ListenerHandler) error
PrepareListenerSocket fills ext's SQE for IORING_OP_SOCKET and stores the sockaddr + backlog for subsequent stages. Small sockaddrs stay inline in ext.UserData; oversized ones stay anchored in the pooled sidecar. After calling this, submit with ring.SubmitExtended(PackExtended(ext)).
ext must be a pool-borrowed slot obtained from ContextPools.Extended. Passing a non-pooled ExtSQE is undefined behavior: the sidecar anchors live past the end of a standalone ExtSQE object.
A nil handler is normalized to NoopListenerHandler.
func SetListenerReady ¶
func SetListenerReady(ext *ExtSQE)
SetListenerReady marks the listener context as ready. Call after LISTEN completes successfully.
Types ¶
type AttrPI ¶
type AttrPI struct {
Flags uint16 // PI flags
AppTag uint16 // Application tag
Len uint32 // Length
Addr uint64 // Address
Seed uint64 // Seed value
// contains filtered or unexported fields
}
AttrPI is the PI attribute information for read/write operations. Matches struct io_uring_attr_pi in Linux.
type BufferGroupsConfig ¶
type BufferGroupsConfig struct {
PicoNum int // 32 B buffers
NanoNum int // 128 B buffers
MicroNum int // 512 B buffers
SmallNum int // 2 KiB buffers
MediumNum int // 8 KiB buffers
BigNum int // 32 KiB buffers
LargeNum int // 128 KiB buffers
GreatNum int // 512 KiB buffers
HugeNum int // 2 MiB buffers
VastNum int // 8 MiB buffers
GiantNum int // 32 MiB buffers
TitanNum int // 128 MiB buffers
}
BufferGroupsConfig configures buffer counts for each tier.
Each field specifies the number of buffers to allocate for that tier. A zero count disables the tier (no memory allocated).
Memory usage calculation:
Total = Sum(TierSize × TierCount × Scale)
Example with the default config (Scale=1):
Pico: 32768 × 32 B = 1 MiB
Nano: 16384 × 128 B = 2 MiB
Micro: 8192 × 512 B = 4 MiB
Small: 4096 × 2 KiB = 8 MiB
Medium: 2048 × 8 KiB = 16 MiB
Big: 1024 × 32 KiB = 32 MiB
Large: 512 × 128 KiB = 64 MiB
Total ≈ 127 MiB per scale
func BufferConfigForBudget ¶
func BufferConfigForBudget(budget int) (BufferGroupsConfig, int)
BufferConfigForBudget returns the BufferGroupsConfig and scale selected for the given memory budget. Use this when you need to inspect or model the largest tier set that fits in the remaining buffer-group memory.
Budget handling matches OptionsForBudget's memory reservation:
- registered buffers target 25% of the budget, rounded upward with an 8 MiB minimum, and bounded by the package registration cap
- ring overhead is reserved from the same budget
- buffer groups use the remaining memory
- if the remaining memory cannot fit the minimal tier set, the returned config is empty and scale is 0
OptionsForBudget does not carry BufferGroupsConfig through Options. It sets Options.MultiSizeBuffer from the default buffer-group shape that New actually allocates, so the scale returned here can differ from OptionsForBudget for budgets where a smaller tier set fits but the default tier set does not.
Example:
cfg, scale := BufferConfigForBudget(256 * MiB) // cfg contains tier configuration, scale is the multiplier
func DefaultBufferGroupsConfig ¶
func DefaultBufferGroupsConfig() BufferGroupsConfig
DefaultBufferGroupsConfig returns the default configuration. It enables the first 7 tiers (Pico through Large), totaling ~127 MiB per scale.
func FullBufferGroupsConfig ¶
func FullBufferGroupsConfig() BufferGroupsConfig
FullBufferGroupsConfig returns configuration with all 12 tiers enabled. It uses ~4 GiB per scale. Use it only on high-memory systems.
func MinimalBufferGroupsConfig ¶
func MinimalBufferGroupsConfig() BufferGroupsConfig
MinimalBufferGroupsConfig returns a reduced configuration. It enables the first 5 tiers (Pico through Medium), totaling ~31 MiB per scale.
type BufferRing ¶
type BufferRing struct {
// contains filtered or unexported fields
}
BufferRing is an opaque handle to an explicitly registered provided-buffer ring. Registration returns an initialized empty ring; Add stages buffers and Advance publishes them to the kernel. The handle is owned by its Uring and remains valid only until Uring.Stop.
Each Add records the buffer address and does not retain the buffer. Caller must keep every added buffer's backing storage reachable and at the same address from the Add call until a completion returns ownership or Uring.Stop tears down the ring. Ownership transfers to the kernel on Advance; do not mutate or reuse a published buffer while the kernel owns it. Add and Advance are not safe for concurrent use.
func (*BufferRing) Add ¶
func (r *BufferRing) Add(buf []byte, bid uint16, offset int) error
Add stages buf at offset from the current unpublished tail with buffer ID bid. offset must be in [0, entries), and len(buf) must be in [1, math.MaxUint32]. Add records buf's address but does not retain buf or transfer ownership. Caller must keep its backing storage reachable and at the same address from this call until a completion returns ownership or Uring.Stop tears down the ring; a later Advance transfers ownership.
func (*BufferRing) Advance ¶
func (r *BufferRing) Advance(count int) error
Advance publishes count previously added buffers and transfers their ownership to the kernel. count must be in [0, entries].
type BundleIterator ¶
type BundleIterator struct {
// contains filtered or unexported fields
}
BundleIterator visits the buffers consumed by one bundle receive CQE in publication order, starting at the CQE's first buffer ID. Managed iterators preserve that order across out-of-order recycling.
The iterator and its buffer slices borrow the original storage. Copying an iterator or collecting its slices does not extend the buffers' lifetime. Finish all borrowed access before recycling buffers or tearing down the ring.
func NewBundleIterator ¶
func NewBundleIterator(cqe CQEView, bufBacking []byte, bufSize int, ringEntries int) (BundleIterator, bool)
NewBundleIterator creates an iterator for the buffers consumed by a bundle CQE.
Parameters:
- cqe: the CQE from a bundle receive operation
- bufBacking: backing memory for the full ring, such as the slice returned by AlignedMem
- bufSize: size of each buffer in the ring
- ringEntries: number of entries in the buffer ring; must be a power of two less than 65536
bufBacking must remain alive for the iterator's lifetime and must cover at least bufSize*ringEntries bytes. For a kernel CQE, match the receive and check CQEView.HasBuffer before passing its byte count and first buffer ID to this constructor. This constructor requires buffers to have been published in consecutive ID order modulo ringEntries, with buffer ID i stored at offset i*bufSize. A CQE alone cannot recover arbitrary publication order. For package-managed rings, use Uring.BundleIterator, which retains the actual order.
The returned iterator is read-only and has no Uring recycle authority. Recycle returns ErrInvalidParam for it. Use Uring.BundleIterator when the consumed buffers belong to a package-managed ring and must be recycled.
A selected slot returned at EOF or on error yields one empty slice. It returns false for invalid geometry or when there are no whole slots to visit.
func (BundleIterator) All ¶
func (it BundleIterator) All() iter.Seq[[]byte]
All yields borrowed buffer slices in publication order.
Usage:
for buf := range iter.All() {
process(buf)
}
func (BundleIterator) AllWithSlotID ¶
func (it BundleIterator) AllWithSlotID() iter.Seq2[uint16, []byte]
AllWithSlotID yields each buffer ID and its borrowed data in publication order.
Usage:
for id, buf := range iter.AllWithSlotID() {
fmt.Printf("Slot ID %d: %d bytes\n", id, len(buf))
}
func (BundleIterator) Buffer ¶
func (it BundleIterator) Buffer(index int) []byte
Buffer returns a borrowed slice at index, or nil if index is outside [0, Count()). The last buffer may be partial.
func (BundleIterator) Collect ¶
func (it BundleIterator) Collect() [][]byte
Collect returns borrowed buffer slices in publication order. It allocates the outer slice for a nonempty bundle; payload bytes remain in the original buffers. Use BundleIterator.All to iterate without allocating a result slice, or BundleIterator.CopyTo to copy payload bytes into caller-owned storage.
func (BundleIterator) CopyTo ¶
func (it BundleIterator) CopyTo(dst []byte) int
CopyTo copies bundle data into dst in publication order and returns min(len(dst), TotalBytes()). Copy into separate caller-owned storage to keep the bytes after recycling the buffers.
func (BundleIterator) Count ¶
func (it BundleIterator) Count() int
Count returns the number of buffers consumed in this bundle.
func (BundleIterator) Recycle ¶
func (it BundleIterator) Recycle(ur *Uring) error
Recycle returns all consumed buffers to the package-managed buffer ring and publishes them for kernel reuse.
Call Recycle after the bundle data has been fully processed and exactly once across all copies of an iterator. After Recycle returns, do not read any buffer yielded by the iterator or one of its copies; ownership of every consumed slot has returned to the kernel.
Recycle is single-threaded: do not call it concurrently with another Recycle on the same Uring, or with any other path that can race with buffer ring provide/advance.
Recycle returns ErrInvalidParam when the iterator came from NewBundleIterator or when ur is not the Uring that created the iterator.
func (BundleIterator) SlotID ¶
func (it BundleIterator) SlotID(index int) uint16
SlotID returns the buffer ID at the given index in the bundle. Managed iterators traverse publication order in O(index) time. Use AllWithSlotID for O(Count()) sequential iteration. Index must be in range [0, Count()).
func (BundleIterator) TotalBytes ¶
func (it BundleIterator) TotalBytes() int
TotalBytes returns the total bytes received in this bundle.
type CQEView ¶
type CQEView struct {
Res int32 // Completion result (directly accessible)
Flags uint32 // CQE flags (directly accessible)
// contains filtered or unexported fields
}
CQEView contains the result, flags, and user_data copied by Uring.Wait. For local requests, user_data is the submission context. Direct fields are inline. Indirect and Extended contexts borrow their targets without rooting them. Match incoming message IDs and Linux resource tags with Context().Raw() before using request accessors. Uring.MsgRing carries its signed value in Res.
Caller must keep targets live and serialize access. Copy needed facts before target mutation, reuse, or release; never dereference a released target. Caller code owns payload lifetimes, completion routing, and retirement.
Property Patterns ¶
- Direct: FullSQE reports false and Extended reports false. Available data: Op, SQE flags, BufGroup, FD, Res, and CQE flags.
- Indirect: FullSQE reports true and Extended reports false. Available data: Direct facts plus a borrowed 64-byte base SQE.
- Extended: FullSQE reports true and Extended reports true. Available data: Indirect facts plus the borrowed ExtSQE escape hatch.
Usage ¶
This ring submits local reads and zero-copy sends. Inspect every returned CQE, including notifications and failed requests.
n, err := ring.Wait(cqes)
for i := range n {
cqe := cqes[i]
if cqe.IsNotification() {
fmt.Printf("send notification on fd=%d\n", cqe.FD())
} else if err := cqe.Err(); err != nil {
fmt.Printf("completion failed: op=%d fd=%d: %v\n", cqe.Op(), cqe.FD(), err)
} else {
fmt.Printf("completed op=%d on fd=%d with res=%d\n", cqe.Op(), cqe.FD(), cqe.Res)
}
if cqe.HasMore() {
// Caller-side runtime code decides whether to keep routing this live stream.
}
if cqe.FullSQE() {
// Indirect and Extended modes also expose the submitted SQE.
fmt.Printf("submitted opcode=%d\n", cqe.SQE().Opcode())
}
}
if err != nil {
return err
}
func (*CQEView) BufGroup ¶
BufGroup returns the submission buffer group index. Direct mode reads the packed field; pointer modes return zero unless IOSQE_BUFFER_SELECT is set. A zero group ID can also be valid.
func (*CQEView) BufID ¶
BufID returns the buffer ID from CQE flags. Only valid when IORING_CQE_F_BUFFER flag is set.
func (*CQEView) BundleBuffers ¶
BundleBuffers returns the first ID and the slot count for an ordinary receive bundle with uniform bufferSize. At EOF or on error, F_BUFFER can return one slot with zero payload. F_BUF_MORE requires incremental buffer accounting. The remaining IDs follow publication order. See Uring.BundleIterator.
func (*CQEView) BundleCount ¶
BundleCount counts buffers containing payload bytes from Res, rounding up. bufferSize must be the uniform published buffer size. It returns zero when Res or bufferSize is non-positive.
func (*CQEView) BundleStartID ¶
BundleStartID returns the starting buffer ID for a bundle operation. Subsequent buffers follow publication order, not numeric ID order. Only valid when IORING_CQE_F_BUFFER flag is set.
func (*CQEView) Context ¶
func (c *CQEView) Context() SQEContext
Context returns the CQE's user_data as an SQEContext. For a local request, pointer modes retain the same borrowed target. Context().Raw() also preserves an incoming message ID or the tag of a retired Linux resource registration.
func (*CQEView) Err ¶
Err applies CompletionError to c.Res. Call it on a matched operation result.
func (*CQEView) ExtSQE ¶
ExtSQE returns the borrowed target for an Extended context. Caller must check Extended() and keep the target live; copy needed facts before target mutation, reuse, or release.
func (*CQEView) Extended ¶
Extended reports whether extended user data is available. Returns true only for Extended mode.
func (*CQEView) FD ¶
FD returns the file descriptor or registered-file index from a local request's live context.
func (*CQEView) FullSQE ¶
FullSQE reports whether the context retains a 64-byte base SQE. It is true for Indirect and Extended modes and does not include SQE128 extensions. The retained fields remain borrowed from the context target.
func (*CQEView) HasBufferMore ¶
HasBufferMore reports whether the buffer was partially consumed (incremental mode). When set, the same buffer ID remains valid for additional data.
func (*CQEView) HasMore ¶
HasMore reports IORING_CQE_F_MORE: the request has further completions, including multishot results or a zero-copy notification.
func (*CQEView) IsNotification ¶
IsNotification reports whether IORING_CQE_F_NOTIF is set.
func (*CQEView) SQE ¶
SQE borrows the retained 64-byte base SQE in Indirect and Extended modes. Direct mode returns an invalid view. Copy needed fields before target mutation, reuse, or release; copying the view preserves the same alias.
func (*CQEView) SocketNonEmpty ¶
SocketNonEmpty reports whether the kernel observed unread socket data after this receive. It is a completion-time hint, not a current readiness check.
type CloneBuffers ¶
type CloneBuffers struct {
SrcFD uint32 // Source ring file descriptor
Flags uint32 // IORING_REGISTER_SRC_* flags
SrcOff uint32 // Source buffer offset
DstOff uint32 // Destination buffer offset
Nr uint32 // Number of buffers to clone
// contains filtered or unexported fields
}
CloneBuffers describes a buffer clone operation. Matches struct io_uring_clone_buffers in Linux.
type ContextPools ¶
type ContextPools struct {
// contains filtered or unexported fields
}
ContextPools holds independent pools of IndirectSQE and ExtSQE contexts. The zero value is not usable; construct pools with NewContextPools. All methods except Reset are safe for concurrent use.
func NewContextPools ¶
func NewContextPools(capacity int) *ContextPools
NewContextPools creates pooled IndirectSQE and ExtSQE contexts with the given per-pool capacity. New pools are ready for immediate use. Capacity is rounded up to a power of two. Values outside [1, 1<<31] panic.
func (*ContextPools) Capacity ¶
func (p *ContextPools) Capacity() int
Capacity returns the per-pool slot count.
func (*ContextPools) Extended ¶
func (p *ContextPools) Extended() *ExtSQE
Extended borrows a cleared ExtSQE from the pool. Returns nil if exhausted. Return it with PutExtended after all operations and borrowed access finish.
func (*ContextPools) ExtendedAvailable ¶
func (p *ContextPools) ExtendedAvailable() int
ExtendedAvailable returns the number of ExtSQE slots available. The count is exact only when no borrow or return overlaps the call. Use Extended to acquire a slot; this count does not reserve one.
func (*ContextPools) Indirect ¶
func (p *ContextPools) Indirect() *IndirectSQE
Indirect borrows an IndirectSQE from the pool. Returns nil if exhausted. The slot retains its previous contents; initialize it before use. Return it with PutIndirect after all operations and borrowed access finish.
func (*ContextPools) IndirectAvailable ¶
func (p *ContextPools) IndirectAvailable() int
IndirectAvailable returns the number of IndirectSQE slots available. The count is exact only when no borrow or return overlaps the call. Use Indirect to acquire a slot; this count does not reserve one.
func (*ContextPools) PutExtended ¶
func (p *ContextPools) PutExtended(ext *ExtSQE)
PutExtended clears an ExtSQE's SQE, UserData, and sidecar anchors, then returns it to the pool. It must be an outstanding borrow from this pool with no pending operations or borrowed access. Do not access or return it again afterward.
func (*ContextPools) PutIndirect ¶
func (p *ContextPools) PutIndirect(indirect *IndirectSQE)
PutIndirect returns an IndirectSQE without clearing its contents. It must be an outstanding borrow from this pool with no pending operations or borrowed access. Do not access or return it again after this call.
func (*ContextPools) Reset ¶
func (p *ContextPools) Reset()
Reset scrubs pooled slot state and reinitializes both pool queues, making all slots available again. Caller must stop all pool access and finish operations using its contexts before calling Reset. Reset invalidates outstanding borrows; do not access or return those contexts afterward. Reset is not safe for concurrent use.
type Ctx0 ¶
Ctx0 has 0 refs, 0 vals, and 56 bytes of data.
type Ctx0V1 ¶
Ctx0V1 has 0 refs, 1 val, and 48 bytes of data.
type Ctx0V2 ¶
type Ctx0V2 struct {
Fn Handler // 8 bytes
Val1 int64 // 8 bytes
Val2 int64 // 8 bytes
Data [40]byte // 40 bytes
}
Ctx0V2 has 0 refs, 2 vals, and 40 bytes of data.
type Ctx0V3 ¶
type Ctx0V3 struct {
Fn Handler // 8 bytes
Val1 int64 // 8 bytes
Val2 int64 // 8 bytes
Val3 int64 // 8 bytes
Data [32]byte // 32 bytes
}
Ctx0V3 has 0 refs, 3 vals, and 32 bytes of data.
type Ctx0V4 ¶
type Ctx0V4 struct {
Fn Handler // 8 bytes
Val1 int64 // 8 bytes
Val2 int64 // 8 bytes
Val3 int64 // 8 bytes
Val4 int64 // 8 bytes
Data [24]byte // 24 bytes
}
Ctx0V4 has 0 refs, 4 vals, and 24 bytes of data.
type Ctx0V5 ¶
type Ctx0V5 struct {
Fn Handler // 8 bytes
Val1 int64 // 8 bytes
Val2 int64 // 8 bytes
Val3 int64 // 8 bytes
Val4 int64 // 8 bytes
Val5 int64 // 8 bytes
Data [16]byte // 16 bytes
}
Ctx0V5 has 0 refs, 5 vals, and 16 bytes of data.
type Ctx0V6 ¶
type Ctx0V6 struct {
Fn Handler // 8 bytes
Val1 int64 // 8 bytes
Val2 int64 // 8 bytes
Val3 int64 // 8 bytes
Val4 int64 // 8 bytes
Val5 int64 // 8 bytes
Val6 int64 // 8 bytes
Data [8]byte // 8 bytes
}
Ctx0V6 has 0 refs, 6 vals, and 8 bytes of data.
type Ctx0V7 ¶
type Ctx0V7 struct {
Fn Handler // 8 bytes
Val1 int64 // 8 bytes
Val2 int64 // 8 bytes
Val3 int64 // 8 bytes
Val4 int64 // 8 bytes
Val5 int64 // 8 bytes
Val6 int64 // 8 bytes
Val7 int64 // 8 bytes
}
Ctx0V7 has 0 refs, 7 vals, and 0 bytes of data.
type Ctx1V1 ¶
type Ctx1V1[T1 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Val1 int64 // 8 bytes Data [40]byte // 40 bytes }
Ctx1V1 has 1 ref, 1 val, 40 bytes data.
type Ctx1V2 ¶
type Ctx1V2[T1 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Data [32]byte // 32 bytes }
Ctx1V2 has 1 ref, 2 vals, 32 bytes data.
type Ctx1V3 ¶
type Ctx1V3[T1 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Data [24]byte // 24 bytes }
Ctx1V3 has 1 ref, 3 vals, 24 bytes data.
type Ctx1V4 ¶
type Ctx1V4[T1 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Val4 int64 // 8 bytes Data [16]byte // 16 bytes }
Ctx1V4 has 1 ref, 4 vals, 16 bytes data.
type Ctx1V5 ¶
type Ctx1V5[T1 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Val4 int64 // 8 bytes Val5 int64 // 8 bytes Data [8]byte // 8 bytes }
Ctx1V5 has 1 ref, 5 vals, 8 bytes data.
type Ctx1V6 ¶
type Ctx1V6[T1 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Val4 int64 // 8 bytes Val5 int64 // 8 bytes Val6 int64 // 8 bytes }
Ctx1V6 has 1 ref, 6 vals, 0 bytes data.
type Ctx2 ¶
type Ctx2[T1, T2 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Data [40]byte // 40 bytes }
Ctx2 has 2 refs, 0 vals, 40 bytes data.
type Ctx2V1 ¶
type Ctx2V1[T1, T2 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Val1 int64 // 8 bytes Data [32]byte // 32 bytes }
Ctx2V1 has 2 refs, 1 val, 32 bytes data.
type Ctx2V2 ¶
type Ctx2V2[T1, T2 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Data [24]byte // 24 bytes }
Ctx2V2 has 2 refs, 2 vals, 24 bytes data.
type Ctx2V3 ¶
type Ctx2V3[T1, T2 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Data [16]byte // 16 bytes }
Ctx2V3 has 2 refs, 3 vals, 16 bytes data.
type Ctx2V4 ¶
type Ctx2V4[T1, T2 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Val4 int64 // 8 bytes Data [8]byte // 8 bytes }
Ctx2V4 has 2 refs, 4 vals, 8 bytes data.
type Ctx2V5 ¶
type Ctx2V5[T1, T2 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Val4 int64 // 8 bytes Val5 int64 // 8 bytes }
Ctx2V5 has 2 refs, 5 vals, 0 bytes data.
type Ctx3 ¶
type Ctx3[T1, T2, T3 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Data [32]byte // 32 bytes }
Ctx3 has 3 refs, 0 vals, 32 bytes data.
type Ctx3V1 ¶
type Ctx3V1[T1, T2, T3 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Val1 int64 // 8 bytes Data [24]byte // 24 bytes }
Ctx3V1 has 3 refs, 1 val, 24 bytes data.
type Ctx3V2 ¶
type Ctx3V2[T1, T2, T3 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Data [16]byte // 16 bytes }
Ctx3V2 has 3 refs, 2 vals, 16 bytes data.
type Ctx3V3 ¶
type Ctx3V3[T1, T2, T3 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Data [8]byte // 8 bytes }
Ctx3V3 has 3 refs, 3 vals, 8 bytes data.
type Ctx3V4 ¶
type Ctx3V4[T1, T2, T3 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes Val4 int64 // 8 bytes }
Ctx3V4 has 3 refs, 4 vals, 0 bytes data.
type Ctx4 ¶
type Ctx4[T1, T2, T3, T4 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Data [24]byte // 24 bytes }
Ctx4 has 4 refs, 0 vals, 24 bytes data.
type Ctx4V1 ¶
type Ctx4V1[T1, T2, T3, T4 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Val1 int64 // 8 bytes Data [16]byte // 16 bytes }
Ctx4V1 has 4 refs, 1 val, 16 bytes data.
type Ctx4V2 ¶
type Ctx4V2[T1, T2, T3, T4 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Data [8]byte // 8 bytes }
Ctx4V2 has 4 refs, 2 vals, 8 bytes data.
type Ctx4V3 ¶
type Ctx4V3[T1, T2, T3, T4 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes Val3 int64 // 8 bytes }
Ctx4V3 has 4 refs, 3 vals, 0 bytes data.
type Ctx5 ¶
type Ctx5[T1, T2, T3, T4, T5 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Ref5 *T5 // 8 bytes Data [16]byte // 16 bytes }
Ctx5 has 5 refs, 0 vals, 16 bytes data.
type Ctx5V1 ¶
type Ctx5V1[T1, T2, T3, T4, T5 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Ref5 *T5 // 8 bytes Val1 int64 // 8 bytes Data [8]byte // 8 bytes }
Ctx5V1 has 5 refs, 1 val, 8 bytes data.
type Ctx5V2 ¶
type Ctx5V2[T1, T2, T3, T4, T5 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Ref5 *T5 // 8 bytes Val1 int64 // 8 bytes Val2 int64 // 8 bytes }
Ctx5V2 has 5 refs, 2 vals, 0 bytes data.
type Ctx6 ¶
type Ctx6[T1, T2, T3, T4, T5, T6 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Ref5 *T5 // 8 bytes Ref6 *T6 // 8 bytes Data [8]byte // 8 bytes }
Ctx6 has 6 refs, 0 vals, 8 bytes data.
type Ctx6V1 ¶
type Ctx6V1[T1, T2, T3, T4, T5, T6 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Ref5 *T5 // 8 bytes Ref6 *T6 // 8 bytes Val1 int64 // 8 bytes }
Ctx6V1 has 6 refs, 1 val, 0 bytes data.
type Ctx7 ¶
type Ctx7[T1, T2, T3, T4, T5, T6, T7 any] struct { Fn Handler // 8 bytes Ref1 *T1 // 8 bytes Ref2 *T2 // 8 bytes Ref3 *T3 // 8 bytes Ref4 *T4 // 8 bytes Ref5 *T5 // 8 bytes Ref6 *T6 // 8 bytes Ref7 *T7 // 8 bytes }
Ctx7 has 7 refs, 0 vals, 0 bytes data.
type CtxRefs0 ¶
type CtxRefs0 struct {
// contains filtered or unexported fields
}
CtxRefs0 is a view into ExtSQE with 0 refs. Use its methods to select the number of vals (0-7).
func ViewCtx ¶
ViewCtx creates a CtxRefs0 for accessing the UserData with 0 refs. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
Example:
c := uring.ViewCtx(sqe).Vals3() // 0 refs, 3 vals c.Val1 = timestamp c.Val2 = flags c.Val3 = seqNum
type CtxRefs1 ¶
type CtxRefs1[T1 any] struct { // contains filtered or unexported fields }
CtxRefs1 is a view into ExtSQE with 1 ref. Use its methods to select the number of vals (0-6).
func ViewCtx1 ¶
ViewCtx1 creates a CtxRefs1 for accessing the UserData with 1 typed ref. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
Example:
c := uring.ViewCtx1[Connection](sqe).Vals1() // 1 ref, 1 val c.Val1 = time.Now().UnixNano()
type CtxRefs2 ¶
type CtxRefs2[T1, T2 any] struct { // contains filtered or unexported fields }
CtxRefs2 is a view into ExtSQE with 2 refs. Use its methods to select the number of vals (0-5).
func ViewCtx2 ¶
ViewCtx2 creates a CtxRefs2 for accessing the UserData with 2 typed refs. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
Example:
c := uring.ViewCtx2[Connection, Buffer](sqe).Vals2() // 2 refs, 2 vals c.Val1 = offset c.Val2 = length
type CtxRefs3 ¶
type CtxRefs3[T1, T2, T3 any] struct { // contains filtered or unexported fields }
CtxRefs3 is a view into ExtSQE with 3 refs. Use its methods to select the number of vals (0-4).
func ViewCtx3 ¶
ViewCtx3 creates a CtxRefs3 for accessing the UserData with 3 typed refs. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
type CtxRefs4 ¶
type CtxRefs4[T1, T2, T3, T4 any] struct { // contains filtered or unexported fields }
CtxRefs4 is a view into ExtSQE with 4 refs. Use its methods to select the number of vals (0-3).
func ViewCtx4 ¶
ViewCtx4 creates a CtxRefs4 for accessing the UserData with 4 typed refs. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
type CtxRefs5 ¶
type CtxRefs5[T1, T2, T3, T4, T5 any] struct { // contains filtered or unexported fields }
CtxRefs5 is a view into ExtSQE with 5 refs. Use its methods to select the number of vals (0-2).
func ViewCtx5 ¶
ViewCtx5 creates a CtxRefs5 for accessing the UserData with 5 typed refs. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
func (CtxRefs5[T1, T2, T3, T4, T5]) Vals0 ¶
Vals0 returns a Ctx5 pointer (5 refs, 0 vals, 16B data).
type CtxRefs6 ¶
type CtxRefs6[T1, T2, T3, T4, T5, T6 any] struct { // contains filtered or unexported fields }
CtxRefs6 is a view into ExtSQE with 6 refs. Use its methods to select the number of vals (0-1).
func ViewCtx6 ¶
ViewCtx6 creates a CtxRefs6 for accessing the UserData with 6 typed refs. Raw overlay; caller must ensure pointer-free refs or keep roots externally.
type CtxRefs7 ¶
type CtxRefs7[T1, T2, T3, T4, T5, T6, T7 any] struct { // contains filtered or unexported fields }
CtxRefs7 is a view into ExtSQE with 7 refs. The only option is Vals0 (no vals available).
type DirectCQE ¶
type DirectCQE struct {
Res int32 // Raw CQE result
Flags uint32 // CQE flags (IORING_CQE_F_*)
Op uint8 // IORING_OP_* opcode
SQEFlags uint8 // SQE flags (IOSQE_*)
BufGroup uint16 // Buffer group index
FD iofd.FD // Submitted descriptor or registered-file index
}
DirectCQE is a compact copied CQE for Direct mode operations. It stores the completion result, CQE flags, and decoded context fields.
Use Uring.WaitDirect when every incoming CQE carries a PackDirect context.
Layout: 16 bytes on supported platforms.
func (*DirectCQE) BufID ¶
BufID returns the buffer ID from CQE flags. Only valid when HasBuffer() returns true.
func (*DirectCQE) Err ¶
Err applies CompletionError to c.Res. Call it on a matched operation result.
func (*DirectCQE) HasMore ¶
HasMore reports IORING_CQE_F_MORE: the request has further completions, including multishot results or a zero-copy notification.
func (*DirectCQE) IsNotification ¶
IsNotification reports whether IORING_CQE_F_NOTIF is set.
type EpollEvent ¶
EpollEvent represents an epoll event. Layout matches struct epoll_event in Linux on amd64.
type ExtCQE ¶
type ExtCQE struct {
Res int32 // Raw CQE result
Flags uint32 // CQE flags (IORING_CQE_F_*)
Ext *ExtSQE // Borrowed ExtSQE with full context
}
ExtCQE is a compact copied CQE for Extended mode operations. It stores the completion result, CQE flags, and borrowed ExtSQE pointer.
Use Uring.WaitExtended when every incoming CQE carries a PackExtended context.
Layout: 16 bytes on supported 64-bit platforms.
func (*ExtCQE) BufID ¶
BufID returns the buffer ID from CQE flags. Only valid when HasBuffer() returns true.
func (*ExtCQE) Err ¶
Err applies CompletionError to c.Res. Call it on a matched operation result.
func (*ExtCQE) HasBufferMore ¶
HasBufferMore reports whether the buffer was partially consumed.
func (*ExtCQE) HasMore ¶
HasMore reports IORING_CQE_F_MORE: the request has further completions, including multishot results or a zero-copy notification.
func (*ExtCQE) IsNotification ¶
IsNotification reports whether IORING_CQE_F_NOTIF is set.
type ExtSQE ¶
type ExtSQE struct {
SQE ioUringSqe // 64 bytes - full system context
UserData [64]byte // 64 bytes - flexible user interpretation
}
ExtSQE stores a 64-byte base SQE and 64 bytes of caller data. Submission overwrites SQE and preserves UserData; UserData is separate from the kernel's SQE128 extension. Copy needed facts before mutation, reuse, or release; do not access pooled storage after PutExtSQE. Its target lifetime follows the SQEContext contract.
The GC does not trace UserData; callers that place pointer-bearing values there must keep the referents reachable outside UserData.
type Features ¶
type Features struct {
// SQEntries is the actual number of SQ entries allocated by the kernel.
SQEntries int
// CQEntries is the actual number of CQ entries allocated by the kernel.
CQEntries int
// SQEBytes is the width of each mapped SQE slot in bytes.
SQEBytes int
// UserDataByteOrder is the byte order for user_data field interpretation.
UserDataByteOrder binary.ByteOrder
}
Features reports the current ring geometry and user_data byte order. ResizeRings updates SQEntries and CQEntries after a successful resize.
type Handler ¶
type Handler = func(ring *Uring, sqe *ioUringSqe, cqe *ioUringCqe)
Handler is the callback function signature for completion handling. It receives the Uring instance, the original SQE, and the completion result.
When embedded in raw `ExtSQE.UserData`, only static non-capturing functions are safe to store directly. Capturing closures and other live Go roots must stay outside raw user-data bytes.
Example:
func handleRecv(ring *Uring, sqe *ioUringSqe, cqe *ioUringCqe) {
if cqe.res < 0 {
// Handle error
return
}
// Process received data
}
type IncrementalHandler ¶
type IncrementalHandler interface {
// OnData receives a borrowed fragment whose length and capacity both equal
// the byte count reported by this completion.
// bufferMore reports IORING_CQE_F_BUF_MORE: the selected buffer remains
// incrementally consumable. It does not report parent-request liveness.
// The buffer is valid until this callback returns.
OnData(buf []byte, bufferMore bool)
// OnComplete is called after a single-shot receive succeeds. The selected
// buffer may remain incrementally consumable by a later operation.
OnComplete()
// OnError is called when an error occurs.
OnError(err error)
}
IncrementalHandler handles incremental receive completion events.
type IncrementalReceiver ¶
type IncrementalReceiver struct {
// contains filtered or unexported fields
}
IncrementalReceiver manages single-shot receives over an IOU_PBUF_RING_INC group. It tracks a separate consumed offset for each buffer ID. IORING_CQE_F_BUF_MORE reports that the kernel retained the selected buffer for later incremental consumption.
func NewIncrementalReceiver ¶
func NewIncrementalReceiver(ring *Uring, pool *ContextPools, groupID uint16, bufSize int, bufBacking []byte, entries int) *IncrementalReceiver
NewIncrementalReceiver creates an incremental receiver over entries contiguous buffers in bufBacking. Buffer ID i must identify bufBacking[i*bufSize:(i+1)*bufSize]. Create the receiver before the group's first receive and use it for every receive that consumes the group. Caller-side completion dispatch must serialize its CQEs in CQ order.
Before calling NewIncrementalReceiver, register the same group with Uring.RegisterBufRingIncremental, add each corresponding bufBacking slice with BufferRing.Add using the matching buffer ID, and publish them with BufferRing.Advance. The receiver keeps bufBacking reachable but does not own the BufferRing registration, which remains owned by Uring until Stop.
func (*IncrementalReceiver) HandleCQE ¶
func (r *IncrementalReceiver) HandleCQE(cqe CQEView) bool
HandleCQE dispatches a receive CQE owned by this receiver and returns true. It returns false for a CQE owned by another receiver or operation. Caller must serialize dispatch in CQ order and dispatch each CQE once. Handling returns the request's ExtSQE to its pool after callbacks finish; copy any needed context-dependent facts before calling HandleCQE.
func (*IncrementalReceiver) Recv ¶
func (r *IncrementalReceiver) Recv(fd iofd.FD, handler IncrementalHandler) error
Recv submits one single-shot receive over the incremental buffer group. The handler receives OnData for a non-empty result. Its bufferMore argument reports whether the selected buffer remains available to later operations. OnComplete runs after the request's successful CQE, including when bufferMore is true.
A nil return means the request was queued. Recv returns ErrInvalidParam for an invalid receiver configuration, or iox.ErrWouldBlock if the pool or SQ is full.
type IncrementalSubscriber ¶
type IncrementalSubscriber struct {
// contains filtered or unexported fields
}
IncrementalSubscriber adapts functions to `IncrementalHandler`.
func NewIncrementalSubscriber ¶
func NewIncrementalSubscriber() *IncrementalSubscriber
NewIncrementalSubscriber creates a subscriber with default handlers.
func (*IncrementalSubscriber) Handler ¶
func (s *IncrementalSubscriber) Handler() IncrementalHandler
Handler returns `s` as an `IncrementalHandler`.
func (*IncrementalSubscriber) OnComplete ¶
func (s *IncrementalSubscriber) OnComplete(fn func()) *IncrementalSubscriber
OnComplete sets the completion handler.
func (*IncrementalSubscriber) OnData ¶
func (s *IncrementalSubscriber) OnData(fn func(buf []byte, hasMore bool)) *IncrementalSubscriber
OnData sets the data handler.
func (*IncrementalSubscriber) OnError ¶
func (s *IncrementalSubscriber) OnError(fn func(err error)) *IncrementalSubscriber
OnError sets the error handler.
type IndirectSQE ¶
type IndirectSQE struct {
// contains filtered or unexported fields
}
IndirectSQE stores the 64-byte base SQE for an indirect context. Submission overwrites it with the encoded SQE. Copy needed fields before mutation, reuse, or release; do not access pooled storage after PutIndirectSQE. Its target lifetime follows the SQEContext contract.
type IoTimespec ¶
IoTimespec is a 128-bit timespec for high-precision timestamps. Matches struct io_timespec in Linux.
type ListenerHandler ¶
type ListenerHandler interface {
// OnSocketCreated reports that socket creation succeeded. Return true to
// continue listener setup or false to abort it.
OnSocketCreated(fd iofd.FD) bool
// OnBound reports that bind succeeded. Return true to continue listener
// setup or false to abort it.
OnBound() bool
// OnListening reports that the socket is now listening.
OnListening()
// OnError reports a terminal failure for the current setup stage.
OnError(op uint8, err error)
}
ListenerHandler receives completion events during listener setup. ListenerOp.HandleCQE invokes callbacks and submits the next stage. Alternatively, the caller can use DecodeListenerCQE and the Prepare helpers. A false callback result stops setup; the caller still owns Close.
type ListenerManager ¶
type ListenerManager struct {
// contains filtered or unexported fields
}
ListenerManager provides convenience methods for starting async listener creation. It prepares the initial SOCKET SQE and submits it. Route completions to ListenerOp.HandleCQE to advance bind→listen, or use DecodeListenerCQE and the Prepare helpers for manual advancement. The caller owns polling, admission retry, and cleanup.
func NewListenerManager ¶
func NewListenerManager(ring *Uring, pool *ContextPools) *ListenerManager
NewListenerManager creates a listener manager.
func (*ListenerManager) ListenTCP4 ¶
func (m *ListenerManager) ListenTCP4(addr *net.TCPAddr, backlog int, handler ListenerHandler) (*ListenerOp, error)
ListenTCP4 prepares and submits the initial SOCKET for TCP IPv4. A nil addr or empty IP binds the IPv4 wildcard; port zero lets the kernel choose. The caller's address is not modified. Dispatch completions through ListenerOp.HandleCQE to finish setup.
func (*ListenerManager) ListenTCP6 ¶
func (m *ListenerManager) ListenTCP6(addr *net.TCPAddr, backlog int, handler ListenerHandler) (*ListenerOp, error)
ListenTCP6 prepares and submits the initial SOCKET for TCP IPv6. A nil addr or empty IP binds the IPv6 wildcard; port zero lets the kernel choose. An IPv4 address selects IPv4. The caller's address is not modified. Dispatch completions through ListenerOp.HandleCQE to finish setup.
func (*ListenerManager) ListenUnix ¶
func (m *ListenerManager) ListenUnix(addr *net.UnixAddr, backlog int, handler ListenerHandler) (*ListenerOp, error)
ListenUnix prepares and submits the initial SOCKET for Unix domain. Dispatch completions through ListenerOp.HandleCQE to finish setup.
func (*ListenerManager) Pool ¶
func (m *ListenerManager) Pool() *ContextPools
Pool returns the context pool.
func (*ListenerManager) Ring ¶
func (m *ListenerManager) Ring() *Uring
Ring returns the underlying Uring instance.
type ListenerOp ¶
type ListenerOp struct {
// contains filtered or unexported fields
}
ListenerOp is a handle to a listener creation operation. It holds the listener FD and advances setup through HandleCQE when selected.
func (*ListenerOp) AcceptMultishot ¶
func (op *ListenerOp) AcceptMultishot(handler MultishotHandler, options ...OpOptionFunc) (*MultishotSubscription, error)
AcceptMultishot starts a multishot accept subscription on a ready listener. Options are forwarded to Uring.AcceptMultishot. Returns ErrNotReady until the listener FD is set and valid. Caller must complete bind and listen before calling; FD validity alone does not establish that the socket is listening.
func (*ListenerOp) Close ¶
func (op *ListenerOp) Close()
Close stops setup callbacks and makes FD return -1. A pending BIND or LISTEN keeps the socket open until its completion is decoded. With no pending setup request, Close releases the socket and pooled context immediately.
Serialize Close with setup dispatch and drain other users of the listener FD before calling it. After an early Close, use ListenerOp.HandleCQE to drain the pending step, then call Close again to return the context. With manual decoding, pass a successful SOCKET result to ListenerOp.SetFD for closure.
func (*ListenerOp) Ext ¶
func (op *ListenerOp) Ext() *ExtSQE
Ext returns the borrowed setup context for Prepare helpers and SubmitExtended. It returns nil after final Close.
func (*ListenerOp) FD ¶
func (op *ListenerOp) FD() iofd.FD
FD returns the listener socket FD, or -1 before creation or after Close.
func (*ListenerOp) HandleCQE ¶
func (op *ListenerOp) HandleCQE(cqe CQEView) (bool, error)
HandleCQE consumes this listener's CQE, invokes its callback, and attempts the next submission once:
SOCKET -> OnSocketCreated -> BIND -> OnBound -> LISTEN -> OnListening
It returns false for unrelated CQEs. A true result reports CQE consumption; OnListening reports readiness. Kernel failures go to OnError; the returned error reports only the next submission's failure. On iox.ErrWouldBlock, the next SQE remains prepared: drive the ring, then retry ring.SubmitExtended(PackExtended(op.Ext())). Never replay the CQE or callback.
Caller must serialize dispatch, retry, and Close and consume each CQE exactly once through this method or DecodeListenerCQE. Callbacks must not reenter dispatch or change the prepared SQE. A false callback result or Close stops advancement; the caller retains cleanup responsibility.
After an earlier Close, this method drains pending setup CQEs without callbacks and closes the setup socket. Call Close again after draining to release the context.
func (*ListenerOp) SetFD ¶
func (op *ListenerOp) SetFD(fd iofd.FD)
SetFD stores a successful SOCKET result, closing it if Close was already called.
type ListenerState ¶
type ListenerState uint8
ListenerState identifies the prepared socket→bind→listen stage or final state.
const ( ListenerStateInit ListenerState = iota // Initial state ListenerStateSocket // Socket creation prepared ListenerStateBind // Bind prepared ListenerStateListen // Listen prepared ListenerStateReady // Listener is ready for accept ListenerStateFailed // Operation failed )
type ListenerStep ¶
type ListenerStep struct {
Op uint8 // Kernel op that completed (IORING_OP_SOCKET, _BIND, _LISTEN)
FD iofd.FD // Successful SOCKET result, or request FD for BIND/LISTEN
State ListenerState // Prepared stage, or ListenerStateFailed on kernel error
Err error // Non-nil if the operation failed
Ext *ExtSQE // The ExtSQE carrying this listener context
Handler ListenerHandler
}
ListenerStep is the decoded result of a listener-related CQE. The caller decides what happens next based on this value.
func DecodeListenerCQE ¶
func DecodeListenerCQE(cqe CQEView) (ListenerStep, bool)
DecodeListenerCQE decodes a CQE into a ListenerStep. Returns (step, true) if the CQE belongs to a listener operation, or (zero, false) if it does not. Decoding retires that setup request. Consume each CQE exactly once, through either DecodeListenerCQE or ListenerOp.HandleCQE.
type ListenerSubscriber ¶
type ListenerSubscriber struct {
// contains filtered or unexported fields
}
ListenerSubscriber adapts functions to `ListenerHandler`.
func NewListenerSubscriber ¶
func NewListenerSubscriber() *ListenerSubscriber
NewListenerSubscriber creates a subscriber with default handlers.
func (*ListenerSubscriber) Handler ¶
func (s *ListenerSubscriber) Handler() ListenerHandler
Handler returns `s` as a `ListenerHandler`.
func (*ListenerSubscriber) OnBound ¶
func (s *ListenerSubscriber) OnBound(fn func() bool) *ListenerSubscriber
OnBound sets the bound handler.
func (*ListenerSubscriber) OnError ¶
func (s *ListenerSubscriber) OnError(fn func(op uint8, err error)) *ListenerSubscriber
OnError sets the error handler.
func (*ListenerSubscriber) OnListening ¶
func (s *ListenerSubscriber) OnListening(fn func()) *ListenerSubscriber
OnListening sets the listening handler.
func (*ListenerSubscriber) OnSocketCreated ¶
func (s *ListenerSubscriber) OnSocketCreated(fn func(fd iofd.FD) bool) *ListenerSubscriber
OnSocketCreated sets the socket-created handler.
type MemRegionReg ¶
type MemRegionReg struct {
RegionUptr uint64 // Pointer to RegionDesc
Flags uint64 // Registration flags (IORING_MEM_REGION_REG_*)
// contains filtered or unexported fields
}
MemRegionReg is the registration structure for memory regions. Matches struct io_uring_mem_region_reg in Linux.
type Msghdr ¶
Msghdr represents a message header for sendmsg/recvmsg. Layout matches struct msghdr in Linux (LP64).
type MultishotAction ¶
type MultishotAction uint8
MultishotAction tells `uring` whether to keep or stop a live subscription.
const ( // MultishotContinue keeps the subscription live. // It applies only while the observed step still carries `IORING_CQE_F_MORE`. MultishotContinue MultishotAction = iota // MultishotStop requests cancellation after the current callback returns. // A final step ignores it because the kernel is already closing the stream. // Submission is best effort. If it fails, the subscription stays active; // caller code can retry with MultishotSubscription.Cancel. MultishotStop )
type MultishotHandler ¶
type MultishotHandler interface {
// OnMultishotStep handles one observed CQE.
// Return `MultishotStop` to request async cancellation after a non-final step.
OnMultishotStep(step MultishotStep) MultishotAction
// OnMultishotStop handles the terminal stop of the subscription.
// It runs at most once if callbacks stay enabled. It carries the terminal
// error or cancellation cause, but not a borrowed CQE view.
// A queued cancellation CQE may still need dispatch after this callback.
OnMultishotStop(err error, cancelled bool)
}
MultishotHandler handles multishot step observations and the terminal stop. Retry and resubmission policy stay in caller-side runtime code outside `uring`.
type MultishotStep ¶
MultishotStep describes one observed multishot CQE.
CQE is a copied descriptor. Its context target is borrowed only during OnMultishotStep; copy needed target fields before returning. Negative CQE.Res values are decoded into Err. Cancelled reports -ECANCELED.
func (MultishotStep) Final ¶
func (s MultishotStep) Final() bool
Final reports whether the observed CQE lacked `IORING_CQE_F_MORE`.
func (MultishotStep) HasMore ¶
func (s MultishotStep) HasMore() bool
HasMore reports whether the observed CQE carried `IORING_CQE_F_MORE`.
type MultishotSubscriber ¶
type MultishotSubscriber struct {
// contains filtered or unexported fields
}
MultishotSubscriber adapts functions to `MultishotHandler`.
func NewMultishotSubscriber ¶
func NewMultishotSubscriber() *MultishotSubscriber
NewMultishotSubscriber creates a subscriber with default handlers.
func (*MultishotSubscriber) Handler ¶
func (s *MultishotSubscriber) Handler() MultishotHandler
Handler returns `s` as a `MultishotHandler`.
func (*MultishotSubscriber) OnMultishotStep ¶
func (s *MultishotSubscriber) OnMultishotStep(step MultishotStep) MultishotAction
OnMultishotStep implements MultishotHandler.
func (*MultishotSubscriber) OnMultishotStop ¶
func (s *MultishotSubscriber) OnMultishotStop(err error, cancelled bool)
OnMultishotStop implements MultishotHandler.
func (*MultishotSubscriber) OnStep ¶
func (s *MultishotSubscriber) OnStep(fn func(step MultishotStep) MultishotAction) *MultishotSubscriber
OnStep sets the multishot step handler.
func (*MultishotSubscriber) OnStop ¶
func (s *MultishotSubscriber) OnStop(fn func(err error, cancelled bool)) *MultishotSubscriber
OnStop sets the multishot terminal stop handler.
type MultishotSubscription ¶
type MultishotSubscription struct {
// contains filtered or unexported fields
}
MultishotSubscription tracks one multishot `io_uring` operation. It delivers zero or more step callbacks until cancelled or exhausted.
Lifecycle:
- Create it with `Uring.AcceptMultishot` or `Uring.ReceiveMultishot`
- Observe `OnMultishotStep` for each original CQE
- Request cancellation with `Cancel` or `Unsubscribe`, or let it end naturally
- If callbacks stay enabled, one `OnMultishotStop` runs at most once
- Dispatch every queued cancellation CQE before final ring teardown
Thread Safety: `Cancel` and `Unsubscribe` are safe for the subscription state itself, but cancel submission follows the ring's submit-state serialization contract. On default single-issuer rings (MultiIssuers is false), call them from the OS-thread-pinned ring owner and serialize them with submit, Wait, WaitDirect, WaitExtended, Stop, and ResizeRings. On MultiIssuers=true rings, the shared-submit lock serializes the cancel SQE. Callbacks run synchronously on the goroutine that dispatches the CQE. Wait returns CQEs; caller code invokes HandleCQE or an extended handler.
func (*MultishotSubscription) Active ¶
func (s *MultishotSubscription) Active() bool
Active reports whether the original terminal CQE has not yet been handled. A false result does not discharge queued cancellation CQEs.
func (*MultishotSubscription) Cancel ¶
func (s *MultishotSubscription) Cancel() error
Cancel asks the kernel to stop this multishot operation. The subscription remains live until its original terminal CQE is handled. Cancel follows the ring's submit-state serialization contract: on default single-issuer rings, call it from the OS-thread-pinned ring owner and serialize it with submit, Wait, WaitDirect, WaitExtended, Stop, and ResizeRings; on MultiIssuers=true rings, the shared-submit lock serializes the cancel SQE.
It is safe to call more than once:
Return Meaning nil Cancellation submitted or no-op non-nil Not submitted; no cancellation CQE for this attempt
The original and cancellation CQEs report the kernel outcomes.
Dispatch both original and cancellation CQEs through HandleCQE or their extended handlers. The pooled original context is retained until both lifetimes end; the cancellation context belongs to the subscription.
If callbacks remain enabled, later CQEs may still deliver `OnMultishotStep` before the terminal CQE delivers `OnMultishotStop`.
func (*MultishotSubscription) HandleCQE ¶
func (s *MultishotSubscription) HandleCQE(cqe CQEView) bool
HandleCQE processes an original or cancellation CQE for this subscription. It returns true for either matched request, including when callbacks are suppressed. Use the original operation and callback delivery to determine who owns a returned resource. It returns false for non-extended CQEs, foreign routes, or pooled ExtSQEs whose owner is no longer this subscription.
HandleCQE is for immediate dispatch in the caller's serialized completion loop. Caller code must call it before the observed ExtSQE can be retired and reused. If copied CQEs outlive that loop, caller code must pair them with its own route state and reject observations for retired subscriptions.
HandleCQE may attempt cancellation when a non-final step returns MultishotStop. It does not wait or rearm the original operation. Failed cancellation admission leaves the subscription active and is not returned by this method; caller code owns retry policy, polling cadence, and handling after original terminality.
func (*MultishotSubscription) State ¶
func (s *MultishotSubscription) State() SubscriptionState
State returns the original request's SubscriptionState.
func (*MultishotSubscription) Unsubscribe ¶
func (s *MultishotSubscription) Unsubscribe()
Unsubscribe suppresses future step and stop callbacks and makes one best-effort cancellation attempt. An in-flight callback may still finish.
After a failed submission, callbacks stay suppressed and the caller can retry MultishotSubscription.Cancel while the original is active. Continue dispatching original and cancellation CQEs. Unsubscribe follows the same serialization contract as Cancel.
The caller must account for resources from suppressed steps, such as sockets returned by Uring.AcceptMultishot. Use Cancel directly to keep receiving those resources in the step handler during shutdown.
type NapiReg ¶
type NapiReg struct {
BusyPollTo uint32 // Busy poll timeout in microseconds
PreferBusyPoll uint8 // Prefer busy poll over sleeping
Opcode uint8 // IO_URING_NAPI_* operation
OpParam uint32 // Operation parameter (strategy or NAPI ID)
// contains filtered or unexported fields
}
NapiReg is the registration structure for NAPI busy polling. Matches struct io_uring_napi in Linux.
type NetworkType ¶
type NetworkType = sock.NetworkType
NetworkType represents the network address family.
type NoopIncrementalHandler ¶
type NoopIncrementalHandler struct{}
NoopIncrementalHandler provides default implementations for IncrementalHandler. Embed this in custom handlers to only override methods you need.
Default behavior:
- OnData: no-op
- OnComplete: no-op
- OnError: no-op
Example:
type myHandler struct {
uring.NoopIncrementalHandler
totalBytes int
}
func (h *myHandler) OnData(buf []byte, bufferMore bool) {
h.totalBytes += len(buf)
}
func (NoopIncrementalHandler) OnComplete ¶
func (NoopIncrementalHandler) OnComplete()
OnComplete is a no-op.
func (NoopIncrementalHandler) OnData ¶
func (NoopIncrementalHandler) OnData([]byte, bool)
OnData is a no-op.
func (NoopIncrementalHandler) OnError ¶
func (NoopIncrementalHandler) OnError(error)
OnError is a no-op.
type NoopListenerHandler ¶
type NoopListenerHandler struct{}
NoopListenerHandler provides default implementations for ListenerHandler. Embed this in custom handlers to only override methods you need.
Default behavior:
- OnSocketCreated: returns true (continue to bind)
- OnBound: returns true (continue to listen)
- OnListening: no-op
- OnError: no-op
Example:
type myHandler struct {
uring.NoopListenerHandler
fd iofd.FD
}
func (h *myHandler) OnSocketCreated(fd iofd.FD) bool {
h.fd = fd
// Set custom socket options here
return true
}
func (NoopListenerHandler) OnBound ¶
func (NoopListenerHandler) OnBound() bool
OnBound returns true to continue the chain.
func (NoopListenerHandler) OnError ¶
func (NoopListenerHandler) OnError(uint8, error)
OnError is a no-op.
func (NoopListenerHandler) OnListening ¶
func (NoopListenerHandler) OnListening()
OnListening is a no-op.
func (NoopListenerHandler) OnSocketCreated ¶
func (NoopListenerHandler) OnSocketCreated(iofd.FD) bool
OnSocketCreated returns true to continue the chain.
type NoopMultishotHandler ¶
type NoopMultishotHandler struct{}
NoopMultishotHandler provides default implementations for MultishotHandler. Embed this in custom handlers to only override methods you need.
Default behavior:
- successful steps continue
- error steps stop
- terminal stop is ignored
When a step returns a resource, its caller must arrange for its disposition. For Uring.AcceptMultishot, transfer or close each successful socket in the step handler or in the caller's serialized completion loop.
func (NoopMultishotHandler) OnMultishotStep ¶
func (NoopMultishotHandler) OnMultishotStep(step MultishotStep) MultishotAction
OnMultishotStep returns the default action for the observed step.
func (NoopMultishotHandler) OnMultishotStop ¶
func (NoopMultishotHandler) OnMultishotStop(error, bool)
OnMultishotStop is a no-op.
type NoopZCHandler ¶
type NoopZCHandler struct{}
NoopZCHandler provides default implementations for ZCHandler. Embed this in custom handlers to only override methods you need.
Default behavior:
- OnCompleted: no-op
- OnNotification: no-op
Example:
type myHandler struct {
uring.NoopZCHandler
bytesSent int32
}
func (h *myHandler) OnCompleted(result int32) {
if result > 0 {
h.bytesSent += result
}
}
func (NoopZCHandler) OnNotification ¶
func (NoopZCHandler) OnNotification(int32)
OnNotification is a no-op.
type NoopZCRXHandler ¶
type NoopZCRXHandler struct{}
NoopZCRXHandler provides default ZCRXHandler behavior. Embed to override selectively.
func (NoopZCRXHandler) OnData ¶
func (NoopZCRXHandler) OnData(buf *ZCRXBuffer) bool
OnData releases the buffer and returns false if release would block.
func (NoopZCRXHandler) OnError ¶
func (NoopZCRXHandler) OnError(error) bool
OnError stops on any error.
type OpOption ¶
type OpOption struct {
// SQE control flags (IOSQE_IO_LINK, IOSQE_IO_DRAIN, IOSQE_ASYNC, etc.)
Flags uint8
// I/O priority. For file I/O: (class<<13)|level where class ∈ {RT=1,BE=2,IDLE=3}.
// For io_uring-specific ops: operation-defined flags (e.g. IORING_ACCEPT_MULTISHOT).
IOPrio uint16
// Registered file table slot index for direct descriptor operations.
// nil leaves the target unspecified.
FileIndex *uint32
// Registered credential personality ID (0 = caller's credentials).
Personality uint16
// Listen backlog depth.
Backlog int
// Kernel-provided buffer size for receive with buffer selection.
ReadBufferSize int
// Write buffer sizing hint.
WriteBufferSize int
// Timeout duration for timeout-class operations.
Duration time.Duration
// File permission mode for open/mkdir operations.
FileMode os.FileMode
// Advisory hint for fadvise/madvise operations.
Fadvise int
// File position or socket-buffer byte offset; see [WithOffset].
Offset int64
// Optional byte limit; nil uses the operation's default. See [WithN].
N *int
// Timeout count. See [WithCount].
Count int
// Timeout clock and behavior flags (IORING_TIMEOUT_ABS, _BOOTTIME, _REALTIME, etc.)
TimeoutFlags uint32
// Splice/tee operation flags (SPLICE_F_MOVE, _NONBLOCK, _MORE, _GIFT).
SpliceFlags uint32
// Fsync behavior flags (IORING_FSYNC_DATASYNC).
FsyncFlags uint32
// URING_CMD behavior flags (IORING_URING_CMD_FIXED, _MULTISHOT).
UringCmdFlags uint32
}
OpOption holds per-operation configuration. Each operation reads only the fields it uses, and ignores the rest.
func (*OpOption) Apply ¶
func (uo *OpOption) Apply(opts ...OpOptionFunc)
Apply applies option functions in order.
type OpOptionFunc ¶
type OpOptionFunc func(opt *OpOption)
OpOptionFunc configures an OpOption.
func WithCount ¶
func WithCount(cnt int) OpOptionFunc
WithCount sets the timeout count. The default is one. For a one-shot timer, zero waits for time alone. For a multishot timer, a positive value limits expirations and zero allows it to repeat until stopped. The count must fit uint32.
func WithDuration ¶
func WithDuration(d time.Duration) OpOptionFunc
WithDuration sets the timeout duration.
func WithFadvise ¶
func WithFadvise(advice int) OpOptionFunc
WithFadvise sets the advisory hint for fadvise/madvise operations.
func WithFileIndex ¶
func WithFileIndex(idx uint32) OpOptionFunc
WithFileIndex makes SocketRaw create a direct descriptor at the specified zero-based slot. IORING_FILE_INDEX_ALLOC requests auto-allocation.
func WithFileMode ¶
func WithFileMode(mode os.FileMode) OpOptionFunc
WithFileMode sets the file permission mode for open/mkdir operations.
func WithFlags ¶
func WithFlags(flags uint8) OpOptionFunc
WithFlags sets SQE control flags (IOSQE_IO_LINK, IOSQE_IO_DRAIN, etc.).
func WithFsyncDataSync ¶
func WithFsyncDataSync() OpOptionFunc
WithFsyncDataSync uses fdatasync semantics (sync data only, skip metadata).
func WithIOPrio ¶
func WithIOPrio(ioprio uint16) OpOptionFunc
WithIOPrio sets the raw I/O priority value.
func WithIOPrioClass ¶
func WithIOPrioClass(class, level uint8) OpOptionFunc
WithIOPrioClass sets I/O priority from class (RT=1, BE=2, IDLE=3) and level (0-7).
func WithN ¶
func WithN(n int) OpOptionFunc
WithN sets the byte limit for operations that use it. Uring.Read, Uring.Write, and Uring.ReadFixed cap it at the buffer length. Uring.Send, Uring.SendFD, Uring.Receive, and Uring.ReceiveFD require it to fit the supplied buffer after WithOffset. Receive operations with buffer selection use WithReadBufferSize instead. ZCTracker.SendZC and ZCTracker.SendZCFixed require a positive limit that fits the selected buffer range after WithOffset. Uring.WriteFixed, Uring.Splice, and Uring.Tee use their explicit lengths.
func WithOffset ¶
func WithOffset(offset int64) OpOptionFunc
WithOffset sets the file position or buffer offset used by an operation. Uring.Read, Uring.Write, Uring.ReadFixed, and Uring.WriteFixed use a file offset; -1 uses and advances the file's current position. Uring.Send, Uring.SendFD, Uring.Receive, and Uring.ReceiveFD use a nonnegative byte offset within the supplied buffer. Receive operations with buffer selection ignore this option. ZCTracker.SendZC uses a byte offset within its buffer; ZCTracker.SendZCFixed uses one within its explicit offset/length range.
func WithPersonality ¶
func WithPersonality(id uint16) OpOptionFunc
WithPersonality sets the registered credential personality ID for per-operation credential override. Register personalities via IORING_REGISTER_PERSONALITY.
func WithReadBufferSize ¶
func WithReadBufferSize(n int) OpOptionFunc
WithReadBufferSize sets the kernel-provided buffer size for receive operations with buffer selection. For raw multishot receive, zero leaves the kernel length uncapped and selects the default-size buffer group. Single-shot receive requires a positive size.
func WithSpliceFlags ¶
func WithSpliceFlags(flags uint32) OpOptionFunc
WithSpliceFlags sets splice/tee operation flags. Combine SPLICE_F_MOVE, SPLICE_F_NONBLOCK, SPLICE_F_MORE, SPLICE_F_GIFT.
func WithTimeoutAbsolute ¶
func WithTimeoutAbsolute() OpOptionFunc
WithTimeoutAbsolute treats the timeout duration as an absolute timestamp.
func WithTimeoutBootTime ¶
func WithTimeoutBootTime() OpOptionFunc
WithTimeoutBootTime uses CLOCK_BOOTTIME (survives system suspend).
func WithTimeoutEtimeSuccess ¶
func WithTimeoutEtimeSuccess() OpOptionFunc
WithTimeoutEtimeSuccess lets the next soft-linked request run when an ordinary Timeout expires. The timer CQE still reports -ETIME.
func WithTimeoutFlags ¶
func WithTimeoutFlags(flags uint32) OpOptionFunc
WithTimeoutFlags replaces the timeout flags. A timer accepts at most one clock selector (IORING_TIMEOUT_BOOTTIME or IORING_TIMEOUT_REALTIME). IORING_TIMEOUT_MULTISHOT requires a relative interval.
func WithTimeoutMultishot ¶
func WithTimeoutMultishot() OpOptionFunc
WithTimeoutMultishot selects a repeating relative timer. WithCount sets the expiration limit. A CQE with IORING_CQE_F_MORE leaves the timer active.
func WithTimeoutRealTime ¶
func WithTimeoutRealTime() OpOptionFunc
WithTimeoutRealTime uses CLOCK_REALTIME (wall clock, NTP-adjusted).
func WithUringCmdFlags ¶
func WithUringCmdFlags(flags uint32) OpOptionFunc
WithUringCmdFlags sets IORING_OP_URING_CMD behavior flags. IORING_URING_CMD_FIXED interprets sqeCtx.BufGroup as a registered buffer index. IORING_URING_CMD_MULTISHOT requires IOSQE_BUFFER_SELECT and interprets sqeCtx.BufGroup as a provided-buffer group. FIXED and MULTISHOT are mutually exclusive.
func WithWriteBufferSize ¶
func WithWriteBufferSize(n int) OpOptionFunc
WithWriteBufferSize sets the write buffer sizing hint.
type OpenHow ¶
OpenHow is the structure for openat2 syscall. Layout matches struct open_how in Linux.
type OptionFunc ¶
type OptionFunc = func(opt *Options)
OptionFunc mutates Options during New construction.
var ( // LargeLockedBufferMemOptions uses the package maximum registered-buffer memory. // This equals the default and keeps the helper-based option style available. LargeLockedBufferMemOptions OptionFunc = func(opt *Options) { opt.LockedBufferMem = registerBufferSize * registerBufferNum } // MultiSizeBufferOptions enables multi-size buffer groups. MultiSizeBufferOptions OptionFunc = func(opt *Options) { opt.MultiSizeBuffer = 1 } )
type Options ¶
type Options struct {
// Entries specifies the number of SQE slots and must be between 1 and
// EntriesHuge, inclusive (use Entries* constants).
Entries int
// LockedBufferMem is the total memory for registered buffers. It must be a
// multiple of BufferSizeLarge from BufferSizeLarge through the package
// maximum selected by LargeLockedBufferMemOptions.
LockedBufferMem int
// ReadBufferSize is the size of each single-size provided buffer. New rounds
// values in [2, 1<<28] upward to a power of two. Multi-size mode ignores it.
ReadBufferSize int
// ReadBufferNum is the number of single-size provided buffers. New rounds
// values in [2, 1<<28] upward to a power of two. Multi-size mode ignores it.
ReadBufferNum int
// ReadBufferGidOffset is the non-negative base group ID. The selected buffer
// layout must fit in the remaining uint16 group-ID namespace.
ReadBufferGidOffset int
// WriteBufferSize is the write buffer sizing hint in bytes.
WriteBufferSize int
// WriteBufferNum is the write buffer count hint.
WriteBufferNum int
// MultiSizeBuffer selects single-size mode at 0. Values in [1, 4096] enable
// multi-size groups and are rounded upward to a power of two.
MultiSizeBuffer int
// MultiIssuers enables shared-submit synchronization and OS-thread migration.
// It defaults to false: one owner must lock its goroutine to an OS thread
// before Start and keep it locked through Stop, serializing ring operations.
// This requests SINGLE_ISSUER + DEFER_TASKRUN and avoids shared-submit
// synchronization. Setting it to true requests COOP_TASKRUN.
MultiIssuers bool
// NotifySucceed disables default CQE suppression on write-like operations.
// Explicit IOSQE_CQE_SKIP_SUCCESS flags still apply.
NotifySucceed bool
// IndirectSubmissionQueue enables the SQ array. When false, New requests
// IORING_SETUP_NO_SQARRAY to reduce ring memory in the direct-index submit path.
IndirectSubmissionQueue bool
// SQE128 requests 128-byte SQE slots for the ring. This is required for
// UringCmdInline, Nop128, and UringCmd128. When false, the ring keeps the
// default 64-byte SQE layout.
SQE128 bool
// HybridPolling enables hybrid I/O polling mode (IORING_SETUP_HYBRID_IOPOLL).
// This delays polling to reduce CPU usage while maintaining low latency.
// Requires: O_DIRECT files on polling-capable storage devices (e.g., NVMe).
// Available since kernel 6.13.
HybridPolling bool
}
Options configures an io_uring instance. New applies option functions in order to the default configuration.
func OptionsForBudget ¶
OptionsForBudget returns Options configured for the given memory budget.
Budget specifies the total memory in bytes to allocate for the io_uring instance. Supports budgets from 16 MiB to 128 GiB (values outside this range are clamped). The returned options use the single-issuer defaults; follow the ownership requirements of New.
Memory is distributed as:
- Ring entries: sized to match expected throughput (more budget = more entries)
- Registered buffers: target 25%, rounded upward with an 8 MiB minimum, and bounded by the package registration cap
- Provided buffers: use the remaining budget after registered buffers and ring overhead
- Multi-size buffer groups use the default tier set and are disabled when it does not fit
- Single-size fallback reduces its buffer count when the default count does not fit
Example:
// 256 MiB budget for a medium server opts := OptionsForBudget(256 * MiB) // 64 MiB budget for memory-constrained environment opts = OptionsForBudget(64 * MiB)
func OptionsForSystem ¶
OptionsForSystem returns Options configured for a machine with the given total memory. It derives a memory budget (25% of system memory) and delegates to OptionsForBudget. The returned options use the single-issuer defaults; follow the ownership requirements of New.
Use the MachineMemory* constants for common configurations:
// 1GB machine (e.g., Linode Nanode, small CI runner) opts := OptionsForSystem(MachineMemory1GB) // 4GB machine (e.g., medium VM) opts = OptionsForSystem(MachineMemory4GB)
Or pass the actual system memory:
opts := OptionsForSystem(3840 * MiB) // 3.75 GiB
func (*Options) Apply ¶
func (uo *Options) Apply(opts ...OptionFunc)
Apply applies option helpers in order.
type PollCloser ¶
type PollCloser = iofd.PollCloser
PollCloser extends PollFd with close capability.
type QueryHdr ¶
type QueryHdr struct {
NextEntry uint64 // Pointer to next query entry
QueryData uint64 // Query-specific data pointer
QueryOp uint32 // Query operation type (IO_URING_QUERY_*)
Size uint32 // Size of the query response
Result int32 // Result code
// contains filtered or unexported fields
}
QueryHdr is the header for query operations. Matches struct io_uring_query_hdr in Linux.
type QueryOpcode ¶
type QueryOpcode struct {
NrRequestOpcodes uint32 // Number of supported IORING_OP_* opcodes
NrRegisterOpcodes uint32 // Number of supported IORING_REGISTER_* opcodes
FeatureFlags uint64 // Raw kernel feature bitmask returned by IORING_REGISTER_QUERY
RingSetupFlags uint64 // Bitmask of IORING_SETUP_* flags
EnterFlags uint64 // Bitmask of IORING_ENTER_* flags
SqeFlags uint64 // Bitmask of IOSQE_* flags
NrQueryOpcodes uint32 // Number of available query opcodes
ResultSize uint32 // Number of query-data bytes returned by the kernel
// contains filtered or unexported fields
}
QueryOpcode returns information about supported io_uring operations. Fields before ResultSize match struct io_uring_query_opcode in Linux.
type QuerySCQ ¶
type QuerySCQ struct {
HdrSize uint64 // SQ/CQ rings header size
HdrAlignment uint64 // Header alignment requirement
ResultSize uint32 // Number of query-data bytes returned by the kernel
}
QuerySCQ returns information about SQ/CQ rings. Fields before ResultSize match struct io_uring_query_scq in Linux.
type QueryZCRX ¶
type QueryZCRX struct {
RegisterFlags uint64 // Bitmask of supported ZCRX_REG_* flags
AreaFlags uint64 // Bitmask of IORING_ZCRX_AREA_* flags
NrCtrlOpcodes uint32 // Number of supported ZCRX_CTRL_* opcodes
Features uint32 // ZCRX_FEATURE_* bitmask (Linux 7.0+; reserved before then)
RqHdrSize uint32 // Refill ring header size
RqHdrAlignment uint32 // Header alignment requirement
ResultSize uint32 // Number of query-data bytes returned by the kernel
// contains filtered or unexported fields
}
QueryZCRX returns information about ZCRX capabilities. Fields before ResultSize match struct io_uring_query_zcrx in Linux.
type RawSockaddr ¶
type RawSockaddr = sock.RawSockaddr
RawSockaddr is the base raw socket address structure.
type RawSockaddrAny ¶
type RawSockaddrAny = sock.RawSockaddrAny
RawSockaddrAny is the widest raw socket address storage type.
type RawSockaddrInet4 ¶
type RawSockaddrInet4 = sock.RawSockaddrInet4
RawSockaddrInet4 is the raw IPv4 socket address structure.
type RawSockaddrInet6 ¶
type RawSockaddrInet6 = sock.RawSockaddrInet6
RawSockaddrInet6 is the raw IPv6 socket address structure.
type RawSockaddrUnix ¶
type RawSockaddrUnix = sock.RawSockaddrUnix
RawSockaddrUnix is the raw Unix domain socket address structure.
type RegWait ¶
type RegWait struct {
Ts Timespec // Timeout specification
MinWaitUsec uint32 // Minimum wait time in microseconds
Flags uint32 // IORING_REG_WAIT_* flags
Sigmask uint64 // Signal mask
SigmaskSz uint32 // Signal mask size
// contains filtered or unexported fields
}
RegWait is a registered wait region entry. Matches struct io_uring_reg_wait in Linux.
type RegionDesc ¶
type RegionDesc struct {
UserAddr uint64 // User address of the region
Size uint64 // Size of the region
Flags uint32 // Region flags
ID uint32 // Region identifier
MmapOffset uint64 // Offset for mmap
// contains filtered or unexported fields
}
RegionDesc describes a memory region for io_uring. Matches struct io_uring_region_desc in Linux.
type RegisterBuffer ¶
type RegisterBuffer = [registerBufferSize]byte
Buffer types re-exported from iobuf.
type RegisterBufferPool ¶
type RegisterBufferPool struct {
// contains filtered or unexported fields
}
RegisterBufferPool is a pool of registered buffers for io_uring. Uses 128 KiB registered buffers aligned with RegisterBuffer.
func NewRegisterBufferPool ¶
func NewRegisterBufferPool(capacity int) *RegisterBufferPool
NewRegisterBufferPool creates a new buffer pool with the given capacity.
func (*RegisterBufferPool) Fill ¶
func (p *RegisterBufferPool) Fill(factory func() RegisterBuffer)
Fill populates the pool using the provided factory function.
type SQEContext ¶
type SQEContext uint64
SQEContext encodes io_uring user_data. Direct mode packs opcode, flags, buffer group, and fd inline. Indirect and Extended modes store tagged addresses of shared context storage.
Copying a context does not copy or keep its target alive. Caller must keep pointer targets reachable and address-stable through completion and all borrowed access. Do not change submitted SQE fields, reuse, or release a target while completions for that request remain pending. The Darwin simulator uses the same context encoding.
const ( // CtxModeDirect indicates inline context (8B, zero allocation). CtxModeDirect SQEContext = 0 << 62 // CtxModeIndirect indicates pointer to IndirectSQE (64B). CtxModeIndirect SQEContext = 1 << 62 // CtxModeExtended indicates pointer to ExtSQE (128B). CtxModeExtended SQEContext = 2 << 62 )
Context mode constants (bits 62-63).
func ForFD ¶
func ForFD(fd int32) SQEContext
ForFD returns a direct-mode context with only the fd set.
func PackDirect ¶
func PackDirect(op, flags uint8, bufGroup uint16, fd int32) SQEContext
PackDirect packs direct-mode submission context.
func PackExtended ¶
func PackExtended(sqe *ExtSQE) SQEContext
PackExtended encodes sqe's address without copying or keeping it alive. Caller must satisfy the SQEContext target-lifetime contract.
func PackIndirect ¶
func PackIndirect(sqe *IndirectSQE) SQEContext
PackIndirect encodes sqe's address without copying or keeping it alive. Caller must satisfy the SQEContext target-lifetime contract.
func SQEContextFromRaw ¶
func SQEContextFromRaw(v uint64) SQEContext
SQEContextFromRaw creates an SQEContext from a raw uint64 value. Used when decoding CQE.userData.
func (SQEContext) BufGroup ¶
func (c SQEContext) BufGroup() uint16
BufGroup returns the buffer group index.
func (SQEContext) ExtSQE ¶
func (c SQEContext) ExtSQE() *ExtSQE
ExtSQE returns the borrowed extended target. Caller must ensure c.IsExtended() and that the target remains live.
func (SQEContext) FD ¶
func (c SQEContext) FD() int32
FD returns the context's fd field, which can hold a registered-file index. Direct mode sign-extends its 30-bit field; pointer modes read the full int32.
func (SQEContext) HasBufferSelect ¶
func (c SQEContext) HasBufferSelect() bool
HasBufferSelect reports whether the IOSQE_BUFFER_SELECT flag is set.
func (SQEContext) IndirectSQE ¶
func (c SQEContext) IndirectSQE() *IndirectSQE
IndirectSQE returns the borrowed indirect target. Caller must ensure c.IsIndirect() and that the target remains live.
func (SQEContext) IsDirect ¶
func (c SQEContext) IsDirect() bool
IsDirect reports whether this is a Direct mode context (inline data).
func (SQEContext) IsExtended ¶
func (c SQEContext) IsExtended() bool
IsExtended reports whether this is an Extended mode context (pointer to 128B).
func (SQEContext) IsIndirect ¶
func (c SQEContext) IsIndirect() bool
IsIndirect reports whether this is an Indirect mode context (pointer to 64B).
func (SQEContext) Mode ¶
func (c SQEContext) Mode() SQEContext
Mode returns the context mode (Direct, Indirect, Extended, or Reserved).
func (SQEContext) OrFlags ¶
func (c SQEContext) OrFlags(flags uint8) SQEContext
OrFlags returns a context with flags ORed into the existing set. Direct mode returns an updated value; Indirect and Extended modes mutate shared target storage and return c.
func (SQEContext) Raw ¶
func (c SQEContext) Raw() uint64
Raw returns the underlying uint64 value for direct use in SQE.userData.
func (SQEContext) WithBufGroup ¶
func (c SQEContext) WithBufGroup(bufGroup uint16) SQEContext
WithBufGroup returns a context with the buffer group replaced. Direct mode returns an updated value; Indirect and Extended modes mutate shared target storage and return c.
func (SQEContext) WithFD ¶
func (c SQEContext) WithFD(fd iofd.FD) SQEContext
WithFD replaces the context's fd field with a descriptor or registered-file index. Direct mode returns an updated value; Indirect and Extended modes mutate shared target storage and return c.
func (SQEContext) WithFlags ¶
func (c SQEContext) WithFlags(flags uint8) SQEContext
WithFlags returns a context with the flags replaced. Direct mode returns an updated value; Indirect and Extended modes mutate shared target storage and return c.
func (SQEContext) WithOp ¶
func (c SQEContext) WithOp(op uint8) SQEContext
WithOp returns a context with the opcode replaced. Direct mode returns an updated value; Indirect and Extended modes mutate shared target storage and return c.
type SQEView ¶
type SQEView struct {
// contains filtered or unexported fields
}
SQEView borrows read-only access to a 64-byte base SQE. Copying the view does not copy the fields or transfer ownership. Copy needed fields before target mutation, reuse, or release; never access released storage. SQE128 extensions are outside this view. The zero value is invalid.
Usage ¶
cqe := cqes[i]
if cqe.FullSQE() {
sqe := cqe.SQE()
op := sqe.Opcode()
fd := sqe.FD()
addr := sqe.Addr()
// ...
}
Field Layout (64 bytes) ¶
┌────────────┬────────────┬────────────┬────────────┐ │ opcode (1) │ flags (1) │ ioprio (2) │ fd (4) │ bytes 0-7 ├────────────┴────────────┴────────────┴────────────┤ │ off (8) │ bytes 8-15 ├───────────────────────────────────────────────────┤ │ addr (8) │ bytes 16-23 ├────────────────────────┬──────────────────────────┤ │ len (4) │ uflags (4) │ bytes 24-31 ├────────────────────────┴──────────────────────────┤ │ userData (8) │ bytes 32-39 ├────────────┬───────────┬──────────────────────────┤ │bufIndex(2) │person.(2) │ spliceFdIn (4) │ bytes 40-47 ├────────────┴───────────┴──────────────────────────┤ │ pad[0] (8) │ bytes 48-55 ├───────────────────────────────────────────────────┤ │ pad[1] (8) │ bytes 56-63 └───────────────────────────────────────────────────┘
func ViewExtSQE ¶
ViewExtSQE borrows the base SQE from ext; it does not copy its fields.
func ViewSQE ¶
func ViewSQE(indirect *IndirectSQE) SQEView
ViewSQE borrows the base SQE from indirect; it does not copy its fields.
func (SQEView) Addr ¶
Addr returns the address/pointer field. Interpretation depends on the operation:
- For read/write: buffer address
- For accept: sockaddr pointer
- For timeout: timespec pointer
func (SQEView) BufGroup ¶
BufGroup returns the buffer group ID. Only valid when IOSQE_BUFFER_SELECT flag is set.
func (SQEView) FileIndex ¶
FileIndex returns the file index for direct file operations. This is a union with spliceFdIn.
func (SQEView) HasBufferSelect ¶
HasBufferSelect reports whether IOSQE_BUFFER_SELECT flag is set.
func (SQEView) HasCQESkipSuccess ¶
HasCQESkipSuccess reports whether IOSQE_CQE_SKIP_SUCCESS flag is set.
func (SQEView) HasFixedFile ¶
HasFixedFile reports whether IOSQE_FIXED_FILE flag is set.
func (SQEView) HasIODrain ¶
HasIODrain reports whether IOSQE_IO_DRAIN flag is set.
func (SQEView) HasIOHardlink ¶
HasIOHardlink reports whether IOSQE_IO_HARDLINK flag is set.
func (SQEView) Len ¶
Len returns the length field. Interpretation depends on the operation:
- For read/write: buffer length
- For accept: zero
- For socket: protocol
func (SQEView) Off ¶
Off returns the offset field. Interpretation depends on the operation:
- For read/write: file offset
- For accept: sockaddr length pointer
- For timeout: completion count, or repeat count for multishot
- For socket: socket type
func (SQEView) Personality ¶
Personality returns the personality ID for credentials.
func (SQEView) RawFD ¶
RawFD returns the same SQE field as SQEView.FD, as an int32.
func (SQEView) SpliceFDIn ¶
SpliceFDIn returns the splice input file descriptor.
func (SQEView) UFlags ¶
UFlags returns the union flags field. Interpretation depends on the operation:
- For read/write: RW flags
- For poll: poll events
- For timeout: timeout flags
- For accept: accept flags
- For open: open flags
- For send/recv: msg flags
- For uring commands: IORING_URING_CMD_* flags
type ScopedExtSQE ¶
type ScopedExtSQE struct {
Ext *ExtSQE
// contains filtered or unexported fields
}
ScopedExtSQE holds a borrowed ExtSQE for deferred release on submission failure. After a successful submission, call ScopedExtSQE.Submitted to transfer return responsibility to completion handling. The context remains borrowed until Uring.PutExtSQE returns it to the pool.
A scope must have one owner: do not copy it or use it concurrently. Do not replace Ext or return it directly while the scope owns it. The zero value holds no context and is safe to Release.
Usage pattern:
scope := ring.NewScopedExtSQE()
if !scope.Valid() {
return iox.ErrWouldBlock
}
defer scope.Release()
uring.CtxV1Of(scope.Ext).Val1 = requestID
ctx := uring.PackExtended(scope.Ext).WithFD(fd)
if err := ring.Read(ctx, buf); err != nil {
return err
}
scope.Submitted()
return nil
func (*ScopedExtSQE) Release ¶
func (s *ScopedExtSQE) Release()
Release returns an unsubmitted context to its ring and clears Ext. Returning it invalidates all pointers and views into that borrow. Repeated calls and calls after ScopedExtSQE.Submitted are no-ops.
func (*ScopedExtSQE) Submitted ¶
func (s *ScopedExtSQE) Submitted()
Submitted marks a successful submission so Release becomes a no-op. It does not submit or return the context. Completion handling must return it with Uring.PutExtSQE after all request completions and borrowed access finish.
func (*ScopedExtSQE) Valid ¶
func (s *ScopedExtSQE) Valid() bool
Valid reports whether Ext is non-nil. It does not check submission state or whether the context has been returned.
type SendTargets ¶
SendTargets represents a caller-owned ordered set of target sockets. The count and descriptors must remain stable during a multicast call.
type Sockaddr ¶
Sockaddr is the socket address interface used by socket operations.
func AddrToSockaddr ¶
AddrToSockaddr converts an Addr to a Sockaddr. Submission paths that stage the result keep the returned Sockaddr alive.
type Statx ¶
type Statx struct {
Mask uint32
Blksize uint32
Attributes uint64
Nlink uint32
Uid uint32
Gid uint32
Mode uint16
Ino uint64
Size uint64
Blocks uint64
Attributes_mask uint64
Atime StatxTimestamp
Btime StatxTimestamp
Ctime StatxTimestamp
Mtime StatxTimestamp
Rdev_major uint32
Rdev_minor uint32
Dev_major uint32
Dev_minor uint32
Mnt_id uint64
Dio_mem_align uint32
Dio_offset_align uint32
// contains filtered or unexported fields
}
Statx represents the statx structure. Layout matches struct statx in Linux.
type StatxTimestamp ¶
StatxTimestamp represents a timestamp in statx.
type SubscriptionState ¶
type SubscriptionState uint32
SubscriptionState describes the original multishot request, independently of any pending cancellation CQE.
Active --cancel submitted--> Cancelling
| |
+---------------+--------------+
| original terminal CQE handled (any result)
v
Stopped
State Active() Cancel()
Active true May submit cancellation
Cancelling true No-op
Stopped false No-op
Stopped is absorbing. It does not imply that cancellation dispatch or the terminal callback has finished. Continue dispatching queued cancellation CQEs through MultishotSubscription.HandleCQE or their extended handlers.
const ( // SubscriptionActive receives completions and can still cancel. SubscriptionActive SubscriptionState = iota // SubscriptionCancelling has enqueued cancel and awaits the original terminal CQE. SubscriptionCancelling // SubscriptionStopped has observed the original terminal CQE. // A queued cancellation CQE may still need dispatch. SubscriptionStopped )
type UnderlyingProtocol ¶
type UnderlyingProtocol = sock.UnderlyingProtocol
UnderlyingProtocol represents the transport protocol.
type Uring ¶
type Uring struct {
*Options
// Features reports actual ring sizing and userdata metadata.
Features *Features
// contains filtered or unexported fields
}
Uring is the main io_uring interface for submitting and completing I/O operations. It wraps the kernel io_uring instance with buffer management and typed operations. Default rings have one owner locked to an OS thread from before Start through Stop. The owner serializes submit, Wait, WaitDirect, WaitExtended, Stop, and ResizeRings. Set MultiIssuers to true for shared submission or OS-thread migration; lifecycle and resource ownership remain caller responsibilities.
func New ¶
func New(options ...OptionFunc) (*Uring, error)
New creates a new io_uring instance with the specified options. It returns ErrInvalidParam for an invalid option domain before creating the ring. A successful call returns an unstarted ring; call Start to initialize buffers and enable it.
Before Start, the caller may transfer the unstarted ring to another goroutine with synchronized, exclusive access. By default, that owner must call runtime.LockOSThread before Start and remain locked through Stop, serializing ring operations. Set Options.MultiIssuers to true to allow shared submission or OS-thread migration.
func (*Uring) Accept ¶
func (ur *Uring) Accept(sqeCtx SQEContext, options ...OpOptionFunc) error
Accept accepts a new connection from a listener socket. The fd in sqeCtx should be set to the listener socket.
func (*Uring) AcceptDirect ¶
func (ur *Uring) AcceptDirect(sqeCtx SQEContext, fileIndex uint32, options ...OpOptionFunc) error
AcceptDirect accepts a connection directly into a registered file table slot. The fileIndex specifies which slot to use (0-based), or use IORING_FILE_INDEX_ALLOC for auto-allocation (the allocated index is returned in CQE res). IORING_FILE_INDEX_ALLOC-1 is not a valid explicit slot because the kernel encoding reserves the next value for auto-allocation. SOCK_CLOEXEC is not supported with direct accept. Requires registered files via RegisterFiles or RegisterFilesSparse.
func (*Uring) AcceptMultishot ¶
func (ur *Uring) AcceptMultishot(sqeCtx SQEContext, handler MultishotHandler, options ...OpOptionFunc) (*MultishotSubscription, error)
AcceptMultishot starts a multishot accept subscription. While callbacks stay enabled, the handler receives one MultishotStep per original CQE and at most one terminal stop. Each successful original CQE returns a process fd in Res, including fd zero. The caller must transfer or close each fd, even on a final or suppressed step. Options may add SQE control flags and accept-specific ioprio flags such as `IORING_ACCEPT_POLL_FIRST`.
func (*Uring) AsyncCancel ¶
func (ur *Uring) AsyncCancel(sqeCtx SQEContext, targetUserData uint64, options ...OpOptionFunc) error
AsyncCancel cancels a pending async operation matched by the user_data value of the original SQE.
func (*Uring) AsyncCancelAll ¶
func (ur *Uring) AsyncCancelAll(sqeCtx SQEContext, options ...OpOptionFunc) error
AsyncCancelAll submits a cancellation request for all pending operations. The cancellation CQE reports the matched count or a negative errno. Each original operation still has its own completion.
func (*Uring) AsyncCancelAny ¶
func (ur *Uring) AsyncCancelAny(sqeCtx SQEContext, options ...OpOptionFunc) error
AsyncCancelAny submits cancellation without filtering by request identity. It may cancel multiple pending operations. The cancellation CQE reports the matched count or a negative errno; each original operation has its own CQE.
func (*Uring) AsyncCancelFD ¶
func (ur *Uring) AsyncCancelFD(sqeCtx SQEContext, cancelAll bool, options ...OpOptionFunc) error
AsyncCancelFD cancels operations on a specific file descriptor. If cancelAll is true, cancels all matching operations and returns count. Otherwise cancels the first matching operation. The FD to cancel is taken from sqeCtx.FD().
func (*Uring) AsyncCancelOpcode ¶
func (ur *Uring) AsyncCancelOpcode(sqeCtx SQEContext, opcode uint8, cancelAll bool, options ...OpOptionFunc) error
AsyncCancelOpcode cancels operations of a specific opcode type. If cancelAll is true, cancels all matching operations and returns count. Otherwise cancels the first matching operation.
func (*Uring) Bind ¶
func (ur *Uring) Bind(sqeCtx SQEContext, addr Addr, options ...OpOptionFunc) error
Bind binds a socket to an address.
func (*Uring) BundleIterator ¶
func (ur *Uring) BundleIterator(cqe CQEView, group uint16) (BundleIterator, bool)
BundleIterator constructs an iterator for one bundle receive CQE from a package-managed buffer group. Pass the registered group of the matched receive. It requires F_BUFFER and a whole-slot return from that group. At EOF or on error, a returned slot yields one empty slice and still requires Recycle.
The returned iterator borrows ring-owned backing memory. Process the buffers before calling Recycle. Call Recycle exactly once across all copies of the iterator, then do not read the yielded buffers. Recycle must run from a single goroutine without racing other buffer-ring recycle/advance activity on the same Uring.
func (*Uring) CQPending ¶
CQPending returns the number of CQEs waiting to be reaped. Caller-side runtime code can use this to decide when to drain completions. On single-issuer rings it is not safe for concurrent use with ResizeRings; caller must serialize those operations.
func (*Uring) CloneBuffers ¶
CloneBuffers clones registered buffers from another io_uring ring. This enables buffer sharing between multiple rings.
On success, the destination retains the cloned buffers and exposes their slices through Uring.RegisteredBuffer.
Parameters:
- src: source ring
- srcOff: source buffer offset
- dstOff: destination buffer offset
- count: number of buffers to clone
- replace: if true, replace existing buffers at destination offset
A zero count clones the complete source table and requires both offsets to be zero. Whole-table cloning requires Linux 6.12+; nonzero offsets or replacement require Linux 6.13+.
Replacing a destination range preserves the registrations outside it.
func (*Uring) CloneBuffersFromRegistered ¶
func (ur *Uring) CloneBuffersFromRegistered(src *Uring, srcRegisteredRingIdx uint32, srcOff, dstOff, count uint32, replace bool) error
CloneBuffersFromRegistered clones buffers from src through a task-registered ring index. src supplies the buffer backing storage. srcRegisteredRingIdx must identify src in the current Linux task's IORING_REGISTER_RING_FDS table. Because that table is task-local, the caller must keep source registration, this call, and source unregistration on the same OS thread.
Cloning and replacement follow Uring.CloneBuffers.
func (*Uring) Close ¶
func (ur *Uring) Close(sqeCtx SQEContext, options ...OpOptionFunc) error
Close submits `IORING_OP_CLOSE` for the descriptor carried in sqeCtx. If sqeCtx carries IOSQE_FIXED_FILE, Close treats its FD field as a registered-file slot and emits close-direct semantics for that slot. It closes a target descriptor; it does not tear down the Uring instance.
func (*Uring) Connect ¶
func (ur *Uring) Connect(sqeCtx SQEContext, remote Addr, options ...OpOptionFunc) error
Connect initiates a socket connection to a remote address.
func (*Uring) EpollWait ¶
func (ur *Uring) EpollWait(sqeCtx SQEContext, events []EpollEvent, timeout int32, options ...OpOptionFunc) error
EpollWait performs an epoll_wait operation via io_uring. The opcode does not accept an inline timeout; timeout must be 0 and callers should use LinkTimeout when they need a deadline. Caller must keep events valid until the operation completes.
func (*Uring) ExtSQE ¶
ExtSQE borrows a cleared ExtSQE for Extended mode submissions. It returns nil if the context pool is exhausted, independently of SQ capacity. Keep the context until all request completions and borrowed access finish, then return it to this ring with PutExtSQE.
func (*Uring) FGetXattr ¶
func (ur *Uring) FGetXattr(sqeCtx SQEContext, name string, value []byte, options ...OpOptionFunc) error
FGetXattr gets an extended attribute from a file descriptor. Caller must keep value valid until completion. The result length is returned in the CQE.
func (*Uring) FSetXattr ¶
func (ur *Uring) FSetXattr(sqeCtx SQEContext, name string, value []byte, flags uint32, options ...OpOptionFunc) error
FSetXattr sets an extended attribute on a file descriptor. Caller must keep value valid until the operation completes.
func (*Uring) FTruncate ¶
func (ur *Uring) FTruncate(sqeCtx SQEContext, length int64, options ...OpOptionFunc) error
FTruncate truncates a file to the specified length.
func (*Uring) Fallocate ¶
func (ur *Uring) Fallocate(sqeCtx SQEContext, mode uint32, offset int64, length int64, options ...OpOptionFunc) error
Fallocate allocates a positive-length file range.
func (*Uring) FileAdvise ¶
func (ur *Uring) FileAdvise(sqeCtx SQEContext, offset int64, length int, advice uint32, options ...OpOptionFunc) error
FileAdvise provides advice about file access patterns.
func (*Uring) FilesUpdate ¶
func (ur *Uring) FilesUpdate(sqeCtx SQEContext, fds []int32, offset int, options ...OpOptionFunc) error
FilesUpdate updates registered files at the specified offset. The fds slice contains the new file descriptors to register. Use -1 to unregister a slot. offset must fit in uint32; math.MaxUint32 is preserved as IORING_FILE_INDEX_ALLOC. Caller must keep fds reachable, address-stable, and unmodified until the operation completes. Allocation mode writes the allocated indexes into fds.
func (*Uring) FixedFdInstall ¶
func (ur *Uring) FixedFdInstall(sqeCtx SQEContext, fixedIndex int, flags uint32, options ...OpOptionFunc) error
FixedFdInstall installs a fixed (registered) file descriptor into the normal file descriptor table. Returns the new fd in the CQE result. The fixedIndex is a non-negative index in the registered files table and must fit in int32. flags may be zero or IORING_FIXED_FD_NO_CLOEXEC.
func (*Uring) FutexWait ¶
func (ur *Uring) FutexWait(sqeCtx SQEContext, addr *uint32, val uint64, mask uint64, flags uint32, options ...OpOptionFunc) error
FutexWait submits an async futex wait operation. It waits only if the value at addr equals val; a mismatch completes with -EAGAIN. A matching wait completes after a wake, cancellation, or error. Caller must keep addr valid until the operation completes.
func (*Uring) FutexWaitV ¶
func (ur *Uring) FutexWaitV(sqeCtx SQEContext, waitv unsafe.Pointer, count uint32, flags uint32, options ...OpOptionFunc) error
FutexWaitV submits a vectored futex wait operation. Waits on multiple futexes simultaneously. The waitv pointer should point to a struct futex_waitv array with 1 through 128 elements. flags must be zero. Caller must keep waitv valid until the operation completes.
func (*Uring) FutexWake ¶
func (ur *Uring) FutexWake(sqeCtx SQEContext, addr *uint32, val uint64, mask uint64, flags uint32, options ...OpOptionFunc) error
FutexWake submits an async futex wake operation. Wakes up to val waiters on the futex at addr, using the specified mask and flags. Caller must keep addr valid until the operation completes.
func (*Uring) GetXattr ¶
func (ur *Uring) GetXattr(sqeCtx SQEContext, path, name string, value []byte, options ...OpOptionFunc) error
GetXattr gets an extended attribute from a path. Caller must keep value valid until completion. The result length is returned in the CQE.
func (*Uring) IndirectSQE ¶
func (ur *Uring) IndirectSQE() *IndirectSQE
IndirectSQE borrows an IndirectSQE for Indirect mode submissions. It returns nil if the context pool is exhausted, independently of SQ capacity. Initialize its retained contents before use. Keep it until all request completions and borrowed access finish, then return it with PutIndirectSQE.
func (*Uring) LinkAt ¶
func (ur *Uring) LinkAt(sqeCtx SQEContext, oldDirfd iofd.FD, oldPath, newPath string, flags uint32, options ...OpOptionFunc) error
LinkAt creates a hard link.
func (*Uring) LinkTimeout ¶
func (ur *Uring) LinkTimeout(sqeCtx SQEContext, d time.Duration, options ...OpOptionFunc) error
LinkTimeout submits a deadline for the preceding IOSQE_IO_LINK chain. Expiry attempts cancellation; the linked operation may already have completed. Caller must observe both the operation and timeout CQEs before retirement.
func (*Uring) Listen ¶
func (ur *Uring) Listen(sqeCtx SQEContext, options ...OpOptionFunc) error
Listen starts listening on a socket.
func (*Uring) MkdirAt ¶
func (ur *Uring) MkdirAt(sqeCtx SQEContext, path string, mode uint32, options ...OpOptionFunc) error
MkdirAt creates a directory.
func (*Uring) MsgRing ¶
func (ur *Uring) MsgRing(sqeCtx SQEContext, userData int64, result int32, options ...OpOptionFunc) error
MsgRing sends a message to the ring identified by sqeCtx.FD(), which may be this ring. The source CQE reports the send result. On the target CQE, Context().Raw() contains the bits of userData and Res contains result, including negative values. Use distinct message IDs and local request tokens when both kinds of CQE share a ring.
func (*Uring) MsgRingFD ¶
func (ur *Uring) MsgRingFD(sqeCtx SQEContext, srcFD uint32, dstSlot uint32, userData int64, skipCQE bool, options ...OpOptionFunc) error
MsgRingFD installs a reference to a registered file in another io_uring instance. sqeCtx.FD() selects the target ring; both rings need registered file tables. srcFD is the source slot, which remains registered. dstSlot selects a target slot, replacing its current file, or IORING_FILE_INDEX_ALLOC to allocate one. userData identifies the target CQE; skipCQE suppresses only that CQE.
When posted, successful source and target CQEs report the same result:
dstSlot Res Explicit slot 0 IORING_FILE_INDEX_ALLOC Allocated slot index
A source CQE reporting -EOVERFLOW means installation succeeded and the target notification failed. With IORING_FILE_INDEX_ALLOC, this result omits the allocated slot index. Reconcile the target table before retrying.
func (*Uring) Multicast ¶
func (ur *Uring) Multicast(sqeCtx SQEContext, targets SendTargets, bufIndex int, p []byte, offset int64, n int, options ...OpOptionFunc) (int, error)
Multicast submits sends to each target in order, automatically selecting copy or zero-copy by payload size and target count. bufIndex selects a registered buffer; use -1 to send from p. offset and n select the payload. Unregistered buffers always use ordinary sends. Registered buffers use zero-copy at 8 KiB for fewer than 8 targets, 4 KiB for 8-63, 3 KiB for 64-511, 2 KiB for 512-4095, and 1.5 KiB for 4096 or more. These are workload heuristics; MulticastZeroCopy uses lower thresholds to favor zero-copy.
sqeCtx must use Direct mode. Each send records its selected opcode and target FD. Registered sends replace the buffer group with bufIndex. Ranges with the same opcode, flags, FD and slot share user_data. To distinguish their results, serialize those sends or submit individual operations with distinct live contexts.
The return count is the accepted target prefix, not completed sends or bytes. Submission stops at the first error, including ErrWouldBlock. Resume with the remaining targets; replaying the accepted prefix can duplicate delivery. A stream send may complete with fewer than n bytes. When completions are enabled, inspect each target's result and resume only its unsent suffix. Keep the payload valid and unmodified until all accepted sends release it. Ordinary sends follow NotifySucceed. Selected zero-copy sends always request completion evidence and reject explicit IOSQE_CQE_SKIP_SUCCESS. Their borrows end on terminal data without MORE or after both data and notification. Inspect each CQE's opcode and flags. Resuming with fewer targets can change the selected operation.
func (*Uring) MulticastZeroCopy ¶
func (ur *Uring) MulticastZeroCopy(sqeCtx SQEContext, targets SendTargets, bufIndex int, offset int64, n int, options ...OpOptionFunc) (int, error)
MulticastZeroCopy submits sends from a registered buffer to each target, automatically favoring zero-copy at lower thresholds than Multicast. It selects zero-copy at 1.5 KiB for fewer than 4 targets, 1 KiB for 4-15, 512 bytes for 16-63, 128 bytes for 64-255, and any size for 256 or more. Smaller payloads use ordinary sends. These thresholds are workload heuristics. It uses the same Direct-context and accepted-prefix contract as Multicast. Each target's data CQE reports byte progress and may describe a short stream send. Caller code owns any submission of that target's unsent suffix.
Both selected paths request completion evidence, independent of NotifySucceed. Explicit IOSQE_CQE_SKIP_SUCCESS is invalid. Keep the buffer range immutable until each accepted ordinary send completes and each zero-copy send reports terminal data without MORE or both data and notification. Inspect each CQE's opcode and flags because a resumed call can select a different operation. The caller decides whether to retry a rejected zero-copy operation.
func (*Uring) MustExtSQE ¶
MustExtSQE gets an ExtSQE from the pool, panicking if exhausted. Use only in contexts where pool exhaustion is a programming error.
func (*Uring) NAPIAddStaticID ¶
NAPIAddStaticID adds a NAPI ID for static tracking mode. Use this when IO_URING_NAPI_TRACKING_STATIC is enabled. Requires kernel 6.13+.
func (*Uring) NAPIDelStaticID ¶
NAPIDelStaticID removes a NAPI ID from static tracking. Use this when IO_URING_NAPI_TRACKING_STATIC is enabled. Requires kernel 6.13+.
func (*Uring) NewScopedExtSQE ¶
func (ur *Uring) NewScopedExtSQE() ScopedExtSQE
NewScopedExtSQE borrows a cleared ExtSQE into a scope. It returns a scope with nil Ext if the context pool is exhausted.
func (*Uring) Nop ¶
func (ur *Uring) Nop(sqeCtx SQEContext, options ...OpOptionFunc) error
Nop submits a no-op request.
func (*Uring) Nop128 ¶
func (ur *Uring) Nop128(sqeCtx SQEContext, options ...OpOptionFunc) error
Nop128 submits a 128-byte NOP operation. Requires a ring created with Options.SQE128; otherwise it returns ErrNotSupported.
func (*Uring) OpenAt ¶
func (ur *Uring) OpenAt(sqeCtx SQEContext, pathname string, openFlags uint32, mode uint32, options ...OpOptionFunc) error
OpenAt opens a file at the given path relative to a directory fd.
func (*Uring) Pipe ¶
func (ur *Uring) Pipe(sqeCtx SQEContext, fds *[2]iofd.FD, pipeFlags uint32, options ...OpOptionFunc) error
Pipe creates a pipe using io_uring. The fds parameter must point to a [2]iofd.FD array where the kernel will write the read end (fds[0]) and write end (fds[1]) file descriptors. On successful completion, fds[0] will be the read end and fds[1] the write end. Caller must keep fds valid until the operation completes. After a successful completion, caller owns both descriptors.
func (*Uring) PollAdd ¶
func (ur *Uring) PollAdd(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
PollAdd adds a file descriptor to the poll set. Events must fit the kernel's unsigned 32-bit poll mask.
func (*Uring) PollAddLevel ¶
func (ur *Uring) PollAddLevel(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
PollAddLevel returns ErrNotSupported because the Linux io_uring poll ABI does not admit IORING_POLL_ADD_LEVEL in a POLL_ADD submission.
func (*Uring) PollAddMultishot ¶
func (ur *Uring) PollAddMultishot(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
PollAddMultishot adds a persistent poll request that generates multiple CQEs. Unlike PollAdd which requires re-submission after each event, multishot poll automatically re-arms and continues generating CQEs until cancelled. Each CQE has IORING_CQE_F_MORE set while poll continues; the final CQE has !IORING_CQE_F_MORE when poll terminates or is cancelled. Events must fit the kernel's unsigned 32-bit poll mask.
func (*Uring) PollAddMultishotLevel ¶
func (ur *Uring) PollAddMultishotLevel(sqeCtx SQEContext, events int, options ...OpOptionFunc) error
PollAddMultishotLevel returns ErrNotSupported because the Linux io_uring poll ABI does not admit IORING_POLL_ADD_LEVEL in a POLL_ADD submission.
func (*Uring) PollRemove ¶
func (ur *Uring) PollRemove(sqeCtx SQEContext, targetUserData uint64, options ...OpOptionFunc) error
PollRemove removes a poll request matched by the original SQE user_data.
func (*Uring) PollUpdate ¶
func (ur *Uring) PollUpdate(sqeCtx SQEContext, oldUserData, newUserData uint64, newEvents, updateFlags int, options ...OpOptionFunc) error
PollUpdate modifies an existing poll request in-place without cancellation. This atomically updates the poll events and/or userData of an active poll.
Parameters:
- sqeCtx: Context for this update operation
- oldUserData: userData of the target poll request to update
- newUserData: New userData (used if updateFlags includes IORING_POLL_UPDATE_USER_DATA)
- newEvents: New poll events (used if updateFlags includes IORING_POLL_UPDATE_EVENTS)
- updateFlags: Combination of: IORING_POLL_UPDATE_EVENTS - update the poll event mask IORING_POLL_UPDATE_USER_DATA - update the userData
The poll is located by matching oldUserData. If no matching poll is found, the operation returns -ENOENT. Zero updateFlags with zero newUserData and newEvents behaves as PollRemove. IORING_POLL_ADD_MULTI is not valid for PollUpdate because Linux preserves the existing shot mode; remove the poll and submit PollAddMultishot to change it. Fields without their corresponding update flag must be zero. Invalid update shapes return ErrInvalidParam before submission.
func (*Uring) PutExtSQE ¶
PutExtSQE clears and returns an ExtSQE borrowed from this ring. Call exactly once after all request completions and borrowed access finish. This includes terminal multishot and zero-copy notification CQEs when present. After return, the ExtSQE and all views into it are invalid.
func (*Uring) PutIndirectSQE ¶
func (ur *Uring) PutIndirectSQE(sqe *IndirectSQE)
PutIndirectSQE returns an IndirectSQE borrowed from this ring without clearing it. Call exactly once after all request completions and borrowed access finish. This includes terminal multishot and zero-copy notification CQEs when present. After return, the IndirectSQE and all views into it are invalid.
func (*Uring) QueryOpcodes ¶
func (ur *Uring) QueryOpcodes() (*QueryOpcode, error)
QueryOpcodes queries the kernel for supported io_uring operations. Returns detailed information about supported opcodes, features, and flags. Requires the Linux 6.18+ baseline.
func (*Uring) QuerySCQ ¶
QuerySCQ queries the kernel for SQ/CQ ring information. Returns header size and alignment requirements for shared rings. Requires kernel 6.19+.
func (*Uring) QueryZCRX ¶
QueryZCRX queries the kernel for ZCRX (zero-copy receive) capabilities. Returns information about supported ZCRX features and configuration. Requires kernel 6.19+.
func (*Uring) Read ¶
func (ur *Uring) Read(sqeCtx SQEContext, b []byte, options ...OpOptionFunc) error
Read performs a read operation. Caller must keep b valid until the operation completes. WithOffset(-1) uses and advances the file's current position.
func (*Uring) ReadFixed ¶
func (ur *Uring) ReadFixed(sqeCtx SQEContext, bufIndex int, options ...OpOptionFunc) ([]byte, error)
ReadFixed performs a read with a registered (fixed) buffer. WithOffset(-1) uses and advances the file's current position.
func (*Uring) ReadV ¶
func (ur *Uring) ReadV(sqeCtx SQEContext, iovs [][]byte, options ...OpOptionFunc) error
ReadV submits a vectored read with file offset zero. Only OpOption.Flags is used. Caller must keep iovs and their backing buffers valid until the operation completes.
func (*Uring) ReadvFixed ¶
func (ur *Uring) ReadvFixed(sqeCtx SQEContext, offset int64, bufIndex int, iovs [][]byte, options ...OpOptionFunc) error
ReadvFixed performs a vectored read into ranges of one registered buffer. bufIndex selects the registered buffer, and every iov must be a nonempty subslice of RegisteredBuffer(bufIndex). An offset of -1 uses and advances the file's current position.
func (*Uring) Receive ¶
func (ur *Uring) Receive(sqeCtx SQEContext, pollFD PollFd, b []byte, options ...OpOptionFunc) error
Receive performs a socket receive operation. If b is nil, it uses kernel buffer selection without MSG_WAITALL. If b is non-nil, it uses MSG_WAITALL, and caller must keep b valid until the operation completes. WithOffset without WithN receives into the remaining buffer range.
func (*Uring) ReceiveBundle ¶
func (ur *Uring) ReceiveBundle(sqeCtx SQEContext, pollFD PollFd, options ...OpOptionFunc) error
ReceiveBundle submits a receive that can consume multiple provided buffers in publication order. A nil return means the request was queued. The CQE reports the receive result. Use Uring.BundleIterator to visit returned slots, including a selected slot carrying zero bytes.
func (*Uring) ReceiveFD ¶
func (ur *Uring) ReceiveFD(sqeCtx SQEContext, fd iofd.FD, b []byte, options ...OpOptionFunc) error
ReceiveFD performs a socket receive operation using an iofd.FD value instead of a PollFd interface. The fd value is encoded verbatim; when sqeCtx carries IOSQE_FIXED_FILE, it denotes a registered-file index. If b is nil, ReceiveFD uses kernel buffer selection without MSG_WAITALL. If b is non-nil, it uses MSG_WAITALL, and caller must keep b valid until the operation completes. WithOffset without WithN receives into the remaining buffer range.
func (*Uring) ReceiveMultishot ¶
func (ur *Uring) ReceiveMultishot(sqeCtx SQEContext, handler MultishotHandler, options ...OpOptionFunc) (*MultishotSubscription, error)
ReceiveMultishot starts a multishot receive subscription with buffer selection. While callbacks stay enabled, the handler receives one MultishotStep per original CQE and at most one terminal stop. Use `step.CQE.BufID()` for the buffer ID and `step.CQE.Res` for the byte count. Options may add SQE control flags and recv-specific ioprio flags such as `IORING_RECVSEND_POLL_FIRST`.
func (*Uring) ReceiveZeroCopy ¶
func (ur *Uring) ReceiveZeroCopy(sqeCtx SQEContext, pollFD PollFd, n int, zcrxIfqIdx uint32, options ...OpOptionFunc) error
ReceiveZeroCopy performs a zero-copy receive operation. Supported Linux 6.18+ kernels provide the opcode; the operation still requires a registered ZCRX interface queue. zcrxIfqIdx is the queue index returned by RegisterZCRXIfq. ReceiveZeroCopy always enables IORING_RECV_MULTISHOT; WithIOPrio may additionally request IORING_RECVSEND_POLL_FIRST.
func (*Uring) RecvMsg ¶
func (ur *Uring) RecvMsg(sqeCtx SQEContext, pollFD PollFd, msg *Msghdr, options ...OpOptionFunc) error
RecvMsg receives a message through the caller-owned message header. Keep the header and its buffers valid at stable addresses through completion. On success, msg.Flags reports payload truncation (MSG_TRUNC) and control-data truncation (MSG_CTRUNC). Namelen can exceed the supplied address capacity. Restore Namelen and Controllen to the offered sizes before reusing the header.
func (*Uring) RegisterBufRingIncremental ¶
func (ur *Uring) RegisterBufRingIncremental(entries int, groupID uint16) (*BufferRing, error)
RegisterBufRingIncremental registers a buffer ring in incremental consumption mode. In this mode, buffers can be partially consumed across multiple completions. IORING_CQE_F_BUF_MORE reports that the selected buffer remains kernel-owned. entries follows the same range and rounding contract as RegisterBufRingMMAP. The returned BufferRing is initialized and empty; populate it with Add and publish staged buffers with Advance before submitting buffer-select I/O.
func (*Uring) RegisterBufRingMMAP ¶
func (ur *Uring) RegisterBufRingMMAP(entries int, groupID uint16) (*BufferRing, error)
RegisterBufRingMMAP registers a buffer ring with kernel-allocated memory. The kernel allocates the ring memory and the application uses mmap to access it. entries must be between 1 and 32768; non-power-of-two values round up. The returned BufferRing is initialized and empty; populate it with Add and publish staged buffers with Advance.
func (*Uring) RegisterBufRingWithFlags ¶
func (ur *Uring) RegisterBufRingWithFlags(entries int, groupID uint16, flags uint16) (*BufferRing, error)
RegisterBufRingWithFlags registers a buffer ring with specified flags. Flags can be combined: IOU_PBUF_RING_MMAP | IOU_PBUF_RING_INC entries must be between 1 and 32768; non-power-of-two values round up. The returned BufferRing is initialized and empty; populate it with Add and publish staged buffers with Advance.
func (*Uring) RegisterFiles ¶
RegisterFiles registers 1 to 2^32-1 process fds for IOSQE_FIXED_FILE. Use -1 for an empty slot. The slice can be reused on return. An existing table yields ErrExists until Uring.UnregisterFiles succeeds.
A fixed read or poll looks up a zero-based slot in the ring's table, saving a process-fd lookup. A linked request can reach that slot after SQ consumption.
func (*Uring) RegisterFilesSparse ¶
RegisterFilesSparse registers a table of count empty file slots. Use Uring.RegisterFilesUpdate to populate slots by index.
func (*Uring) RegisterFilesUpdate ¶
RegisterFilesUpdate updates registered files at the specified offset and returns the number of entries processed by the kernel. Use -1 to clear a slot, or a valid fd to set it. fds must have between 1 and 2^32-1 entries. The update range must fit within the registered file table. The call is synchronous. fds may be reused after it returns. Linux can return a positive prefix count with a nil error. Full completion requires updated == len(fds). If Linux clears a slot and encounters EBADF or ENOMEM acquiring the replacement, that slot stays empty even when updated is zero. Values below -1, including IORING_REGISTER_FILES_SKIP, yield ErrInvalidParam.
For an asynchronous update, use Uring.FilesUpdate and retain fds through its completion.
func (*Uring) RegisterMemRegion ¶
func (ur *Uring) RegisterMemRegion(region *RegionDesc, flags uint64) error
RegisterMemRegion registers a memory region with the io_uring ring. The kernel reads and updates region during this call. Caller-provided backing memory must remain reachable and address-stable until ring teardown. With IORING_MEM_REGION_REG_WAIT_ARG, call this before Uring.Start. Requires kernel 6.13+.
func (*Uring) RegisterNAPI ¶
RegisterNAPI enables NAPI busy polling for network operations. NAPI (New API) enables kernel-side batched network packet processing.
Parameters:
- busyPollTimeout: timeout in microseconds for busy polling
- preferBusyPoll: if true, prefer busy poll over sleeping
- strategy: IO_URING_NAPI_TRACKING_* strategy
Requires kernel 6.9+.
func (*Uring) RegisterZCRXIfq ¶
func (ur *Uring) RegisterZCRXIfq(ifIdx, ifRxq uint32, rqEntries uint32, area *ZCRXAreaReg, region *RegionDesc, rxBufLen uint32) (ZCRXIfqRegistration, error)
RegisterZCRXIfq registers a zero-copy receive interface queue. region must describe the refill-ring memory (IORING_MEM_REGION_TYPE_USER). The kernel reads and updates area and region during this call; their backing memory must remain reachable and address-stable through all kernel use. rqEntries is the requested refill queue size; the returned RqEntries is the effective kernel value. rxBufLen is the desired receive buffer chunk size; zero requests the system page size. A nonzero rxBufLen must be a power of two no smaller than the system page size and requires ZCRX_FEATURE_RX_PAGE_SIZE. The method queries that capability before registration and does not silently fall back to a zero request. Requires the Linux 6.18+ baseline and ZCRX-capable network hardware; nonzero rxBufLen requires the Linux 7.0 capability or a backport.
func (*Uring) RegisteredBuffer ¶
RegisteredBuffer returns the registered buffer at the given index. Returns nil if the index is out of range. The returned slice shares memory with the kernel; writes are visible to zero-copy operations using the same buffer index.
func (*Uring) RegisteredBufferCount ¶
RegisteredBufferCount returns the number of registered buffers.
func (*Uring) RegisteredFileCount ¶
RegisteredFileCount returns the table size established by Uring.RegisterFiles or Uring.RegisterFilesSparse, including empty slots. It returns zero when the ring has no such table.
func (*Uring) RenameAt ¶
func (ur *Uring) RenameAt(sqeCtx SQEContext, oldPath, newPath string, flags uint32, options ...OpOptionFunc) error
RenameAt renames a file at a path.
func (*Uring) ResizeRings ¶
ResizeRings resizes the SQ and CQ rings of this io_uring instance. Pending submissions and completions are preserved. SQE/CQE entry widths and context-pool capacities are unchanged. The caller must serialize resize with submissions, Wait, WaitDirect, WaitExtended, and Stop.
Requirements:
- MultiIssuers and HybridPolling must both be false to retain IORING_SETUP_DEFER_TASKRUN
- The caller must remain locked to one OS thread from before Start through Stop
- The ring must not be in CQ overflow condition
Parameters:
- newSQSize: New SQ ring size (0 keeps the current SQ size)
- newCQSize: New CQ ring size (0 defaults to twice the resulting SQ size)
Nonzero sizes are rounded up to powers of two and clamped to kernel limits. The resulting CQ size must be at least the resulting SQ size. With IndirectSubmissionQueue, changing CQ capacity may temporarily use an additional ring descriptor. If remapping fails after the kernel commits the resize, the ring is closed. Supported on Linux 6.18+.
func (*Uring) RingFD ¶
RingFD returns the io_uring file descriptor. Required for cross-ring operations via IORING_OP_MSG_RING.
func (*Uring) SCTP4Socket ¶
func (ur *Uring) SCTP4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
SCTP4Socket creates an SCTP IPv4 socket.
func (*Uring) SCTP4SocketDirect ¶
func (ur *Uring) SCTP4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
SCTP4SocketDirect creates an SCTP IPv4 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) SCTP6Socket ¶
func (ur *Uring) SCTP6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
SCTP6Socket creates an SCTP IPv6 socket.
func (*Uring) SCTP6SocketDirect ¶
func (ur *Uring) SCTP6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
SCTP6SocketDirect creates an SCTP IPv6 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) SQAvailable ¶
SQAvailable returns the number of SQEs available for submission. Caller-side runtime code can use this for admission control and backpressure. On single-issuer rings it is not safe for concurrent use with ResizeRings; caller must serialize those operations.
func (*Uring) Send ¶
func (ur *Uring) Send(sqeCtx SQEContext, pollFD PollFd, p []byte, options ...OpOptionFunc) error
Send writes data to a socket. Caller must keep p valid until the operation completes. WithOffset without WithN sends the remaining payload range.
func (*Uring) SendFD ¶
func (ur *Uring) SendFD(sqeCtx SQEContext, fd iofd.FD, p []byte, options ...OpOptionFunc) error
SendFD writes data using an iofd.FD value instead of a PollFd interface. The fd value is encoded verbatim; when sqeCtx carries IOSQE_FIXED_FILE, it denotes a registered-file index. Caller must keep p valid until the operation completes. WithOffset without WithN sends the remaining payload range.
func (*Uring) SendMsg ¶
func (ur *Uring) SendMsg(sqeCtx SQEContext, pollFD PollFd, buffers [][]byte, oob []byte, to Addr, options ...OpOptionFunc) error
SendMsg sends a message with control data. Caller must keep buffers and oob valid until the operation completes.
func (*Uring) SendMsgHeader ¶
func (ur *Uring) SendMsgHeader(sqeCtx SQEContext, fd iofd.FD, msg *Msghdr, options ...OpOptionFunc) error
SendMsgHeader submits an ordinary send through a caller-prepared message header. A nil return admits one request; its CQE reports the local byte count or error, including zero for an empty message. iox.ErrWouldBlock admits nothing and leaves msg and the context unchanged, apart from effects of caller option functions.
Caller must supply a valid non-nil msg and keep the header, iovecs, address, control data and payload reachable, address-stable and immutable through target completion. SQ consumption and cancellation completion do not end this borrow. Context identity must also remain valid while cancellation can reference it.
Only Flags and IOPrio options apply, as in SendMsg; IOPrio carries SENDMSG bits. Other option fields and msg.Flags are ignored; SQE message flags are zero. Completion-based reuse requires NotifySucceed and no IOSQE_CQE_SKIP_SUCCESS; callers suppressing success CQEs must establish another terminal release point. With preprovisioned storage and no options, submission does not allocate.
func (*Uring) SetXattr ¶
func (ur *Uring) SetXattr(sqeCtx SQEContext, path, name string, value []byte, flags uint32, options ...OpOptionFunc) error
SetXattr sets an extended attribute on a path. Caller must keep value valid until the operation completes.
func (*Uring) Shutdown ¶
func (ur *Uring) Shutdown(sqeCtx SQEContext, how int, options ...OpOptionFunc) error
Shutdown submits a socket shutdown for the directions selected by how. Use SHUT_RD for reads, SHUT_WR for writes, or SHUT_RDWR for both. The socket descriptor remains open.
func (*Uring) SocketDirect ¶
func (ur *Uring) SocketDirect(sqeCtx SQEContext, domain, typ, proto int, fileIndex uint32, options ...OpOptionFunc) error
SocketDirect creates a socket directly into a registered file table slot. The fileIndex specifies which slot to use (0-based), or use IORING_FILE_INDEX_ALLOC for auto-allocation (the allocated index is returned in CQE res). IORING_FILE_INDEX_ALLOC-1 is not a valid explicit slot because the kernel encoding reserves the next value for auto-allocation. SOCK_CLOEXEC is not supported for direct descriptors. Requires registered files via RegisterFiles or RegisterFilesSparse.
func (*Uring) SocketRaw ¶
func (ur *Uring) SocketRaw(sqeCtx SQEContext, domain, typ, proto int, options ...OpOptionFunc) error
SocketRaw creates a socket using io_uring. The fd field in sqeCtx is ignored (will be set to domain by the kernel). WithFileIndex selects direct-descriptor creation through the same checked zero-based target domain as SocketDirect.
func (*Uring) Splice ¶
func (ur *Uring) Splice(sqeCtx SQEContext, fdIn iofd.FD, n int, options ...OpOptionFunc) error
Splice submits a transfer of up to n bytes between file descriptors.
func (*Uring) Start ¶
Start initializes the io_uring instance with buffers and enables the ring. Context pools are constructed eagerly by New and are intentionally not reset here so any SQEs borrowed before Start remain valid.
With MultiIssuers=false, enabling binds the ring to the calling Linux task. Call runtime.LockOSThread before Start and keep that goroutine locked through Stop, serializing ring operations. Initialization failure closes the ring; calling Start on an already-started ring returns ErrExists without closing it.
func (*Uring) Statx ¶
func (ur *Uring) Statx(sqeCtx SQEContext, path string, flags, mask uint32, stat *Statx, options ...OpOptionFunc) error
Statx gets file status with extended information. Caller must keep stat valid until the operation completes.
func (*Uring) Stop ¶
Stop tears down ring-owned resources and makes the ring permanently unusable. It is idempotent. Caller must drain all in-flight operations, reap outstanding CQEs, and quiesce live subscriptions before calling Stop. Stop is not safe for concurrent use. For a started single-issuer ring, call Stop on the owning goroutine before unlocking its OS thread. An unstarted ring may be stopped by its current owner.
func (*Uring) SubmitAcceptDirectMultishot ¶
func (ur *Uring) SubmitAcceptDirectMultishot(sqeCtx SQEContext, fileIndex uint32, options ...OpOptionFunc) error
SubmitAcceptDirectMultishot submits the raw kernel multishot accept-direct opcode. Each accepted connection uses the next available slot from auto-allocation. fileIndex must be IORING_FILE_INDEX_ALLOC.
func (*Uring) SubmitAcceptMultishot ¶
func (ur *Uring) SubmitAcceptMultishot(sqeCtx SQEContext, options ...OpOptionFunc) error
SubmitAcceptMultishot submits the raw kernel multishot accept opcode. For the managed subscription helper, use Uring.AcceptMultishot.
func (*Uring) SubmitExtended ¶
func (ur *Uring) SubmitExtended(sqeCtx SQEContext) error
SubmitExtended submits an SQE using Extended mode context. The ExtSQE.SQE fields must be populated before calling this method. The io_uring.user_data field is set to the SQEContext (pointer + mode bits).
func (*Uring) SubmitReceiveBundleMultishot ¶
func (ur *Uring) SubmitReceiveBundleMultishot(sqeCtx SQEContext, pollFD PollFd, options ...OpOptionFunc) error
SubmitReceiveBundleMultishot submits the raw kernel multishot bundle receive opcode. Each data CQE describes one bundle; IORING_CQE_F_MORE indicates that further completions may follow for the request. WithReadBufferSize selects the buffer group and the per-completion length cap. A zero size leaves the cap uncapped and selects the default-size buffer group.
func (*Uring) SubmitReceiveMultishot ¶
func (ur *Uring) SubmitReceiveMultishot(sqeCtx SQEContext, pollFD PollFd, b []byte, options ...OpOptionFunc) error
SubmitReceiveMultishot submits the raw kernel multishot receive opcode. For the managed subscription helper, use Uring.ReceiveMultishot. b must be nil because multishot receive requires kernel buffer selection. WithReadBufferSize selects the buffer group and the per-completion length cap. A zero size leaves the cap uncapped and selects the default-size buffer group.
func (*Uring) SubmitReceiveMultishotFD ¶
func (ur *Uring) SubmitReceiveMultishotFD(sqeCtx SQEContext, fd iofd.FD, b []byte, options ...OpOptionFunc) error
SubmitReceiveMultishotFD submits the raw kernel multishot receive opcode using an iofd.FD value instead of a PollFd interface. The fd value is encoded verbatim; when sqeCtx carries IOSQE_FIXED_FILE, it denotes a registered-file index. b must be nil because multishot receive requires kernel buffer selection. WithReadBufferSize selects the buffer group and the per-completion length cap; zero leaves the cap uncapped and selects the default-size buffer group.
func (*Uring) SymlinkAt ¶
func (ur *Uring) SymlinkAt(sqeCtx SQEContext, target, linkpath string, options ...OpOptionFunc) error
SymlinkAt creates a symbolic link.
func (*Uring) Sync ¶
func (ur *Uring) Sync(sqeCtx SQEContext, options ...OpOptionFunc) error
Sync performs a file sync operation.
func (*Uring) SyncFileRange ¶
func (ur *Uring) SyncFileRange(sqeCtx SQEContext, offset int64, length int, syncFlags uint32, options ...OpOptionFunc) error
SyncFileRange syncs a file range to storage.
func (*Uring) TCP4Socket ¶
func (ur *Uring) TCP4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
TCP4Socket creates a TCP IPv4 socket.
func (*Uring) TCP4SocketDirect ¶
func (ur *Uring) TCP4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
TCP4SocketDirect creates a TCP IPv4 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) TCP6Socket ¶
func (ur *Uring) TCP6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
TCP6Socket creates a TCP IPv6 socket.
func (*Uring) TCP6SocketDirect ¶
func (ur *Uring) TCP6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
TCP6SocketDirect creates a TCP IPv6 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) Tee ¶
func (ur *Uring) Tee(sqeCtx SQEContext, fdIn iofd.FD, length int, options ...OpOptionFunc) error
Tee submits a duplication of up to length bytes between pipes.
func (*Uring) Timeout ¶
func (ur *Uring) Timeout(sqeCtx SQEContext, d time.Duration, options ...OpOptionFunc) error
Timeout submits a timer. The default one-shot timer reports zero after one qualifying completion, or -ETIME on expiry. Use WithCount(0) to wait for time alone.
func (*Uring) TimeoutRemove ¶
func (ur *Uring) TimeoutRemove(sqeCtx SQEContext, userData uint64, options ...OpOptionFunc) error
TimeoutRemove removes a timeout request.
func (*Uring) TimeoutUpdate ¶
func (ur *Uring) TimeoutUpdate(sqeCtx SQEContext, userData uint64, d time.Duration, absolute bool, options ...OpOptionFunc) error
TimeoutUpdate modifies an existing timeout request in-place. This atomically updates the timeout's expiration without removing and re-adding.
Parameters:
- sqeCtx: Context for this update operation
- userData: userData of the target timeout to update
- d: New timeout duration
- absolute: If true, d is treated as absolute time; if false, relative from now
func (*Uring) UDP4Socket ¶
func (ur *Uring) UDP4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
UDP4Socket creates a UDP IPv4 socket.
func (*Uring) UDP4SocketDirect ¶
func (ur *Uring) UDP4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
UDP4SocketDirect creates a UDP IPv4 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) UDP6Socket ¶
func (ur *Uring) UDP6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
UDP6Socket creates a UDP IPv6 socket.
func (*Uring) UDP6SocketDirect ¶
func (ur *Uring) UDP6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
UDP6SocketDirect creates a UDP IPv6 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) UDPLITE4Socket ¶
func (ur *Uring) UDPLITE4Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
UDPLITE4Socket creates a UDP-Lite IPv4 socket.
func (*Uring) UDPLITE4SocketDirect ¶
func (ur *Uring) UDPLITE4SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
UDPLITE4SocketDirect creates a UDP-Lite IPv4 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) UDPLITE6Socket ¶
func (ur *Uring) UDPLITE6Socket(sqeCtx SQEContext, options ...OpOptionFunc) error
UDPLITE6Socket creates a UDP-Lite IPv6 socket.
func (*Uring) UDPLITE6SocketDirect ¶
func (ur *Uring) UDPLITE6SocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
UDPLITE6SocketDirect creates a UDP-Lite IPv6 socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) UnixSocket ¶
func (ur *Uring) UnixSocket(sqeCtx SQEContext, options ...OpOptionFunc) error
UnixSocket creates a Unix domain socket.
func (*Uring) UnixSocketDirect ¶
func (ur *Uring) UnixSocketDirect(sqeCtx SQEContext, options ...OpOptionFunc) error
UnixSocketDirect creates a Unix domain socket directly into a registered file table slot. Uses IORING_FILE_INDEX_ALLOC for auto-allocation; returns slot index in CQE res.
func (*Uring) UnlinkAt ¶
func (ur *Uring) UnlinkAt(sqeCtx SQEContext, path string, flags uint32, options ...OpOptionFunc) error
UnlinkAt removes a file or directory.
func (*Uring) UnregisterFiles ¶
UnregisterFiles removes all registered file descriptors. After unregistering, IOSQE_FIXED_FILE flag must not be used until new files are registered.
func (*Uring) UnregisterNAPI ¶
UnregisterNAPI disables NAPI busy polling for this ring.
func (*Uring) UringCmd ¶
func (ur *Uring) UringCmd(sqeCtx SQEContext, cmdOp uint32, cmdData []byte, options ...OpOptionFunc) error
UringCmd submits a generic passthrough command. It encodes cmdData through sqe.addr and sqe.len; use UringCmdInline for drivers that consume sqe.cmd. The submission path retains cmdData until the kernel consumes the SQE. Because the kernel driver may hold cmdData asynchronously until the CQE is posted, caller must keep cmdData valid until the completion is reaped.
func (*Uring) UringCmd128 ¶
func (ur *Uring) UringCmd128(sqeCtx SQEContext, cmdOp uint32, cmdData []byte, options ...OpOptionFunc) error
UringCmd128 submits the separate IORING_OP_URING_CMD128 operation. It provides up to 80 bytes of inline command data inside the SQE and requires a ring created with Options.SQE128; otherwise it returns ErrNotSupported.
func (*Uring) UringCmdInline ¶
func (ur *Uring) UringCmdInline(sqeCtx SQEContext, cmdOp uint32, cmdData []byte, options ...OpOptionFunc) error
UringCmdInline submits an ordinary IORING_OP_URING_CMD operation with up to 80 bytes copied into the SQE command area. It requires a ring created with Options.SQE128; otherwise it returns ErrNotSupported. It does not retain cmdData or require support for the separate IORING_OP_URING_CMD128 opcode.
func (*Uring) Wait ¶
Wait flushes pending submissions and copies the result, flags and raw user_data of each observed CQE. Match incoming message IDs and Linux resource tags before using request accessors. Serialize waits, submission, resize and teardown on a single-issuer ring. On Linux, Wait also drives deferred task work. After a successful enter, a zero-length destination returns (0, nil) and consumes no CQEs. With a nonempty destination, Wait polls an empty Linux IOPOLL ring as needed. If no CQEs are available, Wait returns iox.ErrWouldBlock or, on Linux, ErrCQOverflow if overflow is observed. Inspect every CQE in the returned count.
Here messageID is reserved for incoming messages. Every other CQE belongs to a one-shot read with a context borrowed from ring.ExtSQE and a sequence in Val1.
var cqes [64]CQEView
n, err := ring.Wait(cqes[:])
for i := range n {
cqe := &cqes[i]
if cqe.Context().Raw() == messageID {
handleMessage(cqe.Res)
continue
}
ext := cqe.ExtSQE()
seq := ViewCtx(ext).Vals1().Val1
handleRead(seq, cqe.Res, cqe.Err())
ring.PutExtSQE(ext)
}
if err != nil {
return err
}
func (*Uring) WaitDirect ¶
WaitDirect copies completion events into DirectCQE values, decoding the packed context into the Op, SQEFlags, BufGroup, and FD fields. Use it when every incoming CQE carries a PackDirect context. For rings receiving message IDs or Linux resource tags, use Uring.Wait.
On single-issuer rings it is not safe for concurrent use with submit, Wait, WaitDirect, WaitExtended, Stop, or ResizeRings; caller must serialize those operations. WaitDirect drives pending submissions on Linux. After a successful enter, a zero-length destination returns (0, nil) and consumes no CQEs. With a nonempty destination, polling and empty-CQ errors follow Uring.Wait.
func (*Uring) WaitExtended ¶
WaitExtended copies completion events into ExtCQE values containing the result, CQE flags, and borrowed ExtSQE pointer. Use it when every incoming CQE carries a PackExtended context. For rings receiving message IDs or Linux resource tags, use Uring.Wait.
On single-issuer rings it is not safe for concurrent use with submit, Wait, WaitDirect, WaitExtended, Stop, or ResizeRings; caller must serialize those operations. Caller-side completion code must keep completion referents reachable until CQE reap and serialize retirement. Return Ext to its owning pool only after all request completions, including zero-copy notifications, and borrowed access finish; see Uring.PutExtSQE. WaitExtended drives pending submissions on Linux. After a successful enter, a zero-length destination returns (0, nil) and consumes no CQEs. With a nonempty destination, polling and empty-CQ errors follow Uring.Wait.
func (*Uring) Waitid ¶
func (ur *Uring) Waitid(sqeCtx SQEContext, idtype, id int, infop unsafe.Pointer, options int, opts ...OpOptionFunc) error
Waitid waits for a process to change state asynchronously. idtype specifies which id to wait for (P_ALL, P_PID, P_PGID, P_PIDFD). options must contain at least one of WEXITED, WSTOPPED, or WCONTINUED and may contain only waitid option flags supported by Linux. The siginfo_t result is written to infop. Caller must keep infop valid until the operation completes.
func (*Uring) WithExtSQE ¶
WithExtSQE calls fn with a cleared ExtSQE borrowed from this ring. It returns iox.ErrWouldBlock without calling fn if the pool is exhausted.
If fn returns an error, the context must still be unsubmitted and borrowed; WithExtSQE returns it to the pool before returning that error.
If fn returns nil, fn is responsible for arranging Uring.PutExtSQE exactly once after all request completions and borrowed access finish. Views into the context must not outlive that return. A panic in fn does not return the context.
Example:
err := ring.WithExtSQE(func(ext *uring.ExtSQE) error {
uring.CtxV1Of(ext).Val1 = requestID
ctx := uring.PackExtended(ext).WithFD(fd)
return ring.Read(ctx, buf)
})
func (*Uring) Write ¶
func (ur *Uring) Write(sqeCtx SQEContext, b []byte, options ...OpOptionFunc) error
Write performs a write operation. Caller must keep b valid until the operation completes. WithOffset(-1) uses and advances the file's current position.
func (*Uring) WriteFixed ¶
func (ur *Uring) WriteFixed(sqeCtx SQEContext, bufIndex int, n int, options ...OpOptionFunc) error
WriteFixed submits a write of up to n bytes from a registered buffer. WithOffset(-1) uses and advances the file's current position.
func (*Uring) WriteV ¶
func (ur *Uring) WriteV(sqeCtx SQEContext, iovs [][]byte, options ...OpOptionFunc) error
WriteV submits a vectored write with file offset zero. Only OpOption.Flags is used. Caller must keep iovs and their backing buffers valid until the operation completes.
func (*Uring) WritevFixed ¶
func (ur *Uring) WritevFixed(sqeCtx SQEContext, offset int64, bufIndex int, iovs [][]byte, options ...OpOptionFunc) error
WritevFixed performs a vectored write from ranges of one registered buffer. bufIndex selects the registered buffer, and every iov must be a nonempty subslice of RegisteredBuffer(bufIndex). An offset of -1 uses and advances the file's current position.
func (*Uring) ZCRXExport ¶
ZCRXExport exports a ZCRX instance for cross-ring sharing. The returned descriptor is owned by the caller and can be passed to another process. The caller must close it after all users are drained. Requires kernel 6.19+.
func (*Uring) ZCRXFlushRQ ¶
ZCRXFlushRQ flushes the ZCRX refill queue. This ensures all pending refill queue entries are processed.
type ZCHandler ¶
type ZCHandler interface {
// OnCompleted reports the byte count or negative errno from the data CQE.
OnCompleted(result int32)
// OnNotification ends this send's borrow and repeats its original result.
// Wait for every send borrowing overlapping bytes before rewriting them.
OnNotification(result int32)
}
ZCHandler receives the send result and the release of that send's buffer range.
type ZCRXAreaReg ¶
type ZCRXAreaReg struct {
Addr uint64 // Base address of the area
Len uint64 // Length of the area
RqAreaToken uint64 // Token for RQ area
Flags uint32 // IORING_ZCRX_AREA_* flags
DmabufFD uint32 // DMA buffer file descriptor
Resv [2]uint64 // Reserved
}
ZCRXAreaReg is the area registration for ZCRX. Matches struct io_uring_zcrx_area_reg in Linux.
type ZCRXBuffer ¶
type ZCRXBuffer struct {
// contains filtered or unexported fields
}
ZCRXBuffer wraps a delivered ZCRX receive view. The caller owns the delivered view until Release returns nil. After a successful release, the buffer must not be reused.
func (*ZCRXBuffer) Bytes ¶
func (b *ZCRXBuffer) Bytes() []byte
Bytes returns the received data. Valid until Release returns nil.
func (*ZCRXBuffer) Release ¶
func (b *ZCRXBuffer) Release() error
Release returns the buffer to the kernel via the refill queue. Call on the CQE path. If the refill ring is full, it returns iox.ErrWouldBlock and preserves the buffer for the caller to retry. A zero-length EOF buffer has no refill identity and is released without publishing a refill entry.
type ZCRXConfig ¶
type ZCRXConfig struct {
IfName string // Network interface name (e.g., "eth0"). Required.
RxQueue int // NIC RX queue index. Required.
AreaSize int // Mapped receive area size in bytes.
RqEntries int // Refill queue entries. Must be power of 2.
ChunkSize int // Refill slot size. Must be a power-of-two multiple of page size.
UseHugePages bool // Use huge pages for the area.
}
ZCRXConfig configures a ZCRX receive instance bound to a NIC RX queue.
type ZCRXCqe ¶
type ZCRXCqe struct {
Off uint64 // Offset into the ZCRX area
// contains filtered or unexported fields
}
ZCRXCqe is a zero-copy receive completion queue entry extension. Matches struct io_uring_zcrx_cqe in Linux.
type ZCRXCtrl ¶
type ZCRXCtrl struct {
ZcrxID uint32 // ZCRX instance ID
Op uint32 // ZCRX_CTRL_* operation
Resv [2]uint64 // Reserved
// Union: either ZcExport or ZcFlush based on Op
Data [48]byte // Large enough for both structures
}
ZCRXCtrl is the control structure for ZCRX operations. Matches struct zcrx_ctrl in Linux.
type ZCRXHandler ¶
type ZCRXHandler interface {
// OnData handles received data. Return false for best-effort stop. Zero-length buffers mark TCP EOF and carry no refill identity.
OnData(buf *ZCRXBuffer) bool
// OnError handles a CQE error. Return false for best-effort stop.
OnError(err error) bool
// OnStopped runs once on the CQE path during terminal retirement before state becomes Stopped.
OnStopped()
}
ZCRXHandler handles ZCRX receive events.
type ZCRXIfqReg ¶
type ZCRXIfqReg struct {
IfIdx uint32 // Network interface index
IfRxq uint32 // RX queue index
RqEntries uint32 // Number of refill queue entries
Flags uint32 // ZCRX_REG_* flags
AreaPtr uint64 // Pointer to ZCRXAreaReg
RegionPtr uint64 // Pointer to memory region descriptor
Offsets ZCRXOffsets // Offsets within the ring
ZcrxID uint32 // ZCRX instance ID (output)
RxBufLen uint32 // Chunk size in/out (Linux 7.0+); must be zero before then
Resv [3]uint64 // Reserved
}
ZCRXIfqReg is the interface queue registration for ZCRX. Matches struct io_uring_zcrx_ifq_reg in Linux.
type ZCRXIfqRegistration ¶
type ZCRXIfqRegistration struct {
ID uint32
RqEntries uint32 // Effective refill queue entry count.
Offsets ZCRXOffsets
RxBufLen uint32
}
ZCRXIfqRegistration is the observable result of ZCRX interface-queue registration.
type ZCRXOffsets ¶
type ZCRXOffsets struct {
Head uint32 // Head offset
Tail uint32 // Tail offset
Rqes uint32 // RQE array offset
Resv [2]uint64 // Reserved
// contains filtered or unexported fields
}
ZCRXOffsets describes the layout of a ZCRX refill queue ring. Matches struct io_uring_zcrx_offsets in Linux.
type ZCRXReceiver ¶
type ZCRXReceiver struct {
// contains filtered or unexported fields
}
ZCRXReceiver manages a ZCRX receive lifecycle. External Stop and Close must not race CQE dispatch or terminal retirement. Call Close only after Stopped reports true.
func NewZCRXReceiver ¶
func NewZCRXReceiver(ring *Uring, pool *ContextPools, cfg ZCRXConfig) (*ZCRXReceiver, error)
NewZCRXReceiver creates a ZCRX receiver. The refill queue starts empty; ZCRXBuffer.Release returns delivered buffers to the kernel. Returns ErrNotSupported if ZCRX is unavailable.
func (*ZCRXReceiver) Active ¶
func (r *ZCRXReceiver) Active() bool
Active reports whether the receiver is receiving.
func (*ZCRXReceiver) Close ¶
func (r *ZCRXReceiver) Close() error
Close releases ZCRX resources after the receiver has retired and the owning ring has been stopped. Returns iox.ErrWouldBlock while retirement is still in flight or while the ring still owns the ZCRX IFQ registration. Caller must drain all in-flight operations before calling Close. Close is not safe for concurrent use. Safe to call more than once; subsequent calls return nil.
func (*ZCRXReceiver) Start ¶
func (r *ZCRXReceiver) Start(fd iofd.FD, handler ZCRXHandler) error
Start submits the multishot ZCRX receive. Call at most once. fd must remain valid until terminal retirement.
func (*ZCRXReceiver) Stop ¶
func (r *ZCRXReceiver) Stop() error
Stop requests cancellation of the active multishot receive. Leaves the receiver active if cancel submission fails. Dispatch the cancellation CQE through its extended handler as well as the original receive CQEs. Stopped stays false until both lifetimes end.
func (*ZCRXReceiver) Stopped ¶
func (r *ZCRXReceiver) Stopped() bool
Stopped reports whether terminal retirement is complete. Close still requires the owning ring to have been stopped.
type ZCRXRqe ¶
type ZCRXRqe struct {
Off uint64 // Offset into the ZCRX area
Len uint32 // Length of the buffer
// contains filtered or unexported fields
}
ZCRXRqe is a zero-copy receive refill queue entry. Matches struct io_uring_zcrx_rqe in Linux.
type ZCSubscriber ¶
type ZCSubscriber struct {
// contains filtered or unexported fields
}
ZCSubscriber adapts functions to `ZCHandler`.
func NewZCSubscriber ¶
func NewZCSubscriber() *ZCSubscriber
NewZCSubscriber creates a subscriber with default handlers.
func (*ZCSubscriber) Handler ¶
func (s *ZCSubscriber) Handler() ZCHandler
Handler returns `s` as a `ZCHandler`.
func (*ZCSubscriber) OnCompleted ¶
func (s *ZCSubscriber) OnCompleted(fn func(result int32)) *ZCSubscriber
OnCompleted sets the completed handler.
func (*ZCSubscriber) OnNotification ¶
func (s *ZCSubscriber) OnNotification(fn func(result int32)) *ZCSubscriber
OnNotification sets the notification handler.
type ZCTracker ¶
type ZCTracker struct {
// contains filtered or unexported fields
}
ZCTracker pairs each admitted zero-copy send with its release evidence. Dispatch each CQE once in a serialized completion loop. The tracker calls OnCompleted and then OnNotification once each. Data without MORE triggers both callbacks. Data with MORE requires the matching notification for release, in either arrival order. The tracker then returns the pooled context.
func NewZCTracker ¶
func NewZCTracker(ring *Uring, pool *ContextPools) *ZCTracker
NewZCTracker creates a tracker for managing zero-copy sends.
func (*ZCTracker) HandleCQE ¶
HandleCQE processes a CQE that may be a zero-copy completion or notification. Returns true if the CQE was handled, false if it's not a ZC tracker CQE.
HandleCQE is for immediate dispatch in the caller's serialized completion loop. Caller-side completion code must keep completion referents reachable until CQE reap and serialize retirement.
func (*ZCTracker) SendZC ¶
func (t *ZCTracker) SendZC(fd iofd.FD, buf []byte, handler ZCHandler, options ...OpOptionFunc) error
SendZC submits a zero-copy send from buf. WithOffset and WithN select a nonempty range. Keep its backing reachable and address-stable, and its bytes unchanged, until this send's OnNotification callback. Keep IORING_SEND_VECTORIZED and IORING_RECVSEND_FIXED_BUF clear in WithIOPrio. Use ZCTracker.SendZCFixed for a registered slot. The tracker requires success CQEs regardless of NotifySucceed and rejects explicit IOSQE_CQE_SKIP_SUCCESS. Pool or SQ exhaustion returns iox.ErrWouldBlock.
func (*ZCTracker) SendZCFixed ¶
func (t *ZCTracker) SendZCFixed(fd iofd.FD, bufIndex int, offset int, length int, handler ZCHandler, options ...OpOptionFunc) error
SendZCFixed submits a zero-copy send from a registered buffer. WithOffset and WithN select bytes within the supplied offset/length range. It sets IORING_RECVSEND_FIXED_BUF. Keep IORING_SEND_VECTORIZED clear in WithIOPrio. The lifetime, completion and admission rules are the same as ZCTracker.SendZC.
Source Files
¶
- budget.go
- buffer_rings.go
- buffers.go
- bundle_iter.go
- cancel_linux.go
- cqe_direct_linux.go
- cqe_direct_unix.go
- cqe_extended_linux.go
- cqe_extended_unix.go
- cqe_flags_unix.go
- cqe_view_unix.go
- ctx_linux.go
- ctx_pool_linux.go
- ctx_pool_unix.go
- ctx_scope.go
- ctx_types.go
- ctx_unix.go
- ctx_view.go
- doc.go
- endian_le.go
- entries_unix.go
- errors.go
- ext_anchors.go
- handler_noop.go
- handler_subscriber.go
- incremental_linux.go
- interface_internal.go
- interface_linux.go
- io_uring_linux.go
- listener.go
- multicast_unix.go
- multishot.go
- op_option.go
- operations_linux.go
- options_unix.go
- prlimit_linux_amd64.go
- provided_buffers.go
- provided_buffers_config.go
- sqe_view_unix.go
- submit_keepalive.go
- submit_state.go
- types.go
- types_unix.go
- zc_tracker.go
- zcrx_receiver_linux.go