title: tickit_window(7)

text:
# tickit_window(7)

## NAME
TickitWindow - a window for drawing operations and input

## SYNOPSIS

```
#include <tickit.h>

typedef struct TickitWindow;
```

## DESCRIPTION
A TickitWindow instance represents a rectangular region of the screen. Windows are constructed as sub-divisions of existing windows, ultimately coming from a special "root window" is that represents the entire area of the terminal. Each window allows drawing to its region of the screen by responding to an event that signifies damage to that area that needs to be repainted, and has other events that represent user input.

A window occupies a given size and position within its parent (apart from the root window, which occupies the entire terminal). Conceptually a window can be placed outside of the bounds of its parent, though any drawing output is clipped to the parent (and its parent, hierarchially, all the way to the root). A window may be hidden, at which point none of its output affects the screen, nor will it receive input events.

The child windows of a given parent form an ordered list, the order of which can be modified. Drawing operations on a window only take effect if there are no higher siblings that would obscure it. The stacking order also affects the way that windows receive mouse events, with higher-level window shielding lower ones from receiving an event at a given cell.

Each window tracks whether a single child window has the "input focus"; this is the child window that will be informed of keyboard input events. The innermost window following the focus chain gets the first chance to react to the event, followed by successively outer ones if it remains unhandled.

Newly-exposed areas of windows are tracked by the root window, ready to be rendered by expose events. The root window itself will expose new areas caused by terminal resizes, and the entire root window is entirely exposed initially, to allow the application to run its initial rendering on startup. Each window stores a TickitPen instance that can be used to apply a default style to any rendering operations that take place within it or its children.

## FUNCTIONS
A new top-level TickitWindow instance to represent the entire terminal is created by calling tickit_get_rootwin(3) on the toplevel Tickit instance, further sub-divided into regions using tickit_window_new(3). A window instance stores a reference count to make it easier for applications to manage the lifetime of windows. A new window starts with a count of one, and it can be adjusted using tickit_window_ref(3) and tickit_window_unref(3). When the count reaches zero the instance is destroyed. A window can also be immediately removed from its parent with tickit_window_close(3).

The ancestry of a window can be queried using tickit_window_parent(3) and tickit_window_root(3). The stored child windows can be queried by using tickit_window_children(3) and tickit_window_get_children(3). The backing terminal can be queried with tickit_window_get_term(3).

The stacking order of a window among its siblings can be controlled using tickit_window_raise(3), tickit_window_raise_to_front(3), tickit_window_lower(3) and tickit_window_lower_to_back(3). Its visibility can be controlled using tickit_window_show(3) and tickit_window_hide(3), and queried using tickit_window_is_visible(3).

The position of a window within its parent can be queried using tickit_window_get_geometry(3) and within the terminal as a whole using tickit_window_get_abs_geometry(3). It can be resized using tickit_window_resize(3), moved using tickit_window_reposition(3), or both using tickit_window_set_geometry(3).

A window can be given the input focus using tickit_window_take_focus(3), and can be queried to see if it has the focus using tickit_window_is_focused(3). Windows normally only invoke focus events about themselves, but can be made to invoke events about children windows as well by using tickit_window_set_focus_child_notify(3). When a window has the input focus, the properties of the terminal cursor can be set using tickit_window_set_cursor_position(3), tickit_window_set_cursor_visible(3) and tickit_window_set_cursor_shape(3).

The TickitPen instance associated with each window for drawing purposes can be obtained using tickit_window_get_pen(3), and replaced using tickit_window_set_pen(3). This pen is used during expose events, which can be requested using tickit_window_expose(3). Pending expose events and other activity are performed by calling tickit_window_flush(3) on the root window instance.

While most drawing operations are performed in a deferred manner using expose events, scrolling of the terminal content can be directly requested using tickit_window_scrollrect(3), tickit_window_scroll(3) or tickit_window_scroll_with_children(3).

## EVENTS
A window instance stores a list of event handlers. Each event handler is associated with one event type and stores a function pointer, and an arbitrary pointer containing user data. Event handlers may be installed using tickit_window_bind_event(3) and removed using tickit_window_unbind_event_id(3).

The event types recognised are:

TICKIT_WINDOW_ON_DESTROY

The window instance is being destroyed.

TICKIT_WINDOW_ON_KEY

A key has been pressed on the keyboard while this window has input focus (or is set to steal input). info will point to a structure defined the same as the TICKIT_EV_KEY event described in tickit_term(7).

TICKIT_WINDOW_ON_MOUSE

A mouse button has been pressed or released, the mouse cursor moved while dragging a button, or the wheel has been scrolled while the cursor is within the bounds of this window (or the window is set to steal input), or certain kinds of mouse dragging behaviour have happened. info will point to a structure defined the same as the TICKIT_EV_MOUSE event described in tickit_term(7), except that the position given by the line and col fields will be relative to the window, rather than the terminal as a whole.

In addition to the basic mouse events found at the terminal layer, there are a few additional kinds of events that occur during mouse dragging. These give information about mouse drag motions within a window or between different windows.

TICKIT_MOUSEEV_DRAG_START

A dragging motion has started. This event is delivered just before the TICKIT_MOUSEEV_DRAG event, and gives the original position of the mouse before it started dragging (i.e. the position of the press event).

TICKIT_MOUSEEV_DRAG_OUTSIDE

A dragging motion that was started within this window has now moved outside it. In this case, the position given by the event will be somewhere outside the bounds of the window it is delivered to. This event is delivered directly to the source window; i.e. the window that handled the TICKIT_MOUSEEV_DRAG_START event.

TICKIT_MOUSEEV_DRAG_DROP

A dragging motion has stopped by the mouse button being released. This event is delivered normally at the position of the mouse cursor.

TICKIT_MOUSEEV_DRAG_STOP

A dragging motion has stopped by the mouse button being released. This event is delivered directly to the source window; i.e. the window that handled the TICKIT_MOUSEEV_DRAG_START event. If that is a different window than the one that received the TICKIT_MOUSEEV_DRAG_STOP event then the position may be outside the bounds of the window.

TICKIT_WINDOW_ON_GEOMCHANGE

At least one of the fields of the window geometry have been changed, meaning it now occupies a different area of the screen. info will point to a structure defined as:

```
typedef struct {
    TickitRect rect;
    TickitRect oldrect;
} TickitGeomchangeEventInfo;

```

rect gives the new geometry of the window relative to its parent, and oldrect gives the previous geometry.

TICKIT_WINDOW_ON_EXPOSE

An area of the window needs to be re-rendered because it has now been freshly exposed; either because of stacking or visibility changes of this or sibling windows, a cascaded expose event on its parent, or due to a call to tickit_window_expose(). info will point to a structure defined as:

```
typedef struct {
    TickitRect rect;
    TickitRenderBuffer *rb;
} TickitExposeEventInfo;

```

rect gives the region of the window that needs to be redrawn. This will always be inside the window's bounds. If multiple pending regions need to be exposed, they are output in non-overlapping segments. The handling function or functions should then use the TickitRenderBuffer instance given by the rb field to draw the required contents of the window to. This instance will already be set up with the appropriate drawing pen, clipping rectangle and hole regions to account for the window hierarchy.

TICKIT_WINDOW_ON_FOCUS

This window has either gained or lost the input focus, or a child of it has an this window is set to also notify on that case by using tickit_window_set_focus_child_notify(). info will point to a structure defined as:

```
typedef struct {
    TickitFocusEventType type;
    TickitWindow *win;
} TickitFocusEventInfo;

```

type takes onw of the values TICKIT_FOCUSEV_IN or TICKIT_FOCUSEV_OUT. win will normally be the window that is invoking the event, except for the case of notifications about child windows, where it will indicate which child has changed focus. When a focus change happens, the window losing focus receives its TICKIT_FOCUSEV_OUT event before the window gaining it receives its TICKIT_FOCUSEV_IN.

## CONTROLS
A window instance has a number of runtime-configuration control options that affect its behaviour. These can be set using tickit_window_setctl_int(3), and queried using tickit_window_getctl_int(3). The individual controls have human-readable string names that can be obtained by tickit_windowctl_name(3) and searched by name using tickit_windowctl_lookup(3). The type of a control option can be queried using tickit_windowctl_type(3).

The options are given in an enumeration called TickitWindowCtl. The following control values are recognised:

TICKIT_WINCTL_CURSORBLINK (bool)

The value is a boolean indicating whether the terminal text cursor should blink while this window has the input focus.

TICKIT_WINCTL_CURSORSHAPE (int)

The value is an integer from the TickitCursorShape enumeration indicating what shape the terminal's text cursor should be while this window has the input focus. Values are:

TICKIT_CURSORSHAPE_BLOCK

A solid block filling the entire cell.

TICKIT_CURSORSHAPE_UNDER

An underline below the character.

TICKIT_CURSORSHAPE_LEFT_BAR

A vertical bar to the left of the character.

TICKIT_WINCTL_CURSORVIS (bool)

The value is a boolean indicating whether the terminal text cursor should be visible while this window has the input focus.

TICKIT_WINCTL_FOCUS_CHILD_NOTIFY (bool)

The value is a boolean indicating whether the window will receive TICKIT_EV_FOCUS events when its child windows change focus states (when true), or whether the only focus events it will receive are ones relating to itself directly (when false).

TICKIT_WINCTL_STEAL_INPUT (bool)

The value is a boolean indicating whether the window will receive all key events on its parent first, while it is the front-most child of its parent, even before the sibling that actually has input focus receives them. Additionally, the window will receive all mouse events, even those outside of its geometry. This option is useful when implementing popup windows such as menu bars.

## SEE ALSO
tickit(7), tickit_term(7), tickit_renderbuffer(7), tickit_rect(7)


title: tss2-tcti-cmd(7)

summary: TPM2 Sub-process Command TCTI library

text:
# tss2-tcti-cmd(7)

## NAME
tcti-cmd - TPM2 Sub-process Command TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with a sub-process.

## DESCRIPTION
tcti-cmd is a library that abstracts the details of direct communication with the interface and protocol exposed by a sub-process that can receive and transmit raw TPM2 command and response buffers. The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification” specification.

## EXAMPLES
For example, if you wanted to use the tpm2_send(1) command as the sub-process to send data to and from the TPM, one could do so like this:

```
tpm2_getrandom -T "cmd:tpm2_send -s" --hex 4
```

