From nobody Fri Apr 10 06:22:57 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 BB7B124EF94; Mon, 24 Feb 2025 13:23:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403398; cv=none; b=nriMImy/Mi+gZRyKdgl90Q/0TRNNF/2ByxK1IbyzU/DP4D9m8o/fF6HvAfeDq7cbyFm8nI+2SsUN2P5QzxLuYy40JoEIICJqv2NqPk5DDsDGqRSk0Pgc/VzIdsJrjPcu2Niw04enePI/2HZtX60aC+43UMwVtVBhDB/F/uU9eRM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403398; c=relaxed/simple; bh=7Ehh98LprBCLuWdknMTk4GDYnRj/3Jr2m6jJjFH1+gM=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=LDJXXMrH28R4QCT5u8YGnw4/Lq4X/bsnP4yhJGyV6DEvKZyy3SBS95vEV8ikVDbbUxXaTqw5sNPHw3kpsMUEhJikACjEvNa3RECbup2lDI8x3lRQBuqYVQROZ+eTYtwBZrUJWk4znx9rfiZZilz0B9TT37sI8r1iujpkAMDXwMo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=R5sp4qJf; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="R5sp4qJf" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D60C0C4CED6; Mon, 24 Feb 2025 13:23:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1740403398; bh=7Ehh98LprBCLuWdknMTk4GDYnRj/3Jr2m6jJjFH1+gM=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=R5sp4qJfU2WDDVT3hjef27r5i9XWpMgtpyW22ecnKVV7+mr85VKSiR2vltWvelT2K LG2ph0DWicftgtLBJgz/7anQ5NOiEPNcGNF6+v50hOKfEbZ7gTSV8opn7iH3fViu/b ImIAas6qByqcryD7IWAevsoc5y2gomO+t8gKGkeP+kLbXjevpYUbO7lfA+mBJN+iUT /AvGi+iQkHDyfWS2cZoDTCjRUX+gTtMcFtQ7L3zOLFFH7SWW3C5TFP7IQgVaiKvXmJ bH+ObJ7Unl/jIf2vcWHyrjKbztERxkAK4xDr+w/gpIw9fykU4A4gTR5Vm7uJPXRIR9 j4QcJXKrhODyA== From: Andreas Hindborg Date: Mon, 24 Feb 2025 14:21:51 +0100 Subject: [PATCH v4 1/4] rust: sync: change ` as ForeignOwnable>::PointedTo` to `T` Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250224-configfs-v4-1-9af9b5e611f6@kernel.org> References: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> In-Reply-To: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=3515; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=7Ehh98LprBCLuWdknMTk4GDYnRj/3Jr2m6jJjFH1+gM=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnvHJ2CjhHIGKetvCP9S3T4LQVAEuKyRgZGwIaH wVxNOc2Z3yJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ7xydgAKCRDhuBo+eShj d1kFD/9/aIdTOr6iIkx30MBvgEzNSctbzoEE5WfoDZecUsm/V5aGfE4GiaXe8fVlNFr70+5gZZu PIJZQItgBOaA6ZXmCi4jB53HMBaOIbnAht/u7aZqJMNfpsynIkQHvMqIHXppoZuKrAcdCjTaIuz GR7DgDrBtbSZ3DASVqnkHEh58TkDALxpExEsAl2X69pfDDORlwApC1xzV4O07mTKZIRCKDvcwF8 cYpsKr0tYeZD47vsc5+X0rEMHvG5GK6ilx46LSxWE+ZlZ3UIVaFZnpOLTOPK+tqufS/qx4rHbAQ gbo18OGQwliMSTHEC8MD8iyNtKpLdmDHjlIgKzf4hlH/OvdiUUkUwpTb6ScUKjvy4v4oCxi4rtH kdZI6r4BFZeEHpj+ppvTE4RmBMyq0lB3qSestPiE1kYrdyoHBfOdB/l+FZG/l5iJTvD16oi3RQk 3+m8OG1rv55shjdN09BFg32aSustBtrryHpopKWfPFyAZWpEv6bdxSNoOF42jY66+3u9ti6QHnr qGKiSFi1Wzn7lXP16z1B2rlELYiUZAeNx+vGOdTpJ/4tGvV9VCV/fO2NnQ4aO9ZmjU+4Mjpgxhf fomE1CLLhPBeWlMp0s4ZNDv309fXHWML6ZaLeCBt99DkvDAMs5iZ4lO4VTGEEKWlUwuZjZwJkVm 61slYkaTzEPbZjQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Using `ArcInner` as `PoinedTo` in the `ForeignOwnable` implementation for `Arc` is a bit unfortunate. Using `T` as `PointedTo` does not remove any functionality, but allows `ArcInner` to be private. Further, it allows downstream users to write code that is generic over `Box` and `Arc`, when downstream users need access to `T` after calling `into_foreign`. Reviewed-by: Fiona Behrens Signed-off-by: Andreas Hindborg Reviewed-by: Daniel Almeida Tested-by: Daniel Almeida --- This patch is a dependency for Rust `configfs` abstractions. It allows both `Box` and `Arc` to be used as pointer types in the `configfs` hierarchy. --- rust/kernel/sync/arc.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index dfe4abf82c25..3d77a31e116f 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -143,7 +143,7 @@ pub struct Arc { #[doc(hidden)] #[pin_data] #[repr(C)] -pub struct ArcInner { +struct ArcInner { refcount: Opaque, data: T, } @@ -345,18 +345,25 @@ pub fn into_unique_or_drop(self) -> Option>> { =20 // SAFETY: The `into_foreign` function returns a pointer that is well-alig= ned. unsafe impl ForeignOwnable for Arc { - type PointedTo =3D ArcInner; + type PointedTo =3D T; type Borrowed<'a> =3D ArcBorrow<'a, T>; type BorrowedMut<'a> =3D Self::Borrowed<'a>; =20 fn into_foreign(self) -> *mut Self::PointedTo { - ManuallyDrop::new(self).ptr.as_ptr() + let this =3D ManuallyDrop::new(self).ptr.as_ptr(); + // SAFETY: `x` is a valid pointer to `Self` so the projection belo= w is + // in bounds of the allocation. + unsafe { core::ptr::addr_of_mut!((*this).data) } } =20 unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self { + // SAFETY: We did the reverse offset calculation in `into_foreign`= , so + // the offset calculation below is in bounds of the allocation. + let inner_ptr =3D unsafe { kernel::container_of!(ptr, ArcInner,= data).cast_mut() }; + // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - let inner =3D unsafe { NonNull::new_unchecked(ptr) }; + let inner =3D unsafe { NonNull::new_unchecked(inner_ptr) }; =20 // SAFETY: By the safety requirement of this function, we know tha= t `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `= ptr` is valid and @@ -365,9 +372,13 @@ unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> S= elf { } =20 unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> { + // SAFETY: We did the reverse offset calculation in `into_foreign`= , so + // the offset calculation below is in bounds of the allocation. + let inner_ptr =3D unsafe { kernel::container_of!(ptr, ArcInner,= data).cast_mut() }; + // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous // call to `Self::into_foreign`. - let inner =3D unsafe { NonNull::new_unchecked(ptr) }; + let inner =3D unsafe { NonNull::new_unchecked(inner_ptr) }; =20 // SAFETY: The safety requirements of `from_foreign` ensure that t= he object remains alive // for the lifetime of the returned value. --=20 2.47.0 From nobody Fri Apr 10 06:22:57 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 614BD24EF66; Mon, 24 Feb 2025 13:23:13 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403393; cv=none; b=b/iPYmuLrDDeXjayq8yuN2OtKu1oKKn40lmp+C+0ARmU0EM5bxZfy4rIpW6/m7bXGNpYfk8WXQIpw9QfPQKdOW1SGG8P2SrCgth8l2PvICOTG3sf6z6R8qmhkOsAiV7viRrZldUNp6Z4FB92fcO7zccjg1wlB4qgP2gO1izoUUk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403393; c=relaxed/simple; bh=90ZZBHomjVrDsziU7VSCkEQO+5Oe5K7+JzztSUDHVTI=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=cUvF/uqyWUqQKwFDgxNhnX3PdTatPox2aMxChxi1ai72ck6EIRx/JoHl17Lse/3Cl+vHO/0kZm6u6YLLQM87tt7KJB/rRQbfzijV1pkjnaxWITqAl0+fJKtwguu/nc6V1e8kBvRO6ANHUAnCbgUFcZjcEv9AWy3rIf1/tiLPAew= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BFBevaSK; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="BFBevaSK" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DD04C4CED6; Mon, 24 Feb 2025 13:23:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1740403393; bh=90ZZBHomjVrDsziU7VSCkEQO+5Oe5K7+JzztSUDHVTI=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=BFBevaSKhCzNc2u6CYX8SlymI8YWkg7sxpnlk9JZkM7oOT6jLLQ5Be9wLyMOzQXDT 1IZa8lzWef4haov8PrO1aekQbbTovN8SkARM2GwQwxpfNagRY+zZzJDf2bc1P7J8jI U9fPmVuj8Gn+x0MQEorBVFADhCHjMV/48KC4f80zGfH1RxNTvYSA6MRAacWDnproEq E8G38OsQf13lex/JWj/EbWLuHMDmpG0RdNSv4uKu+KRGXFRSfu0+N1vDcIpqRRGDW/ PD8/GpPYQSaXpbGYLt9hMHzf8QFptb09tx5cXfH7H/MJzpsqOY7gwZFRfz7DKjtNqW o2FderTGKgQHw== From: Andreas Hindborg Date: Mon, 24 Feb 2025 14:21:52 +0100 Subject: [PATCH v4 2/4] rust: configfs: introduce rust support for configfs Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250224-configfs-v4-2-9af9b5e611f6@kernel.org> References: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> In-Reply-To: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=37149; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=90ZZBHomjVrDsziU7VSCkEQO+5Oe5K7+JzztSUDHVTI=; b=owEBbAKT/ZANAwAIAeG4Gj55KGN3AcsmYgBnvHJ3XVp0IxV+IuT0+jCCbgdtfff6otaj5tpQW 2bPh81742aJAjIEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ7xydwAKCRDhuBo+eShj d4UmD/d1STuSRYWbYbV6r/mUlnBijbFRjQ2CMuSs5x3qcUIJPHpBANsgq4QfJhYErfLIrPAFNpP 4Tssig1U8/B0gsnDB1T9TmRQgfF7p4FJH9J06w9OIxlCQl7c+tnOZVH6dvM43wMjXhGrWZQ9Duf MqAYzsXc5sUeeB8nrb2NXRBNWpqLko6Z+3WxJzqDX/8tmyW4YdBDW5fNcrXH8WwAYXEchJicYhl EFwhC2FbBe5LoaURG/1877AhPussK1JhZkIXD+ZtOKVyXzoyG4MFx3rfmsn02CZxJ0ZNj9xr/Oo xJplgLy0nzbv0+WgvTF/iCXoydKofDny/NlCDrRZ8O7Hd/8TNIylzl3yABvl7bcqnAeaWxDGFlA 4jZvk8PIr+esG/WbwFzVA0NPN+crZonSZVESMln1yEjtw5M+QhO1G6f3KWBaY/9AG3tRFX7hv2q 6qltQ5YJoE/9Cg9uXIsa7uoGVtYXiIHLK/9G+fS8w9VJ4isy+OvkHqedJkLb/5qwzt8GhXdF2la xNozHnftVYf4ObcQCBooXPNfatzl9v2YbTzTyz8zT9tmkUao5JyAtdnF5EvCxR5loohzjvAgKIt g/vawQbbhO08CJUcxieTIVw+VgPpXDVSk6WLb8ASHXPsDlg304RjuO0ar1qABgZfREDk7WiPo7O OHQOy5hQRczfP X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 This patch adds a rust API for configfs, thus allowing rust modules to use configfs for configuration. The implementation is a shim on top of the C configfs implementation allowing safe use of the C infrastructure from rust. The patch enables the `const_mut_refs` feature on compilers before rustc 1.83. The feature was stabilized in rustc 1.83 and is not required to be explicitly enabled on later versions. Signed-off-by: Andreas Hindborg Tested-by: Daniel Almeida --- This patch is a direct dependency for `rnull`, the rust null block driver. --- rust/bindings/bindings_helper.h | 1 + rust/helpers/mutex.c | 5 + rust/kernel/configfs.rs | 938 ++++++++++++++++++++++++++++++++++++= ++++ rust/kernel/lib.rs | 2 + 4 files changed, 946 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 55354e4dec14..d115a770306f 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/mutex.c b/rust/helpers/mutex.c index 06575553eda5..3e9b910a88e9 100644 --- a/rust/helpers/mutex.c +++ b/rust/helpers/mutex.c @@ -17,3 +17,8 @@ void rust_helper_mutex_assert_is_held(struct mutex *mutex) { lockdep_assert_held(mutex); } + +void rust_helper_mutex_destroy(struct mutex *lock) +{ + mutex_destroy(lock); +} diff --git a/rust/kernel/configfs.rs b/rust/kernel/configfs.rs new file mode 100644 index 000000000000..fd19ddd209b1 --- /dev/null +++ b/rust/kernel/configfs.rs @@ -0,0 +1,938 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! `configfs` interface. +//! +//! `configfs` is an in-memory pseudo file system for configuration of ker= nel +//! modules. Please see the [C documentation] for details and intended use= of +//! `configfs`. +//! +//! This module does not support the following `configfs` features: +//! +//! - Items. All group children are groups. +//! - Symlink support. +//! - `disconnect_notify` hook. +//! - Default groups. +//! +//! See the [rust_configfs.rs] sample for a full example use of this modul= e. +//! +//! C header: [`include/linux/configfs.h`](srctree/include/linux/configfs.= h) +//! +//! # Example +//! +//! ```ignore +//! use kernel::alloc::flags; +//! use kernel::c_str; +//! use kernel::configfs_attrs; +//! use kernel::configfs; +//! use kernel::new_mutex; +//! use kernel::page::PAGE_SIZE; +//! use kernel::sync::Mutex; +//! use kernel::ThisModule; +//! +//! #[pin_data] +//! struct RustConfigfs { +//! #[pin] +//! config: configfs::Subsystem, +//! } +//! +//! impl kernel::InPlaceModule for RustConfigfs { +//! fn init(_module: &'static ThisModule) -> impl PinInit= { +//! pr_info!("Rust configfs sample (init)\n"); +//! +//! let item_type =3D configfs_attrs! { +//! container: configfs::Subsystem, +//! data: Configuration, +//! attributes: [ +//! message: 0, +//! bar: 1, +//! ], +//! }; +//! +//! try_pin_init!(Self { +//! config <- configfs::Subsystem::new( +//! c_str!("rust_configfs"), item_type, Configuration::new= () +//! ), +//! }) +//! } +//! } +//! +//! #[pin_data] +//! struct Configuration { +//! message: &'static CStr, +//! #[pin] +//! bar: Mutex<(KBox<[u8; PAGE_SIZE]>, usize)>, +//! } +//! +//! impl Configuration { +//! fn new() -> impl PinInit { +//! try_pin_init!(Self { +//! message: c_str!("Hello World\n"), +//! bar <- new_mutex!((KBox::new([0; PAGE_SIZE], flags::GFP_KE= RNEL)?, 0)), +//! }) +//! } +//! } +//! +//! #[vtable] +//! impl configfs::AttributeOperations<0> for Configuration { +//! type Data =3D Configuration; +//! +//! fn show(container: &Configuration, page: &mut [u8; PAGE_SIZE]) -> = Result { +//! pr_info!("Show message\n"); +//! let data =3D container.message; +//! page[0..data.len()].copy_from_slice(data); +//! Ok(data.len()) +//! } +//! } +//! +//! #[vtable] +//! impl configfs::AttributeOperations<1> for Configuration { +//! type Data =3D Configuration; +//! +//! fn show(container: &Configuration, page: &mut [u8; PAGE_SIZE]) -> = Result { +//! pr_info!("Show bar\n"); +//! let guard =3D container.bar.lock(); +//! let data =3D guard.0.as_slice(); +//! let len =3D guard.1; +//! page[0..len].copy_from_slice(&data[0..len]); +//! Ok(len) +//! } +//! +//! fn store(container: &Configuration, page: &[u8]) -> Result { +//! pr_info!("Store bar\n"); +//! let mut guard =3D container.bar.lock(); +//! guard.0[0..page.len()].copy_from_slice(page); +//! guard.1 =3D page.len(); +//! Ok(()) +//! } +//! } +//! ``` +//! +//! [C documentation]: srctree/Documentation/filesystems/configfs.rst +//! [rust_configfs.rs]: srctree/samples/rust/rust_configfs.rs + +use crate::alloc::flags; +use crate::container_of; +use crate::page::PAGE_SIZE; +use crate::prelude::*; +use crate::str::CString; +use crate::sync::Arc; +use crate::sync::ArcBorrow; +use crate::types::ForeignOwnable; +use crate::types::Opaque; +use core::cell::UnsafeCell; +use core::marker::PhantomData; +use core::ptr::addr_of; +use core::ptr::addr_of_mut; + +/// A `configfs` subsystem. +/// +/// This is the top level entrypoint for a `configfs` hierarchy. To regist= er +/// with configfs, embed a field of this type into your kernel module stru= ct. +#[pin_data(PinnedDrop)] +pub struct Subsystem { + #[pin] + subsystem: Opaque, + #[pin] + data: Data, +} + +// SAFETY: We do not provide any operations on `Subsystem`. +unsafe impl Sync for Subsystem {} + +// SAFETY: Ownership of `Subsystem` can safely be transferred to other thr= eads. +unsafe impl Send for Subsystem {} + +impl Subsystem { + /// Create an initializer for a [`Subsystem`]. + /// + /// The subsystem will appear in configfs as a directory name given by + /// `name`. The attributes available in directory are specified by + /// `item_type`. + pub fn new( + name: &'static CStr, + item_type: &'static ItemType, Data>, + data: impl PinInit, + ) -> impl PinInit { + try_pin_init!(Self { + subsystem <- kernel::init::zeroed().chain( + |place: &mut Opaque| { + // SAFETY: We initialized the required fields of `plac= e.group` above. + unsafe { + bindings::config_group_init_type_name( + &mut (*place.get()).su_group, + name.as_ptr(), + item_type.as_ptr(), + ) + }; + + // SAFETY: `place.su_mutex` is valid for use as a mute= x. + unsafe { + bindings::__mutex_init( + &mut (*place.get()).su_mutex, + kernel::optional_name!().as_char_ptr(), + kernel::static_lock_class!().as_ptr(), + ) + } + Ok(()) + } + ), + data <- data, + }) + .pin_chain(|this| { + crate::error::to_result( + // SAFETY: We initialized `this.subsystem` according to C = API contract above. + unsafe { bindings::configfs_register_subsystem(this.subsys= tem.get()) }, + ) + }) + } +} + +#[pinned_drop] +impl PinnedDrop for Subsystem { + fn drop(self: Pin<&mut Self>) { + // SAFETY: We registered `self.subsystem` in the initializer retur= ned by `Self::new`. + unsafe { bindings::configfs_unregister_subsystem(self.subsystem.ge= t()) }; + // SAFETY: We initialized the mutex in `Subsystem::new`. + unsafe { bindings::mutex_destroy(addr_of_mut!((*self.subsystem.get= ()).su_mutex)) }; + } +} + +/// Trait that allows offset calculations for structs that embed a +/// `bindings::config_group`. +/// +/// Users of the `configfs` API should not need to implement this trait. +/// +/// # Safety +/// +/// - Implementers of this trait must embed a `bindings::config_group`. +/// - Methods must be implemented according to method documentation. +pub unsafe trait HasGroup { + /// Return the address of the `bindings::config_group` embedded in `Se= lf`. + /// + /// # Safety + /// + /// - `this` must be a valid allocation of at least the size of `Self`. + unsafe fn group(this: *const Self) -> *const bindings::config_group; + + /// Return the address of the `Self` that `group` is embedded in. + /// + /// # Safety + /// + /// - `group` must point to the `bindings::config_group` that is embed= ded in + /// `Self`. + unsafe fn container_of(group: *const bindings::config_group) -> *const= Self; +} + +// SAFETY: `Subsystem` embeds a field of type `bindings::config_grou= p` +// within the `subsystem` field. +unsafe impl HasGroup for Subsystem { + unsafe fn group(this: *const Self) -> *const bindings::config_group { + // SAFETY: By impl and function safety requirement this projection= is in bounds. + unsafe { addr_of!((*(*this).subsystem.get()).su_group) } + } + + unsafe fn container_of(group: *const bindings::config_group) -> *const= Self { + // SAFETY: By impl and function safety requirement this projection= is in bounds. + let c_subsys_ptr =3D unsafe { container_of!(group, bindings::confi= gfs_subsystem, su_group) }; + let opaque_ptr =3D c_subsys_ptr.cast::>(); + // SAFETY: By impl and function safety requirement, `opaque_ptr` a= nd the + // pointer it returns, are within the same allocation. + unsafe { container_of!(opaque_ptr, Subsystem, subsystem) } + } +} + +/// A `configfs` group. +/// +/// To add a subgroup to `configfs`, pass this type as `ctype` to +/// [`crate::configfs_attrs`] when creating a group in [`GroupOperations::= make_group`]. +#[pin_data] +pub struct Group { + #[pin] + group: Opaque, + #[pin] + data: Data, +} + +impl Group { + /// Create an initializer for a new group. + /// + /// When instantiated, the group will appear as a directory with the n= ame + /// given by `name` and it will contain attributes specified by `item_= type`. + pub fn new( + name: CString, + item_type: &'static ItemType, Data>, + data: impl PinInit, + ) -> impl PinInit { + try_pin_init!(Self { + group <- kernel::init::zeroed().chain(|v: &mut Opaque| { + let place =3D v.get(); + let name =3D name.as_bytes_with_nul().as_ptr(); + // SAFETY: It is safe to initialize a group once it has be= en zeroed. + unsafe { + bindings::config_group_init_type_name(place, name.cast= (), item_type.as_ptr()) + }; + Ok(()) + }), + data <- data, + }) + } +} + +// SAFETY: `Group` embeds a field of type `bindings::config_group` +// within the `group` field. +unsafe impl HasGroup for Group { + unsafe fn group(this: *const Self) -> *const bindings::config_group { + Opaque::raw_get( + // SAFETY: By impl and function safety requirements this field + // projection is within bounds of the allocation. + unsafe { addr_of!((*this).group) }, + ) + } + + unsafe fn container_of(group: *const bindings::config_group) -> *const= Self { + let opaque_ptr =3D group.cast::>(); + // SAFETY: By impl and function safety requirement, `opaque_ptr` a= nd + // pointer it returns will be in the same allocation. + unsafe { container_of!(opaque_ptr, Self, group) } + } +} + +/// # Safety +/// +/// `this` must be a valid pointer. +/// +/// If `this` does not represent the root group of a `configfs` subsystem, +/// `this` must be a pointer to a `bindings::config_group` embedded in a +/// `Group`. +/// +/// Otherwise, `this` must be a pointer to a `bindings::config_group` that +/// is embedded in a `bindings::configfs_subsystem` that is embedded in a +/// `Subsystem`. +unsafe fn get_group_data<'a, Parent>(this: *mut bindings::config_group) ->= &'a Parent { + // SAFETY: `this` is a valid pointer. + let is_root =3D unsafe { (*this).cg_subsys.is_null() }; + + if !is_root { + // SAFETY: By C API contact, `this` is a pointer to a + // `bindings::config_group` that we passed as a return value in fr= om + // `make_group`. Such a pointer is embedded within a `Group`. + unsafe { &(*Group::::container_of(this)).data } + } else { + // SAFETY: By C API contract, `this` is a pointer to the + // `bindings::config_group` field within a `Subsystem`. + unsafe { &(*Subsystem::container_of(this)).data } + } +} + +struct GroupOperationsVTable(PhantomData<(Parent, Child)>); + +impl GroupOperationsVTable +where + Parent: GroupOperations, + Child: 'static, +{ + /// # Safety + /// + /// `this` must be a valid pointer. + /// + /// If `this` does not represent the root group of a `configfs` subsys= tem, + /// `this` must be a pointer to a `bindings::config_group` embedded in= a + /// `Group`. + /// + /// Otherwise, `this` must be a pointer to a `bindings::config_group` = that + /// is embedded in a `bindings::configfs_subsystem` that is embedded i= n a + /// `Subsystem`. + /// + /// `name` must point to a null terminated string. + unsafe extern "C" fn make_group( + this: *mut bindings::config_group, + name: *const kernel::ffi::c_char, + ) -> *mut bindings::config_group { + // SAFETY: By function safety requirements of this function, this = call + // is safe. + let parent_data =3D unsafe { get_group_data(this) }; + + let group_init =3D match Parent::make_group( + parent_data, + // SAFETY: By function safety requirements, name points to a n= ull + // terminated string. + unsafe { CStr::from_char_ptr(name) }, + ) { + Ok(init) =3D> init, + Err(e) =3D> return e.to_ptr(), + }; + + let child_group =3D > as InPlaceInit= >>::try_pin_init( + group_init, + flags::GFP_KERNEL, + ); + + match child_group { + Ok(child_group) =3D> { + let child_group_ptr =3D child_group.into_foreign(); + // SAFETY: We allocated the pointee of `child_ptr` above a= s a + // `Group`. + unsafe { Group::::group(child_group_ptr) }.cast_mut= () + } + Err(e) =3D> e.to_ptr(), + } + } + + /// # Safety + /// + /// If `this` does not represent the root group of a `configfs` subsys= tem, + /// `this` must be a pointer to a `bindings::config_group` embedded in= a + /// `Group`. + /// + /// Otherwise, `this` must be a pointer to a `bindings::config_group` = that + /// is embedded in a `bindings::configfs_subsystem` that is embedded i= n a + /// `Subsystem`. + /// + /// `item` must point to a `bindings::config_item` within a + /// `bindings::config_group` within a `Group`. + unsafe extern "C" fn drop_item( + this: *mut bindings::config_group, + item: *mut bindings::config_item, + ) { + // SAFETY: By function safety requirements of this function, this = call + // is safe. + let parent_data =3D unsafe { get_group_data(this) }; + + // SAFETY: By function safety requirements, `item` is embedded in a + // `config_group`. + let c_child_group_ptr =3D + unsafe { kernel::container_of!(item, bindings::config_group, c= g_item) }; + // SAFETY: By function safety requirements, `c_child_group_ptr` is + // embedded within a `Group`. + let r_child_group_ptr =3D unsafe { Group::::container_of(c_= child_group_ptr) }; + + if Parent::HAS_DROP_ITEM { + Parent::drop_item( + parent_data, + // SAFETY: We called `into_foreign` to produce `r_child_gr= oup_ptr` in + // `make_group`. There are not other borrows of this point= er in existence. + unsafe { + > as ForeignOwnable>::borrow(r_child_= group_ptr.cast_mut()) + }, + ); + } + + // SAFETY: By C API contract, we are required to drop a refcount on + // `item`. + unsafe { bindings::config_item_put(item) }; + } + + const VTABLE: bindings::configfs_group_operations =3D bindings::config= fs_group_operations { + make_item: None, + make_group: Some(Self::make_group), + disconnect_notify: None, + drop_item: Some(Self::drop_item), + is_visible: None, + is_bin_visible: None, + }; +} + +struct ItemOperationsVTable(PhantomData<(Container, Data)= >); + +impl ItemOperationsVTable, Data> +where + Data: 'static, +{ + /// # Safety + /// + /// `this` must be a pointer to a `bindings::config_group` embedded in= a + /// `Group`. + /// + /// This function will destroy the pointee of `this`. The pointee of `= this` + /// must not be accessed after the function returns. + unsafe extern "C" fn release(this: *mut bindings::config_item) { + // SAFETY: By function safety requirements, `this` is embedded in a + // `config_group`. + let c_group_ptr =3D unsafe { kernel::container_of!(this, bindings:= :config_group, cg_item) }; + // SAFETY: By function safety requirements, `c_group_ptr` is + // embedded within a `Group`. + let r_group_ptr =3D unsafe { Group::::container_of(c_group_p= tr) }; + + // SAFETY: We called `into_foreign` on `r_group_ptr` in + // `make_group`. + let pin_self =3D + unsafe { > as ForeignOwnable>::from_foreign(r_= group_ptr.cast_mut()) }; + drop(pin_self); + } + + const VTABLE: bindings::configfs_item_operations =3D bindings::configf= s_item_operations { + release: Some(Self::release), + allow_link: None, + drop_link: None, + }; +} + +impl ItemOperationsVTable, Data> { + const VTABLE: bindings::configfs_item_operations =3D bindings::configf= s_item_operations { + release: None, + allow_link: None, + drop_link: None, + }; +} + +/// Operations implemented by `configfs` groups that can create subgroups. +/// +/// Implement this trait on structs that embed a [`Subsystem`] or a [`Grou= p`]. +#[vtable] +pub trait GroupOperations { + /// The child data object type. + /// + /// This group will create subgroups (subdirectories) backed by this k= ind of + /// object. + type Child: 'static; + + /// Creates a new subgroup. + /// + /// The kernel will call this method in response to `mkdir(2)` in the + /// directory representing `this`. + /// + /// To accept the request to create a group, implementations should + /// return an initializer of a `Group`. To prevent creati= on, + /// return a suitable error. + fn make_group(&self, name: &CStr) -> Result, Error>>; + + /// Prepares the group for removal from configfs. + /// + /// The kernel will call this method before the directory representing + /// `_child` is removed from `configfs`. + /// + /// Implementations can use this method to do house keeping before + /// `configfs` drops its reference to `Child`. + fn drop_item(&self, _child: ArcBorrow<'_, Group>) { + kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR) + } +} + +/// A `configfs` attribute. +/// +/// An attribute appears as a file in configfs, inside a folder that repre= sent +/// the group that the attribute belongs to. +#[repr(transparent)] +pub struct Attribute { + attribute: Opaque, + _p: PhantomData<(O, Data)>, +} + +// SAFETY: We do not provide any operations on `Attribute`. +unsafe impl Sync for Attribute {} + +// SAFETY: Ownership of `Attribute` can safely be transferred to other thr= eads. +unsafe impl Send for Attribute {} + +impl Attribute +where + O: AttributeOperations, +{ + /// # Safety + /// + /// `item` must be embedded in a `bindings::config_group`. + /// + /// If `item` does not represent the root group of a `configfs` subsys= tem, + /// the group must be embedded in a `Group`. + /// + /// Otherwise, the group must be a embedded in a + /// `bindings::configfs_subsystem` that is embedded in a `Subsystem`. + /// + /// `page` must point to a writable buffer of size at least [`PAGE_SIZ= E`]. + unsafe extern "C" fn show( + item: *mut bindings::config_item, + page: *mut kernel::ffi::c_char, + ) -> isize { + let c_group: *mut bindings::config_group =3D + // SAFETY: By function safety requirements, `item` is embedded in a + // `config_group`. + unsafe { container_of!(item, bindings::config_group, cg_item) = }.cast_mut(); + + // SAFETY: The function safety requirements for this function sati= sfy + // the conditions for this call. + let data: &Data =3D unsafe { get_group_data(c_group) }; + + // SAFETY: By function safety requirements, `page` is writable for= `PAGE_SIZE`. + let ret =3D O::show(data, unsafe { &mut *(page as *mut [u8; PAGE_S= IZE]) }); + + match ret { + Ok(size) =3D> size as isize, + Err(err) =3D> err.to_errno() as isize, + } + } + + /// # Safety + /// + /// `item` must be embedded in a `bindings::config_group`. + /// + /// If `item` does not represent the root group of a `configfs` subsys= tem, + /// the group must be embedded in a `Group`. + /// + /// Otherwise, the group must be a embedded in a + /// `bindings::configfs_subsystem` that is embedded in a `Subsystem`. + /// + /// `page` must point to a readable buffer of size at least `size`. + unsafe extern "C" fn store( + item: *mut bindings::config_item, + page: *const kernel::ffi::c_char, + size: usize, + ) -> isize { + let c_group: *mut bindings::config_group =3D + // SAFETY: By function safety requirements, `item` is embedded in a + // `config_group`. + unsafe { container_of!(item, bindings::config_group, cg_item) = }.cast_mut(); + + // SAFETY: The function safety requirements for this function sati= sfy + // the conditions for this call. + let data: &Data =3D unsafe { get_group_data(c_group) }; + + let ret =3D O::store( + data, + // SAFETY: By function safety requirements, `page` is readable + // for at least `size`. + unsafe { core::slice::from_raw_parts(page.cast(), size) }, + ); + + match ret { + Ok(()) =3D> size as isize, + Err(err) =3D> err.to_errno() as isize, + } + } + + /// Create a new attribute. + /// + /// The attribute will appear as a file with name given by `name`. + pub const fn new(name: &'static CStr) -> Self { + Self { + attribute: Opaque::new(bindings::configfs_attribute { + ca_name: name as *const _ as _, + ca_owner: core::ptr::null_mut(), + ca_mode: 0o660, + show: Some(Self::show), + store: if O::HAS_STORE { + Some(Self::store) + } else { + None + }, + }), + _p: PhantomData, + } + } +} + +/// Operations supported by an attribute. +/// +/// Implement this trait on type and pass that type as generic parameter w= hen +/// creating an [`Attribute`]. The type carrying the implementation serve = no +/// purpose other than specifying the attribute operations. +#[vtable] +pub trait AttributeOperations { + /// The type of the object that contains the field that is backing the + /// attribute for this operation. + type Data; + + /// Renders the value of an attribute. + /// + /// This function is called by the kernel to read the value of an attr= ibute. + /// + /// Implementations should write the rendering of the attribute to `pa= ge` + /// and return the number of bytes written. + fn show(data: &Self::Data, page: &mut [u8; PAGE_SIZE]) -> Result; + + /// Stores the value of an attribute. + /// + /// This function is called by the kernel to update the value of an at= tribute. + /// + /// Implementations should parse the value from `page` and update inte= rnal + /// state to reflect the parsed value. + fn store(_data: &Self::Data, _page: &[u8]) -> Result { + kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR) + } +} + +/// A list of attributes. +/// +/// This type is used to construct a new [`ItemType`]. It represents a lis= t of +/// [`Attribute`] that will appear in the directory representing a [`Group= `]. +/// Users should not directly instantiate this type, rather they should us= e the +/// [`kernel::configfs_attrs`] macro to declare a static set of attributes= for a +/// group. +#[repr(transparent)] +pub struct AttributeList( + UnsafeCell<[*mut kernel::ffi::c_void; N]>, + PhantomData, +); + +// SAFETY: Ownership of `AttributeList` can safely be transferred to other= threads. +unsafe impl Send for AttributeList {} + +// SAFETY: We do not provide any operations on `AttributeList` that need s= ynchronization. +unsafe impl Sync for AttributeList {} + +impl AttributeList { + /// # Safety + /// + /// This function can only be called by the `configfs_attrs` + /// macro. + #[doc(hidden)] + pub const unsafe fn new() -> Self { + Self(UnsafeCell::new([core::ptr::null_mut(); N]), PhantomData) + } + + /// # Safety + /// + /// This function can only be called by the `configfs_attrs` + /// macro. + #[doc(hidden)] + pub const unsafe fn add< + const I: usize, + const ID: u64, + O: AttributeOperations, + >( + &'static self, + attribute: &'static Attribute, + ) { + // We need a space at the end of our list for a null terminator. + if I >=3D N - 1 { + kernel::build_error!("Invalid attribute index"); + } + + // SAFETY: This function is only called through the `configfs_attr= s` + // macro. This ensures that we are evaluating the function in const + // context when initializing a static. As such, the reference crea= ted + // below will be exclusive. + unsafe { + (&mut *self.0.get())[I] =3D (attribute as *const Attribute) + .cast_mut() + .cast() + }; + } +} + +/// A representation of the attributes that will appear in a [`Group`] or +/// [`Subsystem`]. +/// +/// Users should not directly instantiate objects of this type. Rather, th= ey +/// should use the [`kernel::configfs_attrs`] macro to statically declare = the +/// shape of a [`Group`] or [`Subsystem`]. +#[pin_data] +pub struct ItemType { + #[pin] + item_type: Opaque, + _p: PhantomData<(Container, Data)>, +} + +// SAFETY: We do not provide any operations on `ItemType` that need synchr= onization. +unsafe impl Sync for ItemType {} + +// SAFETY: Ownership of `ItemType` can safely be transferred to other thre= ads. +unsafe impl Send for ItemType {} + +macro_rules! impl_item_type { + ($tpe:ty) =3D> { + impl ItemType<$tpe, Data> { + #[doc(hidden)] + pub const fn new_with_child_ctor( + owner: &'static ThisModule, + attributes: &'static AttributeList, + ) -> Self + where + Data: GroupOperations, + Child: 'static, + { + Self { + item_type: Opaque::new(bindings::config_item_type { + ct_owner: owner.as_ptr(), + ct_group_ops: (&GroupOperationsVTable::::VTABLE as *const _) + as *mut _, + ct_item_ops: (&ItemOperationsVTable::<$tpe, Data>:= :VTABLE as *const _) + as *mut _, + ct_attrs: attributes as *const _ as _, + ct_bin_attrs: core::ptr::null_mut(), + }), + _p: PhantomData, + } + } + + #[doc(hidden)] + pub const fn new( + owner: &'static ThisModule, + attributes: &'static AttributeList, + ) -> Self { + Self { + item_type: Opaque::new(bindings::config_item_type { + ct_owner: owner.as_ptr(), + ct_group_ops: core::ptr::null_mut(), + ct_item_ops: (&ItemOperationsVTable::<$tpe, Data>:= :VTABLE as *const _) + as *mut _, + ct_attrs: attributes as *const _ as _, + ct_bin_attrs: core::ptr::null_mut(), + }), + _p: PhantomData, + } + } + } + }; +} + +impl_item_type!(Subsystem); +impl_item_type!(Group); + +impl ItemType { + fn as_ptr(&self) -> *const bindings::config_item_type { + self.item_type.get() + } +} + +/// Define a list of configfs attributes statically. +#[macro_export] +macro_rules! configfs_attrs { + ( + container: $container:ty, + data: $data:ty, + attributes: [ + $($name:ident: $attr:literal),* $(,)? + ] $(,)? + ) =3D> { + $crate::configfs_attrs!( + count: + @container($container), + @data($data), + @child(), + @no_child(x), + @attrs($($name $attr)*), + @eat($($name $attr,)*), + @assign(), + @cnt(0usize), + ) + }; + ( + container: $container:ty, + data: $data:ty, + child: $child:ty, + attributes: [ + $($name:ident: $attr:literal),* $(,)? + ] $(,)? + ) =3D> { + $crate::configfs_attrs!( + count: + @container($container), + @data($data), + @child($child), + @no_child(), + @attrs($($name $attr)*), + @eat($($name $attr,)*), + @assign(), + @cnt(0usize), + ) + }; + (count: + @container($container:ty), + @data($data:ty), + @child($($child:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat($name:ident $attr:literal, $($rname:ident $rattr:literal,)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) =3D> { + $crate::configfs_attrs!( + count: + @container($container), + @data($data), + @child($($child)?), + @no_child($($no_child)?), + @attrs($($aname $aattr)*), + @eat($($rname $rattr,)*), + @assign($($assign)* { + const N: usize =3D $cnt; + // The following macro text expands to a call to `Attribut= e::add`. + // SAFETY: We are expanding `configfs_attrs`. + unsafe { + $crate::macros::paste!( + [< $data:upper _ATTRS >] + .add::(&[< $data:upper _ $name:up= per _ATTR >]) + ) + }; + }), + @cnt(1usize + $cnt), + ) + }; + (count: + @container($container:ty), + @data($data:ty), + @child($($child:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat(), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) =3D> + { + $crate::configfs_attrs!( + final: + @container($container), + @data($data), + @child($($child)?), + @no_child($($no_child)?), + @attrs($($aname $aattr)*), + @assign($($assign)*), + @cnt($cnt), + ) + }; + (final: + @container($container:ty), + @data($data:ty), + @child($($child:ty)?), + @no_child($($no_child:ident)?), + @attrs($($name:ident $attr:literal)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) =3D> + { + $crate::macros::paste!{ + { + $( + // SAFETY: We are expanding `configfs_attrs`. + static [< $data:upper _ $name:upper _ATTR >]: + $crate::configfs::Attribute<$attr, $data, $data> = =3D + unsafe { + $crate::configfs::Attribute::new(c_str!(::= core::stringify!($name))) + }; + )* + + + // We need space for a null terminator. + const N: usize =3D $cnt + 1usize; + + // SAFETY: We are expanding `configfs_attrs`. + static [< $data:upper _ATTRS >]: + $crate::configfs::AttributeList =3D + unsafe { $crate::configfs::AttributeList::new() }; + + $($assign)* + + $( + const [<$no_child:upper>]: bool =3D true; + + static [< $data:upper _TPE >] : $crate::configfs::Item= Type<$container, $data> =3D + $crate::configfs::ItemType::<$container, $data>::n= ew::( + &THIS_MODULE, &[<$ data:upper _ATTRS >] + ); + )? + + $( + static [< $data:upper _TPE >]: + $crate::configfs::ItemType<$container, $data> =3D + $crate::configfs::ItemType::<$container, $data= >:: + new_with_child_ctor::( + &THIS_MODULE, &[<$ data:upper _ATTRS >] + ); + )? + + & [< $data:upper _TPE >] + } + } + }; + +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 496ed32b0911..ec84653ab8c7 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -40,6 +40,8 @@ pub mod block; #[doc(hidden)] pub mod build_assert; +#[cfg(CONFIG_CONFIGFS_FS)] +pub mod configfs; pub mod cred; pub mod device; pub mod device_id; --=20 2.47.0 From nobody Fri Apr 10 06:22:57 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 ACE6E19D8BE; Mon, 24 Feb 2025 13:23:29 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403409; cv=none; b=s2s28uQYzrF1kCctGbG6cEaF1RMJ/6Jl4xDehrXuT/yOzU376xA6KorfOOxT0bzEn2ToylJrNchTqSe7JOSt7qMf+R8o6rklPHKzIhjBig3it0AMbhmUl6Hr90PaxkOpIGsV3Jjr0qg+dGDs7fCf3dPLDoQ8iWWEWbGMqB/C4lo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403409; c=relaxed/simple; bh=otL8qnjlip9+uUZetH2yJjYrOd8m4ifjYcTxxT7VZwY=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=K1zXFEHkpq+q5gRLATL+0MoIRGYqZHPbi7LzpIOptMgTMdzhgOOVGBiFM/lLGqM8Z0MFQXMtKd2h90h9YbZe/L5cfRVi4y172olq5OsoUKgTkrQxu4LCQn7UDxqfYYJSLz+DLahc4bZLY9UT8cfHi+DDeObx3nbfL2/faP8DkZo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=eF7FF3Bt; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="eF7FF3Bt" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 67A3BC4CED6; Mon, 24 Feb 2025 13:23:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1740403409; bh=otL8qnjlip9+uUZetH2yJjYrOd8m4ifjYcTxxT7VZwY=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=eF7FF3Bt712Qhq5XiFG7I4j0TBw0p2hkYgLkK3BRylDwVMGedCi2+qA+crGvHbsc4 QFJfjjgC5BE5wCOkci4IjqddPAJBSt28AMnnvJ6yK1rywfVyq/sbt6VEkO0xtWPDiP nilEbIEgMfud4iX84YumCvFzYVSWBNlAp2Z7DkEyO2FalfFN5ziJiflukDObVlTJmO U20NM5sLkaNFPRbw4kBt2P7N9pd/2soY1vzfuV8mLJ0oTDD3QkuXpphTOPyK++hMAw CpUmyixyZ8XukCFWCGvsEMlP33YPjibh0PrVVO6pIcuSEFcnG53+GQhtixwn3gbYro StuEJMK/ahnIg== From: Andreas Hindborg Date: Mon, 24 Feb 2025 14:21:53 +0100 Subject: [PATCH v4 3/4] rust: configfs: add a sample demonstrating configfs usage Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250224-configfs-v4-3-9af9b5e611f6@kernel.org> References: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> In-Reply-To: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=6447; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=otL8qnjlip9+uUZetH2yJjYrOd8m4ifjYcTxxT7VZwY=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnvHJ4zCRWFkBVtZJzM5npHVoAndyA7slVLRbEQ I5RYlkbRI+JAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ7xyeAAKCRDhuBo+eShj d5LqD/9nZ97+EJf4Z8oycCR3vaz7rWJXOpmijX9jy5x9EDZKi3OhVou2WPZQMkNSoMQFBWVXF8Z qIWRWBAN6vcTJ6VUk1uAuqo4zAF13h2sywuMdfL2dFMI7P+o/6i8NcPDNR4Jh4ZUQdTd4fRmeDn m32u2EzgaG7YFQ2zsF6UTmkpGlJ/CGok5NkT7s81bZTu2lFYRxTfguE7pgEhLzFSjyHkMlQhZeA e90PsqSfYWELDK5RySqmknH/pEgr+8zmNcP9nge2X1dWZsNgGqBi6DR7Dk4n8fGLGtV/S+QJatZ qrXTVyNqDGOya0ukfPMvt4svVsX0FUeEXEfvNTPk0xSDQCnYbs922u+tOV8Aj6WD6+htIR6i2zF zRhHwbErNXfoS4mvCvVocAZGrlLGDpaJEokwLZtjP3hMQfwPlkpG4Me6CaeBKZIQ8p+u8Wep6wX RiN0wnChLi9A9+pYEjmY/Nh/plGvAaI67oJF93e3uupZKfTQ6gegB4CnBS++55WNMFegY/ZJ2aR Vm2hwqD08u8X7n1E5gMj9JqGk5ZFnrjCSLx6svUqKbfk1yc0LGRuldSnqHMAgSqaeP5/cxGagmI 8v8Ack54H9CcuCBht36sbBI9siJ2JJloPRrnYL58BxjcN48CnUMBX32PWwmCA+TusPJH8sUt6iY REhswEwez7qA52A== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add a sample to the samples folder, demonstrating the intended use of the rust configfs API. Signed-off-by: Andreas Hindborg Reviewed-by: Daniel Almeida Tested-by: Daniel Almeida --- samples/rust/Kconfig | 11 +++ samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 179 ++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 191 insertions(+) diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 918dbead2c0b..2f97bf9a7b4c 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -10,6 +10,17 @@ menuconfig SAMPLES_RUST =20 if SAMPLES_RUST =20 +config SAMPLE_RUST_CONFIGFS + tristate "Configfs sample" + depends on CONFIGFS_FS + help + This option builds the Rust configfs sample. + + To compile this as a module, choose M here: + the module will be called rust_configfs. + + If unsure, say N. + config SAMPLE_RUST_MINIMAL tristate "Minimal" help diff --git a/samples/rust/Makefile b/samples/rust/Makefile index 5a8ab0df0567..72122f010caf 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -6,6 +6,7 @@ obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE) +=3D rust_misc_devic= e.o obj-$(CONFIG_SAMPLE_RUST_PRINT) +=3D rust_print.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) +=3D rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) +=3D rust_driver_platform.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) +=3D rust_configfs.o =20 rust_print-y :=3D rust_print_main.o rust_print_events.o =20 diff --git a/samples/rust/rust_configfs.rs b/samples/rust/rust_configfs.rs new file mode 100644 index 000000000000..36a2c848a979 --- /dev/null +++ b/samples/rust/rust_configfs.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust configfs sample. + +use kernel::alloc::flags; +use kernel::c_str; +use kernel::configfs; +use kernel::configfs_attrs; +use kernel::new_mutex; +use kernel::page::PAGE_SIZE; +use kernel::prelude::*; +use kernel::sync::Mutex; + +module! { + type: RustConfigfs, + name: "rust_configfs", + author: "Rust for Linux Contributors", + description: "Rust configfs sample", + license: "GPL", +} + +#[pin_data] +struct RustConfigfs { + #[pin] + config: configfs::Subsystem, +} + +#[pin_data] +struct Configuration { + message: &'static CStr, + #[pin] + bar: Mutex<(KBox<[u8; PAGE_SIZE]>, usize)>, +} + +impl Configuration { + fn new() -> impl PinInit { + try_pin_init!(Self { + message: c_str!("Hello World\n"), + bar <- new_mutex!((KBox::new([0; PAGE_SIZE], flags::GFP_KERNEL= )?, 0)), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { + fn init(_module: &'static ThisModule) -> impl PinInit { + pr_info!("Rust configfs sample (init)\n"); + + let item_type =3D configfs_attrs! { + container: configfs::Subsystem, + data: Configuration, + child: Child, + attributes: [ + message: 0, + bar: 1, + ], + }; + + try_pin_init!(Self { + config <- configfs::Subsystem::new( + c_str!("rust_configfs"), item_type, Configuration::new() + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { + type Child =3D Child; + + fn make_group(&self, name: &CStr) -> Result, Error>> { + let tpe =3D configfs_attrs! { + container: configfs::Group, + data: Child, + child: GrandChild, + attributes: [ + baz: 0, + ], + }; + + Ok(configfs::Group::new(name.try_into()?, tpe, Child::new())) + } +} + +#[vtable] +impl configfs::AttributeOperations<0> for Configuration { + type Data =3D Configuration; + + fn show(container: &Configuration, page: &mut [u8; PAGE_SIZE]) -> Resu= lt { + pr_info!("Show message\n"); + let data =3D container.message; + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} + +#[vtable] +impl configfs::AttributeOperations<1> for Configuration { + type Data =3D Configuration; + + fn show(container: &Configuration, page: &mut [u8; PAGE_SIZE]) -> Resu= lt { + pr_info!("Show bar\n"); + let guard =3D container.bar.lock(); + let data =3D guard.0.as_slice(); + let len =3D guard.1; + page[0..len].copy_from_slice(&data[0..len]); + Ok(len) + } + + fn store(container: &Configuration, page: &[u8]) -> Result { + pr_info!("Store bar\n"); + let mut guard =3D container.bar.lock(); + guard.0[0..page.len()].copy_from_slice(page); + guard.1 =3D page.len(); + Ok(()) + } +} + +#[pin_data] +struct Child {} + +impl Child { + fn new() -> impl PinInit { + try_pin_init!(Self {}) + } +} + +#[vtable] +impl configfs::GroupOperations for Child { + type Child =3D GrandChild; + + fn make_group(&self, name: &CStr) -> Result, Error>> { + let tpe =3D configfs_attrs! { + container: configfs::Group, + data: GrandChild, + attributes: [ + gc: 0, + ], + }; + + Ok(configfs::Group::new( + name.try_into()?, + tpe, + GrandChild::new(), + )) + } +} + +#[vtable] +impl configfs::AttributeOperations<0> for Child { + type Data =3D Child; + + fn show(_container: &Child, page: &mut [u8; PAGE_SIZE]) -> Result { + pr_info!("Show baz\n"); + let data =3D c"Hello Baz\n".to_bytes(); + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} + +#[pin_data] +struct GrandChild {} + +impl GrandChild { + fn new() -> impl PinInit { + try_pin_init!(Self {}) + } +} + +#[vtable] +impl configfs::AttributeOperations<0> for GrandChild { + type Data =3D GrandChild; + + fn show(_container: &GrandChild, page: &mut [u8; PAGE_SIZE]) -> Result= { + pr_info!("Show baz\n"); + let data =3D c"Hello GC\n".to_bytes(); + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} --=20 2.47.0 From nobody Fri Apr 10 06:22:57 2026 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (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 4502C248865; Mon, 24 Feb 2025 13:23:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403388; cv=none; b=bHNiqEqOtBxdNYCyCqWZ2pbEY/CVDCABuZhLwuCe66gLLqMNXTCAbQfCtBT5YT4j0sB4a4lzNJr2nhy5F/7KRDy4NE77vGpS/rgdyU+pvMitje6NBTutRY6FDZfoV7ngPQ9XCKZ8OmQhaKNnPtE3E+iUn6EUFZh7lxbzY+/CzKY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1740403388; c=relaxed/simple; bh=+z4Qntkcydw5p8gD+O/kjP+ApAlaMKoppAU6zXIFVBI=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=XkrfB1gQlZgMwAc8uUn0Rf/4abYxBAS/QD5i2u83yo3IYkBkh0LTVjrjfJ+Zkvj3hWVTtOmK/ZL8UAEC2ezt1ge0h6vwTvJpOIW+cJrwK5mbjZxl0jw3i+KR8xjYTx3f4kmUAlS9wfVaVnKWZjwccQ+acUyyRMIVErB5SO5/lQw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=oh8uZrz8; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="oh8uZrz8" Received: by smtp.kernel.org (Postfix) with ESMTPSA id E5E18C4CED6; Mon, 24 Feb 2025 13:23:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1740403387; bh=+z4Qntkcydw5p8gD+O/kjP+ApAlaMKoppAU6zXIFVBI=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=oh8uZrz8vTBOP80tEzohCsQvGzdSkN6JbWv7HUiAGzh3XWaET19DjC+95usJOdmDn jYa9CmCPHR/siSNRonMY2yuqTVqfUPrLCNwAtq/oV2aKLKtFx4wQA8hKJfuUL9Swzb d3LnTlk8fJ7zhbvIMBr4HWHOc/nr1rE4qoMkpFY2bd4tZ4KUpwzjE20FqA0r9E292x dQ0z6K6FF1RnqTZ71ynKeTrzA/U43gAVEZZllcJnqM+1HvOdPNkgP7+QBmN6fTuVWB sdj3df/ppHkdNtRGlSxhasS5Mjv4PF93MyF5FFfGn+/XbsB5bmMHSKzvdNKmq7p+w5 yZXhYcezPQkrQ== From: Andreas Hindborg Date: Mon, 24 Feb 2025 14:21:54 +0100 Subject: [PATCH v4 4/4] MAINTAINERS: add entry for configfs Rust abstractions Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250224-configfs-v4-4-9af9b5e611f6@kernel.org> References: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> In-Reply-To: <20250224-configfs-v4-0-9af9b5e611f6@kernel.org> To: Danilo Krummrich , Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Trevor Gross , Joel Becker , Christoph Hellwig , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.15-dev X-Developer-Signature: v=1; a=openpgp-sha256; l=705; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=+z4Qntkcydw5p8gD+O/kjP+ApAlaMKoppAU6zXIFVBI=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBnvHJ4wlau95nGdwpOnToMKvuyFYPqy7rzfoJ+4 n65timRYTyJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCZ7xyeAAKCRDhuBo+eShj d4+zEACRptyLeLIfcnZAR8wJ808Y8vhaiezLsy2elgxRivoKbUEVoeg6aauggApT37nw8/32o8W 10J7D27KQVvK2Mvo6oUZV04amrkQFFWCFmWKF8TzyLnF9vbBl/vUBZrHwO+wpw6ycX7kanVW+1b 2nbuqgA283NxY/p8VcPq6feQKjcIW2RWvAUxhLFcyZhzbhe2LYg63u0k0oYzYMlimTLvDrvnFNI NSB8NDWGk5D4R3rQX6P6+bjwzuB8X20QJrVyEE50I1uW8B+txJCblyHIPokxVK/W9qQXdnkeihO wE01uaX1+2xYVP+RpkmhmUYmD0mQCAOztw/Aq1/sSwnJabWNr6qto1gJvJ5yhgGWUedJLBoOxWQ Povh0Tl1Iae/qfdNAtS7hzeB1ghxjsi/f/9lYbRjX6eaCDLsB/lkUVMR9dxs913y48ClyxYGfNf eeDSzXAdpTJQpEW9K8OFZ/D6nD3bkvt9DOcLig+tBRWO537GykojsdiXYTBI/qoHFN2ba4LY1ge dOtcb20WgQtjYw0TNQq+9VZQEroaMu0+5imPWauLKUIwylLlSpmw+gdnKfmSDKbfZRLto8yfiLk 4OUO4u11GfJAUwJ7PlNPIxPORrIkr5sLOgh2TFmx2SDcgWqTvrIJMUQ6CVoz9qm3ftgds7bz80m edHufPI+0de+sAA== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Update MAINTAINERS with entry for Rust configfs abstractions. Signed-off-by: Andreas Hindborg Acked-by: Daniel Almeida Tested-by: Daniel Almeida --- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 896a307fa065..9b4d5c12eb43 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5870,6 +5870,13 @@ F: fs/configfs/ F: include/linux/configfs.h F: samples/configfs/ =20 +CONFIGFS [RUST] +M: Andreas Hindborg +L: rust-for-linux@vger.kernel.org +S: Supported +F: rust/kernel/configfs.rs +F: samples/rust/rust_configfs.rs + CONGATEC BOARD CONTROLLER MFD DRIVER M: Thomas Richard S: Maintained --=20 2.47.0