fix: incorrect settings of msi registers.
[lunaix-os.git] / lunaix-os / kernel / time / clock.c
1 #include <lunaix/clock.h>
2 #include <lunaix/timer.h>
3 #include <hal/rtc.h>
4 #include <lunaix/spike.h>
5
6 static volatile time_t sys_time;
7
8 void clock_systime_counter(void* arg);
9
10 void
11 clock_init() {
12     if (!timer_context()) {
13         panick("Systimer not initialized");
14     }
15     
16     // 系统计时器每毫秒累加。
17     timer_run_ms(1, clock_systime_counter, NULL, TIMER_MODE_PERIODIC);
18 }
19
20 void clock_systime_counter(void* arg) {
21     sys_time++;
22 }
23
24 int
25 clock_datatime_eq(datetime_t* a, datetime_t* b) {
26     return a->year == b->year &&
27            a->month == b->month &&
28            a->day == b->day &&
29            a->weekday == b->weekday &&
30            a->minute == b->minute &&
31            a->second == b->second;
32 }
33
34 void
35 clock_walltime(datetime_t* datetime)
36 {
37     datetime_t current;
38     
39     do
40     {
41         while (rtc_read_reg(RTC_REG_A) & 0x80);
42         memcpy(&current, datetime, sizeof(datetime_t));
43
44         datetime->year = rtc_read_reg(RTC_REG_YRS);
45         datetime->month = rtc_read_reg(RTC_REG_MTH);
46         datetime->day = rtc_read_reg(RTC_REG_DAY);
47         datetime->weekday = rtc_read_reg(RTC_REG_WDY);
48         datetime->hour = rtc_read_reg(RTC_REG_HRS);
49         datetime->minute = rtc_read_reg(RTC_REG_MIN);
50         datetime->second = rtc_read_reg(RTC_REG_SEC);
51     } while (!clock_datatime_eq(datetime, &current));
52
53     uint8_t regbv = rtc_read_reg(RTC_REG_B);
54
55     // Convert from bcd to binary when needed
56     if (!RTC_BIN_ENCODED(regbv)) {
57         datetime->year = bcd2dec(datetime->year);
58         datetime->month = bcd2dec(datetime->month);
59         datetime->day = bcd2dec(datetime->day);
60         datetime->hour = bcd2dec(datetime->hour);
61         datetime->minute = bcd2dec(datetime->minute);
62         datetime->second = bcd2dec(datetime->second);
63     }
64
65
66     // To 24 hour format
67     if (!RTC_24HRS_ENCODED(regbv) && (datetime->hour >> 7)) {
68         datetime->hour = (12 + datetime->hour & 0x80);
69     }
70
71     datetime->year += RTC_CURRENT_CENTRY * 100;
72 }
73
74
75 time_t 
76 clock_systime() {
77     return sys_time;
78 }