From nobody Fri Dec 19 09:01:16 2025 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 5FA2D239E95; Thu, 8 May 2025 08:52:57 +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=1746694377; cv=none; b=kn/mfSQBJoU4eptphi+1JqCAm4oOUYd9m7c0cyFyQL2pxIRgF1hyMKng+nJrzFJelf/1dfL7iYNi6iQikPuGD0TDhrtJC5m0rTGnwmF/2Y7zK7fsvzbe12mEt7+q5feWk7wBF2MYAmw0vc8orIiJ9lH16cFVlp0FGimp0UJnpGE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746694377; c=relaxed/simple; bh=25VgMXQwcOeFAfPq2C8F/zh4DuBtW1PXYbNcDT6gYQU=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=pokszRS65m4cg97eObrTtVh1t2u0hCc1yMSicsaMh3TLPDQMCAG537VgStq9OurJRLeKUbw4ncxbP+H6EhwNlTNl9FF46WYaPjRsgbr+paccr4f045reaP7nsFFU7JpqDJYPDXCEPRSc0KwZXMI4A9ImhhmChB5g8DtTI1X0EM4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=fNX7Uxf8; 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="fNX7Uxf8" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 31614C4CEE7; Thu, 8 May 2025 08:52:51 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746694376; bh=25VgMXQwcOeFAfPq2C8F/zh4DuBtW1PXYbNcDT6gYQU=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=fNX7Uxf8FL9KZZe9R7zuaNNxQva6nMAhE2gDqXeHdwh5v8G50Q9umKnryurDEIZcz 4fBDCCoTohgX8Uui2ccF+SC0LnKifudYQ1KULspgJ0wShN00VxSFrq72a8TQWk0X99 LqK65yBTvZdeoNJ/Ai1IEq9um3N1lIhaENaJ6wuCUFMz11LNcwgy6DWVc/YxK3FTvA grjNGOkiIw2U7pKOKOSf3HAj+9kpdYrXJW0GcJ1Yvwd1nn4EReIPTCpUMoK+tM0mla IT/dBUxQFIY9TtCs4zniwr88sJv5ckYBX529DrnuY/weQ/4C6LE/5tlPtOk3ztvYtH QICfpvSL3ET1w== From: Andreas Hindborg Date: Thu, 08 May 2025 10:52:09 +0200 Subject: [PATCH v8 1/3] 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: <20250508-configfs-v8-1-8ebde6180edc@kernel.org> References: <20250508-configfs-v8-0-8ebde6180edc@kernel.org> In-Reply-To: <20250508-configfs-v8-0-8ebde6180edc@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 , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida , Breno Leitao Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.14.2 X-Developer-Signature: v=1; a=openpgp-sha256; l=41518; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=25VgMXQwcOeFAfPq2C8F/zh4DuBtW1PXYbNcDT6gYQU=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBoHHDJaDQ49bk/lCFOvPHpvGUvqsPiGgeYmsvas 8G9IeTBgnqJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaBxwyQAKCRDhuBo+eShj dyYoD/9YpFS/SpKWWq11QIFga/6dbfioAUMZxbt07vHAj20LKj1gACyH4u3BwUWHVoJ13LOwFXq dJ1IJvKooNdJy5wAJiVHEW+prtS/o8gP5+ffzKCWXiqxf/5HbTg5ium+kwLxZD988/8lCFmqG7K 56tCbJea4/u0PsFArDgQPqxEOUVvQI9c5MgcqgKDalx9RYTezDvQbgM6LakKhSIxpojt4FnSuyz v+GvhMcyOa0MegtQC7EiLimu/jTRZxdM8CNO5O7xnNfKmCpsq66nEglGAL+jUMdJD7lrOoyF5r1 4UOMrK7SLtG3FmIva9oyENGCwy38Obu0Y5LYfR8jofZdEwIsmjpwuvOXLU5H3PX3abdNzJ7CM87 RhoSy97sM54Mv1vi0rnOdbij6Ac05SDKH7vY+ftSYIXGjNGQSGjp3cX6o07j6rxyNKYI5AgBOYY w9ieVg7vM6eWlT9RsaAUwMRRxWjbpH/6u/sN31Sg2J1cCpLFiP/uT/q//X/XdEjuBrg/mnkayTL XYARdOma95c+vr2MZArQvZ/ZMXSFmxG1tVHwq8j0GWoBk2wY/4yISO9AprRm6HU0IP2C8GEsxU0 2iFA/N9CUbZloqvdsTNtlhWRG7njY7MJ2inadAH3HonnNEpxOtDj4dL+ER7jU7fK8ZZExy8EDTY s0VTUvqSoOQq0cQ== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add a Rust API for configfs, thus allowing Rust modules to use configfs for configuration. Make the implementation a shim on top of the C configfs implementation, allowing safe use of the C infrastructure from Rust. Signed-off-by: Andreas Hindborg --- 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 | 1049 +++++++++++++++++++++++++++++++++++= ++++ rust/kernel/lib.rs | 2 + 4 files changed, 1057 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index ab37e1d35c70d52e69b754bf855bc19911d156d8..1a532b83a9afedb4965cfaab4ba= c21adbab2a7de 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 06575553eda5c5a99ab27ef38101f9bf0c7f5644..3e9b910a88e9bc20a283901bb4c= 846ea2e4a9616 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 0000000000000000000000000000000000000000..b93ac7b0bebc21caea4a6d35f67= 25b5c900f27ec --- /dev/null +++ b/rust/kernel/configfs.rs @@ -0,0 +1,1049 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! configfs interface: Userspace-driven Kernel Object Configuration +//! +//! configfs is an in-memory pseudo file system for configuration of kernel +//! 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 mod= ule. +//! +//! 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::Opaque; +use core::cell::UnsafeCell; +use core::marker::PhantomData; + +/// A configfs subsystem. +/// +/// This is the top level entrypoint for a configfs hierarchy. To register +/// 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 <- pin_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(&raw 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 [`S= elf`]. + /// + /// # 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 { &raw const (*(*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 <- pin_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 { &raw const (*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` was returned from a call to + // `make_group`. The pointer is known to be 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 subsyste= m, + /// `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_raw(); + // 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 subsyste= m, + /// `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 { container_of!(item, bindings::c= onfig_group, cg_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 { + // SAFETY: We called `into_raw` to produce `r_child_group_ptr`= in + // `make_group`. + let arc: Arc> =3D unsafe { Arc::from_raw(r_child_= group_ptr.cast_mut()) }; + + Parent::drop_item(parent_data, arc.as_arc_borrow()); + arc.into_raw(); + } + + // 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, + }; + + const fn vtable_ptr() -> *const bindings::configfs_group_operations { + &Self::VTABLE as *const bindings::configfs_group_operations + } +} + +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_raw` on `r_group_ptr` in + // `make_group`. + let pin_self: Arc> =3D unsafe { Arc::from_raw(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, + }; + + const fn vtable_ptr() -> *const bindings::configfs_item_operations { + &Self::VTABLE as *const bindings::configfs_item_operations + } +} + +impl ItemOperationsVTable, Data> { + const VTABLE: bindings::configfs_item_operations =3D bindings::configf= s_item_operations { + release: None, + allow_link: None, + drop_link: None, + }; + + const fn vtable_ptr() -> *const bindings::configfs_item_operations { + &Self::VTABLE as *const bindings::configfs_item_operations + } +} + +/// 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 con= figfs drops its + /// reference to `Child`. + /// + /// NOTE: "drop" in the name of this function is not related to the Ru= st drop term. Rather, the + /// name is inherited from the callback name in the underlying C code. + 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 subsyste= m, + /// 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 subsyste= m, + /// 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_char_ptr(), + 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. +/// +/// This trait must be implemented on the `Data` type of for types that +/// implement `HasGroup`. The trait must be implemented once for each +/// attribute of the group. The constant type parameter `ID` maps the +/// implementation to a specific `Attribute`. `ID` must be passed when dec= laring +/// attributes via the [`kernel::configfs_attrs`] macro, to tie +/// `AttributeOperations` implementations to concrete named attributes. +#[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. +/// +/// # Note +/// +/// Instances of this type are constructed statically at compile by the +/// [`kernel::configfs_attrs`] macro. +#[repr(transparent)] +pub struct AttributeList( + /// Null terminated Array of pointers to [`Attribute`]. The type is [`= c_void`] + /// to conform to the C API. + 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 must only be called by the [`kernel::configfs_attrs`] + /// macro. + #[doc(hidden)] + pub const unsafe fn new() -> Self { + Self(UnsafeCell::new([core::ptr::null_mut(); N]), PhantomData) + } + + /// # Safety + /// + /// The caller must ensure that there are no other concurrent accesses= to + /// `self`. That is, the caller has exclusive access to `self.` + #[doc(hidden)] + pub const unsafe fn add( + &'static self, + attribute: &'static Attribute, + ) where + O: AttributeOperations, + { + // We need a space at the end of our list for a null terminator. + const { assert!(I < N - 1, "Invalid attribute index") }; + + // SAFETY: By function safety requirements, we have exclusive acce= ss to + // `self` and the reference created 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_ptr().cast_mut(), + ct_item_ops: ItemOperationsVTable::<$tpe, Data>::v= table_ptr().cast_mut(), + ct_attrs: (attributes as *const AttributeList) + .cast_mut() + .cast(), + 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>::v= table_ptr().cast_mut(), + ct_attrs: (attributes as *const AttributeList) + .cast_mut() + .cast(), + 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. +/// +/// Invoking the macro in the following manner: +/// +/// ```ignore +/// let item_type =3D configfs_attrs! { +/// container: configfs::Subsystem, +/// data: Configuration, +/// child: Child, +/// attributes: [ +/// message: 0, +/// bar: 1, +/// ], +/// }; +/// ``` +/// +/// Expands the following output: +/// +/// ```ignore +/// let item_type =3D { +/// static CONFIGURATION_MESSAGE_ATTR: kernel::configfs::Attribute< +/// 0, +/// Configuration, +/// Configuration, +/// > =3D unsafe { +/// kernel::configfs::Attribute::new({ +/// const S: &str =3D "message\u{0}"; +/// const C: &kernel::str::CStr =3D match kernel::str::CStr::f= rom_bytes_with_nul( +/// S.as_bytes() +/// ) { +/// Ok(v) =3D> v, +/// Err(_) =3D> { +/// core::panicking::panic_fmt(core::const_format_args= !( +/// "string contains interior NUL" +/// )); +/// } +/// }; +/// C +/// }) +/// }; +/// +/// static CONFIGURATION_BAR_ATTR: kernel::configfs::Attribute< +/// 1, +/// Configuration, +/// Configuration +/// > =3D unsafe { +/// kernel::configfs::Attribute::new({ +/// const S: &str =3D "bar\u{0}"; +/// const C: &kernel::str::CStr =3D match kernel::str::CStr::f= rom_bytes_with_nul( +/// S.as_bytes() +/// ) { +/// Ok(v) =3D> v, +/// Err(_) =3D> { +/// core::panicking::panic_fmt(core::const_format_args= !( +/// "string contains interior NUL" +/// )); +/// } +/// }; +/// C +/// }) +/// }; +/// +/// const N: usize =3D (1usize + (1usize + 0usize)) + 1usize; +/// +/// static CONFIGURATION_ATTRS: kernel::configfs::AttributeList =3D +/// unsafe { kernel::configfs::AttributeList::new() }; +/// +/// { +/// const N: usize =3D 0usize; +/// unsafe { CONFIGURATION_ATTRS.add::(&CONFIGURATION_MES= SAGE_ATTR) }; +/// } +/// +/// { +/// const N: usize =3D (1usize + 0usize); +/// unsafe { CONFIGURATION_ATTRS.add::(&CONFIGURATION_BAR= _ATTR) }; +/// } +/// +/// static CONFIGURATION_TPE: +/// kernel::configfs::ItemType ,C= onfiguration> +/// =3D kernel::configfs::ItemType::< +/// configfs::Subsystem, +/// Configuration +/// >::new_with_child_ctor::( +/// &THIS_MODULE, +/// &CONFIGURATION_ATTRS +/// ); +/// +/// &CONFIGURATION_TPE +/// } +/// ``` +#[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: By design of this macro, the name of the variab= le we + // invoke the `add` method on below, is not visible outsid= e of + // the macro expansion. The macro does not operate concurr= ently + // on this variable, and thus we have exclusive access to = the + // variable. + 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 de07aadd1ff5fe46fd89517e234b97a6590c8e93..bcbf5026449d80d3b1493c782d3= c1c63103391e1 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -42,6 +42,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.2 From nobody Fri Dec 19 09:01:16 2025 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 F1781239E95; Thu, 8 May 2025 08:53: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=1746694388; cv=none; b=QPnNAw0ouPGUYozT07b2boux0f6U8bpS8WOGWBQ63qqPct2NuqhZeyO9v7nm5wolEDruvndTFlGUmsdy8wINMS9ZdeDmdit1Oqj6oH7R7+6Jth8UWPShI5hDI1HE7jR0HYqYMhdw6F8IriSaF1xDr2n+HQ4bgFuJNneyUnU4lv8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746694388; c=relaxed/simple; bh=15IRdWQGob8rEQnCZVjyZFm4/ckUzAPLo90k4EdjFYg=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=PpqN7drPXpYzr+9+ecUmCr9NSiaO1B/0BAM7/Aa8jRl05aat5vrZ6LuTKOJfLVBYg1HFdzYcOQ9+IBQRUR1FfNIm6C1W772Z/DT1YZHH6UOOj/UdciYrxLHymvnk5RMYUs18OysL05rUJ0xuWBnbz/8WpDkp05lEuib0riRMkXI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BOo5TH5r; 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="BOo5TH5r" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C9908C4CEE7; Thu, 8 May 2025 08:53:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746694387; bh=15IRdWQGob8rEQnCZVjyZFm4/ckUzAPLo90k4EdjFYg=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=BOo5TH5rZLDF377GP/txciNaj/WL3toVq85kPL0zkROzRADJ1GUJ1LjlrY90h4gyC F9zrwJzYtX06/wlyaiw8SBphq4FlavLQsczBFqa66pqDUBMgosWvgTRUuRaGfZoP3Q 9NdaL15bgbIX7veaLzcxjV10002mdkrFQE0fTeEgKd/jH+yL3a2slsNvt3SAb9DSXQ Jbz9VhxioJNBnO3ys8NqpQLblU7r4nui9TqxpKgRVtiddQwFF/0etAWOIc03bMugLF GnQPk9C2DIsOBBlR8F87H/3YrJEGIpA2L8fDaJyBouHUH7asGUNtxLIjGsvDIvmC/D iWKMiJtclmRPg== From: Andreas Hindborg Date: Thu, 08 May 2025 10:52:10 +0200 Subject: [PATCH v8 2/3] 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: <20250508-configfs-v8-2-8ebde6180edc@kernel.org> References: <20250508-configfs-v8-0-8ebde6180edc@kernel.org> In-Reply-To: <20250508-configfs-v8-0-8ebde6180edc@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 , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida , Breno Leitao Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.14.2 X-Developer-Signature: v=1; a=openpgp-sha256; l=7524; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=15IRdWQGob8rEQnCZVjyZFm4/ckUzAPLo90k4EdjFYg=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBoHHDKL6c6pQQoRsx8uZzhaYVf4qA4WVS8zVa8B lVThMr23iSJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaBxwygAKCRDhuBo+eShj d7sWEAChED/w+wldOgABtlHqB6ECLbtBYbMU8NPxWkW0UmHUNBLdyWSAH0ytJikNfr2C9drjnrg G0grYcTbCYSKYvShHBJx8Ixx97ry1LI+idPbov7bVinok/3thPmvH7vUBFNGor046kKm68w6kvp e/x2zOtyNULIfWObpXw5rvQPF70H7s+M/9kKjTJWj1U/yQHJW76C8LVQhkXgN1UC4HoF2qpHYxA VccPtLUVlNWXgM74+zCiGH1j7nIIrE0TLkxxc8rQlvtQ45YbIPidqU7V31SXCoDe8lVfNV34roC yQFfNCWRfUdqCZATBVa56pxjQSi0355r7Q0d3i+SFOvPb+UcelBAFGw/wp+oz+8Mcf9vKXDvBMT 9ld/fWU0Nx5VStN2bBNWL+R7DlPdlVdgKVH5FwTNnBwuFyp5WVuHEFAsgjG/zEXSPfCdZWKAGxB Ce2MaMBp3zK/bBPmeh6/w/L6CGtLlHjrOMxUmPP4luiZs9TiC39ZQS+RV8ul6GPcvQcKcxzLj/Q qSsTufv1KE6Q2C6Ovmi9dRh/bqbsJURcJcDku57920CDfJV2tw9aTFNIGGDmfT3VvMsxpjyFM11 8F/XWF6CiU6uTAN56ScqYoXKiWm3MkdPqJi0pTrGBfWCoyRFU4qOLJ4MTid/CgJ8YA0mD8RBVjL FcFfylzSub8Trew== 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 --- samples/rust/Kconfig | 11 +++ samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++++++++++++++++++++++++++++++= ++++ 3 files changed, 204 insertions(+) diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index cad52b7120b5143e85d737234be4ff27d2c7f99f..be491ad9b3af1b21d5c1d6000ef= 6c5488f9c5e91 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 c6a2479f7d9cf3a8695fa08b33b71d0df077eb59..b3c9178d654afed5c9553b1b6fa= 91ae8736c316e 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DMA) +=3D rust_dma.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_DRIVER_FAUX) +=3D rust_driver_faux.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 0000000000000000000000000000000000000000..60ddbe62cda31465f799f1c15f9= 2bdc88f855830 --- /dev/null +++ b/samples/rust/rust_configfs.rs @@ -0,0 +1,192 @@ +// 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"); + + // Define a subsystem with the data type `Configuration`, two + // attributes, `message` and `bar` and child group type `Child`. `= mkdir` + // in the directory representing this subsystem will create direct= ories + // backed by the `Child` type. + 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>> { + // Define a group with data type `Child`, one attribute `baz` and = child + // group type `GrandChild`. `mkdir` in the directory representing = this + // group will create directories backed by the `GrandChild` type. + 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` cannot handle structs without braces. +#[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>> { + // Define a group with data type `GrandChild`, one attribute `gc`.= As no + // child type is specified, it will not be possible to create subg= roups + // in this group, and `mkdir`in the directory representing this gr= oup + // will return an 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` cannot handle structs without braces. +#[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 grand child\n"); + let data =3D c"Hello GC\n".to_bytes(); + page[0..data.len()].copy_from_slice(data); + Ok(data.len()) + } +} --=20 2.47.2 From nobody Fri Dec 19 09:01:16 2025 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 01991239E95; Thu, 8 May 2025 08:52:51 +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=1746694372; cv=none; b=Q75JjVRER5R/UFOf8TEs0LxnrUulp+rcAlpEJooLXf3zMZfn2pV1Q7K4qFl//DxRbq4dNPz/ilgQh4+oTzGJRerEDiTHRW6LY/VvzmUB4NUa4X/uHBGkCfKKdTIv3uXO/uM0zwoure30bAkN4IHWm7+rXoLnHGzUkFdFyfg6j1w= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1746694372; c=relaxed/simple; bh=znt+9wtzzRAcAOqqt9JwNgOU5Ajvi3gapCMlcDgxZ1U=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=PPUKoe4A2Ewi0gjcgItAKrTuG1pU9VX/HJ/DSKPsuTBlSyV9DM8i1VOSRVKbkQX7nKsEHm8VgrfRTiiJognFIRdTBMBvJcl1KUGqINRhwfQqZbMt4jgOfRWI6QobB1ttHJImd50C56PfXRToKXU5oOY8lT2xEWCDSL1SXfbdS9A= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=IKQSi/RW; 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="IKQSi/RW" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A6C16C4CEEB; Thu, 8 May 2025 08:52:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1746694371; bh=znt+9wtzzRAcAOqqt9JwNgOU5Ajvi3gapCMlcDgxZ1U=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=IKQSi/RWEXCNhb6G1V7+tfTHmK14VNAZP6kpeR82wdGTqn8Zc0VK1BU06s6t8ajUR boT3hXSu3ZHKqwxy6DoF9Ogno40s5H/d70gHNvFyqVBhl83Bev8ycm20yjmuFtrkVA ZeMf41S31jJQr1Ne/NnJdCGROsyU/QJol1vqmesoHdy4zikDCkcXHHCqswhJUKq29F 7ZyjyonooSqD2D+F+NYKQ7W0Nd6ldmiVlcSKAoB4I+3CDZlbjRrQ8tyCOdp0YHxbj1 9b/jPzomAbEgH5oIozwALyliGbnFOwBBG/FgF0i6AF0cvdKvzuj6I+JfqsUBztDQw5 2AN1FyWXrSZuw== From: Andreas Hindborg Date: Thu, 08 May 2025 10:52:11 +0200 Subject: [PATCH v8 3/3] MAINTAINERS: add 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: <20250508-configfs-v8-3-8ebde6180edc@kernel.org> References: <20250508-configfs-v8-0-8ebde6180edc@kernel.org> In-Reply-To: <20250508-configfs-v8-0-8ebde6180edc@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 , Peter Zijlstra , Ingo Molnar , Will Deacon , Waiman Long , Fiona Behrens , Charalampos Mitrodimas , Daniel Almeida , Breno Leitao Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, Andreas Hindborg X-Mailer: b4 0.14.2 X-Developer-Signature: v=1; a=openpgp-sha256; l=710; i=a.hindborg@kernel.org; h=from:subject:message-id; bh=znt+9wtzzRAcAOqqt9JwNgOU5Ajvi3gapCMlcDgxZ1U=; b=owEBbQKS/ZANAwAIAeG4Gj55KGN3AcsmYgBoHHDLcHwWDmgp1BsPK3/vcBdMMl7ofZKYVNOQg GtiaUzXpbuJAjMEAAEIAB0WIQQSwflHVr98KhXWwBLhuBo+eShjdwUCaBxwywAKCRDhuBo+eShj d2VZEAC4BrY+NlOiyYVhM+jOYNC097mS697letHGY2EqWh9lrIwGRwA3CiICUag2ndkYzM1w8Nn ThqTHMnJEvFW3g6Jav7UG7LL3VlGyoOuY6IzE6UgQDQ3kg3mzHHzSJmtK7Xg7gKU6y1ojWayvOY wdYFiuYVBDqOzLZ7/BSo96xmactGjWwauODkZTF6qV0D2hZ0yPscPpJnad/7Ld2+lYAnO8ZquuD Bjj8ZToxV/O65PGazzOr6y3vZ3tLjMJetZWxeBZzU4uhPHoSV4g9ZwG/YNCnWGLY2bzQzJ47cyO IEHy2PSWYwlO0eMO8Qf4MXcYyR3DuibRagdpmQ7MZ1viu/qRqolyq9Xz9bwOUuxVFiducoFuT3s SR3Vj+ApduAp5L9lLxQVHkq7eZxCBf2IyhtbfobWmx2Hy25Ex5gfeTf9OK61d0u3MJOXLHdXYVc OiD42fbu7TcHhHvO281co9BrZKHsO6GuVBQ6cAmKzZ6TzqVL1u2oUy3+d55sKasmGY6h4KIh7NT JtvMsl3MS8Bk1bZqihGQAJKpYHOw8Ywf4NjVuTt3q2qC/Weh29gTvGNFRkSHxjCpR2IbMd23t19 pfToa8vniza1oA4U9DH8fsfuxHdhDGpOrnH1cOoBcn39W5FNFVFc4s8zPjEQUWES3tOeN1IppxY rOfQzOb+KxMOO/w== X-Developer-Key: i=a.hindborg@kernel.org; a=openpgp; fpr=3108C10F46872E248D1FB221376EB100563EF7A7 Add rust files to configfs MAINTAINERS entry. Signed-off-by: Andreas Hindborg --- MAINTAINERS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 3cbf9ac0d83f619ef873833b26a3aa3f29ff4161..5ccf04e1eb1fd02e7906e94cb5b= 0acd49e334d98 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -5982,7 +5982,9 @@ S: Supported T: git git://git.kernel.org/pub/scm/linux/kernel/git/a.hindborg/linux.git = configfs-next F: fs/configfs/ F: include/linux/configfs.h +F: rust/kernel/configfs.rs F: samples/configfs/ +F: samples/rust/rust_configfs.rs =20 CONGATEC BOARD CONTROLLER MFD DRIVER M: Thomas Richard --=20 2.47.2