os/kernel/
time.rs

1//! 时间相关功能
2
3use spin::RwLock;
4
5use crate::{device::RTC_DRIVERS, pr_info, vfs::TimeSpec};
6
7lazy_static::lazy_static! {
8    /// 墙上时钟,记录自 1970-01-01 00:00:00 UTC 以来的时间(以秒为单位)
9    /// XXX: 使用锁会不会影响精度?
10    pub static ref REALTIME: RwLock<TimeSpec> = RwLock::new(TimeSpec::zero());
11}
12
13/// 初始化时间子系统
14pub fn init() {
15    // 初始化墙上时钟为 0
16    pr_info!("Initializing REALTIME clock...");
17    let mut realtime = REALTIME.write();
18    let sec = RTC_DRIVERS
19        .read()
20        .first()
21        .map(|rtc| rtc.read_epoch() as usize)
22        .unwrap_or(0);
23    let mtime = TimeSpec::monotonic_now();
24    // 这里减去 mtime 是为简化后续的时间计算
25    let time = TimeSpec::new(sec as i64, 0) - mtime;
26    *realtime = time;
27    pr_info!(
28        "REALTIME clock initialized to {:?} seconds since epoch.",
29        time
30    );
31}
32
33/// 更新墙上时钟时间
34/// # 参数:
35/// - `time`: 新的墙上时钟时间
36pub fn update_realtime(time: &TimeSpec) {
37    let mut realtime = REALTIME.write();
38    *realtime = *time - TimeSpec::monotonic_now();
39}
40
41/// 获取当前墙上时钟时间
42pub fn realtime_now() -> TimeSpec {
43    let realtime = REALTIME.read();
44    *realtime + TimeSpec::monotonic_now()
45}