clock-steering 0.3.0

Functionality for manual clock steering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
use statime_base::{Clock, ClockError, Duration, LeapStatus, Timestamp, TAI, UTC};

#[cfg(target_os = "linux")]
use crate::linux_ioctls::{ptp_clock_getcaps, PtpClockCaps};
use std::marker::PhantomData;
#[cfg(target_os = "linux")]
use std::mem::MaybeUninit;
#[cfg(target_os = "linux")]
use std::{
    os::unix::io::{IntoRawFd, RawFd},
    path::Path,
};

/// A Unix OS clock
pub struct UnixClock<Timescale> {
    clock: libc::clockid_t,
    #[cfg(target_os = "linux")]
    fd: Option<RawFd>,
    _timescale: PhantomData<Timescale>,
}

impl<Timescale> std::fmt::Debug for UnixClock<Timescale> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        #[cfg(target_os = "linux")]
        {
            f.debug_struct("UnixClock")
                .field("clock", &self.clock)
                .field("fd", &self.fd)
                .field("_timescale", &self._timescale)
                .finish()
        }

        #[cfg(not(target_os = "linux"))]
        {
            f.debug_struct("UnixClock")
                .field("clock", &self.clock)
                .field("_timescale", &self._timescale)
                .finish()
        }
    }
}

impl<Timescale> Clone for UnixClock<Timescale> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Timescale> Copy for UnixClock<Timescale> {}

impl UnixClock<UTC> {
    /// The standard realtime clock on unix systems.
    ///
    /// ```no_run
    /// use clock_steering::unix::UnixClock;
    /// use statime_base::Clock;
    ///
    /// fn main() {
    ///     let clock = UnixClock::CLOCK_REALTIME;
    ///     let now = clock.now().unwrap();
    ///
    ///     println!("{now:?}");
    /// }
    /// ```
    pub const CLOCK_REALTIME: Self = UnixClock {
        clock: libc::CLOCK_REALTIME,
        #[cfg(target_os = "linux")]
        fd: None,
        _timescale: PhantomData,
    };
}

impl UnixClock<TAI> {
    /// TAI time on linux systems.
    ///
    /// ```no_run
    /// use clock_steering::unix::UnixClock;
    /// use statime_base::Clock;
    ///
    /// fn main() {
    ///     let clock = UnixClock::CLOCK_TAI;
    ///     let now = clock.now().unwrap();
    ///
    ///     println!("{now:?}");
    /// }
    /// ```
    #[cfg(target_os = "linux")]
    pub const CLOCK_TAI: Self = UnixClock {
        clock: libc::CLOCK_TAI,
        fd: None,
        _timescale: PhantomData,
    };

    /// Open a clock device.
    ///
    /// ```no_run
    /// use clock_steering::unix::UnixClock;
    /// use statime_base::Clock;
    ///
    /// fn main() {
    ///     let clock = UnixClock::open("/dev/ptp0").unwrap();
    ///     let now = clock.now().unwrap();
    ///
    ///     println!("{now:?}");
    /// }
    /// ```
    ///
    /// # Errors
    /// Returns an error if the given path cannot be opened.
    #[cfg(target_os = "linux")]
    pub fn open(path: impl AsRef<Path>) -> std::io::Result<Self> {
        let file = std::fs::OpenOptions::new()
            .write(true)
            .read(true)
            .open(path)?;

        // we need an owned fd. the file will be closed when the process exits.
        let clock = Self::safe_from_raw_fd(file.into_raw_fd());

        Ok(clock)
    }

    // Consume an fd and produce a clock id. Clock id is only valid
    // so long as the fd is open, so the RawFd here should
    // not be borrowed.
    #[cfg(target_os = "linux")]
    fn safe_from_raw_fd(fd: RawFd) -> Self {
        let clock = ((!(fd as libc::clockid_t)) << 3) | 3;

        Self {
            clock,
            fd: Some(fd),
            _timescale: PhantomData,
        }
    }

