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 now(&self) -> io::Result<Duration> {
60 self.inner.now()
61 }
62
63 pub fn offset_from(&self, other: &HardwareClock) -> io::Result<i128> {
68 self.reading_from(other).map(|reading| reading.offset)
69 }
70
71 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 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 pub fn reading_from_system_clock(&self, system: SystemClock) -> io::Result<Reading> {
95 self.inner.reading_from_system(system)
96 }
97
98 pub fn offset_from_monotonic(&self) -> io::Result<i128> {
104 self.offset_read_against(SystemClock::Monotonic)
105 }
106
107 pub fn offset_read_against(&self, system: SystemClock) -> io::Result<i128> {
111 self.reading_against(system).map(|reading| reading.offset)
112 }
113
114 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub struct Reading {
149 pub offset: i128,
151 pub span: u64,
153}
154
155const SPAN: i128 = 2_000_000_000;
158
159#[derive(Debug, Clone, Default)]
165pub struct Comparison {
166 kept: VecDeque<(i128, i128)>,
168}
169
170impl Comparison {
171 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 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 pub fn rate(&self) -> Option<f64> {
202 self.fit().map(|(_, _, rate)| rate)
203 }
204
205 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 pub fn is_empty(&self) -> bool {
231 self.kept.is_empty()
232 }
233
234 pub fn keep_last(&mut self, count: usize) {
238 while self.kept.len() > count {
239 self.kept.pop_front();
240 }
241 }
242
243 pub fn clear(&mut self) {
245 self.kept.clear();
246 }
247}
248
249pub fn monotonic_now() -> Duration {
252 platform::monotonic_now()
253}
254
255pub fn system_now(system: SystemClock) -> Duration {
258 platform::system_now(system)
259}
260
261pub fn suspended() -> Duration {
265 platform::suspended()
266}
267
268pub 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 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 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 let fd = unsafe { OwnedFd::from_raw_fd(raw) };
317 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 fn adjust(&self, modes: libc::c_uint, frequency: libc::c_long) -> io::Result<libc::timex> {
330 let mut time: libc::timex = unsafe { std::mem::zeroed() };
332 time.modes = modes;
333 time.freq = frequency;
334 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 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 pub fn reading_from_system(&self, system: SystemClock) -> io::Result<Reading> {
360 #[repr(C)]
362 #[derive(Clone, Copy, Default)]
363 struct Time {
364 seconds: i64,
365 nanoseconds: u32,
366 reserved: u32,
367 }
368 #[repr(C)]
371 struct Extended {
372 samples: u32,
373 clock: i32,
374 reserved: [u32; 2],
375 times: [[Time; 3]; 25],
376 }
377 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 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 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 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 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 let Ok(clock) = HardwareClock::open(0) else {
560 return;
561 };
562 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}