A more useful example would be connecting to a remote machine using ssh and interacting with the remote machine's TPM as if it were local. This uses tpm2_send(1) on a remote machine and uses ssh as the sub-process to create the tunnel to the remote machine. If encrypted sessions are used, the remote machine is blinded to the TPM data and cannot interpose on that traffic.

```
tpm2_getrandom -T "cmd:ssh remotehost tpm2_send" -s --hex 4
```

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.

branch: sisyphus


title: tss2-tcti-device(7)

summary: device driver TCTI library

text:
# tss2-tcti-device(7)

## NAME
tcti-device - device driver TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with the TPM device driver.

## DESCRIPTION
tcti-device is a library that abstracts the details of direct communication with the device node exposed by the Linux kernel driver (typically /dev/tpm0). The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification” specification.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-i2c-ftdi(7)

summary: USB to I2C-based TPM TCTI library

text:
# tss2-tcti-i2c-ftdi(7)

## NAME
tcti-i2c-ftdi - USB to I2C-based TPM TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with a I2C-based TPM over the FTDI MPSSE USB to I2C bridge.

## DESCRIPTION
tcti-i2c-ftdi is a library that abstracts the details of communication with a I2C-based TPM over the FTDI MPSSE USB to I2C bridge. The interface exposed by this library is defined in the “TSS System Level API and and TPM Command Transmission Interface Specification” specification.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-i2c-helper(7)

summary: device driver TCTI library

text:
# tss2-tcti-i2c-helper(7)

## NAME
tcti-i2c-helper - device driver TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for communication via I2C. TPM device driver.

## DESCRIPTION
tcti-i2c-helper is a library that abstracts the details of communication with a TPM via I2C protocol. It uses user supplied methods for I2C and timing operations in order to be platform independent. These methods are supplied to `Tss2_Tcti_I2c_Helper_Init` via the `TSS2_TCTI_I2C_HELPER_PLATFORM` struct.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-mssim(7)

summary: TPM simulator TCTI library

text:
# tss2-tcti-mssim(7)

## NAME
tcti-socket - TPM simulator TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with the Microsoft TPM2 simulator.

## DESCRIPTION
tcti-socket is a library that abstracts the details of direct communication with the interface and protocol exposed by the daemon hosting the TPM2 reference implementation. The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification” specification.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-spi-ftdi(7)

summary: USB to SPI-based TPM TCTI library

text:
# tss2-tcti-spi-ftdi(7)

## NAME
tcti-spi-ftdi - USB to SPI-based TPM TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with a SPI-based TPM over the FTDI MPSSE USB to SPI bridge.

## DESCRIPTION
tcti-spi-ftdi is a library that abstracts the details of communication with a SPI-based TPM over the FTDI MPSSE USB to SPI bridge. The interface exposed by this library is defined in the “TSS System Level API and and TPM Command Transmission Interface Specification” specification.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-spi-helper(7)

summary: device driver TCTI library

text:
# tss2-tcti-spi-helper(7)

## NAME
tcti-spi-helper - device driver TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for communication via SPI. TPM device driver.

## DESCRIPTION
tcti-spi-helper is a library that abstracts the details of communication with a TPM via SPI protocol. It uses user supplied methods for SPI and timing operations in order to be platform independent. These methods are supplied to `Tss2_Tcti_Spi_Init` via the `TSS2_TCTI_SPI_PLATFORM` struct.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-spi-ltt2go(7)

summary: LetsTrust-TPM2Go USB TPM TCTI library

text:
# tss2-tcti-spi-ltt2go(7)

## NAME
tcti-spi-ltt2go - LetsTrust-TPM2Go USB TPM TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with the LetsTrust-TPM2Go USB TPM.

## DESCRIPTION
tcti-spi-ltt2go is a library that abstracts the details of communication with the LetsTrust-TPM2Go USB TPM. The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification” specification.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-spidev(7)

text:
# tss2-tcti-spidev(7)

## NAME
tcti-spidev - TCTI library for accessing TPMs via spidev

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with a TPM that is attached to an spidev device node.

## DESCRIPTION
tcti-spidev is a library that abstracts the details of communication with a TPM that is attached to an spidev device node.. The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification” specification. The configuration of this TCTI takes the filepath to the device node (Default: /dev/spidev0.1).

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tcti-swtpm(7)

summary: TPM simulator TCTI library

text:
# tss2-tcti-swtpm(7)

## NAME
tcti-swtpm - TPM simulator TCTI library

## SYNOPSIS
A TPM Command Transmission Interface (TCTI) module for interaction with the TPM2 software simulator.

## DESCRIPTION
tcti-swtpm is a library that abstracts the details of direct communication with the interface and protocol exposed by the daemon hosting the TPM2 reference implementation. The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification” specification.

## NOTES
It is best not to use the CUSE interface when setting up swtpm, but rather to use the vtpm module proxy:

```
modprobe tpm_vtpm_proxy
swtpm chardev --vtpm-proxy --tpmstate dir=... --tpm2 ...
```

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


title: tss2-tctildr(7)

text:
# tss2-tctildr(7)

## NAME
tss2-tctildr - Simplifiy management of TCTI instance lifecycle.

## SYNOPSIS
This library simplifies the instantiation and finalization of TCTI instances.

## DESCRIPTION
The TCTI dynamic loading and initialization protocol requires a lot of boilerplate code. To reduce duplication the tss2-tctildr library adds the Tss2_TctiLdr_Initialize(), Tss2_TctiLdr_Initialize_Ex(), and Tss2_TctiLdr_Finalize() functions to abstract away the machinery required to load, initialize, and finalize a TCTI context.

To assist in the discovery of TCTIs this library provides the Tss2_TctiLdr_GetInfo() function. This function, paired with a ‘free’ function to free the memory allocated by ‘GetInfo’, provides a simple query interface for discovery of the available and default TCTIs available to the tss2-tctildr implementation

The interface exposed by this library is defined in the “TSS System Level API and TPM Command Transmission Interface Specification”.

## AUTHOR
TPM2 Software Project <https://github.com/tpm2-software/tpm2-tss>

## SEE ALSO
Tss2_Tcti_Device_Init(3), Tss2_Tcti_Socket_Init(3), Tss2_TctiLdr_Initialize(3), Tss2_TctiLdr_Finalize(3), tcti-device(7), tcti-socket(7), tcti-tabrmd(7), tpm2-abrmd(8)

## COLOPHON
This page is part of release 4.1.3 of Open Source implementation of the TCG TPM2 Software Stack (TSS2). A description of the project, information about reporting bugs, and the latest version of this page can be found at https://github.com/tpm2-software/tpm2-tss/.


package: liburing-devel

title: io_uring(7)

summary: Asynchronous I/O facility

text:
# io_uring(7)

## NAME
io_uring - Asynchronous I/O facility

## SYNOPSIS

```
#include <linux/io_uring.h>
```

## DESCRIPTION
io_uring is a Linux-specific API for asynchronous I/O. It allows the user to submit one or more I/O requests, which are processed asynchronously without blocking the calling process. io_uring gets its name from ring buffers which are shared between user space and kernel space. This arrangement allows for efficient I/O, while avoiding the overhead of copying buffers between them, where possible. This interface makes io_uring different from other UNIX I/O APIs, wherein, rather than just communicate between kernel and user space with system calls, ring buffers are used as the main mode of communication. This arrangement has various performance benefits which are discussed in a separate section below. This man page uses the terms shared buffers, shared ring buffers and queues interchangeably.

The general programming model you need to follow for io_uring is outlined below

- Set up shared buffers with io_uring_setup(2) and mmap(2), mapping into user space shared buffers for the submission queue (SQ) and the completion queue (CQ). You place I/O requests you want to make on the SQ, while the kernel places the results of those operations on the CQ.

- For every I/O request you need to make (like to read a file, write a file, accept a socket connection, etc), you create a submission queue entry, or SQE, describe the I/O operation you need to get done and add it to the tail of the submission queue (SQ). Each I/O operation is, in essence, the equivalent of a system call you would have made otherwise, if you were not using io_uring. For instance, a SQE with the opcode set to IORING_OP_READ will request a read operation to be issued that is similar to the read(2) system call. Refer to the opcode documentation in io_uring_enter(2) for all supported opcodes and their properties. You can add more than one SQE to the queue depending on the number of operations you want to request.

- After you add one or more SQEs, you need to call io_uring_enter(2) to tell the kernel to dequeue your I/O requests off the SQ and begin processing them.

- For each SQE you submit, once it is done processing the request, the kernel places a completion queue event or CQE at the tail of the completion queue or CQ. The kernel places exactly one matching CQE in the CQ for every SQE you submit on the SQ. After you retrieve a CQE, minimally, you might be interested in checking the res field of the CQE structure, which corresponds to the return value of the system call's equivalent, had you used it directly without using io_uring. Given that io_uring is an async interface, errno is never used for passing back error information. Instead, res will contain what the equivalent system call would have returned in case of success, and in case of error res will contain -errno. For example, if the normal read system call would have returned -1 and set errno to EINVAL, then res would contain -EINVAL. If the normal system call would have returned a read size of 1024, then res would contain 1024.

- Optionally, io_uring_enter(2) can also wait for a specified number of requests to be processed by the kernel before it returns. If you specified a certain number of completions to wait for, the kernel would have placed at least those many number of CQEs on the CQ, which you can then readily read, right after the return from io_uring_enter(2).

- It is important to remember that I/O requests submitted to the kernel can complete in any order. It is not necessary for the kernel to process one request after another, in the order you placed them. Given that the interface is a ring, the requests are attempted in order, however that doesn't imply any sort of ordering on their execution or completion. When more than one request is in flight, it is not possible to determine which one will execute or complete first. When you dequeue CQEs off the CQ, you should always check which submitted request it corresponds to. The most common method for doing so is utilizing the user_data field in the request, which is passed back on the completion side.

- Concretely, for operations where strict ordering is required, such as for sends and receives on a stream-oriented TCP socket, it is generally unsafe to have more than one outstanding send, or more than one outstanding receive (the two directions are independent) on a given socket at a time, as the kernel may reorder their execution if poll arming or other background kernel activities are involved. However, io_uring provides various facilities to enable applications to efficiently pipeline their operations safely. If the requests are submitted in a single batch, the application may use IOSQE_IO_LINK to enforce an execution order in the kernel. Otherwise, io_uring provides advanced features like multi shot and send/receive bundles to allow applications to provide more data in fewer, more efficient trips to the kernel. Even if these features are used, applications must still ensure they do not overlap different sends or different receives on a given file.

