Skip to contentSkip to conversation

rust: add C wrappers for `ww_mutex` inline functions

PATCH Superseded Onur Özkan 2 participants 6 messages Jun 21, 2025

Subsystems (3)

v4 of 13 Superseded Latest is v13 →

lore
Share & tools
lore

Onur Özkan

author reviewer
#0 lore raw

PATCH v4 1/3 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.

---
 rust/helpers/helpers.c  |  1 +
 rust/helpers/ww_mutex.c | 39 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 40 insertions(+)
 create mode 100644 rust/helpers/ww_mutex.c
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);
+}
+
Signature · 1 line
2.49.0
author reviewer
#3 lore raw

PATCH v4 3/3 add KUnit coverage on Rust `ww_mutex` implementation

Adds coverage around the core ww_mutex functionality

---
 rust/kernel/sync/lock/ww_mutex.rs | 116 ++++++++++++++++++++++++++++++
 1 file changed, 116 insertions(+)
rust/kernel/sync/lock/ww_mutex.rs +116 -0
index 0f77e03304e4..30c6068f315d 100644
@@ -11,6 +11,7 @@
 use crate::{bindings, str::CStr};
 use core::marker::PhantomData;
 use core::{cell::UnsafeCell, pin::Pin};
+use macros::kunit_tests;
 use pin_init::{pin_data, pin_init, pinned_drop, PinInit};
 
 /// Create static `WwClass` instances.
@@ -417,3 +418,118 @@ fn drop(&mut self) {
         unsafe { bindings::ww_mutex_unlock(self.mutex.as_ptr()) };
     }
 }
+
+#[kunit_tests(rust_kernel_ww_mutex)]
+mod tests {
+    use crate::alloc::KBox;
+    use crate::c_str;
+    use crate::prelude::*;
+    use pin_init::stack_pin_init;
+
+    use super::*;
+
+    // A simple coverage on `define_ww_class` macro.
+    define_ww_class!(TEST_WOUND_WAIT_CLASS, wound_wait, c_str!("test_wound_wait"));
+    define_ww_class!(TEST_WAIT_DIE_CLASS, wait_die, c_str!("test_wait_die"));
+
+    #[test]
+    fn test_ww_mutex_basic_lock_unlock() {
+        stack_pin_init!(let class = WwClass::new_wound_wait(c_str!("test_mutex_class")));
+
+        stack_pin_init!(let mutex = WwMutex::new(42, &class));
+
+        // Lock without context
+        let guard = mutex.lock(None).unwrap();
+        assert_eq!(*guard, 42);
+
+        // Drop the lock
+        drop(guard);
+
+        // Lock it again
+        let mut guard = mutex.lock(None).unwrap();
+        *guard = 100;
+        assert_eq!(*guard, 100);
+    }
+
+    #[test]
+    fn test_ww_mutex_trylock() {
+        stack_pin_init!(let class = WwClass::new_wound_wait(c_str!("trylock_class")));
+
+        stack_pin_init!(let mutex = WwMutex::new(123, &class));
+
+        // trylock on unlocked mutex should succeed
+        let guard = mutex.try_lock(None).unwrap();
+        assert_eq!(*guard, 123);
+        drop(guard);
+
+        // lock it first
+        let _guard1 = mutex.lock(None).unwrap();
+
+        // trylock should fail with EBUSY when already locked
+        let result = mutex.try_lock(None);
+        match result {
+            Err(e) => assert_eq!(e, EBUSY),
+            Ok(_) => panic!("Expected `EBUSY` but got success"),
+        }
+    }
+
+    #[test]
+    fn test_ww_mutex_is_locked() {
+        stack_pin_init!(let class = WwClass::new_wait_die(c_str!("locked_check_class")));
+
+        stack_pin_init!(let mutex = WwMutex::new("hello", &class));
+
+        // should not be locked initially
+        assert!(!mutex.is_locked());
+
+        let guard = mutex.lock(None).unwrap();
+        assert!(mutex.is_locked());
+
+        drop(guard);
+        assert!(!mutex.is_locked());
+    }
+
+    #[test]
+    fn test_ww_acquire_context() {
+        stack_pin_init!(let class = WwClass::new_wound_wait(c_str!("ctx_class")));
+
+        stack_pin_init!(let mutex1 = WwMutex::new(1, &class));
+        stack_pin_init!(let mutex2 = WwMutex::new(2, &class));
+
+        let mut ctx = KBox::pin_init(WwAcquireCtx::new(&class), GFP_KERNEL).unwrap();
+
+        // acquire multiple mutexes with same context
+        let guard1 = mutex1.lock(Some(&ctx)).unwrap();
+        let guard2 = mutex2.lock(Some(&ctx)).unwrap();
+
+        assert_eq!(*guard1, 1);
+        assert_eq!(*guard2, 2);
+
+        ctx.as_mut().done();
+
+        // we shouldn't be able to lock once it's `done`.
+        assert!(mutex1.lock(Some(&ctx)).is_err());
+        assert!(mutex2.lock(Some(&ctx)).is_err());
+    }
+
+    #[test]
+    fn test_with_global_classes() {
+        stack_pin_init!(let wound_wait_mutex = WwMutex::new(100, &TEST_WOUND_WAIT_CLASS));
+        stack_pin_init!(let wait_die_mutex = WwMutex::new(200, &TEST_WAIT_DIE_CLASS));
+
+        let ww_guard = wound_wait_mutex.lock(None).unwrap();
+        let wd_guard = wait_die_mutex.lock(None).unwrap();
+
+        assert_eq!(*ww_guard, 100);
+        assert_eq!(*wd_guard, 200);
+
+        assert!(wound_wait_mutex.is_locked());
+        assert!(wait_die_mutex.is_locked());
+
+        drop(ww_guard);
+        drop(wd_guard);
+
+        assert!(!wound_wait_mutex.is_locked());
+        assert!(!wait_die_mutex.is_locked());
+    }
+}
Signature · 1 line
2.49.0
author reviewer
#1 lore raw

