Skip to main content

strat9_kernel/hardware/timer/
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// RTC (Real Time Clock) Driver
24// Reference: MC146818A RTC chip
25//
26// Features:
27// - Current time reading (BCD and binary modes)
28// - CMOS RAM access
29// - Update interrupt handling
30// - Alarm support
31
32#![allow(dead_code)]
33
34use crate::{
35    arch::io::{inb, outb},
36    rtc_math,
37};
38use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
39use spin::Mutex;
40
41// CMOS ports
42const CMOS_ADDR_PORT: u16 = 0x70;
43const CMOS_DATA_PORT: u16 = 0x71;
44
45// CMOS registers
46const CMOS_REG_SECOND: u8 = 0x00;
47const CMOS_REG_MINUTE: u8 = 0x02;
48const CMOS_REG_HOUR: u8 = 0x04;
49const CMOS_REG_WEEKDAY: u8 = 0x06;
50const CMOS_REG_DAY: u8 = 0x07;
51const CMOS_REG_MONTH: u8 = 0x08;
52const CMOS_REG_YEAR: u8 = 0x09;
53const CMOS_REG_STATUS_A: u8 = 0x0A;
54const CMOS_REG_STATUS_B: u8 = 0x0B;
55const CMOS_REG_STATUS_C: u8 = 0x0C;
56
57// Status register A bits
58const STATUS_A_UIP: u8 = 0x80; // Update In Progress
59
60// Status register B bits
61const STATUS_B_PIE: u8 = 0x40; // Periodic interrupt enable
62const STATUS_B_UIE: u8 = 0x10; // Update interrupt enable
63const STATUS_B_DM: u8 = 0x04; // Data mode (1=binary, 0=BCD)
64const STATUS_B_24H: u8 = 0x02; // 24-hour mode
65
66// Status register C bits (read-only, clears interrupts)
67// RTC frequency options (Hz)
68const RTC_FREQ_1024: u8 = 6; // 1024 Hz
69const RTC_FREQ_256: u8 = 8; // 256 Hz
70const RTC_FREQ_64: u8 = 10; // 64 Hz
71const RTC_FREQ_16: u8 = 12; // 16 Hz
72const RTC_FREQ_4: u8 = 14; // 4 Hz
73const RTC_FREQ_1: u8 = 15; // 1 Hz
74
75const CENTURY_REG_CANDIDATES: &[u8] = &[0x32, 0x37];
76
77/// RTC date/time structure
78#[derive(Clone, Copy, Debug)]
79pub struct RtcDateTime {
80    pub second: u8,
81    pub minute: u8,
82    pub hour: u8,
83    pub weekday: u8, // 0=Sunday, 6=Saturday
84    pub day: u8,
85    pub month: u8,
86    pub year: u16,
87    pub century: u16,
88}
89
90impl RtcDateTime {
91    /// Creates a new instance.
92    pub fn new() -> Self {
93        Self {
94            second: 0,
95            minute: 0,
96            hour: 0,
97            weekday: 0,
98            day: 0,
99            month: 0,
100            year: 2000,
101            century: 20,
102        }
103    }
104
105    /// Convert to Unix timestamp (seconds since 1970-01-01 00:00:00 UTC)
106    pub fn to_timestamp(&self) -> u64 {
107        rtc_math::unix_from_civil(
108            i64::from(self.year),
109            u32::from(self.month),
110            u32::from(self.day),
111            self.hour,
112            self.minute,
113            self.second,
114        )
115    }
116
117    /// Convert a Unix timestamp (seconds since 1970-01-01 00:00:00 UTC) to a
118    /// civil date.
119    ///
120    /// Inverse of [`RtcDateTime::to_timestamp`], same shared algorithm ([`crate::rtc_math`]),
121    /// so the two cannot disagree about leap years. Callers that only want to
122    /// display a file timestamp (the shell's `ls -l`) use this instead of
123    /// re-deriving calendar arithmetic with a fixed-length year.
124    pub fn from_timestamp(timestamp: u64) -> Self {
125        let (year, month, day, hour, minute, second, weekday) =
126            rtc_math::civil_from_unix(timestamp);
127        Self {
128            second,
129            minute,
130            hour,
131            weekday,
132            day: day as u8,
133            month: month as u8,
134            year: year as u16,
135            century: ((year / 100) + 1) as u16,
136        }
137    }
138
139    /// Format as ISO 8601 string (simplified)
140    pub fn to_string(&self) -> [u8; 19] {
141        let mut buf = [0u8; 19];
142        let year = self.year;
143
144        // YYYY-MM-DDTHH:MM:SS
145        buf[0] = b'0' + ((year / 1000) % 10) as u8;
146        buf[1] = b'0' + ((year / 100) % 10) as u8;
147        buf[2] = b'0' + ((year / 10) % 10) as u8;
148        buf[3] = b'0' + (year % 10) as u8;
149        buf[4] = b'-';
150        buf[5] = b'0' + (self.month / 10);
151        buf[6] = b'0' + (self.month % 10);
152        buf[7] = b'-';
153        buf[8] = b'0' + (self.day / 10);
154        buf[9] = b'0' + (self.day % 10);
155        buf[10] = b'T';
156        buf[11] = b'0' + (self.hour / 10);
157        buf[12] = b'0' + (self.hour % 10);
158        buf[13] = b':';
159        buf[14] = b'0' + (self.minute / 10);
160        buf[15] = b'0' + (self.minute % 10);
161        buf[16] = b':';
162        buf[17] = b'0' + (self.second / 10);
163        buf[18] = b'0' + (self.second % 10);
164
165        buf
166    }
167}
168
169/// RTC driver state
170pub struct RtcDriver {
171    cmos_century_reg: u8,
172    use_binary: bool,
173    last_update_tick: AtomicU64,
174}
175
176unsafe impl Send for RtcDriver {}
177unsafe impl Sync for RtcDriver {}
178
179static RTC_DRIVER: Mutex<Option<RtcDriver>> = Mutex::new(None);
180static RTC_INITIALIZED: AtomicBool = AtomicBool::new(false);
181static RTC_LAST_TICK: AtomicU64 = AtomicU64::new(0);
182
183/// Read CMOS register
184fn cmos_read(reg: u8) -> u8 {
185    unsafe {
186        outb(CMOS_ADDR_PORT, reg | 0x80); // NMI disable
187        inb(CMOS_DATA_PORT)
188    }
189}
190
191/// Write CMOS register
192fn cmos_write(reg: u8, value: u8) {
193    unsafe {
194        outb(CMOS_ADDR_PORT, reg | 0x80); // NMI disable
195        outb(CMOS_DATA_PORT, value);
196    }
197}
198
199/// Performs the detect century register operation.
200fn detect_century_register(use_binary: bool) -> u8 {
201    if let Some(fadt) = crate::acpi::get_fadt() {
202        let reg = fadt.century;
203        if reg != 0 {
204            let raw = cmos_read(reg);
205            let val = if use_binary {
206                raw
207            } else {
208                rtc_math::bcd_to_binary(raw)
209            };
210            if (19..=21).contains(&val) {
211                return reg;
212            }
213        }
214    }
215
216    for &reg in CENTURY_REG_CANDIDATES {
217        let raw = cmos_read(reg);
218        let val = if use_binary {
219            raw
220        } else {
221            rtc_math::bcd_to_binary(raw)
222        };
223        if (19..=21).contains(&val) {
224            return reg;
225        }
226    }
227
228    0
229}
230
231/// Check if RTC update is in progress
232fn is_update_in_progress() -> bool {
233    cmos_read(CMOS_REG_STATUS_A) & STATUS_A_UIP != 0
234}
235
236/// Read time from RTC registers
237fn read_rtc_time() -> RtcDateTime {
238    #[derive(Clone, Copy, PartialEq, Eq)]
239    struct RawRtc {
240        second: u8,
241        minute: u8,
242        hour: u8,
243        weekday: u8,
244        day: u8,
245        month: u8,
246        year: u8,
247        century: u8,
248        status_b: u8,
249    }
250
251    /// Reads raw once.
252    fn read_raw_once(century_reg: u8) -> RawRtc {
253        RawRtc {
254            second: cmos_read(CMOS_REG_SECOND),
255            minute: cmos_read(CMOS_REG_MINUTE),
256            hour: cmos_read(CMOS_REG_HOUR),
257            weekday: cmos_read(CMOS_REG_WEEKDAY),
258            day: cmos_read(CMOS_REG_DAY),
259            month: cmos_read(CMOS_REG_MONTH),
260            year: cmos_read(CMOS_REG_YEAR),
261            century: if century_reg != 0 {
262                cmos_read(century_reg)
263            } else {
264                0
265            },
266            status_b: cmos_read(CMOS_REG_STATUS_B),
267        }
268    }
269
270    let (century_reg, default_binary) = {
271        let driver = RTC_DRIVER.lock();
272        if let Some(ref drv) = *driver {
273            (drv.cmos_century_reg, drv.use_binary)
274        } else {
275            (0, false)
276        }
277    };
278
279    let mut raw = loop {
280        while is_update_in_progress() {
281            core::hint::spin_loop();
282        }
283        let a = read_raw_once(century_reg);
284        while is_update_in_progress() {
285            core::hint::spin_loop();
286        }
287        let b = read_raw_once(century_reg);
288        if a == b {
289            break b;
290        }
291    };
292
293    let use_binary = if raw.status_b == 0 {
294        default_binary
295    } else {
296        (raw.status_b & STATUS_B_DM) != 0
297    };
298    let pm_bit = raw.hour & 0x80;
299    if !use_binary {
300        raw.second = rtc_math::bcd_to_binary(raw.second);
301        raw.minute = rtc_math::bcd_to_binary(raw.minute);
302        raw.hour = rtc_math::bcd_to_binary(raw.hour & 0x7F);
303        raw.weekday = rtc_math::bcd_to_binary(raw.weekday);
304        raw.day = rtc_math::bcd_to_binary(raw.day);
305        raw.month = rtc_math::bcd_to_binary(raw.month);
306        raw.year = rtc_math::bcd_to_binary(raw.year);
307        if raw.century != 0 {
308            raw.century = rtc_math::bcd_to_binary(raw.century);
309        }
310    }
311
312    let is_24h = (raw.status_b & STATUS_B_24H) != 0;
313    if !is_24h {
314        let pm = pm_bit != 0;
315        raw.hour &= 0x7F;
316        if pm {
317            if raw.hour != 12 {
318                raw.hour = raw.hour.saturating_add(12);
319            }
320        } else if raw.hour == 12 {
321            raw.hour = 0;
322        }
323    }
324
325    let full_year = if raw.century != 0 {
326        (raw.century as u16) * 100 + raw.year as u16
327    } else if raw.year >= 70 {
328        1900 + raw.year as u16
329    } else {
330        2000 + raw.year as u16
331    };
332
333    RtcDateTime {
334        second: raw.second,
335        minute: raw.minute,
336        hour: raw.hour,
337        weekday: raw.weekday.saturating_sub(1),
338        day: raw.day,
339        month: raw.month,
340        year: full_year,
341        century: (full_year / 100) as u16,
342    }
343}
344
345/// Initialize RTC
346pub fn init() -> Result<(), &'static str> {
347    log::info!("[RTC] Initializing RTC...");
348
349    // Read status B to check mode
350    let status_b = cmos_read(CMOS_REG_STATUS_B);
351    let use_binary = (status_b & STATUS_B_DM) != 0;
352
353    let cmos_century_reg = detect_century_register(use_binary);
354
355    let driver = RtcDriver {
356        cmos_century_reg,
357        use_binary,
358        last_update_tick: AtomicU64::new(0),
359    };
360
361    *RTC_DRIVER.lock() = Some(driver);
362
363    // Enable update interrupt (IRQ8)
364    // This would be done in IDT setup
365    // For now, just enable the interrupt in RTC
366    let mut status_b = cmos_read(CMOS_REG_STATUS_B);
367    status_b |= STATUS_B_UIE;
368    cmos_write(CMOS_REG_STATUS_B, status_b);
369
370    // Clear any pending interrupts
371    let _ = cmos_read(CMOS_REG_STATUS_C);
372
373    RTC_INITIALIZED.store(true, Ordering::SeqCst);
374
375    let time = RtcDriver::get_time();
376    log::info!(
377        "[RTC] Initialized: {:04}-{:02}-{:02} {:02}:{:02}:{:02}",
378        time.year,
379        time.month,
380        time.day,
381        time.hour,
382        time.minute,
383        time.second
384    );
385
386    Ok(())
387}
388
389impl RtcDriver {
390    /// Get current time from RTC
391    pub fn get_time() -> RtcDateTime {
392        read_rtc_time()
393    }
394
395    /// Get Unix timestamp
396    pub fn get_timestamp() -> u64 {
397        Self::get_time().to_timestamp()
398    }
399
400    /// Get last update tick
401    pub fn last_update_tick() -> u64 {
402        RTC_LAST_TICK.load(Ordering::Relaxed)
403    }
404}
405
406/// RTC interrupt handler (IRQ8)
407pub fn rtc_interrupt_handler() {
408    // Read status C to clear interrupt
409    let _status_c = cmos_read(CMOS_REG_STATUS_C);
410
411    // Update tick counter
412    RTC_LAST_TICK.fetch_add(1, Ordering::Relaxed);
413
414    // Notify driver
415    let driver = RTC_DRIVER.lock();
416    if let Some(ref drv) = *driver {
417        drv.last_update_tick.fetch_add(1, Ordering::Relaxed);
418    }
419}
420
421/// Check if RTC is available
422pub fn is_available() -> bool {
423    RTC_INITIALIZED.load(Ordering::Relaxed)
424}
425
426/// Get current date/time
427pub fn get_datetime() -> RtcDateTime {
428    RtcDriver::get_time()
429}
430
431/// Get Unix timestamp
432pub fn get_timestamp() -> u64 {
433    RtcDriver::get_timestamp()
434}
435
436/// Set periodic interrupt frequency
437pub fn set_periodic_frequency(freq_hz: u16) {
438    // Rate is encoded as: rate = 32768 / (2^(rate-1))
439    // Valid rates: 6-15 (1024 Hz to 1 Hz)
440    let rate = match freq_hz {
441        1024 => RTC_FREQ_1024,
442        256 => RTC_FREQ_256,
443        64 => RTC_FREQ_64,
444        16 => RTC_FREQ_16,
445        4 => RTC_FREQ_4,
446        1 => RTC_FREQ_1,
447        _ => {
448            log::warn!(
449                "[RTC] Unsupported periodic frequency {} Hz, falling back to 1 Hz",
450                freq_hz
451            );
452            RTC_FREQ_1
453        }
454    };
455
456    let mut status_a = cmos_read(CMOS_REG_STATUS_A);
457    status_a = (status_a & 0xF0) | (rate & 0x0F);
458    cmos_write(CMOS_REG_STATUS_A, status_a);
459}
460
461/// Enable/disable periodic interrupt
462pub fn set_periodic_interrupt(enable: bool) {
463    let mut status_b = cmos_read(CMOS_REG_STATUS_B);
464    if enable {
465        status_b |= STATUS_B_PIE;
466    } else {
467        status_b &= !STATUS_B_PIE;
468    }
469    cmos_write(CMOS_REG_STATUS_B, status_b);
470}
471
472/// Get seconds since boot (approximate, based on RTC updates)
473pub fn uptime_secs() -> u64 {
474    RTC_LAST_TICK.load(Ordering::Relaxed)
475}