Adding to and reading from the queues:

- You add SQEs to the tail of the SQ. The kernel reads SQEs off the head of the queue.

- The kernel adds CQEs to the tail of the CQ. You read CQEs off the head of the queue.

It should be noted that depending on the configuration io_uring's behavior can deviate from the behavior outlined above, like not posting a CQE for every SQE when setting IOSQE_CQE_SKIP_SUCCESS in the SQE or posting multiple CQEs for a single SQE for multi shot operations or requiring an io_uring_enter(2) syscall to make the kernel begin processing newly added SQEs when using submission queue polling.

### Submission queue polling
One of the goals of io_uring is to provide a means for efficient I/O. To this end, io_uring supports a polling mode that lets you avoid the call to io_uring_enter(2), which you use to inform the kernel that you have queued SQEs on to the SQ. With SQ Polling, io_uring starts a kernel thread that polls the submission queue for any I/O requests you submit by adding SQEs. With SQ Polling enabled, there is no need for you to call io_uring_enter(2), letting you avoid the overhead of system calls. A designated kernel thread dequeues SQEs off the SQ as you add them and dispatches them for asynchronous processing.

### Setting up io_uring
The main steps in setting up io_uring consist of mapping in the shared buffers with mmap(2) calls. In the example program included in this man page, the function app_setup_uring() sets up io_uring with a QUEUE_DEPTH deep submission queue. Pay attention to the 2 mmap(2) calls that set up the shared submission and completion queues. If your kernel is older than version 5.4, three mmap(2) calls are required.

### Submitting I/O requests
The process of submitting a request consists of describing the I/O operation you need to get done using an io_uring_sqe structure instance. These details describe the equivalent system call and its parameters. Because the range of I/O operations Linux supports are very varied and the io_uring_sqe structure needs to be able to describe them, it has several fields, some packed into unions for space efficiency. Here is a simplified version of struct io_uring_sqe with some of the most often used fields:

```
struct io_uring_sqe {

        __u8    opcode;         /* type of operation for this sqe */

        __s32   fd;             /* file descriptor to do IO on */

        __u64   off;            /* offset into file */

        __u64   addr;           /* pointer to buffer or iovecs */

        __u32   len;            /* buffer size or number of iovecs */

        __u64   user_data;      /* data to be passed back at completion time */

        __u8    flags;          /* IOSQE_ flags */

        ...
};
```

Here is struct io_uring_sqe in full:

```
struct io_uring_sqe {
	__u8	opcode;		/* type of operation for this sqe */
	__u8	flags;		/* IOSQE_ flags */
	__u16	ioprio;		/* ioprio for the request */
	__s32	fd;		/* file descriptor to do IO on */
	union {
		__u64	off;	/* offset into file */
		__u64	addr2;
		struct {
			__u32	cmd_op;
			__u32	__pad1;
		};
	};
	union {
		__u64	addr;	/* pointer to buffer or iovecs */
		__u64	splice_off_in;
		struct {
			__u32	level;
			__u32	optname;
		};
	};
	__u32	len;		/* buffer size or number of iovecs */
	union {
		__kernel_rwf_t	rw_flags;
		__u32		fsync_flags;
		__u16		poll_events;	/* compatibility */
		__u32		poll32_events;	/* word-reversed for BE */
		__u32		sync_range_flags;
		__u32		msg_flags;
		__u32		timeout_flags;
		__u32		accept_flags;
		__u32		cancel_flags;
		__u32		open_flags;
		__u32		statx_flags;
		__u32		fadvise_advice;
		__u32		splice_flags;
		__u32		rename_flags;
		__u32		unlink_flags;
		__u32		hardlink_flags;
		__u32		xattr_flags;
		__u32		msg_ring_flags;
		__u32		uring_cmd_flags;
		__u32		waitid_flags;
		__u32		futex_flags;
		__u32		install_fd_flags;
		__u32		nop_flags;
	};
	__u64	user_data;	/* data to be passed back at completion time */
	/* pack this to avoid bogus arm OABI complaints */
	union {
		/* index into fixed buffers, if used */
		__u16	buf_index;
		/* for grouped buffer selection */
		__u16	buf_group;
	} __attribute__((packed));
	/* personality to use, if used */
	__u16	personality;
	union {
		__s32	splice_fd_in;
		__u32	file_index;
		__u32	optlen;
		struct {
			__u16	addr_len;
			__u16	__pad3[1];
		};
	};
	union {
		struct {
			__u64	addr3;
			__u64	__pad2[1];
		};
		__u64	optval;
		/*
		 * If the ring is initialized with IORING_SETUP_SQE128, then
		 * this field is used for 80 bytes of arbitrary command data
		 */
		__u8	cmd[0];
	};
};
```

To submit an I/O request to io_uring, you need to acquire a submission queue entry (SQE) from the submission queue (SQ), fill it up with details of the operation you want to submit and call io_uring_enter(2). There are helper functions of the form io_uring_prep_X to enable proper setup of the SQE. If you want to avoid calling io_uring_enter(2), you have the option of setting up Submission Queue Polling.

SQEs are added to the tail of the submission queue. The kernel picks up SQEs off the head of the SQ. The general algorithm to get the next available SQE and update the tail is as follows.

```
struct io_uring_sqe *sqe;
unsigned tail, index;
tail = *sqring->tail;
index = tail & (*sqring->ring_mask);
sqe = &sqring->sqes[index];
/* fill up details about this I/O request */
describe_io(sqe);
/* fill the sqe index into the SQ ring array */
sqring->array[index] = index;
tail++;
atomic_store_explicit(sqring->tail, tail, memory_order_release);
```

To get the index of an entry, the application must mask the current tail index with the size mask of the ring. This holds true for both SQs and CQs. Once the SQE is acquired, the necessary fields are filled in, describing the request. While the CQ ring directly indexes the shared array of CQEs, the submission side has an indirection array between them. The submission side ring buffer is an index into this array, which in turn contains the index into the SQEs.

The following code snippet demonstrates how a read operation, an equivalent of a preadv2(2) system call is described by filling up an SQE with the necessary parameters.

```
struct iovec iovecs[16];

 ...
sqe->opcode = IORING_OP_READV;
sqe->fd = fd;
sqe->addr = (unsigned long) iovecs;
sqe->len = 16;
sqe->off = offset;
sqe->flags = 0;
```

Memory ordering

Modern compilers and CPUs freely reorder reads and writes without affecting the program's outcome to optimize performance. Some aspects of this need to be kept in mind on SMP systems since io_uring involves buffers shared between kernel and user space. These buffers are both visible and modifiable from kernel and user space. As heads and tails belonging to these shared buffers are updated by kernel and user space, changes need to be coherently visible on either side, irrespective of whether a CPU switch took place after the kernel-user mode switch happened. We use memory barriers to enforce this coherency. Being significantly large subjects on their own, memory barriers are out of scope for further discussion on this man page. For more information on modern memory models the reader may refer to the Documentation/memory-barriers.txt in the kernel tree or to the documentation of the formal C11 or kernel memory model.

Letting the kernel know about I/O submissions

Once you place one or more SQEs on to the SQ, you need to let the kernel know that you've done so. You can do this by calling the io_uring_enter(2) system call. This system call is also capable of waiting for a specified count of events to complete. This way, you can be sure to find completion events in the completion queue without having to poll it for events later.

### SQE pointer lifetimes & data stability
Due to the fixed size of the submission queue entry (SQE) some data you provide in order to perform a desired operation will be passed in the form of a pointer rather than value. In this situation, you may free the memory backing the pointer once the succeeding io_uring_enter(2) call has completed; providing it is only required by the operation when submitting.

When IORING_SETUP_SQPOLL is not enabled, this is done when you call io_uring_submit(3) In The event IORING_SETUP_SQPOLL is enabled, you must ensure any provided pointers remain valid until completion.

However, very early kernels (5.4 and earlier) required state to be

stable until the completion occurred regardless. Applications can test for this

behavior by inspecting the IORING_FEAT_SUBMIT_STABLE flag passed back from io_uring_queue_init_params(3).

As an example, the IORING_OP_TIMEOUT operation takes a pointer to a __kernel_timespec struct. This struct is then read by the kernel when you submit the submission queue entries, once submitted, you may free the backing memory of the __kernel_timespec as it will not be read again by the kernel.

It should be noted that this behaviour does not apply to data that is read or written while the operation is inflight. For example, the pointers to a buffer used as part of a IORING_OP_WRITE or IORING_OP_READ operation must remain valid until completion.

### Reading completion events
Similar to the submission queue (SQ), the completion queue (CQ) is a shared buffer between the kernel and user space. Whereas you placed submission queue entries on the tail of the SQ and the kernel read off the head, when it comes to the CQ, the kernel places completion queue events or CQEs on the tail of the CQ and you read off its head.

Submission is flexible (and thus a bit more complicated) since it needs to be able to encode different types of system calls that take various parameters. Completion, on the other hand is simpler since we're looking only for a return value back from the kernel. This is easily understood by looking at the completion queue event structure, struct io_uring_cqe:

```
struct io_uring_cqe {
	__u64	user_data;  /* sqe->data submission passed back */
	__s32	res;        /* result code for this event */
	__u32	flags;
};
```

Here, user_data is custom data that is passed unchanged from submission to completion. That is, from SQEs to CQEs. This field can be used to set context, uniquely identifying submissions that got completed. Given that I/O requests can complete in any order, this field can be used to correlate a submission with a completion. res is the result from the system call that was performed as part of the submission; its return value.

The flags field carries request-specific information. As of the 6.12 kernel, the following flags are defined:

IORING_CQE_F_BUFFER

If set, the upper 16 bits of the flags field carries the buffer ID that was chosen for this request. The request must have been issued with IOSQE_BUFFER_SELECT set, and used with a request type that supports buffer selection. Additionally, buffers must have been provided upfront either via the IORING_OP_PROVIDE_BUFFERS or the IORING_REGISTER_PBUF_RING methods.

IORING_CQE_F_MORE

