Commit f73ca66f authored by Mitchell Levy's avatar Mitchell Levy Committed by Ingo Molnar
Browse files

rust: lockdep: Use Pin for all LockClassKey usages

Reintroduce dynamically-allocated LockClassKeys such that they are
automatically (de)registered. Require that all usages of LockClassKeys
ensure that they are Pin'd.

Currently, only `'static` LockClassKeys are supported, so Pin is
redundant. However, it is intended that dynamically-allocated
LockClassKeys will eventually be supported, so using Pin from the outset
will make that change simpler.

Closes: https://github.com/Rust-for-Linux/linux/issues/1102


Suggested-by: default avatarBenno Lossin <benno.lossin@proton.me>
Suggested-by: default avatarBoqun Feng <boqun.feng@gmail.com>
Signed-off-by: default avatarMitchell Levy <levymitchell0@gmail.com>
Signed-off-by: default avatarBoqun Feng <boqun.feng@gmail.com>
Signed-off-by: default avatarIngo Molnar <mingo@kernel.org>
Reviewed-by: default avatarBenno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20250307232717.1759087-12-boqun.feng@gmail.com
parent 70b9c856
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -30,6 +30,7 @@
#include "signal.c"
#include "slab.c"
#include "spinlock.c"
#include "sync.c"
#include "task.c"
#include "uaccess.c"
#include "vmalloc.c"

rust/helpers/sync.c

0 → 100644
+13 −0
Original line number Diff line number Diff line
// SPDX-License-Identifier: GPL-2.0

#include <linux/lockdep.h>

void rust_helper_lockdep_register_key(struct lock_class_key *k)
{
	lockdep_register_key(k);
}

void rust_helper_lockdep_unregister_key(struct lock_class_key *k)
{
	lockdep_unregister_key(k);
}
+54 −3
Original line number Diff line number Diff line
@@ -5,6 +5,8 @@
//! This module contains the kernel APIs related to synchronisation that have been ported or
//! wrapped for usage by Rust code in the kernel.

use crate::pin_init;
use crate::prelude::*;
use crate::types::Opaque;

mod arc;
@@ -23,15 +25,64 @@

/// Represents a lockdep class. It's a wrapper around C's `lock_class_key`.
#[repr(transparent)]
pub struct LockClassKey(Opaque<bindings::lock_class_key>);
#[pin_data(PinnedDrop)]
pub struct LockClassKey {
    #[pin]
    inner: Opaque<bindings::lock_class_key>,
}

// SAFETY: `bindings::lock_class_key` is designed to be used concurrently from multiple threads and
// provides its own synchronization.
unsafe impl Sync for LockClassKey {}

impl LockClassKey {
    /// Initializes a dynamically allocated lock class key. In the common case of using a
    /// statically allocated lock class key, the static_lock_class! macro should be used instead.
    ///
    /// # Example
    /// ```
    /// # use kernel::{c_str, stack_pin_init};
    /// # use kernel::alloc::KBox;
    /// # use kernel::types::ForeignOwnable;
    /// # use kernel::sync::{LockClassKey, SpinLock};
    ///
    /// let key = KBox::pin_init(LockClassKey::new_dynamic(), GFP_KERNEL)?;
    /// let key_ptr = key.into_foreign();
    ///
    /// {
    ///     stack_pin_init!(let num: SpinLock<u32> = SpinLock::new(
    ///         0,
    ///         c_str!("my_spinlock"),
    ///         // SAFETY: `key_ptr` is returned by the above `into_foreign()`, whose
    ///         // `from_foreign()` has not yet been called.
    ///         unsafe { <Pin<KBox<LockClassKey>> as ForeignOwnable>::borrow(key_ptr) }
    ///     ));
    /// }
    ///
    /// // SAFETY: We dropped `num`, the only use of the key, so the result of the previous
    /// // `borrow` has also been dropped. Thus, it's safe to use from_foreign.
    /// unsafe { drop(<Pin<KBox<LockClassKey>> as ForeignOwnable>::from_foreign(key_ptr)) };
    ///
    /// # Ok::<(), Error>(())
    /// ```
    pub fn new_dynamic() -> impl PinInit<Self> {
        pin_init!(Self {
            // SAFETY: lockdep_register_key expects an uninitialized block of memory
            inner <- Opaque::ffi_init(|slot| unsafe { bindings::lockdep_register_key(slot) })
        })
    }

    pub(crate) fn as_ptr(&self) -> *mut bindings::lock_class_key {
        self.0.get()
        self.inner.get()
    }
}

#[pinned_drop]
impl PinnedDrop for LockClassKey {
    fn drop(self: Pin<&mut Self>) {
        // SAFETY: self.as_ptr was registered with lockdep and self is pinned, so the address
        // hasn't changed. Thus, it's safe to pass to unregister.
        unsafe { bindings::lockdep_unregister_key(self.as_ptr()) }
    }
}

@@ -44,7 +95,7 @@ macro_rules! static_lock_class {
            // SAFETY: lockdep expects uninitialized memory when it's handed a statically allocated
            // lock_class_key
            unsafe { ::core::mem::MaybeUninit::uninit().assume_init() };
        &CLASS
        $crate::prelude::Pin::static_ref(&CLASS)
    }};
}

+2 −3
Original line number Diff line number Diff line
@@ -17,8 +17,7 @@
    time::Jiffies,
    types::Opaque,
};
use core::marker::PhantomPinned;
use core::ptr;
use core::{marker::PhantomPinned, pin::Pin, ptr};
use macros::pin_data;

/// Creates a [`CondVar`] initialiser with the given name and a newly-created lock class.
@@ -103,7 +102,7 @@ unsafe impl Sync for CondVar {}

impl CondVar {
    /// Constructs a new condvar initialiser.
    pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> {
    pub fn new(name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self> {
        pin_init!(Self {
            _pin: PhantomPinned,
            // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
+2 −2
Original line number Diff line number Diff line
@@ -12,7 +12,7 @@
    str::CStr,
    types::{NotThreadSafe, Opaque, ScopeGuard},
};
use core::{cell::UnsafeCell, marker::PhantomPinned};
use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
use macros::pin_data;

pub mod mutex;
@@ -129,7 +129,7 @@ unsafe impl<T: ?Sized + Send, B: Backend> Sync for Lock<T, B> {}

impl<T, B: Backend> Lock<T, B> {
    /// Constructs a new lock initialiser.
    pub fn new(t: T, name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self> {
    pub fn new(t: T, name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self> {
        pin_init!(Self {
            data: UnsafeCell::new(t),
            _pin: PhantomPinned,
Loading