More Rust bindings for device property reads
Subsystems (4)
v8 cover More Rust bindings for device property reads
changes in v8:
* Use a custom enum instead of Either, which is scheduled for removal.
* Add Tested-by tags from Dirk Behme (thanks!)
* Implement Display directly on FwNode, which prints the full path by default. Printing only the name is still possible with the method display_name.
* Rebase onto 6.16-rc1.
* Remove property_present from Device and update users.
Best regards,
Remo
Remo Senekowitsch (9):
rust: device: Create FwNode abstraction for accessing device
properties
rust: device: Enable accessing the FwNode of a Device
rust: device: Move property_present() to FwNode
rust: device: Enable printing fwnode name and path
rust: device: Introduce PropertyGuard
rust: device: Implement accessors for firmware properties
rust: device: Add child accessor and iterator
rust: device: Add property_get_reference_args
samples: rust: platform: Add property read examples
MAINTAINERS | 1 + drivers/cpufreq/rcpufreq_dt.rs | 3 +- drivers/of/unittest-data/tests-platform.dtsi | 3 + rust/helpers/helpers.c | 1 + rust/helpers/property.c | 8 + rust/kernel/device.rs | 20 +- rust/kernel/device/property.rs | 589 +++++++++++++++++++ samples/rust/rust_driver_platform.rs | 60 +- 8 files changed, 678 insertions(+), 7 deletions(-) create mode 100644 rust/helpers/property.c create mode 100644 rust/kernel/device/property.rs
Signature · 1 line
2.49.0
PATCH v8 1/9 rust: device: Create FwNode abstraction for accessing device properties
Accessing device properties is currently done via methods on Device itself, using bindings to device_property_* functions. This is sufficient for the existing method property_present. However, it's not sufficient for other device properties we want to access. For example, iterating over child nodes of a device will yield a fwnode_handle. That's not a device, so it wouldn't be possible to read the properties of that child node. Thus, we need an abstraction over fwnode_handle and methods for reading its properties.
Add a struct FwNode which abstracts over the C struct fwnode_handle. Implement its reference counting analogous to other Rust abstractions over reference-counted C structs.
Subsequent patches will add functionality to access FwNode and read properties with it.
--- MAINTAINERS | 1 + rust/helpers/helpers.c | 1 + rust/helpers/property.c | 8 ++++ rust/kernel/device.rs | 2 + rust/kernel/device/property.rs | 73 ++++++++++++++++++++++++++++++++++ 5 files changed, 85 insertions(+) create mode 100644 rust/helpers/property.c create mode 100644 rust/kernel/device/property.rs
MAINTAINERS +1 -0
@@ -7366,6 +7366,7 @@ F: include/linux/property.h F: include/linux/sysfs.h F: lib/kobj* F: rust/kernel/device.rs +F: rust/kernel/device/ F: rust/kernel/device_id.rs F: rust/kernel/devres.rs F: rust/kernel/driver.rs
rust/helpers/helpers.c +1 -0
@@ -30,6 +30,7 @@#include "platform.c" #include "pci.c" #include "pid_namespace.c" +#include "property.c" #include "rbtree.c" #include "rcu.c" #include "refcount.c"
rust/helpers/property.c new file +8 -0
@@ -0,0 +1,8 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/property.h> + +void rust_helper_fwnode_handle_put (struct fwnode_handle *fwnode) +{ +fwnode_handle_put (fwnode); +}
rust/kernel/device.rs +2 -0
@@ -14,6 +14,8 @@#[cfg( CONFIG_PRINTK )] use crate ::c_str; +pub mod property; +/// A reference-counted device. /// /// This structure represents the Rust abstraction for a C `struct device`. This implementation
rust/kernel/device/property.rs new file +73 -0
73 lines not on this page · raw message
Signature · 1 line
2.49.0
PATCH v8 2/9 rust: device: Enable accessing the FwNode of a Device
In reply to Remo SenekowitschSubsequent patches will add methods for reading properties to FwNode. The first step to accessing these methods will be to access the "root" FwNode of a Device.
Add the method fwnode to Device.
--- rust/kernel/device.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
rust/kernel/device.rs +15 -0
@@ -205,6 +205,21 @@ unsafe fn printk(&self, klevel: &[u8], msg: fmt::Arguments<'_>) { }; } +/// Obtain the [`FwNode`](property::FwNode) corresponding to the device. +pub fn fwnode (&self) ->Option <&property::FwNode > { +// SAFETY: `self` is valid. +let fwnode_handle =unsafe { bindings::__dev_fwnode (self.as_raw ()) }; +if fwnode_handle.is_null () { +return None ; + } +// SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&self`. We +// return a reference instead of an `ARef<FwNode>` because `dev_fwnode()` +// doesn't increment the refcount. It is safe to cast from a +// `struct fwnode_handle*` to a `*const FwNode` because `FwNode` is +// defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`. +Some (unsafe { &*fwnode_handle.cast () }) + } +/// Checks if property is present or not. pub fn property_present (&self, name: &CStr ) ->bool {// SAFETY: By the invariant of `CStr`, `name` is null-terminated.
Signature · 1 line
2.49.0
PATCH v8 3/9 rust: device: Move property_present() to FwNode
In reply to Remo SenekowitschThe new FwNode abstraction will be used for accessing all device properties.
It would be possible to duplicate the methods on the device itself, but since some of the methods on Device would have different type sigatures as the ones on FwNode, this would only lead to inconsistency and confusion. For this reason, property_present is removed from Device and existing users are updated.
--- drivers/cpufreq/rcpufreq_dt.rs | 3 ++- rust/kernel/device.rs | 7 ------- rust/kernel/device/property.rs | 7 +++++++ 3 files changed, 9 insertions(+), 8 deletions(-)
drivers/cpufreq/rcpufreq_dt.rs +2 -1
@@ -20,7 +20,8 @@/// Finds exact supply name from the OF node. fn find_supply_name_exact (dev: &Device , name: &str ) ->Option <CString > {let prop_name =CString ::try_from_fmt (fmt! ("{}-supply" , name)).ok ()?; - dev.property_present (&prop_name) + dev.fwnode ()? + .property_present (&prop_name) .then (||CString ::try_from_fmt (fmt! ("{name}" )).ok ()) .flatten () }
rust/kernel/device.rs +0 -7
@@ -6,7 +6,6 @@use crate ::{ bindings, - str::CStr , types::{ARef ,Opaque }, };use core::{fmt, marker::PhantomData , ptr};
@@ -219,12 +218,6 @@ pub fn fwnode(&self) -> Option<&property::FwNode> {// defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`. Some (unsafe { &*fwnode_handle.cast () }) } - -/// Checks if property is present or not. -pub fn property_present (&self, name: &CStr ) ->bool { -// SAFETY: By the invariant of `CStr`, `name` is null-terminated. -unsafe { bindings::device_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } - } }// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
rust/kernel/device/property.rs +7 -0
@@ -8,6 +8,7 @@use crate ::{ bindings, + str::CStr , types::{ARef ,Opaque }, };
@@ -55,6 +56,12 @@ unsafe fn from_raw(raw: *mut bindings::fwnode_handle) -> ARef<Self> {pub (crate )fn as_raw (&self) -> *mut bindings::fwnode_handle { self.0 .get () } + +/// Checks if property is present or not. +pub fn property_present (&self, name: &CStr ) ->bool { +// SAFETY: By the invariant of `CStr`, `name` is null-terminated. +unsafe { bindings::fwnode_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } + } }// SAFETY: Instances of `FwNode` are always reference-counted.
Signature · 1 line
2.49.0
Danilo Krummrich
maintainerRe: [PATCH v8 3/9] rust: device: Move property_present() to FwNode
(+Viresh, FYI)
Quoted 83 lines · Remo Senekowitsch
The new FwNode abstraction will be used for accessing all device properties.
It would be possible to duplicate the methods on the device itself, but since some of the methods on Device would have different type sigatures as the ones on FwNode, this would only lead to inconsistency and confusion. For this reason,
property_presentis removed from Device and existing users are updated.Signed-off-by Remo Senekowitsch <[email protected]>--- drivers/cpufreq/rcpufreq_dt.rs | 3 ++- rust/kernel/device.rs | 7 ------- rust/kernel/device/property.rs | 7 +++++++ 3 files changed, 9 insertions(+), 8 deletions(-)drivers/cpufreq/rcpufreq_dt.rs +2
-1@@ -20,7 +20,8 @@/// Finds exact supply name from the OF node. fn find_supply_name_exact (dev: &Device , name: &str ) ->Option <CString > {let prop_name =CString ::try_from_fmt (fmt! ("{}-supply" , name)).ok ()?; - dev.property_present (&prop_name) + dev.fwnode ()? + .property_present (&prop_name) .then (||CString ::try_from_fmt (fmt! ("{name}" )).ok ()) .flatten () }rust/kernel/device.rs +0
-7@@ -6,7 +6,6 @@use crate ::{ bindings, - str::CStr , types::{ARef ,Opaque }, };use core::{fmt, marker::PhantomData , ptr};@@ -219,12 +218,6 @@ pub fn fwnode(&self) -> Option<&property::FwNode> {// defined as a `#[repr(transparent)]` wrapper around `fwnode_handle`. Some (unsafe { &*fwnode_handle.cast () }) } - -/// Checks if property is present or not. -pub fn property_present (&self, name: &CStr ) ->bool { -// SAFETY: By the invariant of `CStr`, `name` is null-terminated. -unsafe { bindings::device_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } - } }// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic rust/kernel/device/property.rs +7
-0@@ -8,6 +8,7 @@use crate ::{ bindings, + str::CStr , types::{ARef ,Opaque }, };@@ -55,6 +56,12 @@ unsafe fn from_raw(raw: *mut bindings::fwnode_handle) -> ARef<Self> {pub (crate )fn as_raw (&self) -> *mut bindings::fwnode_handle { self.0 .get () } + +/// Checks if property is present or not. +pub fn property_present (&self, name: &CStr ) ->bool { +// SAFETY: By the invariant of `CStr`, `name` is null-terminated. +unsafe { bindings::fwnode_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } + } }// SAFETY: Instances of `FwNode` are always reference-counted. Signature · 1 line
2.49.0
Re: [PATCH v8 3/9] rust: device: Move property_present() to FwNode
Quoted 1 line · Danilo Krummrich
(+Viresh, FYI)
Thanks Danilo.
Quoted 10 lines · Remo Senekowitsch
Quoted 9 lines
The new FwNode abstraction will be used for accessing all device properties.
It would be possible to duplicate the methods on the device itself, but since some of the methods on Device would have different type sigatures as the ones on FwNode, this would only lead to inconsistency and confusion. For this reason,
property_presentis removed from Device and existing users are updated.
Quoted 6 lines
Quoted 6 lines
Signed-off-by Remo Senekowitsch <[email protected]>--- drivers/cpufreq/rcpufreq_dt.rs | 3 ++- rust/kernel/device.rs | 7 ------- rust/kernel/device/property.rs | 7 +++++++ 3 files changed, 9 insertions(+), 8 deletions(-)
Signature · 1 line
viresh
PATCH v8 4/9 rust: device: Enable printing fwnode name and path
In reply to Remo SenekowitschAdd two new public methods display_name and display_path to FwNode. They can be used by driver authors for logging purposes. In addition, they will be used by core property abstractions for automatic logging, for example when a driver attempts to read a required but missing property.
--- rust/kernel/device/property.rs | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+)
rust/kernel/device/property.rs +76 -0
@@ -57,6 +57,32 @@ pub(crate) fn as_raw(&self) -> *mut bindings::fwnode_handle { self.0 .get () } +/// Returns an object that implements [`Display`](core::fmt::Display) for +/// printing the name of a node. +/// +/// This is an alternative to the default `Display` implementation, which +/// prints the full path. +pub fn display_name (&self) ->impl core::fmt::Display + '_ { +struct FwNodeDisplayName <'a>(&'aFwNode ); + +impl core::fmt::Display for FwNodeDisplayName <'_> { +fn fmt (&self, f: &mut core::fmt::Formatter <'_>) -> core::fmt::Result { +// SAFETY: `self` is valid by its type invariant. +let name =unsafe { bindings::fwnode_get_name (self.0 .as_raw ()) }; +if name.is_null () { +return Ok (()); + } +// SAFETY: +// - `fwnode_get_name` returns null or a valid C string. +// - `name` was checked to be non-null. +let name =unsafe {CStr ::from_char_ptr (name) }; +write! (f,"{name}" ) + } + } + +FwNodeDisplayName (self) + } +/// Checks if property is present or not. pub fn property_present (&self, name: &CStr ) ->bool {// SAFETY: By the invariant of `CStr`, `name` is null-terminated.
@@ -78,3 +104,53 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {unsafe { bindings::fwnode_handle_put (obj.cast ().as_ptr ()) } } } + +enum Node <'a> { +Borrowed (&'aFwNode ), +Owned (ARef <FwNode >), +} + +impl core::fmt::Display for FwNode { +fn fmt (&self, f: &mut core::fmt::Formatter <'_>) -> core::fmt::Result { +// The logic here is the same as the one in lib/vsprintf.c +// (fwnode_full_name_string). + +// SAFETY: `self.as_raw()` is valid by its type invariant. +let num_parents =unsafe { bindings::fwnode_count_parents (self.as_raw ()) }; + +for depthin (0 ..=num_parents).rev () { +let fwnode =if depth ==0 { +Node ::Borrowed (self) + }else { +// SAFETY: `self.as_raw()` is valid. +let ptr =unsafe { bindings::fwnode_get_nth_parent (self.as_raw (), depth) }; +// SAFETY: +// - The depth passed to `fwnode_get_nth_parent` is +// within the valid range, so the returned pointer is +// not null. +// - The reference count was incremented by +// `fwnode_get_nth_parent`. +// - That increment is relinquished to +// `FwNode::from_raw`. +Node ::Owned (unsafe {FwNode ::from_raw (ptr) }) + }; +// Take a reference to the owned or borrowed `FwNode`. +let fwnode: &FwNode =match &fwnode { +Node ::Borrowed (f) => f, +Node ::Owned (f) => f, + }; + +// SAFETY: `fwnode` is valid by its type invariant. +let prefix =unsafe { bindings::fwnode_get_name_prefix (fwnode.as_raw ()) }; +if !prefix.is_null () { +// SAFETY: `fwnode_get_name_prefix` returns null or a +// valid C string. +let prefix =unsafe {CStr ::from_char_ptr (prefix) }; +write! (f,"{prefix}" )?; + } +write! (f,"{}" , fwnode.display_name ())?; + } + +Ok (()) + } +}
Signature · 1 line
2.49.0
PATCH v8 5/9 rust: device: Introduce PropertyGuard
In reply to Remo SenekowitschThis abstraction is a way to force users to specify whether a property is supposed to be required or not. This allows us to move error logging of missing required properties into core, preventing a lot of boilerplate in drivers.
It will be used by upcoming methods for reading device properties.
--- rust/kernel/device/property.rs | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+)
rust/kernel/device/property.rs +59 -0
@@ -105,6 +105,65 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) { } } +/// A helper for reading device properties. +/// +/// Use [`Self::required_by`] if a missing property is considered a bug and +/// [`Self::optional`] otherwise. +/// +/// For convenience, [`Self::or`] and [`Self::or_default`] are provided. +pub struct PropertyGuard <'fwnode, 'name,T > { +/// The result of reading the property. + inner:Result <T >, +/// The fwnode of the property, used for logging in the "required" case. + fwnode: &'fwnodeFwNode , +/// The name of the property, used for logging in the "required" case. + name: &'nameCStr , +} + +impl <T >PropertyGuard <'_, '_,T > { +/// Access the property, indicating it is required. +/// +/// If the property is not present, the error is automatically logged. If a +/// missing property is not an error, use [`Self::optional`] instead. The +/// device is required to associate the log with it. +pub fn required_by (self, dev: &super ::Device ) ->Result <T > { +if self.inner.is_err () { +dev_err! ( + dev, +"{}: property '{}' is missing\n" , + self.fwnode, + self.name + ); + } + self.inner + } + +/// Access the property, indicating it is optional. +/// +/// In contrast to [`Self::required_by`], no error message is logged if +/// the property is not present. +pub fn optional (self) ->Option <T > { + self.inner.ok () + } + +/// Access the property or the specified default value. +/// +/// Do not pass a sentinel value as default to detect a missing property. +/// Use [`Self::required_by`] or [`Self::optional`] instead. +pub fn or (self, default:T ) ->T { + self.inner.unwrap_or (default) + } +} + +impl <T :Default >PropertyGuard <'_, '_,T > { +/// Access the property or a default value. +/// +/// Use [`Self::or`] to specify a custom default value. +pub fn or_default (self) ->T { + self.inner.unwrap_or_default () + } +} +enum Node <'a> {Borrowed (&'aFwNode ),Owned (ARef <FwNode >),
Signature · 1 line
2.49.0
PATCH v8 6/9 rust: device: Implement accessors for firmware properties
In reply to Remo SenekowitschAdd methods to FwNode for reading several firmware property types like strings, integers and arrays.
Most types are read with the generic property_read method. There are two exceptions:
* property_read_bool cannot fail, so the fallible function signature of property_read would not make sense for reading booleans.
* property_read_array_vec can fail because of a dynamic memory allocation. This error must be handled separately, leading to a different function signature than property_read.
The traits Property and PropertyInt drive the generic behavior of property_read. PropertyInt is necessary to associate specific integer types with the C functions to read them. While there is a C function to read integers of generic sizes called fwnode_property_read_int_array, it was preferred not to make this public.
--- rust/kernel/device/property.rs | 255 ++++++++++++++++++++++++++++++++- 1 file changed, 253 insertions(+), 2 deletions(-)
rust/kernel/device/property.rs +253 -2
@@ -4,11 +4,15 @@//! //! C header: [`include/linux/property.h`](srctree/include/linux/property.h) -use core::ptr; +use core::{mem::MaybeUninit , ptr};use crate ::{ + alloc::KVec , bindings, - str::CStr , + error::{to_result,Result }, + prelude::*, + private::Sealed , + str::{CStr ,CString }, types::{ARef ,Opaque }, };
@@ -88,6 +92,104 @@ pub fn property_present(&self, name: &CStr) -> bool {// SAFETY: By the invariant of `CStr`, `name` is null-terminated. unsafe { bindings::fwnode_property_present (self.as_raw ().cast_const (), name.as_char_ptr ()) } } + +/// Returns firmware property `name` boolean value. +pub fn property_read_bool (&self, name: &CStr ) ->bool { +// SAFETY: +// - `name` is non-null and null-terminated. +// - `self.as_raw()` is valid because `self` is valid. +unsafe { bindings::fwnode_property_read_bool (self.as_raw (), name.as_char_ptr ()) } + } + +/// Returns the index of matching string `match_str` for firmware string +/// property `name`. +pub fn property_match_string (&self, name: &CStr , match_str: &CStr ) ->Result <usize > { +// SAFETY: +// - `name` and `match_str` are non-null and null-terminated. +// - `self.as_raw` is valid because `self` is valid. +let ret =unsafe { + bindings::fwnode_property_match_string ( + self.as_raw (), + name.as_char_ptr (), + match_str.as_char_ptr (), + ) + }; +to_result (ret)?; +Ok (retas usize ) + } + +/// Returns firmware property `name` integer array values in a [`KVec`]. +pub fn property_read_array_vec <'fwnode, 'name,T :PropertyInt >( + &'fwnode self, + name: &'nameCStr , + len:usize , + ) ->Result <PropertyGuard <'fwnode, 'name,KVec <T >>> { +let mut val:KVec <T > =KVec ::with_capacity (len,GFP_KERNEL )?; + +let res =T ::read_array_from_fwnode_property (self, name, val.spare_capacity_mut ()); +let res =match res { +Ok (_) => { +// SAFETY: +// - `len` is equal to `val.capacity - val.len`, because +// `val.capacity` is `len` and `val.len` is zero. +// - All elements within the interval [`0`, `len`) were initialized +// by `read_array_from_fwnode_property`. +unsafe { val.inc_len (len) } +Ok (val) + } +Err (e) =>Err (e), + }; +Ok (PropertyGuard { + inner: res, + fwnode: self, + name, + }) + } + +/// Returns integer array length for firmware property `name`. +pub fn property_count_elem <T :PropertyInt >(&self, name: &CStr ) ->Result <usize > { +T ::read_array_len_from_fwnode_property (self, name) + } + +/// Returns the value of firmware property `name`. +/// +/// This method is generic over the type of value to read. The types that +/// can be read are strings, integers and arrays of integers. +/// +/// Reading a [`KVec`] of integers is done with the separate +/// method [`Self::property_read_array_vec`], because it takes an +/// additional `len` argument. +/// +/// Reading a boolean is done with the separate method +/// [`Self::property_read_bool`], because this operation is infallible. +/// +/// For more precise documentation about what types can be read, see +/// the [implementors of Property][Property#implementors] and [its +/// implementations on foreign types][Property#foreign-impls]. +/// +/// # Examples +/// +/// ``` +/// # use kernel::{c_str, device::{Device, property::FwNode}, str::CString}; +/// fn examples(dev: &Device) -> Result { +/// let fwnode = dev.fwnode().ok_or(ENOENT)?; +/// let b: u32 = fwnode.property_read(c_str!("some-number")).required_by(dev)?; +/// if let Some(s) = fwnode.property_read::<CString>(c_str!("some-str")).optional() { +/// // ... +/// } +/// Ok(()) +/// } +/// ``` +pub fn property_read <'fwnode, 'name,T :Property >( + &'fwnode self, + name: &'nameCStr , + ) ->PropertyGuard <'fwnode, 'name,T > { +PropertyGuard { + inner:T ::read_from_fwnode_property (self, name), + fwnode: self, + name, + } + } }// SAFETY: Instances of `FwNode` are always reference-counted.
@@ -105,6 +207,155 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) { } } +/// Implemented for types that can be read as properties. +/// +/// This is implemented for strings, integers and arrays of integers. It's used +/// to make [`FwNode::property_read`] generic over the type of property being +/// read. There are also two dedicated methods to read other types, because they +/// require more specialized function signatures: +/// - [`property_read_bool`](FwNode::property_read_bool) +/// - [`property_read_array_vec`](FwNode::property_read_array_vec) +/// +/// It must be public, because it appears in the signatures of other public +/// functions, but its methods shouldn't be used outside the kernel crate. +pub trait Property :Sized +Sealed { +/// Used to make [`FwNode::property_read`] generic. +fn read_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <Self >; +} + +impl Sealed for CString {} + +impl Property for CString { +fn read_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <Self > { +let mut str: *mut u8 = ptr::null_mut (); +let pstr: *mut _ = &mut str; + +// SAFETY: +// - `name` is non-null and null-terminated. +// - `fwnode.as_raw` is valid because `fwnode` is valid. +let ret =unsafe { + bindings::fwnode_property_read_string (fwnode.as_raw (), name.as_char_ptr (), pstr.cast ()) + }; +to_result (ret)?; + +// SAFETY: +// - `pstr` is a valid pointer to a NUL-terminated C string. +// - It is valid for at least as long as `fwnode`, but it's only used +// within the current function. +// - The memory it points to is not mutated during that time. +let str =unsafe {CStr ::from_char_ptr (*pstr) }; +Ok (str.try_into ()?) + } +} + +/// Implemented for all integers that can be read as properties. +/// +/// This helper trait is needed on top of the existing [`Property`] +/// trait to associate the integer types of various sizes with their +/// corresponding `fwnode_property_read_*_array` functions. +/// +/// It must be public, because it appears in the signatures of other public +/// functions, but its methods shouldn't be used outside the kernel crate. +pub trait PropertyInt :Copy +Sealed { +/// Reads a property array. +fn read_array_from_fwnode_property <'a>( + fwnode: &FwNode , + name: &CStr , + out: &'amut [MaybeUninit <Self >], + ) ->Result <&'amut [Self ]>; + +/// Reads the length of a property array. +fn read_array_len_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <usize >; +} +// This macro generates implementations of the traits `Property` and +// `PropertyInt` for integers of various sizes. Its input is a list +// of pairs separated by commas. The first element of the pair is the +// type of the integer, the second one is the name of its corresponding +// `fwnode_property_read_*_array` function. +macro_rules! impl_property_for_int { + ($($int:ty: $f:ident),* $(,)?) => { $( +impl Sealed for $int {} +impl <const N :usize >Sealed for [$int;N ] {} + +impl PropertyInt for $int { +fn read_array_from_fwnode_property <'a>( + fwnode: &FwNode , + name: &CStr , + out: &'amut [MaybeUninit <Self >], + ) ->Result <&'amut [Self ]> { +// SAFETY: +// - `fwnode`, `name` and `out` are all valid by their type +// invariants. +// - `out.len()` is a valid bound for the memory pointed to by +// `out.as_mut_ptr()`. +// CAST: It's ok to cast from `*mut MaybeUninit<$int>` to a +// `*mut $int` because they have the same memory layout. +let ret =unsafe { +bindings ::$f( + fwnode.as_raw (), + name.as_char_ptr (), + out.as_mut_ptr ().cast (), + out.len (), + ) + }; +to_result (ret)?; +// SAFETY: Transmuting from `&'a mut [MaybeUninit<Self>]` to +// `&'a mut [Self]` is sound, because the previous call to a +// `fwnode_property_read_*_array` function (which didn't fail) +// fully initialized the slice. +Ok (unsafe { core::mem::transmute (out) }) + } + +fn read_array_len_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <usize > { +// SAFETY: +// - `fwnode` and `name` are valid by their type invariants. +// - It's ok to pass a null pointer to the +// `fwnode_property_read_*_array` functions if `nval` is zero. +// This will return the length of the array. +let ret =unsafe { +bindings ::$f( + fwnode.as_raw (), + name.as_char_ptr (), + ptr::null_mut (), +0 , + ) + }; +to_result (ret)?; +Ok (retas usize ) + } + } + +impl Property for $int { +fn read_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <Self > { +let val: [_ ;1 ] = <[$int;1 ]>::read_from_fwnode_property (fwnode, name)?; +Ok (val[0 ]) + } + } + +impl <const N :usize >Property for [$int;N ] { +fn read_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <Self > { +let mut val: [MaybeUninit <$int>;N ] = [const {MaybeUninit ::uninit () };N ]; + + <$int>::read_array_from_fwnode_property (fwnode, name, &mut val)?; + +// SAFETY: `val` is always initialized when +// `fwnode_property_read_*_array` is successful. +Ok (val.map (|v|unsafe { v.assume_init () })) + } + } + )* }; +} +impl_property_for_int! { +u8 : fwnode_property_read_u8_array, +u16 : fwnode_property_read_u16_array, +u32 : fwnode_property_read_u32_array, +u64 : fwnode_property_read_u64_array, +i8 : fwnode_property_read_u8_array, +i16 : fwnode_property_read_u16_array, +i32 : fwnode_property_read_u32_array, +i64 : fwnode_property_read_u64_array, +} +/// A helper for reading device properties. /// /// Use [`Self::required_by`] if a missing property is considered a bug and
Signature · 1 line
2.49.0
PATCH v8 7/9 rust: device: Add child accessor and iterator
In reply to Remo SenekowitschAllow Rust drivers to access children of a fwnode either by name or by iterating over all of them.
In C, there is the function fwnode_get_next_child_node for iteration and the macro fwnode_for_each_child_node that helps with handling the pointers. Instead of a macro, a native iterator is used in Rust such that regular for-loops can be used.
--- rust/kernel/device/property.rs | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+)
rust/kernel/device/property.rs +56 -0
@@ -190,6 +190,62 @@ pub fn property_read<'fwnode, 'name, T: Property>( name, } } + +/// Returns first matching named child node handle. +pub fn get_child_by_name (&self, name: &CStr ) ->Option <ARef <Self >> { +// SAFETY: `self` and `name` are valid by their type invariants. +let child = +unsafe { bindings::fwnode_get_named_child_node (self.as_raw (), name.as_char_ptr ()) }; +if child.is_null () { +return None ; + } +// SAFETY: +// - `fwnode_get_named_child_node` returns a pointer with its refcount +// incremented. +// - That increment is relinquished, i.e. the underlying object is not +// used anymore except via the newly created `ARef`. +Some (unsafe {Self ::from_raw (child) }) + } + +/// Returns an iterator over a node's children. +pub fn children <'a>(&'a self) ->impl Iterator <Item =ARef <FwNode >> + 'a { +let mut prev:Option <ARef <FwNode >> =None ; + + core::iter::from_fn (move || { +let prev_ptr =match prev.take () { +None => ptr::null_mut (), +Some (prev) => { +// We will pass `prev` to `fwnode_get_next_child_node`, +// which decrements its refcount, so we use +// `ARef::into_raw` to avoid decrementing the refcount +// twice. +let prev =ARef ::into_raw (prev); + prev.as_ptr ().cast () + } + }; +// SAFETY: +// - `self.as_raw()` is valid by its type invariant. +// - `prev_ptr` may be null, which is allowed and corresponds to +// getting the first child. Otherwise, `prev_ptr` is valid, as it +// is the stored return value from the previous invocation. +// - `prev_ptr` has its refount incremented. +// - The increment of `prev_ptr` is relinquished, i.e. the +// underlying object won't be used anymore. +let next =unsafe { bindings::fwnode_get_next_child_node (self.as_raw (), prev_ptr) }; +if next.is_null () { +return None ; + } +// SAFETY: +// - `next` is valid because `fwnode_get_next_child_node` returns a +// pointer with its refcount incremented. +// - That increment is relinquished, i.e. the underlying object +// won't be used anymore, except via the newly created +// `ARef<Self>`. +let next =unsafe {FwNode ::from_raw (next) }; + prev =Some (next.clone ()); +Some (next) + }) + } }// SAFETY: Instances of `FwNode` are always reference-counted.
Signature · 1 line
2.49.0
PATCH v8 8/9 rust: device: Add property_get_reference_args
In reply to Remo SenekowitschAllow Rust code to read reference args from device properties. The wrapper type FwNodeReferenceArgs allows callers to access the buffer of read args safely.
--- rust/kernel/device/property.rs | 67 ++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+)
rust/kernel/device/property.rs +67 -0
@@ -246,6 +246,64 @@ pub fn children<'a>(&'a self) -> impl Iterator<Item = ARef<FwNode>> + 'a {Some (next) }) } + +/// Finds a reference with arguments. +pub fn property_get_reference_args ( + &self, + prop: &CStr , + nargs:NArgs <'_>, + index:u32 , + ) ->Result <FwNodeReferenceArgs > { +let mut out_args =FwNodeReferenceArgs ::default (); + +let (nargs_prop, nargs) =match nargs { +NArgs ::Prop (nargs_prop) => (nargs_prop.as_char_ptr (),0 ), +NArgs ::N (nargs) => (ptr::null (), nargs), + }; + +// SAFETY: +// - `self.0.get()` is valid. +// - `prop.as_char_ptr()` is valid and zero-terminated. +// - `nargs_prop` is valid and zero-terminated if `nargs` +// is zero, otherwise it is allowed to be a null-pointer. +let ret =unsafe { + bindings::fwnode_property_get_reference_args ( + self.0 .get (), + prop.as_char_ptr (), + nargs_prop, + nargs, + index, + &mut out_args.0 , + ) + }; +to_result (ret)?; + +Ok (out_args) + } +} + +/// The return value of [`FwNode::property_get_reference_args`]. +#[repr(transparent)] +#[derive( Copy , Clone , Default )] +pub struct FwNodeReferenceArgs (bindings::fwnode_reference_args ); + +impl FwNodeReferenceArgs { +/// Returns the slice of reference arguments. +pub fn as_slice (&self) -> &[u64 ] { +// SAFETY: As per the safety invariant of `FwNodeReferenceArgs`, `nargs` +// is the number of elements in `args` that is valid. +unsafe { core::slice::from_raw_parts (self.0 .args.as_ptr (), self.0 .nargsas usize ) } + } + +/// Returns the number of reference arguments. +pub fn len (&self) ->usize { + self.0 .nargsas usize + } + +/// Returns `true` if there are no reference arguments. +pub fn is_empty (&self) ->bool { + self.0 .nargs ==0 + } }// SAFETY: Instances of `FwNode` are always reference-counted.
@@ -412,6 +470,15 @@ fn read_from_fwnode_property(fwnode: &FwNode, name: &CStr) -> Result<Self> { i64: fwnode_property_read_u64_array, } +/// The number of arguments of a reference. +pub enum NArgs <'a> { +/// The name of the property of the reference indicating the number of +/// arguments. +Prop (&'aCStr ), +/// The known number of arguments. +N (u32 ), +} +/// A helper for reading device properties. /// /// Use [`Self::required_by`] if a missing property is considered a bug and
Signature · 1 line
2.49.0
PATCH v8 9/9 samples: rust: platform: Add property read examples
In reply to Remo SenekowitschAdd some example usage of the device property read methods for DT/ACPI/swnode properties.
--- drivers/of/unittest-data/tests-platform.dtsi | 3 + samples/rust/rust_driver_platform.rs | 60 +++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-)
drivers/of/unittest-data/tests-platform.dtsi +3 -0
@@ -37,6 +37,9 @@ dev@100 { test-device@2 { compatible = "test,rust-device"; reg = <0x2>; + + test,u32-prop = <0xdeadbeef>; + test,i16-array = /bits/ 16 <1 2 (-3) (-4)>; }; };
samples/rust/rust_driver_platform.rs +59 -1
78 lines not on this page · raw message
Signature · 1 line
2.49.0
Danilo Krummrich
maintainerHi Remo,
On Wed, Jun 11, 2025 at 12:28:59PM +0200, Remo Senekowitsch wrote:
I went through the single patches and found the following issues.
Quoted 3 lines
Remo Senekowitsch (9):
rust: device: Create FwNode abstraction for accessing device
properties
This patch creates a warning for FwNode::from_raw() to be unused, and needs this fix:
rust/kernel/device/property.rs +1 -0
@@ -37,6 +37,7 @@ impl FwNode {/// - They relinquish that increment. That is, if there is only one /// increment, callers must not use the underlying object anymore -- it is /// only safe to do so via the newly created `ARef<FwNode>`. +#[expect(dead_code)] unsafe fn from_raw (raw: *mut bindings::fwnode_handle ) ->ARef <Self > {// SAFETY: As per the safety requirements of this function: // - `NonNull::new_unchecked`:
Quoted 3 lines
rust: device: Enable accessing the FwNode of a Device
rust: device: Moveproperty_present()to FwNode
rust: device: Enable printing fwnode name and path
This patch starts using FwNode::from_raw() and hence needs:
rust/kernel/device/property.rs +0 -1
@@ -38,7 +38,6 @@ impl FwNode {/// - They relinquish that increment. That is, if there is only one /// increment, callers must not use the underlying object anymore -- it is /// only safe to do so via the newly created `ARef<FwNode>`. -#[expect(dead_code)] unsafe fn from_raw (raw: *mut bindings::fwnode_handle ) ->ARef <Self > {// SAFETY: As per the safety requirements of this function: // - `NonNull::new_unchecked`:
Quoted 1 line
rust: device: Introduce PropertyGuard
This patch fails to compile (print macros are not included) and needs the following change.
rust/kernel/device/property.rs +1 -0
@@ -8,6 +8,7 @@use crate ::{ bindings, + prelude::*, str::CStr , types::{ARef ,Opaque }, };
Quoted 1 line
rust: device: Implement accessors for firmware properties
This patch also fails to compile, throws a warning about transmute() and hence needs the following change.
rust/kernel/device/property.rs +2 -2
@@ -6,12 +6,12 @@use core::{mem::MaybeUninit , ptr}; +use super ::private::Sealed ;use crate ::{ alloc::KVec , bindings, error::{to_result,Result }, prelude::*, - private::Sealed , str::{CStr ,CString }, types::{ARef ,Opaque }, };
@@ -303,7 +303,7 @@ fn read_array_from_fwnode_property<'a>(// `&'a mut [Self]` is sound, because the previous call to a // `fwnode_property_read_*_array` function (which didn't fail) // fully initialized the slice. -Ok (unsafe { core::mem::transmute (out) }) +Ok (unsafe { core::mem::transmute ::<&mut [MaybeUninit <Self >], &mut [Self ]>(out) }) }fn read_array_len_from_fwnode_property (fwnode: &FwNode , name: &CStr ) ->Result <usize > {
Quoted 3 lines
rust: device: Add child accessor and iterator
rust: device: Addproperty_get_reference_args
samples: rust: platform: Add property read examples
In general, please make sure to compile test every patch of a series individually, not only the entire series.
Otherwise the series looks good. Given that the required fixes are minor, there is no need for you to send a new version, I can apply those changes why I apply the patch series.
- Danilo
Danilo Krummrich
maintainerQuoted 9 lines · Remo Senekowitsch
Remo Senekowitsch (9):
rust: device: Create FwNode abstraction for accessing device
properties
rust: device: Enable accessing the FwNode of a Device
rust: device: Moveproperty_present()to FwNode
rust: device: Enable printing fwnode name and path
rust: device: Introduce PropertyGuard
rust: device: Implement accessors for firmware properties
samples: rust: platform: Add property read examples
Applied to driver-core-testing, thanks!
Once the patches passed 0-day testing they will be merged into driver-core-next.
Quoted 2 lines
rust: device: Add child accessor and iterator
rust: device: Addproperty_get_reference_args
I did drop those two patches for now, because:
(1) They're basically dead code.
(2) It seems that FwNode::property_get_reference_args() leaks a struct fwnode_handle reference. property_get_reference_args() explicitly says that the caller is responsible "for calling fwnode_handle_put() on the returned @args->fwnode pointer", which doesn't seem to happen.
Can you please fix the leak and resend those two patches with an additional one that adds a sample usage of the introduced methods to the platform sample driver?
Quoted 22 lines · Danilo Krummrich
Quoted 9 lines · Remo Senekowitsch
Remo Senekowitsch (9):
rust: device: Create FwNode abstraction for accessing device
properties
rust: device: Enable accessing the FwNode of a Device
rust: device: Moveproperty_present()to FwNode
rust: device: Enable printing fwnode name and path
rust: device: Introduce PropertyGuard
rust: device: Implement accessors for firmware properties
samples: rust: platform: Add property read examplesApplied to driver-core-testing, thanks!
Once the patches passed 0-day testing they will be merged into driver-core-next.
Quoted 2 lines
rust: device: Add child accessor and iterator
rust: device: Addproperty_get_reference_argsI did drop those two patches for now, because:
(1) They're basically dead code.
Quoted 8 lines
(2) It seems that
FwNode::property_get_reference_args()leaks a structfwnode_handlereference.property_get_reference_args()explicitly says that the caller is responsible "for callingfwnode_handle_put()on the returned @args->fwnode pointer", which doesn't seem to happen.Can you please fix the leak and resend those two patches with an additional one that adds a sample usage of the introduced methods to the platform sample driver?
Alright, thanks. I suppose that should be a new patch series, with a new title and starting at v1 ..?
Danilo Krummrich
maintainerQuoted 28 lines · Remo Senekowitsch
Quoted 27 lines · Danilo Krummrich
Quoted 9 lines · Remo Senekowitsch
Remo Senekowitsch (9):
rust: device: Create FwNode abstraction for accessing device
properties
rust: device: Enable accessing the FwNode of a Device
rust: device: Moveproperty_present()to FwNode
rust: device: Enable printing fwnode name and path
rust: device: Introduce PropertyGuard
rust: device: Implement accessors for firmware properties
samples: rust: platform: Add property read examplesApplied to driver-core-testing, thanks!
Once the patches passed 0-day testing they will be merged into driver-core-next.
Quoted 2 lines
rust: device: Add child accessor and iterator
rust: device: Addproperty_get_reference_argsI did drop those two patches for now, because:
(1) They're basically dead code.
(2) It seems that
FwNode::property_get_reference_args()leaks a structfwnode_handlereference.property_get_reference_args()explicitly says that the caller is responsible "for callingfwnode_handle_put()on the returned @args->fwnode pointer", which doesn't seem to happen.
Quoted 6 lines
Quoted 3 lines
Can you please fix the leak and resend those two patches with an additional one that adds a sample usage of the introduced methods to the platform sample driver?
Alright, thanks. I suppose that should be a new patch series, with a new title and starting at v1 ..?
Yes, that's fine. Please make sure to mention that it's a follow-up of this series (ideally with a link).