Skip to main content

rusty_time_clock/
linux.rs

1//! Linux driver: clock_gettime + clock_adjtime (adjtimex).
2//!
3//! M2 scope: read, frequency slew, precise step. Hardware timestamping, PHC, and
4//! refclocks are M7 (mission plan §6.1).
5
6use crate::{ClockDrive, ClockError, ClockRead};
7use rusty_time_core::ClockCommand;
8
9pub struct SystemClock;
10
11/// `adjtimex` accepts frequency in 2^-16 ppm, so this is its granularity.
12const SLEW_RESOLUTION_PPM: f64 = 1.0 / 65_536.0;
13/// The kernel's nominal tick, in microseconds — `1e6 / USER_HZ`.
14///
15/// Read from the C library rather than assumed: USER_HZ is 100 on almost every
16/// build, but it is 1000 on some, and the tick arithmetic is wrong by 10x if
17/// this is guessed.
18fn nominal_tick_us() -> i64 {
19    // SAFETY: sysconf takes an int and returns a long; no pointers involved.
20    let hz = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
21    if hz <= 0 {
22        10_000
23    } else {
24        1_000_000 / hz as i64
25    }
26}
27
28/// The fastest this kernel can actually be slewed.
29///
30/// `ADJ_FREQUENCY` alone stops at 500 ppm; combined with the tick the reachable
31/// range is about ±100000 ppm. This is what `capabilities()` advertises, and
32/// the client loop configures its discipline from it — so it must be a rate the
33/// driver can genuinely deliver, not the width of a struct field.
34fn max_slew_ppm() -> f64 {
35    crate::slew::linux_max_slew_ppm(nominal_tick_us())
36}
37
38fn errno_detail(op: &'static str) -> ClockError {
39    ClockError {
40        op,
41        detail: std::io::Error::last_os_error().to_string(),
42    }
43}
44
45/// Can this process discipline the clock?
46///
47/// A read-only `adjtimex` — mode 0 queries without modifying anything, so this
48/// asks the kernel the question directly rather than inferring from uid, which
49/// would miss a `CAP_SYS_TIME` file capability on an unprivileged binary.
50pub fn can_discipline() -> bool {
51    // Running as root is sufficient and is the common case.
52    // SAFETY: geteuid takes no arguments and cannot fail.
53    if unsafe { libc::geteuid() } == 0 {
54        return true;
55    }
56    // Otherwise probe the capability set for CAP_SYS_TIME (bit 25) in the
57    // effective set, read from /proc/self/status — no syscall wrapper needed
58    // and no side effects.
59    let Ok(status) = std::fs::read_to_string("/proc/self/status") else {
60        return false;
61    };
62    status
63        .lines()
64        .find_map(|line| line.strip_prefix("CapEff:"))
65        .and_then(|hex| u64::from_str_radix(hex.trim(), 16).ok())
66        .map(|caps| caps & (1 << 25) != 0)
67        .unwrap_or(false)
68}
69
70pub(crate) fn platform_capabilities() -> crate::ClockCapabilities {
71    crate::ClockCapabilities {
72        os: "linux",
73        arch: std::env::consts::ARCH,
74        can_read: true,
75        can_discipline: can_discipline(),
76        discipline_requirement: "CAP_SYS_TIME (run as root, or grant the binary the file \
77                                 capability: setcap cap_sys_time+ep /usr/sbin/rtimed)",
78        slew_resolution_ppm: Some(SLEW_RESOLUTION_PPM),
79        max_slew_ppm: max_slew_ppm(),
80        batch_receive: true,
81        mono_resolution_ns: None,
82    }
83}
84
85impl ClockRead for SystemClock {
86    fn wall_ns(&self) -> Result<i128, ClockError> {
87        let mut ts = libc::timespec {
88            tv_sec: 0,
89            tv_nsec: 0,
90        };
91        // SAFETY: ts is a valid, exclusively-owned timespec for the duration of
92        // the call; CLOCK_REALTIME is always available.
93        let rc = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) };
94        if rc != 0 {
95            return Err(errno_detail("clock_gettime(REALTIME)"));
96        }
97        Ok(ts.tv_sec as i128 * 1_000_000_000 + ts.tv_nsec as i128)
98    }
99
100    fn wall_parts(&self) -> Result<(i64, u32), ClockError> {
101        let mut ts = libc::timespec {
102            tv_sec: 0,
103            tv_nsec: 0,
104        };
105        // SAFETY: as above. This is what the kernel hands back anyway, so
106        // returning it unchanged avoids composing a 128-bit nanosecond count
107        // only for the caller to divide it apart again.
108        let rc = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts) };
109        if rc != 0 {
110            return Err(errno_detail("clock_gettime(REALTIME)"));
111        }
112        // No conversion on `tv_sec`: `time_t` is 64-bit on every target this
113        // crate ships to, so `as i64` is an unnecessary cast and `i64::from` a
114        // useless conversion -- clippy rejects both, and it is right about
115        // both. A 32-bit-time_t target would fail to compile here, which is
116        // the right way to find out that it needs one.
117        Ok((ts.tv_sec, ts.tv_nsec as u32))
118    }
119
120    fn mono_s(&self) -> Result<f64, ClockError> {
121        let mut ts = libc::timespec {
122            tv_sec: 0,
123            tv_nsec: 0,
124        };
125        // SAFETY: as above; MONOTONIC_RAW is immune to NTP slewing, which is the
126        // point — sample timestamps must not see our own corrections.
127        let rc = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut ts) };
128        if rc != 0 {
129            return Err(errno_detail("clock_gettime(MONOTONIC_RAW)"));
130        }
131        Ok(ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9)
132    }
133}
134
135/// scaled ppm: adjtimex frequency unit is 2^-16 ppm.
136const FREQ_SCALE: f64 = 65_536.0;
137
138impl ClockDrive for SystemClock {
139    fn apply(&mut self, cmd: &ClockCommand) -> Result<(), ClockError> {
140        match *cmd {
141            ClockCommand::Step { add_seconds } => {
142                let mut tx: libc::timex = // SAFETY: timex is a plain-old-data
143                    // struct; zeroed is a valid initial state the kernel accepts.
144                    unsafe { core::mem::zeroed() };
145                tx.modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO;
146                let ns_total = (add_seconds * 1e9) as i64;
147                let mut sec = ns_total / 1_000_000_000;
148                let mut nsec = ns_total % 1_000_000_000;
149                if nsec < 0 {
150                    // ADJ_SETOFFSET requires tv_usec/tv_nsec in [0, 1e9).
151                    sec -= 1;
152                    nsec += 1_000_000_000;
153                }
154                tx.time.tv_sec = sec;
155                tx.time.tv_usec = nsec; // ADJ_NANO: field carries nanoseconds
156                // SAFETY: tx is valid and exclusively owned for the call.
157                let rc = unsafe { libc::clock_adjtime(libc::CLOCK_REALTIME, &mut tx) };
158                if rc < 0 {
159                    return Err(errno_detail("clock_adjtime(ADJ_SETOFFSET)"));
160                }
161                Ok(())
162            }
163            ClockCommand::Slew {
164                freq_ppm,
165                drain_offset,
166                drain_rate_ppm,
167            } => {
168                // The daemon re-plans every poll, so the drain is folded into the
169                // commanded frequency until the next plan (mission plan §6.1; the
170                // TIMECORP simulator models exactly this driver behavior).
171                let total_ppm =
172                    crate::slew::total_ppm(freq_ppm, drain_offset, drain_rate_ppm, max_slew_ppm());
173                // Split across the tick and the frequency knob: the kernel
174                // clamps ADJ_FREQUENCY at 500 ppm, so anything faster has to
175                // come from the tick or it is silently not applied at all.
176                let (tick_us, residual_ppm) =
177                    crate::slew::linux_tick_and_freq(total_ppm, nominal_tick_us());
178                let mut tx: libc::timex =
179                    // SAFETY: plain-old-data, zeroed is valid.
180                    unsafe { core::mem::zeroed() };
181                tx.modes = libc::ADJ_FREQUENCY | libc::ADJ_TICK;
182                tx.freq = (residual_ppm * FREQ_SCALE) as libc::c_long;
183                tx.tick = tick_us as libc::c_long;
184                // SAFETY: tx is valid and exclusively owned for the call.
185                let rc = unsafe { libc::clock_adjtime(libc::CLOCK_REALTIME, &mut tx) };
186                if rc < 0 {
187                    return Err(errno_detail("clock_adjtime(ADJ_FREQUENCY|ADJ_TICK)"));
188                }
189                Ok(())
190            }
191        }
192    }
193}