    /// Determine offset between file clock and TAI clock (if any)
    /// Returns two system timestamps sandwhiching a timestamp from the
    /// hardware clock.
    ///
    /// # Errors
    /// Returns an error fi the system offset could not be provided.
    #[cfg(target_os = "linux")]
    #[expect(clippy::type_complexity, reason = "FIXME: improve this")]
    #[allow(
        clippy::cast_possible_truncation,
        reason = "Casts for timestamp conversion aren't lossless on all platforms"
    )]
    pub fn system_offset(
        &self,
    ) -> Result<(Timestamp<TAI>, Timestamp<TAI>, Timestamp<TAI>), ClockError> {
        use libc::{ptp_clock_time, ptp_sys_offset, PTP_SYS_OFFSET};

        let Some(fd) = self.fd else {
            return Err(ClockError::InvalidValue);
        };

        let default_ptp_clock_time = ptp_clock_time {
            sec: 0,
            nsec: 0,
            reserved: 0,
        };

        let mut offset = ptp_sys_offset {
            n_samples: 1,
            rsv: [0u32; 3],
            ts: [default_ptp_clock_time; 51],
        };

        // # Safety
        //
        // PTP_SYS_OFFSET receives a valid ptp_sys_offset mutable pointer
        if unsafe { libc::ioctl(fd, PTP_SYS_OFFSET as _, &mut offset) } != 0 {
            let t1 = Self::CLOCK_TAI.now();
            let tp = self.now();
            let t2 = Self::CLOCK_TAI.now();

            Ok((t1?, tp?, t2?))
        } else {
            let tai_offset = Self::CLOCK_TAI.get_tai()?;

            Ok((
                Timestamp::from_seconds_nanos_since_unix_epoch(
                    (offset.ts[0].sec + i64::from(tai_offset)).cast_unsigned(),
                    offset.ts[0].nsec as _,
                ),
                Timestamp::from_seconds_nanos_since_unix_epoch(
                    offset.ts[1].sec.cast_unsigned(),
                    offset.ts[1].nsec as _,
                ),
                Timestamp::from_seconds_nanos_since_unix_epoch(
                    (offset.ts[2].sec + i64::from(tai_offset)).cast_unsigned(),
                    offset.ts[2].nsec as _,
                ),
            ))
        }
    }
}

impl<Timescale> UnixClock<Timescale> {
    /// Disable any kernel disciplining of this clock.
    ///
    /// # Errors
    /// May error if the clock has gone away.
    pub fn disable_kernel(&self) -> Result<(), ClockError> {
        let mut timex = EMPTY_TIMEX;
        self.adjtime(&mut timex)?;

        // We are setting the status bits
        timex.modes = libc::MOD_STATUS;

        // Disable all kernel time control loops (phase lock, frequency lock, pps time and pps frequency).
        timex.status &= !(libc::STA_PLL | libc::STA_FLL | libc::STA_PPSTIME | libc::STA_PPSFREQ);

        // ignore if we cannot disable the kernel time control loops (e.g. external clocks)
        ignore_not_supported(self.adjtime(&mut timex))
    }

    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    fn clock_adjtime(&self, timex: &mut libc::timex) -> Result<(), ClockError> {
        // We don't care about the time status, so the non-error
        // information in the return value of clock_adjtime can be ignored.
        //
        // # Safety
        //
        // The clock_adjtime call is safe because the reference always
        // points to a valid libc::timex.
        //
        // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL
        // error https://man.archlinux.org/man/clock_adjtime.2.en#EINVAL~4
        #[cfg(target_os = "linux")]
        use libc::clock_adjtime as adjtime;

        #[cfg(any(target_os = "freebsd", target_os = "macos"))]
        unsafe fn adjtime(clk_id: libc::clockid_t, buf: *mut libc::timex) -> libc::c_int {
            assert_eq!(
                clk_id,
                libc::CLOCK_REALTIME,
                "only the REALTIME clock is supported"
            );

            libc::ntp_adjtime(buf)
        }

        if unsafe { adjtime(self.clock, timex) } == -1 {
            Err(convert_errno())
        } else {
            Ok(())
        }
    }

