From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D09C83009D4; Wed, 3 Jun 2026 01:10:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449034; cv=none; b=eym7BmLoIImGoEIuT+QKDxun6Zl2YoCKOCvGy8UfWQKbtmOyifuDUNuz+5/aBBQnRgZpCuoWmdHAc9kx1xnNWdEqLOERVwblRswdDAWy3zExfYUddmPTHCp+fIXWzzTXehM8++pzLAX7YRdFdohxYNLkCj3KLLn9WyaU2gU/ilY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449034; c=relaxed/simple; bh=i4XYcmDtnqt8WTR+fYIp8lD6BYSRNbq4l4LKDNpZzTQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=uGgdrw03kIOy0SQ8ugty4A199fzvitDqtgun57CBRaJ0vSM5cm/4y+PgT3vXXce21xJym7cgvlPcF+PNkLRKWsTZpmqsIeXkTEueqB7FXPAIzU8/2BsXHvfB9QnvZ+i+Cx/bqiof4AyNft8R7T8K/GS+i/fBRPUgrcjNRZjhikU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=MxRCovIc; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="MxRCovIc" Received: by smtp.kernel.org (Postfix) with ESMTPSA id B415E1F00898; Wed, 3 Jun 2026 01:10:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449032; bh=wwWFb/VYif3ZZHAOc0E3QU4RogxZ39CKNKOixWvfwK4=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=MxRCovIcwAtWWFXC7oCfKa6sOblVR61MKYnY0VBrzGB6jcsAoTq9qpbnocKsJo5zd XO/gz3x0Zq3V9PzhLfeftL3eRdB8BVpg4nAj6SEK+exKx6YRKY9y5nOLfOBTq0I4cK Om7f3NP5b885eWJrCg0LRSZjRG1I1mOWHCr9pAXo62hY6zvwVnAs/R46xCy5V4nskb veLqMke0wRxpLWPQpPkyyP/s//yhTjusqX3rQ6DPAR018d6FY25tDXydGB+RKmVi2k d6xc0mt2ljnGG8N4if+vr1sP17xGBlch3KiNBtQ6qrP0YpC66eHN2UCA8/npfgUZFN 9dK/7UIT1OqiA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 1/7] rust: types: rename ForLt to CovariantForLt Date: Wed, 3 Jun 2026 03:10:12 +0200 Message-ID: <20260603011020.2073650-2-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Signed-off-by: Danilo Krummrich --- drivers/gpu/nova-core/driver.rs | 4 +- rust/kernel/auxiliary.rs | 23 +++++----- rust/kernel/types.rs | 2 +- rust/kernel/types/for_lt.rs | 61 ++++++++++++++------------- rust/macros/for_lt.rs | 4 +- rust/macros/lib.rs | 11 +++-- samples/rust/rust_driver_auxiliary.rs | 8 ++-- 7 files changed, 57 insertions(+), 56 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index ade73da68be5..dce8b3b8dc6f 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -15,7 +15,7 @@ Atomic, Relaxed, // }, - types::ForLt, + types::CovariantForLt, }; =20 use crate::gpu::Gpu; @@ -29,7 +29,7 @@ pub(crate) struct NovaCore<'bound> { pub(crate) gpu: Gpu<'bound>, bar: pci::Bar<'bound, BAR0_SIZE>, #[allow(clippy::type_complexity)] - _reg: auxiliary::Registration<'bound, ForLt!(())>, + _reg: auxiliary::Registration<'bound, CovariantForLt!(())>, } =20 pub(crate) struct NovaCoreDriver; 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 @@ }, prelude::*, types::{ - ForLt, + CovariantForLt, ForeignOwnable, Opaque, // }, @@ -272,16 +272,16 @@ pub fn parent(&self) -> &device::Device { =20 /// Returns a pinned reference to the registration data set by the reg= istering (parent) driver. /// - /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The r= eturned + /// `F` is the [`CovariantForLt`](trait@CovariantForLt) encoding of th= e data type. The returned /// reference has its lifetime shortened from `'static` to `&self`'s b= orrow lifetime via - /// [`ForLt::cast_ref`]. + /// [`CovariantForLt::cast_ref`]. /// /// Returns [`EINVAL`] if `F` does not match the type used by the pare= nt 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 `stru= ct auxiliary_device`. let ptr =3D 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 fr= om the system. /// -/// The type parameter `F` is a [`ForLt`](trait@ForLt) encoding of the reg= istration -/// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](mac= ro@ForLt). +/// The type parameter `F` is a [`CovariantForLt`](trait@CovariantForLt) e= ncoding 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::reg= istration_data()`]. /// /// # Invariants @@ -408,12 +409,12 @@ struct RegistrationData { /// `self.adev` always holds a valid pointer to an initialized and registe= red /// [`struct auxiliary_device`] whose `registration_data_rust` field point= s to a /// valid `Pin>>>`. -pub struct Registration<'a, F: ForLt + 'static> { +pub struct Registration<'a, F: CovariantForLt + 'static> { adev: NonNull, _phantom: PhantomData>, } =20 -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 @@ pub fn new( } } =20 -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()` i= s a valid registered // `struct auxiliary_device`. @@ -547,7 +548,7 @@ fn drop(&mut self) { } =20 // 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 {} =20 // 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 @@ =20 #[doc(hidden)] pub mod for_lt; -pub use for_lt::ForLt; +pub use for_lt::CovariantForLt; =20 /// 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..ef510ab6c092 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 =20 -//! Provide implementation and test of the `ForLt` trait and macro. +//! Provide implementation and test of the `CovariantForLt` trait and macr= o. //! -//! This module is hidden and user should just use `ForLt!` directly. +//! This module is hidden and user should just use `CovariantForLt!` direc= tly. =20 use core::marker::PhantomData; =20 @@ -15,38 +15,39 @@ /// /// # 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. `CovariantForL= t!` 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 e= lision. /// 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 u3= 2)`. /// # >(); /// # expect_lt::< -/// ForLt!(u32) // Equivalent to `ForLt!(for<'a> u32)`. +/// CovariantForLt!(u32) // Equivalent to `CovariantForLt!(for<'a> u32)`. /// # >(); /// ``` /// @@ -55,10 +56,10 @@ /// 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 @@ /// 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 =3D "false positi= ve")] /// 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 `KB= ox` -/// // 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; =20 @@ -94,11 +95,11 @@ fn cast_ref<'r, 'short: 'r, 'long: 'short>(long: &'r Se= lf::Of<'long>) -> &'r Sel unsafe { core::mem::transmute(long) } } } -pub use macros::ForLt; +pub use macros::CovariantForLt; =20 -/// This is intended to be an "unsafe-to-refer-to" type. +/// Helper type for the `CovariantForLt!` macro. /// -/// 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 b= y macro. /// @@ -107,16 +108,16 @@ fn cast_ref<'r, 'short: 'r, 'long: 'short>(long: &'r = Self::Of<'long>) -> &'r Sel /// `N` is to provide the macro a place to emit arbitrary items, in case i= t needs to prove /// additional properties. #[doc(hidden)] -pub struct UnsafeForLtImpl(PhantomData<(WF,= T)>); +pub struct CovariantForLtImpl(PhantomData<(= WF, T)>); =20 -// This is a helper trait for implementation `ForLt` to be able to use HRT= B. +// This is a helper trait for implementation `CovariantForLt` to be able t= o use HRTB. #[doc(hidden)] pub trait WithLt<'a> { type Of: 'a; } =20 -// 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<= T, WF, 0> { +// SAFETY: In `CovariantForLt!` macro, a covariance proof is generated whe= n naming +// `CovariantForLtImpl` and it will fail to evaluate if the type is not co= variant. +unsafe impl WithLt<'a>, WF> CovariantForLt for Covaria= ntForLtImpl { type Of<'a> =3D >::Of; } diff --git a/rust/macros/for_lt.rs b/rust/macros/for_lt.rs index 364d4113cd10..3cb094d00548 100644 --- a/rust/macros/for_lt.rs +++ b/rust/macros/for_lt.rs @@ -176,7 +176,7 @@ fn prove(&mut self, ty: &'a Type) { } } =20 -pub(crate) fn for_lt(input: HigherRankedType) -> TokenStream { +pub(crate) fn covariant_for_lt(input: HigherRankedType) -> TokenStream { let (ty, lifetime) =3D match input { HigherRankedType::Explicit { lifetime, ty, .. } =3D> (ty, lifetime= ), HigherRankedType::Implicit { ty } =3D> { @@ -235,7 +235,7 @@ fn #cov_proof_name<'__short, '__long: '__short>( ); =20 quote!( - ::kernel::types::for_lt::UnsafeForLtImpl::< + ::kernel::types::for_lt::CovariantForLtImpl::< dyn for<#lifetime> ::kernel::types::for_lt::WithLt<#lifetime, = Of =3D #ty>, #ty_static, { diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 4a48fabbc268..2167cb270928 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -491,14 +491,13 @@ pub fn kunit_tests(attr: TokenStream, input: TokenStr= eam) -> TokenStream { .into() } =20 -/// Obtain a type that implements [`ForLt`] for the given higher-ranked ty= pe. +/// Obtain a type that implements [`CovariantForLt`] for the given higher-= ranked type. /// -/// Please refer to the documentation of the [`ForLt`] trait. +/// Please refer to the documentation of the [`CovariantForLt`] trait. /// -/// [`ForLt`]: trait.ForLt.html +/// [`CovariantForLt`]: trait.CovariantForLt.html #[proc_macro] -// The macro shares the name with the trait. #[allow(non_snake_case)] -pub fn ForLt(input: TokenStream) -> TokenStream { - for_lt::for_lt(parse_macro_input!(input)).into() +pub fn CovariantForLt(input: TokenStream) -> TokenStream { + for_lt::covariant_for_lt(parse_macro_input!(input)).into() } diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index 2c1351040e45..92ee6a6d348e 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -13,7 +13,7 @@ driver, pci, prelude::*, - types::ForLt, + types::CovariantForLt, InPlaceModule, // }; =20 @@ -60,8 +60,8 @@ struct Data<'bound> { =20 #[allow(clippy::type_complexity)] struct ParentData<'bound> { - _reg0: auxiliary::Registration<'bound, ForLt!(Data<'_>)>, - _reg1: auxiliary::Registration<'bound, ForLt!(Data<'_>)>, + _reg0: auxiliary::Registration<'bound, CovariantForLt!(Data<'_>)>, + _reg1: auxiliary::Registration<'bound, CovariantForLt!(Data<'_>)>, } =20 kernel::pci_device_table!( @@ -115,7 +115,7 @@ fn probe<'bound>( =20 impl ParentDriver { fn connect(adev: &auxiliary::Device) -> Result { - let data =3D adev.registration_data::)>()?; + let data =3D adev.registration_data::)>()= ?; let pdev =3D data.parent; =20 dev_info!( --=20 2.54.0 From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1C20F304976; Wed, 3 Jun 2026 01:10:37 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449039; cv=none; b=N52kL9Uj4K3CzT0Me+7p5irlFtQ+y4+xIr1zpFymuTaEixxj4Jm/88irtAhP4Ma9qk8iWluxP1z8jYNqTX2CMyd99jRzIbavfbT/+eUpSsuZVmSDAt+s7/klnQHXySYbNhPQxFl6bfI1wI+GZsrjY53euuIuRKWshGTu/gcV3yo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449039; c=relaxed/simple; bh=cagk3pulaq5ShsvO9EBtr9mU7mNbZy2WBoDZgl7zAfE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=pMexB7ZcHlJIBES8opsexyyXoReB3Nx+HFq8XgSvRJVM6sLMis0TYlVsuxuBqhEm6uvvtWGn766mFzpzzwaKr3Tl1jzOY6/qWQPbtKhsGz6jXpsA7+lQ3OJ/dnZOGWf9PVxww0F6xAztqV/DV5xCLOe9Li8R5rxmfY2PDG/I88A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=bvjpGwio; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="bvjpGwio" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EBCD41F00893; Wed, 3 Jun 2026 01:10:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449037; bh=1KEoJo7IVklqGes8vOy2JYJl+S37vQieuYALZbqcPNc=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=bvjpGwiosFQPvp1zeoC4lFF+SJCs7y4g9VOCmLitoGujV6stCGF63t5PxAewMNBjZ XTQIALLq7SbSSZ6ZzVmQK+LZO1dyULyF2e5wtE/UrfcMncBOKPUtogEkGtG+u3orBk wbi/LwseSAacUWCq6G6vxKti8whTyuSwGwmJI4bT8zFy97xQjJwHSuuJFtceWRsfrP y5fa1YTU8zbnhqRzWkOV7r3Vzo4kZ+zYPUNEgGn9bmrNVs450pTI9T5pN6j5aShZjy JRUZwrw7UiKTUK1BfzJfApIQ2oqsEvwNR4h8kx8OFsBEbSV5YmUgM0uDDRK68m3q9v nRa09YdSvhxQA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 2/7] rust: types: introduce ForLt base trait for CovariantForLt Date: Wed, 3 Jun 2026 03:10:13 +0200 Message-ID: <20260603011020.2073650-3-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a new ForLt trait as a base for CovariantForLt: - ForLt (non-unsafe): represents a type generic over a lifetime, with no covariance guarantee. Provides unsafe fn cast_ref_unchecked() for callers that can justify lifetime shortening via a round-trip safety argument. - 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 where the round-trip argument suffices, without requiring a covariance proof that would fail to compile. The internal macro backend is split accordingly: ForLt! emits ForLtImpl (no covariance proof), CovariantForLt! emits CovariantForLtImpl (with compile-time covariance proof). No existing callers change; they all use CovariantForLt. Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 1 + rust/kernel/types/for_lt.rs | 101 ++++++++++++++++++++++++++++++------ rust/macros/for_lt.rs | 50 ++++++++++++++---- rust/macros/lib.rs | 19 ++++++- 4 files changed, 145 insertions(+), 26 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index cbe6907042d3..c1ed05d1046c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -14,6 +14,7 @@ #[doc(hidden)] pub mod for_lt; pub use for_lt::CovariantForLt; +pub use for_lt::ForLt; =20 /// 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 ef510ab6c092..e1774b03dd1f 100644 --- a/rust/kernel/types/for_lt.rs +++ b/rust/kernel/types/for_lt.rs @@ -1,17 +1,74 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT =20 -//! Provide implementation and test of the `CovariantForLt` trait and macr= o. +//! Provide implementation and test of the `ForLt` and `CovariantForLt` tr= aits and macros. //! -//! This module is hidden and user should just use `CovariantForLt!` direc= tly. +//! This module is hidden and users should just use `ForLt!` / `CovariantF= orLt!` directly. =20 use core::marker::PhantomData; =20 /// Representation of types generic over a lifetime. /// -/// The type must be covariant over the generic lifetime, i.e. the lifetim= e parameter -/// can be soundly shortened. +/// # Macro +/// +/// It is not recommended to implement this trait directly. `ForLt!` macro= is provided to obtain a +/// type that implements this trait. +/// +/// 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 e= lision. +/// 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; + + /// Cast a reference to a shorter lifetime. + /// + /// # Safety + /// + /// The caller must ensure that the lifetime shortening is sound for t= heir use case, + /// e.g. because the `'long` reference originated from a `'short`-to-`= 'static` transmute + /// and this is the reverse leg of that round-trip. + #[inline(always)] + unsafe fn cast_ref_unchecked<'r, 'short: 'r, 'long: 'short>( + long: &'r Self::Of<'long>, + ) -> &'r Self::Of<'short> { + // SAFETY: Caller guarantees the lifetime shortening is sound. + unsafe { core::mem::transmute(long) } + } +} +pub use macros::ForLt; + +/// [`trait@ForLt`] subtrait for types that are covariant over their lifet= ime parameter. /// -/// The lifetime involved must be covariant. +/// Provides a safe [`cast_ref`](CovariantForLt::cast_ref) method for type= s that are proven to be +/// covariant. The `CovariantForLt!` macro syntax is the same as `ForLt!`. /// /// # Macro /// @@ -84,10 +141,7 @@ /// # 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> { @@ -97,27 +151,44 @@ fn cast_ref<'r, 'short: 'r, 'long: 'short>(long: &'r S= elf::Of<'long>) -> &'r Sel } pub use macros::CovariantForLt; =20 -/// Helper type for the `CovariantForLt!` macro. +/// Helper type for the `ForLt!` macro. /// -/// Must only be used by the `CovariantForLt!` macro. +/// Must only be used by the `ForLt!` macro. /// /// `T` is the magic `dyn for<'a> WithLt<'a, TypeThatUse<'a>>` generated b= y macro. /// /// `WF` is a type that the macro can use to assert some specific type is = well-formed. +#[doc(hidden)] +pub struct ForLtImpl(PhantomData<(WF, T)>); + +/// Helper type for the `CovariantForLt!` macro. +/// +/// Must only be used by the `CovariantForLt!` macro. +/// +/// `T` and `WF` are the same as in [`ForLtImpl`]. /// /// `N` is to provide the macro a place to emit arbitrary items, in case i= t needs to prove /// additional properties. #[doc(hidden)] pub struct CovariantForLtImpl(PhantomData<(= WF, T)>); =20 -// This is a helper trait for implementation `CovariantForLt` to be able t= o use HRTB. +// This is a helper trait for implementation `ForLt` to be able to use HRT= B. #[doc(hidden)] pub trait WithLt<'a> { type Of: 'a; } =20 -// SAFETY: In `CovariantForLt!` macro, a covariance proof is generated whe= n naming -// `CovariantForLtImpl` and it will fail to evaluate if the type is not co= variant. -unsafe impl WithLt<'a>, WF> CovariantForLt for Covaria= ntForLtImpl { +impl WithLt<'a>, WF> ForLt for ForLtImpl { + type Of<'a> =3D >::Of; +} + +impl WithLt<'a>, WF, const N: usize> ForLt for Covaria= ntForLtImpl { type Of<'a> =3D >::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. +unsafe impl WithLt<'a>, WF, const N: usize> CovariantF= orLt + for CovariantForLtImpl +{ +} diff --git a/rust/macros/for_lt.rs b/rust/macros/for_lt.rs index 3cb094d00548..ad9809563fab 100644 --- a/rust/macros/for_lt.rs +++ b/rust/macros/for_lt.rs @@ -176,8 +176,10 @@ fn prove(&mut self, ty: &'a Type) { } } =20 -pub(crate) fn covariant_for_lt(input: HigherRankedType) -> TokenStream { - let (ty, lifetime) =3D match input { +/// Resolve the higher-ranked type into a concrete `(ty, lifetime)` pair, = expanding elided +/// lifetimes as needed. Shared by both `for_lt` and `covariant_for_lt`. +fn resolve_hrt(input: HigherRankedType) -> (Type, Lifetime) { + match input { HigherRankedType::Explicit { lifetime, ty, .. } =3D> (ty, lifetime= ), HigherRankedType::Implicit { ty } =3D> { // If there's no explicit `for<'a>` binder, inject a synthetic= `'__elided` lifetime @@ -188,7 +190,41 @@ pub(crate) fn covariant_for_lt(input: HigherRankedType= ) -> TokenStream { }; (ty.expand_elided_lifetime(&lifetime), lifetime) } - }; + } +} + +/// Produce the `'static`-substituted type for the WF check. Shared by bot= h macros. +fn ty_static(ty: &Type, lifetime: &Lifetime) -> Type { + ty.replace_lifetime( + lifetime, + &Lifetime { + apostrophe: Span::mixed_site(), + ident: format_ident!("static"), + }, + ) +} + +pub(crate) fn for_lt(input: HigherRankedType) -> TokenStream { + let (ty, lifetime) =3D resolve_hrt(input); + + // Make sure that the type is wellformed when substituting lifetime wi= th `'static`. + // + // Currently the Rust compiler doesn't check this, see the `ProveWf` d= ocumentation in + // `covariant_for_lt` below. + // + // We prefer to use this way of proving WF-ness as it can work when ge= nerics are involved. + let ty_static =3D ty_static(&ty, &lifetime); + + quote!( + ::kernel::types::for_lt::ForLtImpl::< + dyn for<#lifetime> ::kernel::types::for_lt::WithLt<#lifetime, = Of =3D #ty>, + #ty_static, + > + ) +} + +pub(crate) fn covariant_for_lt(input: HigherRankedType) -> TokenStream { + let (ty, lifetime) =3D resolve_hrt(input); =20 let mut prover =3D Prover(&lifetime, Vec::new()); prover.prove(&ty); @@ -226,13 +262,7 @@ fn #cov_proof_name<'__short, '__long: '__short>( // Currently the Rust compiler doesn't check this, see the above `Prov= eWf` documentation. // // We prefer to use this way of proving WF-ness as it can work when ge= nerics are involved. - let ty_static =3D ty.replace_lifetime( - &lifetime, - &Lifetime { - apostrophe: Span::mixed_site(), - ident: format_ident!("static"), - }, - ); + let ty_static =3D ty_static(&ty, &lifetime); =20 quote!( ::kernel::types::for_lt::CovariantForLtImpl::< diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 2167cb270928..e970769609f3 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -491,11 +491,28 @@ pub fn kunit_tests(attr: TokenStream, input: TokenStr= eam) -> TokenStream { .into() } =20 -/// Obtain a type that implements [`CovariantForLt`] for the given higher-= ranked type. +/// Obtain a type that implements [`ForLt`] for the given higher-ranked ty= pe. +/// +/// Please refer to the documentation of the [`ForLt`] trait. +/// +/// [`ForLt`]: trait.ForLt.html +#[proc_macro] +#[allow(non_snake_case)] +pub fn ForLt(input: TokenStream) -> TokenStream { + for_lt::for_lt(parse_macro_input!(input)).into() +} + +/// Obtain a type that implements [`CovariantForLt`] (and [`ForLt`]) for t= he given higher-ranked +/// type. +/// +/// Unlike [`ForLt!`], this macro additionally proves that the type is cov= ariant over the lifetime, +/// providing a safe [`CovariantForLt::cast_ref`] method. /// /// Please refer to the documentation of the [`CovariantForLt`] trait. /// /// [`CovariantForLt`]: trait.CovariantForLt.html +/// [`CovariantForLt::cast_ref`]: trait.CovariantForLt.html#method.cast_ref +/// [`ForLt`]: trait.ForLt.html #[proc_macro] #[allow(non_snake_case)] pub fn CovariantForLt(input: TokenStream) -> TokenStream { --=20 2.54.0 From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 53DA2306744; Wed, 3 Jun 2026 01:10:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449044; cv=none; b=gV8tWMUU0vIIOH3JXXvgreE1YrH6dUEzXKaDOsVIZWJ6j8HEeG/AJkXP5aIEWw5J8f0sjvxoOx5P3VNr2jvBXPI1PQX6W9nB1gVpry+eMzTMPTVCrK+nqN7AjuV9X3YNhIEolBSIVnHF9+3u8geRkTsT4f2/+N63RarFjZTJo20= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449044; c=relaxed/simple; bh=SUON8+Pxy3vTFTdFwSWkETOPYj9qvIfQ6ZVJE6WrdlI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=rwdTzLDntZDCmGZSMktuspYnknnI1K6GIuGkOh48RAszCktFXzpPY3UCWIKzcDNCf5yxgr/OkcOmKDohhqnMTFox/eGTV3VoalBKEf9d7M/sNEykjnuaEkZr5F179D/zuMqo7QzcK6rlbGhpXNMwJcVkiZrHXVDRzYwPE9qOgDY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=nXjN3Ebs; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="nXjN3Ebs" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2EC6B1F0089C; Wed, 3 Jun 2026 01:10:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449043; bh=TNOt0mG9O+FR4MiS/k0pP+w4HT8cI6FiYjIUvgu1jSs=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=nXjN3Ebs1FIyqTUIp+PWz6wIT1ygi1m6ca7FqnI8qvcTOU76EepelD8okDl1cLdqj VAY9TWHWV0XNgFftl8TGOmTlxtWNcwI3Il54yJmyi8c8wK3WvmtC9I3XttlvttECk8 deq/cjt2qJvAyWE0dy5b9zbWk2fGlmjPNIhxX+0Z6Aieb8IriTw1V6seGr0FGLuQND 4+9Pk0C/yepqSuhG2z3gPPgSbzPXpfkRm68E/KHX4BXIqRADPe5SCgdUTVfIxja+N/ pxknkf2W6c8UvYuIGeXNnHXEWl0C0Q+JdBdQzW7kBGqRRb4QVfFlUofPr+8oZ/v1eD 5VfNkFdRJ3Vuw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 3/7] rust: auxiliary: add registration_data_with() for ForLt types Date: Wed, 3 Jun 2026 03:10:14 +0200 Message-ID: <20260603011020.2073650-4-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Signed-off-by: Danilo Krummrich --- rust/kernel/auxiliary.rs | 89 ++++++++++++++++++++++++++++++---------- 1 file changed, 68 insertions(+), 21 deletions(-) diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index 40a0af74a8e5..81549a3e347e 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -21,6 +21,7 @@ prelude::*, types::{ CovariantForLt, + ForLt, ForeignOwnable, Opaque, // }, @@ -270,18 +271,15 @@ pub fn parent(&self) -> &device::Device { unsafe { parent.as_bound() } } =20 - /// Returns a pinned reference to the registration data set by the reg= istering (parent) driver. + /// Returns the stored registration data as a pinned `'static` referen= ce. /// - /// `F` is the [`CovariantForLt`](trait@CovariantForLt) encoding of th= e data type. The returned - /// reference has its lifetime shortened from `'static` to `&self`'s b= orrow lifetime via - /// [`CovariantForLt::cast_ref`]. + /// Performs null and [`TypeId`] checks, then borrows the stored [`KBo= x`]. /// - /// Returns [`EINVAL`] if `F` does not match the type used by the pare= nt 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= >> { + /// The returned `'static` lifetime was transmuted from the device's b= ound lifetime during + /// registration. Callers must shorten it before exposing it. + unsafe fn registration_data_pinned(&self) -> Resul= t>> { // SAFETY: By the type invariant, `self.as_raw()` is a valid `stru= ct auxiliary_device`. let ptr =3D unsafe { (*self.as_raw()).registration_data_rust }; if ptr.is_null() { @@ -306,10 +304,58 @@ pub fn registration_data= (&self) -> Result>>>::borrow(ptr) }; =20 // SAFETY: `data` is a structurally pinned field of `RegistrationD= ata`. - let pinned: Pin<&F::Of<'_>> =3D unsafe { wrapper.map_unchecked(|w|= &w.data) }; + Ok(unsafe { wrapper.map_unchecked(|w| &w.data) }) + } + + /// Access the registration data set by the registering (parent) drive= r through a closure. + /// + /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The c= losure receives a pinned + /// reference to the registration data. + /// + /// For covariant types that implement [`trait@CovariantForLt`], prefer + /// [`registration_data`](Self::registration_data) which returns a dir= ect reference. + /// + /// Returns [`EINVAL`] if `F` does not match the type used by the pare= nt 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_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` s= ound regardless of + // variance. + let pinned =3D unsafe { self.registration_data_pinned::()? }; + + // SAFETY: See above; the closure's HRTB makes the round-trip soun= d. + let short =3D unsafe { F::cast_ref_unchecked(pinned.get_ref()) }; + + // SAFETY: The data was pinned before the lifetime was shortened; = pinning is + // orthogonal to lifetimes. + Ok(f(unsafe { Pin::new_unchecked(short) })) + } =20 - // SAFETY: The data was pinned when stored; `cast_ref` only shorte= ns - // the lifetime, so the pinning guarantee is preserved. + /// Returns a pinned reference to the registration data set by the reg= istering (parent) driver. + /// + /// This method is only available when `F` implements [`trait@Covarian= tForLt`], which guarantees + /// safe lifetime shortening via [`CovariantForLt::cast_ref`]. + /// + /// For non-covariant types, use the closure-based [`Self::registratio= n_data_with`]. + /// + /// Returns [`EINVAL`] if `F` does not match the type used by the pare= nt 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= >> { + // SAFETY: CovariantForLt guarantees covariance, so cast_ref safel= y shortens the + // `'static` lifetime. + let pinned =3D unsafe { self.registration_data_pinned::()? }; + + // SAFETY: The data was pinned before the lifetime was shortened; = pinning is orthogonal + // to lifetimes. Ok(unsafe { Pin::new_unchecked(F::cast_ref(pinned.get_ref())) }) } } @@ -399,22 +445,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 fr= om the system. /// -/// The type parameter `F` is a [`CovariantForLt`](trait@CovariantForLt) e= ncoding 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::reg= istration_data()`]. +/// The type parameter `F` is a [`ForLt`](trait@ForLt) encoding of the reg= istration +/// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](mac= ro@ForLt). +/// +/// The data can be accessed by the auxiliary driver through [`Device::reg= istration_data()`] and +/// [`Device::registration_data_with()`]. /// /// # Invariants /// /// `self.adev` always holds a valid pointer to an initialized and registe= red /// [`struct auxiliary_device`] whose `registration_data_rust` field point= s to a /// valid `Pin>>>`. -pub struct Registration<'a, F: CovariantForLt + 'static> { +pub struct Registration<'a, F: ForLt + 'static> { adev: NonNull, _phantom: PhantomData>, } =20 -impl<'a, F: CovariantForLt> Registration<'a, F> +impl<'a, F: ForLt> Registration<'a, F> where for<'b> F::Of<'b>: Send + Sync, { @@ -526,7 +573,7 @@ pub fn new( } } =20 -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()` i= s a valid registered // `struct auxiliary_device`. @@ -548,7 +595,7 @@ fn drop(&mut self) { } =20 // 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 {} =20 // 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 {} --=20 2.54.0 From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 807852FD68B; Wed, 3 Jun 2026 01:10:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449049; cv=none; b=pCHiKl9IA2mgR/NMatogYB9NLPI03AZWz5UjhfAIUE+lXN4rynqxjbca5fhwRIMm5c3DRnsBATziwyjJJlx9HPDm2yhJ/QT/20NsAzSKkAAswqcQH/CQmJ36XUKRLSJCreOgqGBOMsDDEfXf5mVXhVKRE5gZ44bKQ1rqUa9fjUM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449049; c=relaxed/simple; bh=uOa12PoX3h/toUlHuGr0ZVOkgaxjpTuBwy1sIBKW98A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=TqI60u0uHKJTo1dJX571cNdm+2AL5eK7ADK/sNyk2tzQCugydcpD0yrIdf+aOmw/a8RpCxwpg9bXMtUFJwbPDjGLHafqpcHCSyUX9b2BVkVUtOpGjo52s+9uyih283hJqKbVmwZk6tcbvfrlsoVcR9zJotF6qPxb5FcbgMecLS0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=LrzbnswS; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="LrzbnswS" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 65C271F00893; Wed, 3 Jun 2026 01:10:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449048; bh=t78Uhk4IqBOMxFqpBa9dZMpGO+12MHy37WkLBCfMbCs=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=LrzbnswS35CLnBgv/FKPUjgo4RR20EobtK/uEFXX8xrbQ73zE+975zrFU6XwmD91T rvQitUoffo8Mvrk4RdKhHznWi5Dsd4yWYSccwAz6MRNUiY5c+J5XEDEAtTn8ousjxJ ubCGLdQvUm0u4+N3YRIJbevc0ipDdFUKDhRc+/WxPhgli5jBWBqXpSYQZYokFQfuSF mEdwi5yIpihSER8bwDBoQx68V82nThwV4dY9Sj7dhxVk1Ae8LzvkgR7CNUxto7dLFf j2x/o1U91nNV/sL9l8mHmNGrWEHmyWeXgunu77hQH8UP5V0Fxbuede5SMbO5K+zGuZ TOeYzjix7dFug== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 4/7] rust: auxiliary: sample: demonstrate ForLt with invariant Mutex type Date: Wed, 3 Jun 2026 03:10:15 +0200 Message-ID: <20260603011020.2073650-5-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Extend the auxiliary driver sample to demonstrate both access patterns: - registration_data() with CovariantForLt!(Data<'_>) for the covariant data type that holds a plain &'bound reference. - registration_data_with() with ForLt!(MutexData<'_>) for an invariant data type that wraps a Mutex<&'bound Device>. Since Mutex is invariant over T, MutexData cannot implement CovariantForLt and must use the closure-based accessor. Signed-off-by: Danilo Krummrich --- samples/rust/rust_driver_auxiliary.rs | 94 +++++++++++++++++++-------- 1 file changed, 68 insertions(+), 26 deletions(-) diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index 92ee6a6d348e..e441ae81fa2c 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -11,14 +11,21 @@ Core, // }, driver, + new_mutex, pci, prelude::*, - types::CovariantForLt, + sync::Mutex, + types::{ + CovariantForLt, + ForLt, // + }, InPlaceModule, // }; =20 const MODULE_NAME: &CStr =3D ::NAME; const AUXILIARY_NAME: &CStr =3D c"auxiliary"; +const COVARIANT_DEV_ID: u32 =3D 0; +const INVARIANT_DEV_ID: u32 =3D 1; =20 struct AuxiliaryDriver; =20 @@ -56,12 +63,26 @@ struct Data<'bound> { parent: &'bound pci::Device, } =20 +/// Registration data with interior mutability. +/// +/// `Mutex<&'bound T>` is invariant over `'bound`, so this type cannot imp= lement +/// [`CovariantForLt`](trait@CovariantForLt). Access must go through the c= losure-based +/// [`auxiliary::Device::registration_data_with()`]. +#[pin_data] +struct MutexData<'bound> { + #[pin] + parent: Mutex<&'bound pci::Device>, + index: u32, +} + struct ParentDriver; =20 #[allow(clippy::type_complexity)] +#[pin_data] struct ParentData<'bound> { _reg0: auxiliary::Registration<'bound, CovariantForLt!(Data<'_>)>, - _reg1: auxiliary::Registration<'bound, CovariantForLt!(Data<'_>)>, + #[pin] + _reg1: auxiliary::Registration<'bound, ForLt!(MutexData<'_>)>, } =20 kernel::pci_device_table!( @@ -81,17 +102,17 @@ fn probe<'bound>( pdev: &'bound pci::Device>, _info: &'bound Self::IdInfo, ) -> impl PinInit, Error> + 'bound { - Ok(ParentData { + try_pin_init!(ParentData { // SAFETY: `ParentData` is the driver's private data, which is= dropped when the // device is unbound; i.e. `mem::forget()` is never called on = it. _reg0: unsafe { auxiliary::Registration::new_with_lt( pdev.as_ref(), AUXILIARY_NAME, - 0, + COVARIANT_DEV_ID, MODULE_NAME, Data { - index: 0, + index: COVARIANT_DEV_ID, parent: pdev, }, )? @@ -101,12 +122,16 @@ fn probe<'bound>( auxiliary::Registration::new_with_lt( pdev.as_ref(), AUXILIARY_NAME, - 1, + INVARIANT_DEV_ID, MODULE_NAME, - Data { - index: 1, - parent: pdev, - }, + pin_init!(MutexData { + parent <- { + let pdev: &pci::Device =3D pdev; + + new_mutex!(pdev) + }, + index: INVARIANT_DEV_ID, + }), )? }, }) @@ -115,22 +140,39 @@ fn probe<'bound>( =20 impl ParentDriver { fn connect(adev: &auxiliary::Device) -> Result { - let data =3D adev.registration_data::)>()= ?; - let pdev =3D data.parent; - - dev_info!( - pdev, - "Connect auxiliary {} with parent: VendorID=3D{}, DeviceID=3D{= :#x}\n", - adev.id(), - pdev.vendor_id(), - pdev.device_id() - ); - - dev_info!( - pdev, - "Connected to auxiliary device with index {}.\n", - data.index - ); + match adev.id() { + // CovariantForLt types can use the direct-reference accessor. + COVARIANT_DEV_ID =3D> { + let data =3D adev.registration_data::)>()?; + let pdev =3D data.parent; + + dev_info!( + pdev, + "Connect auxiliary {} with parent: VendorID=3D{}, Devi= ceID=3D{:#x}\n", + adev.id(), + pdev.vendor_id(), + pdev.device_id() + ); + + dev_info!( + pdev, + "Connected to auxiliary device with index {}.\n", + data.index + ); + } + // Invariant ForLt types (e.g. containing a Mutex) require the= closure-based accessor. + INVARIANT_DEV_ID =3D> { + adev.registration_data_with::), _>(|d= ata| { + let pdev =3D *data.parent.lock(); + dev_info!( + pdev, + "Connected to auxiliary device with index {} (via = Mutex).\n", + data.index + ); + })?; + } + _ =3D> return Err(EINVAL), + } =20 Ok(()) } --=20 2.54.0 From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C99FB2F39C7; Wed, 3 Jun 2026 01:10:53 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449055; cv=none; b=RksbzQrbLVOkSL0rlWCpmJrejKT9FhHwlhKoxQmJX2LPYjQfjeYxjgUwKVbPdFCelV2UOGwK54tB/5Y53QWvYYGE7LMzCgeWJvg6YelTJgYBhS3UirBozTznWo1rUrda6X8OMNFsdMnJllbuiFJOGbRBSnDlLqOkQ/x+SuTPdHA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449055; c=relaxed/simple; bh=fioutdCOCELpXFXFvL3bombMQpXlSnLljw3Dm6YDmbk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Xcmxu7FeoXH0W8HcAiGZVIYB4JstTgvauX7FvCyenpqwAJ9I1MrffFvfnBo9AsDFMysH9hqczwYkiOViaM1J9BjdhmpZRiK6hlagOrG+KkotFclOZnaEpQvUmh+jj2Fv08CjhhcQAhZuEp3HpNbGo+knhbHaDdSCTUtqCeB6jcc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=WZEuJ5C3; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="WZEuJ5C3" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9D92F1F00898; Wed, 3 Jun 2026 01:10:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449053; bh=5u6SKAfOQENdvm9cJV5fTBpN3ZssvduKcZ4mI7udZDE=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=WZEuJ5C3uR808zrPCLf2pFl3JhLLGmxCrxORyVMHaFAvtUeZPYyUVIThwwUMPHnOq XWMFFqe1mRfZ0t93nTXFrYMJX4OF12xSjJ9IW/+CfxIImiYeQMn6qF/ynOR63Tc1DE /nDYS0MD9/LxDOcfQDy1W7rQ8JNIRuN2bB2eehi5MRDYAF3lSrKA1NepQIy9YLdeVo iraHgEvbp3aoHt9YqOXZCa4ulwpbySKlJplI1ISLbiXOMMwbwW73biwMhu/TXYRHdK 49f4BK0x5DW08xyHNddohUHRwChImQkv7ssy9sDYaDWnpXmPOo///BUXmImLoxPz+E xNeZ2g6hFE7fg== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 5/7] rust: devres: add DevresLt for ForLt-aware device resource access Date: Wed, 3 Jun 2026 03:10:16 +0200 Message-ID: <20260603011020.2073650-6-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 applies ForLt's lifetime-shortening operations in all access methods to shorten the stored 'static lifetime to the caller's borrow lifetime. 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. Signed-off-by: Danilo Krummrich --- rust/kernel/devres.rs | 110 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 82cbd8b969fb..23db91377f5e 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -24,6 +24,8 @@ Arc, // }, types::{ + CovariantForLt, + ForLt, ForeignOwnable, Opaque, // }, @@ -365,6 +367,114 @@ fn drop(&mut self) { } } =20 +/// Guard returned by [`DevresLt::try_access`]. +/// +/// Dereferences to `F::Of<'a>`, shortening the lifetime of the stored dat= a to the guard's borrow +/// lifetime. +pub struct DevresGuard<'a, F: CovariantForLt>(RevocableGuard<'a, F::Of<'st= atic>>); + +impl<'a, F: CovariantForLt> core::ops::Deref for DevresGuard<'a, F> { + type Target =3D F::Of<'a>; + + 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 acc= essors ([`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 + F::Of<'static>: Send; + +impl DevresLt +where + F::Of<'static>: Send, +{ + /// Creates a new [`DevresLt`] instance of the given `data`. + /// + /// # Safety + /// + /// The data must remain valid for the device's full bound scope. [`De= vresLt`] 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 =3D unsafe { + pin_init::pin_init_from_closure::, E>(move |slo= t| { + data.__pinned_init(slot.cast()) + }) + }; + + Ok(Self(Devres::new(dev, data)?)) + } + + /// Return a reference of the [`Device`] this [`DevresLt`] instance ha= s been created with. + pub fn device(&self) -> &Device { + self.0.device() + } + + /// Obtain `&F::Of<'_>`, bypassing the [`Revocable`], through a closur= e. + /// + /// This method works like [`DevresLt::access`](DevresLt::access) but = accepts any + /// [`trait@ForLt`] type, not just [`trait@CovariantForLt`]. + pub fn access_with(&self, dev: &Device, f: G) -> Result + where + G: for<'a> FnOnce(&'a F::Of<'a>) -> R, + { + self.0.access(dev).map(|data| { + // SAFETY: The closure's HRTB `for<'a>` prevents the caller fr= om smuggling in + // references with a concrete short lifetime, making the round= -trip from `'static` + // sound regardless of variance. + f(unsafe { F::cast_ref_unchecked(data) }) + }) + } + + /// [`DevresLt`] accessor for [`Revocable::try_access_with`]. + pub fn try_access_with(&self, f: G) -> Option + where + G: for<'a> FnOnce(&'a F::Of<'a>) -> R, + { + self.0.data().try_access_with(|data| { + // SAFETY: The closure's HRTB `for<'a>` prevents the caller fr= om smuggling in + // references with a concrete short lifetime, making the round= -trip from `'static` + // sound regardless of variance. + f(unsafe { F::cast_ref_unchecked(data) }) + }) + } +} + +impl DevresLt +where + F::Of<'static>: Send, +{ + /// Obtain `&'a F::Of<'a>`, bypassing the [`Revocable`]. + /// + /// This method works like [`Devres::access`], but shortens the return= ed reference's lifetime + /// from `'static` to `'a` via [`CovariantForLt::cast_ref`]. + pub fn access<'a>(&'a self, dev: &'a Device) -> Result<&'a F::O= f<'a>> { + self.0.access(dev).map(F::cast_ref) + } + + /// [`DevresLt`] accessor for [`Revocable::try_access`]. + 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 --=20 2.54.0 From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 507E12F39C7; Wed, 3 Jun 2026 01:10:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449060; cv=none; b=HPyPTeJL4EJWrXWC3MHYd/q9vDpMWJ2M0LUX7au/RtP6bmgXiD/DUpbIaZbRBN4H6T11QZuNQ5BhwKPj9RJqDhcFQRexPLRssZdf2GAK0cm6L9/qsK+ACWoYGz7f4XHJRiz2lYfAsXuPwOmIyjwK6n+ZXDWzW8zoqpUHTw6nUQk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449060; c=relaxed/simple; bh=TURasSuevhvFKc+WXuz6qvRLMMGZvPymK0qyzJQs2xk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=h0Nn6Y57H0wvuW2WHJmg07T1O6A2A8ak1com1VFVzkuM09jkfFGjug90ydXix0/L3CiTS3aofvYSt3M44NESVXuZnAMe5Q2AmO0s+Gzvwb1djvUSsZV9dRSHo2McjL/u2bPD0ges9WFUlCkghAUXW4Tln+qgYH5q5wmnybKRbG8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=OE8/tXkL; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="OE8/tXkL" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D5F461F00893; Wed, 3 Jun 2026 01:10:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449058; bh=jFXBZlmIt6khk0+6CdihUMf27NKcoYEyolnsYS/5aD0=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=OE8/tXkLkk0Acfb00xG1OlNXaGaXQZrwIn73AQH+nMxR/sWrYHjxgfKRoUSBbR0Pm kytHZDoalp1lv6hiDIrAaYkURdUxxaJV87/29f8ZjzV3SzCGbqkm8EV8XOSbGZbP7E PF6MLp/KlL5dAIztupy1slPk32KRitQ/Wc4ONA71hqhaV6OaMBLOwfSr79N5we1gcA 7kx+jB+lZ00lscHda/Ax6Lt39X6nL7jJhCFpj83SIE837GtbM9k4WmyebH5nsIWpd0 Yw4a3SahsEZ/rnk0n31pPQ+T0oBzYyABkRk9I3bQmqdMPCiLOqUj2iT9oTizLnTGV6 0eQO4LS+xxy5Q== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 6/7] rust: pci: return DevresLt from Bar::into_devres() Date: Wed, 3 Jun 2026 03:10:17 +0200 Message-ID: <20260603011020.2073650-7-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Signed-off-by: Danilo Krummrich --- rust/kernel/pci.rs | 1 + rust/kernel/pci/io.rs | 37 ++++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-) 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 @@ ConfigSpace, ConfigSpaceKind, ConfigSpaceSize, + DevresBar, Extended, Normal, // }; diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index 0461e01aaa20..7a0d2d74129d 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -6,7 +6,7 @@ use crate::{ bindings, device, - devres::Devres, + devres::DevresLt, io::{ Io, IoCapable, @@ -14,7 +14,11 @@ Mmio, MmioRaw, // }, - prelude::*, // + prelude::*, + types::{ + CovariantForLt, + ForLt, // + }, // }; use core::{ marker::PhantomData, @@ -151,6 +155,19 @@ pub struct Bar<'a, const SIZE: usize =3D 0> { num: i32, } =20 +impl ForLt for Bar<'static, SIZE> { + type Of<'a> =3D 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 =3D DevresLt>; + impl<'a, const SIZE: usize> Bar<'a, SIZE> { pub(super) fn new( pdev: &'a Device, @@ -223,15 +240,13 @@ fn release(&self) { =20 /// 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` guarante= es the `Bar` does not - // actually outlive the device -- access is revoked and the resour= ce is released when the - // device is unbound. - let bar: Bar<'static, SIZE> =3D unsafe { core::mem::transmute(self= ) }; - let pdev =3D 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 unbo= und. + pub fn into_devres(self) -> Result> { + let pdev =3D self.pdev; + // SAFETY: `Bar` only holds a reference to the device and an I/O m= apping, both of which + // remain valid for the device's full bound scope, not just for `'= a`. + unsafe { DevresLt::new(pdev.as_ref(), self) } } } =20 --=20 2.54.0 From nobody Mon Jun 8 06:35:37 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 60110305662; Wed, 3 Jun 2026 01:11:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449065; cv=none; b=YF9TTNE/qD4Z8Id/fPqyHjdE4vcJEMVhO+fbsxUkK0TNKgm+WyuKBA2zVK/BaexKBwVNZs2BupsTg4+UNqkJ5XtlYovjoWL4xB/2L2gQS7DOlBA1hNbnlioiTSH1Tlki3hQ5hU5k+J/00VDUJLyQy+G3w7A+X1YnG1x7dYlUC8Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1780449065; c=relaxed/simple; bh=/bCT7cXo08Ww3XUqF/QPMJs5sd3D3wwtWPa/7j4ewPc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=fdtJASaoDdRDnYNCEIzPDcXu+8yTeqMtcB7HB3ocg/9qF/Lk7eID9RUUhVV6H41pU3lkIB8gZrXyh7tNyUE4W49bFRqHD58F5+zcZNwiUyn9GQhTwJoECn8an8ron3Rl6uz5yMFKPqZi7CuQMLEde8tMCBE8GVEdsfMDJbKoWx0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=LgEpdA1y; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="LgEpdA1y" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1964E1F00898; Wed, 3 Jun 2026 01:10:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1780449063; bh=6kwWxpERwhRfbh+IYbhqXFQAvVIriNywyEds62Ao6CA=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=LgEpdA1ysW/6aW4sNfMAY+vmwXWjmraQAX/521n//865SRjUM0K5USCa9W0rmp8mV kJtjn0vbIlFRpLBSMH43IbdFtr5qpA/M8wS61jkuHqzV7pdAmYFVADgmJfM6g4LFbX s5zVBwIWG5EciXEKIUiIL2smDUQttiYVMhQk1/KnPtxfDjZlQ875R9Mz6N7/29y4Gn R+vrN2bF5qjOx7t8sh+3y0GFri5uDP2GcL/qsEaoDAO1YWilBBoD+u+mqmgVufANnA ykfuJna16K/nJ4u36Odn3M0lIuL2fh2YVfrSjmvTdn/r67lelpXpXm1CuGc9lLcdsd mOzs+75PWde7g== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, dakr@kernel.org, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, aliceryhl@google.com, tmgross@umich.edu, acourbot@nvidia.com, ecourtney@nvidia.com, m.wilczynski@samsung.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, daniel.almeida@collabora.com, bhelgaas@google.com, kwilczynski@kernel.org Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pwm@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v2 7/7] rust: io: mem: return DevresLt from IoMem/ExclusiveIoMem::into_devres() Date: Wed, 3 Jun 2026 03:10:18 +0200 Message-ID: <20260603011020.2073650-8-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260603011020.2073650-1-dakr@kernel.org> References: <20260603011020.2073650-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Signed-off-by: Danilo Krummrich --- drivers/pwm/pwm_th1520.rs | 5 ++- rust/kernel/io/mem.rs | 65 +++++++++++++++++++++++++++------------ 2 files changed, 47 insertions(+), 23 deletions(-) diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs index 48808cd80737..7e3a06ed369f 100644 --- a/drivers/pwm/pwm_th1520.rs +++ b/drivers/pwm/pwm_th1520.rs @@ -24,9 +24,8 @@ use kernel::{ clk::Clk, device::{Bound, Core, Device}, - devres, io::{ - mem::IoMem, + mem::DevresIoMem, Io, // }, of, platform, @@ -92,7 +91,7 @@ struct Th1520WfHw { #[pin_data(PinnedDrop)] struct Th1520PwmDriverData { #[pin] - iomem: devres::Devres>, + iomem: DevresIoMem, clk: Clk, } =20 diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index fc2a3e24f8d5..4691a01a3cf7 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -9,7 +9,7 @@ Bound, Device, // }, - devres::Devres, + devres::DevresLt, io::{ self, resource::{ @@ -20,6 +20,10 @@ MmioRaw, // }, prelude::*, + types::{ + CovariantForLt, + ForLt, // + }, }; =20 /// An IO request for a specific device and resource. @@ -172,6 +176,19 @@ pub struct ExclusiveIoMem<'a, const SIZE: usize> { _region: Region, } =20 +impl ForLt for ExclusiveIoMem<'static, SIZE> { + type Of<'a> =3D 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 =3D 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 @@ fn ioremap(dev: &'a Device, resource: &Resourc= e) -> Result { =20 /// Consume the `ExclusiveIoMem` and register it as a device-managed r= esource. /// - /// The returned `Devres>` can outlive t= he original lifetime - /// `'a`. Access to the I/O memory is revoked when the device is unbou= nd. - pub fn into_devres(self) -> Result>> { - // SAFETY: Casting to `'static` is sound because `Devres` guarante= es 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> =3D unsafe { core::mem::t= ransmute(self) }; - let dev =3D iomem.iomem.dev; - Devres::new(dev, iomem) + /// The returned [`DevresExclusiveIoMem`] can outlive the original bor= row and be stored in + /// driver data. Access to the I/O memory is revoked automatically whe= n the device is unbound. + pub fn into_devres(self) -> Result> { + let dev =3D 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) } } } =20 @@ -232,6 +247,19 @@ pub struct IoMem<'a, const SIZE: usize =3D 0> { io: MmioRaw, } =20 +impl ForLt for IoMem<'static, SIZE> { + type Of<'a> =3D IoMem<'a, SIZE>; +} + +// SAFETY: `IoMem<'a, SIZE>` is covariant over `'a`; it holds `&'a Device<= Bound>`, +// which is covariant. +unsafe impl CovariantForLt for IoMem<'static, SIZE> {} + +/// A device-managed I/O memory region. +/// +/// See [`IoMem::into_devres`]. +pub type DevresIoMem =3D 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 t= he CPU @@ -271,16 +299,13 @@ fn ioremap(dev: &'a Device, resource: &Resourc= e) -> Result { =20 /// Consume the `IoMem` and register it as a device-managed resource. /// - /// The returned `Devres>` can outlive the origin= al - /// 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` guarante= es the `IoMem` does not - // actually outlive the device -- access is revoked and the resour= ce is released when the - // device is unbound. - let iomem: IoMem<'static, SIZE> =3D unsafe { core::mem::transmute(= self) }; - let dev =3D iomem.dev; - Devres::new(dev, iomem) + /// The returned [`DevresIoMem`] can outlive the original borrow and b= e 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 =3D self.dev; + // SAFETY: `IoMem` only holds a device reference and an I/O mappin= g, both of which + // remain valid for the device's full bound scope, not just for `'= a`. + unsafe { DevresLt::new(dev, self) } } } =20 --=20 2.54.0