Skip to main content

device/
real_time_clock.rs

1//! Real-time clock device contract (`/devices/time/real_time_clock`, kind `b'r'`).
2//!
3//! A real-time clock (RTC) stores wall-clock time (UTC) across resets and, on
4//! chips with a battery-backed domain, across power-off. Like Linux, Xila keeps
5//! RTC drivers separate from clocksource drivers: the RTC only supplies and
6//! stores UTC; timers, deadlines and uptime stay on the monotonic clock of the
7//! `time` subsystem and never read this device.
8//!
9//! The upper half (`drivers_peripherals::real_time_clock`) adapts a
10//! `peripherals::real_time_clock::RealTimeClockController` lower half to this
11//! contract. Plain `read` and `write` on the node fail with `Unsupported`:
12//! the clock is only reachable through the control commands below.
13//!
14//! # Control commands (kind `b'r'`)
15//!
16//! | Number | Command    | Direction | Input                  | Output                 | Effect                                              |
17//! |--------|------------|-----------|------------------------|------------------------|-----------------------------------------------------|
18//! | `0x00` | `GET_TIME` | Read      | `RealTimeClockTimeAbi` | `RealTimeClockTimeAbi` | Returns the time the clock holds and its validity.  |
19//! | `0x01` | `SET_TIME` | Write     | `RealTimeClockTimeAbi` | `RealTimeClockTimeAbi` | Sets the clock, then returns the time it now holds. |
20//!
21//! Both commands carry the same versioned payload. In a `GET_TIME` input only
22//! `version` and `reserved` are checked; the time fields are ignored. A wrong
23//! `version`, a non-zero `reserved` or, for `SET_TIME`, `valid != 1` or
24//! `nanoseconds >= 1_000_000_000` fails with `InvalidArgument`. In a `GET_TIME`
25//! output `valid` is `1` when the clock holds a valid time and `0` when it does
26//! not (for example after power-off on a chip without a battery-backed domain);
27//! then `seconds` and `nanoseconds` are zero. A clock that cannot be read or
28//! written fails with `InputOutput`.
29
30use file_system::{ControlCommand, define_command};
31
32/// Path of the real-time clock device node in the virtual file system.
33pub const REAL_TIME_CLOCK_PATH: &str = "/devices/time/real_time_clock";
34
35/// Version of the real-time clock control ABI payload.
36pub const ABI_VERSION: u16 = 1;
37
38/// `valid` value of a clock that holds a valid time.
39pub const VALID: u8 = 1;
40/// `valid` value of a clock that holds no valid time.
41pub const NOT_VALID: u8 = 0;
42
43/// Largest accepted value of `nanoseconds` (exclusive).
44pub const MAX_NANOSECONDS: u32 = 1_000_000_000;
45
46file_system::plain_data! {
47    #[repr(C)]
48    /// UTC wall-clock time held by a real-time clock, plus its ABI version and
49    /// validity. Field order keeps the struct free of padding on 32-bit and
50    /// 64-bit targets: 16 bytes everywhere.
51    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
52    pub struct RealTimeClockTimeAbi {
53        pub version: u16,
54        /// [`VALID`] when the clock holds a valid time, [`NOT_VALID`] otherwise.
55        pub valid: u8,
56        pub reserved: u8,
57        /// Nanoseconds within the second, `0..`[`MAX_NANOSECONDS`].
58        pub nanoseconds: u32,
59        /// Signed Unix seconds since 1970-01-01T00:00:00Z, without timezone or DST.
60        pub seconds: i64,
61    }
62}
63
64define_command!(
65    GET_TIME,
66    Read,
67    crate::kind::REAL_TIME_CLOCK,
68    0x00,
69    RealTimeClockTimeAbi,
70    RealTimeClockTimeAbi
71);
72define_command!(
73    SET_TIME,
74    Write,
75    crate::kind::REAL_TIME_CLOCK,
76    0x01,
77    RealTimeClockTimeAbi,
78    RealTimeClockTimeAbi
79);
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84    use core::mem::{offset_of, size_of};
85    use file_system::ControlDirectionFlags;
86
87    #[test]
88    fn identifiers_are_distinct_and_directions_match_the_contract() {
89        assert_ne!(GET_TIME::IDENTIFIER, SET_TIME::IDENTIFIER);
90        assert_eq!(
91            GET_TIME::IDENTIFIER.get_kind(),
92            crate::kind::REAL_TIME_CLOCK
93        );
94        assert_eq!(
95            SET_TIME::IDENTIFIER.get_kind(),
96            crate::kind::REAL_TIME_CLOCK
97        );
98        assert_eq!(GET_TIME::IDENTIFIER.get_number(), 0x00);
99        assert_eq!(SET_TIME::IDENTIFIER.get_number(), 0x01);
100        assert!(
101            GET_TIME::IDENTIFIER
102                .get_direction()
103                .contains(ControlDirectionFlags::Read)
104        );
105        assert!(
106            SET_TIME::IDENTIFIER
107                .get_direction()
108                .contains(ControlDirectionFlags::Write)
109        );
110        assert!(
111            !GET_TIME::IDENTIFIER
112                .get_direction()
113                .contains(ControlDirectionFlags::Write)
114        );
115    }
116
117    #[test]
118    fn payload_is_sixteen_bytes_without_padding_on_any_target() {
119        // plain_data! already rejects padding at compile time; pin the layout so
120        // a field reorder cannot silently change the wire size.
121        assert_eq!(size_of::<RealTimeClockTimeAbi>(), 16);
122        assert_eq!(offset_of!(RealTimeClockTimeAbi, version), 0);
123        assert_eq!(offset_of!(RealTimeClockTimeAbi, valid), 2);
124        assert_eq!(offset_of!(RealTimeClockTimeAbi, reserved), 3);
125        assert_eq!(offset_of!(RealTimeClockTimeAbi, nanoseconds), 4);
126        assert_eq!(offset_of!(RealTimeClockTimeAbi, seconds), 8);
127    }
128
129    #[test]
130    fn payload_round_trips_through_raw_wire_bytes() {
131        let time = RealTimeClockTimeAbi {
132            version: ABI_VERSION,
133            valid: VALID,
134            reserved: 0,
135            nanoseconds: 123_456_789,
136            seconds: -1,
137        };
138        // The payload crosses the host/guest boundary as raw bytes. It is plain
139        // data without padding, so reading it as bytes is sound.
140        let mut bytes = [0u8; 16];
141        // SAFETY: `RealTimeClockTimeAbi` is `PlainData` and has no padding.
142        unsafe {
143            core::ptr::copy_nonoverlapping(
144                &time as *const RealTimeClockTimeAbi as *const u8,
145                bytes.as_mut_ptr(),
146                bytes.len(),
147            )
148        };
149        // Little-endian wire layout of the pinned field order.
150        assert_eq!(&bytes[0..2], &ABI_VERSION.to_le_bytes());
151        assert_eq!(bytes[2], VALID);
152        assert_eq!(bytes[3], 0);
153        assert_eq!(&bytes[4..8], &123_456_789u32.to_le_bytes());
154        assert_eq!(&bytes[8..16], &(-1i64).to_le_bytes());
155        // SAFETY: every byte pattern is a valid `RealTimeClockTimeAbi`.
156        let decoded: RealTimeClockTimeAbi =
157            unsafe { core::ptr::read(bytes.as_ptr() as *const RealTimeClockTimeAbi) };
158        assert_eq!(decoded, time);
159        // Any byte pattern decodes: the payload is plain data, so a guest can
160        // never send an invalid value such as `2` for the validity byte.
161        let garbage = [0xFFu8; 16];
162        // SAFETY: every byte pattern is valid.
163        let _: RealTimeClockTimeAbi =
164            unsafe { core::ptr::read(garbage.as_ptr() as *const RealTimeClockTimeAbi) };
165    }
166}