lock.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Generic kernel lock and guard.
  3. //!
  4. //! It contains a generic Rust lock and guard that allow for different backends (e.g., mutexes,
  5. //! spinlocks, raw spinlocks) to be provided with minimal effort.
  6. use super::LockClassKey;
  7. use crate::{init::PinInit, pin_init, str::CStr, types::Opaque, types::ScopeGuard};
  8. use core::{cell::UnsafeCell, marker::PhantomData, marker::PhantomPinned};
  9. use macros::pin_data;
  10. pub mod mutex;
  11. pub mod spinlock;
  12. /// The "backend" of a lock.
  13. ///
  14. /// It is the actual implementation of the lock, without the need to repeat patterns used in all
  15. /// locks.
  16. ///
  17. /// # Safety
  18. ///
  19. /// - Implementers must ensure that only one thread/CPU may access the protected data once the lock
  20. /// is owned, that is, between calls to [`lock`] and [`unlock`].
  21. /// - Implementers must also ensure that [`relock`] uses the same locking method as the original
  22. /// lock operation.
  23. ///
  24. /// [`lock`]: Backend::lock
  25. /// [`unlock`]: Backend::unlock
  26. /// [`relock`]: Backend::relock
  27. pub unsafe trait Backend {
  28. /// The state required by the lock.
  29. type State;
  30. /// The state required to be kept between [`lock`] and [`unlock`].
  31. ///
  32. /// [`lock`]: Backend::lock
  33. /// [`unlock`]: Backend::unlock
  34. type GuardState;
  35. /// Initialises the lock.
  36. ///
  37. /// # Safety
  38. ///
  39. /// `ptr` must be valid for write for the duration of the call, while `name` and `key` must
  40. /// remain valid for read indefinitely.
  41. unsafe fn init(
  42. ptr: *mut Self::State,
  43. name: *const crate::ffi::c_char,
  44. key: *mut bindings::lock_class_key,
  45. );
  46. /// Acquires the lock, making the caller its owner.
  47. ///
  48. /// # Safety
  49. ///
  50. /// Callers must ensure that [`Backend::init`] has been previously called.
  51. #[must_use]
  52. unsafe fn lock(ptr: *mut Self::State) -> Self::GuardState;
  53. /// Releases the lock, giving up its ownership.
  54. ///
  55. /// # Safety
  56. ///
  57. /// It must only be called by the current owner of the lock.
  58. unsafe fn unlock(ptr: *mut Self::State, guard_state: &Self::GuardState);
  59. /// Reacquires the lock, making the caller its owner.
  60. ///
  61. /// # Safety
  62. ///
  63. /// Callers must ensure that `guard_state` comes from a previous call to [`Backend::lock`] (or
  64. /// variant) that has been unlocked with [`Backend::unlock`] and will be relocked now.
  65. unsafe fn relock(ptr: *mut Self::State, guard_state: &mut Self::GuardState) {
  66. // SAFETY: The safety requirements ensure that the lock is initialised.
  67. *guard_state = unsafe { Self::lock(ptr) };
  68. }
  69. }
  70. /// A mutual exclusion primitive.
  71. ///
  72. /// Exposes one of the kernel locking primitives. Which one is exposed depends on the lock
  73. /// [`Backend`] specified as the generic parameter `B`.
  74. #[pin_data]
  75. pub struct Lock<T: ?Sized, B: Backend> {
  76. /// The kernel lock object.
  77. #[pin]
  78. state: Opaque<B::State>,
  79. /// Some locks are known to be self-referential (e.g., mutexes), while others are architecture
  80. /// or config defined (e.g., spinlocks). So we conservatively require them to be pinned in case
  81. /// some architecture uses self-references now or in the future.
  82. #[pin]
  83. _pin: PhantomPinned,
  84. /// The data protected by the lock.
  85. pub(crate) data: UnsafeCell<T>,
  86. }
  87. // SAFETY: `Lock` can be transferred across thread boundaries iff the data it protects can.
  88. unsafe impl<T: ?Sized + Send, B: Backend> Send for Lock<T, B> {}
  89. // SAFETY: `Lock` serialises the interior mutability it provides, so it is `Sync` as long as the
  90. // data it protects is `Send`.
  91. unsafe impl<T: ?Sized + Send, B: Backend> Sync for Lock<T, B> {}
  92. impl<T, B: Backend> Lock<T, B> {
  93. /// Constructs a new lock initialiser.
  94. pub fn new(t: T, name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> {
  95. pin_init!(Self {
  96. data: UnsafeCell::new(t),
  97. _pin: PhantomPinned,
  98. // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
  99. // static lifetimes so they live indefinitely.
  100. state <- Opaque::ffi_init(|slot| unsafe {
  101. B::init(slot, name.as_char_ptr(), key.as_ptr())
  102. }),
  103. })
  104. }
  105. }
  106. impl<T: ?Sized, B: Backend> Lock<T, B> {
  107. /// Acquires the lock and gives the caller access to the data protected by it.
  108. pub fn lock(&self) -> Guard<'_, T, B> {
  109. // SAFETY: The constructor of the type calls `init`, so the existence of the object proves
  110. // that `init` was called.
  111. let state = unsafe { B::lock(self.state.get()) };
  112. // SAFETY: The lock was just acquired.
  113. unsafe { Guard::new(self, state) }
  114. }
  115. }
  116. /// A lock guard.
  117. ///
  118. /// Allows mutual exclusion primitives that implement the [`Backend`] trait to automatically unlock
  119. /// when a guard goes out of scope. It also provides a safe and convenient way to access the data
  120. /// protected by the lock.
  121. #[must_use = "the lock unlocks immediately when the guard is unused"]
  122. pub struct Guard<'a, T: ?Sized, B: Backend> {
  123. pub(crate) lock: &'a Lock<T, B>,
  124. pub(crate) state: B::GuardState,
  125. _not_send: PhantomData<*mut ()>,
  126. }
  127. // SAFETY: `Guard` is sync when the data protected by the lock is also sync.
  128. unsafe impl<T: Sync + ?Sized, B: Backend> Sync for Guard<'_, T, B> {}
  129. impl<T: ?Sized, B: Backend> Guard<'_, T, B> {
  130. pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U {
  131. // SAFETY: The caller owns the lock, so it is safe to unlock it.
  132. unsafe { B::unlock(self.lock.state.get(), &self.state) };
  133. let _relock = ScopeGuard::new(||
  134. // SAFETY: The lock was just unlocked above and is being relocked now.
  135. unsafe { B::relock(self.lock.state.get(), &mut self.state) });
  136. cb()
  137. }
  138. }
  139. impl<T: ?Sized, B: Backend> core::ops::Deref for Guard<'_, T, B> {
  140. type Target = T;
  141. fn deref(&self) -> &Self::Target {
  142. // SAFETY: The caller owns the lock, so it is safe to deref the protected data.
  143. unsafe { &*self.lock.data.get() }
  144. }
  145. }
  146. impl<T: ?Sized, B: Backend> core::ops::DerefMut for Guard<'_, T, B> {
  147. fn deref_mut(&mut self) -> &mut Self::Target {
  148. // SAFETY: The caller owns the lock, so it is safe to deref the protected data.
  149. unsafe { &mut *self.lock.data.get() }
  150. }
  151. }
  152. impl<T: ?Sized, B: Backend> Drop for Guard<'_, T, B> {
  153. fn drop(&mut self) {
  154. // SAFETY: The caller owns the lock, so it is safe to unlock it.
  155. unsafe { B::unlock(self.lock.state.get(), &self.state) };
  156. }
  157. }
  158. impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> {
  159. /// Constructs a new immutable lock guard.
  160. ///
  161. /// # Safety
  162. ///
  163. /// The caller must ensure that it owns the lock.
  164. pub(crate) unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
  165. Self {
  166. lock,
  167. state,
  168. _not_send: PhantomData,
  169. }
  170. }
  171. }