    fn ntp_adjtime(timex: &mut libc::timex) -> Result<(), ClockError> {
        #[cfg(any(target_os = "freebsd", target_os = "macos", target_env = "gnu"))]
        use libc::ntp_adjtime as adjtime;

        // ntp_adjtime is equivalent to adjtimex for our purposes
        //
        // https://man7.org/linux/man-pages/man2/adjtimex.2.html
        #[cfg(all(target_os = "linux", target_env = "musl"))]
        use libc::adjtimex as adjtime;

        // We don't care about the time status, so the non-error
        // information in the return value of ntp_adjtime can be ignored.
        // The ntp_adjtime call is safe because the reference always
        // points to a valid libc::timex.
        if unsafe { adjtime(timex) } == -1 {
            Err(convert_errno())
        } else {
            Ok(())
        }
    }

    /// Adjust the clock state with a [`libc::timex`] specifying the desired changes.
    ///
    /// This is a lowlevel function. If possible, use more specialized (trait) methods.
    ///
    /// Note that [`libc::timex`] has a different layout between different operating systems, and
    /// not all fields are available on all operating systems. Keep this in mind when writing
    /// platform-independent code.
    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    fn adjtime(&self, timex: &mut libc::timex) -> Result<(), ClockError> {
        if self.clock == libc::CLOCK_REALTIME {
            Self::ntp_adjtime(timex)
        } else {
            self.clock_adjtime(timex)
        }
    }

    #[cfg_attr(target_os = "linux", allow(unused))]
    fn clock_gettime(&self) -> Result<libc::timespec, ClockError> {
        let mut timespec = libc::timespec::default();

        // # Safety
        //
        // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL
        // error https://linux.die.net/man/3/clock_gettime
        //
        // The timespec pointer is valid.
        cerr(unsafe { libc::clock_gettime(self.clock, &raw mut timespec) })?;

        Ok(timespec)
    }

    #[cfg_attr(target_os = "linux", allow(unused))]
    fn clock_settime(&self, mut timespec: libc::timespec) -> Result<(), ClockError> {
        while timespec.tv_nsec > 1_000_000_000 {
            timespec.tv_sec += 1;
            timespec.tv_nsec -= 1_000_000_000;
        }

        // # Safety
        //
        // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL
        // error https://linux.die.net/man/3/clock_settime
        //
        // The timespec pointer is valid.
        unsafe { cerr(libc::clock_settime(self.clock, &raw const timespec))? };

        Ok(())
    }

