From nobody Fri Dec 19 22:03:08 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 03D8BE56A; Sun, 4 May 2025 17:32:05 +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=1746379929; cv=none; b=i6WFaAT0PjoElPQ7U3FgCyBuxP7qYH0BuTqUZIeWx6kv/A3E9lNztqXaaS924hdw8cksBxU1XZcqL1Q/on8EvgCP5EzaM7tqUg90ALwfxCoYadknUpj3xSKOD2PYtJuNjn3Ikrfmov8tMbZg0QBCBTojZ9ZugHgt4Yly88lkM6Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379929; c=relaxed/simple; bh=sLIMOs86ZUevjJV9wr0yHTtB23Agmsn2XbSfNTjLy0M=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=diVBioFbigOFo1Bz3mDhxUA511MGCtZFR/zOJQXbD01vlflvg0VUolXHU5cLJRy0e1kfi8sZUQecexffGXimf4jwQ40kGTFsPdRARLBGvB82WZpe/o/gwjA/J9/RmANFTO+UtOKLlWs5kap+JPe9x47Tz2wdScYM6HW+beLyfcU= 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 smtp102.mailbox.org (smtp102.mailbox.org [IPv6:2001:67c:2050:b231:465::102]) (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 4ZrBYG0B4Qz9tTL; Sun, 4 May 2025 19:32:02 +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 v4 1/9] rust: device: Create FwNode abstraction for accessing device properties Date: Sun, 4 May 2025 19:31:46 +0200 Message-ID: <20250504173154.488519-2-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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: 4ZrBYG0B4Qz9tTL Content-Type: text/plain; charset="utf-8" Not all property-related APIs can be exposed directly on a device. For example, iterating over child nodes of a device will yield fwnode_handle. Thus, in order to access properties on these child nodes, the property access methods must be implemented on the abstraction over fwnode_handle. Signed-off-by: Remo Senekowitsch --- MAINTAINERS | 2 +- rust/helpers/helpers.c | 1 + rust/helpers/property.c | 8 ++++ rust/kernel/{device.rs =3D> device/mod.rs} | 2 + rust/kernel/device/property.rs | 47 ++++++++++++++++++++++++ 5 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 rust/helpers/property.c rename rust/kernel/{device.rs =3D> device/mod.rs} (99%) create mode 100644 rust/kernel/device/property.rs diff --git a/MAINTAINERS b/MAINTAINERS index 3cbf9ac0d83f6..8a47c0e10e58d 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7247,7 +7247,7 @@ F: include/linux/kobj* 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 + +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/mod.rs similarity index 99% rename from rust/kernel/device.rs rename to rust/kernel/device/mod.rs index 0353c5552769c..d8619d4485fb4 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device/mod.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..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); + +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) { + // 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 Fri Dec 19 22:03:08 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 8462D25776; Sun, 4 May 2025 17:38:49 +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=1746380331; cv=none; b=NcutaDaYm1dt/3Stuiuz6WnuGng3EJnZmaqolEQOVIpWJhcdssyWR9mW6T2P5Lv6FplDvVw3+RN3G1yfXMwZxIfezKx7GsWeWbbtYShjgvieez2rfHNMtB1WWVkDaNGdePMcIktBKeiVNcccuMnrxupanpe8oOgKNm8AUx0c1vw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746380331; c=relaxed/simple; bh=xZMoxyD1M6hO1rjE/H9RTuK9a0wHG4M1f4p3TCszldo=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=VRtGo9nj+1I7KD1UfM6WAQeh9B1NA1wyj4uDdHrJtUc2Sebw2OLFluyIegw8LV7bFtMhQjkfD1y4ARDb+ywGMNkHEFe14RucgqPQQ0dYSZOYdd/H3cZs+0xYG2pRxXEr1XUlCwaVQMwZ988N+rlfydoMpPRvkIopuWrdkMvjhkQ= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYJ12J4z9tk2; Sun, 4 May 2025 19:32:04 +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 v4 2/9] rust: device: Enable accessing the FwNode of a Device Date: Sun, 4 May 2025 19:31:47 +0200 Message-ID: <20250504173154.488519-3-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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" The FwNode is an abstraction over the C struct fwnode_handle. It will be used to access all device properties. Signed-off-by: Remo Senekowitsch --- rust/kernel/device/mod.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rust/kernel/device/mod.rs b/rust/kernel/device/mod.rs index d8619d4485fb4..b4b7056eb80f8 100644 --- a/rust/kernel/device/mod.rs +++ b/rust/kernel/device/mod.rs @@ -186,6 +186,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 Fri Dec 19 22:03:08 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 325BE1EDA35; Sun, 4 May 2025 17:32:09 +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=1746379931; cv=none; b=Q7pQYuxP71r4NB8Tdk/Bavi5RA6mTDXOLg0T+P7axm6xbQ5/9YeVV79vQdc/S2REwxgH+iSOWsjYCas53jyI0svtxDhPnTP9sfHHDiLLcdae7Ab/D1y3DyKN+EMz2kC4IzwPfa4tjw94o0oP+FgorZDAu3Hg7ocyVboC51B+odU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379931; c=relaxed/simple; bh=IuJ/JYEcJX5Y174KySDaQUhQfRssj2v+q0jSvHXpWBU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=LAkGEJhn1gvDQNDie2Cax1An0wkGlSk4GsVM9CHvVOM3jowVPeZc9Z1onzkgKaLdL206aN9hEMW0XhBWN+BUjry1RJ4OjwMc/u5ETm4ErquAXGIQmoDf14kTX2dtIxC6tOYA28uixKVN/VwJEVCRoazovtOVdLyoLpLeXY3PlLs= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYL24Gzz9tch; Sun, 4 May 2025 19:32:06 +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 v4 3/9] rust: device: Move property_present() to FwNode Date: Sun, 4 May 2025 19:31:48 +0200 Message-ID: <20250504173154.488519-4-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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" 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. Hence, remove the method from Device. There aren't any users to update yet. Signed-off-by: Remo Senekowitsch --- rust/kernel/device/mod.rs | 7 ------- rust/kernel/device/property.rs | 8 +++++++- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/rust/kernel/device/mod.rs b/rust/kernel/device/mod.rs index b4b7056eb80f8..15d89cd45e871 100644 --- a/rust/kernel/device/mod.rs +++ b/rust/kernel/device/mod.rs @@ -6,7 +6,6 @@ =20 use crate::{ bindings, - str::CStr, types::{ARef, Opaque}, }; use core::{fmt, marker::PhantomData, ptr}; @@ -200,12 +199,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 e75d55f5856cf..70593343bd811 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -6,7 +6,7 @@ =20 use core::ptr; =20 -use crate::{bindings, types::Opaque}; +use crate::{bindings, str::CStr, types::Opaque}; =20 /// 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_cons= t(), name.as_char_ptr()) } + } } =20 // SAFETY: Instances of `FwNode` are always reference-counted. --=20 2.49.0 From nobody Fri Dec 19 22:03:08 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 27C501EFFB5; Sun, 4 May 2025 17:32:11 +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=1746379934; cv=none; b=tEUNijvVaqwbuCDRLa78SU/Ncwg9f9Lm1IIBwXMOc1ThpGpT2Kk0jy+aciCMrbLv5Cl9bOM/Mq4/fGj1tZl9GE7hsCwnPX2SsJjDaU1e9cQudy3juMOW0pktNY6x30lvwxRoflrguCtSD3p+lG7FUp7oiEiZkh6G6wXF6NQ0YBk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379934; c=relaxed/simple; bh=lBPC/zrvrNHermCXWGNtETuEb0cFund/AAT9AWz+vvM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=KzlZpWjpK9l4jkf9pQb9XFuVCbf2xuRPZyXg+Dx6ToJbWIVTwcA8lnIhVRxP7ZY4egTf3OPs2nOlqHGJKbWGAGdx/6CEI84EHZKa0nX8wNqGwPHfeEgRWyDoNqfqiYjiSlwu70oSt9cwqBskr0+a+Wtx/2M0uuUKATmfLvTTH0Y= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYN2QKvz9tSt; Sun, 4 May 2025 19:32:08 +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 v4 4/9] rust: device: Enable printing fwnode name and path Date: Sun, 4 May 2025 19:31:49 +0200 Message-ID: <20250504173154.488519-5-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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 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 --- 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_han= dle { self.0.get() } =20 + /// 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 =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 strin= g and + // name is not null + let name =3D 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 =3D unsafe { bindings::fwnode_count_parent= s(self.0.as_raw()) }; + + for depth in (0..=3Dnum_parents).rev() { + let fwnode =3D if depth =3D=3D 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_ra= w()` or + // the return value of `bindings::fwnode_get_nth_paren= t` which + // returns a valid pointer to a fwnode_handle if the p= rovided + // depth is within the valid range, which we know to b= e true. + let prefix =3D unsafe { bindings::fwnode_get_name_pref= ix(fwnode) }; + 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, "{}", self.0.display_name())?; + + if depth !=3D 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. --=20 2.49.0 From nobody Fri Dec 19 22:03:08 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 ECE291F3D2C; Sun, 4 May 2025 17:32:19 +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=1746379941; cv=none; b=qt/426xJ5nEID5SCWugGTLzKQiyEm7oX80ZyNiDuxwWCkdxcP6dddVMlczc7Rgp2m0pFhYGlfaD1wkrnXss0FByvLDD8ZiJPHDzhlQ6BtDly9X7IyeSP5s4+QTmKIaDowDs/tRjIjYJy1NL2YMGtqd22YlFKBa6Q9P6zLXmXOs4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379941; c=relaxed/simple; bh=J2lwdCE8iDDP3UvbXLuSXS9ESV77jCz6AkFvJkR0FyU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=nMqGwmbjwXBxx1jfMbj3/sCbFjScg8gCyP+pew+vHhuogHHIISIOjtYV+PfkiQgY7DTj5MFCrIsehg9cBLbGB/dRmlB/7qy6FVcjGVZr50cl955dyT1ygrfN1di5WCKHAUwPkYiI9WLo2fun5s1kilw8TrVpisJ8dMtcxmKXQl4= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYQ25W8z9tQQ; Sun, 4 May 2025 19:32:10 +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 v4 5/9] rust: device: Introduce PropertyGuard Date: Sun, 4 May 2025 19:31:50 +0200 Message-ID: <20250504173154.488519-6-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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" 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 --- 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) { 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, + /// 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.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 { + 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() + } +} --=20 2.49.0 From nobody Fri Dec 19 22:03:08 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 092CA145A05; Sun, 4 May 2025 17:32:15 +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=1746379938; cv=none; b=cUiOFvMe7zllNRyg0rqI/er9+RzYgVJxGjd+v5qCErm+904TclAkuml/TIG4QSf2TngUCHLPrj1Gu0oE4uN//CUMd7uGJZk9Hcf4dZnjHfZUckhMD1FNWBGSOV6N282656qDI8tMzvzKHQPJMWTi54zY3y3P9nGP+qRFcSHaHTA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379938; c=relaxed/simple; bh=MIBAECn1CrmjlKWOx0y71HR4xZbC7jqKpdXTS3h8E/I=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=T0YYeLeKySVpRkndI/Tq07HNgck4ZGrKFwEA22fsWlUt4FRNq6/zmHkpHGRSxDJ4Y6RSMVh68lDkBlQWwIF/g/kX1Pv12VjR/l6mKUW+xjIqrKHfeRuIPyxkExTXNgmMgPkiXnr3rnDEd6FFrnoz4o410VluIkRlFnbIVroiD18= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYS2cBdz9sWC; Sun, 4 May 2025 19:32:12 +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 v4 6/9] rust: device: Add bindings for reading device properties Date: Sun, 4 May 2025 19:31:51 +0200 Message-ID: <20250504173154.488519-7-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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" The device property API is a firmware agnostic API for reading properties from firmware (DT/ACPI) devices nodes and swnodes. While the C API takes a pointer to a caller allocated variable/buffer, the rust API is designed to return a value and can be used in struct initialization. Rust generics are also utilized to support different types of properties where appropriate. Co-developed-by: Rob Herring (Arm) Signed-off-by: Rob Herring (Arm) Signed-off-by: Remo Senekowitsch --- rust/kernel/device/property.rs | 232 ++++++++++++++++++++++++++++++++- 1 file changed, 230 insertions(+), 2 deletions(-) diff --git a/rust/kernel/device/property.rs b/rust/kernel/device/property.rs index 59c61e2493831..413166e2d082e 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -4,9 +4,16 @@ //! //! C header: [`include/linux/property.h`](srctree/include/linux/property.= h) =20 -use core::ptr; +use core::{mem::MaybeUninit, ptr}; =20 -use crate::{bindings, str::CStr, types::Opaque}; +use crate::{ + alloc::KVec, + bindings, + error::{to_result, Result}, + prelude::*, + str::{CStr, CString}, + types::Opaque, +}; =20 /// A reference-counted fwnode_handle. /// @@ -109,6 +116,105 @@ 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)?; + + // SAFETY: `val.as_mut_ptr()` is valid because `KVec::with_capacit= y` + // didn't return an error and it has at least space for `len` numb= er + // of elements. + let err =3D unsafe { read_array_out_param::(self, name, val.as_= mut_ptr(), len) }; + let res =3D if err < 0 { + Err(Error::from_errno(err)) + } else { + // SAFETY: fwnode_property_read_int_array() writes exactly `le= n` + // entries on success + unsafe { val.set_len(len) } + Ok(val) + }; + 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 { + // SAFETY: `out_param` is allowed to be null because `len` is zero. + let ret =3D unsafe { read_array_out_param::(self, name, ptr::nu= ll_mut(), 0) }; + to_result(ret)?; + Ok(ret as usize) + } + + /// 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 integer= s 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 interpret= ed + /// 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::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. @@ -124,6 +230,128 @@ unsafe fn dec_ref(obj: ptr::NonNull) { } } =20 +/// Implemented for several types that can be read as properties. +/// +/// Informally, 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 r= ead +/// other types, because they require more specialized function signatures: +/// - [`property_read_bool`](Device::property_read_bool) +/// - [`property_read_array_vec`](Device::property_read_array_vec) +pub trait Property: Sized { + /// Used to make [`FwNode::property_read`] generic. + fn read_from_fwnode_property(fwnode: &FwNode, name: &CStr) -> Result; +} + +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` contains a non-null ptr on success + 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. +pub trait PropertyInt: Copy { + /// # Safety + /// + /// Callers must uphold the same safety invariants as for the various + /// `fwnode_property_read_*_array` functions. + unsafe fn read_array_from_fwnode_property( + fwnode: *const bindings::fwnode_handle, + propname: *const ffi::c_char, + val: *mut Self, + nval: usize, + ) -> ffi::c_int; +} +// 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 PropertyInt for $int { + unsafe fn read_array_from_fwnode_property( + fwnode: *const bindings::fwnode_handle, + propname: *const ffi::c_char, + val: *mut Self, + nval: usize, + ) -> ffi::c_int { + // SAFETY: The safety invariants on the trait require + // callers to uphold the invariants of the functions + // this macro is called with. + unsafe { + bindings::$f(fwnode, propname, val.cast(), nval) + } + } + } + )* }; +} +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, +} +/// # Safety +/// +/// Callers must ensure that if `len` is non-zero, `out_param` must be +/// valid and point to memory that has enough space to hold at least +/// `len` number of elements. +unsafe fn read_array_out_param( + fwnode: &FwNode, + name: &CStr, + out_param: *mut T, + len: usize, +) -> ffi::c_int { + // SAFETY: `name` is non-null and null-terminated. + // `fwnode.as_raw` is valid because `fwnode` is valid. + // `out_param` is valid and has enough space for at least + // `len` number of elements as per the safety requirement. + unsafe { + T::read_array_from_fwnode_property(fwnode.as_raw(), name.as_char_p= tr(), out_param, len) + } +} +impl Property for [T; N] { + fn read_from_fwnode_property(fwnode: &FwNode, name: &CStr) -> Result { + let mut val: [MaybeUninit; N] =3D [const { MaybeUninit::uninit(= ) }; N]; + + // SAFETY: `val.as_mut_ptr()` is valid and points to enough space = for + // `N` elements. Casting from `*mut MaybeUninit` to `*mut T` is= safe + // because `MaybeUninit` has the same memory layout as `T`. + let ret =3D unsafe { read_array_out_param::(fwnode, name, val.a= s_mut_ptr().cast(), N) }; + to_result(ret)?; + + // SAFETY: `val` is always initialized when + // fwnode_property_read__array is successful. + Ok(val.map(|v| unsafe { v.assume_init() })) + } +} +impl Property for T { + fn read_from_fwnode_property(fwnode: &FwNode, name: &CStr) -> Result { + let val: [_; 1] =3D <[T; 1] as Property>::read_from_fwnode_propert= y(fwnode, name)?; + Ok(val[0]) + } +} + /// 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 Fri Dec 19 22:03:08 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 F2E241E0DEB; Sun, 4 May 2025 17:32:17 +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=1746379939; cv=none; b=iQ8qOmQmrW4pb2Mzk+MXeVqxevMGjnwfsEhKyyax2GZ6ZegudszvZ0NbwxcE8KIxfT7fR41/rewXx3wus2O/QQhOUY4L6cSQ2kT1DJp9dSaahk3XWkrUfOEi6k5rzHe7oa3OJNodt5Ze/jxdLaBjvOLVW5qhzcytHBMzhIPJL5A= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379939; c=relaxed/simple; bh=arVvYY/U4KcowDeyUPfOPUK4/y7MQua5SHBupaDB3gU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=F5Zxpsev81yYacTloR+BCHDn4Z2L/lC5rB+dYhIfLkQAHHqjAHU+U1g2VCIub4hUT9LtIBgKheA6gX+sqNr8VLNqPLHfAGHNHgLYESl+2zBbLqmPkzAjq8CbGbcYBkTAjzH/UWiCWyCZVzYQfHJFg9U+mEHZJmtdUnj4gsxuueU= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYV3TTcz9tSw; Sun, 4 May 2025 19:32:14 +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 v4 7/9] rust: device: Add child accessor and iterator Date: Sun, 4 May 2025 19:31:52 +0200 Message-ID: <20250504173154.488519-8-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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. Signed-off-by: Remo Senekowitsch --- 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 413166e2d082e..10061156f79a8 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -12,7 +12,7 @@ error::{to_result, Result}, prelude::*, str::{CStr, CString}, - types::Opaque, + types::{ARef, Opaque}, }; =20 /// A reference-counted fwnode_handle. @@ -34,6 +34,27 @@ pub struct FwNode(Opaque); =20 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() @@ -215,6 +236,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 Fri Dec 19 22:03:08 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 1562C1F3D58; Sun, 4 May 2025 17:32:19 +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=1746379941; cv=none; b=feM89U60IlNvRMQACHwfZE/0Cnqwo3CHOgwJ8D08n/8ryfAqPpjCu6qSfADoKj0h7bLhIGCqs7hrvwRRkSJL8T/1CAa1bRYp4axzjfFpwnfdxlpOCem6e0v8qwSO7TVi0zfGmHNs5SZd1SFUp93xf5a+KH6Y6FvwxzHNztYupIU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379941; c=relaxed/simple; bh=khpVA+vbpCfpcp+ac2N3aNrX8w8epr9uHVpWDeshWwM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Rs++tE7Y26PuvB2iKkiWcVoQe00waplsaMKBQdkTxbjUNyS9L+YNqOvAQvSN84o0Lgx7KNzHKqSnJc7DJzzMUYEZIhtMPV0/a7RezRDV5JwbFDljSnq1r4NM7hh3+pikX5foN+70wuVY1eIjVTZDWcm6UtS9jQcUWcAOxOz9sPE= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYX45pSz9tch; Sun, 4 May 2025 19:32:16 +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 v4 8/9] rust: device: Add property_get_reference_args Date: Sun, 4 May 2025 19:31:53 +0200 Message-ID: <20250504173154.488519-9-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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. Signed-off-by: Remo Senekowitsch --- 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 10061156f79a8..1cd3886b8f552 100644 --- a/rust/kernel/device/property.rs +++ b/rust/kernel/device/property.rs @@ -292,6 +292,65 @@ 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 `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, `na= rgs` + // 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. @@ -429,6 +488,15 @@ fn read_from_fwnode_property(fwnode: &FwNode, name: &C= Str) -> Result { } } =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 Fri Dec 19 22:03:08 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 1DFC11F4615; Sun, 4 May 2025 17:32:21 +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=1746379943; cv=none; b=YHDMUcKuaxZ9DKVkLKBsvMYNiFdCYqrwQ6Elx1z5ph4SoGMQOaBHtUhr9dg9alxZSWL9f4Ibo7R06+WRdcjSVufw1YdsStK1qjVckhNVdad4AurEhNj3GAkuKKKXXDAPqD5BMPi0QA6VqCyxQlnoc4a5BaKKdIDMGHyv/xOu5Tk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746379943; c=relaxed/simple; bh=77hKcSKMWZYeX5joA52qyQWO7ZcI4hxABnA/VCNsc4w=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=PeKUZlLKLdd4qHTdThNoKfXf9l1vwHVH5xgGuB7Ogqwo3/UJwanCUFW1NR1oXfTpOKJmkJ0o2WzGte1TO9EppmriQ18bpQwc29HuG2W1+IiRdkGbzGpzuGJXYwyerWzUWCEEONXUIp0/4InL7h438g/Qf7h+wgiHWg2jLXgva4E= 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 smtp102.mailbox.org (smtp102.mailbox.org [10.196.197.102]) (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 4ZrBYZ459Sz9sv3; Sun, 4 May 2025 19:32:18 +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 v4 9/9] samples: rust: platform: Add property read examples Date: Sun, 4 May 2025 19:31:54 +0200 Message-ID: <20250504173154.488519-10-remo@buenzli.dev> In-Reply-To: <20250504173154.488519-1-remo@buenzli.dev> References: <20250504173154.488519-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 some example usage of the device property read methods for DT/ACPI/swnode properties. 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 | 71 +++++++++++++++++++- 2 files changed, 72 insertions(+), 2 deletions(-) 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..a04ff4afb1325 100644 --- a/samples/rust/rust_driver_platform.rs +++ b/samples/rust/rust_driver_platform.rs @@ -2,7 +2,7 @@ =20 //! Rust Platform driver sample. =20 -use kernel::{c_str, device::Core, of, platform, prelude::*, types::ARef}; +use kernel::{c_str, device::Core, of, platform, prelude::*, str::CString, = types::ARef}; =20 struct SampleDriver { pdev: ARef, @@ -25,18 +25,85 @@ fn probe( pdev: &platform::Device, info: Option<&Self::IdInfo>, ) -> Result>> { + let dev =3D pdev.as_ref(); + dev_dbg!(pdev.as_ref(), "Probe Rust Platform driver sample.\n"); =20 if let Some(info) =3D info { - dev_info!(pdev.as_ref(), "Probed with info: '{}'.\n", info.0); + dev_info!(dev, "Probed with info: '{}'.\n", info.0); } =20 + Self::properties_parse(dev)?; + let drvdata =3D KBox::new(Self { pdev: pdev.into() }, GFP_KERNEL)?; =20 Ok(drvdata.into()) } } =20 +impl SampleDriver { + fn properties_parse(dev: &kernel::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); + } + + if let Ok(str) =3D fwnode + .property_read::(c_str!("compatible")) + .required_by(dev) + { + dev_info!(dev, "compatible string =3D {:?}\n", str); + } + + let prop =3D fwnode.property_read_bool(c_str!("test,bool-prop")); + dev_info!(dev, "bool prop is {}\n", prop); + + if fwnode.property_present(c_str!("test,u32-prop")) { + dev_info!(dev, "'test,u32-prop' is present\n"); + } + + let prop =3D fwnode + .property_read::(c_str!("test,u32-optional-prop")) + .or(0x12); + dev_info!( + dev, + "'test,u32-optional-prop' is {:#x} (default =3D {:#x})\n", + prop, + 0x12 + ); + + // Missing property without a default will print an error + let _ =3D fwnode + .property_read::(c_str!("test,u32-required-prop")) + .required_by(dev); + + let prop: u32 =3D fwnode + .property_read(c_str!("test,u32-prop")) + .required_by(dev)?; + dev_info!(dev, "'test,u32-prop' is {:#x}\n", prop); + + let prop: [i16; 4] =3D fwnode + .property_read(c_str!("test,i16-array")) + .required_by(dev)?; + dev_info!(dev, "'test,i16-array' is {:?}\n", prop); + dev_info!( + dev, + "'test,i16-array' length is {}\n", + fwnode.property_count_elem::(c_str!("test,i16-array"))?, + ); + + let prop: KVec =3D fwnode + .property_read_array_vec(c_str!("test,i16-array"), 4)? + .required_by(dev)?; + dev_info!(dev, "'test,i16-array' is KVec {:?}\n", prop); + + 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