use core::time::Duration;
use crate::sys::{syscall, vdso};
use crate::time::{Clock, Timestamp};
use crate::{ErrorKind, Result};
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;
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct Timespec {
pub(crate) sec: i64,
pub(crate) nsec: i64,
}
impl Timespec {
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()),
}
}
}
fn gettime(id: u32) -> Result<Timespec> {
if let Some(clock_gettime) = vdso::clock_gettime() {
let mut ts = Timespec::default();
if unsafe { clock_gettime(id as i32, &raw mut ts) } == 0 {
return Ok(ts);
}
}
gettime_syscall(id)
}
fn gettime_syscall(id: u32) -> Result<Timespec> {
let mut ts = Timespec::default();
#[cfg(target_pointer_width = "32")]
unsafe { syscall!(CLOCK_GETTIME64, id, &raw mut ts) }?;
#[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();
#[cfg(target_pointer_width = "32")]
unsafe { syscall!(CLOCK_GETRES_TIME64, clock_id(clock), &raw mut ts) }?;
#[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);
#[cfg(target_pointer_width = "32")]
unsafe {
syscall!(
CLOCK_NANOSLEEP_TIME64,
CLOCK_MONOTONIC,
flags,
&raw const ts,
0
)
}?;
#[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)
}
#[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 {
let tolerance = 5_000_000_000;
assert!((reading - before).abs() < tolerance);
assert!((after - reading).abs() < tolerance);
} else {
assert!(before <= reading, "clock {id}: {before} > {reading}");
assert!(reading <= after, "clock {id}: {reading} > {after}");
}
if let Some(fast) = fast {
let mut ts = Timespec::default();
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() {
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();
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 {
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;
}
}
}
}