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::{ 14*1496ba7bSLoGin arch::{sched::sched, CurrentIrqArch}, 1536fd0130Shoumkh exception::{ 1636fd0130Shoumkh softirq::{softirq_vectors, SoftirqNumber, SoftirqVec}, 1736fd0130Shoumkh InterruptArch, 18bacd691cSlogin }, 1940fe15e0SLoGin kdebug, kerror, kinfo, 20bacd691cSlogin libs::spinlock::SpinLock, 21*1496ba7bSLoGin 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 { 43*1496ba7bSLoGin pcb: Arc<ProcessControlBlock>, 44bacd691cSlogin } 45bacd691cSlogin 46bacd691cSlogin impl WakeUpHelper { 47*1496ba7bSLoGin 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> { 54*1496ba7bSLoGin 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(), 75bacd691cSlogin }))); 76bacd691cSlogin 77bacd691cSlogin result.0.lock().self_ref = Arc::downgrade(&result); 78bacd691cSlogin 79bacd691cSlogin return result; 80bacd691cSlogin } 81bacd691cSlogin 82bacd691cSlogin /// @brief 将定时器插入到定时器链表中 83bacd691cSlogin pub fn activate(&self) { 84bacd691cSlogin let inner_guard = self.0.lock(); 85cde5492fSlogin let timer_list = &mut TIMER_LIST.lock(); 86cde5492fSlogin 87bacd691cSlogin // 链表为空,则直接插入 88bacd691cSlogin if timer_list.is_empty() { 89bacd691cSlogin // FIXME push_timer 90cde5492fSlogin 91bacd691cSlogin timer_list.push_back(inner_guard.self_ref.upgrade().unwrap()); 92cde5492fSlogin 93cde5492fSlogin drop(inner_guard); 94cde5492fSlogin drop(timer_list); 95cde5492fSlogin compiler_fence(Ordering::SeqCst); 96cde5492fSlogin 97bacd691cSlogin return; 98bacd691cSlogin } 99bacd691cSlogin let mut split_pos: usize = 0; 100bacd691cSlogin for (pos, elt) in timer_list.iter().enumerate() { 101bacd691cSlogin if elt.0.lock().expire_jiffies > inner_guard.expire_jiffies { 102bacd691cSlogin split_pos = pos; 103bacd691cSlogin break; 104bacd691cSlogin } 105bacd691cSlogin } 106bacd691cSlogin let mut temp_list: LinkedList<Arc<Timer>> = timer_list.split_off(split_pos); 107bacd691cSlogin timer_list.push_back(inner_guard.self_ref.upgrade().unwrap()); 108bacd691cSlogin timer_list.append(&mut temp_list); 109cde5492fSlogin drop(inner_guard); 110cde5492fSlogin drop(timer_list); 111bacd691cSlogin } 112bacd691cSlogin 113bacd691cSlogin #[inline] 114bacd691cSlogin fn run(&self) { 11536fd0130Shoumkh let r = self.0.lock().timer_func.run(); 11636fd0130Shoumkh if unlikely(r.is_err()) { 11736fd0130Shoumkh kerror!( 11836fd0130Shoumkh "Failed to run timer function: {self:?} {:?}", 11936fd0130Shoumkh r.err().unwrap() 12036fd0130Shoumkh ); 12136fd0130Shoumkh } 122bacd691cSlogin } 123bacd691cSlogin } 124bacd691cSlogin 125bacd691cSlogin /// 定时器类型 12636fd0130Shoumkh #[derive(Debug)] 127bacd691cSlogin pub struct InnerTimer { 128bacd691cSlogin /// 定时器结束时刻 129bacd691cSlogin pub expire_jiffies: u64, 130bacd691cSlogin /// 定时器需要执行的函数结构体 131bacd691cSlogin pub timer_func: Box<dyn TimerFunction>, 132bacd691cSlogin /// self_ref 133bacd691cSlogin self_ref: Weak<Timer>, 134bacd691cSlogin } 135bacd691cSlogin 136bacd691cSlogin #[derive(Debug)] 137bacd691cSlogin pub struct DoTimerSoftirq { 138bacd691cSlogin running: AtomicBool, 139bacd691cSlogin } 140bacd691cSlogin 141bacd691cSlogin impl DoTimerSoftirq { 142bacd691cSlogin pub fn new() -> Self { 143bacd691cSlogin return DoTimerSoftirq { 144bacd691cSlogin running: AtomicBool::new(false), 145bacd691cSlogin }; 146bacd691cSlogin } 147bacd691cSlogin 148bacd691cSlogin fn set_run(&self) -> bool { 149bacd691cSlogin let x = self 150bacd691cSlogin .running 151bacd691cSlogin .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed); 152bacd691cSlogin if x.is_ok() { 153bacd691cSlogin return true; 154bacd691cSlogin } else { 155bacd691cSlogin return false; 156bacd691cSlogin } 157bacd691cSlogin } 158bacd691cSlogin 159bacd691cSlogin fn clear_run(&self) { 160bacd691cSlogin self.running.store(false, Ordering::Release); 161bacd691cSlogin } 162bacd691cSlogin } 163bacd691cSlogin impl SoftirqVec for DoTimerSoftirq { 164bacd691cSlogin fn run(&self) { 165bacd691cSlogin if self.set_run() == false { 166bacd691cSlogin return; 167bacd691cSlogin } 168bacd691cSlogin // 最多只处理TIMER_RUN_CYCLE_THRESHOLD个计时器 169bacd691cSlogin for _ in 0..TIMER_RUN_CYCLE_THRESHOLD { 170bacd691cSlogin // kdebug!("DoTimerSoftirq run"); 171cde5492fSlogin let timer_list = TIMER_LIST.try_lock(); 172cde5492fSlogin if timer_list.is_err() { 173cde5492fSlogin continue; 174cde5492fSlogin } 175cde5492fSlogin let mut timer_list = timer_list.unwrap(); 176bacd691cSlogin 177bacd691cSlogin if timer_list.is_empty() { 178bacd691cSlogin break; 179bacd691cSlogin } 180bacd691cSlogin 181cde5492fSlogin let timer_list_front = timer_list.pop_front().unwrap(); 182cde5492fSlogin // kdebug!("to lock timer_list_front"); 183cde5492fSlogin let mut timer_list_front_guard = None; 184cde5492fSlogin for _ in 0..10 { 185cde5492fSlogin let x = timer_list_front.0.try_lock(); 186cde5492fSlogin if x.is_err() { 187cde5492fSlogin continue; 188bacd691cSlogin } 189cde5492fSlogin timer_list_front_guard = Some(x.unwrap()); 190cde5492fSlogin } 191cde5492fSlogin if timer_list_front_guard.is_none() { 192cde5492fSlogin continue; 193cde5492fSlogin } 194cde5492fSlogin let timer_list_front_guard = timer_list_front_guard.unwrap(); 19536fd0130Shoumkh if timer_list_front_guard.expire_jiffies > TIMER_JIFFIES.load(Ordering::SeqCst) { 196cde5492fSlogin drop(timer_list_front_guard); 197cde5492fSlogin timer_list.push_front(timer_list_front); 198cde5492fSlogin break; 199cde5492fSlogin } 200cde5492fSlogin drop(timer_list_front_guard); 201cde5492fSlogin drop(timer_list); 202cde5492fSlogin timer_list_front.run(); 203bacd691cSlogin } 204bacd691cSlogin 205bacd691cSlogin self.clear_run(); 206bacd691cSlogin } 207bacd691cSlogin } 208bacd691cSlogin 209bacd691cSlogin /// @brief 初始化timer模块 210bacd691cSlogin pub fn timer_init() { 211bacd691cSlogin // FIXME 调用register_trap 212bacd691cSlogin let do_timer_softirq = Arc::new(DoTimerSoftirq::new()); 213bacd691cSlogin softirq_vectors() 214bacd691cSlogin .register_softirq(SoftirqNumber::TIMER, do_timer_softirq) 215bacd691cSlogin .expect("Failed to register timer softirq"); 21640fe15e0SLoGin kinfo!("timer initialized successfully"); 217bacd691cSlogin } 218bacd691cSlogin 219bacd691cSlogin /// 计算接下来n毫秒对应的定时器时间片 220bacd691cSlogin pub fn next_n_ms_timer_jiffies(expire_ms: u64) -> u64 { 22136fd0130Shoumkh return TIMER_JIFFIES.load(Ordering::SeqCst) + 1000 * (expire_ms); 222bacd691cSlogin } 223bacd691cSlogin /// 计算接下来n微秒对应的定时器时间片 224bacd691cSlogin pub fn next_n_us_timer_jiffies(expire_us: u64) -> u64 { 22536fd0130Shoumkh return TIMER_JIFFIES.load(Ordering::SeqCst) + (expire_us); 226bacd691cSlogin } 227bacd691cSlogin 228bacd691cSlogin /// @brief 让pcb休眠timeout个jiffies 229bacd691cSlogin /// 230bacd691cSlogin /// @param timeout 需要休眠的时间(单位:jiffies) 231bacd691cSlogin /// 232bacd691cSlogin /// @return Ok(i64) 剩余需要休眠的时间(单位:jiffies) 233bacd691cSlogin /// 234bacd691cSlogin /// @return Err(SystemError) 错误码 235bacd691cSlogin pub fn schedule_timeout(mut timeout: i64) -> Result<i64, SystemError> { 236bacd691cSlogin // kdebug!("schedule_timeout"); 237bacd691cSlogin if timeout == MAX_TIMEOUT { 238bacd691cSlogin sched(); 239bacd691cSlogin return Ok(MAX_TIMEOUT); 240bacd691cSlogin } else if timeout < 0 { 241bacd691cSlogin kerror!("timeout can't less than 0"); 242bacd691cSlogin return Err(SystemError::EINVAL); 243bacd691cSlogin } else { 244bacd691cSlogin // 禁用中断,防止在这段期间发生调度,造成死锁 24536fd0130Shoumkh let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 24636fd0130Shoumkh 24736fd0130Shoumkh timeout += TIMER_JIFFIES.load(Ordering::SeqCst) as i64; 248*1496ba7bSLoGin let timer = Timer::new( 249*1496ba7bSLoGin WakeUpHelper::new(ProcessManager::current_pcb()), 250*1496ba7bSLoGin timeout as u64, 251*1496ba7bSLoGin ); 252*1496ba7bSLoGin ProcessManager::mark_sleep(true).ok(); 253bacd691cSlogin timer.activate(); 25436fd0130Shoumkh 25536fd0130Shoumkh drop(irq_guard); 256bacd691cSlogin 257bacd691cSlogin sched(); 25836fd0130Shoumkh let time_remaining: i64 = timeout - TIMER_JIFFIES.load(Ordering::SeqCst) as i64; 259bacd691cSlogin if time_remaining >= 0 { 260bacd691cSlogin // 被提前唤醒,返回剩余时间 261bacd691cSlogin return Ok(time_remaining); 262bacd691cSlogin } else { 263bacd691cSlogin return Ok(0); 264bacd691cSlogin } 265bacd691cSlogin } 266bacd691cSlogin } 267bacd691cSlogin 268bacd691cSlogin pub fn timer_get_first_expire() -> Result<u64, SystemError> { 269bacd691cSlogin // FIXME 270bacd691cSlogin // kdebug!("rs_timer_get_first_expire,timer_jif = {:?}", TIMER_JIFFIES); 271bacd691cSlogin for _ in 0..10 { 272bacd691cSlogin match TIMER_LIST.try_lock() { 273bacd691cSlogin Ok(timer_list) => { 274bacd691cSlogin // kdebug!("rs_timer_get_first_expire TIMER_LIST lock successfully"); 275bacd691cSlogin if timer_list.is_empty() { 276bacd691cSlogin // kdebug!("timer_list is empty"); 277bacd691cSlogin return Ok(0); 278bacd691cSlogin } else { 279bacd691cSlogin // kdebug!("timer_list not empty"); 280bacd691cSlogin return Ok(timer_list.front().unwrap().0.lock().expire_jiffies); 281bacd691cSlogin } 282bacd691cSlogin } 283bacd691cSlogin // 加锁失败返回啥?? 284bacd691cSlogin Err(_) => continue, 285bacd691cSlogin } 286bacd691cSlogin } 28779a452ceShoumkh return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); 288bacd691cSlogin } 289bacd691cSlogin 290bacd691cSlogin pub fn update_timer_jiffies(add_jiffies: u64) -> u64 { 29136fd0130Shoumkh let prev = TIMER_JIFFIES.fetch_add(add_jiffies, Ordering::SeqCst); 29236fd0130Shoumkh compiler_fence(Ordering::SeqCst); 29336fd0130Shoumkh update_wall_time(); 29436fd0130Shoumkh 29536fd0130Shoumkh compiler_fence(Ordering::SeqCst); 29636fd0130Shoumkh return prev + add_jiffies; 297bacd691cSlogin } 29836fd0130Shoumkh 299bacd691cSlogin pub fn clock() -> u64 { 30036fd0130Shoumkh return TIMER_JIFFIES.load(Ordering::SeqCst); 301bacd691cSlogin } 302bacd691cSlogin // ====== 重构完成后请删掉extern C ====== 303bacd691cSlogin #[no_mangle] 304bacd691cSlogin pub extern "C" fn rs_clock() -> u64 { 305bacd691cSlogin clock() 306bacd691cSlogin } 307bacd691cSlogin 308bacd691cSlogin // ====== 以下为给C提供的接口 ====== 309bacd691cSlogin #[no_mangle] 310bacd691cSlogin pub extern "C" fn rs_schedule_timeout(timeout: i64) -> i64 { 311bacd691cSlogin match schedule_timeout(timeout) { 312bacd691cSlogin Ok(v) => { 313bacd691cSlogin return v; 314bacd691cSlogin } 315bacd691cSlogin Err(e) => { 316bacd691cSlogin kdebug!("rs_schedule_timeout run failed"); 317bacd691cSlogin return e.to_posix_errno() as i64; 318bacd691cSlogin } 319bacd691cSlogin } 320bacd691cSlogin } 321bacd691cSlogin 322bacd691cSlogin #[no_mangle] 323bacd691cSlogin pub extern "C" fn rs_timer_init() { 324bacd691cSlogin timer_init(); 325bacd691cSlogin } 326bacd691cSlogin 327bacd691cSlogin #[no_mangle] 328bacd691cSlogin pub extern "C" fn rs_timer_next_n_ms_jiffies(expire_ms: u64) -> u64 { 329bacd691cSlogin return next_n_ms_timer_jiffies(expire_ms); 330bacd691cSlogin } 331bacd691cSlogin 332bacd691cSlogin #[no_mangle] 333bacd691cSlogin pub extern "C" fn rs_timer_next_n_us_jiffies(expire_us: u64) -> u64 { 334bacd691cSlogin return next_n_us_timer_jiffies(expire_us); 335bacd691cSlogin } 336bacd691cSlogin 337bacd691cSlogin #[no_mangle] 338bacd691cSlogin pub extern "C" fn rs_timer_get_first_expire() -> i64 { 339bacd691cSlogin match timer_get_first_expire() { 340bacd691cSlogin Ok(v) => return v as i64, 341cde5492fSlogin Err(_) => return 0, 342bacd691cSlogin } 343bacd691cSlogin } 344bacd691cSlogin 345bacd691cSlogin #[no_mangle] 346bacd691cSlogin pub extern "C" fn rs_update_timer_jiffies(add_jiffies: u64) -> u64 { 347bacd691cSlogin return update_timer_jiffies(add_jiffies); 348bacd691cSlogin } 349