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