Debian Codegraph @

src/unix.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use crate::{Clock, LeapIndicator, TimeOffset, Timestamp};
2 use std::time::Duration;
3 #[cfg(target_os = "linux")]
4 use std::{
5 os::unix::io::{IntoRawFd, RawFd},
6 path::Path,
7 };
8
9 /// A Unix OS clock
10 #[derive(Debug, Clone, Copy)]
11 pub struct UnixClock {
12 clock: libc::clockid_t,
13 #[cfg(target_os = "linux")]
14 fd: Option<RawFd>,
15 }
16
17 impl UnixClock {
18 /// The standard realtime clock on unix systems.
19 ///
20 /// ```no_run
21 /// use clock_steering::{Clock, unix::UnixClock};
22 ///
23 /// fn main() -> std::io::Result<()> {
24 /// let clock = UnixClock::CLOCK_REALTIME;
25 /// let now = clock.now()?;
26 ///
27 /// println!("{now:?}");
28 ///
29 /// Ok(())
30 /// }
31 /// ```
32 pub const CLOCK_REALTIME: Self = UnixClock {
33 clock: libc::CLOCK_REALTIME,
34 #[cfg(target_os = "linux")]
35 fd: None,
36 };
37
38 /// TAI time on linux systems.
39 ///
40 /// ```no_run
41 /// use clock_steering::{Clock, unix::UnixClock};
42 ///
43 /// fn main() -> std::io::Result<()> {
44 /// let clock = UnixClock::CLOCK_TAI;
45 /// let now = clock.now()?;
46 ///
47 /// println!("{now:?}");
48 ///
49 /// Ok(())
50 /// }
51 /// ```
52 #[cfg(target_os = "linux")]
53 pub const CLOCK_TAI: Self = UnixClock {
54 clock: libc::CLOCK_TAI,
55 fd: None,
56 };
57
58 /// Open a clock device.
59 ///
60 /// ```no_run
61 /// use clock_steering::{Clock, unix::UnixClock};
62 ///
63 /// fn main() -> std::io::Result<()> {
64 /// let clock = UnixClock::open("/dev/ptp0")?;
65 /// let now = clock.now()?;
66 ///
67 /// println!("{now:?}");
68 ///
69 /// Ok(())
70 /// }
71 /// ```
72 #[cfg(target_os = "linux")]
73 pub fn open(path: impl AsRef<Path>) -> std::io::Result<Self> {
74 let file = std::fs::OpenOptions::new()
75 .write(true)
76 .read(true)
77 .open(path)?;
78
79 // we need an owned fd. the file will be closed when the process exits.
80 Ok(Self::safe_from_raw_fd(file.into_raw_fd()))
81 }
82
83 // Consume an fd and produce a clock id. Clock id is only valid
84 // so long as the fd is open, so the RawFd here should
85 // not be borrowed.
86 #[cfg(target_os = "linux")]
87 fn safe_from_raw_fd(fd: RawFd) -> Self {
88 let clock = ((!(fd as libc::clockid_t)) << 3) | 3;
89
90 Self {
91 clock,
92 fd: Some(fd),
93 }
94 }
95
96 /// Determine offset between file clock and TAI clock (if any)
97 /// Returns two system timestamps sandwhiching a timestamp from the
98 /// hardware clock.
99 #[cfg(target_os = "linux")]
100 pub fn system_offset(&self) -> Result<(Timestamp, Timestamp, Timestamp), Error> {
101 let Some(fd) = self.fd else {
102 return Err(Error::Invalid);
103 };
104
105 // TODO: remove type and constant definitions once libc updates
106 #[repr(C)]
107 #[derive(Default, Clone, Copy, PartialEq, Eq)]
108 #[allow(non_camel_case_types)]
109 struct ptp_clock_time {
110 sec: libc::__s64,
111 nsec: libc::__u32,
112 reserved: libc::__u32,
113 }
114
115 #[repr(C)]
116 #[derive(Clone, Copy, PartialEq, Eq)]
117 #[allow(non_camel_case_types)]
118 struct ptp_sys_offset {
119 n_samples: libc::c_uint,
120 rsv: [libc::c_uint; 3],
121 ts: [ptp_clock_time; 51],
122 }
123
124 // Needed as arrays larger than 32 elements don't implement default.
125 impl Default for ptp_sys_offset {
126 fn default() -> Self {
127 Self {
128 n_samples: Default::default(),
129 rsv: Default::default(),
130 ts: [Default::default(); 51],
131 }
132 }
133 }
134
135 const PTP_SYS_OFFSET: libc::c_uint = 0x43403d05;
136
137 let mut offset = ptp_sys_offset {
138 n_samples: 1,
139 ..Default::default()
140 };
141
142 // # Safety
143 // Safe since PTP_SYS_OFFSET expects as argument a mutable pointer to
144 // ptp_sys_offset and offset is valid during the call
145 if unsafe { libc::ioctl(fd, PTP_SYS_OFFSET as _, &mut offset as *mut ptp_sys_offset) } != 0
146 {
147 let t1 = Self::CLOCK_TAI.now();
148 let tp = self.now();
149 let t2 = Self::CLOCK_TAI.now();
150
151 Ok((t1?, tp?, t2?))
152 } else {
153 let tai_offset = Self::CLOCK_TAI.get_tai()?;
154
155 Ok((
156 Timestamp {
157 seconds: (offset.ts[0].sec + tai_offset as i64) as _,
158 nanos: offset.ts[0].nsec as _,
159 },
160 Timestamp {
161 seconds: offset.ts[1].sec as _,
162 nanos: offset.ts[1].nsec as _,
163 },
164 Timestamp {
165 seconds: (offset.ts[2].sec + tai_offset as i64) as _,
166 nanos: offset.ts[2].nsec as _,
167 },
168 ))
169 }
170 }
171
172 fn clock_adjtime(&self, timex: &mut libc::timex) -> Result<(), Error> {
173 // We don't care about the time status, so the non-error
174 // information in the return value of clock_adjtime can be ignored.
175 //
176 // # Safety
177 //
178 // The clock_adjtime call is safe because the reference always
179 // points to a valid libc::timex.
180 //
181 // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL
182 // error https://man.archlinux.org/man/clock_adjtime.2.en#EINVAL~4
183 #[cfg(target_os = "linux")]
184 use libc::clock_adjtime as adjtime;
185
186 #[cfg(any(target_os = "freebsd", target_os = "macos"))]
187 unsafe fn adjtime(clk_id: libc::clockid_t, buf: *mut libc::timex) -> libc::c_int {
188 assert_eq!(
189 clk_id,
190 libc::CLOCK_REALTIME,
191 "only the REALTIME clock is supported"
192 );
193
194 libc::ntp_adjtime(buf)
195 }
196
197 if unsafe { adjtime(self.clock, timex) } == -1 {
198 Err(convert_errno())
199 } else {
200 Ok(())
201 }
202 }
203
204 fn ntp_adjtime(timex: &mut libc::timex) -> Result<(), Error> {
205 #[cfg(any(target_os = "freebsd", target_os = "macos", target_env = "gnu"))]
206 use libc::ntp_adjtime as adjtime;
207
208 // ntp_adjtime is equivalent to adjtimex for our purposes
209 //
210 // https://man7.org/linux/man-pages/man2/adjtimex.2.html
211 #[cfg(all(target_os = "linux", target_env = "musl"))]
212 use libc::adjtimex as adjtime;
213
214 // We don't care about the time status, so the non-error
215 // information in the return value of ntp_adjtime can be ignored.
216 // The ntp_adjtime call is safe because the reference always
217 // points to a valid libc::timex.
218 if unsafe { adjtime(timex) } == -1 {
219 Err(convert_errno())
220 } else {
221 Ok(())
222 }
223 }
224
225 /// Adjust the clock state with a [`libc::timex`] specifying the desired changes.
226 ///
227 /// This is a lowlevel function. If possible, use more specialized (trait) methods.
228 ///
229 /// Note that [`libc::timex`] has a different layout between different operating systems, and
230 /// not all fields are available on all operating systems. Keep this in mind when writing
231 /// platform-independent code.
232 fn adjtime(&self, timex: &mut libc::timex) -> Result<(), Error> {
233 if self.clock == libc::CLOCK_REALTIME {
234 Self::ntp_adjtime(timex)
235 } else {
236 self.clock_adjtime(timex)
237 }
238 }
239
240 #[cfg_attr(target_os = "linux", allow(unused))]
241 fn clock_gettime(&self) -> Result<libc::timespec, Error> {
242 let mut timespec = EMPTY_TIMESPEC;
243
244 // # Safety
245 //
246 // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL
247 // error https://linux.die.net/man/3/clock_gettime
248 //
249 // The timespec pointer is valid.
250 cerr(unsafe { libc::clock_gettime(self.clock, &mut timespec) })?;
251
252 Ok(timespec)
253 }
254
255 #[cfg_attr(target_os = "linux", allow(unused))]
256 fn clock_settime(&self, mut timespec: libc::timespec) -> Result<(), Error> {
257 while timespec.tv_nsec > 1_000_000_000 {
258 timespec.tv_sec += 1;
259 timespec.tv_nsec -= 1_000_000_000;
260 }
261
262 // # Safety
263 //
264 // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL
265 // error https://linux.die.net/man/3/clock_settime
266 //
267 // The timespec pointer is valid.
268 unsafe { cerr(libc::clock_settime(self.clock, &timespec))? };
269
270 Ok(())
271 }
272
273 #[cfg_attr(target_os = "linux", allow(unused))]
274 fn step_clock_by_timespec(&self, offset: TimeOffset) -> Result<Timestamp, Error> {
275 let mut timespec = self.clock_gettime()?;
276
277 // see https://github.com/rust-lang/libc/issues/1848
278 #[cfg_attr(target_env = "musl", allow(deprecated))]
279 {
280 timespec.tv_sec += offset.seconds as libc::time_t;
281 timespec.tv_nsec += offset.nanos as libc::c_long;
282 }
283
284 self.clock_settime(timespec)?;
285
286 Ok(current_time_timespec(timespec, Precision::Nano))
287 }
288
289 fn error_estimate_timex(est_error: Duration, max_error: Duration) -> libc::timex {
290 let modes = libc::MOD_ESTERROR | libc::MOD_MAXERROR;
291
292 // these fields are always in microseconds
293 let esterror = est_error.as_nanos() as libc::c_long / 1000;
294 let maxerror = max_error.as_nanos() as libc::c_long / 1000;
295
•296 let mut result = EMPTY_TIMEX;
297 result.modes = modes;
298 result.esterror = esterror.into();
299 result.maxerror = maxerror.into();
300 result
301 }
302
303 #[cfg(target_os = "linux")]
304 fn step_clock_timex(offset: TimeOffset) -> libc::timex {
305 // we provide the offset in nanoseconds
306 let modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO;
307
308 let time = libc::timeval {
309 tv_sec: offset.seconds,
•310 tv_usec: offset.nanos as _,
311 };
312
•313 let mut result = EMPTY_TIMEX;
314 result.modes = modes;
315 result.time = time;
316 result
317 }
318
319 #[cfg(target_os = "linux")]
320 fn step_clock_by_timex(&self, offset: TimeOffset) -> Result<Timestamp, Error> {
321 let mut timex = Self::step_clock_timex(offset);
322 self.adjtime(&mut timex)?;
323 self.extract_current_time(&timex)
324 }
325
326 fn extract_current_time(&self, _timex: &libc::timex) -> Result<Timestamp, Error> {
327 #[cfg(target_os = "linux")]
328 // hardware clocks may not report the timestamp
329 if _timex.time.tv_sec != 0 && _timex.time.tv_usec != 0 {
330 // in a timex, the status flag determines precision
331 let precision = match _timex.status & libc::STA_NANO {
332 0 => Precision::Micro,
333 _ => Precision::Nano,
334 };
335
336 return Ok(current_time_timeval(_timex.time, precision));
337 }
338
339 // clock_gettime always gives nanoseconds
340 let timespec = self.clock_gettime()?;
341 Ok(current_time_timespec(timespec, Precision::Nano))
342 }
343
344 #[inline(always)]
345 fn update_timex<F>(&self, f: F) -> Result<(), Error>
346 where
347 F: FnOnce(libc::timex) -> libc::timex,
348 {
349 let mut timex = EMPTY_TIMEX;
350 self.adjtime(&mut timex)?;
351
352 timex = f(timex);
353
354 self.adjtime(&mut timex)
355 }
356
357 #[inline(always)]
358 fn update_status<F>(&self, f: F) -> Result<(), Error>
359 where
360 F: FnOnce(libc::c_int) -> libc::c_int,
361 {
362 self.update_timex(|mut timex| {
363 // We are setting the status bits
364 timex.modes = libc::MOD_STATUS;
365
366 // update the status flags
367 timex.status = f(timex.status);
368
369 timex
370 })
371 }
372
373 fn set_frequency_timex(ppm: f64) -> libc::timex {
374 // We do an offset with precision
375 let mut timex = EMPTY_TIMEX;
376
377 // set the frequency (MOD_FREQUENCY is an alias for ADJ_FREQUENCY on linux)
378 timex.modes = libc::MOD_FREQUENCY;
379
380 // NTP Kapi expects frequency adjustment in units of 2^-16 ppm
381 // but our input is in units of seconds drift per second, so convert.
382 let frequency = (ppm * 65536.0).round() as libc::c_long;
383
384 // Since Linux 2.6.26, the supplied value is clamped to the range (-32768000,
385 // +32768000). In older kernels, an EINVAL error occurs if the supplied value is
386 // out of range. (32768000 is 500 << 16)
•387 timex.freq = frequency.clamp(-32_768_000 + 1, 32_768_000 - 1).into();
388
389 timex
390 }
391 }
392
393 impl Clock for UnixClock {
394 type Error = Error;
395
396 fn now(&self) -> Result<Timestamp, Self::Error> {
397 let mut ntp_kapi_timex = EMPTY_TIMEX;
398
399 if self.adjtime(&mut ntp_kapi_timex).is_ok() {
400 self.extract_current_time(&ntp_kapi_timex)
401 } else {
402 self.clock_gettime()
403 .map(|ts| current_time_timespec(ts, Precision::Nano))
404 }
405 }
406
407 fn resolution(&self) -> Result<Timestamp, Self::Error> {
408 let mut timespec = EMPTY_TIMESPEC;
409
410 cerr(unsafe { libc::clock_getres(self.clock, &mut timespec) })?;
411
412 Ok(current_time_timespec(timespec, Precision::Nano))
413 }
414
415 fn get_frequency(&self) -> Result<f64, Self::Error> {
416 let mut timex = EMPTY_TIMEX;
417 self.adjtime(&mut timex)?;
418
419 Ok((timex.freq as f64) / 65536.0)
420 }
421
422 fn set_frequency(&self, frequency: f64) -> Result<Timestamp, Self::Error> {
423 let mut timex = Self::set_frequency_timex(frequency);
424 self.adjtime(&mut timex)?;
425 self.extract_current_time(&timex)
426 }
427
428 #[cfg(target_os = "linux")]
429 fn step_clock(&self, offset: TimeOffset) -> Result<Timestamp, Self::Error> {
430 self.step_clock_by_timex(offset)
431 }
432
433 #[cfg(any(target_os = "freebsd", target_os = "macos"))]
434 fn step_clock(&self, offset: TimeOffset) -> Result<Timestamp, Self::Error> {
435 self.step_clock_by_timespec(offset)
436 }
437
438 fn set_leap_seconds(&self, leap_status: LeapIndicator) -> Result<(), Self::Error> {
439 self.update_status(|status| {
440 (status & !(libc::STA_UNSYNC | libc::STA_INS | libc::STA_DEL))
441 | leap_status.as_status_bit()
442 })
443 }
444
445 fn error_estimate_update(
446 &self,
447 est_error: Duration,
448 max_error: Duration,
449 ) -> Result<(), Self::Error> {
450 let mut timex = Self::error_estimate_timex(est_error, max_error);
451 Error::ignore_not_supported(self.adjtime(&mut timex))
452 }
453
454 fn disable_kernel_ntp_algorithm(&self) -> Result<(), Self::Error> {
455 let mut timex = EMPTY_TIMEX;
456 self.adjtime(&mut timex)?;
457
458 // We are setting the status bits
459 timex.modes = libc::MOD_STATUS;
460
461 // Disable all kernel time control loops (phase lock, frequency lock, pps time and pps frequency).
462 timex.status &= !(libc::STA_PLL | libc::STA_FLL | libc::STA_PPSTIME | libc::STA_PPSFREQ);
463
464 // ignore if we cannot disable the kernel time control loops (e.g. external clocks)
465 Error::ignore_not_supported(self.adjtime(&mut timex))
466 }
467
468 #[cfg(target_os = "linux")]
469 fn set_tai(&self, tai_offset: i32) -> Result<(), Error> {
•470 let mut timex = EMPTY_TIMEX;
471 timex.modes = libc::ADJ_TAI;
472 timex.constant = tai_offset as _;
473
474 self.clock_adjtime(&mut timex)
475 }
476
477 #[cfg(not(target_os = "linux"))]
478 fn set_tai(&self, _tai_offset: i32) -> Result<(), Error> {
479 Err(Error::NotSupported)
480 }
481
482 #[cfg(target_os = "linux")]
483 fn get_tai(&self) -> Result<i32, Error> {
484 let mut timex = EMPTY_TIMEX;
485 if self.clock_adjtime(&mut timex).is_ok() {
486 Ok(timex.tai)
487 } else {
488 // hardware clock which doesn't have an offset anyway
489 Ok(0)
490 }
491 }
492
493 #[cfg(not(target_os = "linux"))]
494 fn get_tai(&self) -> Result<i32, Error> {
495 Err(Error::NotSupported)
496 }
497 }
498
499 /// Errors that can be thrown by modifying a unix clock
500 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
501 pub enum Error {
502 /// Insufficient permissions to interact with the clock.
503 NoPermission,
504 /// No access to the clock.
505 NoAccess,
506 /// Invalid operation requested
507 Invalid,
508 /// Clock device has gone away
509 NoDevice,
510 /// Clock operation requested is not supported by operating system.
511 NotSupported,
512 }
513
514 impl core::fmt::Display for Error {
515 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
516 use Error::*;
517
518 let msg = match self {
519 NoPermission => "Insufficient permissions to interact with the clock.",
520 NoAccess => "No access to the clock.",
521 Invalid => "Invalid operation requested",
522 NoDevice => "Clock device has gone away",
523 NotSupported => "Clock operation requested is not supported by operating system.",
524 };
525
526 f.write_str(msg)
527 }
528 }
529
530 impl std::error::Error for Error {}
531
532 impl Error {
533 /// Turn the `Error::NotSupported` error variant into `Ok(())`, to silently
534 /// ignore operations that are not supported by the current clock. All
535 /// other input values are untouched.
536 pub fn ignore_not_supported(res: Result<(), Error>) -> Result<(), Error> {
537 match res {
538 Err(Error::NotSupported) => Ok(()),
539 other => other,
540 }
541 }
542
543 // TODO: use https://doc.rust-lang.org/std/io/type.RawOsError.html when stable
544 fn into_raw_os_error(self) -> i32 {
545 match self {
546 Self::NoPermission => libc::EPERM,
547 Self::NoAccess => libc::EACCES,
548 Self::Invalid => libc::EINVAL,
549 Self::NoDevice => libc::ENODEV,
550 Self::NotSupported => libc::EOPNOTSUPP,
551 }
552 }
553 }
554
555 impl From<Error> for std::io::Error {
556 fn from(value: Error) -> Self {
557 std::io::Error::from_raw_os_error(value.into_raw_os_error())
558 }
559 }
560
561 fn error_number() -> libc::c_int {
562 #[cfg(target_os = "linux")]
563 unsafe {
564 *libc::__errno_location()
565 }
566
567 #[cfg(not(target_os = "linux"))]
568 unsafe {
569 *libc::__error()
570 }
571 }
572
573 // Convert those error numbers that can occur for calls to the following
574 // functions
575 // - ntp_adjtimex https://man7.org/linux/man-pages/man3/ntp_adjtime.3.html
576 // - clock_gettime & clock_settime https://man7.org/linux/man-pages/man3/clock_gettime.3.html
577 fn convert_errno() -> Error {
578 match error_number() {
579 libc::EINVAL => Error::Invalid,
580 // The documentation is a bit unclear if this can happen with
581 // non-dynamic clocks like the ntp kapi clock, however deal with it just in case.
582 libc::ENODEV => Error::NoDevice,
583 libc::EOPNOTSUPP => Error::NotSupported,
584 libc::EPERM => Error::NoPermission,
585 libc::EACCES => Error::NoAccess,
586 libc::EFAULT => unreachable!("we always pass in valid (accessible) buffers"),
587 // No other errors should occur
588 other => {
589 let error = std::io::Error::from_raw_os_error(other);
590 unreachable!("error code `{other}` ({error:?}) should not occur")
591 }
592 }
593 }
594
595 fn cerr(c_int: libc::c_int) -> Result<(), Error> {
596 if c_int == -1 {
597 Err(convert_errno())
598 } else {
599 Ok(())
600 }
601 }
602
603 pub(crate) enum Precision {
604 Nano,
605 #[cfg_attr(any(target_os = "freebsd", target_os = "macos"), allow(unused))]
606 Micro,
607 }
608
609 #[cfg_attr(target_os = "linux", allow(unused))]
610 fn current_time_timespec(timespec: libc::timespec, precision: Precision) -> Timestamp {
611 let mut seconds = timespec.tv_sec;
612
613 let nanos: i32 = timespec.tv_nsec as _;
614
615 let mut nanos = match precision {
616 Precision::Nano => nanos,
617 Precision::Micro => nanos.checked_mul(1000).unwrap_or_default(),
618 };
619
620 // on macOS (at least) we've observed higher nanosecond counts than appear valid
621 while nanos > 1_000_000_000 {
622 seconds = seconds.wrapping_add(1);
623 nanos -= 1_000_000_000;
624 }
625
626 // we disallow negative nanoseconds
627 while nanos < 0 {
628 seconds = seconds.wrapping_sub(1);
629 nanos += 1_000_000_000;
630 }
631
632 Timestamp {
633 seconds,
634 nanos: nanos as u32,
635 }
636 }
637
638 #[cfg_attr(not(target_os = "linux"), allow(unused))]
639 fn current_time_timeval(timespec: libc::timeval, precision: Precision) -> Timestamp {
640 let seconds = timespec.tv_sec;
641 let nanos = match precision {
642 Precision::Nano => timespec.tv_usec as u32,
643 Precision::Micro => (timespec.tv_usec as u32)
644 .checked_mul(1000)
645 .unwrap_or_default(),
646 };
647
648 Timestamp { seconds, nanos }
649 }
650
•651 const EMPTY_TIMESPEC: libc::timespec = unsafe { core::mem::zeroed() };
652
653 // Libc has no good other way of obtaining this, so let's at least make our
654 // functions more readable.
655 #[cfg(all(target_os = "linux", target_env = "gnu"))]
•656 pub const EMPTY_TIMEX: libc::timex = unsafe { core::mem::zeroed() };
657
658 #[cfg(all(target_os = "linux", target_env = "musl"))]
659 pub const EMPTY_TIMEX: libc::timex = libc::timex {
660 modes: 0,
661 offset: 0,
662 freq: 0,
663 maxerror: 0,
664 esterror: 0,
665 status: 0,
666 constant: 0,
667 precision: 0,
668 tolerance: 0,
669 time: libc::timeval {
670 tv_sec: 0,
671 tv_usec: 0,
672 },
673 tick: 0,
674 ppsfreq: 0,
675 jitter: 0,
676 shift: 0,
677 stabil: 0,
678 jitcnt: 0,
679 calcnt: 0,
680 errcnt: 0,
681 stbcnt: 0,
682 tai: 0,
683 __padding: [0; 11],
684 };
685
686 #[cfg(any(target_os = "freebsd", target_os = "macos"))]
687 pub const EMPTY_TIMEX: libc::timex = libc::timex {
688 modes: 0,
689 offset: 0,
690 freq: 0,
691 maxerror: 0,
692 esterror: 0,
693 status: 0,
694 constant: 0,
695 precision: 0,
696 tolerance: 0,
697 ppsfreq: 0,
698 jitter: 0,
699 shift: 0,
700 stabil: 0,
701 jitcnt: 0,
702 calcnt: 0,
703 errcnt: 0,
704 stbcnt: 0,
705 };
706
707 impl LeapIndicator {
708 fn as_status_bit(self) -> libc::c_int {
709 match self {
710 LeapIndicator::NoWarning => 0,
711 LeapIndicator::Leap61 => libc::STA_INS,
712 LeapIndicator::Leap59 => libc::STA_DEL,
713 LeapIndicator::Unknown => libc::STA_UNSYNC,
714 }
715 }
716 }
717
718 #[cfg(test)]
719 mod tests {
720 use super::*;
721
722 #[test]
723 fn test_time_now_does_not_crash() {
724 let clock = UnixClock::CLOCK_REALTIME;
725 assert_ne!(clock.now().unwrap(), Timestamp::default(),);
726 }
727
728 #[test]
729 fn realtime_gettime() {
730 let clock = UnixClock::CLOCK_REALTIME;
731 let time = clock.clock_gettime().unwrap();
732
733 assert_ne!((time.tv_sec, time.tv_nsec), (0, 0))
734 }
735
736 #[test]
737 #[ignore = "requires permissions, useful for testing permissions"]
738 fn ptp0_gettime() {
739 let clock = UnixClock::CLOCK_REALTIME;
740 let time = clock.clock_gettime().unwrap();
741
742 assert_ne!((time.tv_sec, time.tv_nsec), (0, 0))
743 }
744
745 #[test]
746 #[ignore = "requires permissions, useful for testing permissions"]
747 fn step_clock() {
748 UnixClock::CLOCK_REALTIME
749 .step_clock(TimeOffset {
750 seconds: 0,
751 nanos: 0,
752 })
753 .unwrap();
754 }
755
756 #[cfg(target_os = "linux")]
757 #[test]
758 fn test_step_clock() {
759 let offset = TimeOffset {
760 seconds: 1,
761 nanos: 200000000,
762 };
763 let timex = UnixClock::step_clock_timex(offset);
764
765 assert_eq!(timex.modes, libc::ADJ_SETOFFSET | libc::ADJ_NANO);
766
767 assert_eq!(timex.time.tv_sec, 1);
768 assert_eq!(timex.time.tv_usec, 200_000_000);
769 }
770
771 #[test]
772 fn test_error_estimate() {
773 let est_error = Duration::from_secs_f64(0.5);
774 let max_error = Duration::from_secs_f64(1.2);
775 let timex = UnixClock::error_estimate_timex(est_error, max_error);
776
777 assert_eq!(timex.modes, libc::MOD_ESTERROR | libc::MOD_MAXERROR);
778
779 // these fields are always in microseconds
780 assert_eq!(timex.esterror, 500_000);
781 assert_eq!(timex.maxerror, 1_200_000);
782 }
783
784 #[test]
785 fn test_now() {
786 let resolution = UnixClock::CLOCK_REALTIME.now().unwrap();
787
788 assert_ne!(resolution, Timestamp::default());
789 }
790
791 #[test]
792 fn test_resolution() {
793 let resolution = UnixClock::CLOCK_REALTIME.resolution().unwrap();
794
795 assert_ne!(resolution, Timestamp::default());
796 }
797 }