1 // SPDX-License-Identifier: GPL-2.0
3 //! A wrapper for data protected by a lock that does not wrap it.
5 use super::{lock::Backend, lock::Lock};
6 use crate::build_assert;
7 use core::{cell::UnsafeCell, mem::size_of, ptr};
9 /// Allows access to some data to be serialised by a lock that does not wrap it.
11 /// In most cases, data protected by a lock is wrapped by the appropriate lock type, e.g.,
12 /// [`super::Mutex`] or [`super::SpinLock`]. [`LockedBy`] is meant for cases when this is not
13 /// possible. For example, if a container has a lock and some data in the contained elements needs
14 /// to be protected by the same lock.
16 /// [`LockedBy`] wraps the data in lieu of another locking primitive, and only allows access to it
17 /// when the caller shows evidence that the 'external' lock is locked. It panics if the evidence
18 /// refers to the wrong instance of the lock.
22 /// The following is an example for illustrative purposes: `InnerDirectory::bytes_used` is an
23 /// aggregate of all `InnerFile::bytes_used` and must be kept consistent; so we wrap `InnerFile` in
24 /// a `LockedBy` so that it shares a lock with `InnerDirectory`. This allows us to enforce at
25 /// compile-time that access to `InnerFile` is only granted when an `InnerDirectory` is also
26 /// locked; we enforce at run time that the right `InnerDirectory` is locked.
29 /// use kernel::sync::{LockedBy, Mutex};
31 /// struct InnerFile {
37 /// inner: LockedBy<InnerFile, InnerDirectory>,
40 /// struct InnerDirectory {
41 /// /// The sum of the bytes used by all files.
43 /// _files: Vec<File>,
46 /// struct Directory {
48 /// inner: Mutex<InnerDirectory>,
51 /// /// Prints `bytes_used` from both the directory and file.
52 /// fn print_bytes_used(dir: &Directory, file: &File) {
53 /// let guard = dir.inner.lock();
54 /// let inner_file = file.inner.access(&guard);
55 /// pr_info!("{} {}", guard.bytes_used, inner_file.bytes_used);
58 /// /// Increments `bytes_used` for both the directory and file.
59 /// fn inc_bytes_used(dir: &Directory, file: &File) {
60 /// let mut guard = dir.inner.lock();
61 /// guard.bytes_used += 10;
63 /// let file_inner = file.inner.access_mut(&mut guard);
64 /// file_inner.bytes_used += 10;
67 /// /// Creates a new file.
68 /// fn new_file(ino: u32, dir: &Directory) -> File {
71 /// inner: LockedBy::new(&dir.inner, InnerFile { bytes_used: 0 }),
75 pub struct LockedBy<T: ?Sized, U: ?Sized> {
80 // SAFETY: `LockedBy` can be transferred across thread boundaries iff the data it protects can.
81 unsafe impl<T: ?Sized + Send, U: ?Sized> Send for LockedBy<T, U> {}
83 // SAFETY: `LockedBy` 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, U: ?Sized> Sync for LockedBy<T, U> {}
87 impl<T, U> LockedBy<T, U> {
88 /// Constructs a new instance of [`LockedBy`].
90 /// It stores a raw pointer to the owner that is never dereferenced. It is only used to ensure
91 /// that the right owner is being used to access the protected data. If the owner is freed, the
92 /// data becomes inaccessible; if another instance of the owner is allocated *on the same
93 /// memory location*, the data becomes accessible again: none of this affects memory safety
94 /// because in any case at most one thread (or CPU) can access the protected data at a time.
95 pub fn new<B: Backend>(owner: &Lock<U, B>, data: T) -> Self {
97 size_of::<Lock<U, B>>() > 0,
98 "The lock type cannot be a ZST because it may be impossible to distinguish instances"
101 owner: owner.data.get(),
102 data: UnsafeCell::new(data),
107 impl<T: ?Sized, U> LockedBy<T, U> {
108 /// Returns a reference to the protected data when the caller provides evidence (via a
109 /// reference) that the owner is locked.
111 /// `U` cannot be a zero-sized type (ZST) because there are ways to get an `&U` that matches
112 /// the data protected by the lock without actually holding it.
116 /// Panics if `owner` is different from the data protected by the lock used in
117 /// [`new`](LockedBy::new).
118 pub fn access<'a>(&'a self, owner: &'a U) -> &'a T {
121 "`U` cannot be a ZST because `owner` wouldn't be unique"
123 if !ptr::eq(owner, self.owner) {
124 panic!("mismatched owners");
127 // SAFETY: `owner` is evidence that the owner is locked.
128 unsafe { &*self.data.get() }
131 /// Returns a mutable reference to the protected data when the caller provides evidence (via a
132 /// mutable owner) that the owner is locked mutably.
134 /// `U` cannot be a zero-sized type (ZST) because there are ways to get an `&mut U` that
135 /// matches the data protected by the lock without actually holding it.
137 /// Showing a mutable reference to the owner is sufficient because we know no other references
142 /// Panics if `owner` is different from the data protected by the lock used in
143 /// [`new`](LockedBy::new).
144 pub fn access_mut<'a>(&'a self, owner: &'a mut U) -> &'a mut T {
147 "`U` cannot be a ZST because `owner` wouldn't be unique"
149 if !ptr::eq(owner, self.owner) {
150 panic!("mismatched owners");
153 // SAFETY: `owner` is evidence that there is only one reference to the owner.
154 unsafe { &mut *self.data.get() }