use std::io;
use crate::host::{Host, ReadError};
const ADJTIMEX: &str = "adjtimex(2)";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct KernelSync {
pub state: i32,
pub status: i32,
pub maxerror_us: i64,
pub esterror_us: i64,
pub offset_ns: i64,
pub freq_ppm: f64,
}
impl KernelSync {
pub const STA_UNSYNC: i32 = 0x0040;
pub const STA_INS: i32 = 0x0010;
pub const STA_DEL: i32 = 0x0020;
pub const STA_NANO: i32 = 0x2000;
pub const MAXERROR_LIMIT_US: i64 = 16_000_000;
pub fn read(host: &Host) -> Result<Self, ReadError> {
if !host.is_live() {
return Err(ReadError::NotLive(ADJTIMEX));
}
if !cfg!(target_os = "linux") {
return Err(ReadError::NotLinux(ADJTIMEX));
}
Self::read_live().map_err(|kind| ReadError::Io {
path: ADJTIMEX.to_owned(),
kind,
})
}
#[allow(clippy::missing_const_for_fn)] pub(crate) fn read_live() -> Result<Self, io::ErrorKind> {
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
{
let (state, tx) = adjtimex()?;
Ok(Self::from_raw(
state,
tx.status,
tx.offset,
tx.freq,
tx.maxerror,
tx.esterror,
))
}
#[cfg(not(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
)))]
{
Err(io::ErrorKind::Unsupported)
}
}
#[cfg(any(
test,
all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
)
))]
#[must_use]
pub(crate) fn from_raw(
state: i32,
status: i32,
offset: i64,
freq: i64,
maxerror_us: i64,
esterror_us: i64,
) -> Self {
#[allow(clippy::cast_precision_loss)] let freq_ppm = freq as f64 / 65_536.0;
Self {
state,
status,
maxerror_us,
esterror_us,
offset_ns: if status & Self::STA_NANO != 0 {
offset
} else {
offset.saturating_mul(1_000)
},
freq_ppm,
}
}
#[must_use]
pub const fn unsynchronised(&self) -> bool {
self.status & Self::STA_UNSYNC != 0
}
#[must_use]
pub const fn maxerror_kept(&self) -> bool {
self.maxerror_us < Self::MAXERROR_LIMIT_US
}
#[must_use]
pub const fn leap_pending(&self) -> bool {
self.status & (Self::STA_INS | Self::STA_DEL) != 0 || matches!(self.state, 1..=3)
}
#[must_use]
pub(crate) fn maxerror_ns(&self) -> u64 {
u64::try_from(self.maxerror_us)
.unwrap_or(0)
.saturating_mul(1_000)
}
}
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
#[repr(C)]
#[derive(Clone, Copy)]
struct Timex {
_modes: u32,
_pad0: u32,
offset: i64,
freq: i64,
maxerror: i64,
esterror: i64,
status: i32,
_pad1: u32,
_constant: i64,
_precision: i64,
_tolerance: i64,
_time: [i64; 2],
_tick: i64,
_ppsfreq: i64,
_jitter: i64,
_shift: i32,
_pad2: u32,
_stabil: i64,
_jitcnt: i64,
_calcnt: i64,
_errcnt: i64,
_stbcnt: i64,
_tai: i32,
_reserved: [i32; 11],
}
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
const _: () = {
use std::mem::{align_of, offset_of, size_of};
assert!(size_of::<Timex>() == 208);
assert!(align_of::<Timex>() == 8);
assert!(offset_of!(Timex, _modes) == 0);
assert!(offset_of!(Timex, offset) == 8);
assert!(offset_of!(Timex, freq) == 16);
assert!(offset_of!(Timex, maxerror) == 24);
assert!(offset_of!(Timex, esterror) == 32);
assert!(offset_of!(Timex, status) == 40);
assert!(offset_of!(Timex, _constant) == 48);
assert!(offset_of!(Timex, _time) == 72);
assert!(offset_of!(Timex, _tick) == 88);
assert!(offset_of!(Timex, _shift) == 112);
assert!(offset_of!(Timex, _stabil) == 120);
assert!(offset_of!(Timex, _tai) == 160);
assert!(offset_of!(Timex, _reserved) == 164);
};
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
#[allow(unsafe_code)]
fn adjtimex() -> Result<(i32, Timex), io::ErrorKind> {
unsafe extern "C" {
fn adjtimex(buf: *mut Timex) -> std::ffi::c_int;
}
let mut tx = Timex {
_modes: 0,
_pad0: 0,
offset: 0,
freq: 0,
maxerror: 0,
esterror: 0,
status: 0,
_pad1: 0,
_constant: 0,
_precision: 0,
_tolerance: 0,
_time: [0; 2],
_tick: 0,
_ppsfreq: 0,
_jitter: 0,
_shift: 0,
_pad2: 0,
_stabil: 0,
_jitcnt: 0,
_calcnt: 0,
_errcnt: 0,
_stbcnt: 0,
_tai: 0,
_reserved: [0; 11],
};
let state = unsafe { adjtimex(&raw mut tx) };
if state < 0 {
return Err(io::Error::last_os_error().kind());
}
Ok((state, tx))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_raw_fields_scale_as_the_kernel_defines_them() {
let k = KernelSync::from_raw(0, 0x0001, -250, -819_200, 1_500, 20);
assert_eq!(k.offset_ns, -250_000);
assert!((k.freq_ppm + 12.5).abs() < f64::EPSILON);
assert_eq!(k.maxerror_ns(), 1_500_000);
assert!(!k.unsynchronised() && k.maxerror_kept() && !k.leap_pending());
let k = KernelSync::from_raw(5, 0x2041, -250, 0, 16_000_000, 0);
assert_eq!(k.offset_ns, -250);
assert!(k.unsynchronised() && !k.maxerror_kept());
for (state, status) in [(0, 0x0010), (0, 0x0020), (1, 0), (2, 0), (3, 0)] {
assert!(KernelSync::from_raw(state, status, 0, 0, 0, 0).leap_pending());
}
assert!(!KernelSync::from_raw(4, 0, 0, 0, 0, 0).leap_pending());
}
#[test]
fn only_the_running_linux_host_is_asked() {
let tree = Host::at(std::env::temp_dir());
assert_eq!(KernelSync::read(&tree), Err(ReadError::NotLive(ADJTIMEX)));
let live = KernelSync::read(&Host::system());
if cfg!(target_os = "linux") {
assert!(
live.as_ref().is_ok_and(|k| (0..=5).contains(&k.state)),
"{live:?}"
);
} else {
assert_eq!(live, Err(ReadError::NotLinux(ADJTIMEX)));
}
}
}