* [PATCH v5 0/9] More Rust bindings for device property reads
@ 2025-05-20 20:00 Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 1/9] rust: device: Create FwNode abstraction for accessing device properties Remo Senekowitsch
` (8 more replies)
0 siblings, 9 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
changes in v5:
* Move rust/kernel/device/mod.rs back to rust/kernel/device.rs.
* Reword some commit messages.
* Leave property_present on Device for now to make merging easier.
* Cleanup Rust platform driver sample.
* Fix conflict with alloc-next tree.
* Improve documentation and safety comments.
* Seal the traits Property and PropertyInt.
* Move more logic into the PropertyInt trait, making its methods safe.
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: Add 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/of/unittest-data/tests-platform.dtsi | 3 +
rust/helpers/helpers.c | 1 +
rust/helpers/property.c | 8 +
rust/kernel/device.rs | 17 +
rust/kernel/device/property.rs | 578 +++++++++++++++++++
samples/rust/rust_driver_platform.rs | 60 +-
7 files changed, 667 insertions(+), 1 deletion(-)
create mode 100644 rust/helpers/property.c
create mode 100644 rust/kernel/device/property.rs
--
2.49.0
^ permalink raw reply [flat|nested] 22+ messages in thread
* [PATCH v5 1/9] rust: device: Create FwNode abstraction for accessing device properties
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device Remo Senekowitsch
` (7 subsequent siblings)
8 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
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.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
MAINTAINERS | 1 +
rust/helpers/helpers.c | 1 +
rust/helpers/property.c | 8 ++++++
rust/kernel/device.rs | 2 ++
rust/kernel/device/property.rs | 47 ++++++++++++++++++++++++++++++++++
5 files changed, 59 insertions(+)
create mode 100644 rust/helpers/property.c
create mode 100644 rust/kernel/device/property.rs
diff --git a/MAINTAINERS b/MAINTAINERS
index 3cbf9ac0d83f6..0b95c4b0f657e 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -7248,6 +7248,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
diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
index 1e7c84df72521..6aac840417648 100644
--- a/rust/helpers/helpers.c
+++ b/rust/helpers/helpers.c
@@ -25,6 +25,7 @@
#include "platform.c"
#include "pci.c"
#include "pid_namespace.c"
+#include "property.c"
#include "rbtree.c"
#include "rcu.c"
#include "refcount.c"
diff --git a/rust/helpers/property.c b/rust/helpers/property.c
new file mode 100644
index 0000000000000..08f68e2dac4a9
--- /dev/null
+++ b/rust/helpers/property.c
@@ -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);
+}
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 0353c5552769c..d8619d4485fb4 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -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
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
new file mode 100644
index 0000000000000..e75d55f5856cf
--- /dev/null
+++ b/rust/kernel/device/property.rs
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Unified device property interface.
+//!
+//! C header: [`include/linux/property.h`](srctree/include/linux/property.h)
+
+use core::ptr;
+
+use crate::{bindings, types::Opaque};
+
+/// A reference-counted fwnode_handle.
+///
+/// This structure represents the Rust abstraction for a
+/// C `struct fwnode_handle`. This implementation abstracts the usage of an
+/// already existing C `struct fwnode_handle` within Rust code that we get
+/// passed from the C side.
+///
+/// # Invariants
+///
+/// A `FwNode` instance represents a valid `struct fwnode_handle` created by the
+/// C portion of the kernel.
+///
+/// Instances of this type are always reference-counted, that is, a call to
+/// `fwnode_handle_get` ensures that the allocation remains valid at least until
+/// the matching call to `fwnode_handle_put`.
+#[repr(transparent)]
+pub struct FwNode(Opaque<bindings::fwnode_handle>);
+
+impl FwNode {
+ /// Obtain the raw `struct fwnode_handle *`.
+ pub(crate) fn as_raw(&self) -> *mut bindings::fwnode_handle {
+ self.0.get()
+ }
+}
+
+// SAFETY: Instances of `FwNode` are always reference-counted.
+unsafe impl crate::types::AlwaysRefCounted for FwNode {
+ fn inc_ref(&self) {
+ // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
+ unsafe { bindings::fwnode_handle_get(self.as_raw()) };
+ }
+
+ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
+ // SAFETY: The safety requirements guarantee that the refcount is non-zero.
+ unsafe { bindings::fwnode_handle_put(obj.cast().as_ptr()) }
+ }
+}
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 1/9] rust: device: Create FwNode abstraction for accessing device properties Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-21 11:59 ` Greg Kroah-Hartman
2025-05-20 20:00 ` [PATCH v5 3/9] rust: device: Add property_present() to FwNode Remo Senekowitsch
` (6 subsequent siblings)
8 siblings, 1 reply; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
Subsequent 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`.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device.rs | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index d8619d4485fb4..b4b7056eb80f8 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -186,6 +186,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.
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 3/9] rust: device: Add property_present() to FwNode
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 1/9] rust: device: Create FwNode abstraction for accessing device properties Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 4/9] rust: device: Enable printing fwnode name and path Remo Senekowitsch
` (5 subsequent siblings)
8 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
The new FwNode abstraction will be used for accessing all device
properties, so it must have the property_present method.
It's 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.
So, in the future, property_perent will be removed from Device. However,
there's a user about to be merged, so the method is left to make merging
easier.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device/property.rs | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index e75d55f5856cf..70593343bd811 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -6,7 +6,7 @@
use core::ptr;
-use crate::{bindings, types::Opaque};
+use crate::{bindings, str::CStr, types::Opaque};
/// A reference-counted fwnode_handle.
///
@@ -31,6 +31,12 @@ impl FwNode {
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.
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
` (2 preceding siblings ...)
2025-05-20 20:00 ` [PATCH v5 3/9] rust: device: Add property_present() to FwNode Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-21 12:02 ` Greg Kroah-Hartman
2025-05-21 12:38 ` Miguel Ojeda
2025-05-20 20:00 ` [PATCH v5 5/9] rust: device: Introduce PropertyGuard Remo Senekowitsch
` (4 subsequent siblings)
8 siblings, 2 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
Add 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.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
1 file changed, 72 insertions(+)
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index 70593343bd811..6ccc7947f9c31 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -32,6 +32,78 @@ 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.
+ pub fn display_name(&self) -> impl core::fmt::Display + '_ {
+ struct FwNodeDisplayName<'a>(&'a FwNode);
+
+ 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 and
+ // name is not null
+ let name = unsafe { CStr::from_char_ptr(name) };
+ write!(f, "{name}")
+ }
+ }
+
+ FwNodeDisplayName(self)
+ }
+
+ /// Returns an object that implements [`Display`](core::fmt::Display) for
+ /// printing the full path of a node.
+ pub fn display_path(&self) -> impl core::fmt::Display + '_ {
+ struct FwNodeDisplayPath<'a>(&'a FwNode);
+
+ impl core::fmt::Display for FwNodeDisplayPath<'_> {
+ 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.0.as_raw()` is valid by its type invariant
+ let num_parents = unsafe { bindings::fwnode_count_parents(self.0.as_raw()) };
+
+ for depth in (0..=num_parents).rev() {
+ let fwnode = if depth == 0 {
+ self.0.as_raw()
+ } else {
+ // SAFETY: `self.0.as_raw()` is valid
+ unsafe { bindings::fwnode_get_nth_parent(self.0.as_raw(), depth) }
+ };
+
+ // SAFETY: fwnode is valid, it is either `self.0.as_raw()` or
+ // the return value of `bindings::fwnode_get_nth_parent` which
+ // returns a valid pointer to a fwnode_handle if the provided
+ // depth is within the valid range, which we know to be true.
+ let prefix = unsafe { bindings::fwnode_get_name_prefix(fwnode) };
+ 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, "{}", self.0.display_name())?;
+
+ if depth != 0 {
+ // SAFETY: `fwnode` is valid, because `depth` is
+ // a valid depth of a parent of `self.0.as_raw()`.
+ // `fwnode_get_nth_parent` increments the refcount and
+ // we are responsible to decrement it.
+ unsafe { bindings::fwnode_handle_put(fwnode) }
+ }
+ }
+
+ Ok(())
+ }
+ }
+
+ FwNodeDisplayPath(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.
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 5/9] rust: device: Introduce PropertyGuard
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
` (3 preceding siblings ...)
2025-05-20 20:00 ` [PATCH v5 4/9] rust: device: Enable printing fwnode name and path Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 6/9] rust: device: Implement accessors for firmware properties Remo Senekowitsch
` (3 subsequent siblings)
8 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
This 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.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device/property.rs | 59 ++++++++++++++++++++++++++++++++++
1 file changed, 59 insertions(+)
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index 6ccc7947f9c31..59c61e2493831 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -123,3 +123,62 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
unsafe { bindings::fwnode_handle_put(obj.cast().as_ptr()) }
}
}
+
+/// 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: &'fwnode FwNode,
+ /// The name of the property, used for logging in the "required" case.
+ name: &'name CStr,
+}
+
+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.display_path(),
+ 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()
+ }
+}
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 6/9] rust: device: Implement accessors for firmware properties
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
` (4 preceding siblings ...)
2025-05-20 20:00 ` [PATCH v5 5/9] rust: device: Introduce PropertyGuard Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-21 21:34 ` kernel test robot
2025-05-22 20:23 ` Benno Lossin
2025-05-20 20:00 ` [PATCH v5 7/9] rust: device: Add child accessor and iterator Remo Senekowitsch
` (2 subsequent siblings)
8 siblings, 2 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
Add 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.
Co-developed-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device/property.rs | 253 ++++++++++++++++++++++++++++++++-
1 file changed, 251 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index 59c61e2493831..5e70db30adacf 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -4,9 +4,17 @@
//!
//! C header: [`include/linux/property.h`](srctree/include/linux/property.h)
-use core::ptr;
+use core::{mem::MaybeUninit, ptr};
-use crate::{bindings, str::CStr, types::Opaque};
+use crate::{
+ alloc::KVec,
+ bindings,
+ error::{to_result, Result},
+ prelude::*,
+ private::Sealed,
+ str::{CStr, CString},
+ types::Opaque,
+};
/// A reference-counted fwnode_handle.
///
@@ -109,6 +117,103 @@ 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(ret as usize)
+ }
+
+ /// Returns firmware property `name` integer array values in a KVec
+ pub fn property_read_array_vec<'fwnode, 'name, T: PropertyInt>(
+ &'fwnode self,
+ name: &'name CStr,
+ 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. Informally,
+ /// the types that can be read are booleans, strings, unsigned integers and
+ /// arrays of unsigned integers.
+ ///
+ /// Reading a [`KVec`] of integers is done with the separate
+ /// method [`Self::property_read_array_vec`], because it takes an
+ /// additional `len` argument.
+ ///
+ /// When reading a boolean, this method never fails. A missing property
+ /// is interpreted as `false`, whereas a present property is interpreted
+ /// as `true`.
+ ///
+ /// 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: &'name CStr,
+ ) -> PropertyGuard<'fwnode, 'name, T> {
+ PropertyGuard {
+ inner: T::read_from_fwnode_property(self, name),
+ fwnode: self,
+ name,
+ }
+ }
}
// SAFETY: Instances of `FwNode` are always reference-counted.
@@ -124,6 +229,150 @@ 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: &'a mut [MaybeUninit<Self>],
+ ) -> Result<&'a mut [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: &'a mut [MaybeUninit<Self>],
+ ) -> Result<&'a mut [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(ret as 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
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 7/9] rust: device: Add child accessor and iterator
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
` (5 preceding siblings ...)
2025-05-20 20:00 ` [PATCH v5 6/9] rust: device: Implement accessors for firmware properties Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 8/9] rust: device: Add property_get_reference_args Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 9/9] samples: rust: platform: Add property read examples Remo Senekowitsch
8 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
Allow 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.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device/property.rs | 79 +++++++++++++++++++++++++++++++++-
1 file changed, 78 insertions(+), 1 deletion(-)
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index 5e70db30adacf..0365c91a2e5b9 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -13,7 +13,7 @@
prelude::*,
private::Sealed,
str::{CStr, CString},
- types::Opaque,
+ types::{ARef, Opaque},
};
/// A reference-counted fwnode_handle.
@@ -35,6 +35,27 @@
pub struct FwNode(Opaque<bindings::fwnode_handle>);
impl FwNode {
+ /// # Safety
+ ///
+ /// Callers must ensure that:
+ /// - The reference count was incremented at least once.
+ /// - 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>`.
+ unsafe fn from_raw(raw: *mut bindings::fwnode_handle) -> ARef<Self> {
+ // SAFETY: As per the safety requirements of this function:
+ // - `NonNull::new_unchecked`:
+ // - `raw` is not null.
+ // - `ARef::from_raw`:
+ // - `raw` has an incremented refcount.
+ // - that increment is relinquished, i.e. it won't be decremented
+ // elsewhere.
+ // CAST: It is safe to cast from a `*mut fwnode_handle` to
+ // `*mut FwNode`, because `FwNode` is defined as a
+ // `#[repr(transparent)]` wrapper around `fwnode_handle`.
+ unsafe { ARef::from_raw(ptr::NonNull::new_unchecked(raw.cast())) }
+ }
+
/// Obtain the raw `struct fwnode_handle *`.
pub(crate) fn as_raw(&self) -> *mut bindings::fwnode_handle {
self.0.get()
@@ -214,6 +235,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.
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 8/9] rust: device: Add property_get_reference_args
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
` (6 preceding siblings ...)
2025-05-20 20:00 ` [PATCH v5 7/9] rust: device: Add child accessor and iterator Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 9/9] samples: rust: platform: Add property read examples Remo Senekowitsch
8 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
Allow Rust code to read reference args from device properties. The
wrapper type `FwNodeReferenceArgs` allows callers to access the buffer
of read args safely.
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
rust/kernel/device/property.rs | 68 ++++++++++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
index 0365c91a2e5b9..510903473695e 100644
--- a/rust/kernel/device/property.rs
+++ b/rust/kernel/device/property.rs
@@ -291,6 +291,65 @@ 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 `property_get_reference_args`.
+///
+/// - [`Device::property_get_reference_args`]
+/// - [`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.nargs as usize) }
+ }
+
+ /// Returns the number of reference arguments.
+ pub fn len(&self) -> usize {
+ self.0.nargs as 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.
@@ -450,6 +509,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(&'a CStr),
+ /// 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
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* [PATCH v5 9/9] samples: rust: platform: Add property read examples
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
` (7 preceding siblings ...)
2025-05-20 20:00 ` [PATCH v5 8/9] rust: device: Add property_get_reference_args Remo Senekowitsch
@ 2025-05-20 20:00 ` Remo Senekowitsch
8 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-20 20:00 UTC (permalink / raw)
To: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme,
Remo Senekowitsch
Cc: linux-kernel, devicetree, rust-for-linux
Add some example usage of the device property read methods for
DT/ACPI/swnode properties.
Co-developed-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
---
drivers/of/unittest-data/tests-platform.dtsi | 3 +
samples/rust/rust_driver_platform.rs | 60 +++++++++++++++++++-
2 files changed, 62 insertions(+), 1 deletion(-)
diff --git a/drivers/of/unittest-data/tests-platform.dtsi b/drivers/of/unittest-data/tests-platform.dtsi
index 4171f43cf01cc..50a51f38afb60 100644
--- a/drivers/of/unittest-data/tests-platform.dtsi
+++ b/drivers/of/unittest-data/tests-platform.dtsi
@@ -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)>;
};
};
diff --git a/samples/rust/rust_driver_platform.rs b/samples/rust/rust_driver_platform.rs
index 8b42b3cfb363a..c0abf78d0683b 100644
--- a/samples/rust/rust_driver_platform.rs
+++ b/samples/rust/rust_driver_platform.rs
@@ -2,7 +2,14 @@
//! Rust Platform driver sample.
-use kernel::{c_str, device::Core, of, platform, prelude::*, types::ARef};
+use kernel::{
+ c_str,
+ device::{self, Core},
+ of, platform,
+ prelude::*,
+ str::CString,
+ types::ARef,
+};
struct SampleDriver {
pdev: ARef<platform::Device>,
@@ -31,12 +38,63 @@ fn probe(
dev_info!(pdev.as_ref(), "Probed with info: '{}'.\n", info.0);
}
+ Self::properties_parse(pdev.as_ref())?;
+
let drvdata = KBox::new(Self { pdev: pdev.into() }, GFP_KERNEL)?;
Ok(drvdata.into())
}
}
+impl SampleDriver {
+ fn properties_parse(dev: &device::Device) -> Result {
+ let fwnode = dev.fwnode().ok_or(ENOENT)?;
+
+ if let Ok(idx) =
+ fwnode.property_match_string(c_str!("compatible"), c_str!("test,rust-device"))
+ {
+ dev_info!(dev, "matched compatible string idx = {}\n", idx);
+ }
+
+ let name = c_str!("compatible");
+ let prop = fwnode.property_read::<CString>(name).required_by(dev)?;
+ dev_info!(dev, "'{name}'='{prop:?}'\n");
+
+ let name = c_str!("test,bool-prop");
+ let prop = fwnode.property_read_bool(c_str!("test,bool-prop"));
+ dev_info!(dev, "'{name}'='{prop}'\n");
+
+ if fwnode.property_present(c_str!("test,u32-prop")) {
+ dev_info!(dev, "'test,u32-prop' is present\n");
+ }
+
+ let name = c_str!("test,u32-optional-prop");
+ let prop = fwnode.property_read::<u32>(name).or(0x12);
+ dev_info!(dev, "'{name}'='{prop:#x}' (default = 0x12)\n",);
+
+ // A missing required property will print an error. Discard the error to
+ // prevent properties_parse from failing in that case.
+ let name = c_str!("test,u32-required-prop");
+ let _ = fwnode.property_read::<u32>(name).required_by(dev);
+
+ let name = c_str!("test,u32-prop");
+ let prop: u32 = fwnode.property_read(name).required_by(dev)?;
+ dev_info!(dev, "'{name}'='{prop:#x}'\n");
+
+ let name = c_str!("test,i16-array");
+ let prop: [i16; 4] = fwnode.property_read(name).required_by(dev)?;
+ dev_info!(dev, "'{name}'='{prop:?}'\n");
+ let len = fwnode.property_count_elem::<u16>(name)?;
+ dev_info!(dev, "'{name}' length is {len}\n",);
+
+ let name = c_str!("test,i16-array");
+ let prop: KVec<i16> = fwnode.property_read_array_vec(name, 4)?.required_by(dev)?;
+ dev_info!(dev, "'{name}'='{prop:?}' (KVec)\n");
+
+ Ok(())
+ }
+}
+
impl Drop for SampleDriver {
fn drop(&mut self) {
dev_dbg!(self.pdev.as_ref(), "Remove Rust Platform driver sample.\n");
--
2.49.0
^ permalink raw reply related [flat|nested] 22+ messages in thread
* Re: [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device
2025-05-20 20:00 ` [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device Remo Senekowitsch
@ 2025-05-21 11:59 ` Greg Kroah-Hartman
2025-05-21 12:45 ` Remo Senekowitsch
0 siblings, 1 reply; 22+ messages in thread
From: Greg Kroah-Hartman @ 2025-05-21 11:59 UTC (permalink / raw)
To: Remo Senekowitsch
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Tue, May 20, 2025 at 10:00:17PM +0200, Remo Senekowitsch wrote:
> Subsequent 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`.
>
> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> ---
> rust/kernel/device.rs | 15 +++++++++++++++
> 1 file changed, 15 insertions(+)
>
> diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
> index d8619d4485fb4..b4b7056eb80f8 100644
> --- a/rust/kernel/device.rs
> +++ b/rust/kernel/device.rs
> @@ -186,6 +186,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()) };
Why isn't this calling __dev_fwnode_const()? And there's no way to just
use dev_fwnode() directly? Ugh, it's a macro...
thanks,
greg k-h
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-20 20:00 ` [PATCH v5 4/9] rust: device: Enable printing fwnode name and path Remo Senekowitsch
@ 2025-05-21 12:02 ` Greg Kroah-Hartman
2025-05-21 13:03 ` Remo Senekowitsch
2025-05-21 12:38 ` Miguel Ojeda
1 sibling, 1 reply; 22+ messages in thread
From: Greg Kroah-Hartman @ 2025-05-21 12:02 UTC (permalink / raw)
To: Remo Senekowitsch
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
> Add 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.
>
> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> ---
> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
> 1 file changed, 72 insertions(+)
>
> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
> index 70593343bd811..6ccc7947f9c31 100644
> --- a/rust/kernel/device/property.rs
> +++ b/rust/kernel/device/property.rs
> @@ -32,6 +32,78 @@ 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.
> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
> + struct FwNodeDisplayName<'a>(&'a FwNode);
> +
> + 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(());
So if there is no name, you are returning Ok()? Are you sure that's ok
to do? What will the result of the string look like then?
thanks,
greg k-h
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-20 20:00 ` [PATCH v5 4/9] rust: device: Enable printing fwnode name and path Remo Senekowitsch
2025-05-21 12:02 ` Greg Kroah-Hartman
@ 2025-05-21 12:38 ` Miguel Ojeda
1 sibling, 0 replies; 22+ messages in thread
From: Miguel Ojeda @ 2025-05-21 12:38 UTC (permalink / raw)
To: Remo Senekowitsch
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Greg Kroah-Hartman, Rafael J. Wysocki, Dirk Behme, linux-kernel,
devicetree, rust-for-linux
On Tue, May 20, 2025 at 10:01 PM Remo Senekowitsch <remo@buenzli.dev> wrote:
>
> + // SAFETY: self is valid by its type invariant
Please try to be consistent with the style of the rest of the code,
e.g. use Markdown in comments and end with a period (you do it in some
cases, but most are missing).
Thanks!
Cheers,
Miguel
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device
2025-05-21 11:59 ` Greg Kroah-Hartman
@ 2025-05-21 12:45 ` Remo Senekowitsch
0 siblings, 0 replies; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-21 12:45 UTC (permalink / raw)
To: Greg Kroah-Hartman
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Wed May 21, 2025 at 1:59 PM CEST, Greg Kroah-Hartman wrote:
> On Tue, May 20, 2025 at 10:00:17PM +0200, Remo Senekowitsch wrote:
>> Subsequent 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`.
>>
>> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
>> ---
>> rust/kernel/device.rs | 15 +++++++++++++++
>> 1 file changed, 15 insertions(+)
>>
>> diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
>> index d8619d4485fb4..b4b7056eb80f8 100644
>> --- a/rust/kernel/device.rs
>> +++ b/rust/kernel/device.rs
>> @@ -186,6 +186,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()) };
>
> Why isn't this calling __dev_fwnode_const()? And there's no way to just
> use dev_fwnode() directly? Ugh, it's a macro...
I think I had that in earlier versions of the patch series. There was
a helper to call the macro from Rust. It was pointed out that this is
not clearly expressing the intent - whether fwnode is mutated or not.
And I think someone said the fwnode can be mutated so __dev_fwnode() is
semantically correct.
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-21 12:02 ` Greg Kroah-Hartman
@ 2025-05-21 13:03 ` Remo Senekowitsch
2025-05-21 16:58 ` Greg Kroah-Hartman
0 siblings, 1 reply; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-21 13:03 UTC (permalink / raw)
To: Greg Kroah-Hartman
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Wed May 21, 2025 at 2:02 PM CEST, Greg Kroah-Hartman wrote:
> On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
>> Add 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.
>>
>> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
>> ---
>> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
>> 1 file changed, 72 insertions(+)
>>
>> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
>> index 70593343bd811..6ccc7947f9c31 100644
>> --- a/rust/kernel/device/property.rs
>> +++ b/rust/kernel/device/property.rs
>> @@ -32,6 +32,78 @@ 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.
>> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
>> + struct FwNodeDisplayName<'a>(&'a FwNode);
>> +
>> + 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(());
>
> So if there is no name, you are returning Ok()? Are you sure that's ok
> to do? What will the result of the string look like then?
In that case we're not writing anything to the formatter, which is
equivalent to an empty string. `Ok(())` means that writing succeeded.
I assumed that a valid node would always have a name. And we're
guaranteed to have a valid node. So I assumed this case would never
happen and didn't think too hard about it. But even if a valid node has
not name, empty string is probably the correct thing, right?
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-21 13:03 ` Remo Senekowitsch
@ 2025-05-21 16:58 ` Greg Kroah-Hartman
2025-05-21 18:36 ` Remo Senekowitsch
0 siblings, 1 reply; 22+ messages in thread
From: Greg Kroah-Hartman @ 2025-05-21 16:58 UTC (permalink / raw)
To: Remo Senekowitsch
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Wed, May 21, 2025 at 03:03:07PM +0200, Remo Senekowitsch wrote:
> On Wed May 21, 2025 at 2:02 PM CEST, Greg Kroah-Hartman wrote:
> > On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
> >> Add 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.
> >>
> >> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> >> ---
> >> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
> >> 1 file changed, 72 insertions(+)
> >>
> >> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
> >> index 70593343bd811..6ccc7947f9c31 100644
> >> --- a/rust/kernel/device/property.rs
> >> +++ b/rust/kernel/device/property.rs
> >> @@ -32,6 +32,78 @@ 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.
> >> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
> >> + struct FwNodeDisplayName<'a>(&'a FwNode);
> >> +
> >> + 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(());
> >
> > So if there is no name, you are returning Ok()? Are you sure that's ok
> > to do? What will the result of the string look like then?
>
> In that case we're not writing anything to the formatter, which is
> equivalent to an empty string. `Ok(())` means that writing succeeded.
>
> I assumed that a valid node would always have a name. And we're
> guaranteed to have a valid node. So I assumed this case would never
> happen and didn't think too hard about it. But even if a valid node has
> not name, empty string is probably the correct thing, right?
I don't know what this "name" is used for. An empty string might not be
what you want to use here, given that you could be naming something
based on it, right? fwnode_get_name() is used for many things,
including the detection if a name is not present at all, and if not,
then the code needs to clean up and abort.
So what exactly are you going to be using this for?
thanks,
greg k-h
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-21 16:58 ` Greg Kroah-Hartman
@ 2025-05-21 18:36 ` Remo Senekowitsch
2025-05-21 19:13 ` Danilo Krummrich
0 siblings, 1 reply; 22+ messages in thread
From: Remo Senekowitsch @ 2025-05-21 18:36 UTC (permalink / raw)
To: Greg Kroah-Hartman
Cc: Rob Herring, Saravana Kannan, Miguel Ojeda, Alex Gaynor,
Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Wed May 21, 2025 at 6:58 PM CEST, Greg Kroah-Hartman wrote:
> On Wed, May 21, 2025 at 03:03:07PM +0200, Remo Senekowitsch wrote:
>> On Wed May 21, 2025 at 2:02 PM CEST, Greg Kroah-Hartman wrote:
>> > On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
>> >> Add 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.
>> >>
>> >> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
>> >> ---
>> >> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
>> >> 1 file changed, 72 insertions(+)
>> >>
>> >> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
>> >> index 70593343bd811..6ccc7947f9c31 100644
>> >> --- a/rust/kernel/device/property.rs
>> >> +++ b/rust/kernel/device/property.rs
>> >> @@ -32,6 +32,78 @@ 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.
>> >> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
>> >> + struct FwNodeDisplayName<'a>(&'a FwNode);
>> >> +
>> >> + 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(());
>> >
>> > So if there is no name, you are returning Ok()? Are you sure that's ok
>> > to do? What will the result of the string look like then?
>>
>> In that case we're not writing anything to the formatter, which is
>> equivalent to an empty string. `Ok(())` means that writing succeeded.
>>
>> I assumed that a valid node would always have a name. And we're
>> guaranteed to have a valid node. So I assumed this case would never
>> happen and didn't think too hard about it. But even if a valid node has
>> not name, empty string is probably the correct thing, right?
>
> I don't know what this "name" is used for. An empty string might not be
> what you want to use here, given that you could be naming something
> based on it, right? fwnode_get_name() is used for many things,
> including the detection if a name is not present at all, and if not,
> then the code needs to clean up and abort.
>
> So what exactly are you going to be using this for?
Valid question... I'm not using it for anything. I was trying to match
the C API which has capabilities to print a fwnode's name and full path.
I think the format specifiers are %pfwP and %pfwf if I'm reading the
source correctly. It also looks to me like the C API for printing fwnode
names does the same thing - print nothing if the name is null. [1] [2]
[1] https://elixir.bootlin.com/linux/v6.14.7/source/lib/vsprintf.c#L2242
[2] https://elixir.bootlin.com/linux/v6.14.7/source/lib/vsprintf.c#L711
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-21 18:36 ` Remo Senekowitsch
@ 2025-05-21 19:13 ` Danilo Krummrich
2025-05-22 4:49 ` Greg Kroah-Hartman
0 siblings, 1 reply; 22+ messages in thread
From: Danilo Krummrich @ 2025-05-21 19:13 UTC (permalink / raw)
To: Remo Senekowitsch
Cc: Greg Kroah-Hartman, Rob Herring, Saravana Kannan, Miguel Ojeda,
Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Wed, May 21, 2025 at 08:36:10PM +0200, Remo Senekowitsch wrote:
> On Wed May 21, 2025 at 6:58 PM CEST, Greg Kroah-Hartman wrote:
> > On Wed, May 21, 2025 at 03:03:07PM +0200, Remo Senekowitsch wrote:
> >> On Wed May 21, 2025 at 2:02 PM CEST, Greg Kroah-Hartman wrote:
> >> > On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
> >> >> Add 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.
> >> >>
> >> >> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> >> >> ---
> >> >> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
> >> >> 1 file changed, 72 insertions(+)
> >> >>
> >> >> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
> >> >> index 70593343bd811..6ccc7947f9c31 100644
> >> >> --- a/rust/kernel/device/property.rs
> >> >> +++ b/rust/kernel/device/property.rs
> >> >> @@ -32,6 +32,78 @@ 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.
> >> >> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
> >> >> + struct FwNodeDisplayName<'a>(&'a FwNode);
> >> >> +
> >> >> + 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(());
> >> >
> >> > So if there is no name, you are returning Ok()? Are you sure that's ok
> >> > to do? What will the result of the string look like then?
> >>
> >> In that case we're not writing anything to the formatter, which is
> >> equivalent to an empty string. `Ok(())` means that writing succeeded.
> >>
> >> I assumed that a valid node would always have a name. And we're
> >> guaranteed to have a valid node. So I assumed this case would never
> >> happen and didn't think too hard about it. But even if a valid node has
> >> not name, empty string is probably the correct thing, right?
> >
> > I don't know what this "name" is used for. An empty string might not be
> > what you want to use here, given that you could be naming something
> > based on it, right? fwnode_get_name() is used for many things,
> > including the detection if a name is not present at all, and if not,
> > then the code needs to clean up and abort.
> >
> > So what exactly are you going to be using this for?
>
> Valid question... I'm not using it for anything.
You're using this in PropertyGuard::required_by(), where you use display_path()
and hence display_name() to print the node path in the error case.
So, currently, this is only used in the error case when a property of a given
node that is required by a driver can't be found.
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 6/9] rust: device: Implement accessors for firmware properties
2025-05-20 20:00 ` [PATCH v5 6/9] rust: device: Implement accessors for firmware properties Remo Senekowitsch
@ 2025-05-21 21:34 ` kernel test robot
2025-05-22 20:23 ` Benno Lossin
1 sibling, 0 replies; 22+ messages in thread
From: kernel test robot @ 2025-05-21 21:34 UTC (permalink / raw)
To: Remo Senekowitsch, Rob Herring, Saravana Kannan, Miguel Ojeda,
Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
Danilo Krummrich, Greg Kroah-Hartman, Rafael J. Wysocki,
Dirk Behme
Cc: llvm, oe-kbuild-all, linux-kernel, devicetree, rust-for-linux
Hi Remo,
kernel test robot noticed the following build errors:
[auto build test ERROR on rust/rust-next]
[also build test ERROR on driver-core/driver-core-testing driver-core/driver-core-next driver-core/driver-core-linus robh/for-next linus/master v6.15-rc7 next-20250521]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Remo-Senekowitsch/rust-device-Create-FwNode-abstraction-for-accessing-device-properties/20250521-040612
base: https://github.com/Rust-for-Linux/linux rust-next
patch link: https://lore.kernel.org/r/20250520200024.268655-7-remo%40buenzli.dev
patch subject: [PATCH v5 6/9] rust: device: Implement accessors for firmware properties
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20250522/202505220521.EPHBSqQg-lkp@intel.com/config)
compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff)
rustc: rustc 1.78.0 (9b00956e5 2024-04-29)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250522/202505220521.EPHBSqQg-lkp@intel.com/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202505220521.EPHBSqQg-lkp@intel.com/
All errors (new ones prefixed by >>):
>> error[E0432]: unresolved import `crate::private`
--> rust/kernel/device/property.rs:14:5
|
14 | private::Sealed,
| ^^^^^^^
| |
| unresolved import
| help: a similar path exists: `crate::device::private`
--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-21 19:13 ` Danilo Krummrich
@ 2025-05-22 4:49 ` Greg Kroah-Hartman
2025-05-22 5:47 ` Danilo Krummrich
0 siblings, 1 reply; 22+ messages in thread
From: Greg Kroah-Hartman @ 2025-05-22 4:49 UTC (permalink / raw)
To: Danilo Krummrich
Cc: Remo Senekowitsch, Rob Herring, Saravana Kannan, Miguel Ojeda,
Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Wed, May 21, 2025 at 09:13:08PM +0200, Danilo Krummrich wrote:
> On Wed, May 21, 2025 at 08:36:10PM +0200, Remo Senekowitsch wrote:
> > On Wed May 21, 2025 at 6:58 PM CEST, Greg Kroah-Hartman wrote:
> > > On Wed, May 21, 2025 at 03:03:07PM +0200, Remo Senekowitsch wrote:
> > >> On Wed May 21, 2025 at 2:02 PM CEST, Greg Kroah-Hartman wrote:
> > >> > On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
> > >> >> Add 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.
> > >> >>
> > >> >> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> > >> >> ---
> > >> >> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
> > >> >> 1 file changed, 72 insertions(+)
> > >> >>
> > >> >> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
> > >> >> index 70593343bd811..6ccc7947f9c31 100644
> > >> >> --- a/rust/kernel/device/property.rs
> > >> >> +++ b/rust/kernel/device/property.rs
> > >> >> @@ -32,6 +32,78 @@ 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.
> > >> >> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
> > >> >> + struct FwNodeDisplayName<'a>(&'a FwNode);
> > >> >> +
> > >> >> + 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(());
> > >> >
> > >> > So if there is no name, you are returning Ok()? Are you sure that's ok
> > >> > to do? What will the result of the string look like then?
> > >>
> > >> In that case we're not writing anything to the formatter, which is
> > >> equivalent to an empty string. `Ok(())` means that writing succeeded.
> > >>
> > >> I assumed that a valid node would always have a name. And we're
> > >> guaranteed to have a valid node. So I assumed this case would never
> > >> happen and didn't think too hard about it. But even if a valid node has
> > >> not name, empty string is probably the correct thing, right?
> > >
> > > I don't know what this "name" is used for. An empty string might not be
> > > what you want to use here, given that you could be naming something
> > > based on it, right? fwnode_get_name() is used for many things,
> > > including the detection if a name is not present at all, and if not,
> > > then the code needs to clean up and abort.
> > >
> > > So what exactly are you going to be using this for?
> >
> > Valid question... I'm not using it for anything.
>
> You're using this in PropertyGuard::required_by(), where you use display_path()
> and hence display_name() to print the node path in the error case.
>
> So, currently, this is only used in the error case when a property of a given
> node that is required by a driver can't be found.
And in that case, the "normal" dev_err() output should be all that is
needed here, not a "pretty printer" that might fail to document it at
all :)
thanks,
greg k-h
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 4/9] rust: device: Enable printing fwnode name and path
2025-05-22 4:49 ` Greg Kroah-Hartman
@ 2025-05-22 5:47 ` Danilo Krummrich
0 siblings, 0 replies; 22+ messages in thread
From: Danilo Krummrich @ 2025-05-22 5:47 UTC (permalink / raw)
To: Greg Kroah-Hartman
Cc: Remo Senekowitsch, Rob Herring, Saravana Kannan, Miguel Ojeda,
Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
Rafael J. Wysocki, Dirk Behme, linux-kernel, devicetree,
rust-for-linux
On Thu, May 22, 2025 at 06:49:15AM +0200, Greg Kroah-Hartman wrote:
> On Wed, May 21, 2025 at 09:13:08PM +0200, Danilo Krummrich wrote:
> > On Wed, May 21, 2025 at 08:36:10PM +0200, Remo Senekowitsch wrote:
> > > On Wed May 21, 2025 at 6:58 PM CEST, Greg Kroah-Hartman wrote:
> > > > On Wed, May 21, 2025 at 03:03:07PM +0200, Remo Senekowitsch wrote:
> > > >> On Wed May 21, 2025 at 2:02 PM CEST, Greg Kroah-Hartman wrote:
> > > >> > On Tue, May 20, 2025 at 10:00:19PM +0200, Remo Senekowitsch wrote:
> > > >> >> Add 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.
> > > >> >>
> > > >> >> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> > > >> >> ---
> > > >> >> rust/kernel/device/property.rs | 72 ++++++++++++++++++++++++++++++++++
> > > >> >> 1 file changed, 72 insertions(+)
> > > >> >>
> > > >> >> diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs
> > > >> >> index 70593343bd811..6ccc7947f9c31 100644
> > > >> >> --- a/rust/kernel/device/property.rs
> > > >> >> +++ b/rust/kernel/device/property.rs
> > > >> >> @@ -32,6 +32,78 @@ 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.
> > > >> >> + pub fn display_name(&self) -> impl core::fmt::Display + '_ {
> > > >> >> + struct FwNodeDisplayName<'a>(&'a FwNode);
> > > >> >> +
> > > >> >> + 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(());
> > > >> >
> > > >> > So if there is no name, you are returning Ok()? Are you sure that's ok
> > > >> > to do? What will the result of the string look like then?
> > > >>
> > > >> In that case we're not writing anything to the formatter, which is
> > > >> equivalent to an empty string. `Ok(())` means that writing succeeded.
> > > >>
> > > >> I assumed that a valid node would always have a name. And we're
> > > >> guaranteed to have a valid node. So I assumed this case would never
> > > >> happen and didn't think too hard about it. But even if a valid node has
> > > >> not name, empty string is probably the correct thing, right?
> > > >
> > > > I don't know what this "name" is used for. An empty string might not be
> > > > what you want to use here, given that you could be naming something
> > > > based on it, right? fwnode_get_name() is used for many things,
> > > > including the detection if a name is not present at all, and if not,
> > > > then the code needs to clean up and abort.
> > > >
> > > > So what exactly are you going to be using this for?
> > >
> > > Valid question... I'm not using it for anything.
> >
> > You're using this in PropertyGuard::required_by(), where you use display_path()
> > and hence display_name() to print the node path in the error case.
> >
> > So, currently, this is only used in the error case when a property of a given
> > node that is required by a driver can't be found.
>
> And in that case, the "normal" dev_err() output should be all that is
> needed here, not a "pretty printer" that might fail to document it at
> all :)
That's what the code does; PropertyGuard::required_by() uses dev_err!() to print
the string.
It's just that the functions from the C side that provide the strings are
abstracted in an implementation of core::fmt::Display for the FwNode, which is
the idiomatic way to abstract a string representations of a type.
And since Display::fmt() is fallible, we need to decide if NULL is a valid value
for fwnode_get_name() to return. The interface, i.e. struct fwnode_operations,
does not document this, but to me it seems that fwnode_get_name() returning a
NULL pointer is an error case.
^ permalink raw reply [flat|nested] 22+ messages in thread
* Re: [PATCH v5 6/9] rust: device: Implement accessors for firmware properties
2025-05-20 20:00 ` [PATCH v5 6/9] rust: device: Implement accessors for firmware properties Remo Senekowitsch
2025-05-21 21:34 ` kernel test robot
@ 2025-05-22 20:23 ` Benno Lossin
1 sibling, 0 replies; 22+ messages in thread
From: Benno Lossin @ 2025-05-22 20:23 UTC (permalink / raw)
To: Remo Senekowitsch, Rob Herring, Saravana Kannan, Miguel Ojeda,
Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Alice Ryhl, Trevor Gross,
Danilo Krummrich, Greg Kroah-Hartman, Rafael J. Wysocki,
Dirk Behme
Cc: linux-kernel, devicetree, rust-for-linux
On Tue May 20, 2025 at 10:00 PM CEST, Remo Senekowitsch wrote:
> Add 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.
>
> Co-developed-by: Rob Herring (Arm) <robh@kernel.org>
> Signed-off-by: Rob Herring (Arm) <robh@kernel.org>
> Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
> ---
> rust/kernel/device/property.rs | 253 ++++++++++++++++++++++++++++++++-
> 1 file changed, 251 insertions(+), 2 deletions(-)
I already like this design much better than your previous version.
I probably won't have the time to review the other patches, but one
thing that I notice was the lack of lists in `SAFETY` comments. If there
are multiple justification in a single `SAFETY` comment, we us a bullet
markdown list. (same for requirements in a `# Safety` section)
---
Cheers,
Benno
^ permalink raw reply [flat|nested] 22+ messages in thread
end of thread, other threads:[~2025-05-22 20:23 UTC | newest]
Thread overview: 22+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-05-20 20:00 [PATCH v5 0/9] More Rust bindings for device property reads Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 1/9] rust: device: Create FwNode abstraction for accessing device properties Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 2/9] rust: device: Enable accessing the FwNode of a Device Remo Senekowitsch
2025-05-21 11:59 ` Greg Kroah-Hartman
2025-05-21 12:45 ` Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 3/9] rust: device: Add property_present() to FwNode Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 4/9] rust: device: Enable printing fwnode name and path Remo Senekowitsch
2025-05-21 12:02 ` Greg Kroah-Hartman
2025-05-21 13:03 ` Remo Senekowitsch
2025-05-21 16:58 ` Greg Kroah-Hartman
2025-05-21 18:36 ` Remo Senekowitsch
2025-05-21 19:13 ` Danilo Krummrich
2025-05-22 4:49 ` Greg Kroah-Hartman
2025-05-22 5:47 ` Danilo Krummrich
2025-05-21 12:38 ` Miguel Ojeda
2025-05-20 20:00 ` [PATCH v5 5/9] rust: device: Introduce PropertyGuard Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 6/9] rust: device: Implement accessors for firmware properties Remo Senekowitsch
2025-05-21 21:34 ` kernel test robot
2025-05-22 20:23 ` Benno Lossin
2025-05-20 20:00 ` [PATCH v5 7/9] rust: device: Add child accessor and iterator Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 8/9] rust: device: Add property_get_reference_args Remo Senekowitsch
2025-05-20 20:00 ` [PATCH v5 9/9] samples: rust: platform: Add property read examples Remo Senekowitsch
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).