Skip to content

Commit e87ca94

Browse files
committed
rust: lock: introduce Mutex
This is the `struct mutex` lock backend and allows Rust code to use the kernel mutex idiomatically. Cc: Peter Zijlstra <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Will Deacon <[email protected]> Cc: Waiman Long <[email protected]> Signed-off-by: Wedson Almeida Filho <[email protected]>
1 parent 07f0795 commit e87ca94

File tree

4 files changed

+128
-0
lines changed

4 files changed

+128
-0
lines changed

rust/helpers.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,20 @@
2121
#include <linux/bug.h>
2222
#include <linux/build_bug.h>
2323
#include <linux/refcount.h>
24+
#include <linux/mutex.h>
2425

2526
__noreturn void rust_helper_BUG(void)
2627
{
2728
BUG();
2829
}
2930
EXPORT_SYMBOL_GPL(rust_helper_BUG);
3031

32+
void rust_helper_mutex_lock(struct mutex *lock)
33+
{
34+
mutex_lock(lock);
35+
}
36+
EXPORT_SYMBOL_GPL(rust_helper_mutex_lock);
37+
3138
refcount_t rust_helper_REFCOUNT_INIT(int n)
3239
{
3340
return (refcount_t)REFCOUNT_INIT(n);

rust/kernel/sync.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ mod arc;
1111
pub mod lock;
1212

1313
pub use arc::{Arc, ArcBorrow, UniqueArc};
14+
pub use lock::mutex::Mutex;
1415

1516
/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`.
1617
#[repr(transparent)]

rust/kernel/sync/lock.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ use crate::{bindings, init::PinInit, pin_init, str::CStr, types::Opaque};
1010
use core::{cell::UnsafeCell, marker::PhantomData, marker::PhantomPinned};
1111
use macros::pin_data;
1212

13+
pub mod mutex;
14+
1315
/// The "backend" of a lock.
1416
///
1517
/// It is the actual implementation of the lock, without the need to repeat patterns used in all

rust/kernel/sync/lock/mutex.rs

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! A kernel mutex.
4+
//!
5+
//! This module allows Rust code to use the kernel's `struct mutex`.
6+
7+
use crate::bindings;
8+
9+
/// Creates a [`Mutex`] initialiser with the given name and a newly-created lock class.
10+
///
11+
/// It uses the name if one is given, otherwise it generates one based on the file name and line
12+
/// number.
13+
#[macro_export]
14+
macro_rules! new_mutex {
15+
($inner:expr $(, $name:literal)? $(,)?) => {
16+
$crate::sync::Mutex::new(
17+
$inner, $crate::optional_name!($($name)?), $crate::static_lock_class!())
18+
};
19+
}
20+
21+
/// A mutual exclusion primitive.
22+
///
23+
/// Exposes the kernel's [`struct mutex`]. When multiple threads attempt to lock the same mutex,
24+
/// only one at a time is allowed to progress, the others will block (sleep) until the mutex is
25+
/// unlocked, at which point another thread will be allowed to wake up and make progress.
26+
///
27+
/// Since it may block, [`Mutex`] needs to be used with care in atomic contexts.
28+
///
29+
/// Instances of [`Mutex`] need a lock class and to be pinned. The recommended way to create such
30+
/// instances is with the [`pin_init`](crate::pin_init) and [`new_mutex`] macros.
31+
///
32+
/// # Examples
33+
///
34+
/// The following example shows how to declare, allocate and initialise a struct (`Example`) that
35+
/// contains an inner struct (`Inner`) that is protected by a mutex.
36+
///
37+
/// ```
38+
/// use kernel::{init::InPlaceInit, init::PinInit, new_mutex, pin_init, sync::Mutex};
39+
///
40+
/// struct Inner {
41+
/// a: u32,
42+
/// b: u32,
43+
/// }
44+
///
45+
/// #[pin_data]
46+
/// struct Example {
47+
/// c: u32,
48+
/// #[pin]
49+
/// d: Mutex<Inner>,
50+
/// }
51+
///
52+
/// impl Example {
53+
/// fn new() -> impl PinInit<Self> {
54+
/// pin_init!(Self {
55+
/// c: 10,
56+
/// d <- new_mutex!(Inner { a: 20, b: 30 }),
57+
/// })
58+
/// }
59+
/// }
60+
///
61+
/// // Allocate a boxed `Example`.
62+
/// let e = Box::pin_init(Example::new())?;
63+
/// assert_eq!(e.c, 10);
64+
/// assert_eq!(e.d.lock().a, 20);
65+
/// assert_eq!(e.d.lock().b, 30);
66+
/// ```
67+
///
68+
/// The following example shows how to use interior mutability to modify the contents of a struct
69+
/// protected by a mutex despite only having a shared reference:
70+
///
71+
/// ```
72+
/// use kernel::sync::Mutex;
73+
///
74+
/// struct Example {
75+
/// a: u32,
76+
/// b: u32,
77+
/// }
78+
///
79+
/// fn example(m: &Mutex<Example>) {
80+
/// let mut guard = m.lock();
81+
/// guard.a += 10;
82+
/// guard.b += 20;
83+
/// }
84+
/// ```
85+
///
86+
/// [`struct mutex`]: ../../../../include/linux/mutex.h
87+
pub type Mutex<T> = super::Lock<T, MutexBackend>;
88+
89+
/// A kernel `struct mutex` lock backend.
90+
pub struct MutexBackend;
91+
92+
// SAFETY: The underlying kernel `struct mutex` object ensures mutual exclusion.
93+
unsafe impl super::Backend for MutexBackend {
94+
type State = bindings::mutex;
95+
type GuardState = ();
96+
97+
unsafe fn init(
98+
ptr: *mut Self::State,
99+
name: *const core::ffi::c_char,
100+
key: *mut bindings::lock_class_key,
101+
) {
102+
// SAFETY: The safety requirements ensure that `ptr` is valid for writes, and `name` and
103+
// `key` are valid for read indefinitely.
104+
unsafe { bindings::__mutex_init(ptr, name, key) }
105+
}
106+
107+
unsafe fn lock(ptr: *mut Self::State) -> Self::GuardState {
108+
// SAFETY: The safety requirements of this function ensure that `ptr` points to valid
109+
// memory, and that it has been initialised before.
110+
unsafe { bindings::mutex_lock(ptr) };
111+
}
112+
113+
unsafe fn unlock(ptr: *mut Self::State, _guard_state: &Self::GuardState) {
114+
// SAFETY: The safety requirements of this function ensure that `ptr` is valid and that the
115+
// caller is the owner of the mutex.
116+
unsafe { bindings::mutex_unlock(ptr) };
117+
}
118+
}

0 commit comments

Comments
 (0)