1use std::collections::VecDeque;
6use std::io;
7use std::time::Duration;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SystemClock {
12 Realtime,
14 Monotonic,
17 MonotonicRaw,
19 Tai,
22}
23
24pub struct HardwareClock {
26 inner: platform::HardwareClock,
27}
28
29impl HardwareClock {
30 pub fn open(index: u32) -> io::Result<Self> {
33 Ok(Self {
34 inner: platform::HardwareClock::open(index, false)?,
35 })
36 }
37
38 pub fn open_adjustable(index: u32) -> io::Result<Self> {
40 Ok(Self {
41 inner: platform::HardwareClock::open(index, true)?,
42 })
43 }
44
45 pub fn frequency_adjustment(&self) -> io::Result<f64> {
48 self.inner.frequency_adjustment()
49 }
50
51 pub fn set_frequency_adjustment(&self, ppb: f64) -> io::Result<()> {
55 self.inner.set_frequency_adjustment(ppb)
56 }
57
58 pub fn step(&self, by: i128) -> io::Result<()> {
61 self.inner.step(by)
62 }
63
64 pub fn now(&self) -> io::Result<Duration> {
66 self.inner.now()
67 }
68
69 pub fn offset_from(&self, other: &HardwareClock) -> io::Result<i128> {
74 self.reading_from(other).map(|reading| reading.offset)
75 }
76
77 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 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 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 pub fn reading_from_system_clock(&self, system: SystemClock) -> io::Result<Reading> {
114 self.system_reading(system)
115 }
116
117 pub fn offset_from_monotonic(&self) -> io::Result<i128> {
123 self.offset_read_against(SystemClock::Monotonic)
124 }
125
126 pub fn offset_read_against(&self, system: SystemClock) -> io::Result<i128> {
130 self.reading_against(system).map(|reading| reading.offset)
131 }
132
133 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct Reading {
168 pub offset: i128,
170 pub span: u64,
172}
173
174const SPAN: i128 = 2_000_000_000;
177
178#[derive(Debug, Clone)]
184pub struct Comparison {
185 kept: VecDeque<(i128, i128)>,
187 span: i128,
189}
190
191impl Default for Comparison {
192 fn default() -> Self {
193 Self {
194 kept: VecDeque::new(),
195 span: SPAN,
196 }
197 }
198}
199
200impl Comparison {
201 pub fn keeping(span: Duration) -> Self {
204 Self {
205 kept: VecDeque::new(),
206 span: i128::try_from(span.as_nanos()).unwrap_or(i128::MAX),
207 }
208 }
209
210 pub fn update(&mut self, at: i128, offset: i128) {
212 if self.kept.back().is_some_and(|(last, _)| at <= *last) {
213 return;
214 }
215 self.kept.push_back((at, offset));
216 while self
217 .kept
218 .front()
219 .is_some_and(|(first, _)| at - first > self.span)
220 && self.kept.len() > 2
221 {
222 self.kept.pop_front();
223 }
224 }
225
226 pub fn offset_at(&self, at: i128) -> i128 {
229 let Some(&(last_at, last_offset)) = self.kept.back() else {
230 return 0;
231 };
232 let Some((mean_at, mean_offset, rate)) = self.fit() else {
233 return last_offset;
234 };
235 last_offset + (mean_offset + rate * ((at - last_at) as f64 - mean_at)).round() as i128
236 }
237
238 pub fn rate(&self) -> Option<f64> {
241 self.fit().map(|(_, _, rate)| rate)
242 }
243
244 fn fit(&self) -> Option<(f64, f64, f64)> {
248 let &(last_at, last_offset) = self.kept.back()?;
249 if self.kept.len() < 2 {
250 return None;
251 }
252 let count = self.kept.len() as f64;
253 let points = || {
254 self.kept
255 .iter()
256 .map(move |&(at, offset)| ((at - last_at) as f64, (offset - last_offset) as f64))
257 };
258 let mean_at = points().map(|(at, _)| at).sum::<f64>() / count;
259 let mean_offset = points().map(|(_, offset)| offset).sum::<f64>() / count;
260 let (spread, covariance) =
261 points().fold((0.0, 0.0), |(spread, covariance), (at, offset)| {
262 let at = at - mean_at;
263 (spread + at * at, covariance + at * (offset - mean_offset))
264 });
265 (spread > 0.0).then(|| (mean_at, mean_offset, covariance / spread))
266 }
267
268 pub fn last_at(&self) -> Option<i128> {
270 self.kept.back().map(|(at, _)| *at)
271 }
272
273 pub fn is_empty(&self) -> bool {
275 self.kept.is_empty()
276 }
277
278 pub fn keep_last(&mut self, count: usize) {
282 while self.kept.len() > count {
283 self.kept.pop_front();
284 }
285 }
286
287 pub fn clear(&mut self) {
289 self.kept.clear();
290 }
291
292 pub fn step(&mut self, by: i128) {
295 for (at, offset) in &mut self.kept {
296 *at += by;
297 *offset += by;
298 }
299 }
300}
301
302pub fn monotonic_now() -> Duration {
305 platform::monotonic_now()
306}
307
308pub fn system_now(system: SystemClock) -> Duration {
311 platform::system_now(system)
312}
313
314pub fn suspended() -> Duration {
318 platform::suspended()
319}
320
321pub fn precise_sleeps() {
326 platform::precise_sleeps();
327}
328
329#[cfg(target_os = "linux")]
330#[allow(unsafe_code)]
331mod platform {
332 use super::{Reading, SystemClock};
333 use std::io;
334 use std::mem::size_of;
335 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
336 use std::time::Duration;
337
338 pub struct HardwareClock {
339 _fd: OwnedFd,
340 id: libc::clockid_t,
341 }
342
343 fn read(id: libc::clockid_t) -> io::Result<Duration> {
344 let mut time = libc::timespec {
345 tv_sec: 0,
346 tv_nsec: 0,
347 };
348 if unsafe { libc::clock_gettime(id, &raw mut time) } < 0 {
350 return Err(io::Error::last_os_error());
351 }
352 Ok(Duration::new(time.tv_sec as u64, time.tv_nsec as u32))
353 }
354
355 impl HardwareClock {
356 pub fn open(index: u32, adjustable: bool) -> io::Result<Self> {
357 let path = format!("/dev/ptp{index}\0");
358 let mode = if adjustable {
359 libc::O_RDWR
360 } else {
361 libc::O_RDONLY
362 };
363 let raw = unsafe { libc::open(path.as_ptr().cast(), mode | libc::O_CLOEXEC) };
365 if raw < 0 {
366 return Err(io::Error::last_os_error());
367 }
368 let fd = unsafe { OwnedFd::from_raw_fd(raw) };
370 let id = ((!fd.as_raw_fd()) << 3) | 3;
373 Ok(Self { _fd: fd, id })
374 }
375
376 pub fn now(&self) -> io::Result<Duration> {
377 read(self.id)
378 }
379
380 fn adjust(&self, modes: libc::c_uint, frequency: libc::c_long) -> io::Result<libc::timex> {
383 let mut time: libc::timex = unsafe { std::mem::zeroed() };
385 time.modes = modes;
386 time.freq = frequency;
387 if unsafe { libc::clock_adjtime(self.id, &raw mut time) } < 0 {
389 return Err(io::Error::last_os_error());
390 }
391 Ok(time)
392 }
393
394 const SCALED_PPB: f64 = 65.536;
396
397 pub fn frequency_adjustment(&self) -> io::Result<f64> {
398 Ok(self.adjust(0, 0)?.freq as f64 / Self::SCALED_PPB)
399 }
400
401 pub fn set_frequency_adjustment(&self, ppb: f64) -> io::Result<()> {
402 self.adjust(
403 libc::ADJ_FREQUENCY,
404 (ppb * Self::SCALED_PPB).round() as libc::c_long,
405 )
406 .map(|_| ())
407 }
408
409 pub fn step(&self, by: i128) -> io::Result<()> {
410 let mut time: libc::timex = unsafe { std::mem::zeroed() };
412 time.modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO;
415 time.time.tv_sec = by.div_euclid(1_000_000_000) as libc::time_t;
416 time.time.tv_usec = by.rem_euclid(1_000_000_000) as libc::suseconds_t;
417 if unsafe { libc::clock_adjtime(self.id, &raw mut time) } < 0 {
419 return Err(io::Error::last_os_error());
420 }
421 Ok(())
422 }
423
424 pub fn reading_from_system(&self, system: SystemClock) -> io::Result<Reading> {
428 self.extended_reading(system).map_err(|error| {
429 if error.raw_os_error() == Some(libc::EOPNOTSUPP) {
430 io::Error::new(io::ErrorKind::Unsupported, error)
431 } else {
432 error
433 }
434 })
435 }
436
437 fn extended_reading(&self, system: SystemClock) -> io::Result<Reading> {
438 #[repr(C)]
440 #[derive(Clone, Copy, Default)]
441 struct Time {
442 seconds: i64,
443 nanoseconds: u32,
444 reserved: u32,
445 }
446 #[repr(C)]
449 struct Extended {
450 samples: u32,
451 clock: i32,
452 reserved: [u32; 2],
453 times: [[Time; 3]; 25],
454 }
455 const PTP_SYS_OFFSET_EXTENDED: libc::c_ulong =
457 0xc000_0000 | ((size_of::<Extended>() as libc::c_ulong) << 16) | (0x3d << 8) | 9;
458 let mut request = Extended {
459 samples: 9,
460 clock: id_of(system),
461 reserved: [0; 2],
462 times: [[Time::default(); 3]; 25],
463 };
464 if unsafe {
467 libc::ioctl(
468 self._fd.as_raw_fd(),
469 PTP_SYS_OFFSET_EXTENDED as _,
470 &raw mut request,
471 )
472 } < 0
473 {
474 return Err(io::Error::last_os_error());
475 }
476 let nanos = |time: Time| {
477 i128::from(time.seconds) * 1_000_000_000 + i128::from(time.nanoseconds)
478 };
479 request.times[..request.samples.min(25) as usize]
480 .iter()
481 .map(|[before, clock, after]| {
482 let (before, after) = (nanos(*before), nanos(*after));
483 Reading {
484 offset: nanos(*clock) - (before + after) / 2,
485 span: u64::try_from(after - before).unwrap_or(u64::MAX),
486 }
487 })
488 .min_by_key(|reading| reading.span)
489 .ok_or_else(|| io::Error::other("the clock gave no samples"))
490 }
491 }
492
493 pub fn monotonic_now() -> Duration {
494 read(libc::CLOCK_MONOTONIC).unwrap_or_default()
495 }
496
497 fn id_of(system: SystemClock) -> libc::clockid_t {
498 match system {
499 SystemClock::Realtime => libc::CLOCK_REALTIME,
500 SystemClock::Monotonic => libc::CLOCK_MONOTONIC,
501 SystemClock::MonotonicRaw => libc::CLOCK_MONOTONIC_RAW,
502 SystemClock::Tai => libc::CLOCK_TAI,
503 }
504 }
505
506 pub fn system_now(system: SystemClock) -> Duration {
507 read(id_of(system)).unwrap_or_default()
508 }
509
510 pub fn suspended() -> Duration {
511 let boot = read(libc::CLOCK_BOOTTIME).unwrap_or_default();
512 boot.saturating_sub(monotonic_now())
513 }
514
515 pub fn precise_sleeps() {
516 unsafe {
519 libc::prctl(libc::PR_SET_TIMERSLACK, 1 as libc::c_ulong);
520 }
521 }
522}
523
524#[cfg(not(target_os = "linux"))]
525mod platform {
526 use std::io;
527 use std::time::Duration;
528
529 pub struct HardwareClock;
530
531 impl HardwareClock {
532 pub fn open(_index: u32, _adjustable: bool) -> io::Result<Self> {
533 Err(unsupported())
534 }
535
536 pub fn now(&self) -> io::Result<Duration> {
537 Ok(Duration::ZERO)
538 }
539
540 pub fn frequency_adjustment(&self) -> io::Result<f64> {
541 Err(unsupported())
542 }
543
544 pub fn set_frequency_adjustment(&self, _ppb: f64) -> io::Result<()> {
545 Err(unsupported())
546 }
547
548 pub fn step(&self, _by: i128) -> io::Result<()> {
549 Err(unsupported())
550 }
551
552 pub fn reading_from_system(
553 &self,
554 _system: super::SystemClock,
555 ) -> io::Result<super::Reading> {
556 Err(unsupported())
557 }
558 }
559
560 fn unsupported() -> io::Error {
561 io::Error::new(
562 io::ErrorKind::Unsupported,
563 "hardware clocks are not supported on this system yet",
564 )
565 }
566
567 pub fn monotonic_now() -> Duration {
568 use std::sync::OnceLock;
569 static START: OnceLock<std::time::Instant> = OnceLock::new();
570 START.get_or_init(std::time::Instant::now).elapsed()
571 }
572
573 pub fn system_now(_system: super::SystemClock) -> Duration {
574 monotonic_now()
575 }
576
577 pub fn suspended() -> Duration {
578 Duration::ZERO
579 }
580
581 pub fn precise_sleeps() {}
582}
583
584#[cfg(test)]
585mod comparison_tests {
586 use super::*;
587
588 #[test]
589 fn a_steady_drift_is_followed_between_comparisons() {
590 let mut comparison = Comparison::default();
591 for step in 0..30i128 {
593 comparison.update(step * 100_000_000, 1_000 + step * 600);
594 }
595 let last = 29 * 100_000_000;
596 assert_eq!(comparison.offset_at(last), 1_000 + 29 * 600);
597 assert_eq!(
598 comparison.offset_at(last + 50_000_000),
599 1_000 + 29 * 600 + 300
600 );
601 assert_eq!(
602 comparison.offset_at(last - 50_000_000),
603 1_000 + 29 * 600 - 300
604 );
605 assert!((comparison.rate().unwrap() - 6e-6).abs() < 1e-12);
606 }
607
608 #[test]
609 fn the_error_of_one_comparison_is_mostly_filtered_out() {
610 let mut comparison = Comparison::default();
611 for step in 0..20i128 {
613 let error = if step % 2 == 0 { 50 } else { -50 };
614 comparison.update(step * 100_000_000, step * 600 + error);
615 }
616 let last = 19 * 100_000_000;
617 let off = comparison.offset_at(last) - 19 * 600;
618 assert!(off.abs() <= 15, "off by {off} ns");
619 }
620
621 #[test]
622 fn a_longer_span_keeps_older_comparisons() {
623 let mut short = Comparison::default();
624 let mut long = Comparison::keeping(Duration::from_secs(16));
625 for step in 0..100i128 {
626 short.update(step * 100_000_000, step * 600);
627 long.update(step * 100_000_000, step * 600);
628 }
629 assert_eq!(short.kept.len(), 21);
630 assert_eq!(long.kept.len(), 100);
631 long.clear();
632 long.update(0, 0);
633 long.update(20_000_000_000, 0);
634 assert_eq!(long.kept.len(), 2);
635 }
636
637 #[test]
638 fn a_step_moves_the_line_and_keeps_its_rate() {
639 let mut comparison = Comparison::keeping(Duration::from_secs(16));
640 for step in 0..100i128 {
641 comparison.update(step * 100_000_000, 5_000 + step * 774);
642 }
643 let rate = comparison.rate();
644 let before = comparison.offset_at(10_000_000_000);
645 let by = (1 << 32) * 1_000;
646 comparison.step(by);
647 assert_eq!(comparison.rate(), rate);
648 assert_eq!(comparison.offset_at(10_000_000_000 + by), before + by);
649 assert_eq!(comparison.last_at(), Some(9_900_000_000 + by));
650 comparison.update(10_000_000_000 + by, before + by);
651 assert_eq!(comparison.kept.len(), 101);
652 }
653
654 #[test]
655 fn one_comparison_is_taken_as_it_is() {
656 let mut comparison = Comparison::default();
657 assert!(comparison.is_empty());
658 assert_eq!(comparison.offset_at(5), 0);
659 comparison.update(10, 42);
660 assert_eq!(comparison.offset_at(1_000_000), 42);
661 assert_eq!(comparison.rate(), None);
662 comparison.clear();
663 assert!(comparison.is_empty());
664 }
665}
666
667#[cfg(all(test, target_os = "linux"))]
668mod tests {
669 use super::*;
670
671 #[test]
672 fn a_hardware_clock_reads_when_there_is_one() {
673 let Ok(clock) = HardwareClock::open(0) else {
675 return;
676 };
677 let first = clock.offset_from_monotonic().unwrap();
680 std::thread::sleep(Duration::from_millis(20));
681 let second = clock.offset_from_monotonic().unwrap();
682 assert!((second - first).abs() < 100_000, "{first} then {second}");
683 }
684
685 #[test]
686 fn the_monotonic_clock_moves_on() {
687 let before = monotonic_now();
688 std::thread::sleep(Duration::from_millis(2));
689 assert!(monotonic_now() > before);
690 }
691}