mirror of https://github.com/torvalds/linux.git
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>
This commit is contained in:
parent
a095d0d1e4
commit
a38dfd60fe
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 @@ fn as_ref(&self) -> &device::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 {}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue