oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! POSIX asynchronous I/O, for `io::macos`.
//!
//! The kernel reads a control block when an operation is submitted (it
//! takes a copy, by its sources), and knows the operation by the *address*
//! of the block from then on: that is what `aio_error`, `aio_return`,
//! `aio_cancel` and `aio_suspend` look up.
//! An operation holds one of the places of the process (`kern.aioprocmax`)
//! from its submission until `aio_return` has taken its result.

// Without `alloc` there is no operation: only the limits are read.
#![cfg_attr(not(feature = "alloc"), allow(dead_code, unused_imports))]

use core::ffi::{c_char, c_int, c_void};
use core::time::Duration;

use crate::sys::{cvt, errno, last_error};
use crate::{Error, ErrorKind, Result};

/// `struct sigevent`: how the completion of an operation is told: not at
/// all (`SIGEV_NONE`, zero) or by a signal (`SIGEV_SIGNAL`), which is all
/// the kernel accepts.
#[repr(C)]
pub(crate) struct Sigevent {
    notify: c_int,
    signo: c_int,
    value: *mut c_void,
    notify_function: *mut c_void,
    notify_attributes: *mut c_void,
}

/// `struct aiocb`.
#[repr(C)]
pub(crate) struct Aiocb {
    fildes: c_int,
    offset: i64,
    buf: *mut c_void,
    nbytes: usize,
    reqprio: c_int,
    sigevent: Sigevent,
    lio_opcode: c_int,
}

// The layouts of <sys/aio.h> and <sys/signal.h>, which are the same on
// x86_64 and aarch64 (compiled and printed on both).
const _: () = assert!(size_of::<Sigevent>() == 32 && align_of::<Sigevent>() == 8);
const _: () = assert!(size_of::<Aiocb>() == 80 && align_of::<Aiocb>() == 8);
const _: () = assert!(core::mem::offset_of!(Aiocb, offset) == 8);
const _: () = assert!(core::mem::offset_of!(Aiocb, buf) == 16);
const _: () = assert!(core::mem::offset_of!(Aiocb, nbytes) == 24);
const _: () = assert!(core::mem::offset_of!(Aiocb, reqprio) == 32);
const _: () = assert!(core::mem::offset_of!(Aiocb, sigevent) == 40);
const _: () = assert!(core::mem::offset_of!(Aiocb, lio_opcode) == 72);

impl Aiocb {
    /// A block that describes nothing.
    pub(crate) const fn new() -> Self {
        Self {
            fildes: -1,
            offset: 0,
            buf: core::ptr::null_mut(),
            nbytes: 0,
            reqprio: 0,
            sigevent: Sigevent::new(None),
            lio_opcode: 0,
        }
    }

    /// Describes an operation on `fd`: `len` bytes at `buf`, at `offset`
    /// in the file.
    pub(crate) fn set(&mut self, fd: c_int, buf: *mut u8, len: usize, offset: i64) {
        self.fildes = fd;
        self.offset = offset;
        self.buf = buf.cast();
        // More than `INT_MAX` bytes is an invalid argument to the kernel:
        // a longer buffer is used in part, which is a short read or write.
        self.nbytes = len.min(MAX_LEN);
    }

    /// Says how the completion of the operation is told: by `signal`, or
    /// not at all.
    pub(crate) fn set_notice(&mut self, signal: Option<c_int>) {
        self.sigevent = Sigevent::new(signal);
    }

    /// Says what the block asks for when it is one of a list
    /// (`lio_listio`): a read or a write. A flush cannot be listed.
    pub(crate) fn set_listed(&mut self, request: Request) {
        self.lio_opcode = match request {
            Request::Read => LIO_READ,
            Request::Write => LIO_WRITE,
            Request::Sync | Request::SyncData => LIO_NOP,
        };
    }
}

impl Sigevent {
    const fn new(signal: Option<c_int>) -> Self {
        let (notify, signo) = match signal {
            Some(signal) => (SIGEV_SIGNAL, signal),
            None => (SIGEV_NONE, 0),
        };
        Self {
            notify,
            signo,
            value: core::ptr::null_mut(),
            notify_function: core::ptr::null_mut(),
            notify_attributes: core::ptr::null_mut(),
        }
    }
}

