Implement TryFrom<&device::Device> for &Device. This allows us to get a &pci::Device from a generic &Device in a safe way; the conversion fails if the device' bus type does not match with the PCI bus type. Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx> Reviewed-by: Benno Lossin <benno.lossin@xxxxxxxxx> Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx> --- rust/kernel/device.rs | 1 - rust/kernel/pci.rs | 25 +++++++++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index 67a2fc46cf4c..0bbc67edd38d 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -66,7 +66,6 @@ pub(crate) fn as_raw(&self) -> *mut bindings::device { } /// Returns a raw pointer to the device' bus type. - #[expect(unused)] pub(crate) fn bus_type_raw(&self) -> *const bindings::bus_type { // SAFETY: // - By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`. diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 22a32172b108..8b7fcfe8bffc 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -6,7 +6,7 @@ use crate::{ alloc::flags::*, - bindings, device, + bindings, container_of, device, device_id::RawDeviceId, devres::Devres, driver, @@ -20,7 +20,7 @@ use core::{ marker::PhantomData, ops::Deref, - ptr::{addr_of_mut, NonNull}, + ptr::{addr_of, addr_of_mut, NonNull}, }; use kernel::prelude::*; @@ -466,6 +466,27 @@ fn as_ref(&self) -> &device::Device { } } +impl TryFrom<&device::Device> for &Device { + type Error = kernel::error::Error; + + fn try_from(dev: &device::Device) -> Result<Self, Self::Error> { + #[allow(unused_unsafe)] + // SAFETY: rustc < 1.82 falsely treats this as unsafe, see: + // https://blog.rust-lang.org/2024/10/17/Rust-1.82.0.html#safely-addressing-unsafe-statics + if dev.bus_type_raw() != unsafe { addr_of!(bindings::pci_bus_type) } { + return Err(EINVAL); + } + + // SAFETY: We've just verified that the bus type of `dev` equals `bindings::pci_bus_type`, + // hence `dev` must be embedded in a valid `struct pci_dev` as guaranteed by the + // corresponding C code. + let pdev = unsafe { container_of!(dev.as_raw(), bindings::pci_dev, dev) }; + + // SAFETY: `pdev` is a valid pointer to a `struct pci_dev`. + Ok(unsafe { &*pdev.cast() }) + } +} + // SAFETY: A `Device` is always reference-counted and can be released from any thread. unsafe impl Send for Device {} -- 2.48.1