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