|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! A wrapper for data protected by a lock that does not wrap it. |
| 4 | +
|
| 5 | +use super::{lock::Backend, lock::Lock}; |
| 6 | +use core::{cell::UnsafeCell, ptr}; |
| 7 | + |
| 8 | +/// Allows access to some data to be serialised by a lock that does not wrap it. |
| 9 | +/// |
| 10 | +/// In most cases, data protected by a lock is wrapped by the appropriate lock type, e.g., |
| 11 | +/// [`super::Mutex`] or [`super::SpinLock`]. [`LockedBy`] is meant for cases when this is not |
| 12 | +/// possible. For example, if a container has a lock and some data in the contained elements needs |
| 13 | +/// to be protected by the same lock. |
| 14 | +/// |
| 15 | +/// [`LockedBy`] wraps the data in lieu of another locking primitive, and only allows access to it |
| 16 | +/// when the caller shows evidence that the 'external' lock is locked. It panics if the evidence |
| 17 | +/// refers to the wrong instance of the lock. |
| 18 | +/// |
| 19 | +/// # Examples |
| 20 | +/// |
| 21 | +/// The following is an example for illustrative purposes: `InnerDirectory::bytes_used` is an |
| 22 | +/// aggregate of all `InnerFile::bytes_used` and must be kept consistent; so we wrap `InnerFile` in |
| 23 | +/// a `LockedBy` so that it shares a lock with `InnerDirectory`. This allows us to enforce at |
| 24 | +/// compile-time that access to `InnerFile` is only granted when an `InnerDirectory` is also |
| 25 | +/// locked; we enforce at run time that the right `InnerDirectory` is locked. |
| 26 | +/// |
| 27 | +/// ``` |
| 28 | +/// use kernel::sync::{LockedBy, Mutex}; |
| 29 | +/// |
| 30 | +/// struct InnerFile { |
| 31 | +/// bytes_used: u64, |
| 32 | +/// } |
| 33 | +/// |
| 34 | +/// struct File { |
| 35 | +/// _ino: u32, |
| 36 | +/// inner: LockedBy<InnerFile, InnerDirectory>, |
| 37 | +/// } |
| 38 | +/// |
| 39 | +/// struct InnerDirectory { |
| 40 | +/// /// The sum of the bytes used by all files. |
| 41 | +/// bytes_used: u64, |
| 42 | +/// _files: Vec<File>, |
| 43 | +/// } |
| 44 | +/// |
| 45 | +/// struct Directory { |
| 46 | +/// _ino: u32, |
| 47 | +/// inner: Mutex<InnerDirectory>, |
| 48 | +/// } |
| 49 | +/// |
| 50 | +/// /// Prints `bytes_used` from both the directory and file. |
| 51 | +/// fn print_bytes_used(dir: &Directory, file: &File) { |
| 52 | +/// let guard = dir.inner.lock(); |
| 53 | +/// let inner_file = file.inner.access(&guard); |
| 54 | +/// pr_info!("{} {}", guard.bytes_used, inner_file.bytes_used); |
| 55 | +/// } |
| 56 | +/// |
| 57 | +/// /// Increments `bytes_used` for both the directory and file. |
| 58 | +/// fn inc_bytes_used(dir: &Directory, file: &File) { |
| 59 | +/// let mut guard = dir.inner.lock(); |
| 60 | +/// guard.bytes_used += 10; |
| 61 | +/// |
| 62 | +/// let file_inner = file.inner.access_mut(&mut guard); |
| 63 | +/// file_inner.bytes_used += 10; |
| 64 | +/// } |
| 65 | +/// |
| 66 | +/// /// Creates a new file. |
| 67 | +/// fn new_file(ino: u32, dir: &Directory) -> File { |
| 68 | +/// File { |
| 69 | +/// _ino: ino, |
| 70 | +/// inner: LockedBy::new(&dir.inner, InnerFile { bytes_used: 0 }), |
| 71 | +/// } |
| 72 | +/// } |
| 73 | +/// ``` |
| 74 | +pub struct LockedBy<T: ?Sized, U: ?Sized> { |
| 75 | + owner: *const U, |
| 76 | + data: UnsafeCell<T>, |
| 77 | +} |
| 78 | + |
| 79 | +// SAFETY: `LockedBy` can be transferred across thread boundaries iff the data it protects can. |
| 80 | +unsafe impl<T: ?Sized + Send, U: ?Sized> Send for LockedBy<T, U> {} |
| 81 | + |
| 82 | +// SAFETY: `LockedBy` serialises the interior mutability it provides, so it is `Sync` as long as the |
| 83 | +// data it protects is `Send`. |
| 84 | +unsafe impl<T: ?Sized + Send, U: ?Sized> Sync for LockedBy<T, U> {} |
| 85 | + |
| 86 | +impl<T, U: ?Sized> LockedBy<T, U> { |
| 87 | + /// Constructs a new instance of [`LockedBy`]. |
| 88 | + /// |
| 89 | + /// It stores a raw pointer to the owner that is never dereferenced. It is only used to ensure |
| 90 | + /// that the right owner is being used to access the protected data. If the owner is freed, the |
| 91 | + /// data becomes inaccessible; if another instance of the owner is allocated *on the same |
| 92 | + /// memory location*, the data becomes accessible again: none of this affects memory safety |
| 93 | + /// because in any case at most one thread (or CPU) can access the protected data at a time. |
| 94 | + pub fn new(owner: &Lock<U, impl Backend>, data: T) -> Self { |
| 95 | + Self { |
| 96 | + owner: owner.data.get(), |
| 97 | + data: UnsafeCell::new(data), |
| 98 | + } |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +impl<T: ?Sized, U> LockedBy<T, U> { |
| 103 | + /// Returns a reference to the protected data when the caller provides evidence (via a |
| 104 | + /// reference) that the owner is locked. |
| 105 | + /// |
| 106 | + /// `U` cannot be a zero-sized type (ZST) because there are ways to get an `&U` that matches |
| 107 | + /// the data protected by the lock without actually holding it. |
| 108 | + /// |
| 109 | + /// # Panics |
| 110 | + /// |
| 111 | + /// Panics if `owner` is different from the data protected by the lock used in |
| 112 | + /// [`new`](LockedBy::new). |
| 113 | + pub fn access<'a>(&'a self, owner: &'a U) -> &'a T { |
| 114 | + // Detect the usage of SZTs, which are supported, at compile time. |
| 115 | + crate::build_assert!(core::mem::size_of::<U>() > 0); |
| 116 | + if !ptr::eq(owner, self.owner) { |
| 117 | + panic!("mismatched owners"); |
| 118 | + } |
| 119 | + |
| 120 | + // SAFETY: `owner` is evidence that the owner is locked. |
| 121 | + unsafe { &*self.data.get() } |
| 122 | + } |
| 123 | + |
| 124 | + /// Returns a mutable reference to the protected data when the caller provides evidence (via a |
| 125 | + /// mutable owner) that the owner is locked mutably. |
| 126 | + /// |
| 127 | + /// `U` cannot be a zero-sized type (ZST) because there are ways to get an `&mut U` that |
| 128 | + /// matches the data protected by the lock without actually holding it. |
| 129 | + /// |
| 130 | + /// Showing a mutable reference to the owner is sufficient because we know no other references |
| 131 | + /// can exist to it. |
| 132 | + /// |
| 133 | + /// # Panics |
| 134 | + /// |
| 135 | + /// Panics if `owner` is different from the data protected by the lock used in |
| 136 | + /// [`new`](LockedBy::new). |
| 137 | + pub fn access_mut<'a>(&'a self, owner: &'a mut U) -> &'a mut T { |
| 138 | + // Detect the usage of SZTs, which are supported, at compile time. |
| 139 | + crate::build_assert!(core::mem::size_of::<U>() > 0); |
| 140 | + if !ptr::eq(owner, self.owner) { |
| 141 | + panic!("mismatched owners"); |
| 142 | + } |
| 143 | + |
| 144 | + // SAFETY: `owner` is evidence that there is only one reference to the owner. |
| 145 | + unsafe { &mut *self.data.get() } |
| 146 | + } |
| 147 | +} |
0 commit comments