Skip to contentSkip to conversation

Add `ww_mutex` support & abstraction for Rust tree

PATCH In review onur-ozkan 3 participants 3 messages Jun 16, 2025 – Jun 17, 2025

Subsystems (3)
lore
Share & tools
lore

onur-ozkan

author reviewer
#0 lore raw

PATCH 1/1 Add `ww_mutex` support & abstraction for Rust tree

Adds Rust bindings for the kernel's ww_mutex infrastructure to enable deadlock-free acquisition of multiple related locks.

The implementation abstracts ww_mutex.h header and wraps the existing C ww_mutex with three main types:
- WwClass for grouping related mutexes
- WwAcquireCtx for tracking lock acquisition context
- WwMutex<T> for the actual lock

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. The `rust/helpers/ww_mutex.c file provides C function wrappers around these inline implementations, so bindgen can see them and generate the corresponding Rust code.

---
 rust/helpers/helpers.c            |   1 +
 rust/helpers/ww_mutex.c           |  39 +++
 rust/kernel/error.rs              |   1 +
 rust/kernel/sync/lock.rs          |   1 +
 rust/kernel/sync/lock/ww_mutex.rs | 501 ++++++++++++++++++++++++++++++
 5 files changed, 543 insertions(+)
 create mode 100644 rust/helpers/ww_mutex.c
 create mode 100644 rust/kernel/sync/lock/ww_mutex.rs
rust/helpers/helpers.c +1 -0
index 0f1b5d115985..fd071cbe20a1 100644
@@ -44,3 +44,4 @@
 #include "wait.c"
 #include "workqueue.c"
 #include "xarray.c"
+#include "ww_mutex.c"
rust/helpers/ww_mutex.c new file +39 -0
new file mode 100644
index 000000000000..61a487653394
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/ww_mutex.h>
+
+void rust_helper_ww_mutex_init(struct ww_mutex *lock, struct ww_class *ww_class)
+{
+	ww_mutex_init(lock, ww_class);
+}
+
+void rust_helper_ww_acquire_init(struct ww_acquire_ctx *ctx, struct ww_class *ww_class)
+{
+	ww_acquire_init(ctx, ww_class);
+}
+
+void rust_helper_ww_acquire_done(struct ww_acquire_ctx *ctx)
+{
+	ww_acquire_done(ctx);
+}
+
+void rust_helper_ww_acquire_fini(struct ww_acquire_ctx *ctx)
+{
+	ww_acquire_fini(ctx);
+}
+
+void rust_helper_ww_mutex_lock_slow(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
+{
+	ww_mutex_lock_slow(lock, ctx);
+}
+
+int rust_helper_ww_mutex_lock_slow_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
+{
+	return ww_mutex_lock_slow_interruptible(lock, ctx);
+}
+
+bool rust_helper_ww_mutex_is_locked(struct ww_mutex *lock)
+{
+	return ww_mutex_is_locked(lock);
+}
+
rust/kernel/error.rs +1 -0
index 3dee3139fcd4..94d8014b236b 100644
@@ -84,6 +84,7 @@ macro_rules! declare_err {
     declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
     declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
     declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
+    declare_err!(EDEADLK, "Resource deadlock avoided.");
 }
 
 /// Generic integer kernel error.
rust/kernel/sync/lock.rs +1 -0
index e82fa5be289c..8824ebc81084 100644
@@ -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 +501 -0

501 lines not on this page · raw message

2.49.0

#1 lore raw

Hi,

Thanks for the patch.

[Add Rust and Locking]

Could you please cc more people and lists for the next version? You can find that information via scripts/get_maintainer.pl or the "LOCKING PRIMITIVES" and "RUST" sections in MAINTAINERS file in the kernel source.

Some comments from a quick look:

On Mon, Jun 16, 2025 at 07:24:48PM +0300, onur-ozkan wrote:
[...]

Quoted 18 lines
rust/kernel/sync/lock/ww_mutex.rs new file +18 -0
+/// Implementation of C side `ww_class`.
+///
+/// Represents a group of mutexes that can participate in deadlock avoidance together.
+/// All mutexes that might be acquired together should use the same class.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::sync::lock::ww_mutex::WwClass;
+/// use kernel::c_str;
+///
+/// let _wait_die_class = unsafe { WwClass::new(c_str!("graphics_buffers"), true) };
+/// let _wound_wait_class = unsafe { WwClass::new(c_str!("memory_pools"), false) };
+///
+/// # Ok::<(), Error>(())
+/// ```
+#[repr(transparent)]
+pub struct WwClass(Opaque<bindings::ww_class>);

