Skip to main content

strat9_kernel/s9vm/
rtc.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! s9vm : MC146818-compatible CMOS real-time clock model for guests.
24//!
25//! A PC-compatible guest reads the wall clock through two I/O ports: the
26//! **index port** (`0x70`) selects one of 128 CMOS registers (bit 7 gates the
27//! NMI), and the **data port** (`0x71`) reads or writes the selected register.
28//! This module models the MC146818 (and its CMOS RAM) as pure state: the kernel
29//! calls [`CmosRtc::write_index`] / [`CmosRtc::read_data`] /
30//! [`CmosRtc::write_data`] when it emulates those ports, and never touches
31//! hardware.
32//!
33//! # Time is computed, never stored per field
34//!
35//! Only a UNIX timestamp is kept. The calendar registers (`sec`, `min`,
36//! `hour`, `weekday`, `day`, `month`, `year`, `century`) are **computed on
37//! read** from that timestamp, so the clock cannot drift between the fields and
38//! never needs a periodic update: the kernel advances it explicitly with
39//! [`CmosRtc::advance`] (for instance with the time elapsed between two vCPU
40//! runs) or [`CmosRtc::advance_events`] when it also wants the interrupt
41//! events. [`CmosRtc::new`] starts at the UNIX epoch, `1970-01-01T00:00:00Z`,
42//! which is a valid calendar date, and leap years are handled by the civil
43//! date conversion.
44//!
45//! # Interrupt model
46//!
47//! The chip's three interrupt sources are modelled from a **32.768 kHz
48//! reference clock** ([`REFERENCE_HZ`]), the divider input of status register A:
49//!
50//! - **periodic**: the rate-select field `RS3:0` (status A bits `3:0`) selects a
51//!   periodic frequency `REFERENCE_HZ >> (RS - 1)` for `RS in 3..=15`; `RS < 3`
52//!   disables the periodic interrupt. The counter is a phase accumulator, so a
53//!   slow poller does not lose phase: the events of a whole interval collapse
54//!   into one observed event, but the next event keeps the exact rate.
55//! - **update-ended**: one event at every second boundary of the host clock.
56//! - **alarm**: the alarm bytes (`0x01` seconds, `0x03` minutes, `0x05` hours,
57//!   and `0x31` day of month in this model) are compared with the guest-visible
58//!   time at the new second boundary. A byte in `0xC0..=0xFF` means **don't
59//!   care**, as on the chip: the top two bits at `11` are never produced by BCD
60//!   or 12-hour encoding, so the convention is unambiguous. The chip itself has
61//!   no day-of-month alarm register, so the model keeps that byte in spare CMOS
62//!   RAM at [`REG_DAY_ALARM`]; the weekday alarm byte is not compared.
63//!
64//! Events set the status-C flags (`PF`, `AF`, `UF`) **whether or not the
65//! matching enable bit in status B is set**, as on the hardware; the enable
66//! bits (`PIE`, `AIE`, `UIE`) only gate the interrupt request. The summary bit
67//! `IRQF` (status C bit 7) is not stored: it is computed on read as the OR of
68//! the enabled event flags. Reading status C returns the flags and clears them,
69//! exactly once.
70//!
71//! A single [`CmosRtc::advance_events`] call reports at most **one event of
72//! each kind** because [`RtcEvents`] uses booleans: a caller that advances by
73//! several periods still sees `periodic = true` once, and one status-C flag.
74//! This is the documented granularity; poll more often to observe each period.
75//!
76//! Register semantics, following the chip:
77//!
78//! | Index | Register | Model behaviour |
79//! |---|---|---|
80//! | `0x00` | seconds | computed |
81//! | `0x01` | seconds alarm | writable RAM, compared (don't-care bytes) |
82//! | `0x02` | minutes | computed |
83//! | `0x03` | minutes alarm | writable RAM, compared (don't-care bytes) |
84//! | `0x04` | hours | computed |
85//! | `0x05` | hours alarm | writable RAM, compared (don't-care bytes) |
86//! | `0x06` | weekday (`1` = Sunday .. `7` = Saturday) | computed |
87//! | `0x07` | day of month | computed |
88//! | `0x08` | month | computed |
89//! | `0x09` | year (two digits) | computed |
90//! | `0x0A` | status A | divider/rate writable, UIP always `0` |
91//! | `0x0B` | status B | writable; enables, formats and SET |
92//! | `0x0C` | status C | event flags + computed `IRQF`; reading clears |
93//! | `0x0D` | status D | reads `0x80` (valid RAM and time) |
94//! | `0x0E..=0x7F` | CMOS RAM | writable, default `0` (except `0x31`, `0x32`) |
95//! | `0x31` | day-of-month alarm (model extension) | writable RAM, compared (don't-care bytes) |
96//! | `0x32` | century | computed |
97//!
98//! # Invariants
99//!
100//! - UIP (status A, bit 7) always reads as zero: the model is instantaneous, a
101//!   driver may read the fields in any order;
102//! - status C flags are generated by events (or by [`CmosRtc::raise_status_c`]
103//!   for the caller) and cleared by the read that returns them; the guest can
104//!   never set them by writing status C;
105//! - while status B SET is asserted, the computed time is frozen at the moment
106//!   SET was written (the host may then program the clock), and clearing SET
107//!   makes the computed registers follow the current timestamp again; events
108//!   keep being generated from the host clock, and the alarm compares the
109//!   frozen guest-visible time;
110//! - writes to the computed time registers are accepted (they land in CMOS RAM
111//!   bytes) but do not change the clock: a driver must use an external time
112//!   source, which is the documented behaviour of this model;
113//! - `new` reports a valid calendar in BCD, 24-hour mode, with every interrupt
114//!   disabled.
115//!
116//! This module is pure `core` code and is host-tested by `s9vm-tests`.
117
118use crate::rtc_math;
119
120/// I/O port selecting a CMOS register (and gating the NMI with bit 7).
121pub const INDEX_PORT: u16 = 0x70;
122/// I/O port reading or writing the selected CMOS register.
123pub const DATA_PORT: u16 = 0x71;
124/// Bit of the index port that disables the NMI when set.
125pub const NMI_PORT_MASK: u8 = 0x80;
126/// I/O APIC line wired to the RTC periodic interrupt.
127pub const IRQ_LINE: u8 = 8;
128/// Frequency of the RTC reference clock (the divider input), in hertz.
129pub const REFERENCE_HZ: u32 = 32_768;
130/// Top two bits of an alarm byte meaning "don't care".
131pub const ALARM_DONT_CARE_MASK: u8 = 0xC0;
132
133/// Number of CMOS registers addressable by the index port.
134pub const REGISTER_COUNT: usize = 128;
135
136/// Seconds register.
137pub const REG_SECONDS: u8 = 0x00;
138/// Seconds alarm register.
139pub const REG_SECONDS_ALARM: u8 = 0x01;
140/// Minutes register.
141pub const REG_MINUTES: u8 = 0x02;
142/// Minutes alarm register.
143pub const REG_MINUTES_ALARM: u8 = 0x03;
144/// Hours register.
145pub const REG_HOURS: u8 = 0x04;
146/// Hours alarm register.
147pub const REG_HOURS_ALARM: u8 = 0x05;
148/// Weekday register (`1` = Sunday .. `7` = Saturday).
149pub const REG_WEEKDAY: u8 = 0x06;
150/// Day-of-month register.
151pub const REG_DAY: u8 = 0x07;
152/// Month register.
153pub const REG_MONTH: u8 = 0x08;
154/// Two-digit year register.
155pub const REG_YEAR: u8 = 0x09;
156/// Status register A.
157pub const REG_STATUS_A: u8 = 0x0A;
158/// Status register B.
159pub const REG_STATUS_B: u8 = 0x0B;
160/// Status register C.
161pub const REG_STATUS_C: u8 = 0x0C;
162/// Status register D.
163pub const REG_STATUS_D: u8 = 0x0D;
164/// Day-of-month alarm register.
165///
166/// The chip has no day-of-month alarm register (its alarm covers seconds,
167/// minutes and hours only). The model needs one to honour the guest-requested
168/// alarm, so it uses a spare CMOS RAM byte, next to the century register, with
169/// the same "don't care" convention as the standard alarm bytes.
170pub const REG_DAY_ALARM: u8 = 0x31;
171/// Century register.
172pub const REG_CENTURY: u8 = 0x32;
173
174/// Bits of status register A.
175pub mod status_a {
176    /// Update-in-progress; always reads as `0` in this model.
177    pub const UIP: u8 = 0x80;
178    /// Divider and rate-select bits (bits 6:0).
179    pub const DIVIDER_MASK: u8 = 0x7F;
180    /// Rate-select field (bits 3:0): periodic interrupt frequency.
181    pub const RATE_SELECT_MASK: u8 = 0x0F;
182    /// Lowest rate-select value that enables the periodic interrupt.
183    pub const MIN_RATE_SELECT: u8 = 3;
184    /// Default value: 32.768 kHz divider input, `RS = 6`, 1024 Hz periodic rate.
185    pub const DEFAULT: u8 = 0x26;
186}
187
188/// Bits of status register B.
189pub mod status_b {
190    /// `1` = the clock is frozen and may be programmed.
191    pub const SET: u8 = 0x80;
192    /// `1` = periodic interrupt enabled.
193    pub const PERIODIC_INTERRUPT: u8 = 0x40;
194    /// `1` = alarm interrupt enabled.
195    pub const ALARM_INTERRUPT: u8 = 0x20;
196    /// `1` = update-ended interrupt enabled.
197    pub const UPDATE_ENDED_INTERRUPT: u8 = 0x10;
198    /// `1` = binary register format, `0` = BCD.
199    pub const BINARY: u8 = 0x04;
200    /// `1` = 24-hour mode, `0` = 12-hour mode (bit 7 of hours = PM).
201    pub const HOURS_24: u8 = 0x02;
202    /// `1` = daylight-saving time enabled (formatting hint only).
203    pub const DAYLIGHT_SAVING: u8 = 0x01;
204    /// Default value: BCD, 24-hour mode, every interrupt disabled.
205    pub const DEFAULT: u8 = HOURS_24;
206}
207
208/// Bits of status register C.
209pub mod status_c {
210    /// Interrupt request summary: OR of the enabled event flags.
211    ///
212    /// Computed on read, never stored.
213    pub const IRQF: u8 = 0x80;
214    /// Periodic-interrupt flag.
215    pub const PERIODIC: u8 = 0x40;
216    /// Alarm-interrupt flag.
217    pub const ALARM: u8 = 0x20;
218    /// Update-ended-interrupt flag.
219    pub const UPDATED: u8 = 0x10;
220    /// Mask of the event flags (the part that is stored and cleared on read).
221    pub const EVENT_FLAGS: u8 = PERIODIC | ALARM | UPDATED;
222}
223
224/// Bits of status register D.
225pub mod status_d {
226    /// The CMOS RAM and the time are valid.
227    pub const VALID: u8 = 0x80;
228}
229
230/// True when `port` belongs to the modelled CMOS RTC (`0x70` or `0x71`).
231pub const fn handles_port(port: u16) -> bool {
232    port == INDEX_PORT || port == DATA_PORT
233}
234
235/// True when an alarm byte carries the "don't care" convention.
236///
237/// The top two bits at `11` (`0xC0..=0xFF`) mean "ignore this field"; no value
238/// produced by BCD or by the 12-hour encoding sets both bits.
239pub const fn alarm_dont_care(value: u8) -> bool {
240    value & ALARM_DONT_CARE_MASK == ALARM_DONT_CARE_MASK
241}
242
243/// Events produced by one [`CmosRtc::advance_events`] call.
244///
245/// Each field is a boolean: an interval that spans several periods or several
246/// seconds still reports one event per kind, and latches one status-C flag.
247#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
248pub struct RtcEvents {
249    /// At least one periodic interrupt period elapsed.
250    pub periodic: bool,
251    /// At least one second boundary was crossed (update-ended).
252    pub update_ended: bool,
253    /// The alarm matched at the new second boundary.
254    pub alarm: bool,
255}
256
257impl RtcEvents {
258    /// No event occurred.
259    pub const NONE: Self = Self {
260        periodic: false,
261        update_ended: false,
262        alarm: false,
263    };
264
265    /// True if at least one event occurred.
266    pub const fn any(self) -> bool {
267        self.periodic || self.update_ended || self.alarm
268    }
269}
270
271/// Model of an MC146818-compatible CMOS RTC and its CMOS RAM.
272#[derive(Clone, Debug, PartialEq, Eq)]
273pub struct CmosRtc {
274    /// Currently selected register (`0..=127`).
275    index: u8,
276    /// NMI disabled by the last index-port write (bit 7 of the index byte).
277    nmi_disabled: bool,
278    /// Current UNIX timestamp, in seconds.
279    unix_time: u64,
280    /// Timestamp captured when status B SET was written.
281    frozen: Option<u64>,
282    /// Status register A (UIP excluded when read).
283    status_a: u8,
284    /// Status register B.
285    status_b: u8,
286    /// Status register C flags, cleared on read.
287    status_c: u8,
288    /// Sub-second remainder of the 32.768 kHz reference clock.
289    sub_second_remainder: u64,
290    /// Phase of the periodic interrupt, in reference-clock ticks.
291    periodic_accumulator: u64,
292    /// CMOS RAM bytes; the computed registers are only mirrors of the clock.
293    ram: [u8; REGISTER_COUNT],
294}
295
296impl CmosRtc {
297    /// Creates a clock at the UNIX epoch, BCD, 24-hour, with a valid calendar.
298    pub fn new() -> Self {
299        Self {
300            index: 0,
301            nmi_disabled: false,
302            unix_time: 0,
303            frozen: None,
304            status_a: status_a::DEFAULT,
305            status_b: status_b::DEFAULT,
306            status_c: 0,
307            sub_second_remainder: 0,
308            periodic_accumulator: 0,
309            ram: [0; REGISTER_COUNT],
310        }
311    }
312
313    /// Sets the clock to `seconds` since the UNIX epoch.
314    ///
315    /// If status B SET is asserted, the frozen snapshot is updated too, so the
316    /// guest sees the newly programmed time.
317    pub fn set_unix_time(&mut self, seconds: u64) {
318        self.unix_time = seconds;
319        if self.frozen.is_some() {
320            self.frozen = Some(seconds);
321        }
322    }
323
324    /// Current UNIX timestamp, in seconds.
325    ///
326    /// This is the host-side time: it keeps advancing even while status B SET
327    /// freezes the **guest-visible** calendar registers.
328    pub const fn unix_time(&self) -> u64 {
329        self.unix_time
330    }
331
332    /// Advances the clock by `seconds` (saturating at [`u64::MAX`]).
333    ///
334    /// This is the historical helper used by the device model: it advances the
335    /// time, generates the same interrupt events as
336    /// [`Self::advance_events`] (so status C and [`Self::irq_asserted`] stay
337    /// coherent) and discards the returned events.
338    pub fn advance(&mut self, seconds: u64) {
339        let _ = self.advance_events(seconds, 0);
340    }
341
342    /// Advances the clock and reports the interrupt events of the interval.
343    ///
344    /// `seconds` is whole host seconds; `sub_second_ticks` is an additional
345    /// fraction expressed in **32.768 kHz reference-clock ticks**
346    /// ([`REFERENCE_HZ`]) : typically `elapsed_ticks / 32768` remainders passed
347    /// by a caller that only has a finer-grained clock. The two are added and
348    /// the sub-second remainder is carried across calls, so repeated calls with
349    /// small tick counts do not drift.
350    ///
351    /// The returned [`RtcEvents`] carries at most one event of each kind:
352    ///
353    /// - `periodic`: at least one periodic period elapsed. The phase
354    ///   accumulator is maintained modulo the programmed period, so the *rate*
355    ///   stays exact even when a poll covers several periods;
356    /// - `update_ended`: at least one second boundary was crossed (the model
357    ///   has no update cycle to interrupt, so this is the advertised
358    ///   update-ended event);
359    /// - `alarm`: the alarm bytes matched at the new second boundary. A single
360    ///   large jump evaluates the alarm once, on the final second; poll more
361    ///   often if an intermediate alarm instant must not be missed.
362    ///
363    /// Events always latch the matching status-C flag (`PF`, `AF`, `UF`), as on
364    /// the hardware; the status-B enables only decide whether `IRQF` is
365    /// asserted. Reading status C clears the flags.
366    ///
367    /// The clock saturates at [`u64::MAX`]; events are then computed from the
368    /// ticks that actually elapsed.
369    pub fn advance_events(&mut self, seconds: u64, sub_second_ticks: u64) -> RtcEvents {
370        // Saturating u128 arithmetic: a hostile caller cannot overflow the
371        // second/tick product, and the divisions have a non-zero divisor.
372        // `elapsed_ticks` is what the periodic phase consumes; `total_ticks`
373        // adds the fraction carried from the previous call, which matters only
374        // for whole-second (update-ended) detection.
375        let elapsed_ticks = u128::from(seconds)
376            .saturating_mul(u128::from(REFERENCE_HZ))
377            .saturating_add(u128::from(sub_second_ticks));
378        let total_ticks = elapsed_ticks.saturating_add(u128::from(self.sub_second_remainder));
379        let whole_seconds_128 = total_ticks / u128::from(REFERENCE_HZ);
380        self.sub_second_remainder = (total_ticks % u128::from(REFERENCE_HZ)) as u64;
381
382        let previous = self.unix_time;
383        let whole_seconds = if whole_seconds_128 > u128::from(u64::MAX) {
384            u64::MAX
385        } else {
386            whole_seconds_128 as u64
387        };
388        self.unix_time = self.unix_time.saturating_add(whole_seconds);
389        let elapsed_seconds = self.unix_time.saturating_sub(previous);
390
391        let mut events = RtcEvents::NONE;
392        if let Some(rate) = self.periodic_rate_hz() {
393            // The rate is always a power of two, so the period divides the
394            // reference frequency exactly and the shift never truncates.
395            let period_ticks = u128::from(REFERENCE_HZ / rate);
396            let accumulated = u128::from(self.periodic_accumulator) + elapsed_ticks;
397            events.periodic = accumulated >= period_ticks;
398            self.periodic_accumulator = (accumulated % period_ticks) as u64;
399        } else {
400            self.periodic_accumulator = 0;
401        }
402
403        if elapsed_seconds > 0 {
404            events.update_ended = true;
405            events.alarm = self.alarm_matches();
406        }
407
408        let mut flags = 0;
409        if events.periodic {
410            flags |= status_c::PERIODIC;
411        }
412        if events.alarm {
413            flags |= status_c::ALARM;
414        }
415        if events.update_ended {
416            flags |= status_c::UPDATED;
417        }
418        self.status_c |= flags;
419        events
420    }
421
422    /// Periodic interrupt frequency in hertz, or `None` when disabled.
423    ///
424    /// The rate-select field `RS3:0` follows the chip encoding:
425    /// `rate = 32768 >> (RS - 1)` for `RS in 3..=15`; `RS` below 3 disables the
426    /// periodic interrupt. The default status A (`0x26`) selects `RS = 6`, that
427    /// is 1024 Hz.
428    pub fn periodic_rate_hz(&self) -> Option<u32> {
429        let rate_select = self.status_a & status_a::RATE_SELECT_MASK;
430        if rate_select < status_a::MIN_RATE_SELECT {
431            None
432        } else {
433            Some(REFERENCE_HZ >> (rate_select - 1))
434        }
435    }
436
437    /// True while the interrupt request line is asserted.
438    ///
439    /// Computed, not stored: the OR of the event flags whose enable bit is set
440    /// in status B : exactly the `IRQF` bit that a status-C read returns.
441    pub const fn irq_asserted(&self) -> bool {
442        let enabled = self.status_b;
443        (self.status_c & status_c::PERIODIC != 0 && enabled & status_b::PERIODIC_INTERRUPT != 0)
444            || (self.status_c & status_c::ALARM != 0 && enabled & status_b::ALARM_INTERRUPT != 0)
445            || (self.status_c & status_c::UPDATED != 0
446                && enabled & status_b::UPDATE_ENDED_INTERRUPT != 0)
447    }
448
449    /// True when the periodic interrupt is enabled in status B.
450    pub const fn periodic_interrupt_enabled(&self) -> bool {
451        self.status_b & status_b::PERIODIC_INTERRUPT != 0
452    }
453
454    /// True when the alarm interrupt is enabled in status B.
455    pub const fn alarm_interrupt_enabled(&self) -> bool {
456        self.status_b & status_b::ALARM_INTERRUPT != 0
457    }
458
459    /// True when the update-ended interrupt is enabled in status B.
460    pub const fn update_ended_interrupt_enabled(&self) -> bool {
461        self.status_b & status_b::UPDATE_ENDED_INTERRUPT != 0
462    }
463
464    /// True in 24-hour mode (status B bit 1).
465    pub const fn hours_24_mode(&self) -> bool {
466        self.status_b & status_b::HOURS_24 != 0
467    }
468
469    /// True in binary data mode (status B bit 2).
470    pub const fn binary_mode(&self) -> bool {
471        self.status_b & status_b::BINARY != 0
472    }
473
474    /// True when the daylight-saving hint is set (status B bit 0).
475    ///
476    /// The model does not shift the clock: the bit is exposed for drivers that
477    /// report or program it, and has no effect on the computed time.
478    pub const fn daylight_saving_enabled(&self) -> bool {
479        self.status_b & status_b::DAYLIGHT_SAVING != 0
480    }
481
482    /// True while status B SET freezes the guest-visible calendar.
483    pub const fn clock_frozen(&self) -> bool {
484        self.status_b & status_b::SET != 0
485    }
486
487    /// Writes the index port.
488    ///
489    /// Bit 7 disables the NMI; bits 6:0 select the CMOS register. The selected
490    /// register is what the next data-port access reads or writes.
491    pub fn write_index(&mut self, value: u8) {
492        self.nmi_disabled = value & NMI_PORT_MASK != 0;
493        self.index = value & !NMI_PORT_MASK;
494    }
495
496    /// Currently selected register index (`0..=127`).
497    pub const fn index(&self) -> u8 {
498        self.index
499    }
500
501    /// True when the last index-port write disabled the NMI.
502    pub const fn nmi_disabled(&self) -> bool {
503        self.nmi_disabled
504    }
505
506    /// Reads the data port for the selected register.
507    pub fn read_data(&mut self) -> u8 {
508        match self.index {
509            REG_SECONDS => self.encode(self.seconds()),
510            REG_MINUTES => self.encode(self.minutes()),
511            REG_HOURS => self.encode_hours(),
512            REG_WEEKDAY => self.encode(self.weekday()),
513            REG_DAY => self.encode(self.day()),
514            REG_MONTH => self.encode(self.month()),
515            REG_YEAR => self.encode(self.year() % 100),
516            REG_CENTURY => self.encode(self.year() / 100),
517            REG_STATUS_A => self.status_a & status_a::DIVIDER_MASK,
518            REG_STATUS_B => self.status_b,
519            REG_STATUS_C => {
520                // The event flags are returned once and cleared; the summary
521                // bit is computed from the enables and never stored.
522                let mut value = self.status_c & status_c::EVENT_FLAGS;
523                if self.irq_asserted() {
524                    value |= status_c::IRQF;
525                }
526                self.status_c = 0;
527                value
528            }
529            REG_STATUS_D => status_d::VALID,
530            _ => self.ram[usize::from(self.index)],
531        }
532    }
533
534    /// Writes the data port for the selected register.
535    ///
536    /// Computed time registers are accepted and kept as CMOS RAM bytes but do
537    /// not move the clock (see the module documentation). Status C and D are
538    /// read-only; writes to them are ignored.
539    pub fn write_data(&mut self, value: u8) {
540        match self.index {
541            REG_STATUS_A => {
542                self.status_a = value & status_a::DIVIDER_MASK;
543                // Changing the rate restarts the periodic phase, as the
544                // divider chain does on the chip.
545                self.periodic_accumulator = 0;
546            }
547            REG_STATUS_B => self.write_status_b(value),
548            REG_STATUS_C | REG_STATUS_D => {}
549            _ => self.ram[usize::from(self.index)] = value,
550        }
551    }
552
553    /// Writes a CMOS RAM byte directly, without going through the index and
554    /// data ports.
555    ///
556    /// Firmware configuration (floppy drive types at `0x10`, extended-memory
557    /// size at `0x30`/`0x31`) is planted this way before the guest starts; the
558    /// guest may overwrite it through the normal ports afterwards.
559    pub fn set_ram(&mut self, register: u8, value: u8) {
560        self.ram[usize::from(register)] = value;
561    }
562
563    /// Reads a CMOS RAM byte directly.
564    pub fn ram(&self, register: u8) -> u8 {
565        self.ram[usize::from(register)]
566    }
567
568    /// Raises interrupt flags in status register C.
569    ///
570    /// The device model calls this when an external event must be latched; the
571    /// guest observes the bits once, then the read that returns them clears
572    /// them. Only the event flags are accepted: `IRQF` is computed by the model
573    /// and a caller cannot force it.
574    pub fn raise_status_c(&mut self, flags: u8) {
575        self.status_c |= flags & status_c::EVENT_FLAGS;
576    }
577
578    /// Writes status register B, capturing or releasing the SET freeze.
579    fn write_status_b(&mut self, value: u8) {
580        let was_set = self.status_b & status_b::SET != 0;
581        let is_set = value & status_b::SET != 0;
582        match (was_set, is_set) {
583            (false, true) => self.frozen = Some(self.unix_time),
584            (true, false) => self.frozen = None,
585            _ => {}
586        }
587        self.status_b = value;
588    }
589
590    /// Timestamp the computed registers are derived from.
591    fn clock(&self) -> u64 {
592        self.frozen.unwrap_or(self.unix_time)
593    }
594
595    /// Seconds (`0..=59`).
596    fn seconds(&self) -> u64 {
597        self.clock() % 60
598    }
599
600    /// Minutes (`0..=59`).
601    fn minutes(&self) -> u64 {
602        (self.clock() / 60) % 60
603    }
604
605    /// Hours in 24-hour form (`0..=23`).
606    fn hours(&self) -> u64 {
607        (self.clock() / 3600) % 24
608    }
609
610    /// Day of week, `1` = Sunday .. `7` = Saturday.
611    fn weekday(&self) -> u64 {
612        let days = self.clock() / 86_400;
613        // The UNIX epoch (day 0) was a Thursday: Sunday-based numbering makes
614        // Thursday the fifth day of the week.
615        (days + 4) % 7 + 1
616    }
617
618    /// Day of the month (`1..=31`).
619    fn day(&self) -> u64 {
620        u64::from(rtc_math::civil_from_days(self.days()).2)
621    }
622
623    /// Month (`1..=12`).
624    fn month(&self) -> u64 {
625        u64::from(rtc_math::civil_from_days(self.days()).1)
626    }
627
628    /// Full Gregorian year.
629    fn year(&self) -> u64 {
630        rtc_math::civil_from_days(self.days()).0
631    }
632
633    /// Whole days since the UNIX epoch.
634    fn days(&self) -> u64 {
635        self.clock() / 86_400
636    }
637
638    /// Encodes a value in the format selected by status B (binary or BCD).
639    fn encode(&self, value: u64) -> u8 {
640        if self.status_b & status_b::BINARY != 0 {
641            value as u8
642        } else {
643            rtc_math::binary_to_bcd(value as u8)
644        }
645    }
646
647    /// Encodes the hours register, honouring the 12/24-hour mode.
648    fn encode_hours(&self) -> u8 {
649        self.encode_hours_value(self.hours())
650    }
651
652    /// Encodes a 24-hour value into the guest-visible hours byte.
653    fn encode_hours_value(&self, hours: u64) -> u8 {
654        if self.status_b & status_b::HOURS_24 != 0 {
655            return self.encode(hours);
656        }
657        let hour12 = if hours % 12 == 0 { 12 } else { hours % 12 };
658        let mut value = self.encode(hour12);
659        if hours >= 12 {
660            value |= 0x80;
661        }
662        value
663    }
664
665    /// True when the guest-visible time matches the programmed alarm.
666    ///
667    /// Seconds, minutes, hours and the model's day-of-month byte are compared;
668    /// a byte in `0xC0..=0xFF` is a wildcard. The comparison uses the current
669    /// display encoding, so a guest must program the alarm bytes in the same
670    /// BCD/binary and 12/24-hour mode as the time registers.
671    fn alarm_matches(&self) -> bool {
672        let clock = self.clock();
673        let seconds = clock % 60;
674        let minutes = (clock / 60) % 60;
675        let hours = (clock / 3600) % 24;
676        let day = self.day();
677        alarm_byte_matches(
678            self.ram[usize::from(REG_SECONDS_ALARM)],
679            self.encode(seconds),
680        ) && alarm_byte_matches(
681            self.ram[usize::from(REG_MINUTES_ALARM)],
682            self.encode(minutes),
683        ) && alarm_byte_matches(
684            self.ram[usize::from(REG_HOURS_ALARM)],
685            self.encode_hours_value(hours),
686        ) && alarm_byte_matches(self.ram[usize::from(REG_DAY_ALARM)], self.encode(day))
687    }
688}
689
690/// Compares one alarm byte with the encoded current value.
691///
692/// A "don't care" byte always matches; otherwise the bytes must be identical.
693fn alarm_byte_matches(alarm: u8, current: u8) -> bool {
694    alarm_dont_care(alarm) || alarm == current
695}
696
697impl Default for CmosRtc {
698    fn default() -> Self {
699        Self::new()
700    }
701}