xref: /DragonOS/kernel/src/time/timer.rs (revision 11f78b73e7b18ef04e05e63612f8027eda0740e7)
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     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         ProcessManager::mark_sleep(true).ok();
257         sched();
258         return Ok(MAX_TIMEOUT);
259     } else if timeout < 0 {
260         kerror!("timeout can't less than 0");
261         return Err(SystemError::EINVAL);
262     } else {
263         // 禁用中断,防止在这段期间发生调度,造成死锁
264         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
265 
266         timeout += TIMER_JIFFIES.load(Ordering::SeqCst) as i64;
267         let timer = Timer::new(
268             WakeUpHelper::new(ProcessManager::current_pcb()),
269             timeout as u64,
270         );
271         ProcessManager::mark_sleep(true).ok();
272         timer.activate();
273 
274         drop(irq_guard);
275 
276         sched();
277         let time_remaining: i64 = timeout - TIMER_JIFFIES.load(Ordering::SeqCst) as i64;
278         if time_remaining >= 0 {
279             // 被提前唤醒,返回剩余时间
280             return Ok(time_remaining);
281         } else {
282             return Ok(0);
283         }
284     }
285 }
286 
287 pub fn timer_get_first_expire() -> Result<u64, SystemError> {
288     // FIXME
289     // kdebug!("rs_timer_get_first_expire,timer_jif = {:?}", TIMER_JIFFIES);
290     for _ in 0..10 {
291         match TIMER_LIST.try_lock_irqsave() {
292             Ok(timer_list) => {
293                 // kdebug!("rs_timer_get_first_expire TIMER_LIST lock successfully");
294                 if timer_list.is_empty() {
295                     // kdebug!("timer_list is empty");
296                     return Ok(0);
297                 } else {
298                     // kdebug!("timer_list not empty");
299                     return Ok(timer_list.front().unwrap().0.lock().expire_jiffies);
300                 }
301             }
302             // 加锁失败返回啥??
303             Err(_) => continue,
304         }
305     }
306     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
307 }
308 
309 /// 更新系统时间片
310 ///
311 /// todo: 这里的实现有问题,貌似把HPET的500us当成了500个jiffies,然后update_wall_time()里面也硬编码了这个500us
312 pub fn update_timer_jiffies(add_jiffies: u64) -> u64 {
313     let prev = TIMER_JIFFIES.fetch_add(add_jiffies, Ordering::SeqCst);
314     compiler_fence(Ordering::SeqCst);
315     update_wall_time();
316 
317     compiler_fence(Ordering::SeqCst);
318     return prev + add_jiffies;
319 }
320 
321 pub fn clock() -> u64 {
322     return TIMER_JIFFIES.load(Ordering::SeqCst);
323 }
324 
325 // ====== 以下为给C提供的接口 ======
326 
327 #[no_mangle]
328 pub extern "C" fn rs_timer_init() {
329     timer_init();
330 }
331