Skip to content

Commit 2c1e84a

Browse files
committed
rust: make Lock trait unsafe.
Without this, one could implement a lock that doesn't really provide mutual exclusion, which could result in UB. For example, a no-op `Lock` implementation could provide guards from two different threads concurrently, which could be used by `LockedBy` to generate two mutable references to the same underlying object. Marking `Lock` unsafe has no implication on driver code because all implementations are expected to come from the `kernel` crate anyway. Signed-off-by: Wedson Almeida Filho <[email protected]>
1 parent 6d76783 commit 2c1e84a

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

rust/kernel/sync/guard.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,12 @@ impl<'a, L: Lock + ?Sized> Guard<'a, L> {
6464
///
6565
/// [`Guard`] is written such that any mutual exclusion primitive that can implement this trait can
6666
/// also benefit from having an automatic way to unlock itself.
67-
pub trait Lock {
67+
///
68+
/// # Safety
69+
///
70+
/// Implementers of this trait must ensure that only one thread/CPU may access the protected data
71+
/// once the lock is held, that is, between calls to `lock_noguard` and `unlock`.
72+
pub unsafe trait Lock {
6873
/// The type of the data protected by the lock.
6974
type Inner: ?Sized;
7075

rust/kernel/sync/mutex.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@ impl<T: ?Sized> NeedsLockClass for Mutex<T> {
7777
}
7878
}
7979

80-
impl<T: ?Sized> Lock for Mutex<T> {
80+
// SAFETY: The underlying kernel `struct mutex` object ensures mutual exclusion.
81+
unsafe impl<T: ?Sized> Lock for Mutex<T> {
8182
type Inner = T;
8283
type GuardContext = ();
8384

rust/kernel/sync/spinlock.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ impl<T: ?Sized> NeedsLockClass for SpinLock<T> {
8080
}
8181
}
8282

83-
impl<T: ?Sized> Lock for SpinLock<T> {
83+
// SAFETY: The underlying kernel `spinlock_t` object ensures mutual exclusion.
84+
unsafe impl<T: ?Sized> Lock for SpinLock<T> {
8485
type Inner = T;
8586
type GuardContext = ();
8687

0 commit comments

Comments
 (0)