Re: [PATCH v16 11/17] rust: sync: lock: Add `Backend::BackendInContext`

From: Benno Lossin

Date: Mon Dec 22 2025 - 01:19:31 EST


On Mon Dec 15, 2025 at 6:57 PM CET, Lyude Paul wrote:
> diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
> index bf2d94c1999bd..938ffe1bac06c 100644
> --- a/rust/kernel/sync/lock.rs
> +++ b/rust/kernel/sync/lock.rs
> @@ -30,10 +30,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 the
> +/// lock 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;
> @@ -47,6 +52,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;
> +

I'm wondering if it'd be better to have a subtrait of `Backend` that
stores all this information instead:

pub unsafe trait BackendWithContext: Backend {
type Context<'a>;

type ContextualBackend: Backend<State = Self::State>;
}

That way, we don't need to specify `()` for the `Context`/`BackendInContext`
in e.g. `Mutex`. And the safety requirements also get much simpler: the
state requirement is directly encoded in the trait bound and the other
part loses the `if` condition.

Then only implement the `lock_with` method on `Lock<T, B>` where `B` is
a `BackendWithContext`.

Cheers,
Benno

> /// Initialises the lock.
> ///
> /// # Safety