If set, the application should expect more completions from the request. This is used for requests that can generate multiple completions, such as multi-shot requests, receive, or accept.

IORING_CQE_F_SOCK_NONEMPTY

If set, upon receiving the data from the socket in the current request, the socket still had data left on completion of this request.

IORING_CQE_F_NOTIF

Set for notification CQEs, as seen with the zero-copy networking send and receive support.

IORING_CQE_F_BUF_MORE

If set, the buffer ID set in the completion will get more completions. This means that the provided buffer has been partially consumed and there's more buffer space left, and hence the application should expect more completions with this buffer ID. Each completion will continue where the previous one left off. This can only happen if the provided buffer ring has been setup with IOU_PBUF_RING_INC to allow for incremental / partial consumption of buffers.

IORING_CQE_F_SKIP

If the ring has been configured with IORING_SETUP_CQE_MIXED , then CQEs may be posted which has this flag set. This can happen if the ring is a single 16b CQE entry away from wrapping, but someone needs to post a 32b CQE. As CQEs must be contiguous in memory, a filler/pad CQE needs to get posted to allow posting of the 32b CQE. CQEs with this flag set should simply be skipped and ignored, they serve no other purpose than to fill a gap in the CQ ring.

IORING_CQE_F_32

If the ring has been configured with IORING_SETUP_CQE_MIXED , this flag is set when the CQE is of the 32b type. This tells the application that there's an extra 16b of space in this CQE, and that to get to the next CQE the CQ ring must be advanced by twice as much as for a normal 16b CQE.

The general sequence to read completion events off the completion queue is as follows:

```
unsigned head;
head = *cqring->head;
if (head != atomic_load_acquire(cqring->tail)) {

    struct io_uring_cqe *cqe;

    unsigned index;

    index = head & (cqring->mask);

    cqe = &cqring->cqes[index];

    /* process completed CQE */

    process_cqe(cqe);

    /* CQE consumption complete */

    head++;
}
atomic_store_explicit(cqring->head, head, memory_order_release);
```

It helps to be reminded that the kernel adds CQEs to the tail of the CQ, while you need to dequeue them off the head. To get the index of an entry at the head, the application must mask the current head index with the size mask of the ring. Once the CQE has been consumed or processed, the head needs to be updated to reflect the consumption of the CQE. Attention should be paid to the read and write barriers to ensure successful read and update of the head.

### io_uring performance
Because of the shared ring buffers between kernel and user space, io_uring can be a zero-copy system. Copying buffers to and from becomes necessary when system calls that transfer data between kernel and user space are involved. But since the bulk of the communication in io_uring is via buffers shared between the kernel and user space, this huge performance overhead is completely avoided.

While system calls may not seem like a significant overhead, in high performance applications, making a lot of them will begin to matter. While workarounds the operating system has in place to deal with Spectre and Meltdown are ideally best done away with, unfortunately, some of these workarounds are around the system call interface, making system calls not as cheap as before on affected hardware. While newer hardware should not need these workarounds, hardware with these vulnerabilities can be expected to be in the wild for a long time. While using synchronous programming interfaces or even when using asynchronous programming interfaces under Linux, there is at least one system call involved in the submission of each request. In io_uring, on the other hand, you can batch several requests in one go, simply by queueing up multiple SQEs, each describing an I/O operation you want and make a single call to io_uring_enter(2). This is possible due to io_uring's shared buffers based design.

While this batching in itself can avoid the overhead associated with potentially multiple and frequent system calls, you can reduce even this overhead further with Submission Queue Polling, by having the kernel poll and pick up your SQEs for processing as you add them to the submission queue. This avoids the io_uring_enter(2) call you need to make to tell the kernel to pick SQEs up. For high-performance applications, this means even fewer system call overheads.

## CONFORMING TO
io_uring is Linux-specific.

## EXAMPLES
The following example uses io_uring to copy stdin to stdout. Using shell redirection, you should be able to copy files with this example. Because it uses a queue depth of only one, this example processes I/O requests one after the other. It is purposefully kept this way to aid understanding. In real-world scenarios however, you'll want to have a larger queue depth to parallelize I/O request processing so as to gain the kind of performance benefits io_uring provides with its asynchronous processing of requests.

```
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <linux/fs.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdatomic.h>
#include <errno.h>
#include <linux/io_uring.h>
#define QUEUE_DEPTH 1
#define BLOCK_SZ    1024
/* Macros for barriers needed by io_uring */
#define io_uring_smp_store_release(p, v)            \

    atomic_store_explicit((_Atomic typeof(*(p)) *)(p), (v), \

                  memory_order_release)
#define io_uring_smp_load_acquire(p)                \

    atomic_load_explicit((_Atomic typeof(*(p)) *)(p),   \

                 memory_order_acquire)
int ring_fd;
unsigned *sring_tail, *sring_mask, *sring_array,

            *cring_head, *cring_tail, *cring_mask;
struct io_uring_sqe *sqes;
struct io_uring_cqe *cqes;
char buff[BLOCK_SZ];
off_t offset;
/*

 * System call wrappers provided since glibc does not yet

 * provide wrappers for io_uring system calls.
* */
int io_uring_setup(unsigned entries, struct io_uring_params *p)
{

    int ret;

    ret = syscall(__NR_io_uring_setup, entries, p);

    return (ret < 0) ? -errno : ret;
}
int io_uring_enter(int ring_fd, unsigned int to_submit,

                   unsigned int min_complete, unsigned int flags)
{

    int ret;

    ret = syscall(__NR_io_uring_enter, ring_fd, to_submit,

                  min_complete, flags, NULL, 0);

    return (ret < 0) ? -errno : ret;
}
int app_setup_uring(void) {

    struct io_uring_params p;

    void *sq_ptr, *cq_ptr;

    /* See io_uring_setup(2) for io_uring_params.flags you can set */

    memset(&p, 0, sizeof(p));

    ring_fd = io_uring_setup(QUEUE_DEPTH, &p);

    if (ring_fd < 0) {

        perror("io_uring_setup");

        return 1;

    }

    /*

     * io_uring communication happens via 2 shared kernel-user space ring

     * buffers, which can be jointly mapped with a single mmap() call in

     * kernels >= 5.4.

     */

    int sring_sz = p.sq_off.array + p.sq_entries * sizeof(unsigned);

    int cring_sz = p.cq_off.cqes + p.cq_entries * sizeof(struct io_uring_cqe);

    /* Rather than check for kernel version, the recommended way is to

     * check the features field of the io_uring_params structure, which is a

     * bitmask. If IORING_FEAT_SINGLE_MMAP is set, we can do away with the

     * second mmap() call to map in the completion ring separately.

     */

    if (p.features & IORING_FEAT_SINGLE_MMAP) {

        if (cring_sz > sring_sz)

            sring_sz = cring_sz;

        cring_sz = sring_sz;

    }

    /* Map in the submission and completion queue ring buffers.

     *  Kernels < 5.4 only map in the submission queue, though.

     */

    sq_ptr = mmap(0, sring_sz, PROT_READ | PROT_WRITE,

                  MAP_SHARED | MAP_POPULATE,

                  ring_fd, IORING_OFF_SQ_RING);

    if (sq_ptr == MAP_FAILED) {

        perror("mmap");

        return 1;

    }

    if (p.features & IORING_FEAT_SINGLE_MMAP) {

        cq_ptr = sq_ptr;

    } else {

        /* Map in the completion queue ring buffer in older kernels separately */

        cq_ptr = mmap(0, cring_sz, PROT_READ | PROT_WRITE,

                      MAP_SHARED | MAP_POPULATE,

                      ring_fd, IORING_OFF_CQ_RING);

        if (cq_ptr == MAP_FAILED) {

            perror("mmap");

            return 1;

        }

    }

    /* Save useful fields for later easy reference */

    sring_tail = sq_ptr + p.sq_off.tail;

    sring_mask = sq_ptr + p.sq_off.ring_mask;

    sring_array = sq_ptr + p.sq_off.array;

    /* Map in the submission queue entries array */

    sqes = mmap(0, p.sq_entries * sizeof(struct io_uring_sqe),

                   PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE,

                   ring_fd, IORING_OFF_SQES);

    if (sqes == MAP_FAILED) {

        perror("mmap");

        return 1;

    }

    /* Save useful fields for later easy reference */

    cring_head = cq_ptr + p.cq_off.head;

    cring_tail = cq_ptr + p.cq_off.tail;

    cring_mask = cq_ptr + p.cq_off.ring_mask;

    cqes = cq_ptr + p.cq_off.cqes;

    return 0;
}
/*
* Read from completion queue.
* In this function, we read completion events from the completion queue.
* We dequeue the CQE, update and head and return the result of the operation.
* */
int read_from_cq() {

    struct io_uring_cqe *cqe;

    unsigned head;

    /* Read barrier */

    head = io_uring_smp_load_acquire(cring_head);

    /*

    * Remember, this is a ring buffer. If head == tail, it means that the

    * buffer is empty.

    * */

    if (head == *cring_tail)

        return -1;

    /* Get the entry */

    cqe = &cqes[head & (*cring_mask)];

    if (cqe->res < 0)

        fprintf(stderr, "Error: %s\n", strerror(abs(cqe->res)));

    head++;

    /* Write barrier so that update to the head are made visible */

    io_uring_smp_store_release(cring_head, head);

    return cqe->res;
}
/*
* Submit a read or a write request to the submission queue.
* */
int submit_to_sq(int fd, int op) {

    unsigned index, tail;

    /* Add our submission queue entry to the tail of the SQE ring buffer */

    tail = *sring_tail;

    index = tail & *sring_mask;

    struct io_uring_sqe *sqe = &sqes[index];

    /* Fill in the parameters required for the read or write operation */

    sqe->opcode = op;

    sqe->fd = fd;

    sqe->addr = (unsigned long) buff;

    if (op == IORING_OP_READ) {

        memset(buff, 0, sizeof(buff));

        sqe->len = BLOCK_SZ;

    }

    else {

        sqe->len = strlen(buff);

    }

    sqe->off = offset;

    sring_array[index] = index;

    tail++;

    /* Update the tail */

    io_uring_smp_store_release(sring_tail, tail);

    /*

    * Tell the kernel we have submitted events with the io_uring_enter()

    * system call. We also pass in the IORING_ENTER_GETEVENTS flag which

    * causes the io_uring_enter() call to wait until min_complete

    * (the 3rd param) events complete.

    * */

    int ret =  io_uring_enter(ring_fd, 1,1,

                              IORING_ENTER_GETEVENTS);

    if(ret < 0) {

        perror("io_uring_enter");

        return -1;

    }

    return ret;
}
int main(int argc, char *argv[]) {

    int res;

    /* Setup io_uring for use */

    if(app_setup_uring()) {

        fprintf(stderr, "Unable to setup uring!\n");

        return 1;

    }

    /*

    * A while loop that reads from stdin and writes to stdout.

    * Breaks on EOF.

    */

    while (1) {

        /* Initiate read from stdin and wait for it to complete */

        submit_to_sq(STDIN_FILENO, IORING_OP_READ);

        /* Read completion queue entry */

        res = read_from_cq();

        if (res > 0) {

            /* Read successful. Write to stdout. */

            submit_to_sq(STDOUT_FILENO, IORING_OP_WRITE);

            read_from_cq();

        } else if (res == 0) {

            /* reached EOF */

            break;

        }

        else if (res < 0) {

            /* Error reading file */

            fprintf(stderr, "Error: %s\n", strerror(abs(res)));

            break;

        }

        offset += res;

    }

    return 0;
}
```

