rust: add ww_mutex support
Subsystems (3)
Onur Özkan
reviewerPATCH v9 5/7 rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
In reply to Onur ÖzkanCovers the entire low-level locking API (lock, try_lock, slow path, interruptible variants) and integration with kernel bindings.
--- rust/kernel/sync/lock/ww_mutex.rs | 433 ++++++++++++++++++ rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs | 172 +++++++ 2 files changed, 605 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs
rust/kernel/sync/lock/ww_mutex.rs +433 -0
@@ -1,7 +1,440 @@// SPDX-License-Identifier: GPL-2.0 //! Rust abstractions for the kernel's wound-wait locking primitives. +//! +//! It is designed to avoid deadlocks when locking multiple [`Mutex`]es +//! that belong to the same [`Class`]. Each lock acquisition uses an +//! [`AcquireCtx`] to track ordering and ensure forward progress. +//! +//! See srctree/Documentation/locking/ww-mutex-design.rst for more details. +use crate ::error::to_result; +use crate ::prelude::*; +use crate ::types::{NotThreadSafe ,Opaque }; +use crate ::{bindings, container_of}; + +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; + +pub use acquire_ctx::AcquireCtx ;pub use class::Class ;mod class; +mod acquire_ctx; +mod class; + +/// A wound-wait (ww) mutex that is powered with deadlock avoidance +/// when acquiring multiple locks of the same [`Class`]. +/// +/// Each mutex belongs to a [`Class`], which the wound-wait algorithm +/// uses to figure out the order of acquisition and prevent deadlocks. +/// +/// # Examples +/// +/// ``` +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use kernel::sync::lock::ww_mutex::{AcquireCtx, Class, Mutex}; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// let mutex = Arc::pin_init(Mutex::new(42, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// let guard = ctx.lock(&mutex)?; +/// assert_eq!(*guard, 42); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data] +#[repr( C )] +pub struct Mutex <'a,T : ?Sized > { + _p:PhantomData <&'aClass >, +#[pin] + inner:Opaque <bindings::ww_mutex >, + data:UnsafeCell <T >, +} + +impl <'class,T >Mutex <'class,T > { +/// Initializes [`Mutex`] with the given `data` and [`Class`]. +pub fn new (data:T , class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (Mutex { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_mutex | { +// SAFETY: `class` is valid for the lifetime `'class` captured by `Self`. +unsafe { bindings::ww_mutex_init (slot, class_ptr) } + }), + data:UnsafeCell ::new (data), + _p:PhantomData + }) + } +} + +impl <'class,T : ?Sized >Mutex <'class,T > { +/// Checks if this [`Mutex`] is currently locked. +/// +/// The returned value is racy as another thread can acquire +/// or release the lock immediately after this call returns. +pub fn is_locked (&self) ->bool { +// SAFETY: It's safe to call `ww_mutex_is_locked` on +// a valid mutex. +unsafe { bindings::ww_mutex_is_locked (self.inner.get ()) } + } + +/// Locks this [`Mutex`] without [`AcquireCtx`]. +pub fn lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Interruptible ) + } + +/// Locks this [`Mutex`] without [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::SlowInterruptible ) + } + +/// Tries to lock this [`Mutex`] with no [`AcquireCtx`] and without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Try ) + } +} + +impl <'class>Mutex <'class, ()> { +/// Creates a [`Mutex`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'a`. +/// - ww_class associated with this mutex must be valid for +/// the lifetime `'class`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_mutex ) -> &'aSelf { +// SAFETY: By the safety contract, the caller guarantees that `ptr` +// points to a valid `ww_mutex` which is the `inner` field of `Mutex`, +// that it remains valid for the lifetime `'a` and the associated +// ww_class outlives `'class`. +// +// Because [`Mutex`] is `#[repr(C)]`, the `inner` field sits at a +// stable offset that `container_of!` can safely rely on. +unsafe { &*container_of! (Opaque ::cast_from (ptr),Self , inner) } + } +} + +// SAFETY: `Mutex` can be sent to another thread if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send >Send for Mutex <'_,T > {} + +// SAFETY: `Mutex` can be shared across threads if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send +Sync >Sync for Mutex <'_,T > {} + +/// A guard that provides exclusive access to the data protected +/// by a [`Mutex`]. +/// +/// # Invariants +/// +/// The guard holds an exclusive lock on the associated [`Mutex`]. The lock is held +/// for the entire lifetime of this guard and is automatically released when the +/// guard is dropped. +#[must_use = "the lock unlocks immediately when the guard is unused" ] +pub struct MutexGuard <'a,T : ?Sized > { + mutex: &'aMutex <'a,T >, + _not_send:NotThreadSafe , +} + +impl <'a,T : ?Sized >MutexGuard <'a,T > { +/// Creates a new guard for the given [`Mutex`]. +fn new (mutex: &'aMutex <'a,T >) ->Self { +assert! (mutex.is_locked ()); + +Self { + mutex, + _not_send:NotThreadSafe , + } + } +} + +impl <'a>MutexGuard <'a, ()> { +/// Creates a [`MutexGuard`] from a raw pointer. +/// +/// If the given pointer refers to a mutex that is not locked, +/// returns [`EINVAL`]. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'b`. +/// - The `ww_class` associated with the `ww_mutex` must be valid for the lifetime `'b`. +pub unsafe fn from_raw <'b>(ptr: *mut bindings::ww_mutex ) ->Result <MutexGuard <'b, ()>> { +// SAFETY: By this function's safety contract, the caller guarantees that `ptr` points to a +// valid `ww_mutex` which is the `inner` field of a `Mutex`. The caller also guarantees +// that both `ptr` and the associated `ww_class` are valid for the lifetime `'b`. +let mutex =unsafe {Mutex ::from_raw (ptr) }; + +if !mutex.is_locked () { +return Err (EINVAL ); + } + +Ok (MutexGuard ::new (mutex)) + } +} + +impl <T : ?Sized > core::ops::Deref for MutexGuard <'_,T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &*self.mutex.data.get () } + } +} + +impl <T : ?Sized +Unpin > core::ops::DerefMut for MutexGuard <'_,T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &mut *self.mutex.data.get () } + } +} + +impl <T : ?Sized >Drop for MutexGuard <'_,T > { +fn drop (&mut self) { +// SAFETY: self.mutex is locked and are about to release it. +unsafe { bindings::ww_mutex_unlock (self.mutex.inner.get ()) }; + } +} + +// SAFETY: `MutexGuard` can be shared between threads if the data can. +unsafe impl <T : ?Sized +Sync >Sync for MutexGuard <'_,T > {} + +/// Locking kinds used by [`lock_common`] to unify the internal +/// locking logic. +/// +/// It's best not to expose this type (and [`lock_common`]) to the +/// kernel, as it allows internal API changes without worrying +/// about breaking external compatibility. +#[derive( Copy , Clone , Debug )] +enum LockKind { +/// Blocks until lock is acquired. +Regular , +/// Blocks but can be interrupted by signals. +Interruptible , +/// Used in slow path after deadlock detection. +Slow , +/// Slow path but interruptible. +SlowInterruptible , +/// Does not block, returns immediately if busy. +Try , +} + +/// Internal helper that unifies the different locking kinds. +/// +/// Returns [`EINVAL`] if the [`Mutex`] has a different [`Class`]. +fn lock_common <'a,T : ?Sized >( + mutex: &'aMutex <'a,T >, + ctx:Option <&AcquireCtx <'_>>, + kind:LockKind , +) ->Result <MutexGuard <'a,T >> { +let mutex_ptr = mutex.inner.get (); + +let ctx_ptr =match ctx { +Some (acquire_ctx) => { +let ctx_ptr = acquire_ctx.inner.get (); + +// SAFETY: `ctx_ptr` is a valid pointer for the entire +// lifetime of `ctx`. +let ctx_class =unsafe { (*ctx_ptr).ww_class }; + +// SAFETY: `mutex_ptr` is a valid pointer for the entire +// lifetime of `mutex`. +let mutex_class =unsafe { (*mutex_ptr).ww_class }; + +// `ctx` and `mutex` must use the same class. +if ctx_class != mutex_class { +return Err (EINVAL ); + } + + ctx_ptr + } +None => core::ptr::null_mut (), + }; + +match kind { +LockKind ::Regular => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Interruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Slow => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +unsafe { bindings::ww_mutex_lock_slow (mutex_ptr, ctx_ptr) }; + } +LockKind ::SlowInterruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_slow_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Try => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_trylock (mutex_ptr, ctx_ptr) }; + +if ret ==0 { +return Err (EBUSY ); + }else { +to_result (ret)?; + } + } + }; + +Ok (MutexGuard ::new (mutex)) +} + +#[kunit_tests(rust_kernel_ww_mutex)] +mod tests { +use crate ::prelude::*; +use crate ::sync::Arc ; +use crate ::{define_wd_class, define_ww_class}; + +use super ::*; + +define_ww_class! (TEST_WOUND_WAIT_CLASS ); +define_wd_class! (TEST_WAIT_DIE_CLASS ); + +#[test] +fn test_ww_mutex_basic_lock_unlock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (42 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +let guard = ctx.lock (&mutex)?; +assert_eq! (*guard,42 ); + +// Drop the lock. +drop (guard); + +let mut guard = ctx.lock (&mutex)?; + *guard =100 ; +assert_eq! (*guard,100 ); + +Ok (()) + } + +#[test] +fn test_ww_mutex_trylock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (123 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// `try_lock` on unlocked mutex should succeed. +let guard = ctx.try_lock (&mutex)?; +assert_eq! (*guard,123 ); + +// Now it should fail immediately as it's already locked. +assert! (ctx.try_lock (&mutex).is_err ()); + +Ok (()) + } + +#[test] +fn test_ww_mutex_is_locked () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ("hello" , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +// Should not be locked initially. +assert! (!mutex.is_locked ()); + +let guard = ctx.lock (&mutex)?; +assert! (mutex.is_locked ()); + +drop (guard); +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_ww_acquire_context_done () ->Result { +let mutex1 =Arc ::pin_init (Mutex ::new (1 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let mutex2 =Arc ::pin_init (Mutex ::new (2 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// Acquire multiple mutexes with the same context. +let guard1 = ctx.lock (&mutex1)?; +let guard2 = ctx.lock (&mutex2)?; + +assert_eq! (*guard1,1 ); +assert_eq! (*guard2,2 ); + +// SAFETY: It's called exactly once here and nowhere else. +unsafe { ctx.done () }; + +// We shouldn't be able to lock once it's `done`. +assert! (ctx.lock (&mutex1).is_err ()); +assert! (ctx.lock (&mutex2).is_err ()); + +Ok (()) + } + +#[test] +fn test_mutex_without_ctx () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (100 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let guard = mutex.lock ()?; + +assert_eq! (*guard,100 ); +assert! (mutex.is_locked ()); + +drop (guard); + +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_guard_from_raw_with_unlocked_mutex () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ((), &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +assert! (!mutex.is_locked ()); + +// SAFETY: `mutex` remains valid for the duration of this test. +match unsafe {MutexGuard ::from_raw (mutex.inner.get ()) } { +// Should fail with `EINVAL` because the mutex is not locked. +Err (e) =>assert_eq! (e,EINVAL ), + _ =>unreachable! (), + }; + +Ok (()) + } +} +>>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)
rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs new file +172 -0
172 lines not on this page · raw message
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v9 7/7 MAINTAINERS: add Onur Özkan as WW MUTEX maintainer
In reply to Onur ÖzkanAdd myself as a WW MUTEX maintainer to reflect ongoing work and future maintenance of WW MUTEX.
--- MAINTAINERS | 1 + 1 file changed, 1 insertion(+)
MAINTAINERS +1 -0
@@ -14711,6 +14711,7 @@ M: Peter Zijlstra <[email protected]> M: Ingo Molnar <[email protected]> M: Will Deacon <[email protected]> M: Boqun Feng <[email protected]> (LOCKDEP & RUST) +M: Onur Özkan <[email protected]> (WW MUTEX) R: Waiman Long <[email protected]> L: [email protected] S: Maintained
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v9 6/7 rust: ww_mutex: implement LockSet
In reply to Onur ÖzkanLockSet is a high-level and safe API built on top of ww_mutex which provides a safe and easy to use API while keeping the ww_mutex semantics.
When EDEADLK is hit it drops all held locks, resets the acquire context and retries the given (by the user) locking algorithm until it succeeds.
--- rust/kernel/sync/lock/ww_mutex.rs | 6 + rust/kernel/sync/lock/ww_mutex/lock_set.rs | 370 +++++++++++++++++++++ 2 files changed, 376 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex/lock_set.rs
rust/kernel/sync/lock/ww_mutex.rs +6 -0
@@ -6,6 +6,10 @@//! that belong to the same [`Class`]. Each lock acquisition uses an //! [`AcquireCtx`] to track ordering and ensure forward progress. //! +//! It is recommended to use [`LockSet`] as it provides safe high-level +//! interface that automatically handles deadlocks, retries and context +//! management. +//! //! See srctree/Documentation/locking/ww-mutex-design.rst for more details. use crate ::error::to_result;
@@ -18,10 +22,12 @@pub use acquire_ctx::AcquireCtx ;pub use class::Class ; +pub use lock_set::LockSet ;mod class;mod acquire_ctx;mod class; +mod lock_set;/// A wound-wait (ww) mutex that is powered with deadlock avoidance /// when acquiring multiple locks of the same [`Class`].
rust/kernel/sync/lock/ww_mutex/lock_set.rs new file +370 -0
370 lines not on this page · raw message
Signature · 1 line
2.51.2
Onur Özkan
reviewerv9 cover rust: add ww_mutex support
Changes in v9:
- Added __rust_helper prefixes to ww_mutex.c.
- Reworked on Class to remove pinned initialization functions and added documentation suggesting its use as a global variable as this is its only usage on the C side.
- Added myself as a maintainer of WW Mutex.
- Various minor updates (commit description updates, minor code rearrangements, etc.).
Changes in v8:
- Various minor updates (e.g., doc updates, removing unnecessary lifetime annotations, etc.).
- Changed C implementation to always provide ww_class field in ww_mutex and ww_acquire_ctx types so we can access it from Rust easily.
- Locking functions are now safe to call.
- Added class validation logic to ww_mutex::lock_common.
Changes in v7:
- Split Class and AcquireCtx into separate modules.
- Removed "Ww" prefixes from type names.
- Renamed exec.rs -> lock_set.rs and ExecContext -> LockSet.
- Removed transmute logic from LockSet (formerly ExecContext).
- Improved various doc-comments.
- Marked certain AcquireCtx functions as unsafe.
- Added from_raw constructors for Mutex, MutexGuard, AcquireCtx and Class.
- LockSet::cleanup_on_deadlock no longer triggers reallocations when reinitializing AcquireCtx.
- Incorporated various minor improvements suggested on the v6 series.
Changes in v6:
- Added unpinned_new constructor for WwClass and updated global macros.
- Changed all tests (and docs) to use Arc/KBox instead of stack_pin_init for WwMutex and WwAcquireCtx.
- Added LockKind and lock_common helper to unify locking logic.
- Added context-based and context-free locking functions for WwMutex.
- Added ww_mutex/exec module, a high-level API with auto EDEADLK handling mechanism.
Changes in v5:
- Addressed documentation review notes.
- Removed unwrap()s in examples and KUnit tests.
Onur Özkan (7):
rust: add C wrappers for ww_mutex inline functions
ww_mutex: add ww_class field unconditionally
rust: error: add EDEADLK
rust: implement Class for ww_class support
rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
rust: ww_mutex: implement LockSet
MAINTAINERS: add Onur Özkan as WW MUTEX maintainer
MAINTAINERS | 2 + include/linux/ww_mutex.h | 8 +- rust/helpers/helpers.c | 1 + rust/helpers/ww_mutex.c | 45 ++ rust/kernel/error.rs | 1 + rust/kernel/sync/lock.rs | 1 + rust/kernel/sync/lock/ww_mutex.rs | 446 ++++++++++++++++++ rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs | 172 +++++++ rust/kernel/sync/lock/ww_mutex/class.rs | 139 ++++++ rust/kernel/sync/lock/ww_mutex/lock_set.rs | 370 +++++++++++++++ 10 files changed, 1179 insertions(+), 6 deletions(-) create mode 100644 rust/helpers/ww_mutex.c create mode 100644 rust/kernel/sync/lock/ww_mutex.rs create mode 100644 rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs create mode 100644 rust/kernel/sync/lock/ww_mutex/class.rs create mode 100644 rust/kernel/sync/lock/ww_mutex/lock_set.rs
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v9 1/7 rust: add C wrappers for ww_mutex inline functions
Some of the kernel's ww_mutex functions are implemented as static inline, so they are inaccessible from Rust as bindgen can't generate code on them. This patch provides C function wrappers around these inline implementations, so bindgen can see them and generate the corresponding Rust code.
--- MAINTAINERS | 1 + rust/helpers/helpers.c | 1 + rust/helpers/ww_mutex.c | 45 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 rust/helpers/ww_mutex.c
MAINTAINERS +1 -0
@@ -14728,6 +14728,7 @@ F: kernel/locking/ F: lib/locking*.[ch] F: rust/helpers/mutex.c F: rust/helpers/spinlock.c +F: rust/helpers/ww_mutex.c F: rust/kernel/sync/lock.rs F: rust/kernel/sync/lock/ F: rust/kernel/sync/locked_by.rs
rust/helpers/helpers.c +1 -0
@@ -61,4 +61,5 @@#include "vmalloc.c" #include "wait.c" #include "workqueue.c" +#include "ww_mutex.c" #include "xarray.c"
rust/helpers/ww_mutex.c new file +45 -0
45 lines not on this page · raw message
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v9 2/7 ww_mutex: add ww_class field unconditionally
In reply to Onur ÖzkanRemoves DEBUG_WW_MUTEXES guard around the ww_class field in struct ww_mutex and struct ww_acquire_ctx to always initialize it.
Keeping the class pointer available unconditionally allows Rust abstractions to keep from_raw() simple on Mutex and AcquireCtx, simplify AcquireCtx reinitialization logic and validate Mutex and AcquireCtx class pairing in much simpler way.
--- include/linux/ww_mutex.h | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-)
include/linux/ww_mutex.h +2 -6
@@ -47,9 +47,7 @@ struct ww_class {struct ww_mutex {struct WW_MUTEX_BASE base;struct ww_acquire_ctx *ctx; -#ifdef DEBUG_WW_MUTEXES struct ww_class *ww_class; -#endif };struct ww_acquire_ctx {
@@ -58,9 +56,9 @@ struct ww_acquire_ctx {unsigned int acquired;unsigned short wounded;unsigned short is_wait_die; +struct ww_class *ww_class;#ifdef DEBUG_WW_MUTEXES unsigned int done_acquire; -struct ww_class *ww_class;void *contending_lock;#endif #ifdef CONFIG_DEBUG_LOCK_ALLOC
@@ -110,9 +108,7 @@ static inline void ww_mutex_init(struct ww_mutex *lock, {ww_mutex_base_init (&lock->base, ww_class->mutex_name, &ww_class->mutex_key); lock->ctx =NULL ; -#ifdef DEBUG_WW_MUTEXES lock->ww_class = ww_class; -#endif }/**
@@ -147,8 +143,8 @@ static inline void ww_acquire_init(struct ww_acquire_ctx *ctx, ctx->acquired =0 ; ctx->wounded = false; ctx->is_wait_die = ww_class->is_wait_die; -#ifdef DEBUG_WW_MUTEXES ctx->ww_class = ww_class; +#ifdef DEBUG_WW_MUTEXES ctx->done_acquire =0 ; ctx->contending_lock =NULL ;#endif
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v9 4/7 rust: implement Class for ww_class support
In reply to Onur ÖzkanAdds the Class type, the first step in supporting ww_mutex in Rust. Class represents ww_class, used for deadlock avoidance for supporting both wait-die and wound-wait semantics.
Also adds the define_class macro for safely declaring static instances.
--- rust/kernel/sync/lock.rs | 1 + rust/kernel/sync/lock/ww_mutex.rs | 7 ++ rust/kernel/sync/lock/ww_mutex/class.rs | 139 ++++++++++++++++++++++++ 3 files changed, 147 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex.rs create mode 100644 rust/kernel/sync/lock/ww_mutex/class.rs
rust/kernel/sync/lock.rs +1 -0
@@ -15,6 +15,7 @@pub mod mutex;pub mod spinlock; +pub mod ww_mutex;pub (super )mod global;pub use global::{GlobalGuard ,GlobalLock ,GlobalLockBackend ,GlobalLockedBy };
rust/kernel/sync/lock/ww_mutex.rs new file +7 -0
@@ -0,0 +1,7 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust abstractions for the kernel's wound-wait locking primitives. + +pub use class::Class ; + +mod class;
rust/kernel/sync/lock/ww_mutex/class.rs new file +139 -0
139 lines not on this page · raw message
Signature · 1 line
2.51.2
Onur Özkan
reviewerPATCH v9 3/7 rust: error: add EDEADLK
In reply to Onur ÖzkanThis is needed for the ww_mutex implementation so
we can handle EDEADLK on lock attempts.
--- rust/kernel/error.rs | 1 + 1 file changed, 1 insertion(+)
rust/kernel/error.rs +1 -0
@@ -66,6 +66,7 @@ macro_rules! declare_err {declare_err! (EPIPE ,"Broken pipe." );declare_err! (EDOM ,"Math argument out of domain of func." );declare_err! (ERANGE ,"Math result not representable." ); +declare_err! (EDEADLK ,"Resource deadlock avoided." );declare_err! (EOVERFLOW ,"Value too large for defined data type." );declare_err! (ETIMEDOUT ,"Connection timed out." );declare_err! (ERESTARTSYS ,"Restart the system call." );
Signature · 1 line
2.51.2
Re: [PATCH v9 3/7] rust: error: add EDEADLK
Quoted 4 lines · On Fri, 2 Jan 2026 20:52:58 +0300 Onur Özkan <[email protected]> wrote:
This is needed for the
ww_muteximplementation so
we can handle EDEADLK on lock attempts.Signed-off-by Onur Özkan <[email protected]>
I forgot to include
tags from the v7 series for this file. :(
Quoted 16 lines
--- rust/kernel/error.rs | 1 + 1 file changed, 1 insertion(+)rust/kernel/error.rs +1
-0@@ -66,6 +66,7 @@ macro_rules! declare_err {declare_err! (EPIPE ,"Broken pipe." );declare_err! (EDOM ,"Math argument out of domain of func." );declare_err! (ERANGE ,"Math result not representable." ); +declare_err! (EDEADLK ,"Resource deadlock avoided." );declare_err! (EOVERFLOW ,"Value too large for defined data type." );declare_err! (ETIMEDOUT ,"Connection timed out." );declare_err! (ERESTARTSYS ,"Restart the system call." );
kernel test robot
build botRe: [PATCH v9 5/7] rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
In reply to Onur Özkankernel test robot noticed the following build errors:
Hi Onur,
kernel test robot noticed the following build errors:
[auto build test ERROR on tip/locking/core]
[also build test ERROR on rust/rust-next linus/master v6.16-rc1 next-20251219] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Onur-zkan/rust-add-C-wrappers-for-ww_mutex-inline-functions/20260103-021353 base: tip/locking/core patch link: https://lore.kernel.org/r/20260102175302.194435-6-work%40onurozkan.dev patch subject: [PATCH v9 5/7] rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260103/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) rustc: rustc 1.88.0 (6b00bc388 2025-06-23) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260103/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
PATH=/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INFO PATH=/opt/cross/rustc-1.88.0-bindgen-0.72.1/cargo/bin:/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS= -fno-crash-diagnostics -Wno-error=return-type -Wreturn-type -funsigned-char -Wundef W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck
make: Entering directory '/kbuild/src/consumer'
make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
>> error: expected item, found `>>`
--> rust/kernel/sync/lock/ww_mutex.rs:440:1
|
440 | >>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)
| ^^ expected item
|
= note: for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>
--
>> error: expected item, found `>>`
--> rust/kernel/sync/lock/ww_mutex.rs:440:1
|
440 | >>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)
| ^^ expected item
|
= note: for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>
--
Error writing files: failed to resolve mod ww_mutex: cannot parse rust/kernel/sync/lock/ww_mutex.rs
>> error: expected item, found `>>`
--> rust/kernel/sync/lock/ww_mutex.rs:440:1
|
440 | >>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)
| ^^ expected item
|
= note: for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Boqun Feng
maintainerRe: [PATCH v9 5/7] rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
In reply to Onur ÖzkanQuoted 59 lines · Onur Özkan
Covers the entire low-level locking API (lock,
try_lock, slow path, interruptible variants) and integration with kernel bindings.Signed-off-by Onur Özkan <[email protected]>--- rust/kernel/sync/lock/ww_mutex.rs | 433 ++++++++++++++++++ rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs | 172 +++++++ 2 files changed, 605 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex/acquire_ctx.rsrust/kernel/sync/lock/ww_mutex.rs +36
-0@@ -1,7 +1,440 @@// SPDX-License-Identifier: GPL-2.0 //! Rust abstractions for the kernel's wound-wait locking primitives. +//! +//! It is designed to avoid deadlocks when locking multiple [`Mutex`]es +//! that belong to the same [`Class`]. Each lock acquisition uses an +//! [`AcquireCtx`] to track ordering and ensure forward progress. +//! +//! See srctree/Documentation/locking/ww-mutex-design.rst for more details. +use crate ::error::to_result; +use crate ::prelude::*; +use crate ::types::{NotThreadSafe ,Opaque }; +use crate ::{bindings, container_of}; + +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; + +pub use acquire_ctx::AcquireCtx ;pub use class::Class ;mod class; +mod acquire_ctx; +mod class; + +/// A wound-wait (ww) mutex that is powered with deadlock avoidance +/// when acquiring multiple locks of the same [`Class`]. +/// +/// Each mutex belongs to a [`Class`], which the wound-wait algorithm +/// uses to figure out the order of acquisition and prevent deadlocks. +/// +/// # Examples +/// +/// ``` +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use kernel::sync::lock::ww_mutex::{AcquireCtx, Class, Mutex}; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// let mutex = Arc::pin_init(Mutex::new(42, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?;
rust/kernel/sync/lock/ww_mutex.rs line 53
Quoted 10 lines
rust/kernel/sync/lock/ww_mutex.rs +10
-0+/// +/// let guard = ctx.lock(&mutex)?; +/// assert_eq!(*guard, 42); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data] +#[repr( C )] +pub struct Mutex <'a,T : ?Sized > { + _p:PhantomData <&'aClass >,
We should be able to do:
class: &'a Class,
then we don't need to patch #2 in the series, right?
Regards,
Boqun
Quoted 568 lines
rust/kernel/sync/lock/ww_mutex.rs +387
-0+#[pin] + inner: Opaque<bindings::ww_mutex>, + data: UnsafeCell<T>, +} + +impl <'class,T >Mutex <'class,T > { +/// Initializes [`Mutex`] with the given `data` and [`Class`]. +pub fn new (data:T , class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (Mutex { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_mutex | { +// SAFETY: `class` is valid for the lifetime `'class` captured by `Self`. +unsafe { bindings::ww_mutex_init (slot, class_ptr) } + }), + data:UnsafeCell ::new (data), + _p:PhantomData + }) + } +} + +impl <'class,T : ?Sized >Mutex <'class,T > { +/// Checks if this [`Mutex`] is currently locked. +/// +/// The returned value is racy as another thread can acquire +/// or release the lock immediately after this call returns. +pub fn is_locked (&self) ->bool { +// SAFETY: It's safe to call `ww_mutex_is_locked` on +// a valid mutex. +unsafe { bindings::ww_mutex_is_locked (self.inner.get ()) } + } + +/// Locks this [`Mutex`] without [`AcquireCtx`]. +pub fn lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Interruptible ) + } + +/// Locks this [`Mutex`] without [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::SlowInterruptible ) + } + +/// Tries to lock this [`Mutex`] with no [`AcquireCtx`] and without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Try ) + } +} + +impl <'class>Mutex <'class, ()> { +/// Creates a [`Mutex`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'a`. +/// - ww_class associated with this mutex must be valid for +/// the lifetime `'class`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_mutex ) -> &'aSelf { +// SAFETY: By the safety contract, the caller guarantees that `ptr` +// points to a valid `ww_mutex` which is the `inner` field of `Mutex`, +// that it remains valid for the lifetime `'a` and the associated +// ww_class outlives `'class`. +// +// Because [`Mutex`] is `#[repr(C)]`, the `inner` field sits at a +// stable offset that `container_of!` can safely rely on. +unsafe { &*container_of! (Opaque ::cast_from (ptr),Self , inner) } + } +} + +// SAFETY: `Mutex` can be sent to another thread if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send >Send for Mutex <'_,T > {} + +// SAFETY: `Mutex` can be shared across threads if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send +Sync >Sync for Mutex <'_,T > {} + +/// A guard that provides exclusive access to the data protected +/// by a [`Mutex`]. +/// +/// # Invariants +/// +/// The guard holds an exclusive lock on the associated [`Mutex`]. The lock is held +/// for the entire lifetime of this guard and is automatically released when the +/// guard is dropped. +#[must_use = "the lock unlocks immediately when the guard is unused" ] +pub struct MutexGuard <'a,T : ?Sized > { + mutex: &'aMutex <'a,T >, + _not_send:NotThreadSafe , +} + +impl <'a,T : ?Sized >MutexGuard <'a,T > { +/// Creates a new guard for the given [`Mutex`]. +fn new (mutex: &'aMutex <'a,T >) ->Self { +assert! (mutex.is_locked ()); + +Self { + mutex, + _not_send:NotThreadSafe , + } + } +} + +impl <'a>MutexGuard <'a, ()> { +/// Creates a [`MutexGuard`] from a raw pointer. +/// +/// If the given pointer refers to a mutex that is not locked, +/// returns [`EINVAL`]. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'b`. +/// - The `ww_class` associated with the `ww_mutex` must be valid for the lifetime `'b`. +pub unsafe fn from_raw <'b>(ptr: *mut bindings::ww_mutex ) ->Result <MutexGuard <'b, ()>> { +// SAFETY: By this function's safety contract, the caller guarantees that `ptr` points to a +// valid `ww_mutex` which is the `inner` field of a `Mutex`. The caller also guarantees +// that both `ptr` and the associated `ww_class` are valid for the lifetime `'b`. +let mutex =unsafe {Mutex ::from_raw (ptr) }; + +if !mutex.is_locked () { +return Err (EINVAL ); + } + +Ok (MutexGuard ::new (mutex)) + } +} + +impl <T : ?Sized > core::ops::Deref for MutexGuard <'_,T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &*self.mutex.data.get () } + } +} + +impl <T : ?Sized +Unpin > core::ops::DerefMut for MutexGuard <'_,T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &mut *self.mutex.data.get () } + } +} + +impl <T : ?Sized >Drop for MutexGuard <'_,T > { +fn drop (&mut self) { +// SAFETY: self.mutex is locked and are about to release it. +unsafe { bindings::ww_mutex_unlock (self.mutex.inner.get ()) }; + } +} + +// SAFETY: `MutexGuard` can be shared between threads if the data can. +unsafe impl <T : ?Sized +Sync >Sync for MutexGuard <'_,T > {} + +/// Locking kinds used by [`lock_common`] to unify the internal +/// locking logic. +/// +/// It's best not to expose this type (and [`lock_common`]) to the +/// kernel, as it allows internal API changes without worrying +/// about breaking external compatibility. +#[derive( Copy , Clone , Debug )] +enum LockKind { +/// Blocks until lock is acquired. +Regular , +/// Blocks but can be interrupted by signals. +Interruptible , +/// Used in slow path after deadlock detection. +Slow , +/// Slow path but interruptible. +SlowInterruptible , +/// Does not block, returns immediately if busy. +Try , +} + +/// Internal helper that unifies the different locking kinds. +/// +/// Returns [`EINVAL`] if the [`Mutex`] has a different [`Class`]. +fn lock_common <'a,T : ?Sized >( + mutex: &'aMutex <'a,T >, + ctx:Option <&AcquireCtx <'_>>, + kind:LockKind , +) ->Result <MutexGuard <'a,T >> { +let mutex_ptr = mutex.inner.get (); + +let ctx_ptr =match ctx { +Some (acquire_ctx) => { +let ctx_ptr = acquire_ctx.inner.get (); + +// SAFETY: `ctx_ptr` is a valid pointer for the entire +// lifetime of `ctx`. +let ctx_class =unsafe { (*ctx_ptr).ww_class }; + +// SAFETY: `mutex_ptr` is a valid pointer for the entire +// lifetime of `mutex`. +let mutex_class =unsafe { (*mutex_ptr).ww_class }; + +// `ctx` and `mutex` must use the same class. +if ctx_class != mutex_class { +return Err (EINVAL ); + } + + ctx_ptr + } +None => core::ptr::null_mut (), + }; + +match kind { +LockKind ::Regular => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Interruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Slow => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +unsafe { bindings::ww_mutex_lock_slow (mutex_ptr, ctx_ptr) }; + } +LockKind ::SlowInterruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_slow_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Try => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_trylock (mutex_ptr, ctx_ptr) }; + +if ret ==0 { +return Err (EBUSY ); + }else { +to_result (ret)?; + } + } + }; + +Ok (MutexGuard ::new (mutex)) +} + +#[kunit_tests(rust_kernel_ww_mutex)] +mod tests { +use crate ::prelude::*; +use crate ::sync::Arc ; +use crate ::{define_wd_class, define_ww_class}; + +use super ::*; + +define_ww_class! (TEST_WOUND_WAIT_CLASS ); +define_wd_class! (TEST_WAIT_DIE_CLASS ); + +#[test] +fn test_ww_mutex_basic_lock_unlock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (42 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +let guard = ctx.lock (&mutex)?; +assert_eq! (*guard,42 ); + +// Drop the lock. +drop (guard); + +let mut guard = ctx.lock (&mutex)?; + *guard =100 ; +assert_eq! (*guard,100 ); + +Ok (()) + } + +#[test] +fn test_ww_mutex_trylock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (123 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// `try_lock` on unlocked mutex should succeed. +let guard = ctx.try_lock (&mutex)?; +assert_eq! (*guard,123 ); + +// Now it should fail immediately as it's already locked. +assert! (ctx.try_lock (&mutex).is_err ()); + +Ok (()) + } + +#[test] +fn test_ww_mutex_is_locked () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ("hello" , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +// Should not be locked initially. +assert! (!mutex.is_locked ()); + +let guard = ctx.lock (&mutex)?; +assert! (mutex.is_locked ()); + +drop (guard); +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_ww_acquire_context_done () ->Result { +let mutex1 =Arc ::pin_init (Mutex ::new (1 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let mutex2 =Arc ::pin_init (Mutex ::new (2 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// Acquire multiple mutexes with the same context. +let guard1 = ctx.lock (&mutex1)?; +let guard2 = ctx.lock (&mutex2)?; + +assert_eq! (*guard1,1 ); +assert_eq! (*guard2,2 ); + +// SAFETY: It's called exactly once here and nowhere else. +unsafe { ctx.done () }; + +// We shouldn't be able to lock once it's `done`. +assert! (ctx.lock (&mutex1).is_err ()); +assert! (ctx.lock (&mutex2).is_err ()); + +Ok (()) + } + +#[test] +fn test_mutex_without_ctx () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (100 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let guard = mutex.lock ()?; + +assert_eq! (*guard,100 ); +assert! (mutex.is_locked ()); + +drop (guard); + +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_guard_from_raw_with_unlocked_mutex () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ((), &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +assert! (!mutex.is_locked ()); + +// SAFETY: `mutex` remains valid for the duration of this test. +match unsafe {MutexGuard ::from_raw (mutex.inner.get ()) } { +// Should fail with `EINVAL` because the mutex is not locked. +Err (e) =>assert_eq! (e,EINVAL ), + _ =>unreachable! (), + }; + +Ok (()) + } +} +>>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs new file +172
-0@@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Provides [`AcquireCtx`] for managing multiple wound/wait +//! mutexes from the same [`Class`]. + +use crate ::bindings; +use crate ::prelude::*; +use crate ::types::Opaque ; + +use core::marker::PhantomData ; + +use super ::{lock_common,Class ,LockKind ,Mutex ,MutexGuard }; + +/// Groups multiple [`Mutex`]es for deadlock avoidance when acquired +/// with the same [`Class`]. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::lock::ww_mutex::{Class, AcquireCtx, Mutex}; +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// // Create mutexes. +/// let mutex1 = Arc::pin_init(Mutex::new(1, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let mutex2 = Arc::pin_init(Mutex::new(2, &SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// // Create acquire context for deadlock avoidance. +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// let guard1 = ctx.lock(&mutex1)?; +/// let guard2 = ctx.lock(&mutex2)?; +/// +/// // Mark acquisition phase as complete. +/// // SAFETY: It's called exactly once here and nowhere else. +/// unsafe { ctx.done() }; +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data( PinnedDrop )] +#[repr(transparent)] +pub struct AcquireCtx <'a> { +#[pin] +pub (super ) inner:Opaque <bindings::ww_acquire_ctx >, + _p:PhantomData <&'aClass >, +} + +impl <'class>AcquireCtx <'class> { +/// Initializes a new [`AcquireCtx`] with the given [`Class`]. +pub fn new (class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (AcquireCtx { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_acquire_ctx | { +// SAFETY: `class` is valid for the lifetime `'class` captured +// by `AcquireCtx`. +unsafe { bindings::ww_acquire_init (slot, class_ptr) } + }), + _p:PhantomData + }) + } + +/// Creates a [`AcquireCtx`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is a valid pointer to the `inner` field +/// of [`AcquireCtx`] and that it remains valid for the lifetime `'a`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_acquire_ctx ) -> &'aSelf { +// SAFETY: By the safety contract, `ptr` is valid to construct `AcquireCtx`. +unsafe { &*ptr.cast () } + } + +/// Marks the end of the acquire phase. +/// +/// Calling this function is optional. It is just useful to document +/// the code and clearly designated the acquire phase from actually +/// using the locked data structures. +/// +/// After calling this function, no more mutexes can be acquired with +/// this context. +/// +/// # Safety +/// +/// The caller must ensure that this function is called only once +/// and after calling it, no further mutexes are acquired using +/// this context. +pub unsafe fn done (&self) { +// SAFETY: By the safety contract, the caller guarantees that this +// function is called only once. +unsafe { bindings::ww_acquire_done (self.inner.get ()) }; + } + +/// Re-initializes the [`AcquireCtx`]. +/// +/// Must be called after releasing all locks when [`EDEADLK`] occurs. +/// +/// # Safety +/// +/// The caller must ensure no locks are held in this [`AcquireCtx`]. +pub unsafe fn reinit (self:Pin <&mut Self >) { +let ctx = self.inner.get (); + +// SAFETY: `ww_class` is always a valid pointer in properly initialized +// `AcquireCtx`. +let class_ptr =unsafe { (*ctx).ww_class }; + +// SAFETY: +// - Lifetime of any guard (which hold an immutable borrow of `self`) cannot overlap +// with the execution of this function. This enforces that all locks acquired via +// this context have been released. +// +// - `ctx` is guaranteed to be initialized because `ww_acquire_fini` +// can only be called from the `Drop` implementation. +// +// - `ww_acquire_fini` is safe to call on an initialized context. +unsafe { bindings::ww_acquire_fini (ctx) }; + +// SAFETY: `ww_acquire_init` is safe to call with valid pointers +// to initialize an uninitialized context. +unsafe { bindings::ww_acquire_init (ctx, class_ptr) }; + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`]. +pub fn lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Interruptible ) + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::SlowInterruptible ) + } + +/// Tries to lock the [`Mutex`] on this [`AcquireCtx`] without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Try ) + } +} + +#[pinned_drop] +impl PinnedDrop for AcquireCtx <'_> { +fn drop (self:Pin <&mut Self >) { +// SAFETY: Given the lifetime bounds we know no locks are held, +// so calling `ww_acquire_fini` is safe. +unsafe { bindings::ww_acquire_fini (self.inner.get ()) }; + } +}Signature · 1 line
2.51.2
Onur Özkan
reviewerRe: [PATCH v9 5/7] rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
Quoted 73 lines · On Tue, 22 Sep 2026 10:54:22 +0200 Boqun Feng <[email protected]> wrote:
Quoted 59 lines · Onur Özkan
Covers the entire low-level locking API (lock,
try_lock, slow path, interruptible variants) and integration with kernel bindings.Signed-off-by Onur Özkan <[email protected]>--- rust/kernel/sync/lock/ww_mutex.rs | 433 ++++++++++++++++++ rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs | 172 +++++++ 2 files changed, 605 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex/acquire_ctx.rsrust/kernel/sync/lock/ww_mutex.rs +36
-0@@ -1,7 +1,440 @@// SPDX-License-Identifier: GPL-2.0 //! Rust abstractions for the kernel's wound-wait locking primitives. +//! +//! It is designed to avoid deadlocks when locking multiple [`Mutex`]es +//! that belong to the same [`Class`]. Each lock acquisition uses an +//! [`AcquireCtx`] to track ordering and ensure forward progress. +//! +//! See srctree/Documentation/locking/ww-mutex-design.rst for more details. +use crate ::error::to_result; +use crate ::prelude::*; +use crate ::types::{NotThreadSafe ,Opaque }; +use crate ::{bindings, container_of}; + +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; + +pub use acquire_ctx::AcquireCtx ;pub use class::Class ;mod class; +mod acquire_ctx; +mod class; + +/// A wound-wait (ww) mutex that is powered with deadlock avoidance +/// when acquiring multiple locks of the same [`Class`]. +/// +/// Each mutex belongs to a [`Class`], which the wound-wait algorithm +/// uses to figure out the order of acquisition and prevent deadlocks. +/// +/// # Examples +/// +/// ``` +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use kernel::sync::lock::ww_mutex::{AcquireCtx, Class, Mutex}; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// let mutex = Arc::pin_init(Mutex::new(42, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; rust/kernel/sync/lock/ww_mutex.rs line 53
Quoted 10 lines
rust/kernel/sync/lock/ww_mutex.rs +10
-0+/// +/// let guard = ctx.lock(&mutex)?; +/// assert_eq!(*guard, 42); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data] +#[repr( C )] +pub struct Mutex <'a,T : ?Sized > { + _p:PhantomData <&'aClass >,We should be able to do:
Quoted 7 lines
class: &'a Class,
then we don't need to patch #2 in the series, right?
Regards,
Boqun
I assume you are suggesting passing the Class reference to from_raw() functions as well?
If so, we discussed this in previous revisions. Daniel suggested passing the class explicitly to from_raw() as an alternative [1]. We then discussed that approach versus making the C fields unconditional and both Lyude and Daniel supported the C change [2].
That is the rationale for patch #2, it lets us validate class pairing while keeping from_raw() simple for existing C objects.
It also keeps AcquireCtx::reinit() simpler by letting it recover the original class without requiring the caller to supply it again.
[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/[email protected]
Thanks,
Onur
Quoted 568 lines
Quoted 568 lines
rust/kernel/sync/lock/ww_mutex.rs +387
-0+#[pin] + inner: Opaque<bindings::ww_mutex>, + data: UnsafeCell<T>, +} + +impl <'class,T >Mutex <'class,T > { +/// Initializes [`Mutex`] with the given `data` and [`Class`]. +pub fn new (data:T , class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (Mutex { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_mutex | { +// SAFETY: `class` is valid for the lifetime `'class` captured by `Self`. +unsafe { bindings::ww_mutex_init (slot, class_ptr) } + }), + data:UnsafeCell ::new (data), + _p:PhantomData + }) + } +} + +impl <'class,T : ?Sized >Mutex <'class,T > { +/// Checks if this [`Mutex`] is currently locked. +/// +/// The returned value is racy as another thread can acquire +/// or release the lock immediately after this call returns. +pub fn is_locked (&self) ->bool { +// SAFETY: It's safe to call `ww_mutex_is_locked` on +// a valid mutex. +unsafe { bindings::ww_mutex_is_locked (self.inner.get ()) } + } + +/// Locks this [`Mutex`] without [`AcquireCtx`]. +pub fn lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Interruptible ) + } + +/// Locks this [`Mutex`] without [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::SlowInterruptible ) + } + +/// Tries to lock this [`Mutex`] with no [`AcquireCtx`] and without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Try ) + } +} + +impl <'class>Mutex <'class, ()> { +/// Creates a [`Mutex`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'a`. +/// - ww_class associated with this mutex must be valid for +/// the lifetime `'class`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_mutex ) -> &'aSelf { +// SAFETY: By the safety contract, the caller guarantees that `ptr` +// points to a valid `ww_mutex` which is the `inner` field of `Mutex`, +// that it remains valid for the lifetime `'a` and the associated +// ww_class outlives `'class`. +// +// Because [`Mutex`] is `#[repr(C)]`, the `inner` field sits at a +// stable offset that `container_of!` can safely rely on. +unsafe { &*container_of! (Opaque ::cast_from (ptr),Self , inner) } + } +} + +// SAFETY: `Mutex` can be sent to another thread if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send >Send for Mutex <'_,T > {} + +// SAFETY: `Mutex` can be shared across threads if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send +Sync >Sync for Mutex <'_,T > {} + +/// A guard that provides exclusive access to the data protected +/// by a [`Mutex`]. +/// +/// # Invariants +/// +/// The guard holds an exclusive lock on the associated [`Mutex`]. The lock is held +/// for the entire lifetime of this guard and is automatically released when the +/// guard is dropped. +#[must_use = "the lock unlocks immediately when the guard is unused" ] +pub struct MutexGuard <'a,T : ?Sized > { + mutex: &'aMutex <'a,T >, + _not_send:NotThreadSafe , +} + +impl <'a,T : ?Sized >MutexGuard <'a,T > { +/// Creates a new guard for the given [`Mutex`]. +fn new (mutex: &'aMutex <'a,T >) ->Self { +assert! (mutex.is_locked ()); + +Self { + mutex, + _not_send:NotThreadSafe , + } + } +} + +impl <'a>MutexGuard <'a, ()> { +/// Creates a [`MutexGuard`] from a raw pointer. +/// +/// If the given pointer refers to a mutex that is not locked, +/// returns [`EINVAL`]. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'b`. +/// - The `ww_class` associated with the `ww_mutex` must be valid for the lifetime `'b`. +pub unsafe fn from_raw <'b>(ptr: *mut bindings::ww_mutex ) ->Result <MutexGuard <'b, ()>> { +// SAFETY: By this function's safety contract, the caller guarantees that `ptr` points to a +// valid `ww_mutex` which is the `inner` field of a `Mutex`. The caller also guarantees +// that both `ptr` and the associated `ww_class` are valid for the lifetime `'b`. +let mutex =unsafe {Mutex ::from_raw (ptr) }; + +if !mutex.is_locked () { +return Err (EINVAL ); + } + +Ok (MutexGuard ::new (mutex)) + } +} + +impl <T : ?Sized > core::ops::Deref for MutexGuard <'_,T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &*self.mutex.data.get () } + } +} + +impl <T : ?Sized +Unpin > core::ops::DerefMut for MutexGuard <'_,T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &mut *self.mutex.data.get () } + } +} + +impl <T : ?Sized >Drop for MutexGuard <'_,T > { +fn drop (&mut self) { +// SAFETY: self.mutex is locked and are about to release it. +unsafe { bindings::ww_mutex_unlock (self.mutex.inner.get ()) }; + } +} + +// SAFETY: `MutexGuard` can be shared between threads if the data can. +unsafe impl <T : ?Sized +Sync >Sync for MutexGuard <'_,T > {} + +/// Locking kinds used by [`lock_common`] to unify the internal +/// locking logic. +/// +/// It's best not to expose this type (and [`lock_common`]) to the +/// kernel, as it allows internal API changes without worrying +/// about breaking external compatibility. +#[derive( Copy , Clone , Debug )] +enum LockKind { +/// Blocks until lock is acquired. +Regular , +/// Blocks but can be interrupted by signals. +Interruptible , +/// Used in slow path after deadlock detection. +Slow , +/// Slow path but interruptible. +SlowInterruptible , +/// Does not block, returns immediately if busy. +Try , +} + +/// Internal helper that unifies the different locking kinds. +/// +/// Returns [`EINVAL`] if the [`Mutex`] has a different [`Class`]. +fn lock_common <'a,T : ?Sized >( + mutex: &'aMutex <'a,T >, + ctx:Option <&AcquireCtx <'_>>, + kind:LockKind , +) ->Result <MutexGuard <'a,T >> { +let mutex_ptr = mutex.inner.get (); + +let ctx_ptr =match ctx { +Some (acquire_ctx) => { +let ctx_ptr = acquire_ctx.inner.get (); + +// SAFETY: `ctx_ptr` is a valid pointer for the entire +// lifetime of `ctx`. +let ctx_class =unsafe { (*ctx_ptr).ww_class }; + +// SAFETY: `mutex_ptr` is a valid pointer for the entire +// lifetime of `mutex`. +let mutex_class =unsafe { (*mutex_ptr).ww_class }; + +// `ctx` and `mutex` must use the same class. +if ctx_class != mutex_class { +return Err (EINVAL ); + } + + ctx_ptr + } +None => core::ptr::null_mut (), + }; + +match kind { +LockKind ::Regular => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Interruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Slow => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +unsafe { bindings::ww_mutex_lock_slow (mutex_ptr, ctx_ptr) }; + } +LockKind ::SlowInterruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_slow_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Try => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_trylock (mutex_ptr, ctx_ptr) }; + +if ret ==0 { +return Err (EBUSY ); + }else { +to_result (ret)?; + } + } + }; + +Ok (MutexGuard ::new (mutex)) +} + +#[kunit_tests(rust_kernel_ww_mutex)] +mod tests { +use crate ::prelude::*; +use crate ::sync::Arc ; +use crate ::{define_wd_class, define_ww_class}; + +use super ::*; + +define_ww_class! (TEST_WOUND_WAIT_CLASS ); +define_wd_class! (TEST_WAIT_DIE_CLASS ); + +#[test] +fn test_ww_mutex_basic_lock_unlock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (42 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +let guard = ctx.lock (&mutex)?; +assert_eq! (*guard,42 ); + +// Drop the lock. +drop (guard); + +let mut guard = ctx.lock (&mutex)?; + *guard =100 ; +assert_eq! (*guard,100 ); + +Ok (()) + } + +#[test] +fn test_ww_mutex_trylock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (123 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// `try_lock` on unlocked mutex should succeed. +let guard = ctx.try_lock (&mutex)?; +assert_eq! (*guard,123 ); + +// Now it should fail immediately as it's already locked. +assert! (ctx.try_lock (&mutex).is_err ()); + +Ok (()) + } + +#[test] +fn test_ww_mutex_is_locked () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ("hello" , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +// Should not be locked initially. +assert! (!mutex.is_locked ()); + +let guard = ctx.lock (&mutex)?; +assert! (mutex.is_locked ()); + +drop (guard); +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_ww_acquire_context_done () ->Result { +let mutex1 =Arc ::pin_init (Mutex ::new (1 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let mutex2 =Arc ::pin_init (Mutex ::new (2 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// Acquire multiple mutexes with the same context. +let guard1 = ctx.lock (&mutex1)?; +let guard2 = ctx.lock (&mutex2)?; + +assert_eq! (*guard1,1 ); +assert_eq! (*guard2,2 ); + +// SAFETY: It's called exactly once here and nowhere else. +unsafe { ctx.done () }; + +// We shouldn't be able to lock once it's `done`. +assert! (ctx.lock (&mutex1).is_err ()); +assert! (ctx.lock (&mutex2).is_err ()); + +Ok (()) + } + +#[test] +fn test_mutex_without_ctx () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (100 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let guard = mutex.lock ()?; + +assert_eq! (*guard,100 ); +assert! (mutex.is_locked ()); + +drop (guard); + +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_guard_from_raw_with_unlocked_mutex () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ((), &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +assert! (!mutex.is_locked ()); + +// SAFETY: `mutex` remains valid for the duration of this test. +match unsafe {MutexGuard ::from_raw (mutex.inner.get ()) } { +// Should fail with `EINVAL` because the mutex is not locked. +Err (e) =>assert_eq! (e,EINVAL ), + _ =>unreachable! (), + }; + +Ok (()) + } +} +>>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs new file +172
-0@@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Provides [`AcquireCtx`] for managing multiple wound/wait +//! mutexes from the same [`Class`]. + +use crate ::bindings; +use crate ::prelude::*; +use crate ::types::Opaque ; + +use core::marker::PhantomData ; + +use super ::{lock_common,Class ,LockKind ,Mutex ,MutexGuard }; + +/// Groups multiple [`Mutex`]es for deadlock avoidance when acquired +/// with the same [`Class`]. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::lock::ww_mutex::{Class, AcquireCtx, Mutex}; +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// // Create mutexes. +/// let mutex1 = Arc::pin_init(Mutex::new(1, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let mutex2 = Arc::pin_init(Mutex::new(2, &SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// // Create acquire context for deadlock avoidance. +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// let guard1 = ctx.lock(&mutex1)?; +/// let guard2 = ctx.lock(&mutex2)?; +/// +/// // Mark acquisition phase as complete. +/// // SAFETY: It's called exactly once here and nowhere else. +/// unsafe { ctx.done() }; +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data( PinnedDrop )] +#[repr(transparent)] +pub struct AcquireCtx <'a> { +#[pin] +pub (super ) inner:Opaque <bindings::ww_acquire_ctx >, + _p:PhantomData <&'aClass >, +} + +impl <'class>AcquireCtx <'class> { +/// Initializes a new [`AcquireCtx`] with the given [`Class`]. +pub fn new (class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (AcquireCtx { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_acquire_ctx | { +// SAFETY: `class` is valid for the lifetime `'class` captured +// by `AcquireCtx`. +unsafe { bindings::ww_acquire_init (slot, class_ptr) } + }), + _p:PhantomData + }) + } + +/// Creates a [`AcquireCtx`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is a valid pointer to the `inner` field +/// of [`AcquireCtx`] and that it remains valid for the lifetime `'a`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_acquire_ctx ) -> &'aSelf { +// SAFETY: By the safety contract, `ptr` is valid to construct `AcquireCtx`. +unsafe { &*ptr.cast () } + } + +/// Marks the end of the acquire phase. +/// +/// Calling this function is optional. It is just useful to document +/// the code and clearly designated the acquire phase from actually +/// using the locked data structures. +/// +/// After calling this function, no more mutexes can be acquired with +/// this context. +/// +/// # Safety +/// +/// The caller must ensure that this function is called only once +/// and after calling it, no further mutexes are acquired using +/// this context. +pub unsafe fn done (&self) { +// SAFETY: By the safety contract, the caller guarantees that this +// function is called only once. +unsafe { bindings::ww_acquire_done (self.inner.get ()) }; + } + +/// Re-initializes the [`AcquireCtx`]. +/// +/// Must be called after releasing all locks when [`EDEADLK`] occurs. +/// +/// # Safety +/// +/// The caller must ensure no locks are held in this [`AcquireCtx`]. +pub unsafe fn reinit (self:Pin <&mut Self >) { +let ctx = self.inner.get (); + +// SAFETY: `ww_class` is always a valid pointer in properly initialized +// `AcquireCtx`. +let class_ptr =unsafe { (*ctx).ww_class }; + +// SAFETY: +// - Lifetime of any guard (which hold an immutable borrow of `self`) cannot overlap +// with the execution of this function. This enforces that all locks acquired via +// this context have been released. +// +// - `ctx` is guaranteed to be initialized because `ww_acquire_fini` +// can only be called from the `Drop` implementation. +// +// - `ww_acquire_fini` is safe to call on an initialized context. +unsafe { bindings::ww_acquire_fini (ctx) }; + +// SAFETY: `ww_acquire_init` is safe to call with valid pointers +// to initialize an uninitialized context. +unsafe { bindings::ww_acquire_init (ctx, class_ptr) }; + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`]. +pub fn lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Interruptible ) + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::SlowInterruptible ) + } + +/// Tries to lock the [`Mutex`] on this [`AcquireCtx`] without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Try ) + } +} + +#[pinned_drop] +impl PinnedDrop for AcquireCtx <'_> { +fn drop (self:Pin <&mut Self >) { +// SAFETY: Given the lifetime bounds we know no locks are held, +// so calling `ww_acquire_fini` is safe. +unsafe { bindings::ww_acquire_fini (self.inner.get ()) }; + } +}Signature · 1 line
2.51.2
Boqun Feng
maintainerRe: [PATCH v9 5/7] rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
Quoted 87 lines · Onur Özkan
Quoted 73 lines · On Tue, 22 Sep 2026 10:54:22 +0200 Boqun Feng <[email protected]> wrote:
Quoted 59 lines · Onur Özkan
Covers the entire low-level locking API (lock,
try_lock, slow path, interruptible variants) and integration with kernel bindings.Signed-off-by Onur Özkan <[email protected]>--- rust/kernel/sync/lock/ww_mutex.rs | 433 ++++++++++++++++++ rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs | 172 +++++++ 2 files changed, 605 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex/acquire_ctx.rsrust/kernel/sync/lock/ww_mutex.rs +36
-0@@ -1,7 +1,440 @@// SPDX-License-Identifier: GPL-2.0 //! Rust abstractions for the kernel's wound-wait locking primitives. +//! +//! It is designed to avoid deadlocks when locking multiple [`Mutex`]es +//! that belong to the same [`Class`]. Each lock acquisition uses an +//! [`AcquireCtx`] to track ordering and ensure forward progress. +//! +//! See srctree/Documentation/locking/ww-mutex-design.rst for more details. +use crate ::error::to_result; +use crate ::prelude::*; +use crate ::types::{NotThreadSafe ,Opaque }; +use crate ::{bindings, container_of}; + +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; + +pub use acquire_ctx::AcquireCtx ;pub use class::Class ;mod class; +mod acquire_ctx; +mod class; + +/// A wound-wait (ww) mutex that is powered with deadlock avoidance +/// when acquiring multiple locks of the same [`Class`]. +/// +/// Each mutex belongs to a [`Class`], which the wound-wait algorithm +/// uses to figure out the order of acquisition and prevent deadlocks. +/// +/// # Examples +/// +/// ``` +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use kernel::sync::lock::ww_mutex::{AcquireCtx, Class, Mutex}; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// let mutex = Arc::pin_init(Mutex::new(42, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; rust/kernel/sync/lock/ww_mutex.rs line 53
Quoted 10 lines
rust/kernel/sync/lock/ww_mutex.rs +10
-0+/// +/// let guard = ctx.lock(&mutex)?; +/// assert_eq!(*guard, 42); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data] +#[repr( C )] +pub struct Mutex <'a,T : ?Sized > { + _p:PhantomData <&'aClass >,We should be able to do:
Quoted 7 lines
class: &'a Class,
then we don't need to patch #2 in the series, right?
Regards,
BoqunI assume you are suggesting passing the Class reference to
from_raw()functions as well?
Quoted 8 lines
If so, we discussed this in previous revisions. Daniel suggested passing the class explicitly to
from_raw()as an alternative [1]. We then discussed that approach versus making the C fields unconditional and both Lyude and Daniel supported the C change [2].That is the rationale for patch #2, it lets us validate class pairing while keeping
from_raw()simple for existing C objects.
I understand, however, we need C side to be OK to the change as well.
Quoted 3 lines
It also keeps
AcquireCtx::reinit()simpler by letting it recover the original class without requiring the caller to supply it again.
But if AcquireCtx has a:
class: &'a Class
as a field, reinit() can just use that, right? It only affects from_raw() design seems to me.
Regards,
Boqun
Quoted 574 lines
[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/[email protected]Thanks,
OnurQuoted 568 lines
Quoted 568 lines
rust/kernel/sync/lock/ww_mutex.rs +387
-0+#[pin] + inner: Opaque<bindings::ww_mutex>, + data: UnsafeCell<T>, +} + +impl <'class,T >Mutex <'class,T > { +/// Initializes [`Mutex`] with the given `data` and [`Class`]. +pub fn new (data:T , class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (Mutex { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_mutex | { +// SAFETY: `class` is valid for the lifetime `'class` captured by `Self`. +unsafe { bindings::ww_mutex_init (slot, class_ptr) } + }), + data:UnsafeCell ::new (data), + _p:PhantomData + }) + } +} + +impl <'class,T : ?Sized >Mutex <'class,T > { +/// Checks if this [`Mutex`] is currently locked. +/// +/// The returned value is racy as another thread can acquire +/// or release the lock immediately after this call returns. +pub fn is_locked (&self) ->bool { +// SAFETY: It's safe to call `ww_mutex_is_locked` on +// a valid mutex. +unsafe { bindings::ww_mutex_is_locked (self.inner.get ()) } + } + +/// Locks this [`Mutex`] without [`AcquireCtx`]. +pub fn lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Interruptible ) + } + +/// Locks this [`Mutex`] without [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::SlowInterruptible ) + } + +/// Tries to lock this [`Mutex`] with no [`AcquireCtx`] and without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Try ) + } +} + +impl <'class>Mutex <'class, ()> { +/// Creates a [`Mutex`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'a`. +/// - ww_class associated with this mutex must be valid for +/// the lifetime `'class`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_mutex ) -> &'aSelf { +// SAFETY: By the safety contract, the caller guarantees that `ptr` +// points to a valid `ww_mutex` which is the `inner` field of `Mutex`, +// that it remains valid for the lifetime `'a` and the associated +// ww_class outlives `'class`. +// +// Because [`Mutex`] is `#[repr(C)]`, the `inner` field sits at a +// stable offset that `container_of!` can safely rely on. +unsafe { &*container_of! (Opaque ::cast_from (ptr),Self , inner) } + } +} + +// SAFETY: `Mutex` can be sent to another thread if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send >Send for Mutex <'_,T > {} + +// SAFETY: `Mutex` can be shared across threads if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send +Sync >Sync for Mutex <'_,T > {} + +/// A guard that provides exclusive access to the data protected +/// by a [`Mutex`]. +/// +/// # Invariants +/// +/// The guard holds an exclusive lock on the associated [`Mutex`]. The lock is held +/// for the entire lifetime of this guard and is automatically released when the +/// guard is dropped. +#[must_use = "the lock unlocks immediately when the guard is unused" ] +pub struct MutexGuard <'a,T : ?Sized > { + mutex: &'aMutex <'a,T >, + _not_send:NotThreadSafe , +} + +impl <'a,T : ?Sized >MutexGuard <'a,T > { +/// Creates a new guard for the given [`Mutex`]. +fn new (mutex: &'aMutex <'a,T >) ->Self { +assert! (mutex.is_locked ()); + +Self { + mutex, + _not_send:NotThreadSafe , + } + } +} + +impl <'a>MutexGuard <'a, ()> { +/// Creates a [`MutexGuard`] from a raw pointer. +/// +/// If the given pointer refers to a mutex that is not locked, +/// returns [`EINVAL`]. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'b`. +/// - The `ww_class` associated with the `ww_mutex` must be valid for the lifetime `'b`. +pub unsafe fn from_raw <'b>(ptr: *mut bindings::ww_mutex ) ->Result <MutexGuard <'b, ()>> { +// SAFETY: By this function's safety contract, the caller guarantees that `ptr` points to a +// valid `ww_mutex` which is the `inner` field of a `Mutex`. The caller also guarantees +// that both `ptr` and the associated `ww_class` are valid for the lifetime `'b`. +let mutex =unsafe {Mutex ::from_raw (ptr) }; + +if !mutex.is_locked () { +return Err (EINVAL ); + } + +Ok (MutexGuard ::new (mutex)) + } +} + +impl <T : ?Sized > core::ops::Deref for MutexGuard <'_,T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &*self.mutex.data.get () } + } +} + +impl <T : ?Sized +Unpin > core::ops::DerefMut for MutexGuard <'_,T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &mut *self.mutex.data.get () } + } +} + +impl <T : ?Sized >Drop for MutexGuard <'_,T > { +fn drop (&mut self) { +// SAFETY: self.mutex is locked and are about to release it. +unsafe { bindings::ww_mutex_unlock (self.mutex.inner.get ()) }; + } +} + +// SAFETY: `MutexGuard` can be shared between threads if the data can. +unsafe impl <T : ?Sized +Sync >Sync for MutexGuard <'_,T > {} + +/// Locking kinds used by [`lock_common`] to unify the internal +/// locking logic. +/// +/// It's best not to expose this type (and [`lock_common`]) to the +/// kernel, as it allows internal API changes without worrying +/// about breaking external compatibility. +#[derive( Copy , Clone , Debug )] +enum LockKind { +/// Blocks until lock is acquired. +Regular , +/// Blocks but can be interrupted by signals. +Interruptible , +/// Used in slow path after deadlock detection. +Slow , +/// Slow path but interruptible. +SlowInterruptible , +/// Does not block, returns immediately if busy. +Try , +} + +/// Internal helper that unifies the different locking kinds. +/// +/// Returns [`EINVAL`] if the [`Mutex`] has a different [`Class`]. +fn lock_common <'a,T : ?Sized >( + mutex: &'aMutex <'a,T >, + ctx:Option <&AcquireCtx <'_>>, + kind:LockKind , +) ->Result <MutexGuard <'a,T >> { +let mutex_ptr = mutex.inner.get (); + +let ctx_ptr =match ctx { +Some (acquire_ctx) => { +let ctx_ptr = acquire_ctx.inner.get (); + +// SAFETY: `ctx_ptr` is a valid pointer for the entire +// lifetime of `ctx`. +let ctx_class =unsafe { (*ctx_ptr).ww_class }; + +// SAFETY: `mutex_ptr` is a valid pointer for the entire +// lifetime of `mutex`. +let mutex_class =unsafe { (*mutex_ptr).ww_class }; + +// `ctx` and `mutex` must use the same class. +if ctx_class != mutex_class { +return Err (EINVAL ); + } + + ctx_ptr + } +None => core::ptr::null_mut (), + }; + +match kind { +LockKind ::Regular => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Interruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Slow => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +unsafe { bindings::ww_mutex_lock_slow (mutex_ptr, ctx_ptr) }; + } +LockKind ::SlowInterruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_slow_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Try => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_trylock (mutex_ptr, ctx_ptr) }; + +if ret ==0 { +return Err (EBUSY ); + }else { +to_result (ret)?; + } + } + }; + +Ok (MutexGuard ::new (mutex)) +} + +#[kunit_tests(rust_kernel_ww_mutex)] +mod tests { +use crate ::prelude::*; +use crate ::sync::Arc ; +use crate ::{define_wd_class, define_ww_class}; + +use super ::*; + +define_ww_class! (TEST_WOUND_WAIT_CLASS ); +define_wd_class! (TEST_WAIT_DIE_CLASS ); + +#[test] +fn test_ww_mutex_basic_lock_unlock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (42 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +let guard = ctx.lock (&mutex)?; +assert_eq! (*guard,42 ); + +// Drop the lock. +drop (guard); + +let mut guard = ctx.lock (&mutex)?; + *guard =100 ; +assert_eq! (*guard,100 ); + +Ok (()) + } + +#[test] +fn test_ww_mutex_trylock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (123 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// `try_lock` on unlocked mutex should succeed. +let guard = ctx.try_lock (&mutex)?; +assert_eq! (*guard,123 ); + +// Now it should fail immediately as it's already locked. +assert! (ctx.try_lock (&mutex).is_err ()); + +Ok (()) + } + +#[test] +fn test_ww_mutex_is_locked () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ("hello" , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +// Should not be locked initially. +assert! (!mutex.is_locked ()); + +let guard = ctx.lock (&mutex)?; +assert! (mutex.is_locked ()); + +drop (guard); +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_ww_acquire_context_done () ->Result { +let mutex1 =Arc ::pin_init (Mutex ::new (1 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let mutex2 =Arc ::pin_init (Mutex ::new (2 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// Acquire multiple mutexes with the same context. +let guard1 = ctx.lock (&mutex1)?; +let guard2 = ctx.lock (&mutex2)?; + +assert_eq! (*guard1,1 ); +assert_eq! (*guard2,2 ); + +// SAFETY: It's called exactly once here and nowhere else. +unsafe { ctx.done () }; + +// We shouldn't be able to lock once it's `done`. +assert! (ctx.lock (&mutex1).is_err ()); +assert! (ctx.lock (&mutex2).is_err ()); + +Ok (()) + } + +#[test] +fn test_mutex_without_ctx () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (100 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let guard = mutex.lock ()?; + +assert_eq! (*guard,100 ); +assert! (mutex.is_locked ()); + +drop (guard); + +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_guard_from_raw_with_unlocked_mutex () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ((), &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +assert! (!mutex.is_locked ()); + +// SAFETY: `mutex` remains valid for the duration of this test. +match unsafe {MutexGuard ::from_raw (mutex.inner.get ()) } { +// Should fail with `EINVAL` because the mutex is not locked. +Err (e) =>assert_eq! (e,EINVAL ), + _ =>unreachable! (), + }; + +Ok (()) + } +} +>>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs new file +172
-0@@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Provides [`AcquireCtx`] for managing multiple wound/wait +//! mutexes from the same [`Class`]. + +use crate ::bindings; +use crate ::prelude::*; +use crate ::types::Opaque ; + +use core::marker::PhantomData ; + +use super ::{lock_common,Class ,LockKind ,Mutex ,MutexGuard }; + +/// Groups multiple [`Mutex`]es for deadlock avoidance when acquired +/// with the same [`Class`]. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::lock::ww_mutex::{Class, AcquireCtx, Mutex}; +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// // Create mutexes. +/// let mutex1 = Arc::pin_init(Mutex::new(1, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let mutex2 = Arc::pin_init(Mutex::new(2, &SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// // Create acquire context for deadlock avoidance. +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// let guard1 = ctx.lock(&mutex1)?; +/// let guard2 = ctx.lock(&mutex2)?; +/// +/// // Mark acquisition phase as complete. +/// // SAFETY: It's called exactly once here and nowhere else. +/// unsafe { ctx.done() }; +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data( PinnedDrop )] +#[repr(transparent)] +pub struct AcquireCtx <'a> { +#[pin] +pub (super ) inner:Opaque <bindings::ww_acquire_ctx >, + _p:PhantomData <&'aClass >, +} + +impl <'class>AcquireCtx <'class> { +/// Initializes a new [`AcquireCtx`] with the given [`Class`]. +pub fn new (class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (AcquireCtx { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_acquire_ctx | { +// SAFETY: `class` is valid for the lifetime `'class` captured +// by `AcquireCtx`. +unsafe { bindings::ww_acquire_init (slot, class_ptr) } + }), + _p:PhantomData + }) + } + +/// Creates a [`AcquireCtx`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is a valid pointer to the `inner` field +/// of [`AcquireCtx`] and that it remains valid for the lifetime `'a`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_acquire_ctx ) -> &'aSelf { +// SAFETY: By the safety contract, `ptr` is valid to construct `AcquireCtx`. +unsafe { &*ptr.cast () } + } + +/// Marks the end of the acquire phase. +/// +/// Calling this function is optional. It is just useful to document +/// the code and clearly designated the acquire phase from actually +/// using the locked data structures. +/// +/// After calling this function, no more mutexes can be acquired with +/// this context. +/// +/// # Safety +/// +/// The caller must ensure that this function is called only once +/// and after calling it, no further mutexes are acquired using +/// this context. +pub unsafe fn done (&self) { +// SAFETY: By the safety contract, the caller guarantees that this +// function is called only once. +unsafe { bindings::ww_acquire_done (self.inner.get ()) }; + } + +/// Re-initializes the [`AcquireCtx`]. +/// +/// Must be called after releasing all locks when [`EDEADLK`] occurs. +/// +/// # Safety +/// +/// The caller must ensure no locks are held in this [`AcquireCtx`]. +pub unsafe fn reinit (self:Pin <&mut Self >) { +let ctx = self.inner.get (); + +// SAFETY: `ww_class` is always a valid pointer in properly initialized +// `AcquireCtx`. +let class_ptr =unsafe { (*ctx).ww_class }; + +// SAFETY: +// - Lifetime of any guard (which hold an immutable borrow of `self`) cannot overlap +// with the execution of this function. This enforces that all locks acquired via +// this context have been released. +// +// - `ctx` is guaranteed to be initialized because `ww_acquire_fini` +// can only be called from the `Drop` implementation. +// +// - `ww_acquire_fini` is safe to call on an initialized context. +unsafe { bindings::ww_acquire_fini (ctx) }; + +// SAFETY: `ww_acquire_init` is safe to call with valid pointers +// to initialize an uninitialized context. +unsafe { bindings::ww_acquire_init (ctx, class_ptr) }; + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`]. +pub fn lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Interruptible ) + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::SlowInterruptible ) + } + +/// Tries to lock the [`Mutex`] on this [`AcquireCtx`] without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Try ) + } +} + +#[pinned_drop] +impl PinnedDrop for AcquireCtx <'_> { +fn drop (self:Pin <&mut Self >) { +// SAFETY: Given the lifetime bounds we know no locks are held, +// so calling `ww_acquire_fini` is safe. +unsafe { bindings::ww_acquire_fini (self.inner.get ()) }; + } +}Signature · 1 line
2.51.2
Boqun Feng
maintainerRe: [PATCH v9 2/7] ww_mutex: add ww_class field unconditionally
In reply to Onur ÖzkanQuoted 9 lines · Onur Özkan
Removes
DEBUG_WW_MUTEXESguard around theww_classfield in structww_mutexand structww_acquire_ctxto always initialize it.Keeping the class pointer available unconditionally allows Rust abstractions to keep
from_raw()simple on Mutex and AcquireCtx, simplify AcquireCtx reinitialization logic and validate Mutex and AcquireCtx class pairing in much simpler way.
@Peter and @Waiman, any dispute on this patch? I would like to make some progress on this since it'll be needed for GPUVM and KMS if I understand correctly.
Regards,
Boqun
Quoted 54 lines
Signed-off-by Onur Özkan <[email protected]>--- include/linux/ww_mutex.h | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-)include/linux/ww_mutex.h +2
-6@@ -47,9 +47,7 @@ struct ww_class {struct ww_mutex {struct WW_MUTEX_BASE base;struct ww_acquire_ctx *ctx; -#ifdef DEBUG_WW_MUTEXES struct ww_class *ww_class; -#endif };struct ww_acquire_ctx {@@ -58,9 +56,9 @@ struct ww_acquire_ctx {unsigned int acquired;unsigned short wounded;unsigned short is_wait_die; +struct ww_class *ww_class;#ifdef DEBUG_WW_MUTEXES unsigned int done_acquire; -struct ww_class *ww_class;void *contending_lock;#endif #ifdef CONFIG_DEBUG_LOCK_ALLOC @@ -110,9 +108,7 @@ static inline void ww_mutex_init(struct ww_mutex *lock, {ww_mutex_base_init (&lock->base, ww_class->mutex_name, &ww_class->mutex_key); lock->ctx =NULL ; -#ifdef DEBUG_WW_MUTEXES lock->ww_class = ww_class; -#endif }/** @@ -147,8 +143,8 @@ static inline void ww_acquire_init(struct ww_acquire_ctx *ctx, ctx->acquired =0 ; ctx->wounded = false; ctx->is_wait_die = ww_class->is_wait_die; -#ifdef DEBUG_WW_MUTEXES ctx->ww_class = ww_class; +#ifdef DEBUG_WW_MUTEXES ctx->done_acquire =0 ; ctx->contending_lock =NULL ;#endif Signature · 1 line
2.51.2
Onur Özkan
reviewerRe: [PATCH v9 5/7] rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard
In reply to Boqun FengQuoted 105 lines · On Wed, 23 Sep 2026 07:32:37 +0200 Boqun Feng <[email protected]> wrote:
Quoted 87 lines · Onur Özkan
Quoted 73 lines · On Tue, 22 Sep 2026 10:54:22 +0200 Boqun Feng <[email protected]> wrote:
Quoted 59 lines · Onur Özkan
Covers the entire low-level locking API (lock,
try_lock, slow path, interruptible variants) and integration with kernel bindings.Signed-off-by Onur Özkan <[email protected]>--- rust/kernel/sync/lock/ww_mutex.rs | 433 ++++++++++++++++++ rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs | 172 +++++++ 2 files changed, 605 insertions(+) create mode 100644 rust/kernel/sync/lock/ww_mutex/acquire_ctx.rsrust/kernel/sync/lock/ww_mutex.rs +36
-0@@ -1,7 +1,440 @@// SPDX-License-Identifier: GPL-2.0 //! Rust abstractions for the kernel's wound-wait locking primitives. +//! +//! It is designed to avoid deadlocks when locking multiple [`Mutex`]es +//! that belong to the same [`Class`]. Each lock acquisition uses an +//! [`AcquireCtx`] to track ordering and ensure forward progress. +//! +//! See srctree/Documentation/locking/ww-mutex-design.rst for more details. +use crate ::error::to_result; +use crate ::prelude::*; +use crate ::types::{NotThreadSafe ,Opaque }; +use crate ::{bindings, container_of}; + +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; + +pub use acquire_ctx::AcquireCtx ;pub use class::Class ;mod class; +mod acquire_ctx; +mod class; + +/// A wound-wait (ww) mutex that is powered with deadlock avoidance +/// when acquiring multiple locks of the same [`Class`]. +/// +/// Each mutex belongs to a [`Class`], which the wound-wait algorithm +/// uses to figure out the order of acquisition and prevent deadlocks. +/// +/// # Examples +/// +/// ``` +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use kernel::sync::lock::ww_mutex::{AcquireCtx, Class, Mutex}; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// let mutex = Arc::pin_init(Mutex::new(42, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; rust/kernel/sync/lock/ww_mutex.rs line 53
Quoted 10 lines
rust/kernel/sync/lock/ww_mutex.rs +10
-0+/// +/// let guard = ctx.lock(&mutex)?; +/// assert_eq!(*guard, 42); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data] +#[repr( C )] +pub struct Mutex <'a,T : ?Sized > { + _p:PhantomData <&'aClass >,We should be able to do:
Quoted 7 lines
class: &'a Class,
then we don't need to patch #2 in the series, right?
Regards,
BoqunI assume you are suggesting passing the Class reference to
from_raw()functions as well?Quoted 8 lines
If so, we discussed this in previous revisions. Daniel suggested passing the class explicitly to
from_raw()as an alternative [1]. We then discussed that approach versus making the C fields unconditional and both Lyude and Daniel supported the C change [2].That is the rationale for patch #2, it lets us validate class pairing while keeping
from_raw()simple for existing C objects.I understand, however, we need C side to be OK to the change as well.
Quoted 3 lines
It also keeps
AcquireCtx::reinit()simpler by letting it recover the original class without requiring the caller to supply it again.But if AcquireCtx has a:
Quoted 7 lines
class: &'a Class
as a field,
reinit()can just use that, right? It only affectsfrom_raw()design seems to me.Regards,
Boqun
Yeah, that's just a nice side effect of this approach. The primary reason is from_raw() functions.
Quoted 575 lines
Quoted 575 lines
[1] https://lore.kernel.org/all/[email protected]
[2] https://lore.kernel.org/all/[email protected]Thanks,
OnurQuoted 568 lines
Quoted 568 lines
rust/kernel/sync/lock/ww_mutex.rs +387
-0+#[pin] + inner: Opaque<bindings::ww_mutex>, + data: UnsafeCell<T>, +} + +impl <'class,T >Mutex <'class,T > { +/// Initializes [`Mutex`] with the given `data` and [`Class`]. +pub fn new (data:T , class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (Mutex { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_mutex | { +// SAFETY: `class` is valid for the lifetime `'class` captured by `Self`. +unsafe { bindings::ww_mutex_init (slot, class_ptr) } + }), + data:UnsafeCell ::new (data), + _p:PhantomData + }) + } +} + +impl <'class,T : ?Sized >Mutex <'class,T > { +/// Checks if this [`Mutex`] is currently locked. +/// +/// The returned value is racy as another thread can acquire +/// or release the lock immediately after this call returns. +pub fn is_locked (&self) ->bool { +// SAFETY: It's safe to call `ww_mutex_is_locked` on +// a valid mutex. +unsafe { bindings::ww_mutex_is_locked (self.inner.get ()) } + } + +/// Locks this [`Mutex`] without [`AcquireCtx`]. +pub fn lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Interruptible ) + } + +/// Locks this [`Mutex`] without [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::SlowInterruptible ) + } + +/// Tries to lock this [`Mutex`] with no [`AcquireCtx`] and without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock (&self) ->Result <MutexGuard <'_,T >> { +lock_common (self,None ,LockKind ::Try ) + } +} + +impl <'class>Mutex <'class, ()> { +/// Creates a [`Mutex`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'a`. +/// - ww_class associated with this mutex must be valid for +/// the lifetime `'class`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_mutex ) -> &'aSelf { +// SAFETY: By the safety contract, the caller guarantees that `ptr` +// points to a valid `ww_mutex` which is the `inner` field of `Mutex`, +// that it remains valid for the lifetime `'a` and the associated +// ww_class outlives `'class`. +// +// Because [`Mutex`] is `#[repr(C)]`, the `inner` field sits at a +// stable offset that `container_of!` can safely rely on. +unsafe { &*container_of! (Opaque ::cast_from (ptr),Self , inner) } + } +} + +// SAFETY: `Mutex` can be sent to another thread if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send >Send for Mutex <'_,T > {} + +// SAFETY: `Mutex` can be shared across threads if the protected +// data `T` can be. +unsafe impl <T : ?Sized +Send +Sync >Sync for Mutex <'_,T > {} + +/// A guard that provides exclusive access to the data protected +/// by a [`Mutex`]. +/// +/// # Invariants +/// +/// The guard holds an exclusive lock on the associated [`Mutex`]. The lock is held +/// for the entire lifetime of this guard and is automatically released when the +/// guard is dropped. +#[must_use = "the lock unlocks immediately when the guard is unused" ] +pub struct MutexGuard <'a,T : ?Sized > { + mutex: &'aMutex <'a,T >, + _not_send:NotThreadSafe , +} + +impl <'a,T : ?Sized >MutexGuard <'a,T > { +/// Creates a new guard for the given [`Mutex`]. +fn new (mutex: &'aMutex <'a,T >) ->Self { +assert! (mutex.is_locked ()); + +Self { + mutex, + _not_send:NotThreadSafe , + } + } +} + +impl <'a>MutexGuard <'a, ()> { +/// Creates a [`MutexGuard`] from a raw pointer. +/// +/// If the given pointer refers to a mutex that is not locked, +/// returns [`EINVAL`]. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that: +/// +/// - `ptr` is a valid pointer to a `ww_mutex`. +/// - `ptr` must remain valid for the lifetime `'b`. +/// - The `ww_class` associated with the `ww_mutex` must be valid for the lifetime `'b`. +pub unsafe fn from_raw <'b>(ptr: *mut bindings::ww_mutex ) ->Result <MutexGuard <'b, ()>> { +// SAFETY: By this function's safety contract, the caller guarantees that `ptr` points to a +// valid `ww_mutex` which is the `inner` field of a `Mutex`. The caller also guarantees +// that both `ptr` and the associated `ww_class` are valid for the lifetime `'b`. +let mutex =unsafe {Mutex ::from_raw (ptr) }; + +if !mutex.is_locked () { +return Err (EINVAL ); + } + +Ok (MutexGuard ::new (mutex)) + } +} + +impl <T : ?Sized > core::ops::Deref for MutexGuard <'_,T > { +type Target =T ; + +fn deref (&self) -> &Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &*self.mutex.data.get () } + } +} + +impl <T : ?Sized +Unpin > core::ops::DerefMut for MutexGuard <'_,T > { +fn deref_mut (&mut self) -> &mut Self ::Target { +// SAFETY: self.mutex is locked, so we have exclusive access. +unsafe { &mut *self.mutex.data.get () } + } +} + +impl <T : ?Sized >Drop for MutexGuard <'_,T > { +fn drop (&mut self) { +// SAFETY: self.mutex is locked and are about to release it. +unsafe { bindings::ww_mutex_unlock (self.mutex.inner.get ()) }; + } +} + +// SAFETY: `MutexGuard` can be shared between threads if the data can. +unsafe impl <T : ?Sized +Sync >Sync for MutexGuard <'_,T > {} + +/// Locking kinds used by [`lock_common`] to unify the internal +/// locking logic. +/// +/// It's best not to expose this type (and [`lock_common`]) to the +/// kernel, as it allows internal API changes without worrying +/// about breaking external compatibility. +#[derive( Copy , Clone , Debug )] +enum LockKind { +/// Blocks until lock is acquired. +Regular , +/// Blocks but can be interrupted by signals. +Interruptible , +/// Used in slow path after deadlock detection. +Slow , +/// Slow path but interruptible. +SlowInterruptible , +/// Does not block, returns immediately if busy. +Try , +} + +/// Internal helper that unifies the different locking kinds. +/// +/// Returns [`EINVAL`] if the [`Mutex`] has a different [`Class`]. +fn lock_common <'a,T : ?Sized >( + mutex: &'aMutex <'a,T >, + ctx:Option <&AcquireCtx <'_>>, + kind:LockKind , +) ->Result <MutexGuard <'a,T >> { +let mutex_ptr = mutex.inner.get (); + +let ctx_ptr =match ctx { +Some (acquire_ctx) => { +let ctx_ptr = acquire_ctx.inner.get (); + +// SAFETY: `ctx_ptr` is a valid pointer for the entire +// lifetime of `ctx`. +let ctx_class =unsafe { (*ctx_ptr).ww_class }; + +// SAFETY: `mutex_ptr` is a valid pointer for the entire +// lifetime of `mutex`. +let mutex_class =unsafe { (*mutex_ptr).ww_class }; + +// `ctx` and `mutex` must use the same class. +if ctx_class != mutex_class { +return Err (EINVAL ); + } + + ctx_ptr + } +None => core::ptr::null_mut (), + }; + +match kind { +LockKind ::Regular => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Interruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Slow => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +unsafe { bindings::ww_mutex_lock_slow (mutex_ptr, ctx_ptr) }; + } +LockKind ::SlowInterruptible => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_lock_slow_interruptible (mutex_ptr, ctx_ptr) }; + +to_result (ret)?; + } +LockKind ::Try => { +// SAFETY: `Mutex` is always pinned. If `AcquireCtx` is `Some`, it is pinned, +// if `None`, it is set to `core::ptr::null_mut()`. Both cases are safe. +let ret =unsafe { bindings::ww_mutex_trylock (mutex_ptr, ctx_ptr) }; + +if ret ==0 { +return Err (EBUSY ); + }else { +to_result (ret)?; + } + } + }; + +Ok (MutexGuard ::new (mutex)) +} + +#[kunit_tests(rust_kernel_ww_mutex)] +mod tests { +use crate ::prelude::*; +use crate ::sync::Arc ; +use crate ::{define_wd_class, define_ww_class}; + +use super ::*; + +define_ww_class! (TEST_WOUND_WAIT_CLASS ); +define_wd_class! (TEST_WAIT_DIE_CLASS ); + +#[test] +fn test_ww_mutex_basic_lock_unlock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (42 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +let guard = ctx.lock (&mutex)?; +assert_eq! (*guard,42 ); + +// Drop the lock. +drop (guard); + +let mut guard = ctx.lock (&mutex)?; + *guard =100 ; +assert_eq! (*guard,100 ); + +Ok (()) + } + +#[test] +fn test_ww_mutex_trylock () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (123 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// `try_lock` on unlocked mutex should succeed. +let guard = ctx.try_lock (&mutex)?; +assert_eq! (*guard,123 ); + +// Now it should fail immediately as it's already locked. +assert! (ctx.try_lock (&mutex).is_err ()); + +Ok (()) + } + +#[test] +fn test_ww_mutex_is_locked () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ("hello" , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +// Should not be locked initially. +assert! (!mutex.is_locked ()); + +let guard = ctx.lock (&mutex)?; +assert! (mutex.is_locked ()); + +drop (guard); +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_ww_acquire_context_done () ->Result { +let mutex1 =Arc ::pin_init (Mutex ::new (1 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let mutex2 =Arc ::pin_init (Mutex ::new (2 , &TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; +let ctx =KBox ::pin_init (AcquireCtx ::new (&TEST_WAIT_DIE_CLASS ),GFP_KERNEL )?; + +// Acquire multiple mutexes with the same context. +let guard1 = ctx.lock (&mutex1)?; +let guard2 = ctx.lock (&mutex2)?; + +assert_eq! (*guard1,1 ); +assert_eq! (*guard2,2 ); + +// SAFETY: It's called exactly once here and nowhere else. +unsafe { ctx.done () }; + +// We shouldn't be able to lock once it's `done`. +assert! (ctx.lock (&mutex1).is_err ()); +assert! (ctx.lock (&mutex2).is_err ()); + +Ok (()) + } + +#[test] +fn test_mutex_without_ctx () ->Result { +let mutex =Arc ::pin_init (Mutex ::new (100 , &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; +let guard = mutex.lock ()?; + +assert_eq! (*guard,100 ); +assert! (mutex.is_locked ()); + +drop (guard); + +assert! (!mutex.is_locked ()); + +Ok (()) + } + +#[test] +fn test_guard_from_raw_with_unlocked_mutex () ->Result { +let mutex =Arc ::pin_init (Mutex ::new ((), &TEST_WOUND_WAIT_CLASS ),GFP_KERNEL )?; + +assert! (!mutex.is_locked ()); + +// SAFETY: `mutex` remains valid for the duration of this test. +match unsafe {MutexGuard ::from_raw (mutex.inner.get ()) } { +// Should fail with `EINVAL` because the mutex is not locked. +Err (e) =>assert_eq! (e,EINVAL ), + _ =>unreachable! (), + }; + +Ok (()) + } +} +>>>>>>> 90f935950ff8 (rust: ww_mutex: add Mutex, AcquireCtx and MutexGuard)rust/kernel/sync/lock/ww_mutex/acquire_ctx.rs new file +172
-0@@ -0,0 +1,172 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Provides [`AcquireCtx`] for managing multiple wound/wait +//! mutexes from the same [`Class`]. + +use crate ::bindings; +use crate ::prelude::*; +use crate ::types::Opaque ; + +use core::marker::PhantomData ; + +use super ::{lock_common,Class ,LockKind ,Mutex ,MutexGuard }; + +/// Groups multiple [`Mutex`]es for deadlock avoidance when acquired +/// with the same [`Class`]. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::lock::ww_mutex::{Class, AcquireCtx, Mutex}; +/// use kernel::define_ww_class; +/// use kernel::sync::Arc; +/// use pin_init::stack_pin_init; +/// +/// define_ww_class!(SOME_WW_CLASS); +/// +/// // Create mutexes. +/// let mutex1 = Arc::pin_init(Mutex::new(1, &SOME_WW_CLASS), GFP_KERNEL)?; +/// let mutex2 = Arc::pin_init(Mutex::new(2, &SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// // Create acquire context for deadlock avoidance. +/// let ctx = KBox::pin_init(AcquireCtx::new(&SOME_WW_CLASS), GFP_KERNEL)?; +/// +/// let guard1 = ctx.lock(&mutex1)?; +/// let guard2 = ctx.lock(&mutex2)?; +/// +/// // Mark acquisition phase as complete. +/// // SAFETY: It's called exactly once here and nowhere else. +/// unsafe { ctx.done() }; +/// +/// # Ok::<(), Error>(()) +/// ``` +#[pin_data( PinnedDrop )] +#[repr(transparent)] +pub struct AcquireCtx <'a> { +#[pin] +pub (super ) inner:Opaque <bindings::ww_acquire_ctx >, + _p:PhantomData <&'aClass >, +} + +impl <'class>AcquireCtx <'class> { +/// Initializes a new [`AcquireCtx`] with the given [`Class`]. +pub fn new (class: &'classClass ) ->impl PinInit <Self > { +let class_ptr = class.inner.get (); +pin_init! (AcquireCtx { + inner <-Opaque ::ffi_init (|slot: *mut bindings::ww_acquire_ctx | { +// SAFETY: `class` is valid for the lifetime `'class` captured +// by `AcquireCtx`. +unsafe { bindings::ww_acquire_init (slot, class_ptr) } + }), + _p:PhantomData + }) + } + +/// Creates a [`AcquireCtx`] from a raw pointer. +/// +/// This function is intended for interoperability with C code. +/// +/// # Safety +/// +/// The caller must ensure that `ptr` is a valid pointer to the `inner` field +/// of [`AcquireCtx`] and that it remains valid for the lifetime `'a`. +pub unsafe fn from_raw <'a>(ptr: *mut bindings::ww_acquire_ctx ) -> &'aSelf { +// SAFETY: By the safety contract, `ptr` is valid to construct `AcquireCtx`. +unsafe { &*ptr.cast () } + } + +/// Marks the end of the acquire phase. +/// +/// Calling this function is optional. It is just useful to document +/// the code and clearly designated the acquire phase from actually +/// using the locked data structures. +/// +/// After calling this function, no more mutexes can be acquired with +/// this context. +/// +/// # Safety +/// +/// The caller must ensure that this function is called only once +/// and after calling it, no further mutexes are acquired using +/// this context. +pub unsafe fn done (&self) { +// SAFETY: By the safety contract, the caller guarantees that this +// function is called only once. +unsafe { bindings::ww_acquire_done (self.inner.get ()) }; + } + +/// Re-initializes the [`AcquireCtx`]. +/// +/// Must be called after releasing all locks when [`EDEADLK`] occurs. +/// +/// # Safety +/// +/// The caller must ensure no locks are held in this [`AcquireCtx`]. +pub unsafe fn reinit (self:Pin <&mut Self >) { +let ctx = self.inner.get (); + +// SAFETY: `ww_class` is always a valid pointer in properly initialized +// `AcquireCtx`. +let class_ptr =unsafe { (*ctx).ww_class }; + +// SAFETY: +// - Lifetime of any guard (which hold an immutable borrow of `self`) cannot overlap +// with the execution of this function. This enforces that all locks acquired via +// this context have been released. +// +// - `ctx` is guaranteed to be initialized because `ww_acquire_fini` +// can only be called from the `Drop` implementation. +// +// - `ww_acquire_fini` is safe to call on an initialized context. +unsafe { bindings::ww_acquire_fini (ctx) }; + +// SAFETY: `ww_acquire_init` is safe to call with valid pointers +// to initialize an uninitialized context. +unsafe { bindings::ww_acquire_init (ctx, class_ptr) }; + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`]. +pub fn lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Regular ) + } + +/// Similar to [`Self::lock`], but can be interrupted by signals. +pub fn lock_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Interruptible ) + } + +/// Locks the given [`Mutex`] on this [`AcquireCtx`] using the slow path. +/// +/// This function should be used when [`Self::lock`] fails (typically due +/// to a potential deadlock). +pub fn lock_slow <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Slow ) + } + +/// Similar to [`Self::lock_slow`], but can be interrupted by signals. +pub fn lock_slow_interruptible <'a,T >( + &'a self, + mutex: &'aMutex <'a,T >, + ) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::SlowInterruptible ) + } + +/// Tries to lock the [`Mutex`] on this [`AcquireCtx`] without blocking. +/// +/// Unlike [`Self::lock`], no deadlock handling is performed. +pub fn try_lock <'a,T >(&'a self, mutex: &'aMutex <'a,T >) ->Result <MutexGuard <'a,T >> { +lock_common (mutex,Some (self),LockKind ::Try ) + } +} + +#[pinned_drop] +impl PinnedDrop for AcquireCtx <'_> { +fn drop (self:Pin <&mut Self >) { +// SAFETY: Given the lifetime bounds we know no locks are held, +// so calling `ww_acquire_fini` is safe. +unsafe { bindings::ww_acquire_fini (self.inner.get ()) }; + } +}Signature · 1 line
2.51.2