From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 9D09226F2BE; Mon, 27 Apr 2026 22:12:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327934; cv=none; b=c3eckqKjr15VOdAf+CsfstMljBZdQBWpENWpGfqrAxSZVFa3g9o96fHkbSIfEHqEvU0/eSj0K1QKMZVmxQR1Ae7M6YIMW+MmyrLtQ47XAw+nY69bbA872jBXlmxEi8AgJfXQRaz/kJwwKQQh6cHHInYdhXHjcFSJCVMlYOe+T7g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327934; c=relaxed/simple; bh=ju+F7o8Yl0nyozmN8SThTNujs1B0GOs/rWyZh4FMitg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=K7jRC9E0QPx4ICGqiA3JeTPrkoLcMYfmwj74Aq0vp/hDTJZhwABw7V/zpOrVtmYU6OgJ32sSE3p54HAushcwMnTEXfmCdA21eZ/zA40DDQTKJ6+AMXWBJlGfu8b2HSOSTtuyS2K8+hqSegopyk5coW4X2Vsdrj2koa01TD/+TeM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=B0DI94d2; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="B0DI94d2" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9F904C19425; Mon, 27 Apr 2026 22:12:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327934; bh=ju+F7o8Yl0nyozmN8SThTNujs1B0GOs/rWyZh4FMitg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=B0DI94d2eRFKDr3/VwZbkkFsvz36IGsGDJhc8SmdCK5Z5cARqCTNNFlEfE9EwcpKg IqSQS7X0la8Qy4Uu9wC5Z47YmGqMDrIdAB6CIl7Kk2CYVGhaghWLzWUiChXNp6wGK3 sGHygogvD8WI7CopuAM5NyRz9NXzAEZ2ipxldU+Ssx0W/HgaH3OWWeAc2NDKawW9FY NY9+I9h8GlXTG1y/UVjx2uovH8iyQ0xKNgmXJQmPg844taSQlRztSkbNfwkrxs9aY1 IyaoJNYxpsYna35Tk2JTSso2ezu9t73QM1O73Zhb6F2DLvze3BSEujdZ+SjyNc+Zjd 7nyxZcE1D64lQ== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 01/24] rust: driver core: drop drvdata before devres release Date: Tue, 28 Apr 2026 00:10:59 +0200 Message-ID: <20260427221155.2144848-2-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Move the post_unbind_rust callback before devres_release_all() in device_unbind_cleanup(). With drvdata() removed, the driver's bus device private data is only accessible by the owning driver itself. It is hence safe to drop the driver's bus device private data before devres actions are released. This reordering is the key enabler for Higher-Ranked Lifetime Types (HRT) in Rust device drivers -- it allows driver structs to hold direct references to devres-managed resources, because the bus device private data (and with it all such references) is guaranteed to be dropped while the underlying devres resources are still alive. Without this change, devres resources would be freed first, leaving the driver's bus device private data with dangling references during its destructor. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/base/dd.c | 2 +- include/linux/device/driver.h | 4 ++-- rust/kernel/driver.rs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/drivers/base/dd.c b/drivers/base/dd.c index 5799a60fd058..be59d2e13a15 100644 --- a/drivers/base/dd.c +++ b/drivers/base/dd.c @@ -593,9 +593,9 @@ static DEVICE_ATTR_RW(state_synced); =20 static void device_unbind_cleanup(struct device *dev) { - devres_release_all(dev); if (dev->driver->p_cb.post_unbind_rust) dev->driver->p_cb.post_unbind_rust(dev); + devres_release_all(dev); arch_teardown_dma_ops(dev); kfree(dev->dma_range_map); dev->dma_range_map =3D NULL; diff --git a/include/linux/device/driver.h b/include/linux/device/driver.h index bbc67ec513ed..38e9a4679447 100644 --- a/include/linux/device/driver.h +++ b/include/linux/device/driver.h @@ -123,8 +123,8 @@ struct device_driver { struct driver_private *p; struct { /* - * Called after remove() and after all devres entries have been - * processed. This is a Rust only callback. + * Called after remove() but before devres entries are released. + * This is a Rust only callback. */ void (*post_unbind_rust)(struct device *dev); } p_cb; diff --git a/rust/kernel/driver.rs b/rust/kernel/driver.rs index 36de8098754d..8f0e50729215 100644 --- a/rust/kernel/driver.rs +++ b/rust/kernel/driver.rs @@ -189,8 +189,8 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::= device) { // INVARIANT: `dev` is valid for the duration of the `post_unbind_= callback()`. let dev =3D unsafe { &*dev.cast::>() }; =20 - // `remove()` and all devres callbacks have been completed at this= point, hence drop the - // driver's device private data. + // `remove()` has been completed at this point; devres resources a= re still valid and will + // be released after the driver's bus device private data is dropp= ed. // // SAFETY: By the safety requirements of the `Driver` trait, `T::D= riverData` is the // driver's device private data type. --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 0FAA43A7F4B; Mon, 27 Apr 2026 22:12:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327941; cv=none; b=DpqVAgAC8p95Udu+L1X7+urblH1t167TVxRmWSiBFdwvsiww6opaUIsMHHSHOfJH+bgVpdGEuMHaz3UPMKD6NeaDxHWgQfCbtQHB4znbqYynPkx4Yeif6ApAEEhiQDxgIf9RkxhtAMMpaMlozw6ABJXozqFKrjJUWK1nJb7Dz+Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327941; c=relaxed/simple; bh=pZq55eZRbTUZKxw9zFnJXT0p6kpbJ6klMByaUzBGqrM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=OF1Z4bypCXA/TalF3GOwvobnvUoLs2G3XgW/na5MaRhlJa0WYLRiTsdk7Yc4yrC9AoadGpwcl2o2dSzISOX0adV76/x2oj1pMu+ikpswBlsmwCz5BpPhT4yYMQQ0cw8pxagt1duhiqjxHACMcnaXsSS6+UT+g5EMf2eU+3K1KW0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=eQAgRJnW; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="eQAgRJnW" Received: by smtp.kernel.org (Postfix) with ESMTPSA id ED1B3C2BCB7; Mon, 27 Apr 2026 22:12:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327940; bh=pZq55eZRbTUZKxw9zFnJXT0p6kpbJ6klMByaUzBGqrM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eQAgRJnWO09slwMNvi5KoH/ECuE3dX56H3NTQmoRISAJfYPKST2BKY3GQmasQK/+o tzRIVCG2DjKfdAZWGiNdZwQo5XxG05X4hQ/zsLS1bHhcUsIT5XR1x5ktYAQBxr1EcZ +Xkgmfv/aaByw/8SIwwTWRCrRyfuZFPuGq+HaU8/N3LVK4/vvT0SauQpeF4lJv11CY JUZdqTiCxRvxljRH4cDnmC6+40QCyzckAYdfYFGGavK1PK/341c4Ifjqqwhz1BbICq S1Zw+qc6td7rvxj+9So05Taxbb68hKXQYeigw0ZysZh2zdiEYtoMkNLFGgZOxngig/ AMaqjN8lMppjw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH 02/24] rust: types: add `ForLt` trait for higher-ranked lifetime support Date: Tue, 28 Apr 2026 00:11:00 +0200 Message-ID: <20260427221155.2144848-3-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" From: Gary Guo There are a few cases, e.g. when dealing with data referencing each other, one might want to write code that are generic over lifetimes. For example, if you want take a function that takes `&'a Foo` and gives `Bar<'a>`, you can write: f: impl for<'a> FnOnce(&'a Foo) -> Bar<'a>, However, it becomes tricky when you want that function to not have a fixed `Bar`, but have it be generic again. In this case, one needs something that is generic over types that are themselves generic over lifetimes. `ForLt` provides such support. It provides a trait `ForLt` which describes a type generic over lifetime. One may use `ForLt::Of<'a>` to get an instance of a type for a specific lifetime. For the case of cross referencing, one would almost always want the lifetime to be covariant. Therefore this is also made a requirement for the `ForLt` trait, so functions with `ForLt` trait bound can assume covariance. A macro `ForLt!()` is provided to be able to obtain a type that implements `ForLt`. For example, `ForLt!(for<'a> Bar<'a>)` would yield a type that `::Of<'a>` is `Bar<'a>`. This also works with lifetime elision, e.g. `ForLt!(Bar<'_>)` or for types without lifetime at all, e.g. `ForLt!(u32)`. The API design draws inspiration from the higher-kinded-types [1] crate, however different design decision has been taken (e.g. covariance requirement) and the implementation is independent. License headers use "Apache-2.0 OR MIT" because I anticipate this to be used in pin-init crate too which is licensed as such. Link: https://docs.rs/higher-kinded-types/ [1] Signed-off-by: Gary Guo Acked-by: Uwe Kleine-K=C3=B6nig --- rust/Makefile | 1 + rust/kernel/types.rs | 4 + rust/kernel/types/for_lt.rs | 117 +++++++++++++++++ rust/macros/for_lt.rs | 242 ++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 12 ++ 5 files changed, 376 insertions(+) create mode 100644 rust/kernel/types/for_lt.rs create mode 100644 rust/macros/for_lt.rs diff --git a/rust/Makefile b/rust/Makefile index b361bfedfdf0..c5a9a3339416 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -110,6 +110,7 @@ syn-cfgs :=3D \ feature=3D"parsing" \ feature=3D"printing" \ feature=3D"proc-macro" \ + feature=3D"visit" \ feature=3D"visit-mut" =20 syn-flags :=3D \ diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 4329d3c2c2e5..3119401dcb9f 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -11,6 +11,10 @@ }; use pin_init::{PinInit, Wrapper, Zeroable}; =20 +#[doc(hidden)] +pub mod for_lt; +pub use for_lt::ForLt; + /// Used to transfer ownership to and from foreign (non-Rust) languages. /// /// Ownership is transferred from Rust to a foreign language by calling [`= Self::into_foreign`] and diff --git a/rust/kernel/types/for_lt.rs b/rust/kernel/types/for_lt.rs new file mode 100644 index 000000000000..4983cc761f80 --- /dev/null +++ b/rust/kernel/types/for_lt.rs @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Provide implementation and test of the `ForLt` trait and macro. +//! +//! This module is hidden and user should just use `ForLt!` directly. + +use core::marker::PhantomData; + +/// 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 shorterned. +/// +/// The lifetime involved must be covariant. +/// +/// # 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 does not involved 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)` +/// # >(); +/// ``` +/// +/// The macro will attempt to prove that the type is indeed covariant over= the lifetime supplied. +/// When it cannot be syntactically proven, it will emit checks to ask the= Rust compiler to prove +/// it. +/// ```ignore,compile_fail +/// # use kernel::types::ForLt; +/// # fn expect_lt() {} +/// # expect_lt::< +/// ForLt!(fn(&u32)) // Contravariant, will fail compilation. +/// # >(); +/// ``` +/// +/// There is a limitation if the type refer to generic parameters; if the = macro cannot prove the +/// covariance syntactically, the emitted checks will fail the compilation= as it needs to refer to +/// the generic parameter but is in a separate item. +/// ``` +/// # use kernel::types::ForLt; +/// fn expect_lt() {} +/// # #[allow(clippy::unnecessary_safety_comment, reason =3D "false positi= ve")] +/// fn generic_fn() { +/// // Syntactically proven by the macro +/// expect_lt::(); +/// // Syntactically proven by the macro +/// expect_lt::)>(); +/// // Cannot be syntactically proven, need to check covariance of `KB= ox` +/// // expect_lt::)>(); +/// } +/// ``` +/// +/// # Safety +/// +/// `Self::Of<'a>` must be covariant over the lifetime `'a`. +pub unsafe trait ForLt { + /// The type parameterized by the lifetime. + type Of<'a>; + + /// 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> { + // SAFETY: This is sound as this trait guarantees covariance. + unsafe { core::mem::transmute(long) } + } +} +pub use macros::ForLt; + +/// This is intended to be an "unsafe-to-refer-to" type. +/// +/// 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. +/// +/// `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)>); + +// This is a helper trait for implementation `ForLt` to be able to use HRT= B. +#[doc(hidden)] +pub trait WithLt<'a> { + type Of; +} + +// 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> { + type Of<'a> =3D >::Of; +} diff --git a/rust/macros/for_lt.rs b/rust/macros/for_lt.rs new file mode 100644 index 000000000000..df2027789713 --- /dev/null +++ b/rust/macros/for_lt.rs @@ -0,0 +1,242 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use proc_macro2::{ + Span, + TokenStream, // +}; +use quote::{ + format_ident, + quote, // +}; +use syn::{ + parse::{ + Parse, + ParseStream, // + }, + visit::Visit, + visit_mut::VisitMut, + Lifetime, + Result, + Token, + Type, // +}; + +pub(crate) enum HigherRankedType { + Explicit { + _for_token: Token![for], + _lt_token: Token![<], + lifetime: Lifetime, + _gt_token: Token![>], + ty: Type, + }, + Implicit { + ty: Type, + }, +} + +impl Parse for HigherRankedType { + fn parse(input: ParseStream<'_>) -> Result { + if input.peek(Token![for]) { + Ok(Self::Explicit { + _for_token: input.parse()?, + _lt_token: input.parse()?, + lifetime: input.parse()?, + _gt_token: input.parse()?, + ty: input.parse()?, + }) + } else { + Ok(Self::Implicit { ty: input.parse()? }) + } + } +} + +trait TypeExt { + fn expand_elided_lifetime(&self, explicit_lt: &Lifetime) -> Type; + fn replace_lifetime(&self, src: &Lifetime, dst: &Lifetime) -> Type; + fn has_lifetime(&self, lt: &Lifetime) -> bool; +} + +impl TypeExt for Type { + fn expand_elided_lifetime(&self, explicit_lt: &Lifetime) -> Type { + struct ElidedLifetimeExpander<'a>(&'a Lifetime); + + impl VisitMut for ElidedLifetimeExpander<'_> { + fn visit_lifetime_mut(&mut self, lifetime: &mut Lifetime) { + // Expand explicit `'_` + if lifetime.ident =3D=3D "_" { + *lifetime =3D self.0.clone(); + } + } + + fn visit_type_reference_mut(&mut self, reference: &mut syn::Ty= peReference) { + syn::visit_mut::visit_type_reference_mut(self, reference); + + if reference.lifetime.is_none() { + reference.lifetime =3D Some(self.0.clone()); + } + } + } + + let mut ret =3D self.clone(); + ElidedLifetimeExpander(explicit_lt).visit_type_mut(&mut ret); + ret + } + + fn replace_lifetime(&self, src: &Lifetime, dst: &Lifetime) -> Type { + struct LifetimeReplacer<'a>(&'a Lifetime, &'a Lifetime); + + impl VisitMut for LifetimeReplacer<'_> { + fn visit_lifetime_mut(&mut self, lifetime: &mut Lifetime) { + if lifetime.ident =3D=3D self.0.ident { + *lifetime =3D self.1.clone(); + } + } + } + + let mut ret =3D self.clone(); + LifetimeReplacer(src, dst).visit_type_mut(&mut ret); + ret + } + + fn has_lifetime(&self, lt: &Lifetime) -> bool { + struct HasLifetime<'a>(&'a Lifetime, bool); + + impl Visit<'_> for HasLifetime<'_> { + fn visit_lifetime(&mut self, lifetime: &Lifetime) { + if lifetime.ident =3D=3D self.0.ident { + self.1 =3D true; + } + } + } + + let mut visitor =3D HasLifetime(lt, false); + visitor.visit_type(self); + visitor.1 + } +} + +struct Prover<'a>(&'a Lifetime, Vec<&'a Type>); + +impl<'a> Prover<'a> { + /// Prove that `ty` is covariant over `'lt`. + /// + /// This also needs to prove that it'll be wellformed for any instance= of `'lt`. + /// It can be assumed that `ty` will be wellformed if `'lt` is substit= uted to `'static`. + fn prove(&mut self, ty: &'a Type) { + match ty { + Type::Paren(ty) =3D> self.prove(&ty.elem), + Type::Group(ty) =3D> self.prove(&ty.elem), + + // No lifetime involved + Type::Never(_) =3D> {} + + // `[T; N]` and `[T]` is covariant over `T`. + Type::Array(ty) =3D> self.prove(&ty.elem), + Type::Slice(ty) =3D> self.prove(&ty.elem), + + Type::Tuple(ty) =3D> { + for elem in &ty.elems { + self.prove(elem); + } + } + + // `*const T` is covariant over `T` + Type::Ptr(ty) if ty.const_token.is_some() =3D> self.prove(&ty.= elem), + + // `&T` is covariant over `T` and lifetime. + // + // Note that if we encounter `&'other_lt T`, then we still nee= d to make sure the type + // is wellformed if `T` involves `&'lt`, so we defer to the co= mpiler. + // + // This is to block cases like `ForLt!(for<'a> &'static &'a u3= 2)`, as the presence of + // the type implies `'a: 'static` but this is unsound. + Type::Reference(ty) + if ty.mutability.is_none() && ty.lifetime.as_ref() =3D=3D = Some(self.0) =3D> + { + self.prove(&ty.elem) + } + + // `&[mut] T` is covariant over lifetime. + // In case we have `&[mut] NoLifetime`, we don't need to do ad= ditional checks. + Type::Reference(ty) if !ty.elem.has_lifetime(self.0) =3D> (), + + // No mention of lifetime at all, no need to perform compiler = check. + ty if !ty.has_lifetime(self.0) =3D> (), + + // Otherwise, we need to emit checks so that compiler can dete= rmine if the types are + // actually covariant. + ty =3D> self.1.push(ty), + } + } +} + +pub(crate) fn for_lt(input: HigherRankedType) -> TokenStream { + let (ty, lifetime) =3D 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 + // and expand elided sites. + let lifetime =3D Lifetime { + apostrophe: Span::mixed_site(), + ident: format_ident!("__elided", span =3D Span::mixed_site= ()), + }; + (ty.expand_elided_lifetime(&lifetime), lifetime) + } + }; + + let mut prover =3D Prover(&lifetime, Vec::new()); + prover.prove(&ty); + + let mut proof =3D Vec::new(); + + // Emit proofs for every type that requires additional compiler help i= n proving covariance. + for (idx, required_proof) in prover.1.into_iter().enumerate() { + // Insert a proof that the type is well-formed. + // + // This is intended to workaround a Rust compiler soundness bug re= lated to HRTB. + // https://github.com/rust-lang/rust/issues/152489 + // + // This needs to be a struct instead of fn to avoid the implied WF= bounds. + let wf_proof_name =3D format_ident!("ProveWf{idx}"); + proof.push(quote!( + struct #wf_proof_name<#lifetime>( + ::core::marker::PhantomData<&#lifetime ()>, #required_proof + ); + )); + + // Insert a proof that the type is covariant. + let cov_proof_name =3D format_ident!("prove_covariant_{idx}"); + proof.push(quote!( + fn #cov_proof_name<'__short, '__long: '__short>( + long: #wf_proof_name<'__long> + ) -> #wf_proof_name<'__short> { + long + } + )); + } + + // Make sure that the type is wellformed when substituting lifetime wi= th `'static`. + // + // Currently the Rust compiler doesn't check this, see the above Prove= Wf 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"), + }, + ); + + quote!( + ::kernel::types::for_lt::UnsafeForLtImpl::< + dyn for<#lifetime> ::kernel::types::for_lt::WithLt<#lifetime, = Of =3D #ty>, + #ty_static, + { + #(#proof)* + + 0 + } + > + ) +} diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 2cfd59e0f9e7..e5f6f8318112 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -17,6 +17,7 @@ mod concat_idents; mod export; mod fmt; +mod for_lt; mod helpers; mod kunit; mod module; @@ -489,3 +490,14 @@ pub fn kunit_tests(attr: TokenStream, input: TokenStre= am) -> TokenStream { .unwrap_or_else(|e| e.into_compile_error()) .into() } + +/// Obtain a type that implements `ForLt` for the given higher-ranked type. +/// +/// Please refer to the documentation of [`ForLt`] trait. +/// +/// [`ForLt`]: trait.ForLt.html +#[proc_macro] +#[allow(non_snake_case)] // The macro shares the name with the trait. +pub fn ForLt(input: TokenStream) -> TokenStream { + for_lt::for_lt(parse_macro_input!(input)).into() +} --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 521123793BB; Mon, 27 Apr 2026 22:12:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327947; cv=none; b=NqmsxIXdEaMWKEx/IR6Y4qX0tZaMbQfh12F6J5+s9wx+0n9gMM/McARG8qsYwGiVUcovK62v+exCD9Y92YnAJXYPcBfY6UjJ59TT55UD3eGk2GCnTX0kA33GP6Pz71HW5rclNwYxD4c+adFFo1GHDUY3Ask93nFL3JzHA8PeEek= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327947; c=relaxed/simple; bh=bM12jT1hv0K0oENDCBepC4nrrQUDFCBN7Pb+KzPNmtA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=d7Njre9t3l84FCi5jlTIN+64UsEDKaVVvdLoS1Tz/jD/N5mS8d4F6Px2RFTRTYdiSrW/q8h2h0POWBPwlCsoBIq246AV04hIbxoKWYU+it8oYPBK862Og7vO6WkoVsqnkq4cIa+Pw1p4z7+jA37LcHGODxJ35xJ6Pk5yqOjwuvA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=dJLRKLjR; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="dJLRKLjR" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 19B69C19425; Mon, 27 Apr 2026 22:12:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327947; bh=bM12jT1hv0K0oENDCBepC4nrrQUDFCBN7Pb+KzPNmtA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dJLRKLjRm9qlfsoANY2fNN4UtrsSDSd7D+xH5aB4COfjRw7n/QHDm96SJn7XnB4PX J9hzk1e+EKPC4SU2TmXraGD3g7QAFijLpGK7VwvpCZY4ESZ/f0uFK0aJDyqpijdU40 SX7nSiNxoSYnjx5aLu0tPAJ7i2IVobXsM5ozDYjWyezcCSt8Yx+nuchuAw/SN/bOCi Y8/H55/J5Ws2Do3nbhGYPCG+GMSMnQ2UYLlpLrDyMgZj4hfcdtx6j4m41uyUnJqB27 SueqprNZm0gboHo8WVABYI87am+945g0j3AP+XWmIuTrWVTVs7osXRTUz+fN57rzFs qaCQ2uP3eegzw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 03/24] rust: devres: add ForLt support to Devres Date: Tue, 28 Apr 2026 00:11:01 +0200 Message-ID: <20260427221155.2144848-4-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Use ForLt::cast_ref() in Devres access methods, enabling lifetime shortening for types that are covariant over their lifetime parameter. This is a no-op for 'static types, but prepares Devres for use with lifetime-parameterized types such as pci::Bar<'_, SIZE>. Add DevresGuard as a wrapper around RevocableGuard that applies ForLt::cast_ref() on deref(). Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/devres.rs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 9e5f93aed20c..7baabcdb1ad3 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -24,6 +24,7 @@ Arc, // }, types::{ + ForLt, ForeignOwnable, Opaque, // }, @@ -324,22 +325,26 @@ pub fn access<'a>(&'a self, dev: &'a Device) -= > Result<&'a T> { // SAFETY: `dev` being the same device as the device this `Devres`= has been created for // proves that `self.data` hasn't been revoked and is guaranteed t= o not be revoked as long // as `dev` lives; `dev` lives at least as long as `self`. - Ok(unsafe { self.data().access() }) + Ok(::cast_ref(unsafe { self.data().access() })) } =20 /// [`Devres`] accessor for [`Revocable::try_access`]. - pub fn try_access(&self) -> Option> { - self.data().try_access() + #[allow(clippy::type_complexity)] + pub fn try_access(&self) -> Option> { + self.data().try_access().map(DevresGuard) } =20 /// [`Devres`] accessor for [`Revocable::try_access_with`]. pub fn try_access_with R>(&self, f: F) -> Option { - self.data().try_access_with(f) + self.data() + .try_access_with(|data| f(::cast_ref(data))) } =20 /// [`Devres`] accessor for [`Revocable::try_access_with_guard`]. pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> O= ption<&'a T> { - self.data().try_access_with_guard(guard) + self.data() + .try_access_with_guard(guard) + .map(::cast_ref) } } =20 @@ -365,6 +370,20 @@ fn drop(&mut self) { } } =20 +/// Guard returned by [`Devres::try_access`]. +/// +/// Dereferences to `F::Of<'a>`, applying [`ForLt::cast_ref`] to shorten t= he lifetime of the +/// stored data to the guard's borrow lifetime. +pub struct DevresGuard<'a, F: ForLt>(RevocableGuard<'a, F::Of<'static>>); + +impl<'a, F: ForLt> core::ops::Deref for DevresGuard<'a, F> { + type Target =3D F::Of<'a>; + + fn deref(&self) -> &Self::Target { + F::cast_ref(&*self.0) + } +} + /// 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 Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 A280526F2BE; Mon, 27 Apr 2026 22:12:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327953; cv=none; b=b3vDcDHfpNKg6TllAOYjfiScgeO5bhflkEHJfmTbBlACpZ6QJD73biPTERQUD+8KhAs/WY9K8E1C9iBTn4tbFSNIQtx/51eG2wdbPRa1uc/Sp+sNqJovzLm1erc4qkqTMcmkbUewsQBubkqEZ++HTjaWVMCUpT8bPbT/6gBe8yQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327953; c=relaxed/simple; bh=Ati2vPAhnUy/yRihj18ZVX8vWDPBaY6FgcnT2mNf5VQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=lnWtejeJ+js8lRbDx2YBObtBMhhjxnJ8+Z2c+K+DZ1q97DrOgQrEylWr6sKwPyGIrUt88+1MyXz9DlfwMaenGc7B0yfWjf3gZra2PcFOXgsmh6rU+Gzr51ySeHEEcIFO1fCT0PNejE6rXgx/xr2Anv+6831JR6t/vvGkLFT9fVY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Z0SXXuMi; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Z0SXXuMi" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 646BCC2BCB5; Mon, 27 Apr 2026 22:12:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327953; bh=Ati2vPAhnUy/yRihj18ZVX8vWDPBaY6FgcnT2mNf5VQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Z0SXXuMi6XVskH6BEWb1d0OgooVVS++6oDw5xpPSYFQG8y73wco9uA3rAsWS5CsYl LzKdIyioztkN3kpNbtfhXZiPbBhlcBc7/AZ7DMY7Gc6EJm2QfzWmuP27e2gg9+AiAE /zBJyNAQyLypvUxBwP5GtJaF3FZPAkFhwbyb8McmCb/3ETP+tcOrGouNmYpYRSaOKb TkdyWExk8Ud8ZlvEK1abmxsnLavKhekYgzkdvlscm7CFcxIMVlhZp3cXZUuiZzuMOn I3bCxXGQfCzfQtenEp05tARDsj/Kj3VF+Z1FBb3gqFrj9ismWV3t+wcGJbkdoXLY5T Pyy/Q8u44I2Kw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 04/24] rust: device: generalize drvdata methods over ForLt Date: Tue, 28 Apr 2026 00:11:02 +0200 Message-ID: <20260427221155.2144848-5-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Generalize set_drvdata(), drvdata_obtain() and drvdata_borrow() to take F: ForLt, enabling Higher-Ranked Lifetime Types (HRT) for device private data. The data is initialized as F::Of<'a> and stored as F::Of<'static>; ForLt guarantees covariance, making it sound to shorten the stored 'static lifetime to the borrow lifetime of &self. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/auxiliary.rs | 7 ++-- rust/kernel/device.rs | 80 +++++++++++++++++++++++++++++----------- rust/kernel/driver.rs | 15 +++++--- rust/kernel/i2c.rs | 13 ++++--- rust/kernel/pci.rs | 11 ++++-- rust/kernel/platform.rs | 11 ++++-- rust/kernel/usb.rs | 11 ++++-- 7 files changed, 101 insertions(+), 47 deletions(-) diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index 467befea8e44..5cd10b254baf 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -20,6 +20,7 @@ }, prelude::*, types::{ + ForLt, ForeignOwnable, Opaque, // }, @@ -46,7 +47,7 @@ // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. unsafe impl driver::DriverLayout for Adapter { type DriverType =3D bindings::auxiliary_driver; - type DriverData =3D T; + type DriverData =3D ForLt!(T); const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 @@ -97,7 +98,7 @@ extern "C" fn probe_callback( from_result(|| { let data =3D T::probe(adev, info); =20 - adev.as_ref().set_drvdata(data)?; + adev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -112,7 +113,7 @@ extern "C" fn remove_callback(adev: *mut bindings::auxi= liary_device) { // SAFETY: `remove_callback` is only ever called after a successfu= l call to // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called // and stored a `Pin>`. - let data =3D unsafe { adev.as_ref().drvdata_borrow::() }; + let data =3D unsafe { adev.as_ref().drvdata_borrow::() = }; =20 T::unbind(adev, data); } diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index fd50399aadea..09cbe8a438a9 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -10,6 +10,7 @@ prelude::*, sync::aref::ARef, types::{ + ForLt, ForeignOwnable, Opaque, // }, // @@ -202,23 +203,41 @@ pub unsafe fn as_bound(&self) -> &Device { } =20 impl Device { - /// Store a pointer to the bound driver's private data. - pub fn set_drvdata(&self, data: impl PinInit) ->= Result { + /// Store the bound driver's private data. + /// + /// `F` is the [`ForLt`] encoding of the data type. For types without = a lifetime parameter, + /// use [`ForLt!(T)`](macro@ForLt). For lifetime-parameterized types, = the data is + /// initialized as `F::Of<'a>` and stored as `F::Of<'static>`; lifetim= es are erased and do not + /// affect layout, while [`ForLt`] guarantees covariance for safe life= time shortening. + /// + /// [`ForLt`]: trait@ForLt + pub fn set_drvdata<'a, F: ForLt>(&self, data: impl PinInit, = Error>) -> Result + where + F::Of<'static>: 'static, + { let data =3D KBox::pin_init(data, GFP_KERNEL)?; =20 + // SAFETY: Lifetimes are erased and do not affect layout, so Of<'a= > and Of<'static> have + // identical representation. The raw pointer is type-erased throug= h c_void anyway. + let ptr =3D KBox::into_raw(unsafe { Pin::into_inner_unchecked(data= ) }); + // SAFETY: By the type invariants, `self.as_raw()` is a valid poin= ter to a `struct device`. - unsafe { bindings::dev_set_drvdata(self.as_raw(), data.into_foreig= n().cast()) }; + unsafe { bindings::dev_set_drvdata(self.as_raw(), ptr.cast()) }; =20 Ok(()) } =20 /// Take ownership of the private data stored in this [`Device`]. /// + /// `F` is the [`ForLt`] encoding of the data type. The returned [`KBo= x`] has its lifetime + /// tied to `&self`, ensuring it is dropped before the device goes awa= y. + /// /// # Safety /// - /// - The type `T` must match the type of the `ForeignOwnable` previou= sly stored by - /// [`Device::set_drvdata`]. - pub(crate) unsafe fn drvdata_obtain(&self) -> Option>> { + /// - `F` must match the [`ForLt`] type previously stored by [`Device:= :set_drvdata`]. + /// + /// [`ForLt`]: trait@ForLt + pub(crate) unsafe fn drvdata_obtain(&self) -> Option>>> { // SAFETY: By the type invariants, `self.as_raw()` is a valid poin= ter to a `struct device`. let ptr =3D unsafe { bindings::dev_get_drvdata(self.as_raw()) }; =20 @@ -230,24 +249,34 @@ pub(crate) unsafe fn drvdata_obtain(&self= ) -> Option>> { } =20 // SAFETY: - // - If `ptr` is not NULL, it comes from a previous call to `into_= foreign()`. - // - `dev_get_drvdata()` guarantees to return the same pointer giv= en to `dev_set_drvdata()` - // in `into_foreign()`. - Some(unsafe { Pin::>::from_foreign(ptr.cast()) }) + // - If `ptr` is not NULL, it was stored by a previous call to `se= t_drvdata()`, which + // stores a pointer via `KBox::into_raw()`. + // - Lifetimes are erased and do not affect layout, so reconstruct= ing as `F::Of<'_>` + // (tied to `&self`) is sound. + // - `dev_get_drvdata()` guarantees to return the same pointer giv= en to + // `dev_set_drvdata()`. + Some(unsafe { Pin::new_unchecked(KBox::from_raw(ptr.cast())) }) } =20 /// Borrow the driver's private data bound to this [`Device`]. /// + /// `F` is the [`ForLt`] encoding of the data type. The returned refer= ence has its lifetime + /// shortened from `'static` to `&self`'s borrow lifetime via [`ForLt:= :cast_ref`]. + /// /// # Safety /// /// - Must only be called after a preceding call to [`Device::set_drvd= ata`] and before the /// device is fully unbound. - /// - The type `T` must match the type of the `ForeignOwnable` previou= sly stored by - /// [`Device::set_drvdata`]. - pub unsafe fn drvdata_borrow(&self) -> Pin<&T> { + /// - `F` must match the [`ForLt`] type previously stored by [`Device:= :set_drvdata`]. + /// + /// [`ForLt`]: trait@ForLt + pub unsafe fn drvdata_borrow(&self) -> Pin<&F::Of<'_>> + where + F::Of<'static>: 'static, + { // SAFETY: `drvdata_unchecked()` has the exact same safety require= ments as the ones // required by this method. - unsafe { self.drvdata_unchecked() } + unsafe { self.drvdata_unchecked::() } } } =20 @@ -258,18 +287,25 @@ impl Device { /// /// - Must only be called after a preceding call to [`Device::set_drvd= ata`] and before /// the device is fully unbound. - /// - The type `T` must match the type of the `ForeignOwnable` previou= sly stored by - /// [`Device::set_drvdata`]. - unsafe fn drvdata_unchecked(&self) -> Pin<&T> { + /// - `F` must match the [`ForLt`] type previously stored by [`Device:= :set_drvdata`]. + unsafe fn drvdata_unchecked(&self) -> Pin<&F::Of<'_>> + where + F::Of<'static>: 'static, + { // SAFETY: By the type invariants, `self.as_raw()` is a valid poin= ter to a `struct device`. let ptr =3D unsafe { bindings::dev_get_drvdata(self.as_raw()) }; =20 // SAFETY: - // - By the safety requirements of this function, `ptr` comes from= a previous call to - // `into_foreign()`. - // - `dev_get_drvdata()` guarantees to return the same pointer giv= en to `dev_set_drvdata()` - // in `into_foreign()`. - unsafe { Pin::>::borrow(ptr.cast()) } + // - By the safety requirements of this function, `ptr` was stored= by a previous call to + // `set_drvdata()` via `KBox::into_raw()`. + // - `dev_get_drvdata()` guarantees to return the same pointer giv= en to + // `dev_set_drvdata()`. + let pinned: Pin<&F::Of<'static>> =3D + unsafe { Pin::>>::borrow(ptr.cast()) }; + + // SAFETY: `ForLt` guarantees covariance, making it sound to short= en 'static to &self's + // lifetime via cast_ref(). + unsafe { Pin::new_unchecked(F::cast_ref(pinned.get_ref())) } } } =20 diff --git a/rust/kernel/driver.rs b/rust/kernel/driver.rs index 8f0e50729215..29a67b12c872 100644 --- a/rust/kernel/driver.rs +++ b/rust/kernel/driver.rs @@ -99,7 +99,10 @@ device, of, prelude::*, - types::Opaque, + types::{ + ForLt, + Opaque, // + }, ThisModule, // }; =20 @@ -112,14 +115,16 @@ /// /// Implementors must guarantee that: /// - `DriverType` is `repr(C)`, -/// - `DriverData` is the type of the driver's device private data. +/// - `DriverData` is the [`ForLt`] encoding of the driver's device privat= e data type. /// - `DriverType` embeds a valid `struct device_driver` at byte offset `D= EVICE_DRIVER_OFFSET`. +/// +/// [`ForLt`]: trait@ForLt pub unsafe trait DriverLayout { /// The specific driver type embedding a `struct device_driver`. type DriverType: Default; =20 - /// The type of the driver's device private data. - type DriverData; + /// The [`ForLt`](trait@ForLt) encoding of the driver's device private= data type. + type DriverData: ForLt; =20 /// Byte offset of the embedded `struct device_driver` within `DriverT= ype`. /// @@ -193,7 +198,7 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::= device) { // be released after the driver's bus device private data is dropp= ed. // // SAFETY: By the safety requirements of the `Driver` trait, `T::D= riverData` is the - // driver's device private data type. + // ForLt encoding of the driver's device private data type. drop(unsafe { dev.drvdata_obtain::() }); } =20 diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index 7b908f0c5a58..cde3dd7a6cc7 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -20,7 +20,10 @@ ARef, AlwaysRefCounted, // }, - types::Opaque, // + types::{ + ForLt, + Opaque, // + }, // }; =20 use core::{ @@ -98,7 +101,7 @@ macro_rules! i2c_device_table { // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. unsafe impl driver::DriverLayout for Adapter { type DriverType =3D bindings::i2c_driver; - type DriverData =3D T; + type DriverData =3D ForLt!(T); const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 @@ -165,7 +168,7 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_c= lient) -> kernel::ffi::c_ from_result(|| { let data =3D T::probe(idev, info); =20 - idev.as_ref().set_drvdata(data)?; + idev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -177,7 +180,7 @@ extern "C" fn remove_callback(idev: *mut bindings::i2c_= client) { // SAFETY: `remove_callback` is only ever called after a successfu= l call to // `probe_callback`, hence it's guaranteed that `I2cClient::set_dr= vdata()` has been called // and stored a `Pin>`. - let data =3D unsafe { idev.as_ref().drvdata_borrow::() }; + let data =3D unsafe { idev.as_ref().drvdata_borrow::() = }; =20 T::unbind(idev, data); } @@ -189,7 +192,7 @@ extern "C" fn shutdown_callback(idev: *mut bindings::i2= c_client) { // SAFETY: `shutdown_callback` is only ever called after a success= ful call to // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called // and stored a `Pin>`. - let data =3D unsafe { idev.as_ref().drvdata_borrow::() }; + let data =3D unsafe { idev.as_ref().drvdata_borrow::() = }; =20 T::shutdown(idev, data); } diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index af74ddff6114..fe5148f41d8b 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -19,7 +19,10 @@ }, prelude::*, str::CStr, - types::Opaque, + types::{ + ForLt, + Opaque, // + }, ThisModule, // }; use core::{ @@ -64,7 +67,7 @@ // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. unsafe impl driver::DriverLayout for Adapter { type DriverType =3D bindings::pci_driver; - type DriverData =3D T; + type DriverData =3D ForLt!(T); const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 @@ -115,7 +118,7 @@ extern "C" fn probe_callback( from_result(|| { let data =3D T::probe(pdev, info); =20 - pdev.as_ref().set_drvdata(data)?; + pdev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -130,7 +133,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::pci_= dev) { // SAFETY: `remove_callback` is only ever called after a successfu= l call to // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called // and stored a `Pin>`. - let data =3D unsafe { pdev.as_ref().drvdata_borrow::() }; + let data =3D unsafe { pdev.as_ref().drvdata_borrow::() = }; =20 T::unbind(pdev, data); } diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 8917d4ee499f..7ff69e3eea90 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -27,7 +27,10 @@ }, of, prelude::*, - types::Opaque, + types::{ + ForLt, + Opaque, // + }, ThisModule, // }; =20 @@ -50,7 +53,7 @@ // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. unsafe impl driver::DriverLayout for Adapter { type DriverType =3D bindings::platform_driver; - type DriverData =3D T; + type DriverData =3D ForLt!(T); const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 @@ -103,7 +106,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platf= orm_device) -> kernel::ff from_result(|| { let data =3D T::probe(pdev, info); =20 - pdev.as_ref().set_drvdata(data)?; + pdev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -118,7 +121,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::plat= form_device) { // SAFETY: `remove_callback` is only ever called after a successfu= l call to // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called // and stored a `Pin>`. - let data =3D unsafe { pdev.as_ref().drvdata_borrow::() }; + let data =3D unsafe { pdev.as_ref().drvdata_borrow::() = }; =20 T::unbind(pdev, data); } diff --git a/rust/kernel/usb.rs b/rust/kernel/usb.rs index 9c17a672cd27..9b9d3ae41087 100644 --- a/rust/kernel/usb.rs +++ b/rust/kernel/usb.rs @@ -19,7 +19,10 @@ }, prelude::*, sync::aref::AlwaysRefCounted, - types::Opaque, + types::{ + ForLt, + Opaque, // + }, ThisModule, // }; use core::{ @@ -41,7 +44,7 @@ // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. unsafe impl driver::DriverLayout for Adapter { type DriverType =3D bindings::usb_driver; - type DriverData =3D T; + type DriverData =3D ForLt!(T); const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 @@ -93,7 +96,7 @@ extern "C" fn probe_callback( let data =3D T::probe(intf, id, info); =20 let dev: &device::Device =3D intf.as_ref= (); - dev.set_drvdata(data)?; + dev.set_drvdata::(data)?; Ok(0) }) } @@ -110,7 +113,7 @@ extern "C" fn disconnect_callback(intf: *mut bindings::= usb_interface) { // SAFETY: `disconnect_callback` is only ever called after a succe= ssful call to // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called // and stored a `Pin>`. - let data =3D unsafe { dev.drvdata_borrow::() }; + let data =3D unsafe { dev.drvdata_borrow::() }; =20 T::disconnect(intf, data); } --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 A848226F2BE; Mon, 27 Apr 2026 22:12:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327959; cv=none; b=kNaDRx+vHizcldBk9bTyT26pr84552ov2Rq9mhkp01VlY6+Om1yrKIrnJC8Rdh0cirn5cSRrM+1uKKSogFH0ZLkY53c5MzBIUkLM50wKsWnItd5Tx9F7oi7AKVzkt+IQhPsWZ3Gg9s+Z1bahgApduASKLvJ+EsDHD8KOztCcCxM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327959; c=relaxed/simple; bh=LHxKj2Sqgk+a3BT1FgcDoIHc1Tx9bGrGlwRiqgYkiCM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=SQgPiCOR4CiyvihL8hlO7XnoTkwp+PmMHKwQpxK3xBKtKXXjzjlxho8ukK1GsJ2GyksP035xr+CQv8tCmKGJ8XDBJGwepTFwhIUIEJlrVmbQPrtLx7Mqktah2YCDDfOo0U6dYWsLSB0sgMYkMuSW3LbbftrMJlPj04e74H4z2c4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BopU7sLk; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="BopU7sLk" Received: by smtp.kernel.org (Postfix) with ESMTPSA id AE6DBC19425; Mon, 27 Apr 2026 22:12:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327959; bh=LHxKj2Sqgk+a3BT1FgcDoIHc1Tx9bGrGlwRiqgYkiCM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BopU7sLkdBecu6RzsUKESdx7jKEorWFsjYHninRucrKzOsyfaIZxAnbqOXmsf78yA LmBdvjlPHJ97CZ3/RZFmbxtU/RuVlMvkjTGHeIFrwlvhMgK2HPW6Rrym9ig+Kg/QTQ xcRNBDNx2WH4AgWRSd2W2W5BkQBYSPhfArdATJ+MhZUf3RGa4k1d+M/Pvkp8a/Ww6p 3Zv6Vz+kqxpkom45ckoM2Sf3kOI9wASJPg8k0aANf6FSFjcEg1HtidmpZK5UhjWmu8 N46jRAPCJSQNUMHtm8CK2gtUrh0gGJdFLV7OXWW/i1SOHOSTeGmvoLbqBN476do3CH GhapsOt446RNw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 05/24] rust: driver: make Adapter trait lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:03 +0200 Message-ID: <20260427221155.2144848-6-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Parameterize the Adapter trait with a lifetime, changing the id_info(), of_id_info() and acpi_id_info() methods to take &'a Device and return &'a Self::IdInfo instead of &'static. This is needed for the ForLt conversion of bus driver traits. Once Driver becomes lifetime-parameterized, its IdInfo associated type may depend on the lifetime parameter. With Adapter<'a>, the impl can set IdInfo =3D as Driver<'a>>::IdInfo and the lifetime flows through naturally, avoiding the need for transmute. For the current non-lifetime-parameterized Driver trait, this is a no-op type relaxation; IdInfo is 'static and &'static coerces to &'a. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/driver.rs | 16 ++++++++++------ rust/kernel/i2c.rs | 10 +++++----- rust/kernel/platform.rs | 4 ++-- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/rust/kernel/driver.rs b/rust/kernel/driver.rs index 29a67b12c872..91490040d77e 100644 --- a/rust/kernel/driver.rs +++ b/rust/kernel/driver.rs @@ -96,7 +96,11 @@ =20 use crate::{ acpi, - device, + device::{ + self, + Bound, + Device, // + }, of, prelude::*, types::{ @@ -192,7 +196,7 @@ extern "C" fn post_unbind_callback(dev: *mut bindings::= device) { // a `struct device`. // // INVARIANT: `dev` is valid for the duration of the `post_unbind_= callback()`. - let dev =3D unsafe { &*dev.cast::>() }; + let dev =3D unsafe { &*dev.cast::>() = }; =20 // `remove()` has been completed at this point; devres resources a= re still valid and will // be released after the driver's bus device private data is dropp= ed. @@ -289,7 +293,7 @@ fn init( /// of a device and a driver. /// /// It provides bus independent functions for device / driver interactions. -pub trait Adapter { +pub trait Adapter<'a> { /// The type holding driver private data about each device id supporte= d by the driver. type IdInfo: 'static; =20 @@ -299,7 +303,7 @@ pub trait Adapter { /// Returns the driver's private data from the matching entry in the [= `acpi::IdTable`], if any. /// /// If this returns `None`, it means there is no match with an entry i= n the [`acpi::IdTable`]. - fn acpi_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo>= { + fn acpi_id_info(dev: &'a Device) -> Option<&'a Self::IdInfo> { #[cfg(not(CONFIG_ACPI))] { let _ =3D dev; @@ -333,7 +337,7 @@ fn acpi_id_info(dev: &device::Device) -> Option<&'stati= c Self::IdInfo> { /// Returns the driver's private data from the matching entry in the [= `of::IdTable`], if any. /// /// If this returns `None`, it means there is no match with an entry i= n the [`of::IdTable`]. - fn of_id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> { + fn of_id_info(dev: &'a Device) -> Option<&'a Self::IdInfo> { #[cfg(not(CONFIG_OF))] { let _ =3D dev; @@ -369,7 +373,7 @@ fn of_id_info(dev: &device::Device) -> Option<&'static = Self::IdInfo> { /// /// If this returns `None`, it means that there is no match in any of = the ID tables directly /// associated with a [`device::Device`]. - fn id_info(dev: &device::Device) -> Option<&'static Self::IdInfo> { + fn id_info(dev: &'a Device) -> Option<&'a Self::IdInfo> { let id =3D Self::acpi_id_info(dev); if id.is_some() { return id; diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index cde3dd7a6cc7..08d310aa9d6b 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -162,8 +162,8 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c_c= lient) -> kernel::ffi::c_ // INVARIANT: `idev` is valid for the duration of `probe_callback(= )`. let idev =3D unsafe { &*idev.cast::>() }; =20 - let info =3D - Self::i2c_id_info(idev).or_else(|| ::= id_info(idev.as_ref())); + let info =3D Self::i2c_id_info(idev) + .or_else(|| >::id_info(idev.as_ref= ())); =20 from_result(|| { let data =3D T::probe(idev, info); @@ -198,14 +198,14 @@ extern "C" fn shutdown_callback(idev: *mut bindings::= i2c_client) { } =20 /// The [`i2c::IdTable`] of the corresponding driver. - fn i2c_id_table() -> Option::IdInfo>= > { + fn i2c_id_table() -> Option>= ::IdInfo>> { T::I2C_ID_TABLE } =20 /// Returns the driver's private data from the matching entry in the [= `i2c::IdTable`], if any. /// /// If this returns `None`, it means there is no match with an entry i= n the [`i2c::IdTable`]. - fn i2c_id_info(dev: &I2cClient) -> Option<&'static ::IdInfo> { + fn i2c_id_info(dev: &I2cClient) -> Option<&'static >::IdInfo> { let table =3D Self::i2c_id_table()?; =20 // SAFETY: @@ -225,7 +225,7 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static ::Id } } =20 -impl driver::Adapter for Adapter { +impl<'a, T: Driver + 'static> driver::Adapter<'a> for Adapter { type IdInfo =3D T::IdInfo; =20 fn of_id_table() -> Option> { diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 7ff69e3eea90..1585b6a1ac45 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -101,7 +101,7 @@ extern "C" fn probe_callback(pdev: *mut bindings::platf= orm_device) -> kernel::ff // // INVARIANT: `pdev` is valid for the duration of `probe_callback(= )`. let pdev =3D unsafe { &*pdev.cast::>(= ) }; - let info =3D ::id_info(pdev.as_ref()); + let info =3D >::id_info(pdev.as_ref()); =20 from_result(|| { let data =3D T::probe(pdev, info); @@ -127,7 +127,7 @@ extern "C" fn remove_callback(pdev: *mut bindings::plat= form_device) { } } =20 -impl driver::Adapter for Adapter { +impl<'a, T: Driver + 'static> driver::Adapter<'a> for Adapter { type IdInfo =3D T::IdInfo; =20 fn of_id_table() -> Option> { --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 2D9863793BB; Mon, 27 Apr 2026 22:12:45 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327966; cv=none; b=H2pc/z3/h3F8isEb8SvTVNYOQOVKfZrzfWRlYBRV3vO/UTVKCma58NP4oqkEPpqnOeYdnj18Tr2s7ypGZ1P0trRidDW1/gvyVNVrQGRu9YOcqDwIgjDftjhryZV+fmAFlkFINiGZcEca3SPGi2aZZdS7r7YUfWQldBL7RVyb2vQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327966; c=relaxed/simple; bh=VjAUar7iUek881IcjlBLE2afDi6SB1mE1iW+SiRaRgw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=qYVOfz6tiqPUosqjNiHrRGt/zAVNMxJbkU3k21VrlDr9cb0KqiU7JTo/1tAjL9FOiybIq1yOFdqLZS0q2Gj8KUINzpdPqY0os/oWherHD7Zr2wz5Blsmrz+oTDw9oUrxvxWeoK7rWEbUoBlBPKEJLFBerfRJCsvC8N0uPbKZ8kI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=oCnJZRBa; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="oCnJZRBa" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 058CAC2BCB5; Mon, 27 Apr 2026 22:12:39 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327965; bh=VjAUar7iUek881IcjlBLE2afDi6SB1mE1iW+SiRaRgw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=oCnJZRBads/lxnPJyOs/wfgySb4LDK/YI9GTuIrbTSkZDDYkhdCWrgrhVIb+8LoGb qGleP9nvxlQYxx7/YOlp7kI+HgtwfZPC6ejrIZCL7Xm1o/2S93HM4+1ynCqG/0QizI JijgQxV1ZP/khPzZNLzpLcSUZo+Tdzw//DiAWxl6TKy1GP5uBme7gJ/7I+7kwCoM/Y KiuyZgij4uT8KjUBzszseotZ2/+nSmH6rj8Scxz0fMn9RKvRSvESUtxYxNa6XpMq32 673yrs5Tsck645DlzkvHvU+rPuWJP80lvWxrW3Jc89t/oJSFJBHHA0huwYlikiUru7 M4x6oELI2KMHg== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 06/24] rust: pci: implement Sync for Device Date: Tue, 28 Apr 2026 00:11:04 +0200 Message-ID: <20260427221155.2144848-7-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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 Sync for Device in addition to Device. The underlying struct pci_dev is the same; Bound is a zero-sized type-state marker that does not affect thread safety. This is needed for pci::Bar to hold &'a Device (required for Bar::into_devres()) while remaining Send. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/pci.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index fe5148f41d8b..6f82f2e6c74f 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -526,3 +526,7 @@ unsafe impl Send for Device {} // SAFETY: `Device` can be shared among threads because all methods of `De= vice` // (i.e. `Device) are thread safe. unsafe impl Sync for Device {} + +// SAFETY: Same as `Device` -- the underlying `struct pci_dev` is = the same; +// `Bound` is a zero-sized type-state marker that does not affect thread s= afety. +unsafe impl Sync for Device {} --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 87F0C3793BB; Mon, 27 Apr 2026 22:12:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327972; cv=none; b=LNI7Mwt8YiLXTErZ3nNoZWk2D2DOtmSrHpGVPTRimpsRBm76W21RB2ujPmfeooeZn9po+aC5aZw3FUqtLS+oOFbwElmd2ldREjkwMRprJwnVaWkWA7O2AS+sdz4J6Ah5ZaoOfM/3jYb3Z2YjjtK3hlEk23T+NAq6dYaIGKmoZzw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327972; c=relaxed/simple; bh=ZL0zZCof376hKMo9gCVpVeB8x9AGCrUGR4sSsGtHfmE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=eNXzx/f/IATUdoCQGba8IUCGKoaX4IXICDxR0v4RXfz/6XGs/pC8OesGvjfdA6RJ48aqfP2UolqcG9pk9i6xxepFHPb43oEULySTCIfBxF8tMHB1+eFN/4B5DY12OGZWJgELqkRqo9Qy3rFqiFvBc9ZpBrN22RpMF9+JFdq2NCs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=fhs4XRkL; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="fhs4XRkL" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4FDFDC19425; Mon, 27 Apr 2026 22:12:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327972; bh=ZL0zZCof376hKMo9gCVpVeB8x9AGCrUGR4sSsGtHfmE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fhs4XRkLdj6f/yxZNfHY6NuvcXE6SzB2cRVRxBtKOZ+l1bM47Btenuklj8PnO7Euf khfDpJdzT032Ikvv4at1RhXzxCH+/+1Uvn3f7KoeMRwvTKb+zkfMZUb7u1o/pCbF0d /dEr7ZJPu53xD9cenRMXcnCj8FI+xI+R4kKbUj6YbyPkIH9SsuNQaDDYtB7ifcWCS0 gGzh7PfW+xelHhV9gbUUJTnsKh7Zt0j6wVOd87hRgmZwoLvA/OLNIh+TCTHjl8t+Cx /C5H5XJL/M7py5KzI5XsYcqHQpa4xfxahE7QsRiLg7qI+JtkTIyO5t2GIE48cKwSEh hsBF0GHxBhvdA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 07/24] rust: platform: implement Sync for Device Date: Tue, 28 Apr 2026 00:11:05 +0200 Message-ID: <20260427221155.2144848-8-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Device uses the same underlying struct platform_device as Device; Bound is a zero-sized type-state marker that does not affect thread safety. This is needed for drivers to store &'a platform::Device in their HRT private data while remaining Send. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/platform.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 1585b6a1ac45..ae648304eb5b 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -564,3 +564,7 @@ unsafe impl Send for Device {} // SAFETY: `Device` can be shared among threads because all methods of `De= vice` // (i.e. `Device) are thread safe. unsafe impl Sync for Device {} + +// SAFETY: Same as `Device` -- the underlying `struct platform_dev= ice` is the same; +// `Bound` is a zero-sized type-state marker that does not affect thread s= afety. +unsafe impl Sync for Device {} --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 C83D53A9630; Mon, 27 Apr 2026 22:12:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327978; cv=none; b=HJSvEaZ1sN2mEOWugwTbLIAgEnMHXcZKSlNFXbRHPtALWEFRcN0cJHK0hmBwuqid14uO4Dx/l/g38sDpLCwrHbgtHI2jZ3SinMttq1wrCD1O9R0fk88UXRV0E7njUSV4fDVWAOQvsQ9mJZAY9mf7x5ZJf2ImeKI8TDqvAlgb7p8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327978; c=relaxed/simple; bh=yr8B+4rt/53Knez9GYsPy8kH5qdqBUAoWhXDtRNohr0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=cPxKZpmkKVSDqvHQ4RUjAPcI1M4ausUzP+SAIaxRBP7k0iiCdS3nExTtAVmOnasf9yNi1hrxvbPbUDR2df1XU6cMWPfzXuPSN3Tpqqz+7ZIhwD5TQWENfosnUHjuyOrpIFYRpOiDxaQT+RhA6TMSXlC/Myw1eEaSLLySwaEadqk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=hRAZBQDT; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="hRAZBQDT" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9A084C2BCB5; Mon, 27 Apr 2026 22:12:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327978; bh=yr8B+4rt/53Knez9GYsPy8kH5qdqBUAoWhXDtRNohr0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hRAZBQDTvT3S9AqkGWDbTNPEVAS3MP3JPhQQKSCj97OAdzLxXMI+QvTq++4rkUYAl bSVaKBzRYrpVbi6cIHmQe1C2waWZlCuZEGiQd24otVcKb6RGENUB3iWiVqGdr5NVLo NjqGDR/Sp2EXEzzxsegbw0nJLCfhQKkauuxgMd9FGrndfiymSXpB6SgaH9vdenzpru bYpLWBukNn81mIqBXdkGZn9jNfV9Cn5m9/3jWj9qYgZ1UOhQ4xdxfDGk+sHbDbJyN6 iDsKtyXXJZRT1vNrFU3I5Tw6WhyZxJigtrZGulBGYNHezHu2ZDIdjXTJ+4gkYQKpNI yfyrqVTAV7Jxg== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 08/24] rust: auxiliary: implement Sync for Device Date: Tue, 28 Apr 2026 00:11:06 +0200 Message-ID: <20260427221155.2144848-9-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Device uses the same underlying struct auxiliary_device as Device; Bound is a zero-sized type-state marker that does not affect thread safety. This is needed for drivers to store &'a auxiliary::Device in their HRT private data while remaining Send. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/auxiliary.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index 5cd10b254baf..8a278ddb5b95 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -366,6 +366,10 @@ unsafe impl Send for Device {} // (i.e. `Device) are thread safe. unsafe impl Sync for Device {} =20 +// SAFETY: Same as `Device` -- the underlying `struct auxiliary_de= vice` is the same; +// `Bound` is a zero-sized type-state marker that does not affect thread s= afety. +unsafe impl Sync for Device {} + /// Wrapper that stores a [`TypeId`] alongside the registration data for r= untime type checking. #[repr(C)] #[pin_data] --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 CD4243ACA6F; Mon, 27 Apr 2026 22:13:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327986; cv=none; b=PBeJ9AqXXR+ks5kkCkpnW6OH+T4MvVL/nU/IqsSfJKddfR4NOWViUBhmzy0B2YfZvP3/tJqBcsDJklHkNjm1hbFpEvTYC99hXMzFwZsVrerOm21Rtkcz5EvH0NN2Gpj3EMKaJYYtbiSYa09/BZ02bMLysAyDqBSeY680p35EqUI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327986; c=relaxed/simple; bh=sZLqtheFtbTBM6ybbYnAo9fMYpWxi0B2jumJwk9Z3cs=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=LTlOhoqUstGxndNnAJcbA74P9N2RvIOmWh3ASYsoIiWqkA/6OMreSP10RMPXTjbWDovb3pNl0Fz1O45ss7q6OWQ7LkHeEdPuCee+E9UEeQYBhZxdS/80pr+aenBWVvJzGtuRIYTFFCA6cTHQUMl7DNC1L3pwpJ0ZOPVWjRGT8BA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=QCTlgvTV; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="QCTlgvTV" Received: by smtp.kernel.org (Postfix) with ESMTPSA id E483FC19425; Mon, 27 Apr 2026 22:12:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327984; bh=sZLqtheFtbTBM6ybbYnAo9fMYpWxi0B2jumJwk9Z3cs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QCTlgvTV6FJHT3hQpDJhYJVDws5vZuwpsyLdFXn1Ezq4MjTkMvHsEuWGZDtCWUDEI h72knNyqRACPfgsu/da1PxSroKTP+FCEBidk8Yq2pPzpJqq19+tUcXcobnsGP7lc7u 0ZODNbkXz+g8diiaZxCqlQvMQYll5PdX1BHHiwtVhOhLoxhf7ccVhMZkJ3JjAsAsXy 2FUno9OVC2YQqNd4mhctCLD0je5jEB7tsswhGAdl4MZoOv4vkmsVUO5L7C1313kPzD mafFDzdfw9r/wydKN5/wUiMNGF5HrKvbhUFsP1TakxLKpDvUboStrrT7uN0BoIC7r+ XnFb36DELy1vA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 09/24] rust: usb: implement Sync for Device Date: Tue, 28 Apr 2026 00:11:07 +0200 Message-ID: <20260427221155.2144848-10-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Device uses the same underlying struct usb_device as Device; Bound is a zero-sized type-state marker that does not affect thread safety. This is needed for drivers to store &'a usb::Device in their HRT private data while remaining Send. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/usb.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/kernel/usb.rs b/rust/kernel/usb.rs index 9b9d3ae41087..442e456fd2d3 100644 --- a/rust/kernel/usb.rs +++ b/rust/kernel/usb.rs @@ -467,6 +467,10 @@ unsafe impl Send for Device {} // allow any mutation through a shared reference. unsafe impl Sync for Device {} =20 +// SAFETY: Same as `Device` -- the underlying `struct usb_device` = is the same; +// `Bound` is a zero-sized type-state marker that does not affect thread s= afety. +unsafe impl Sync for Device {} + /// Declares a kernel module that exposes a single USB driver. /// /// # Examples --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 8FEEB3A9D92; Mon, 27 Apr 2026 22:13:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327991; cv=none; b=tgpjHCQW8JG0zIVBC3V1bLcZPGL0r5pfNazvqoOLty1IN44cAkHgAh9nXVMiKCASIB6K+tLd7oKg/c9cXw/4eNJoTe6YW2CbYCOw6VsgasFQHOIaPpeItPDByi0Sl3L392eH/e9ReLDuA7bmgSnwRPv4DDKRVh+Yzr6OF10JS2Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327991; c=relaxed/simple; bh=auHxUUsQH6YXhhsoPM2i0zRThcG3GjhIs2ycbNDnDEE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=fcpzTJjc0vllHVnD3vfbHO05mJZY+R4wAOa238REEcYA5ZhHJiLaTqFcG7lD+xaGWOC7j+ac6ExAZ2huSpMW6MsK7Wzby+3dBFinT+7yguaqDkjkv0AaqG/C/bKmHvDvCE2KRYvuBR9Ikx9wHZNOnodUvl2YFLzdpONfWxqIuYk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Tpxe20+p; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Tpxe20+p" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 620F6C2BCB5; Mon, 27 Apr 2026 22:13:05 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327991; bh=auHxUUsQH6YXhhsoPM2i0zRThcG3GjhIs2ycbNDnDEE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Tpxe20+pywFn3Tok0SQvaoZWh+7phDXK2kLMxayygbnAbIGpo4k5r99nyg4ok/TJ/ SBrRKriatJkTg+0/rNlGho/QEAN0URtpVftUITiFgz2PeDEoV+PZVNxNFH1xG+PPeM 2l938aLVge8Y5kYhVxsdNslPc7pfluaqm1oARKGxJQluXP7FWJVv8KXlEF6MARCVK0 R03bksZMeUO14VT8jFy1rBybwQBp4DWLGX+z2POqWWcfj3J6li5f2ak6K9SenC1p3N 7DnNU0RItI+Fs6iuvcc1ndUxyHPK59ARQzj2B906M/KbqDQOr7YNNJf236NiaDcESF hqZrZA6jz778g== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 10/24] rust: device: implement Sync for Device Date: Tue, 28 Apr 2026 00:11:08 +0200 Message-ID: <20260427221155.2144848-11-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" The underlying `struct device` is the same for all device contexts; `Bound` is a zero-sized type-state marker that does not affect thread safety. Implement `Sync` for `Device` with the same safety argument as the existing `Device` implementation. This is needed for types that hold `&'a Device`, such as `io::mem::IoMem`, to be `Send`. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/device.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index 09cbe8a438a9..b330b87178d3 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -503,6 +503,10 @@ unsafe impl Send for Device {} // synchronization in `struct device`. unsafe impl Sync for Device {} =20 +// SAFETY: Same as `Device` -- the underlying `struct device` is t= he same; `Bound` is a +// zero-sized type-state marker that does not affect thread safety. +unsafe impl Sync for Device {} + /// Marker trait for the context or scope of a bus specific device. /// /// [`DeviceContext`] is a marker trait for types representing the context= of a bus specific --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 D673E3A9DA5; Mon, 27 Apr 2026 22:13:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327997; cv=none; b=W1hfcM8BwQN+I4FQLrKjbyxxMU1TqFI77Qi+UBbsGyPi+gkJivRtgHgC4g0nKjhJ3jc9jBvFqKNGv8RFcQgp8p+szuisQ/lhbF7tYwXTzVvEGOmZEuXMeMUsTiZX8HrGIefv+wSiI0QkQatO3lz3U0o8Q0KyOKl3RTd0kd6J+co= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777327997; c=relaxed/simple; bh=mdjo1NZwY5GoH4ibGKBJ7f7j6FWnfOwIVwRbt0mj7p8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=TGsp8DwGUUkUk2GRoukghpy70J56fcHiOrzd4NneFTF4ZwcPum26j91Zw7npr+FUIspl3e1rt1Gc0yDzfM3jUt//c41ph0TbPCVFR8q+O2Yh7wiCDX5XDHHSNgQ2UX4XNxGZTx6g8b8i26MOPqj6qBywqeHbiMO9QqMkdWLD5jE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=REQ5Dyjo; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="REQ5Dyjo" Received: by smtp.kernel.org (Postfix) with ESMTPSA id AD84AC19425; Mon, 27 Apr 2026 22:13:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777327997; bh=mdjo1NZwY5GoH4ibGKBJ7f7j6FWnfOwIVwRbt0mj7p8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=REQ5Dyjo/Xb+75phlrQLoIxvYM5LR5mtCtMVWPLh5geplHJXnuSyrsql6WyyEP4/V aKFZmr1SXxWKEVFBHAdtlwHRkAOUq+Qv/khAGsMUe0O27l+vzFObYPs8zhpRZyQ5jy E+siO0xo9hYb0KfxOKUMC5+bkWOvUlNUS7Es7Nq+Xi/SDEmFGaqMnq1QjzGyWfU7R+ DlrGZeV7heLceZgTuCZvAydC5X6MsmudvKfpacI9F9WJKXtXQ1zbZvhaqPinLG0sgB Y48nbOux0IhkvOcXcCWT9f0dyXlN00y27+YqDB79n3DBFKgdg1Xo/tboW7gwSl2kLr +UeJ6mGlwoBGw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 11/24] rust: pci: make Driver trait lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:09 +0200 Message-ID: <20260427221155.2144848-12-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Make pci::Driver take a lifetime parameter 'a that ties device resources to the binding scope. Internally, Adapter becomes Adapter with a HRTB bound for<'a> F::Of<'a>: Driver<'a>; module_pci_driver! wraps the driver type in ForLt!() so drivers don't have to. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/nova-core/driver.rs | 9 ++- drivers/gpu/nova-core/nova_core.rs | 4 +- rust/kernel/pci.rs | 79 +++++++++++++++++++-------- samples/rust/rust_dma.rs | 9 ++- samples/rust/rust_driver_auxiliary.rs | 13 +++-- samples/rust/rust_driver_pci.rs | 11 ++-- 6 files changed, 86 insertions(+), 39 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index 8fe484d357f6..815489dd92d0 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -50,7 +50,7 @@ pub(crate) struct NovaCore { kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - ::IdInfo, + >::IdInfo, [ // Modern NVIDIA GPUs will show up as either VGA or 3D controllers. ( @@ -72,11 +72,14 @@ pub(crate) struct NovaCore { ] ); =20 -impl pci::Driver for NovaCore { +impl<'a> pci::Driver<'a> for NovaCore { type IdInfo =3D (); const ID_TABLE: pci::IdTable =3D &PCI_TABLE; =20 - fn probe(pdev: &pci::Device, _info: &Self::IdInfo) -> impl PinIn= it { + fn probe( + pdev: &'a pci::Device, + _info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { pin_init::pin_init_scope(move || { dev_dbg!(pdev, "Probe Nova Core GPU driver.\n"); =20 diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nov= a_core.rs index 04a1fa6b25f8..49c093a0cb42 100644 --- a/drivers/gpu/nova-core/nova_core.rs +++ b/drivers/gpu/nova-core/nova_core.rs @@ -7,6 +7,7 @@ driver::Registration, pci, prelude::*, + types::ForLt, InPlaceModule, // }; =20 @@ -46,8 +47,9 @@ fn drop(&mut self) { struct NovaCoreModule { // Fields are dropped in declaration order, so `_driver` is dropped fi= rst, // then `_debugfs_guard` clears `DEBUGFS_ROOT`. + #[allow(clippy::type_complexity)] #[pin] - _driver: Registration>, + _driver: Registration>, _debugfs_guard: DebugfsRootGuard, } =20 diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 6f82f2e6c74f..73d9fcff99c4 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -58,22 +58,34 @@ }; =20 /// An adapter for the registration of PCI drivers. -pub struct Adapter(T); +/// +/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver= 's device +/// private data type, i.e. `F::Of<'a>` is the driver struct parameterized= by `'a`. The macro +/// `module_pci_driver!` generates this automatically via `ForLt!()`. +pub struct Adapter(PhantomData); =20 // SAFETY: // - `bindings::pci_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `F::Of<'static>` is the stored type of the driver's device private da= ta. // - `struct pci_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. -unsafe impl driver::DriverLayout for Adapter { +unsafe impl driver::DriverLayout for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ type DriverType =3D bindings::pci_driver; - type DriverData =3D ForLt!(T); + type DriverData =3D F; const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 // SAFETY: A call to `unregister` for a given instance of `DriverType` is = guaranteed to be valid if // a preceding call to `register` has been successful. -unsafe impl driver::RegistrationOps for Adapter { +unsafe impl driver::RegistrationOps for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ unsafe fn register( pdrv: &Opaque, name: &'static CStr, @@ -84,7 +96,7 @@ unsafe fn register( (*pdrv.get()).name =3D name.as_char_ptr(); (*pdrv.get()).probe =3D Some(Self::probe_callback); (*pdrv.get()).remove =3D Some(Self::remove_callback); - (*pdrv.get()).id_table =3D T::ID_TABLE.as_ptr(); + (*pdrv.get()).id_table =3D as Driver<'static>>= ::ID_TABLE.as_ptr(); } =20 // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`. @@ -99,7 +111,11 @@ unsafe fn unregister(pdrv: &Opaque) { } } =20 -impl Adapter { +impl Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ extern "C" fn probe_callback( pdev: *mut bindings::pci_dev, id: *const bindings::pci_device_id, @@ -113,12 +129,12 @@ extern "C" fn probe_callback( // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `stru= ct pci_device_id` and // does not add additional invariants, so it's safe to transmute. let id =3D unsafe { &*id.cast::() }; - let info =3D T::ID_TABLE.info(id.index()); =20 from_result(|| { - let data =3D T::probe(pdev, info); + let info =3D as Driver<'_>>::ID_TABLE.info(id.index= ()); + let data =3D as Driver<'_>>::probe(pdev, info); =20 - pdev.as_ref().set_drvdata::(data)?; + pdev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -131,16 +147,18 @@ extern "C" fn remove_callback(pdev: *mut bindings::pc= i_dev) { let pdev =3D unsafe { &*pdev.cast::>(= ) }; =20 // SAFETY: `remove_callback` is only ever called after a successfu= l call to - // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called - // and stored a `Pin>`. - let data =3D unsafe { pdev.as_ref().drvdata_borrow::() = }; + // `probe_callback`, hence it's guaranteed that drvdata has been s= et. + let data =3D unsafe { pdev.as_ref().drvdata_borrow::() }; =20 - T::unbind(pdev, data); + as Driver<'_>>::unbind(pdev, data); } } =20 /// Declares a kernel module that exposes a single PCI driver. /// +/// The `type` field accepts a driver type, optionally with a lifetime pla= ceholder `'_` for +/// lifetime-parameterized drivers. The macro wraps it in [`ForLt!`] autom= atically. +/// /// # Examples /// ///```ignore @@ -152,10 +170,16 @@ extern "C" fn remove_callback(pdev: *mut bindings::pc= i_dev) { /// license: "GPL v2", /// } ///``` +/// +/// [`ForLt!`]: macro@ForLt +/// [`ForLt`]: trait@ForLt #[macro_export] macro_rules! module_pci_driver { -($($f:tt)*) =3D> { - $crate::module_driver!(, $crate::pci::Adapter, { $($f)* }); +(type: $type:ty, $($rest:tt)*) =3D> { + $crate::module_driver!(, $crate::pci::Adapter, { + type: $crate::types::ForLt!($type), + $($rest)* + }); }; } =20 @@ -261,6 +285,9 @@ macro_rules! pci_device_table { =20 /// The PCI driver trait. /// +/// Drivers implement this trait with a lifetime parameter `'a` that ties = device resources to the +/// device scope. +/// /// # Examples /// ///``` @@ -271,7 +298,7 @@ macro_rules! pci_device_table { /// kernel::pci_device_table!( /// PCI_TABLE, /// MODULE_PCI_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// ( /// pci::DeviceId::from_id(pci::Vendor::REDHAT, bindings::PCI_= ANY_ID as u32), @@ -280,21 +307,22 @@ macro_rules! pci_device_table { /// ] /// ); /// -/// impl pci::Driver for MyDriver { +/// impl<'a> pci::Driver<'a> for MyDriver { /// type IdInfo =3D (); /// const ID_TABLE: pci::IdTable =3D &PCI_TABLE; /// /// fn probe( -/// _pdev: &pci::Device, -/// _id_info: &Self::IdInfo, -/// ) -> impl PinInit { +/// _pdev: &'a pci::Device, +/// _id_info: &'a Self::IdInfo, +/// ) -> impl PinInit + 'a { /// Err(ENODEV) /// } /// } ///``` +/// /// Drivers must implement this trait in order to get a PCI driver registe= red. Please refer to the /// `Adapter` documentation for an example. -pub trait Driver: Send { +pub trait Driver<'a>: Send { /// The type holding information about each device id supported by the= driver. // TODO: Use `associated_type_defaults` once stabilized: // @@ -310,7 +338,10 @@ pub trait Driver: Send { /// /// Called when a new pci device is added or discovered. Implementers = should /// attempt to initialize the device here. - fn probe(dev: &Device, id_info: &Self::IdInfo) -> impl P= inInit; + fn probe( + dev: &'a Device, + id_info: &'a Self::IdInfo, + ) -> impl PinInit + 'a; =20 /// PCI driver unbind. /// @@ -322,7 +353,7 @@ pub trait Driver: Send { /// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be perfo= rmed in `Self::drop`. - fn unbind(dev: &Device, this: Pin<&Self>) { + fn unbind(dev: &'a Device, this: Pin<&'a Self>) { let _ =3D (dev, this); } } diff --git a/samples/rust/rust_dma.rs b/samples/rust/rust_dma.rs index 129bb4b39c04..8b6f8c923049 100644 --- a/samples/rust/rust_dma.rs +++ b/samples/rust/rust_dma.rs @@ -52,15 +52,18 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {} kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - ::IdInfo, + >::IdInfo, [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())] ); =20 -impl pci::Driver for DmaSampleDriver { +impl<'a> pci::Driver<'a> for DmaSampleDriver { type IdInfo =3D (); const ID_TABLE: pci::IdTable =3D &PCI_TABLE; =20 - fn probe(pdev: &pci::Device, _info: &Self::IdInfo) -> impl PinIn= it { + fn probe( + pdev: &'a pci::Device, + _info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { pin_init::pin_init_scope(move || { dev_info!(pdev, "Probe DMA test driver.\n"); =20 diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index 319ef734c02b..f57b2b03adb6 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -14,6 +14,7 @@ driver, pci, prelude::*, + types::ForLt, InPlaceModule, // }; =20 @@ -59,16 +60,19 @@ struct ParentDriver { kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - ::IdInfo, + >::IdInfo, [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())] ); =20 -impl pci::Driver for ParentDriver { +impl<'a> pci::Driver<'a> for ParentDriver { type IdInfo =3D (); =20 const ID_TABLE: pci::IdTable =3D &PCI_TABLE; =20 - fn probe(pdev: &pci::Device, _info: &Self::IdInfo) -> impl PinIn= it { + fn probe( + pdev: &'a pci::Device, + _info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { Ok(Self { _reg0: auxiliary::Registration::new( pdev.as_ref(), @@ -116,7 +120,8 @@ fn connect(adev: &auxiliary::Device) -> Result { #[pin_data] struct SampleModule { #[pin] - _pci_driver: driver::Registration>, + #[allow(clippy::type_complexity)] + _pci_driver: driver::Registration>, #[pin] _aux_driver: driver::Registration>, } diff --git a/samples/rust/rust_driver_pci.rs b/samples/rust/rust_driver_pci= .rs index 47d3e84fab63..2747beecb5fd 100644 --- a/samples/rust/rust_driver_pci.rs +++ b/samples/rust/rust_driver_pci.rs @@ -77,7 +77,7 @@ struct SampleDriver { kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - ::IdInfo, + >::IdInfo, [( pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), TestIndex::NO_EVENTFD @@ -138,12 +138,15 @@ fn config_space(pdev: &pci::Device) { } } =20 -impl pci::Driver for SampleDriver { +impl<'a> pci::Driver<'a> for SampleDriver { type IdInfo =3D TestIndex; =20 const ID_TABLE: pci::IdTable =3D &PCI_TABLE; =20 - fn probe(pdev: &pci::Device, info: &Self::IdInfo) -> impl PinIni= t { + fn probe( + pdev: &'a pci::Device, + info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { pin_init::pin_init_scope(move || { let vendor =3D pdev.vendor_id(); dev_dbg!( @@ -174,7 +177,7 @@ fn probe(pdev: &pci::Device, info: &Self::IdInfo)= -> impl PinInit, this: Pin<&Self>) { + fn unbind(pdev: &'a pci::Device, this: Pin<&'a Self>) { if let Ok(bar) =3D this.bar.access(pdev.as_ref()) { // Reset pci-testdev by writing a new test index. bar.write_reg(regs::TEST::zeroed().with_index(this.index)); --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 44D1D3ACEE1; Mon, 27 Apr 2026 22:13:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328004; cv=none; b=SwMo+4GNQfP6fRhRQmOecFMxUnczuiy19eo1wkyTRbu3IRIcDKmOaa79Mpsuj7JbyhBQyfHkSw3jaI7kj5BFKkkTYq4rIStVxpZoQsnL6YQBqSmwr+TE/pYssapuurij+ZKiZS9KGlb0Eag2bbsEK7YPbAcJ2LvpKWbZtrOaAX0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328004; c=relaxed/simple; bh=SbAAS0eADHxx3DW9A0GSuIcQ7Z1EZxALrR6avIv2uEo=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=UAW8zJHHtk7Eupa0rrR7Zj9qUHaTXNXS1Ue7vOml+xfkp0f5wg+RkYOgcwMusRpc7rXmKlW/ZXlNOhZbYHxXhMFCd094tRIKS4T9gCQjDMMzNP7JzuLpRD0Esi3U3dmRtX5Heaf3BVPVuUvrb45nS29tF0j0JJToBGYY0sS4l9U= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=XtvLu9O5; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="XtvLu9O5" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0439AC2BCB6; Mon, 27 Apr 2026 22:13:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328003; bh=SbAAS0eADHxx3DW9A0GSuIcQ7Z1EZxALrR6avIv2uEo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=XtvLu9O5wx83IVLI0xcCL+XYbcSgk9I7l5pDwudA4ugR8IetY1J7ZP8JkK3RelTx5 9wTDlKBWIrCIzCj6fGlPo0d134QQy+1a8G64zqw0nXox7H4WuwbbuHHEtbZb3rUp76 S8QO3p/shJ/YSjj/FQadgMGjxkAQnTb5JQnAyRLY/eE0qWrZ2/a6Eby8IUzWQgfUN4 tTyMV5R0+Eb8qIRq3NaiIvBBqMnn98jHE8LInbEGqkNa4YKnVchAzZRlHv63azmKQN TMfNpFFYWlfzuY6MVl6jB9vf17xFKY92pFKUuQECSdJP6djwmw/oZ83bYpDKdmB3r5 weUJforu5dQ7w== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 12/24] rust: platform: make Driver trait lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:10 +0200 Message-ID: <20260427221155.2144848-13-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Make platform::Driver take a lifetime parameter 'a that ties device resources to the binding scope. Internally, Adapter becomes Adapter with a bound for<'a> F::Of<'a>: Driver<'a>; module_platform_driver! wraps the driver type in ForLt!() so drivers don't have to. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/cpufreq/rcpufreq_dt.rs | 10 +-- drivers/gpu/drm/tyr/driver.rs | 10 +-- drivers/pwm/pwm_th1520.rs | 10 +-- rust/kernel/cpufreq.rs | 8 +-- rust/kernel/driver.rs | 9 ++- rust/kernel/io/mem.rs | 16 ++--- rust/kernel/platform.rs | 92 ++++++++++++++++++---------- samples/rust/rust_debugfs.rs | 10 +-- samples/rust/rust_driver_platform.rs | 12 ++-- samples/rust/rust_i2c_client.rs | 12 ++-- samples/rust/rust_soc.rs | 12 ++-- 11 files changed, 116 insertions(+), 85 deletions(-) diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs index f17bf64c22e2..06c05f946829 100644 --- a/drivers/cpufreq/rcpufreq_dt.rs +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -195,18 +195,18 @@ fn register_em(policy: &mut cpufreq::Policy) { kernel::of_device_table!( OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [(of::DeviceId::new(c"operating-points-v2"), ())] ); =20 -impl platform::Driver for CPUFreqDTDriver { +impl<'a> platform::Driver<'a> for CPUFreqDTDriver { type IdInfo =3D (); const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); =20 fn probe( - pdev: &platform::Device, - _id_info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + _id_info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { cpufreq::Registration::::new_foreign_owned(pdev.a= s_ref())?; Ok(Self {}) } diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs index 279710b36a10..7cc47ec76863 100644 --- a/drivers/gpu/drm/tyr/driver.rs +++ b/drivers/gpu/drm/tyr/driver.rs @@ -82,21 +82,21 @@ fn issue_soft_reset(dev: &Device, iomem: &Devres= ) -> Result { kernel::of_device_table!( OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [ (of::DeviceId::new(c"rockchip,rk3588-mali"), ()), (of::DeviceId::new(c"arm,mali-valhall-csf"), ()) ] ); =20 -impl platform::Driver for TyrPlatformDriverData { +impl<'a> platform::Driver<'a> for TyrPlatformDriverData { type IdInfo =3D (); const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); =20 fn probe( - pdev: &platform::Device, - _info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + _info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { let core_clk =3D Clk::get(pdev.as_ref(), Some(c"core"))?; let stacks_clk =3D OptionalClk::get(pdev.as_ref(), Some(c"stacks")= )?; let coregroup_clk =3D OptionalClk::get(pdev.as_ref(), Some(c"coreg= roup"))?; diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs index ddd44a5ce497..7139f3f4373d 100644 --- a/drivers/pwm/pwm_th1520.rs +++ b/drivers/pwm/pwm_th1520.rs @@ -310,18 +310,18 @@ fn drop(self: Pin<&mut Self>) { kernel::of_device_table!( OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [(of::DeviceId::new(c"thead,th1520-pwm"), ())] ); =20 -impl platform::Driver for Th1520PwmPlatformDriver { +impl<'a> platform::Driver<'a> for Th1520PwmPlatformDriver { type IdInfo =3D (); const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); =20 fn probe( - pdev: &platform::Device, - _id_info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + _id_info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { let dev =3D pdev.as_ref(); let request =3D pdev.io_request_by_index(0).ok_or(ENODEV)?; =20 diff --git a/rust/kernel/cpufreq.rs b/rust/kernel/cpufreq.rs index d8d26870bea2..ac59cdfd633c 100644 --- a/rust/kernel/cpufreq.rs +++ b/rust/kernel/cpufreq.rs @@ -886,14 +886,14 @@ fn register_em(_policy: &mut Policy) { /// } /// } /// -/// impl platform::Driver for SampleDriver { +/// impl<'a> platform::Driver<'a> for SampleDriver { /// type IdInfo =3D (); /// const OF_ID_TABLE: Option> =3D None; /// /// fn probe( -/// pdev: &platform::Device, -/// _id_info: Option<&Self::IdInfo>, -/// ) -> impl PinInit { +/// pdev: &'a platform::Device, +/// _id_info: Option<&'a Self::IdInfo>, +/// ) -> impl PinInit + 'a { /// cpufreq::Registration::::new_foreign_owned(pdev.= as_ref())?; /// Ok(Self {}) /// } diff --git a/rust/kernel/driver.rs b/rust/kernel/driver.rs index 91490040d77e..03974690406b 100644 --- a/rust/kernel/driver.rs +++ b/rust/kernel/driver.rs @@ -13,7 +13,7 @@ //! The main driver interface is defined by a bus specific driver trait. F= or instance: //! //! ```ignore -//! pub trait Driver: Send { +//! pub trait Driver<'a>: Send { //! /// The type holding information about each device ID supported by= the driver. //! type IdInfo: 'static; //! @@ -24,10 +24,13 @@ //! const ACPI_ID_TABLE: Option> =3D None; //! //! /// Driver probe. -//! fn probe(dev: &Device, id_info: &Self::IdInfo) -> im= pl PinInit; +//! fn probe( +//! dev: &'a Device, +//! id_info: &'a Self::IdInfo, +//! ) -> impl PinInit + 'a; //! //! /// Driver unbind (optional). -//! fn unbind(dev: &Device, this: Pin<&Self>) { +//! fn unbind(dev: &'a Device, this: Pin<&'a Self>) { //! let _ =3D (dev, this); //! } //! } diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index 7dc78d547f7a..a483e59054e8 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -60,13 +60,13 @@ pub(crate) unsafe fn new(device: &'a Device, res= ource: &'a Resource) -> S /// }; /// struct SampleDriver; /// - /// impl platform::Driver for SampleDriver { + /// impl<'a> platform::Driver<'a> for SampleDriver { /// # type IdInfo =3D (); /// /// fn probe( - /// pdev: &platform::Device, - /// info: Option<&Self::IdInfo>, - /// ) -> impl PinInit { + /// pdev: &'a platform::Device, + /// info: Option<&'a Self::IdInfo>, + /// ) -> impl PinInit + 'a { /// let offset =3D 0; // Some offset. /// /// // If the size is known at compile time, use [`Self::iomap_s= ized`]. @@ -124,13 +124,13 @@ pub fn iomap_exclusive_sized( /// }; /// struct SampleDriver; /// - /// impl platform::Driver for SampleDriver { + /// impl<'a> platform::Driver<'a> for SampleDriver { /// # type IdInfo =3D (); /// /// fn probe( - /// pdev: &platform::Device, - /// info: Option<&Self::IdInfo>, - /// ) -> impl PinInit { + /// pdev: &'a platform::Device, + /// info: Option<&'a Self::IdInfo>, + /// ) -> impl PinInit + 'a { /// let offset =3D 0; // Some offset. /// /// // Unlike [`Self::iomap_sized`], here the size of the memory= region diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index ae648304eb5b..ec41886b0ba3 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -44,33 +44,45 @@ }; =20 /// An adapter for the registration of platform drivers. -pub struct Adapter(T); +/// +/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver= 's device +/// private data type, i.e. `F::Of<'a>` is the driver struct parameterized= by `'a`. The macro +/// `module_platform_driver!` generates this automatically via `ForLt!()`. +pub struct Adapter(PhantomData); =20 // SAFETY: // - `bindings::platform_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `F::Of<'static>` is the stored type of the driver's device private da= ta. // - `struct platform_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. -unsafe impl driver::DriverLayout for Adapter { +unsafe impl driver::DriverLayout for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ type DriverType =3D bindings::platform_driver; - type DriverData =3D ForLt!(T); + type DriverData =3D F; const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 // SAFETY: A call to `unregister` for a given instance of `DriverType` is = guaranteed to be valid if // a preceding call to `register` has been successful. -unsafe impl driver::RegistrationOps for Adapter { +unsafe impl driver::RegistrationOps for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ unsafe fn register( pdrv: &Opaque, name: &'static CStr, module: &'static ThisModule, ) -> Result { - let of_table =3D match T::OF_ID_TABLE { + let of_table =3D match as Driver<'static>>::OF_ID_= TABLE { Some(table) =3D> table.as_ptr(), None =3D> core::ptr::null(), }; =20 - let acpi_table =3D match T::ACPI_ID_TABLE { + let acpi_table =3D match as Driver<'static>>::ACPI= _ID_TABLE { Some(table) =3D> table.as_ptr(), None =3D> core::ptr::null(), }; @@ -94,19 +106,23 @@ unsafe fn unregister(pdrv: &Opaque) { } } =20 -impl Adapter { +impl Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> = kernel::ffi::c_int { // SAFETY: The platform bus only ever calls the probe callback wit= h a valid pointer to a // `struct platform_device`. // // INVARIANT: `pdev` is valid for the duration of `probe_callback(= )`. let pdev =3D unsafe { &*pdev.cast::>(= ) }; - let info =3D >::id_info(pdev.as_ref()); =20 from_result(|| { - let data =3D T::probe(pdev, info); + let info =3D >::id_info(pdev.as_re= f()); + let data =3D as Driver<'_>>::probe(pdev, info); =20 - pdev.as_ref().set_drvdata::(data)?; + pdev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -119,28 +135,34 @@ extern "C" fn remove_callback(pdev: *mut bindings::pl= atform_device) { let pdev =3D unsafe { &*pdev.cast::>(= ) }; =20 // SAFETY: `remove_callback` is only ever called after a successfu= l call to - // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called - // and stored a `Pin>`. - let data =3D unsafe { pdev.as_ref().drvdata_borrow::() = }; + // `probe_callback`, hence it's guaranteed that drvdata has been s= et. + let data =3D unsafe { pdev.as_ref().drvdata_borrow::() }; =20 - T::unbind(pdev, data); + as Driver<'_>>::unbind(pdev, data); } } =20 -impl<'a, T: Driver + 'static> driver::Adapter<'a> for Adapter { - type IdInfo =3D T::IdInfo; +impl<'a, F> driver::Adapter<'a> for Adapter +where + F: ForLt + 'static, + for<'b> F::Of<'b>: Driver<'b>, +{ + type IdInfo =3D as Driver<'a>>::IdInfo; =20 fn of_id_table() -> Option> { - T::OF_ID_TABLE + as Driver<'a>>::OF_ID_TABLE } =20 fn acpi_id_table() -> Option> { - T::ACPI_ID_TABLE + as Driver<'a>>::ACPI_ID_TABLE } } =20 /// Declares a kernel module that exposes a single platform driver. /// +/// The `type` field accepts a driver type, optionally with a lifetime pla= ceholder `'_` for +/// lifetime-parameterized drivers. The macro wraps it in [`ForLt!`] autom= atically. +/// /// # Examples /// /// ```ignore @@ -152,10 +174,16 @@ fn acpi_id_table() -> Option> { /// license: "GPL v2", /// } /// ``` +/// +/// [`ForLt!`]: macro@ForLt +/// [`ForLt`]: trait@ForLt #[macro_export] macro_rules! module_platform_driver { - ($($f:tt)*) =3D> { - $crate::module_driver!(, $crate::platform::Adapter, { $($f)*= }); + (type: $type:ty, $($rest:tt)*) =3D> { + $crate::module_driver!(, $crate::platform::Adapter, { + type: $crate::types::ForLt!($type), + $($rest)* + }); }; } =20 @@ -178,7 +206,7 @@ macro_rules! module_platform_driver { /// kernel::of_device_table!( /// OF_TABLE, /// MODULE_OF_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// (of::DeviceId::new(c"test,device"), ()) /// ] @@ -187,26 +215,26 @@ macro_rules! module_platform_driver { /// kernel::acpi_device_table!( /// ACPI_TABLE, /// MODULE_ACPI_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// (acpi::DeviceId::new(c"LNUXBEEF"), ()) /// ] /// ); /// -/// impl platform::Driver for MyDriver { +/// impl<'a> platform::Driver<'a> for MyDriver { /// type IdInfo =3D (); /// const OF_ID_TABLE: Option> =3D Some(&OF_= TABLE); /// const ACPI_ID_TABLE: Option> =3D Some(= &ACPI_TABLE); /// /// fn probe( -/// _pdev: &platform::Device, -/// _id_info: Option<&Self::IdInfo>, -/// ) -> impl PinInit { +/// _pdev: &'a platform::Device, +/// _id_info: Option<&'a Self::IdInfo>, +/// ) -> impl PinInit + 'a { /// Err(ENODEV) /// } /// } ///``` -pub trait Driver: Send { +pub trait Driver<'a>: Send { /// The type holding driver private data about each device id supporte= d by the driver. // TODO: Use associated_type_defaults once stabilized: // @@ -226,9 +254,9 @@ pub trait Driver: Send { /// Called when a new platform device is added or discovered. /// Implementers should attempt to initialize the device here. fn probe( - dev: &Device, - id_info: Option<&Self::IdInfo>, - ) -> impl PinInit; + dev: &'a Device, + id_info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a; =20 /// Platform driver unbind. /// @@ -240,7 +268,7 @@ fn probe( /// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be perfo= rmed in `Self::drop`. - fn unbind(dev: &Device, this: Pin<&Self>) { + fn unbind(dev: &'a Device, this: Pin<&'a Self>) { let _ =3D (dev, this); } } diff --git a/samples/rust/rust_debugfs.rs b/samples/rust/rust_debugfs.rs index 0963efe19f93..0d88a9aaa957 100644 --- a/samples/rust/rust_debugfs.rs +++ b/samples/rust/rust_debugfs.rs @@ -111,19 +111,19 @@ fn from_str(s: &str) -> Result { kernel::acpi_device_table!( ACPI_TABLE, MODULE_ACPI_TABLE, - ::IdInfo, + >::IdInfo, [(acpi::DeviceId::new(c"LNUXBEEF"), ())] ); =20 -impl platform::Driver for RustDebugFs { +impl<'a> platform::Driver<'a> for RustDebugFs { type IdInfo =3D (); const OF_ID_TABLE: Option> =3D None; const ACPI_ID_TABLE: Option> =3D Some(&ACP= I_TABLE); =20 fn probe( - pdev: &platform::Device, - _info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + _info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { RustDebugFs::new(pdev).pin_chain(|this| { this.counter.store(91, Relaxed); { diff --git a/samples/rust/rust_driver_platform.rs b/samples/rust/rust_drive= r_platform.rs index f2229d176fb9..cf9177bf3202 100644 --- a/samples/rust/rust_driver_platform.rs +++ b/samples/rust/rust_driver_platform.rs @@ -88,26 +88,26 @@ struct SampleDriver { kernel::of_device_table!( OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [(of::DeviceId::new(c"test,rust-device"), Info(42))] ); =20 kernel::acpi_device_table!( ACPI_TABLE, MODULE_ACPI_TABLE, - ::IdInfo, + >::IdInfo, [(acpi::DeviceId::new(c"LNUXBEEF"), Info(0))] ); =20 -impl platform::Driver for SampleDriver { +impl<'a> platform::Driver<'a> for SampleDriver { type IdInfo =3D Info; const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); const ACPI_ID_TABLE: Option> =3D Some(&ACP= I_TABLE); =20 fn probe( - pdev: &platform::Device, - info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { let dev =3D pdev.as_ref(); =20 dev_dbg!(dev, "Probe Rust Platform driver sample.\n"); diff --git a/samples/rust/rust_i2c_client.rs b/samples/rust/rust_i2c_client= .rs index 8d2c12e535b0..342755df8b95 100644 --- a/samples/rust/rust_i2c_client.rs +++ b/samples/rust/rust_i2c_client.rs @@ -88,14 +88,14 @@ struct SampleDriver { kernel::of_device_table!( OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [(of::DeviceId::new(c"test,rust-device"), ())] ); =20 kernel::acpi_device_table!( ACPI_TABLE, MODULE_ACPI_TABLE, - ::IdInfo, + >::IdInfo, [(acpi::DeviceId::new(c"LNUXBEEF"), ())] ); =20 @@ -104,15 +104,15 @@ struct SampleDriver { const BOARD_INFO: i2c::I2cBoardInfo =3D i2c::I2cBoardInfo::new(c"rust_driver_i2c", SAMPLE_I2C_CLIENT_ADDR); =20 -impl platform::Driver for SampleDriver { +impl<'a> platform::Driver<'a> for SampleDriver { type IdInfo =3D (); const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); const ACPI_ID_TABLE: Option> =3D Some(&ACP= I_TABLE); =20 fn probe( - pdev: &platform::Device, - _info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + _info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { dev_info!( pdev.as_ref(), "Probe Rust I2C Client registration sample.\n" diff --git a/samples/rust/rust_soc.rs b/samples/rust/rust_soc.rs index 8079c1c48416..16f1e4bcfa36 100644 --- a/samples/rust/rust_soc.rs +++ b/samples/rust/rust_soc.rs @@ -24,26 +24,26 @@ struct SampleSocDriver { kernel::of_device_table!( OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [(of::DeviceId::new(c"test,rust-device"), ())] ); =20 kernel::acpi_device_table!( ACPI_TABLE, MODULE_ACPI_TABLE, - ::IdInfo, + >::IdInfo, [(acpi::DeviceId::new(c"LNUXBEEF"), ())] ); =20 -impl platform::Driver for SampleSocDriver { +impl<'a> platform::Driver<'a> for SampleSocDriver { type IdInfo =3D (); const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); const ACPI_ID_TABLE: Option> =3D Some(&ACP= I_TABLE); =20 fn probe( - pdev: &platform::Device, - _info: Option<&Self::IdInfo>, - ) -> impl PinInit { + pdev: &'a platform::Device, + _info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { dev_dbg!(pdev, "Probe Rust SoC driver sample.\n"); =20 let pdev =3D pdev.into(); --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 7A0413ACEFE; Mon, 27 Apr 2026 22:13:30 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328010; cv=none; b=kDyl/CdAkSMwRAcQRtoiBdGCPNCtNyL8Sqx3ZpwDiuJ3cSm6cyPTPPP4ahHngwIxddfF02GfzNXNyyWZsCNO+fRFtymukxK/gQu3chcr1tgXqIo94TqbcZm0jjDp4zAeTFBySjA3pXmMTs8a0YVd8TCLf1zCpNIr96RO20vrp6U= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328010; c=relaxed/simple; bh=Ax3xwk04aGwKxPdkslM0oEwfMzNKZapM3aM+lkIWrMQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=SZUVtYHfG9BwKxM9kqYUE7+2mQVpPGwf6oZO1vZjJHkMU2pA5+kq42q+UidFLXlzSZ6/RFSH9Uddm55axq/mV2dJ0CyhX9yPAKkbFZuyYkW+4RS1LeKVIO7Dg/Kq6ERqJBFIQlfO53KzPstHRlWpXmlA7reS3Uq1WKFB1KGmXsI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=YnO230/X; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="YnO230/X" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4E832C2BCB5; Mon, 27 Apr 2026 22:13:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328010; bh=Ax3xwk04aGwKxPdkslM0oEwfMzNKZapM3aM+lkIWrMQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=YnO230/XG6ZJElTZX0PkzIyd40DOrsF6s2I8DP2WYVvPn3+hNTYrJmCsXUIP2OhNa z8ESPWFYRBc8Nn698cRa+oeCjeSk3YoVusYQMt9rvQ9RL9yCJENMq0OFuJ1NO030tA XjW7BnEIqXwA9DLqtkuaUSr70K3fHUqVeK4tEa0Y3ROLqspJQfwlKf8ywsCHbC/PwB 2pKsVeJx891r/Zo5TmcCNnQ76+8oi0YNx+BOkKYyWGb1+BV3Ej8BcOFNAygrq4DVz1 PXGW8J3oB+D2oGPQwK4miDKgfdKqUvSHOw2X+vrCuKo6XLSIxh5gTLh5TMpMw4cxjS Hn8S5l6Bq7qnQ== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 13/24] rust: auxiliary: make Driver trait lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:11 +0200 Message-ID: <20260427221155.2144848-14-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Make auxiliary::Driver take a lifetime parameter 'a that ties device resources to the binding scope. Internally, Adapter becomes Adapter with a bound for<'a> F::Of<'a>: Driver<'a>; module_auxiliary_driver! wraps the driver type in ForLt!() so drivers don't have to. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/drm/nova/driver.rs | 9 ++-- rust/kernel/auxiliary.rs | 59 ++++++++++++++++++--------- samples/rust/rust_driver_auxiliary.rs | 12 ++++-- 3 files changed, 54 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/nova/driver.rs b/drivers/gpu/drm/nova/driver.rs index b1af0a099551..183d0e679a0b 100644 --- a/drivers/gpu/drm/nova/driver.rs +++ b/drivers/gpu/drm/nova/driver.rs @@ -42,18 +42,21 @@ pub(crate) struct NovaData { kernel::auxiliary_device_table!( AUX_TABLE, MODULE_AUX_TABLE, - ::IdInfo, + >::IdInfo, [( auxiliary::DeviceId::new(NOVA_CORE_MODULE_NAME, AUXILIARY_NAME), () )] ); =20 -impl auxiliary::Driver for NovaDriver { +impl<'a> auxiliary::Driver<'a> for NovaDriver { type IdInfo =3D (); const ID_TABLE: auxiliary::IdTable =3D &AUX_TABLE; =20 - fn probe(adev: &auxiliary::Device, _info: &Self::IdInfo) -> impl= PinInit { + fn probe( + adev: &'a auxiliary::Device, + _info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { let data =3D try_pin_init!(NovaData { adev: adev.into() }); =20 let drm =3D drm::Device::::new(adev.as_ref(), data)?; diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index 8a278ddb5b95..f593a21a16be 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -38,22 +38,34 @@ }; =20 /// An adapter for the registration of auxiliary drivers. -pub struct Adapter(T); +/// +/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver= 's device +/// private data type, i.e. `F::Of<'a>` is the driver struct parameterized= by `'a`. The macro +/// `module_auxiliary_driver!` generates this automatically via `ForLt!()`. +pub struct Adapter(PhantomData); =20 // SAFETY: // - `bindings::auxiliary_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `F::Of<'static>` is the stored type of the driver's device private da= ta. // - `struct auxiliary_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. -unsafe impl driver::DriverLayout for Adapter { +unsafe impl driver::DriverLayout for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ type DriverType =3D bindings::auxiliary_driver; - type DriverData =3D ForLt!(T); + type DriverData =3D F; const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 // SAFETY: A call to `unregister` for a given instance of `DriverType` is = guaranteed to be valid if // a preceding call to `register` has been successful. -unsafe impl driver::RegistrationOps for Adapter { +unsafe impl driver::RegistrationOps for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ unsafe fn register( adrv: &Opaque, name: &'static CStr, @@ -64,7 +76,7 @@ unsafe fn register( (*adrv.get()).name =3D name.as_char_ptr(); (*adrv.get()).probe =3D Some(Self::probe_callback); (*adrv.get()).remove =3D Some(Self::remove_callback); - (*adrv.get()).id_table =3D T::ID_TABLE.as_ptr(); + (*adrv.get()).id_table =3D as Driver<'static>>= ::ID_TABLE.as_ptr(); } =20 // SAFETY: `adrv` is guaranteed to be a valid `DriverType`. @@ -79,7 +91,11 @@ unsafe fn unregister(adrv: &Opaque) { } } =20 -impl Adapter { +impl Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ extern "C" fn probe_callback( adev: *mut bindings::auxiliary_device, id: *const bindings::auxiliary_device_id, @@ -93,12 +109,12 @@ extern "C" fn probe_callback( // SAFETY: `DeviceId` is a `#[repr(transparent)`] wrapper of `stru= ct auxiliary_device_id` // and does not add additional invariants, so it's safe to transmu= te. let id =3D unsafe { &*id.cast::() }; - let info =3D T::ID_TABLE.info(id.index()); =20 from_result(|| { - let data =3D T::probe(adev, info); + let info =3D as Driver<'_>>::ID_TABLE.info(id.index= ()); + let data =3D as Driver<'_>>::probe(adev, info); =20 - adev.as_ref().set_drvdata::(data)?; + adev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -111,19 +127,21 @@ extern "C" fn remove_callback(adev: *mut bindings::au= xiliary_device) { let adev =3D unsafe { &*adev.cast::>(= ) }; =20 // SAFETY: `remove_callback` is only ever called after a successfu= l call to - // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called - // and stored a `Pin>`. - let data =3D unsafe { adev.as_ref().drvdata_borrow::() = }; + // `probe_callback`, hence it's guaranteed that drvdata has been s= et. + let data =3D unsafe { adev.as_ref().drvdata_borrow::() }; =20 - T::unbind(adev, data); + as Driver<'_>>::unbind(adev, data); } } =20 /// Declares a kernel module that exposes a single auxiliary driver. #[macro_export] macro_rules! module_auxiliary_driver { - ($($f:tt)*) =3D> { - $crate::module_driver!(, $crate::auxiliary::Adapter, { $($f)= * }); + (type: $type:ty, $($rest:tt)*) =3D> { + $crate::module_driver!(, $crate::auxiliary::Adapter, { + type: $crate::types::ForLt!($type), + $($rest)* + }); }; } =20 @@ -195,7 +213,7 @@ macro_rules! auxiliary_device_table { /// The auxiliary driver trait. /// /// Drivers must implement this trait in order to get an auxiliary driver = registered. -pub trait Driver { +pub trait Driver<'a>: Send { /// The type holding information about each device id supported by the= driver. /// /// TODO: Use associated_type_defaults once stabilized: @@ -209,7 +227,10 @@ pub trait Driver { /// Auxiliary driver probe. /// /// Called when an auxiliary device is matches a corresponding driver. - fn probe(dev: &Device, id_info: &Self::IdInfo) -> impl P= inInit; + fn probe( + dev: &'a Device, + id_info: &'a Self::IdInfo, + ) -> impl PinInit + 'a; =20 /// Auxiliary driver unbind. /// @@ -221,7 +242,7 @@ pub trait Driver { /// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be perfo= rmed in `Self::drop`. - fn unbind(dev: &Device, this: Pin<&Self>) { + fn unbind(dev: &'a Device, this: Pin<&'a Self>) { let _ =3D (dev, this); } } diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index f57b2b03adb6..d35963ac7fa4 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -26,16 +26,19 @@ kernel::auxiliary_device_table!( AUX_TABLE, MODULE_AUX_TABLE, - ::IdInfo, + >::IdInfo, [(auxiliary::DeviceId::new(MODULE_NAME, AUXILIARY_NAME), ())] ); =20 -impl auxiliary::Driver for AuxiliaryDriver { +impl<'a> auxiliary::Driver<'a> for AuxiliaryDriver { type IdInfo =3D (); =20 const ID_TABLE: auxiliary::IdTable =3D &AUX_TABLE; =20 - fn probe(adev: &auxiliary::Device, _info: &Self::IdInfo) -> impl= PinInit { + fn probe( + adev: &'a auxiliary::Device, + _info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { dev_info!( adev, "Probing auxiliary driver for auxiliary device with id=3D{}\n", @@ -123,7 +126,8 @@ struct SampleModule { #[allow(clippy::type_complexity)] _pci_driver: driver::Registration>, #[pin] - _aux_driver: driver::Registration>, + #[allow(clippy::type_complexity)] + _aux_driver: driver::Registration>, } =20 impl InPlaceModule for SampleModule { --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 C6E2C3AD500; Mon, 27 Apr 2026 22:13:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328016; cv=none; b=VCbYSoTOJGEwuqqANoeIw0alBiwH+EY/FM6INS3nzTgeFqBeMGD/Jb7nnbKk1sxTdja5M1EufcfNK6uW1UK6xLsD3ePP6c1BrcSC8LJDVXoZa4+mZgehGuvdG1WSSqRzzXzTFDd/MQMeWIKvHaswM/opsw1/Gud1IMF8R9+1jgU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328016; c=relaxed/simple; bh=fYpYyJUHzZkxcr62qUd+Bupt8j3iNvgRc3q30X3mPgE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=nEoI+xuUqmTcNdvNCh/DR4Yl6qGRdRvvDMCkaKpEOEN8otawxZM41ei2QLytmy5z9IN+RbZbh0TmSw1/UIqBic3Ne3RliwtIRDaDMWG72ZXj5HsGvS0LS2Ygp2v1o40h8vAum2vEr9UcRfCs3SjVTZc9jF6Ja+WlurBSUVXlOHg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Xz60eMTw; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Xz60eMTw" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9A275C19425; Mon, 27 Apr 2026 22:13:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328016; bh=fYpYyJUHzZkxcr62qUd+Bupt8j3iNvgRc3q30X3mPgE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Xz60eMTwi9F9Xopxl23ANXhzlrKa8KRUQ74F6VU5w+e8bzuAWSzV5TwPtI0vVpdav V3F6rNYgZ87FgkTdG0ZCLT0rzlpai178fhUXc9FeTjkhIpZOa9k/1MtAqVZ+cL8ky0 PIAiAggVBi2102ji8oWmXmKIj56HEl6ijBWEDkjvdKhZzEvuLtnJZKAKUCR6vensXk 7nDSyEnfLyAwj0zG0I8VO5agWq88jJinRVQaDy7h9yi7Pxy6sEmEGdK35gWU5HJqIX r2DZ79/MVnwxsN8vWJL4PzB/iP9I4VClh+K22BlZk9QTAtPjcqhp7vCzk23Vl51EaX EocGnyooTDO0Q== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 14/24] rust: auxiliary: generalize Registration over ForLt Date: Tue, 28 Apr 2026 00:11:12 +0200 Message-ID: <20260427221155.2144848-15-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Generalize Registration to Registration and Device::registration_data() to return Pin<&F::Of<'_>>. The stored 'static lifetime is shortened to the borrow lifetime of &self via ForLt::cast_ref; ForLt's covariance guarantee makes this sound. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/nova-core/driver.rs | 4 +- rust/kernel/auxiliary.rs | 80 ++++++++++++++++++--------- samples/rust/rust_driver_auxiliary.rs | 7 ++- 3 files changed, 61 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index 815489dd92d0..2a17fc99d9b6 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -21,6 +21,7 @@ }, Arc, }, + types::ForLt, }; =20 use crate::gpu::Gpu; @@ -32,7 +33,8 @@ pub(crate) struct NovaCore { #[pin] pub(crate) gpu: Gpu, - _reg: Devres>, + #[allow(clippy::type_complexity)] + _reg: Devres>, } =20 const BAR0_SIZE: usize =3D SZ_16M; diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index f593a21a16be..e27de4be4d87 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -287,12 +287,19 @@ pub fn parent(&self) -> &device::Device { =20 /// Returns a pinned reference to the registration data set by the reg= istering (parent) driver. /// - /// Returns [`EINVAL`] if `T` does not match the type used by the pare= nt driver when calling + /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The r= eturned + /// reference has its lifetime shortened from `'static` to `&self`'s b= orrow lifetime via + /// [`ForLt::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>> + where + F::Of<'static>: 'static, + { // 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() { @@ -305,18 +312,23 @@ pub fn registration_data(&self) -> Result= > { =20 // SAFETY: `ptr` is non-null and was set via `into_foreign()` in `= Registration::new()`; // `RegistrationData` is `#[repr(C)]` with `type_id` at offset 0, = so reading a `TypeId` - // at the start of the allocation is valid regardless of `T`. + // at the start of the allocation is valid regardless of `F`. let type_id =3D unsafe { ptr.cast::().read() }; - if type_id !=3D TypeId::of::() { + if type_id !=3D TypeId::of::>() { return Err(EINVAL); } =20 - // SAFETY: The `TypeId` check above confirms that the stored type = is `T`; `ptr` remains - // valid until `Registration::drop()` calls `from_foreign()`. - let wrapper =3D unsafe { Pin::>>::borrow(= ptr) }; + // 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 =3D unsafe { Pin::>>>::borrow(ptr) }; =20 // SAFETY: `data` is a structurally pinned field of `RegistrationD= ata`. - Ok(unsafe { wrapper.map_unchecked(|w| &w.data) }) + let pinned: Pin<&F::Of<'static>> =3D unsafe { wrapper.map_unchecke= d(|w| &w.data) }; + + // SAFETY: ForLt guarantees covariance, making it sound to shorten= 'static to &self's + // lifetime via cast_ref. + Ok(unsafe { Pin::new_unchecked(F::cast_ref(pinned.get_ref())) }) } } =20 @@ -405,43 +417,54 @@ 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 `T` is the type of the registration data owned by t= he registering (parent) -/// driver. It can be accessed by the auxiliary driver through -/// [`Device::registration_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()`]. /// /// # Invariants /// /// `self.adev` always holds a valid pointer to an initialized and registe= red /// [`struct auxiliary_device`], and `registration_data` points to a valid -/// `Pin>>`. -pub struct Registration { +/// `Pin>>>`. +pub struct Registration +where + F::Of<'static>: 'static, +{ adev: NonNull, - _data: PhantomData, + _data: PhantomData, } =20 -impl Registration { +impl Registration +where + F::Of<'static>: Send + 'static, +{ /// Create and register a new auxiliary device with the given registra= tion data. /// /// The `data` is owned by the registration and can be accessed throug= h the auxiliary device /// via [`Device::registration_data()`]. - pub fn new( - parent: &device::Device, + pub fn new<'a, E>( + parent: &'a device::Device, name: &CStr, id: u32, modname: &CStr, - data: impl PinInit, + data: impl PinInit, E>, ) -> Result> where Error: From, { let data =3D KBox::pin_init::( try_pin_init!(RegistrationData { - type_id: TypeId::of::(), + type_id: TypeId::of::>(), data <- data, }), GFP_KERNEL, )?; =20 + // SAFETY: Lifetimes are erased and do not affect layout, so Regis= trationData> + // and RegistrationData> have identical representat= ion. + let data: Pin>>> =3D + unsafe { core::mem::transmute(data) }; + let boxed =3D KBox::new(Opaque::::zero= ed(), GFP_KERNEL)?; let adev =3D boxed.get(); =20 @@ -470,9 +493,11 @@ pub fn new( let ret =3D unsafe { bindings::__auxiliary_device_add(adev, modnam= e.as_char_ptr()) }; if ret !=3D 0 { // SAFETY: `registration_data` was set above via `into_foreign= ()`. - let _ =3D unsafe { - Pin::>>::from_foreign((*adev).reg= istration_data_rust) - }; + drop(unsafe { + Pin::>>>::from_foreig= n( + (*adev).registration_data_rust, + ) + }); =20 // SAFETY: `adev` is guaranteed to be a valid pointer to a // `struct auxiliary_device`, which has been initialized. @@ -494,7 +519,10 @@ pub fn new( } } =20 -impl Drop for Registration { +impl Drop for Registration +where + F::Of<'static>: 'static, +{ fn drop(&mut self) { // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` i= s a valid registered // `struct auxiliary_device`. @@ -502,7 +530,7 @@ fn drop(&mut self) { =20 // SAFETY: `registration_data` was set in `new()` via `into_foreig= n()`. drop(unsafe { - Pin::>>::from_foreign( + Pin::>>>::from_foreign( (*self.adev.as_ptr()).registration_data_rust, ) }); @@ -516,7 +544,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 {} +unsafe impl Send for Registration where F::Of<'static>: Send = {} =20 // SAFETY: `Registration` does not expose any methods or fields that need = synchronization. -unsafe impl Sync for Registration {} +unsafe impl Sync for Registration where F::Of<'static>: Send = {} diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index d35963ac7fa4..4ad619c5731e 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -55,9 +55,10 @@ struct Data { index: u32, } =20 +#[allow(clippy::type_complexity)] struct ParentDriver { - _reg0: Devres>, - _reg1: Devres>, + _reg0: Devres>, + _reg1: Devres>, } =20 kernel::pci_device_table!( @@ -100,7 +101,7 @@ fn connect(adev: &auxiliary::Device) -> Result { let dev =3D adev.parent(); let pdev: &pci::Device =3D dev.try_into()?; =20 - let data =3D adev.registration_data::()?; + let data =3D adev.registration_data::()?; =20 dev_info!( dev, --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 E58853AC0FB; Mon, 27 Apr 2026 22:13:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328023; cv=none; b=fJ8fw+/C34HBqOmBFpYleI6RD1nNzE6uElZDsKBwKgCxlJS9EM+UEUsZIiTzXmJDpX32MbRiuxpQMN+BfwQRM3zKPQCB6np5iPEIWxUdIQEE1E0AR7tYxrFrOB+UrUGTXCZRa0MxMx0ZBtaQejw4SA0vw/Ji64xA4ILNkV+VB1g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328023; c=relaxed/simple; bh=2wRXyoiGYh3N2MxiZpU0KF0q9rWzHw+tYKK7qMjArxI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=XUtQ/LpuHQDpAulOw0wjA6UL49pDxH8dTTEWrxc+ILv1DWyG+di8EMRy52My61fI9Ns1N8Oo4iCwNUsaBfaqYtf0aS3wTpSGpu/wQm/UOh1zdH88IUm5s7u3UeuE6+8Amh+HWpbk83rCFF+wRtXkfFuAHZa/7uhOsXJTGVO0KJo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=bQGkmtrf; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="bQGkmtrf" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EA442C19425; Mon, 27 Apr 2026 22:13:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328022; bh=2wRXyoiGYh3N2MxiZpU0KF0q9rWzHw+tYKK7qMjArxI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bQGkmtrfaOtuV8b1phg4BUOsZwWTo2RGRcZLJkJvxY84H0cAgrv0s1WFxR7FvnQPj ZyV6+O/clFd90kJOW/a6ltyel9t5FglZoFE7lOoOvdCaPUhymgXpKBERhilzisUgqC q9PSC0MCU0EbI2JsqE/QK8UpsIl6OsePWv8QIPYrjpQH3CnHf/CqbVmSR62Y8L7paX ikOJQb763jtz56W4bgS+DdXbeJSEIgbEf6wkWgGB1AiVQvPgusJYtdMLrk/X6at2sT DhlAAhBweOysTvimZ87GnzvOYsJzx5XiFgU+j03r4Jcmf2ueM6wTgzwbUFClsoJp/C nz1bJk/e+RWJQ== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 15/24] samples: rust: rust_driver_auxiliary: showcase lifetime-bound registration data Date: Tue, 28 Apr 2026 00:11:13 +0200 Message-ID: <20260427221155.2144848-16-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Make the Data struct lifetime-parameterized, storing a reference to the parent pci::Device. This demonstrates that registration data can hold device resources tied to the parent driver's lifetime. In connect(), retrieve the parent PCI device from the registration data rather than casting through adev.parent(). Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- samples/rust/rust_driver_auxiliary.rs | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driv= er_auxiliary.rs index 4ad619c5731e..010ec2201a69 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -51,14 +51,15 @@ fn probe( } } =20 -struct Data { +struct Data<'a> { index: u32, + parent: &'a pci::Device, } =20 #[allow(clippy::type_complexity)] struct ParentDriver { - _reg0: Devres>, - _reg1: Devres>, + _reg0: Devres)>>, + _reg1: Devres)>>, } =20 kernel::pci_device_table!( @@ -83,14 +84,20 @@ fn probe( AUXILIARY_NAME, 0, MODULE_NAME, - Data { index: 0 }, + Data { + index: 0, + parent: pdev, + }, )?, _reg1: auxiliary::Registration::new( pdev.as_ref(), AUXILIARY_NAME, 1, MODULE_NAME, - Data { index: 1 }, + Data { + index: 1, + parent: pdev, + }, )?, }) } @@ -98,13 +105,11 @@ fn probe( =20 impl ParentDriver { fn connect(adev: &auxiliary::Device) -> Result { - let dev =3D adev.parent(); - let pdev: &pci::Device =3D dev.try_into()?; - - let data =3D adev.registration_data::()?; + let data =3D adev.registration_data::)>()?; + let pdev =3D data.parent; =20 dev_info!( - dev, + pdev, "Connect auxiliary {} with parent: VendorID=3D{}, DeviceID=3D{= :#x}\n", adev.id(), pdev.vendor_id(), @@ -112,7 +117,7 @@ fn connect(adev: &auxiliary::Device) -> Result { ); =20 dev_info!( - dev, + pdev, "Connected to auxiliary device with index {}.\n", data.index ); --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 6ACA43AB262; Mon, 27 Apr 2026 22:13:49 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328029; cv=none; b=K7d6IxoE7DrnrwGqc3vVz1T4wCRMxUC33dnm0dVwCwxoZdHqFEpjsdJ0YM96EG2b9b9bcP0/NFA7UpWboycJ5vfJLntUNdiJsqfWOw4ad0jCFJFX+P/iMjtzXH9usXNy5Ll9U6is/2gN5mgLK/Y7KGYRd91Qygzte7qR21FIU9w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328029; c=relaxed/simple; bh=LqoJmyLMcfvlHKDJq6T+tkDE6stHA+a+dnj6GefZ9os=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=JeJvrDbN6o3nxFjS0YwoYqR3LHJKn+NczTQ8ZBnIS9SdK8a7Wuc/sZYhqyKFPN0hpL6RKVwnJ8BPGjUGD0eZPl/gr+6MZmuz1q1MYy4UNTfMNBhYHNYHYTzgHeE4V0qAoJBGQ4Bce9C1wbBa3b/wAkraWhDX/cyEjw+pHx2yRic= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=aFiYEfVB; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="aFiYEfVB" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 410D6C2BCB6; Mon, 27 Apr 2026 22:13:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328029; bh=LqoJmyLMcfvlHKDJq6T+tkDE6stHA+a+dnj6GefZ9os=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=aFiYEfVByRv2PjDa9rjYPjgR9q/fQlaBcDWAP+n9ARzSi35I3fnQBQL4jXkKGDFqb Z+VfYo+FSkRbNwQd6HzuNL2R+VKCaOPP2Vt7a5oRB1f1lN8QHUS7mkwa2kqHPVBPHD l03xRWXLrvCwYveEXJEMCVnnLbogwLsr1wkfNlkwlAmoq9F+HdY8YjBxU3qt84QonQ vdiQnv2fsuVsGsUCmq1lVdBEMwCQFAmiGn60q3rtrxY6WPr2VXXMG+6L4Xh1xwYO4V WJEmvDbKfwovia/wetB+zMtncjlIo7goJfWZX5JKqF73OCnqP5s8BCruWMyK6RvsV7 duihnqd6v+KKw== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 16/24] rust: usb: make Driver trait lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:14 +0200 Message-ID: <20260427221155.2144848-17-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Make usb::Driver take a lifetime parameter 'a that ties device resources to the binding scope. Internally, Adapter becomes Adapter with a bound for<'a> F::Of<'a>: Driver<'a>; module_usb_driver! wraps the driver type in ForLt!() so drivers don't have to. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/usb.rs | 84 ++++++++++++++++++++------------- samples/rust/rust_driver_usb.rs | 14 +++--- 2 files changed, 58 insertions(+), 40 deletions(-) diff --git a/rust/kernel/usb.rs b/rust/kernel/usb.rs index 442e456fd2d3..f519444cf8d0 100644 --- a/rust/kernel/usb.rs +++ b/rust/kernel/usb.rs @@ -35,22 +35,34 @@ }; =20 /// An adapter for the registration of USB drivers. -pub struct Adapter(T); +/// +/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver= 's device +/// private data type, i.e. `F::Of<'a>` is the driver struct parameterized= by `'a`. The macro +/// `module_usb_driver!` generates this automatically via `ForLt!()`. +pub struct Adapter(PhantomData); =20 // SAFETY: // - `bindings::usb_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `F::Of<'static>` is the stored type of the driver's device private da= ta. // - `struct usb_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. -unsafe impl driver::DriverLayout for Adapter { +unsafe impl driver::DriverLayout for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ type DriverType =3D bindings::usb_driver; - type DriverData =3D ForLt!(T); + type DriverData =3D F; const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 // SAFETY: A call to `unregister` for a given instance of `DriverType` is = guaranteed to be valid if // a preceding call to `register` has been successful. -unsafe impl driver::RegistrationOps for Adapter { +unsafe impl driver::RegistrationOps for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ unsafe fn register( udrv: &Opaque, name: &'static CStr, @@ -61,7 +73,7 @@ unsafe fn register( (*udrv.get()).name =3D name.as_char_ptr(); (*udrv.get()).probe =3D Some(Self::probe_callback); (*udrv.get()).disconnect =3D Some(Self::disconnect_callback); - (*udrv.get()).id_table =3D T::ID_TABLE.as_ptr(); + (*udrv.get()).id_table =3D as Driver<'static>>= ::ID_TABLE.as_ptr(); } =20 // SAFETY: `udrv` is guaranteed to be a valid `DriverType`. @@ -76,7 +88,11 @@ unsafe fn unregister(udrv: &Opaque) { } } =20 -impl Adapter { +impl Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ extern "C" fn probe_callback( intf: *mut bindings::usb_interface, id: *const bindings::usb_device_id, @@ -87,16 +103,16 @@ extern "C" fn probe_callback( // INVARIANT: `intf` is valid for the duration of `probe_callback(= )`. let intf =3D unsafe { &*intf.cast::>() }; =20 - from_result(|| { - // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `= struct usb_device_id` and - // does not add additional invariants, so it's safe to transmu= te. - let id =3D unsafe { &*id.cast::() }; + // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `stru= ct usb_device_id` and + // does not add additional invariants, so it's safe to transmute. + let id =3D unsafe { &*id.cast::() }; =20 - let info =3D T::ID_TABLE.info(id.index()); - let data =3D T::probe(intf, id, info); + from_result(|| { + let info =3D as Driver<'_>>::ID_TABLE.info(id.index= ()); + let data =3D as Driver<'_>>::probe(intf, id, info); =20 let dev: &device::Device =3D intf.as_ref= (); - dev.set_drvdata::(data)?; + dev.set_drvdata::(data)?; Ok(0) }) } @@ -111,11 +127,10 @@ extern "C" fn disconnect_callback(intf: *mut bindings= ::usb_interface) { let dev: &device::Device =3D intf.as_ref(); =20 // SAFETY: `disconnect_callback` is only ever called after a succe= ssful call to - // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called - // and stored a `Pin>`. - let data =3D unsafe { dev.drvdata_borrow::() }; + // `probe_callback`, hence it's guaranteed that drvdata has been s= et. + let data =3D unsafe { dev.drvdata_borrow::() }; =20 - T::disconnect(intf, data); + as Driver<'_>>::disconnect(intf, data); } } =20 @@ -281,29 +296,29 @@ macro_rules! usb_device_table { /// kernel::usb_device_table!( /// USB_TABLE, /// MODULE_USB_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// (usb::DeviceId::from_id(0x1234, 0x5678), ()), /// (usb::DeviceId::from_id(0xabcd, 0xef01), ()), /// ] /// ); /// -/// impl usb::Driver for MyDriver { +/// impl<'a> usb::Driver<'a> for MyDriver { /// type IdInfo =3D (); /// const ID_TABLE: usb::IdTable =3D &USB_TABLE; /// /// fn probe( -/// _interface: &usb::Interface, -/// _id: &usb::DeviceId, -/// _info: &Self::IdInfo, -/// ) -> impl PinInit { +/// _interface: &'a usb::Interface, +/// _id: &'a usb::DeviceId, +/// _info: &'a Self::IdInfo, +/// ) -> impl PinInit + 'a { /// Err(ENODEV) /// } /// -/// fn disconnect(_interface: &usb::Interface, _data: Pin<&Self>= ) {} +/// fn disconnect(_interface: &'a usb::Interface, _data: Pin<&'a= Self>) {} /// } ///``` -pub trait Driver { +pub trait Driver<'a> { /// The type holding information about each one of the device ids supp= orted by the driver. type IdInfo: 'static; =20 @@ -315,15 +330,15 @@ pub trait Driver { /// Called when a new USB interface is bound to this driver. /// Implementers should attempt to initialize the interface here. fn probe( - interface: &Interface, - id: &DeviceId, - id_info: &Self::IdInfo, - ) -> impl PinInit; + interface: &'a Interface, + id: &'a DeviceId, + id_info: &'a Self::IdInfo, + ) -> impl PinInit + 'a; =20 /// USB driver disconnect. /// /// Called when the USB interface is about to be unbound from this dri= ver. - fn disconnect(interface: &Interface, data: Pin<&Self>); + fn disconnect(interface: &'a Interface, data: Pin<&'a Se= lf>); } =20 /// A USB interface. @@ -486,7 +501,10 @@ unsafe impl Sync for Device {} /// ``` #[macro_export] macro_rules! module_usb_driver { - ($($f:tt)*) =3D> { - $crate::module_driver!(, $crate::usb::Adapter, { $($f)* }); + (type: $type:ty, $($rest:tt)*) =3D> { + $crate::module_driver!(, $crate::usb::Adapter, { + type: $crate::types::ForLt!($type), + $($rest)* + }); } } diff --git a/samples/rust/rust_driver_usb.rs b/samples/rust/rust_driver_usb= .rs index ab72e99e1274..6f3e5db9f35d 100644 --- a/samples/rust/rust_driver_usb.rs +++ b/samples/rust/rust_driver_usb.rs @@ -20,26 +20,26 @@ struct SampleDriver { kernel::usb_device_table!( USB_TABLE, MODULE_USB_TABLE, - ::IdInfo, + >::IdInfo, [(usb::DeviceId::from_id(0x1234, 0x5678), ()),] ); =20 -impl usb::Driver for SampleDriver { +impl<'a> usb::Driver<'a> for SampleDriver { type IdInfo =3D (); const ID_TABLE: usb::IdTable =3D &USB_TABLE; =20 fn probe( - intf: &usb::Interface, - _id: &usb::DeviceId, - _info: &Self::IdInfo, - ) -> impl PinInit { + intf: &'a usb::Interface, + _id: &'a usb::DeviceId, + _info: &'a Self::IdInfo, + ) -> impl PinInit + 'a { let dev: &device::Device =3D intf.as_ref(); dev_info!(dev, "Rust USB driver sample probed\n"); =20 Ok(Self { _intf: intf.into() }) } =20 - fn disconnect(intf: &usb::Interface, _data: Pin<&Self>) { + fn disconnect(intf: &'a usb::Interface, _data: Pin<&'a Self>) { let dev: &device::Device =3D intf.as_ref(); dev_info!(dev, "Rust USB driver sample disconnected\n"); } --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 871993ACF1F; Mon, 27 Apr 2026 22:13:55 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328035; cv=none; b=V/sYwupkKaQ6PZvf6cosQ+3B2JGESY6erwE060Lypj0Cx6mBtLe/lhWMq3rboU8LIxZn+nsqOkGwHgBybjyfAb1vQL22SAxMzHqeBmPXuidDFYlQOE6igSNuhTXGO/ulZINvEI6KCzkJT5s4RA/vLijbjG1uekAwagKIoWNhmo8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328035; c=relaxed/simple; bh=ru1OCYUc534Gm2mrQq6Ir697MoQdZy8URoT3Gukyl0E=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=bXgB9rx9RyktYFbxqOfz5fjt8sNGXtfj1+agbP4sxcMa6ouaTS6w3KTHK8h3ox4oZD7dnTjvQWKjKtBCC7jQOhTicuhBPQHaCRl1wa0GO9u5C+tlem8MMUkuLfxyXWyQCqEg2sv1S7P35N7UtzkygWj43WlKO/9UMlmL696RUXU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=ttiwFdWh; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="ttiwFdWh" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8C975C19425; Mon, 27 Apr 2026 22:13:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328035; bh=ru1OCYUc534Gm2mrQq6Ir697MoQdZy8URoT3Gukyl0E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ttiwFdWhBUqiITT4H2ptesCXtBZTLIOSXkOjqkaUNBpnmX8TqAYnDHnqcZrKB6jSF 6xSXWLRRNxVcSsdt8ejTnt5ElHsaZj2QoMCQtpGFxR5liHzQwWB6n3IMDkBzuV/Wti VN+CX3lBD76TrQWyEoVstqX5j0Qsiol1zUUYNcQChQACz8OxAhmMR/6bW54GSHCVxf 1nq8mr9aJM0hHV1qmEko9OZZvI15cCtBGIo+4G4lME5WHmlFk3g9G7JFigXbchE1WY LMiJNhgS2trG7+e66OuphvwmYqNSZKdEg7aukBv2DbNcIqN2PuGBtLH0F0NOhVHngW OaIXqKg/qb5fg== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 17/24] rust: i2c: make Driver trait lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:15 +0200 Message-ID: <20260427221155.2144848-18-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Make i2c::Driver take a lifetime parameter 'a that ties device resources to the binding scope. Internally, Adapter becomes Adapter with a bound for<'a> F::Of<'a>: Driver<'a>; module_i2c_driver! wraps the driver type in ForLt!() so drivers don't have to. Signed-off-by: Danilo Krummrich Acked-by: Igor Korotin Acked-by: Uwe Kleine-K=C3=B6nig --- rust/kernel/i2c.rs | 116 +++++++++++++++++++------------- samples/rust/rust_driver_i2c.rs | 18 ++--- 2 files changed, 78 insertions(+), 56 deletions(-) diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index 08d310aa9d6b..4464146d6c4d 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -92,43 +92,57 @@ macro_rules! i2c_device_table { } =20 /// An adapter for the registration of I2C drivers. -pub struct Adapter(T); +/// +/// `F` is a [`ForLt`](trait@ForLt) type that maps lifetimes to the driver= 's device +/// private data type, i.e. `F::Of<'a>` is the driver struct parameterized= by `'a`. The macro +/// `module_i2c_driver!` generates this automatically via `ForLt!()`. +pub struct Adapter(PhantomData); =20 // SAFETY: // - `bindings::i2c_driver` is a C type declared as `repr(C)`. -// - `T` is the type of the driver's device private data. +// - `F::Of<'static>` is the stored type of the driver's device private da= ta. // - `struct i2c_driver` embeds a `struct device_driver`. // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `st= ruct device_driver`. -unsafe impl driver::DriverLayout for Adapter { +unsafe impl driver::DriverLayout for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ type DriverType =3D bindings::i2c_driver; - type DriverData =3D ForLt!(T); + type DriverData =3D F; const DEVICE_DRIVER_OFFSET: usize =3D core::mem::offset_of!(Self::Driv= erType, driver); } =20 // SAFETY: A call to `unregister` for a given instance of `DriverType` is = guaranteed to be valid if // a preceding call to `register` has been successful. -unsafe impl driver::RegistrationOps for Adapter { +unsafe impl driver::RegistrationOps for Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ unsafe fn register( idrv: &Opaque, name: &'static CStr, module: &'static ThisModule, ) -> Result { build_assert!( - T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I= 2C_ID_TABLE.is_some(), + as Driver<'static>>::ACPI_ID_TABLE.is_some() + || as Driver<'static>>::OF_ID_TABLE.is_som= e() + || as Driver<'static>>::I2C_ID_TABLE.is_so= me(), "At least one of ACPI/OF/Legacy tables must be present when re= gistering an i2c driver" ); =20 - let i2c_table =3D match T::I2C_ID_TABLE { + let i2c_table =3D match as Driver<'static>>::I2C_I= D_TABLE { Some(table) =3D> table.as_ptr(), None =3D> core::ptr::null(), }; =20 - let of_table =3D match T::OF_ID_TABLE { + let of_table =3D match as Driver<'static>>::OF_ID_= TABLE { Some(table) =3D> table.as_ptr(), None =3D> core::ptr::null(), }; =20 - let acpi_table =3D match T::ACPI_ID_TABLE { + let acpi_table =3D match as Driver<'static>>::ACPI= _ID_TABLE { Some(table) =3D> table.as_ptr(), None =3D> core::ptr::null(), }; @@ -154,7 +168,11 @@ unsafe fn unregister(idrv: &Opaque) { } } =20 -impl Adapter { +impl Adapter +where + F: ForLt + 'static, + for<'a> F::Of<'a>: Driver<'a>, +{ extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kerne= l::ffi::c_int { // SAFETY: The I2C bus only ever calls the probe callback with a v= alid pointer to a // `struct i2c_client`. @@ -162,13 +180,12 @@ extern "C" fn probe_callback(idev: *mut bindings::i2c= _client) -> kernel::ffi::c_ // INVARIANT: `idev` is valid for the duration of `probe_callback(= )`. let idev =3D unsafe { &*idev.cast::>() }; =20 - let info =3D Self::i2c_id_info(idev) - .or_else(|| >::id_info(idev.as_ref= ())); - from_result(|| { - let data =3D T::probe(idev, info); + let info =3D Self::i2c_id_info(idev) + .or_else(|| >::id_info(idev.as= _ref())); + let data =3D as Driver<'_>>::probe(idev, info); =20 - idev.as_ref().set_drvdata::(data)?; + idev.as_ref().set_drvdata::(data)?; Ok(0) }) } @@ -178,11 +195,10 @@ extern "C" fn remove_callback(idev: *mut bindings::i2= c_client) { let idev =3D unsafe { &*idev.cast::>() }; =20 // SAFETY: `remove_callback` is only ever called after a successfu= l call to - // `probe_callback`, hence it's guaranteed that `I2cClient::set_dr= vdata()` has been called - // and stored a `Pin>`. - let data =3D unsafe { idev.as_ref().drvdata_borrow::() = }; + // `probe_callback`, hence it's guaranteed that drvdata has been s= et. + let data =3D unsafe { idev.as_ref().drvdata_borrow::() }; =20 - T::unbind(idev, data); + as Driver<'_>>::unbind(idev, data); } =20 extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) { @@ -190,23 +206,22 @@ extern "C" fn shutdown_callback(idev: *mut bindings::= i2c_client) { let idev =3D unsafe { &*idev.cast::>() }; =20 // SAFETY: `shutdown_callback` is only ever called after a success= ful call to - // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called - // and stored a `Pin>`. - let data =3D unsafe { idev.as_ref().drvdata_borrow::() = }; + // `probe_callback`, hence it's guaranteed that drvdata has been s= et. + let data =3D unsafe { idev.as_ref().drvdata_borrow::() }; =20 - T::shutdown(idev, data); + as Driver<'_>>::shutdown(idev, data); } =20 /// The [`i2c::IdTable`] of the corresponding driver. - fn i2c_id_table() -> Option>= ::IdInfo>> { - T::I2C_ID_TABLE + fn i2c_id_table<'a>() -> Option as Driver<'a>>::IdI= nfo>> { + as Driver<'a>>::I2C_ID_TABLE } =20 /// Returns the driver's private data from the matching entry in the [= `i2c::IdTable`], if any. /// /// If this returns `None`, it means there is no match with an entry i= n the [`i2c::IdTable`]. - fn i2c_id_info(dev: &I2cClient) -> Option<&'static >::IdInfo> { - let table =3D Self::i2c_id_table()?; + fn i2c_id_info<'a>(dev: &I2cClient) -> Option<&'a as Driver= <'a>>::IdInfo> { + let table =3D Self::i2c_id_table::<'a>()?; =20 // SAFETY: // - `table` has static lifetime, hence it's valid for reads @@ -225,15 +240,19 @@ fn i2c_id_info(dev: &I2cClient) -> Option<&'static driver::Adapter<'a> for Adapter { - type IdInfo =3D T::IdInfo; +impl<'a, F> driver::Adapter<'a> for Adapter +where + F: ForLt + 'static, + F::Of<'a>: Driver<'a>, +{ + type IdInfo =3D as Driver<'a>>::IdInfo; =20 fn of_id_table() -> Option> { - T::OF_ID_TABLE + as Driver<'a>>::OF_ID_TABLE } =20 fn acpi_id_table() -> Option> { - T::ACPI_ID_TABLE + as Driver<'a>>::ACPI_ID_TABLE } } =20 @@ -252,8 +271,11 @@ fn acpi_id_table() -> Option> { /// ``` #[macro_export] macro_rules! module_i2c_driver { - ($($f:tt)*) =3D> { - $crate::module_driver!(, $crate::i2c::Adapter, { $($f)* }); + (type: $type:ty, $($rest:tt)*) =3D> { + $crate::module_driver!(, $crate::i2c::Adapter, { + type: $crate::types::ForLt!($type), + $($rest)* + }); }; } =20 @@ -271,7 +293,7 @@ macro_rules! module_i2c_driver { /// kernel::acpi_device_table!( /// ACPI_TABLE, /// MODULE_ACPI_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// (acpi::DeviceId::new(c"LNUXBEEF"), ()) /// ] @@ -280,7 +302,7 @@ macro_rules! module_i2c_driver { /// kernel::i2c_device_table!( /// I2C_TABLE, /// MODULE_I2C_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// (i2c::DeviceId::new(c"rust_driver_i2c"), ()) /// ] @@ -289,30 +311,30 @@ macro_rules! module_i2c_driver { /// kernel::of_device_table!( /// OF_TABLE, /// MODULE_OF_TABLE, -/// ::IdInfo, +/// >::IdInfo, /// [ /// (of::DeviceId::new(c"test,device"), ()) /// ] /// ); /// -/// impl i2c::Driver for MyDriver { +/// impl<'a> i2c::Driver<'a> for MyDriver { /// type IdInfo =3D (); /// const I2C_ID_TABLE: Option> =3D Some(&I= 2C_TABLE); /// const OF_ID_TABLE: Option> =3D Some(&OF_= TABLE); /// const ACPI_ID_TABLE: Option> =3D Some(= &ACPI_TABLE); /// /// fn probe( -/// _idev: &i2c::I2cClient, -/// _id_info: Option<&Self::IdInfo>, -/// ) -> impl PinInit { +/// _idev: &'a i2c::I2cClient, +/// _id_info: Option<&'a Self::IdInfo>, +/// ) -> impl PinInit + 'a { /// Err(ENODEV) /// } /// -/// fn shutdown(_idev: &i2c::I2cClient, this: Pin<&Self>) { +/// fn shutdown(_idev: &'a i2c::I2cClient, _this: Pin<&'a Self>)= { /// } /// } ///``` -pub trait Driver: Send { +pub trait Driver<'a>: Send { /// The type holding information about each device id supported by the= driver. // TODO: Use `associated_type_defaults` once stabilized: // @@ -335,9 +357,9 @@ pub trait Driver: Send { /// Called when a new i2c client is added or discovered. /// Implementers should attempt to initialize the client here. fn probe( - dev: &I2cClient, - id_info: Option<&Self::IdInfo>, - ) -> impl PinInit; + dev: &'a I2cClient, + id_info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a; =20 /// I2C driver shutdown. /// @@ -350,7 +372,7 @@ fn probe( /// This callback is distinct from final resource cleanup, as the driv= er instance remains valid /// after it returns. Any deallocation or teardown of driver-owned res= ources should instead be /// handled in `Self::drop`. - fn shutdown(dev: &I2cClient, this: Pin<&Self>) { + fn shutdown(dev: &'a I2cClient, this: Pin<&'a Self>) { let _ =3D (dev, this); } =20 @@ -364,7 +386,7 @@ fn shutdown(dev: &I2cClient, this: Pin<&S= elf>) { /// operations to gracefully tear down the device. /// /// Otherwise, release operations for driver resources should be perfo= rmed in `Self::drop`. - fn unbind(dev: &I2cClient, this: Pin<&Self>) { + fn unbind(dev: &'a I2cClient, this: Pin<&'a Self>) { let _ =3D (dev, this); } } diff --git a/samples/rust/rust_driver_i2c.rs b/samples/rust/rust_driver_i2c= .rs index 6be79f9e9fb5..f86c1cf7c786 100644 --- a/samples/rust/rust_driver_i2c.rs +++ b/samples/rust/rust_driver_i2c.rs @@ -15,25 +15,25 @@ kernel::acpi_device_table! { ACPI_TABLE, MODULE_ACPI_TABLE, - ::IdInfo, + >::IdInfo, [(acpi::DeviceId::new(c"LNUXBEEF"), 0)] } =20 kernel::i2c_device_table! { I2C_TABLE, MODULE_I2C_TABLE, - ::IdInfo, + >::IdInfo, [(i2c::DeviceId::new(c"rust_driver_i2c"), 0)] } =20 kernel::of_device_table! { OF_TABLE, MODULE_OF_TABLE, - ::IdInfo, + >::IdInfo, [(of::DeviceId::new(c"test,rust_driver_i2c"), 0)] } =20 -impl i2c::Driver for SampleDriver { +impl<'a> i2c::Driver<'a> for SampleDriver { type IdInfo =3D u32; =20 const ACPI_ID_TABLE: Option> =3D Some(&ACP= I_TABLE); @@ -41,9 +41,9 @@ impl i2c::Driver for SampleDriver { const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); =20 fn probe( - idev: &i2c::I2cClient, - info: Option<&Self::IdInfo>, - ) -> impl PinInit { + idev: &'a i2c::I2cClient, + info: Option<&'a Self::IdInfo>, + ) -> impl PinInit + 'a { let dev =3D idev.as_ref(); =20 dev_info!(dev, "Probe Rust I2C driver sample.\n"); @@ -55,11 +55,11 @@ fn probe( Ok(Self) } =20 - fn shutdown(idev: &i2c::I2cClient, _this: Pin<&Self>) { + fn shutdown(idev: &'a i2c::I2cClient, _this: Pin<&'a Self>) { dev_info!(idev.as_ref(), "Shutdown Rust I2C driver sample.\n"); } =20 - fn unbind(idev: &i2c::I2cClient, _this: Pin<&Self>) { + fn unbind(idev: &'a i2c::I2cClient, _this: Pin<&'a Self>) { dev_info!(idev.as_ref(), "Unbind Rust I2C driver sample.\n"); } } --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 0BD143ACA6A; Mon, 27 Apr 2026 22:14:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328042; cv=none; b=S7rMJuuRzhyF6A/ovokfYjEw7HxZ/a7LgsV9+LmV7X2x7ztDfEHNyoK4QT4i0UXJCw1RGf2d5rbdLUsyX/DqFftNyeeIOFWp9k3d2PgdYioPr5NMhhYpRT8WjwpW2BNgLHeki/IboJ68GrhbPZ+RJjpM8AnHu3c4lHSSBRVdji0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328042; c=relaxed/simple; bh=XnijSudcWQAapd0374W3K9ATDhBTvKUTXq++FwUr1Nc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=U1+JxrpBhvI5BazYFjTcJaUd7H0dqJATfvP8vbjMqDJ07geADW4/1fxuNi6mx+yvt3f8o1KdK3C4VYAqmFjiHxw3zdvSBM9Ss1q52X9SHmwjiyXs5eQZzePqfoBjHtqk+07jKwuwuQyGSdPC21RaIsJoELEs3rQVrzD//2Uh80o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=aHfZXwja; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="aHfZXwja" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D7A5EC2BCC9; Mon, 27 Apr 2026 22:13:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328041; bh=XnijSudcWQAapd0374W3K9ATDhBTvKUTXq++FwUr1Nc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=aHfZXwjaO1uc4MUkUeMV1jC4RFzG8CO7MSDtbI1XtbRHQrf06dyzI0i05F6kijAZq Is+160jlrXVeC/mWC4Y6ZmqzWDAJ7e/tSLcZNCg20z7491thkAWCdmh4UlxA7vF9aq MR3yyVEGFP+pZqJgdMWtzEffcZ5TXD0/U2jO+ytVuL4VjVkLhrZxwL2ZKzQaK1+neq n97TzPwandrCKrfWwFh7oRuGcF1UCsZ/eG953w28akmWlSKWtppXh9y6m1f2pPSONB FzcwKUdAUTTy+NK3WfknNrz7+rY1MvYYs8kKqL6Lck1QSy1//BSPuMPCGZ32ET2yQq znbizWisG8B2w== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 18/24] rust: pci: make Bar lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:16 +0200 Message-ID: <20260427221155.2144848-19-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Convert pci::Bar to pci::Bar<'a, SIZE>, storing &'a Device to tie the BAR mapping lifetime to the device. iomap_region_sized() now returns Result> directly instead of impl PinInit>, Error>. Add Bar::into_devres() to consume the bar and register it as a device-managed resource, returning Devres>. The lifetime is erased to 'static because Devres guarantees the bar does not actually outlive the device -- access is revoked on unbind. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/nova-core/driver.rs | 7 +++-- rust/kernel/devres.rs | 2 +- rust/kernel/pci/io.rs | 50 ++++++++++++++++++--------------- samples/rust/rust_driver_pci.rs | 5 ++-- 4 files changed, 35 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index 2a17fc99d9b6..149a20748e86 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -47,7 +47,7 @@ pub(crate) struct NovaCore { // DMA addresses. These systems should be quite rare. const GPU_DMA_BITS: u32 =3D 47; =20 -pub(crate) type Bar0 =3D pci::Bar; +pub(crate) type Bar0 =3D pci::Bar<'static, BAR0_SIZE>; =20 kernel::pci_device_table!( PCI_TABLE, @@ -93,8 +93,9 @@ fn probe( // other threads of execution. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::new::())? }; =20 - let bar =3D Arc::pin_init( - pdev.iomap_region_sized::(0, c"nova-core/bar0"), + let bar =3D Arc::new( + pdev.iomap_region_sized::(0, c"nova-core/bar0")? + .into_devres()?, GFP_KERNEL, )?; =20 diff --git a/rust/kernel/devres.rs b/rust/kernel/devres.rs index 7baabcdb1ad3..6f3c58355d10 100644 --- a/rust/kernel/devres.rs +++ b/rust/kernel/devres.rs @@ -305,7 +305,7 @@ pub fn device(&self) -> &Device { /// pci, // /// }; /// - /// fn from_core(dev: &pci::Device, devres: Devres= >) -> Result { + /// fn from_core(dev: &pci::Device, devres: Devres>) -> Result { /// let bar =3D devres.access(dev.as_ref())?; /// /// let _ =3D bar.read32(0x0); diff --git a/rust/kernel/pci/io.rs b/rust/kernel/pci/io.rs index ae78676c927f..6116c55412bc 100644 --- a/rust/kernel/pci/io.rs +++ b/rust/kernel/pci/io.rs @@ -14,8 +14,7 @@ Mmio, MmioRaw, // }, - prelude::*, - sync::aref::ARef, // + prelude::*, // }; use core::{ marker::PhantomData, @@ -146,14 +145,14 @@ impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSp= ace<'a, S> { /// /// `Bar` always holds an `IoRaw` instance that holds a valid pointer to t= he start of the I/O /// memory mapped PCI BAR and its size. -pub struct Bar { - pdev: ARef, +pub struct Bar<'a, const SIZE: usize =3D 0> { + pdev: &'a Device, io: MmioRaw, num: i32, } =20 -impl Bar { - pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result { +impl<'a, const SIZE: usize> Bar<'a, SIZE> { + pub(super) fn new(pdev: &'a Device, num: u32, name: &CS= tr) -> Result { let len =3D pdev.resource_len(num)?; if len =3D=3D 0 { return Err(ENOMEM); @@ -196,11 +195,7 @@ pub(super) fn new(pdev: &Device, num: u32, name: &CStr= ) -> Result { } }; =20 - Ok(Bar { - pdev: pdev.into(), - io, - num, - }) + Ok(Bar { pdev, io, num }) } =20 /// # Safety @@ -219,11 +214,24 @@ unsafe fn do_release(pdev: &Device, ioptr: usize, num= : i32) { =20 fn release(&self) { // SAFETY: The safety requirements are guaranteed by the type inva= riant of `self.pdev`. - unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) }; + unsafe { Self::do_release(self.pdev, self.io.addr(), self.num) }; + } + + /// 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) } } =20 -impl Bar { +impl Bar<'_> { #[inline] pub(super) fn index_is_valid(index: u32) -> bool { // A `struct pci_dev` owns an array of resources with at most `PCI= _NUM_RESOURCES` entries. @@ -231,13 +239,13 @@ pub(super) fn index_is_valid(index: u32) -> bool { } } =20 -impl Drop for Bar { +impl Drop for Bar<'_, SIZE> { fn drop(&mut self) { self.release(); } } =20 -impl Deref for Bar { +impl Deref for Bar<'_, SIZE> { type Target =3D Mmio; =20 fn deref(&self) -> &Self::Target { @@ -252,17 +260,13 @@ impl Device { pub fn iomap_region_sized<'a, const SIZE: usize>( &'a self, bar: u32, - name: &'a CStr, - ) -> impl PinInit>, Error> + 'a { - Devres::new(self.as_ref(), Bar::::new(self, bar, name)) + name: &CStr, + ) -> Result> { + Bar::new(self, bar, name) } =20 /// Maps an entire PCI BAR after performing a region-request on it. - pub fn iomap_region<'a>( - &'a self, - bar: u32, - name: &'a CStr, - ) -> impl PinInit, Error> + 'a { + pub fn iomap_region<'a>(&'a self, bar: u32, name: &CStr) -> Result> { self.iomap_region_sized::<0>(bar, name) } =20 diff --git a/samples/rust/rust_driver_pci.rs b/samples/rust/rust_driver_pci= .rs index 2747beecb5fd..38d639731229 100644 --- a/samples/rust/rust_driver_pci.rs +++ b/samples/rust/rust_driver_pci.rs @@ -45,7 +45,7 @@ mod regs { pub(super) const END: usize =3D 0x10; } =20 -type Bar0 =3D pci::Bar<{ regs::END }>; +type Bar0 =3D pci::Bar<'static, { regs::END }>; =20 #[derive(Copy, Clone, Debug)] struct TestIndex(u8); @@ -160,7 +160,8 @@ fn probe( pdev.set_master(); =20 Ok(try_pin_init!(Self { - bar <- pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_= driver_pci"), + bar: pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_dr= iver_pci")? + .into_devres()?, index: *info, _: { let bar =3D bar.access(pdev.as_ref())?; --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 5D0413A9D92; Mon, 27 Apr 2026 22:14:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328048; cv=none; b=vCDDvjPViWIEKdq5GVsC2jIyC8xWlBqFyPTmde1BPtI68ZJ05EgBzv9+IFa2sW12t9vbMWhJCE++MYH6d0lvbSBAhWgz02KzGGxjjySNLIbGC3Y1+W6vmFn+hv4Y4oXv31ivTERgRCD4yz7EMUU9ukLdc4XxoU9dxFRbZv2l/RI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328048; c=relaxed/simple; bh=oDLfz4P+cSYONbkhLgBov+ZXz5OHB6gJXhSmiwV6qCg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=dSIdecJFv1OjWKLQhWESYOuZjdn1AkulYK+7ScCAJqXoeHDZfRB9DcFYN9/p9gT4Ik/7ObR3H7EoWoP07tSN/lAC6zZJOTxRdYvptLBHXfDT9KOWuodKy/EJnpoT4FgXKsrnMrMANqxjqINOSa1nDGvyhzFXH3nH4wQIsCT3Z5k= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=eFgnlEm3; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="eFgnlEm3" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3004DC19425; Mon, 27 Apr 2026 22:14:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328048; bh=oDLfz4P+cSYONbkhLgBov+ZXz5OHB6gJXhSmiwV6qCg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eFgnlEm3pXg0eh312U6fN2BXIxcUv+3BK/HvTQvxBpeyfFlsq75qrE28AMPb8sRuX Pr/Pv7dZIaEWsENJXnWAQnkU4n7ynPxpeQR+yLTS53RX4kCRHqFas5WyBPtqJkjx01 ILKaNS0fdNS2mbtISXFmHUpph7D09Y+odVxPqvq1uC6jEIkPNUhtS3qyUFBznuTxsO TzuLthDfWjJn3ivkrCJdamlvkw4E9gP9C/MKAlgAaCOj780p6ArfelGybOkd21gj8/ UHT+FQqvmH3wBafkn1BDQcrc6EmlUdxxYMyFb/KJXr1GSfQAntxNoTJ8US+pNWifBH u/viU9eFZOmoA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 19/24] rust: io: make IoMem and ExclusiveIoMem lifetime-parameterized Date: Tue, 28 Apr 2026 00:11:17 +0200 Message-ID: <20260427221155.2144848-20-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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 lifetime parameter to IoMem<'a, SIZE> and ExclusiveIoMem<'a, SIZE>, storing a &'a Device reference to tie the mapping to the device's lifetime. This mirrors the pci::Bar<'a, SIZE> design and enables drivers to hold I/O memory mappings directly in their HRT private data, tied to the device lifetime. IoRequest::iomap_* methods now return the mapping directly instead of wrapping it in Devres. Callers that need device-managed revocation can call the new into_devres() method. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/drm/tyr/driver.rs | 4 +- drivers/pwm/pwm_th1520.rs | 4 +- rust/kernel/io/mem.rs | 102 +++++++++++++++++----------------- 3 files changed, 55 insertions(+), 55 deletions(-) diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs index 7cc47ec76863..eaa84efdfdf7 100644 --- a/drivers/gpu/drm/tyr/driver.rs +++ b/drivers/gpu/drm/tyr/driver.rs @@ -37,7 +37,7 @@ regs, // }; =20 -pub(crate) type IoMem =3D kernel::io::mem::IoMem; +pub(crate) type IoMem =3D kernel::io::mem::IoMem<'static, SZ_2M>; =20 pub(crate) struct TyrDrmDriver; =20 @@ -109,7 +109,7 @@ fn probe( let sram_regulator =3D Regulator::::get(pdev.a= s_ref(), c"sram")?; =20 let request =3D pdev.io_request_by_index(0).ok_or(ENODEV)?; - let iomem =3D Arc::pin_init(request.iomap_sized::(), GFP_KE= RNEL)?; + let iomem =3D Arc::new(request.iomap_sized::()?.into_devres= ()?, GFP_KERNEL)?; =20 issue_soft_reset(pdev.as_ref(), &iomem)?; gpu::l2_power_on(pdev.as_ref(), &iomem)?; diff --git a/drivers/pwm/pwm_th1520.rs b/drivers/pwm/pwm_th1520.rs index 7139f3f4373d..a45fe359c371 100644 --- a/drivers/pwm/pwm_th1520.rs +++ b/drivers/pwm/pwm_th1520.rs @@ -92,7 +92,7 @@ struct Th1520WfHw { #[pin_data(PinnedDrop)] struct Th1520PwmDriverData { #[pin] - iomem: devres::Devres>, + iomem: devres::Devres>, clk: Clk, } =20 @@ -351,7 +351,7 @@ fn probe( dev, TH1520_MAX_PWM_NUM, try_pin_init!(Th1520PwmDriverData { - iomem <- request.iomap_sized::(), + iomem <- request.iomap_sized::()?.int= o_devres(), clk <- clk, }), )?; diff --git a/rust/kernel/io/mem.rs b/rust/kernel/io/mem.rs index a483e59054e8..12b773bc994d 100644 --- a/rust/kernel/io/mem.rs +++ b/rust/kernel/io/mem.rs @@ -73,22 +73,19 @@ pub(crate) unsafe fn new(device: &'a Device, res= ource: &'a Resource) -> S /// // /// // No runtime checks will apply when reading and writing. /// let request =3D pdev.io_request_by_index(0).ok_or(ENODEV)?; - /// let iomem =3D request.iomap_sized::<42>(); - /// let iomem =3D KBox::pin_init(iomem, GFP_KERNEL)?; - /// - /// let io =3D iomem.access(pdev.as_ref())?; + /// let iomem =3D request.iomap_sized::<42>()?; /// /// // Read and write a 32-bit value at `offset`. - /// let data =3D io.read32(offset); + /// let data =3D iomem.read32(offset); /// - /// io.write32(data, offset); + /// iomem.write32(data, offset); /// /// # Ok(SampleDriver) /// } /// } /// ``` - pub fn iomap_sized(self) -> impl PinInit>, Error> + 'a { - IoMem::new(self) + pub fn iomap_sized(self) -> Result>= { + IoMem::ioremap(self.device, self.resource) } =20 /// Same as [`Self::iomap_sized`] but with exclusive access to the @@ -97,10 +94,8 @@ pub fn iomap_sized(self) -> impl PinI= nit>, /// This uses the [`ioremap()`] C API. /// /// [`ioremap()`]: https://docs.kernel.org/driver-api/device-io.html#g= etting-access-to-the-device - pub fn iomap_exclusive_sized( - self, - ) -> impl PinInit>, Error> + 'a { - ExclusiveIoMem::new(self) + pub fn iomap_exclusive_sized(self) -> Result> { + ExclusiveIoMem::ioremap(self.device, self.resource) } =20 /// Maps an [`IoRequest`] where the size is not known at compile time, @@ -138,27 +133,24 @@ pub fn iomap_exclusive_sized( /// // family of functions should be used, leading to runtime ch= ecks on every /// // access. /// let request =3D pdev.io_request_by_index(0).ok_or(ENODEV)?; - /// let iomem =3D request.iomap(); - /// let iomem =3D KBox::pin_init(iomem, GFP_KERNEL)?; - /// - /// let io =3D iomem.access(pdev.as_ref())?; + /// let iomem =3D request.iomap()?; /// - /// let data =3D io.try_read32(offset)?; + /// let data =3D iomem.try_read32(offset)?; /// - /// io.try_write32(data, offset)?; + /// iomem.try_write32(data, offset)?; /// /// # Ok(SampleDriver) /// } /// } /// ``` - pub fn iomap(self) -> impl PinInit>, Error> + 'a { - Self::iomap_sized::<0>(self) + pub fn iomap(self) -> Result> { + self.iomap_sized::<0>() } =20 /// Same as [`Self::iomap`] but with exclusive access to the underlying /// region. - pub fn iomap_exclusive(self) -> impl PinInit>= , Error> + 'a { - Self::iomap_exclusive_sized::<0>(self) + pub fn iomap_exclusive(self) -> Result> { + self.iomap_exclusive_sized::<0>() } } =20 @@ -167,9 +159,9 @@ pub fn iomap_exclusive(self) -> impl PinInit>, Error> + /// # Invariants /// /// - [`ExclusiveIoMem`] has exclusive access to the underlying [`IoMem`]. -pub struct ExclusiveIoMem { +pub struct ExclusiveIoMem<'a, const SIZE: usize> { /// The underlying `IoMem` instance. - iomem: IoMem, + iomem: IoMem<'a, SIZE>, =20 /// The region abstraction. This represents exclusive access to the /// range represented by the underlying `iomem`. @@ -178,9 +170,9 @@ pub struct ExclusiveIoMem { _region: Region, } =20 -impl ExclusiveIoMem { +impl<'a, const SIZE: usize> ExclusiveIoMem<'a, SIZE> { /// Creates a new `ExclusiveIoMem` instance. - fn ioremap(resource: &Resource) -> Result { + fn ioremap(dev: &'a Device, resource: &Resource) -> Result { let start =3D resource.start(); let size =3D resource.size(); let name =3D resource.name().unwrap_or_default(); @@ -194,26 +186,29 @@ fn ioremap(resource: &Resource) -> Result { ) .ok_or(EBUSY)?; =20 - let iomem =3D IoMem::ioremap(resource)?; + let iomem =3D IoMem::ioremap(dev, resource)?; =20 - let iomem =3D ExclusiveIoMem { + Ok(ExclusiveIoMem { iomem, _region: region, - }; - - Ok(iomem) + }) } =20 - /// Creates a new `ExclusiveIoMem` instance from a previously acquired= [`IoRequest`]. - pub fn new<'a>(io_request: IoRequest<'a>) -> impl PinInit= , Error> + 'a { - let dev =3D io_request.device; - let res =3D io_request.resource; - - Devres::new(dev, Self::ioremap(res)) + /// 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) } } =20 -impl Deref for ExclusiveIoMem { +impl Deref for ExclusiveIoMem<'_, SIZE> { type Target =3D Mmio; =20 fn deref(&self) -> &Self::Target { @@ -230,12 +225,13 @@ fn deref(&self) -> &Self::Target { /// /// [`IoMem`] always holds an [`MmioRaw`] instance that holds a valid poin= ter to the /// start of the I/O memory mapped region. -pub struct IoMem { +pub struct IoMem<'a, const SIZE: usize =3D 0> { + dev: &'a Device, io: MmioRaw, } =20 -impl IoMem { - fn ioremap(resource: &Resource) -> Result { +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 // word width rather than the bus address width. // @@ -267,28 +263,32 @@ fn ioremap(resource: &Resource) -> Result { } =20 let io =3D MmioRaw::new(addr as usize, size)?; - let io =3D IoMem { io }; =20 - Ok(io) + Ok(IoMem { dev, io }) } =20 - /// Creates a new `IoMem` instance from a previously acquired [`IoRequ= est`]. - pub fn new<'a>(io_request: IoRequest<'a>) -> impl PinInit= , Error> + 'a { - let dev =3D io_request.device; - let res =3D io_request.resource; - - Devres::new(dev, Self::ioremap(res)) + /// 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) } } =20 -impl Drop for IoMem { +impl Drop for IoMem<'_, SIZE> { fn drop(&mut self) { // SAFETY: Safe as by the invariant of `Io`. unsafe { bindings::iounmap(self.io.addr() as *mut c_void) } } } =20 -impl Deref for IoMem { +impl Deref for IoMem<'_, SIZE> { type Target =3D Mmio; =20 fn deref(&self) -> &Self::Target { --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 A2DEE3AD50D; Mon, 27 Apr 2026 22:14:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328054; cv=none; b=uq09KvAQoe3c0q9VFakLWUh7qO3DopYDLnsHeH2OxPQHeQGP42X0wruRMehspKJJNp3QAs82kxuGKxX+T8mHKrLUW4uDhZ3fpMqpkWgd2BEVaAMDH3INVJSvTECjr3zU0dLkty3I1q8AZRlxT3fPXqV+YJgez+E3sUP1D/mrrag= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328054; c=relaxed/simple; bh=XiapHwreBkWCEuUnKNcDw0jpNWgyfgymZLeXPuHxqy0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Kn0u5Qqabc4u9CBHPB7Y+yx2nvBksLsBbJlgVT8xrw6ORLbJILMR0hznvFK1PnbdcpUYz6fXvGkeZGNZX3zWvLIu496sNuDvft9ibqdbULJfxIy5dx0dt9a7PRWzjjHXCfNOjNkEFxfQfUWs76HUnADWZtj7lSxk73GmaIYF0hs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=e5a52eLG; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="e5a52eLG" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7A906C2BCB6; Mon, 27 Apr 2026 22:14:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328054; bh=XiapHwreBkWCEuUnKNcDw0jpNWgyfgymZLeXPuHxqy0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=e5a52eLGli+O/acn0H7GNgrRvd2gsA94IDJ2pALf9WnLRw6E3MYqHMbmR2XMKX8Im SzMhCHVZiY9d9ALBdRxcor0owOPvX0R9KtpwuOhy+o1bTQOCmS/vLXwLZzizJO+i4J v7gRIwkHzDIsbar07FDbu4IuSvnxpJTDrPp1spnf/XsKL76ECGGg7GKhB8GbYhjrQC 9KNa16Md94CMpWFalQN3aNSj682XSMCeLjyixpPWnCLaK/8N82y9M6KSzcQ8qBHfpm 6vV+m/9qa0lu7OJRQCD3UfwHNBM10wB676tBWV0CIcoSx/y6wXMmD7BNRR9e5cItKb 5jQiGFny0S3LQ== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH 20/24] samples: rust: rust_driver_pci: use HRT lifetime for Bar Date: Tue, 28 Apr 2026 00:11:18 +0200 Message-ID: <20260427221155.2144848-21-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Convert the sample driver to SampleDriver<'a>, taking advantage of the lifetime-parameterized Driver trait. The driver struct holds &'a pci::Device directly instead of ARef, and pci::Bar<'a> directly instead of Devres. This removes PinnedDrop, pin_init_scope, and runtime revocation checks on BAR access. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- samples/rust/rust_driver_pci.rs | 89 +++++++++++++++------------------ 1 file changed, 39 insertions(+), 50 deletions(-) diff --git a/samples/rust/rust_driver_pci.rs b/samples/rust/rust_driver_pci= .rs index 38d639731229..7f763f43a38d 100644 --- a/samples/rust/rust_driver_pci.rs +++ b/samples/rust/rust_driver_pci.rs @@ -9,7 +9,6 @@ Bound, Core, // }, - devres::Devres, io::{ register, register::Array, @@ -17,8 +16,7 @@ }, num::Bounded, pci, - prelude::*, - sync::aref::ARef, // + prelude::*, // }; =20 mod regs { @@ -45,7 +43,7 @@ mod regs { pub(super) const END: usize =3D 0x10; } =20 -type Bar0 =3D pci::Bar<'static, { regs::END }>; +type Bar0<'a> =3D pci::Bar<'a, { regs::END }>; =20 #[derive(Copy, Clone, Debug)] struct TestIndex(u8); @@ -66,26 +64,24 @@ impl TestIndex { const NO_EVENTFD: Self =3D Self(0); } =20 -#[pin_data(PinnedDrop)] -struct SampleDriver { - pdev: ARef, - #[pin] - bar: Devres, +struct SampleDriver<'a> { + pdev: &'a pci::Device, + bar: Bar0<'a>, index: TestIndex, } =20 kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - >::IdInfo, + as pci::Driver<'_>>::IdInfo, [( pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), TestIndex::NO_EVENTFD )] ); =20 -impl SampleDriver { - fn testdev(index: &TestIndex, bar: &Bar0) -> Result { +impl SampleDriver<'_> { + fn testdev(index: &TestIndex, bar: &Bar0<'_>) -> Result { // Select the test. bar.write_reg(regs::TEST::zeroed().with_index(*index)); =20 @@ -138,7 +134,7 @@ fn config_space(pdev: &pci::Device) { } } =20 -impl<'a> pci::Driver<'a> for SampleDriver { +impl<'a> pci::Driver<'a> for SampleDriver<'a> { type IdInfo =3D TestIndex; =20 const ID_TABLE: pci::IdTable =3D &PCI_TABLE; @@ -147,54 +143,47 @@ fn probe( pdev: &'a pci::Device, info: &'a Self::IdInfo, ) -> impl PinInit + 'a { - pin_init::pin_init_scope(move || { - let vendor =3D pdev.vendor_id(); - dev_dbg!( - pdev, - "Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n", - vendor, - pdev.device_id() - ); - - pdev.enable_device_mem()?; - pdev.set_master(); - - Ok(try_pin_init!(Self { - bar: pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_dr= iver_pci")? - .into_devres()?, - index: *info, - _: { - let bar =3D bar.access(pdev.as_ref())?; - - dev_info!( - pdev, - "pci-testdev data-match count: {}\n", - Self::testdev(info, bar)? - ); - Self::config_space(pdev); - }, - pdev: pdev.into(), - })) + let vendor =3D pdev.vendor_id(); + dev_dbg!( + pdev, + "Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n", + vendor, + pdev.device_id() + ); + + pdev.enable_device_mem()?; + pdev.set_master(); + + let bar =3D pdev.iomap_region_sized::<{ regs::END }>(0, c"rust_dri= ver_pci")?; + + dev_info!( + pdev, + "pci-testdev data-match count: {}\n", + Self::testdev(info, &bar)? + ); + Self::config_space(pdev); + + Ok(Self { + pdev, + bar, + index: *info, }) } =20 - fn unbind(pdev: &'a pci::Device, this: Pin<&'a Self>) { - if let Ok(bar) =3D this.bar.access(pdev.as_ref()) { - // Reset pci-testdev by writing a new test index. - bar.write_reg(regs::TEST::zeroed().with_index(this.index)); - } + fn unbind(_pdev: &'a pci::Device, this: Pin<&'a Self>) { + this.bar + .write_reg(regs::TEST::zeroed().with_index(this.index)); } } =20 -#[pinned_drop] -impl PinnedDrop for SampleDriver { - fn drop(self: Pin<&mut Self>) { +impl Drop for SampleDriver<'_> { + fn drop(&mut self) { dev_dbg!(self.pdev, "Remove Rust PCI driver sample.\n"); } } =20 kernel::module_pci_driver! { - type: SampleDriver, + type: SampleDriver<'_>, name: "rust_driver_pci", authors: ["Danilo Krummrich"], description: "Rust PCI driver", --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 EFDDE3AD528; Mon, 27 Apr 2026 22:14:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328061; cv=none; b=IJKy0C9T/8i4UCmnXqSbI9bRY27h+WvjHLHgNbnfqDgnRION4TtvW4ztTGzMqKybWaNXnrFjyZ6vxvIs4W+L5FniK+Y23CvF7wrlOuiquB2kQUHXUrnDQPZz+KGiE5ZcPSTj8nixD+AR1g9R2kDQa/nXsF+K6J6O/yJezOg21Zw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328061; c=relaxed/simple; bh=+vCZJoneZObXHz+HrSLsZDDMk+BGXI4VJJ4WNODomsU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=MOLQswjRkWU25KCwDxL1ie0+sm2zcfLl8KVLwV0mAuk7a8dR5LFePXjk4u7niBd/pPw/6RNp5edDnEDbyg+aBIXIv9VBd5fA6x1sobmLqvs4LJ9WmGYFJTfYAXGVoOFKagxTdMAUbq+8yXH0sn1+99FlLA5qudp6pM4J8/PDs10= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=W75RH2Y9; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="W75RH2Y9" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C523EC19425; Mon, 27 Apr 2026 22:14:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328060; bh=+vCZJoneZObXHz+HrSLsZDDMk+BGXI4VJJ4WNODomsU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=W75RH2Y9F/+siwPQ1JHURZcogobZ9/VrlGLtxYgFA1gLCsqjOxrPQg1XKsISLV87C fQsa1U+tA3GM6aDw9oqcXpq5cLE+zLKREDMDG8R4OU9DliimeWPWQlG3kyJA7b5S7z ooGGLlzy1lXyPGwJ5q3stU6oLo6vInOjyWIa6D2C/FoLh6wMzJiRKEiVCBmR3IQgKe K7BFdXEiftt7WobIFyHxAHliiFeowDzCMDGRqPmLbKKR/m4a1yUzwHJVmPydCDKmIG yGznAjvJr6qehxk0Y5WUo7FrhKCcPUS5wIOfw08fSkAlbj9rXqvhoP1GC5FQqwFXIw pUy8/Ka1tYgpA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH REF 21/24] gpu: nova-core: use HRT lifetime for Bar Date: Tue, 28 Apr 2026 00:11:19 +0200 Message-ID: <20260427221155.2144848-22-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Take advantage of the lifetime-parameterized pci::Bar<'a> to hold the BAR mapping directly in NovaCore<'a>, and pass a borrowed reference to Gpu<'a>. This eliminates the Arc> indirection, removes runtime revocation checks for BAR access, and simplifies Gpu::unbind(). Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/nova-core/driver.rs | 40 ++++++++++++++---------------- drivers/gpu/nova-core/gpu.rs | 27 ++++++++------------ drivers/gpu/nova-core/nova_core.rs | 2 +- 3 files changed, 30 insertions(+), 39 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index 149a20748e86..ec9cecb30f63 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -14,12 +14,9 @@ }, prelude::*, sizes::SZ_16M, - sync::{ - atomic::{ - Atomic, - Relaxed, // - }, - Arc, + sync::atomic::{ + Atomic, + Relaxed, // }, types::ForLt, }; @@ -30,9 +27,10 @@ static AUXILIARY_ID_COUNTER: Atomic =3D Atomic::new(0); =20 #[pin_data] -pub(crate) struct NovaCore { +pub(crate) struct NovaCore<'a> { #[pin] - pub(crate) gpu: Gpu, + pub(crate) gpu: Gpu<'a>, + bar: pci::Bar<'a, BAR0_SIZE>, #[allow(clippy::type_complexity)] _reg: Devres>, } @@ -47,12 +45,12 @@ pub(crate) struct NovaCore { // DMA addresses. These systems should be quite rare. const GPU_DMA_BITS: u32 =3D 47; =20 -pub(crate) type Bar0 =3D pci::Bar<'static, BAR0_SIZE>; +pub(crate) type Bar0 =3D kernel::io::Mmio; =20 kernel::pci_device_table!( PCI_TABLE, MODULE_PCI_TABLE, - >::IdInfo, + as pci::Driver<'_>>::IdInfo, [ // Modern NVIDIA GPUs will show up as either VGA or 3D controllers. ( @@ -74,7 +72,7 @@ pub(crate) struct NovaCore { ] ); =20 -impl<'a> pci::Driver<'a> for NovaCore { +impl<'a> pci::Driver<'a> for NovaCore<'a> { type IdInfo =3D (); const ID_TABLE: pci::IdTable =3D &PCI_TABLE; =20 @@ -93,14 +91,14 @@ fn probe( // other threads of execution. unsafe { pdev.dma_set_mask_and_coherent(DmaMask::new::())? }; =20 - let bar =3D Arc::new( - pdev.iomap_region_sized::(0, c"nova-core/bar0")? - .into_devres()?, - GFP_KERNEL, - )?; - - Ok(try_pin_init!(Self { - gpu <- Gpu::new(pdev, bar.clone(), bar.access(pdev.as_ref(= ))?), + Ok(try_pin_init!(NovaCore { + bar: pdev.iomap_region_sized::(0, c"nova-core/b= ar0")?, + // TODO: Use `&bar` self-referential pin-init syntax once = available. + // + // SAFETY: `bar` is initialized before this expression is = evaluated + // (`try_pin_init!()` initializes fields in declaration or= der), lives at a pinned + // stable address, and is dropped after `gpu` (struct fiel= d drop order). + gpu <- Gpu::new(pdev, unsafe { &*core::ptr::from_ref(bar) = }), _reg: auxiliary::Registration::new( pdev.as_ref(), c"nova-drm", @@ -114,7 +112,7 @@ fn probe( }) } =20 - fn unbind(pdev: &pci::Device, this: Pin<&Self>) { - this.gpu.unbind(pdev.as_ref()); + fn unbind(_pdev: &'a pci::Device, this: Pin<&'a Self>) { + this.gpu.unbind(); } } diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 0f6fe9a1b955..922197f2aeef 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -2,13 +2,11 @@ =20 use kernel::{ device, - devres::Devres, fmt, io::Io, num::Bounded, pci, - prelude::*, - sync::Arc, // + prelude::*, // }; =20 use crate::{ @@ -224,10 +222,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Res= ult { =20 /// Structure holding the resources required to operate the GPU. #[pin_data] -pub(crate) struct Gpu { +pub(crate) struct Gpu<'a> { spec: Spec, - /// MMIO mapping of PCI BAR 0 - bar: Arc>, + /// MMIO mapping of PCI BAR 0. + bar: &'a Bar0, /// System memory page required for flushing all pending GPU-side memo= ry writes done through /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-= barrier operation). sysmem_flush: SysmemFlush, @@ -240,10 +238,9 @@ pub(crate) struct Gpu { gsp: Gsp, } =20 -impl Gpu { - pub(crate) fn new<'a>( +impl<'a> Gpu<'a> { + pub(crate) fn new( pdev: &'a pci::Device, - devres_bar: Arc>, bar: &'a Bar0, ) -> impl PinInit + 'a { try_pin_init!(Self { @@ -257,6 +254,8 @@ pub(crate) fn new<'a>( .inspect_err(|_| dev_err!(pdev, "GFW boot did not comp= lete\n"))?; }, =20 + bar, + sysmem_flush: SysmemFlush::register(pdev.as_ref(), bar, spec.c= hipset)?, =20 gsp_falcon: Falcon::new( @@ -270,19 +269,13 @@ pub(crate) fn new<'a>( gsp <- Gsp::new(pdev), =20 _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon= )? }, - - bar: devres_bar, }) } =20 /// Called when the corresponding [`Device`](device::Device) is unboun= d. /// /// Note: This method must only be called from `Driver::unbind`. - pub(crate) fn unbind(&self, dev: &device::Device) { - kernel::warn_on!(self - .bar - .access(dev) - .inspect(|bar| self.sysmem_flush.unregister(bar)) - .is_err()); + pub(crate) fn unbind(&self) { + self.sysmem_flush.unregister(self.bar); } } diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nov= a_core.rs index 49c093a0cb42..ed5eb39c8201 100644 --- a/drivers/gpu/nova-core/nova_core.rs +++ b/drivers/gpu/nova-core/nova_core.rs @@ -49,7 +49,7 @@ struct NovaCoreModule { // then `_debugfs_guard` clears `DEBUGFS_ROOT`. #[allow(clippy::type_complexity)] #[pin] - _driver: Registration>, + _driver: Registration)>>, _debugfs_guard: DebugfsRootGuard, } =20 --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 901EB3B19D4; Mon, 27 Apr 2026 22:14:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328067; cv=none; b=hmLKQhSJNr5U/BBAmd4pt6SHrXqIpbXz/j2+cA7Ep1hXbM7clvXTH9GvKqWnbFBSS5NSFM9v2/+V3mGwz2dnCocU4ijXdaXHKMs5ByEygFay/b5GhEfVe2UBV0hj7+E9O0w3GSv6pmS8NzBim001G6lMv2rBVZAMB9TUnRF44jA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328067; c=relaxed/simple; bh=hYy8LQDnO+hisbOptHtgqKp36k1YyJTGix7eeoo2qKk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=a7auGlE90LnSGD3byLYli0X76YCfzM3JWJzQXPVV4kDrOMfb++w2Ikzj1EQqRn2AhNPCBzhPDFErpZBFykm/hf+k9PMgyCNb/+GK7TviJQL8/myRmYs+vzycU3k/DSWs7aYzew4qmzj3jDzxynj18laNfhCI+HVEnE/LZ1xsVCU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BqDRm9LT; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="BqDRm9LT" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1AFB6C2BCB5; Mon, 27 Apr 2026 22:14:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328067; bh=hYy8LQDnO+hisbOptHtgqKp36k1YyJTGix7eeoo2qKk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BqDRm9LTAxT+LFyHHIuPW75dzJcoI9Ybx7Pav2R3kJM6ezZK8ghNMm+Vgu0kZDyZK 1LudCaJgONM+Un6S/kbl7SB8Mcga8LywZ7inQvNuX1KcK7KaSNDiyXC7DBPDVdTKor 0q2svsR7Us01zcKWz6u/qqn6vkMogrDSopGHpgCW5TGai40EemoNAzP0c0nAQAfQN4 l2N+0gniTfMs4GFNXBcrNGkoZtep7KOXCrc+BN9b5PlcSlhqV7AuaookXi4u61d0b9 TflB5dPw/5CUgL0yAScR61V23nWsROYxBmcBHmPPDz34QgZrIkEkjFfH5hf1xXxnE3 DpmWxroqy3GiQ== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich , Eliot Courtney Subject: [PATCH REF 22/24] gpu: nova-core: unregister sysmem flush page from Drop Date: Tue, 28 Apr 2026 00:11:20 +0200 Message-ID: <20260427221155.2144848-23-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Now that SysmemFlush can borrow the Bar via HRT lifetime, store a &'a Bar0 reference and implement Drop to automatically unregister the sysmem flush page. This removes the need for manual unregister() calls and the Gpu::unbind() method. Reported-by: Eliot Courtney Closes: https://lore.kernel.org/all/20260409-fix-systemflush-v1-1-a1d6c968f= 17c@nvidia.com/ Fixes: 6554ad65b589 ("gpu: nova-core: register sysmem flush page") Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/nova-core/driver.rs | 4 ---- drivers/gpu/nova-core/fb.rs | 22 ++++++++++------------ drivers/gpu/nova-core/gpu.rs | 9 +-------- 3 files changed, 11 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver= .rs index ec9cecb30f63..401ae213991f 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -111,8 +111,4 @@ fn probe( })) }) } - - fn unbind(_pdev: &'a pci::Device, this: Pin<&'a Self>) { - this.gpu.unbind(); - } } diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs index bdd5eed760e1..cbc42e98afca 100644 --- a/drivers/gpu/nova-core/fb.rs +++ b/drivers/gpu/nova-core/fb.rs @@ -46,21 +46,20 @@ /// Because of this, the sysmem flush memory page must be registered as ea= rly as possible during /// driver initialization, and before any falcon is reset. /// -/// Users are responsible for manually calling [`Self::unregister`] before= dropping this object, -/// otherwise the GPU might still use it even after it has been freed. -pub(crate) struct SysmemFlush { +pub(crate) struct SysmemFlush<'a> { /// Chipset we are operating on. chipset: Chipset, device: ARef, + bar: &'a Bar0, /// Keep the page alive as long as we need it. page: CoherentHandle, } =20 -impl SysmemFlush { +impl<'a> SysmemFlush<'a> { /// Allocate a memory page and register it as the sysmem flush page. pub(crate) fn register( dev: &device::Device, - bar: &Bar0, + bar: &'a Bar0, chipset: Chipset, ) -> Result { let page =3D CoherentHandle::alloc(dev, kernel::page::PAGE_SIZE, G= FP_KERNEL)?; @@ -70,19 +69,18 @@ pub(crate) fn register( Ok(Self { chipset, device: dev.into(), + bar, page, }) } +} =20 - /// Unregister the managed sysmem flush page. - /// - /// In order to gracefully tear down the GPU, users must make sure to = call this method before - /// dropping the object. - pub(crate) fn unregister(&self, bar: &Bar0) { +impl Drop for SysmemFlush<'_> { + fn drop(&mut self) { let hal =3D hal::fb_hal(self.chipset); =20 - if hal.read_sysmem_flush_page(bar) =3D=3D self.page.dma_handle() { - let _ =3D hal.write_sysmem_flush_page(bar, 0).inspect_err(|e| { + if hal.read_sysmem_flush_page(self.bar) =3D=3D self.page.dma_handl= e() { + let _ =3D hal.write_sysmem_flush_page(self.bar, 0).inspect_err= (|e| { dev_warn!( &self.device, "failed to unregister sysmem flush page: {:?}\n", diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs index 922197f2aeef..ff9a90a46609 100644 --- a/drivers/gpu/nova-core/gpu.rs +++ b/drivers/gpu/nova-core/gpu.rs @@ -228,7 +228,7 @@ pub(crate) struct Gpu<'a> { bar: &'a Bar0, /// System memory page required for flushing all pending GPU-side memo= ry writes done through /// PCIE into system memory, via sysmembar (A GPU-initiated HW memory-= barrier operation). - sysmem_flush: SysmemFlush, + sysmem_flush: SysmemFlush<'a>, /// GSP falcon instance, used for GSP boot up and cleanup. gsp_falcon: Falcon, /// SEC2 falcon instance, used for GSP boot up and cleanup. @@ -271,11 +271,4 @@ pub(crate) fn new( _: { gsp.boot(pdev, bar, spec.chipset, gsp_falcon, sec2_falcon= )? }, }) } - - /// Called when the corresponding [`Device`](device::Device) is unboun= d. - /// - /// Note: This method must only be called from `Driver::unbind`. - pub(crate) fn unbind(&self) { - self.sysmem_flush.unregister(self.bar); - } } --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 DFBDC3AE183; Mon, 27 Apr 2026 22:14:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328074; cv=none; b=EbfthtNvB4TxPoj1Ur6859Z685sXecFI+ZRmzZmL6I2at3mEoNj2uys112MAV9mOrikqpOGWZ26sGFqYFQrxkuv8xyBk10QfPK+ckxdy6Rn011B1ODESv+LFztRVZND5WduJvk/CmOb9mC49D+DlUqZfNcI1nV3hkJq/Xkn1xo4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328074; c=relaxed/simple; bh=3Y4jgtQFS1dMkKwizJ/kytTN4rfwuMJ6Fr3rkFzLank=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=i46AdG2uuoAKjRnzLJo2csfCXW/i42aEEDtkHsZ7DIM0pqqVFug2EP+JSYUOuqrStUvHHfCRYL2OQC1YAkATTGdjFrAyyky46vg0BGcbslvxtf9PSzEBvrbfJRDEt5DV1qCm71Ll86VgzDxP5Q2Wv8Ya8WH1VXmJnCfbIL7fc70= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=B4Wy1KVG; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="B4Wy1KVG" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 90922C19425; Mon, 27 Apr 2026 22:14:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328073; bh=3Y4jgtQFS1dMkKwizJ/kytTN4rfwuMJ6Fr3rkFzLank=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=B4Wy1KVGfeNbp6Dt+rvDiw8edx31HNXJTJqeVmBLQ4y5ANPxgjDpgr61KAeWXJ/jC 6Vns2yDV17GvYmbiaG3DXD4NfG/9eyGdP3OuF4XFtE0OPfg+XgYqKaW26Ukoc8FI+s pE44TP/BrjMZsmA+mzo25XeLlGNx6VblNyrbZ3kGqIV1OjN3m7PEo2Xqn8BBDPg6b/ sjAY4OkBNam75q9uxZPdPNK7qIR8h7WUkjRQEYoELitutB7KsIUMj2phUwEW7tHXn3 5KTFo/gvhoxUHpiJ8uMN6JuI8cwmrTy5FZp+y9emB+oXf6PS1NY4aLfOlSmJVVnBGE fgLFqIwoBZMEA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH REF 23/24] gpu: nova-core: replace ARef with &'a Device in SysmemFlush Date: Tue, 28 Apr 2026 00:11:21 +0200 Message-ID: <20260427221155.2144848-24-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Now that SysmemFlush is lifetime-parameterized, the ARef is unnecessary -- a plain &'a Device reference suffices. Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- drivers/gpu/nova-core/fb.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/nova-core/fb.rs b/drivers/gpu/nova-core/fb.rs index cbc42e98afca..e5a2c9d42f27 100644 --- a/drivers/gpu/nova-core/fb.rs +++ b/drivers/gpu/nova-core/fb.rs @@ -15,8 +15,7 @@ Alignable, Alignment, // }, - sizes::*, - sync::aref::ARef, // + sizes::*, // }; =20 use crate::{ @@ -49,7 +48,7 @@ pub(crate) struct SysmemFlush<'a> { /// Chipset we are operating on. chipset: Chipset, - device: ARef, + device: &'a device::Device, bar: &'a Bar0, /// Keep the page alive as long as we need it. page: CoherentHandle, @@ -58,7 +57,7 @@ pub(crate) struct SysmemFlush<'a> { impl<'a> SysmemFlush<'a> { /// Allocate a memory page and register it as the sysmem flush page. pub(crate) fn register( - dev: &device::Device, + dev: &'a device::Device, bar: &'a Bar0, chipset: Chipset, ) -> Result { @@ -68,7 +67,7 @@ pub(crate) fn register( =20 Ok(Self { chipset, - device: dev.into(), + device: dev, bar, page, }) --=20 2.54.0 From nobody Wed Jun 17 05:11:07 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 376BD3ACA51; Mon, 27 Apr 2026 22:14:39 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328080; cv=none; b=ZkkbS2KDorAtzqLFmTeutEzLbFAEEmz+xrnmddOMMY7pyc7dJIfcEZ1aKKeISH1vGEipMB3z9OiLGpShe8iibtEYg4NQeFNuan3DCJBrPFhVMn2338Gn//Hi66A0XBysRKyghAiNgLfXoYOoI1O9xHmvpciXSEWVZmoQjGSMT1c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1777328080; c=relaxed/simple; bh=E8DtrBLrYNArPpJF86GXwFeCoMuUblCF+p22mHtKF5E=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=jVsa/qO2UFvOfc3qJgrxJFAIB46zgcorZu2VqrKD1D72v2vMcWUfn6LmJQO5PdKgCjYpYqT87cLeGTo8Tbn3RMeLloQj6Om3tDL9L6vvFM63ch2T1ejFOJZvw3oJbsVAcGuwAoh7HHExRIi9NPNOdkjGmsrozpQ3Q/1NyJPRmQA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=p6W4oeKO; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="p6W4oeKO" Received: by smtp.kernel.org (Postfix) with ESMTPSA id DB888C2BCB5; Mon, 27 Apr 2026 22:14:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1777328079; bh=E8DtrBLrYNArPpJF86GXwFeCoMuUblCF+p22mHtKF5E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=p6W4oeKOQM7jk9jUoesyFgPltNs3rvUvJ9lYlQcxOYgJ6MKYpnV/2PWjGc4O6Z2eb OR2tKoInE0qj80ZUwdAGFDLG4KTetFGk1Mcf4t5ByMJsB3c1ULTqJ3Usu1SZh1w1TO WxDVArGn6/bxZq0SsSxaYf6HzaY4TXNrLwAMm4lr3cW8GW/thYh6Nz8M8ORmihfJr9 OqI6G35dQV1DQq9pVVfRW9IxKUFn7KltdTAEQagbAfhmotKOyNua/Lke93ARGdheGU dC3a4xk7VM5u4w1NFuaIIZSl2DV6pVKkWCaY0owAM0qH7kTKDX66LvYg4HueAW+yn+ bT5jiQBXLlbsA== From: Danilo Krummrich To: gregkh@linuxfoundation.org, rafael@kernel.org, acourbot@nvidia.com, aliceryhl@google.com, david.m.ertman@intel.com, ira.weiny@intel.com, leon@kernel.org, viresh.kumar@linaro.org, m.wilczynski@samsung.com, ukleinek@kernel.org, bhelgaas@google.com, kwilczynski@kernel.org, abdiel.janulgue@gmail.com, robin.murphy@arm.com, markus.probst@posteo.de, ojeda@kernel.org, boqun@kernel.org, gary@garyguo.net, bjorn3_gh@protonmail.com, lossin@kernel.org, a.hindborg@kernel.org, tmgross@umich.edu Cc: driver-core@lists.linux.dev, linux-kernel@vger.kernel.org, nova-gpu@lists.linux.dev, dri-devel@lists.freedesktop.org, linux-pm@vger.kernel.org, linux-pwm@vger.kernel.org, linux-pci@vger.kernel.org, rust-for-linux@vger.kernel.org, Danilo Krummrich Subject: [PATCH REF 24/24] gpu: drm: tyr: use HRT lifetime for IoMem Date: Tue, 28 Apr 2026 00:11:22 +0200 Message-ID: <20260427221155.2144848-25-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260427221155.2144848-1-dakr@kernel.org> References: <20260427221155.2144848-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" Take advantage of the lifetime-parameterized IoMem<'a> to use the memory mapping directly during probe, eliminating the Arc> indirection. Since the IoMem is only used during probe, this also simplifies Register::read/write to be infallible -- the Devres access check is no longer needed, so reads return u32 directly and writes return (). Signed-off-by: Danilo Krummrich Acked-by: Uwe Kleine-K=C3=B6nig --- Not yet updated to Tyr using the register!() macro, but probably good enoug= h for reference. --- drivers/gpu/drm/tyr/driver.rs | 14 ++++---- drivers/gpu/drm/tyr/gpu.rs | 62 +++++++++++++++++------------------ drivers/gpu/drm/tyr/regs.rs | 21 +++--------- 3 files changed, 41 insertions(+), 56 deletions(-) diff --git a/drivers/gpu/drm/tyr/driver.rs b/drivers/gpu/drm/tyr/driver.rs index eaa84efdfdf7..d305ad433e03 100644 --- a/drivers/gpu/drm/tyr/driver.rs +++ b/drivers/gpu/drm/tyr/driver.rs @@ -10,7 +10,6 @@ Core, Device, // }, - devres::Devres, drm, drm::ioctl, io::poll, @@ -23,7 +22,6 @@ sizes::SZ_2M, sync::{ aref::ARef, - Arc, Mutex, // }, time, // @@ -37,7 +35,7 @@ regs, // }; =20 -pub(crate) type IoMem =3D kernel::io::mem::IoMem<'static, SZ_2M>; +pub(crate) type IoMem =3D kernel::io::Mmio; =20 pub(crate) struct TyrDrmDriver; =20 @@ -65,11 +63,11 @@ pub(crate) struct TyrDrmDeviceData { pub(crate) gpu_info: GpuInfo, } =20 -fn issue_soft_reset(dev: &Device, iomem: &Devres) -> Result { - regs::GPU_CMD.write(dev, iomem, regs::GPU_CMD_SOFT_RESET)?; +fn issue_soft_reset(dev: &Device, iomem: &IoMem) -> Result { + regs::GPU_CMD.write(iomem, regs::GPU_CMD_SOFT_RESET); =20 poll::read_poll_timeout( - || regs::GPU_IRQ_RAWSTAT.read(dev, iomem), + || Ok(regs::GPU_IRQ_RAWSTAT.read(iomem)), |status| *status & regs::GPU_IRQ_RAWSTAT_RESET_COMPLETED !=3D 0, time::Delta::from_millis(1), time::Delta::from_millis(100), @@ -109,12 +107,12 @@ fn probe( let sram_regulator =3D Regulator::::get(pdev.a= s_ref(), c"sram")?; =20 let request =3D pdev.io_request_by_index(0).ok_or(ENODEV)?; - let iomem =3D Arc::new(request.iomap_sized::()?.into_devres= ()?, GFP_KERNEL)?; + let iomem =3D request.iomap_sized::()?; =20 issue_soft_reset(pdev.as_ref(), &iomem)?; gpu::l2_power_on(pdev.as_ref(), &iomem)?; =20 - let gpu_info =3D GpuInfo::new(pdev.as_ref(), &iomem)?; + let gpu_info =3D GpuInfo::new(&iomem); gpu_info.log(pdev); =20 let platform: ARef =3D pdev.into(); diff --git a/drivers/gpu/drm/tyr/gpu.rs b/drivers/gpu/drm/tyr/gpu.rs index a88775160f98..bb0473c85bf7 100644 --- a/drivers/gpu/drm/tyr/gpu.rs +++ b/drivers/gpu/drm/tyr/gpu.rs @@ -10,7 +10,6 @@ Bound, Device, // }, - devres::Devres, io::poll, platform, prelude::*, @@ -35,37 +34,36 @@ pub(crate) struct GpuInfo(pub(crate) uapi::drm_panthor_gpu_info); =20 impl GpuInfo { - pub(crate) fn new(dev: &Device, iomem: &Devres) -> Resul= t { - let gpu_id =3D regs::GPU_ID.read(dev, iomem)?; - let csf_id =3D regs::GPU_CSF_ID.read(dev, iomem)?; - let gpu_rev =3D regs::GPU_REVID.read(dev, iomem)?; - let core_features =3D regs::GPU_CORE_FEATURES.read(dev, iomem)?; - let l2_features =3D regs::GPU_L2_FEATURES.read(dev, iomem)?; - let tiler_features =3D regs::GPU_TILER_FEATURES.read(dev, iomem)?; - let mem_features =3D regs::GPU_MEM_FEATURES.read(dev, iomem)?; - let mmu_features =3D regs::GPU_MMU_FEATURES.read(dev, iomem)?; - let thread_features =3D regs::GPU_THREAD_FEATURES.read(dev, iomem)= ?; - let max_threads =3D regs::GPU_THREAD_MAX_THREADS.read(dev, iomem)?; - let thread_max_workgroup_size =3D regs::GPU_THREAD_MAX_WORKGROUP_S= IZE.read(dev, iomem)?; - let thread_max_barrier_size =3D regs::GPU_THREAD_MAX_BARRIER_SIZE.= read(dev, iomem)?; - let coherency_features =3D regs::GPU_COHERENCY_FEATURES.read(dev, = iomem)?; - - let texture_features =3D regs::GPU_TEXTURE_FEATURES0.read(dev, iom= em)?; - - let as_present =3D regs::GPU_AS_PRESENT.read(dev, iomem)?; - - let shader_present =3D u64::from(regs::GPU_SHADER_PRESENT_LO.read(= dev, iomem)?); + pub(crate) fn new(iomem: &IoMem) -> Self { + let gpu_id =3D regs::GPU_ID.read(iomem); + let csf_id =3D regs::GPU_CSF_ID.read(iomem); + let gpu_rev =3D regs::GPU_REVID.read(iomem); + let core_features =3D regs::GPU_CORE_FEATURES.read(iomem); + let l2_features =3D regs::GPU_L2_FEATURES.read(iomem); + let tiler_features =3D regs::GPU_TILER_FEATURES.read(iomem); + let mem_features =3D regs::GPU_MEM_FEATURES.read(iomem); + let mmu_features =3D regs::GPU_MMU_FEATURES.read(iomem); + let thread_features =3D regs::GPU_THREAD_FEATURES.read(iomem); + let max_threads =3D regs::GPU_THREAD_MAX_THREADS.read(iomem); + let thread_max_workgroup_size =3D regs::GPU_THREAD_MAX_WORKGROUP_S= IZE.read(iomem); + let thread_max_barrier_size =3D regs::GPU_THREAD_MAX_BARRIER_SIZE.= read(iomem); + let coherency_features =3D regs::GPU_COHERENCY_FEATURES.read(iomem= ); + + let texture_features =3D regs::GPU_TEXTURE_FEATURES0.read(iomem); + + let as_present =3D regs::GPU_AS_PRESENT.read(iomem); + + let shader_present =3D u64::from(regs::GPU_SHADER_PRESENT_LO.read(= iomem)); let shader_present =3D - shader_present | u64::from(regs::GPU_SHADER_PRESENT_HI.read(de= v, iomem)?) << 32; + shader_present | u64::from(regs::GPU_SHADER_PRESENT_HI.read(io= mem)) << 32; =20 - let tiler_present =3D u64::from(regs::GPU_TILER_PRESENT_LO.read(de= v, iomem)?); - let tiler_present =3D - tiler_present | u64::from(regs::GPU_TILER_PRESENT_HI.read(dev,= iomem)?) << 32; + let tiler_present =3D u64::from(regs::GPU_TILER_PRESENT_LO.read(io= mem)); + let tiler_present =3D tiler_present | u64::from(regs::GPU_TILER_PR= ESENT_HI.read(iomem)) << 32; =20 - let l2_present =3D u64::from(regs::GPU_L2_PRESENT_LO.read(dev, iom= em)?); - let l2_present =3D l2_present | u64::from(regs::GPU_L2_PRESENT_HI.= read(dev, iomem)?) << 32; + let l2_present =3D u64::from(regs::GPU_L2_PRESENT_LO.read(iomem)); + let l2_present =3D l2_present | u64::from(regs::GPU_L2_PRESENT_HI.= read(iomem)) << 32; =20 - Ok(Self(uapi::drm_panthor_gpu_info { + Self(uapi::drm_panthor_gpu_info { gpu_id, gpu_rev, csf_id, @@ -88,7 +86,7 @@ pub(crate) fn new(dev: &Device, iomem: &Devres) -> Result { core_features, pad: 0, gpu_features: 0, - })) + }) } =20 pub(crate) fn log(&self, pdev: &platform::Device) { @@ -208,11 +206,11 @@ fn from(value: u32) -> Self { } =20 /// Powers on the l2 block. -pub(crate) fn l2_power_on(dev: &Device, iomem: &Devres) -> R= esult { - regs::L2_PWRON_LO.write(dev, iomem, 1)?; +pub(crate) fn l2_power_on(dev: &Device, iomem: &IoMem) -> Result { + regs::L2_PWRON_LO.write(iomem, 1); =20 poll::read_poll_timeout( - || regs::L2_READY_LO.read(dev, iomem), + || Ok(regs::L2_READY_LO.read(iomem)), |status| *status =3D=3D 1, Delta::from_millis(1), Delta::from_millis(100), diff --git a/drivers/gpu/drm/tyr/regs.rs b/drivers/gpu/drm/tyr/regs.rs index 611870c2e6af..0881b3812afd 100644 --- a/drivers/gpu/drm/tyr/regs.rs +++ b/drivers/gpu/drm/tyr/regs.rs @@ -7,16 +7,7 @@ // does. #![allow(dead_code)] =20 -use kernel::{ - bits::bit_u32, - device::{ - Bound, - Device, // - }, - devres::Devres, - io::Io, - prelude::*, // -}; +use kernel::{bits::bit_u32, io::Io}; =20 use crate::driver::IoMem; =20 @@ -29,15 +20,13 @@ =20 impl Register { #[inline] - pub(crate) fn read(&self, dev: &Device, iomem: &Devres) = -> Result { - let value =3D (*iomem).access(dev)?.read32(OFFSET); - Ok(value) + pub(crate) fn read(&self, iomem: &IoMem) -> u32 { + iomem.read32(OFFSET) } =20 #[inline] - pub(crate) fn write(&self, dev: &Device, iomem: &Devres,= value: u32) -> Result { - (*iomem).access(dev)?.write32(value, OFFSET); - Ok(()) + pub(crate) fn write(&self, iomem: &IoMem, value: u32) { + iomem.write32(value, OFFSET); } } =20 --=20 2.54.0