rust/kernel/sync/lock/ww_mutex.rs line 42

Quoted 10 lines
rust/kernel/sync/lock/ww_mutex.rs new file +10 -0
+
+// SAFETY: `WwClass` can be shared between threads.
+unsafe impl Sync for WwClass {}
+
+impl WwClass {
+    /// Creates `WwClass` that wraps C side `ww_class`.
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that the returned `WwClass` is not moved or freed

You can make WwClass #[pin_data] & !Unpin as well.

Quoted 57 lines
rust/kernel/sync/lock/ww_mutex.rs new file +57 -0
+    /// while any `WwMutex` instances using this class exist.
+    pub unsafe fn new(name: &'static CStr, is_wait_die: bool) -> Self {
+        Self(Opaque::new(bindings::ww_class {
+            stamp: bindings::atomic_long_t { counter: 0 },
+            acquire_name: name.as_char_ptr(),
+            mutex_name: name.as_char_ptr(),
+            is_wait_die: is_wait_die as u32,
+
+            // `lock_class_key` doesn't have any value
+            acquire_key: bindings::lock_class_key {},
+            mutex_key: bindings::lock_class_key {},
+        }))
+    }
+}
+
+/// Implementation of C side `ww_acquire_ctx`.
+///
+/// An acquire context is used to group multiple mutex acquisitions together
+/// for deadlock avoidance. It must be used when acquiring multiple mutexes
+/// of the same class.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::sync::lock::ww_mutex::{WwClass, WwAcquireCtx, WwMutex};
+/// use kernel::alloc::KBox;
+/// use kernel::c_str;
+///
+/// let class = unsafe { WwClass::new(c_str!("my_class"), false) };
+///
+/// // Create mutexes
+/// let mutex1 = unsafe { KBox::pin_init(WwMutex::new(1u32, &class), GFP_KERNEL).unwrap() };
+/// let mutex2 = unsafe { KBox::pin_init(WwMutex::new(2u32, &class), GFP_KERNEL).unwrap() };
+///
+/// // Create acquire context for deadlock avoidance
+/// let mut ctx = KBox::pin_init(
+///     unsafe { WwAcquireCtx::new(&class) },
+///     GFP_KERNEL
+/// ).unwrap();
+///
+/// // Acquire multiple locks safely
+/// let guard1 = mutex1.as_ref().lock(Some(&ctx)).unwrap();
+/// let guard2 = mutex2.as_ref().lock(Some(&ctx)).unwrap();
+///
+/// // Mark acquisition phase as complete
+/// ctx.as_mut().done();
+///
+/// # Ok::<(), Error>(())
+/// ```
+#[pin_data(PinnedDrop)]
+pub struct WwAcquireCtx {
+    #[pin]
+    inner: Opaque<bindings::ww_acquire_ctx>,
+    #[pin]
+    _pin: PhantomPinned,
+}
+

rust/kernel/sync/lock/ww_mutex.rs line 109

