xref: /DragonOS/kernel/src/time/timekeep.rs (revision c75089286e9d49cef8d039446bf570c1bd4d2550)
1 #![allow(dead_code)]
2 
3 use crate::driver::timers::rtc::rtc::RtcTime;
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: RtcTime = RtcTime::default();
19 
20     {
21         let r = rtc_time.get();
22         // 返回错误码
23         if r.is_err() {
24             return r.unwrap_err() as ktime_t;
25         }
26     }
27 
28     let mut day_count: i32 = 0;
29     for year in 1970..rtc_time.year {
30         let leap: bool = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
31         if leap {
32             day_count += 366;
33         } else {
34             day_count += 365;
35         }
36     }
37     for month in 1..rtc_time.month {
38         match month {
39             1 | 3 | 5 | 7 | 8 | 10 | 12 => day_count += 31,
40             2 => day_count += 28,
41             4 | 6 | 9 | 11 => day_count += 30,
42             _ => day_count += 0,
43         }
44     }
45 
46     day_count += rtc_time.day - 1;
47     //转换成纳秒
48     let timestamp: ktime_t = day_count as i64 * 86_400_000_000_000i64
49         + (rtc_time.hour - 8) as i64 * 3_600_000_000_000i64
50         + rtc_time.minute as i64 * 60_000_000_000i64
51         + rtc_time.second as i64 * 1_000_000_000u64 as ktime_t;
52 
53     return timestamp;
54 }
55 
56 /// @brief 暴露给外部使用的接口,返回一个时间戳
57 #[inline]
58 pub fn ktime_get_real_ns() -> i64 {
59     let kt: ktime_t = ktime_get_real();
60     return ktime_to_ns(kt);
61 }
62