Skip to main content

raw_ether/
clock.rs

1//! A network interface's PTP hardware clock, which gPTP keeps on the
2//! network's time, read from Linux's `/dev/ptpN`, and two such clocks
3//! compared. Elsewhere opening fails as unsupported.
4
5use std::collections::VecDeque;
6use std::io;
7use std::time::Duration;
8
9/// One of this computer's clocks, to compare a hardware clock with.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SystemClock {
12    /// The wall clock, which NTP steps and slews.
13    Realtime,
14    /// The clock `std::time::Instant` and sleeps run on: slewed by NTP,
15    /// never stepped.
16    Monotonic,
17    /// The oscillator as it runs, which nothing adjusts.
18    MonotonicRaw,
19    /// International atomic time: the wall clock and the kernel's TAI
20    /// offset, which is zero until something such as chrony sets it.
21    Tai,
22}
23
24/// A PTP hardware clock.
25pub struct HardwareClock {
26    inner: platform::HardwareClock,
27}
28
29impl HardwareClock {
30    /// Opens the clock with `index`, as an interface reports it in
31    /// [`crate::Interface::hardware_clock`].
32    pub fn open(index: u32) -> io::Result<Self> {
33        Ok(Self {
34            inner: platform::HardwareClock::open(index, false)?,
35        })
36    }
37
38    /// Opens the clock with `index` to adjust it as well as read it.
39    pub fn open_adjustable(index: u32) -> io::Result<Self> {
40        Ok(Self {
41            inner: platform::HardwareClock::open(index, true)?,
42        })
43    }
44
45    /// How far the clock's frequency is adjusted from its oscillator's, in
46    /// parts per billion.
47    pub fn frequency_adjustment(&self) -> io::Result<f64> {
48        self.inner.frequency_adjustment()
49    }
50
51    /// Adjusts the clock's frequency to `ppb` parts per billion from its
52    /// oscillator's: 0 lets it run free. Needs the clock opened with
53    /// [`open_adjustable`](Self::open_adjustable).
54    pub fn set_frequency_adjustment(&self, ppb: f64) -> io::Result<()> {
55        self.inner.set_frequency_adjustment(ppb)
56    }
57
58    /// Sets the clock `by` nanoseconds on, back where negative. Needs the
59    /// clock opened with [`open_adjustable`](Self::open_adjustable).
60    pub fn step(&self, by: i128) -> io::Result<()> {
61        self.inner.step(by)
62    }
63
64    /// The clock's time, from the PTP epoch.
65    pub fn now(&self) -> io::Result<Duration> {
66        self.inner.now()
67    }
68
69    /// How far this clock is ahead of `other`, in nanoseconds: each read
70    /// by its driver between two readings of the system clock, the
71    /// tightest of several pairs kept, so the system clock drops out.
72    /// Linux only; elsewhere unsupported.
73    pub fn offset_from(&self, other: &HardwareClock) -> io::Result<i128> {
74        self.reading_from(other).map(|reading| reading.offset)
75    }
76
77    /// [`offset_from`](Self::offset_from) with its span: the two clocks'
78    /// spans together.
79    pub fn reading_from(&self, other: &HardwareClock) -> io::Result<Reading> {
80        let ours = self.system_reading(SystemClock::Realtime)?;
81        let theirs = other.system_reading(SystemClock::Realtime)?;
82        Ok(Reading {
83            offset: ours.offset - theirs.offset,
84            span: ours.span.saturating_add(theirs.span),
85        })
86    }
87
88    /// The driver's reading against `system`, or where it has none, one
89    /// read as [`reading_against`](Self::reading_against) reads it.
90    /// iwlwifi's radio clock has none: its PTP_SYS_OFFSET_PRECISE is a
91    /// firmware command of about 1 ms that logs a line each time.
92    fn system_reading(&self, system: SystemClock) -> io::Result<Reading> {
93        match self.inner.reading_from_system(system) {
94            Err(error) if error.kind() == io::ErrorKind::Unsupported => {
95                self.reading_against(system)
96            }
97            read => read,
98        }
99    }
100
101    /// How far this clock is ahead of `system`, in nanoseconds, from its
102    /// driver's tightest of several readings between two of `system`'s
103    /// (PTP_SYS_OFFSET_EXTENDED). A kernel too old to take a clock other
104    /// than the wall clock for it refuses the others, and then
105    /// [`offset_read_against`](Self::offset_read_against) serves.
106    pub fn offset_from_system_clock(&self, system: SystemClock) -> io::Result<i128> {
107        self.reading_from_system_clock(system)
108            .map(|reading| reading.offset)
109    }
110
111    /// [`offset_from_system_clock`](Self::offset_from_system_clock) with
112    /// the span of the reading kept.
113    pub fn reading_from_system_clock(&self, system: SystemClock) -> io::Result<Reading> {
114        self.system_reading(system)
115    }
116
117    /// How far the clock is ahead of this computer's monotonic clock, in
118    /// nanoseconds, read between two readings of the monotonic clock: of
119    /// a few tries, the closest-read of those near their median, as a
120    /// clock can now and then be read wrong (a 2^32 ns tear has been seen
121    /// on one card's).
122    pub fn offset_from_monotonic(&self) -> io::Result<i128> {
123        self.offset_read_against(SystemClock::Monotonic)
124    }
125
126    /// How far the clock is ahead of `system`, in nanoseconds, read as
127    /// [`offset_from_monotonic`](Self::offset_from_monotonic) reads it:
128    /// looser than the driver's readings, but on every kernel.
129    pub fn offset_read_against(&self, system: SystemClock) -> io::Result<i128> {
130        self.reading_against(system).map(|reading| reading.offset)
131    }
132
133    /// [`offset_read_against`](Self::offset_read_against) with the span of
134    /// the try kept. Where none stands near the median, the median's.
135    pub fn reading_against(&self, system: SystemClock) -> io::Result<Reading> {
136        let mut tries = [Reading { offset: 0, span: 0 }; 5];
137        for slot in &mut tries {
138            let before = system_now(system);
139            let clock = self.now()?;
140            let after = system_now(system);
141            let span = after.saturating_sub(before).as_nanos();
142            let middle = before + (after - before) / 2;
143            *slot = Reading {
144                offset: clock.as_nanos() as i128 - middle.as_nanos() as i128,
145                span: u64::try_from(span).unwrap_or(u64::MAX),
146            };
147        }
148        let mut sorted = tries;
149        sorted.sort_unstable_by_key(|reading| reading.offset);
150        let median = sorted[sorted.len() / 2];
151        Ok(tries
152            .into_iter()
153            .filter(|reading| (reading.offset - median.offset).abs() <= 10_000)
154            .min_by_key(|reading| reading.span)
155            .unwrap_or(median))
156    }
157}
158
159/// A hardware clock against another clock, read between two of the
160/// other's readings: how far it was ahead, and how long the reading took
161/// from the other's first to its second. The hardware clock is latched
162/// somewhere in that span, so a reading is off by up to half of it; a
163/// slow one, held up on the way to the latch or after it, by up to half
164/// of what it took beyond the usual. Comparisons that must hold to less
165/// than a microsecond can leave such readings out.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct Reading {
168    /// The hardware clock less the other, in nanoseconds.
169    pub offset: i128,
170    /// How long the reading took, in nanoseconds.
171    pub span: u64,
172}
173
174/// How far back comparisons count towards the rate, in nanoseconds: long
175/// enough that each comparison's own error hardly moves it.
176const SPAN: i128 = 2_000_000_000;
177
178/// Two clocks compared now and then, with the rate between them, so that
179/// a time on one is put on the other as the two stood when it was taken,
180/// not as at the last comparison: clocks some ppm apart drift hundreds of
181/// ns between comparisons. A line fitted through the comparisons kept
182/// gives both, so no one comparison's error carries over whole.
183#[derive(Debug, Clone, Default)]
184pub struct Comparison {
185    /// (when, on the clock compared, in ns; its time less the other's)
186    kept: VecDeque<(i128, i128)>,
187}
188
189impl Comparison {
190    /// The clock compared read `at`, and `offset` ahead of the other.
191    pub fn update(&mut self, at: i128, offset: i128) {
192        if self.kept.back().is_some_and(|(last, _)| at <= *last) {
193            return;
194        }
195        self.kept.push_back((at, offset));
196        while self
197            .kept
198            .front()
199            .is_some_and(|(first, _)| at - first > SPAN)
200            && self.kept.len() > 2
201        {
202            self.kept.pop_front();
203        }
204    }
205
206    /// How far ahead of the other the clock compared was at `at`, a time
207    /// on it.
208    pub fn offset_at(&self, at: i128) -> i128 {
209        let Some(&(last_at, last_offset)) = self.kept.back() else {
210            return 0;
211        };
212        let Some((mean_at, mean_offset, rate)) = self.fit() else {
213            return last_offset;
214        };
215        last_offset + (mean_offset + rate * ((at - last_at) as f64 - mean_at)).round() as i128
216    }
217
218    /// How much faster the clock compared runs than the other, as a
219    /// fraction, once compared twice.
220    pub fn rate(&self) -> Option<f64> {
221        self.fit().map(|(_, _, rate)| rate)
222    }
223
224    /// The least-squares line through the comparisons kept: their mean
225    /// time and offset, each from the last's so as to keep the precision,
226    /// and the slope.
227    fn fit(&self) -> Option<(f64, f64, f64)> {
228        let &(last_at, last_offset) = self.kept.back()?;
229        if self.kept.len() < 2 {
230            return None;
231        }
232        let count = self.kept.len() as f64;
233        let points = || {
234            self.kept
235                .iter()
236                .map(move |&(at, offset)| ((at - last_at) as f64, (offset - last_offset) as f64))
237        };
238        let mean_at = points().map(|(at, _)| at).sum::<f64>() / count;
239        let mean_offset = points().map(|(_, offset)| offset).sum::<f64>() / count;
240        let (spread, covariance) =
241            points().fold((0.0, 0.0), |(spread, covariance), (at, offset)| {
242                let at = at - mean_at;
243                (spread + at * at, covariance + at * (offset - mean_offset))
244            });
245        (spread > 0.0).then(|| (mean_at, mean_offset, covariance / spread))
246    }
247
248    /// Whether the clocks have been compared yet.
249    pub fn is_empty(&self) -> bool {
250        self.kept.is_empty()
251    }
252
253    /// Forgets all but the last `count` comparisons, as when the rate
254    /// between the clocks changed and the older ones would only drag the
255    /// line.
256    pub fn keep_last(&mut self, count: usize) {
257        while self.kept.len() > count {
258            self.kept.pop_front();
259        }
260    }
261
262    /// Forgets every comparison, as after one of the clocks was set.
263    pub fn clear(&mut self) {
264        self.kept.clear();
265    }
266}
267
268/// This computer's monotonic clock: the clock `std::time::Instant` reads,
269/// as a duration from its unspecified start.
270pub fn monotonic_now() -> Duration {
271    platform::monotonic_now()
272}
273
274/// One of this computer's clocks, as a duration from its epoch. Elsewhere
275/// than on Linux the monotonic clock stands in for all three.
276pub fn system_now(system: SystemClock) -> Duration {
277    platform::system_now(system)
278}
279
280/// How long this computer has been suspended since it started: what the
281/// boot clock has counted beyond the monotonic clock. It grows at each
282/// resume. Elsewhere than on Linux it stays zero.
283pub fn suspended() -> Duration {
284    platform::suspended()
285}
286
287/// Has the calling thread's sleeps end as close to when they were asked
288/// for as the system can, for a thread that paces frames: on Linux a
289/// timer slack of a nanosecond in place of 50 microseconds. Elsewhere it
290/// does nothing.
291pub fn precise_sleeps() {
292    platform::precise_sleeps();
293}
294
295#[cfg(target_os = "linux")]
296#[allow(unsafe_code)]
297mod platform {
298    use super::{Reading, SystemClock};
299    use std::io;
300    use std::mem::size_of;
301    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
302    use std::time::Duration;
303
304    pub struct HardwareClock {
305        _fd: OwnedFd,
306        id: libc::clockid_t,
307    }
308
309    fn read(id: libc::clockid_t) -> io::Result<Duration> {
310        let mut time = libc::timespec {
311            tv_sec: 0,
312            tv_nsec: 0,
313        };
314        // SAFETY: `time` is a valid timespec that lives through the call.
315        if unsafe { libc::clock_gettime(id, &raw mut time) } < 0 {
316            return Err(io::Error::last_os_error());
317        }
318        Ok(Duration::new(time.tv_sec as u64, time.tv_nsec as u32))
319    }
320
321    impl HardwareClock {
322        pub fn open(index: u32, adjustable: bool) -> io::Result<Self> {
323            let path = format!("/dev/ptp{index}\0");
324            let mode = if adjustable {
325                libc::O_RDWR
326            } else {
327                libc::O_RDONLY
328            };
329            // SAFETY: `path` is NUL-terminated and lives through the call.
330            let raw = unsafe { libc::open(path.as_ptr().cast(), mode | libc::O_CLOEXEC) };
331            if raw < 0 {
332                return Err(io::Error::last_os_error());
333            }
334            // SAFETY: `raw` is a descriptor this function just opened.
335            let fd = unsafe { OwnedFd::from_raw_fd(raw) };
336            // A dynamic clock's ID is made from its descriptor
337            // (FD_TO_CLOCKID: CLOCKFD in the low bits).
338            let id = ((!fd.as_raw_fd()) << 3) | 3;
339            Ok(Self { _fd: fd, id })
340        }
341
342        pub fn now(&self) -> io::Result<Duration> {
343            read(self.id)
344        }
345
346        /// clock_adjtime on the clock: sets what `modes` names, here no
347        /// more than the frequency, and gives the adjustments as they stand.
348        fn adjust(&self, modes: libc::c_uint, frequency: libc::c_long) -> io::Result<libc::timex> {
349            // SAFETY: timex is plain data, valid when zeroed.
350            let mut time: libc::timex = unsafe { std::mem::zeroed() };
351            time.modes = modes;
352            time.freq = frequency;
353            // SAFETY: `time` is a valid timex that lives through the call.
354            if unsafe { libc::clock_adjtime(self.id, &raw mut time) } < 0 {
355                return Err(io::Error::last_os_error());
356            }
357            Ok(time)
358        }
359
360        /// timex's freq is in ppm with 16 fractional bits.
361        const SCALED_PPB: f64 = 65.536;
362
363        pub fn frequency_adjustment(&self) -> io::Result<f64> {
364            Ok(self.adjust(0, 0)?.freq as f64 / Self::SCALED_PPB)
365        }
366
367        pub fn set_frequency_adjustment(&self, ppb: f64) -> io::Result<()> {
368            self.adjust(
369                libc::ADJ_FREQUENCY,
370                (ppb * Self::SCALED_PPB).round() as libc::c_long,
371            )
372            .map(|_| ())
373        }
374
375        pub fn step(&self, by: i128) -> io::Result<()> {
376            // SAFETY: timex is plain data, valid when zeroed.
377            let mut time: libc::timex = unsafe { std::mem::zeroed() };
378            // With ADJ_NANO, the offset's microseconds field holds
379            // nanoseconds, from 0 to a second.
380            time.modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO;
381            time.time.tv_sec = by.div_euclid(1_000_000_000) as libc::time_t;
382            time.time.tv_usec = by.rem_euclid(1_000_000_000) as libc::suseconds_t;
383            // SAFETY: `time` is a valid timex that lives through the call.
384            if unsafe { libc::clock_adjtime(self.id, &raw mut time) } < 0 {
385                return Err(io::Error::last_os_error());
386            }
387            Ok(())
388        }
389
390        /// The clock less the system clock, from its driver's tightest of
391        /// several readings between two of the system clock
392        /// (PTP_SYS_OFFSET_EXTENDED), or unsupported where it has none.
393        pub fn reading_from_system(&self, system: SystemClock) -> io::Result<Reading> {
394            self.extended_reading(system).map_err(|error| {
395                if error.raw_os_error() == Some(libc::EOPNOTSUPP) {
396                    io::Error::new(io::ErrorKind::Unsupported, error)
397                } else {
398                    error
399                }
400            })
401        }
402
403        fn extended_reading(&self, system: SystemClock) -> io::Result<Reading> {
404            /// struct ptp_clock_time, from linux/ptp_clock.h.
405            #[repr(C)]
406            #[derive(Clone, Copy, Default)]
407            struct Time {
408                seconds: i64,
409                nanoseconds: u32,
410                reserved: u32,
411            }
412            /// struct ptp_sys_offset_extended: system, clock and system
413            /// again, for each sample.
414            #[repr(C)]
415            struct Extended {
416                samples: u32,
417                clock: i32,
418                reserved: [u32; 2],
419                times: [[Time; 3]; 25],
420            }
421            /// _IOWR('=', 9, struct ptp_sys_offset_extended).
422            const PTP_SYS_OFFSET_EXTENDED: libc::c_ulong =
423                0xc000_0000 | ((size_of::<Extended>() as libc::c_ulong) << 16) | (0x3d << 8) | 9;
424            let mut request = Extended {
425                samples: 9,
426                clock: id_of(system),
427                reserved: [0; 2],
428                times: [[Time::default(); 3]; 25],
429            };
430            // SAFETY: `request` is the struct the ioctl takes, and lives
431            // through the call.
432            if unsafe {
433                libc::ioctl(
434                    self._fd.as_raw_fd(),
435                    PTP_SYS_OFFSET_EXTENDED as _,
436                    &raw mut request,
437                )
438            } < 0
439            {
440                return Err(io::Error::last_os_error());
441            }
442            let nanos = |time: Time| {
443                i128::from(time.seconds) * 1_000_000_000 + i128::from(time.nanoseconds)
444            };
445            request.times[..request.samples.min(25) as usize]
446                .iter()
447                .map(|[before, clock, after]| {
448                    let (before, after) = (nanos(*before), nanos(*after));
449                    Reading {
450                        offset: nanos(*clock) - (before + after) / 2,
451                        span: u64::try_from(after - before).unwrap_or(u64::MAX),
452                    }
453                })
454                .min_by_key(|reading| reading.span)
455                .ok_or_else(|| io::Error::other("the clock gave no samples"))
456        }
457    }
458
459    pub fn monotonic_now() -> Duration {
460        read(libc::CLOCK_MONOTONIC).unwrap_or_default()
461    }
462
463    fn id_of(system: SystemClock) -> libc::clockid_t {
464        match system {
465            SystemClock::Realtime => libc::CLOCK_REALTIME,
466            SystemClock::Monotonic => libc::CLOCK_MONOTONIC,
467            SystemClock::MonotonicRaw => libc::CLOCK_MONOTONIC_RAW,
468            SystemClock::Tai => libc::CLOCK_TAI,
469        }
470    }
471
472    pub fn system_now(system: SystemClock) -> Duration {
473        read(id_of(system)).unwrap_or_default()
474    }
475
476    pub fn suspended() -> Duration {
477        let boot = read(libc::CLOCK_BOOTTIME).unwrap_or_default();
478        boot.saturating_sub(monotonic_now())
479    }
480
481    pub fn precise_sleeps() {
482        // SAFETY: prctl with PR_SET_TIMERSLACK takes plain integers and
483        // changes only the calling thread.
484        unsafe {
485            libc::prctl(libc::PR_SET_TIMERSLACK, 1 as libc::c_ulong);
486        }
487    }
488}
489
490#[cfg(not(target_os = "linux"))]
491mod platform {
492    use std::io;
493    use std::time::Duration;
494
495    pub struct HardwareClock;
496
497    impl HardwareClock {
498        pub fn open(_index: u32, _adjustable: bool) -> io::Result<Self> {
499            Err(unsupported())
500        }
501
502        pub fn now(&self) -> io::Result<Duration> {
503            Ok(Duration::ZERO)
504        }
505
506        pub fn frequency_adjustment(&self) -> io::Result<f64> {
507            Err(unsupported())
508        }
509
510        pub fn set_frequency_adjustment(&self, _ppb: f64) -> io::Result<()> {
511            Err(unsupported())
512        }
513
514        pub fn step(&self, _by: i128) -> io::Result<()> {
515            Err(unsupported())
516        }
517
518        pub fn reading_from_system(
519            &self,
520            _system: super::SystemClock,
521        ) -> io::Result<super::Reading> {
522            Err(unsupported())
523        }
524    }
525
526    fn unsupported() -> io::Error {
527        io::Error::new(
528            io::ErrorKind::Unsupported,
529            "hardware clocks are not supported on this system yet",
530        )
531    }
532
533    pub fn monotonic_now() -> Duration {
534        use std::sync::OnceLock;
535        static START: OnceLock<std::time::Instant> = OnceLock::new();
536        START.get_or_init(std::time::Instant::now).elapsed()
537    }
538
539    pub fn system_now(_system: super::SystemClock) -> Duration {
540        monotonic_now()
541    }
542
543    pub fn suspended() -> Duration {
544        Duration::ZERO
545    }
546
547    pub fn precise_sleeps() {}
548}
549
550#[cfg(test)]
551mod comparison_tests {
552    use super::*;
553
554    #[test]
555    fn a_steady_drift_is_followed_between_comparisons() {
556        let mut comparison = Comparison::default();
557        // 6 ppm apart: 600 ns more every 100 ms.
558        for step in 0..30i128 {
559            comparison.update(step * 100_000_000, 1_000 + step * 600);
560        }
561        let last = 29 * 100_000_000;
562        assert_eq!(comparison.offset_at(last), 1_000 + 29 * 600);
563        assert_eq!(
564            comparison.offset_at(last + 50_000_000),
565            1_000 + 29 * 600 + 300
566        );
567        assert_eq!(
568            comparison.offset_at(last - 50_000_000),
569            1_000 + 29 * 600 - 300
570        );
571        assert!((comparison.rate().unwrap() - 6e-6).abs() < 1e-12);
572    }
573
574    #[test]
575    fn the_error_of_one_comparison_is_mostly_filtered_out() {
576        let mut comparison = Comparison::default();
577        // 6 ppm apart, each comparison 50 ns off one way or the other.
578        for step in 0..20i128 {
579            let error = if step % 2 == 0 { 50 } else { -50 };
580            comparison.update(step * 100_000_000, step * 600 + error);
581        }
582        let last = 19 * 100_000_000;
583        let off = comparison.offset_at(last) - 19 * 600;
584        assert!(off.abs() <= 15, "off by {off} ns");
585    }
586
587    #[test]
588    fn one_comparison_is_taken_as_it_is() {
589        let mut comparison = Comparison::default();
590        assert!(comparison.is_empty());
591        assert_eq!(comparison.offset_at(5), 0);
592        comparison.update(10, 42);
593        assert_eq!(comparison.offset_at(1_000_000), 42);
594        assert_eq!(comparison.rate(), None);
595        comparison.clear();
596        assert!(comparison.is_empty());
597    }
598}
599
600#[cfg(all(test, target_os = "linux"))]
601mod tests {
602    use super::*;
603
604    #[test]
605    fn a_hardware_clock_reads_when_there_is_one() {
606        // Computers without /dev/ptp0, or not allowed to read it, skip it.
607        let Ok(clock) = HardwareClock::open(0) else {
608            return;
609        };
610        // The grandmaster keeps whatever timescale it has; the clock only
611        // has to run on, at the monotonic clock's pace give or take.
612        let first = clock.offset_from_monotonic().unwrap();
613        std::thread::sleep(Duration::from_millis(20));
614        let second = clock.offset_from_monotonic().unwrap();
615        assert!((second - first).abs() < 100_000, "{first} then {second}");
616    }
617
618    #[test]
619    fn the_monotonic_clock_moves_on() {
620        let before = monotonic_now();
621        std::thread::sleep(Duration::from_millis(2));
622        assert!(monotonic_now() > before);
623    }
624}