Skip to content

Commit d857e42

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 085c23a commit d857e42

File tree

4 files changed

+123
-1
lines changed

4 files changed

+123
-1
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: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88
use crate::types::Opaque;
99

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

0 commit comments

Comments
 (0)