xref: /DragonOS/kernel/src/libs/rwlock.rs (revision 3959e94df38073fdb80b199777015f95611ba05f)
1f1284c35SGou Ngai #![allow(dead_code)]
2f1284c35SGou Ngai use core::{
3f1284c35SGou Ngai     cell::UnsafeCell,
4f1284c35SGou Ngai     hint::spin_loop,
5f1284c35SGou Ngai     mem::{self, ManuallyDrop},
6f1284c35SGou Ngai     ops::{Deref, DerefMut},
7f1284c35SGou Ngai     sync::atomic::{AtomicU32, Ordering},
8f1284c35SGou Ngai };
9f1284c35SGou Ngai 
1091e9d4abSLoGin use system_error::SystemError;
1191e9d4abSLoGin 
1240fe15e0SLoGin use crate::{
131496ba7bSLoGin     arch::CurrentIrqArch,
141496ba7bSLoGin     exception::{InterruptArch, IrqFlagsGuard},
151496ba7bSLoGin     process::ProcessManager,
1640fe15e0SLoGin };
17f1284c35SGou Ngai 
18f1284c35SGou Ngai ///RwLock读写锁
19f1284c35SGou Ngai 
20f1284c35SGou Ngai /// @brief READER位占据从右往左数第三个比特位
21f1284c35SGou Ngai const READER: u32 = 1 << 2;
22f1284c35SGou Ngai 
23f1284c35SGou Ngai /// @brief UPGRADED位占据从右到左数第二个比特位
24f1284c35SGou Ngai const UPGRADED: u32 = 1 << 1;
25f1284c35SGou Ngai 
26f1284c35SGou Ngai /// @brief WRITER位占据最右边的比特位
27f1284c35SGou Ngai const WRITER: u32 = 1;
28f1284c35SGou Ngai 
29f1284c35SGou Ngai const READER_BIT: u32 = 2;
30f1284c35SGou Ngai 
31f1284c35SGou Ngai /// @brief 读写锁的基本数据结构
32f1284c35SGou Ngai /// @param lock 32位原子变量,最右边的两位从左到右分别是UPGRADED,WRITER (标志位)
33f1284c35SGou Ngai ///             剩下的bit位存储READER数量(除了MSB)
34f1284c35SGou Ngai ///             对于标志位,0代表无, 1代表有
35f1284c35SGou Ngai ///             对于剩下的比特位表征READER的数量的多少
36f1284c35SGou Ngai ///             lock的MSB必须为0,否则溢出
37f1284c35SGou Ngai #[derive(Debug)]
38f1284c35SGou Ngai pub struct RwLock<T> {
39f1284c35SGou Ngai     lock: AtomicU32,
40f1284c35SGou Ngai     data: UnsafeCell<T>,
41f1284c35SGou Ngai }
42f1284c35SGou Ngai 
43f1284c35SGou Ngai /// @brief  READER守卫的数据结构
44f1284c35SGou Ngai /// @param lock 是对RwLock的lock属性值的只读引用
45f1284c35SGou Ngai pub struct RwLockReadGuard<'a, T: 'a> {
46f1284c35SGou Ngai     data: *const T,
47f1284c35SGou Ngai     lock: &'a AtomicU32,
482f6f547aSGnoCiYeH     irq_guard: Option<IrqFlagsGuard>,
49f1284c35SGou Ngai }
50f1284c35SGou Ngai 
51f1284c35SGou Ngai /// @brief UPGRADED是介于READER和WRITER之间的一种锁,它可以升级为WRITER,
52f1284c35SGou Ngai ///        UPGRADED守卫的数据结构,注册UPGRADED锁只需要查看UPGRADED和WRITER的比特位
53f1284c35SGou Ngai ///        但是当UPGRADED守卫注册后,不允许有新的读者锁注册
54f1284c35SGou Ngai /// @param inner    是对RwLock数据结构的只读引用
55f1284c35SGou Ngai pub struct RwLockUpgradableGuard<'a, T: 'a> {
56f1284c35SGou Ngai     data: *const T,
57f1284c35SGou Ngai     inner: &'a RwLock<T>,
582f6f547aSGnoCiYeH     irq_guard: Option<IrqFlagsGuard>,
59f1284c35SGou Ngai }
60f1284c35SGou Ngai 
61f1284c35SGou Ngai /// @brief WRITER守卫的数据结构
62f1284c35SGou Ngai /// @param data     RwLock的data的可变引用
63f1284c35SGou Ngai /// @param inner    是对RwLock数据结构的只读引用
64f1284c35SGou Ngai pub struct RwLockWriteGuard<'a, T: 'a> {
65f1284c35SGou Ngai     data: *mut T,
66f1284c35SGou Ngai     inner: &'a RwLock<T>,
671496ba7bSLoGin     irq_guard: Option<IrqFlagsGuard>,
68f1284c35SGou Ngai }
69f1284c35SGou Ngai 
70f1284c35SGou Ngai unsafe impl<T: Send> Send for RwLock<T> {}
71f1284c35SGou Ngai unsafe impl<T: Send + Sync> Sync for RwLock<T> {}
72f1284c35SGou Ngai 
73f1284c35SGou Ngai /// @brief RwLock的API
74f1284c35SGou Ngai impl<T> RwLock<T> {
75f1284c35SGou Ngai     #[inline]
76f1284c35SGou Ngai     /// @brief  RwLock的初始化
77f1284c35SGou Ngai     pub const fn new(data: T) -> Self {
78f1284c35SGou Ngai         return RwLock {
79f1284c35SGou Ngai             lock: AtomicU32::new(0),
80f1284c35SGou Ngai             data: UnsafeCell::new(data),
81f1284c35SGou Ngai         };
82f1284c35SGou Ngai     }
83f1284c35SGou Ngai 
84f1284c35SGou Ngai     #[allow(dead_code)]
85f1284c35SGou Ngai     #[inline]
86f1284c35SGou Ngai     /// @brief 将读写锁的皮扒掉,返回内在的data,返回的是一个真身而非引用
87f1284c35SGou Ngai     pub fn into_inner(self) -> T {
88f1284c35SGou Ngai         let RwLock { data, .. } = self;
89f1284c35SGou Ngai         return data.into_inner();
90f1284c35SGou Ngai     }
91f1284c35SGou Ngai 
92f1284c35SGou Ngai     #[allow(dead_code)]
93f1284c35SGou Ngai     #[inline]
94f1284c35SGou Ngai     /// @brief 返回data的raw pointer,
95f1284c35SGou Ngai     /// unsafe
96f1284c35SGou Ngai     pub fn as_mut_ptr(&self) -> *mut T {
97f1284c35SGou Ngai         return self.data.get();
98f1284c35SGou Ngai     }
99f1284c35SGou Ngai 
100f1284c35SGou Ngai     #[allow(dead_code)]
101f1284c35SGou Ngai     #[inline]
102f1284c35SGou Ngai     /// @brief 获取实时的读者数并尝试加1,如果增加值成功则返回增加1后的读者数,否则panic
103676b8ef6SMork     fn current_reader(&self) -> Result<u32, SystemError> {
104f1284c35SGou Ngai         const MAX_READERS: u32 = core::u32::MAX >> READER_BIT >> 1; //右移3位
105f1284c35SGou Ngai 
106f1284c35SGou Ngai         let value = self.lock.fetch_add(READER, Ordering::Acquire);
107f1284c35SGou Ngai         //value二进制形式的MSB不能为1, 否则导致溢出
108f1284c35SGou Ngai 
109f1284c35SGou Ngai         if value > MAX_READERS << READER_BIT {
110f1284c35SGou Ngai             self.lock.fetch_sub(READER, Ordering::Release);
111f1284c35SGou Ngai             //panic!("Too many lock readers, cannot safely proceed");
112676b8ef6SMork             return Err(SystemError::EOVERFLOW);
113f1284c35SGou Ngai         } else {
114f1284c35SGou Ngai             return Ok(value);
115f1284c35SGou Ngai         }
116f1284c35SGou Ngai     }
117f1284c35SGou Ngai 
118f1284c35SGou Ngai     #[allow(dead_code)]
119f1284c35SGou Ngai     #[inline]
120f1284c35SGou Ngai     /// @brief 尝试获取READER守卫
121f1284c35SGou Ngai     pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
1221496ba7bSLoGin         ProcessManager::preempt_disable();
12340fe15e0SLoGin         let r = self.inner_try_read();
12440fe15e0SLoGin         if r.is_none() {
1251496ba7bSLoGin             ProcessManager::preempt_enable();
12640fe15e0SLoGin         }
12740fe15e0SLoGin         return r;
12840fe15e0SLoGin     }
12940fe15e0SLoGin 
13040fe15e0SLoGin     fn inner_try_read(&self) -> Option<RwLockReadGuard<T>> {
131f1284c35SGou Ngai         let reader_value = self.current_reader();
132f1284c35SGou Ngai         //得到自增后的reader_value, 包括了尝试获得READER守卫的进程
133f1284c35SGou Ngai 
134b5b571e0SLoGin         let value = if let Ok(rv) = reader_value {
135b5b571e0SLoGin             rv
136f1284c35SGou Ngai         } else {
137b5b571e0SLoGin             return None;
138b5b571e0SLoGin         };
139f1284c35SGou Ngai 
140f1284c35SGou Ngai         //判断有没有writer和upgrader
141f1284c35SGou Ngai         //注意, 若upgrader存在,已经存在的读者继续占有锁,但新读者不允许获得锁
142f1284c35SGou Ngai         if value & (WRITER | UPGRADED) != 0 {
143f1284c35SGou Ngai             self.lock.fetch_sub(READER, Ordering::Release);
144f1284c35SGou Ngai             return None;
145f1284c35SGou Ngai         } else {
146f1284c35SGou Ngai             return Some(RwLockReadGuard {
147f1284c35SGou Ngai                 data: unsafe { &*self.data.get() },
148f1284c35SGou Ngai                 lock: &self.lock,
1492f6f547aSGnoCiYeH                 irq_guard: None,
150f1284c35SGou Ngai             });
151f1284c35SGou Ngai         }
152f1284c35SGou Ngai     }
153f1284c35SGou Ngai 
154f1284c35SGou Ngai     #[allow(dead_code)]
155f1284c35SGou Ngai     #[inline]
156f1284c35SGou Ngai     /// @brief 获得READER的守卫
157f1284c35SGou Ngai     pub fn read(&self) -> RwLockReadGuard<T> {
158f1284c35SGou Ngai         loop {
159f1284c35SGou Ngai             match self.try_read() {
160f1284c35SGou Ngai                 Some(guard) => return guard,
161f1284c35SGou Ngai                 None => spin_loop(),
162f1284c35SGou Ngai             }
163f1284c35SGou Ngai         } //忙等待
164f1284c35SGou Ngai     }
165f1284c35SGou Ngai 
1660d6cf65aSLoGin     /// 关中断并获取读者守卫
1672f6f547aSGnoCiYeH     pub fn read_irqsave(&self) -> RwLockReadGuard<T> {
1682f6f547aSGnoCiYeH         loop {
1692f6f547aSGnoCiYeH             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
1702f6f547aSGnoCiYeH             match self.try_read() {
1712f6f547aSGnoCiYeH                 Some(mut guard) => {
1722f6f547aSGnoCiYeH                     guard.irq_guard = Some(irq_guard);
1732f6f547aSGnoCiYeH                     return guard;
1742f6f547aSGnoCiYeH                 }
1752f6f547aSGnoCiYeH                 None => spin_loop(),
1762f6f547aSGnoCiYeH             }
1772f6f547aSGnoCiYeH         }
1782f6f547aSGnoCiYeH     }
1792f6f547aSGnoCiYeH 
1800d6cf65aSLoGin     /// 尝试关闭中断并获取读者守卫
1810d6cf65aSLoGin     pub fn try_read_irqsave(&self) -> Option<RwLockReadGuard<T>> {
1820d6cf65aSLoGin         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
1830d6cf65aSLoGin         if let Some(mut guard) = self.try_read() {
1840d6cf65aSLoGin             guard.irq_guard = Some(irq_guard);
1850d6cf65aSLoGin             return Some(guard);
1860d6cf65aSLoGin         } else {
1870d6cf65aSLoGin             return None;
1880d6cf65aSLoGin         }
1890d6cf65aSLoGin     }
1900d6cf65aSLoGin 
191f1284c35SGou Ngai     #[allow(dead_code)]
192f1284c35SGou Ngai     #[inline]
193f1284c35SGou Ngai     /// @brief 获取读者+UPGRADER的数量, 不能保证能否获得同步值
194f1284c35SGou Ngai     pub fn reader_count(&self) -> u32 {
195f1284c35SGou Ngai         let state = self.lock.load(Ordering::Relaxed);
196f1284c35SGou Ngai         return state / READER + (state & UPGRADED) / UPGRADED;
197f1284c35SGou Ngai     }
198f1284c35SGou Ngai 
199f1284c35SGou Ngai     #[allow(dead_code)]
200f1284c35SGou Ngai     #[inline]
201f1284c35SGou Ngai     /// @brief 获取写者数量,不能保证能否获得同步值
202f1284c35SGou Ngai     pub fn writer_count(&self) -> u32 {
203f1284c35SGou Ngai         return (self.lock.load(Ordering::Relaxed) & WRITER) / WRITER;
204f1284c35SGou Ngai     }
205f1284c35SGou Ngai 
2064fda81ceSLoGin     #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
207f1284c35SGou Ngai     #[allow(dead_code)]
208f1284c35SGou Ngai     #[inline]
209f1284c35SGou Ngai     /// @brief 尝试获得WRITER守卫
210f1284c35SGou Ngai     pub fn try_write(&self) -> Option<RwLockWriteGuard<T>> {
2111496ba7bSLoGin         ProcessManager::preempt_disable();
21240fe15e0SLoGin         let r = self.inner_try_write();
21340fe15e0SLoGin         if r.is_none() {
2141496ba7bSLoGin             ProcessManager::preempt_enable();
21540fe15e0SLoGin         }
21640fe15e0SLoGin 
21740fe15e0SLoGin         return r;
21840fe15e0SLoGin     } //当架构为arm时,有些代码需要作出调整compare_exchange=>compare_exchange_weak
21940fe15e0SLoGin 
2204fda81ceSLoGin     #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
22140fe15e0SLoGin     #[allow(dead_code)]
22252bcb59eSGnoCiYeH     #[inline]
22352bcb59eSGnoCiYeH     pub fn try_write_irqsave(&self) -> Option<RwLockWriteGuard<T>> {
22452bcb59eSGnoCiYeH         ProcessManager::preempt_disable();
22552bcb59eSGnoCiYeH         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
22652bcb59eSGnoCiYeH         let r = self.inner_try_write().map(|mut g| {
22752bcb59eSGnoCiYeH             g.irq_guard = Some(irq_guard);
22852bcb59eSGnoCiYeH             g
22952bcb59eSGnoCiYeH         });
23052bcb59eSGnoCiYeH         if r.is_none() {
23152bcb59eSGnoCiYeH             ProcessManager::preempt_enable();
23252bcb59eSGnoCiYeH         }
23352bcb59eSGnoCiYeH 
23452bcb59eSGnoCiYeH         return r;
23552bcb59eSGnoCiYeH     }
23652bcb59eSGnoCiYeH 
23752bcb59eSGnoCiYeH     #[cfg(any(target_arch = "x86_64", target_arch = "riscv64"))]
23852bcb59eSGnoCiYeH     #[allow(dead_code)]
23940fe15e0SLoGin     fn inner_try_write(&self) -> Option<RwLockWriteGuard<T>> {
240f1284c35SGou Ngai         let res: bool = self
241f1284c35SGou Ngai             .lock
2421d489963Skong             .compare_exchange(0, WRITER, Ordering::Acquire, Ordering::Relaxed)
2431d489963Skong             .is_ok();
244f1284c35SGou Ngai         //只有lock大小为0的时候能获得写者守卫
245f1284c35SGou Ngai         if res {
246f1284c35SGou Ngai             return Some(RwLockWriteGuard {
247f1284c35SGou Ngai                 data: unsafe { &mut *self.data.get() },
248f1284c35SGou Ngai                 inner: self,
2491496ba7bSLoGin                 irq_guard: None,
250f1284c35SGou Ngai             });
251f1284c35SGou Ngai         } else {
252f1284c35SGou Ngai             return None;
253f1284c35SGou Ngai         }
25440fe15e0SLoGin     }
255f1284c35SGou Ngai 
256f1284c35SGou Ngai     #[allow(dead_code)]
257f1284c35SGou Ngai     #[inline]
258f1284c35SGou Ngai     /// @brief 获得WRITER守卫
259f1284c35SGou Ngai     pub fn write(&self) -> RwLockWriteGuard<T> {
260f1284c35SGou Ngai         loop {
261f1284c35SGou Ngai             match self.try_write() {
262f1284c35SGou Ngai                 Some(guard) => return guard,
263f1284c35SGou Ngai                 None => spin_loop(),
264f1284c35SGou Ngai             }
265f1284c35SGou Ngai         }
266f1284c35SGou Ngai     }
267f1284c35SGou Ngai 
268f1284c35SGou Ngai     #[allow(dead_code)]
269f1284c35SGou Ngai     #[inline]
2701496ba7bSLoGin     /// @brief 获取WRITER守卫并关中断
2711496ba7bSLoGin     pub fn write_irqsave(&self) -> RwLockWriteGuard<T> {
2721496ba7bSLoGin         loop {
2731496ba7bSLoGin             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
2741496ba7bSLoGin             match self.try_write() {
2751496ba7bSLoGin                 Some(mut guard) => {
2761496ba7bSLoGin                     guard.irq_guard = Some(irq_guard);
2771496ba7bSLoGin                     return guard;
2781496ba7bSLoGin                 }
2791496ba7bSLoGin                 None => spin_loop(),
2801496ba7bSLoGin             }
2811496ba7bSLoGin         }
2821496ba7bSLoGin     }
2831496ba7bSLoGin 
2841496ba7bSLoGin     #[allow(dead_code)]
2851496ba7bSLoGin     #[inline]
286f1284c35SGou Ngai     /// @brief 尝试获得UPGRADER守卫
287f1284c35SGou Ngai     pub fn try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>> {
2881496ba7bSLoGin         ProcessManager::preempt_disable();
28940fe15e0SLoGin         let r = self.inner_try_upgradeable_read();
29040fe15e0SLoGin         if r.is_none() {
2911496ba7bSLoGin             ProcessManager::preempt_enable();
29240fe15e0SLoGin         }
29340fe15e0SLoGin 
29440fe15e0SLoGin         return r;
29540fe15e0SLoGin     }
29640fe15e0SLoGin 
29770a4e555SLoGin     #[allow(dead_code)]
29870a4e555SLoGin     pub fn try_upgradeable_read_irqsave(&self) -> Option<RwLockUpgradableGuard<T>> {
29970a4e555SLoGin         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
30070a4e555SLoGin         ProcessManager::preempt_disable();
30170a4e555SLoGin         let mut r = self.inner_try_upgradeable_read();
30270a4e555SLoGin         if r.is_none() {
30370a4e555SLoGin             ProcessManager::preempt_enable();
30470a4e555SLoGin         } else {
30570a4e555SLoGin             r.as_mut().unwrap().irq_guard = Some(irq_guard);
30670a4e555SLoGin         }
30770a4e555SLoGin 
30870a4e555SLoGin         return r;
30970a4e555SLoGin     }
31070a4e555SLoGin 
31140fe15e0SLoGin     fn inner_try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>> {
312f1284c35SGou Ngai         // 获得UPGRADER守卫不需要查看读者位
313f1284c35SGou Ngai         // 如果获得读者锁失败,不需要撤回fetch_or的原子操作
314f1284c35SGou Ngai         if self.lock.fetch_or(UPGRADED, Ordering::Acquire) & (WRITER | UPGRADED) == 0 {
315f1284c35SGou Ngai             return Some(RwLockUpgradableGuard {
316f1284c35SGou Ngai                 inner: self,
317f1284c35SGou Ngai                 data: unsafe { &mut *self.data.get() },
3182f6f547aSGnoCiYeH                 irq_guard: None,
319f1284c35SGou Ngai             });
320f1284c35SGou Ngai         } else {
321f1284c35SGou Ngai             return None;
322f1284c35SGou Ngai         }
323f1284c35SGou Ngai     }
324f1284c35SGou Ngai 
325f1284c35SGou Ngai     #[allow(dead_code)]
326f1284c35SGou Ngai     #[inline]
327f1284c35SGou Ngai     /// @brief 获得UPGRADER守卫
328f1284c35SGou Ngai     pub fn upgradeable_read(&self) -> RwLockUpgradableGuard<T> {
329f1284c35SGou Ngai         loop {
330f1284c35SGou Ngai             match self.try_upgradeable_read() {
331f1284c35SGou Ngai                 Some(guard) => return guard,
332f1284c35SGou Ngai                 None => spin_loop(),
333f1284c35SGou Ngai             }
334f1284c35SGou Ngai         }
335f1284c35SGou Ngai     }
336f1284c35SGou Ngai 
3372f6f547aSGnoCiYeH     #[inline]
3382f6f547aSGnoCiYeH     /// @brief 获得UPGRADER守卫
3392f6f547aSGnoCiYeH     pub fn upgradeable_read_irqsave(&self) -> RwLockUpgradableGuard<T> {
3402f6f547aSGnoCiYeH         loop {
3412f6f547aSGnoCiYeH             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
3422f6f547aSGnoCiYeH             match self.try_upgradeable_read() {
3432f6f547aSGnoCiYeH                 Some(mut guard) => {
3442f6f547aSGnoCiYeH                     guard.irq_guard = Some(irq_guard);
3452f6f547aSGnoCiYeH                     return guard;
3462f6f547aSGnoCiYeH                 }
3472f6f547aSGnoCiYeH                 None => spin_loop(),
3482f6f547aSGnoCiYeH             }
3492f6f547aSGnoCiYeH         }
3502f6f547aSGnoCiYeH     }
3512f6f547aSGnoCiYeH 
352f1284c35SGou Ngai     #[allow(dead_code)]
353f1284c35SGou Ngai     #[inline]
354f1284c35SGou Ngai     //extremely unsafe behavior
355f1284c35SGou Ngai     /// @brief 强制减少READER数
356f1284c35SGou Ngai     pub unsafe fn force_read_decrement(&self) {
357f1284c35SGou Ngai         debug_assert!(self.lock.load(Ordering::Relaxed) & !WRITER > 0);
358f1284c35SGou Ngai         self.lock.fetch_sub(READER, Ordering::Release);
359f1284c35SGou Ngai     }
360f1284c35SGou Ngai 
361f1284c35SGou Ngai     #[allow(dead_code)]
362f1284c35SGou Ngai     #[inline]
363f1284c35SGou Ngai     //extremely unsafe behavior
364f1284c35SGou Ngai     /// @brief 强制给WRITER解锁
365f1284c35SGou Ngai     pub unsafe fn force_write_unlock(&self) {
366f1284c35SGou Ngai         debug_assert_eq!(self.lock.load(Ordering::Relaxed) & !(WRITER | UPGRADED), 0);
367f1284c35SGou Ngai         self.lock.fetch_and(!(WRITER | UPGRADED), Ordering::Release);
368f1284c35SGou Ngai     }
369f1284c35SGou Ngai 
370f1284c35SGou Ngai     #[allow(dead_code)]
37113776c11Slogin     pub unsafe fn get_mut(&mut self) -> &mut T {
372f1284c35SGou Ngai         unsafe { &mut *self.data.get() }
373f1284c35SGou Ngai     }
374*3959e94dS曾俊 
375*3959e94dS曾俊     #[allow(dead_code)]
376*3959e94dS曾俊     pub unsafe fn force_get_ref(&self) -> &T {
377*3959e94dS曾俊         unsafe { &*self.data.get() }
378*3959e94dS曾俊     }
379f1284c35SGou Ngai }
380f1284c35SGou Ngai 
381f1284c35SGou Ngai impl<T: Default> Default for RwLock<T> {
382f1284c35SGou Ngai     fn default() -> Self {
383f1284c35SGou Ngai         Self::new(Default::default())
384f1284c35SGou Ngai     }
385f1284c35SGou Ngai }
386f1284c35SGou Ngai 
387f1284c35SGou Ngai /// @brief 由原有的值创建新的锁
388f1284c35SGou Ngai impl<T> From<T> for RwLock<T> {
389f1284c35SGou Ngai     fn from(data: T) -> Self {
390f1284c35SGou Ngai         return Self::new(data);
391f1284c35SGou Ngai     }
392f1284c35SGou Ngai }
393f1284c35SGou Ngai 
394f1284c35SGou Ngai impl<'rwlock, T> RwLockReadGuard<'rwlock, T> {
39590a0a490SLoGin     /// @brief 释放守卫,获得保护的值的不可变引用
39690a0a490SLoGin     ///
39790a0a490SLoGin     /// ## Safety
39890a0a490SLoGin     ///
39990a0a490SLoGin     /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
40090a0a490SLoGin     /// 因此必须小心的手动维护好preempt count。
40190a0a490SLoGin     ///
40290a0a490SLoGin     /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
403f1284c35SGou Ngai     #[allow(dead_code)]
404f1284c35SGou Ngai     #[inline]
40590a0a490SLoGin     pub unsafe fn leak(this: Self) -> &'rwlock T {
40690a0a490SLoGin         let this = ManuallyDrop::new(this);
40790a0a490SLoGin         return unsafe { &*this.data };
408f1284c35SGou Ngai     }
409f1284c35SGou Ngai }
410f1284c35SGou Ngai 
411f1284c35SGou Ngai impl<'rwlock, T> RwLockUpgradableGuard<'rwlock, T> {
412f1284c35SGou Ngai     #[allow(dead_code)]
413f1284c35SGou Ngai     #[inline]
414f1284c35SGou Ngai     /// @brief 尝试将UPGRADER守卫升级为WRITER守卫
4152f6f547aSGnoCiYeH     pub fn try_upgrade(mut self) -> Result<RwLockWriteGuard<'rwlock, T>, Self> {
416f1284c35SGou Ngai         let res = self.inner.lock.compare_exchange(
417f1284c35SGou Ngai             UPGRADED,
418f1284c35SGou Ngai             WRITER,
419f1284c35SGou Ngai             Ordering::Acquire,
420f1284c35SGou Ngai             Ordering::Relaxed,
421f1284c35SGou Ngai         );
422f1284c35SGou Ngai         //当且仅当只有UPGRADED守卫时可以升级
423f1284c35SGou Ngai 
424f1284c35SGou Ngai         if res.is_ok() {
425f1284c35SGou Ngai             let inner = self.inner;
4262f6f547aSGnoCiYeH             let irq_guard = self.irq_guard.take();
427f1284c35SGou Ngai             mem::forget(self);
428f1284c35SGou Ngai 
429f1284c35SGou Ngai             Ok(RwLockWriteGuard {
430f1284c35SGou Ngai                 data: unsafe { &mut *inner.data.get() },
431f1284c35SGou Ngai                 inner,
4322f6f547aSGnoCiYeH                 irq_guard,
433f1284c35SGou Ngai             })
434f1284c35SGou Ngai         } else {
435f1284c35SGou Ngai             Err(self)
436f1284c35SGou Ngai         }
437f1284c35SGou Ngai     }
438f1284c35SGou Ngai 
439f1284c35SGou Ngai     #[allow(dead_code)]
440f1284c35SGou Ngai     #[inline]
441f1284c35SGou Ngai     /// @brief 将upgrader升级成writer
442f1284c35SGou Ngai     pub fn upgrade(mut self) -> RwLockWriteGuard<'rwlock, T> {
443f1284c35SGou Ngai         loop {
444f1284c35SGou Ngai             self = match self.try_upgrade() {
445f1284c35SGou Ngai                 Ok(writeguard) => return writeguard,
446f1284c35SGou Ngai                 Err(former) => former,
447f1284c35SGou Ngai             };
448f1284c35SGou Ngai 
449f1284c35SGou Ngai             spin_loop();
450f1284c35SGou Ngai         }
451f1284c35SGou Ngai     }
452f1284c35SGou Ngai 
453f1284c35SGou Ngai     #[allow(dead_code)]
454f1284c35SGou Ngai     #[inline]
455f1284c35SGou Ngai     /// @brief UPGRADER降级为READER
4562f6f547aSGnoCiYeH     pub fn downgrade(mut self) -> RwLockReadGuard<'rwlock, T> {
457f1284c35SGou Ngai         while self.inner.current_reader().is_err() {
458f1284c35SGou Ngai             spin_loop();
459f1284c35SGou Ngai         }
460f1284c35SGou Ngai 
461f1284c35SGou Ngai         let inner: &RwLock<T> = self.inner;
4622f6f547aSGnoCiYeH         let irq_guard = self.irq_guard.take();
463f1284c35SGou Ngai         // 自动移去UPGRADED比特位
464f1284c35SGou Ngai         mem::drop(self);
465f1284c35SGou Ngai 
466f1284c35SGou Ngai         RwLockReadGuard {
467f1284c35SGou Ngai             data: unsafe { &*inner.data.get() },
468f1284c35SGou Ngai             lock: &inner.lock,
4692f6f547aSGnoCiYeH             irq_guard,
470f1284c35SGou Ngai         }
471f1284c35SGou Ngai     }
472f1284c35SGou Ngai 
473f1284c35SGou Ngai     #[allow(dead_code)]
474f1284c35SGou Ngai     #[inline]
47590a0a490SLoGin     /// @brief 返回内部数据的引用,消除守卫
47690a0a490SLoGin     ///
47790a0a490SLoGin     /// ## Safety
47890a0a490SLoGin     ///
47990a0a490SLoGin     /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
48090a0a490SLoGin     /// 因此必须小心的手动维护好preempt count。
48190a0a490SLoGin     ///
48290a0a490SLoGin     /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
48390a0a490SLoGin     pub unsafe fn leak(this: Self) -> &'rwlock T {
48490a0a490SLoGin         let this: ManuallyDrop<RwLockUpgradableGuard<'_, T>> = ManuallyDrop::new(this);
485f1284c35SGou Ngai 
486f1284c35SGou Ngai         unsafe { &*this.data }
487f1284c35SGou Ngai     }
488f1284c35SGou Ngai }
489f1284c35SGou Ngai 
490f1284c35SGou Ngai impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> {
491f1284c35SGou Ngai     #[allow(dead_code)]
492f1284c35SGou Ngai     #[inline]
49390a0a490SLoGin     /// @brief 返回内部数据的引用,消除守卫
49490a0a490SLoGin     ///
49590a0a490SLoGin     /// ## Safety
49690a0a490SLoGin     ///
49790a0a490SLoGin     /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
49890a0a490SLoGin     /// 因此必须小心的手动维护好preempt count。
49990a0a490SLoGin     ///
50090a0a490SLoGin     /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
50190a0a490SLoGin     pub unsafe fn leak(this: Self) -> &'rwlock T {
502f1284c35SGou Ngai         let this = ManuallyDrop::new(this);
503f1284c35SGou Ngai 
504f1284c35SGou Ngai         return unsafe { &*this.data };
505f1284c35SGou Ngai     }
506f1284c35SGou Ngai 
507f1284c35SGou Ngai     #[allow(dead_code)]
508f1284c35SGou Ngai     #[inline]
509f1284c35SGou Ngai     /// @brief 将WRITER降级为READER
5102f6f547aSGnoCiYeH     pub fn downgrade(mut self) -> RwLockReadGuard<'rwlock, T> {
511f1284c35SGou Ngai         while self.inner.current_reader().is_err() {
512f1284c35SGou Ngai             spin_loop();
513f1284c35SGou Ngai         }
514f1284c35SGou Ngai         //本质上来说绝对保证没有任何读者
515f1284c35SGou Ngai 
516f1284c35SGou Ngai         let inner = self.inner;
5172f6f547aSGnoCiYeH         let irq_guard = self.irq_guard.take();
518f1284c35SGou Ngai         mem::drop(self);
519f1284c35SGou Ngai 
520f1284c35SGou Ngai         return RwLockReadGuard {
521f1284c35SGou Ngai             data: unsafe { &*inner.data.get() },
522f1284c35SGou Ngai             lock: &inner.lock,
5232f6f547aSGnoCiYeH             irq_guard,
524f1284c35SGou Ngai         };
525f1284c35SGou Ngai     }
526f1284c35SGou Ngai 
527f1284c35SGou Ngai     #[allow(dead_code)]
528f1284c35SGou Ngai     #[inline]
529f1284c35SGou Ngai     /// @brief 将WRITER降级为UPGRADER
5302f6f547aSGnoCiYeH     pub fn downgrade_to_upgradeable(mut self) -> RwLockUpgradableGuard<'rwlock, T> {
531f1284c35SGou Ngai         debug_assert_eq!(
532f1284c35SGou Ngai             self.inner.lock.load(Ordering::Acquire) & (WRITER | UPGRADED),
533f1284c35SGou Ngai             WRITER
534f1284c35SGou Ngai         );
535f1284c35SGou Ngai 
536f1284c35SGou Ngai         self.inner.lock.store(UPGRADED, Ordering::Release);
537f1284c35SGou Ngai 
538f1284c35SGou Ngai         let inner = self.inner;
539f1284c35SGou Ngai 
5402f6f547aSGnoCiYeH         let irq_guard = self.irq_guard.take();
541f1284c35SGou Ngai         mem::forget(self);
542f1284c35SGou Ngai 
543f1284c35SGou Ngai         return RwLockUpgradableGuard {
544f1284c35SGou Ngai             inner,
545f1284c35SGou Ngai             data: unsafe { &*inner.data.get() },
5462f6f547aSGnoCiYeH             irq_guard,
547f1284c35SGou Ngai         };
548f1284c35SGou Ngai     }
549f1284c35SGou Ngai }
550f1284c35SGou Ngai 
551f1284c35SGou Ngai impl<'rwlock, T> Deref for RwLockReadGuard<'rwlock, T> {
552f1284c35SGou Ngai     type Target = T;
553f1284c35SGou Ngai 
554f1284c35SGou Ngai     fn deref(&self) -> &Self::Target {
555f1284c35SGou Ngai         return unsafe { &*self.data };
556f1284c35SGou Ngai     }
557f1284c35SGou Ngai }
558f1284c35SGou Ngai 
559f1284c35SGou Ngai impl<'rwlock, T> Deref for RwLockUpgradableGuard<'rwlock, T> {
560f1284c35SGou Ngai     type Target = T;
561f1284c35SGou Ngai 
562f1284c35SGou Ngai     fn deref(&self) -> &Self::Target {
563f1284c35SGou Ngai         return unsafe { &*self.data };
564f1284c35SGou Ngai     }
565f1284c35SGou Ngai }
566f1284c35SGou Ngai 
567f1284c35SGou Ngai impl<'rwlock, T> Deref for RwLockWriteGuard<'rwlock, T> {
568f1284c35SGou Ngai     type Target = T;
569f1284c35SGou Ngai 
570f1284c35SGou Ngai     fn deref(&self) -> &Self::Target {
571f1284c35SGou Ngai         return unsafe { &*self.data };
572f1284c35SGou Ngai     }
573f1284c35SGou Ngai }
574f1284c35SGou Ngai 
575f1284c35SGou Ngai impl<'rwlock, T> DerefMut for RwLockWriteGuard<'rwlock, T> {
576f1284c35SGou Ngai     fn deref_mut(&mut self) -> &mut Self::Target {
577f1284c35SGou Ngai         return unsafe { &mut *self.data };
578f1284c35SGou Ngai     }
579f1284c35SGou Ngai }
580f1284c35SGou Ngai 
581f1284c35SGou Ngai impl<'rwlock, T> Drop for RwLockReadGuard<'rwlock, T> {
582f1284c35SGou Ngai     fn drop(&mut self) {
583f1284c35SGou Ngai         debug_assert!(self.lock.load(Ordering::Relaxed) & !(WRITER | UPGRADED) > 0);
584f1284c35SGou Ngai         self.lock.fetch_sub(READER, Ordering::Release);
5851496ba7bSLoGin         ProcessManager::preempt_enable();
586f1284c35SGou Ngai     }
587f1284c35SGou Ngai }
588f1284c35SGou Ngai 
589f1284c35SGou Ngai impl<'rwlock, T> Drop for RwLockUpgradableGuard<'rwlock, T> {
590f1284c35SGou Ngai     fn drop(&mut self) {
591f1284c35SGou Ngai         debug_assert_eq!(
592f1284c35SGou Ngai             self.inner.lock.load(Ordering::Relaxed) & (WRITER | UPGRADED),
593f1284c35SGou Ngai             UPGRADED
594f1284c35SGou Ngai         );
595f1284c35SGou Ngai         self.inner.lock.fetch_sub(UPGRADED, Ordering::AcqRel);
5961496ba7bSLoGin         ProcessManager::preempt_enable();
597f1284c35SGou Ngai         //这里为啥要AcqRel? Release应该就行了?
598f1284c35SGou Ngai     }
599f1284c35SGou Ngai }
600f1284c35SGou Ngai 
601f1284c35SGou Ngai impl<'rwlock, T> Drop for RwLockWriteGuard<'rwlock, T> {
602f1284c35SGou Ngai     fn drop(&mut self) {
603f1284c35SGou Ngai         debug_assert_eq!(self.inner.lock.load(Ordering::Relaxed) & WRITER, WRITER);
604f1284c35SGou Ngai         self.inner
605f1284c35SGou Ngai             .lock
606f1284c35SGou Ngai             .fetch_and(!(WRITER | UPGRADED), Ordering::Release);
6071496ba7bSLoGin         self.irq_guard.take();
6081496ba7bSLoGin         ProcessManager::preempt_enable();
609f1284c35SGou Ngai     }
610f1284c35SGou Ngai }
611