    #[cfg_attr(target_os = "linux", allow(unused))]
    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    fn step_clock_by_timespec(&self, offset: Duration) -> Result<Timestamp<Timescale>, ClockError> {
        let steps = offset.as_raw_steps();
        #[cfg_attr(
            target_env = "musl",
            allow(
                deprecated,
                reason = "see https://github.com/rust-lang/libc/issues/1848"
            )
        )]
        let seconds: libc::time_t = (steps >> 64)
            .try_into()
            .map_err(|_| ClockError::InvalidValue)?;
        #[allow(
            clippy::cast_possible_truncation,
            reason = "the resulting value will always fit in an u32"
        )]
        let nanos = (((steps.cast_unsigned() & u128::from(u64::MAX)) * 1_000_000_000) >> 64)
            as libc::c_long;

        let mut timespec = self.clock_gettime()?;

        // see https://github.com/rust-lang/libc/issues/1848
        #[cfg_attr(target_env = "musl", allow(deprecated))]
        #[allow(
            clippy::cast_possible_wrap,
            reason = "The actual value is always possible, but not unsigned on all platforms."
        )]
        #[allow(
            clippy::cast_lossless,
            reason = "The cast can be done lossless on some, but not all, platforms."
        )]
        {
            timespec.tv_sec += seconds;
            timespec.tv_nsec += nanos;
        }

        self.clock_settime(timespec)?;

        Ok(current_time_timespec(timespec, Precision::Nano))
    }

    fn error_estimate_timex(esterror: Duration, maxerror: Duration) -> libc::timex {
        let modes = libc::MOD_ESTERROR | libc::MOD_MAXERROR;

        // these fields are always in microseconds
        let esterror =
            libc::c_long::try_from((esterror.as_nanos() + 500) / 1000).unwrap_or(libc::c_long::MAX);
        let maxerror =
            libc::c_long::try_from((maxerror.as_nanos() + 500) / 1000).unwrap_or(libc::c_long::MAX);

        libc::timex {
            modes,
            esterror,
            maxerror,
            ..EMPTY_TIMEX
        }
    }

    #[cfg(target_os = "linux")]
    fn step_clock_timex(offset: Duration) -> Result<libc::timex, ClockError> {
        // we provide the offset in nanoseconds
        let modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO;

        let nanos = offset.as_nanos();
        let seconds = nanos
            .div_euclid(1_000_000_000)
            .try_into()
            .map_err(|_| ClockError::InvalidValue)?;
        #[allow(
            clippy::cast_possible_truncation,
            reason = "the resulting value will always fit in an u32"
        )]
        let nanos = nanos.rem_euclid(1_000_000_000) as _;

        let time = libc::timeval {
            tv_sec: seconds,
            tv_usec: nanos,
        };

        Ok(libc::timex {
            modes,
            time,
            ..EMPTY_TIMEX
        })
    }

    #[cfg(target_os = "linux")]
    fn step_clock_by_timex(&self, offset: Duration) -> Result<Timestamp<Timescale>, ClockError> {
        let mut timex = Self::step_clock_timex(offset)?;
        self.adjtime(&mut timex)?;
        self.extract_current_time(&timex)
    }

    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    fn extract_current_time(
        &self,
        #[cfg_attr(target_os = "macos", allow(unused))] timex: &libc::timex,
    ) -> Result<Timestamp<Timescale>, ClockError> {
        #[cfg(target_os = "linux")]
        // hardware clocks may not report the timestamp
        if timex.time.tv_sec != 0 && timex.time.tv_usec != 0 {
            // in a timex, the status flag determines precision
            let precision = match timex.status & libc::STA_NANO {
                0 => Precision::Micro,
                _ => Precision::Nano,
            };

            return Ok(current_time_timeval(timex.time, precision));
        }

        // clock_gettime always gives nanoseconds
        let timespec = self.clock_gettime()?;
        Ok(current_time_timespec(timespec, Precision::Nano))
    }

    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    fn update_timex<F>(&self, f: F) -> Result<(), ClockError>
    where
        F: FnOnce(libc::timex) -> libc::timex,
    {
        let mut timex = EMPTY_TIMEX;
        self.adjtime(&mut timex)?;

        timex = f(timex);

        self.adjtime(&mut timex)
    }

    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    fn update_status<F>(&self, f: F) -> Result<(), ClockError>
    where
        F: FnOnce(libc::c_int) -> libc::c_int,
    {
        self.update_timex(|mut timex| {
            // We are setting the status bits
            timex.modes = libc::MOD_STATUS;

            // update the status flags
            timex.status = f(timex.status);

            timex
        })
    }

    #[expect(
        clippy::cast_possible_truncation,
        reason = "Truncating the frequency is acceptable here."
    )]
    fn set_frequency_timex(ppm: f64) -> libc::timex {
        // We do an offset with precision
        let mut timex = EMPTY_TIMEX;

        // set the frequency (MOD_FREQUENCY is an alias for ADJ_FREQUENCY on linux)
        timex.modes = libc::MOD_FREQUENCY;

        // NTP Kapi expects frequency adjustment in units of 2^-16 ppm
        // but our input is in units of seconds drift per second, so convert.
        let frequency = (ppm * 65536.0).round() as libc::c_long;

        // Since Linux 2.6.26, the supplied value is clamped to the range (-32768000,
        // +32768000). In older kernels, an EINVAL error occurs if the supplied value is
        // out of range. (32768000 is 500 << 16)
        timex.freq = frequency.clamp(-32_768_000 + 1, 32_768_000 - 1);

        timex
    }

    /// Set the TAI offset on the given clock.
    ///
    /// # Errors
    /// May error if the clock does not support setting the TAI offset.
    #[cfg(target_os = "linux")]
    pub fn set_tai(&self, tai_offset: i32) -> Result<(), ClockError> {
        #[allow(
            clippy::useless_conversion,
            reason = "This conversion is not useless on all platforms."
        )]
        let mut timex = libc::timex {
            modes: libc::ADJ_TAI,
            constant: tai_offset.into(),
            ..EMPTY_TIMEX
        };

        self.clock_adjtime(&mut timex)
    }

    /// Set the TAI offset on the given clock.
    ///
    /// # Errors
    /// May error if the clock does not support setting the TAI offset.
    #[cfg(not(target_os = "linux"))]
    pub fn set_tai(&self, _tai_offset: i32) -> Result<(), ClockError> {
        Err(ClockError::NotSupported)
    }

    /// Get the TAI offset on the given clock.
    ///
    /// # Errors
    /// May error if the clock does not support getting the TAI offset.
    #[cfg(target_os = "linux")]
    pub fn get_tai(&self) -> Result<i32, ClockError> {
        let mut timex = EMPTY_TIMEX;
        if self.clock_adjtime(&mut timex).is_ok() {
            Ok(timex.tai)
        } else {
            // hardware clock which doesn't have an offset anyway
            Ok(0)
        }
    }

    /// Get the TAI offset on the given clock.
    ///
    /// # Errors
    /// May error if the clock does not support getting the TAI offset.
    #[cfg(not(target_os = "linux"))]
    pub fn get_tai(&self) -> Result<i32, ClockError> {
        Err(ClockError::NotSupported)
    }

    /// Get the clock's resolution.
    ///
    /// The output [`Timestamp`] will be all zeros when the resolution is
    /// unavailable.
    ///
    /// # Errors
    /// May error if the clcok has gone away
    pub fn resolution(&self) -> Result<Duration, ClockError> {
        let mut timespec = libc::timespec::default();

        cerr(unsafe { libc::clock_getres(self.clock, &raw mut timespec) })?;

        Ok(if timespec.tv_nsec == 0 && timespec.tv_sec == 0 {
            Duration::from_seconds_nanos(0, 1)
        } else {
            #[allow(
                clippy::cast_possible_truncation,
                reason = "tv_nsec is guaranteed to be between 0 and 1_000_000_000, truncation doesn't happen on all platforms though."
            )]
            #[expect(
                clippy::cast_sign_loss,
                reason = "tv_nsec is guaranteed to be between 0 and 1_000_000_000"
            )]
            #[allow(
                clippy::useless_conversion,
                reason = "Conversion is not useless on all platforms."
            )]
            Duration::from_seconds_nanos(timespec.tv_sec.into(), timespec.tv_nsec as u32)
        })
    }

    #[cfg(target_os = "linux")]
    fn fetch_max_frequency_adjustment(&self) -> Result<f64, ClockError> {
        if let Some(fd) = self.fd {
            let mut caps = MaybeUninit::<PtpClockCaps>::zeroed();

            if unsafe { ptp_clock_getcaps(fd, caps.as_mut_ptr()) } == 0 {
                let caps = unsafe { caps.assume_init() };

                Ok(f64::from(caps.max_adj) * 1e-9)
            } else if error_number() == libc::ENOTTY {
                // Not a PTP device, use system clock defaults
                Ok(500e-6)
            } else {
                Err(convert_errno())
            }
        } else {
            // System clock, use system defaults
            Ok(500e-6)
        }
    }

    #[cfg(not(target_os = "linux"))]
    #[allow(
        clippy::trivially_copy_pass_by_ref,
        reason = "Allows a consistent interface between platforms."
    )]
    #[allow(
        clippy::unnecessary_wraps,
        reason = "Allows a consistent interface between platforms."
    )]
    fn fetch_max_frequency_adjustment(&self) -> Result<f64, ClockError> {
        Ok(500e-6)
    }
}

