xref: /DragonOS/kernel/src/libs/spinlock.rs (revision 38b341b8aa671f75ac26d05059aa2e9a09e653b7)
1 #![allow(dead_code)]
2 use core::ptr::read_volatile;
3 
4 use crate::arch::x86_64::asm::irqflags::{local_irq_restore, local_irq_save};
5 use crate::arch::x86_64::interrupt::{cli, sti};
6 use crate::include::bindings::bindings::{spin_lock, spin_unlock, spinlock_t};
7 
8 /// @brief 保存中断状态到flags中,关闭中断,并对自旋锁加锁
9 #[inline]
10 pub fn spin_lock_irqsave(lock: *mut spinlock_t, flags: &mut u64) {
11     local_irq_save(flags);
12     unsafe {
13         spin_lock(lock);
14     }
15 }
16 
17 /// @brief 恢复rflags以及中断状态并解锁自旋锁
18 #[inline]
19 pub fn spin_unlock_irqrestore(lock: *mut spinlock_t, flags: &u64) {
20     unsafe {
21         spin_unlock(lock);
22     }
23     // kdebug!("123");
24     local_irq_restore(flags);
25 }
26 
27 /// 判断一个自旋锁是否已经被加锁
28 #[inline]
29 pub fn spin_is_locked(lock: &spinlock_t) -> bool {
30     let val = unsafe { read_volatile(&lock.lock as *const i8) };
31 
32     return if val == 0 { true } else { false };
33 }
34 
35 impl Default for spinlock_t {
36     fn default() -> Self {
37         Self { lock: 1 }
38     }
39 }
40 
41 /// @brief 关闭中断并加锁
42 pub fn spin_lock_irq(lock: *mut spinlock_t){
43     cli();
44     unsafe{spin_lock(lock);}
45 }
46 
47 /// @brief 解锁并开中断
48 pub fn spin_unlock_irq(lock: *mut spinlock_t){
49     unsafe{spin_unlock(lock);}
50     sti();
51 }