/// The kernel refuses to read or write more than `INT_MAX` bytes at once.
const MAX_LEN: usize = c_int::MAX as usize;

const SIGEV_NONE: c_int = 0;
const SIGEV_SIGNAL: c_int = 1;

/// What a block of a list asks for (`aio_lio_opcode`).
const LIO_NOP: c_int = 0;
const LIO_READ: c_int = 1;
const LIO_WRITE: c_int = 2;

/// Whether `lio_listio` returns once the operations are queued, or once
/// they are over.
const LIO_NOWAIT: c_int = 1;
const LIO_WAIT: c_int = 2;

/// `AIO_LISTIO_MAX`: how many blocks `lio_listio` takes. A constant of the
/// kernel, which no `sysctl` changes.
pub(crate) const LISTIO_MAX: usize = 16;

/// What `aio_cancel` answers.
const AIO_CANCELED: c_int = 2;

/// `aio_fsync` takes one of two open flags to say how much to write.
const O_SYNC: c_int = 0x80;
const O_DSYNC: c_int = 0x40_0000;

/// `struct timespec`.
#[repr(C)]
struct Timespec {
    sec: i64,
    nsec: i64,
}

unsafe extern "C" {
    fn aio_read(cb: *mut Aiocb) -> c_int;
    fn aio_write(cb: *mut Aiocb) -> c_int;
    fn aio_fsync(op: c_int, cb: *mut Aiocb) -> c_int;
    /// Returns the error number of the operation, `EINPROGRESS` while it
    /// runs, or -1 with `errno` when the kernel knows no such operation.
    fn aio_error(cb: *const Aiocb) -> c_int;
    fn aio_return(cb: *mut Aiocb) -> isize;
    fn aio_cancel(fd: c_int, cb: *mut Aiocb) -> c_int;
    fn aio_suspend(list: *const *const Aiocb, count: c_int, timeout: *const Timespec) -> c_int;
    fn lio_listio(
        mode: c_int,
        list: *const *mut Aiocb,
        count: c_int,
        notice: *mut Sigevent,
    ) -> c_int;
    fn sysctlbyname(
        name: *const c_char,
        old: *mut c_void,
        old_len: *mut usize,
        new: *mut c_void,
        new_len: usize,
    ) -> c_int;
}

/// What is to be done with a block.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Request {
    Read,
    Write,
    Sync,
    SyncData,
}

/// Submits the operation `cb` describes.
///
/// # Safety
///
/// `cb` must point to a block that stays at its address, as does the
/// buffer it names, until the operation is over and [`take`] has returned
/// its outcome.
pub(crate) unsafe fn submit(cb: *mut Aiocb, request: Request) -> Result<()> {
    // SAFETY: the caller's contract.
    cvt(unsafe {
        match request {
            Request::Read => aio_read(cb),
            Request::Write => aio_write(cb),
            Request::Sync => aio_fsync(O_SYNC, cb),
            Request::SyncData => aio_fsync(O_DSYNC, cb),
        }
    })?;
    Ok(())
}

/// Submits the operations the blocks of `list` describe, each of which
/// [`Aiocb::set_listed`] gave its request, with one call. With `wait` the
/// call returns when they are all over. `notice` is the signal sent when
/// the last of them is over, which replaces the notice of each block; it
/// is not used with `wait`.
///
/// An error does not say that nothing was submitted: [`submitted`] tells
/// of each block.
///
/// # Safety
///
/// As [`submit`], for every block of `list`, whatever this returns.
pub(crate) unsafe fn submit_list(
    list: &[*mut Aiocb],
    wait: bool,
    notice: Option<c_int>,
) -> Result<()> {
    let count = c_int::try_from(list.len()).map_err(|_| Error::from(ErrorKind::InvalidInput))?;
    let mut notice = notice
        .filter(|_| !wait)
        .map(|signal| Sigevent::new(Some(signal)));
    let notice = notice
        .as_mut()
        .map_or(core::ptr::null_mut(), |notice| notice as *mut _);
    let mode = if wait { LIO_WAIT } else { LIO_NOWAIT };
    // SAFETY: the list and the notice are read by the call; the rest is
    // the caller's contract.
    cvt(unsafe { lio_listio(mode, list.as_ptr(), count, notice) })?;
    Ok(())
}

