96 lines
1.8 KiB
C
96 lines
1.8 KiB
C
/* SPDX-License-Identifier: GPL-2.0-only */
|
|
#include <kernel/time.h>
|
|
#include <drivers/pio.h>
|
|
|
|
#include "rtc.h"
|
|
|
|
#define CMOS_INDEX 0x70
|
|
#define CMOS_DATA 0x71
|
|
|
|
static u8 cmos_read(u8 reg)
|
|
{
|
|
outb(CMOS_INDEX, reg | 0x80);
|
|
return inb(CMOS_DATA);
|
|
}
|
|
|
|
static u8 bcd_to_bin(u8 bcd)
|
|
{
|
|
return (bcd & 0x0F) + ((bcd >> 4) * 10);
|
|
}
|
|
|
|
static void wait_update()
|
|
{
|
|
u8 last = cmos_read(0x00);
|
|
while (cmos_read(0x00) == last)
|
|
;
|
|
return;
|
|
}
|
|
|
|
u64 tsc_calibrate()
|
|
{
|
|
u64 start;
|
|
u64 end;
|
|
wait_update();
|
|
start = rdtsc();
|
|
wait_update();
|
|
end = rdtsc();
|
|
return end - start;
|
|
}
|
|
|
|
time_t arch_get_real_time()
|
|
{
|
|
struct rtc_regs r;
|
|
r.sec = cmos_read(0x00);
|
|
r.min = cmos_read(0x02);
|
|
r.hour = cmos_read(0x04);
|
|
r.day = cmos_read(0x07);
|
|
r.mon = cmos_read(0x08);
|
|
r.year = cmos_read(0x09);
|
|
r.century = cmos_read(0x32);
|
|
r.reg_b = cmos_read(0x0B);
|
|
|
|
if (!(r.reg_b & 0x04)) {
|
|
/* bcd */
|
|
r.sec = bcd_to_bin(r.sec);
|
|
r.min = bcd_to_bin(r.min);
|
|
r.hour = bcd_to_bin(r.hour);
|
|
r.day = bcd_to_bin(r.day);
|
|
r.mon = bcd_to_bin(r.mon);
|
|
r.year = bcd_to_bin(r.year);
|
|
r.century = bcd_to_bin(r.century);
|
|
}
|
|
|
|
if (!(r.reg_b & 0x02)) {
|
|
/* 12 hour */
|
|
bool pm = r.hour & 0x80;
|
|
r.hour &= 0x7F;
|
|
if (pm)
|
|
r.hour += 12;
|
|
if (r.hour == 12 && !pm)
|
|
r.hour = 0;
|
|
if (r.hour == 24)
|
|
r.hour = 12;
|
|
}
|
|
|
|
if (r.century)
|
|
r.year += r.century * 100;
|
|
else
|
|
r.year += (r.year < 70) ? 2000 : 1900;
|
|
|
|
static const u8 dpm[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
|
i64 days = 0;
|
|
for (int y = 1970; y < r.year; y++)
|
|
days += 365 + ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0);
|
|
for (int m = 1; m < r.mon; m++) {
|
|
days += dpm[m - 1];
|
|
if (m == 2 && ((r.year % 4 == 0 && r.year % 100 != 0) || r.year % 400 == 0))
|
|
days += 1;
|
|
}
|
|
days += r.day - 1;
|
|
|
|
return days * 86400 + r.hour * 3600 + r.min * 60 + r.sec;
|
|
}
|
|
|
|
void rtc_init()
|
|
{
|
|
}
|