dope-uring 0.77.0

Owned io_uring backend for dope
Documentation
use std::{
    marker, mem,
    num::{self, NonZero},
    ptr,
    sync::atomic,
};

use dope_sys::{
    io::Close,
    ring::{
        create::Cause,
        layout::{Layout, Region},
    },
};
use o3::base::num::bounded;

use crate::{
    Mapping,
    reactor::{
        cq, mappings,
        ring::{self, Axis, Cleanup, Error, Ring, map},
        sq,
    },
};

#[derive(Debug)]
pub(crate) struct Map {
    rings: mappings::Buffer<u8>,
    entries: mappings::Buffer<u8>,
}

impl Map {
    fn reserve(region: Region, len: NonZero<usize>) -> Result<mappings::Buffer<u8>, map::Open> {
        let owned = mappings::Region::reserve::<0>(len).map_err(|code| {
            map::Open::Failure(Mapping::Syscall {
                region,
                len,
                code: code.into(),
            })
        })?;
        match owned.admit() {
            Ok(buffer) => Ok(buffer),
            Err(null) => {
                let failure = Mapping::Null { region, len };
                Err(match null.try_close() {
                    Ok(()) => map::Open::Failure(failure),
                    Err(unmap) => map::Open::Cleanup { failure, unmap },
                })
            }
        }
    }

    /// Reserves liburing 2.6's 320-byte shared header allowance without the SQ index array.
    pub(in crate::reactor::ring) fn open<T>(
        sq_count: NonZero<u32>,
        cq_count: NonZero<u32>,
        taskrun: bool,
    ) -> Result<Ring<T>, Error> {
        use crate::reactor::ring::ffi;

        let sq = Axis::round(Region::Submission, sq_count)?;
        let cq = Axis::round(Region::Completion, cq_count)?;
        let sqe_len = Self::extent::<sq::Entry>(Region::Entries, 0, sq.entries())?;
        let ring_len = Self::extent::<cq::Entry<()>>(Region::Completion, 320, cq.entries())?;
        let sqes = Self::reserve(Region::Entries, sqe_len).map_err(|open| open.recover(None))?;
        let rings = match Self::reserve(Region::Submission, ring_len) {
            Ok(rings) => rings,
            Err(open) => return Err(open.recover(Some(sqes))),
        };
        let maps = Self {
            rings,
            entries: sqes,
        };
        let mut flags = ffi::SETUP_SUBMIT_ALL
            | ffi::SETUP_SINGLE_ISSUER
            | ffi::SETUP_NO_SQARRAY
            | ffi::SETUP_CQSIZE
            | ffi::SETUP_NO_MMAP;
        if taskrun {
            flags |= ffi::SETUP_DEFER_TASKRUN | ffi::SETUP_TASKRUN_FLAG;
        }
        let mut params = ffi::Parameters {
            flags,
            cq_entries: cq_count.get(),
            ..ffi::Parameters::default()
        };
        params.sq_off.user_address = maps.entries.as_ptr() as u64;
        params.cq_off.user_address = maps.rings.as_ptr() as u64;
        let fd = match ffi::Fd::setup(sq_count, &mut params) {
            Ok(fd) => fd,
            Err(cause) => {
                return Err(Cleanup::finish(None, Cause::Setup(cause), maps.try_close()));
            }
        };
        let (sq, cq) = match maps.queues(sq, cq, &params) {
            Ok(queues) => queues,
            Err(cause) => {
                return Err(Cleanup::finish(
                    Some(fd),
                    Cause::Layout(cause),
                    maps.try_close(),
                ));
            }
        };
        Ok(Ring {
            fd,
            mapped: map::Mapped {
                sq,
                completion: cq,
                maps,
            },
            features: params.features,
            local: marker::PhantomData,
        })
    }

    pub(in crate::reactor::ring) fn try_close(self) -> Result<(), map::Closing> {
        map::Closing::close(self.entries, Some(self.rings))
    }

    fn extent<T>(
        region: Region,
        offset: u32,
        entries: num::NonZero<u32>,
    ) -> Result<num::NonZero<usize>, Layout> {
        const { assert!(mem::size_of::<T>() > 0) };
        let stride = num::NonZero::<usize>::MIN.saturating_add(mem::size_of::<T>() - 1);
        let width = num::NonZero::<usize>::MIN.saturating_add(entries.get() as usize - 1);
        width
            .checked_mul(stride)
            .and_then(|bytes| bytes.checked_add(offset as usize))
            .ok_or_else(|| Layout::Overflow {
                region,
                offset: bounded::raw::U32::clamp(offset as usize),
                entries: bounded::raw::U32::clamp(entries.get() as usize),
                stride: Self::size(stride.get()),
            })
    }

    fn size(value: usize) -> bounded::U64<0, { u64::MAX }> {
        const { assert!(usize::BITS <= u64::BITS) };
        bounded::U64::clamp(value as u64)
    }

    fn at<T>(
        &self,
        region: Region,
        offset: u32,
        count: num::NonZero<u32>,
    ) -> Result<ptr::NonNull<T>, Layout> {
        let end = Self::extent::<T>(region, offset, count)?.get();
        let start = offset as usize;
        let align = mem::align_of::<T>();
        if !start.is_multiple_of(align) || end > self.rings.bytes().get() {
            return Err(Layout::Offset {
                region,
                offset: bounded::raw::U32::clamp(start),
                bytes: Self::size(end - start),
                maximum: Self::size(self.rings.bytes().get()),
                alignment: Self::size(align),
            });
        }
        // SAFETY: the nonempty field lies in this mapping, aligned to its ABI type.
        Ok(unsafe { self.rings.base().add(start).cast::<T>() })
    }

    fn indices(
        &self,
        region: Region,
        head: u32,
        tail: u32,
    ) -> Result<[ptr::NonNull<atomic::AtomicU32>; 2], Layout> {
        Ok([
            self.at(region, head, num::NonZero::<u32>::MIN)?,
            self.at(region, tail, num::NonZero::<u32>::MIN)?,
        ])
    }

    fn queues(
        &self,
        submit: Axis,
        complete: Axis,
        params: &ring::ffi::Parameters,
    ) -> Result<(sq::raw::State, cq::raw::State), Layout> {
        let input = Region::Submission;
        let finish = Region::Completion;
        submit.check(input, params.sq_entries)?;
        complete.check(finish, params.cq_entries)?;
        let sq = self.indices(input, params.sq_off.head, params.sq_off.tail)?;
        let flags = self.at(input, params.sq_off.flags, NonZero::<u32>::MIN)?;
        let cq = self.indices(finish, params.cq_off.head, params.cq_off.tail)?;
        let entries = self.at(finish, params.cq_off.cqes, complete.entries())?;
        // SAFETY: the SQE mapping starts on a page boundary and was allocated for this exact axis.
        // Both rings' aligned fields and the entire CQ array are in the live shared mapping.
        // The sole caller transfers both mappings with these states into the same exclusive Ring.
        Ok(unsafe {
            (
                sq::raw::State::new(submit, sq, flags, self.entries.base().cast()),
                cq::raw::State::new(complete, cq, entries),
            )
        })
    }
}