[PATCH v2 v2 1/1] rust: device: add platdata accessors

From: pengfuyuan
Date: Fri Jan 09 2026 - 03:06:22 EST


Implement generic accessors for the platform data of a device.

Platform data is typically set by platform code when creating the device (e.g.
via `platform_device_add_data()`). Drivers may use it to obtain per-device,
platform-provided configuration.

The accessor is `unsafe` because the caller must ensure that the chosen `T`
matches the actual object referenced by `platform_data`.

Platform data is generally a C type, so the method returns `&Opaque<T>` to
avoid creating a Rust reference to potentially uninitialised or otherwise
invalid C data. Drivers can then perform the FFI dereference behind an explicit
`unsafe` block.

The method is implemented for `Device<Ctx>` so it is available in all device
states. If no platform data is present, `-ENOENT` is returned.

Signed-off-by: pengfuyuan <pengfuyuan@xxxxxxxxxx>
---
rust/kernel/device.rs | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)

diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index c79be2e2bfe3..90ccc433dfe7 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -483,6 +483,37 @@ pub fn fwnode(&self) -> Option<&property::FwNode> {
// defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`.
Some(unsafe { &*fwnode_handle.cast() })
}
+
+ /// Access the platform data for this device.
+ ///
+ /// Platform data is typically set by platform code when creating the device and is expected
+ /// to remain valid while the device is alive.
+ ///
+ /// Returns a reference to the opaque platform data, or [`ENOENT`] if no platform data
+ /// is set.
+ ///
+ /// # Safety
+ ///
+ /// Callers must ensure that:
+ /// - If platform data is set (i.e., `platform_data` is not null), the pointer points to valid,
+ /// properly aligned storage for `T` and remains valid for the lifetime of the returned
+ /// reference.
+ /// - The type `T` matches the type of the platform data structure set by platform code.
+ pub unsafe fn platdata<T>(&self) -> Result<&Opaque<T>> {
+ // SAFETY: By the type invariants, `self.as_raw()` is a valid pointer to a `struct device`.
+ let ptr = unsafe { (*self.as_raw()).platform_data };
+
+ if ptr.is_null() {
+ return Err(ENOENT);
+ }
+
+ // SAFETY:
+ // - `ptr` is not null (checked above).
+ // - By the safety requirements of this function, `ptr` points to valid, properly aligned
+ // storage for `T` and remains valid for the lifetime of the returned reference.
+ // - `Opaque<T>` allows any bit pattern, so we can safely create a reference to it.
+ Ok(unsafe { &*ptr.cast::<Opaque<T>>() })
+ }
}

// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
--
2.25.1