dope-uring 0.77.0

Owned io_uring backend for dope
Documentation
mod thread;
mod timer;

pub(crate) use timer::Timer;

use std::{iter, mem, ops, os::fd, ptr};

use dope_sys::{
    Errno, kernel,
    thread::{
        Thread, affinity,
        signal::{self, Acquire},
    },
};
use linux_raw_sys::general;
use o3::{
    base::{marker::ThreadBound, num::bounded},
    mem::slot,
};

use crate::Backend;

pub(crate) fn has_crc32() -> bool {
    // SAFETY: AArch64 AT_HWCAP is immutable loader data; HWCAP_CRC32 is bit 7.
    (unsafe { libc::getauxval(libc::AT_HWCAP) } & (1 << 7)) != 0
}

pub struct Cpus {
    mask: libc::cpu_set_t,
    indices: ops::Range<u16>,
    remaining: u16,
}

impl Cpus {
    const LIMIT: u16 = {
        assert!(libc::CPU_SETSIZE > 0 && (libc::CPU_SETSIZE as usize) <= u16::MAX as usize);
        libc::CPU_SETSIZE as u16
    };

    fn consume(&mut self, cpu: u16) -> affinity::raw::Cpu {
        self.remaining -= 1;
        // SAFETY: both ends of the mask iterator only yield admitted CPU indices.
        unsafe { affinity::raw::Cpu::new(cpu) }
    }

    fn contains(mask: &libc::cpu_set_t, cpu: u16) -> bool {
        // SAFETY: the iterator bounds every index by CPU_SETSIZE and current()
        // initialized the mask.
        unsafe {
            let cpu = bounded::raw::U32::<0, { Self::LIMIT as u32 - 1 }>::from_proven(cpu.into());
            libc::CPU_ISSET(cpu.into_usize(), mask)
        }
    }
}

impl Iterator for Cpus {
    type Item = affinity::raw::Cpu;

    fn next(&mut self) -> Option<Self::Item> {
        let cpu = self.indices.find(|&cpu| Self::contains(&self.mask, cpu))?;
        Some(self.consume(cpu))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = usize::from(self.remaining);
        (len, Some(len))
    }
}

impl DoubleEndedIterator for Cpus {
    fn next_back(&mut self) -> Option<Self::Item> {
        let cpu = self.indices.rfind(|&cpu| Self::contains(&self.mask, cpu))?;
        Some(self.consume(cpu))
    }
}

impl ExactSizeIterator for Cpus {}
impl iter::FusedIterator for Cpus {}

type SavedMask = mem::MaybeUninit<[u8; general::_NSIG.div_ceil(u8::BITS) as usize]>;

#[derive(Debug)]
pub struct Receiver {
    fd: fd::OwnedFd,
    previous: SavedMask,
    _thread: ThreadBound,
}

impl fd::AsFd for Receiver {
    fn as_fd(&self) -> fd::BorrowedFd<'_> {
        self.fd.as_fd()
    }
}

const _: () = {
    assert!(size_of::<SavedMask>() <= size_of::<libc::sigset_t>());
    assert!(size_of::<Option<Receiver>>() == size_of::<Receiver>());
};

// SAFETY: PID/TID equality identifies the original thread. Mask installation
// is the last fallible operation and its previous value stays in this receiver.
unsafe impl signal::raw::Receiver for Receiver {
    fn is_main() -> bool {
        // SAFETY: both calls query native identity without borrowing caller storage.
        unsafe { libc::syscall(libc::SYS_gettid) == libc::getpid() as libc::c_long }
    }

    unsafe fn try_new(
        vacant: slot::raw::Vacant<'_, Self>,
    ) -> Result<slot::Occupied<'_, Self>, signal::raw::Rejected<'_, Self>> {
        use dope_sys::io::fd::raw::Adopt;

        let mut mask = mem::MaybeUninit::<libc::sigset_t>::uninit();
        // SAFETY: libc initializes this set in place; both signals are valid.
        // signalfd transfers an fd or sets errno. Only native code reads the opaque mask.
        let fd = unsafe {
            libc::sigemptyset(mask.as_mut_ptr());
            libc::sigaddset(mask.as_mut_ptr(), libc::SIGTERM);
            libc::sigaddset(mask.as_mut_ptr(), libc::SIGINT);
            let raw = libc::signalfd(-1, mask.as_ptr(), libc::SFD_CLOEXEC | libc::SFD_NONBLOCK);
            fd::OwnedFd::try_adopt::<Backend, Errno>(raw)
        }
        .map_err(Acquire::SignalFd)?;
        let mut previous = mem::MaybeUninit::<libc::sigset_t>::uninit();
        // SAFETY: libc gets a full output object. Its kernel mask occupies the
        // leading bytes in native word order; SavedMask has byte alignment.
        let previous = unsafe {
            let code = libc::pthread_sigmask(libc::SIG_BLOCK, mask.as_ptr(), previous.as_mut_ptr());
            kernel::raw::Status::new(code)
                .try_pthread()
                .map_err(Acquire::MaskBlock)?;
            previous.as_ptr().cast::<SavedMask>().read()
        };
        Ok(vacant.insert(Self {
            fd,
            previous,
            _thread: ThreadBound::NEW,
        }))
    }

    fn try_wait<B: Thread<Receiver = Self>>(source: &signal::Source<'_, B>) -> Result<(), Errno> {
        use std::os::fd::{AsFd as _, AsRawFd as _};

        let mut info = mem::MaybeUninit::<libc::signalfd_siginfo>::uninit();
        const SIZE: libc::c_int = mem::size_of::<libc::signalfd_siginfo>() as libc::c_int;
        // SAFETY: the borrowed signalfd supplies one complete writable record or sets errno.
        unsafe {
            let len = libc::read(
                source.as_fd().as_raw_fd(),
                info.as_mut_ptr().cast(),
                SIZE as usize,
            );
            kernel::raw::Status::from_count(len)
                .admit_exact::<SIZE>()
                .try_admit::<Backend, Errno>()
        }
    }

    fn restore(&self) -> Result<(), signal::ReleaseFault> {
        let mut previous = mem::MaybeUninit::<libc::sigset_t>::zeroed();
        // SAFETY: the saved kernel bytes fit this native object. libc receives
        // its full extent, including initialized space beyond the kernel mask.
        unsafe {
            previous
                .as_mut_ptr()
                .cast::<SavedMask>()
                .write(self.previous);
            let code = libc::pthread_sigmask(libc::SIG_SETMASK, previous.as_ptr(), ptr::null_mut());
            kernel::raw::Status::new(code).try_pthread()
        }
        .map_err(signal::ReleaseFault::Mask)
    }
}