136fd0130Shoumkh use alloc::sync::Arc; 236fd0130Shoumkh use core::sync::atomic::{compiler_fence, AtomicBool, AtomicI64, Ordering}; 3*da152319SLoGin use system_error::SystemError; 436fd0130Shoumkh 536fd0130Shoumkh use crate::{ 636fd0130Shoumkh arch::CurrentIrqArch, 736fd0130Shoumkh exception::InterruptArch, 840fe15e0SLoGin kdebug, kinfo, 936fd0130Shoumkh libs::rwlock::RwLock, 105b59005fSLoGin time::{ 115b59005fSLoGin jiffies::{clocksource_default_clock, jiffies_init}, 125b59005fSLoGin timekeep::ktime_get_real_ns, 135b59005fSLoGin TimeSpec, 145b59005fSLoGin }, 1536fd0130Shoumkh }; 1636fd0130Shoumkh 1736fd0130Shoumkh use super::{ 1836fd0130Shoumkh clocksource::{clocksource_cyc2ns, Clocksource, CycleNum, HZ}, 1936fd0130Shoumkh syscall::PosixTimeval, 2036fd0130Shoumkh NSEC_PER_SEC, USEC_PER_SEC, 2136fd0130Shoumkh }; 2236fd0130Shoumkh /// NTP周期频率 2336fd0130Shoumkh pub const NTP_INTERVAL_FREQ: u64 = HZ; 2436fd0130Shoumkh /// NTP周期长度 2536fd0130Shoumkh pub const NTP_INTERVAL_LENGTH: u64 = NSEC_PER_SEC as u64 / NTP_INTERVAL_FREQ; 2636fd0130Shoumkh /// NTP转换比例 2736fd0130Shoumkh pub const NTP_SCALE_SHIFT: u32 = 32; 2836fd0130Shoumkh 2936fd0130Shoumkh /// timekeeping休眠标志,false为未休眠 3036fd0130Shoumkh pub static TIMEKEEPING_SUSPENDED: AtomicBool = AtomicBool::new(false); 3136fd0130Shoumkh /// 已经递增的微秒数 3236fd0130Shoumkh static __ADDED_USEC: AtomicI64 = AtomicI64::new(0); 3336fd0130Shoumkh /// 已经递增的秒数 3436fd0130Shoumkh static __ADDED_SEC: AtomicI64 = AtomicI64::new(0); 3536fd0130Shoumkh /// timekeeper全局变量,用于管理timekeeper模块 3636fd0130Shoumkh static mut __TIMEKEEPER: Option<Timekeeper> = None; 3736fd0130Shoumkh 3836fd0130Shoumkh #[derive(Debug)] 3936fd0130Shoumkh pub struct Timekeeper(RwLock<TimekeeperData>); 4036fd0130Shoumkh 4136fd0130Shoumkh #[allow(dead_code)] 4236fd0130Shoumkh #[derive(Debug)] 4336fd0130Shoumkh pub struct TimekeeperData { 4436fd0130Shoumkh /// 用于计时的当前时钟源。 4536fd0130Shoumkh clock: Option<Arc<dyn Clocksource>>, 4636fd0130Shoumkh /// 当前时钟源的移位值。 4736fd0130Shoumkh shift: i32, 4836fd0130Shoumkh /// 一个NTP间隔中的时钟周期数。 4936fd0130Shoumkh cycle_interval: CycleNum, 5036fd0130Shoumkh /// 一个NTP间隔中时钟移位的纳秒数。 5136fd0130Shoumkh xtime_interval: u64, 5236fd0130Shoumkh /// 5336fd0130Shoumkh xtime_remainder: i64, 5436fd0130Shoumkh /// 每个NTP间隔累积的原始纳米秒 5536fd0130Shoumkh raw_interval: i64, 5636fd0130Shoumkh /// 时钟移位纳米秒余数 5736fd0130Shoumkh xtime_nsec: u64, 5836fd0130Shoumkh /// 积累时间和ntp时间在ntp位移纳秒量上的差距 5936fd0130Shoumkh ntp_error: i64, 6036fd0130Shoumkh /// 用于转换时钟偏移纳秒和ntp偏移纳秒的偏移量 6136fd0130Shoumkh ntp_error_shift: i32, 6236fd0130Shoumkh /// NTP调整时钟乘法器 6336fd0130Shoumkh mult: u32, 6436fd0130Shoumkh raw_time: TimeSpec, 6536fd0130Shoumkh wall_to_monotonic: TimeSpec, 6636fd0130Shoumkh total_sleep_time: TimeSpec, 6736fd0130Shoumkh xtime: TimeSpec, 6836fd0130Shoumkh } 6936fd0130Shoumkh impl TimekeeperData { 7036fd0130Shoumkh pub fn new() -> Self { 7136fd0130Shoumkh Self { 7236fd0130Shoumkh clock: None, 7336fd0130Shoumkh shift: Default::default(), 7436fd0130Shoumkh cycle_interval: CycleNum(0), 7536fd0130Shoumkh xtime_interval: Default::default(), 7636fd0130Shoumkh xtime_remainder: Default::default(), 7736fd0130Shoumkh raw_interval: Default::default(), 7836fd0130Shoumkh xtime_nsec: Default::default(), 7936fd0130Shoumkh ntp_error: Default::default(), 8036fd0130Shoumkh ntp_error_shift: Default::default(), 8136fd0130Shoumkh mult: Default::default(), 8236fd0130Shoumkh xtime: TimeSpec { 8336fd0130Shoumkh tv_nsec: 0, 8436fd0130Shoumkh tv_sec: 0, 8536fd0130Shoumkh }, 8636fd0130Shoumkh wall_to_monotonic: TimeSpec { 8736fd0130Shoumkh tv_nsec: 0, 8836fd0130Shoumkh tv_sec: 0, 8936fd0130Shoumkh }, 9036fd0130Shoumkh total_sleep_time: TimeSpec { 9136fd0130Shoumkh tv_nsec: 0, 9236fd0130Shoumkh tv_sec: 0, 9336fd0130Shoumkh }, 9436fd0130Shoumkh raw_time: TimeSpec { 9536fd0130Shoumkh tv_nsec: 0, 9636fd0130Shoumkh tv_sec: 0, 9736fd0130Shoumkh }, 9836fd0130Shoumkh } 9936fd0130Shoumkh } 10036fd0130Shoumkh } 10136fd0130Shoumkh impl Timekeeper { 10236fd0130Shoumkh /// # 设置timekeeper的参数 10336fd0130Shoumkh /// 10436fd0130Shoumkh /// ## 参数 10536fd0130Shoumkh /// 10636fd0130Shoumkh /// * 'clock' - 指定的时钟实际类型。初始为ClocksourceJiffies 10736fd0130Shoumkh pub fn timekeeper_setup_internals(&self, clock: Arc<dyn Clocksource>) { 1080d6cf65aSLoGin let mut timekeeper = self.0.write_irqsave(); 10936fd0130Shoumkh // 更新clock 11036fd0130Shoumkh let mut clock_data = clock.clocksource_data(); 11136fd0130Shoumkh clock_data.watchdog_last = clock.read(); 11236fd0130Shoumkh if clock.update_clocksource_data(clock_data).is_err() { 11336fd0130Shoumkh kdebug!("timekeeper_setup_internals:update_clocksource_data run failed"); 11436fd0130Shoumkh } 11536fd0130Shoumkh timekeeper.clock.replace(clock.clone()); 11636fd0130Shoumkh 11736fd0130Shoumkh let clock_data = clock.clocksource_data(); 11836fd0130Shoumkh let mut temp = NTP_INTERVAL_LENGTH << clock_data.shift; 11936fd0130Shoumkh let ntpinterval = temp; 12036fd0130Shoumkh temp += (clock_data.mult / 2) as u64; 12136fd0130Shoumkh // do div 12236fd0130Shoumkh 12336fd0130Shoumkh timekeeper.cycle_interval = CycleNum(temp); 12436fd0130Shoumkh timekeeper.xtime_interval = temp * clock_data.mult as u64; 12540fe15e0SLoGin // 这里可能存在下界溢出问题,debug模式下会报错panic 12636fd0130Shoumkh timekeeper.xtime_remainder = (ntpinterval - timekeeper.xtime_interval) as i64; 12736fd0130Shoumkh timekeeper.raw_interval = (timekeeper.xtime_interval >> clock_data.shift) as i64; 12836fd0130Shoumkh timekeeper.xtime_nsec = 0; 12936fd0130Shoumkh timekeeper.shift = clock_data.shift as i32; 13036fd0130Shoumkh 13136fd0130Shoumkh timekeeper.ntp_error = 0; 13236fd0130Shoumkh timekeeper.ntp_error_shift = (NTP_SCALE_SHIFT - clock_data.shift) as i32; 13336fd0130Shoumkh 13436fd0130Shoumkh timekeeper.mult = clock_data.mult; 13536fd0130Shoumkh } 13636fd0130Shoumkh 13736fd0130Shoumkh /// # 获取当前时钟源距离上次检测走过的纳秒数 13836fd0130Shoumkh #[allow(dead_code)] 13936fd0130Shoumkh pub fn tk_get_ns(&self) -> u64 { 1400d6cf65aSLoGin let timekeeper = self.0.read_irqsave(); 14136fd0130Shoumkh let clock = timekeeper.clock.clone().unwrap(); 1420d6cf65aSLoGin drop(timekeeper); 14336fd0130Shoumkh let clock_now = clock.read(); 144911132c4SDonkey Kane let clock_data = clock.clocksource_data(); 145911132c4SDonkey Kane let clock_delta = clock_now.div(clock_data.watchdog_last).data() & clock_data.mask.bits(); 146911132c4SDonkey Kane // clock_shift的值错误导致时间流逝速度异常,+5为临时修改以确保系统正常运作,目前追踪到的设置在DragonOS-dev/blob/fix_time/kernel/src/time/jiffies.rs#L18,但是修改无效 147911132c4SDonkey Kane return clocksource_cyc2ns(CycleNum(clock_delta), clock_data.mult, clock_data.shift + 5); 14836fd0130Shoumkh } 14936fd0130Shoumkh } 15036fd0130Shoumkh pub fn timekeeper() -> &'static Timekeeper { 1518d94ea66SYJwu2023 let r = unsafe { __TIMEKEEPER.as_ref().unwrap() }; 1528d94ea66SYJwu2023 1538d94ea66SYJwu2023 return r; 15436fd0130Shoumkh } 15536fd0130Shoumkh 15636fd0130Shoumkh pub fn timekeeper_init() { 15736fd0130Shoumkh unsafe { __TIMEKEEPER = Some(Timekeeper(RwLock::new(TimekeeperData::new()))) }; 15836fd0130Shoumkh } 15936fd0130Shoumkh 16036fd0130Shoumkh /// # 获取1970.1.1至今的UTC时间戳(最小单位:nsec) 16136fd0130Shoumkh /// 16236fd0130Shoumkh /// ## 返回值 16336fd0130Shoumkh /// 16436fd0130Shoumkh /// * 'TimeSpec' - 时间戳 16536fd0130Shoumkh pub fn getnstimeofday() -> TimeSpec { 16640fe15e0SLoGin // kdebug!("enter getnstimeofday"); 16736fd0130Shoumkh 168911132c4SDonkey Kane let nsecs; 16936fd0130Shoumkh let mut _xtime = TimeSpec { 17036fd0130Shoumkh tv_nsec: 0, 17136fd0130Shoumkh tv_sec: 0, 17236fd0130Shoumkh }; 17336fd0130Shoumkh loop { 1740d6cf65aSLoGin match timekeeper().0.try_read_irqsave() { 17536fd0130Shoumkh None => continue, 17636fd0130Shoumkh Some(tk) => { 17736fd0130Shoumkh _xtime = tk.xtime; 17836fd0130Shoumkh drop(tk); 179911132c4SDonkey Kane nsecs = timekeeper().tk_get_ns(); 18036fd0130Shoumkh // TODO 不同架构可能需要加上不同的偏移量 18136fd0130Shoumkh break; 18236fd0130Shoumkh } 18336fd0130Shoumkh } 18436fd0130Shoumkh } 185911132c4SDonkey Kane _xtime.tv_nsec += nsecs as i64; 186911132c4SDonkey Kane // let sec = __ADDED_SEC.load(Ordering::SeqCst); 187911132c4SDonkey Kane // _xtime.tv_sec += sec; 18836fd0130Shoumkh while _xtime.tv_nsec >= NSEC_PER_SEC.into() { 18936fd0130Shoumkh _xtime.tv_nsec -= NSEC_PER_SEC as i64; 19036fd0130Shoumkh _xtime.tv_sec += 1; 19136fd0130Shoumkh } 19236fd0130Shoumkh 19336fd0130Shoumkh // TODO 将xtime和当前时间源的时间相加 19436fd0130Shoumkh 19536fd0130Shoumkh return _xtime; 19636fd0130Shoumkh } 19736fd0130Shoumkh 19836fd0130Shoumkh /// # 获取1970.1.1至今的UTC时间戳(最小单位:usec) 19936fd0130Shoumkh /// 20036fd0130Shoumkh /// ## 返回值 20136fd0130Shoumkh /// 20236fd0130Shoumkh /// * 'PosixTimeval' - 时间戳 20336fd0130Shoumkh pub fn do_gettimeofday() -> PosixTimeval { 20436fd0130Shoumkh let tp = getnstimeofday(); 20536fd0130Shoumkh return PosixTimeval { 20636fd0130Shoumkh tv_sec: tp.tv_sec, 20736fd0130Shoumkh tv_usec: (tp.tv_nsec / 1000) as i32, 20836fd0130Shoumkh }; 20936fd0130Shoumkh } 21036fd0130Shoumkh 211*da152319SLoGin pub fn do_settimeofday64(time: TimeSpec) -> Result<(), SystemError> { 212*da152319SLoGin timekeeper().0.write_irqsave().xtime = time; 213*da152319SLoGin // todo: 模仿linux,实现时间误差校准。 214*da152319SLoGin // https://code.dragonos.org.cn/xref/linux-6.6.21/kernel/time/timekeeping.c?fi=do_settimeofday64#1312 215*da152319SLoGin return Ok(()); 216*da152319SLoGin } 217*da152319SLoGin 21836fd0130Shoumkh /// # 初始化timekeeping模块 2195b59005fSLoGin #[inline(never)] 22036fd0130Shoumkh pub fn timekeeping_init() { 22140fe15e0SLoGin kinfo!("Initializing timekeeping module..."); 22236fd0130Shoumkh let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 22336fd0130Shoumkh timekeeper_init(); 22436fd0130Shoumkh 22536fd0130Shoumkh // TODO 有ntp模块后 在此初始化ntp模块 22636fd0130Shoumkh 22736fd0130Shoumkh let clock = clocksource_default_clock(); 22836fd0130Shoumkh clock 22936fd0130Shoumkh .enable() 23036fd0130Shoumkh .expect("clocksource_default_clock enable failed"); 23136fd0130Shoumkh timekeeper().timekeeper_setup_internals(clock); 23236fd0130Shoumkh // 暂时不支持其他架构平台对时间的设置 所以使用x86平台对应值初始化 2330d6cf65aSLoGin let mut timekeeper = timekeeper().0.write_irqsave(); 23436fd0130Shoumkh timekeeper.xtime.tv_nsec = ktime_get_real_ns(); 23536fd0130Shoumkh 236911132c4SDonkey Kane //参考https://elixir.bootlin.com/linux/v4.4/source/kernel/time/timekeeping.c#L1251 对wtm进行初始化 237911132c4SDonkey Kane ( 238911132c4SDonkey Kane timekeeper.wall_to_monotonic.tv_nsec, 239911132c4SDonkey Kane timekeeper.wall_to_monotonic.tv_sec, 240911132c4SDonkey Kane ) = (-timekeeper.xtime.tv_nsec, -timekeeper.xtime.tv_sec); 24136fd0130Shoumkh 24236fd0130Shoumkh __ADDED_USEC.store(0, Ordering::SeqCst); 24336fd0130Shoumkh __ADDED_SEC.store(0, Ordering::SeqCst); 24436fd0130Shoumkh 24536fd0130Shoumkh drop(irq_guard); 2465b59005fSLoGin jiffies_init(); 24740fe15e0SLoGin kinfo!("timekeeping_init successfully"); 24836fd0130Shoumkh } 24936fd0130Shoumkh 25036fd0130Shoumkh /// # 使用当前时钟源增加wall time 2510d6cf65aSLoGin pub fn update_wall_time(delta_us: i64) { 25236fd0130Shoumkh // kdebug!("enter update_wall_time, stack_use = {:}",stack_use); 25336fd0130Shoumkh compiler_fence(Ordering::SeqCst); 25436fd0130Shoumkh let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 25536fd0130Shoumkh // 如果在休眠那就不更新 25636fd0130Shoumkh if TIMEKEEPING_SUSPENDED.load(Ordering::SeqCst) { 25736fd0130Shoumkh return; 25836fd0130Shoumkh } 25936fd0130Shoumkh 26036fd0130Shoumkh // ===== 请不要删除这些注释 ===== 26136fd0130Shoumkh // let clock = timekeeper.clock.clone().unwrap(); 26236fd0130Shoumkh // let clock_data = clock.clocksource_data(); 26336fd0130Shoumkh // let offset = (clock.read().div(clock_data.watchdog_last).data()) & clock_data.mask.bits(); 26436fd0130Shoumkh 26536fd0130Shoumkh // timekeeper.xtime_nsec = (timekeeper.xtime.tv_nsec as u64) << timekeeper.shift; 26636fd0130Shoumkh // // TODO 当有ntp模块之后 需要将timekeep与ntp进行同步并检查 26736fd0130Shoumkh // timekeeper.xtime.tv_nsec = ((timekeeper.xtime_nsec as i64) >> timekeeper.shift) + 1; 26836fd0130Shoumkh // timekeeper.xtime_nsec -= (timekeeper.xtime.tv_nsec as u64) << timekeeper.shift; 26936fd0130Shoumkh 27036fd0130Shoumkh // timekeeper.xtime.tv_nsec += offset as i64; 27136fd0130Shoumkh // while unlikely(timekeeper.xtime.tv_nsec >= NSEC_PER_SEC.into()) { 27236fd0130Shoumkh // timekeeper.xtime.tv_nsec -= NSEC_PER_SEC as i64; 27336fd0130Shoumkh // timekeeper.xtime.tv_sec += 1; 27436fd0130Shoumkh // // TODO 需要处理闰秒 27536fd0130Shoumkh // } 27636fd0130Shoumkh // ================ 27736fd0130Shoumkh compiler_fence(Ordering::SeqCst); 278be8cdf4bSLoGin 2790d6cf65aSLoGin __ADDED_USEC.fetch_add(delta_us, Ordering::SeqCst); 28036fd0130Shoumkh compiler_fence(Ordering::SeqCst); 28136fd0130Shoumkh let mut retry = 10; 28236fd0130Shoumkh 28336fd0130Shoumkh let usec = __ADDED_USEC.load(Ordering::SeqCst); 28436fd0130Shoumkh if usec % USEC_PER_SEC as i64 == 0 { 28536fd0130Shoumkh compiler_fence(Ordering::SeqCst); 28636fd0130Shoumkh 28736fd0130Shoumkh __ADDED_SEC.fetch_add(1, Ordering::SeqCst); 28836fd0130Shoumkh compiler_fence(Ordering::SeqCst); 28936fd0130Shoumkh } 290be8cdf4bSLoGin // 一分钟同步一次 29136fd0130Shoumkh loop { 29236fd0130Shoumkh if (usec & !((1 << 26) - 1)) != 0 { 29336fd0130Shoumkh if __ADDED_USEC 29436fd0130Shoumkh .compare_exchange(usec, 0, Ordering::SeqCst, Ordering::SeqCst) 29536fd0130Shoumkh .is_ok() 29636fd0130Shoumkh || retry == 0 29736fd0130Shoumkh { 29836fd0130Shoumkh // 同步时间 29936fd0130Shoumkh // 我感觉这里会出问题:多个读者不退出的话,写者就无法写入 30036fd0130Shoumkh // 然后这里会超时,导致在中断返回之后,会不断的进入这个中断,最终爆栈。 301be8cdf4bSLoGin let mut timekeeper = timekeeper().0.write_irqsave(); 30236fd0130Shoumkh timekeeper.xtime.tv_nsec = ktime_get_real_ns(); 30336fd0130Shoumkh timekeeper.xtime.tv_sec = 0; 30436fd0130Shoumkh __ADDED_SEC.store(0, Ordering::SeqCst); 30536fd0130Shoumkh drop(timekeeper); 30636fd0130Shoumkh break; 30736fd0130Shoumkh } 30836fd0130Shoumkh retry -= 1; 30936fd0130Shoumkh } else { 31036fd0130Shoumkh break; 31136fd0130Shoumkh } 31236fd0130Shoumkh } 31336fd0130Shoumkh // TODO 需要检查是否更新时间源 31436fd0130Shoumkh compiler_fence(Ordering::SeqCst); 31536fd0130Shoumkh drop(irq_guard); 31636fd0130Shoumkh compiler_fence(Ordering::SeqCst); 31736fd0130Shoumkh } 31836fd0130Shoumkh // TODO timekeeping_adjust 31936fd0130Shoumkh // TODO wall_to_monotic 320