strat9_kernel/rtc_math.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//! Pure calendar and BCD arithmetic shared by the RTC implementations.
24//!
25//! Two very different components need the same arithmetic: the **host** CMOS
26//! driver ([`crate::hardware::timer::rtc`]), which reads the real MC146818 and
27//! converts its registers to and from UNIX time, and the **s9vm guest RTC
28//! device model** ([`crate::s9vm::rtc`]), which does the opposite : it computes
29//! the register values a guest reads from an emulated chip. Keeping one copy of
30//! the Howard Hinnant civil-date algorithm and of the BCD conversions in a
31//! neutral, dependency-free module guarantees the two cannot disagree about
32//! leap years, month lengths or digit packing.
33//!
34//! Everything here is pure `core` code with no I/O and no state: it is
35//! host-tested through both users.
36
37/// Seconds in one day.
38pub const SECONDS_PER_DAY: u64 = 86_400;
39/// Days in one common year.
40pub const DAYS_PER_YEAR: u32 = 365;
41/// UNIX epoch day offset used by the civil-date algorithm.
42const CIVIL_EPOCH_SHIFT: i64 = 719_468;
43
44/// Number of days in `month` of `year` (Gregorian calendar).
45///
46/// `month` is `1..=12`; an out-of-range month returns 0 instead of panicking.
47pub const fn days_in_month(year: u32, month: u32) -> u32 {
48 match month {
49 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
50 4 | 6 | 9 | 11 => 30,
51 2 => {
52 if is_leap_year(year) {
53 29
54 } else {
55 28
56 }
57 }
58 _ => 0,
59 }
60}
61
62/// True if `year` is a Gregorian leap year.
63pub const fn is_leap_year(year: u32) -> bool {
64 year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
65}
66
67/// Converts a packed BCD byte to binary (`0x42 -> 42`).
68pub const fn bcd_to_binary(bcd: u8) -> u8 {
69 (bcd & 0x0F) + ((bcd >> 4) * 10)
70}
71
72/// Converts a binary value (`0..=99`) to packed BCD (`42 -> 0x42`).
73///
74/// Values above 99 are saturated at 99 so a corrupt register write can never
75/// produce a BCD byte with a non-digit nibble.
76pub const fn binary_to_bcd(value: u8) -> u8 {
77 let value = if value > 99 { 99 } else { value };
78 ((value / 10) << 4) | (value % 10)
79}
80
81/// Splits UNIX `seconds` into `(hour, minute, second)`.
82pub const fn day_time(seconds: u64) -> (u8, u8, u8) {
83 let rem = seconds % SECONDS_PER_DAY;
84 (
85 (rem / 3600) as u8,
86 ((rem / 60) % 60) as u8,
87 (rem % 60) as u8,
88 )
89}
90
91/// Day of week for `days` since 1970-01-01, `0` = Sunday .. `6` = Saturday.
92pub const fn weekday_from_days(days: u64) -> u8 {
93 // 1970-01-01 was a Thursday.
94 ((days + 4) % 7) as u8
95}
96
97/// Converts days since `1970-01-01` to a Gregorian `(year, month, day)`.
98///
99/// Howard Hinnant's `civil_from_days` algorithm, in unsigned arithmetic. The
100/// shift to a March-based year keeps the leap-day correction uniform.
101pub const fn civil_from_days(days: u64) -> (u64, u32, u32) {
102 let z = days + CIVIL_EPOCH_SHIFT as u64;
103 let era = z / 146_097;
104 let doe = z % 146_097;
105 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
106 let year = yoe + era * 400;
107 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
108 let mp = (5 * doy + 2) / 153;
109 let day = doy - (153 * mp + 2) / 5 + 1;
110 let month = if mp < 10 { mp + 3 } else { mp - 9 };
111 let year = if month <= 2 { year + 1 } else { year };
112 (year, month as u32, day as u32)
113}
114
115/// Converts UNIX `seconds` to a civil date-time.
116///
117/// Returns `(year, month, day, hour, minute, second, weekday)` where the
118/// weekday is `0` = Sunday .. `6` = Saturday, matching the host RTC driver;
119/// the guest RTC model adds one for its own `1` = Sunday register convention.
120pub const fn civil_from_unix(seconds: u64) -> (u64, u32, u32, u8, u8, u8, u8) {
121 let days = seconds / SECONDS_PER_DAY;
122 let (year, month, day) = civil_from_days(days);
123 let (hour, minute, second) = day_time(seconds);
124 (
125 year,
126 month,
127 day,
128 hour,
129 minute,
130 second,
131 weekday_from_days(days),
132 )
133}
134
135/// Converts a civil date-time to UNIX seconds.
136///
137/// The inverse of [`civil_from_unix`]; out-of-range fields are clamped to a
138/// valid date (month/day to the month's length) instead of panicking, so a
139/// caller reading a partially initialised structure cannot trap the kernel.
140pub fn unix_from_civil(year: i64, month: u32, day: u32, hour: u8, minute: u8, second: u8) -> u64 {
141 let month = month.clamp(1, 12);
142 let days_in = days_in_month(year as u32, month);
143 let day = day.clamp(1, days_in.max(1)) as i64;
144 let mut y = year;
145 let mut m = i64::from(month);
146 if m <= 2 {
147 y -= 1;
148 m += 12;
149 }
150 let days =
151 365 * y + y / 4 - y / 100 + y / 400 + (153 * (m - 3) + 2) / 5 + day - 1 - CIVIL_EPOCH_SHIFT;
152 let seconds = days * SECONDS_PER_DAY as i64
153 + i64::from(hour.min(23)) * 3600
154 + i64::from(minute.min(59)) * 60
155 + i64::from(second.min(59));
156 if seconds <= 0 {
157 0
158 } else {
159 seconds as u64
160 }
161}