impl<Timescale: Send + 'static> Clock<Timescale> for UnixClock<Timescale> {
    fn now(&self) -> Result<Timestamp<Timescale>, ClockError> {
        let mut ntp_kapi_timex = EMPTY_TIMEX;

        if self.adjtime(&mut ntp_kapi_timex).is_ok() {
            Ok(self.extract_current_time(&ntp_kapi_timex)?)
        } else {
            Ok(self
                .clock_gettime()
                .map(|ts| current_time_timespec(ts, Precision::Nano))?)
        }
    }

    fn set_frequency(&self, freq: f64) -> Result<Timestamp<Timescale>, ClockError> {
        let mut timex = Self::set_frequency_timex(freq * 1e6);
        self.adjtime(&mut timex)?;
        self.extract_current_time(&timex)
    }

    #[allow(
        clippy::cast_precision_loss,
        reason = "Precision loss is acceptable here."
    )]
    #[allow(
        clippy::cast_lossless,
        reason = "Cast is not lossless on all platforms."
    )]
    fn get_frequency(&self) -> Result<f64, ClockError> {
        let mut timex = EMPTY_TIMEX;
        self.adjtime(&mut timex)?;

        Ok((timex.freq as f64) / 65536.0e6)
    }

    fn max_frequency(&self) -> Result<f64, ClockError> {
        self.fetch_max_frequency_adjustment()
    }

    #[cfg(target_os = "linux")]
    fn step_clock(&self, offset: Duration) -> Result<Timestamp<Timescale>, ClockError> {
        self.step_clock_by_timex(offset)
    }

    #[cfg(not(target_os = "linux"))]
    fn step_clock(&self, offset: Duration) -> Result<Timestamp<Timescale>, ClockError> {
        self.step_clock_by_timespec(offset)
    }

    fn error_estimate_update(
        &self,
        est_error: Duration,
        max_error: Duration,
    ) -> Result<(), ClockError> {
        let mut timex = Self::error_estimate_timex(est_error, max_error);
        ignore_not_supported(self.adjtime(&mut timex))
    }

    fn leap_update(&self, leap_status: LeapStatus) -> Result<(), ClockError> {
        self.update_status(|status| {
            (status & !(libc::STA_INS | libc::STA_DEL))
                | match leap_status {
                    LeapStatus::None => 0,
                    LeapStatus::Leap59 => libc::STA_DEL,
                    LeapStatus::Leap61 => libc::STA_INS,
                }
        })
    }

    fn synchronization_update(&self, synchronized: bool) -> Result<(), ClockError> {
        self.update_status(|status| {
            if synchronized {
                status & !libc::STA_UNSYNC
            } else {
                status | libc::STA_UNSYNC
            }
        })
    }
}