PATCH v4 2/3 implement ww_mutex abstraction for the Rust tree

In reply to Onur Özkan

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

The patch 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

---
 rust/kernel/error.rs              |   1 +
 rust/kernel/sync/lock.rs          |   1 +
 rust/kernel/sync/lock/ww_mutex.rs | 419 ++++++++++++++++++++++++++++++
 3 files changed, 421 insertions(+)
 create mode 100644 rust/kernel/sync/lock/ww_mutex.rs
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 +419 -0

419 lines not on this page · raw message

Signature · 1 line
2.49.0
#5 lore raw
In reply to Onur Özkan
Quoted 4 lines · Onur Özkan

#include "workqueue.c"
#include "xarray.c"
+#include "ww_mutex.c"

Please keep the list sorted.

Also, a couple nits on the series:

- The title would normally be ... vN 1/M ..., rather than the other
way around. You can make Git generate it for you with git format-patch -vN.

- Typically you want to give a changelog, either per-patch (ideal,
especially for non-trivial patches that change a lot) after the first --- line, or per-series (in the cover letter, which is also generally good to have for multi-patch series).

Thanks!

Cheers,
Miguel

#2 lore raw

Re: [PATCH 2/3 v4] implement ww_mutex abstraction for the Rust tree

In reply to Onur Özkan

Hi Onur,

A few docs-related nits, for these and future patches (some apply several times).

Quoted 2 lines · Onur Özkan
Suggested-by [email protected]

Please use the usual format for names/emails, like in the other tags. (Link also typically goes after Suggested-by to link to the suggestion).

Quoted 1 line

+ declare_err!(EDEADLK, "Resource deadlock avoided.");

This should go after ERANGE.

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

Quoted 2 lines
rust/kernel/sync/lock/ww_mutex.rs new file +2 -0
+//! This module provides Rust abstractions for the Linux kernel's `ww_mutex` implementation,
+//! which provides deadlock avoidance through a wait-wound or wait-die algorithm.

Please link the C header like other modules do (with the srctree/ syntax).

In addition, if there are good C docs, you can link those, e.g.

https://docs.kernel.org/locking/ww-mutex-design.html

Quoted 1 line

+use crate::prelude::EBUSY;

Please import the entire prelude, rather than a subset -- that is its goal after all.

In turn, that means you can drop other imports.

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

Quoted 2 lines
rust/kernel/sync/lock/ww_mutex.rs new file +2 -0
+/// Represents a group of mutexes that can participate in deadlock avoidance together.
+/// All mutexes that might be acquired together should use the same class.

The first paragraph is a title ("short description"), which is used in lists of Rust items, so it is best to keep it short. So I would recommend moving the second sentence to a new paragraph.

I would also probably suggest dropping the "Represents", i.e. you can just start with "A group ...", since it is an item.

Quoted 1 line

+ // Ref: https://github.com/torvalds/linux/blob/master/include/linux/ww_mutex.h#L85-L89

These line numbers will likely go stale, and we typically don't link like this.

If you feel like you should link to particular lines, then I can suggest git.kernel.org/linus/ instead and a tag to keep it stable, e.g.:

    https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/ww_mutex.h?h=v6.16-rc2#n85

Also, please use <> to wrap links.

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

Quoted 6 lines
rust/kernel/sync/lock/ww_mutex.rs new file +6 -0
+    /// Creates a `WwClass`.
+    ///
+    /// It's `pub` only so it can be used by the `define_ww_class!` macro.
+    ///
+    /// You should not use this function directly. Use the `define_ww_class!`
+    /// macro or call `WwClass::new_wait_die` or `WwClass::new_wound_wait` instead.

Please use intra-doc links wherever they may work, e.g. [WwClass].

Quoted 1 line

+/// // Create mutexes

Period at the end.

Quoted 1 line

+/// let mut ctx = KBox::pin_init(WwAcquireCtx::new(&class), GFP_KERNEL).unwrap();

Please avoid unwrap() and other panics in examples (and in KUnit tests too -- I will mention it there). assert*! is fine, though, if you want to show that something is a particular value (that is relevant for the example) etc.

More generally, the idea is to try to write code in examples like we would in normal kernel code.

Quoted 1 line

/// use kernel::error::code::EDEADLK;

Some of these should be already available from the prelude, which gets imported automatically, i.e. please check if you can reduce the number of imports in the examples.

Thanks!

Cheers,
Miguel

#4 lore raw

Re: [PATCH 3/3 v4] add KUnit coverage on Rust `ww_mutex` implementation

In reply to Onur Özkan
Quoted 2 lines · Onur Özkan

+ let guard = mutex.lock(None).unwrap();

Like in examples in docs, please try to avoid panicking if possible. assert*!s are fine, though -- they are mapped especially and do not panic.

KUnit tests now support -> Result too, so you can use that too, which is also handy to write code more kernel like, e.g. to replace things that the test is not really concerned about but that should generally not fail like the memory allocation unwrap() that you have below.

Thanks!

Cheers,
Miguel