From 2c91f57e81a7ece7b0b83e93462558f661055963 Mon Sep 17 00:00:00 2001 From: Danilo Krummrich Date: Fri, 26 Jun 2026 20:36:08 +0200 Subject: rust: types: rename ForLt to CovariantForLt Rename ForLt to CovariantForLt to prepare for the introduction of a new ForLt base trait that does not require covariance. The existing ForLt trait requires covariance, which enables the safe cast_ref() method. This rename preserves the same semantics under a more precise name, making room for a weaker ForLt trait in a subsequent commit. No functional change. Reviewed-by: Alexandre Courbot Reviewed-by: Gary Guo Acked-by: Miguel Ojeda Link: https://patch.msgid.link/20260626183630.2585057-2-dakr@kernel.org Signed-off-by: Danilo Krummrich --- rust/kernel/auxiliary.rs | 23 +++++++++--------- rust/kernel/types.rs | 2 +- rust/kernel/types/for_lt.rs | 57 +++++++++++++++++++++++---------------------- 3 files changed, 42 insertions(+), 40 deletions(-) (limited to 'rust/kernel') diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index c42928d5a239..40a0af74a8e5 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -20,7 +20,7 @@ use crate::{ }, prelude::*, types::{ - ForLt, + CovariantForLt, ForeignOwnable, Opaque, // }, @@ -272,16 +272,16 @@ impl Device { /// Returns a pinned reference to the registration data set by the registering (parent) driver. /// - /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The returned + /// `F` is the [`CovariantForLt`](trait@CovariantForLt) encoding of the data type. The returned /// reference has its lifetime shortened from `'static` to `&self`'s borrow lifetime via - /// [`ForLt::cast_ref`]. + /// [`CovariantForLt::cast_ref`]. /// /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling /// [`Registration::new()`]. /// /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was /// registered by a C driver. - pub fn registration_data(&self) -> Result>> { + pub fn registration_data(&self) -> Result>> { // SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`. let ptr = unsafe { (*self.as_raw()).registration_data_rust }; if ptr.is_null() { @@ -399,8 +399,9 @@ struct RegistrationData { /// This type represents the registration of a [`struct auxiliary_device`]. When its parent device /// is unbound, the corresponding auxiliary device will be unregistered from the system. /// -/// The type parameter `F` is a [`ForLt`](trait@ForLt) encoding of the registration -/// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](macro@ForLt). +/// The type parameter `F` is a [`CovariantForLt`](trait@CovariantForLt) encoding of the +/// registration data type. For non-lifetime-parameterized types, use +/// [`CovariantForLt!(T)`](macro@CovariantForLt). /// The data can be accessed by the auxiliary driver through [`Device::registration_data()`]. /// /// # Invariants @@ -408,12 +409,12 @@ struct RegistrationData { /// `self.adev` always holds a valid pointer to an initialized and registered /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a /// valid `Pin>>>`. -pub struct Registration<'a, F: ForLt + 'static> { +pub struct Registration<'a, F: CovariantForLt + 'static> { adev: NonNull, _phantom: PhantomData>, } -impl<'a, F: ForLt> Registration<'a, F> +impl<'a, F: CovariantForLt> Registration<'a, F> where for<'b> F::Of<'b>: Send + Sync, { @@ -525,7 +526,7 @@ where } } -impl Drop for Registration<'_, F> { +impl Drop for Registration<'_, F> { fn drop(&mut self) { // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered // `struct auxiliary_device`. @@ -547,7 +548,7 @@ impl Drop for Registration<'_, F> { } // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread. -unsafe impl Send for Registration<'_, F> where for<'a> F::Of<'a>: Send {} +unsafe impl Send for Registration<'_, F> where for<'a> F::Of<'a>: Send {} // SAFETY: `Registration` does not expose any methods or fields that need synchronization. -unsafe impl Sync for Registration<'_, F> where for<'a> F::Of<'a>: Send {} +unsafe impl Sync for Registration<'_, F> where for<'a> F::Of<'a>: Send {} diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index ac316fd7b538..cbe6907042d3 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -13,7 +13,7 @@ use pin_init::{PinInit, Wrapper, Zeroable}; #[doc(hidden)] pub mod for_lt; -pub use for_lt::ForLt; +pub use for_lt::CovariantForLt; /// Used to transfer ownership to and from foreign (non-Rust) languages. /// diff --git a/rust/kernel/types/for_lt.rs b/rust/kernel/types/for_lt.rs index d44323c28e8d..a11f7509633c 100644 --- a/rust/kernel/types/for_lt.rs +++ b/rust/kernel/types/for_lt.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT -//! Provide implementation and test of the `ForLt` trait and macro. +//! Provide implementation and test of the `CovariantForLt` trait and macro. //! -//! This module is hidden and user should just use `ForLt!` directly. +//! This module is hidden and user should just use `CovariantForLt!` directly. use core::marker::PhantomData; @@ -15,38 +15,39 @@ use core::marker::PhantomData; /// /// # Macro /// -/// It is not recommended to implement this trait directly. `ForLt!` macro is provided to obtain a -/// type that implements this trait. +/// It is not recommended to implement this trait directly. `CovariantForLt!` macro is provided to +/// obtain a type that implements this trait. /// /// The full syntax is /// /// ``` -/// # use kernel::types::ForLt; -/// # fn expect_lt() {} +/// # use kernel::types::CovariantForLt; +/// # fn expect_lt() {} /// # struct TypeThatUse<'a>(&'a ()); /// # expect_lt::< -/// ForLt!(for<'a> TypeThatUse<'a>) +/// CovariantForLt!(for<'a> TypeThatUse<'a>) /// # >(); /// ``` /// -/// which gives a type so that ` TypeThatUse<'a>) as ForLt>::Of<'b>` +/// which gives a type so that +/// ` TypeThatUse<'a>) as CovariantForLt>::Of<'b>` /// is `TypeThatUse<'b>`. /// /// You may also use a short-hand syntax which works similar to lifetime elision. /// The macro also accepts types that do not involve a lifetime at all. /// /// ``` -/// # use kernel::types::ForLt; -/// # fn expect_lt() {} +/// # use kernel::types::CovariantForLt; +/// # fn expect_lt() {} /// # struct TypeThatUse<'a>(&'a ()); /// # expect_lt::< -/// ForLt!(TypeThatUse<'_>) // Equivalent to `ForLt!(for<'a> TypeThatUse<'a>)`. +/// CovariantForLt!(TypeThatUse<'_>) // Equivalent to `CovariantForLt!(for<'a> TypeThatUse<'a>)`. /// # >(); /// # expect_lt::< -/// ForLt!(&u32) // Equivalent to `ForLt!(for<'a> &'a u32)`. +/// CovariantForLt!(&u32) // Equivalent to `CovariantForLt!(for<'a> &'a u32)`. /// # >(); /// # expect_lt::< -/// ForLt!(u32) // Equivalent to `ForLt!(for<'a> u32)`. +/// CovariantForLt!(u32) // Equivalent to `CovariantForLt!(for<'a> u32)`. /// # >(); /// ``` /// @@ -55,10 +56,10 @@ use core::marker::PhantomData; /// it. /// /// ```ignore,compile_fail -/// # use kernel::types::ForLt; -/// # fn expect_lt() {} +/// # use kernel::types::CovariantForLt; +/// # fn expect_lt() {} /// # expect_lt::< -/// ForLt!(fn(&u32)) // Contravariant, will fail compilation. +/// CovariantForLt!(fn(&u32)) // Contravariant, will fail compilation. /// # >(); /// ``` /// @@ -67,23 +68,23 @@ use core::marker::PhantomData; /// the generic parameter but is in a separate item. /// /// ``` -/// # use kernel::types::ForLt; -/// fn expect_lt() {} +/// # use kernel::types::CovariantForLt; +/// fn expect_lt() {} /// # #[allow(clippy::unnecessary_safety_comment, reason = "false positive")] /// fn generic_fn() { /// // Syntactically proven by the macro -/// expect_lt::(); +/// expect_lt::(); /// // Syntactically proven by the macro -/// expect_lt::)>(); +/// expect_lt::)>(); /// // Cannot be syntactically proven, need to check covariance of `KBox` -/// // expect_lt::)>(); +/// // expect_lt::)>(); /// } /// ``` /// /// # Safety /// /// `Self::Of<'a>` must be covariant over the lifetime `'a`. -pub unsafe trait ForLt { +pub unsafe trait CovariantForLt { /// The type parameterized by the lifetime. type Of<'a>: 'a; @@ -94,11 +95,11 @@ pub unsafe trait ForLt { unsafe { core::mem::transmute(long) } } } -pub use macros::ForLt; +pub use macros::CovariantForLt; /// This is intended to be an "unsafe-to-refer-to" type. /// -/// Must only be used by the `ForLt!` macro. +/// Must only be used by the `CovariantForLt!` macro. /// /// `T` is the magic `dyn for<'a> WithLt<'a, TypeThatUse<'a>>` generated by macro. /// @@ -109,14 +110,14 @@ pub use macros::ForLt; #[doc(hidden)] pub struct UnsafeForLtImpl(PhantomData<(WF, T)>); -// This is a helper trait for implementation `ForLt` to be able to use HRTB. +// This is a helper trait for implementation `CovariantForLt` to be able to use HRTB. #[doc(hidden)] pub trait WithLt<'a> { type Of: 'a; } -// SAFETY: In `ForLt!` macro, a covariance proof is generated when naming `UnsafeForLtImpl` -// and it will fail to evaluate if the type is not covariant. -unsafe impl WithLt<'a>, WF> ForLt for UnsafeForLtImpl { +// SAFETY: In `CovariantForLt!` macro, a covariance proof is generated when naming +// `UnsafeForLtImpl` and it will fail to evaluate if the type is not covariant. +unsafe impl WithLt<'a>, WF> CovariantForLt for UnsafeForLtImpl { type Of<'a> = >::Of; } -- cgit v1.2.3 From 1b56056294d45162325bb491f0356fbc6b473a12 Mon Sep 17 00:00:00 2001 From: Danilo Krummrich Date: Fri, 26 Jun 2026 20:36:09 +0200 Subject: rust: types: introduce ForLt base trait for CovariantForLt Add a new ForLt trait as a base for CovariantForLt: - ForLt (non-unsafe): represents a type generic over a lifetime, with no covariance guarantee. - CovariantForLt (unsafe): becomes a subtrait of ForLt that additionally proves the type is covariant over its lifetime parameter, providing a safe cast_ref() method. This split allows non-covariant types (e.g. types behind a Mutex) to implement ForLt and participate in DevresLt / registration data patterns that use HRTB closures for sound access, without requiring a covariance proof that would fail to compile. Both macros share the UnsafeForLtImpl helper type, distinguished by a const generic N: ForLt! emits N = 0 (no covariance proof), CovariantForLt! emits N = 1 (with compile-time covariance proof). Reviewed-by: Gary Guo Acked-by: Miguel Ojeda Link: https://patch.msgid.link/20260626183630.2585057-3-dakr@kernel.org [ Merge ForLt pub use, inline resolve_hrt/ty_static, add intra-doc links. - Danilo ] Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 5 ++- rust/kernel/types/for_lt.rs | 80 +++++++++++++++++++++++++++++++++++---------- 2 files changed, 67 insertions(+), 18 deletions(-) (limited to 'rust/kernel') diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index cbe6907042d3..699aabe01ee5 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -13,7 +13,10 @@ use pin_init::{PinInit, Wrapper, Zeroable}; #[doc(hidden)] pub mod for_lt; -pub use for_lt::CovariantForLt; +pub use for_lt::{ + CovariantForLt, + ForLt, // +}; /// Used to transfer ownership to and from foreign (non-Rust) languages. /// diff --git a/rust/kernel/types/for_lt.rs b/rust/kernel/types/for_lt.rs index a11f7509633c..b8f422c802dc 100644 --- a/rust/kernel/types/for_lt.rs +++ b/rust/kernel/types/for_lt.rs @@ -1,22 +1,67 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT -//! Provide implementation and test of the `CovariantForLt` trait and macro. +//! Provide implementation and test of the [`trait@ForLt`] and [`trait@CovariantForLt`] traits and +//! macros. //! -//! This module is hidden and user should just use `CovariantForLt!` directly. +//! This module is hidden and users should just use [`ForLt!`](macro@ForLt) / +//! [`CovariantForLt!`](macro@CovariantForLt) directly. use core::marker::PhantomData; /// Representation of types generic over a lifetime. /// -/// The type must be covariant over the generic lifetime, i.e. the lifetime parameter -/// can be soundly shortened. +/// # Macro +/// +/// It is not recommended to implement this trait directly. [`ForLt!`](macro@ForLt) macro is +/// provided to obtain a type that implements this trait. /// -/// The lifetime involved must be covariant. +/// The full syntax is +/// +/// ``` +/// # use kernel::types::ForLt; +/// # fn expect_lt() {} +/// # struct TypeThatUse<'a>(&'a ()); +/// # expect_lt::< +/// ForLt!(for<'a> TypeThatUse<'a>) +/// # >(); +/// ``` +/// +/// which gives a type so that ` TypeThatUse<'a>) as ForLt>::Of<'b>` +/// is `TypeThatUse<'b>`. +/// +/// You may also use a short-hand syntax which works similar to lifetime elision. +/// The macro also accepts types that do not involve a lifetime at all. +/// +/// ``` +/// # use kernel::types::ForLt; +/// # fn expect_lt() {} +/// # struct TypeThatUse<'a>(&'a ()); +/// # expect_lt::< +/// ForLt!(TypeThatUse<'_>) // Equivalent to `ForLt!(for<'a> TypeThatUse<'a>)`. +/// # >(); +/// # expect_lt::< +/// ForLt!(&u32) // Equivalent to `ForLt!(for<'a> &'a u32)`. +/// # >(); +/// # expect_lt::< +/// ForLt!(u32) // Equivalent to `ForLt!(for<'a> u32)`. +/// # >(); +/// ``` +pub trait ForLt { + /// The type parameterized by the lifetime. + type Of<'a>: 'a; +} +pub use macros::ForLt; + +/// [`trait@ForLt`] subtrait for types that are covariant over their lifetime parameter. +/// +/// Provides a safe [`cast_ref`](CovariantForLt::cast_ref) method for types that are proven to be +/// covariant. The `CovariantForLt!` macro syntax is the same as `ForLt!`. /// /// # Macro /// -/// It is not recommended to implement this trait directly. `CovariantForLt!` macro is provided to -/// obtain a type that implements this trait. +/// It is not recommended to implement this trait directly. +/// [`CovariantForLt!`](macro@CovariantForLt) macro is provided to obtain a type that implements +/// this trait. /// /// The full syntax is /// @@ -84,10 +129,7 @@ use core::marker::PhantomData; /// # Safety /// /// `Self::Of<'a>` must be covariant over the lifetime `'a`. -pub unsafe trait CovariantForLt { - /// The type parameterized by the lifetime. - type Of<'a>: 'a; - +pub unsafe trait CovariantForLt: ForLt { /// Cast a reference to a shorter lifetime. #[inline(always)] fn cast_ref<'r, 'short: 'r, 'long: 'short>(long: &'r Self::Of<'long>) -> &'r Self::Of<'short> { @@ -99,25 +141,29 @@ pub use macros::CovariantForLt; /// This is intended to be an "unsafe-to-refer-to" type. /// -/// Must only be used by the `CovariantForLt!` macro. +/// Must only be used by the [`ForLt!`](macro@ForLt) / [`CovariantForLt!`](macro@CovariantForLt) +/// macros. /// /// `T` is the magic `dyn for<'a> WithLt<'a, TypeThatUse<'a>>` generated by macro. /// /// `WF` is a type that the macro can use to assert some specific type is well-formed. /// /// `N` is to provide the macro a place to emit arbitrary items, in case it needs to prove -/// additional properties. +/// additional properties. [`ForLt!`](macro@ForLt) emits `N = 0`; +/// [`CovariantForLt!`](macro@CovariantForLt) emits `N = 1` after a covariance proof. #[doc(hidden)] pub struct UnsafeForLtImpl(PhantomData<(WF, T)>); -// This is a helper trait for implementation `CovariantForLt` to be able to use HRTB. +// This is a helper trait for implementation of `ForLt` / `CovariantForLt` to be able to use HRTB. #[doc(hidden)] pub trait WithLt<'a> { type Of: 'a; } -// SAFETY: In `CovariantForLt!` macro, a covariance proof is generated when naming -// `UnsafeForLtImpl` and it will fail to evaluate if the type is not covariant. -unsafe impl WithLt<'a>, WF> CovariantForLt for UnsafeForLtImpl { +impl WithLt<'a>, WF, const N: usize> ForLt for UnsafeForLtImpl { type Of<'a> = >::Of; } + +// SAFETY: In `CovariantForLt!` macro, a covariance proof is generated in the `N` const generic +// and it will fail to evaluate if the type is not covariant. Only `N = 1` gets this impl. +unsafe impl WithLt<'a>, WF> CovariantForLt for UnsafeForLtImpl {} -- cgit v1.2.3 From 491784c54cc10dcc018059a2f2594dd336fa480b Mon Sep 17 00:00:00 2001 From: Danilo Krummrich Date: Fri, 26 Jun 2026 20:36:10 +0200 Subject: rust: auxiliary: add registration_data_with() for ForLt types Add registration_data_with() taking a for<'a> closure that receives Pin<&'a F::Of<'a>>, which works with any ForLt type. Taking a for<'a> closure rather than returning a direct reference prevents callers from choosing a concrete lifetime for the data, which is required for soundness with non-covariant ForLt types. Extract the common null-check, TypeId-check and KBox-borrow logic into a private registration_data_pinned() helper shared by both registration_data_with() and the existing registration_data(). Relax Registration's bound from CovariantForLt to ForLt so that non-covariant types can be registered. Reviewed-by: Gary Guo Reviewed-by: Alexandre Courbot Link: https://patch.msgid.link/20260626183630.2585057-4-dakr@kernel.org Signed-off-by: Danilo Krummrich --- rust/kernel/auxiliary.rs | 93 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 67 insertions(+), 26 deletions(-) (limited to 'rust/kernel') diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index 40a0af74a8e5..19a488700bb9 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -21,6 +21,7 @@ use crate::{ prelude::*, types::{ CovariantForLt, + ForLt, ForeignOwnable, Opaque, // }, @@ -270,18 +271,15 @@ impl Device { unsafe { parent.as_bound() } } - /// Returns a pinned reference to the registration data set by the registering (parent) driver. + /// Returns the stored registration data as a pinned reference. /// - /// `F` is the [`CovariantForLt`](trait@CovariantForLt) encoding of the data type. The returned - /// reference has its lifetime shortened from `'static` to `&self`'s borrow lifetime via - /// [`CovariantForLt::cast_ref`]. + /// Performs null and [`TypeId`] checks, then borrows the stored [`KBox`]. /// - /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling - /// [`Registration::new()`]. + /// # Safety /// - /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was - /// registered by a C driver. - pub fn registration_data(&self) -> Result>> { + /// Callers must ensure that the lifetime shortening from the original `'static` storage to + /// `'_` is sound, e.g. via an HRTB closure or [`CovariantForLt`] guarantee. + unsafe fn registration_data_pinned(&self) -> Result>> { // SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`. let ptr = unsafe { (*self.as_raw()).registration_data_rust }; if ptr.is_null() { @@ -300,17 +298,59 @@ impl Device { return Err(EINVAL); } - // SAFETY: The `TypeId` check above confirms that the stored type matches - // `F::Of<'static>`; `ptr` remains valid until `Registration::drop()` calls - // `from_foreign()`. - let wrapper = unsafe { Pin::>>>::borrow(ptr) }; + // SAFETY: The `TypeId` check above confirms that the stored type matches `F`'s + // encoding; lifetimes are erased at runtime, so borrowing as `F::Of<'_>` is + // layout-compatible with the stored `F::Of<'static>`. `ptr` remains valid until + // `Registration::drop()` calls `from_foreign()`. + let wrapper = unsafe { Pin::>>>::borrow(ptr) }; // SAFETY: `data` is a structurally pinned field of `RegistrationData`. - let pinned: Pin<&F::Of<'_>> = unsafe { wrapper.map_unchecked(|w| &w.data) }; + Ok(unsafe { wrapper.map_unchecked(|w| &w.data) }) + } - // SAFETY: The data was pinned when stored; `cast_ref` only shortens - // the lifetime, so the pinning guarantee is preserved. - Ok(unsafe { Pin::new_unchecked(F::cast_ref(pinned.get_ref())) }) + /// Access the registration data set by the registering (parent) driver through a closure. + /// + /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The closure receives a pinned + /// reference to the registration data. + /// + /// For covariant types that implement [`trait@CovariantForLt`], prefer + /// [`registration_data`](Self::registration_data) which returns a direct reference. + /// + /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling + /// [`Registration::new()`]. + /// + /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was + /// registered by a C driver. + #[inline] + pub fn registration_data_with( + &self, + f: impl for<'a> FnOnce(Pin<&'a F::Of<'a>>) -> R, + ) -> Result { + // SAFETY: The HRTB closure prevents the caller from smuggling in references with a + // concrete short lifetime, making the round-trip from `'static` sound regardless of + // variance. + let pinned = unsafe { self.registration_data_pinned::()? }; + + Ok(f(pinned)) + } + + /// Returns a pinned reference to the registration data set by the registering (parent) driver. + /// + /// This method is only available when `F` implements [`trait@CovariantForLt`], which guarantees + /// that the lifetime shortening is sound. + /// + /// For non-covariant types, use the closure-based [`Self::registration_data_with`]. + /// + /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling + /// [`Registration::new()`]. + /// + /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was + /// registered by a C driver. + #[inline] + pub fn registration_data(&self) -> Result>> { + // SAFETY: `CovariantForLt` guarantees covariance, which makes the lifetime shortening + // from `'static` to `'_` performed by `registration_data_pinned` sound. + unsafe { self.registration_data_pinned::() } } } @@ -399,22 +439,23 @@ struct RegistrationData { /// This type represents the registration of a [`struct auxiliary_device`]. When its parent device /// is unbound, the corresponding auxiliary device will be unregistered from the system. /// -/// The type parameter `F` is a [`CovariantForLt`](trait@CovariantForLt) encoding of the -/// registration data type. For non-lifetime-parameterized types, use -/// [`CovariantForLt!(T)`](macro@CovariantForLt). -/// The data can be accessed by the auxiliary driver through [`Device::registration_data()`]. +/// The type parameter `F` is a [`ForLt`](trait@ForLt) encoding of the registration +/// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](macro@ForLt). +/// +/// The data can be accessed by the auxiliary driver through [`Device::registration_data()`] and +/// [`Device::registration_data_with()`]. /// /// # Invariants /// /// `self.adev` always holds a valid pointer to an initialized and registered /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a /// valid `Pin>>>`. -pub struct Registration<'a, F: CovariantForLt + 'static> { +pub struct Registration<'a, F: ForLt + 'static> { adev: NonNull, _phantom: PhantomData>, } -impl<'a, F: CovariantForLt> Registration<'a, F> +impl<'a, F: ForLt> Registration<'a, F> where for<'b> F::Of<'b>: Send + Sync, { @@ -526,7 +567,7 @@ where } } -impl Drop for Registration<'_, F> { +impl Drop for Registration<'_, F> { fn drop(&mut self) { // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered // `struct auxiliary_device`. @@ -548,7 +589,7 @@ impl Drop for Registration<'_, F> { } // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread. -unsafe impl Send for Registration<'_, F> where for<'a> F::Of<'a>: Send {} +unsafe impl Send for Registration<'_, F> where for<'a> F::Of<'a>: Send {} // SAFETY: `Registration` does not expose any methods or fields that need synchronization. -unsafe impl Sync for Registration<'_, F> where for<'a> F::Of<'a>: Send {} +unsafe impl Sync for Registration<'_, F> where for<'a> F::Of<'a>: Send {} -- cgit v1.2.3 From b85f672a3e68ed16e8c7fa96ec1f090a173930ad Mon Sep 17 00:00:00 2001 From: Danilo Krummrich Date: Fri, 26 Jun 2026 20:36:12 +0200 Subject: rust: devres: add DevresLt for ForLt-aware device resource access Devres stores resources as T and returns &'a T from access(). For lifetime-parameterized types like Bar<'a, SIZE> that are transmuted to 'static for storage, this exposes the synthetic 'static lifetime to callers -- any method on the stored type that returns a reference with its lifetime parameter would yield a &'static reference, which is unsound. Add DevresLt, a thin wrapper around Devres> that shortens the stored 'static lifetime to the caller's borrow lifetime in all access methods. DevresLt::new() is unsafe because the caller must guarantee that the data remains valid for the device's full bound scope; the internal transmute from F::Of<'a> to F::Of<'static> would otherwise allow use-after-free. Two access patterns are provided: - CovariantForLt types get direct-reference accessors (access, try_access) that return shortened references via CovariantForLt::cast_ref. - Plain ForLt types use closure-based accessors (access_with, try_access_with) whose universally quantified lifetime prevents callers from smuggling in concrete short-lived references. Reviewed-by: Alexandre Courbot Link: https://patch.msgid.link/20260626183630.2585057-6-dakr@kernel.org Signed-off-by: Danilo Krummrich --- rust/kernel/devres.rs | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) (limited to 'rust/kernel') diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 11ce500e9b76..b7c075a39ba4 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -24,6 +24,8 @@ use crate::{ Arc, // }, types::{ + CovariantForLt, + ForLt, ForeignOwnable, Opaque, // }, @@ -365,6 +367,110 @@ impl Drop for Devres { } } +/// Guard returned by [`DevresLt::try_access`]. +/// +/// Dereferences to `F::Of<'a>`, shortening the lifetime of the stored data to the guard's borrow +/// lifetime. +pub struct DevresGuard<'a, F: CovariantForLt>(RevocableGuard<'a, F::Of<'static>>); + +impl<'a, F: CovariantForLt> core::ops::Deref for DevresGuard<'a, F> { + type Target = F::Of<'a>; + + #[inline] + fn deref(&self) -> &Self::Target { + F::cast_ref(&*self.0) + } +} + +/// Device-managed resource with [`ForLt`](trait@ForLt)-aware access. +/// +/// `DevresLt` wraps [`Devres`] and shortens the stored `'static` lifetime to the caller's borrow +/// lifetime in all access methods. +/// +/// Types that implement [`trait@CovariantForLt`] get direct-reference accessors ([`Self::access`], +/// [`Self::try_access`]). Plain [`ForLt`](trait@ForLt) types use closure-based accessors +/// ([`Self::access_with`], [`Self::try_access_with`]). +pub struct DevresLt(Devres>) +where + for<'a> F::Of<'a>: Send; + +impl DevresLt +where + for<'a> F::Of<'a>: Send, +{ + /// Creates a new [`DevresLt`] instance of the given `data`. + /// + /// # Safety + /// + /// The data must remain valid for the device's full bound scope. [`DevresLt`] allows + /// access until the device is unbound, which may outlast `'a`. + pub unsafe fn new<'a, E>( + dev: &'a Device, + data: impl PinInit, E>, + ) -> Result + where + Error: From, + { + // SAFETY: The caller guarantees the data is valid for the device's full bound scope. + // Lifetimes do not affect layout, so F::Of<'a> and F::Of<'static> have identical + // representation; casting the slot pointer is sound. + let data = unsafe { + pin_init::pin_init_from_closure::, E>(move |slot| { + data.__pinned_init(slot.cast()) + }) + }; + + Ok(Self(Devres::new(dev, data)?)) + } + + /// Return a reference of the [`Device`] this [`DevresLt`] instance has been created with. + #[inline] + pub fn device(&self) -> &Device { + self.0.device() + } + + /// Obtain `&F::Of<'_>`, bypassing the [`Revocable`], through a closure. + /// + /// This method works like [`DevresLt::access`](DevresLt::access) but accepts any + /// [`trait@ForLt`] type, not just [`trait@CovariantForLt`]. + #[inline] + pub fn access_with(&self, dev: &Device, f: G) -> Result + where + G: for<'a> FnOnce(&F::Of<'a>) -> R, + { + self.0.access(dev).map(f) + } + + /// [`DevresLt`] accessor for [`Revocable::try_access_with`]. + #[inline] + pub fn try_access_with(&self, f: G) -> Option + where + G: for<'a> FnOnce(&F::Of<'a>) -> R, + { + self.0.data().try_access_with(f) + } +} + +impl DevresLt +where + for<'a> F::Of<'a>: Send, +{ + /// Obtain `&'a F::Of<'a>`, bypassing the [`Revocable`]. + /// + /// This method works like [`Devres::access`], but shortens the returned reference's lifetime + /// from `'static` to `'a` via [`CovariantForLt::cast_ref`]. + #[inline] + pub fn access<'a>(&'a self, dev: &'a Device) -> Result<&'a F::Of<'a>> { + self.0.access(dev).map(F::cast_ref) + } + + /// [`DevresLt`] accessor for [`Revocable::try_access`]. + #[inline] + pub fn try_access(&self) -> Option> { + self.0.data().try_access().map(DevresGuard) + } +} + /// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound. fn register_foreign

