xref: /DragonOS/kernel/src/libs/rwlock.rs (revision 2f6f547ae05c19871138e558ba6943ff07f4c68c)
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 
1040fe15e0SLoGin use crate::{
111496ba7bSLoGin     arch::CurrentIrqArch,
121496ba7bSLoGin     exception::{InterruptArch, IrqFlagsGuard},
131496ba7bSLoGin     process::ProcessManager,
1440fe15e0SLoGin     syscall::SystemError,
1540fe15e0SLoGin };
16f1284c35SGou Ngai 
17f1284c35SGou Ngai ///RwLock读写锁
18f1284c35SGou Ngai 
19f1284c35SGou Ngai /// @brief READER位占据从右往左数第三个比特位
20f1284c35SGou Ngai const READER: u32 = 1 << 2;
21f1284c35SGou Ngai 
22f1284c35SGou Ngai /// @brief UPGRADED位占据从右到左数第二个比特位
23f1284c35SGou Ngai const UPGRADED: u32 = 1 << 1;
24f1284c35SGou Ngai 
25f1284c35SGou Ngai /// @brief WRITER位占据最右边的比特位
26f1284c35SGou Ngai const WRITER: u32 = 1;
27f1284c35SGou Ngai 
28f1284c35SGou Ngai const READER_BIT: u32 = 2;
29f1284c35SGou Ngai 
30f1284c35SGou Ngai /// @brief 读写锁的基本数据结构
31f1284c35SGou Ngai /// @param lock 32位原子变量,最右边的两位从左到右分别是UPGRADED,WRITER (标志位)
32f1284c35SGou Ngai ///             剩下的bit位存储READER数量(除了MSB)
33f1284c35SGou Ngai ///             对于标志位,0代表无, 1代表有
34f1284c35SGou Ngai ///             对于剩下的比特位表征READER的数量的多少
35f1284c35SGou Ngai ///             lock的MSB必须为0,否则溢出
36f1284c35SGou Ngai #[derive(Debug)]
37f1284c35SGou Ngai pub struct RwLock<T> {
38f1284c35SGou Ngai     lock: AtomicU32,
39f1284c35SGou Ngai     data: UnsafeCell<T>,
40f1284c35SGou Ngai }
41f1284c35SGou Ngai 
42f1284c35SGou Ngai /// @brief  READER守卫的数据结构
43f1284c35SGou Ngai /// @param lock 是对RwLock的lock属性值的只读引用
44f1284c35SGou Ngai pub struct RwLockReadGuard<'a, T: 'a> {
45f1284c35SGou Ngai     data: *const T,
46f1284c35SGou Ngai     lock: &'a AtomicU32,
47*2f6f547aSGnoCiYeH     irq_guard: Option<IrqFlagsGuard>,
48f1284c35SGou Ngai }
49f1284c35SGou Ngai 
50f1284c35SGou Ngai /// @brief UPGRADED是介于READER和WRITER之间的一种锁,它可以升级为WRITER,
51f1284c35SGou Ngai ///        UPGRADED守卫的数据结构,注册UPGRADED锁只需要查看UPGRADED和WRITER的比特位
52f1284c35SGou Ngai ///        但是当UPGRADED守卫注册后,不允许有新的读者锁注册
53f1284c35SGou Ngai /// @param inner    是对RwLock数据结构的只读引用
54f1284c35SGou Ngai pub struct RwLockUpgradableGuard<'a, T: 'a> {
55f1284c35SGou Ngai     data: *const T,
56f1284c35SGou Ngai     inner: &'a RwLock<T>,
57*2f6f547aSGnoCiYeH     irq_guard: Option<IrqFlagsGuard>,
58f1284c35SGou Ngai }
59f1284c35SGou Ngai 
60f1284c35SGou Ngai /// @brief WRITER守卫的数据结构
61f1284c35SGou Ngai /// @param data     RwLock的data的可变引用
62f1284c35SGou Ngai /// @param inner    是对RwLock数据结构的只读引用
63f1284c35SGou Ngai pub struct RwLockWriteGuard<'a, T: 'a> {
64f1284c35SGou Ngai     data: *mut T,
65f1284c35SGou Ngai     inner: &'a RwLock<T>,
661496ba7bSLoGin     irq_guard: Option<IrqFlagsGuard>,
67f1284c35SGou Ngai }
68f1284c35SGou Ngai 
69f1284c35SGou Ngai unsafe impl<T: Send> Send for RwLock<T> {}
70f1284c35SGou Ngai unsafe impl<T: Send + Sync> Sync for RwLock<T> {}
71f1284c35SGou Ngai 
72f1284c35SGou Ngai /// @brief RwLock的API
73f1284c35SGou Ngai impl<T> RwLock<T> {
74f1284c35SGou Ngai     #[inline]
75f1284c35SGou Ngai     /// @brief  RwLock的初始化
76f1284c35SGou Ngai     pub const fn new(data: T) -> Self {
77f1284c35SGou Ngai         return RwLock {
78f1284c35SGou Ngai             lock: AtomicU32::new(0),
79f1284c35SGou Ngai             data: UnsafeCell::new(data),
80f1284c35SGou Ngai         };
81f1284c35SGou Ngai     }
82f1284c35SGou Ngai 
83f1284c35SGou Ngai     #[allow(dead_code)]
84f1284c35SGou Ngai     #[inline]
85f1284c35SGou Ngai     /// @brief 将读写锁的皮扒掉,返回内在的data,返回的是一个真身而非引用
86f1284c35SGou Ngai     pub fn into_inner(self) -> T {
87f1284c35SGou Ngai         let RwLock { data, .. } = self;
88f1284c35SGou Ngai         return data.into_inner();
89f1284c35SGou Ngai     }
90f1284c35SGou Ngai 
91f1284c35SGou Ngai     #[allow(dead_code)]
92f1284c35SGou Ngai     #[inline]
93f1284c35SGou Ngai     /// @brief 返回data的raw pointer,
94f1284c35SGou Ngai     /// unsafe
95f1284c35SGou Ngai     pub fn as_mut_ptr(&self) -> *mut T {
96f1284c35SGou Ngai         return self.data.get();
97f1284c35SGou Ngai     }
98f1284c35SGou Ngai 
99f1284c35SGou Ngai     #[allow(dead_code)]
100f1284c35SGou Ngai     #[inline]
101f1284c35SGou Ngai     /// @brief 获取实时的读者数并尝试加1,如果增加值成功则返回增加1后的读者数,否则panic
102676b8ef6SMork     fn current_reader(&self) -> Result<u32, SystemError> {
103f1284c35SGou Ngai         const MAX_READERS: u32 = core::u32::MAX >> READER_BIT >> 1; //右移3位
104f1284c35SGou Ngai 
105f1284c35SGou Ngai         let value = self.lock.fetch_add(READER, Ordering::Acquire);
106f1284c35SGou Ngai         //value二进制形式的MSB不能为1, 否则导致溢出
107f1284c35SGou Ngai 
108f1284c35SGou Ngai         if value > MAX_READERS << READER_BIT {
109f1284c35SGou Ngai             self.lock.fetch_sub(READER, Ordering::Release);
110f1284c35SGou Ngai             //panic!("Too many lock readers, cannot safely proceed");
111676b8ef6SMork             return Err(SystemError::EOVERFLOW);
112f1284c35SGou Ngai         } else {
113f1284c35SGou Ngai             return Ok(value);
114f1284c35SGou Ngai         }
115f1284c35SGou Ngai     }
116f1284c35SGou Ngai 
117f1284c35SGou Ngai     #[allow(dead_code)]
118f1284c35SGou Ngai     #[inline]
119f1284c35SGou Ngai     /// @brief 尝试获取READER守卫
120f1284c35SGou Ngai     pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
1211496ba7bSLoGin         ProcessManager::preempt_disable();
12240fe15e0SLoGin         let r = self.inner_try_read();
12340fe15e0SLoGin         if r.is_none() {
1241496ba7bSLoGin             ProcessManager::preempt_enable();
12540fe15e0SLoGin         }
12640fe15e0SLoGin         return r;
12740fe15e0SLoGin     }
12840fe15e0SLoGin 
12940fe15e0SLoGin     fn inner_try_read(&self) -> Option<RwLockReadGuard<T>> {
130f1284c35SGou Ngai         let reader_value = self.current_reader();
131f1284c35SGou Ngai         //得到自增后的reader_value, 包括了尝试获得READER守卫的进程
132f1284c35SGou Ngai         let value;
133f1284c35SGou Ngai 
134f1284c35SGou Ngai         if reader_value.is_err() {
135f1284c35SGou Ngai             return None; //获取失败
136f1284c35SGou Ngai         } else {
137f1284c35SGou Ngai             value = reader_value.unwrap();
138f1284c35SGou Ngai         }
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,
149*2f6f547aSGnoCiYeH                 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 
166*2f6f547aSGnoCiYeH     pub fn read_irqsave(&self) -> RwLockReadGuard<T> {
167*2f6f547aSGnoCiYeH         loop {
168*2f6f547aSGnoCiYeH             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
169*2f6f547aSGnoCiYeH             match self.try_read() {
170*2f6f547aSGnoCiYeH                 Some(mut guard) => {
171*2f6f547aSGnoCiYeH                     guard.irq_guard = Some(irq_guard);
172*2f6f547aSGnoCiYeH                     return guard;
173*2f6f547aSGnoCiYeH                 }
174*2f6f547aSGnoCiYeH                 None => spin_loop(),
175*2f6f547aSGnoCiYeH             }
176*2f6f547aSGnoCiYeH         }
177*2f6f547aSGnoCiYeH     }
178*2f6f547aSGnoCiYeH 
179f1284c35SGou Ngai     #[allow(dead_code)]
180f1284c35SGou Ngai     #[inline]
181f1284c35SGou Ngai     /// @brief 获取读者+UPGRADER的数量, 不能保证能否获得同步值
182f1284c35SGou Ngai     pub fn reader_count(&self) -> u32 {
183f1284c35SGou Ngai         let state = self.lock.load(Ordering::Relaxed);
184f1284c35SGou Ngai         return state / READER + (state & UPGRADED) / UPGRADED;
185f1284c35SGou Ngai     }
186f1284c35SGou Ngai 
187f1284c35SGou Ngai     #[allow(dead_code)]
188f1284c35SGou Ngai     #[inline]
189f1284c35SGou Ngai     /// @brief 获取写者数量,不能保证能否获得同步值
190f1284c35SGou Ngai     pub fn writer_count(&self) -> u32 {
191f1284c35SGou Ngai         return (self.lock.load(Ordering::Relaxed) & WRITER) / WRITER;
192f1284c35SGou Ngai     }
193f1284c35SGou Ngai 
194f1284c35SGou Ngai     #[cfg(target_arch = "x86_64")]
195f1284c35SGou Ngai     #[allow(dead_code)]
196f1284c35SGou Ngai     #[inline]
197f1284c35SGou Ngai     /// @brief 尝试获得WRITER守卫
198f1284c35SGou Ngai     pub fn try_write(&self) -> Option<RwLockWriteGuard<T>> {
1991496ba7bSLoGin         ProcessManager::preempt_disable();
20040fe15e0SLoGin         let r = self.inner_try_write();
20140fe15e0SLoGin         if r.is_none() {
2021496ba7bSLoGin             ProcessManager::preempt_enable();
20340fe15e0SLoGin         }
20440fe15e0SLoGin 
20540fe15e0SLoGin         return r;
20640fe15e0SLoGin     } //当架构为arm时,有些代码需要作出调整compare_exchange=>compare_exchange_weak
20740fe15e0SLoGin 
20840fe15e0SLoGin     #[cfg(target_arch = "x86_64")]
20940fe15e0SLoGin     #[allow(dead_code)]
21040fe15e0SLoGin     fn inner_try_write(&self) -> Option<RwLockWriteGuard<T>> {
211f1284c35SGou Ngai         let res: bool = self
212f1284c35SGou Ngai             .lock
2131d489963Skong             .compare_exchange(0, WRITER, Ordering::Acquire, Ordering::Relaxed)
2141d489963Skong             .is_ok();
215f1284c35SGou Ngai         //只有lock大小为0的时候能获得写者守卫
216f1284c35SGou Ngai         if res {
217f1284c35SGou Ngai             return Some(RwLockWriteGuard {
218f1284c35SGou Ngai                 data: unsafe { &mut *self.data.get() },
219f1284c35SGou Ngai                 inner: self,
2201496ba7bSLoGin                 irq_guard: None,
221f1284c35SGou Ngai             });
222f1284c35SGou Ngai         } else {
223f1284c35SGou Ngai             return None;
224f1284c35SGou Ngai         }
22540fe15e0SLoGin     }
226f1284c35SGou Ngai 
227f1284c35SGou Ngai     #[allow(dead_code)]
228f1284c35SGou Ngai     #[inline]
229f1284c35SGou Ngai     /// @brief 获得WRITER守卫
230f1284c35SGou Ngai     pub fn write(&self) -> RwLockWriteGuard<T> {
231f1284c35SGou Ngai         loop {
232f1284c35SGou Ngai             match self.try_write() {
233f1284c35SGou Ngai                 Some(guard) => return guard,
234f1284c35SGou Ngai                 None => spin_loop(),
235f1284c35SGou Ngai             }
236f1284c35SGou Ngai         }
237f1284c35SGou Ngai     }
238f1284c35SGou Ngai 
239f1284c35SGou Ngai     #[allow(dead_code)]
240f1284c35SGou Ngai     #[inline]
2411496ba7bSLoGin     /// @brief 获取WRITER守卫并关中断
2421496ba7bSLoGin     pub fn write_irqsave(&self) -> RwLockWriteGuard<T> {
2431496ba7bSLoGin         loop {
2441496ba7bSLoGin             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
2451496ba7bSLoGin             match self.try_write() {
2461496ba7bSLoGin                 Some(mut guard) => {
2471496ba7bSLoGin                     guard.irq_guard = Some(irq_guard);
2481496ba7bSLoGin                     return guard;
2491496ba7bSLoGin                 }
2501496ba7bSLoGin                 None => spin_loop(),
2511496ba7bSLoGin             }
2521496ba7bSLoGin         }
2531496ba7bSLoGin     }
2541496ba7bSLoGin 
2551496ba7bSLoGin     #[allow(dead_code)]
2561496ba7bSLoGin     #[inline]
257f1284c35SGou Ngai     /// @brief 尝试获得UPGRADER守卫
258f1284c35SGou Ngai     pub fn try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>> {
2591496ba7bSLoGin         ProcessManager::preempt_disable();
26040fe15e0SLoGin         let r = self.inner_try_upgradeable_read();
26140fe15e0SLoGin         if r.is_none() {
2621496ba7bSLoGin             ProcessManager::preempt_enable();
26340fe15e0SLoGin         }
26440fe15e0SLoGin 
26540fe15e0SLoGin         return r;
26640fe15e0SLoGin     }
26740fe15e0SLoGin 
26840fe15e0SLoGin     fn inner_try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>> {
269f1284c35SGou Ngai         // 获得UPGRADER守卫不需要查看读者位
270f1284c35SGou Ngai         // 如果获得读者锁失败,不需要撤回fetch_or的原子操作
271f1284c35SGou Ngai         if self.lock.fetch_or(UPGRADED, Ordering::Acquire) & (WRITER | UPGRADED) == 0 {
272f1284c35SGou Ngai             return Some(RwLockUpgradableGuard {
273f1284c35SGou Ngai                 inner: self,
274f1284c35SGou Ngai                 data: unsafe { &mut *self.data.get() },
275*2f6f547aSGnoCiYeH                 irq_guard: None,
276f1284c35SGou Ngai             });
277f1284c35SGou Ngai         } else {
278f1284c35SGou Ngai             return None;
279f1284c35SGou Ngai         }
280f1284c35SGou Ngai     }
281f1284c35SGou Ngai 
282f1284c35SGou Ngai     #[allow(dead_code)]
283f1284c35SGou Ngai     #[inline]
284f1284c35SGou Ngai     /// @brief 获得UPGRADER守卫
285f1284c35SGou Ngai     pub fn upgradeable_read(&self) -> RwLockUpgradableGuard<T> {
286f1284c35SGou Ngai         loop {
287f1284c35SGou Ngai             match self.try_upgradeable_read() {
288f1284c35SGou Ngai                 Some(guard) => return guard,
289f1284c35SGou Ngai                 None => spin_loop(),
290f1284c35SGou Ngai             }
291f1284c35SGou Ngai         }
292f1284c35SGou Ngai     }
293f1284c35SGou Ngai 
294*2f6f547aSGnoCiYeH     #[inline]
295*2f6f547aSGnoCiYeH     /// @brief 获得UPGRADER守卫
296*2f6f547aSGnoCiYeH     pub fn upgradeable_read_irqsave(&self) -> RwLockUpgradableGuard<T> {
297*2f6f547aSGnoCiYeH         loop {
298*2f6f547aSGnoCiYeH             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
299*2f6f547aSGnoCiYeH             match self.try_upgradeable_read() {
300*2f6f547aSGnoCiYeH                 Some(mut guard) => {
301*2f6f547aSGnoCiYeH                     guard.irq_guard = Some(irq_guard);
302*2f6f547aSGnoCiYeH                     return guard;
303*2f6f547aSGnoCiYeH                 }
304*2f6f547aSGnoCiYeH                 None => spin_loop(),
305*2f6f547aSGnoCiYeH             }
306*2f6f547aSGnoCiYeH         }
307*2f6f547aSGnoCiYeH     }
308*2f6f547aSGnoCiYeH 
309f1284c35SGou Ngai     #[allow(dead_code)]
310f1284c35SGou Ngai     #[inline]
311f1284c35SGou Ngai     //extremely unsafe behavior
312f1284c35SGou Ngai     /// @brief 强制减少READER数
313f1284c35SGou Ngai     pub unsafe fn force_read_decrement(&self) {
314f1284c35SGou Ngai         debug_assert!(self.lock.load(Ordering::Relaxed) & !WRITER > 0);
315f1284c35SGou Ngai         self.lock.fetch_sub(READER, Ordering::Release);
316f1284c35SGou Ngai     }
317f1284c35SGou Ngai 
318f1284c35SGou Ngai     #[allow(dead_code)]
319f1284c35SGou Ngai     #[inline]
320f1284c35SGou Ngai     //extremely unsafe behavior
321f1284c35SGou Ngai     /// @brief 强制给WRITER解锁
322f1284c35SGou Ngai     pub unsafe fn force_write_unlock(&self) {
323f1284c35SGou Ngai         debug_assert_eq!(self.lock.load(Ordering::Relaxed) & !(WRITER | UPGRADED), 0);
324f1284c35SGou Ngai         self.lock.fetch_and(!(WRITER | UPGRADED), Ordering::Release);
325f1284c35SGou Ngai     }
326f1284c35SGou Ngai 
327f1284c35SGou Ngai     #[allow(dead_code)]
32813776c11Slogin     pub unsafe fn get_mut(&mut self) -> &mut T {
329f1284c35SGou Ngai         unsafe { &mut *self.data.get() }
330f1284c35SGou Ngai     }
331f1284c35SGou Ngai }
332f1284c35SGou Ngai 
333f1284c35SGou Ngai impl<T: Default> Default for RwLock<T> {
334f1284c35SGou Ngai     fn default() -> Self {
335f1284c35SGou Ngai         Self::new(Default::default())
336f1284c35SGou Ngai     }
337f1284c35SGou Ngai }
338f1284c35SGou Ngai 
339f1284c35SGou Ngai /// @brief 由原有的值创建新的锁
340f1284c35SGou Ngai impl<T> From<T> for RwLock<T> {
341f1284c35SGou Ngai     fn from(data: T) -> Self {
342f1284c35SGou Ngai         return Self::new(data);
343f1284c35SGou Ngai     }
344f1284c35SGou Ngai }
345f1284c35SGou Ngai 
346f1284c35SGou Ngai impl<'rwlock, T> RwLockReadGuard<'rwlock, T> {
34790a0a490SLoGin     /// @brief 释放守卫,获得保护的值的不可变引用
34890a0a490SLoGin     ///
34990a0a490SLoGin     /// ## Safety
35090a0a490SLoGin     ///
35190a0a490SLoGin     /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
35290a0a490SLoGin     /// 因此必须小心的手动维护好preempt count。
35390a0a490SLoGin     ///
35490a0a490SLoGin     /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
355f1284c35SGou Ngai     #[allow(dead_code)]
356f1284c35SGou Ngai     #[inline]
35790a0a490SLoGin     pub unsafe fn leak(this: Self) -> &'rwlock T {
35890a0a490SLoGin         let this = ManuallyDrop::new(this);
35990a0a490SLoGin         return unsafe { &*this.data };
360f1284c35SGou Ngai     }
361f1284c35SGou Ngai }
362f1284c35SGou Ngai 
363f1284c35SGou Ngai impl<'rwlock, T> RwLockUpgradableGuard<'rwlock, T> {
364f1284c35SGou Ngai     #[allow(dead_code)]
365f1284c35SGou Ngai     #[inline]
366f1284c35SGou Ngai     /// @brief 尝试将UPGRADER守卫升级为WRITER守卫
367*2f6f547aSGnoCiYeH     pub fn try_upgrade(mut self) -> Result<RwLockWriteGuard<'rwlock, T>, Self> {
368f1284c35SGou Ngai         let res = self.inner.lock.compare_exchange(
369f1284c35SGou Ngai             UPGRADED,
370f1284c35SGou Ngai             WRITER,
371f1284c35SGou Ngai             Ordering::Acquire,
372f1284c35SGou Ngai             Ordering::Relaxed,
373f1284c35SGou Ngai         );
374f1284c35SGou Ngai         //当且仅当只有UPGRADED守卫时可以升级
375f1284c35SGou Ngai 
376f1284c35SGou Ngai         if res.is_ok() {
377f1284c35SGou Ngai             let inner = self.inner;
378*2f6f547aSGnoCiYeH             let irq_guard = self.irq_guard.take();
379f1284c35SGou Ngai             mem::forget(self);
380f1284c35SGou Ngai 
381f1284c35SGou Ngai             Ok(RwLockWriteGuard {
382f1284c35SGou Ngai                 data: unsafe { &mut *inner.data.get() },
383f1284c35SGou Ngai                 inner,
384*2f6f547aSGnoCiYeH                 irq_guard,
385f1284c35SGou Ngai             })
386f1284c35SGou Ngai         } else {
387f1284c35SGou Ngai             Err(self)
388f1284c35SGou Ngai         }
389f1284c35SGou Ngai     }
390f1284c35SGou Ngai 
391f1284c35SGou Ngai     #[allow(dead_code)]
392f1284c35SGou Ngai     #[inline]
393f1284c35SGou Ngai     /// @brief 将upgrader升级成writer
394f1284c35SGou Ngai     pub fn upgrade(mut self) -> RwLockWriteGuard<'rwlock, T> {
395f1284c35SGou Ngai         loop {
396f1284c35SGou Ngai             self = match self.try_upgrade() {
397f1284c35SGou Ngai                 Ok(writeguard) => return writeguard,
398f1284c35SGou Ngai                 Err(former) => former,
399f1284c35SGou Ngai             };
400f1284c35SGou Ngai 
401f1284c35SGou Ngai             spin_loop();
402f1284c35SGou Ngai         }
403f1284c35SGou Ngai     }
404f1284c35SGou Ngai 
405f1284c35SGou Ngai     #[allow(dead_code)]
406f1284c35SGou Ngai     #[inline]
407f1284c35SGou Ngai     /// @brief UPGRADER降级为READER
408*2f6f547aSGnoCiYeH     pub fn downgrade(mut self) -> RwLockReadGuard<'rwlock, T> {
409f1284c35SGou Ngai         while self.inner.current_reader().is_err() {
410f1284c35SGou Ngai             spin_loop();
411f1284c35SGou Ngai         }
412f1284c35SGou Ngai 
413f1284c35SGou Ngai         let inner: &RwLock<T> = self.inner;
414*2f6f547aSGnoCiYeH         let irq_guard = self.irq_guard.take();
415f1284c35SGou Ngai         // 自动移去UPGRADED比特位
416f1284c35SGou Ngai         mem::drop(self);
417f1284c35SGou Ngai 
418f1284c35SGou Ngai         RwLockReadGuard {
419f1284c35SGou Ngai             data: unsafe { &*inner.data.get() },
420f1284c35SGou Ngai             lock: &inner.lock,
421*2f6f547aSGnoCiYeH             irq_guard,
422f1284c35SGou Ngai         }
423f1284c35SGou Ngai     }
424f1284c35SGou Ngai 
425f1284c35SGou Ngai     #[allow(dead_code)]
426f1284c35SGou Ngai     #[inline]
42790a0a490SLoGin     /// @brief 返回内部数据的引用,消除守卫
42890a0a490SLoGin     ///
42990a0a490SLoGin     /// ## Safety
43090a0a490SLoGin     ///
43190a0a490SLoGin     /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
43290a0a490SLoGin     /// 因此必须小心的手动维护好preempt count。
43390a0a490SLoGin     ///
43490a0a490SLoGin     /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
43590a0a490SLoGin     pub unsafe fn leak(this: Self) -> &'rwlock T {
43690a0a490SLoGin         let this: ManuallyDrop<RwLockUpgradableGuard<'_, T>> = ManuallyDrop::new(this);
437f1284c35SGou Ngai 
438f1284c35SGou Ngai         unsafe { &*this.data }
439f1284c35SGou Ngai     }
440f1284c35SGou Ngai }
441f1284c35SGou Ngai 
442f1284c35SGou Ngai impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> {
443f1284c35SGou Ngai     #[allow(dead_code)]
444f1284c35SGou Ngai     #[inline]
44590a0a490SLoGin     /// @brief 返回内部数据的引用,消除守卫
44690a0a490SLoGin     ///
44790a0a490SLoGin     /// ## Safety
44890a0a490SLoGin     ///
44990a0a490SLoGin     /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
45090a0a490SLoGin     /// 因此必须小心的手动维护好preempt count。
45190a0a490SLoGin     ///
45290a0a490SLoGin     /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
45390a0a490SLoGin     pub unsafe fn leak(this: Self) -> &'rwlock T {
454f1284c35SGou Ngai         let this = ManuallyDrop::new(this);
455f1284c35SGou Ngai 
456f1284c35SGou Ngai         return unsafe { &*this.data };
457f1284c35SGou Ngai     }
458f1284c35SGou Ngai 
459f1284c35SGou Ngai     #[allow(dead_code)]
460f1284c35SGou Ngai     #[inline]
461f1284c35SGou Ngai     /// @brief 将WRITER降级为READER
462*2f6f547aSGnoCiYeH     pub fn downgrade(mut self) -> RwLockReadGuard<'rwlock, T> {
463f1284c35SGou Ngai         while self.inner.current_reader().is_err() {
464f1284c35SGou Ngai             spin_loop();
465f1284c35SGou Ngai         }
466f1284c35SGou Ngai         //本质上来说绝对保证没有任何读者
467f1284c35SGou Ngai 
468f1284c35SGou Ngai         let inner = self.inner;
469*2f6f547aSGnoCiYeH         let irq_guard = self.irq_guard.take();
470f1284c35SGou Ngai         mem::drop(self);
471f1284c35SGou Ngai 
472f1284c35SGou Ngai         return RwLockReadGuard {
473f1284c35SGou Ngai             data: unsafe { &*inner.data.get() },
474f1284c35SGou Ngai             lock: &inner.lock,
475*2f6f547aSGnoCiYeH             irq_guard,
476f1284c35SGou Ngai         };
477f1284c35SGou Ngai     }
478f1284c35SGou Ngai 
479f1284c35SGou Ngai     #[allow(dead_code)]
480f1284c35SGou Ngai     #[inline]
481f1284c35SGou Ngai     /// @brief 将WRITER降级为UPGRADER
482*2f6f547aSGnoCiYeH     pub fn downgrade_to_upgradeable(mut self) -> RwLockUpgradableGuard<'rwlock, T> {
483f1284c35SGou Ngai         debug_assert_eq!(
484f1284c35SGou Ngai             self.inner.lock.load(Ordering::Acquire) & (WRITER | UPGRADED),
485f1284c35SGou Ngai             WRITER
486f1284c35SGou Ngai         );
487f1284c35SGou Ngai 
488f1284c35SGou Ngai         self.inner.lock.store(UPGRADED, Ordering::Release);
489f1284c35SGou Ngai 
490f1284c35SGou Ngai         let inner = self.inner;
491f1284c35SGou Ngai 
492*2f6f547aSGnoCiYeH         let irq_guard = self.irq_guard.take();
493f1284c35SGou Ngai         mem::forget(self);
494f1284c35SGou Ngai 
495f1284c35SGou Ngai         return RwLockUpgradableGuard {
496f1284c35SGou Ngai             inner,
497f1284c35SGou Ngai             data: unsafe { &*inner.data.get() },
498*2f6f547aSGnoCiYeH             irq_guard,
499f1284c35SGou Ngai         };
500f1284c35SGou Ngai     }
501f1284c35SGou Ngai }
502f1284c35SGou Ngai 
503f1284c35SGou Ngai impl<'rwlock, T> Deref for RwLockReadGuard<'rwlock, T> {
504f1284c35SGou Ngai     type Target = T;
505f1284c35SGou Ngai 
506f1284c35SGou Ngai     fn deref(&self) -> &Self::Target {
507f1284c35SGou Ngai         return unsafe { &*self.data };
508f1284c35SGou Ngai     }
509f1284c35SGou Ngai }
510f1284c35SGou Ngai 
511f1284c35SGou Ngai impl<'rwlock, T> Deref for RwLockUpgradableGuard<'rwlock, T> {
512f1284c35SGou Ngai     type Target = T;
513f1284c35SGou Ngai 
514f1284c35SGou Ngai     fn deref(&self) -> &Self::Target {
515f1284c35SGou Ngai         return unsafe { &*self.data };
516f1284c35SGou Ngai     }
517f1284c35SGou Ngai }
518f1284c35SGou Ngai 
519f1284c35SGou Ngai impl<'rwlock, T> Deref for RwLockWriteGuard<'rwlock, T> {
520f1284c35SGou Ngai     type Target = T;
521f1284c35SGou Ngai 
522f1284c35SGou Ngai     fn deref(&self) -> &Self::Target {
523f1284c35SGou Ngai         return unsafe { &*self.data };
524f1284c35SGou Ngai     }
525f1284c35SGou Ngai }
526f1284c35SGou Ngai 
527f1284c35SGou Ngai impl<'rwlock, T> DerefMut for RwLockWriteGuard<'rwlock, T> {
528f1284c35SGou Ngai     fn deref_mut(&mut self) -> &mut Self::Target {
529f1284c35SGou Ngai         return unsafe { &mut *self.data };
530f1284c35SGou Ngai     }
531f1284c35SGou Ngai }
532f1284c35SGou Ngai 
533f1284c35SGou Ngai impl<'rwlock, T> Drop for RwLockReadGuard<'rwlock, T> {
534f1284c35SGou Ngai     fn drop(&mut self) {
535f1284c35SGou Ngai         debug_assert!(self.lock.load(Ordering::Relaxed) & !(WRITER | UPGRADED) > 0);
536f1284c35SGou Ngai         self.lock.fetch_sub(READER, Ordering::Release);
5371496ba7bSLoGin         ProcessManager::preempt_enable();
538f1284c35SGou Ngai     }
539f1284c35SGou Ngai }
540f1284c35SGou Ngai 
541f1284c35SGou Ngai impl<'rwlock, T> Drop for RwLockUpgradableGuard<'rwlock, T> {
542f1284c35SGou Ngai     fn drop(&mut self) {
543f1284c35SGou Ngai         debug_assert_eq!(
544f1284c35SGou Ngai             self.inner.lock.load(Ordering::Relaxed) & (WRITER | UPGRADED),
545f1284c35SGou Ngai             UPGRADED
546f1284c35SGou Ngai         );
547f1284c35SGou Ngai         self.inner.lock.fetch_sub(UPGRADED, Ordering::AcqRel);
5481496ba7bSLoGin         ProcessManager::preempt_enable();
549f1284c35SGou Ngai         //这里为啥要AcqRel? Release应该就行了?
550f1284c35SGou Ngai     }
551f1284c35SGou Ngai }
552f1284c35SGou Ngai 
553f1284c35SGou Ngai impl<'rwlock, T> Drop for RwLockWriteGuard<'rwlock, T> {
554f1284c35SGou Ngai     fn drop(&mut self) {
555f1284c35SGou Ngai         debug_assert_eq!(self.inner.lock.load(Ordering::Relaxed) & WRITER, WRITER);
556f1284c35SGou Ngai         self.inner
557f1284c35SGou Ngai             .lock
558f1284c35SGou Ngai             .fetch_and(!(WRITER | UPGRADED), Ordering::Release);
5591496ba7bSLoGin         self.irq_guard.take();
5601496ba7bSLoGin         ProcessManager::preempt_enable();
561f1284c35SGou Ngai     }
562f1284c35SGou Ngai }
563