Skip to content

Commit e3bd837

Browse files
committed
rust: sync: introduce LockedBy
This allows us to have data protected by a lock despite not being wrapped by it. Access is granted by providing evidence that the lock is held by the caller. Signed-off-by: Wedson Almeida Filho <[email protected]>
1 parent 40b2784 commit e3bd837

File tree

3 files changed

+131
-1
lines changed

3 files changed

+131
-1
lines changed

rust/kernel/sync.rs

+2
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ use crate::types::Opaque;
1010
mod arc;
1111
mod condvar;
1212
pub mod lock;
13+
mod locked_by;
1314

1415
pub use arc::{Arc, ArcBorrow, UniqueArc};
1516
pub use condvar::CondVar;
1617
pub use lock::{mutex::Mutex, spinlock::SpinLock};
18+
pub use locked_by::LockedBy;
1719

1820
/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`.
1921
#[repr(transparent)]

rust/kernel/sync/lock.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ pub struct Lock<T: ?Sized, B: Backend> {
111111
_pin: PhantomPinned,
112112

113113
/// The data protected by the lock.
114-
data: UnsafeCell<T>,
114+
pub(crate) data: UnsafeCell<T>,
115115
}
116116

117117
// SAFETY: `Lock` can be transferred across thread boundaries iff the data it protects can.

rust/kernel/sync/locked_by.rs

+128
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
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.
17+
///
18+
/// # Examples
19+
///
20+
/// The following is an example for illustrative purposes: `InnerDirectory::bytes_used` is an
21+
/// aggregate of all `InnerFile::bytes_used` and must be kept consistent; so we wrap `InnerFile` in
22+
/// a `LockedBy` so that it shares a lock with `InnerDirectory`. This allows us to enforce at
23+
/// compile-time that access to `InnerFile` is only granted when an `InnerDirectory` is also
24+
/// locked; we enforce at run time that the right `InnerDirectory` is locked.
25+
///
26+
/// ```
27+
/// use kernel::sync::{LockedBy, Mutex};
28+
///
29+
/// struct InnerFile {
30+
/// bytes_used: u64,
31+
/// }
32+
///
33+
/// struct File {
34+
/// _ino: u32,
35+
/// inner: LockedBy<InnerFile, InnerDirectory>,
36+
/// }
37+
///
38+
/// struct InnerDirectory {
39+
/// /// The sum of the bytes used by all files.
40+
/// bytes_used: u64,
41+
/// _files: Vec<File>,
42+
/// }
43+
///
44+
/// struct Directory {
45+
/// _ino: u32,
46+
/// inner: Mutex<InnerDirectory>,
47+
/// }
48+
///
49+
/// /// Prints `bytes_used` from both the directory and file.
50+
/// fn print_bytes_used(dir: &Directory, file: &File) {
51+
/// let guard = dir.inner.lock();
52+
/// let inner_file = file.inner.access(&guard);
53+
/// pr_info!("{} {}", guard.bytes_used, inner_file.bytes_used);
54+
/// }
55+
///
56+
/// /// Increments `bytes_used` for both the directory and file.
57+
/// fn inc_bytes_used(dir: &Directory, file: &File) {
58+
/// let mut guard = dir.inner.lock();
59+
/// guard.bytes_used += 10;
60+
///
61+
/// let file_inner = file.inner.access_mut(&mut guard);
62+
/// file_inner.bytes_used += 10;
63+
/// }
64+
///
65+
/// /// Creates a new file.
66+
/// fn new_file(ino: u32, dir: &Directory) -> File {
67+
/// File {
68+
/// _ino: ino,
69+
/// inner: LockedBy::new(&dir.inner, InnerFile { bytes_used: 0 }),
70+
/// }
71+
/// }
72+
/// ```
73+
pub struct LockedBy<T: ?Sized, U: ?Sized> {
74+
owner: *const U,
75+
data: UnsafeCell<T>,
76+
}
77+
78+
// SAFETY: `LockedBy` can be transferred across thread boundaries iff the data it protects can.
79+
unsafe impl<T: ?Sized + Send, U: ?Sized> Send for LockedBy<T, U> {}
80+
81+
// SAFETY: `LockedBy` serialises the interior mutability it provides, so it is `Sync` as long as the
82+
// data it protects is `Send`.
83+
unsafe impl<T: ?Sized + Send, U: ?Sized> Sync for LockedBy<T, U> {}
84+
85+
impl<T, U: ?Sized> LockedBy<T, U> {
86+
/// Constructs a new instance of [`LockedBy`].
87+
///
88+
/// It stores a raw pointer to the owner that is never dereferenced. It is only used to ensure
89+
/// that the right owner is being used to access the protected data. If the owner is freed, the
90+
/// data becomes inaccessible; if another instance of the owner is allocated *on the same
91+
/// memory location*, the data becomes accessible again: none of this affects memory safety
92+
/// because in any case at most one thread (or CPU) can access the protected data at a time.
93+
pub fn new(owner: &Lock<U, impl Backend>, data: T) -> Self {
94+
Self {
95+
owner: owner.data.get(),
96+
data: UnsafeCell::new(data),
97+
}
98+
}
99+
}
100+
101+
impl<T: ?Sized, U> LockedBy<T, U> {
102+
/// Returns a reference to the protected data when the caller provides evidence (via a
103+
/// reference) that the owner is locked.
104+
pub fn access<'a>(&'a self, owner: &'a U) -> &'a T {
105+
crate::build_assert!(core::mem::size_of::<U>() > 0);
106+
if !ptr::eq(owner, self.owner) {
107+
panic!("mismatched owners");
108+
}
109+
110+
// SAFETY: `owner` is evidence that the owner is locked.
111+
unsafe { &*self.data.get() }
112+
}
113+
114+
/// Returns a mutable reference to the protected data when the caller provides evidence (via a
115+
/// mutable owner) that the owner is locked mutably.
116+
///
117+
/// Showing a mutable reference to the owner is sufficient because we know no other references
118+
/// can exist to it.
119+
pub fn access_mut<'a>(&'a self, owner: &'a mut U) -> &'a mut T {
120+
crate::build_assert!(core::mem::size_of::<U>() > 0);
121+
if !ptr::eq(owner, self.owner) {
122+
panic!("mismatched owners");
123+
}
124+
125+
// SAFETY: `owner` is evidence that there is only one reference to the owner.
126+
unsafe { &mut *self.data.get() }
127+
}
128+
}

0 commit comments

Comments
 (0)