dope-uring 0.77.0

Owned io_uring backend for dope
Documentation
mod create;
mod open;
mod source;

use std::{
    mem,
    num::NonZero,
    os::fd::{AsFd, AsRawFd as _, BorrowedFd, OwnedFd},
};

use dope_sys::{
    Errno,
    io::{
        fd,
        file::{self, metadata, watch::Event},
        pipe,
        reactor::{complete, submit},
        socket::addr,
    },
    kernel,
};
use o3::{alloc::BoxArrayExt as _, base::marker::ThreadBound};

use crate::{
    Backend,
    reactor::{op::sockets, sq},
};

#[repr(transparent)]
pub struct Metadata(pub(crate) mem::MaybeUninit<libc::statx>);

impl Metadata {
    pub const UNINIT: Self = Self(mem::MaybeUninit::uninit());
    pub(crate) const MASK: u32 = libc::STATX_TYPE | libc::STATX_SIZE;

    /// # Safety
    /// A successful native operation initialized this output and ended access.
    pub unsafe fn try_result(
        &self,
    ) -> Result<(file::Kind, file::Offset, Option<metadata::Identity>), metadata::Error> {
        // SAFETY: the successful native writer initialized the complete statx.
        let raw = unsafe { self.0.assume_init_ref() };
        if let Some(missing) = NonZero::new(Self::MASK & !raw.stx_mask) {
            return Err(metadata::Error::Missing(missing));
        }
        let size =
            file::Offset::new(raw.stx_size).ok_or(metadata::Error::Overflow(raw.stx_size))?;
        let identity = (raw.stx_mask & libc::STATX_INO != 0).then_some(metadata::Identity {
            device: libc::makedev(raw.stx_dev_major, raw.stx_dev_minor),
            inode: raw.stx_ino,
        });
        Ok((file::Kind::from_mode(raw.stx_mode.into()), size, identity))
    }
}

const _: () = {
    assert!(mem::size_of::<Metadata>() == 256);
    assert!(mem::align_of::<Metadata>() == 8);
};

pub(crate) fn pipe(flags: libc::c_int) -> Result<(OwnedFd, OwnedFd), pipe::Error> {
    let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit();
    // SAFETY: OwnedFd has RawFd's representation. Zero transfers both new descriptors.
    unsafe {
        let status = libc::pipe2(fds.as_mut_ptr().cast(), flags);
        kernel::raw::Status::new(status)
            .try_zero::<Backend, Errno>()
            .map_err(pipe::Error::Open)?;
        Ok(fds.assume_init().into())
    }
}

/// A deferred request whose host retains every encoded address.
#[derive(Debug)]
pub struct Deferred {
    slot: sq::Fixed,
    address: *const (),
    length: addr::Socklen,
    _thread: ThreadBound,
}

impl Deferred {
    /// # Safety
    /// Retain the address through completion or until this unsubmitted connect is dropped.
    pub unsafe fn new(slot: sq::Fixed, address: addr::Addr<'_>) -> Self {
        let (address, length) = address.parts();
        Self {
            slot,
            address,
            length,
            _thread: ThreadBound::NEW,
        }
    }

    pub(crate) fn submit<T: complete::raw::Token>(
        self,
        vacancy: sq::raw::Vacancy<'_, T>,
        token: T,
    ) {
        let mut entry = sq::Entry::new(sockets::CONNECT, sq::Descriptor::Fixed(self.slot));
        let fields = entry.fields();
        fields.command.address = self.address as u64;
        fields.command.offset = (self.length.get() as u64).to_ne_bytes();
        // SAFETY: construction retained this address through completion.
        unsafe { submit::raw::Vacancy::push(vacancy, sq::Borrowed::new(entry), token) };
    }
}

const CAPACITY: usize = 32 * 1024;

pub struct Stream {
    file: OwnedFd,
    buffer: Box<[mem::MaybeUninit<u8>; CAPACITY]>,
    offset: usize,
    filled: usize,
    _thread: ThreadBound,
}

#[repr(transparent)]
pub struct Watch {
    file: OwnedFd,
    thread: ThreadBound,
}