## SEE ALSO
io_uring_enter(2) io_uring_register(2) io_uring_setup(2)


title: io_uring_cancelation(7)

summary: io_uring request cancelation overview

text:
# io_uring_cancelation(7)

## NAME
io_uring_cancelation - io_uring request cancelation overview

## DESCRIPTION
io_uring provides mechanisms to cancel in-flight requests before they complete naturally. This is useful for implementing timeouts, handling connection drops, closing connections that go away, or when a request is no longer needed.

### Why cancel requests?
Common scenarios requiring cancelation:

- Timeouts: Cancel a read or accept that has been pending too long

- Connection management: Cancel pending operations when a connection is closed

- Resource cleanup: Cancel operations on a file descriptor being closed

- Multishot termination: Stop a multishot operation that is no longer needed

### Basic cancelation
The primary cancelation mechanism is IORING_OP_ASYNC_CANCEL (set up with io_uring_prep_cancel(3) or related functions). By default, it cancels a request matching a specific user_data:

```
/* Submit a read with user_data = 1234 */
sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, fd, buf, len, 0);
io_uring_sqe_set_data64(sqe, 1234);
io_uring_submit(ring);
/* Later, cancel it */
sqe = io_uring_get_sqe(ring);
io_uring_prep_cancel64(sqe, 1234, 0);
io_uring_submit(ring);
```

### Cancelation results
When a cancelation is submitted, two CQEs are generated:

The canceled request's CQE:

- res is set to -ECANCELED (or occasionally -EINTR if the operation was already in progress)

- The user_data identifies which request was canceled

The cancel request's CQE:

- res is 0 on success (request was found and canceled)

- res is -ENOENT if no matching request was found

- res is -EALREADY if the request was found but already completing

The order of these CQEs is not guaranteed. The application may receive the cancel CQE before or after the canceled request's CQE.

### Cancelation flags
Various flags modify cancelation behavior:

IORING_ASYNC_CANCEL_ALL

Cancel all matching requests, not just the first one found. The cancel CQE's res indicates how many requests were canceled.

IORING_ASYNC_CANCEL_FD

Match requests by file descriptor instead of user_data. Cancels requests operating on the specified fd:

```
io_uring_prep_cancel_fd(sqe, fd, IORING_ASYNC_CANCEL_FD);
```

IORING_ASYNC_CANCEL_ANY

Cancel any single request, ignoring user_data matching. Useful for draining a ring of all pending requests when combined with IORING_ASYNC_CANCEL_ALL.

IORING_ASYNC_CANCEL_FD_FIXED

The file descriptor is a fixed file (registered file index) rather than a regular fd.

Flags can be combined:

```
/* Cancel all requests on a specific fd */
io_uring_prep_cancel_fd(sqe, fd,

    IORING_ASYNC_CANCEL_FD | IORING_ASYNC_CANCEL_ALL);
/* Cancel all pending requests in the ring */
io_uring_prep_cancel(sqe, NULL,

    IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_ALL);
```

### Race conditions
Cancelation is inherently racy. Between submitting the cancel request and the kernel processing it:

- The target request may complete successfully

- The target request may fail for another reason

- The target request may already be in a non-cancelable state

Applications must handle these cases:

```
io_uring_wait_cqe(ring, &cqe);
if (cqe->user_data == cancel_user_data) {

    /* This is the cancel operation's result */

    if (cqe->res == -ENOENT) {

        /* Request already completed or not found */

    } else if (cqe->res == -EALREADY) {

        /* Request was found but completing */

    } else if (cqe->res >= 0) {

        /* Successfully canceled res requests */

    }
} else {

    /* This is the original request's result */

    if (cqe->res == -ECANCELED) {

        /* Request was canceled */

    } else {

        /* Request completed normally (or with error) */

    }
}
```

### Link timeouts
For timing out a single operation, link timeouts are often simpler than explicit cancelation. See io_uring_linked_requests(7) for details:

```
sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, fd, buf, len, 0);
sqe->flags |= IOSQE_IO_LINK;
sqe = io_uring_get_sqe(ring);
io_uring_prep_link_timeout(sqe, &timeout, 0);
```

The kernel handles the cancelation automatically if the timeout expires.

### Canceling multishot requests
Multishot requests (see io_uring_multishot(7)) continue generating completions until canceled or an error occurs. To stop a multishot request:

```
/* Cancel a multishot accept */
io_uring_prep_cancel64(sqe, accept_user_data, 0);
```

After cancelation:

- The multishot generates a final CQE with -ECANCELED

- The IORING_CQE_F_MORE flag is not set on this final CQE

- The cancel CQE indicates success

### Canceling by file descriptor
When a file descriptor is closed (either via close(2) or IORING_OP_CLOSE), pending requests operating on that fd are not automatically canceled. This differs from synchronous I/O behavior and is a common source of confusion.

In synchronous I/O, closing a file descriptor is typically the last reference to the underlying file, so the close completes any pending operations. However, io_uring holds its own reference to the file for each pending request. Closing the application's fd does not release these references — the pending read, recv, or other operation continues to hold a reference and will not automatically complete or fail.

If an application expects a pending read on an fd to post a completion when the fd is closed, that will not happen. The request must be explicitly canceled:

```
/* Cancel all operations on fd before closing */
sqe = io_uring_get_sqe(ring);
io_uring_prep_cancel_fd(sqe, fd,

    IORING_ASYNC_CANCEL_FD | IORING_ASYNC_CANCEL_ALL);
io_uring_submit(ring);
/* Wait for cancelations, then close */
```

### Shutdown cancelation
When an io_uring instance is closed (via io_uring_queue_exit(3) or closing the ring file descriptor), all pending requests are automatically canceled. Manual cancelation before shutdown is not required.

However, if the application needs to ensure all requests are completed before proceeding (e.g., to process their results or free associated resources), explicit cancelation can be used:

```
/* Cancel everything */
sqe = io_uring_get_sqe(ring);
io_uring_prep_cancel(sqe, NULL,

    IORING_ASYNC_CANCEL_ANY | IORING_ASYNC_CANCEL_ALL);
io_uring_submit(ring);
/* Wait for all CQEs */
while (pending_count > 0) {

    io_uring_wait_cqe(ring, &cqe);

    pending_count--;

    io_uring_cqe_seen(ring, cqe);
}
```

### Synchronous cancelation
For cases where the application needs to cancel requests and wait for the cancelation to complete in a single blocking call, io_uring_register_sync_cancel(3) provides a synchronous interface:

```
struct io_uring_sync_cancel_reg reg = {

    .addr = user_data,

    .timeout.tv_sec = 5,
};
ret = io_uring_register_sync_cancel(ring, &reg);
```

This blocks until the matching request is canceled or the timeout expires. It is useful when the application cannot easily integrate asynchronous cancelation into its event loop.

## NOTES

- Not all operations are cancelable. Operations that have already been submitted to hardware (e.g., disk I/O in progress) typically cannot be canceled.

- Cancelation is asynchronous. The cancel request itself may take time to complete.

- When using IORING_ASYNC_CANCEL_ALL, the cancel CQE's res field contains the count of canceled requests.

- Fixed files can be canceled using IORING_ASYNC_CANCEL_FD_FIXED with the file index instead of a regular fd.

- Poll operations and multishot requests are generally good candidates for cancelation. Completed disk I/O is not.

## SEE ALSO
io_uring(7), io_uring_linked_requests(7), io_uring_multishot(7), io_uring_prep_cancel(3), io_uring_prep_cancel64(3), io_uring_prep_cancel_fd(3), io_uring_prep_link_timeout(3), io_uring_register_sync_cancel(3)


title: io_uring_linked_requests(7)

summary: io_uring linked requests overview

text:
# io_uring_linked_requests(7)

## NAME
io_uring_linked_requests - io_uring linked requests overview

## DESCRIPTION
Linked requests allow applications to chain multiple io_uring operations together, creating dependencies between them. When requests are linked, they execute sequentially rather than concurrently, with each request starting only after the previous one in the chain completes.

### Why use linked requests?
Normal io_uring submissions are independent and may execute in any order or concurrently. However, some operations have natural dependencies:

- Read from one file, then write to another

- Connect to a server, then send a request

- Accept a connection, then receive data

- Perform an operation with a timeout

Without linking, applications would need to wait for completions and submit follow-up requests manually. Linked requests allow the entire chain to be submitted at once, reducing round trips between user space and the kernel.

Linked requests are most beneficial when:

- Operations must execute in a specific order

- Later operations depend on earlier ones succeeding

- You want to attach a timeout to an operation

- Reducing submission latency is important

### Creating linked requests
Requests are linked by setting the IOSQE_IO_LINK flag on a request. This links it to the next request in the submission. The chain continues until a request without the link flag is encountered.

```
struct io_uring_sqe *sqe;
/* First request in chain */
sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, fd_in, buf, len, 0);
sqe->flags |= IOSQE_IO_LINK;
/* Second request, linked to first */
sqe = io_uring_get_sqe(ring);
io_uring_prep_write(sqe, fd_out, buf, len, 0);
sqe->flags |= IOSQE_IO_LINK;
/* Third request, end of chain (no link flag) */
sqe = io_uring_get_sqe(ring);
io_uring_prep_fsync(sqe, fd_out, 0);
io_uring_submit(ring);
```

