From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-alma10-1.taild15c8.ts.net [100.103.45.18]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 07ED03AD52E; Mon, 25 May 2026 20:32:16 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=100.103.45.18 ARC-Seal:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779741139; cv=none; b=Tv8NXe/y0gAPwBOzdij1Yhk3JEDArXL4nJsyV5I73SKluEGMvMN61Wd6UasEzs+oa7yFNtkxwqCSgRE8RR01AY2s/thy0cv6ge0kJdBJFdDn4B4NBrKVDS3N+2PMpp985ZS+GCW5t4TWy0l773PfiMPukaL2S/BhpdrxvYfER0g= ARC-Message-Signature:i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779741139; c=relaxed/simple; bh=4DHQw9eKOJiPSF0yo6o6S+FEkFSRtACLgacvFmGr/OU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=EL+vzjnza5AwYgtIXcSNWMjdoc/k8FmSzkeoShcuVylVzeITYScO2q9OP9pmgT/dNuN3jLalpcrKBW0nXNbTMzGjkBF6uhYxFKghq6kOkQFtKcUZjRsv/k3HuCBPlDkOahUU6kJphOTcnXI9docqClLXkdaKvJDDPTVqXUFReHg= ARC-Authentication-Results:i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=YMWblnp9; arc=none smtp.client-ip=100.103.45.18 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="YMWblnp9" Received: by smtp.kernel.org (Postfix) with ESMTPSA id CE3731F00A3C; Mon, 25 May 2026 20:32:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=kernel.org; s=k20260515; t=1779741136; bh=VlEFGAzw+HUYppR1B8Mu1locJbyWufzNCgGKfk+h2vA=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=YMWblnp9Hf07OuhKdAsN4znef0aXSHAyDlnUxBDP4HyFIoim2Xep6kUHK9w9BlE9v cCgo1RKqi+dY0zW+s2PzVY00LtG2lqeUQrUMgimS2ebIbQz74KI8bfoXRY1Qbw9qWx 7x9r8lQJkfu1CMpa/rsCrjkmbasbjWXqRg2md3Ur7M3f7VGo90flssuxW1kc4MACjP 63hJidMnB9rQBjykWkvqR/wDrSQkcnKJRzFGiHm238fZicQGlKWf1CS8+nRo/hcbvd lzYiYOsiGJja7dGd/+WWahJU+0c1nC1eBjXq9oJvCqTIfFQb/lkZSi387r96a3vcyv iPSnvdWT7cNKQ== 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, igor.korotin@linux.dev, daniel.almeida@collabora.com, pcolberg@redhat.com 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 v5 23/24] rust: auxiliary: generalize Registration over ForLt Date: Mon, 25 May 2026 22:21:10 +0200 Message-ID: <20260525202921.124698-24-dakr@kernel.org> X-Mailer: git-send-email 2.54.0 In-Reply-To: <20260525202921.124698-1-dakr@kernel.org> References: <20260525202921.124698-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: nova-gpu@lists.linux.dev List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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. Reviewed-by: Greg Kroah-Hartman Reviewed-by: Alexandre Courbot Reviewed-by: Eliot Courtney Signed-off-by: Danilo Krummrich --- drivers/gpu/nova-core/driver.rs | 13 ++-- rust/kernel/auxiliary.rs | 108 +++++++++++++++++++------- samples/rust/rust_driver_auxiliary.rs | 19 +++-- 3 files changed, 96 insertions(+), 44 deletions(-) diff --git a/drivers/gpu/nova-core/driver.rs b/drivers/gpu/nova-core/driver.rs index fa898fe5c893..d3f2245ba2e0 100644 --- a/drivers/gpu/nova-core/driver.rs +++ b/drivers/gpu/nova-core/driver.rs @@ -3,7 +3,6 @@ use kernel::{ auxiliary, device::Core, - devres::Devres, dma::Device, dma::DmaMask, pci, @@ -21,6 +20,7 @@ }, Arc, }, + types::ForLt, }; use crate::gpu::Gpu; @@ -29,10 +29,11 @@ static AUXILIARY_ID_COUNTER: Atomic = Atomic::new(0); #[pin_data] -pub(crate) struct NovaCore { +pub(crate) struct NovaCore<'bound> { #[pin] pub(crate) gpu: Gpu, - _reg: Devres>, + #[allow(clippy::type_complexity)] + _reg: auxiliary::Registration<'bound, ForLt!(())>, } pub(crate) struct NovaCoreDriver; @@ -76,13 +77,13 @@ pub(crate) struct NovaCore { impl pci::Driver for NovaCoreDriver { type IdInfo = (); - type Data<'bound> = NovaCore; + type Data<'bound> = NovaCore<'bound>; const ID_TABLE: pci::IdTable = &PCI_TABLE; fn probe<'bound>( pdev: &'bound pci::Device>, _info: &'bound Self::IdInfo, - ) -> impl PinInit + 'bound { + ) -> impl PinInit, Error> + 'bound { pin_init::pin_init_scope(move || { dev_dbg!(pdev, "Probe Nova Core GPU driver.\n"); @@ -115,7 +116,7 @@ fn probe<'bound>( }) } - fn unbind<'bound>(pdev: &'bound pci::Device>, this: Pin<&NovaCore>) { + fn unbind<'bound>(pdev: &'bound pci::Device>, this: Pin<&Self::Data<'bound>>) { this.gpu.unbind(pdev.as_ref()); } } diff --git a/rust/kernel/auxiliary.rs b/rust/kernel/auxiliary.rs index 7a1b1a7b7ca6..75ddb0220748 100644 --- a/rust/kernel/auxiliary.rs +++ b/rust/kernel/auxiliary.rs @@ -12,7 +12,7 @@ RawDeviceId, RawDeviceIdIndex, // }, - devres::Devres, + driver, error::{ from_result, @@ -20,6 +20,7 @@ }, prelude::*, types::{ + ForLt, ForeignOwnable, Opaque, // }, @@ -271,12 +272,16 @@ pub fn parent(&self) -> &device::Device { /// Returns a pinned reference to the registration data set by the registering (parent) driver. /// - /// Returns [`EINVAL`] if `T` does not match the type used by the parent driver when calling + /// `F` is the [`ForLt`](trait@ForLt) encoding of the data type. The returned + /// reference has its lifetime shortened from `'static` to `&self`'s borrow lifetime via + /// [`ForLt::cast_ref`]. + /// + /// Returns [`EINVAL`] if `F` does not match the type used by the parent driver when calling /// [`Registration::new()`]. /// /// Returns [`ENOENT`] if no registration data has been set, e.g. when the device was /// registered by a C driver. - pub fn registration_data(&self) -> Result> { + pub fn registration_data(&self) -> Result>> { // SAFETY: By the type invariant, `self.as_raw()` is a valid `struct auxiliary_device`. let ptr = unsafe { (*self.as_raw()).registration_data_rust }; if ptr.is_null() { @@ -289,18 +294,23 @@ pub fn registration_data(&self) -> Result> { // 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 = unsafe { ptr.cast::().read() }; - if type_id != TypeId::of::() { + if type_id != TypeId::of::() { return Err(EINVAL); } - // SAFETY: The `TypeId` check above confirms that the stored type is `T`; `ptr` remains - // valid until `Registration::drop()` calls `from_foreign()`. - let wrapper = unsafe { Pin::>>::borrow(ptr) }; + // SAFETY: The `TypeId` check above confirms that the stored type matches + // `F::Of<'static>`; `ptr` remains valid until `Registration::drop()` calls + // `from_foreign()`. + let wrapper = unsafe { Pin::>>>::borrow(ptr) }; // SAFETY: `data` is a structurally pinned field of `RegistrationData`. - Ok(unsafe { wrapper.map_unchecked(|w| &w.data) }) + let pinned: Pin<&F::Of<'static>> = unsafe { wrapper.map_unchecked(|w| &w.data) }; + + // SAFETY: The data was pinned when stored; `cast_ref` only shortens + // the lifetime, so the pinning guarantee is preserved. + Ok(unsafe { Pin::new_unchecked(F::cast_ref(pinned.get_ref())) }) } } @@ -389,43 +399,61 @@ struct RegistrationData { /// This type represents the registration of a [`struct auxiliary_device`]. When its parent device /// is unbound, the corresponding auxiliary device will be unregistered from the system. /// -/// The type parameter `T` is the type of the registration data owned by the 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 registration +/// data type. For non-lifetime-parameterized types, use [`ForLt!(T)`](macro@ForLt). +/// The data can be accessed by the auxiliary driver through [`Device::registration_data()`]. /// /// # Invariants /// /// `self.adev` always holds a valid pointer to an initialized and registered /// [`struct auxiliary_device`] whose `registration_data_rust` field points to a -/// valid `Pin>>`. -pub struct Registration { +/// valid `Pin>>>`. +pub struct Registration<'a, F: ForLt + 'static> { adev: NonNull, - _data: PhantomData, + #[allow(clippy::type_complexity)] + _phantom: PhantomData<(fn(&'a ()) -> &'a (), F)>, } -impl Registration { +impl<'a, F: ForLt> Registration<'a, F> +where + for<'b> F::Of<'b>: Send + Sync, +{ /// Create and register a new auxiliary device with the given registration data. /// /// The `data` is owned by the registration and can be accessed through the auxiliary device /// via [`Device::registration_data()`]. - pub fn new( - parent: &device::Device, + /// + /// # Safety + /// + /// The caller must not `mem::forget()` the returned [`Registration`] or otherwise prevent its + /// [`Drop`] implementation from running, since the registration data may contain borrowed + /// references that become invalid after `'a` ends. + /// + /// If the registration data is `'static`, use the safe [`Registration::new()`] instead. + pub unsafe fn new_with_lt( + parent: &'a device::Device, name: &CStr, id: u32, modname: &CStr, - data: impl PinInit, - ) -> Result> + data: impl PinInit, E>, + ) -> Result where Error: From, { let data = KBox::pin_init::( try_pin_init!(RegistrationData { - type_id: TypeId::of::(), + type_id: TypeId::of::(), data <- data, }), GFP_KERNEL, )?; + // SAFETY: `'a` is invariant (via `Registration`'s `PhantomData`). Lifetimes do not + // affect layout, so RegistrationData> and RegistrationData> + // have identical representation. + let data: Pin>>> = + unsafe { core::mem::transmute(data) }; + let boxed: KBox> = KBox::zeroed(GFP_KERNEL)?; let adev = boxed.get(); @@ -455,7 +483,9 @@ pub fn new( if ret != 0 { // SAFETY: `registration_data` was set above via `into_foreign()`. drop(unsafe { - Pin::>>::from_foreign((*adev).registration_data_rust) + Pin::>>>::from_foreign( + (*adev).registration_data_rust, + ) }); // SAFETY: `adev` is guaranteed to be a valid pointer to a @@ -467,18 +497,36 @@ pub fn new( // INVARIANT: The device will remain registered until `auxiliary_device_delete()` is // called, which happens in `Self::drop()`. - let reg = Self { + Ok(Self { // SAFETY: `adev` is guaranteed to be non-null, since the `KBox` was allocated // successfully. adev: unsafe { NonNull::new_unchecked(adev) }, - _data: PhantomData, - }; + _phantom: PhantomData, + }) + } - Devres::new::(parent, reg) + /// Create and register a new auxiliary device with `'static` registration data. + /// + /// Safe variant of [`Registration::new_with_lt()`] for registration data that does not contain + /// borrowed references. + pub fn new( + parent: &'a device::Device, + name: &CStr, + id: u32, + modname: &CStr, + data: impl PinInit, E>, + ) -> Result + where + F::Of<'a>: 'static, + Error: From, + { + // SAFETY: `F::Of<'a>: 'static` guarantees the data contains no borrowed references, + // so forgetting the `Registration` cannot cause use-after-free. + unsafe { Self::new_with_lt(parent, name, id, modname, data) } } } -impl Drop for Registration { +impl Drop for Registration<'_, F> { fn drop(&mut self) { // SAFETY: By the type invariant of `Self`, `self.adev.as_ptr()` is a valid registered // `struct auxiliary_device`. @@ -486,7 +534,7 @@ fn drop(&mut self) { // SAFETY: `registration_data` was set in `new()` via `into_foreign()`. drop(unsafe { - Pin::>>::from_foreign( + Pin::>>>::from_foreign( (*self.adev.as_ptr()).registration_data_rust, ) }); @@ -500,7 +548,7 @@ fn drop(&mut self) { } // SAFETY: A `Registration` of a `struct auxiliary_device` can be released from any thread. -unsafe impl Send for Registration {} +unsafe impl Send for Registration<'_, F> where for<'a> F::Of<'a>: Send {} // SAFETY: `Registration` does not expose any methods or fields that need synchronization. -unsafe impl Sync for Registration {} +unsafe impl Sync for Registration<'_, F> where for<'a> F::Of<'a>: Send {} diff --git a/samples/rust/rust_driver_auxiliary.rs b/samples/rust/rust_driver_auxiliary.rs index b30a4d5cdf8a..e3e811a14110 100644 --- a/samples/rust/rust_driver_auxiliary.rs +++ b/samples/rust/rust_driver_auxiliary.rs @@ -10,10 +10,10 @@ Bound, Core, // }, - devres::Devres, driver, pci, prelude::*, + types::ForLt, InPlaceModule, // }; @@ -55,9 +55,12 @@ struct Data { index: u32, } -struct ParentDriver { - _reg0: Devres>, - _reg1: Devres>, +struct ParentDriver; + +#[allow(clippy::type_complexity)] +struct ParentData<'bound> { + _reg0: auxiliary::Registration<'bound, ForLt!(Data)>, + _reg1: auxiliary::Registration<'bound, ForLt!(Data)>, } kernel::pci_device_table!( @@ -69,15 +72,15 @@ struct ParentDriver { impl pci::Driver for ParentDriver { type IdInfo = (); - type Data<'bound> = Self; + type Data<'bound> = ParentData<'bound>; const ID_TABLE: pci::IdTable = &PCI_TABLE; fn probe<'bound>( pdev: &'bound pci::Device>, _info: &'bound Self::IdInfo, - ) -> impl PinInit + 'bound { - Ok(Self { + ) -> impl PinInit, Error> + 'bound { + Ok(ParentData { _reg0: auxiliary::Registration::new( pdev.as_ref(), AUXILIARY_NAME, @@ -101,7 +104,7 @@ fn connect(adev: &auxiliary::Device) -> Result { let dev = adev.parent(); let pdev: &pci::Device = dev.try_into()?; - let data = adev.registration_data::()?; + let data = adev.registration_data::()?; dev_info!( dev, -- 2.54.0