4 * @brief RTC & CMOS abstraction. Reference: MC146818A & Intel Series 500 PCH datasheet
8 * @copyright Copyright (c) 2022
12 #include <lunaix/time.h>
13 #include <klibc/string.h>
17 uint8_t regA = rtc_read_reg(RTC_REG_A | WITH_NMI_DISABLED);
18 regA = (regA & ~0x7f) | RTC_FREQUENCY_1024HZ | RTC_DIVIDER_33KHZ;
19 rtc_write_reg(RTC_REG_A | WITH_NMI_DISABLED, regA);
21 // Make sure the rtc timer is disabled by default
26 rtc_read_reg(uint8_t reg_selector)
28 io_outb(RTC_INDEX_PORT, reg_selector);
29 return io_inb(RTC_TARGET_PORT);
33 rtc_write_reg(uint8_t reg_selector, uint8_t val)
35 io_outb(RTC_INDEX_PORT, reg_selector);
36 io_outb(RTC_TARGET_PORT, val);
42 return ((bcd & 0xF0) >> 1) + ((bcd & 0xF0) >> 3) + (bcd & 0xf);
46 rtc_date_same(datetime_t* a, datetime_t* b) {
47 return a->year == b->year &&
48 a->month == b->month &&
50 a->weekday == b->weekday &&
51 a->minute == b->minute &&
52 a->second == b->second;
56 time_getdatetime(datetime_t* datetime)
62 while (rtc_read_reg(RTC_REG_A) & 0x80);
63 memcpy(¤t, datetime, sizeof(datetime_t));
65 datetime->year = rtc_read_reg(RTC_REG_YRS);
66 datetime->month = rtc_read_reg(RTC_REG_MTH);
67 datetime->day = rtc_read_reg(RTC_REG_DAY);
68 datetime->weekday = rtc_read_reg(RTC_REG_WDY);
69 datetime->hour = rtc_read_reg(RTC_REG_HRS);
70 datetime->minute = rtc_read_reg(RTC_REG_MIN);
71 datetime->second = rtc_read_reg(RTC_REG_SEC);
72 } while (!rtc_date_same(datetime, ¤t));
74 uint8_t regbv = rtc_read_reg(RTC_REG_B);
76 // Convert from bcd to binary when needed
77 if (!RTC_BIN_ENCODED(regbv)) {
78 datetime->year = bcd2dec(datetime->year);
79 datetime->month = bcd2dec(datetime->month);
80 datetime->day = bcd2dec(datetime->day);
81 datetime->hour = bcd2dec(datetime->hour);
82 datetime->minute = bcd2dec(datetime->minute);
83 datetime->second = bcd2dec(datetime->second);
88 if (!RTC_24HRS_ENCODED(regbv) && (datetime->hour >> 7)) {
89 datetime->hour = (12 + datetime->hour & 0x80);
92 datetime->year += RTC_CURRENT_CENTRY * 100;
97 uint8_t regB = rtc_read_reg(RTC_REG_B | WITH_NMI_DISABLED);
98 rtc_write_reg(RTC_REG_B | WITH_NMI_DISABLED, regB | RTC_TIMER_ON);
102 rtc_disable_timer() {
103 uint8_t regB = rtc_read_reg(RTC_REG_B | WITH_NMI_DISABLED);
104 rtc_write_reg(RTC_REG_B | WITH_NMI_DISABLED, regB & ~RTC_TIMER_ON);