In this example, the read completes first, then the write, then the fsync. Each operation waits for the previous one to complete before starting.

### Soft links vs hard links
There are two types of links, which differ in how they handle errors:

Soft links (IOSQE_IO_LINK)

If a request in the chain fails (returns a negative error code), all subsequent requests in the chain are canceled with -ECANCELED. This is useful when later operations depend on earlier ones succeeding.

Hard links (IOSQE_IO_HARDLINK)

The chain continues executing even if a request fails. Each request runs regardless of the outcome of previous requests. This is useful when you want to attempt all operations even if some fail.

```
/* Soft link: write is canceled if read fails */
sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, fd, buf, len, 0);
sqe->flags |= IOSQE_IO_LINK;
sqe = io_uring_get_sqe(ring);
io_uring_prep_write(sqe, fd2, buf, len, 0);
/* Hard link: write runs even if read fails */
sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, fd, buf, len, 0);
sqe->flags |= IOSQE_IO_HARDLINK;
sqe = io_uring_get_sqe(ring);
io_uring_prep_write(sqe, fd2, buf, len, 0);
```

### Link timeouts
A common use of linked requests is to add a timeout to an operation. The IORING_OP_LINK_TIMEOUT operation (set up with io_uring_prep_link_timeout(3)) is designed specifically for this:

```
struct __kernel_timespec ts = { .tv_sec = 5, .tv_nsec = 0 };
/* The operation to be timed */
sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, fd, buf, len, 0);
sqe->flags |= IOSQE_IO_LINK;
/* The timeout, linked to the read */
sqe = io_uring_get_sqe(ring);
io_uring_prep_link_timeout(sqe, &ts, 0);
io_uring_submit(ring);
```

If the read completes before the timeout:

- The read CQE has the actual result

- The timeout CQE has -ECANCELED

If the timeout expires first:

- The read CQE has -ECANCELED (or -EINTR if it was in progress)

- The timeout CQE has -ETIME

Link timeouts only apply to the immediately preceding request in the chain. To timeout an entire chain, the timeout must be linked after the last operation.

### Completion ordering
Each request in a linked chain generates its own CQE. Completions for linked requests are ordered — the CQE for an earlier request in the chain will be posted before the CQE for a later request.

Applications can rely on this ordering when processing completions. However, if other unlinked requests are in flight, their completions may be interleaved with the chain's completions.

### Error handling
For soft-linked chains, error handling is straightforward:

- Check each CQE's result

- If a request failed, all subsequent requests will have -ECANCELED

- The first non-canceled error indicates where the chain broke

```
/* Processing a linked chain's completions */
for (int i = 0; i < chain_length; i++) {

    io_uring_wait_cqe(ring, &cqe);

    if (cqe->res == -ECANCELED) {

        /* Previous request in chain failed */

    } else if (cqe->res < 0) {

        /* This request failed, caused chain break */

        handle_error(cqe->res);

    } else {

        /* Success */

        handle_success(cqe->res);

    }

    io_uring_cqe_seen(ring, cqe);
}
```

### Common patterns
Copy with sync:

Read data, write it elsewhere, then sync:

```
io_uring_prep_read(sqe1, src_fd, buf, len, 0);
sqe1->flags |= IOSQE_IO_LINK;
io_uring_prep_write(sqe2, dst_fd, buf, len, 0);
sqe2->flags |= IOSQE_IO_LINK;
io_uring_prep_fsync(sqe3, dst_fd, 0);
```

Connect with timeout:

Attempt connection with a time limit:

```
io_uring_prep_connect(sqe1, sockfd, addr, addrlen);
sqe1->flags |= IOSQE_IO_LINK;
io_uring_prep_link_timeout(sqe2, &timeout, 0);
```

Send after connect:

Connect then immediately send data:

```
io_uring_prep_connect(sqe1, sockfd, addr, addrlen);
sqe1->flags |= IOSQE_IO_LINK;
io_uring_prep_send(sqe2, sockfd, data, len, 0);
```

## NOTES

- Linked requests must be submitted together in the same io_uring_submit(3) call. The chain is defined by the order of SQEs in the submission.

- The link flag on the last request in a chain is ignored (it has nothing to link to).

- Chains can be arbitrarily long, limited only by SQ ring size.

- Mixing IOSQE_IO_LINK and IOSQE_IO_HARDLINK in the same chain is allowed. Each link's type determines what happens if that specific request fails.

- Linked requests share the same personality if set, allowing credential inheritance through the chain.

- If a request in a chain is canceled (e.g., via io_uring_prep_cancel(3)), the chain breaks as if that request had failed.

- Linked requests have performance implications: they force sequential execution, preventing the kernel from optimizing or parallelizing operations. Use links only when ordering is required. For independent operations, submitting them without links allows the kernel to execute them concurrently or reorder them for better performance.

## SEE ALSO
io_uring(7), io_uring_prep_link_timeout(3), io_uring_prep_cancel(3), io_uring_sqe_set_flags(3)


title: io_uring_multishot(7)

summary: io_uring multishot requests overview

text:
# io_uring_multishot(7)

## NAME
io_uring_multishot - io_uring multishot requests overview

## DESCRIPTION
Multishot requests are a class of io_uring operations where a single submission queue entry (SQE) can generate multiple completion queue entries (CQEs). This is in contrast to normal "oneshot" operations where each SQE produces exactly one CQE.

### Why use multishot requests?
Traditional I/O operations require submitting a new request for each operation. For high-frequency operations like accepting connections or receiving data, this creates overhead:

- CPU cycles spent preparing and submitting SQEs

- Memory bandwidth for SQE/CQE processing

- Potential for gaps between completions and new submissions

Multishot requests eliminate this overhead by keeping the operation active after each completion. The kernel automatically re-arms the operation, generating a new CQE when the next event occurs. Additionally, the internal poll mechanism remains persistent for the request, avoiding the need to manipulate poll state for each operation.

Multishot operations are most beneficial for:

- Network servers accepting many connections

- Applications receiving data on long-lived connections

- Event monitoring with poll

- Any scenario with repeated identical operations

### How multishot works
When a multishot operation completes, the CQE has the IORING_CQE_F_MORE flag set in cqe->flags. This indicates that the operation remains active and more completions will follow. The operation continues until:

- An error occurs (the final CQE will not have IORING_CQE_F_MORE set)

- The operation is explicitly canceled

- A termination condition specific to the operation is met (e.g., buffer exhaustion for receives)

The final CQE for a multishot operation will not have IORING_CQE_F_MORE set, indicating the operation has terminated.

### Multishot accept
io_uring_prep_multishot_accept(3) and io_uring_prep_multishot_accept_direct(3) set up a multishot accept operation. Each incoming connection generates a CQE with the new file descriptor in cqe->res.

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_multishot_accept(sqe, listen_fd, NULL, NULL, 0);
```

The operation continues accepting connections until an error occurs or it is canceled. Using the direct variant with IORING_FILE_INDEX_ALLOC allows accepted sockets to be placed directly into the fixed file table.

### Multishot receive
io_uring_prep_recv_multishot(3) sets up a multishot receive operation. Each time data arrives on the socket, a CQE is generated. This is typically used with provided buffers (see io_uring_provided_buffers(7)):

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_recv_multishot(sqe, sockfd, NULL, 0, 0);
sqe->buf_group = bgid;
sqe->flags |= IOSQE_BUFFER_SELECT;
```

Each completion includes:

- IORING_CQE_F_MORE if more completions will follow

- IORING_CQE_F_BUFFER indicating a buffer was selected

- The buffer ID in the upper bits of cqe->flags

- The number of bytes received in cqe->res

The multishot receive terminates when an error occurs, the connection closes, or the buffer ring is exhausted.

### Multishot recvmsg
io_uring_prep_recvmsg_multishot(3) is similar to multishot receive but uses the msghdr structure for scatter/gather I/O and ancillary data. A provided buffer is used for each message, with the kernel writing a struct io_uring_recvmsg_out header at the start of the buffer containing the actual message parameters.

### Multishot read
io_uring_prep_read_multishot(3) sets up a multishot read operation, typically used with pipes or other stream-oriented file descriptors. Like multishot receive, this is used with provided buffers:

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_read_multishot(sqe, fd, 0, 0, bgid);
```

The operation generates a CQE each time data becomes available to read.

### Multishot poll
io_uring_prep_poll_multishot(3) sets up a multishot poll operation, or it can be done manually by setting the IORING_POLL_ADD_MULTI flag:

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_poll_multishot(sqe, fd, POLLIN);
/* or equivalently: */
io_uring_prep_poll_add(sqe, fd, POLLIN);
sqe->len |= IORING_POLL_ADD_MULTI;
```

Each time the polled condition becomes true, a CQE is generated with the triggered events in cqe->res. Unlike oneshot poll which is automatically removed after triggering, multishot poll remains active.

For level-triggered events, the application should be careful to handle the event (e.g., read all available data) before the next poll completion, or spurious wakeups may occur.

### Multishot waitid
io_uring_prep_waitid(3) can operate in multishot mode by setting IORING_ACCEPT_MULTISHOT in the flags. This allows waiting for multiple child process state changes with a single SQE.

### Handling multishot completions
Applications must check for IORING_CQE_F_MORE to determine if the operation is still active:

```
struct io_uring_cqe *cqe;
while (io_uring_peek_cqe(ring, &cqe) == 0) {

    if (cqe->res < 0) {

        /* Error occurred, operation terminated */

        handle_error(cqe->res);

    } else {

        process_completion(cqe);

    }

    if (!(cqe->flags & IORING_CQE_F_MORE)) {

        /* Operation terminated, may need to resubmit */

        rearm_if_needed();

    }

    io_uring_cqe_seen(ring, cqe);
}
```

