rwlock.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. #![allow(dead_code)]
  2. use core::{
  3. cell::UnsafeCell,
  4. hint::spin_loop,
  5. mem::{self, ManuallyDrop},
  6. ops::{Deref, DerefMut},
  7. sync::atomic::{AtomicU32, Ordering},
  8. };
  9. use system_error::SystemError;
  10. use crate::{
  11. arch::CurrentIrqArch,
  12. exception::{InterruptArch, IrqFlagsGuard},
  13. process::ProcessManager,
  14. };
  15. ///RwLock读写锁
  16. /// @brief READER位占据从右往左数第三个比特位
  17. const READER: u32 = 1 << 2;
  18. /// @brief UPGRADED位占据从右到左数第二个比特位
  19. const UPGRADED: u32 = 1 << 1;
  20. /// @brief WRITER位占据最右边的比特位
  21. const WRITER: u32 = 1;
  22. const READER_BIT: u32 = 2;
  23. /// @brief 读写锁的基本数据结构
  24. /// @param lock 32位原子变量,最右边的两位从左到右分别是UPGRADED,WRITER (标志位)
  25. /// 剩下的bit位存储READER数量(除了MSB)
  26. /// 对于标志位,0代表无, 1代表有
  27. /// 对于剩下的比特位表征READER的数量的多少
  28. /// lock的MSB必须为0,否则溢出
  29. #[derive(Debug)]
  30. pub struct RwLock<T> {
  31. lock: AtomicU32,
  32. data: UnsafeCell<T>,
  33. }
  34. /// @brief READER守卫的数据结构
  35. /// @param lock 是对RwLock的lock属性值的只读引用
  36. pub struct RwLockReadGuard<'a, T: 'a> {
  37. data: *const T,
  38. lock: &'a AtomicU32,
  39. irq_guard: Option<IrqFlagsGuard>,
  40. }
  41. /// @brief UPGRADED是介于READER和WRITER之间的一种锁,它可以升级为WRITER,
  42. /// UPGRADED守卫的数据结构,注册UPGRADED锁只需要查看UPGRADED和WRITER的比特位
  43. /// 但是当UPGRADED守卫注册后,不允许有新的读者锁注册
  44. /// @param inner 是对RwLock数据结构的只读引用
  45. pub struct RwLockUpgradableGuard<'a, T: 'a> {
  46. data: *const T,
  47. inner: &'a RwLock<T>,
  48. irq_guard: Option<IrqFlagsGuard>,
  49. }
  50. /// @brief WRITER守卫的数据结构
  51. /// @param data RwLock的data的可变引用
  52. /// @param inner 是对RwLock数据结构的只读引用
  53. pub struct RwLockWriteGuard<'a, T: 'a> {
  54. data: *mut T,
  55. inner: &'a RwLock<T>,
  56. irq_guard: Option<IrqFlagsGuard>,
  57. }
  58. unsafe impl<T: Send> Send for RwLock<T> {}
  59. unsafe impl<T: Send + Sync> Sync for RwLock<T> {}
  60. /// @brief RwLock的API
  61. impl<T> RwLock<T> {
  62. #[inline]
  63. /// @brief RwLock的初始化
  64. pub const fn new(data: T) -> Self {
  65. return RwLock {
  66. lock: AtomicU32::new(0),
  67. data: UnsafeCell::new(data),
  68. };
  69. }
  70. #[allow(dead_code)]
  71. #[inline]
  72. /// @brief 将读写锁的皮扒掉,返回内在的data,返回的是一个真身而非引用
  73. pub fn into_inner(self) -> T {
  74. let RwLock { data, .. } = self;
  75. return data.into_inner();
  76. }
  77. #[allow(dead_code)]
  78. #[inline]
  79. /// @brief 返回data的raw pointer,
  80. /// unsafe
  81. pub fn as_mut_ptr(&self) -> *mut T {
  82. return self.data.get();
  83. }
  84. #[allow(dead_code)]
  85. #[inline]
  86. /// @brief 获取实时的读者数并尝试加1,如果增加值成功则返回增加1后的读者数,否则panic
  87. fn current_reader(&self) -> Result<u32, SystemError> {
  88. const MAX_READERS: u32 = u32::MAX >> READER_BIT >> 1; //右移3位
  89. let value = self.lock.fetch_add(READER, Ordering::Acquire);
  90. //value二进制形式的MSB不能为1, 否则导致溢出
  91. if value > MAX_READERS << READER_BIT {
  92. self.lock.fetch_sub(READER, Ordering::Release);
  93. //panic!("Too many lock readers, cannot safely proceed");
  94. return Err(SystemError::EOVERFLOW);
  95. } else {
  96. return Ok(value);
  97. }
  98. }
  99. #[allow(dead_code)]
  100. #[inline]
  101. /// @brief 尝试获取READER守卫
  102. pub fn try_read(&self) -> Option<RwLockReadGuard<T>> {
  103. ProcessManager::preempt_disable();
  104. let r = self.inner_try_read();
  105. if r.is_none() {
  106. ProcessManager::preempt_enable();
  107. }
  108. return r;
  109. }
  110. fn inner_try_read(&self) -> Option<RwLockReadGuard<T>> {
  111. let reader_value = self.current_reader();
  112. //得到自增后的reader_value, 包括了尝试获得READER守卫的进程
  113. let value = if let Ok(rv) = reader_value {
  114. rv
  115. } else {
  116. return None;
  117. };
  118. //判断有没有writer和upgrader
  119. //注意, 若upgrader存在,已经存在的读者继续占有锁,但新读者不允许获得锁
  120. if value & (WRITER | UPGRADED) != 0 {
  121. self.lock.fetch_sub(READER, Ordering::Release);
  122. return None;
  123. } else {
  124. return Some(RwLockReadGuard {
  125. data: unsafe { &*self.data.get() },
  126. lock: &self.lock,
  127. irq_guard: None,
  128. });
  129. }
  130. }
  131. #[allow(dead_code)]
  132. #[inline]
  133. /// @brief 获得READER的守卫
  134. pub fn read(&self) -> RwLockReadGuard<T> {
  135. loop {
  136. match self.try_read() {
  137. Some(guard) => return guard,
  138. None => spin_loop(),
  139. }
  140. } //忙等待
  141. }
  142. /// 关中断并获取读者守卫
  143. pub fn read_irqsave(&self) -> RwLockReadGuard<T> {
  144. loop {
  145. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  146. match self.try_read() {
  147. Some(mut guard) => {
  148. guard.irq_guard = Some(irq_guard);
  149. return guard;
  150. }
  151. None => spin_loop(),
  152. }
  153. }
  154. }
  155. /// 尝试关闭中断并获取读者守卫
  156. pub fn try_read_irqsave(&self) -> Option<RwLockReadGuard<T>> {
  157. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  158. if let Some(mut guard) = self.try_read() {
  159. guard.irq_guard = Some(irq_guard);
  160. return Some(guard);
  161. } else {
  162. return None;
  163. }
  164. }
  165. #[allow(dead_code)]
  166. #[inline]
  167. /// @brief 获取读者+UPGRADER的数量, 不能保证能否获得同步值
  168. pub fn reader_count(&self) -> u32 {
  169. let state = self.lock.load(Ordering::Relaxed);
  170. return state / READER + (state & UPGRADED) / UPGRADED;
  171. }
  172. #[allow(dead_code)]
  173. #[inline]
  174. /// @brief 获取写者数量,不能保证能否获得同步值
  175. pub fn writer_count(&self) -> u32 {
  176. return (self.lock.load(Ordering::Relaxed) & WRITER) / WRITER;
  177. }
  178. #[allow(dead_code)]
  179. #[inline]
  180. /// @brief 尝试获得WRITER守卫
  181. pub fn try_write(&self) -> Option<RwLockWriteGuard<T>> {
  182. ProcessManager::preempt_disable();
  183. let r = self.inner_try_write();
  184. if r.is_none() {
  185. ProcessManager::preempt_enable();
  186. }
  187. return r;
  188. } //当架构为arm时,有些代码需要作出调整compare_exchange=>compare_exchange_weak
  189. #[allow(dead_code)]
  190. #[inline]
  191. pub fn try_write_irqsave(&self) -> Option<RwLockWriteGuard<T>> {
  192. ProcessManager::preempt_disable();
  193. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  194. let r = self.inner_try_write().map(|mut g| {
  195. g.irq_guard = Some(irq_guard);
  196. g
  197. });
  198. if r.is_none() {
  199. ProcessManager::preempt_enable();
  200. }
  201. return r;
  202. }
  203. #[allow(dead_code)]
  204. fn inner_try_write(&self) -> Option<RwLockWriteGuard<T>> {
  205. let res: bool = self
  206. .lock
  207. .compare_exchange(0, WRITER, Ordering::Acquire, Ordering::Relaxed)
  208. .is_ok();
  209. //只有lock大小为0的时候能获得写者守卫
  210. if res {
  211. return Some(RwLockWriteGuard {
  212. data: unsafe { &mut *self.data.get() },
  213. inner: self,
  214. irq_guard: None,
  215. });
  216. } else {
  217. return None;
  218. }
  219. }
  220. #[allow(dead_code)]
  221. #[inline]
  222. /// @brief 获得WRITER守卫
  223. pub fn write(&self) -> RwLockWriteGuard<T> {
  224. loop {
  225. match self.try_write() {
  226. Some(guard) => return guard,
  227. None => spin_loop(),
  228. }
  229. }
  230. }
  231. #[allow(dead_code)]
  232. #[inline]
  233. /// @brief 获取WRITER守卫并关中断
  234. pub fn write_irqsave(&self) -> RwLockWriteGuard<T> {
  235. loop {
  236. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  237. match self.try_write() {
  238. Some(mut guard) => {
  239. guard.irq_guard = Some(irq_guard);
  240. return guard;
  241. }
  242. None => spin_loop(),
  243. }
  244. }
  245. }
  246. #[allow(dead_code)]
  247. #[inline]
  248. /// @brief 尝试获得UPGRADER守卫
  249. pub fn try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>> {
  250. ProcessManager::preempt_disable();
  251. let r = self.inner_try_upgradeable_read();
  252. if r.is_none() {
  253. ProcessManager::preempt_enable();
  254. }
  255. return r;
  256. }
  257. #[allow(dead_code)]
  258. pub fn try_upgradeable_read_irqsave(&self) -> Option<RwLockUpgradableGuard<T>> {
  259. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  260. ProcessManager::preempt_disable();
  261. let mut r = self.inner_try_upgradeable_read();
  262. if r.is_none() {
  263. ProcessManager::preempt_enable();
  264. } else {
  265. r.as_mut().unwrap().irq_guard = Some(irq_guard);
  266. }
  267. return r;
  268. }
  269. fn inner_try_upgradeable_read(&self) -> Option<RwLockUpgradableGuard<T>> {
  270. // 获得UPGRADER守卫不需要查看读者位
  271. // 如果获得读者锁失败,不需要撤回fetch_or的原子操作
  272. if self.lock.fetch_or(UPGRADED, Ordering::Acquire) & (WRITER | UPGRADED) == 0 {
  273. return Some(RwLockUpgradableGuard {
  274. inner: self,
  275. data: unsafe { &mut *self.data.get() },
  276. irq_guard: None,
  277. });
  278. } else {
  279. return None;
  280. }
  281. }
  282. #[allow(dead_code)]
  283. #[inline]
  284. /// @brief 获得UPGRADER守卫
  285. pub fn upgradeable_read(&self) -> RwLockUpgradableGuard<T> {
  286. loop {
  287. match self.try_upgradeable_read() {
  288. Some(guard) => return guard,
  289. None => spin_loop(),
  290. }
  291. }
  292. }
  293. #[inline]
  294. /// @brief 获得UPGRADER守卫
  295. pub fn upgradeable_read_irqsave(&self) -> RwLockUpgradableGuard<T> {
  296. loop {
  297. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  298. match self.try_upgradeable_read() {
  299. Some(mut guard) => {
  300. guard.irq_guard = Some(irq_guard);
  301. return guard;
  302. }
  303. None => spin_loop(),
  304. }
  305. }
  306. }
  307. #[allow(dead_code)]
  308. #[inline]
  309. //extremely unsafe behavior
  310. /// @brief 强制减少READER数
  311. pub unsafe fn force_read_decrement(&self) {
  312. debug_assert!(self.lock.load(Ordering::Relaxed) & !WRITER > 0);
  313. self.lock.fetch_sub(READER, Ordering::Release);
  314. }
  315. #[allow(dead_code)]
  316. #[inline]
  317. //extremely unsafe behavior
  318. /// @brief 强制给WRITER解锁
  319. pub unsafe fn force_write_unlock(&self) {
  320. debug_assert_eq!(self.lock.load(Ordering::Relaxed) & !(WRITER | UPGRADED), 0);
  321. self.lock.fetch_and(!(WRITER | UPGRADED), Ordering::Release);
  322. }
  323. #[allow(dead_code)]
  324. pub unsafe fn get_mut(&mut self) -> &mut T {
  325. unsafe { &mut *self.data.get() }
  326. }
  327. #[allow(dead_code)]
  328. pub unsafe fn force_get_ref(&self) -> &T {
  329. unsafe { &*self.data.get() }
  330. }
  331. }
  332. impl<T: Default> Default for RwLock<T> {
  333. fn default() -> Self {
  334. Self::new(Default::default())
  335. }
  336. }
  337. /// @brief 由原有的值创建新的锁
  338. impl<T> From<T> for RwLock<T> {
  339. fn from(data: T) -> Self {
  340. return Self::new(data);
  341. }
  342. }
  343. impl<'rwlock, T> RwLockReadGuard<'rwlock, T> {
  344. /// @brief 释放守卫,获得保护的值的不可变引用
  345. ///
  346. /// ## Safety
  347. ///
  348. /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
  349. /// 因此必须小心的手动维护好preempt count。
  350. ///
  351. /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
  352. #[allow(dead_code)]
  353. #[inline]
  354. pub unsafe fn leak(this: Self) -> &'rwlock T {
  355. let this = ManuallyDrop::new(this);
  356. return unsafe { &*this.data };
  357. }
  358. }
  359. impl<'rwlock, T> RwLockUpgradableGuard<'rwlock, T> {
  360. #[allow(dead_code)]
  361. #[inline]
  362. /// @brief 尝试将UPGRADER守卫升级为WRITER守卫
  363. pub fn try_upgrade(mut self) -> Result<RwLockWriteGuard<'rwlock, T>, Self> {
  364. let res = self.inner.lock.compare_exchange(
  365. UPGRADED,
  366. WRITER,
  367. Ordering::Acquire,
  368. Ordering::Relaxed,
  369. );
  370. //当且仅当只有UPGRADED守卫时可以升级
  371. if res.is_ok() {
  372. let inner = self.inner;
  373. let irq_guard = self.irq_guard.take();
  374. mem::forget(self);
  375. Ok(RwLockWriteGuard {
  376. data: unsafe { &mut *inner.data.get() },
  377. inner,
  378. irq_guard,
  379. })
  380. } else {
  381. Err(self)
  382. }
  383. }
  384. #[allow(dead_code)]
  385. #[inline]
  386. /// @brief 将upgrader升级成writer
  387. pub fn upgrade(mut self) -> RwLockWriteGuard<'rwlock, T> {
  388. loop {
  389. self = match self.try_upgrade() {
  390. Ok(writeguard) => return writeguard,
  391. Err(former) => former,
  392. };
  393. spin_loop();
  394. }
  395. }
  396. #[allow(dead_code)]
  397. #[inline]
  398. /// @brief UPGRADER降级为READER
  399. pub fn downgrade(mut self) -> RwLockReadGuard<'rwlock, T> {
  400. while self.inner.current_reader().is_err() {
  401. spin_loop();
  402. }
  403. let inner: &RwLock<T> = self.inner;
  404. let irq_guard = self.irq_guard.take();
  405. // 自动移去UPGRADED比特位
  406. mem::drop(self);
  407. RwLockReadGuard {
  408. data: unsafe { &*inner.data.get() },
  409. lock: &inner.lock,
  410. irq_guard,
  411. }
  412. }
  413. #[allow(dead_code)]
  414. #[inline]
  415. /// @brief 返回内部数据的引用,消除守卫
  416. ///
  417. /// ## Safety
  418. ///
  419. /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
  420. /// 因此必须小心的手动维护好preempt count。
  421. ///
  422. /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
  423. pub unsafe fn leak(this: Self) -> &'rwlock T {
  424. let this: ManuallyDrop<RwLockUpgradableGuard<'_, T>> = ManuallyDrop::new(this);
  425. unsafe { &*this.data }
  426. }
  427. }
  428. impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> {
  429. #[allow(dead_code)]
  430. #[inline]
  431. /// @brief 返回内部数据的引用,消除守卫
  432. ///
  433. /// ## Safety
  434. ///
  435. /// 由于这样做可能导致守卫在另一个线程中被释放,从而导致pcb的preempt count不正确,
  436. /// 因此必须小心的手动维护好preempt count。
  437. ///
  438. /// 并且,leak还可能导致锁的状态不正确。因此请仔细考虑是否真的需要使用这个函数。
  439. pub unsafe fn leak(this: Self) -> &'rwlock T {
  440. let this = ManuallyDrop::new(this);
  441. return unsafe { &*this.data };
  442. }
  443. #[allow(dead_code)]
  444. #[inline]
  445. /// @brief 将WRITER降级为READER
  446. pub fn downgrade(mut self) -> RwLockReadGuard<'rwlock, T> {
  447. while self.inner.current_reader().is_err() {
  448. spin_loop();
  449. }
  450. //本质上来说绝对保证没有任何读者
  451. let inner = self.inner;
  452. let irq_guard = self.irq_guard.take();
  453. mem::drop(self);
  454. return RwLockReadGuard {
  455. data: unsafe { &*inner.data.get() },
  456. lock: &inner.lock,
  457. irq_guard,
  458. };
  459. }
  460. #[allow(dead_code)]
  461. #[inline]
  462. /// @brief 将WRITER降级为UPGRADER
  463. pub fn downgrade_to_upgradeable(mut self) -> RwLockUpgradableGuard<'rwlock, T> {
  464. debug_assert_eq!(
  465. self.inner.lock.load(Ordering::Acquire) & (WRITER | UPGRADED),
  466. WRITER
  467. );
  468. self.inner.lock.store(UPGRADED, Ordering::Release);
  469. let inner = self.inner;
  470. let irq_guard = self.irq_guard.take();
  471. mem::forget(self);
  472. return RwLockUpgradableGuard {
  473. inner,
  474. data: unsafe { &*inner.data.get() },
  475. irq_guard,
  476. };
  477. }
  478. }
  479. impl<T> Deref for RwLockReadGuard<'_, T> {
  480. type Target = T;
  481. fn deref(&self) -> &Self::Target {
  482. return unsafe { &*self.data };
  483. }
  484. }
  485. impl<T> Deref for RwLockUpgradableGuard<'_, T> {
  486. type Target = T;
  487. fn deref(&self) -> &Self::Target {
  488. return unsafe { &*self.data };
  489. }
  490. }
  491. impl<T> Deref for RwLockWriteGuard<'_, T> {
  492. type Target = T;
  493. fn deref(&self) -> &Self::Target {
  494. return unsafe { &*self.data };
  495. }
  496. }
  497. impl<T> DerefMut for RwLockWriteGuard<'_, T> {
  498. fn deref_mut(&mut self) -> &mut Self::Target {
  499. return unsafe { &mut *self.data };
  500. }
  501. }
  502. impl<T> Drop for RwLockReadGuard<'_, T> {
  503. fn drop(&mut self) {
  504. debug_assert!(self.lock.load(Ordering::Relaxed) & !(WRITER | UPGRADED) > 0);
  505. self.lock.fetch_sub(READER, Ordering::Release);
  506. ProcessManager::preempt_enable();
  507. }
  508. }
  509. impl<T> Drop for RwLockUpgradableGuard<'_, T> {
  510. fn drop(&mut self) {
  511. debug_assert_eq!(
  512. self.inner.lock.load(Ordering::Relaxed) & (WRITER | UPGRADED),
  513. UPGRADED
  514. );
  515. self.inner.lock.fetch_sub(UPGRADED, Ordering::AcqRel);
  516. ProcessManager::preempt_enable();
  517. //这里为啥要AcqRel? Release应该就行了?
  518. }
  519. }
  520. impl<T> Drop for RwLockWriteGuard<'_, T> {
  521. fn drop(&mut self) {
  522. debug_assert_eq!(self.inner.lock.load(Ordering::Relaxed) & WRITER, WRITER);
  523. self.inner
  524. .lock
  525. .fetch_and(!(WRITER | UPGRADED), Ordering::Release);
  526. self.irq_guard.take();
  527. ProcessManager::preempt_enable();
  528. }
  529. }