1use core::mem::size_of;
4
5use crate::errno::SysResult;
6use crate::raw::{nr, syscall2, syscall4};
7
8pub const CLOCK_REALTIME: i32 = 0;
10pub const CLOCK_MONOTONIC: i32 = 1;
12pub const TIMER_ABSTIME: i32 = 1;
14
15#[repr(C)]
17#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
18pub struct Timespec {
19 pub tv_sec: i64,
20 pub tv_nsec: i64,
21}
22
23#[repr(C)]
25#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
26pub struct Timeval {
27 pub tv_sec: i64,
28 pub tv_usec: i64,
29}
30
31const _: () = {
32 assert!(size_of::<Timespec>() == 16);
33 assert!(size_of::<Timeval>() == 16);
34};
35
36pub fn clock_gettime(clock_id: i32) -> SysResult<Timespec> {
38 let mut ts = Timespec::default();
39 unsafe {
41 syscall2(
42 nr::CLOCK_GETTIME,
43 clock_id as usize,
44 core::ptr::from_mut(&mut ts) as usize,
45 )?;
46 }
47 Ok(ts)
48}
49
50pub fn clock_settime(clock_id: i32, ts: &Timespec) -> SysResult<()> {
52 unsafe {
54 syscall2(
55 nr::CLOCK_SETTIME,
56 clock_id as usize,
57 core::ptr::from_ref(ts) as usize,
58 )?;
59 }
60 Ok(())
61}
62
63pub fn nanosleep(req: &Timespec, rem: Option<&mut Timespec>) -> SysResult<()> {
66 let rem_ptr = rem.map_or(0, |r| core::ptr::from_mut(r) as usize);
67 unsafe {
70 syscall4(
71 nr::CLOCK_NANOSLEEP,
72 CLOCK_MONOTONIC as usize,
73 0,
74 core::ptr::from_ref(req) as usize,
75 rem_ptr,
76 )?;
77 }
78 Ok(())
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84 use crate::raw::with_mock_syscall;
85
86 #[test]
87 fn clock_gettime_and_nanosleep_pass_expected_arguments() {
88 let ts = with_mock_syscall(
89 |sysno, args| {
90 assert_eq!(sysno, nr::CLOCK_GETTIME);
91 assert_eq!(args[0], CLOCK_MONOTONIC as usize);
92 let out = args[1] as *mut Timespec;
93 unsafe {
95 *out = Timespec {
96 tv_sec: 42,
97 tv_nsec: 123_456_789,
98 };
99 }
100 Ok(0)
101 },
102 || clock_gettime(CLOCK_MONOTONIC).unwrap(),
103 );
104 assert_eq!(
105 ts,
106 Timespec {
107 tv_sec: 42,
108 tv_nsec: 123_456_789,
109 }
110 );
111
112 const REQ: Timespec = Timespec {
113 tv_sec: 1,
114 tv_nsec: 500,
115 };
116 let mut rem = Timespec::default();
117 with_mock_syscall(
118 |sysno, args| {
119 assert_eq!(sysno, nr::CLOCK_NANOSLEEP);
120 assert_eq!(args[0], CLOCK_MONOTONIC as usize);
121 assert_eq!(args[1], 0);
122 let req_ptr = args[2] as *const Timespec;
123 assert_eq!(unsafe { *req_ptr }, REQ);
125 assert!(args[3] != 0);
126 Ok(0)
127 },
128 || nanosleep(&REQ, Some(&mut rem)).unwrap(),
129 );
130 }
131}