### Canceling multishot operations
Multishot operations can be canceled using io_uring_prep_cancel(3) or related functions. The cancellation request generates its own CQE, and the multishot operation generates a final CQE (typically with -ECANCELED) without IORING_CQE_F_MORE set.

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_cancel64(sqe, user_data, 0);
```

### Integration with provided buffers
Multishot receive and read operations are designed to work with provided buffer rings (see io_uring_provided_buffers(7)). Each completion consumes a buffer from the ring, and the application must return buffers to the ring to keep the operation running.

If the buffer ring becomes empty, the multishot operation terminates with -ENOBUFS. Applications should ensure adequate buffers are available and promptly return used buffers to the ring.

## NOTES

- Always check IORING_CQE_F_MORE to know if a multishot operation is still active.

- Multishot operations may generate many CQEs quickly. Ensure the CQ ring is large enough to avoid overflow.

- When using provided buffers with multishot receives, monitor buffer availability to prevent premature termination.

- Multishot operations are edge-triggered conceptually — they generate completions when events occur, not continuously while conditions are true.

- Error completions from multishot operations do not have IORING_CQE_F_MORE set, indicating termination.

## SEE ALSO
io_uring(7), io_uring_provided_buffers(7), io_uring_prep_multishot_accept(3), io_uring_prep_recv_multishot(3), io_uring_prep_recvmsg_multishot(3), io_uring_prep_read_multishot(3), io_uring_prep_poll_add(3), io_uring_prep_poll_multishot(3), io_uring_prep_cancel(3)


title: io_uring_provided_buffers(7)

summary: io_uring provided buffer rings overview

text:
# io_uring_provided_buffers(7)

## NAME
io_uring_provided_buffers - io_uring provided buffer rings overview

## DESCRIPTION
Provided buffer rings allow applications to supply a pool of buffers to the kernel that can be dynamically selected at operation completion time. This is particularly useful for operations where the buffer requirements are not known upfront, such as receiving data from network sockets or reading from pipes.

### Why use provided buffers?
Traditional I/O operations require the application to specify a buffer when submitting the request. For receive operations on sockets or reads from pipes, this presents a challenge: the application doesn't know how much data will arrive, so it must either:

- Allocate a large buffer for each pending operation, wasting memory

- Use small buffers and potentially require multiple operations

- Limit the number of pending operations to control memory usage

Provided buffer rings solve this by letting the kernel select an appropriately-sized buffer from a shared pool at completion time. Multiple operations can share the same buffer pool, and buffers are only consumed when data actually arrives.

Provided buffers are most beneficial for:

- Network servers with many concurrent connections

- Applications receiving variable-length messages

- Scenarios where memory efficiency is important

### Buffer ring concepts
A provided buffer ring is a circular buffer shared between the application and kernel:

- The application adds buffers to the ring by writing entries and advancing the tail

- The kernel consumes buffers from the ring by reading entries and advancing the head

- Each buffer has a unique buffer ID (bid) within its buffer group

- Buffer groups are identified by a buffer group ID (bgid)

Multiple buffer rings can exist simultaneously, each with a different buffer group ID. Operations specify which buffer group to use.

### Setting up a buffer ring
Buffer rings are set up using io_uring_setup_buf_ring(3), which handles allocation, registration, and initialization:

```
struct io_uring_buf_ring *br;
int bgid = 1;  /* buffer group ID */
int err;
br = io_uring_setup_buf_ring(ring, 128, bgid, 0, &err);
if (!br) {

    fprintf(stderr, "buffer ring setup failed: %d\n", err);

    return err;
}
```

The ring must have a power-of-two number of entries, up to a maximum of 32768 (2^15).

Alternatively, applications can use io_uring_register_buf_ring(3) for more control over the setup process, including kernel-allocated rings using the IOU_PBUF_RING_MMAP flag.

### Adding buffers to the ring
Buffers are added using io_uring_buf_ring_add(3) and made visible to the kernel with io_uring_buf_ring_advance(3):

```
int mask = io_uring_buf_ring_mask(128);
for (int i = 0; i < 128; i++) {

    void *buf = malloc(4096);

    io_uring_buf_ring_add(br, buf, 4096, i, mask, i);
}
io_uring_buf_ring_advance(br, 128);
```

Each buffer is assigned a buffer ID (the third parameter). Buffer IDs should be unique within the buffer group but can be reused after a buffer is returned.

### Using provided buffers in operations
To use provided buffers, set the IOSQE_BUFFER_SELECT flag on the SQE and specify the buffer group ID:

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_recv(sqe, sockfd, NULL, 4096, 0);
io_uring_sqe_set_flags(sqe, IOSQE_BUFFER_SELECT);
io_uring_sqe_set_buf_group(sqe, bgid);
```

Note that addr is set to NULL (or ignored) since the kernel will select the buffer. The len field specifies the maximum amount of data to receive.

Operations that support provided buffers include:

- IORING_OP_READ / IORING_OP_RECV

- IORING_OP_READV (single vector only)

- IORING_OP_RECVMSG

### Handling completions
When an operation using provided buffers completes, the CQE indicates which buffer was used:

- IORING_CQE_F_BUFFER is set in cqe->flags

- The buffer ID is in the upper 16 bits of cqe->flags, extractable via cqe->flags >> IORING_CQE_BUFFER_SHIFT

- cqe->res contains the number of bytes transferred

```
struct io_uring_cqe *cqe;
io_uring_wait_cqe(ring, &cqe);
if (cqe->flags & IORING_CQE_F_BUFFER) {

    int bid = cqe->flags >> IORING_CQE_BUFFER_SHIFT;

    void *buf = buffers[bid];  /* application's buffer tracking */

    int len = cqe->res;

    /* process data in buf */

    process_data(buf, len);

    /* return buffer to ring for reuse */

    io_uring_buf_ring_add(br, buf, 4096, bid, mask, 0);

    io_uring_buf_ring_advance(br, 1);
}
io_uring_cqe_seen(ring, cqe);
```

If no buffer was available when the operation completed, the operation fails with -ENOBUFS.

