1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Generic kernel lock and guard. 4 //! 5 //! It contains a generic Rust lock and guard that allow for different backends (e.g., mutexes, 6 //! spinlocks, raw spinlocks) to be provided with minimal effort. 7 8 use super::LockClassKey; 9 use crate::{ 10 init::PinInit, 11 pin_init, 12 str::CStr, 13 types::{NotThreadSafe, Opaque, ScopeGuard}, 14 }; 15 use core::{cell::UnsafeCell, marker::PhantomPinned}; 16 use macros::pin_data; 17 18 pub mod mutex; 19 pub mod spinlock; 20 21 pub(super) mod global; 22 pub use global::{GlobalGuard, GlobalLock, GlobalLockBackend, GlobalLockedBy}; 23 24 /// The "backend" of a lock. 25 /// 26 /// It is the actual implementation of the lock, without the need to repeat patterns used in all 27 /// locks. 28 /// 29 /// # Safety 30 /// 31 /// - Implementers must ensure that only one thread/CPU may access the protected data once the lock 32 /// is owned, that is, between calls to [`lock`] and [`unlock`]. 33 /// - Implementers must also ensure that [`relock`] uses the same locking method as the original 34 /// lock operation. 35 /// 36 /// [`lock`]: Backend::lock 37 /// [`unlock`]: Backend::unlock 38 /// [`relock`]: Backend::relock 39 pub unsafe trait Backend { 40 /// The state required by the lock. 41 type State; 42 43 /// The state required to be kept between [`lock`] and [`unlock`]. 44 /// 45 /// [`lock`]: Backend::lock 46 /// [`unlock`]: Backend::unlock 47 type GuardState; 48 49 /// Initialises the lock. 50 /// 51 /// # Safety 52 /// 53 /// `ptr` must be valid for write for the duration of the call, while `name` and `key` must 54 /// remain valid for read indefinitely. 55 unsafe fn init( 56 ptr: *mut Self::State, 57 name: *const crate::ffi::c_char, 58 key: *mut bindings::lock_class_key, 59 ); 60 61 /// Acquires the lock, making the caller its owner. 62 /// 63 /// # Safety 64 /// 65 /// Callers must ensure that [`Backend::init`] has been previously called. 66 #[must_use] 67 unsafe fn lock(ptr: *mut Self::State) -> Self::GuardState; 68 69 /// Tries to acquire the lock. 70 /// 71 /// # Safety 72 /// 73 /// Callers must ensure that [`Backend::init`] has been previously called. 74 unsafe fn try_lock(ptr: *mut Self::State) -> Option<Self::GuardState>; 75 76 /// Releases the lock, giving up its ownership. 77 /// 78 /// # Safety 79 /// 80 /// It must only be called by the current owner of the lock. 81 unsafe fn unlock(ptr: *mut Self::State, guard_state: &Self::GuardState); 82 83 /// Reacquires the lock, making the caller its owner. 84 /// 85 /// # Safety 86 /// 87 /// Callers must ensure that `guard_state` comes from a previous call to [`Backend::lock`] (or 88 /// variant) that has been unlocked with [`Backend::unlock`] and will be relocked now. 89 unsafe fn relock(ptr: *mut Self::State, guard_state: &mut Self::GuardState) { 90 // SAFETY: The safety requirements ensure that the lock is initialised. 91 *guard_state = unsafe { Self::lock(ptr) }; 92 } 93 } 94 95 /// A mutual exclusion primitive. 96 /// 97 /// Exposes one of the kernel locking primitives. Which one is exposed depends on the lock 98 /// [`Backend`] specified as the generic parameter `B`. 99 #[repr(C)] 100 #[pin_data] 101 pub struct Lock<T: ?Sized, B: Backend> { 102 /// The kernel lock object. 103 #[pin] 104 state: Opaque<B::State>, 105 106 /// Some locks are known to be self-referential (e.g., mutexes), while others are architecture 107 /// or config defined (e.g., spinlocks). So we conservatively require them to be pinned in case 108 /// some architecture uses self-references now or in the future. 109 #[pin] 110 _pin: PhantomPinned, 111 112 /// The data protected by the lock. 113 pub(crate) data: UnsafeCell<T>, 114 } 115 116 // SAFETY: `Lock` can be transferred across thread boundaries iff the data it protects can. 117 unsafe impl<T: ?Sized + Send, B: Backend> Send for Lock<T, B> {} 118 119 // SAFETY: `Lock` serialises the interior mutability it provides, so it is `Sync` as long as the 120 // data it protects is `Send`. 121 unsafe impl<T: ?Sized + Send, B: Backend> Sync for Lock<T, B> {} 122 123 impl<T, B: Backend> Lock<T, B> { 124 /// Constructs a new lock initialiser. 125 pub fn new(t: T, name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> { 126 pin_init!(Self { 127 data: UnsafeCell::new(t), 128 _pin: PhantomPinned, 129 // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have 130 // static lifetimes so they live indefinitely. 131 state <- Opaque::ffi_init(|slot| unsafe { 132 B::init(slot, name.as_char_ptr(), key.as_ptr()) 133 }), 134 }) 135 } 136 } 137 138 impl<B: Backend> Lock<(), B> { 139 /// Constructs a [`Lock`] from a raw pointer. 140 /// 141 /// This can be useful for interacting with a lock which was initialised outside of Rust. 142 /// 143 /// # Safety 144 /// 145 /// The caller promises that `ptr` points to a valid initialised instance of [`State`] during 146 /// the whole lifetime of `'a`. 147 /// 148 /// [`State`]: Backend::State 149 pub unsafe fn from_raw<'a>(ptr: *mut B::State) -> &'a Self { 150 // SAFETY: 151 // - By the safety contract `ptr` must point to a valid initialised instance of `B::State` 152 // - Since the lock data type is `()` which is a ZST, `state` is the only non-ZST member of 153 // the struct 154 // - Combined with `#[repr(C)]`, this guarantees `Self` has an equivalent data layout to 155 // `B::State`. 156 unsafe { &*ptr.cast() } 157 } 158 } 159 160 impl<T: ?Sized, B: Backend> Lock<T, B> { 161 /// Acquires the lock and gives the caller access to the data protected by it. 162 pub fn lock(&self) -> Guard<'_, T, B> { 163 // SAFETY: The constructor of the type calls `init`, so the existence of the object proves 164 // that `init` was called. 165 let state = unsafe { B::lock(self.state.get()) }; 166 // SAFETY: The lock was just acquired. 167 unsafe { Guard::new(self, state) } 168 } 169 170 /// Tries to acquire the lock. 171 /// 172 /// Returns a guard that can be used to access the data protected by the lock if successful. 173 pub fn try_lock(&self) -> Option<Guard<'_, T, B>> { 174 // SAFETY: The constructor of the type calls `init`, so the existence of the object proves 175 // that `init` was called. 176 unsafe { B::try_lock(self.state.get()).map(|state| Guard::new(self, state)) } 177 } 178 } 179 180 /// A lock guard. 181 /// 182 /// Allows mutual exclusion primitives that implement the [`Backend`] trait to automatically unlock 183 /// when a guard goes out of scope. It also provides a safe and convenient way to access the data 184 /// protected by the lock. 185 #[must_use = "the lock unlocks immediately when the guard is unused"] 186 pub struct Guard<'a, T: ?Sized, B: Backend> { 187 pub(crate) lock: &'a Lock<T, B>, 188 pub(crate) state: B::GuardState, 189 _not_send: NotThreadSafe, 190 } 191 192 // SAFETY: `Guard` is sync when the data protected by the lock is also sync. 193 unsafe impl<T: Sync + ?Sized, B: Backend> Sync for Guard<'_, T, B> {} 194 195 impl<T: ?Sized, B: Backend> Guard<'_, T, B> { 196 pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U { 197 // SAFETY: The caller owns the lock, so it is safe to unlock it. 198 unsafe { B::unlock(self.lock.state.get(), &self.state) }; 199 200 let _relock = ScopeGuard::new(|| 201 // SAFETY: The lock was just unlocked above and is being relocked now. 202 unsafe { B::relock(self.lock.state.get(), &mut self.state) }); 203 204 cb() 205 } 206 } 207 208 impl<T: ?Sized, B: Backend> core::ops::Deref for Guard<'_, T, B> { 209 type Target = T; 210 211 fn deref(&self) -> &Self::Target { 212 // SAFETY: The caller owns the lock, so it is safe to deref the protected data. 213 unsafe { &*self.lock.data.get() } 214 } 215 } 216 217 impl<T: ?Sized, B: Backend> core::ops::DerefMut for Guard<'_, T, B> { 218 fn deref_mut(&mut self) -> &mut Self::Target { 219 // SAFETY: The caller owns the lock, so it is safe to deref the protected data. 220 unsafe { &mut *self.lock.data.get() } 221 } 222 } 223 224 impl<T: ?Sized, B: Backend> Drop for Guard<'_, T, B> { 225 fn drop(&mut self) { 226 // SAFETY: The caller owns the lock, so it is safe to unlock it. 227 unsafe { B::unlock(self.lock.state.get(), &self.state) }; 228 } 229 } 230 231 impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> { 232 /// Constructs a new immutable lock guard. 233 /// 234 /// # Safety 235 /// 236 /// The caller must ensure that it owns the lock. 237 pub unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self { 238 Self { 239 lock, 240 state, 241 _not_send: NotThreadSafe, 242 } 243 } 244 } 245