[PATCH 3/3] rust: sync: Add Guard::new_unchecked()

Lyude Paul
2024-11-20T22:35:16Z

Asserting is_locked() for unsafe Guard::new() calls is quite useful for
verifying safety for callers outside the lock module. But in the lock
module, it's a bit unnecessary and a potential performance hit for safe
rust code. Mainly because it implies all safe lock acquisitions in rust
will have to run this debug assertion.

So, let's split out Guard::new() by adding a Guard::new_unchecked()
function that skips this debug assertion. Of course, we leave this function
as private and note that it is only ever intended for use in this specific
module.

Signed-off-by: Lyude Paul <lyude@redhat.com>
---
rust/kernel/sync/lock.rs | 17 +++++++++++++++--
1 file changed, 15 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
index 0a7f2ed767423..2fd4b665ffc9a 100644
--- a/rust/kernel/sync/lock.rs
+++ b/rust/kernel/sync/lock.rs
@@ -166,7 +166,7 @@ pub fn lock(&self) -> Guard<'_, T, B> {
// that `init` was called.
let state = unsafe { B::lock(self.state.get()) };
// SAFETY: The lock was just acquired.
- unsafe { Guard::new(self, state) }
+ unsafe { Guard::new_unchecked(self, state) }
}

/// Tries to acquire the lock.
@@ -175,7 +175,7 @@ pub fn lock(&self) -> Guard<'_, T, B> {
pub fn try_lock(&self) -> Option<Guard<'_, T, B>> {
// SAFETY: The constructor of the type calls `init`, so the existence of the object proves
// that `init` was called.
- unsafe { B::try_lock(self.state.get()).map(|state| Guard::new(self, state)) }
+ unsafe { B::try_lock(self.state.get()).map(|state| Guard::new_unchecked(self, state)) }
}

/// Return whether or not the lock is currently acquired.
@@ -255,6 +255,19 @@ impl<'a, T: ?Sized, B: Backend> Guard<'a, T, B> {
pub unsafe fn new(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
debug_assert!(lock.is_locked());

+ // SAFETY: Our safety requirements fulfill the requirements of this function.
+ unsafe { Self::new_unchecked(lock, state) }
+ }
+
+ /// Constructs a new immutable lock guard without assertions.
+ ///
+ /// Unlike [`Guard::new`], this function does not run a debug assertion to ensure the lock has
+ /// been acquired. It should only be used in this module.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that it owns the lock.
+ unsafe fn new_unchecked(lock: &'a Lock<T, B>, state: B::GuardState) -> Self {
Self {
lock,
state,
--
2.47.0