oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `sync` on Linux: `futex`, in its 64-bit time variant on 32-bit
//! architectures.

use core::sync::atomic::AtomicU32;
use core::time::Duration;

use crate::Result;
use crate::sys::time::Timespec;
use crate::sys::{errno, syscall};

// include/uapi/linux/futex.h
const FUTEX_WAIT: u32 = 0;
const FUTEX_WAKE: u32 = 1;
const FUTEX_PRIVATE_FLAG: u32 = 128;

/// Whether the wait ended otherwise than by its timeout.
pub(crate) fn wait(atomic: &AtomicU32, expected: u32, timeout: Option<Duration>) -> Result<bool> {
    // A relative timeout, on CLOCK_MONOTONIC; seconds beyond what the kernel
    // counts saturate to its "never".
    let timeout = timeout.map(Timespec::from_duration);
    let timeout = timeout
        .as_ref()
        .map_or(core::ptr::null(), core::ptr::from_ref);
    let op = FUTEX_WAIT | FUTEX_PRIVATE_FLAG;
    // SAFETY: the kernel reads the atomic, which is borrowed, and one
    // `__kernel_timespec` if the pointer is not null.
    #[cfg(target_pointer_width = "32")]
    let result = unsafe { syscall!(FUTEX_TIME64, atomic.as_ptr(), op, expected, timeout) };
    // SAFETY: as above; `timespec` has that layout on 64-bit architectures.
    #[cfg(target_pointer_width = "64")]
    let result = unsafe { syscall!(FUTEX, atomic.as_ptr(), op, expected, timeout) };
    match result {
        Ok(_) => Ok(true),
        Err(e) => match e.raw_os_error() {
            // The value was not the expected one, or a signal handler ran.
            errno::EAGAIN | errno::EINTR => Ok(true),
            errno::ETIMEDOUT => Ok(false),
            _ => Err(e),
        },
    }
}

pub(crate) fn wake(atomic: &AtomicU32, all: bool) {
    let count = if all { i32::MAX } else { 1 };
    let op = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
    // SAFETY: the kernel only uses the address as a key. FUTEX_WAKE takes no
    // timeout, so the call is the same on every architecture; it cannot fail
    // for a valid address.
    #[cfg(target_pointer_width = "32")]
    let _ = unsafe { syscall!(FUTEX_TIME64, atomic.as_ptr(), op, count) };
    // SAFETY: as above.
    #[cfg(target_pointer_width = "64")]
    let _ = unsafe { syscall!(FUTEX, atomic.as_ptr(), op, count) };
}