oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `time` on Linux: `clock_gettime`, `clock_getres` and `clock_nanosleep`,
//! in their 64-bit time variants on 32-bit architectures.
//!
//! Clocks are read through the vDSO where it has the function (see
//! [`vdso`]), which answers without entering the kernel for the wall clock
//! and the monotonic ones, and with the system call otherwise: when there is
//! no vDSO or it cannot be found, and when its function fails.

use core::time::Duration;

use crate::sys::{syscall, vdso};
use crate::time::{Clock, Timestamp};
use crate::{ErrorKind, Result};

// include/uapi/linux/time.h
const CLOCK_REALTIME: u32 = 0;
const CLOCK_MONOTONIC: u32 = 1;
const CLOCK_PROCESS_CPUTIME_ID: u32 = 2;
const CLOCK_THREAD_CPUTIME_ID: u32 = 3;
const CLOCK_BOOTTIME: u32 = 7;
const TIMER_ABSTIME: u32 = 1;

/// `struct __kernel_timespec`: what the `*_time64` calls of 32-bit
/// architectures take, and the layout of `struct timespec` on 64-bit ones.
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct Timespec {
    pub(crate) sec: i64,
    pub(crate) nsec: i64,
}

impl Timespec {
    /// The duration as a `timespec`; seconds beyond `i64` saturate, and the
    /// kernel saturates what it cannot count in turn.
    pub(crate) fn from_duration(duration: Duration) -> Self {
        Self {
            sec: i64::try_from(duration.as_secs()).unwrap_or(i64::MAX),
            nsec: duration.subsec_nanos().into(),
        }
    }

    fn to_duration(self) -> Result<Duration> {
        match (u64::try_from(self.sec), u32::try_from(self.nsec)) {
            (Ok(sec), Ok(nsec)) if nsec < 1_000_000_000 => Ok(Duration::new(sec, nsec)),
            _ => Err(ErrorKind::Other.into()),
        }
    }
}

/// Reads a clock, without entering the kernel when the vDSO can do it.
fn gettime(id: u32) -> Result<Timespec> {
    if let Some(clock_gettime) = vdso::clock_gettime() {
        let mut ts = Timespec::default();
        // SAFETY: the vDSO's function writes one `__kernel_timespec` to
        // `ts`, and needs nothing but the C calling convention.
        if unsafe { clock_gettime(id as i32, &raw mut ts) } == 0 {
            return Ok(ts);
        }
        // Anything else (`-ENOSYS` for a clock the vDSO does not serve, or
        // a real error) is for the system call to report.
    }
    gettime_syscall(id)
}

/// Reads a clock with the system call.
fn gettime_syscall(id: u32) -> Result<Timespec> {
    let mut ts = Timespec::default();
    // SAFETY: the kernel writes one `__kernel_timespec` to `ts`.
    #[cfg(target_pointer_width = "32")]
    unsafe { syscall!(CLOCK_GETTIME64, id, &raw mut ts) }?;
    // SAFETY: as above; `timespec` has that layout on 64-bit architectures.
    #[cfg(target_pointer_width = "64")]
    unsafe { syscall!(CLOCK_GETTIME, id, &raw mut ts) }?;
    Ok(ts)
}

fn clock_id(clock: Clock) -> u32 {
    match clock {
        Clock::Monotonic => CLOCK_MONOTONIC,
        Clock::Boottime => CLOCK_BOOTTIME,
        Clock::ProcessCpu => CLOCK_PROCESS_CPUTIME_ID,
        Clock::ThreadCpu => CLOCK_THREAD_CPUTIME_ID,
    }
}

pub(crate) fn now() -> Result<Timestamp> {
    let ts = gettime(CLOCK_REALTIME)?;
    match u32::try_from(ts.nsec) {
        Ok(nanos) if nanos < 1_000_000_000 => Ok(Timestamp {
            secs: ts.sec,
            nanos,
        }),
        _ => Err(ErrorKind::Other.into()),
    }
}

pub(crate) fn clock(clock: Clock) -> Result<Duration> {
    gettime(clock_id(clock))?.to_duration()
}

pub(crate) fn resolution(clock: Clock) -> Result<Duration> {
    let mut ts = Timespec::default();
    // SAFETY: the kernel writes one `__kernel_timespec` to `ts`.
    #[cfg(target_pointer_width = "32")]
    unsafe { syscall!(CLOCK_GETRES_TIME64, clock_id(clock), &raw mut ts) }?;
    // SAFETY: as above; `timespec` has that layout on 64-bit architectures.
    #[cfg(target_pointer_width = "64")]
    unsafe { syscall!(CLOCK_GETRES, clock_id(clock), &raw mut ts) }?;
    ts.to_duration()
}

