Skip to main content

rusty_time_clock/
refclock.rs

1//! Reference-clock transports: gpsd's shared memory, chrony's SOCK protocol,
2//! and PTP hardware clocks.
3//!
4//! These are the interfaces a GPS receiver or a NIC actually presents. The
5//! decision about whether a reading is *usable* lives in
6//! `rusty_time_core::refclock`; this module only gets the bytes.
7//!
8//! Both wire layouts below are ABI-compatible with what gpsd and chrony
9//! already write, because the point of implementing them is to work with the
10//! receivers people already run.
11
12use crate::ClockError;
13use rusty_time_core::refclock::{LeapWarning, RefclockSample};
14
15/// gpsd / ntpd shared-memory refclock (the `SHM` driver).
16///
17/// gpsd writes a fixed struct into a SysV shared-memory segment keyed
18/// `0x4E545030 + unit` — the ASCII of "NTP0", "NTP1" and so on. Every NTP
19/// implementation reads the same layout, which is why it is spelled out here
20/// rather than generated: the struct is the interface.
21#[cfg(unix)]
22pub mod shm {
23    use super::*;
24
25    /// Base SysV key: the bytes "NTP0".
26    pub const SHM_KEY_BASE: i32 = 0x4E54_5030;
27
28    /// Byte offsets into `struct shmTime` on a 64-bit platform, where
29    /// `time_t` is 8 bytes and the compiler pads before each one.
30    mod layout {
31        pub const MODE: usize = 0;
32        pub const COUNT: usize = 4;
33        pub const CLOCK_SEC: usize = 8;
34        pub const CLOCK_USEC: usize = 16;
35        pub const RECEIVE_SEC: usize = 24;
36        pub const RECEIVE_USEC: usize = 32;
37        pub const LEAP: usize = 36;
38        pub const PRECISION: usize = 40;
39        pub const VALID: usize = 48;
40        pub const CLOCK_NSEC: usize = 52;
41        pub const RECEIVE_NSEC: usize = 56;
42        /// Total size including trailing `dummy[8]` and padding.
43        pub const SIZE: usize = 96;
44    }
45
46    /// An attached gpsd shared-memory segment.
47    pub struct ShmRefclock {
48        base: *mut u8,
49        unit: i32,
50    }
51
52    // SAFETY: the pointer addresses a shared-memory mapping owned by this
53    // process for the object's lifetime; all access below is through volatile
54    // reads of plain integers at fixed offsets, and the type exposes no way to
55    // alias it mutably.
56    unsafe impl Send for ShmRefclock {}
57
58    impl ShmRefclock {
59        /// Attach to the segment for `unit` (0..=3 by convention).
60        ///
61        /// Read-only: a time client has no business writing a producer's
62        /// segment, and attaching read-only means a bug here cannot corrupt
63        /// gpsd's view.
64        pub fn attach(unit: i32) -> Result<ShmRefclock, ClockError> {
65            let key = SHM_KEY_BASE + unit;
66            // SAFETY: shmget with size 0 and no IPC_CREAT looks up an existing
67            // segment; it either returns a valid id or -1.
68            let id = unsafe { libc::shmget(key, layout::SIZE, 0) };
69            if id < 0 {
70                return Err(ClockError {
71                    op: "shmget",
72                    detail: format!(
73                        "no SHM segment for unit {unit} (key {key:#x}): {}",
74                        std::io::Error::last_os_error()
75                    ),
76                });
77            }
78            // SAFETY: `id` is a valid segment id from shmget; SHM_RDONLY maps
79            // it read-only.
80            let base = unsafe { libc::shmat(id, core::ptr::null(), libc::SHM_RDONLY) };
81            if base as isize == -1 {
82                return Err(ClockError {
83                    op: "shmat",
84                    detail: std::io::Error::last_os_error().to_string(),
85                });
86            }
87            Ok(ShmRefclock {
88                base: base.cast::<u8>(),
89                unit,
90            })
91        }
92
93        pub fn unit(&self) -> i32 {
94            self.unit
95        }
96
97        fn read_i32(&self, offset: usize) -> i32 {
98            // SAFETY: offset is one of the fixed layout constants, all well
99            // inside SIZE, and the mapping is at least SIZE bytes. Volatile
100            // because a separate process writes this memory concurrently.
101            unsafe { core::ptr::read_volatile(self.base.add(offset).cast::<i32>()) }
102        }
103
104        fn read_i64(&self, offset: usize) -> i64 {
105            // SAFETY: as above; these offsets are 8-byte aligned by the layout.
106            unsafe { core::ptr::read_volatile(self.base.add(offset).cast::<i64>()) }
107        }
108
109        /// Take a sample, or `None` if the producer has not published one.
110        ///
111        /// Implements the protocol's two modes. Mode 1 is the one that matters:
112        /// the reader checks `count` before and after copying and retries if it
113        /// changed, because the producer writes the struct without a lock and a
114        /// sample torn across that write would be a plausible-looking wrong
115        /// time.
116        pub fn sample(&self) -> Option<RefclockSample> {
117            for _ in 0..4 {
118                if self.read_i32(layout::VALID) == 0 {
119                    return None;
120                }
121                let mode = self.read_i32(layout::MODE);
122                let count_before = self.read_i32(layout::COUNT);
123
124                let clock_sec = self.read_i64(layout::CLOCK_SEC);
125                let clock_usec = self.read_i32(layout::CLOCK_USEC);
126                let clock_nsec = self.read_i32(layout::CLOCK_NSEC);
127                let receive_sec = self.read_i64(layout::RECEIVE_SEC);
128                let receive_usec = self.read_i32(layout::RECEIVE_USEC);
129                let receive_nsec = self.read_i32(layout::RECEIVE_NSEC);
130                let leap = self.read_i32(layout::LEAP);
131                let precision = self.read_i32(layout::PRECISION);
132
133                if mode == 1 {
134                    let count_after = self.read_i32(layout::COUNT);
135                    if count_before != count_after {
136                        continue; // torn read; the producer was mid-update
137                    }
138                }
139
140                // The nanosecond fields are authoritative when present; the
141                // microsecond ones are the older interface kept for producers
142                // that predate them.
143                let sub_ns = |nsec: i32, usec: i32| -> i64 {
144                    if nsec != 0 {
145                        nsec as i64
146                    } else {
147                        usec as i64 * 1_000
148                    }
149                };
150                let clock_ns = sub_ns(clock_nsec, clock_usec);
151                let receive_ns = sub_ns(receive_nsec, receive_usec);
152
153                // Difference the integer parts first. Converting both times to
154                // f64 and subtracting would round each to ~100 ns at epoch
155                // magnitude, losing exactly the precision a refclock exists to
156                // provide.
157                let offset_s =
158                    (clock_sec - receive_sec) as f64 + (clock_ns - receive_ns) as f64 * 1e-9;
159
160                return Some(RefclockSample {
161                    // "clock" is the reference's time; "receive" is ours.
162                    local_s: receive_sec as f64 + receive_ns as f64 * 1e-9,
163                    offset_s,
164                    precision_log2: precision.clamp(-32, 0) as i8,
165                    leap: LeapWarning::from_wire(leap),
166                });
167            }
168            None
169        }
170    }
171
172    impl Drop for ShmRefclock {
173        fn drop(&mut self) {
174            // SAFETY: `base` came from shmat and is detached exactly once.
175            unsafe {
176                libc::shmdt(self.base.cast::<libc::c_void>());
177            }
178        }
179    }
180}
181
182/// chrony's SOCK refclock protocol.
183///
184/// The producer (gpsd, or anything else) connects to a Unix datagram socket
185/// and sends a fixed 40-byte struct per sample. Simpler and safer than shared
186/// memory — no torn reads, and the kernel does the framing.
187#[cfg(unix)]
188pub mod sock {
189    use super::*;
190    use std::os::unix::net::UnixDatagram;
191
192    /// "SOCK" — the magic chrony checks so a stray datagram cannot be mistaken
193    /// for a time sample.
194    pub const SOCK_MAGIC: i32 = 0x534F_434B;
195    /// Wire size of `struct sock_sample` on a 64-bit platform.
196    pub const SAMPLE_SIZE: usize = 40;
197
198    /// A listening SOCK refclock endpoint.
199    pub struct SockRefclock {
200        socket: UnixDatagram,
201    }
202
203    impl SockRefclock {
204        /// Bind the socket a producer will send to.
205        pub fn bind(path: &str) -> Result<SockRefclock, ClockError> {
206            let _ = std::fs::remove_file(path);
207            let socket = UnixDatagram::bind(path).map_err(|e| ClockError {
208                op: "bind SOCK refclock",
209                detail: format!("{path}: {e}"),
210            })?;
211            socket.set_nonblocking(true).map_err(|e| ClockError {
212                op: "set_nonblocking",
213                detail: e.to_string(),
214            })?;
215            Ok(SockRefclock { socket })
216        }
217
218        /// Read one pending sample, if any.
219        pub fn try_sample(&self) -> Option<RefclockSample> {
220            let mut buf = [0u8; SAMPLE_SIZE];
221            let received = self.socket.recv(&mut buf).ok()?;
222            if received != SAMPLE_SIZE {
223                return None;
224            }
225            decode_sample(&buf)
226        }
227    }
228
229    /// Decode one `struct sock_sample`. Separate and pure so the layout is
230    /// tested without a socket.
231    pub fn decode_sample(buf: &[u8]) -> Option<RefclockSample> {
232        if buf.len() < SAMPLE_SIZE {
233            return None;
234        }
235        // The length check above guarantees every fixed offset below is in
236        // range, so these cannot fail; the arrays are sized at compile time.
237        let i32_at = |o: usize| {
238            let mut b = [0u8; 4];
239            b.copy_from_slice(&buf[o..o + 4]);
240            i32::from_ne_bytes(b)
241        };
242        let i64_at = |o: usize| {
243            let mut b = [0u8; 8];
244            b.copy_from_slice(&buf[o..o + 8]);
245            i64::from_ne_bytes(b)
246        };
247        let f64_at = |o: usize| {
248            let mut b = [0u8; 8];
249            b.copy_from_slice(&buf[o..o + 8]);
250            f64::from_ne_bytes(b)
251        };
252
253        // struct sock_sample {
254        //   struct timeval tv;  // 0: sec (8), usec (8)
255        //   double offset;      // 16
256        //   int pulse;          // 24
257        //   int leap;           // 28
258        //   int _pad;           // 32
259        //   int magic;          // 36
260        // }
261        if i32_at(36) != SOCK_MAGIC {
262            return None; // not one of ours
263        }
264        let sec = i64_at(0);
265        let usec = i64_at(8);
266        let offset = f64_at(16);
267        let leap = i32_at(28);
268
269        // The producer reports the offset directly, so it is stored verbatim
270        // rather than folded into a reference time and subtracted back out.
271        Some(RefclockSample {
272            local_s: sec as f64 + usec as f64 * 1e-6,
273            offset_s: offset,
274            precision_log2: -20,
275            leap: LeapWarning::from_wire(leap),
276        })
277    }
278}
279
280/// PTP hardware clocks (`/dev/ptp*`).
281///
282/// A PHC is a clock on the NIC (or, on a hypervisor, a paravirtual device)
283/// that is disciplined independently of the system clock. Reading it tells us
284/// what the system clock's error is against a source that did not go through
285/// the network at all.
286#[cfg(target_os = "linux")]
287pub mod phc {
288    use super::*;
289    use std::os::fd::{AsRawFd, OwnedFd};
290
291    /// An open PTP hardware clock.
292    pub struct Phc {
293        fd: OwnedFd,
294        index: u32,
295    }
296
297    /// Turn a `/dev/ptpN` descriptor into the clockid `clock_gettime` wants.
298    ///
299    /// Linux encodes dynamic POSIX clocks as `(~fd << 3) | 3`; there is no
300    /// constant for it, which is why it is spelled out.
301    fn fd_to_clockid(fd: i32) -> libc::clockid_t {
302        ((!fd) << 3) | 3
303    }
304
305    impl Phc {
306        /// Open `/dev/ptp{index}`.
307        pub fn open(index: u32) -> Result<Phc, ClockError> {
308            let path = format!("/dev/ptp{index}");
309            let file = std::fs::File::open(&path).map_err(|e| ClockError {
310                op: "open PHC",
311                detail: format!("{path}: {e}"),
312            })?;
313            Ok(Phc {
314                fd: OwnedFd::from(file),
315                index,
316            })
317        }
318
319        pub fn index(&self) -> u32 {
320            self.index
321        }
322
323        /// Read the PHC's current time, in Unix seconds.
324        pub fn read_s(&self) -> Result<f64, ClockError> {
325            let mut ts = libc::timespec {
326                tv_sec: 0,
327                tv_nsec: 0,
328            };
329            // SAFETY: ts is valid and exclusively owned; the clockid is derived
330            // from a descriptor this object keeps open for the call's duration.
331            let rc = unsafe { libc::clock_gettime(fd_to_clockid(self.fd.as_raw_fd()), &mut ts) };
332            if rc != 0 {
333                return Err(ClockError {
334                    op: "clock_gettime(PHC)",
335                    detail: std::io::Error::last_os_error().to_string(),
336                });
337            }
338            Ok(ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9)
339        }
340
341        /// Sample the PHC against the system clock.
342        ///
343        /// Reads system, PHC, system and takes the midpoint of the two system
344        /// readings, so the unavoidable read latency is split rather than
345        /// charged entirely to one side. `PTP_SYS_OFFSET_PRECISE` does better
346        /// where hardware supports it; this works everywhere.
347        pub fn sample(&self) -> Result<RefclockSample, ClockError> {
348            let clock = crate::SystemClock;
349            let before = clock.wall_ns()? as f64 * 1e-9;
350            let phc = self.read_s()?;
351            let after = clock.wall_ns()? as f64 * 1e-9;
352            let midpoint = (before + after) / 2.0;
353            Ok(RefclockSample {
354                local_s: midpoint,
355                offset_s: phc - midpoint,
356                // Half the read window is the honest precision claim.
357                precision_log2: ((after - before).max(1e-9).log2().ceil() as i32).clamp(-32, 0)
358                    as i8,
359                leap: LeapWarning::None,
360            })
361        }
362    }
363
364    use crate::ClockRead;
365}
366
367#[cfg(test)]
368#[path = "refclock_tests.rs"]
369mod refclock_tests;