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