Skip to main content

libc_rs/
time.rs

1//! Clocks, timestamps, and high-resolution sleep syscalls.
2
3use core::mem::size_of;
4#[cfg(all(target_arch = "aarch64", target_os = "none"))]
5use core::sync::atomic::{AtomicU64, Ordering};
6
7use crate::errno::SysResult;
8use crate::raw::{nr, syscall2, syscall4};
9
10/// System-wide real-time clock identifier.
11pub const CLOCK_REALTIME: i32 = 0;
12/// Monotonic clock identifier (cannot jump backwards).
13pub const CLOCK_MONOTONIC: i32 = 1;
14/// Flag indicating an absolute target time for `clock_nanosleep`.
15pub const TIMER_ABSTIME: i32 = 1;
16
17/// Seconds and nanoseconds timestamp matching the 64-bit kernel `struct timespec`.
18#[repr(C)]
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub struct Timespec {
21    pub tv_sec: i64,
22    pub tv_nsec: i64,
23}
24
25/// Seconds and microseconds timestamp matching the 64-bit kernel `struct timeval`.
26#[repr(C)]
27#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
28pub struct Timeval {
29    pub tv_sec: i64,
30    pub tv_usec: i64,
31}
32
33const _: () = {
34    assert!(size_of::<Timespec>() == 16);
35    assert!(size_of::<Timeval>() == 16);
36};
37
38/// Queries the current value of `clock_id` via the `CLOCK_GETTIME` syscall.
39pub fn clock_gettime_syscall(clock_id: i32) -> SysResult<Timespec> {
40    let mut ts = Timespec::default();
41    // SAFETY: `ts` is a valid, aligned stack `Timespec` for the kernel to write into.
42    unsafe {
43        syscall2(
44            nr::CLOCK_GETTIME,
45            clock_id as usize,
46            core::ptr::from_mut(&mut ts) as usize,
47        )?;
48    }
49    Ok(ts)
50}
51
52/// Queries the current value of `clock_id`.
53pub fn clock_gettime(clock_id: i32) -> SysResult<Timespec> {
54    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
55    if clock_id == CLOCK_MONOTONIC {
56        static CACHED_HZ: AtomicU64 = AtomicU64::new(0);
57        let mut hz = CACHED_HZ.load(Ordering::Relaxed);
58        if hz == 0 {
59            hz = crate::raw::read_cntfrq_el0();
60            if hz != 0 {
61                CACHED_HZ.store(hz, Ordering::Relaxed);
62            }
63        }
64        let ticks = crate::raw::read_cntvct_el0();
65        if let Some(secs) = ticks.checked_div(hz) {
66            let rem = ticks - secs * hz;
67            let tv_sec = secs as i64;
68            let tv_nsec = ((rem as u128 * 1_000_000_000) / (hz as u128)) as i64;
69            return Ok(Timespec { tv_sec, tv_nsec });
70        }
71    }
72    clock_gettime_syscall(clock_id)
73}
74
75/// Sets the time of `clock_id` to `ts`.
76pub fn clock_settime(clock_id: i32, ts: &Timespec) -> SysResult<()> {
77    // SAFETY: `ts` is a valid shared reference to a `Timespec`.
78    unsafe {
79        syscall2(
80            nr::CLOCK_SETTIME,
81            clock_id as usize,
82            core::ptr::from_ref(ts) as usize,
83        )?;
84    }
85    Ok(())
86}
87
88/// Sleeps for the relative interval `req` on `CLOCK_MONOTONIC`, optionally writing
89/// any remaining duration into `rem` if interrupted.
90pub fn nanosleep(req: &Timespec, rem: Option<&mut Timespec>) -> SysResult<()> {
91    let rem_ptr = rem.map_or(0, |r| core::ptr::from_mut(r) as usize);
92    // SAFETY: `req` is a valid `Timespec` reference and `rem_ptr` is either 0 (null)
93    // or a valid mutable `Timespec` pointer.
94    unsafe {
95        syscall4(
96            nr::CLOCK_NANOSLEEP,
97            CLOCK_MONOTONIC as usize,
98            0,
99            core::ptr::from_ref(req) as usize,
100            rem_ptr,
101        )?;
102    }
103    Ok(())
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use crate::raw::with_mock_syscall;
110
111    #[test]
112    fn clock_gettime_and_nanosleep_pass_expected_arguments() {
113        let ts = with_mock_syscall(
114            |sysno, args| {
115                assert_eq!(sysno, nr::CLOCK_GETTIME);
116                assert_eq!(args[0], CLOCK_MONOTONIC as usize);
117                let out = args[1] as *mut Timespec;
118                // SAFETY: `out` points to the stack `Timespec` in `clock_gettime`.
119                unsafe {
120                    *out = Timespec {
121                        tv_sec: 42,
122                        tv_nsec: 123_456_789,
123                    };
124                }
125                Ok(0)
126            },
127            || clock_gettime(CLOCK_MONOTONIC).unwrap(),
128        );
129        assert_eq!(
130            ts,
131            Timespec {
132                tv_sec: 42,
133                tv_nsec: 123_456_789,
134            }
135        );
136
137        const REQ: Timespec = Timespec {
138            tv_sec: 1,
139            tv_nsec: 500,
140        };
141        let mut rem = Timespec::default();
142        with_mock_syscall(
143            |sysno, args| {
144                assert_eq!(sysno, nr::CLOCK_NANOSLEEP);
145                assert_eq!(args[0], CLOCK_MONOTONIC as usize);
146                assert_eq!(args[1], 0);
147                let req_ptr = args[2] as *const Timespec;
148                // SAFETY: `req_ptr` points to `REQ`.
149                assert_eq!(unsafe { *req_ptr }, REQ);
150                assert!(args[3] != 0);
151                Ok(0)
152            },
153            || nanosleep(&REQ, Some(&mut rem)).unwrap(),
154        );
155    }
156}