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