[PATCH v3 06/10] rust: pci: drop driver data before remove returns
From: Zhi Wang
Date: Wed Sep 30 2026 - 06:36:50 EST
Drop PCI private data before the remove callback returns, so its
destructors run within PCI core's removal context.
Call unbind while private data remains installed, then take and release
the data. Taking it clears drvdata, so post_unbind does not release it
again. All borrows must end before the data is removed.
Suggested-by: Danilo Krummrich <dakr@xxxxxxxxxx>
Signed-off-by: Zhi Wang <zhiw@xxxxxxxxxx>
---
rust/kernel/device.rs | 4 ++--
rust/kernel/pci.rs | 6 ++++++
2 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 2291d85b6849..1f6bb58396e2 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -243,8 +243,8 @@ impl<Ctx: InternalBoundContext> Device<Ctx> {
///
/// # Safety
///
- /// - Must only be called after a preceding call to [`Device::set_drvdata`] and before the
- /// device is fully unbound.
+ /// - The data stored by [`Device::set_drvdata`] must still be installed and remain valid
+ /// for the returned borrow.
/// - The type `T` must match the type of the `ForeignOwnable` previously stored by
/// [`Device::set_drvdata`].
pub unsafe fn drvdata_borrow<T>(&self) -> Pin<&T> {
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index dcb0cdd0d426..1599b3a613d7 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -141,6 +141,12 @@ extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {
let data = unsafe { pdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
T::unbind(pdev, data);
+
+ // SAFETY: The driver's unbind callback has returned, and no callbacks retain a borrow.
+ let data = unsafe { pdev.as_ref().drvdata_obtain::<T::Data<'_>>() };
+
+ // Drop private data before returning to PCI core, while its removal context is valid.
+ drop(data);
}
}
--
2.53.0