Quoted 10 lines
rust/kernel/sync/lock/ww_mutex.rs new file +10 -0
+// SAFETY: `WwAcquireCtx` is safe to send between threads when not in use.
+unsafe impl Send for WwAcquireCtx {}
+
+impl WwAcquireCtx {
+    /// Initializes `Self` with calling C side `ww_acquire_init` inside.
+    ///
+    /// # Safety
+    ///
+    /// The caller must ensure that the `ww_class` remains valid for the lifetime
+    /// of this context.

You can make the type system check this for you by:

    pub struct WwAcquireCtx<'a> {
        #[pin]
        inner: Opaque<bindings::ww_acquire_ctx>,
        #[pin]
        _pin: PhantomPinned,
        _p: PhantomData<&'a WwClass>
    }

and

    impl<'ctx> WwAcquireCtx<'ctx> {
        pub fn new<'class: 'ctx>(ww_class: &'class WwClass) -> impl PinInit<Self> {
	    ...
	}
    }

the lifetime of the reference on WwClass should outlive the lifetime of WwAcquireCtx.

Similar for WwMutex. BUT all the existing ww_classes are static, alternatively, you can make Ww{AcquireCtx,Mutex}::new() take a &'static WwClass.

Regards,
Boqun

Quoted 14 lines
rust/kernel/sync/lock/ww_mutex.rs new file +14 -0
+    pub unsafe fn new(ww_class: &WwClass) -> impl PinInit<Self> {
+        let raw_ptr = ww_class.0.get();
+
+        pin_init!(WwAcquireCtx {
+            inner <- Opaque::ffi_init(|slot: *mut bindings::ww_acquire_ctx| {
+                // SAFETY: The caller guarantees that `ww_class` remains valid.
+                unsafe {
+                    bindings::ww_acquire_init(slot, raw_ptr)
+                }
+            }),
+            _pin: PhantomPinned,
+        })
+    }
+

[...]

#2 lore raw
In reply to onur-ozkan
kernel test robot noticed the following build errors:

Hi onur-ozkan,

kernel test robot noticed the following build errors:

[auto build test ERROR on rust/rust-next]
[also build test ERROR on linus/master v6.16-rc2 next-20250616] [cannot apply to tip/locking/core]
[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-ozkan/Add-ww_mutex-support-abstraction-for-Rust-tree/20250617-003523
base:   https://github.com/Rust-for-Linux/linux rust-next
patch link:    https://lore.kernel.org/r/20250616162448.31641-1-work%40onurozkan.dev
patch subject: [PATCH] Add `ww_mutex` support & abstraction for Rust tree
config: x86_64-randconfig-074-20250617 (https://download.01.org/0day-ci/archive/20250617/[email protected]/config)
compiler: clang version 20.1.2 (https://github.com/llvm/llvm-project 58df0ef89dd64126512e4ee27b4ac3fd8ddf6247)
rustc: rustc 1.78.0 (9b00956e5 2024-04-29)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250617/[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 >>):

***
*** Rust bindings generator 'bindgen' < 0.69.5 together with libclang >= 19.1 *** may not work due to a bug (https://github.com/rust-lang/rust-bindgen/pull/2824),
*** unless patched (like Debian's).
*** Your bindgen version: 0.65.1
*** Your libclang version: 20.1.2
***
***
*** Please see Documentation/rust/quick-start.rst for details
*** on how to set up the Rust support.
***

>> error[E0063]: missing field `__bindgen_anon_1` in initializer of `bindings::lock_class_key`

--> rust/kernel/sync/lock/ww_mutex.rs:52:26
|
52 | acquire_key: bindings::lock_class_key {},
| ^^^^^^^^^^^^^^^^^^^^^^^^ missing __bindgen_anon_1
--

>> error[E0063]: missing field `__bindgen_anon_1` in initializer of `bindings::lock_class_key`

--> rust/kernel/sync/lock/ww_mutex.rs:53:24
|
53 | mutex_key: bindings::lock_class_key {},
| ^^^^^^^^^^^^^^^^^^^^^^^^ missing __bindgen_anon_1

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki