use core::ffi::{CStr, c_void};
use core::fmt;
use core::marker::PhantomData;
use core::ptr::{self, NonNull};
use core::sync::atomic::{AtomicU16, AtomicU32, Ordering, fence};
use core::time::Duration;
use crate::event::{Interest, Readiness};
use crate::fs::{Metadata, OpenOptions};
use crate::io::{IoSlice, IoSliceMut};
use crate::macros::flags;
use crate::net::{
Address, AsSocket, Family, Protocol, RawAddr, RecvFlags, SendFlags, Shutdown, Type,
};
use crate::sys::uring as sys;
use crate::{AsHandle, BorrowedHandle, Error, ErrorKind, OwnedHandle, Result};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct RawSqe {
pub opcode: u8,
pub flags: u8,
pub ioprio: u16,
pub fd: i32,
pub off: u64,
pub addr: u64,
pub len: u32,
pub op_flags: u32,
pub user_data: u64,
pub buf_index: u16,
pub personality: u16,
pub file_index: u32,
pub addr3: u64,
pub pad: u64,
}
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct Cqe {
user_data: u64,
res: i32,
flags: u32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct Timespec {
pub sec: i64,
pub nsec: i64,
}
const _: () = {
assert!(size_of::<RawSqe>() == 64);
assert!(core::mem::offset_of!(RawSqe, user_data) == 32);
assert!(core::mem::offset_of!(RawSqe, addr3) == 48);
assert!(size_of::<Cqe>() == 16);
assert!(size_of::<Timespec>() == 16);
assert!(size_of::<SockAddr>() >= RawAddr::CAPACITY + 4);
};
impl From<Duration> for Timespec {
fn from(duration: Duration) -> Self {
Self {
sec: i64::try_from(duration.as_secs()).unwrap_or(i64::MAX),
nsec: duration.subsec_nanos().into(),
}
}
}
#[repr(transparent)]
pub struct SockAddr(RawAddr);
impl SockAddr {
pub fn new() -> Self {
let mut raw = RawAddr::new();
raw.set_len(RawAddr::CAPACITY);
Self(raw)
}
pub fn from_address(addr: &Address) -> Result<Self> {
RawAddr::encode(addr).map(Self)
}
pub fn set_received_len(&mut self, len: u32) {
self.0.set_len((len as usize).min(RawAddr::CAPACITY));
}
pub fn address(&self) -> Option<Address> {
self.0.decode()
}
}
impl Default for SockAddr {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for SockAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("SockAddr").field(&self.address()).finish()
}
}
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct MsgHdr {
pub name: *mut c_void,
pub name_len: u32,
pub iov: *mut c_void,
pub iov_len: usize,
pub control: *mut c_void,
pub control_len: usize,
pub flags: i32,
}
impl MsgHdr {
#[inline]
pub const fn new() -> Self {
Self {
name: ptr::null_mut(),
name_len: 0,
iov: ptr::null_mut(),
iov_len: 0,
control: ptr::null_mut(),
control_len: 0,
flags: 0,
}
}
#[inline]
pub fn to(mut self, addr: &SockAddr) -> Self {
self.name = ptr::from_ref(addr).cast_mut().cast();
self.name_len = addr.0.len();
self
}
#[inline]
pub const fn from(mut self, addr: *mut SockAddr) -> Self {
self.name = addr.cast();
self.name_len = RawAddr::CAPACITY as u32;
self
}
#[inline]
pub const fn buffers<T>(mut self, bufs: *const T, count: usize) -> Self {
self.iov = bufs.cast_mut().cast();
self.iov_len = count;
self
}
}
impl Default for MsgHdr {
fn default() -> Self {
Self::new()
}
}
#[repr(transparent)]
pub struct Statx(crate::sys::fs::Statx);
impl Statx {
#[inline]
pub fn new() -> Self {
Self(crate::sys::fs::Statx::default())
}
pub fn metadata(&self) -> Metadata {
crate::sys::fs::statx_metadata(&self.0)
}
}
impl Default for Statx {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Statx {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Statx").finish_non_exhaustive()
}
}
#[derive(Clone, Copy)]
#[repr(C, align(8))]
pub struct WaitInfo([i32; 32]);
const CLD_EXITED: i32 = 1;
const CLD_KILLED: i32 = 2;
const CLD_DUMPED: i32 = 3;
impl WaitInfo {
const FIELDS: usize = if cfg!(target_pointer_width = "64") {
4
} else {
3
};
#[inline]
pub const fn new() -> Self {
Self([0; 32])
}
#[inline]
pub fn pid(&self) -> Option<u32> {
match self.0[Self::FIELDS] {
0 => None,
pid => Some(pid as u32),
}
}
#[inline]
pub fn exit_code(&self) -> Option<i32> {
(self.pid().is_some() && self.0[2] == CLD_EXITED).then(|| self.0[Self::FIELDS + 2])
}
#[inline]
pub fn signal(&self) -> Option<i32> {
(self.pid().is_some() && matches!(self.0[2], CLD_KILLED | CLD_DUMPED))
.then(|| self.0[Self::FIELDS + 2])
}
}
impl Default for WaitInfo {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for WaitInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WaitInfo")
.field("pid", &self.pid())
.field("exit_code", &self.exit_code())
.field("signal", &self.signal())
.finish()
}
}
const _: () = {
assert!(size_of::<MsgHdr>() == 7 * size_of::<usize>());
assert!(size_of::<Statx>() == 256);
assert!(size_of::<WaitInfo>() == 128);
assert!(size_of::<Restriction>() == 16);
assert!(size_of::<FileSlot<'_>>() == 4);
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Advice {
Normal = 0,
Random = 1,
Sequential = 2,
WillNeed = 3,
DontNeed = 4,
}
flags! {
pub struct FallocateMode: u32 {
const KEEP_SIZE = 0x01;
const PUNCH_HOLE = 0x02;
const COLLAPSE_RANGE = 0x08;
const ZERO_RANGE = 0x10;
const INSERT_RANGE = 0x20;
}
}
flags! {
pub struct RenameFlags: u32 {
const NO_REPLACE = 1 << 0;
const EXCHANGE = 1 << 1;
}
}
flags! {
pub struct SpliceFlags: u32 {
const MOVE = 1 << 0;
const NONBLOCK = 1 << 1;
const MORE = 1 << 2;
}
}
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct FileSlot<'a>(i32, PhantomData<BorrowedHandle<'a>>);
impl<'a> FileSlot<'a> {
pub const EMPTY: Self = Self(-1, PhantomData);
pub const KEEP: Self = Self(-2, PhantomData);
#[inline]
pub const fn file(handle: BorrowedHandle<'a>) -> Self {
Self(handle.as_raw(), PhantomData)
}
}
impl fmt::Debug for FileSlot<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
-1 => f.write_str("FileSlot::EMPTY"),
-2 => f.write_str("FileSlot::KEEP"),
fd => f.debug_tuple("FileSlot").field(&fd).finish(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum RegisterOp {
Buffers = 0,
UnregisterBuffers = 1,
Files = 2,
UnregisterFiles = 3,
Eventfd = 4,
UnregisterEventfd = 5,
FilesUpdate = 6,
Probe = 8,
Restrictions = 11,
EnableRings = 12,
Files2 = 13,
IowqAff = 17,
UnregisterIowqAff = 18,
IowqMaxWorkers = 19,
RingFds = 20,
UnregisterRingFds = 21,
PbufRing = 22,
UnregisterPbufRing = 23,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Restriction {
opcode: u16,
value: u8,
resv: u8,
resv2: [u32; 3],
}
impl Restriction {
const fn new(opcode: u16, value: u8) -> Self {
Self {
opcode,
value,
resv: 0,
resv2: [0; 3],
}
}
#[inline]
pub const fn op(opcode: Opcode) -> Self {
Self::op_raw(opcode as u8)
}
#[inline]
pub const fn op_raw(opcode: u8) -> Self {
Self::new(sys::IORING_RESTRICTION_SQE_OP, opcode)
}
#[inline]
pub const fn register(op: RegisterOp) -> Self {
Self::register_raw(op as u8)
}
#[inline]
pub const fn register_raw(op: u8) -> Self {
Self::new(sys::IORING_RESTRICTION_REGISTER_OP, op)
}
#[inline]
pub const fn flags_allowed(flags: SqeFlags) -> Self {
Self::new(sys::IORING_RESTRICTION_SQE_FLAGS_ALLOWED, flags.bits())
}
#[inline]
pub const fn flags_required(flags: SqeFlags) -> Self {
Self::new(sys::IORING_RESTRICTION_SQE_FLAGS_REQUIRED, flags.bits())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Opcode {
Nop = 0,
Readv = 1,
Writev = 2,
Fsync = 3,
ReadFixed = 4,
WriteFixed = 5,
PollAdd = 6,
PollRemove = 7,
Sendmsg = 9,
Recvmsg = 10,
Timeout = 11,
TimeoutRemove = 12,
Accept = 13,
AsyncCancel = 14,
LinkTimeout = 15,
Connect = 16,
Fallocate = 17,
Openat = 18,
Close = 19,
Statx = 21,
Read = 22,
Write = 23,
Fadvise = 24,
Madvise = 25,
Send = 26,
Recv = 27,
Openat2 = 28,
Splice = 30,
ProvideBuffers = 31,
RemoveBuffers = 32,
Tee = 33,
Shutdown = 34,
Renameat = 35,
Unlinkat = 36,
Mkdirat = 37,
Symlinkat = 38,
Linkat = 39,
MsgRing = 40,
Socket = 45,
UringCmd = 46,
SendZc = 47,
SendmsgZc = 48,
ReadMultishot = 49,
Waitid = 50,
FutexWait = 51,
FutexWake = 52,
}
flags! {
pub struct SqeFlags: u8 {
const FIXED_FILE = 1 << 0;
const DRAIN = 1 << 1;
const LINK = 1 << 2;
const HARD_LINK = 1 << 3;
const ASYNC = 1 << 4;
const BUFFER_SELECT = 1 << 5;
const CQE_SKIP_SUCCESS = 1 << 6;
}
}
flags! {
pub struct Features: u32 {
const SINGLE_MMAP = 1 << 0;
const NODROP = 1 << 1;
const SUBMIT_STABLE = 1 << 2;
const RW_CUR_POS = 1 << 3;
const FAST_POLL = 1 << 5;
const EXT_ARG = 1 << 8;
const SQPOLL_NONFIXED = 1 << 7;
const NATIVE_WORKERS = 1 << 9;
const RSRC_TAGS = 1 << 10;
const CQE_SKIP = 1 << 11;
}
}
pub const CURRENT_POSITION: u64 = u64::MAX;
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct Sqe(RawSqe);
fn fd(handle: impl AsHandle) -> i32 {
handle.as_handle().as_raw()
}
fn socket_fd(socket: impl AsSocket) -> i32 {
socket.as_socket().as_raw()
}
impl Sqe {
const fn op(opcode: Opcode, fd: i32) -> RawSqe {
RawSqe {
opcode: opcode as u8,
flags: 0,
ioprio: 0,
fd,
off: 0,
addr: 0,
len: 0,
op_flags: 0,
user_data: 0,
buf_index: 0,
personality: 0,
file_index: 0,
addr3: 0,
pad: 0,
}
}
#[inline]
pub const unsafe fn from_raw(raw: RawSqe) -> Self {
Self(raw)
}
#[inline]
pub const fn as_raw(&self) -> &RawSqe {
&self.0
}
#[inline]
pub const fn user_data(mut self, user_data: u64) -> Self {
self.0.user_data = user_data;
self
}
#[inline]
pub const fn flags(mut self, flags: SqeFlags) -> Self {
self.0.flags |= flags.bits() & !(sys::IOSQE_FIXED_FILE | sys::IOSQE_BUFFER_SELECT);
self
}
#[inline]
pub const fn fixed_file(mut self, index: u32) -> Self {
self.0.fd = index as i32;
self.0.flags |= sys::IOSQE_FIXED_FILE;
self
}
#[inline]
pub const fn nop() -> Self {
Self(Self::op(Opcode::Nop, -1))
}
#[inline]
pub unsafe fn read(handle: impl AsHandle, buf: *mut u8, len: u32, offset: u64) -> Self {
let mut raw = Self::op(Opcode::Read, fd(handle));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.off = offset;
Self(raw)
}
#[inline]
pub unsafe fn write(handle: impl AsHandle, buf: *const u8, len: u32, offset: u64) -> Self {
let mut raw = Self::op(Opcode::Write, fd(handle));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.off = offset;
Self(raw)
}
#[inline]
pub unsafe fn readv(
handle: impl AsHandle,
bufs: *const IoSliceMut<'_>,
count: u32,
offset: u64,
) -> Self {
let mut raw = Self::op(Opcode::Readv, fd(handle));
raw.addr = bufs.addr() as u64;
raw.len = count;
raw.off = offset;
Self(raw)
}
#[inline]
pub unsafe fn writev(
handle: impl AsHandle,
bufs: *const IoSlice<'_>,
count: u32,
offset: u64,
) -> Self {
let mut raw = Self::op(Opcode::Writev, fd(handle));
raw.addr = bufs.addr() as u64;
raw.len = count;
raw.off = offset;
Self(raw)
}
#[inline]
pub unsafe fn read_fixed(
handle: impl AsHandle,
buf: *mut u8,
len: u32,
offset: u64,
index: u16,
) -> Self {
let mut raw = Self::op(Opcode::ReadFixed, fd(handle));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.off = offset;
raw.buf_index = index;
Self(raw)
}
#[inline]
pub unsafe fn write_fixed(
handle: impl AsHandle,
buf: *const u8,
len: u32,
offset: u64,
index: u16,
) -> Self {
let mut raw = Self::op(Opcode::WriteFixed, fd(handle));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.off = offset;
raw.buf_index = index;
Self(raw)
}
#[inline]
pub fn fsync(handle: impl AsHandle, data_only: bool) -> Self {
let mut raw = Self::op(Opcode::Fsync, fd(handle));
if data_only {
raw.op_flags = sys::IORING_FSYNC_DATASYNC;
}
Self(raw)
}
#[inline]
pub unsafe fn accept(socket: impl AsSocket, addr: *mut SockAddr) -> Self {
let mut raw = Self::op(Opcode::Accept, socket_fd(socket));
if !addr.is_null() {
raw.addr = addr.addr() as u64;
raw.off = (addr.addr() + RawAddr::LEN_OFFSET) as u64;
}
raw.op_flags = crate::sys::net::SOCK_CLOEXEC as u32;
Self(raw)
}
#[inline]
pub unsafe fn connect(socket: impl AsSocket, addr: *const SockAddr) -> Self {
let mut raw = Self::op(Opcode::Connect, socket_fd(socket));
raw.addr = addr.addr() as u64;
raw.off = u64::from(unsafe { (*addr).0.len() });
Self(raw)
}
#[inline]
pub unsafe fn send(socket: impl AsSocket, buf: *const u8, len: u32, flags: SendFlags) -> Self {
let mut raw = Self::op(Opcode::Send, socket_fd(socket));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.op_flags = crate::sys::net::send_flags(flags) as u32;
Self(raw)
}
#[inline]
pub unsafe fn recv(socket: impl AsSocket, buf: *mut u8, len: u32, flags: RecvFlags) -> Self {
let mut raw = Self::op(Opcode::Recv, socket_fd(socket));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.op_flags = crate::sys::net::recv_flags(flags) as u32;
Self(raw)
}
#[inline]
pub fn shutdown(socket: impl AsSocket, how: Shutdown) -> Self {
let mut raw = Self::op(Opcode::Shutdown, socket_fd(socket));
raw.len = match how {
Shutdown::Read => 0,
Shutdown::Write => 1,
Shutdown::Both => 2,
};
Self(raw)
}
#[inline]
pub unsafe fn timeout(time: *const Timespec, count: u32) -> Self {
let mut raw = Self::op(Opcode::Timeout, -1);
raw.addr = time.addr() as u64;
raw.len = 1;
raw.off = u64::from(count);
Self(raw)
}
#[inline]
pub unsafe fn timeout_at(time: *const Timespec, count: u32) -> Self {
let mut sqe = unsafe { Self::timeout(time, count) };
sqe.0.op_flags = sys::IORING_TIMEOUT_ABS;
sqe
}
#[inline]
pub const fn timeout_remove(user_data: u64) -> Self {
let mut raw = Self::op(Opcode::TimeoutRemove, -1);
raw.addr = user_data;
Self(raw)
}
#[inline]
pub unsafe fn link_timeout(time: *const Timespec) -> Self {
let mut raw = Self::op(Opcode::LinkTimeout, -1);
raw.addr = time.addr() as u64;
raw.len = 1;
Self(raw)
}
#[inline]
pub const fn cancel(user_data: u64) -> Self {
let mut raw = Self::op(Opcode::AsyncCancel, -1);
raw.addr = user_data;
Self(raw)
}
#[inline]
pub fn poll_add(handle: impl AsHandle, interest: Interest) -> Self {
let handle = handle.as_handle();
let mut raw = Self::op(Opcode::PollAdd, handle.as_raw());
let events = crate::sys::event::PollFd::new(handle.as_raw(), interest).events();
raw.op_flags = u32::from(events as u16);
Self(raw)
}
#[inline]
pub const fn poll_remove(user_data: u64) -> Self {
let mut raw = Self::op(Opcode::PollRemove, -1);
raw.addr = user_data;
Self(raw)
}
#[inline]
pub fn close(handle: OwnedHandle) -> Self {
Self(Self::op(Opcode::Close, handle.into_raw()))
}
#[inline]
pub unsafe fn openat(
dir: Option<BorrowedHandle<'_>>,
path: *const core::ffi::c_char,
options: &OpenOptions,
) -> Self {
let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
let mut raw = Self::op(Opcode::Openat, dir);
raw.addr = path.addr() as u64;
raw.len = options.mode;
raw.op_flags = crate::sys::fs::open_flags(options) as u32;
Self(raw)
}
#[inline]
pub unsafe fn open(path: &CStr, options: &OpenOptions) -> Self {
unsafe { Self::openat(None, path.as_ptr(), options) }
}
#[inline]
pub unsafe fn statx(
dir: Option<BorrowedHandle<'_>>,
path: *const core::ffi::c_char,
follow: bool,
out: *mut Statx,
) -> Self {
let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
let mut raw = Self::op(Opcode::Statx, dir);
raw.addr = path.addr() as u64;
raw.off = out.addr() as u64;
raw.len = crate::sys::fs::STATX_MASK;
if !follow {
raw.op_flags = crate::sys::fs::AT_SYMLINK_NOFOLLOW as u32;
}
Self(raw)
}
#[inline]
pub fn fallocate(handle: impl AsHandle, mode: FallocateMode, offset: u64, len: u64) -> Self {
let mut raw = Self::op(Opcode::Fallocate, fd(handle));
raw.off = offset;
raw.addr = len;
raw.len = mode.bits();
Self(raw)
}
#[inline]
pub fn fadvise(handle: impl AsHandle, offset: u64, len: u32, advice: Advice) -> Self {
let mut raw = Self::op(Opcode::Fadvise, fd(handle));
raw.off = offset;
raw.len = len;
raw.op_flags = advice as u32;
Self(raw)
}
#[inline]
pub unsafe fn madvise(addr: *mut u8, len: u32, advice: Advice) -> Self {
let mut raw = Self::op(Opcode::Madvise, -1);
raw.addr = addr.addr() as u64;
raw.len = len;
raw.op_flags = advice as u32;
Self(raw)
}
#[inline]
pub unsafe fn renameat(
old_dir: Option<BorrowedHandle<'_>>,
old_path: *const core::ffi::c_char,
new_dir: Option<BorrowedHandle<'_>>,
new_path: *const core::ffi::c_char,
flags: RenameFlags,
) -> Self {
let at = |dir: Option<BorrowedHandle<'_>>| {
dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw)
};
let mut raw = Self::op(Opcode::Renameat, at(old_dir));
raw.addr = old_path.addr() as u64;
raw.len = at(new_dir) as u32;
raw.off = new_path.addr() as u64;
raw.op_flags = flags.bits();
Self(raw)
}
#[inline]
pub unsafe fn unlinkat(
dir: Option<BorrowedHandle<'_>>,
path: *const core::ffi::c_char,
directory: bool,
) -> Self {
let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
let mut raw = Self::op(Opcode::Unlinkat, dir);
raw.addr = path.addr() as u64;
if directory {
raw.op_flags = crate::sys::fs::AT_REMOVEDIR as u32;
}
Self(raw)
}
#[inline]
pub unsafe fn mkdirat(
dir: Option<BorrowedHandle<'_>>,
path: *const core::ffi::c_char,
mode: u32,
) -> Self {
let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
let mut raw = Self::op(Opcode::Mkdirat, dir);
raw.addr = path.addr() as u64;
raw.len = mode;
Self(raw)
}
#[inline]
pub unsafe fn symlinkat(
target: *const core::ffi::c_char,
dir: Option<BorrowedHandle<'_>>,
link_path: *const core::ffi::c_char,
) -> Self {
let dir = dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw);
let mut raw = Self::op(Opcode::Symlinkat, dir);
raw.addr = target.addr() as u64;
raw.off = link_path.addr() as u64;
Self(raw)
}
#[inline]
pub unsafe fn linkat(
old_dir: Option<BorrowedHandle<'_>>,
old_path: *const core::ffi::c_char,
new_dir: Option<BorrowedHandle<'_>>,
new_path: *const core::ffi::c_char,
follow: bool,
) -> Self {
const FOLLOW: u32 = 0x400;
let at = |dir: Option<BorrowedHandle<'_>>| {
dir.map_or(crate::sys::fs::AT_FDCWD, BorrowedHandle::as_raw)
};
let mut raw = Self::op(Opcode::Linkat, at(old_dir));
raw.addr = old_path.addr() as u64;
raw.len = at(new_dir) as u32;
raw.off = new_path.addr() as u64;
if follow {
raw.op_flags = FOLLOW;
}
Self(raw)
}
#[inline]
pub fn splice(
from: impl AsHandle,
from_offset: Option<u64>,
to: impl AsHandle,
to_offset: Option<u64>,
len: u32,
flags: SpliceFlags,
) -> Self {
let mut raw = Self::op(Opcode::Splice, fd(to));
raw.file_index = fd(from) as u32;
raw.addr = from_offset.unwrap_or(u64::MAX);
raw.off = to_offset.unwrap_or(u64::MAX);
raw.len = len;
raw.op_flags = flags.bits();
Self(raw)
}
#[inline]
pub fn tee(from: impl AsHandle, to: impl AsHandle, len: u32, flags: SpliceFlags) -> Self {
let mut raw = Self::op(Opcode::Tee, fd(to));
raw.file_index = fd(from) as u32;
raw.len = len;
raw.op_flags = flags.bits();
Self(raw)
}
#[inline]
pub fn socket(family: Family, ty: Type, protocol: Protocol) -> Self {
let mut raw = Self::op(Opcode::Socket, crate::sys::net::family(family));
raw.off = (crate::sys::net::socket_kind(ty) | crate::sys::net::SOCK_CLOEXEC) as u64;
raw.len = protocol.number() as u32;
Self(raw)
}
#[inline]
pub unsafe fn sendmsg(socket: impl AsSocket, msg: *const MsgHdr, flags: SendFlags) -> Self {
let mut raw = Self::op(Opcode::Sendmsg, socket_fd(socket));
raw.addr = msg.addr() as u64;
raw.len = 1;
raw.op_flags = crate::sys::net::send_flags(flags) as u32;
Self(raw)
}
#[inline]
pub unsafe fn recvmsg(socket: impl AsSocket, msg: *mut MsgHdr, flags: RecvFlags) -> Self {
let mut raw = Self::op(Opcode::Recvmsg, socket_fd(socket));
raw.addr = msg.addr() as u64;
raw.len = 1;
raw.op_flags = crate::sys::net::recv_flags(flags) as u32;
Self(raw)
}
#[inline]
pub unsafe fn send_zc(
socket: impl AsSocket,
buf: *const u8,
len: u32,
flags: SendFlags,
) -> Self {
let mut raw = Self::op(Opcode::SendZc, socket_fd(socket));
raw.addr = buf.addr() as u64;
raw.len = len;
raw.op_flags = crate::sys::net::send_flags(flags) as u32;
Self(raw)
}
#[inline]
pub unsafe fn sendmsg_zc(socket: impl AsSocket, msg: *const MsgHdr, flags: SendFlags) -> Self {
let mut raw = Self::op(Opcode::SendmsgZc, socket_fd(socket));
raw.addr = msg.addr() as u64;
raw.len = 1;
raw.op_flags = crate::sys::net::send_flags(flags) as u32;
Self(raw)
}
#[inline]
pub fn accept_multishot(socket: impl AsSocket) -> Self {
let mut raw = Self::op(Opcode::Accept, socket_fd(socket));
raw.op_flags = crate::sys::net::SOCK_CLOEXEC as u32;
raw.ioprio = sys::IORING_ACCEPT_MULTISHOT;
Self(raw)
}
#[inline]
pub unsafe fn recv_multishot(socket: impl AsSocket, group: u16, flags: RecvFlags) -> Self {
let mut raw = Self::op(Opcode::Recv, socket_fd(socket));
raw.op_flags = crate::sys::net::recv_flags(flags) as u32;
raw.ioprio = sys::IORING_RECV_MULTISHOT;
unsafe { Self(raw).buffer_select(group) }
}
#[inline]
pub unsafe fn read_multishot(handle: impl AsHandle, group: u16) -> Self {
let mut raw = Self::op(Opcode::ReadMultishot, fd(handle));
raw.off = CURRENT_POSITION;
unsafe { Self(raw).buffer_select(group) }
}
#[inline]
pub fn poll_multishot(handle: impl AsHandle, interest: Interest) -> Self {
let mut sqe = Self::poll_add(handle, interest);
sqe.0.len = sys::IORING_POLL_ADD_MULTI;
sqe
}
#[inline]
pub unsafe fn timeout_multishot(time: *const Timespec, repeats: u32) -> Self {
let mut sqe = unsafe { Self::timeout(time, repeats) };
sqe.0.op_flags = sys::IORING_TIMEOUT_MULTISHOT;
sqe
}
#[inline]
pub const unsafe fn buffer_select(mut self, group: u16) -> Self {
self.0.flags |= sys::IOSQE_BUFFER_SELECT;
self.0.buf_index = group;
self
}
#[inline]
pub unsafe fn provide_buffers(
addr: *mut u8,
len: u32,
count: u16,
group: u16,
first_id: u16,
) -> Self {
let mut raw = Self::op(Opcode::ProvideBuffers, i32::from(count));
raw.addr = addr.addr() as u64;
raw.len = len;
raw.off = u64::from(first_id);
raw.buf_index = group;
Self(raw)
}
#[inline]
pub const fn remove_buffers(count: u16, group: u16) -> Self {
let mut raw = Self::op(Opcode::RemoveBuffers, count as i32);
raw.buf_index = group;
Self(raw)
}
#[inline]
pub const fn cancel_all(user_data: u64) -> Self {
let mut sqe = Self::cancel(user_data);
sqe.0.op_flags = sys::IORING_ASYNC_CANCEL_ALL;
sqe
}
#[inline]
pub fn cancel_fd(handle: impl AsHandle) -> Self {
let mut raw = Self::op(Opcode::AsyncCancel, fd(handle));
raw.op_flags = sys::IORING_ASYNC_CANCEL_FD | sys::IORING_ASYNC_CANCEL_ALL;
Self(raw)
}
#[inline]
pub const fn cancel_any() -> Self {
let mut raw = Self::op(Opcode::AsyncCancel, -1);
raw.op_flags = sys::IORING_ASYNC_CANCEL_ANY | sys::IORING_ASYNC_CANCEL_ALL;
Self(raw)
}
#[inline]
pub fn msg_ring(target: impl AsHandle, result: u32, user_data: u64) -> Self {
let mut raw = Self::op(Opcode::MsgRing, fd(target));
raw.len = result;
raw.off = user_data;
Self(raw)
}
#[inline]
pub unsafe fn futex_wait(addr: *const AtomicU32, expected: u32) -> Self {
let mut raw = Self::op(Opcode::FutexWait, sys::FUTEX2_U32_PRIVATE);
raw.addr = addr.addr() as u64;
raw.off = u64::from(expected);
raw.addr3 = sys::FUTEX_BITSET_MATCH_ANY;
Self(raw)
}
#[inline]
pub fn futex_wake(addr: *const AtomicU32, count: u32) -> Self {
let mut raw = Self::op(Opcode::FutexWake, sys::FUTEX2_U32_PRIVATE);
raw.addr = addr.addr() as u64;
raw.off = u64::from(count);
raw.addr3 = sys::FUTEX_BITSET_MATCH_ANY;
Self(raw)
}
#[inline]
pub unsafe fn waitid_pid(pid: u32, info: *mut WaitInfo) -> Self {
const P_PID: u32 = 1;
unsafe { Self::waitid(P_PID, pid as i32, info) }
}
#[inline]
pub unsafe fn waitid_pidfd(pidfd: impl AsHandle, info: *mut WaitInfo) -> Self {
const P_PIDFD: u32 = 3;
unsafe { Self::waitid(P_PIDFD, fd(pidfd), info) }
}
unsafe fn waitid(which: u32, id: i32, info: *mut WaitInfo) -> Self {
const WEXITED: u32 = 4;
let mut raw = Self::op(Opcode::Waitid, id);
raw.len = which;
raw.off = info.addr() as u64;
raw.file_index = WEXITED;
Self(raw)
}
#[inline]
pub unsafe fn uring_cmd(handle: impl AsHandle, cmd_op: u32, cmd: [u8; 16]) -> Self {
let mut raw = Self::op(Opcode::UringCmd, fd(handle));
raw.off = u64::from(cmd_op);
let (low, high) = cmd.split_at(8);
raw.addr3 = u64::from_ne_bytes(low.try_into().unwrap_or([0; 8]));
raw.pad = u64::from_ne_bytes(high.try_into().unwrap_or([0; 8]));
Self(raw)
}
}
impl Cqe {
#[inline]
pub const fn user_data(&self) -> u64 {
self.user_data
}
#[inline]
pub fn result(&self) -> Result<u32> {
if self.res < 0 {
Err(Error::from_raw_os_error(self.res.wrapping_neg()))
} else {
Ok(self.res as u32)
}
}
#[inline]
pub const fn raw_result(&self) -> i32 {
self.res
}
#[inline]
pub const fn flags(&self) -> u32 {
self.flags
}
#[inline]
pub const fn has_more(&self) -> bool {
self.flags & sys::IORING_CQE_F_MORE != 0
}
#[inline]
pub const fn buffer_id(&self) -> Option<u16> {
if self.flags & sys::IORING_CQE_F_BUFFER != 0 {
Some((self.flags >> sys::IORING_CQE_BUFFER_SHIFT) as u16)
} else {
None
}
}
#[inline]
pub const fn is_notification(&self) -> bool {
self.flags & sys::IORING_CQE_F_NOTIF != 0
}
#[inline]
pub const fn socket_nonempty(&self) -> bool {
self.flags & sys::IORING_CQE_F_SOCK_NONEMPTY != 0
}
#[inline]
pub fn readiness(&self) -> Readiness {
if self.res < 0 {
return Readiness::empty();
}
crate::sys::event::PollFd::answered(self.res as i16).readiness()
}
}
impl fmt::Debug for Cqe {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Cqe")
.field("user_data", &self.user_data)
.field("result", &self.result())
.field("flags", &self.flags)
.finish()
}
}
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub struct Setup {
cq_entries: u32,
flags: u32,
sq_thread_idle: u32,
sq_thread_cpu: u32,
wq_fd: u32,
}
impl Setup {
#[inline]
pub const fn new() -> Self {
Self {
cq_entries: 0,
flags: 0,
sq_thread_idle: 0,
sq_thread_cpu: 0,
wq_fd: 0,
}
}
#[inline]
pub const fn cq_entries(mut self, entries: u32) -> Self {
self.cq_entries = entries;
self.flags |= sys::IORING_SETUP_CQSIZE;
self
}
#[inline]
pub const fn clamp(mut self, clamp: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_CLAMP, clamp);
self
}
#[inline]
pub const fn coop_taskrun(mut self, enabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_COOP_TASKRUN, enabled);
self
}
#[inline]
pub const fn single_issuer(mut self, enabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_SINGLE_ISSUER, enabled);
self
}
#[inline]
pub const fn defer_taskrun(mut self, enabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_DEFER_TASKRUN, enabled);
if enabled {
self.flags |= sys::IORING_SETUP_SINGLE_ISSUER;
}
self
}
#[inline]
pub const fn submit_all(mut self, enabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_SUBMIT_ALL, enabled);
self
}
#[inline]
pub const fn sqpoll(mut self, idle: Duration) -> Self {
self.flags |= sys::IORING_SETUP_SQPOLL;
let millis = idle.as_millis();
self.sq_thread_idle = if millis == 0 {
1
} else if millis > u32::MAX as u128 {
u32::MAX
} else {
millis as u32
};
self
}
#[inline]
pub const fn sqpoll_cpu(mut self, cpu: u32) -> Self {
self.flags |= sys::IORING_SETUP_SQ_AFF;
self.sq_thread_cpu = cpu;
self
}
#[inline]
pub const fn attach_wq(mut self, ring: BorrowedHandle<'_>) -> Self {
self.flags |= sys::IORING_SETUP_ATTACH_WQ;
self.wq_fd = ring.as_raw() as u32;
self
}
#[inline]
pub const fn disabled(mut self, disabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_R_DISABLED, disabled);
self
}
#[inline]
pub const fn sqe128(mut self, enabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_SQE128, enabled);
self
}
#[inline]
pub const fn cqe32(mut self, enabled: bool) -> Self {
self.flags = set(self.flags, sys::IORING_SETUP_CQE32, enabled);
self
}
}
const fn set(flags: u32, flag: u32, on: bool) -> u32 {
if on { flags | flag } else { flags & !flag }
}
struct Map {
ptr: NonNull<u8>,
len: usize,
}
impl Map {
fn new(fd: BorrowedHandle<'_>, offset: u64, len: usize) -> Result<Self> {
Self::of(crate::sys::mem::map_shared(fd, offset, len)?, len)
}
fn anonymous(len: usize) -> Result<Self> {
let options = crate::mem::MapOptions::new();
Self::of(crate::sys::mem::map_anonymous(len, &options)?, len)
}
fn of(ptr: *mut u8, len: usize) -> Result<Self> {
match NonNull::new(ptr) {
Some(ptr) => Ok(Self { ptr, len }),
None => Err(ErrorKind::Other.into()),
}
}
fn at<T>(&self, offset: usize, count: usize) -> Result<NonNull<T>> {
let size = size_of::<T>().checked_mul(count);
let end = size.and_then(|size| offset.checked_add(size));
match end {
Some(end) if end <= self.len && offset.is_multiple_of(align_of::<T>()) => {
Ok(unsafe { self.ptr.add(offset) }.cast())
}
_ => Err(ErrorKind::Other.into()),
}
}
}
impl Drop for Map {
fn drop(&mut self) {
let _ = unsafe { crate::sys::mem::unmap(self.ptr.as_ptr(), self.len) };
}
}
pub struct Ring {
sq_head: NonNull<AtomicU32>,
sq_tail: NonNull<AtomicU32>,
sq_flags: NonNull<AtomicU32>,
sq_mask: u32,
sq_entries: u32,
sqe_shift: u32,
sqes: NonNull<RawSqe>,
cq_head: NonNull<AtomicU32>,
cq_tail: NonNull<AtomicU32>,
cq_overflow: NonNull<AtomicU32>,
cq_mask: u32,
cq_entries: u32,
cqe_shift: u32,
cqes: NonNull<Cqe>,
features: Features,
probe: Probe,
sqpoll: bool,
ring_index: Option<u32>,
pushed: u64,
completed: u64,
fd: OwnedHandle,
_sq_map: Map,
_cq_map: Option<Map>,
_sqes_map: Map,
}
unsafe impl Send for Ring {}
unsafe impl Sync for Ring {}
#[derive(Clone)]
pub struct Probe {
last: u8,
supported: [u32; 8],
}
impl Probe {
#[inline]
pub fn supports(&self, opcode: Opcode) -> bool {
self.supports_raw(opcode as u8)
}
#[inline]
pub fn supports_raw(&self, opcode: u8) -> bool {
self.supported[usize::from(opcode / 32)] & (1 << (opcode % 32)) != 0
}
#[inline]
pub fn last_opcode(&self) -> u8 {
self.last
}
}
impl fmt::Debug for Probe {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Probe")
.field("last_opcode", &self.last)
.finish_non_exhaustive()
}
}
impl Ring {
pub fn new(entries: u32) -> Result<Self> {
Self::with_setup(entries, &Setup::new())
}
pub fn with_setup(entries: u32, setup: &Setup) -> Result<Self> {
let mut params = sys::Params {
flags: setup.flags,
cq_entries: setup.cq_entries,
sq_thread_cpu: setup.sq_thread_cpu,
sq_thread_idle: setup.sq_thread_idle,
wq_fd: setup.wq_fd,
..sys::Params::default()
};
let fd = sys::setup(entries, &mut params)?;
let sqe_shift = u32::from(setup.flags & sys::IORING_SETUP_SQE128 != 0);
let cqe_shift = u32::from(setup.flags & sys::IORING_SETUP_CQE32 != 0);
let sq = ¶ms.sq_off;
let cq = ¶ms.cq_off;
let (sq_entries, cq_entries) = (params.sq_entries as usize, params.cq_entries as usize);
let (sqe_places, cqe_places) = (sq_entries << sqe_shift, cq_entries << cqe_shift);
let (Some(sq_len), Some(cq_len), Some(sqes_len)) = (
sq_entries
.checked_mul(size_of::<u32>())
.and_then(|len| len.checked_add(sq.array as usize)),
cqe_places
.checked_mul(size_of::<Cqe>())
.and_then(|len| len.checked_add(cq.cqes as usize)),
sqe_places.checked_mul(size_of::<RawSqe>()),
) else {
return Err(ErrorKind::Other.into());
};
if !params.sq_entries.is_power_of_two() || !params.cq_entries.is_power_of_two() {
return Err(ErrorKind::Other.into());
}
let handle = fd.as_handle();
let (sq_map, cq_map) = if params.features & sys::IORING_FEAT_SINGLE_MMAP != 0 {
let len = sq_len.max(cq_len);
(Map::new(handle, sys::IORING_OFF_SQ_RING, len)?, None)
} else {
(
Map::new(handle, sys::IORING_OFF_SQ_RING, sq_len)?,
Some(Map::new(handle, sys::IORING_OFF_CQ_RING, cq_len)?),
)
};
let sqes_map = Map::new(handle, sys::IORING_OFF_SQES, sqes_len)?;
let cq_ring = cq_map.as_ref().unwrap_or(&sq_map);
let array = sq_map.at::<u32>(sq.array as usize, sq_entries)?;
for index in 0..params.sq_entries {
unsafe { array.add(index as usize).write(index) };
}
let mut ring = Self {
sq_head: sq_map.at(sq.head as usize, 1)?,
sq_tail: sq_map.at(sq.tail as usize, 1)?,
sq_flags: sq_map.at(sq.flags as usize, 1)?,
sq_mask: params.sq_entries - 1,
sq_entries: params.sq_entries,
sqe_shift,
sqes: sqes_map.at(0, sqe_places)?,
cq_head: cq_ring.at(cq.head as usize, 1)?,
cq_tail: cq_ring.at(cq.tail as usize, 1)?,
cq_overflow: cq_ring.at(cq.overflow as usize, 1)?,
cq_mask: params.cq_entries - 1,
cq_entries: params.cq_entries,
cqe_shift,
cqes: cq_ring.at(cq.cqes as usize, cqe_places)?,
features: Features(params.features),
probe: Probe {
last: 0,
supported: [0; 8],
},
sqpoll: setup.flags & sys::IORING_SETUP_SQPOLL != 0,
ring_index: None,
pushed: 0,
completed: 0,
fd,
_sq_map: sq_map,
_cq_map: cq_map,
_sqes_map: sqes_map,
};
ring.probe = ring.ask_probe()?;
Ok(ring)
}
#[inline]
pub fn features(&self) -> Features {
self.features
}
#[inline]
pub fn sq_entries(&self) -> u32 {
self.sq_entries
}
#[inline]
pub fn cq_entries(&self) -> u32 {
self.cq_entries
}
#[inline]
fn atomic(&self, pointer: NonNull<AtomicU32>) -> &AtomicU32 {
unsafe { pointer.as_ref() }
}
#[inline]
pub fn unsubmitted(&self) -> u32 {
let head = self.atomic(self.sq_head).load(Ordering::Acquire);
let tail = self.atomic(self.sq_tail).load(Ordering::Relaxed);
tail.wrapping_sub(head)
}
pub fn push(&mut self, sqe: Sqe) -> Result<()> {
self.push_entry(sqe, None)
}
pub fn push_wide(&mut self, sqe: Sqe, more: &[u8; 64]) -> Result<()> {
if self.sqe_shift == 0 {
return Err(ErrorKind::InvalidInput.into());
}
self.push_entry(sqe, Some(more))
}
fn push_entry(&mut self, sqe: Sqe, more: Option<&[u8; 64]>) -> Result<()> {
if !self.probe.supports_raw(sqe.0.opcode) {
return Err(ErrorKind::Unsupported.into());
}
let head = self.atomic(self.sq_head).load(Ordering::Acquire);
let tail = self.atomic(self.sq_tail).load(Ordering::Relaxed);
if tail.wrapping_sub(head) >= self.sq_entries {
return Err(ErrorKind::WouldBlock.into());
}
let place = ((tail & self.sq_mask) as usize) << self.sqe_shift;
unsafe {
let slot = self.sqes.add(place);
slot.write(sqe.0);
if self.sqe_shift != 0 {
let rest = slot.add(1).cast::<[u8; 64]>();
rest.write(more.copied().unwrap_or([0; 64]));
}
}
self.atomic(self.sq_tail)
.store(tail.wrapping_add(1), Ordering::Release);
self.pushed += 1;
Ok(())
}
#[inline]
pub fn needs_wakeup(&self) -> bool {
fence(Ordering::SeqCst);
self.atomic(self.sq_flags).load(Ordering::Relaxed) & sys::IORING_SQ_NEED_WAKEUP != 0
}
fn enter(&mut self, want: u32, mut flags: u32, arg: *const sys::GeteventsArg) -> Result<usize> {
let to_submit = self.unsubmitted();
if self.sqpoll && self.needs_wakeup() {
flags |= sys::IORING_ENTER_SQ_WAKEUP;
}
let fd = match self.ring_index {
Some(index) => {
flags |= sys::IORING_ENTER_REGISTERED_RING;
index as i32
}
None => self.fd.as_raw(),
};
unsafe { sys::enter(fd, to_submit, want, flags, arg) }
}
pub fn submit(&mut self) -> Result<usize> {
let pending = self.unsubmitted();
if pending == 0 || (self.sqpoll && !self.needs_wakeup()) {
return Ok(pending as usize);
}
self.enter(0, 0, ptr::null())
}
pub fn wait_for_room(&mut self) -> Result<()> {
if !self.sqpoll {
return self.submit().map(drop);
}
self.enter(0, sys::IORING_ENTER_SQ_WAIT, ptr::null())
.map(drop)
}
pub fn wait(&mut self, want: u32, timeout: Option<Duration>) -> Result<usize> {
let Some(timeout) = timeout else {
return self.enter(want, sys::IORING_ENTER_GETEVENTS, ptr::null());
};
if !self.features.contains(Features::EXT_ARG) {
return Err(ErrorKind::Unsupported.into());
}
let time = Timespec::from(timeout);
let arg = sys::GeteventsArg {
sigmask: 0,
sigmask_sz: 0,
min_wait_usec: 0,
ts: (&raw const time).addr() as u64,
};
let flags = sys::IORING_ENTER_GETEVENTS | sys::IORING_ENTER_EXT_ARG;
match self.enter(want, flags, &raw const arg) {
Err(error) if error.raw_os_error() == crate::sys::errno::ETIME => Ok(0),
result => result,
}
}
#[inline]
pub fn ready(&self) -> u32 {
let tail = self.atomic(self.cq_tail).load(Ordering::Acquire);
let head = self.atomic(self.cq_head).load(Ordering::Relaxed);
tail.wrapping_sub(head)
}
pub fn pop(&mut self) -> Option<Cqe> {
self.pop_wide().map(|(cqe, _)| cqe)
}
pub fn pop_wide(&mut self) -> Option<(Cqe, [u64; 2])> {
let head = self.atomic(self.cq_head).load(Ordering::Relaxed);
let tail = self.atomic(self.cq_tail).load(Ordering::Acquire);
if head == tail {
return None;
}
let place = ((head & self.cq_mask) as usize) << self.cqe_shift;
let (cqe, more) = unsafe {
let slot = self.cqes.add(place);
let more = if self.cqe_shift != 0 {
slot.add(1).cast::<[u64; 2]>().read()
} else {
[0; 2]
};
(slot.read(), more)
};
self.atomic(self.cq_head)
.store(head.wrapping_add(1), Ordering::Release);
if !cqe.has_more() {
self.completed += 1;
}
Some((cqe, more))
}
#[inline]
pub fn in_flight(&self) -> u64 {
self.pushed
.wrapping_sub(u64::from(self.unsubmitted()))
.wrapping_sub(self.completed)
}
#[inline]
pub fn overflowed(&self) -> bool {
self.atomic(self.sq_flags).load(Ordering::Relaxed) & sys::IORING_SQ_CQ_OVERFLOW != 0
}
#[inline]
pub fn dropped(&self) -> u32 {
self.atomic(self.cq_overflow).load(Ordering::Relaxed)
}
unsafe fn register(&self, opcode: u32, arg: *const c_void, count: usize) -> Result<usize> {
let count = u32::try_from(count).map_err(|_| Error::from(ErrorKind::InvalidInput))?;
unsafe { sys::register(self.fd.as_raw(), opcode, arg, count) }
}
fn or_unsupported(&self, error: Error, witness: Opcode) -> Error {
if error.raw_os_error() == crate::sys::errno::EINVAL && !self.probe.supports(witness) {
ErrorKind::Unsupported.into()
} else {
error
}
}
fn ask_probe(&self) -> Result<Probe> {
let mut probe: sys::Probe = unsafe { core::mem::zeroed() };
unsafe {
self.register(
sys::IORING_REGISTER_PROBE,
(&raw mut probe).cast(),
sys::PROBE_OPS,
)
}?;
let mut supported = [0; 8];
for op in &probe.ops[..usize::from(probe.ops_len)] {
if op.flags & sys::IO_URING_OP_SUPPORTED != 0 {
supported[usize::from(op.op / 32)] |= 1 << (op.op % 32);
}
}
Ok(Probe {
last: probe.last_op,
supported,
})
}
#[inline]
pub fn probe(&self) -> &Probe {
&self.probe
}
pub fn enable(&self) -> Result<()> {
unsafe { self.register(sys::IORING_REGISTER_ENABLE_RINGS, ptr::null(), 0) }.map(drop)
}
pub fn register_restrictions(&self, allowed: &[Restriction]) -> Result<()> {
unsafe {
self.register(
sys::IORING_REGISTER_RESTRICTIONS,
allowed.as_ptr().cast(),
allowed.len(),
)
}
.map(drop)
}
pub fn register_buffers(&self, bufs: &[IoSliceMut<'_>]) -> Result<()> {
unsafe {
self.register(
sys::IORING_REGISTER_BUFFERS,
bufs.as_ptr().cast(),
bufs.len(),
)
}
.map(drop)
}
pub fn unregister_buffers(&self) -> Result<()> {
unsafe { self.register(sys::IORING_UNREGISTER_BUFFERS, ptr::null(), 0) }.map(drop)
}
pub fn register_files(&self, files: &[BorrowedHandle<'_>]) -> Result<()> {
unsafe {
self.register(
sys::IORING_REGISTER_FILES,
files.as_ptr().cast(),
files.len(),
)
}
.map(drop)
}
pub fn register_files_sparse(&self, count: u32) -> Result<()> {
let table = sys::RsrcRegister {
nr: count,
flags: sys::IORING_RSRC_REGISTER_SPARSE,
resv2: 0,
data: 0,
tags: 0,
};
unsafe {
self.register(
sys::IORING_REGISTER_FILES2,
(&raw const table).cast(),
size_of::<sys::RsrcRegister>(),
)
}
.map(drop)
.map_err(|error| self.or_unsupported(error, Opcode::Socket))
}
pub fn register_files_update(&self, offset: u32, files: &[FileSlot<'_>]) -> Result<usize> {
let update = sys::RsrcUpdate {
offset,
resv: 0,
data: files.as_ptr().addr() as u64,
};
unsafe {
self.register(
sys::IORING_REGISTER_FILES_UPDATE,
(&raw const update).cast(),
files.len(),
)
}
}
pub fn unregister_files(&self) -> Result<()> {
unsafe { self.register(sys::IORING_UNREGISTER_FILES, ptr::null(), 0) }.map(drop)
}
pub fn register_eventfd(&self, eventfd: impl AsHandle) -> Result<()> {
let fd = eventfd.as_handle().as_raw();
unsafe { self.register(sys::IORING_REGISTER_EVENTFD, (&raw const fd).cast(), 1) }.map(drop)
}
pub fn unregister_eventfd(&self) -> Result<()> {
unsafe { self.register(sys::IORING_UNREGISTER_EVENTFD, ptr::null(), 0) }.map(drop)
}
pub fn set_iowq_affinity(&self, mask: &[usize]) -> Result<()> {
unsafe {
self.register(
sys::IORING_REGISTER_IOWQ_AFF,
mask.as_ptr().cast(),
size_of_val(mask),
)
}
.map(drop)
.map_err(|error| self.iowq_unsupported(error))
}
pub fn clear_iowq_affinity(&self) -> Result<()> {
unsafe { self.register(sys::IORING_UNREGISTER_IOWQ_AFF, ptr::null(), 0) }
.map(drop)
.map_err(|error| self.iowq_unsupported(error))
}
fn iowq_unsupported(&self, error: Error) -> Error {
if error.raw_os_error() == crate::sys::errno::EINVAL
&& !self.features.contains(Features::RSRC_TAGS)
{
ErrorKind::Unsupported.into()
} else {
error
}
}
pub fn set_iowq_max_workers(&self, bounded: u32, unbounded: u32) -> Result<(u32, u32)> {
let mut limits = [bounded, unbounded];
unsafe {
self.register(
sys::IORING_REGISTER_IOWQ_MAX_WORKERS,
(&raw mut limits).cast(),
2,
)
}
.map_err(|error| self.or_unsupported(error, Opcode::Mkdirat))?;
Ok((limits[0], limits[1]))
}
pub fn register_ring_fd(&mut self) -> Result<()> {
if self.ring_index.is_some() {
return Err(ErrorKind::AlreadyExists.into());
}
let mut update = sys::RsrcUpdate {
offset: u32::MAX,
resv: 0,
data: self.fd.as_raw() as u64,
};
unsafe { self.register(sys::IORING_REGISTER_RING_FDS, (&raw mut update).cast(), 1) }
.map_err(|error| self.or_unsupported(error, Opcode::MsgRing))?;
self.ring_index = Some(update.offset);
Ok(())
}
pub fn unregister_ring_fd(&mut self) -> Result<()> {
let Some(index) = self.ring_index else {
return Err(ErrorKind::InvalidInput.into());
};
let update = sys::RsrcUpdate {
offset: index,
resv: 0,
data: 0,
};
unsafe {
self.register(
sys::IORING_UNREGISTER_RING_FDS,
(&raw const update).cast(),
1,
)
}?;
self.ring_index = None;
Ok(())
}
}
impl AsHandle for Ring {
#[inline]
fn as_handle(&self) -> BorrowedHandle<'_> {
self.fd.as_handle()
}
}
impl fmt::Debug for Ring {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ring")
.field("fd", &self.fd)
.field("sq_entries", &self.sq_entries)
.field("cq_entries", &self.cq_entries)
.field("features", &self.features)
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub struct Buf {
id: u16,
len: u32,
}
impl Buf {
#[inline]
pub const fn id(&self) -> u16 {
self.id
}
#[inline]
pub const fn len(&self) -> usize {
self.len as usize
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
}
pub struct BufRing {
fd: OwnedHandle,
group: u16,
count: u16,
buf_len: u32,
tail: u16,
held: u16,
entries: NonNull<sys::Buf>,
state: NonNull<u8>,
bufs: NonNull<u8>,
map: core::mem::ManuallyDrop<Map>,
}
unsafe impl Send for BufRing {}
unsafe impl Sync for BufRing {}
impl BufRing {
pub fn new(ring: &Ring, group: u16, count: u16, buf_len: u32) -> Result<Self> {
if !count.is_power_of_two() || count > 1 << 15 || buf_len == 0 {
return Err(ErrorKind::InvalidInput.into());
}
let page = crate::sys::mem::page_size();
let entries = usize::from(count);
let ring_len = (entries * size_of::<sys::Buf>() + entries).next_multiple_of(page);
let len = entries
.checked_mul(buf_len as usize)
.and_then(|bufs| bufs.checked_add(ring_len))
.filter(|len| *len <= isize::MAX as usize)
.ok_or(ErrorKind::InvalidInput)?;
let fd = crate::sys::io::duplicate(ring.as_handle())?;
let map = Map::anonymous(len)?;
let ring_entries: NonNull<sys::Buf> = map.at(0, entries)?;
let state = map.at(entries * size_of::<sys::Buf>(), entries)?;
let bufs = map.at(ring_len, len - ring_len)?;
let registration = sys::BufReg {
ring_addr: ring_entries.addr().get() as u64,
ring_entries: u32::from(count),
bgid: group,
flags: 0,
resv: [0; 3],
};
unsafe {
ring.register(
sys::IORING_REGISTER_PBUF_RING,
(&raw const registration).cast(),
1,
)
}
.map_err(|error| ring.or_unsupported(error, Opcode::Socket))?;
let mut this = Self {
fd,
group,
count,
buf_len,
tail: 0,
held: 0,
entries: ring_entries,
state,
bufs,
map: core::mem::ManuallyDrop::new(map),
};
for id in 0..count {
this.add(id);
}
Ok(this)
}
#[inline]
pub fn group(&self) -> u16 {
self.group
}
#[inline]
pub fn count(&self) -> u16 {
self.count
}
#[inline]
pub fn buf_len(&self) -> u32 {
self.buf_len
}
#[inline]
pub fn held(&self) -> u16 {
self.held
}
fn ring_tail(&self) -> &AtomicU16 {
unsafe {
self.entries
.cast::<u8>()
.add(sys::BUF_RING_TAIL)
.cast::<AtomicU16>()
.as_ref()
}
}
fn add(&mut self, id: u16) {
let place = usize::from(self.tail & (self.count - 1));
let addr = self.bufs.addr().get() + usize::from(id) * self.buf_len as usize;
unsafe {
let entry = self.entries.add(place).as_ptr();
(&raw mut (*entry).addr).write(addr as u64);
(&raw mut (*entry).len).write(self.buf_len);
(&raw mut (*entry).bid).write(id);
}
self.tail = self.tail.wrapping_add(1);
self.ring_tail().store(self.tail, Ordering::Release);
}
fn state(&self, id: u16) -> Option<NonNull<u8>> {
(id < self.count).then(|| unsafe { self.state.add(usize::from(id)) })
}
pub unsafe fn take(&mut self, cqe: &Cqe) -> Option<Buf> {
let id = cqe.buffer_id()?;
let state = self.state(id)?;
unsafe {
if state.read() != 0 {
return None;
}
state.write(1);
}
self.held += 1;
Some(Buf {
id,
len: (cqe.raw_result().max(0) as u32).min(self.buf_len),
})
}
pub fn bytes(&self, buf: &Buf) -> &[u8] {
match self.state(buf.id) {
Some(state) if unsafe { state.read() } != 0 => unsafe {
let start = self.bufs.add(usize::from(buf.id) * self.buf_len as usize);
core::slice::from_raw_parts(start.as_ptr(), buf.len.min(self.buf_len) as usize)
},
_ => &[],
}
}
pub fn give_back(&mut self, buf: Buf) {
let Some(state) = self.state(buf.id) else {
return;
};
unsafe {
if state.read() == 0 {
return;
}
state.write(0);
}
self.held -= 1;
self.add(buf.id);
}
}
impl Drop for BufRing {
fn drop(&mut self) {
let registration = sys::BufReg {
ring_addr: 0,
ring_entries: 0,
bgid: self.group,
flags: 0,
resv: [0; 3],
};
let gone = unsafe {
sys::register(
self.fd.as_raw(),
sys::IORING_UNREGISTER_PBUF_RING,
(&raw const registration).cast(),
1,
)
};
match gone {
Ok(_) => {}
Err(error) if error.raw_os_error() == crate::sys::errno::ENOENT => {}
Err(_) => return,
}
unsafe { core::mem::ManuallyDrop::drop(&mut self.map) };
}
}
impl fmt::Debug for BufRing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BufRing")
.field("group", &self.group)
.field("count", &self.count)
.field("buf_len", &self.buf_len)
.field("held", &self.held)
.finish_non_exhaustive()
}
}