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