Re: [PATCH v9 8/9] rust: sync: lock: Add `Backend::BackendInContext`

From: Dirk Behme
Date: Mon Mar 03 2025 - 09:23:51 EST


On 27.02.25 23:10, Lyude Paul wrote:
> From: Boqun Feng <boqun.feng@xxxxxxxxx>
>
> `SpinLock`'s backend can be used for `SpinLockIrq`, if the interrupts
> are disabled. And it actually provides performance gains since
> interrupts are not needed to be disabled anymore. So add
> `Backend::BackendInContext` to describe the case where one backend can
> be used for another. Use the it to implement the `lock_with()` so that


Use the it -> Use it (drop "the")?


> `SpinLockIrq` can avoid disabling interrupts by using `SpinLock`'s
> backend.
>
> Signed-off-by: Boqun Feng <boqun.feng@xxxxxxxxx>
> Signed-off-by: Lyude Paul <lyude@xxxxxxxxxx>
> ---
> rust/kernel/sync/lock.rs | 26 ++++++++++++++++++--
> rust/kernel/sync/lock/mutex.rs | 1 +
> rust/kernel/sync/lock/spinlock.rs | 41 +++++++++++++++++++++++++++++++
> 3 files changed, 66 insertions(+), 2 deletions(-)
>
> diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
> index e7c1fd028435e..54c77972c83f8 100644
> --- a/rust/kernel/sync/lock.rs
> +++ b/rust/kernel/sync/lock.rs
> @@ -32,10 +32,15 @@
> /// is owned, that is, between calls to [`lock`] and [`unlock`].
> /// - Implementers must also ensure that [`relock`] uses the same locking method as the original
> /// lock operation.
> +/// - Implementers must ensure if [`BackendInContext`] is a [`Backend`], it's safe to acquire lock


to acquire the lock (add "the")?


> +/// under the [`Context`], the [`State`] of two backends must be the same.
> ///
> /// [`lock`]: Backend::lock
> /// [`unlock`]: Backend::unlock
> /// [`relock`]: Backend::relock
> +/// [`BackendInContext`]: Backend::BackendInContext
> +/// [`Context`]: Backend::Context
> +/// [`State`]: Backend::State
> pub unsafe trait Backend {
> /// The state required by the lock.
> type State;
> @@ -49,6 +54,9 @@ pub unsafe trait Backend {
> /// The context which can be provided to acquire the lock with a different backend.
> type Context<'a>;
>
> + /// The alternative backend we can use if a [`Context`](Backend::Context) is provided.
> + type BackendInContext: Sized;
> +
> /// Initialises the lock.
> ///
> /// # Safety
> @@ -170,8 +178,22 @@ pub unsafe fn from_raw<'a>(ptr: *mut B::State) -> &'a Self {
> impl<T: ?Sized, B: Backend> Lock<T, B> {
> /// Acquires the lock with the given context and gives the caller access to the data protected
> /// by it.
> - pub fn lock_with<'a>(&'a self, _context: B::Context<'a>) -> Guard<'a, T, B> {
> - todo!()
> + pub fn lock_with<'a>(&'a self, _context: B::Context<'a>) -> Guard<'a, T, B::BackendInContext>
> + where
> + B::BackendInContext: Backend,
> + {
> + // SAFETY: Per the safety guarantee of `Backend`, if `B::BackendIncontext` and `B` should
> + // have the same state, therefore the layout of the lock is the same so it's safe the

the -> to (safe to convert)?

Cheers,

Dirk