clock-steering-0.2.1/.cargo_vcs_info.json0000644000000001360000000000100137450ustar { "git": { "sha1": "09770e5a695bebda20339314e67e1d787433dca8" }, "path_in_vcs": "" }clock-steering-0.2.1/.github/dependabot.yml000064400000000000000000000002131046102023000167210ustar 00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: weekly open-pull-requests-limit: 10 clock-steering-0.2.1/.github/workflows/build.yaml000064400000000000000000000110201046102023000201070ustar 00000000000000name: checks permissions: contents: read on: push: branches: - main pull_request: schedule: - cron: '0 4 * * *' merge_group: branches: - main jobs: format: name: Format runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 with: persist-credentials: false - name: Install rust toolchain uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af with: toolchain: stable override: true default: true components: rustfmt - name: Check formatting uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505 with: command: fmt args: --all --check build: name: Clippy & Test ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest] rust: - 1.66.0 target: - "" features: - "" steps: - name: Checkout sources uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 with: persist-credentials: false - name: Install ${{ matrix.rust }} toolchain uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af with: toolchain: ${{ matrix.rust }} override: true - name: cargo build run: cargo build ${{ matrix.features }} - name: cargo test run: cargo test env: RUST_BACKTRACE: 1 build-musl: name: Clippy & Test ubuntu-latest / MUSL runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 with: persist-credentials: false - name: Install rust toolchain uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af with: toolchain: stable override: true default: true components: clippy target: x86_64-unknown-linux-musl - name: cargo build run: cargo build ${{ matrix.features }} - name: cargo test run: cargo test env: RUST_BACKTRACE: 1 build-freebsd: name: Clippy & Test FreeBSD runs-on: ubuntu-latest steps: - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 - name: test on freebsd uses: vmactions/freebsd-vm@12c207ac1ba13827f25726fe93f9c2e6f685f0f3 with: usesh: true mem: 4096 copyback: false prepare: | pkg install -y curl curl https://sh.rustup.rs -sSf --output rustup.sh sh rustup.sh -y --profile default --default-toolchain 1.66.0 # cannot use `--profile minimal` because of clippy echo "~~~~ rustc --version ~~~~" $HOME/.cargo/bin/rustc --version echo "~~~~ freebsd-version ~~~~" freebsd-version run: $HOME/.cargo/bin/cargo clippy -- -D warnings && $HOME/.cargo/bin/cargo build && $HOME/.cargo/bin/cargo test clippy-raspberry-pi: name: ClippyRaspberryPi runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 with: persist-credentials: false - name: Install rust toolchain uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af with: toolchain: stable override: true default: true components: clippy target: armv7-unknown-linux-gnueabihf # Use zig as our C compiler for convenient cross-compilation. We run into rustls having a dependency on `ring`. # This crate uses C and assembly code, and because of its build scripts, `cargo clippy` needs to be able to compile # that code for our target. - uses: goto-bus-stop/setup-zig@7ab2955eb728f5440978d5824358023be3a2802d with: version: 0.9.0 - name: Install cargo-zigbuild uses: taiki-e/install-action@32300fcc7462d35c920c6d4a42efe7bc39b61569 with: tool: cargo-zigbuild - name: Run clippy uses: actions-rs/cargo@844f36862e911db73fe0815f00a4a2602c279505 env: TARGET_CC: "/home/runner/.cargo/bin/cargo-zigbuild zig cc -- -target arm-linux-gnueabihf -mcpu=generic+v7a+vfp3-d32+thumb2-neon -g" with: command: clippy args: --target armv7-unknown-linux-gnueabihf --workspace --all-targets -- -D warnings clock-steering-0.2.1/.gitignore000064400000000000000000000000241046102023000145210ustar 00000000000000/target /Cargo.lock clock-steering-0.2.1/COPYRIGHT000064400000000000000000000005161046102023000140320ustar 00000000000000Copyright (c) 2022-2023 Tweede Golf and Contributors Except as otherwise noted (below and/or in individual files), this project is licensed under the Apache License, Version 2.0 or or the MIT license or , at your option. clock-steering-0.2.1/Cargo.toml0000644000000015330000000000100117450ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.66" name = "clock-steering" version = "0.2.1" publish = true description = "Functionality for manual clock steering" homepage = "https://github.com/pendulum-project/timestamped-socket" readme = "README.md" license = "Apache-2.0 OR MIT" repository = "https://github.com/pendulum-project/timestamped-socket" [dependencies.libc] version = "0.2.145" clock-steering-0.2.1/Cargo.toml.orig000064400000000000000000000007151046102023000154270ustar 00000000000000[package] name = "clock-steering" description = "Functionality for manual clock steering" version = "0.2.1" edition = "2021" license = "Apache-2.0 OR MIT" repository = "https://github.com/pendulum-project/timestamped-socket" homepage = "https://github.com/pendulum-project/timestamped-socket" publish = true rust-version = "1.66" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] libc = "0.2.145" clock-steering-0.2.1/LICENSE-APACHE000064400000000000000000000251241046102023000144650ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2022 tweede golf b.v. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. clock-steering-0.2.1/LICENSE-MIT000064400000000000000000000020651046102023000141740ustar 00000000000000Copyright (c) 2022-2023 Tweede Golf and Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. clock-steering-0.2.1/README.md000064400000000000000000000005761046102023000140240ustar 00000000000000# clock-steering Functionality for manual clock steering - the process of keeping a clock synchronized to some external reference. This code is used in our implementations of NTP [ntpd-rs](https://github.com/pendulum-project/ntpd-rs) and PTP [statime](https://github.com/pendulum-project/statime). This crate is part of the [pendulum project](https://github.com/pendulum-project). clock-steering-0.2.1/src/lib.rs000064400000000000000000000073111046102023000144420ustar 00000000000000//! Logic for steering OS clocks, aimed at NTP and PTP. //! //! This code is used in our implementations of NTP [ntpd-rs](https://github.com/pendulum-project/ntpd-rs) and PTP [statime](https://github.com/pendulum-project/statime). use core::time::Duration; #[cfg(unix)] pub mod unix; /// A moment in time. /// /// The format makes it easy to convert into libc data structures, and supports subnanoseconds that /// certain hardware can provide for additional precision. The value is an offset from the [unix epoch](https://en.wikipedia.org/wiki/Unix_time). #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Timestamp { pub seconds: libc::time_t, /// Nanos must be between 0 and 999999999 inclusive pub nanos: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct TimeOffset { pub seconds: libc::time_t, /// Nanos must be between 0 and 999999999 inclusive pub nanos: u32, } /// Indicate whether a leap second must be applied #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)] pub enum LeapIndicator { /// No leap second warning #[default] NoWarning, /// Last minute of the day has 61 seconds Leap61, /// Last minute of the day has 59 seconds Leap59, /// Unknown leap second status (the clock is unsynchronized) Unknown, } /// Trait for reading information from and modifying an OS clock pub trait Clock { type Error: std::error::Error; // feature(error_in_core) https://github.com/rust-lang/rust/issues/103765 // type Error: core::error::Error; /// Get the current time. fn now(&self) -> Result; /// Get the clock's resolution. /// /// The output [`Timestamp`] will be all zeros when the resolution is /// unavailable. fn resolution(&self) -> Result; /// Change the frequency of the clock. /// Returns the time at which the change was applied. /// /// The unit of the input is milliseconds (of drift) per second, /// compared to the "natural" frequency of the clock. fn set_frequency(&self, frequency: f64) -> Result; /// Get the frequency of the clock /// The unit of the output is milliseconds (of drift) per second, /// compared to the "natural" frequency of the clock. fn get_frequency(&self) -> Result; /// Change the current time of the clock by an offset. /// Returns the time at which the change was applied. fn step_clock(&self, offset: TimeOffset) -> Result; /// Change the indicators for upcoming leap seconds. fn set_leap_seconds(&self, leap_status: LeapIndicator) -> Result<(), Self::Error>; /// Disable all standard NTP kernel clock discipline. It is all your responsibility now. /// /// The disabled settings are: /// /// - [`libc::STA_PLL`]: kernel phase-locked loop /// - [`libc::STA_FLL`]: kernel frequency-locked loop /// - [`libc::STA_PPSTIME`]: pulse-per-second time /// - [`libc::STA_PPSFREQ`]: pulse-per-second frequency discipline fn disable_kernel_ntp_algorithm(&self) -> Result<(), Self::Error>; /// Set the offset between TAI and UTC. fn set_tai(&self, tai_offset: i32) -> Result<(), Self::Error>; /// Get the offset between TAI and UTC. fn get_tai(&self) -> Result; /// Provide the system with the current best estimates for the statistical /// error of the clock, and the maximum deviation due to frequency error and /// distance to the root clock. fn error_estimate_update( &self, estimated_error: Duration, maximum_error: Duration, ) -> Result<(), Self::Error>; } clock-steering-0.2.1/src/unix.rs000064400000000000000000000603151046102023000146620ustar 00000000000000use crate::{Clock, LeapIndicator, TimeOffset, Timestamp}; use std::time::Duration; #[cfg(target_os = "linux")] use std::{ os::unix::io::{IntoRawFd, RawFd}, path::Path, }; /// A Unix OS clock #[derive(Debug, Clone, Copy)] pub struct UnixClock { clock: libc::clockid_t, #[cfg(target_os = "linux")] fd: Option, } impl UnixClock { /// The standard realtime clock on unix systems. /// /// ```no_run /// use clock_steering::{Clock, unix::UnixClock}; /// /// fn main() -> std::io::Result<()> { /// let clock = UnixClock::CLOCK_REALTIME; /// let now = clock.now()?; /// /// println!("{now:?}"); /// /// Ok(()) /// } /// ``` pub const CLOCK_REALTIME: Self = UnixClock { clock: libc::CLOCK_REALTIME, #[cfg(target_os = "linux")] fd: None, }; /// TAI time on linux systems. /// /// ```no_run /// use clock_steering::{Clock, unix::UnixClock}; /// /// fn main() -> std::io::Result<()> { /// let clock = UnixClock::CLOCK_TAI; /// let now = clock.now()?; /// /// println!("{now:?}"); /// /// Ok(()) /// } /// ``` #[cfg(target_os = "linux")] pub const CLOCK_TAI: Self = UnixClock { clock: libc::CLOCK_TAI, fd: None, }; /// Open a clock device. /// /// ```no_run /// use clock_steering::{Clock, unix::UnixClock}; /// /// fn main() -> std::io::Result<()> { /// let clock = UnixClock::open("/dev/ptp0")?; /// let now = clock.now()?; /// /// println!("{now:?}"); /// /// Ok(()) /// } /// ``` #[cfg(target_os = "linux")] pub fn open(path: impl AsRef) -> std::io::Result { 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. Ok(Self::safe_from_raw_fd(file.into_raw_fd())) } // 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), } } /// Determine offset between file clock and TAI clock (if any) /// Returns two system timestamps sandwhiching a timestamp from the /// hardware clock. #[cfg(target_os = "linux")] pub fn system_offset(&self) -> Result<(Timestamp, Timestamp, Timestamp), Error> { let Some(fd) = self.fd else { return Err(Error::Invalid); }; // TODO: remove type and constant definitions once libc updates #[repr(C)] #[derive(Default, Clone, Copy, PartialEq, Eq)] #[allow(non_camel_case_types)] struct ptp_clock_time { sec: libc::__s64, nsec: libc::__u32, reserved: libc::__u32, } #[repr(C)] #[derive(Clone, Copy, PartialEq, Eq)] #[allow(non_camel_case_types)] struct ptp_sys_offset { n_samples: libc::c_uint, rsv: [libc::c_uint; 3], ts: [ptp_clock_time; 51], } // Needed as arrays larger than 32 elements don't implement default. impl Default for ptp_sys_offset { fn default() -> Self { Self { n_samples: Default::default(), rsv: Default::default(), ts: [Default::default(); 51], } } } const PTP_SYS_OFFSET: libc::c_uint = 0x43403d05; let mut offset = ptp_sys_offset { n_samples: 1, ..Default::default() }; // # Safety // Safe since PTP_SYS_OFFSET expects as argument a mutable pointer to // ptp_sys_offset and offset is valid during the call if unsafe { libc::ioctl(fd, PTP_SYS_OFFSET as _, &mut offset as *mut ptp_sys_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 { seconds: (offset.ts[0].sec + tai_offset as i64) as _, nanos: offset.ts[0].nsec as _, }, Timestamp { seconds: offset.ts[1].sec as _, nanos: offset.ts[1].nsec as _, }, Timestamp { seconds: (offset.ts[2].sec + tai_offset as i64) as _, nanos: offset.ts[2].nsec as _, }, )) } } fn clock_adjtime(&self, timex: &mut libc::timex) -> Result<(), Error> { // 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<(), Error> { #[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. fn adjtime(&self, timex: &mut libc::timex) -> Result<(), Error> { 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 { let mut timespec = EMPTY_TIMESPEC; // # 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, &mut timespec) })?; Ok(timespec) } #[cfg_attr(target_os = "linux", allow(unused))] fn clock_settime(&self, mut timespec: libc::timespec) -> Result<(), Error> { 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, ×pec))? }; Ok(()) } #[cfg_attr(target_os = "linux", allow(unused))] fn step_clock_by_timespec(&self, offset: TimeOffset) -> Result { let mut timespec = self.clock_gettime()?; // see https://github.com/rust-lang/libc/issues/1848 #[cfg_attr(target_env = "musl", allow(deprecated))] { timespec.tv_sec += offset.seconds as libc::time_t; timespec.tv_nsec += offset.nanos as libc::c_long; } self.clock_settime(timespec)?; Ok(current_time_timespec(timespec, Precision::Nano)) } fn error_estimate_timex(est_error: Duration, max_error: Duration) -> libc::timex { let modes = libc::MOD_ESTERROR | libc::MOD_MAXERROR; // these fields are always in microseconds let esterror = est_error.as_nanos() as libc::c_long / 1000; let maxerror = max_error.as_nanos() as libc::c_long / 1000; libc::timex { modes, esterror, maxerror, ..EMPTY_TIMEX } } #[cfg(target_os = "linux")] fn step_clock_timex(offset: TimeOffset) -> libc::timex { // we provide the offset in nanoseconds let modes = libc::ADJ_SETOFFSET | libc::ADJ_NANO; let time = libc::timeval { tv_sec: offset.seconds, tv_usec: offset.nanos as libc::suseconds_t, }; libc::timex { modes, time, ..EMPTY_TIMEX } } #[cfg(target_os = "linux")] fn step_clock_by_timex(&self, offset: TimeOffset) -> Result { let mut timex = Self::step_clock_timex(offset); self.adjtime(&mut timex)?; self.extract_current_time(&timex) } fn extract_current_time(&self, _timex: &libc::timex) -> Result { #[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)) } #[inline(always)] fn update_timex(&self, f: F) -> Result<(), Error> where F: FnOnce(libc::timex) -> libc::timex, { let mut timex = EMPTY_TIMEX; self.adjtime(&mut timex)?; timex = f(timex); self.adjtime(&mut timex) } #[inline(always)] fn update_status(&self, f: F) -> Result<(), Error> 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 }) } 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 } } impl Clock for UnixClock { type Error = Error; fn now(&self) -> Result { let mut ntp_kapi_timex = EMPTY_TIMEX; if self.adjtime(&mut ntp_kapi_timex).is_ok() { self.extract_current_time(&ntp_kapi_timex) } else { self.clock_gettime() .map(|ts| current_time_timespec(ts, Precision::Nano)) } } fn resolution(&self) -> Result { let mut timespec = EMPTY_TIMESPEC; cerr(unsafe { libc::clock_getres(self.clock, &mut timespec) })?; Ok(current_time_timespec(timespec, Precision::Nano)) } fn get_frequency(&self) -> Result { let mut timex = EMPTY_TIMEX; self.adjtime(&mut timex)?; Ok((timex.freq as f64) / 65536.0) } fn set_frequency(&self, frequency: f64) -> Result { let mut timex = Self::set_frequency_timex(frequency); self.adjtime(&mut timex)?; self.extract_current_time(&timex) } #[cfg(target_os = "linux")] fn step_clock(&self, offset: TimeOffset) -> Result { self.step_clock_by_timex(offset) } #[cfg(any(target_os = "freebsd", target_os = "macos"))] fn step_clock(&self, offset: TimeOffset) -> Result { self.step_clock_by_timespec(offset) } fn set_leap_seconds(&self, leap_status: LeapIndicator) -> Result<(), Self::Error> { self.update_status(|status| { (status & !(libc::STA_UNSYNC | libc::STA_INS | libc::STA_DEL)) | leap_status.as_status_bit() }) } fn error_estimate_update( &self, est_error: Duration, max_error: Duration, ) -> Result<(), Self::Error> { let mut timex = Self::error_estimate_timex(est_error, max_error); Error::ignore_not_supported(self.adjtime(&mut timex)) } fn disable_kernel_ntp_algorithm(&self) -> Result<(), Self::Error> { 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) Error::ignore_not_supported(self.adjtime(&mut timex)) } #[cfg(target_os = "linux")] fn set_tai(&self, tai_offset: i32) -> Result<(), Error> { let mut timex = libc::timex { modes: libc::ADJ_TAI, constant: tai_offset as _, ..EMPTY_TIMEX }; self.clock_adjtime(&mut timex) } #[cfg(not(target_os = "linux"))] fn set_tai(&self, _tai_offset: i32) -> Result<(), Error> { Err(Error::NotSupported) } #[cfg(target_os = "linux")] fn get_tai(&self) -> Result { 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) } } #[cfg(not(target_os = "linux"))] fn get_tai(&self) -> Result { Err(Error::NotSupported) } } /// Errors that can be thrown by modifying a unix clock #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Error { /// Insufficient permissions to interact with the clock. NoPermission, /// No access to the clock. NoAccess, /// Invalid operation requested Invalid, /// Clock device has gone away NoDevice, /// Clock operation requested is not supported by operating system. NotSupported, } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { use Error::*; let msg = match self { NoPermission => "Insufficient permissions to interact with the clock.", NoAccess => "No access to the clock.", Invalid => "Invalid operation requested", NoDevice => "Clock device has gone away", NotSupported => "Clock operation requested is not supported by operating system.", }; f.write_str(msg) } } impl std::error::Error for Error {} impl Error { /// Turn the `Error::NotSupported` error variant into `Ok(())`, to silently /// ignore operations that are not supported by the current clock. All /// other input values are untouched. pub fn ignore_not_supported(res: Result<(), Error>) -> Result<(), Error> { match res { Err(Error::NotSupported) => Ok(()), other => other, } } // TODO: use https://doc.rust-lang.org/std/io/type.RawOsError.html when stable fn into_raw_os_error(self) -> i32 { match self { Self::NoPermission => libc::EPERM, Self::NoAccess => libc::EACCES, Self::Invalid => libc::EINVAL, Self::NoDevice => libc::ENODEV, Self::NotSupported => libc::EOPNOTSUPP, } } } impl From for std::io::Error { fn from(value: Error) -> Self { std::io::Error::from_raw_os_error(value.into_raw_os_error()) } } 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() -> Error { match error_number() { libc::EINVAL => Error::Invalid, // 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 => Error::NoDevice, libc::EOPNOTSUPP => Error::NotSupported, libc::EPERM => Error::NoPermission, libc::EACCES => Error::NoAccess, libc::EFAULT => unreachable!("we always pass in valid (accessible) buffers"), // No other errors should occur other => { let error = std::io::Error::from_raw_os_error(other); unreachable!("error code `{other}` ({error:?}) should not occur") } } } fn cerr(c_int: libc::c_int) -> Result<(), Error> { if c_int == -1 { Err(convert_errno()) } else { Ok(()) } } pub(crate) enum Precision { Nano, #[cfg_attr(any(target_os = "freebsd", target_os = "macos"), allow(unused))] Micro, } #[cfg_attr(target_os = "linux", allow(unused))] fn current_time_timespec(timespec: libc::timespec, precision: Precision) -> Timestamp { 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 { seconds, nanos: nanos as u32, } } #[cfg_attr(not(target_os = "linux"), allow(unused))] fn current_time_timeval(timespec: libc::timeval, precision: Precision) -> Timestamp { 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 { seconds, nanos } } const EMPTY_TIMESPEC: libc::timespec = libc::timespec { tv_sec: 0, tv_nsec: 0, }; // 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, }; #[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], }; #[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, }; impl LeapIndicator { fn as_status_bit(self) -> libc::c_int { match self { LeapIndicator::NoWarning => 0, LeapIndicator::Leap61 => libc::STA_INS, LeapIndicator::Leap59 => libc::STA_DEL, LeapIndicator::Unknown => libc::STA_UNSYNC, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_time_now_does_not_crash() { let clock = UnixClock::CLOCK_REALTIME; assert_ne!(clock.now().unwrap(), Timestamp::default(),); } #[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(TimeOffset { seconds: 0, nanos: 0, }) .unwrap(); } #[cfg(target_os = "linux")] #[test] fn test_step_clock() { let offset = TimeOffset { seconds: 1, nanos: 200000000, }; let timex = UnixClock::step_clock_timex(offset); 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_secs_f64(0.5); let max_error = Duration::from_secs_f64(1.2); let timex = UnixClock::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::default()); } #[test] fn test_resolution() { let resolution = UnixClock::CLOCK_REALTIME.resolution().unwrap(); assert_ne!(resolution, Timestamp::default()); } }