]> www.infradead.org Git - users/jedix/linux-maple.git/commitdiff
rust: platform: impl TryFrom<&Device> for &platform::Device
authorDanilo Krummrich <dakr@kernel.org>
Fri, 21 Mar 2025 21:47:55 +0000 (22:47 +0100)
committerDanilo Krummrich <dakr@kernel.org>
Sat, 19 Apr 2025 08:20:25 +0000 (10:20 +0200)
Implement TryFrom<&device::Device> for &Device.

This allows us to get a &platform::Device from a generic &Device in a safe
way; the conversion fails if the device' bus type does not match with
the platform bus type.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20250321214826.140946-4-dakr@kernel.org
[ Support device context types, use dev_is_platform() helper. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
rust/helpers/platform.c
rust/kernel/platform.rs

index ab9b9f3173014e0550eab43b9b73b1af5b6dbf1c..82171233d12fe74999c1698d6f318730e7442172 100644 (file)
@@ -11,3 +11,8 @@ void rust_helper_platform_set_drvdata(struct platform_device *pdev, void *data)
 {
        platform_set_drvdata(pdev, data);
 }
+
+bool rust_helper_dev_is_platform(const struct device *dev)
+{
+       return dev_is_platform(dev);
+}
index b1c48cd95cd69d92d2b39ccdbb27c31daab8706e..08849d92c07418d6390803bb8cc51516368bca84 100644 (file)
@@ -5,7 +5,7 @@
 //! C header: [`include/linux/platform_device.h`](srctree/include/linux/platform_device.h)
 
 use crate::{
-    bindings, device, driver,
+    bindings, container_of, device, driver,
     error::{to_result, Result},
     of,
     prelude::*,
@@ -218,6 +218,26 @@ impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
     }
 }
 
+impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
+    type Error = kernel::error::Error;
+
+    fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
+        // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
+        // `struct device`.
+        if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
+            return Err(EINVAL);
+        }
+
+        // SAFETY: We've just verified that the bus type of `dev` equals
+        // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
+        // `struct platform_device` as guaranteed by the corresponding C code.
+        let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
+
+        // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
+        Ok(unsafe { &*pdev.cast() })
+    }
+}
+
 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
 unsafe impl Send for Device {}