rust: of: Add basic DeviceNode abstractions,
Subsystems (2)
PATCH v2 1/1 rust: of: Add basic DeviceNode abstractions,
Add a safe wrapper arround struct device_node, which is capable of:
* reading string, u32 and bool properties
* iterating over children
--- rust/bindings/bindings_helper.h | 1 + rust/helpers/of.c | 10 +++ rust/kernel/of.rs | 150 ++++++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+)
(quoted diff) +0 -0
b/rust/bindings/bindings_helper.h
index 81796d5e16e8..e670b8e42787 100644
rust/bindings/bindings_helper.h +1 -0
@@ -59,6 +59,7 @@#include <linux/jump_label.h> #include <linux/mdio.h> #include <linux/miscdevice.h> +#include <linux/of.h> #include <linux/of_device.h> #include <linux/pci.h> #include <linux/phy.h>
rust/helpers/of.c +0 -0
@@ -6,3 +6,13 @@ bool rust_helper_is_of_node(const struct fwnode_handle
*fwnode)
{
return is_of_node(fwnode);
}
+
+struct device_node *rust_helper_of_node_get(struct device_node *node) +{
+ return of_node_get(node);
+}
+
+void rust_helper_of_node_put(struct device_node *node)
+{
+ of_node_put(node);
+}
rust/kernel/of.rs +4 -0
@@ -1,12 +1,16 @@// SPDX-License-Identifier: GPL-2.0 //! Device Tree / Open Firmware abstractions. +//! +//! C header: [`include/linux/of.h`](srctree/include/linux/of.h) use crate ::{ bindings, device_id::{RawDeviceId ,RawDeviceIdIndex }, prelude::*, + types::{ARef ,Opaque }, }; +use core::ptr::NonNull ;/// IdTable type for OF drivers. pub type IdTable<T> = &'static dyn
kernel::device_id::IdTable<DeviceId, T>;
@@ -16,6 +20,20 @@
#[derive(Clone, Copy)]
pub struct DeviceId(bindings::of_device_id);
+/// The device node representation.
+///
+/// This structure represents the Rust abstraction for a C struct device_node. The implementation
+/// abstracts the usage of an already existing C struct device_node within Rust code that we get
+/// passed from the C side.
+///
+/// # Invariants
+///
+/// A [DeviceNode] instance represents a valid struct device_node created by the C portion of the kernel. +#[repr(transparent)]
+pub struct DeviceNode(Opaque<bindings::device_node>);
+
+struct DeviceNodeIterator<'a>(&'a DeviceNode, Option<NonNull<bindings::device_node>>);
+
// SAFETY: DeviceId is a #[repr(transparent)] wrapper of `struct
of_device_id` and
// does not add additional invariants, so it's safe to transmute toRawType.
unsafe impl RawDeviceId for DeviceId {
@@ -63,3 +81,135 @@ macro_rules! of_device_table {
$crate::module_device_table!("of", $module_table_name,
$table_name);
}; }
+
+impl DeviceNode {
+ const fn as_raw(&self) -> *mut bindings::device_node {
+ self.0.get()
+ }
+
+ /// Returns the device tree populated by the bootloader.
+ pub fn root() -> Option<&'static DeviceNode> {
+ // SAFETY: of_root is guaranteed to be a pointer to a validstruct device_node or a null-pointer.
+ NonNull::new(unsafe { bindings::of_root })
+ // CAST: DeviceNode is a transparent wrapper ofOpaque<bindings::device_node>.
+ // SAFETY: ptr is guaranteed to be a pointer to a validstruct device_node.
+ .map(|ptr| unsafe { ptr.cast().as_ref() })
+ }
+
+ /// Returns an iterator over the children of this device node.
+ pub fn children(&self) -> impl Iterator<Item = ARef<DeviceNode>> +
use<'_> {
+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ let initial = unsafe {bindings::of_get_next_child(self.as_raw(), core::ptr::null_mut()) };
+ DeviceNodeIterator(self, NonNull::new(initial.cast()))
+ }
+
+ /// Returns the name of the device node.
+ pub fn name(&self) -> Option<&CStr> {
+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ let name = unsafe { (*self.as_raw()).name };
+ if name.is_null() {
+ None
+ } else {
+ // SAFETY: name is valid by the safety requirements.
+ Some(unsafe { CStr::from_char_ptr(name) })
+ }
+ }
+
+ /// Returns the full name (name including the full_name of the
parent) of the device node.
+ pub fn full_name(&self) -> Option<&CStr> {
+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ let full_name = unsafe { (*self.as_raw()).full_name };
+ if full_name.is_null() {
+ None
+ } else {
+ // SAFETY: full_name is valid by the safety
requirements.
+ Some(unsafe { CStr::from_char_ptr(full_name) })
+ }
+ }
+
+ /// Find and read a u32 from a multi-value property.
+ pub fn property_read_u32_index(&self, propname: &CStr, index: u32)
-> Result<u32> {
+ let mut value = 0;
+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ let ret = unsafe {
+ bindings::of_property_read_u32_index(
+ self.as_raw(), + propname.as_char_ptr(), + index, + &mut value,
+ )
+ };
+ if ret != 0 {
+ return Err(Error::from_errno(ret));
+ }
+ Ok(value)
+ }
+
+ /// Find and read a string from a property.
+ pub fn property_read_string(&self, propname: &CStr) ->
Result<&CStr> {
+ let mut value = core::ptr::null();
+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ let ret = unsafe {
+ bindings::of_property_read_string(self.as_raw(),propname.as_char_ptr(), &mut value)
+ };
+ if ret != 0 {
+ return Err(Error::from_errno(ret));
+ }
+ // SAFETY: value is guaranteed to be a valid C string
pointer.
+ Ok(unsafe { CStr::from_char_ptr(value) })
+ }
+
+ /// Find a property.
+ ///
+ /// Returns true if the property exists false otherwise.
+ pub fn property_read_bool(&self, propname: &CStr) -> bool {+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ unsafe { bindings::of_property_read_bool(self.as_raw(),propname.as_char_ptr()) }
+ }
+
+ /// Find the child node by name for this device node.
+ pub fn child_by_name(&self, name: &CStr) ->
Option<ARef<DeviceNode>> {
+ // SAFETY: self.as_raw is guaranteed to be a pointer to a
valid struct device_node.
+ let node = unsafe {bindings::of_get_child_by_name(self.as_raw(), name.as_char_ptr()) };
+ // SAFETY: node is guaranteed to be a pointer to a validstruct device_node or a null-pointer.
+ Some(unsafe { ARef::from_raw(NonNull::new(node)?.cast()) })
+ }
+}
+
+// SAFETY: A DeviceNode is always reference-counted and can be released from any thread.
+unsafe impl Send for DeviceNode {}
+
+// SAFETY: DeviceNode can be shared among threads because all methods of DeviceNode are thread safe.
+unsafe impl Sync for DeviceNode {}
+
+// SAFETY: Instances of DeviceNode are always reference-counted. +unsafe impl kernel::types::AlwaysRefCounted for DeviceNode {
+ fn inc_ref(&self) {
+ // SAFETY: The existence of a shared reference guarantees that
the refcount is non-zero.
+ unsafe { bindings::of_node_get(self.as_raw()) };
+ }
+
+ unsafe fn dec_ref(obj: NonNull<Self>) {
+ // SAFETY: The safety requirements guarantee that the refcount
is non-zero.
+ unsafe { bindings::of_node_put(obj.cast().as_ptr()) }
+ }
+}
+
+impl<'a> Iterator for DeviceNodeIterator<'a> {
+ type Item = ARef<DeviceNode>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let prev = self.1.take()?;
+
+ // CAST: DeviceNode is a transparent wrapper ofOpaque<bindings::device_node>.
+ // SAFETY: ptr is guaranteed to be a pointer to a validstruct device_node.
+ let result = ARef::from(unsafe {
prev.cast::<DeviceNode>().as_ref() });
+
+ // SAFETY:
+ // - self.0.as_raw is guaranteed to be a pointer to a validstruct device_node.
+ // - prev is guaranteed to be a pointer to a valid `struct
device_node`.
+ self.1 =
+ NonNull::new(unsafe {bindings::of_get_next_child(self.0.as_raw(), prev.as_ptr()) });
+ Some(result)
+ }
+}
Signature · 1 line
2.49.1
Danilo Krummrich
reviewerQuoted 7 lines · Markus Probst
Add a safe wrapper arround
struct device_node, which is capable of:* reading string, u32 and bool properties
* iterating over children
Signed-off-by Markus Probst <[email protected]>
Can you please expand on the commit message a bit? What's the motivation? Why can't you use device/fwnode properties instead?
Also, the patch seems mangled by your mail client, the corresponding MTA, etc. Please have a look into fixing this up. You can also try to send a patch to yourself first and see if it still applies for this purpose.
Thanks,
Danilo
Didn't know device::fwnode existed until now (I am new to linux kernel development and therefore aren' familiar with the entire codebase yet). This should make the patch obsolete.
Also I will fix my email client for future patch submittions. Thanks for pointing that out.
- Markus Probst
Quoted 911 lines · Danilo Krummrich
Quoted 8 lines · Markus Probst
Add a safe wrapper arround
struct device_node, which is capable of:* reading string, u32 and bool properties
* iterating over children
Signed-off-by Markus Probst <[email protected]>Can you please expand on the commit message a bit? What's the motivation? Why
can't you use device/fwnode properties instead?Also, the patch seems mangled by your mail client, the corresponding MTA, etc.
Please have a look into fixing this up. You can also try to send a patch to
yourself first and see if it still applies for this purpose.Thanks,
DaniloQuoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines
Quoted 889 lines