From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-202.mailbox.org (mout-p-202.mailbox.org [80.241.56.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 63D34263F5E; Wed, 11 Jun 2025 10:29:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637778; cv=none; b=mYRufYc1EkF95crg77RWEz3YxxHNQFXvZdH+9Lbt1ZnMbd8o63QsA4Lvy89FydpacYZ426R03S9GhYBIXzGdynz8A4ilOqNDk2lkdS7OkMR9JxEDI8jRMhM7zioUpwRqMTXvf2xk7EXCyDk9O+BUqN96PxJy7X+khDlnZM/+1i0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637778; c=relaxed/simple; bh=3wwu9xxCuYneQw2jEgFoc4WF3Au0xB94g8Xa6k4Ump8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=j4Qlm+GmhFwijKyuqhSN8574CVA2OWIok+r9rJY9R7AtFmnbl4LJW3PIVYOhIj7gmpR2HKZnIN4rkz2uwBZxmx30zF8Ab+NtkDbDVw9g7npGlr7fOv/N4EzfRZ4c1+UYakpFWV56FiBa8MCgacWXhPHZeH1E6YKRPkDWRdLMXU0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [IPv6:2001:67c:2050:b231:465::202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-202.mailbox.org (Postfix) with ESMTPS id 4bHMND56Wnz9tPV; Wed, 11 Jun 2025 12:29:32 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 1/9] rust: device: Create FwNode abstraction for accessing device properties Date: Wed, 11 Jun 2025 12:29:00 +0200 Message-ID: <20250611102908.212514-2-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Rspamd-Queue-Id: 4bHMND56Wnz9tPV Content-Type: text/plain; charset="utf-8" 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. Tested-by: Dirk Behme Signed-off-by: Remo Senekowitsch --- 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 diff --git a/MAINTAINERS b/MAINTAINERS index a92290fffa163..9f724cd556f48 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -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 diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 0f1b5d1159859..ed00695af971e 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -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" 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 + +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 dea06b79ecb53..d6237827a9369 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -14,6 +14,8 @@ #[cfg(CONFIG_PRINTK)] use crate::c_str; =20 +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..03850b7bb8087 --- /dev/null +++ b/rust/kernel/device/property.rs @@ -0,0 +1,73 @@ +// 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::{ARef, 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); + +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`. + unsafe fn from_raw(raw: *mut bindings::fwnode_handle) -> ARef { + // 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() + } +} + +// 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) { + // SAFETY: The safety requirements guarantee that the refcount is + // non-zero. + unsafe { bindings::fwnode_handle_put(obj.cast().as_ptr()) } + } +} --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-201.mailbox.org (mout-p-201.mailbox.org [80.241.56.171]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9026526280F; Wed, 11 Jun 2025 10:29:40 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.171 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637782; cv=none; b=sNYWUv9sOVvU1wfopa9+LAx9OmlAkFJJBtUIxEBw6Pu4bgZMDVX0DiBrJTfxZfQ+cPTpd3DtpDvIZeFTDrAL62uPN8cGBhvuCGiiMKEyRi9Gk8HmDYC1xCimmrzUZ8u69iSPHzU7eVk47+Q7SXweCrBBSDbFdVQGMNqQ05kBc2Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637782; c=relaxed/simple; bh=hwdlFyCcTxFJRhAmgRPoYDoX5BfMe9FtVpwQHVWfm7k=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RhPz308FE7Qt1mXIjlqQ383mIHUY6U0/K/nZAP9pqcNPJBUFPo7iaGmRY8guqq8VPBo6feHNXrAxeTkwOjvBBgv1DcbAYkQAzpYHzJGYOXKh6PDzk/OsXMpEiY+ZjSQPhBXh3snm5TnxHpFzGipZ37RcDgsn4JeeVdX3x3HPOgs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.171 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [10.196.197.202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-201.mailbox.org (Postfix) with ESMTPS id 4bHMNK08j8z9tfM; Wed, 11 Jun 2025 12:29:37 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 2/9] rust: device: Enable accessing the FwNode of a Device Date: Wed, 11 Jun 2025 12:29:01 +0200 Message-ID: <20250611102908.212514-3-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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`. Tested-by: Dirk Behme Signed-off-by: Remo Senekowitsch --- rust/kernel/device.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index d6237827a9369..b69f03a7f8d30 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -205,6 +205,21 @@ unsafe fn printk(&self, klevel: &[u8], msg: fmt::Argum= ents<'_>) { }; } =20 + /// Obtain the [`FwNode`](property::FwNode) corresponding to the devic= e. + pub fn fwnode(&self) -> Option<&property::FwNode> { + // SAFETY: `self` is valid. + let fwnode_handle =3D unsafe { bindings::__dev_fwnode(self.as_raw(= )) }; + if fwnode_handle.is_null() { + return None; + } + // SAFETY: `fwnode_handle` is valid. Its lifetime is tied to `&sel= f`. We + // return a reference instead of an `ARef` because `dev_fw= node()` + // 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_hand= le`. + 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. --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-103.mailbox.org (mout-p-103.mailbox.org [80.241.56.161]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A4E3A262FEA; Wed, 11 Jun 2025 10:29:49 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.161 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637791; cv=none; b=LImrUitUIafmwIpzk9vey6/MqpyGwFXJwH9aqtMhQ0w5ExDMe4cdF+bZ6oZvFlMoLmKr1bM/rCdd89eOFgKPZZ+ydjTetgIjT2Ntm+YLc7G5M+q+M4HNTpgrMQHHQq3PfZnEpoajyOU0Ty566hMtlTXowLR3+JNMtEWBIJzrTw8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637791; c=relaxed/simple; bh=QkMlQTTUIeB2daj1wKpftXyVVqXYCZwwM5eWfLCXFeI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=f+eNNmFyHC9hSazjbtxKGA1xeqSkc/gLrGwEajamoRMMia6W4FBSrGhf4xdo3iDiCebHruQQAG4DZ5YU43zaGOcIAl9gsPavLdz8omXcEu2ORz4Gt+yrLVV4y3cFeB9TlT73VwK9OtcDa4pSsRJYfYeKACTVZ+tPKfWmEYPIniQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.161 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [IPv6:2001:67c:2050:b231:465::202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-103.mailbox.org (Postfix) with ESMTPS id 4bHMNM687vz9tMg; Wed, 11 Jun 2025 12:29:39 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 3/9] rust: device: Move property_present() to FwNode Date: Wed, 11 Jun 2025 12:29:02 +0200 Message-ID: <20250611102908.212514-4-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Rspamd-Queue-Id: 4bHMNM687vz9tMg Content-Type: text/plain; charset="utf-8" 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_present is removed from Device and existing users are updated. Signed-off-by: Remo Senekowitsch Acked-by: Viresh Kumar --- drivers/cpufreq/rcpufreq_dt.rs | 3 ++- rust/kernel/device.rs | 7 ------- rust/kernel/device/property.rs | 7 +++++++ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/drivers/cpufreq/rcpufreq_dt.rs b/drivers/cpufreq/rcpufreq_dt.rs index 94ed81644fe1c..4eb240dc9fdc8 100644 --- a/drivers/cpufreq/rcpufreq_dt.rs +++ b/drivers/cpufreq/rcpufreq_dt.rs @@ -20,7 +20,8 @@ /// Finds exact supply name from the OF node. fn find_supply_name_exact(dev: &Device, name: &str) -> Option { let prop_name =3D 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() } diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index b69f03a7f8d30..241a395d529a1 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -6,7 +6,6 @@ =20 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_hand= le`. 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_cons= t(), name.as_char_ptr()) } - } } =20 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend= on `Device`'s generic diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs index 03850b7bb8087..50c61aa056e6b 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -8,6 +8,7 @@ =20 use crate::{ bindings, + str::CStr, types::{ARef, Opaque}, }; =20 @@ -55,6 +56,12 @@ unsafe fn from_raw(raw: *mut bindings::fwnode_handle) ->= ARef { 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_cons= t(), name.as_char_ptr()) } + } } =20 // SAFETY: Instances of `FwNode` are always reference-counted. --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-103.mailbox.org (mout-p-103.mailbox.org [80.241.56.161]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C1A9A267B65; Wed, 11 Jun 2025 10:29:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.161 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637794; cv=none; b=Uyt82cjYZav4BoPWpc1cvyVmSZPDxLo0/3RGxW2RBUy+zuCUk+YMIPO8f+TanQPw/YaYnQI6ZdZx/iGLL3FID3m448Ge4n7HOt6STllR5rLtP1CX1EesDH+TyWzvnoLhqyjTUlxFlkokE5Cv5i+XYsblot3gXbDvDRjiCMiYRHQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637794; c=relaxed/simple; bh=2BoW4pFaIctzE8BFvVPtU04cbrv4X3tZKXfOo1/sW/A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Tk5/L0RIYom1zuGltXpUAkV5SX/lSy94H9aZt3zvjgm9CkC4EYjrQIeea5uMcfFMvFam847oGdqi1ARbjzwQhYBbt0AFaNXPFzdTYmb/D+pJMtU55QUh38zYGQVaIb32xRhtlpCfZxJgcXAqQlj1UpQhg8M5pwOb64ueNi2lAdY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.161 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [IPv6:2001:67c:2050:b231:465::202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-103.mailbox.org (Postfix) with ESMTPS id 4bHMNR0zGNz9tKs; Wed, 11 Jun 2025 12:29:43 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 4/9] rust: device: Enable printing fwnode name and path Date: Wed, 11 Jun 2025 12:29:03 +0200 Message-ID: <20250611102908.212514-5-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Rspamd-Queue-Id: 4bHMNR0zGNz9tKs Content-Type: text/plain; charset="utf-8" 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. Tested-by: Dirk Behme Signed-off-by: Remo Senekowitsch --- rust/kernel/device/property.rs | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs index 50c61aa056e6b..4cac335bad78c 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -57,6 +57,32 @@ pub(crate) fn as_raw(&self) -> *mut bindings::fwnode_han= dle { self.0.get() } =20 + /// 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, wh= ich + /// prints the full path. + 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 =3D 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 =3D 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) { unsafe { bindings::fwnode_handle_put(obj.cast().as_ptr()) } } } + +enum Node<'a> { + Borrowed(&'a FwNode), + Owned(ARef), +} + +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 =3D unsafe { bindings::fwnode_count_parents(self.a= s_raw()) }; + + for depth in (0..=3Dnum_parents).rev() { + let fwnode =3D if depth =3D=3D 0 { + Node::Borrowed(self) + } else { + // SAFETY: `self.as_raw()` is valid. + let ptr =3D 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 =3D match &fwnode { + Node::Borrowed(f) =3D> f, + Node::Owned(f) =3D> f, + }; + + // SAFETY: `fwnode` is valid by its type invariant. + let prefix =3D unsafe { bindings::fwnode_get_name_prefix(fwnod= e.as_raw()) }; + if !prefix.is_null() { + // SAFETY: `fwnode_get_name_prefix` returns null or a + // valid C string. + let prefix =3D unsafe { CStr::from_char_ptr(prefix) }; + write!(f, "{prefix}")?; + } + write!(f, "{}", fwnode.display_name())?; + } + + Ok(()) + } +} --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-101.mailbox.org (mout-p-101.mailbox.org [80.241.56.151]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 55A80262FF8; Wed, 11 Jun 2025 10:29:50 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.151 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637792; cv=none; b=jCNO+IZoS5kaIaMsuXZtrRlYmwnATl3ADv1+8L1Lq4si0TF75kb3sKArdasw9ZaLcUlMZrLNCvPVsUPHFEPnLR2wyit4ve+nXawXTQYkBA8JfZC6+1gsEpJVaQ873LRaXMWRGNSXHhp/qOCFlxWXnTo18jYqo0f2rv/B18ZXXXA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637792; c=relaxed/simple; bh=oH/N2sg5h5okYpIq7ww7V/12H2KDUPswj9/GQjgDL8g=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=IEvYyWVDa5M+lbHRZRNAmtV8sQx8OtnxPA6/OXN64mGR7RDen+xQ7tYhVDFeRq7/CseQDQmpiTPe4xG3QwvBvlfjZ5rty1f0Puo2+M+EyFotGaxncwLRhDYSaA5AOe9KQgCOn+8hLnI2qjGPZPMgivcZXpZBevkFxMdHtXOhi/A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.151 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [IPv6:2001:67c:2050:b231:465::202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-101.mailbox.org (Postfix) with ESMTPS id 4bHMNV4cctz9sWc; Wed, 11 Jun 2025 12:29:46 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 5/9] rust: device: Introduce PropertyGuard Date: Wed, 11 Jun 2025 12:29:04 +0200 Message-ID: <20250611102908.212514-6-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Rspamd-Queue-Id: 4bHMNV4cctz9sWc Content-Type: text/plain; charset="utf-8" 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. Tested-by: Dirk Behme Signed-off-by: Remo Senekowitsch --- 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 4cac335bad78c..a10033d310e60 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -105,6 +105,65 @@ unsafe fn dec_ref(obj: ptr::NonNull) { } } =20 +/// 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, + /// The fwnode of the property, used for logging in the "required" cas= e. + fwnode: &'fwnode FwNode, + /// The name of the property, used for logging in the "required" case. + name: &'name CStr, +} + +impl 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 { + 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 { + self.inner.ok() + } + + /// Access the property or the specified default value. + /// + /// Do not pass a sentinel value as default to detect a missing proper= ty. + /// Use [`Self::required_by`] or [`Self::optional`] instead. + pub fn or(self, default: T) -> T { + self.inner.unwrap_or(default) + } +} + +impl 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(&'a FwNode), Owned(ARef), --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-102.mailbox.org (mout-p-102.mailbox.org [80.241.56.152]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 88033269838; Wed, 11 Jun 2025 10:29:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.152 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637801; cv=none; b=RwBzcGBgf0oXejJtbfTLruQsR0rZ8KNurwo+snlIgJC5mmq4qfMY4+q+WpN19VDTJUk5qQ9CjyyKSOLxTBTaB+VqvKfndxwygIP50IJ8GJxG+iCv6O8ml1uV+EGCVUNDDbQjB9x+4gJ6fNMHE3zrzwgW5k9wqDIuKpCh/hHSSsk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637801; c=relaxed/simple; bh=/f7JQZotF6idlITyJvgTcy5CSDukulN5LnD3CH9ilQI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=PDU7PH9GJXYNOqzhNcyvaG8DOkHXKC8h6ItVge1I6LvaCGiVigqcO5wUV2MgcRd0k9/aNweKWChUQQJWkcG8KyUqhKel/OJu2RS6Vtd4CmpgJogAZCIftQivTDpmA6wYOgdCTAO9gGf4/UtYGfTIj/L7irmmSq/7NacxckH9y9M= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.152 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [10.196.197.202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-102.mailbox.org (Postfix) with ESMTPS id 4bHMNZ09N0z9tcd; Wed, 11 Jun 2025 12:29:50 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 6/9] rust: device: Implement accessors for firmware properties Date: Wed, 11 Jun 2025 12:29:05 +0200 Message-ID: <20250611102908.212514-7-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Tested-by: Dirk Behme Co-developed-by: Rob Herring (Arm) Signed-off-by: Rob Herring (Arm) Signed-off-by: Remo Senekowitsch --- rust/kernel/device/property.rs | 255 ++++++++++++++++++++++++++++++++- 1 file changed, 253 insertions(+), 2 deletions(-) diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs index a10033d310e60..75621abe81174 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -4,11 +4,15 @@ //! //! C header: [`include/linux/property.h`](srctree/include/linux/property.= h) =20 -use core::ptr; +use core::{mem::MaybeUninit, ptr}; =20 use crate::{ + alloc::KVec, bindings, - str::CStr, + error::{to_result, Result}, + prelude::*, + private::Sealed, + str::{CStr, CString}, types::{ARef, Opaque}, }; =20 @@ -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_cons= t(), 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.a= s_char_ptr()) } + } + + /// Returns the index of matching string `match_str` for firmware stri= ng + /// property `name`. + pub fn property_match_string(&self, name: &CStr, match_str: &CStr) -> = Result { + // SAFETY: + // - `name` and `match_str` are non-null and null-terminated. + // - `self.as_raw` is valid because `self` is valid. + let ret =3D 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>> { + let mut val: KVec =3D KVec::with_capacity(len, GFP_KERNEL)?; + + let res =3D T::read_array_from_fwnode_property(self, name, val.spa= re_capacity_mut()); + let res =3D match res { + Ok(_) =3D> { + // 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 in= itialized + // by `read_array_from_fwnode_property`. + unsafe { val.inc_len(len) } + Ok(val) + } + Err(e) =3D> Err(e), + }; + Ok(PropertyGuard { + inner: res, + fwnode: self, + name, + }) + } + + /// Returns integer array length for firmware property `name`. + pub fn property_count_elem(&self, name: &CStr) -> Resu= lt { + 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 t= hat + /// 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::CSt= ring}; + /// fn examples(dev: &Device) -> Result { + /// let fwnode =3D dev.fwnode().ok_or(ENOENT)?; + /// let b: u32 =3D fwnode.property_read(c_str!("some-number")).req= uired_by(dev)?; + /// if let Some(s) =3D fwnode.property_read::(c_str!("som= e-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, + } + } } =20 // SAFETY: Instances of `FwNode` are always reference-counted. @@ -105,6 +207,155 @@ unsafe fn dec_ref(obj: ptr::NonNull) { } } =20 +/// 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 be= ing +/// read. There are also two dedicated methods to read other types, becaus= e 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; +} + +impl Sealed for CString {} + +impl Property for CString { + fn read_from_fwnode_property(fwnode: &FwNode, name: &CStr) -> Result { + let mut str: *mut u8 =3D ptr::null_mut(); + let pstr: *mut _ =3D &mut str; + + // SAFETY: + // - `name` is non-null and null-terminated. + // - `fwnode.as_raw` is valid because `fwnode` is valid. + let ret =3D 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 u= sed + // within the current function. + // - The memory it points to is not mutated during that time. + let str =3D 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], + ) -> Result<&'a mut [Self]>; + + /// Reads the length of a property array. + fn read_array_len_from_fwnode_property(fwnode: &FwNode, name: &CStr) -= > Result; +} +// 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),* $(,)?) =3D> { $( + impl Sealed for $int {} + impl Sealed for [$int; N] {} + + impl PropertyInt for $int { + fn read_array_from_fwnode_property<'a>( + fwnode: &FwNode, + name: &CStr, + out: &'a mut [MaybeUninit], + ) -> 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 t= o 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 =3D 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]` = to + // `&'a mut [Self]` is sound, because the previous call to= a + // `fwnode_property_read_*_array` function (which didn't f= ail) + // fully initialized the slice. + Ok(unsafe { core::mem::transmute(out) }) + } + + fn read_array_len_from_fwnode_property(fwnode: &FwNode, name: = &CStr) -> Result { + // SAFETY: + // - `fwnode` and `name` are valid by their type invariant= s. + // - 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 =3D 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 { + let val: [_; 1] =3D <[$int; 1]>::read_from_fwnode_property= (fwnode, name)?; + Ok(val[0]) + } + } + + impl Property for [$int; N] { + fn read_from_fwnode_property(fwnode: &FwNode, name: &CStr) -> = Result { + let mut val: [MaybeUninit<$int>; N] =3D [const { MaybeUnin= it::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 --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-103.mailbox.org (mout-p-103.mailbox.org [80.241.56.161]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B4547268FDC; Wed, 11 Jun 2025 10:29:57 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.161 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637799; cv=none; b=aJOQolg/aVbOZzMfusGmCisq72WZsWpgM6JmgA+FDWFZ3LmZKSPHOS7c1208TJYoY5E4hN8diCzqfFzTtBpXz9TBeY4RMGPqko+1Pa9kOyGrqryEUwi7XCZh1jKbXeAU3VJidl2u9ySXLRgXwymDo0VL6s0DmGKxUoM8yfjN+ug= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637799; c=relaxed/simple; bh=IC0k/l4rEhjH3tIjjrmqfGtCCK/twgZwgB2SXcQaOTY=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=m6jxMLPZcb9DP5UYDgLQiTJm0XrsONq020Q7D1vqmOeqhsOyg8WJ7uJWIDJVJGXv9mOARoJ/pwMmvfG88gqOAK7pxiGLvJIzUEB3cy8dGYSYshaoieqSqTx/7X8P8qAWeqs2obLd0xLB4SpRzEiojCUWSj26TS22kiM9jB0KIyk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.161 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [10.196.197.202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-103.mailbox.org (Postfix) with ESMTPS id 4bHMNf3l0Cz9tMg; Wed, 11 Jun 2025 12:29:54 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 7/9] rust: device: Add child accessor and iterator Date: Wed, 11 Jun 2025 12:29:06 +0200 Message-ID: <20250611102908.212514-8-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Tested-by: Dirk Behme Signed-off-by: Remo Senekowitsch --- rust/kernel/device/property.rs | 56 ++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs index 75621abe81174..cd640adf18ca5 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -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> { + // SAFETY: `self` and `name` are valid by their type invariants. + let child =3D + 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 refc= ount + // 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> = + 'a { + let mut prev: Option> =3D None; + + core::iter::from_fn(move || { + let prev_ptr =3D match prev.take() { + None =3D> ptr::null_mut(), + Some(prev) =3D> { + // 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 =3D 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 =3D unsafe { bindings::fwnode_get_next_child_node(sel= f.as_raw(), prev_ptr) }; + if next.is_null() { + return None; + } + // SAFETY: + // - `next` is valid because `fwnode_get_next_child_node` retu= rns 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`. + let next =3D unsafe { FwNode::from_raw(next) }; + prev =3D Some(next.clone()); + Some(next) + }) + } } =20 // SAFETY: Instances of `FwNode` are always reference-counted. --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-202.mailbox.org (mout-p-202.mailbox.org [80.241.56.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4BD6426A081; Wed, 11 Jun 2025 10:30:01 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637803; cv=none; b=aYE80ceISjgYjXzGj9WtxLN5l5/5vCjBGjerYTmN21dfwdgtfRdUqH9MZ9eS5oonmMhKDLDd//5InyKDOa4QDYWW7wD4qGLK8F2mTnvKjLJ5DrAt9km6AeT7BoyllJs3HDa3hnVZwdvuD6bOHkY1jw8nt1FSf3VVhEUG+QLqN9Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637803; c=relaxed/simple; bh=HZo7sWs6Rd/8ppVZwK1eaOO/YcXTMZfvUnndHC7pUEc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=BKzkRd0pOcUp5K7tXchyV9YoPA1085teEwLA3Sg9sjmCb/I2Vr2pyEyQS/I7liHL2P1HEsEPJ86kFGfeObhtEUj/wuNIpbRCe0Q0Mu0GdiO1+75bJlQOPNxllJFpebSPZb1B9pK4oSf7cTONOKNeWsS9C7sZ/9/NhBZvDncaNY4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [10.196.197.202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-202.mailbox.org (Postfix) with ESMTPS id 4bHMNj5XdJz9tQ8; Wed, 11 Jun 2025 12:29:57 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 8/9] rust: device: Add property_get_reference_args Date: Wed, 11 Jun 2025 12:29:07 +0200 Message-ID: <20250611102908.212514-9-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Allow Rust code to read reference args from device properties. The wrapper type `FwNodeReferenceArgs` allows callers to access the buffer of read args safely. Tested-by: Dirk Behme Signed-off-by: Remo Senekowitsch --- rust/kernel/device/property.rs | 67 ++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs index cd640adf18ca5..28d9848ea5fb1 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -246,6 +246,64 @@ pub fn children<'a>(&'a self) -> impl Iterator> + 'a { Some(next) }) } + + /// Finds a reference with arguments. + pub fn property_get_reference_args( + &self, + prop: &CStr, + nargs: NArgs<'_>, + index: u32, + ) -> Result { + let mut out_args =3D FwNodeReferenceArgs::default(); + + let (nargs_prop, nargs) =3D match nargs { + NArgs::Prop(nargs_prop) =3D> (nargs_prop.as_char_ptr(), 0), + NArgs::N(nargs) =3D> (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 =3D 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.= 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 =3D=3D 0 + } } =20 // SAFETY: Instances of `FwNode` are always reference-counted. @@ -412,6 +470,15 @@ fn read_from_fwnode_property(fwnode: &FwNode, name: &C= Str) -> Result { i64: fwnode_property_read_u64_array, } =20 +/// 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 --=20 2.49.0 From nobody Sat Oct 11 04:14:27 2025 Received: from mout-p-202.mailbox.org (mout-p-202.mailbox.org [80.241.56.172]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 57E8826AAA3; Wed, 11 Jun 2025 10:30:05 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=80.241.56.172 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637806; cv=none; b=AGczJSjh6FlI1BMG1kLiEbCVduRAHqyuGt4okxWz43OZLzg0noZDkjc8oAk6MOr9WwQyEr7yvD0QTGsPsaPa4BzRwymdX5mBCuduVPXoJFNiksu7X7N6PaHVN0d0vL+r3a3D9fGdtjVlAFwM7NBVnPPeDmef1Lp7RZVkaOZvDdQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1749637806; c=relaxed/simple; bh=R/L1yz/OFtaKsGYyJS6vXs8rb7mCAM3V5P4qgQyt1eg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=u2kXIMM8/Mvc9J0dHZe8cwVKlwV387VWHKL+o2d1jW8pFKJR42tUIm1vFqEtz6pVLWC/yE0XMDIZqQbaV7xq0EZjIzsy4TpdbAOr1Qsz+NfoAV5TNLefPd+joNPbkB334mkN2DPw2PNBAuvoUsYsriropVY8ad5yubixrJuLkfs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev; spf=pass smtp.mailfrom=buenzli.dev; arc=none smtp.client-ip=80.241.56.172 Authentication-Results: smtp.subspace.kernel.org; dmarc=none (p=none dis=none) header.from=buenzli.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=buenzli.dev Received: from smtp202.mailbox.org (smtp202.mailbox.org [IPv6:2001:67c:2050:b231:465::202]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mout-p-202.mailbox.org (Postfix) with ESMTPS id 4bHMNn6Z3sz9tQS; Wed, 11 Jun 2025 12:30:01 +0200 (CEST) From: Remo Senekowitsch To: Rob Herring , Saravana Kannan , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Dirk Behme , Remo Senekowitsch Cc: linux-kernel@vger.kernel.org, devicetree@vger.kernel.org, rust-for-linux@vger.kernel.org Subject: [PATCH v8 9/9] samples: rust: platform: Add property read examples Date: Wed, 11 Jun 2025 12:29:08 +0200 Message-ID: <20250611102908.212514-10-remo@buenzli.dev> In-Reply-To: <20250611102908.212514-1-remo@buenzli.dev> References: <20250611102908.212514-1-remo@buenzli.dev> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Rspamd-Queue-Id: 4bHMNn6Z3sz9tQS Content-Type: text/plain; charset="utf-8" Add some example usage of the device property read methods for DT/ACPI/swnode properties. Tested-by: Dirk Behme Co-developed-by: Rob Herring (Arm) Signed-off-by: Rob Herring (Arm) Signed-off-by: Remo Senekowitsch --- 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/unit= test-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 =3D "test,rust-device"; reg =3D <0x2>; + + test,u32-prop =3D <0xdeadbeef>; + test,i16-array =3D /bits/ 16 <1 2 (-3) (-4)>; }; }; =20 diff --git a/samples/rust/rust_driver_platform.rs b/samples/rust/rust_drive= r_platform.rs index 8b42b3cfb363a..c0abf78d0683b 100644 --- a/samples/rust/rust_driver_platform.rs +++ b/samples/rust/rust_driver_platform.rs @@ -2,7 +2,14 @@ =20 //! Rust Platform driver sample. =20 -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, +}; =20 struct SampleDriver { pdev: ARef, @@ -31,12 +38,63 @@ fn probe( dev_info!(pdev.as_ref(), "Probed with info: '{}'.\n", info.0); } =20 + Self::properties_parse(pdev.as_ref())?; + let drvdata =3D KBox::new(Self { pdev: pdev.into() }, GFP_KERNEL)?; =20 Ok(drvdata.into()) } } =20 +impl SampleDriver { + fn properties_parse(dev: &device::Device) -> Result { + let fwnode =3D dev.fwnode().ok_or(ENOENT)?; + + if let Ok(idx) =3D + fwnode.property_match_string(c_str!("compatible"), c_str!("tes= t,rust-device")) + { + dev_info!(dev, "matched compatible string idx =3D {}\n", idx); + } + + let name =3D c_str!("compatible"); + let prop =3D fwnode.property_read::(name).required_by(dev= )?; + dev_info!(dev, "'{name}'=3D'{prop:?}'\n"); + + let name =3D c_str!("test,bool-prop"); + let prop =3D fwnode.property_read_bool(c_str!("test,bool-prop")); + dev_info!(dev, "'{name}'=3D'{prop}'\n"); + + if fwnode.property_present(c_str!("test,u32-prop")) { + dev_info!(dev, "'test,u32-prop' is present\n"); + } + + let name =3D c_str!("test,u32-optional-prop"); + let prop =3D fwnode.property_read::(name).or(0x12); + dev_info!(dev, "'{name}'=3D'{prop:#x}' (default =3D 0x12)\n",); + + // A missing required property will print an error. Discard the er= ror to + // prevent properties_parse from failing in that case. + let name =3D c_str!("test,u32-required-prop"); + let _ =3D fwnode.property_read::(name).required_by(dev); + + let name =3D c_str!("test,u32-prop"); + let prop: u32 =3D fwnode.property_read(name).required_by(dev)?; + dev_info!(dev, "'{name}'=3D'{prop:#x}'\n"); + + let name =3D c_str!("test,i16-array"); + let prop: [i16; 4] =3D fwnode.property_read(name).required_by(dev)= ?; + dev_info!(dev, "'{name}'=3D'{prop:?}'\n"); + let len =3D fwnode.property_count_elem::(name)?; + dev_info!(dev, "'{name}' length is {len}\n",); + + let name =3D c_str!("test,i16-array"); + let prop: KVec =3D fwnode.property_read_array_vec(name, 4)?.r= equired_by(dev)?; + dev_info!(dev, "'{name}'=3D'{prop:?}' (KVec)\n"); + + Ok(()) + } +} + impl Drop for SampleDriver { fn drop(&mut self) { dev_dbg!(self.pdev.as_ref(), "Remove Rust Platform driver sample.\= n"); --=20 2.49.0