Skip to contentSkip to conversation

rust: devres: add DevresLt for ForLt-aware device resource access

PATCH New Danilo Krummrich 1 participant 4 messages May 6

Subsystems (10)
PCI Driver core Rust PWM +6 more subsystems
lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

cover rust: devres: add DevresLt for ForLt-aware device resource access

Devres<T> stores resources as T and hands out &'bound T from its access methods. For lifetime-parameterized types like Bar<'bound, SIZE> that are transmuted to 'static for storage, the synthetic 'static leaks to callers -- any method on the stored type that surfaces its lifetime parameter would yield a &'static reference, which is unsound.

This series adds DevresLt<F: ForLt>, a thin wrapper around Devres<F::Of<'static>> that applies ForLt::cast_ref in all access paths to shorten the stored 'static back to the caller's borrow lifetime. Devres<T: Send> remains unchanged for static resource types.

Also implement ForLt for Bar, IoMem and ExclusiveIoMem, and their into_devres() methods to return DevresLt instead of plain Devres. Provide convenience type aliases DevresBar, DevresIoMem and DevresExclusiveIoMem.

This series depends on [1].

[1] https://lore.kernel.org/driver-core/[email protected]/

Danilo Krummrich (3):
rust: devres: add DevresLt for ForLt-aware device resource access
rust: pci: return DevresLt from Bar::into_devres()
rust: io: mem: return DevresLt from
IoMem/ExclusiveIoMem::into_devres()

 drivers/pwm/pwm_th1520.rs |  5 +-
 rust/kernel/devres.rs     | 97 ++++++++++++++++++++++++++++++++++++---
 rust/kernel/io/mem.rs     | 55 ++++++++++++++++------
 rust/kernel/pci.rs        |  1 +
 rust/kernel/pci/io.rs     | 30 ++++++++----
 5 files changed, 155 insertions(+), 33 deletions(-)
Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH 1/3 rust: devres: add DevresLt for ForLt-aware device resource access

Devres<T> stores resources as T and returns &'bound T from access(). For lifetime-parameterized types like Bar<'bound, SIZE> that are transmuted to 'static for storage, this exposes the synthetic 'static lifetime to callers -- any method on the stored type that returns a reference with its lifetime parameter would yield a &'static reference, which is unsound.

Add DevresLt<F: ForLt>, a thin wrapper around Devres<F::Of<'static>> that applies ForLt::cast_ref in all access methods to shorten the stored 'static lifetime to the caller's borrow lifetime.

Devres<T: Send> remains unchanged for static resource types.

---
 rust/kernel/devres.rs | 97 +++++++++++++++++++++++++++++++++++++++----
 1 file changed, 90 insertions(+), 7 deletions(-)
rust/kernel/devres.rs +90 -7
index 58efe80474bd..c9c698901871 100644
@@ -24,6 +24,7 @@
         Arc, //
     },
     types::{
+        ForLt,
         ForeignOwnable,
         Opaque, //
     },
@@ -122,7 +123,7 @@ struct Inner<T> {
 /// # Ok(())
 /// # }
 /// ```
-pub struct Devres<T: Send> {
+pub struct Devres<T: Send + 'static> {
     dev: ARef<Device>,
     inner: Arc<Inner<T>>,
 }
@@ -184,7 +185,7 @@ pub(super) unsafe fn devres_node_remove(
     }
 }
 
-impl<T: Send> Devres<T> {
+impl<T: Send + 'static> Devres<T> {
     /// Creates a new [`Devres`] instance of the given `data`.
     ///
     /// The `data` encapsulated within the returned `Devres` instance' `data` will be
@@ -237,7 +238,7 @@ pub fn new<E>(dev: &Device<Bound>, data: impl PinInit<T, E>) -> Result<Self>
         })
     }
 