/// Whether the kernel has an operation submitted with `cb` whose outcome
/// was not taken: what tells, after a list was refused in part, which of
/// its blocks were queued.
///
/// # Safety
///
/// `cb` must point to a block that is still allocated.
pub(crate) unsafe fn submitted(cb: *const Aiocb) -> bool {
    // SAFETY: the kernel looks the address up, and reads nothing there.
    unsafe { aio_error(cb) != -1 }
}

/// The outcome of the operation submitted with `cb`, which the kernel then
/// forgets; `None` while it runs.
///
/// # Safety
///
/// `cb` must be a block an operation was submitted with, whose outcome was
/// not taken yet.
pub(crate) unsafe fn take(cb: *mut Aiocb) -> Option<Result<usize>> {
    // SAFETY: the kernel looks the address up, and reads nothing there.
    let error = unsafe { aio_error(cb) };
    if error == errno::EINPROGRESS {
        return None;
    }
    if error == -1 {
        // The kernel knows no such operation: there is nothing to wait
        // for, and nothing to take.
        return Some(Err(last_error()));
    }
    // SAFETY: as above. This frees the place the operation held.
    let count = unsafe { aio_return(cb) };
    Some(if error != 0 {
        Err(Error::from_raw_os_error(error))
    } else if count < 0 {
        Err(last_error())
    } else {
        Ok(count as usize)
    })
}

/// Asks the kernel to give up the operation submitted with `cb` on `fd`.
/// Whether it did: an operation a thread of the kernel has started on is
/// not given up.
///
/// # Safety
///
/// `cb` must point to a block that is still allocated.
pub(crate) unsafe fn cancel(fd: c_int, cb: *mut Aiocb) -> Result<bool> {
    // SAFETY: the kernel reads the block to check the descriptor.
    let answer = cvt(unsafe { aio_cancel(fd, cb) })?;
    Ok(answer == AIO_CANCELED)
}

/// Waits until one of the operations of `list` is over, or `timeout`
/// passes: whether one is. Operations that are not listed do not end the
/// wait.
///
/// # Safety
///
/// Every block of `list` must be one whose operation was submitted and
/// whose outcome was not taken. (The kernel answers `EINVAL` when it knows
/// none of them.)
pub(crate) unsafe fn suspend(list: &[*const Aiocb], timeout: Option<Duration>) -> Result<bool> {
    let timeout = timeout.map(|timeout| Timespec {
        sec: i64::try_from(timeout.as_secs()).unwrap_or(i64::MAX),
        nsec: timeout.subsec_nanos().into(),
    });
    let timeout = timeout
        .as_ref()
        .map_or(core::ptr::null(), |t| t as *const _);
    let count = c_int::try_from(list.len()).map_err(|_| Error::from(ErrorKind::InvalidInput))?;
    // SAFETY: the list and the timeout are read by the call.
    match cvt(unsafe { aio_suspend(list.as_ptr(), count, timeout) }) {
        Ok(_) => Ok(true),
        // What the kernel says of a timeout that passed.
        Err(error) if error.raw_os_error() == errno::EAGAIN => Ok(false),
        Err(error) => Err(error),
    }
}

fn limit(name: &core::ffi::CStr) -> Result<u32> {
    let mut value: c_int = 0;
    let mut len = size_of::<c_int>();
    // SAFETY: the name is NUL-terminated, and the function writes at most
    // `len` bytes to `value`: the value is an `int`.
    cvt(unsafe {
        sysctlbyname(
            name.as_ptr(),
            (&raw mut value).cast(),
            &raw mut len,
            core::ptr::null_mut(),
            0,
        )
    })?;
    u32::try_from(value).map_err(|_| ErrorKind::Other.into())
}

/// `kern.aiomax`, `kern.aioprocmax`, `kern.aiothreads`.
pub(crate) fn limits() -> Result<(u32, u32, u32)> {
    Ok((
        limit(c"kern.aiomax")?,
        limit(c"kern.aioprocmax")?,
        limit(c"kern.aiothreads")?,
    ))
}