fn ignore_not_supported(result: Result<(), ClockError>) -> Result<(), ClockError> {
    match result {
        Err(ClockError::InvalidValue) => Ok(()),
        result => result,
    }
}

fn error_number() -> libc::c_int {
    #[cfg(target_os = "linux")]
    unsafe {
        *libc::__errno_location()
    }

    #[cfg(not(target_os = "linux"))]
    unsafe {
        *libc::__error()
    }
}

// Convert those error numbers that can occur for calls to the following
// functions
// - ntp_adjtimex https://man7.org/linux/man-pages/man3/ntp_adjtime.3.html
// - clock_gettime & clock_settime https://man7.org/linux/man-pages/man3/clock_gettime.3.html
fn convert_errno() -> ClockError {
    match error_number() {
        libc::EINVAL | libc::ERANGE => ClockError::InvalidValue,
        // The documentation is a bit unclear if this can happen with
        // non-dynamic clocks like the ntp kapi clock, however deal with it just in case.
        libc::ENODEV => ClockError::NoDevice,
        libc::EOPNOTSUPP => ClockError::NotSupported,
        libc::EPERM | libc::EACCES => ClockError::PermissionDenied,
        _ => ClockError::Unknown,
    }
}

fn cerr(c_int: libc::c_int) -> Result<(), ClockError> {
    if c_int == -1 {
        Err(convert_errno())
    } else {
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Precision {
    Nano,
    #[cfg_attr(any(target_os = "freebsd", target_os = "macos"), allow(unused))]
    Micro,
}

#[cfg_attr(target_os = "linux", allow(unused))]
#[allow(
    clippy::cast_possible_truncation,
    reason = "tv_nsec is always less than 1_000_000_000, which fits in an i32"
)]
#[allow(
    clippy::useless_conversion,
    reason = "Conversion is necessary on some platforms."
)]
fn current_time_timespec<Timescale>(
    timespec: libc::timespec,
    precision: Precision,
) -> Timestamp<Timescale> {
    let mut seconds = timespec.tv_sec;

    let nanos: i32 = timespec.tv_nsec as _;

    let mut nanos = match precision {
        Precision::Nano => nanos,
        Precision::Micro => nanos.checked_mul(1000).unwrap_or_default(),
    };

    // on macOS (at least) we've observed higher nanosecond counts than appear valid
    while nanos > 1_000_000_000 {
        seconds = seconds.wrapping_add(1);
        nanos -= 1_000_000_000;
    }

    // we disallow negative nanoseconds
    while nanos < 0 {
        seconds = seconds.wrapping_sub(1);
        nanos += 1_000_000_000;
    }

    Timestamp::from_seconds_nanos_since_unix_epoch(
        seconds.cast_unsigned().into(),
        nanos.cast_unsigned(),
    )
}

