dope-uring 0.76.0

Owned io_uring backend for dope
Documentation
use std::{marker, num::NonZero};

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

use crate::reactor::{
    cq, ring,
    ring::{Cleanup, Error, Ring, map},
    sq,
};

#[derive(Clone, Copy, Debug)]
pub(crate) struct Axis {
    entries: NonZero<u32>,
    mask: u32,
}

impl Axis {
    fn round(region: Region, count: NonZero<u32>) -> Result<Self, Layout> {
        let entries = count.checked_next_power_of_two().ok_or(Layout::Entries {
            region,
            actual: bounded::raw::U32::clamp(count.get() as usize),
        })?;
        Ok(Self {
            entries,
            mask: entries.get() - 1,
        })
    }

    fn check(self, region: Region, actual: u32) -> Result<(), Layout> {
        if actual == self.entries.get() {
            return Ok(());
        }
        Err(Layout::Entries {
            region,
            actual: bounded::raw::U32::clamp(actual as usize),
        })
    }

    pub(crate) const fn entries(self) -> NonZero<u32> {
        self.entries
    }

    pub(crate) const fn mask(self) -> u32 {
        self.mask
    }
}

pub(in crate::reactor::ring) struct Plan {
    sq: Axis,
    cq: Axis,
    maps: map::Set,
}

impl Plan {
    /// 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 ring::ffi::{self, Map};

        let sq = Axis::round(Region::Submission, sq_count).map_err(Error::Layout)?;
        let cq = Axis::round(Region::Completion, cq_count).map_err(Error::Layout)?;
        let sqe_len =
            Map::extent::<sq::Entry>(Region::Entries, 0, sq.entries).map_err(Error::Layout)?;
        let ring_len = Map::extent::<cq::Entry<()>>(Region::Completion, 320, cq.entries)
            .map_err(Error::Layout)?;
        let sqes = Map::new(Region::Entries, sqe_len).map_err(|open| open.recover(None))?;
        let rings = match Map::new(Region::Submission, ring_len) {
            Ok(rings) => rings,
            Err(open) => return Err(open.recover(Some(sqes))),
        };
        let plan = Self {
            sq,
            cq,
            maps: map::Set {
                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 = plan.maps.entries.address();
        params.cq_off.user_address = plan.maps.rings.address();
        let fd = match ffi::Fd::setup(sq_count, &mut params) {
            Ok(fd) => fd,
            Err(cause) => {
                return Err(Cleanup::finish(
                    None,
                    Cause::Setup(cause),
                    plan.maps.try_close(),
                ));
            }
        };
        let (sq, cq) = match plan.queues(&params) {
            Ok(queues) => queues,
            Err(cause) => {
                return Err(Cleanup::finish(
                    Some(fd),
                    Cause::Layout(cause),
                    plan.maps.try_close(),
                ));
            }
        };
        Ok(Ring {
            fd,
            mapped: map::Mapped {
                sq,
                completion: cq,
                maps: plan.maps,
            },
            features: params.features,
            local: marker::PhantomData,
        })
    }

    fn queues(
        &self,
        params: &ring::ffi::Parameters,
    ) -> Result<(sq::raw::State, cq::raw::State), Layout> {
        let submit = Region::Submission;
        let complete = Region::Completion;
        self.sq.check(submit, params.sq_entries)?;
        self.cq.check(complete, params.cq_entries)?;
        let rings = &self.maps.rings;
        let sq = rings.indices(submit, params.sq_off.head, params.sq_off.tail)?;
        let flags = rings.at(submit, params.sq_off.flags, NonZero::<u32>::MIN)?;
        let cq = rings.indices(complete, params.cq_off.head, params.cq_off.tail)?;
        let entries = rings.at(complete, params.cq_off.cqes, self.cq.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(self.sq, sq, flags, self.maps.entries.sqes()),
                cq::raw::State::new(self.cq, cq, entries),
            )
        })
    }
}