diff options
author | Danilo Krummrich <dakr@kernel.org> | 2025-03-21 22:47:55 +0100 |
---|---|---|
committer | Danilo Krummrich <dakr@kernel.org> | 2025-04-19 10:20:25 +0200 |
commit | a38dfd60fe53a46a93517f02a061bb34c47946dc (patch) | |
tree | 1f51b84e91c35208b2573cebb8b38d12cdf73295 /rust/kernel | |
parent | a095d0d1e4849ee25c28d43d713a8f433d7f1f27 (diff) |
rust: platform: impl TryFrom<&Device> for &platform::Device
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>
Diffstat (limited to 'rust/kernel')
-rw-r--r-- | rust/kernel/platform.rs | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index b1c48cd95cd6..08849d92c074 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -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 {} |