#[cfg_attr(not(target_os = "linux"), allow(unused))]
#[allow(
    clippy::cast_possible_truncation,
    reason = "tv_usec is always less than 1_000_000_000, which fits in an i32"
)]
#[expect(clippy::cast_sign_loss, reason = "tv_usec is guaranteed to be >=0")]
fn current_time_timeval<Timescale>(
    timespec: libc::timeval,
    precision: Precision,
) -> Timestamp<Timescale> {
    let seconds = timespec.tv_sec;
    let nanos = match precision {
        Precision::Nano => timespec.tv_usec as u32,
        Precision::Micro => (timespec.tv_usec as u32)
            .checked_mul(1000)
            .unwrap_or_default(),
    };

    Timestamp::from_seconds_nanos_since_unix_epoch(seconds as _, nanos)
}

/// Convenient way of getting an empty [`libc::timex`] struct.
// Libc has no good other way of obtaining this, so let's at least make our
// functions more readable.
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub const EMPTY_TIMEX: libc::timex = libc::timex {
    modes: 0,
    offset: 0,
    freq: 0,
    maxerror: 0,
    esterror: 0,
    status: 0,
    constant: 0,
    precision: 0,
    tolerance: 0,
    time: libc::timeval {
        tv_sec: 0,
        tv_usec: 0,
    },
    tick: 0,
    ppsfreq: 0,
    jitter: 0,
    shift: 0,
    stabil: 0,
    jitcnt: 0,
    calcnt: 0,
    errcnt: 0,
    stbcnt: 0,
    tai: 0,
    __unused1: 0,
    __unused2: 0,
    __unused3: 0,
    __unused4: 0,
    __unused5: 0,
    __unused6: 0,
    __unused7: 0,
    __unused8: 0,
    __unused9: 0,
    __unused10: 0,
    __unused11: 0,
};

