1 use core::{ 2 cell::UnsafeCell, 3 ops::{Deref, DerefMut}, 4 }; 5 6 use alloc::collections::LinkedList; 7 8 use crate::{ 9 arch::{asm::current::current_pcb, sched::sched}, 10 include::bindings::bindings::{ 11 pid_t, process_control_block, process_wakeup, EBUSY, PROC_INTERRUPTIBLE, PROC_RUNNING, 12 }, 13 libs::spinlock::SpinLockGuard, 14 }; 15 16 use super::spinlock::SpinLock; 17 18 #[derive(Debug)] 19 struct MutexInner { 20 /// 当前Mutex是否已经被上锁(上锁时,为true) 21 is_locked: bool, 22 /// 等待获得这个锁的进程的链表 23 wait_list: LinkedList<&'static mut process_control_block>, 24 } 25 26 /// @brief Mutex互斥量结构体 27 /// 请注意!由于Mutex属于休眠锁,因此,如果您的代码可能在中断上下文内执行,请勿采用Mutex! 28 #[derive(Debug)] 29 pub struct Mutex<T> { 30 /// 该Mutex保护的数据 31 data: UnsafeCell<T>, 32 /// Mutex内部的信息 33 inner: SpinLock<MutexInner>, 34 } 35 36 /// @brief Mutex的守卫 37 #[derive(Debug)] 38 pub struct MutexGuard<'a, T: 'a> { 39 lock: &'a Mutex<T>, 40 } 41 42 unsafe impl<T> Sync for Mutex<T> where T: Send {} 43 44 impl<T> Mutex<T> { 45 /// @brief 初始化一个新的Mutex对象 46 #[allow(dead_code)] 47 pub const fn new(value: T) -> Self { 48 return Self { 49 data: UnsafeCell::new(value), 50 inner: SpinLock::new(MutexInner { 51 is_locked: false, 52 wait_list: LinkedList::<&'static mut process_control_block>::new(), 53 }), 54 }; 55 } 56 57 /// @brief 对Mutex加锁 58 /// @return MutexGuard<T> 返回Mutex的守卫,您可以使用这个守卫来操作被保护的数据 59 #[inline(always)] 60 #[allow(dead_code)] 61 pub fn lock(&self) -> MutexGuard<T> { 62 loop { 63 let mut inner: SpinLockGuard<MutexInner> = self.inner.lock(); 64 // 当前mutex已经上锁 65 if inner.is_locked { 66 // 检查当前进程是否处于等待队列中,如果不在,就加到等待队列内 67 if self.check_pid_in_wait_list(&inner, current_pcb().pid) == false { 68 inner.wait_list.push_back(current_pcb()); 69 } 70 71 // 加到等待唤醒的队列,然后睡眠 72 drop(inner); 73 self.__sleep(); 74 } else { 75 // 加锁成功 76 inner.is_locked = true; 77 drop(inner); 78 break; 79 } 80 } 81 82 // 加锁成功,返回一个守卫 83 return MutexGuard { lock: self }; 84 } 85 86 /// @brief 尝试对Mutex加锁。如果加锁失败,不会将当前进程加入等待队列。 87 /// @return Ok 加锁成功,返回Mutex的守卫 88 /// @return Err 如果Mutex当前已经上锁,则返回Err. 89 #[inline(always)] 90 #[allow(dead_code)] 91 pub fn try_lock(&self) -> Result<MutexGuard<T>, i32> { 92 let mut inner = self.inner.lock(); 93 94 // 如果当前mutex已经上锁,则失败 95 if inner.is_locked { 96 return Err(-(EBUSY as i32)); 97 } else { 98 // 加锁成功 99 inner.is_locked = true; 100 return Ok(MutexGuard { lock: self }); 101 } 102 } 103 104 /// @brief Mutex内部的睡眠函数 105 fn __sleep(&self) { 106 current_pcb().state &= !(PROC_RUNNING as u64); 107 current_pcb().state |= PROC_INTERRUPTIBLE as u64; 108 sched(); 109 } 110 111 /// @brief 放锁。 112 /// 113 /// 本函数只能是私有的,且只能被守卫的drop方法调用,否则将无法保证并发安全。 114 fn unlock(&self) { 115 let mut inner: SpinLockGuard<MutexInner> = self.inner.lock(); 116 // 当前mutex一定是已经加锁的状态 117 assert!(inner.is_locked); 118 // 标记mutex已经解锁 119 inner.is_locked = false; 120 if inner.wait_list.is_empty() { 121 return; 122 } 123 124 // wait_list不为空,则获取下一个要被唤醒的进程的pcb 125 let to_wakeup: &mut process_control_block = inner.wait_list.pop_front().unwrap(); 126 drop(inner); 127 128 unsafe { 129 process_wakeup(to_wakeup); 130 } 131 } 132 133 /// @brief 检查进程是否在该mutex的等待队列内 134 #[inline] 135 fn check_pid_in_wait_list(&self, inner: &MutexInner, pid: pid_t) -> bool { 136 for p in inner.wait_list.iter() { 137 if p.pid == pid { 138 // 在等待队列内 139 return true; 140 } 141 } 142 143 // 不在等待队列内 144 return false; 145 } 146 } 147 148 /// 实现Deref trait,支持通过获取MutexGuard来获取临界区数据的不可变引用 149 impl<T> Deref for MutexGuard<'_, T> { 150 type Target = T; 151 152 fn deref(&self) -> &Self::Target { 153 return unsafe { &*self.lock.data.get() }; 154 } 155 } 156 157 /// 实现DerefMut trait,支持通过获取MutexGuard来获取临界区数据的可变引用 158 impl<T> DerefMut for MutexGuard<'_, T> { 159 fn deref_mut(&mut self) -> &mut Self::Target { 160 return unsafe { &mut *self.lock.data.get() }; 161 } 162 } 163 164 /// @brief 为MutexGuard实现Drop方法,那么,一旦守卫的生命周期结束,就会自动释放自旋锁,避免了忘记放锁的情况 165 impl<T> Drop for MutexGuard<'_, T> { 166 fn drop(&mut self) { 167 self.lock.unlock(); 168 } 169 } 170