dope-uring 0.77.0

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

use dope_sys::{
    io::Close,
    memory,
    memory::{
        Context as _,
        buffer::{self, Index as _, provided},
    },
};

use crate::reactor::{
    buffers::{self, Open, Selected},
    cq::Buffer,
    mappings, ring,
};

#[repr(C)]
#[derive(Debug)]
struct Entry {
    addr: u64,
    len: u32,
    bid: Buffer,
    tail: u16,
}

#[derive(Debug)]
pub struct Producer<L: memory::raw::Receive> {
    entries: mappings::Buffer<Entry>,
    base: *const u8,
    layout: L,
    mask: num::NonZero<u16>,
    tail: u16,
    published: u16,
}

impl<L: memory::raw::Receive> provided::Producer for Producer<L> {
    type Layout = L;
    type Context = buffers::raw::Context<L>;
    type Error = Open<L>;

    fn new(context: &Self::Context) -> Result<Self, Self::Error> {
        let base = context.as_ptr();
        let layout = context.layout();
        let capacity = layout.capacity();
        let tail = layout.entries().get();
        let ring = tail.next_power_of_two();
        let mut entries = mappings::Buffer::<Entry>::allocate(usize::from(ring))?;
        // SAFETY: the fresh zeroed mapping holds exactly ring valid entries.
        // Rounding up the logical count covers the prefix before registration.
        let (offered, spare) = unsafe {
            slice::from_raw_parts_mut(entries.as_mut_ptr(), usize::from(ring))
                .split_at_mut_unchecked(usize::from(tail))
        };
        let mut bid = Buffer::ZERO;
        for entry in offered {
            entry.addr = bid.address(base, capacity) as u64;
            entry.len = capacity.get();
            entry.bid = bid;
            bid.advance();
        }
        for entry in spare {
            entry.len = capacity.get();
        }
        let producer = Self {
            entries,
            base,
            layout,
            // SAFETY: Layout admits 2..=32768, so the mask is in 1..=32767.
            mask: unsafe { num::NonZero::new_unchecked(ring - 1) },
            tail,
            published: tail,
        };
        producer.publish(tail);
        Ok(producer)
    }

    fn flush(&mut self) {
        if self.tail == self.published {
            return;
        }
        self.publish(self.tail);
        self.published = self.tail;
    }

    fn layout(&self) -> L {
        self.layout
    }
}

impl<L: memory::raw::Receive> Producer<L> {
    pub(in crate::reactor) fn into_region(self) -> mappings::Region {
        self.entries.into_region()
    }

    pub(in crate::reactor) fn registration(&self, group: u16) -> ring::ffi::Buffers {
        ring::ffi::Buffers {
            ring_address: self.entries.as_ptr() as u64,
            ring_entries: u32::from(self.mask.get()) + 1,
            group,
            flags: 0,
            reserved: [0; 3],
        }
    }

    /// # Safety
    /// Return this producer's selected BID exactly once after all access has ended.
    pub(crate) unsafe fn defer(&mut self, bid: Buffer) {
        let tail = self.tail;
        let position = tail & self.mask.get();
        // SAFETY: the caller returns this producer's unique slot;
        // the mask selects a vacant cell. Non-incremental, single-buffer
        // receives leave its installed length intact, including on short I/O.
        unsafe {
            let entry = self.entries.as_mut_ptr().add(usize::from(position));
            (&raw mut (*entry).addr).write(bid.address(self.base, self.layout.capacity()) as u64);
            (&raw mut (*entry).bid).write(bid);
        }
        self.tail = tail.wrapping_add(1);
    }

    fn publish(&self, value: u16) {
        // SAFETY: the nonempty ring's first tail has AtomicU16 size/alignment.
        unsafe {
            use atomic::{AtomicU16, Ordering};

            let entry = self.entries.as_ptr().cast_mut();
            AtomicU16::from_ptr(&raw mut (*entry).tail).store(value, Ordering::Release);
        }
    }
}

impl<L: memory::raw::Receive> buffer::raw::Select for Producer<L> {
    type Pending = Selected<L::Extent, <L::Extent as memory::raw::Extent>::Capacity>;
    type Index = Buffer;

    unsafe fn select(&self, buffer: Self::Index) -> Result<Self::Pending, Self::Index> {
        if buffer.is_within(self.layout.entries()) {
            return Ok(Selected {
                index: buffer,
                len: self.layout.limit(),
                extent: marker::PhantomData,
            });
        }
        Err(buffer)
    }
}

impl<L: memory::raw::Receive, E: memory::raw::Extent, N: Copy> memory::raw::Release<Selected<E, N>>
    for Producer<L>
{
    unsafe fn release(&mut self, buffer: Selected<E, N>) {
        // SAFETY: this consumes the unique selected slot from the caller's paired producer.
        unsafe { self.defer(buffer.index) }
    }
}

impl<L: memory::raw::Receive> Close for Producer<L> {
    type State = <mappings::Region as Close>::State;

    fn try_close(self) -> Result<(), Self::State> {
        self.entries.try_close()
    }
}

const _: () = {
    assert!(mem::size_of::<Entry>() == 16);
    assert!(mem::align_of::<Entry>() == 8);
    assert!(mem::offset_of!(Entry, addr) == 0);
    assert!(mem::offset_of!(Entry, len) == 8);
    assert!(mem::offset_of!(Entry, bid) == 12);
    assert!(mem::offset_of!(Entry, tail) == 14);
    assert!(mem::size_of::<atomic::AtomicU16>() == mem::size_of::<u16>());
    assert!(mem::align_of::<atomic::AtomicU16>() == mem::align_of::<u16>());
};