/// Convenient way of getting an empty [`libc::timex`] struct.
#[cfg(all(target_os = "linux", target_env = "musl"))]
pub const EMPTY_TIMEX: libc::timex = libc::timex {
    modes: 0,
    offset: 0,
    freq: 0,
    maxerror: 0,
    esterror: 0,
    status: 0,
    constant: 0,
    precision: 0,
    tolerance: 0,
    time: libc::timeval {
        tv_sec: 0,
        tv_usec: 0,
    },
    tick: 0,
    ppsfreq: 0,
    jitter: 0,
    shift: 0,
    stabil: 0,
    jitcnt: 0,
    calcnt: 0,
    errcnt: 0,
    stbcnt: 0,
    tai: 0,
    __padding: [0; 11],
};

/// Convenient way of getting an empty [`libc::timex`] struct.
#[cfg(any(target_os = "freebsd", target_os = "macos"))]
pub const EMPTY_TIMEX: libc::timex = libc::timex {
    modes: 0,
    offset: 0,
    freq: 0,
    maxerror: 0,
    esterror: 0,
    status: 0,
    constant: 0,
    precision: 0,
    tolerance: 0,
    ppsfreq: 0,
    jitter: 0,
    shift: 0,
    stabil: 0,
    jitcnt: 0,
    calcnt: 0,
    errcnt: 0,
    stbcnt: 0,
};

#[cfg(test)]
mod tests {
    use statime_base::{Clock, Duration, Timestamp, UTC};

    use super::UnixClock;

    #[test]
    fn test_time_now_does_not_crash() {
        let clock = UnixClock::CLOCK_REALTIME;
        assert_ne!(clock.now().unwrap(), Timestamp::UNIX_EPOCH,);
    }

    #[test]
    fn realtime_gettime() {
        let clock = UnixClock::CLOCK_REALTIME;
        let time = clock.clock_gettime().unwrap();

        assert_ne!((time.tv_sec, time.tv_nsec), (0, 0));
    }

    #[test]
    #[ignore = "requires permissions, useful for testing permissions"]
    fn ptp0_gettime() {
        let clock = UnixClock::CLOCK_REALTIME;
        let time = clock.clock_gettime().unwrap();

        assert_ne!((time.tv_sec, time.tv_nsec), (0, 0));
    }

    #[test]
    #[ignore = "requires permissions, useful for testing permissions"]
    fn step_clock() {
        UnixClock::CLOCK_REALTIME
            .step_clock(Duration::from_seconds_nanos(0, 0))
            .unwrap();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_step_clock() {
        let offset = Duration::from_seconds_nanos(1, 200_000_000);
        let timex = UnixClock::<UTC>::step_clock_timex(offset).unwrap();

        assert_eq!(timex.modes, libc::ADJ_SETOFFSET | libc::ADJ_NANO);

        assert_eq!(timex.time.tv_sec, 1);
        assert_eq!(timex.time.tv_usec, 200_000_000);
    }

    #[test]
    fn test_error_estimate() {
        let est_error = Duration::from_seconds_nanos(0, 500_000_000);
        let max_error = Duration::from_seconds_nanos(1, 200_000_000);
        let timex = UnixClock::<UTC>::error_estimate_timex(est_error, max_error);

        assert_eq!(timex.modes, libc::MOD_ESTERROR | libc::MOD_MAXERROR);

        // these fields are always in microseconds
        assert_eq!(timex.esterror, 500_000);
        assert_eq!(timex.maxerror, 1_200_000);
    }

    #[test]
    fn test_now() {
        let resolution = UnixClock::CLOCK_REALTIME.now().unwrap();

        assert_ne!(resolution, Timestamp::UNIX_EPOCH);
    }

    #[test]
    fn test_resolution() {
        let resolution = UnixClock::CLOCK_REALTIME.resolution().unwrap();

        assert_ne!(resolution, Duration::ZERO);
    }

    #[test]
    fn test_capabilities() {
        let clock = UnixClock::CLOCK_REALTIME;

        assert!(clock.max_frequency().is_ok());
    }
}