From 2c1e84ac7d3f9394790e15302c81d1d7771c744a Mon Sep 17 00:00:00 2001 From: Wedson Almeida Filho Date: Fri, 15 Oct 2021 16:47:57 +0100 Subject: [PATCH] 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 --- rust/kernel/sync/guard.rs | 7 ++++++- rust/kernel/sync/mutex.rs | 3 ++- rust/kernel/sync/spinlock.rs | 3 ++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/rust/kernel/sync/guard.rs b/rust/kernel/sync/guard.rs index 79f6bd708e1dea..3af735d363571d 100644 --- a/rust/kernel/sync/guard.rs +++ b/rust/kernel/sync/guard.rs @@ -64,7 +64,12 @@ impl<'a, L: Lock + ?Sized> Guard<'a, L> { /// /// [`Guard`] is written such that any mutual exclusion primitive that can implement this trait can /// also benefit from having an automatic way to unlock itself. -pub trait Lock { +/// +/// # Safety +/// +/// Implementers of this trait must ensure that only one thread/CPU may access the protected data +/// once the lock is held, that is, between calls to `lock_noguard` and `unlock`. +pub unsafe trait Lock { /// The type of the data protected by the lock. type Inner: ?Sized; diff --git a/rust/kernel/sync/mutex.rs b/rust/kernel/sync/mutex.rs index 4ceca07b201e89..7053a5136abb94 100644 --- a/rust/kernel/sync/mutex.rs +++ b/rust/kernel/sync/mutex.rs @@ -77,7 +77,8 @@ impl NeedsLockClass for Mutex { } } -impl Lock for Mutex { +// SAFETY: The underlying kernel `struct mutex` object ensures mutual exclusion. +unsafe impl Lock for Mutex { type Inner = T; type GuardContext = (); diff --git a/rust/kernel/sync/spinlock.rs b/rust/kernel/sync/spinlock.rs index 11b918dab3a04c..6fa00a514aac95 100644 --- a/rust/kernel/sync/spinlock.rs +++ b/rust/kernel/sync/spinlock.rs @@ -80,7 +80,8 @@ impl NeedsLockClass for SpinLock { } } -impl Lock for SpinLock { +// SAFETY: The underlying kernel `spinlock_t` object ensures mutual exclusion. +unsafe impl Lock for SpinLock { type Inner = T; type GuardContext = ();