(dev: &Device, data: P) -> Result where -- cgit v1.2.3 From e7e6bf5af80e7454ebb92a998a2ab931cb27204f Mon Sep 17 00:00:00 2001 From: Danilo Krummrich Date: Fri, 26 Jun 2026 20:36:13 +0200 Subject: rust: pci: return DevresLt from Bar::into_devres() Implement ForLt and CovariantForLt for Bar<'static, SIZE> so that DevresLt can shorten the stored 'static lifetime back to the caller's borrow lifetime. CovariantForLt is sound because Bar<'a, SIZE> only holds &'a Device, which is covariant over 'a. Since DevresLt::new() handles the lifetime transmutation internally, into_devres() no longer needs an explicit transmute to Bar<'static>. Add a DevresBar type alias for convenience. Reviewed-by: Alexandre Courbot Link: https://patch.msgid.link/20260626183630.2585057-7-dakr@kernel.org [ Add default SIZE parameter to DevresBar. - Danilo ] Signed-off-by: Danilo Krummrich --- rust/kernel/pci.rs | 1 + rust/kernel/pci/io.rs | 37 ++++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-) (limited to 'rust/kernel') diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 5071cae6543f..f783b9d9fa26 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -45,6 +45,7 @@ pub use self::io::{ ConfigSpace, ConfigSpaceKind, ConfigSpaceSize, + DevresBar, Extended, Normal, // }; diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 0461e01aaa20..6ebfbf368cd3 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -6,7 +6,7 @@ use super::Device; use crate::{ bindings, device, - devres::Devres, + devres::DevresLt, io::{ Io, IoCapable, @@ -14,7 +14,11 @@ use crate::{ Mmio, MmioRaw, // }, - prelude::*, // + prelude::*, + types::{ + CovariantForLt, + ForLt, // + }, // }; use core::{ marker::PhantomData, @@ -151,6 +155,19 @@ pub struct Bar<'a, const SIZE: usize = 0> { num: i32, } +impl ForLt for Bar<'static, SIZE> { + type Of<'a> = Bar<'a, SIZE>; +} + +// SAFETY: `Bar<'a, SIZE>` is covariant over `'a`; it holds `&'a Device`, +// which is covariant. +unsafe impl CovariantForLt for Bar<'static, SIZE> {} + +/// A device-managed PCI BAR mapping. +/// +/// See [`Bar::into_devres`]. +pub type DevresBar = DevresLt>; + impl<'a, const SIZE: usize> Bar<'a, SIZE> { pub(super) fn new( pdev: &'a Device, @@ -223,15 +240,13 @@ impl<'a, const SIZE: usize> Bar<'a, SIZE> { /// Consume the `Bar` and register it as a device-managed resource. /// - /// The returned `Devres>` can outlive the original lifetime `'a`. Access - /// to the BAR is revoked when the device is unbound. - pub fn into_devres(self) -> Result>> { - // SAFETY: Casting to `'static` is sound because `Devres` guarantees the `Bar` does not - // actually outlive the device -- access is revoked and the resource is released when the - // device is unbound. - let bar: Bar<'static, SIZE> = unsafe { core::mem::transmute(self) }; - let pdev = bar.pdev; - Devres::new(pdev.as_ref(), bar) + /// The returned [`DevresBar`] can outlive the original borrow and be stored in driver data. + /// Access to the BAR is revoked automatically when the device is unbound. + pub fn into_devres(self) -> Result> { + let pdev = self.pdev; + // SAFETY: `Bar` only holds a reference to the device and an I/O mapping, both of which + // remain valid for the device's full bound scope, not just for `'a`. + unsafe { DevresLt::new(pdev.as_ref(), self) } } } -- cgit v1.2.3 From 7488dc14b05aa4a478497ee1b498a4a46ab9428c Mon Sep 17 00:00:00 2001 From: Danilo Krummrich Date: Fri, 26 Jun 2026 20:36:14 +0200 Subject: rust: io: mem: return DevresLt from IoMem/ExclusiveIoMem::into_devres() Implement ForLt and CovariantForLt for IoMem<'static, SIZE> and ExclusiveIoMem<'static, SIZE> so that DevresLt can shorten the stored 'static lifetime back to the caller's borrow lifetime. CovariantForLt is sound because both types only hold &'a Device, which is covariant over 'a. Since DevresLt::new() handles the lifetime transmutation internally, into_devres() no longer needs an explicit transmute to 'static. Add DevresIoMem and DevresExclusiveIoMem type aliases. Reviewed-by: Alexandre Courbot Link: https://patch.msgid.link/20260626183630.2585057-8-dakr@kernel.org [ Add default SIZE parameter to DevresIoMem. - Danilo ] Signed-off-by: Danilo Krummrich --- rust/kernel/io/mem.rs | 65 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 45 insertions(+), 20 deletions(-) (limited to 'rust/kernel') diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index fc2a3e24f8d5..931f2fa3bb10 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -9,7 +9,7 @@ use crate::{ Bound, Device, // }, - devres::Devres, + devres::DevresLt, io::{ self, resource::{ @@ -20,6 +20,10 @@ use crate::{ MmioRaw, // }, prelude::*, + types::{ + CovariantForLt, + ForLt, // + }, }; /// An IO request for a specific device and resource. @@ -172,6 +176,19 @@ pub struct ExclusiveIoMem<'a, const SIZE: usize> { _region: Region, } +impl ForLt for ExclusiveIoMem<'static, SIZE> { + type Of<'a> = ExclusiveIoMem<'a, SIZE>; +} + +// SAFETY: `ExclusiveIoMem<'a, SIZE>` is covariant over `'a`; it holds an `IoMem<'a, SIZE>`, +// which holds `&'a Device`, which is covariant. +unsafe impl CovariantForLt for ExclusiveIoMem<'static, SIZE> {} + +/// A device-managed exclusive I/O memory region. +/// +/// See [`ExclusiveIoMem::into_devres`]. +pub type DevresExclusiveIoMem = DevresLt>; + impl<'a, const SIZE: usize> ExclusiveIoMem<'a, SIZE> { /// Creates a new `ExclusiveIoMem` instance. fn ioremap(dev: &'a Device, resource: &Resource) -> Result { @@ -198,15 +215,13 @@ impl<'a, const SIZE: usize> ExclusiveIoMem<'a, SIZE> { /// Consume the `ExclusiveIoMem` and register it as a device-managed resource. /// - /// The returned `Devres>` can outlive the original lifetime - /// `'a`. Access to the I/O memory is revoked when the device is unbound. - pub fn into_devres(self) -> Result>> { - // SAFETY: Casting to `'static` is sound because `Devres` guarantees the - // `ExclusiveIoMem` does not actually outlive the device -- access is revoked and the - // resource is released when the device is unbound. - let iomem: ExclusiveIoMem<'static, SIZE> = unsafe { core::mem::transmute(self) }; - let dev = iomem.iomem.dev; - Devres::new(dev, iomem) + /// The returned [`DevresExclusiveIoMem`] can outlive the original borrow and be stored in + /// driver data. Access to the I/O memory is revoked automatically when the device is unbound. + pub fn into_devres(self) -> Result> { + let dev = self.iomem.dev; + // SAFETY: `ExclusiveIoMem` only holds a device reference and an I/O mapping, both of + // which remain valid for the device's full bound scope, not just for `'a`. + unsafe { DevresLt::new(dev, self) } } } @@ -232,6 +247,19 @@ pub struct IoMem<'a, const SIZE: usize = 0> { io: MmioRaw, } +impl ForLt for IoMem<'static, SIZE> { + type Of<'a> = IoMem<'a, SIZE>; +} + +// SAFETY: `IoMem<'a, SIZE>` is covariant over `'a`; it holds `&'a Device`, +// which is covariant. +unsafe impl CovariantForLt for IoMem<'static, SIZE> {} + +/// A device-managed I/O memory region. +/// +/// See [`IoMem::into_devres`]. +pub type DevresIoMem = DevresLt>; + impl<'a, const SIZE: usize> IoMem<'a, SIZE> { fn ioremap(dev: &'a Device, resource: &Resource) -> Result { // Note: Some ioremap() implementations use types that depend on the CPU @@ -271,16 +299,13 @@ impl<'a, const SIZE: usize> IoMem<'a, SIZE> { /// Consume the `IoMem` and register it as a device-managed resource. /// - /// The returned `Devres>` can outlive the original - /// lifetime `'a`. Access to the I/O memory is revoked when the device - /// is unbound. - pub fn into_devres(self) -> Result>> { - // SAFETY: Casting to `'static` is sound because `Devres` guarantees the `IoMem` does not - // actually outlive the device -- access is revoked and the resource is released when the - // device is unbound. - let iomem: IoMem<'static, SIZE> = unsafe { core::mem::transmute(self) }; - let dev = iomem.dev; - Devres::new(dev, iomem) + /// The returned [`DevresIoMem`] can outlive the original borrow and be stored in driver data. + /// Access to the I/O memory is revoked automatically when the device is unbound. + pub fn into_devres(self) -> Result> { + let dev = self.dev; + // SAFETY: `IoMem` only holds a device reference and an I/O mapping, both of which + // remain valid for the device's full bound scope, not just for `'a`. + unsafe { DevresLt::new(dev, self) } } } -- cgit v1.2.3