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