-    fn data(&self) -> &Revocable<T> {
+    pub(crate) fn data(&self) -> &Revocable<T> {
         &self.inner.data
     }
 
@@ -297,15 +298,19 @@ pub fn device(&self) -> &Device {
     /// #![cfg(CONFIG_PCI)]
     /// use kernel::{
     ///     device::Core,
-    ///     devres::Devres,
+    ///     devres::DevresLt,
     ///     io::{
     ///         Io,
     ///         IoKnownSize, //
     ///     },
-    ///     pci, //
+    ///     pci,
+    ///     types::ForLt, //
     /// };
     ///
-    /// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<'_, 0x4>>) -> Result {
+    /// fn from_core(
+    ///     dev: &pci::Device<Core>,
+    ///     devres: DevresLt<ForLt!(pci::Bar<'_, 0x4>)>,
+    /// ) -> Result {
     ///     let bar = devres.access(dev.as_ref())?;
     ///
     ///     let _ = bar.read32(0x0);
@@ -353,7 +358,7 @@ unsafe impl<T: Send> Send for Devres<T> {}
 // SAFETY: `Devres` can be shared with any task, if `T: Sync`.
 unsafe impl<T: Send + Sync> Sync for Devres<T> {}
 
-impl<T: Send> Drop for Devres<T> {
+impl<T: Send + 'static> Drop for Devres<T> {
     fn drop(&mut self) {
         // SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data
         // anymore, hence it is safe not to wait for the grace period to finish.
@@ -369,6 +374,84 @@ fn drop(&mut self) {
     }
 }
 
+/// Guard returned by [`DevresLt::try_access`].
+///
+/// Dereferences to `F::Of<'bound>`, applying [`ForLt::cast_ref`] to shorten the lifetime of the
+/// stored data to the guard's borrow lifetime.
+pub struct DevresGuard<'bound, F: ForLt>(RevocableGuard<'bound, F::Of<'static>>);
+
+impl<'bound, F: ForLt> core::ops::Deref for DevresGuard<'bound, F> {
+    type Target = F::Of<'bound>;
+
+    fn deref(&self) -> &Self::Target {
+        F::cast_ref(&*self.0)
+    }
+}
+
+/// Device-managed resource with [`ForLt`](trait@ForLt)-aware access.
+///
+/// `DevresLt` wraps [`Devres`] and applies [`ForLt::cast_ref`] in its access methods to shorten
+/// the stored `'static` lifetime to the caller's borrow lifetime. This prevents transmuted
+/// `'static` lifetimes from leaking to users.
+///
+/// Use this for resource types that implement [`ForLt`](trait@ForLt) and are stored with a
+/// transmuted `'static` lifetime (e.g. [`pci::Bar`]).
+///
+/// [`pci::Bar`]: crate::pci::Bar
+pub struct DevresLt<F: ForLt>(Devres<F::Of<'static>>)
+where
+    F::Of<'static>: Send;
+
+impl<F: ForLt> DevresLt<F>
+where
+    F::Of<'static>: Send,
+{
+    /// Creates a new [`DevresLt`] instance of the given `data`.
+    pub fn new<E>(dev: &Device<Bound>, data: impl PinInit<F::Of<'static>, E>) -> Result<Self>
+    where
+        Error: From<E>,
+    {
+        Ok(Self(Devres::new(dev, data)?))
+    }
+
+    /// Return a reference of the [`Device`] this [`DevresLt`] instance has been created with.
+    pub fn device(&self) -> &Device {
+        self.0.device()
+    }
+
+    /// Obtain `&'bound F::Of<'bound>`, bypassing the [`Revocable`].
+    ///
+    /// This method works like [`Devres::access`], but shortens the returned reference's lifetime
+    /// from `'static` to `'bound` via [`ForLt::cast_ref`].
+    pub fn access<'bound>(
+        &'bound self,
+        dev: &'bound Device<Bound>,
+    ) -> Result<&'bound F::Of<'bound>> {
+        self.0.access(dev).map(F::cast_ref)
+    }
+
+    /// [`DevresLt`] accessor for [`Revocable::try_access`].
+    pub fn try_access(&self) -> Option<DevresGuard<'_, F>> {
+        self.0.data().try_access().map(DevresGuard)
+    }
+
+    /// [`DevresLt`] accessor for [`Revocable::try_access_with`].
+    pub fn try_access_with<R, G>(&self, f: G) -> Option<R>
+    where
+        G: for<'bound> FnOnce(&'bound F::Of<'bound>) -> R,
+    {
+        self.0.data().try_access_with(|data| f(F::cast_ref(data)))
+    }
+
+    /// [`DevresLt`] accessor for [`Revocable::try_access_with_guard`].
+    pub fn try_access_with_guard<'bound>(
+        &'bound self,
+        guard: &'bound rcu::Guard,
+    ) -> Option<&'bound F::Of<'bound>> {
+        self.0.data().try_access_with_guard(guard).map(F::cast_ref)
+    }
+}
+
 /// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.
 fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
 where
Signature · 1 line
2.54.0
author maintainer
#2 lore raw

PATCH 2/3 rust: pci: return DevresLt from Bar::into_devres()

In reply to Danilo Krummrich

Implement ForLt for Bar<'static, SIZE> so that DevresLt can shorten the stored 'static lifetime back to the caller's borrow lifetime via ForLt::cast_ref. Without this, Devres<Bar<'static, SIZE>>::access() would return &'bound Bar<'static, SIZE>, allowing the inner 'static to leak through methods like pdev().

Add a DevresBar<SIZE> type alias for convenience.

---
 rust/kernel/pci.rs    |  1 +
 rust/kernel/pci/io.rs | 30 ++++++++++++++++++++++--------
 2 files changed, 23 insertions(+), 8 deletions(-)
rust/kernel/pci.rs +1 -0
index 1335857cae94..265d06b18e42 100644
@@ -48,6 +48,7 @@
     ConfigSpace,
     ConfigSpaceKind,
     ConfigSpaceSize,
+    DevresBar,
     Extended,
     Normal, //
 };
rust/kernel/pci/io.rs +22 -8
index 5668394a155b..7a5b5210cf66 100644
@@ -6,7 +6,7 @@
 use crate::{
     bindings,
     device,
-    devres::Devres,
+    devres::DevresLt,
     io::{
         Io,
         IoCapable,
@@ -14,7 +14,8 @@
         Mmio,
         MmioRaw, //
     },
-    prelude::*, //
+    prelude::*,
+    types::ForLt, //
 };
 use core::{
     marker::PhantomData,
@@ -151,6 +152,18 @@ pub struct Bar<'bound, const SIZE: usize = 0> {
     num: i32,
 }
 
+// SAFETY: `Bar<'bound, SIZE>` is covariant over `'bound` -- it holds
+// `&'bound Device<Bound>`, which is covariant. Shortening the lifetime
+// is therefore sound.
+unsafe impl<const SIZE: usize> ForLt for Bar<'static, SIZE> {
+    type Of<'bound> = Bar<'bound, SIZE>;
+}
+
+/// A device-managed PCI BAR mapping.
+///
+/// See [`Bar::into_devres`].
+pub type DevresBar<const SIZE: usize> = DevresLt<Bar<'static, SIZE>>;
+
 impl<'bound, const SIZE: usize> Bar<'bound, SIZE> {
     pub(super) fn new(pdev: &'bound Device<device::Bound>, num: u32, name: &CStr) -> Result<Self> {
         let len = pdev.resource_len(num)?;
@@ -219,15 +232,16 @@ fn release(&self) {
 
     /// Consume the `Bar` and register it as a device-managed resource.
     ///
-    /// The returned `Devres<Bar<'static, SIZE>>` can outlive the original lifetime `'bound`. Access
-    /// to the BAR is revoked when the device is unbound.
-    pub fn into_devres(self) -> Result<Devres<Bar<'static, SIZE>>> {
-        // SAFETY: Casting to `'static` is sound because `Devres` guarantees the `Bar` does not
+    /// Access methods on the returned [`DevresLt`] shorten the inner lifetime via
+    /// [`ForLt::cast_ref`], so the transmuted `'static` is never exposed to callers.
+    pub fn into_devres(self) -> Result<DevresLt<Bar<'static, SIZE>>> {
+        // SAFETY: Casting to `'static` is sound because `DevresLt` guarantees the `Bar` does not
         // actually outlive the device -- access is revoked and the resource is released when the
-        // device is unbound.
+        // device is unbound. The `ForLt` encoding ensures `access()` shortens the lifetime back
+        // to the caller's borrow, preventing `'static` from leaking.
         let bar: Bar<'static, SIZE> = unsafe { core::mem::transmute(self) };
         let pdev = bar.pdev;
-        Devres::new(pdev.as_ref(), bar)
+        DevresLt::new(pdev.as_ref(), bar)
     }
 }
 
Signature · 1 line
2.54.0
author maintainer
#3 lore raw

PATCH 3/3 rust: io: mem: return DevresLt from IoMem/ExclusiveIoMem::into_devres()

In reply to Danilo Krummrich

Implement ForLt for IoMem<'static, SIZE> and ExclusiveIoMem<'static, SIZE> so that DevresLt can shorten the stored 'static lifetime back to the caller's borrow lifetime via ForLt::cast_ref.

Change into_devres() to return DevresLt instead of Devres; add DevresIoMem<SIZE> and DevresExclusiveIoMem<SIZE> type aliases.

---
 drivers/pwm/pwm_th1520.rs |  5 ++--
 rust/kernel/io/mem.rs     | 55 ++++++++++++++++++++++++++++-----------
 2 files changed, 42 insertions(+), 18 deletions(-)
drivers/pwm/pwm_th1520.rs +2 -3
index 3deb39d8e0fc..6b094be35310 100644
@@ -24,9 +24,8 @@
 use kernel::{
     clk::Clk,
     device::{Bound, Core, Device},
-    devres,
     io::{
-        mem::IoMem,
+        mem::DevresIoMem,
         Io, //
     },
     of, platform,
@@ -92,7 +91,7 @@ struct Th1520WfHw {
 #[pin_data(PinnedDrop)]
 struct Th1520PwmDriverData {
     #[pin]
-    iomem: devres::Devres<IoMem<'static, TH1520_PWM_REG_SIZE>>,
+    iomem: DevresIoMem<TH1520_PWM_REG_SIZE>,
     clk: Clk,
 }
 
rust/kernel/io/mem.rs +40 -15

96 lines not on this page · raw message

Signature · 1 line
2.54.0