101876902SGou Ngai #![allow(dead_code)] 2ba0d93d8SGou Ngai 3*af097f9fS黄铭涛 use core::intrinsics::unlikely; 4*af097f9fS黄铭涛 5da152319SLoGin use system_error::SystemError; 6da152319SLoGin 7da152319SLoGin use crate::driver::rtc::interface::rtc_read_time_default; 8da152319SLoGin 9*af097f9fS黄铭涛 use super::{PosixTimeSpec, NSEC_PER_SEC}; 10*af097f9fS黄铭涛 11*af097f9fS黄铭涛 // 参考:https://code.dragonos.org.cn/xref/linux-3.4.99/include/linux/time.h#110 12*af097f9fS黄铭涛 const KTIME_MAX: i64 = !(1u64 << 63) as i64; 13*af097f9fS黄铭涛 const KTIME_SEC_MAX: i64 = KTIME_MAX / NSEC_PER_SEC as i64; 1401876902SGou Ngai 1501876902SGou Ngai #[allow(non_camel_case_types)] 1601876902SGou Ngai pub type ktime_t = i64; 1701876902SGou Ngai 1801876902SGou Ngai // @brief 将ktime_t类型转换为纳秒类型 1901876902SGou Ngai #[inline] ktime_to_ns(kt: ktime_t) -> i642001876902SGou Ngaifn ktime_to_ns(kt: ktime_t) -> i64 { 21840045afSLoGin return kt; 2201876902SGou Ngai } 2301876902SGou Ngai 2401876902SGou Ngai /// @brief 从RTC获取当前时间,然后计算时间戳。 2501876902SGou Ngai /// 时间戳为从UTC+0 1970-01-01 00:00到当前UTC+0时间,所经过的纳秒数。 2601876902SGou Ngai /// 注意,由于当前未引入时区,因此本函数默认时区为UTC+8来计算 ktime_get_real() -> Result<ktime_t, SystemError>27da152319SLoGinfn ktime_get_real() -> Result<ktime_t, SystemError> { 28da152319SLoGin let rtc_time = rtc_read_time_default()?; 296fc066acSJomo let time_spec: PosixTimeSpec = rtc_time.into(); 30da152319SLoGin let r = time_spec.tv_sec * 1_000_000_000 + time_spec.tv_nsec; 31da152319SLoGin return Ok(r); 3201876902SGou Ngai } 3301876902SGou Ngai 3401876902SGou Ngai /// @brief 暴露给外部使用的接口,返回一个时间戳 3501876902SGou Ngai #[inline] ktime_get_real_ns() -> i643601876902SGou Ngaipub fn ktime_get_real_ns() -> i64 { 37da152319SLoGin let kt: ktime_t = ktime_get_real().unwrap_or(0); 3801876902SGou Ngai return ktime_to_ns(kt); 3901876902SGou Ngai } 40*af097f9fS黄铭涛 41*af097f9fS黄铭涛 // # 用于将两个ktime_t类型的变量相加 42*af097f9fS黄铭涛 // #[inline(always)] 43*af097f9fS黄铭涛 // pub(super) fn ktime_add(add1: ktime_t, add2: ktime_t) -> ktime_t { 44*af097f9fS黄铭涛 // let res = add1 + add2; 45*af097f9fS黄铭涛 // } 46*af097f9fS黄铭涛 47*af097f9fS黄铭涛 /// # 通过sec和nsec构造一个ktime_t 48*af097f9fS黄铭涛 #[inline(always)] ktime_set(secs: i64, nsecs: u64) -> ktime_t49*af097f9fS黄铭涛fn ktime_set(secs: i64, nsecs: u64) -> ktime_t { 50*af097f9fS黄铭涛 if unlikely(secs >= KTIME_SEC_MAX) { 51*af097f9fS黄铭涛 return KTIME_MAX; 52*af097f9fS黄铭涛 } 53*af097f9fS黄铭涛 54*af097f9fS黄铭涛 return secs * NSEC_PER_SEC as i64 + nsecs as i64; 55*af097f9fS黄铭涛 } 56*af097f9fS黄铭涛 57*af097f9fS黄铭涛 /// # 将PosixTimeSpec转换成ktime_t 58*af097f9fS黄铭涛 #[inline(always)] timespec_to_ktime(ts: PosixTimeSpec) -> ktime_t59*af097f9fS黄铭涛pub fn timespec_to_ktime(ts: PosixTimeSpec) -> ktime_t { 60*af097f9fS黄铭涛 return ktime_set(ts.tv_sec, ts.tv_nsec as u64); 61*af097f9fS黄铭涛 } 62