Skip to content

Commit

Permalink
rust/kernel: remove config #ifdef in mutex.rs file
Browse files Browse the repository at this point in the history
The use of `#ifdef CONFIG_` statements in .c/.rs files should be
avoided: it makes the code much more unmaintainable over time. See:
https://lore.kernel.org/lkml/[email protected]/

Use a Rust-C helper instead to leverage automatic `CONFIG` selection
in C kernel headers.

Signed-off-by: Sven Van Asbroeck <[email protected]>
  • Loading branch information
Sven Van Asbroeck committed Jun 5, 2021
1 parent bfe9ec6 commit a8553d8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
7 changes: 7 additions & 0 deletions rust/helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <linux/highmem.h>
#include <linux/uio.h>
#include <linux/errname.h>
#include <linux/mutex.h>

void rust_helper_BUG(void)
{
Expand Down Expand Up @@ -123,6 +124,12 @@ const char *rust_helper_errname(int err)
return errname(err);
}

void rust_helper_mutex_lock(struct mutex *lock)
{
mutex_lock(lock);
}
EXPORT_SYMBOL_GPL(rust_helper_mutex_lock);

/* We use bindgen's --size_t-is-usize option to bind the C size_t type
* as the Rust usize type, so we can use it in contexts where Rust
* expects a usize like slice (array) indices. usize is defined to be
Expand Down
15 changes: 7 additions & 8 deletions rust/kernel/sync/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,18 @@ impl<T: ?Sized> NeedsLockClass for Mutex<T> {
}
}

extern "C" {
fn rust_helper_mutex_lock(mutex: *mut bindings::mutex);
}

impl<T: ?Sized> Lock for Mutex<T> {
type Inner = T;

#[cfg(not(CONFIG_DEBUG_LOCK_ALLOC))]
fn lock_noguard(&self) {
// SAFETY: `mutex` points to valid memory.
unsafe { bindings::mutex_lock(self.mutex.get()) };
}

#[cfg(CONFIG_DEBUG_LOCK_ALLOC)]
fn lock_noguard(&self) {
// SAFETY: `mutex` points to valid memory.
unsafe { bindings::mutex_lock_nested(self.mutex.get(), 0) };
unsafe {
rust_helper_mutex_lock(self.mutex.get());
}
}

unsafe fn unlock(&self) {
Expand Down

0 comments on commit a8553d8

Please sign in to comment.