136fd0130Shoumkh use core::{ 236fd0130Shoumkh fmt::Debug, 336fd0130Shoumkh intrinsics::unlikely, 436fd0130Shoumkh sync::atomic::{compiler_fence, AtomicBool, AtomicU64, Ordering}, 536fd0130Shoumkh }; 6bacd691cSlogin 7bacd691cSlogin use alloc::{ 8bacd691cSlogin boxed::Box, 9bacd691cSlogin collections::LinkedList, 10bacd691cSlogin sync::{Arc, Weak}, 11bacd691cSlogin }; 12bacd691cSlogin 13bacd691cSlogin use crate::{ 141496ba7bSLoGin arch::{sched::sched, CurrentIrqArch}, 1536fd0130Shoumkh exception::{ 1636fd0130Shoumkh softirq::{softirq_vectors, SoftirqNumber, SoftirqVec}, 1736fd0130Shoumkh InterruptArch, 18bacd691cSlogin }, 1940fe15e0SLoGin kdebug, kerror, kinfo, 20bacd691cSlogin libs::spinlock::SpinLock, 211496ba7bSLoGin process::{ProcessControlBlock, ProcessManager}, 22bacd691cSlogin syscall::SystemError, 23bacd691cSlogin }; 24bacd691cSlogin 2536fd0130Shoumkh use super::timekeeping::update_wall_time; 2636fd0130Shoumkh 27bacd691cSlogin const MAX_TIMEOUT: i64 = i64::MAX; 28bacd691cSlogin const TIMER_RUN_CYCLE_THRESHOLD: usize = 20; 2936fd0130Shoumkh static TIMER_JIFFIES: AtomicU64 = AtomicU64::new(0); 30bacd691cSlogin 31bacd691cSlogin lazy_static! { 32bacd691cSlogin pub static ref TIMER_LIST: SpinLock<LinkedList<Arc<Timer>>> = SpinLock::new(LinkedList::new()); 33bacd691cSlogin } 34bacd691cSlogin 35bacd691cSlogin /// 定时器要执行的函数的特征 3636fd0130Shoumkh pub trait TimerFunction: Send + Sync + Debug { 3736fd0130Shoumkh fn run(&mut self) -> Result<(), SystemError>; 38bacd691cSlogin } 39bacd691cSlogin 4036fd0130Shoumkh #[derive(Debug)] 41bacd691cSlogin /// WakeUpHelper函数对应的结构体 42bacd691cSlogin pub struct WakeUpHelper { 431496ba7bSLoGin pcb: Arc<ProcessControlBlock>, 44bacd691cSlogin } 45bacd691cSlogin 46bacd691cSlogin impl WakeUpHelper { 471496ba7bSLoGin pub fn new(pcb: Arc<ProcessControlBlock>) -> Box<WakeUpHelper> { 48bacd691cSlogin return Box::new(WakeUpHelper { pcb }); 49bacd691cSlogin } 50bacd691cSlogin } 51bacd691cSlogin 52bacd691cSlogin impl TimerFunction for WakeUpHelper { 5336fd0130Shoumkh fn run(&mut self) -> Result<(), SystemError> { 541496ba7bSLoGin ProcessManager::wakeup(&self.pcb).ok(); 5536fd0130Shoumkh return Ok(()); 56bacd691cSlogin } 57bacd691cSlogin } 58bacd691cSlogin 5936fd0130Shoumkh #[derive(Debug)] 60bacd691cSlogin pub struct Timer(SpinLock<InnerTimer>); 61bacd691cSlogin 62bacd691cSlogin impl Timer { 63bacd691cSlogin /// @brief 创建一个定时器(单位:ms) 64bacd691cSlogin /// 65bacd691cSlogin /// @param timer_func 定时器需要执行的函数对应的结构体 66bacd691cSlogin /// 67bacd691cSlogin /// @param expire_jiffies 定时器结束时刻 68bacd691cSlogin /// 69bacd691cSlogin /// @return 定时器结构体 70bacd691cSlogin pub fn new(timer_func: Box<dyn TimerFunction>, expire_jiffies: u64) -> Arc<Self> { 71bacd691cSlogin let result: Arc<Timer> = Arc::new(Timer(SpinLock::new(InnerTimer { 72bacd691cSlogin expire_jiffies, 73bacd691cSlogin timer_func, 74bacd691cSlogin self_ref: Weak::default(), 75*971462beSGnoCiYeH triggered: false, 76bacd691cSlogin }))); 77bacd691cSlogin 78bacd691cSlogin result.0.lock().self_ref = Arc::downgrade(&result); 79bacd691cSlogin 80bacd691cSlogin return result; 81bacd691cSlogin } 82bacd691cSlogin 83bacd691cSlogin /// @brief 将定时器插入到定时器链表中 84bacd691cSlogin pub fn activate(&self) { 85bacd691cSlogin let inner_guard = self.0.lock(); 86cde5492fSlogin let timer_list = &mut TIMER_LIST.lock(); 87cde5492fSlogin 88bacd691cSlogin // 链表为空,则直接插入 89bacd691cSlogin if timer_list.is_empty() { 90bacd691cSlogin // FIXME push_timer 91cde5492fSlogin 92bacd691cSlogin timer_list.push_back(inner_guard.self_ref.upgrade().unwrap()); 93cde5492fSlogin 94cde5492fSlogin drop(inner_guard); 95cde5492fSlogin drop(timer_list); 96cde5492fSlogin compiler_fence(Ordering::SeqCst); 97cde5492fSlogin 98bacd691cSlogin return; 99bacd691cSlogin } 100bacd691cSlogin let mut split_pos: usize = 0; 101bacd691cSlogin for (pos, elt) in timer_list.iter().enumerate() { 102bacd691cSlogin if elt.0.lock().expire_jiffies > inner_guard.expire_jiffies { 103bacd691cSlogin split_pos = pos; 104bacd691cSlogin break; 105bacd691cSlogin } 106bacd691cSlogin } 107bacd691cSlogin let mut temp_list: LinkedList<Arc<Timer>> = timer_list.split_off(split_pos); 108bacd691cSlogin timer_list.push_back(inner_guard.self_ref.upgrade().unwrap()); 109bacd691cSlogin timer_list.append(&mut temp_list); 110cde5492fSlogin drop(inner_guard); 111cde5492fSlogin drop(timer_list); 112bacd691cSlogin } 113bacd691cSlogin 114bacd691cSlogin #[inline] 115bacd691cSlogin fn run(&self) { 116*971462beSGnoCiYeH let mut timer = self.0.lock(); 117*971462beSGnoCiYeH timer.triggered = true; 118*971462beSGnoCiYeH let r = timer.timer_func.run(); 11936fd0130Shoumkh if unlikely(r.is_err()) { 12036fd0130Shoumkh kerror!( 12136fd0130Shoumkh "Failed to run timer function: {self:?} {:?}", 12236fd0130Shoumkh r.err().unwrap() 12336fd0130Shoumkh ); 12436fd0130Shoumkh } 125bacd691cSlogin } 126*971462beSGnoCiYeH 127*971462beSGnoCiYeH /// ## 判断定时器是否已经触发 128*971462beSGnoCiYeH pub fn timeout(&self) -> bool { 129*971462beSGnoCiYeH self.0.lock().triggered 130*971462beSGnoCiYeH } 131*971462beSGnoCiYeH 132*971462beSGnoCiYeH /// ## 取消定时器任务 133*971462beSGnoCiYeH pub fn cancel(&self) -> bool { 134*971462beSGnoCiYeH TIMER_LIST 135*971462beSGnoCiYeH .lock() 136*971462beSGnoCiYeH .drain_filter(|x| Arc::<Timer>::as_ptr(&x) == self as *const Timer); 137*971462beSGnoCiYeH true 138*971462beSGnoCiYeH } 139bacd691cSlogin } 140bacd691cSlogin 141bacd691cSlogin /// 定时器类型 14236fd0130Shoumkh #[derive(Debug)] 143bacd691cSlogin pub struct InnerTimer { 144bacd691cSlogin /// 定时器结束时刻 145bacd691cSlogin pub expire_jiffies: u64, 146bacd691cSlogin /// 定时器需要执行的函数结构体 147bacd691cSlogin pub timer_func: Box<dyn TimerFunction>, 148bacd691cSlogin /// self_ref 149bacd691cSlogin self_ref: Weak<Timer>, 150*971462beSGnoCiYeH /// 判断该计时器是否触发 151*971462beSGnoCiYeH triggered: bool, 152bacd691cSlogin } 153bacd691cSlogin 154bacd691cSlogin #[derive(Debug)] 155bacd691cSlogin pub struct DoTimerSoftirq { 156bacd691cSlogin running: AtomicBool, 157bacd691cSlogin } 158bacd691cSlogin 159bacd691cSlogin impl DoTimerSoftirq { 160bacd691cSlogin pub fn new() -> Self { 161bacd691cSlogin return DoTimerSoftirq { 162bacd691cSlogin running: AtomicBool::new(false), 163bacd691cSlogin }; 164bacd691cSlogin } 165bacd691cSlogin 166bacd691cSlogin fn set_run(&self) -> bool { 167bacd691cSlogin let x = self 168bacd691cSlogin .running 169bacd691cSlogin .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed); 170bacd691cSlogin if x.is_ok() { 171bacd691cSlogin return true; 172bacd691cSlogin } else { 173bacd691cSlogin return false; 174bacd691cSlogin } 175bacd691cSlogin } 176bacd691cSlogin 177bacd691cSlogin fn clear_run(&self) { 178bacd691cSlogin self.running.store(false, Ordering::Release); 179bacd691cSlogin } 180bacd691cSlogin } 181bacd691cSlogin impl SoftirqVec for DoTimerSoftirq { 182bacd691cSlogin fn run(&self) { 183bacd691cSlogin if self.set_run() == false { 184bacd691cSlogin return; 185bacd691cSlogin } 186bacd691cSlogin // 最多只处理TIMER_RUN_CYCLE_THRESHOLD个计时器 187bacd691cSlogin for _ in 0..TIMER_RUN_CYCLE_THRESHOLD { 188bacd691cSlogin // kdebug!("DoTimerSoftirq run"); 189cde5492fSlogin let timer_list = TIMER_LIST.try_lock(); 190cde5492fSlogin if timer_list.is_err() { 191cde5492fSlogin continue; 192cde5492fSlogin } 193cde5492fSlogin let mut timer_list = timer_list.unwrap(); 194bacd691cSlogin 195bacd691cSlogin if timer_list.is_empty() { 196bacd691cSlogin break; 197bacd691cSlogin } 198bacd691cSlogin 199cde5492fSlogin let timer_list_front = timer_list.pop_front().unwrap(); 200cde5492fSlogin // kdebug!("to lock timer_list_front"); 201cde5492fSlogin let mut timer_list_front_guard = None; 202cde5492fSlogin for _ in 0..10 { 203cde5492fSlogin let x = timer_list_front.0.try_lock(); 204cde5492fSlogin if x.is_err() { 205cde5492fSlogin continue; 206bacd691cSlogin } 207cde5492fSlogin timer_list_front_guard = Some(x.unwrap()); 208cde5492fSlogin } 209cde5492fSlogin if timer_list_front_guard.is_none() { 210cde5492fSlogin continue; 211cde5492fSlogin } 212cde5492fSlogin let timer_list_front_guard = timer_list_front_guard.unwrap(); 21336fd0130Shoumkh if timer_list_front_guard.expire_jiffies > TIMER_JIFFIES.load(Ordering::SeqCst) { 214cde5492fSlogin drop(timer_list_front_guard); 215cde5492fSlogin timer_list.push_front(timer_list_front); 216cde5492fSlogin break; 217cde5492fSlogin } 218cde5492fSlogin drop(timer_list_front_guard); 219cde5492fSlogin drop(timer_list); 220cde5492fSlogin timer_list_front.run(); 221bacd691cSlogin } 222bacd691cSlogin 223bacd691cSlogin self.clear_run(); 224bacd691cSlogin } 225bacd691cSlogin } 226bacd691cSlogin 227bacd691cSlogin /// @brief 初始化timer模块 228bacd691cSlogin pub fn timer_init() { 229bacd691cSlogin // FIXME 调用register_trap 230bacd691cSlogin let do_timer_softirq = Arc::new(DoTimerSoftirq::new()); 231bacd691cSlogin softirq_vectors() 232bacd691cSlogin .register_softirq(SoftirqNumber::TIMER, do_timer_softirq) 233bacd691cSlogin .expect("Failed to register timer softirq"); 23440fe15e0SLoGin kinfo!("timer initialized successfully"); 235bacd691cSlogin } 236bacd691cSlogin 237bacd691cSlogin /// 计算接下来n毫秒对应的定时器时间片 238bacd691cSlogin pub fn next_n_ms_timer_jiffies(expire_ms: u64) -> u64 { 23936fd0130Shoumkh return TIMER_JIFFIES.load(Ordering::SeqCst) + 1000 * (expire_ms); 240bacd691cSlogin } 241bacd691cSlogin /// 计算接下来n微秒对应的定时器时间片 242bacd691cSlogin pub fn next_n_us_timer_jiffies(expire_us: u64) -> u64 { 24336fd0130Shoumkh return TIMER_JIFFIES.load(Ordering::SeqCst) + (expire_us); 244bacd691cSlogin } 245bacd691cSlogin 246bacd691cSlogin /// @brief 让pcb休眠timeout个jiffies 247bacd691cSlogin /// 248bacd691cSlogin /// @param timeout 需要休眠的时间(单位:jiffies) 249bacd691cSlogin /// 250bacd691cSlogin /// @return Ok(i64) 剩余需要休眠的时间(单位:jiffies) 251bacd691cSlogin /// 252bacd691cSlogin /// @return Err(SystemError) 错误码 253bacd691cSlogin pub fn schedule_timeout(mut timeout: i64) -> Result<i64, SystemError> { 254bacd691cSlogin // kdebug!("schedule_timeout"); 255bacd691cSlogin if timeout == MAX_TIMEOUT { 256bacd691cSlogin sched(); 257bacd691cSlogin return Ok(MAX_TIMEOUT); 258bacd691cSlogin } else if timeout < 0 { 259bacd691cSlogin kerror!("timeout can't less than 0"); 260bacd691cSlogin return Err(SystemError::EINVAL); 261bacd691cSlogin } else { 262bacd691cSlogin // 禁用中断,防止在这段期间发生调度,造成死锁 26336fd0130Shoumkh let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 26436fd0130Shoumkh 26536fd0130Shoumkh timeout += TIMER_JIFFIES.load(Ordering::SeqCst) as i64; 2661496ba7bSLoGin let timer = Timer::new( 2671496ba7bSLoGin WakeUpHelper::new(ProcessManager::current_pcb()), 2681496ba7bSLoGin timeout as u64, 2691496ba7bSLoGin ); 2701496ba7bSLoGin ProcessManager::mark_sleep(true).ok(); 271bacd691cSlogin timer.activate(); 27236fd0130Shoumkh 27336fd0130Shoumkh drop(irq_guard); 274bacd691cSlogin 275bacd691cSlogin sched(); 27636fd0130Shoumkh let time_remaining: i64 = timeout - TIMER_JIFFIES.load(Ordering::SeqCst) as i64; 277bacd691cSlogin if time_remaining >= 0 { 278bacd691cSlogin // 被提前唤醒,返回剩余时间 279bacd691cSlogin return Ok(time_remaining); 280bacd691cSlogin } else { 281bacd691cSlogin return Ok(0); 282bacd691cSlogin } 283bacd691cSlogin } 284bacd691cSlogin } 285bacd691cSlogin 286bacd691cSlogin pub fn timer_get_first_expire() -> Result<u64, SystemError> { 287bacd691cSlogin // FIXME 288bacd691cSlogin // kdebug!("rs_timer_get_first_expire,timer_jif = {:?}", TIMER_JIFFIES); 289bacd691cSlogin for _ in 0..10 { 290bacd691cSlogin match TIMER_LIST.try_lock() { 291bacd691cSlogin Ok(timer_list) => { 292bacd691cSlogin // kdebug!("rs_timer_get_first_expire TIMER_LIST lock successfully"); 293bacd691cSlogin if timer_list.is_empty() { 294bacd691cSlogin // kdebug!("timer_list is empty"); 295bacd691cSlogin return Ok(0); 296bacd691cSlogin } else { 297bacd691cSlogin // kdebug!("timer_list not empty"); 298bacd691cSlogin return Ok(timer_list.front().unwrap().0.lock().expire_jiffies); 299bacd691cSlogin } 300bacd691cSlogin } 301bacd691cSlogin // 加锁失败返回啥?? 302bacd691cSlogin Err(_) => continue, 303bacd691cSlogin } 304bacd691cSlogin } 30579a452ceShoumkh return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); 306bacd691cSlogin } 307bacd691cSlogin 308bacd691cSlogin pub fn update_timer_jiffies(add_jiffies: u64) -> u64 { 30936fd0130Shoumkh let prev = TIMER_JIFFIES.fetch_add(add_jiffies, Ordering::SeqCst); 31036fd0130Shoumkh compiler_fence(Ordering::SeqCst); 31136fd0130Shoumkh update_wall_time(); 31236fd0130Shoumkh 31336fd0130Shoumkh compiler_fence(Ordering::SeqCst); 31436fd0130Shoumkh return prev + add_jiffies; 315bacd691cSlogin } 31636fd0130Shoumkh 317bacd691cSlogin pub fn clock() -> u64 { 31836fd0130Shoumkh return TIMER_JIFFIES.load(Ordering::SeqCst); 319bacd691cSlogin } 320bacd691cSlogin // ====== 重构完成后请删掉extern C ====== 321bacd691cSlogin #[no_mangle] 322bacd691cSlogin pub extern "C" fn rs_clock() -> u64 { 323bacd691cSlogin clock() 324bacd691cSlogin } 325bacd691cSlogin 326bacd691cSlogin // ====== 以下为给C提供的接口 ====== 327bacd691cSlogin #[no_mangle] 328bacd691cSlogin pub extern "C" fn rs_schedule_timeout(timeout: i64) -> i64 { 329bacd691cSlogin match schedule_timeout(timeout) { 330bacd691cSlogin Ok(v) => { 331bacd691cSlogin return v; 332bacd691cSlogin } 333bacd691cSlogin Err(e) => { 334bacd691cSlogin kdebug!("rs_schedule_timeout run failed"); 335bacd691cSlogin return e.to_posix_errno() as i64; 336bacd691cSlogin } 337bacd691cSlogin } 338bacd691cSlogin } 339bacd691cSlogin 340bacd691cSlogin #[no_mangle] 341bacd691cSlogin pub extern "C" fn rs_timer_init() { 342bacd691cSlogin timer_init(); 343bacd691cSlogin } 344bacd691cSlogin 345bacd691cSlogin #[no_mangle] 346bacd691cSlogin pub extern "C" fn rs_timer_next_n_ms_jiffies(expire_ms: u64) -> u64 { 347bacd691cSlogin return next_n_ms_timer_jiffies(expire_ms); 348bacd691cSlogin } 349bacd691cSlogin 350bacd691cSlogin #[no_mangle] 351bacd691cSlogin pub extern "C" fn rs_timer_next_n_us_jiffies(expire_us: u64) -> u64 { 352bacd691cSlogin return next_n_us_timer_jiffies(expire_us); 353bacd691cSlogin } 354bacd691cSlogin 355bacd691cSlogin #[no_mangle] 356bacd691cSlogin pub extern "C" fn rs_timer_get_first_expire() -> i64 { 357bacd691cSlogin match timer_get_first_expire() { 358bacd691cSlogin Ok(v) => return v as i64, 359cde5492fSlogin Err(_) => return 0, 360bacd691cSlogin } 361bacd691cSlogin } 362bacd691cSlogin 363bacd691cSlogin #[no_mangle] 364bacd691cSlogin pub extern "C" fn rs_update_timer_jiffies(add_jiffies: u64) -> u64 { 365bacd691cSlogin return update_timer_jiffies(add_jiffies); 366bacd691cSlogin } 367