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, Default)]
184pub struct Comparison {
185 kept: VecDeque<(i128, i128)>,
187}
188
189impl Comparison {
190 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 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 pub fn rate(&self) -> Option<f64> {
221 self.fit().map(|(_, _, rate)| rate)
222 }
223
224 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 pub fn is_empty(&self) -> bool {
250 self.kept.is_empty()
251 }
252
253 pub fn keep_last(&mut self, count: usize) {
257 while self.kept.len() > count {
258 self.kept.pop_front();
259 }
260 }
261
262 pub fn clear(&mut self) {
264 self.kept.clear();
265 }
266}
267
268pub fn monotonic_now() -> Duration {
271 platform::monotonic_now()
272}
273
274pub fn system_now(system: SystemClock) -> Duration {
277 platform::system_now(system)
278}
279
280pub fn suspended() -> Duration {
284 platform::suspended()
285}
286
287pub 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 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 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 let fd = unsafe { OwnedFd::from_raw_fd(raw) };
336 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 fn adjust(&self, modes: libc::c_uint, frequency: libc::c_long) -> io::Result<libc::timex> {
349 let mut time: libc::timex = unsafe { std::mem::zeroed() };
351 time.modes = modes;
352 time.freq = frequency;
353 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 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 let mut time: libc::timex = unsafe { std::mem::zeroed() };
378 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 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 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 #[repr(C)]
406 #[derive(Clone, Copy, Default)]
407 struct Time {
408 seconds: i64,
409 nanoseconds: u32,
410 reserved: u32,
411 }
412 #[repr(C)]
415 struct Extended {
416 samples: u32,
417 clock: i32,
418 reserved: [u32; 2],
419 times: [[Time; 3]; 25],
420 }
421 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 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 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 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 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 let Ok(clock) = HardwareClock::open(0) else {
608 return;
609 };
610 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}