kernel/sync/lock.rs
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
8use super::LockClassKey;
9use crate::{
10 prelude::*,
11 str::CStr,
12 types::{NotThreadSafe, Opaque, ScopeGuard},
13};
14
15use core::{
16 cell::UnsafeCell,
17 convert::Infallible,
18 marker::PhantomPinned,
19 pin::Pin, //
20};
21use pin_init::{
22 pin_data,
23 PinInit,
24 Wrapper, //
25};
26
27pub mod mutex;
28pub mod spinlock;
29
30pub(super) mod global;
31pub use global::{GlobalGuard, GlobalLock, GlobalLockBackend, GlobalLockedBy};
32
33/// The "backend" of a lock.
34///
35/// It is the actual implementation of the lock, without the need to repeat patterns used in all
36/// locks.
37///
38/// # Safety
39///
40/// - Implementers must ensure that only one thread/CPU may access the protected data once the lock
41/// is owned, that is, between calls to [`lock`] and [`unlock`].
42/// - Implementers must also ensure that [`relock`] uses the same locking method as the original
43/// lock operation.
44///
45/// [`lock`]: Backend::lock
46/// [`unlock`]: Backend::unlock
47/// [`relock`]: Backend::relock
48pub unsafe trait Backend {
49 /// The state required by the lock.
50 type State;
51
52 /// The state required to be kept between [`lock`] and [`unlock`].
53 ///
54 /// [`lock`]: Backend::lock
55 /// [`unlock`]: Backend::unlock
56 type GuardState;
57
58 /// Initialises the lock.
59 ///
60 /// # Safety
61 ///
62 /// `ptr` must be valid for write for the duration of the call, while `name` and `key` must
63 /// remain valid for read indefinitely.
64 unsafe fn init(
65 ptr: *mut Self::State,
66 name: *const crate::ffi::c_char,
67 key: *mut bindings::lock_class_key,
68 );
69
70 /// Acquires the lock, making the caller its owner.
71 ///
72 /// # Safety
73 ///
74 /// Callers must ensure that [`Backend::init`] has been previously called.
75 #[must_use]
76 unsafe fn lock(ptr: *mut Self::State) -> Self::GuardState;
77
78 /// Tries to acquire the lock.
79 ///
80 /// # Safety
81 ///
82 /// Callers must ensure that [`Backend::init`] has been previously called.
83 unsafe fn try_lock(ptr: *mut Self::State) -> Option<Self::GuardState>;
84
85 /// Releases the lock, giving up its ownership.
86 ///
87 /// # Safety
88 ///
89 /// It must only be called by the current owner of the lock.
90 unsafe fn unlock(ptr: *mut Self::State, guard_state: &Self::GuardState);
91
92 /// Reacquires the lock, making the caller its owner.
93 ///
94 /// # Safety
95 ///
96 /// Callers must ensure that `guard_state` comes from a previous call to [`Backend::lock`] (or
97 /// variant) that has been unlocked with [`Backend::unlock`] and will be relocked now.
98 unsafe fn relock(ptr: *mut Self::State, guard_state: &mut Self::GuardState) {
99 // SAFETY: The safety requirements ensure that the lock is initialised.
100 *guard_state = unsafe { Self::lock(ptr) };
101 }
102
103 /// Asserts that the lock is held using lockdep.
104 ///
105 /// # Safety
106 ///
107 /// Callers must ensure that [`Backend::init`] has been previously called.
108 unsafe fn assert_is_held(ptr: *mut Self::State);
109}
110
111/// A mutual exclusion primitive.
112///
113/// Exposes one of the kernel locking primitives. Which one is exposed depends on the lock
114/// [`Backend`] specified as the generic parameter `B`.
115#[repr(C)]
116#[pin_data]
117pub struct Lock<T: ?Sized, B: Backend> {
118 /// The kernel lock object.
119 #[pin]
120 state: Opaque<B::State>,
121
122 /// Some locks are known to be self-referential (e.g., mutexes), while others are architecture
123 /// or config defined (e.g., spinlocks). So we conservatively require them to be pinned in case
124 /// some architecture uses self-references now or in the future.
125 #[pin]
126 _pin: PhantomPinned,
127
128 /// The data protected by the lock.
129 #[pin]
130 pub(crate) data: UnsafeCell<T>,
131}
132
133// SAFETY: `Lock` can be transferred across thread boundaries iff the data it protects can.
134unsafe impl<T: ?Sized + Send, B: Backend> Send for Lock<T, B> {}
135
136// SAFETY: `Lock` serialises the interior mutability it provides, so it is `Sync` as long as the
137// data it protects is `Send`.
138unsafe impl<T: ?Sized + Send, B: Backend> Sync for Lock<T, B> {}
139
140impl<T, B: Backend> Lock<T, B> {
141 /// Constructs a new lock initialiser.
142 pub fn new<E>(
143 t: impl PinInit<T, E>,
144 name: &'static CStr,
145 key: Pin<&'static LockClassKey>,
146 ) -> impl PinInit<Self, E>
147 where
148 E: From<Infallible>,
149 {
150 pin_init!(Self {
151 data <- UnsafeCell::pin_init(t),
152 _pin: PhantomPinned,
153 // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
154 // static lifetimes so they live indefinitely.
155 state <- Opaque::ffi_init(|slot| unsafe {
156 B::init(slot, name.as_char_ptr(), key.as_ptr())
157 }),
158 }? E)
159 }
160}
161
162impl<B: Backend> Lock<(), B> {
163 /// Constructs a [`Lock`] from a raw pointer.
164 ///
165 /// This can be useful for interacting with a lock which was initialised outside of Rust.
166 ///
167 /// # Safety
168 ///
169 /// The caller promises that `ptr` points to a valid initialised instance of [`State`] during
170 /// the whole lifetime of `'a`.
171 ///
172 /// [`State`]: Backend::State
173 #[inline]
174 pub unsafe fn from_raw<'a>(ptr: *mut B::State) -> &'a Self {
175 // SAFETY:
176 // - By the safety contract `ptr` must point to a valid initialised instance of `B::State`
177 // - Since the lock data type is `()` which is a ZST, `state` is the only non-ZST member of
178 // the struct
179 // - Combined with `#[repr(C)]`, this guarantees `Self` has an equivalent data layout to
180 // `B::State`.
181 unsafe { &*ptr.cast() }
182 }
183}
184
185impl<T: ?Sized, B: Backend> Lock<T, B> {
186 /// Acquires the lock and gives the caller access to the data protected by it.
187 #[inline]
188 pub fn lock(&self) -> Guard<'_, T, B> {
189 // SAFETY: The constructor of the type calls `init`, so the existence of the object proves
190 // that `init` was called.
191 let state = unsafe { B::lock(self.state.get()) };
192 // SAFETY: The lock was just acquired.
193 unsafe { Guard::new(self, state) }
194 }
195
196 /// Tries to acquire the lock.
197 ///
198 /// Returns a guard that can be used to access the data protected by the lock if successful.
199 // `Option<T>` is not `#[must_use]` even if `T` is, thus the attribute is needed here.
200 #[must_use = "if unused, the lock will be immediately unlocked"]
201 #[inline]
202 pub fn try_lock(&self) -> Option<Guard<'_, T, B>> {
203 // SAFETY: The constructor of the type calls `init`, so the existence of the object proves
204 // that `init` was called.
205 unsafe { B::try_lock(self.state.get()).map(|state| Guard::new(self, state)) }
206 }
207}
208
209/// A lock guard.
210///
211/// Allows mutual exclusion primitives that implement the [`Backend`] trait to automatically unlock
212/// when a guard goes out of scope. It also provides a safe and convenient way to access the data
213/// protected by the lock.
214#[must_use = "the lock unlocks immediately when the guard is unused"]
215pub struct Guard<'a, T: ?Sized, B: Backend> {
216 pub(crate) lock: &'a Lock<T, B>,
217 pub(crate) state: B::GuardState,
218 _not_send: NotThreadSafe,
219}
220
221// SAFETY: `Guard` is sync when the data protected by the lock is also sync.
222unsafe impl<T: Sync + ?Sized, B: Backend> Sync for Guard<'_, T, B> {}
223
224impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> {
225 /// Returns the lock that this guard originates from.
226 ///
227 /// # Examples
228 ///
229 /// The following example shows how to use [`Guard::lock_ref()`] to assert the corresponding
230 /// lock is held.
231 ///
232 /// ```
233 /// # use kernel::{new_spinlock, sync::lock::{Backend, Guard, Lock}};
234 /// # use pin_init::stack_pin_init;
235 ///
236 /// fn assert_held<T, B: Backend>(guard: &Guard<'_, T, B>, lock: &Lock<T, B>) {
237 /// // Address-equal means the same lock.
238 /// assert!(core::ptr::eq(guard.lock_ref(), lock));
239 /// }
240 ///
241 /// // Creates a new lock on the stack.
242 /// stack_pin_init!{
243 /// let l = new_spinlock!(42)
244 /// }
245 ///
246 /// let g = l.lock();
247 ///
248 /// // `g` originates from `l`.
249 /// assert_held(&g, &l);
250 /// ```
251 pub fn lock_ref(&self) -> &'a Lock<T, B> {
252 self.lock
253 }
254
255 pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U {
256 // SAFETY: The caller owns the lock, so it is safe to unlock it.
257 unsafe { B::unlock(self.lock.state.get(), &self.state) };
258
259 let _relock = ScopeGuard::new(||
260 // SAFETY: The lock was just unlocked above and is being relocked now.
261 unsafe { B::relock(self.lock.state.get(), &mut self.state) });
262
263 cb()
264 }
265
266 /// Returns a pinned mutable reference to the protected data.
267 ///
268 /// The guard implements [`DerefMut`] when `T: Unpin`, so for [`Unpin`]
269 /// types [`DerefMut`] should be used instead of this function.
270 ///
271 /// [`DerefMut`]: core::ops::DerefMut
272 /// [`Unpin`]: core::marker::Unpin
273 ///
274 /// # Examples
275 ///
276 /// ```
277 /// # use kernel::sync::{Mutex, MutexGuard};
278 /// # use core::{pin::Pin, marker::PhantomPinned};
279 /// struct Data(PhantomPinned);
280 ///
281 /// fn example(mutex: &Mutex<Data>) {
282 /// let mut data: MutexGuard<'_, Data> = mutex.lock();
283 /// let mut data: Pin<&mut Data> = data.as_mut();
284 /// }
285 /// ```
286 pub fn as_mut(&mut self) -> Pin<&mut T> {
287 // SAFETY: `self.lock.data` is structurally pinned.
288 unsafe { Pin::new_unchecked(&mut *self.lock.data.get()) }
289 }
290}
291
292impl<T: ?Sized, B: Backend> core::ops::Deref for Guard<'_, T, B> {
293 type Target = T;
294
295 #[inline]
296 fn deref(&self) -> &Self::Target {
297 // SAFETY: The caller owns the lock, so it is safe to deref the protected data.
298 unsafe { &*self.lock.data.get() }
299 }
300}
301
302impl<T: ?Sized, B: Backend> core::ops::DerefMut for Guard<'_, T, B>
303where
304 T: Unpin,
305{
306 #[inline]
307 fn deref_mut(&mut self) -> &mut Self::Target {
308 // SAFETY: The caller owns the lock, so it is safe to deref the protected data.
309 unsafe { &mut *self.lock.data.get() }
310 }
311}
312
313impl<T: ?Sized, B: Backend> Drop for Guard<'_, T, B> {
314 #[inline]
315 fn drop(&mut self) {
316 // SAFETY: The caller owns the lock, so it is safe to unlock it.
317 unsafe { B::unlock(self.lock.state.get(), &self.state) };
318 }
319}
320
321impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> {
322 /// Constructs a new immutable lock guard.
323 ///
324 /// # Safety
325 ///
326 /// The caller must ensure that it owns the lock.
327 #[inline]
328 pub unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
329 // SAFETY: The caller can only hold the lock if `Backend::init` has already been called.
330 unsafe { B::assert_is_held(lock.state.get()) };
331
332 Self {
333 lock,
334 state,
335 _not_send: NotThreadSafe,
336 }
337 }
338}