[PATCH 1/2] rust/kernel: Add platform::Device::from_raw()

Lyude Paul
2025-01-22T23:54:27Z

Just a convenience method to convert from a raw struct platform_device
pointer into a platform::Device object, which we'll be using in the next
commit.

Signed-off-by: Lyude Paul <lyude@redhat.com>
---
rust/kernel/platform.rs | 17 ++++++++++++++++-
1 file changed, 16 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs
index 50e6b04218132..75dc7824eccf4 100644
--- a/rust/kernel/platform.rs
+++ b/rust/kernel/platform.rs
@@ -14,7 +14,7 @@
ThisModule,
};

-use core::ptr::addr_of_mut;
+use core::ptr::{NonNull, addr_of_mut};

/// An adapter for the registration of platform drivers.
pub struct Adapter<T: Driver>(T);
@@ -186,6 +186,21 @@ unsafe fn from_dev(dev: ARef<device::Device>) -> Self {
Self(dev)
}

+ /// Convert a raw pointer to a `struct platform_device` into a `Device`.
+ ///
+ /// # Safety
+ ///
+ /// * `pdev` must be a valid pointer to a `bindings::platform_device`.
+ /// * The caller must be guaranteed to hold at least one reference to `pdev`.
+ unsafe fn from_raw(pdev: *mut bindings::platform_device) -> Self {
+ // SAFETY:
+ // * Our safety contract ensures `pdev` is a valid pointer which we hold at least one
+ // reference to.
+ // * struct device and `device::Device` have equivalent data layouts via the
+ // `device::Device` type invariants.
+ Self(unsafe { ARef::from_raw(NonNull::new_unchecked(addr_of_mut!((*pdev).dev).cast())) })
+ }
+
fn as_raw(&self) -> *mut bindings::platform_device {
// SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
// embedded in `struct platform_device`.
--
2.47.1