xref: /DragonOS/kernel/src/time/timekeep.rs (revision 882f0b7e7498dbff8de527b2b9159b7f6e6359c9)
1 #![allow(dead_code)]
2 
3 use crate::driver::timers::rtc::rtc::{rtc_get_cmos_time, rtc_time_t};
4 
5 #[allow(non_camel_case_types)]
6 pub type ktime_t = i64;
7 
8 // @brief 将ktime_t类型转换为纳秒类型
9 #[inline]
10 fn ktime_to_ns(kt: ktime_t) -> i64 {
11     return kt as i64;
12 }
13 
14 /// @brief 从RTC获取当前时间,然后计算时间戳。
15 /// 时间戳为从UTC+0 1970-01-01 00:00到当前UTC+0时间,所经过的纳秒数。
16 /// 注意,由于当前未引入时区,因此本函数默认时区为UTC+8来计算
17 fn ktime_get_real() -> ktime_t {
18     let mut rtc_time: rtc_time_t = rtc_time_t {
19         second: (0),
20         minute: (0),
21         hour: (0),
22         day: (0),
23         month: (0),
24         year: (0),
25     };
26 
27     //调用rtc.h里面的函数
28     rtc_get_cmos_time(&mut rtc_time);
29 
30     let mut day_count: i32 = 0;
31     for year in 1970..rtc_time.year {
32         let leap: bool = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
33         if leap {
34             day_count += 366;
35         } else {
36             day_count += 365;
37         }
38     }
39     for month in 1..rtc_time.month {
40         match month {
41             1 | 3 | 5 | 7 | 8 | 10 | 12 => day_count += 31,
42             2 => day_count += 28,
43             4 | 6 | 9 | 11 => day_count += 30,
44             _ => day_count += 0,
45         }
46     }
47 
48     day_count += rtc_time.day - 1;
49     //转换成纳秒
50     let timestamp: ktime_t = day_count as i64 * 86_400_000_000_000i64
51         + (rtc_time.hour - 8) as i64 * 3_600_000_000_000i64
52         + rtc_time.minute as i64 * 60_000_000_000i64
53         + rtc_time.second as i64 * 1_000_000_000u64 as ktime_t;
54 
55     return timestamp;
56 }
57 
58 /// @brief 暴露给外部使用的接口,返回一个时间戳
59 #[inline]
60 pub fn ktime_get_real_ns() -> i64 {
61     let kt: ktime_t = ktime_get_real();
62     return ktime_to_ns(kt);
63 }
64