### Multishot operations
Provided buffers are particularly powerful with multishot operations like io_uring_prep_recv_multishot(3). A single SQE can generate multiple completions, each consuming a buffer from the ring:

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_recv_multishot(sqe, sockfd, NULL, 0, 0);
io_uring_sqe_set_flags(sqe, IOSQE_BUFFER_SELECT);
io_uring_sqe_set_buf_group(sqe, bgid);
```

Completions with IORING_CQE_F_MORE set indicate more completions will follow. The multishot operation continues until an error occurs, the buffer ring is exhausted, or the operation is canceled.

### Incremental buffer consumption
Buffer rings can be set up with the IOU_PBUF_RING_INC flag to enable incremental consumption. With this mode, large buffers can be partially consumed across multiple operations:

- Completions with IORING_CQE_F_BUF_MORE indicate the buffer will be used for more completions

- Each completion picks up where the previous left off

- The buffer is only returned when consumed completely or on error

This is useful for registering large buffer regions that are consumed in smaller chunks.

### Returning buffers
When finished with a buffer, return it to the ring using io_uring_buf_ring_add(3) followed by io_uring_buf_ring_advance(3). For efficiency when processing multiple CQEs, use io_uring_buf_ring_cq_advance(3) to advance both the CQ and buffer ring in a single operation.

### Buffer ring status
Applications can query how many buffers are available using io_uring_buf_ring_available(3), which returns the number of buffers the kernel has not yet consumed. The current kernel head position can be retrieved with io_uring_buf_ring_head(3).

### Cleaning up
Buffer rings are freed using io_uring_free_buf_ring(3), which unregisters the ring and frees the ring memory (if it was allocated by io_uring_setup_buf_ring(3)). Applications must free the individual buffers themselves.

## NOTES

- Buffer ring entries must be a power of two, maximum 32768.

- Buffer IDs are 16-bit values (0-65535).

- If no buffer is available when an operation needs one, the operation fails with -ENOBUFS. Applications should ensure the ring is adequately stocked.

- Provided buffers cannot be used with registered (fixed) buffers. These are separate mechanisms.

- For multishot receives, ensure buffers are returned to the ring promptly to avoid running out.

### Legacy provided buffers
Earlier kernels supported provided buffers via IORING_OP_PROVIDE_BUFFERS and IORING_OP_REMOVE_BUFFERS. This mechanism required submitting SQEs to add or remove buffers, adding latency and overhead. The ring-based mechanism described above supersedes this approach and should be used for all new applications. The legacy interface remains for backwards compatibility.

## SEE ALSO
io_uring(7), io_uring_setup_buf_ring(3), io_uring_free_buf_ring(3), io_uring_register_buf_ring(3), io_uring_unregister_buf_ring(3), io_uring_buf_ring_add(3), io_uring_buf_ring_advance(3), io_uring_buf_ring_cq_advance(3), io_uring_buf_ring_available(3), io_uring_prep_recv_multishot(3)


title: io_uring_registered_buffers(7)

summary: io_uring registered buffers overview

text:
# io_uring_registered_buffers(7)

## NAME
io_uring_registered_buffers - io_uring registered buffers overview

## DESCRIPTION
Registered buffers are a performance optimization feature of io_uring that allows applications to pre-register a set of buffers with the kernel. When buffers are registered, the kernel pins the memory and creates long-term mappings, eliminating the overhead of mapping and unmapping buffer memory for each I/O operation.

### Why use registered buffers?
For every I/O operation that transfers data between user space and the kernel, the kernel must perform several operations on the buffer memory:

- Verify the memory is accessible to the process

- Pin the pages in memory to prevent them from being swapped out

- Set up kernel mappings to access the memory

These operations, while individually fast, add up when performing many small I/O operations. By registering buffers once upfront, these costs are paid only once, and subsequent I/O operations can use the pre-mapped buffers directly.

Registered buffers are most beneficial for applications that:

- Perform many small I/O operations

- Reuse the same buffers repeatedly

- Need the lowest possible per-I/O overhead

### Registering buffers
Buffers are registered using io_uring_register_buffers(3) or io_uring_register_buffers_tags(3). The buffers are described using an array of struct iovec structures:

```
struct iovec iovecs[2];
iovecs[0].iov_base = buf1;
iovecs[0].iov_len = 4096;
iovecs[1].iov_base = buf2;
iovecs[1].iov_len = 8192;
ret = io_uring_register_buffers(ring, iovecs, 2);
```

The buffers must be anonymous memory (allocated via malloc(3), mmap(2) with MAP_ANONYMOUS, or similar). File-backed memory is not supported.

There is a limit of 1 GiB per individual buffer. Huge pages are supported and the entire huge page will be pinned even if only part of it is used.

The buffers are charged against the user's RLIMIT_MEMLOCK resource limit on kernels before 5.12. On kernel 5.12 and later with IORING_FEAT_NATIVE_WORKERS support, cgroup memory accounting is used instead and no memlock limit applies.

Unless running as root, if buffer registration fails with ENOMEM, the memlock limit may need to be increased. The current limit can be checked with:

```
ulimit -l
```

The limit can be increased for the current shell session with:

```
ulimit -l unlimited
```

For a permanent change, edit /etc/security/limits.conf or use setrlimit(2) programmatically with RLIMIT_MEMLOCK.

### Using registered buffers
To use a registered buffer in an I/O operation, use the fixed buffer variants of the prep functions:

- io_uring_prep_read_fixed(3) instead of io_uring_prep_read(3)

- io_uring_prep_write_fixed(3) instead of io_uring_prep_write(3)

- io_uring_prep_readv_fixed(3) instead of io_uring_prep_readv(3)

- io_uring_prep_writev_fixed(3) instead of io_uring_prep_writev(3)

Zero-copy send operations can also use registered buffers:

- io_uring_prep_send_zc(3) with IORING_RECVSEND_FIXED_BUF

- io_uring_prep_sendmsg_zc(3) with IORING_RECVSEND_FIXED_BUF

These functions take a buf_index parameter that specifies which registered buffer to use (0-indexed into the array passed to io_uring_register_buffers(3)).

The memory range used for the I/O operation must fall within the bounds of the registered buffer. It is valid to use only a portion of a registered buffer for an operation.

```
/* Use first 1024 bytes of registered buffer 0 */
io_uring_prep_read_fixed(sqe, fd, buf1, 1024, offset, 0);
/* Use registered buffer 1 */
io_uring_prep_write_fixed(sqe, fd, buf2, 2048, offset, 1);
```

### Sparse buffer registration
Applications can register a sparse buffer table using io_uring_register_buffers_sparse(3). This creates a table with empty slots that can be filled in later using io_uring_register_buffers_update_tag(3). This is useful when the full set of buffers is not known at registration time.

```
/* Create sparse table with 10 slots */
ret = io_uring_register_buffers_sparse(ring, 10);
/* Later, fill in slot 3 */
struct iovec iov = { .iov_base = buf, .iov_len = 4096 };
ret = io_uring_register_buffers_update_tag(ring, 3, &iov, NULL, 1);
```

### Buffer tagging
When using io_uring_register_buffers_tags(3) or io_uring_register_buffers_update_tag(3), each buffer can be associated with a tag value. When a buffer is unregistered (either explicitly or by replacing it), and there are no more in-flight operations using that buffer, a completion queue entry is posted with user_data set to the tag value and all other fields zeroed.

This allows applications to know when it is safe to free or reuse the buffer memory.

### Updating registered buffers
Registered buffers can be updated in place using io_uring_register_buffers_update_tag(3). This can:

- Replace an existing buffer with a new one

- Fill in a sparse slot

- Remove a buffer by setting the iovec to zero length

Updating buffers does not immediately free resources. The old buffer remains valid until all in-flight operations complete.

### Unregistering buffers
Buffers are unregistered using io_uring_unregister_buffers(3). This releases all registered buffers. Buffers are also automatically unregistered when the io_uring instance is destroyed.

Applications do not need to explicitly unregister buffers before shutting down the ring. However, page unpinning may happen asynchronously, so pages may not be immediately available after ring destruction.

### Cloning buffers
Registered buffers can be cloned from one ring to another using io_uring_clone_buffers(3) or io_uring_clone_buffers_offset(3). This allows multiple rings to share the same set of registered buffers without re-registering them.

## NOTES

- Registered buffers provide the most benefit for small, frequent I/O operations where the per-operation overhead is significant.

- For large I/O operations, the buffer mapping overhead is small relative to the actual I/O time, so registered buffers may not provide much benefit.

- The maximum number of registered buffers is limited by available kernel memory and the RLIMIT_MEMLOCK limit (on older kernels).

- Registered buffers cannot be used with provided buffer rings (IOSQE_BUFFER_SELECT). These are separate mechanisms for different use cases.

## SEE ALSO
io_uring(7), io_uring_registered_files(7), setrlimit(2), io_uring_register_buffers(3), io_uring_register_buffers_tags(3), io_uring_register_buffers_sparse(3), io_uring_register_buffers_update_tag(3), io_uring_unregister_buffers(3), io_uring_prep_read_fixed(3), io_uring_prep_write_fixed(3), io_uring_prep_send_zc(3), io_uring_prep_sendmsg_zc(3), io_uring_clone_buffers(3)


title: io_uring_registered_files(7)

summary: io_uring registered files overview

text:
# io_uring_registered_files(7)

## NAME
io_uring_registered_files - io_uring registered files overview

## DESCRIPTION
Registered files (also known as fixed files) are a performance optimization feature of io_uring that allows applications to pre-register a set of file descriptors with the kernel. When files are registered, the kernel takes a reference to each file, avoiding the overhead of looking up file descriptors and taking references for each I/O operation.

### Why use registered files?
For every I/O operation that uses a file descriptor, the kernel must:

- Look up the file descriptor in the process's file descriptor table

- Take a reference to the file to ensure it remains valid during the operation

- Release the reference when the operation completes

For applications performing many I/O operations, especially on threaded applications where the file table is shared (making reference counting more expensive), these overheads accumulate. By registering files once, the reference is held for the lifetime of the registration, and operations can use the file directly without per-operation lookups or reference counting.

Registered files are most beneficial for applications that:

- Perform many I/O operations on the same set of files

- Are multi-threaded (where file table operations are more expensive)

- Need the lowest possible per-I/O overhead

### Registering files
Files are registered using io_uring_register_files(3) or io_uring_register_files_tags(3). The files are described using an array of file descriptors:

```
int fds[3];
fds[0] = open("file1", O_RDONLY);
fds[1] = open("file2", O_RDONLY);
fds[2] = open("file3", O_WRONLY | O_CREAT, 0644);
ret = io_uring_register_files(ring, fds, 3);
```

Once registered, the original file descriptors can be closed if desired. The kernel holds its own references to the underlying files.

### Using registered files
To use a registered file in an I/O operation, set the IOSQE_FIXED_FILE flag in the SQE's flags field, and use the index into the registered file array (not the original file descriptor) in the fd field:

```
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_read(sqe, 0, buf, len, offset);  /* index 0, not fd */
io_uring_sqe_set_flags(sqe, IOSQE_FIXED_FILE);
```

The index is 0-based into the array passed to io_uring_register_files(3).

### Sparse file registration
The file array can be sparse, meaning some slots can be empty. Empty slots are indicated by setting the file descriptor to -1. Applications can create a fully sparse table using io_uring_register_files_sparse(3) and fill in slots later:

```
/* Create sparse table with 100 slots */
ret = io_uring_register_files_sparse(ring, 100);
/* Later, fill in slot 5 */
int fd = open("file", O_RDONLY);
ret = io_uring_register_files_update(ring, 5, &fd, 1);
```

### Updating registered files
Registered files can be updated using io_uring_register_files_update(3) or io_uring_register_files_update_tag(3). This can:

- Replace an existing file with a new one

- Fill in an empty slot

- Remove a file by setting the descriptor to -1

To skip updating certain slots while updating others, use the special value IORING_REGISTER_FILES_SKIP.

```
int fds[3];
fds[0] = new_fd;                        /* replace slot 0 */
fds[1] = IORING_REGISTER_FILES_SKIP;    /* leave slot 1 unchanged */
fds[2] = -1;                            /* remove slot 2 */
ret = io_uring_register_files_update(ring, 0, fds, 3);
```

Updates do not require the ring to be idle on kernels 5.13 and later. On older kernels, updates would wait for in-flight operations to complete.

### File tagging
When using io_uring_register_files_tags(3) or io_uring_register_files_update_tag(3), each file can be associated with a tag value. When a file is unregistered (either explicitly or by replacement), and there are no more in-flight operations using that file, a completion queue entry is posted with user_data set to the tag value and all other fields zeroed.

This notification mechanism allows applications to know when it is safe to perform cleanup actions associated with the file.

### Direct file descriptors
Some io_uring operations can allocate file descriptors directly into the registered file table, avoiding the regular file descriptor table entirely. This is done by setting the file_index field in the SQE (using io_uring_sqe_set_target_fixed_file(3)) to the desired slot, or using IORING_FILE_INDEX_ALLOC to have io_uring allocate the next available slot.

Operations that support direct descriptors include:

- IORING_OP_OPENAT / IORING_OP_OPENAT2

- IORING_OP_ACCEPT

- IORING_OP_SOCKET

- IORING_OP_PIPE

When using IORING_FILE_INDEX_ALLOC, the application should use io_uring_register_file_alloc_range(3) to specify which range of the file table should be used for allocations.

```
/* Reserve slots 50-99 for dynamic allocation */
io_uring_register_file_alloc_range(ring, 50, 50);
/* Accept with direct descriptor allocation */
struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
io_uring_prep_accept_direct(sqe, listen_fd, NULL, NULL, 0,

                            IORING_FILE_INDEX_ALLOC);
```

The allocated slot index is returned in the CQE res field on success.

### Closing direct descriptors
Direct descriptors (files that exist only in the registered file table) can be closed using IORING_OP_CLOSE with the IOSQE_FIXED_FILE flag set, or by updating the slot to -1 using io_uring_register_files_update(3).

### Unregistering files
Files are unregistered using io_uring_unregister_files(3). This releases all registered files. Files are also automatically unregistered when the io_uring instance is destroyed.

Applications do not need to explicitly unregister files before shutting down the ring.

## NOTES

- Registered files provide the most benefit for applications performing many operations on the same files, especially multi-threaded applications.

- Direct descriptors (files that only exist in the registered table) are not visible to operations outside io_uring, such as read(2) or write(2).

- The IOSQE_FIXED_FILE flag must be set when using a registered file index; without it, the fd field is interpreted as a regular file descriptor.

- It is an error to use IOSQE_FIXED_FILE with an index that does not correspond to a registered file.

## SEE ALSO
io_uring(7), io_uring_registered_buffers(7), io_uring_register_files(3), io_uring_register_files_tags(3), io_uring_register_files_sparse(3), io_uring_register_files_update(3), io_uring_register_files_update_tag(3), io_uring_unregister_files(3), io_uring_register_file_alloc_range(3)