impl Watch {
    /// Observes moved-in entries and invalidation of one fixed directory.
    pub fn try_new(path: &std::ffi::CStr) -> Result<Self, Errno> {
        // SAFETY: init transfers one descriptor or leaves this thread's errno.
        let file = unsafe {
            <OwnedFd as fd::raw::Adopt>::try_adopt::<Backend, Errno>(libc::inotify_init1(
                libc::IN_NONBLOCK | libc::IN_CLOEXEC,
            ))
        }?;
        // SAFETY: the descriptor and terminated path stay live for this one registration.
        let raw = unsafe {
            libc::inotify_add_watch(
                file.as_raw_fd(),
                path.as_ptr(),
                libc::IN_MOVED_TO
                    | libc::IN_MOVE_SELF
                    | libc::IN_DELETE_SELF
                    | libc::IN_ONLYDIR
                    | libc::IN_DONT_FOLLOW,
            )
        };
        // SAFETY: add_watch returns a nonnegative watch id or -1 with unchanged errno.
        unsafe { kernel::raw::Status::new(raw).try_value::<Backend, Errno>() }?;
        Ok(Self {
            file,
            thread: ThreadBound::NEW,
        })
    }
}

impl AsFd for Watch {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.file.as_fd()
    }
}

pub struct Events<'a>(&'a [u8]);

impl<'a> Iterator for Events<'a> {
    type Item = Event<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.0.is_empty() {
            return None;
        }
        const HEADER: usize = mem::size_of::<libc::inotify_event>();
        // SAFETY: the retained native prefix consists of complete initialized records.
        let event = unsafe {
            self.0
                .as_ptr()
                .cast::<libc::inotify_event>()
                .read_unaligned()
        };
        // SAFETY: the native length bounds this complete record within the admitted read.
        let (record, rest) = unsafe { self.0.split_at_unchecked(HEADER + event.len as usize) };
        self.0 = rest;
        Some(match event.mask & !libc::IN_ISDIR {
            libc::IN_MOVED_TO => Event::MovedIn(&record[HEADER..]),
            libc::IN_Q_OVERFLOW => Event::Overflow,
            // SAFETY: every admitted native record carries a nonzero event mask.
            _ => Event::Invalidated(unsafe { NonZero::new_unchecked(event.mask) }),
        })
    }
}

// SAFETY: the stream exclusively owns its descriptor and buffer. Refilling only
// writes the buffer after the previous Entry borrow has ended.
// Watch owns its fixed descriptor; events retain the caller's admitted byte borrow.
unsafe impl file::raw::Directory for Backend {
    type Stream = Stream;
    type Watch = Watch;
    type Events<'a> = Events<'a>;

    unsafe fn watch_events<'a>(_: &Self::Watch, bytes: &'a [u8]) -> Self::Events<'a> {
        Events(bytes)
    }

    fn from_fd<E: From<Errno>>(file: OwnedFd) -> Result<Stream, file::OpenError<E>> {
        Ok(Stream {
            file,
            buffer: Box::try_uninit().map_err(file::OpenError::Allocation)?,
            offset: 0,
            filled: 0,
            _thread: ThreadBound::NEW,
        })
    }

    fn descriptor(stream: &Stream) -> kernel::raw::Descriptor {
        // SAFETY: the stream exclusively owns this live nonnegative descriptor.
        unsafe { kernel::raw::Descriptor::new(stream.file.as_raw_fd()) }
    }

    fn next(stream: &mut Stream) -> Result<Option<file::Entry<'_>>, Errno> {
        if stream.offset == stream.filled {
            // SAFETY: the exclusively borrowed buffer supplies exactly CAPACITY
            // writable bytes; getdents64 reports complete native directory records.
            let result = unsafe {
                libc::syscall(
                    libc::SYS_getdents64,
                    stream.file.as_raw_fd(),
                    stream.buffer.as_mut_ptr(),
                    CAPACITY,
                )
            };
            // SAFETY: the exact syscall operand bounds every successful count by
            // CAPACITY; failure leaves this thread's positive errno unchanged.
            let count = unsafe {
                kernel::raw::Status::from_count(result as libc::ssize_t).try_count::<Self, Errno>()
            };
            stream.filled = match count {
                Ok(count) => count.get(),
                Err(Errno::NOT_FOUND) => 0,
                Err(error) => return Err(error),
            };
            stream.offset = 0;
            if stream.filled == 0 {
                return Ok(None);
            }
        }
        // SAFETY: the completed batch retains this record's initialized native
        // fields and terminated name. Each positive d_reclen advances to the next
        // complete record or filled; the cursor cannot leave the completed batch.
        // Padding remains MaybeUninit and is never read or exposed as bytes.
        let pointer = unsafe {
            stream
                .buffer
                .as_ptr()
                .add(stream.offset)
                .cast::<libc::dirent64>()
        };
        stream.offset += unsafe { (&raw const (*pointer).d_reclen).read_unaligned() } as usize;
        let kind = unsafe { (&raw const (*pointer).d_type).read() };
        let name = unsafe { std::ffi::CStr::from_ptr((&raw const (*pointer).d_name).cast()) };
        Ok(Some(file::Entry {
            name,
            kind: file::Kind::from_dirent(kind),
        }))
    }
}