xref: /DragonOS/kernel/src/exception/mod.rs (revision 4ad52e57e612a88ab09413c7ac0072db96a93632)
1 use system_error::SystemError;
2 
3 use crate::arch::CurrentIrqArch;
4 
5 pub mod init;
6 pub mod ipi;
7 pub mod softirq;
8 
9 /// 中断的架构相关的trait
10 pub trait InterruptArch: Send + Sync {
11     /// 架构相关的中断初始化
12     unsafe fn arch_irq_init() -> Result<(), SystemError>;
13     /// 使能中断
14     unsafe fn interrupt_enable();
15     /// 禁止中断
16     unsafe fn interrupt_disable();
17     /// 检查中断是否被禁止
18     fn is_irq_enabled() -> bool;
19 
20     /// 保存当前中断状态,并且禁止中断
21     unsafe fn save_and_disable_irq() -> IrqFlagsGuard;
22     unsafe fn restore_irq(flags: IrqFlags);
23 }
24 
25 #[derive(Debug, Clone, Copy)]
26 pub struct IrqFlags {
27     flags: usize,
28 }
29 
30 impl IrqFlags {
31     pub fn new(flags: usize) -> Self {
32         IrqFlags { flags }
33     }
34 
35     pub fn flags(&self) -> usize {
36         self.flags
37     }
38 }
39 
40 /// @brief 当前中断状态的保护器,当该对象被drop时,会恢复之前的中断状态
41 ///
42 /// # Example
43 ///
44 /// ```
45 /// use crate::arch::CurrentIrqArch;
46 ///
47 /// // disable irq and save irq state (这是唯一的获取IrqFlagsGuard的方法)
48 /// let guard = unsafe{CurrentIrqArch::save_and_disable_irq()};
49 ///
50 /// // do something
51 ///
52 /// // 销毁guard时,会恢复之前的中断状态
53 /// drop(guard);
54 ///
55 /// ```
56 #[derive(Debug)]
57 pub struct IrqFlagsGuard {
58     flags: IrqFlags,
59 }
60 
61 impl IrqFlagsGuard {
62     /// @brief 创建IrqFlagsGuard对象
63     ///
64     /// # Safety
65     ///
66     /// 该函数不安全,因为它不会检查flags是否是一个有效的IrqFlags对象, 而当它被drop时,会恢复flags中的中断状态
67     ///
68     /// 该函数只应被`CurrentIrqArch::save_and_disable_irq`调用
69     pub unsafe fn new(flags: IrqFlags) -> Self {
70         IrqFlagsGuard { flags }
71     }
72 }
73 impl Drop for IrqFlagsGuard {
74     fn drop(&mut self) {
75         unsafe {
76             CurrentIrqArch::restore_irq(self.flags);
77         }
78     }
79 }
80