fn nanosleep(flags: u32, time: Duration) -> Result<()> {
    let ts = Timespec::from_duration(time);
    // SAFETY: the kernel reads one `__kernel_timespec` from `ts`; no
    // remaining time is asked for.
    #[cfg(target_pointer_width = "32")]
    unsafe {
        syscall!(
            CLOCK_NANOSLEEP_TIME64,
            CLOCK_MONOTONIC,
            flags,
            &raw const ts,
            0
        )
    }?;
    // SAFETY: as above; `timespec` has that layout on 64-bit architectures.
    #[cfg(target_pointer_width = "64")]
    unsafe { syscall!(CLOCK_NANOSLEEP, CLOCK_MONOTONIC, flags, &raw const ts, 0) }?;
    Ok(())
}

pub(crate) fn sleep(duration: Duration) -> Result<()> {
    nanosleep(0, duration)
}

pub(crate) fn sleep_until(deadline: Duration) -> Result<()> {
    nanosleep(TIMER_ABSTIME, deadline)
}

#[cfg(test)]
mod tests {
    use super::*;

    const CLOCKS: [u32; 5] = [
        CLOCK_REALTIME,
        CLOCK_MONOTONIC,
        CLOCK_PROCESS_CPUTIME_ID,
        CLOCK_THREAD_CPUTIME_ID,
        CLOCK_BOOTTIME,
    ];

    fn nanos(ts: Timespec) -> i128 {
        assert!((0..1_000_000_000).contains(&ts.nsec));
        i128::from(ts.sec) * 1_000_000_000 + i128::from(ts.nsec)
    }

    /// The vDSO and the system call read the same clocks. Whether there is
    /// a vDSO function depends on the kernel and the emulator (see the
    /// `lookup` test of `vdso`); either way `gettime` must agree with the
    /// system call.
    #[test]
    fn vdso_agrees_with_syscall() {
        let fast = vdso::clock_gettime();
        for id in CLOCKS {
            for _ in 0..100 {
                let before = nanos(gettime_syscall(id).unwrap());
                let reading = nanos(gettime(id).unwrap());
                let after = nanos(gettime_syscall(id).unwrap());
                if id == CLOCK_REALTIME {
                    // The wall clock may be set between two readings, though
                    // hardly by much.
                    let tolerance = 5_000_000_000;
                    assert!((reading - before).abs() < tolerance);
                    assert!((after - reading).abs() < tolerance);
                } else {
                    // The others only go forwards, whoever reads them.
                    assert!(before <= reading, "clock {id}: {before} > {reading}");
                    assert!(reading <= after, "clock {id}: {reading} > {after}");
                }
                if let Some(fast) = fast {
                    // The function itself, not the fallback behind it.
                    let mut ts = Timespec::default();
                    // SAFETY: as in `gettime`.
                    assert_eq!(unsafe { fast(id as i32, &raw mut ts) }, 0, "clock {id}");
                    if id != CLOCK_REALTIME {
                        assert!(nanos(ts) >= reading, "clock {id}");
                    }
                }
            }
        }
    }

    #[test]
    fn vdso_errors_are_the_system_calls() {
        // No such clock: the vDSO refuses, and the error reported is the
        // system call's.
        let id = 0x7fff_0000;
        assert_eq!(gettime(id).map(|_| ()), gettime_syscall(id).map(|_| ()));
        assert_eq!(
            gettime(id).map(|_| ()).unwrap_err().kind(),
            ErrorKind::InvalidInput
        );
        if let Some(fast) = vdso::clock_gettime() {
            let mut ts = Timespec::default();
            // SAFETY: as in `gettime`.
            assert_ne!(unsafe { fast(id as i32, &raw mut ts) }, 0);
        }
    }

    #[test]
    fn readings_never_go_backwards() {
        for id in [CLOCK_MONOTONIC, CLOCK_BOOTTIME] {
            let mut last = nanos(gettime(id).unwrap());
            for i in 0..200_000 {
                // Mostly the fast path, with the system call mixed in: the
                // two must agree on the order of events.
                let now = if i % 16 == 0 {
                    gettime_syscall(id)
                } else {
                    gettime(id)
                };
                let now = nanos(now.unwrap());
                assert!(now >= last, "clock {id} went backwards: {last} then {now}");
                last = now;
            }
        }
    }
}