Qualify FreeBSD kernel time and supervise bounded POSIX process groups natively

This commit is contained in:
2026-11-19 20:14:34 +01:00
parent 6bf6e2539c
commit 8acbee6a60
5 changed files with 131 additions and 1 deletions
+81
View File
@@ -0,0 +1,81 @@
//! Read-only FreeBSD kernel discipline for the signed reconciliation clock.
//! Never adjust the guest clock. No cached qualification across a failed read.
use crate::reconcile::{ClockReading, SyncClock};
use anyhow::{Context, Result, ensure};
use chrono::{DateTime, TimeDelta, Utc};
use std::{mem::MaybeUninit, time::Instant};
pub struct NativeClock {
origin: DateTime<Utc>,
monotonic: Instant,
}
impl Default for NativeClock {
fn default() -> Self {
Self {
origin: Utc::now(),
monotonic: Instant::now(),
}
}
}
impl NativeClock {
fn observation(&self) -> Result<(DateTime<Utc>, TimeDelta)> {
let start = Instant::now();
let mut raw = MaybeUninit::<libc::ntptimeval>::zeroed();
// SAFETY: the read-only syscall writes the platform's ntptimeval.
let result = unsafe { libc::ntp_gettime(raw.as_mut_ptr()) };
ensure!(result == libc::TIME_OK, "FREEBSD_CLOCK_UNQUALIFIED");
let sample = unsafe { raw.assume_init() };
let wall =
DateTime::from_timestamp(sample.time.tv_sec, u32::try_from(sample.time.tv_nsec)?)
.context("FREEBSD_CLOCK_INVALID")?;
let duration = TimeDelta::from_std(start.elapsed())?;
ensure!(
sample.time_state == libc::TIME_OK
&& (0..=5_000_000).contains(&sample.maxerror)
&& (0..=sample.maxerror).contains(&sample.esterror)
&& sample.time.tv_nsec < 1_000_000_000
&& duration <= TimeDelta::milliseconds(100)
&& ((wall - self.origin) - TimeDelta::from_std(self.monotonic.elapsed())?)
.num_milliseconds()
.unsigned_abs()
<= 5000,
"FREEBSD_CLOCK_UNQUALIFIED"
);
Ok((wall, TimeDelta::microseconds(sample.maxerror) + duration))
}
}
impl SyncClock for NativeClock {
fn now(&self) -> Result<DateTime<Utc>> {
Ok(self.observation()?.0)
}
fn reading(&self) -> Result<ClockReading> {
let (wall, error) = self.observation()?;
Ok(ClockReading {
own_wall: wall,
upper: wall + error,
})
}
fn bounds(&self) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
let (wall, error) = self.observation()?;
Ok((wall - error, wall + error))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore = "requires a FreeBSD guest synchronized by ntpd"]
fn native_bounds_and_monotonic_fence() -> Result<()> {
let mut clock = NativeClock::default();
let (low, high) = clock.bounds()?;
ensure!(low <= high && high - low <= TimeDelta::milliseconds(10200));
clock.origin += TimeDelta::minutes(1);
ensure!(clock.bounds().is_err());
Ok(())
}
}