rust: configfs abstractions
Subsystems (5)
Andreas Hindborg
maintainercover rust: configfs abstractions
This series adds a safe Rust API that allows Rust modules to interface the configfs machinery.
The first patch in the series is a resend of a patch that previously appeard on list, adapted to apply on top of rust-6.14.
The series contains an example for the samples folder to demonstrate usage of the API. As such, there is no inline example in the documentation.
The last patch adds a maintainer entry for the Rust configfs abstractions, to make it absolutely clear that I will commit to maintain these abstractions, if required. Feel free to drop this patch if this is not required.
The series is a dependency of rnull, the Rust null block driver. Please see [1] for initial configfs support in rnull.
[1] https://github.com/metaspace/linux/commit/6a52980852f6a8c234ad06d53e57eeb4c870f472
---
Andreas Hindborg (3):
rust: sync: change <Arc<T> as ForeignOwnable>::PointedTo to T
rust: configfs: introduce rust support for configfs
MAINTAINERS: add entry for configfs Rust abstractions
Tamir Duberstein (1):
rust: types: add ForeignOwnable::PointedTo
MAINTAINERS | 7 + init/Kconfig | 3 + rust/bindings/bindings_helper.h | 1 + rust/kernel/alloc/kbox.rs | 38 +- rust/kernel/configfs.rs | 811 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 3 + rust/kernel/miscdevice.rs | 8 +- rust/kernel/sync/arc.rs | 30 +- rust/kernel/types.rs | 46 ++- samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++ 12 files changed, 1106 insertions(+), 45 deletions(-)
---
base-commit: ceff0757f5dafb5be5205988171809c877b1d3e3
change-id: 20250131-configfs-b888cd82d84a
Best regards,
Signature · 1 line
Andreas Hindborg <[email protected]>
Andreas Hindborg
maintainerPATCH 1/4 rust: types: add `ForeignOwnable::PointedTo`
From: Tamir Duberstein <[email protected]>
Allow implementors to specify the foreign pointer type; this exposes information about the pointed-to type such as its alignment.
This requires the trait to be unsafe since it is now possible for implementors to break soundness by returning a misaligned pointer.
Encoding the pointer type in the trait (and avoiding pointer casts) allows the compiler to check that implementors return the correct pointer type. This is preferable to directly encoding the alignment in the trait using a constant as the compiler would be unable to check it.
---
This is a resend of the patch at the link below, adapted to apply on top of rust-6.14.
--- rust/kernel/alloc/kbox.rs | 38 ++++++++++++++++++++------------------ rust/kernel/miscdevice.rs | 8 ++++---- rust/kernel/sync/arc.rs | 21 ++++++++++++--------- rust/kernel/types.rs | 46 +++++++++++++++++++++++++++++++--------------- 4 files changed, 67 insertions(+), 46 deletions(-)
rust/kernel/alloc/kbox.rs +20 -18
@@ -349,68 +349,70 @@ fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> } } -impl <T : 'static,A >ForeignOwnable for Box <T ,A > +// SAFETY: The `into_foreign` function returns a pointer that is well-aligned. +unsafe impl <T : 'static,A >ForeignOwnable for Box <T ,A >where A :Allocator , { +type PointedTo =T ;type Borrowed <'a> = &'aT ;type BorrowedMut <'a> = &'amut T ; -fn into_foreign (self) -> *mut crate ::ffi::c_void { -Box ::into_raw (self).cast () +fn into_foreign (self) -> *mut Self ::PointedTo { +Box ::into_raw (self) } -unsafe fn from_foreign (ptr: *mut crate ::ffi::c_void ) ->Self { +unsafe fn from_foreign (ptr: *mut Self ::PointedTo ) ->Self {// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -unsafe {Box ::from_raw (ptr.cast ()) } +unsafe {Box ::from_raw (ptr) } } -unsafe fn borrow <'a>(ptr: *mut crate ::ffi::c_void ) -> &'aT { +unsafe fn borrow <'a>(ptr: *mut Self ::PointedTo ) -> &'aT {// SAFETY: The safety requirements of this method ensure that the object remains alive and // immutable for the duration of 'a. -unsafe { &*ptr.cast () } +unsafe { &*ptr } } -unsafe fn borrow_mut <'a>(ptr: *mut crate ::ffi::c_void ) -> &'amut T { -let ptr = ptr.cast (); +unsafe fn borrow_mut <'a>(ptr: *mut Self ::PointedTo ) -> &'amut T {// SAFETY: The safety requirements of this method ensure that the pointer is valid and that // nothing else will access the value for the duration of 'a. unsafe { &mut *ptr } } } -impl <T : 'static,A >ForeignOwnable for Pin <Box <T ,A >> +// SAFETY: The `into_foreign` function returns a pointer that is well-aligned. +unsafe impl <T : 'static,A >ForeignOwnable for Pin <Box <T ,A >>where A :Allocator , { +type PointedTo =T ;type Borrowed <'a> =Pin <&'aT >;type BorrowedMut <'a> =Pin <&'amut T >; -fn into_foreign (self) -> *mut crate ::ffi::c_void { +fn into_foreign (self) -> *mut Self ::PointedTo {// SAFETY: We are still treating the box as pinned. -Box ::into_raw (unsafe {Pin ::into_inner_unchecked (self) }).cast () +Box ::into_raw (unsafe {Pin ::into_inner_unchecked (self) }) } -unsafe fn from_foreign (ptr: *mut crate ::ffi::c_void ) ->Self { +unsafe fn from_foreign (ptr: *mut Self ::PointedTo ) ->Self {// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -unsafe {Pin ::new_unchecked (Box ::from_raw (ptr.cast ())) } +unsafe {Pin ::new_unchecked (Box ::from_raw (ptr)) } } -unsafe fn borrow <'a>(ptr: *mut crate ::ffi::c_void ) ->Pin <&'aT > { +unsafe fn borrow <'a>(ptr: *mut Self ::PointedTo ) ->Pin <&'aT > {// SAFETY: The safety requirements for this function ensure that the object is still alive, // so it is safe to dereference the raw pointer. // The safety requirements of `from_foreign` also ensure that the object remains alive for // the lifetime of the returned value. -let r =unsafe { &*ptr.cast () }; +let r =unsafe { &*ptr };// SAFETY: This pointer originates from a `Pin<Box<T>>`. unsafe {Pin ::new_unchecked (r) } } -unsafe fn borrow_mut <'a>(ptr: *mut crate ::ffi::c_void ) ->Pin <&'amut T > { -let ptr = ptr.cast (); +unsafe fn borrow_mut <'a>(ptr: *mut Self ::PointedTo ) ->Pin <&'amut T > {// SAFETY: The safety requirements for this function ensure that the object is still alive, // so it is safe to dereference the raw pointer. // The safety requirements of `from_foreign` also ensure that the object remains alive for
rust/kernel/miscdevice.rs +4 -4
@@ -189,7 +189,7 @@ impl<T: MiscDevice> VtableHelper<T> { };// SAFETY: The open call of a file owns the private data. -unsafe { (*file).private_data = ptr.into_foreign () }; +unsafe { (*file).private_data = ptr.into_foreign ().cast () };0 }
@@ -205,7 +205,7 @@ impl<T: MiscDevice> VtableHelper<T> {// SAFETY: The release call of a file owns the private data. let private =unsafe { (*file).private_data };// SAFETY: The release call of a file owns the private data. -let ptr =unsafe { <T ::Ptr as ForeignOwnable >::from_foreign (private) }; +let ptr =unsafe { <T ::Ptr as ForeignOwnable >::from_foreign (private.cast ()) };T ::release (ptr);
@@ -223,7 +223,7 @@ impl<T: MiscDevice> VtableHelper<T> {// SAFETY: The ioctl call of a file can access the private data. let private =unsafe { (*file).private_data };// SAFETY: Ioctl calls can borrow the private data of the file. -let device =unsafe { <T ::Ptr as ForeignOwnable >::borrow (private) }; +let device =unsafe { <T ::Ptr as ForeignOwnable >::borrow (private.cast ()) };match T ::ioctl (device, cmd, arg) {Ok (ret) => retas c_long ,
@@ -243,7 +243,7 @@ impl<T: MiscDevice> VtableHelper<T> {// SAFETY: The compat ioctl call of a file can access the private data. let private =unsafe { (*file).private_data };// SAFETY: Ioctl calls can borrow the private data of the file. -let device =unsafe { <T ::Ptr as ForeignOwnable >::borrow (private) }; +let device =unsafe { <T ::Ptr as ForeignOwnable >::borrow (private.cast ()) };match T ::compat_ioctl (device, cmd, arg) {Ok (ret) => retas c_long ,
rust/kernel/sync/arc.rs +12 -9
@@ -140,9 +140,10 @@ pub struct Arc<T: ?Sized> { _p: PhantomData<ArcInner<T>>, } +#[doc(hidden)] #[pin_data] #[repr( C )] -struct ArcInner <T : ?Sized > { +pub struct ArcInner <T : ?Sized > { refcount:Opaque <bindings::refcount_t >, data:T , }
@@ -342,18 +343,20 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> { } } -impl <T : 'static>ForeignOwnable for Arc <T > { +// SAFETY: The `into_foreign` function returns a pointer that is well-aligned. +unsafe impl <T : 'static>ForeignOwnable for Arc <T > { +type PointedTo =ArcInner <T >;type Borrowed <'a> =ArcBorrow <'a,T >;type BorrowedMut <'a> =Self ::Borrowed <'a>; -fn into_foreign (self) -> *mut crate ::ffi::c_void { -ManuallyDrop ::new (self).ptr.as_ptr ().cast () +fn into_foreign (self) -> *mut Self ::PointedTo { +ManuallyDrop ::new (self).ptr.as_ptr () } -unsafe fn from_foreign (ptr: *mut crate ::ffi::c_void ) ->Self { +unsafe fn from_foreign (ptr: *mut Self ::PointedTo ) ->Self {// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -let inner =unsafe {NonNull ::new_unchecked (ptr.cast ::<ArcInner <T >>()) }; +let inner =unsafe {NonNull ::new_unchecked (ptr) };// SAFETY: By the safety requirement of this function, we know that `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and
@@ -361,17 +364,17 @@ unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self {unsafe {Self ::from_inner (inner) } } -unsafe fn borrow <'a>(ptr: *mut crate ::ffi::c_void ) ->ArcBorrow <'a,T > { +unsafe fn borrow <'a>(ptr: *mut Self ::PointedTo ) ->ArcBorrow <'a,T > {// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -let inner =unsafe {NonNull ::new_unchecked (ptr.cast ::<ArcInner <T >>()) }; +let inner =unsafe {NonNull ::new_unchecked (ptr) };// SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive // for the lifetime of the returned value. unsafe {ArcBorrow ::new (inner) } } -unsafe fn borrow_mut <'a>(ptr: *mut crate ::ffi::c_void ) ->ArcBorrow <'a,T > { +unsafe fn borrow_mut <'a>(ptr: *mut Self ::PointedTo ) ->ArcBorrow <'a,T > {// SAFETY: The safety requirements for `borrow_mut` are a superset of the safety // requirements for `borrow`. unsafe {Self ::borrow (ptr) }
rust/kernel/types.rs +31 -15
96 lines not on this page · raw message
Signature · 1 line
2.47.0
Re: [PATCH 1/4] rust: types: add `ForeignOwnable::PointedTo`
Quoted 8 lines · Andreas Hindborg
From: Tamir Duberstein <[email protected]>
Allow implementors to specify the foreign pointer type; this exposes information about the pointed-to type such as its alignment.
This requires the trait to be
unsafesince it is now possible for implementors to break soundness by returning a misaligned pointer.
Quoted 9 lines
Encoding the pointer type in the trait (and avoiding pointer casts) allows the compiler to check that implementors return the correct pointer type. This is preferable to directly encoding the alignment in the trait using a constant as the compiler would be unable to check it.
Reviewed-by Andreas Hindborg <[email protected]>Signed-off-by Tamir Duberstein <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>
Re: [PATCH 1/4] rust: types: add `ForeignOwnable::PointedTo`
In reply to Andreas HindborgQuoted 9 lines · Andreas Hindborg
From: Tamir Duberstein <[email protected]>
Allow implementors to specify the foreign pointer type; this exposes information about the pointed-to type such as its alignment.
This requires the trait to be
unsafesince it is now possible for implementors to break soundness by returning a misaligned pointer.
Quoted 8 lines
Encoding the pointer type in the trait (and avoiding pointer casts) allows the compiler to check that implementors return the correct pointer type. This is preferable to directly encoding the alignment in the trait using a constant as the compiler would be unable to check it.
Reviewed-by Andreas Hindborg <[email protected]>Signed-off-by Tamir Duberstein <[email protected]>Signed-off-by Andreas Hindborg <[email protected]>
I would have gone a different route with this API, but I won't block it.
Andreas Hindborg
maintainerPATCH 2/4 rust: sync: change `<Arc<T> as ForeignOwnable>::PointedTo` to `T`
In reply to Andreas HindborgUsing 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.
---
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(-)
rust/kernel/sync/arc.rs +16 -5
@@ -143,7 +143,7 @@ pub struct Arc<T: ?Sized> {#[doc(hidden)] #[pin_data] #[repr( C )] -pub struct ArcInner <T : ?Sized > { +struct ArcInner <T : ?Sized > { refcount:Opaque <bindings::refcount_t >, data:T , }
@@ -345,18 +345,25 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {// SAFETY: The `into_foreign` function returns a pointer that is well-aligned. unsafe impl <T : 'static>ForeignOwnable for Arc <T > { -type PointedTo =ArcInner <T >; +type PointedTo =T ;type Borrowed <'a> =ArcBorrow <'a,T >;type BorrowedMut <'a> =Self ::Borrowed <'a>;fn into_foreign (self) -> *mut Self ::PointedTo { -ManuallyDrop ::new (self).ptr.as_ptr () +let x =ManuallyDrop ::new (self).ptr.as_ptr (); +// SAFETY: `x` is a valid pointer to `Self` so the projection below is +// in bounds of the allocation. +unsafe { core::ptr::addr_of_mut!((*x).data) } }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 =unsafe { kernel::container_of!(ptr,ArcInner <T >, data).cast_mut () }; +// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -let inner =unsafe {NonNull ::new_unchecked (ptr) }; +let inner =unsafe {NonNull ::new_unchecked (inner_ptr) };// SAFETY: By the safety requirement of this function, we know that `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) -> Self { }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 =unsafe { kernel::container_of!(ptr,ArcInner <T >, data).cast_mut () }; +// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -let inner =unsafe {NonNull ::new_unchecked (ptr) }; +let inner =unsafe {NonNull ::new_unchecked (inner_ptr) };// SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive // for the lifetime of the returned value.
Signature · 1 line
2.47.0
Re: [PATCH 2/4] rust: sync: change `<Arc<T> as ForeignOwnable>::PointedTo` to `T`
Quoted 7 lines · Andreas Hindborg
Using
ArcInnerasPoinedToin theForeignOwnableimplementation forArcis a bit unfortunate. UsingTasPointedTodoes not remove any functionality, but allowsArcInnerto be private. Further, it allows downstream users to write code that is generic overBoxandArc, when downstream users need access toTafter callinginto_foreign.Signed-off-by Andreas Hindborg <[email protected]>
Bit unfortunate that we first in the patch before made it public and now private again, but it makes sense to split patches.
Think I also found this weird when I wrote my LED patch, so this makes a lot of sense as this is what I would expect.
Quoted 66 lines
---
This patch is a dependency for Rust
configfsabstractions. It allows bothBoxandArcto be used as pointer types in theconfigfshierarchy.--- rust/kernel/sync/arc.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-)rust/kernel/sync/arc.rs +16
-5@@ -143,7 +143,7 @@ pub struct Arc<T: ?Sized> {#[doc(hidden)] #[pin_data] #[repr( C )] -pub struct ArcInner <T : ?Sized > { +struct ArcInner <T : ?Sized > { refcount:Opaque <bindings::refcount_t >, data:T , }@@ -345,18 +345,25 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {// SAFETY: The `into_foreign` function returns a pointer that is well-aligned. unsafe impl <T : 'static>ForeignOwnable for Arc <T > { -type PointedTo =ArcInner <T >; +type PointedTo =T ;type Borrowed <'a> =ArcBorrow <'a,T >;type BorrowedMut <'a> =Self ::Borrowed <'a>;fn into_foreign (self) -> *mut Self ::PointedTo { -ManuallyDrop ::new (self).ptr.as_ptr () +let x =ManuallyDrop ::new (self).ptr.as_ptr (); +// SAFETY: `x` is a valid pointer to `Self` so the projection below is +// in bounds of the allocation. +unsafe { core::ptr::addr_of_mut!((*x).data) } }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 =unsafe { kernel::container_of!(ptr,ArcInner <T >, data).cast_mut () }; +// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -let inner =unsafe {NonNull ::new_unchecked (ptr) }; +let inner =unsafe {NonNull ::new_unchecked (inner_ptr) };// SAFETY: By the safety requirement of this function, we know that `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) -> Self { }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 =unsafe { kernel::container_of!(ptr,ArcInner <T >, data).cast_mut () }; +// SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. -let inner =unsafe {NonNull ::new_unchecked (ptr) }; +let inner =unsafe {NonNull ::new_unchecked (inner_ptr) };// SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive // for the lifetime of the returned value.
Andreas Hindborg
maintainerPATCH 3/4 rust: configfs: introduce rust support for configfs
In reply to Andreas HindborgThis 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.
---
This patch is a direct dependency for rnull, the rust null block driver.
--- init/Kconfig | 3 + rust/bindings/bindings_helper.h | 1 + rust/kernel/configfs.rs | 811 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 3 + samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++ 7 files changed, 1022 insertions(+)
init/Kconfig +3 -0
@@ -132,6 +132,9 @@ config CC_HAS_COUNTED_BY config RUSTC_HAS_COERCE_POINTEE def_bool RUSTC_VERSION >= 108400 +config RUSTC_HAS_CONST_MUT_REFS_MERGED + def_bool RUSTC_VERSION >= 108300 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE))
rust/bindings/bindings_helper.h +1 -0
@@ -10,6 +10,7 @@#include <linux/blk-mq.h> #include <linux/blk_types.h> #include <linux/blkdev.h> +#include <linux/configfs.h> #include <linux/cred.h> #include <linux/errname.h> #include <linux/ethtool.h>
rust/kernel/configfs.rs new file +811 -0
811 lines not on this page · raw message
rust/kernel/lib.rs +3 -0
@@ -19,6 +19,7 @@#![cfg_attr(not( CONFIG_RUSTC_HAS_COERCE_POINTEE ), feature(unsize))] #![feature(inline_const)] #![feature(lint_reasons)] +#![cfg_attr(not( CONFIG_RUSTC_HAS_CONST_MUT_REFS_MERGED ), feature(const_mut_refs))] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling.
@@ -35,6 +36,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 error;
samples/rust/Kconfig +11 -0
@@ -30,6 +30,17 @@ config SAMPLE_RUST_PRINT If unsure, say N. +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_HOSTPROGS bool "Host programs" help
samples/rust/Makefile +1 -0
@@ -3,6 +3,7 @@ ccflags-y += -I$(src) # needed for trace events obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/rust_configfs.rs new file +192 -0
192 lines not on this page · raw message
Signature · 1 line
2.47.0
Re: [PATCH 3/4] rust: configfs: introduce rust support for configfs
Quoted 532 lines · Andreas Hindborg
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_refsfeature 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 <[email protected]>---
This patch is a direct dependency for
rnull, the rust null block driver.--- init/Kconfig | 3 + rust/bindings/bindings_helper.h | 1 + rust/kernel/configfs.rs | 811 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 3 + samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++ 7 files changed, 1022 insertions(+)init/Kconfig +3
-0@@ -132,6 +132,9 @@ config CC_HAS_COUNTED_BY config RUSTC_HAS_COERCE_POINTEE def_bool RUSTC_VERSION >= 108400 +config RUSTC_HAS_CONST_MUT_REFS_MERGED + def_bool RUSTC_VERSION >= 108300 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE))rust/bindings/bindings_helper.h +1
-0@@ -10,6 +10,7 @@#include <linux/blk-mq.h> #include <linux/blk_types.h> #include <linux/blkdev.h> +#include <linux/configfs.h> #include <linux/cred.h> #include <linux/errname.h> #include <linux/ethtool.h> rust/kernel/configfs.rs new file +476
-0@@ -0,0 +1,811 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! `configfs` interface. +//! +//! `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. +//! - Item `release` hook +//! - Default groups. +//! +//! See the [rust_configfs.rs] sample for a full example use of this module. +//! +//! C header: [`include/linux/configfs.h`](srctree/include/linux/configfs.h) +//! +//! [C documentation]: srctree/Documentation/filesystems/configfs.rst +//! [rust_configfs.rs]: srctree/samples/rust/rust_configfs.rs + +use crate ::container_of; +use crate ::page::PAGE_SIZE ; +use crate ::types::ForeignOwnable ; +use crate ::{prelude::*, types::Opaque }; +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; +use core::ptr::addr_of; +use core::ptr::addr_of_mut; +use kernel::alloc::flags; +use kernel::str::CString ; + +/// A `configfs` subsystem. +/// +/// This is the top level entrypoint for a `configfs` hierarchy. Embed a field +/// of this type into a struct and implement [`HasSubsystem`] for the struct +/// with the [`kernel::impl_has_subsystem`] macro. Instantiate the subsystem with +/// [`Subsystem::register`]. +/// +/// A [`Subsystem`] is also a [`Group`], and implementing [`HasSubsystem`] for a +/// type will automatically implement [`HasGroup`] for the type. +#[pin_data( PinnedDrop )] +pub struct Subsystem <DATA > { +#[pin] + subsystem:Opaque <bindings::configfs_subsystem >, +#[pin] + data:DATA , +} + +// SAFETY: We do not provide any operations on `Subsystem`. +unsafe impl <DATA >Sync for Subsystem <DATA > {} + +// SAFETY: Ownership of `Subsystem` can safely be transferred to other threads. +unsafe impl <DATA >Send for Subsystem <DATA > {} + +impl <DATA >Subsystem <DATA > { +/// 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: &'staticCStr , + item_type: &'staticItemType <DATA >, + data:impl PinInit <DATA ,Error >, + ) ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + subsystem <- kernel::init::zeroed ().chain ( + |place: &mut Opaque <bindings::configfs_subsystem >| { +// SAFETY: All of `place` is valid for write. +unsafe { +addr_of_mut! ((*place.get ()).su_group.cg_item.ci_name ) + .write (name.as_ptr ().cast_mut ().cast ()) + }; +// SAFETY: All of `place` is valid for write. +unsafe { +addr_of_mut! ((*place.get ()).su_group.cg_item.ci_type) + .write (item_type.as_ptr ()) + }; +// SAFETY: We initialized the required fields of `place.group` above. +unsafe { bindings::config_group_init (&mut (*place.get ()).su_group) }; +// SAFETY: `place.su_mutex` is valid for use as a mutex. +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.subsystem.get ()) }, + ) + }) + } +} + +#[pinned_drop] +impl <DATA >PinnedDrop for Subsystem <DATA > { +fn drop (self:Pin <&mut Self >) { +// SAFETY: We registered `self.subsystem` in the initializer returned by `Self::new`. +unsafe { bindings::configfs_unregister_subsystem (self.subsystem.get ()) }; + } +} + +/// Trait that allows offset calculations for structs that embed a `bindings::config_group`. +/// +/// # Safety +/// +/// - Implementers of this trait must embed a `bindings::config_group`. +/// - Methods must be implemented according to method documentation. +unsafe trait HasGroup <DATA > { +/// Return the address of the `bindings::config_group` embedded in `Self`. +/// +/// # 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 embedded in +/// `Self`. +unsafe fn container_of (group: *const bindings::config_group ) -> *const Self ; +} + +// SAFETY: `Subsystem<DATA>` embeds a field of type `bindings::config_group` +// within the `subsystem` field. +unsafe impl <DATA >HasGroup <DATA >for Subsystem <DATA > { +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 =unsafe {container_of! (group, bindings::configfs_subsystem, su_group) }; +let opaque_ptr = c_subsys_ptr.cast ::<Opaque <bindings::configfs_subsystem >>(); +// SAFETY: By impl and function safety requirement, `opaque_ptr` and the +// pointer it returns, are within the same allocation. +unsafe {container_of! (opaque_ptr,Subsystem <DATA >, subsystem) } + } +} + +/// A `configfs` group. +/// +/// To add a subgroup to `configfs`, embed a field of this type into a struct +/// and use it for the `CHLD` generic of [`GroupOperations`]. +#[pin_data] +pub struct Group <DATA > { +#[pin] + group:Opaque <bindings::config_group >, +#[pin] + data:DATA , +} + +impl <DATA >Group <DATA > { +/// Create an initializer for a new group. +/// +/// When instantiated, the group will appear as a directory with the name +/// given by `name` and it will contain attributes specified by `item_type`. +pub fn new ( + name:CString , + item_type: &'staticItemType <DATA >, + data:impl PinInit <DATA ,Error >, + ) ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + group <- kernel::init::zeroed ().chain (|v: &mut Opaque <bindings::config_group >| { +let place = v.get (); +let name = name.as_bytes_with_nul ().as_ptr (); +// SAFETY: It is safe to initialize a group once it has been zeroed. +unsafe { + bindings::config_group_init_type_name (place, nameas _ , item_type.as_ptr ()) + }; +Ok (()) + }), + data <- data, + }) + } +} + +// SAFETY: `Group<DATA>` embeds a field of type `bindings::config_group` +// within the `group` field. +unsafe impl <DATA >HasGroup <DATA >for Group <DATA > { +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 = group.cast ::<Opaque <bindings::config_group >>(); +// SAFETY: By impl and function safety requirement, `opaque_ptr` and +// pointer it returns will be in the same allocation. +unsafe {container_of! (opaque_ptr,Self , group) } + } +} + +struct GroupOperationsVTable <PAR ,CHLD ,CPTR ,PCPTR >(PhantomData <(PAR ,CHLD ,CPTR ,PCPTR )>) +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>; + +/// # 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<PAR>`. +/// +/// 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<PAR>`. +unsafe fn get_group_data <'a,PAR >(this: *mut bindings::config_group ) -> &'aPAR { +// SAFETY: `this` is a valid pointer. +let is_root =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 from +// `make_group`. Such a pointer is embedded within a `Group<PAR>`. +unsafe { &(*Group ::<PAR >::container_of (this)).data } + }else { +// SAFETY: By C API contract, `this` is a pointer to the +// `bindings::config_group` field within a `Subsystem<PAR>`. +unsafe { &(*Subsystem ::container_of (this)).data } + } +} + +impl <PAR ,CHLD ,CPTR ,PCPTR >GroupOperationsVTable <PAR ,CHLD ,CPTR ,PCPTR > +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>, +{ +/// # 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<PAR>`. +/// +/// 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<PAR>`. +/// +/// `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 =unsafe {get_group_data (this) }; + +let group_init =match PAR ::make_group ( + parent_data, +// SAFETY: By function safety requirements, name points to a null +// terminated string. +unsafe {CStr ::from_char_ptr (name) }, + ) { +Ok (init) => init, +Err (e) =>return e.to_ptr (), + }; + +let child_group =CPTR ::try_pin_init (group_init, flags::GFP_KERNEL ); + +match child_group { +Ok (child_group) => { +let child_group_ptr = child_group.into_foreign (); +// SAFETY: We allocated the pointee of `child_ptr` above as a +// `Group<CHLD>`. +unsafe {Group ::<CHLD >::group (child_group_ptr) }.cast_mut () + } +Err (e) => e.to_ptr (), + } + } + +/// # Safety +/// +/// 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<PAR>`. +/// +/// 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<PAR>`. +/// +/// `item` must point to a `bindings::config_item` within a +/// `bindings::config_group` within a `Group<CHLD>`. +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 =unsafe {get_group_data (this) }; + +// SAFETY: By function safety requirements, `item` is embedded in a +// `config_group`. +let c_child_group_ptr = +unsafe { kernel::container_of!(item, bindings::config_group, cg_item) }; +// SAFETY: By function safety requirements, `c_child_group_ptr` is +// embedded within a `Group<CHLD>`. +let r_child_group_ptr =unsafe {Group ::<CHLD >::container_of (c_child_group_ptr) }; + +if PAR ::HAS_DROP_ITEM { +PAR ::drop_item ( + parent_data, +// SAFETY: We called `into_foreign` to produce `r_child_group_ptr` in +// `make_group`. There are not other borrows of this pointer in existence. +unsafe {PCPTR ::borrow (r_child_group_ptr.cast_mut ()) }, + ); + } + +// SAFETY: By C API contract, `configfs` is not going to touch `item` +// again. +unsafe { bindings::config_item_put (item) }; + +// SAFETY: We called `into_foreign` on `r_chilc_group_ptr` in +// `make_group`. +let pin_child:PCPTR =unsafe {PCPTR ::from_foreign (r_child_group_ptr.cast_mut ()) }; +drop (pin_child); + } + +const VTABLE : bindings::configfs_group_operations = bindings::configfs_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 , + }; +} + +/// Operations implemented by `configfs` groups that can create subgroups. +/// +/// Implement this trait on structs that embed a [`Subsystem`] or a [`Group`]. +#[vtable] +pub trait GroupOperations { +/// The parent data object type. +/// +/// The implementer of this trait is this kind of data object. Shold be set +/// to `Self`. +type Parent ; + +/// The child data object type. +/// +/// This group will create subgroups (subdirectories) backed by this kind of +/// object. +type Child ; + +/// The type of the pointer used to point to [`Self::Child`]. +/// +/// This pointer type should support pinned in-place initialization. +type ChildPointer :InPlaceInit <Group <Self ::Child >,PinnedSelf =Self ::PinChildPointer >; + +/// The pinned version of the child pointer. +/// +/// This type must be convertible to a raw pointer according to [`ForeignOwnable`]. +type PinChildPointer :ForeignOwnable <PointedTo =Group <Self ::Child >>; + +/// 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 +/// instantiate a `CHLD` and return a `CPTR` to it. To prevent creation, +/// return a suitable error. +fn make_group ( + this: &Self ::Parent , + name: &CStr , + ) ->Result <impl PinInit <Group <Self ::Child >,Error >>; + +/// 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 `CHLD`. +fn drop_item ( + _this: &Self ::Parent , + _child: <Self ::PinChildPointer as ForeignOwnable >::Borrowed <'_>, + ) { + kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR ) + } +} + +/// A `configfs` attribute. +/// +/// An attribute appear as a file in configfs, inside a folder that represent +/// the group that the attribute belongs to. +#[repr(transparent)] +pub struct Attribute <const ID :u64 ,AO ,DATA > { + attribute:Opaque <bindings::configfs_attribute >, + _p:PhantomData <(AO ,DATA )>, +} + +// SAFETY: We do not provide any operations on `Attribute`. +unsafe impl <const ID :u64 ,AO ,DATA >Sync for Attribute <ID ,AO ,DATA > {} + +// SAFETY: Ownership of `Attribute` can safely be transferred to other threads. +unsafe impl <const ID :u64 ,AO ,DATA >Send for Attribute <ID ,AO ,DATA > {} + +impl <const ID :u64 ,AO ,DATA >Attribute <ID ,AO ,DATA > +where +AO :AttributeOperations <ID ,Data =DATA >, +{ +/// # Safety +/// +/// `item` must be embedded in a `bindings::config_group`. +/// +/// If `item` does not represent the root group of a `configfs` subsystem, +/// the group must be embedded in a `Group<PAR>`. +/// +/// Otherwise, the group must be a embedded in a +/// `bindings::configfs_subsystem` that is embedded in a `Subsystem<PAR>`. +/// +/// `page` must point to a writable buffer of size at least [`PAGE_SIZE`]. +unsafe extern "C" fn show ( + item: *mut bindings::config_item , + page: *mut kernel::ffi::c_char , + ) ->isize { +let c_group: *mut bindings::config_group = +// 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 satisfy +// the conditions for this call. +let data: &DATA =unsafe {get_group_data (c_group) }; + +// SAFETY: By function safety requirements, `page` is writable for `PAGE_SIZE`. +let ret =AO ::show (data,unsafe { &mut *(pageas *mut [u8 ;PAGE_SIZE ]) }); + +match ret { +Ok (size) => sizeas isize , +Err (err) => 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` subsystem, +/// the group must be embedded in a `Group<PAR>`. +/// +/// Otherwise, the group must be a embedded in a +/// `bindings::configfs_subsystem` that is embedded in a `Subsystem<PAR>`. +/// +/// `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 = +// 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 satisfy +// the conditions for this call. +let data: &DATA =unsafe {get_group_data (c_group) }; +
rust/kernel/configfs.rs line 486
Quoted 10 lines
rust/kernel/configfs.rs new file +10
-0+let ret =AO ::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 (()) => sizeas isize , +Err (err) => err.to_errno ()as isize ,
Do we reach the Err arm here?
Quoted 498 lines
rust/kernel/configfs.rs new file +325
-0+ } + } + +/// Create a new attribute. +/// +/// The attribute will appear as a file with name given by `name`. +pub const fn new (name: &'staticCStr ) ->Self { +Self { + attribute:Opaque ::new (bindings::configfs_attribute { + ca_name: nameas *const _ as _ , + ca_owner: core::ptr::null_mut (), + ca_mode:0o660 , + show:Some (Self ::show), + store:if AO ::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 when +/// creating an [`Attribute`]. The type carrying the implementation serve no +/// purpose other than specifying the attribute operations. +#[vtable] +pub trait AttributeOperations <const ID :u64 =0 > { +/// The type of the object that contains the field that is backing the +/// attribute for this operation. +type Data ; + +/// This function is called by the kernel to read the value of an attribute. +/// +/// Implementations should write the rendering of the attribute to `page` +/// and return the number of bytes written. +fn show (data: &Self ::Data , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize >; + +/// This function is called by the kernel to update the value of an attribute. +/// +/// Implementations should parse the value from `page` and update internal +/// state to reflect the parsed value. Partial writes are not supported and +/// implementations should expect the full page to arrive in one write +/// operation. +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 list of +/// [`Attribute`] that will appear in the directory representing a [`Group`]. +/// Users should not directly instantiate this type, rather they should use the +/// [`kernel::configfs_attrs`] macro to declare a static set of attributes for a +/// group. +#[repr(transparent)] +pub struct AttributeList <const N :usize ,DATA >( +UnsafeCell <[*mut kernel::ffi::c_void ;N ]>, +PhantomData <DATA >, +); + +// SAFETY: Ownership of `AttributeList` can safely be transferred to other threads. +unsafe impl <const N :usize ,DATA >Send for AttributeList <N ,DATA > {} + +// SAFETY: We do not provide any operations on `AttributeList` that need synchronization. +unsafe impl <const N :usize ,DATA >Sync for AttributeList <N ,DATA > {} + +impl <const N :usize ,DATA >AttributeList <N ,DATA > { +#[doc(hidden)] +/// # Safety +/// +/// This function can only be called by expanding the `configfs_attrs` +/// macro. +pub const unsafe fn new () ->Self { +Self (UnsafeCell ::new ([core::ptr::null_mut ();N ]),PhantomData ) + } + +#[doc(hidden)] +/// # Safety +/// +/// This function can only be called by expanding the `configfs_attrs` +/// macro. +pub const unsafe fn add < +const I :usize , +const ID :u64 , +O :AttributeOperations <ID ,Data =DATA >, + >( + &'static self, + attribute: &'staticAttribute <ID ,O ,DATA >, + ) { +if I >=N -1 { + kernel::build_error!("Invalid attribute index" ); + } + +// SAFETY: This function is only called through `configfs_attrs`. This +// ensures that we are evaluating the function in const context when +// initializing a static. As such, the reference created below will be +// exclusive. +unsafe { + (&mut *self.0 .get ())[I ] = (attributeas *const Attribute <ID ,O ,DATA >) + .cast_mut () + .cast () + }; + } +} + +/// A representation of the attributes that will appear in a [`Group`]. +/// +/// Users should not directly instantiate objects of this type. Rather, they +/// should use the [`kernel::configfs_attrs`] macro to statically declare the +/// shape of a [`Group`]. +#[pin_data] +pub struct ItemType <DATA > { +#[pin] + item_type:Opaque <bindings::config_item_type >, + _p:PhantomData <DATA >, +} + +// SAFETY: We do not provide any operations on `ItemType` that need synchronization. +unsafe impl <DATA >Sync for ItemType <DATA > {} + +// SAFETY: Ownership of `ItemType` can safely be transferred to other threads. +unsafe impl <DATA >Send for ItemType <DATA > {} + +impl <DATA >ItemType <DATA > { +#[doc(hidden)] +pub const fn new_with_child_ctor <const N :usize ,PAR ,CHLD ,CPTR ,PCPTR >( + owner: &'staticThisModule , + attributes: &'staticAttributeList <N ,DATA >, + ) ->Self +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>, + { +Self { + item_type:Opaque ::new (bindings::config_item_type { + ct_owner: owner.as_ptr (), + ct_group_ops: (&GroupOperationsVTable ::<PAR ,CHLD ,CPTR ,PCPTR >::VTABLE as *const _ ) +as *mut _ , + ct_item_ops: core::ptr::null_mut (), + ct_attrs: attributesas *const _ as _ , + ct_bin_attrs: core::ptr::null_mut (), + }), + _p:PhantomData , + } + } + +#[doc(hidden)] +pub const fn new <const N :usize >( + owner: &'staticThisModule , + attributes: &'staticAttributeList <N ,DATA >, + ) ->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: core::ptr::null_mut (), + ct_attrs: attributesas *const _ as _ , + ct_bin_attrs: core::ptr::null_mut (), + }), + _p:PhantomData , + } + } +} + +impl <DATA >ItemType <DATA > { +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, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child (), + @no_child (x), + @attrs ($($name $attr)*), + @eat ($($name $attr,)*), + @assign (), + @cnt (0usize ), + ) + }; + ( + container: $container:ty, + child: $child:ty, + pointer: $pointer:ty, + pinned: $pinned:ty, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child ($child, $pointer, $pinned), + @no_child (), + @attrs ($($name $attr)*), + @eat ($($name $attr,)*), + @assign (), + @cnt (0usize ), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned: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), + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child ($($child, $pointer, $pinned)?), + @no_child ($($no_child)?), + @attrs ($($aname $aattr)*), + @eat ($($rname $rattr,)*), + @assign ($($assign)* { +const N :usize = $cnt; +// SAFETY: We are expanding `configfs_attrs`. +unsafe { + $crate ::macros::paste!( [< $container:upper _ATTRS >]) + .add ::<N , $attr,_ >( + & $crate ::macros::paste!( [< $container:upper _ $name:upper _ATTR >]) + ) + }; + }), + @cnt (1usize + $cnt), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat(), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) => + { + $crate::configfs_attrs!(final: + @container ($container), + @child ($($child, $pointer, $pinned)?), + @no_child ($($no_child)?), + @attrs ($($aname $aattr)*), + @assign ($($assign)*), + @cnt ($cnt), + ) + }; + (final: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($name:ident $attr:literal)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) => + { + { + $( + $crate::macros::paste!{ +// SAFETY: We are expanding `configfs_attrs`. +static [< $container:upper _ $name:upper _ATTR >]: + $crate ::configfs::Attribute <$attr, $container, $container> = +unsafe { + $crate ::configfs::Attribute ::new (c_str! (::core::stringify!($name))) + }; + } + )* + + +const N :usize = $cnt +1usize ; + $crate::macros::paste!{ +// SAFETY: We are expanding `configfs_attrs`. +static [< $container:upper _ATTRS >]: + $crate ::configfs::AttributeList <N , $container> = +unsafe { $crate ::configfs::AttributeList ::new () }; + } + + $($assign)* + + $( + $crate ::macros::paste!{ +const [<$no_child:upper>]:bool =true ; + }; + + $crate ::macros::paste!{ +static [< $container:upper _TPE >] : $crate ::configfs::ItemType <$container> = + $crate ::configfs::ItemType ::new ::<N >( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + $( + $crate ::macros::paste!{ +static [< $container:upper _TPE >]: + $crate ::configfs::ItemType <$container> = + $crate ::configfs::ItemType ::new_with_child_ctor :: + <N , $container, $child, $pointer, $pinned>( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + &$crate ::macros::paste!( [< $container:upper _TPE >] ) + } + }; + +}rust/kernel/lib.rs +3
-0@@ -19,6 +19,7 @@#![cfg_attr(not( CONFIG_RUSTC_HAS_COERCE_POINTEE ), feature(unsize))] #![feature(inline_const)] #![feature(lint_reasons)] +#![cfg_attr(not( CONFIG_RUSTC_HAS_CONST_MUT_REFS_MERGED ), feature(const_mut_refs))] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. @@ -35,6 +36,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 error;samples/rust/Kconfig +11
-0@@ -30,6 +30,17 @@ config SAMPLE_RUST_PRINT If unsure, say N. +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_HOSTPROGS bool "Host programs" helpsamples/rust/Makefile +1
-0@@ -3,6 +3,7 @@ ccflags-y += -I$(src) # needed for trace events obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.osamples/rust/rust_configfs.rs new file +112
-0@@ -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::prelude::*; +use kernel::sync::Arc ; +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 <Configuration >, +} + +#[pin_data] +struct Configuration { + message: &'staticCStr , +#[pin] + bar:Mutex <(KBox <[u8 ;4096 ]>,usize )>, +} + +impl Configuration { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + message:c_str! ("Hello World\n" ), + bar <-new_mutex! ((KBox ::new ([0 ;4096 ], flags::GFP_KERNEL )?,0 )), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { +fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +pr_info! ("Rust configfs sample (init)\n" ); + +let item_type =configfs_attrs! { + container:Configuration , + child:Child , + pointer:Arc <configfs::Group <Child >>, + pinned:Arc <configfs::Group <Child >>, + attributes: [ + message:0 , + bar:1 , + ], + }; + +try_pin_init! (Self { + config <- configfs::Subsystem ::new ( + kernel::c_str!("rust_configfs" ), item_type,Configuration ::new () + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { +type Parent =Self ; +type Child =Child ; +type ChildPointer =Arc <configfs::Group <Child >>; +type PinChildPointer =Arc <configfs::Group <Child >>; + +fn make_group ( + _this: &Self , + name: &CStr , + ) ->Result <impl PinInit <configfs::Group <Child >,Error >> { +let tpe =configfs_attrs! { + container:Child , + child:GrandChild , + pointer:Arc <configfs::Group <GrandChild >>, + pinned:Arc <configfs::Group <GrandChild >>, + attributes: [ + baz:0 , + ], + }; + +Ok (configfs::Group ::new (name.try_into ()?, tpe,Child ::new ())) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show message\n" ); +let data = container.message; + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +} + +#[vtable] +impl configfs::AttributeOperations <1 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show bar\n" ); +let guard = container.bar.lock (); +let data = guard.0 .as_slice (); +let len = guard.1 ;
samples/rust/rust_configfs.rs line 122
Quoted 10 lines
samples/rust/rust_configfs.rs new file +10
-0+ 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 = container.bar.lock (); + guard.0 [0 ..page.len ()].copy_from_slice (page); + guard.1 = page.len (); +Ok (())
Do we return Err() here? It seems to me that this will either return Ok(()) or panic at,
guard.0[0..page.len()].copy_from_slice(page);
C. Mitrodimas
Quoted 70 lines
samples/rust/rust_configfs.rs new file +70
-0+ } +} + +#[pin_data] +struct Child {} + +impl Child { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::GroupOperations for Child { +type Parent =Self ; +type Child =GrandChild ; +type ChildPointer =Arc <configfs::Group <GrandChild >>; +type PinChildPointer =Arc <configfs::Group <GrandChild >>; + +fn make_group ( + _this: &Self , + name: &CStr , + ) ->Result <impl PinInit <configfs::Group <GrandChild >,Error >> { +let tpe =configfs_attrs! { + container:GrandChild , + attributes: [ + gc:0 , + ], + }; + +Ok (configfs::Group ::new ( + name.try_into ()?, + tpe, +GrandChild ::new (), + )) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Child { +type Data =Child ; + +fn show (_container: &Child , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show baz\n" ); +let data =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 <Self ,Error > { +try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for GrandChild { +type Data =GrandChild ; + +fn show (_container: &GrandChild , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show baz\n" ); +let data =c"Hello GC\n" .to_bytes (); + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +}
Andreas Hindborg
maintainerRe: [PATCH 3/4] rust: configfs: introduce rust support for configfs
Quoted 15 lines · Charalampos Mitrodimas
Quoted 13 lines · Andreas Hindborg
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_refsfeature 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 <[email protected]>---
[cut]
Quoted 30 lines
Quoted 30 lines
rust/kernel/configfs.rs new file +30
-0+ +/// # Safety +/// +/// `item` must be embedded in a `bindings::config_group`. +/// +/// If `item` does not represent the root group of a `configfs` subsystem, +/// the group must be embedded in a `Group<PAR>`. +/// +/// Otherwise, the group must be a embedded in a +/// `bindings::configfs_subsystem` that is embedded in a `Subsystem<PAR>`. +/// +/// `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 = +// 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 satisfy +// the conditions for this call. +let data: &DATA =unsafe {get_group_data (c_group) }; + +let ret =AO ::store ( + data, +// SAFETY: By function safety requirements, `page` is readable + // for at least `size`.
Quoted 8 lines
rust/kernel/configfs.rs line 486
Quoted 6 lines
rust/kernel/configfs.rs new file +6
-0+ unsafe { core::slice::from_raw_parts(page.cast(), size) }, + ); + +match ret { +Ok (()) => sizeas isize , +Err (err) => err.to_errno ()as isize ,Do we reach the Err arm here?
Yes, when AO::store returns Err(_), the error arm should evaluate.
Quoted 512 lines
Quoted 499 lines
rust/kernel/configfs.rs new file +325
-0+ } + } + +/// Create a new attribute. +/// +/// The attribute will appear as a file with name given by `name`. +pub const fn new (name: &'staticCStr ) ->Self { +Self { + attribute:Opaque ::new (bindings::configfs_attribute { + ca_name: nameas *const _ as _ , + ca_owner: core::ptr::null_mut (), + ca_mode:0o660 , + show:Some (Self ::show), + store:if AO ::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 when +/// creating an [`Attribute`]. The type carrying the implementation serve no +/// purpose other than specifying the attribute operations. +#[vtable] +pub trait AttributeOperations <const ID :u64 =0 > { +/// The type of the object that contains the field that is backing the +/// attribute for this operation. +type Data ; + +/// This function is called by the kernel to read the value of an attribute. +/// +/// Implementations should write the rendering of the attribute to `page` +/// and return the number of bytes written. +fn show (data: &Self ::Data , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize >; + +/// This function is called by the kernel to update the value of an attribute. +/// +/// Implementations should parse the value from `page` and update internal +/// state to reflect the parsed value. Partial writes are not supported and +/// implementations should expect the full page to arrive in one write +/// operation. +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 list of +/// [`Attribute`] that will appear in the directory representing a [`Group`]. +/// Users should not directly instantiate this type, rather they should use the +/// [`kernel::configfs_attrs`] macro to declare a static set of attributes for a +/// group. +#[repr(transparent)] +pub struct AttributeList <const N :usize ,DATA >( +UnsafeCell <[*mut kernel::ffi::c_void ;N ]>, +PhantomData <DATA >, +); + +// SAFETY: Ownership of `AttributeList` can safely be transferred to other threads. +unsafe impl <const N :usize ,DATA >Send for AttributeList <N ,DATA > {} + +// SAFETY: We do not provide any operations on `AttributeList` that need synchronization. +unsafe impl <const N :usize ,DATA >Sync for AttributeList <N ,DATA > {} + +impl <const N :usize ,DATA >AttributeList <N ,DATA > { +#[doc(hidden)] +/// # Safety +/// +/// This function can only be called by expanding the `configfs_attrs` +/// macro. +pub const unsafe fn new () ->Self { +Self (UnsafeCell ::new ([core::ptr::null_mut ();N ]),PhantomData ) + } + +#[doc(hidden)] +/// # Safety +/// +/// This function can only be called by expanding the `configfs_attrs` +/// macro. +pub const unsafe fn add < +const I :usize , +const ID :u64 , +O :AttributeOperations <ID ,Data =DATA >, + >( + &'static self, + attribute: &'staticAttribute <ID ,O ,DATA >, + ) { +if I >=N -1 { + kernel::build_error!("Invalid attribute index" ); + } + +// SAFETY: This function is only called through `configfs_attrs`. This +// ensures that we are evaluating the function in const context when +// initializing a static. As such, the reference created below will be +// exclusive. +unsafe { + (&mut *self.0 .get ())[I ] = (attributeas *const Attribute <ID ,O ,DATA >) + .cast_mut () + .cast () + }; + } +} + +/// A representation of the attributes that will appear in a [`Group`]. +/// +/// Users should not directly instantiate objects of this type. Rather, they +/// should use the [`kernel::configfs_attrs`] macro to statically declare the +/// shape of a [`Group`]. +#[pin_data] +pub struct ItemType <DATA > { +#[pin] + item_type:Opaque <bindings::config_item_type >, + _p:PhantomData <DATA >, +} + +// SAFETY: We do not provide any operations on `ItemType` that need synchronization. +unsafe impl <DATA >Sync for ItemType <DATA > {} + +// SAFETY: Ownership of `ItemType` can safely be transferred to other threads. +unsafe impl <DATA >Send for ItemType <DATA > {} + +impl <DATA >ItemType <DATA > { +#[doc(hidden)] +pub const fn new_with_child_ctor <const N :usize ,PAR ,CHLD ,CPTR ,PCPTR >( + owner: &'staticThisModule , + attributes: &'staticAttributeList <N ,DATA >, + ) ->Self +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>, + { +Self { + item_type:Opaque ::new (bindings::config_item_type { + ct_owner: owner.as_ptr (), + ct_group_ops: (&GroupOperationsVTable ::<PAR ,CHLD ,CPTR ,PCPTR >::VTABLE as *const _ ) +as *mut _ , + ct_item_ops: core::ptr::null_mut (), + ct_attrs: attributesas *const _ as _ , + ct_bin_attrs: core::ptr::null_mut (), + }), + _p:PhantomData , + } + } + +#[doc(hidden)] +pub const fn new <const N :usize >( + owner: &'staticThisModule , + attributes: &'staticAttributeList <N ,DATA >, + ) ->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: core::ptr::null_mut (), + ct_attrs: attributesas *const _ as _ , + ct_bin_attrs: core::ptr::null_mut (), + }), + _p:PhantomData , + } + } +} + +impl <DATA >ItemType <DATA > { +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, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child (), + @no_child (x), + @attrs ($($name $attr)*), + @eat ($($name $attr,)*), + @assign (), + @cnt (0usize ), + ) + }; + ( + container: $container:ty, + child: $child:ty, + pointer: $pointer:ty, + pinned: $pinned:ty, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child ($child, $pointer, $pinned), + @no_child (), + @attrs ($($name $attr)*), + @eat ($($name $attr,)*), + @assign (), + @cnt (0usize ), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned: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), + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child ($($child, $pointer, $pinned)?), + @no_child ($($no_child)?), + @attrs ($($aname $aattr)*), + @eat ($($rname $rattr,)*), + @assign ($($assign)* { +const N :usize = $cnt; +// SAFETY: We are expanding `configfs_attrs`. +unsafe { + $crate ::macros::paste!( [< $container:upper _ATTRS >]) + .add ::<N , $attr,_ >( + & $crate ::macros::paste!( [< $container:upper _ $name:upper _ATTR >]) + ) + }; + }), + @cnt (1usize + $cnt), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat(), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) => + { + $crate::configfs_attrs!(final: + @container ($container), + @child ($($child, $pointer, $pinned)?), + @no_child ($($no_child)?), + @attrs ($($aname $aattr)*), + @assign ($($assign)*), + @cnt ($cnt), + ) + }; + (final: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($name:ident $attr:literal)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) => + { + { + $( + $crate::macros::paste!{ +// SAFETY: We are expanding `configfs_attrs`. +static [< $container:upper _ $name:upper _ATTR >]: + $crate ::configfs::Attribute <$attr, $container, $container> = +unsafe { + $crate ::configfs::Attribute ::new (c_str! (::core::stringify!($name))) + }; + } + )* + + +const N :usize = $cnt +1usize ; + $crate::macros::paste!{ +// SAFETY: We are expanding `configfs_attrs`. +static [< $container:upper _ATTRS >]: + $crate ::configfs::AttributeList <N , $container> = +unsafe { $crate ::configfs::AttributeList ::new () }; + } + + $($assign)* + + $( + $crate ::macros::paste!{ +const [<$no_child:upper>]:bool =true ; + }; + + $crate ::macros::paste!{ +static [< $container:upper _TPE >] : $crate ::configfs::ItemType <$container> = + $crate ::configfs::ItemType ::new ::<N >( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + $( + $crate ::macros::paste!{ +static [< $container:upper _TPE >]: + $crate ::configfs::ItemType <$container> = + $crate ::configfs::ItemType ::new_with_child_ctor :: + <N , $container, $child, $pointer, $pinned>( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + &$crate ::macros::paste!( [< $container:upper _TPE >] ) + } + }; + +}rust/kernel/lib.rs +3
-0@@ -19,6 +19,7 @@#![cfg_attr(not( CONFIG_RUSTC_HAS_COERCE_POINTEE ), feature(unsize))] #![feature(inline_const)] #![feature(lint_reasons)] +#![cfg_attr(not( CONFIG_RUSTC_HAS_CONST_MUT_REFS_MERGED ), feature(const_mut_refs))] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. @@ -35,6 +36,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 error;samples/rust/Kconfig +11
-0@@ -30,6 +30,17 @@ config SAMPLE_RUST_PRINT If unsure, say N. +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_HOSTPROGS bool "Host programs" helpsamples/rust/Makefile +1
-0@@ -3,6 +3,7 @@ ccflags-y += -I$(src) # needed for trace events obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.osamples/rust/rust_configfs.rs new file +112
-0@@ -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::prelude::*; +use kernel::sync::Arc ; +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 <Configuration >, +} + +#[pin_data] +struct Configuration { + message: &'staticCStr , +#[pin] + bar:Mutex <(KBox <[u8 ;4096 ]>,usize )>, +} + +impl Configuration { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + message:c_str! ("Hello World\n" ), + bar <-new_mutex! ((KBox ::new ([0 ;4096 ], flags::GFP_KERNEL )?,0 )), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { +fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +pr_info! ("Rust configfs sample (init)\n" ); + +let item_type =configfs_attrs! { + container:Configuration , + child:Child , + pointer:Arc <configfs::Group <Child >>, + pinned:Arc <configfs::Group <Child >>, + attributes: [ + message:0 , + bar:1 , + ], + }; + +try_pin_init! (Self { + config <- configfs::Subsystem ::new ( + kernel::c_str!("rust_configfs" ), item_type,Configuration ::new () + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { +type Parent =Self ; +type Child =Child ; +type ChildPointer =Arc <configfs::Group <Child >>; +type PinChildPointer =Arc <configfs::Group <Child >>; + +fn make_group ( + _this: &Self , + name: &CStr , + ) ->Result <impl PinInit <configfs::Group <Child >,Error >> { +let tpe =configfs_attrs! { + container:Child , + child:GrandChild , + pointer:Arc <configfs::Group <GrandChild >>, + pinned:Arc <configfs::Group <GrandChild >>, + attributes: [ + baz:0 , + ], + }; + +Ok (configfs::Group ::new (name.try_into ()?, tpe,Child ::new ())) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show message\n" ); +let data = container.message; + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +} + +#[vtable] +impl configfs::AttributeOperations <1 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show bar\n" ); +let guard = container.bar.lock (); +let data = guard.0 .as_slice (); +let len = guard.1 ;samples/rust/rust_configfs.rs line 122
Quoted 10 lines
samples/rust/rust_configfs.rs new file +10
-0+ 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 = container.bar.lock (); + guard.0 [0 ..page.len ()].copy_from_slice (page); + guard.1 = page.len (); +Ok (())Do we return
Err()here? It seems to me that this will either return Ok(()) or panic at,
Quoted 1 line
guard.0[0..page.len()].copy_from_slice(page);
configfs guarantees that the attribute buffer is never more than PAGE_SIZE, so this particular code will not panic on systems where PAGE_SIZE is 4k. I should probably use the constant for the buffer size though.
Also, I will add this info about the buffer size to the configfs::AttributeOperatiosn trait documentation.
Thanks!
Best regards,
Andreas Hindborg
Re: [PATCH 3/4] rust: configfs: introduce rust support for configfs
In reply to Andreas HindborgQuoted 89 lines · Andreas Hindborg
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_refsfeature 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 <[email protected]>---
This patch is a direct dependency for
rnull, the rust null block driver.--- init/Kconfig | 3 + rust/bindings/bindings_helper.h | 1 + rust/kernel/configfs.rs | 811 ++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 3 + samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_configfs.rs | 192 ++++++++++ 7 files changed, 1022 insertions(+)init/Kconfig +3
-0@@ -132,6 +132,9 @@ config CC_HAS_COUNTED_BY config RUSTC_HAS_COERCE_POINTEE def_bool RUSTC_VERSION >= 108400 +config RUSTC_HAS_CONST_MUT_REFS_MERGED + def_bool RUSTC_VERSION >= 108300 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE))rust/bindings/bindings_helper.h +1
-0@@ -10,6 +10,7 @@#include <linux/blk-mq.h> #include <linux/blk_types.h> #include <linux/blkdev.h> +#include <linux/configfs.h> #include <linux/cred.h> #include <linux/errname.h> #include <linux/ethtool.h> rust/kernel/configfs.rs new file +33
-0@@ -0,0 +1,811 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! `configfs` interface. +//! +//! `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. +//! - Item `release` hook +//! - Default groups. +//! +//! See the [rust_configfs.rs] sample for a full example use of this module. +//! +//! C header: [`include/linux/configfs.h`](srctree/include/linux/configfs.h) +//! +//! [C documentation]: srctree/Documentation/filesystems/configfs.rst +//! [rust_configfs.rs]: srctree/samples/rust/rust_configfs.rs + +use crate ::container_of; +use crate ::page::PAGE_SIZE ; +use crate ::types::ForeignOwnable ; +use crate ::{prelude::*, types::Opaque }; +use core::cell::UnsafeCell ; +use core::marker::PhantomData ; +use core::ptr::addr_of; +use core::ptr::addr_of_mut; +use kernel::alloc::flags; +use kernel::str::CString ;
rust/kernel/configfs.rs line 43
Quoted 10 lines
rust/kernel/configfs.rs new file +10
-0+ +/// A `configfs` subsystem. +/// +/// This is the top level entrypoint for a `configfs` hierarchy. Embed a field +/// of this type into a struct and implement [`HasSubsystem`] for the struct +/// with the [`kernel::impl_has_subsystem`] macro. Instantiate the subsystem with +/// [`Subsystem::register`]. +/// +/// A [`Subsystem`] is also a [`Group`], and implementing [`HasSubsystem`] for a +/// type will automatically implement [`HasGroup`] for the type.
Rustdoc is unhappy about this (and other lines where HasGroup is used) as HasGroup is private and therefore rustdoc cannot resolve this link.
rust/kernel/configfs.rs line 45
Quoted 2 lines
rust/kernel/configfs.rs new file +2
-0+#[pin_data( PinnedDrop )] +pub struct Subsystem <DATA > {
I would favour this as PascalCase (so Subsystem<Data>), as this is a generic type and not a generic const (I always see all uppercase for const generics).
Quoted 52 lines
rust/kernel/configfs.rs new file +52
-0+#[pin] + subsystem: Opaque<bindings::configfs_subsystem>, +#[pin] + data: DATA, +} + +// SAFETY: We do not provide any operations on `Subsystem`. +unsafe impl <DATA >Sync for Subsystem <DATA > {} + +// SAFETY: Ownership of `Subsystem` can safely be transferred to other threads. +unsafe impl <DATA >Send for Subsystem <DATA > {} + +impl <DATA >Subsystem <DATA > { +/// 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: &'staticCStr , + item_type: &'staticItemType <DATA >, + data:impl PinInit <DATA ,Error >, + ) ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + subsystem <- kernel::init::zeroed ().chain ( + |place: &mut Opaque <bindings::configfs_subsystem >| { +// SAFETY: All of `place` is valid for write. +unsafe { +addr_of_mut! ((*place.get ()).su_group.cg_item.ci_name ) + .write (name.as_ptr ().cast_mut ().cast ()) + }; +// SAFETY: All of `place` is valid for write. +unsafe { +addr_of_mut! ((*place.get ()).su_group.cg_item.ci_type) + .write (item_type.as_ptr ()) + }; +// SAFETY: We initialized the required fields of `place.group` above. +unsafe { bindings::config_group_init (&mut (*place.get ()).su_group) }; +// SAFETY: `place.su_mutex` is valid for use as a mutex. +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.subsystem.get()) },
rust/kernel/configfs.rs line 107
Quoted 10 lines
rust/kernel/configfs.rs new file +10
-0+ ) + }) + } +} + +#[pinned_drop] +impl <DATA >PinnedDrop for Subsystem <DATA > { +fn drop (self:Pin <&mut Self >) { +// SAFETY: We registered `self.subsystem` in the initializer returned by `Self::new`. +unsafe { bindings::configfs_unregister_subsystem (self.subsystem.get ()) };
I see other users (e.g. gpio-virtuser[0]) to also destroy the mutex, is that a required action?
[0]: https://elixir.bootlin.com/linux/v6.13.1/source/drivers/gpio/gpio-virtuser.c#L1841
rust/kernel/configfs.rs line 116
Quoted 9 lines
rust/kernel/configfs.rs new file +9
-0+ } +} + +/// Trait that allows offset calculations for structs that embed a `bindings::config_group`. +/// +/// # Safety +/// +/// - Implementers of this trait must embed a `bindings::config_group`. +/// - Methods must be implemented according to method documentation.
according to methode documentation sounds a bit vague, but I do see where you are comming from, don't have any better ideas
Quoted 120 lines
rust/kernel/configfs.rs new file +120
-0+unsafe trait HasGroup <DATA > { +/// Return the address of the `bindings::config_group` embedded in `Self`. +/// +/// # 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 embedded in +/// `Self`. +unsafe fn container_of (group: *const bindings::config_group ) -> *const Self ; +} + +// SAFETY: `Subsystem<DATA>` embeds a field of type `bindings::config_group` +// within the `subsystem` field. +unsafe impl <DATA >HasGroup <DATA >for Subsystem <DATA > { +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 =unsafe {container_of! (group, bindings::configfs_subsystem, su_group) }; +let opaque_ptr = c_subsys_ptr.cast ::<Opaque <bindings::configfs_subsystem >>(); +// SAFETY: By impl and function safety requirement, `opaque_ptr` and the +// pointer it returns, are within the same allocation. +unsafe {container_of! (opaque_ptr,Subsystem <DATA >, subsystem) } + } +} + +/// A `configfs` group. +/// +/// To add a subgroup to `configfs`, embed a field of this type into a struct +/// and use it for the `CHLD` generic of [`GroupOperations`]. +#[pin_data] +pub struct Group <DATA > { +#[pin] + group:Opaque <bindings::config_group >, +#[pin] + data:DATA , +} + +impl <DATA >Group <DATA > { +/// Create an initializer for a new group. +/// +/// When instantiated, the group will appear as a directory with the name +/// given by `name` and it will contain attributes specified by `item_type`. +pub fn new ( + name:CString , + item_type: &'staticItemType <DATA >, + data:impl PinInit <DATA ,Error >, + ) ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + group <- kernel::init::zeroed ().chain (|v: &mut Opaque <bindings::config_group >| { +let place = v.get (); +let name = name.as_bytes_with_nul ().as_ptr (); +// SAFETY: It is safe to initialize a group once it has been zeroed. +unsafe { + bindings::config_group_init_type_name (place, nameas _ , item_type.as_ptr ()) + }; +Ok (()) + }), + data <- data, + }) + } +} + +// SAFETY: `Group<DATA>` embeds a field of type `bindings::config_group` +// within the `group` field. +unsafe impl <DATA >HasGroup <DATA >for Group <DATA > { +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 = group.cast ::<Opaque <bindings::config_group >>(); +// SAFETY: By impl and function safety requirement, `opaque_ptr` and +// pointer it returns will be in the same allocation. +unsafe {container_of! (opaque_ptr,Self , group) } + } +} + +struct GroupOperationsVTable <PAR ,CHLD ,CPTR ,PCPTR >(PhantomData <(PAR ,CHLD ,CPTR ,PCPTR )>) +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>; + +/// # 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<PAR>`. +/// +/// 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<PAR>`. +unsafe fn get_group_data <'a,PAR >(this: *mut bindings::config_group ) -> &'aPAR { +// SAFETY: `this` is a valid pointer. +let is_root =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 from +// `make_group`. Such a pointer is embedded within a `Group<PAR>`. +unsafe { &(*Group ::<PAR >::container_of (this)).data } + }else { +// SAFETY: By C API contract, `this` is a pointer to the +// `bindings::config_group` field within a `Subsystem<PAR>`.
rust/kernel/configfs.rs line 246
Quoted 10 lines
rust/kernel/configfs.rs new file +10
-0+unsafe { &(*Subsystem ::container_of (this)).data } + } +} + +impl <PAR ,CHLD ,CPTR ,PCPTR >GroupOperationsVTable <PAR ,CHLD ,CPTR ,PCPTR > +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>, +{
I usualy favour having struct and then impls for the functions direcly above each other. Here you have th get_group_data function between that, maybe it makes sense to move that function either further up or down.
So far this is all that I did direcly see.
Thanks,
Fiona
Quoted 818 lines
rust/kernel/configfs.rs new file +565
-0+/// # 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<PAR>`. +/// +/// 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<PAR>`. +/// +/// `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 =unsafe {get_group_data (this) }; + +let group_init =match PAR ::make_group ( + parent_data, +// SAFETY: By function safety requirements, name points to a null +// terminated string. +unsafe {CStr ::from_char_ptr (name) }, + ) { +Ok (init) => init, +Err (e) =>return e.to_ptr (), + }; + +let child_group =CPTR ::try_pin_init (group_init, flags::GFP_KERNEL ); + +match child_group { +Ok (child_group) => { +let child_group_ptr = child_group.into_foreign (); +// SAFETY: We allocated the pointee of `child_ptr` above as a +// `Group<CHLD>`. +unsafe {Group ::<CHLD >::group (child_group_ptr) }.cast_mut () + } +Err (e) => e.to_ptr (), + } + } + +/// # Safety +/// +/// 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<PAR>`. +/// +/// 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<PAR>`. +/// +/// `item` must point to a `bindings::config_item` within a +/// `bindings::config_group` within a `Group<CHLD>`. +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 =unsafe {get_group_data (this) }; + +// SAFETY: By function safety requirements, `item` is embedded in a +// `config_group`. +let c_child_group_ptr = +unsafe { kernel::container_of!(item, bindings::config_group, cg_item) }; +// SAFETY: By function safety requirements, `c_child_group_ptr` is +// embedded within a `Group<CHLD>`. +let r_child_group_ptr =unsafe {Group ::<CHLD >::container_of (c_child_group_ptr) }; + +if PAR ::HAS_DROP_ITEM { +PAR ::drop_item ( + parent_data, +// SAFETY: We called `into_foreign` to produce `r_child_group_ptr` in +// `make_group`. There are not other borrows of this pointer in existence. +unsafe {PCPTR ::borrow (r_child_group_ptr.cast_mut ()) }, + ); + } + +// SAFETY: By C API contract, `configfs` is not going to touch `item` +// again. +unsafe { bindings::config_item_put (item) }; + +// SAFETY: We called `into_foreign` on `r_chilc_group_ptr` in +// `make_group`. +let pin_child:PCPTR =unsafe {PCPTR ::from_foreign (r_child_group_ptr.cast_mut ()) }; +drop (pin_child); + } + +const VTABLE : bindings::configfs_group_operations = bindings::configfs_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 , + }; +} + +/// Operations implemented by `configfs` groups that can create subgroups. +/// +/// Implement this trait on structs that embed a [`Subsystem`] or a [`Group`]. +#[vtable] +pub trait GroupOperations { +/// The parent data object type. +/// +/// The implementer of this trait is this kind of data object. Shold be set +/// to `Self`. +type Parent ; + +/// The child data object type. +/// +/// This group will create subgroups (subdirectories) backed by this kind of +/// object. +type Child ; + +/// The type of the pointer used to point to [`Self::Child`]. +/// +/// This pointer type should support pinned in-place initialization. +type ChildPointer :InPlaceInit <Group <Self ::Child >,PinnedSelf =Self ::PinChildPointer >; + +/// The pinned version of the child pointer. +/// +/// This type must be convertible to a raw pointer according to [`ForeignOwnable`]. +type PinChildPointer :ForeignOwnable <PointedTo =Group <Self ::Child >>; + +/// 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 +/// instantiate a `CHLD` and return a `CPTR` to it. To prevent creation, +/// return a suitable error. +fn make_group ( + this: &Self ::Parent , + name: &CStr , + ) ->Result <impl PinInit <Group <Self ::Child >,Error >>; + +/// 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 `CHLD`. +fn drop_item ( + _this: &Self ::Parent , + _child: <Self ::PinChildPointer as ForeignOwnable >::Borrowed <'_>, + ) { + kernel::build_error!(kernel::error::VTABLE_DEFAULT_ERROR ) + } +} + +/// A `configfs` attribute. +/// +/// An attribute appear as a file in configfs, inside a folder that represent +/// the group that the attribute belongs to. +#[repr(transparent)] +pub struct Attribute <const ID :u64 ,AO ,DATA > { + attribute:Opaque <bindings::configfs_attribute >, + _p:PhantomData <(AO ,DATA )>, +} + +// SAFETY: We do not provide any operations on `Attribute`. +unsafe impl <const ID :u64 ,AO ,DATA >Sync for Attribute <ID ,AO ,DATA > {} + +// SAFETY: Ownership of `Attribute` can safely be transferred to other threads. +unsafe impl <const ID :u64 ,AO ,DATA >Send for Attribute <ID ,AO ,DATA > {} + +impl <const ID :u64 ,AO ,DATA >Attribute <ID ,AO ,DATA > +where +AO :AttributeOperations <ID ,Data =DATA >, +{ +/// # Safety +/// +/// `item` must be embedded in a `bindings::config_group`. +/// +/// If `item` does not represent the root group of a `configfs` subsystem, +/// the group must be embedded in a `Group<PAR>`. +/// +/// Otherwise, the group must be a embedded in a +/// `bindings::configfs_subsystem` that is embedded in a `Subsystem<PAR>`. +/// +/// `page` must point to a writable buffer of size at least [`PAGE_SIZE`]. +unsafe extern "C" fn show ( + item: *mut bindings::config_item , + page: *mut kernel::ffi::c_char , + ) ->isize { +let c_group: *mut bindings::config_group = +// 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 satisfy +// the conditions for this call. +let data: &DATA =unsafe {get_group_data (c_group) }; + +// SAFETY: By function safety requirements, `page` is writable for `PAGE_SIZE`. +let ret =AO ::show (data,unsafe { &mut *(pageas *mut [u8 ;PAGE_SIZE ]) }); + +match ret { +Ok (size) => sizeas isize , +Err (err) => 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` subsystem, +/// the group must be embedded in a `Group<PAR>`. +/// +/// Otherwise, the group must be a embedded in a +/// `bindings::configfs_subsystem` that is embedded in a `Subsystem<PAR>`. +/// +/// `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 = +// 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 satisfy +// the conditions for this call. +let data: &DATA =unsafe {get_group_data (c_group) }; + +let ret =AO ::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 (()) => sizeas isize , +Err (err) => 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: &'staticCStr ) ->Self { +Self { + attribute:Opaque ::new (bindings::configfs_attribute { + ca_name: nameas *const _ as _ , + ca_owner: core::ptr::null_mut (), + ca_mode:0o660 , + show:Some (Self ::show), + store:if AO ::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 when +/// creating an [`Attribute`]. The type carrying the implementation serve no +/// purpose other than specifying the attribute operations. +#[vtable] +pub trait AttributeOperations <const ID :u64 =0 > { +/// The type of the object that contains the field that is backing the +/// attribute for this operation. +type Data ; + +/// This function is called by the kernel to read the value of an attribute. +/// +/// Implementations should write the rendering of the attribute to `page` +/// and return the number of bytes written. +fn show (data: &Self ::Data , page: &mut [u8 ;PAGE_SIZE ]) ->Result <usize >; + +/// This function is called by the kernel to update the value of an attribute. +/// +/// Implementations should parse the value from `page` and update internal +/// state to reflect the parsed value. Partial writes are not supported and +/// implementations should expect the full page to arrive in one write +/// operation. +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 list of +/// [`Attribute`] that will appear in the directory representing a [`Group`]. +/// Users should not directly instantiate this type, rather they should use the +/// [`kernel::configfs_attrs`] macro to declare a static set of attributes for a +/// group. +#[repr(transparent)] +pub struct AttributeList <const N :usize ,DATA >( +UnsafeCell <[*mut kernel::ffi::c_void ;N ]>, +PhantomData <DATA >, +); + +// SAFETY: Ownership of `AttributeList` can safely be transferred to other threads. +unsafe impl <const N :usize ,DATA >Send for AttributeList <N ,DATA > {} + +// SAFETY: We do not provide any operations on `AttributeList` that need synchronization. +unsafe impl <const N :usize ,DATA >Sync for AttributeList <N ,DATA > {} + +impl <const N :usize ,DATA >AttributeList <N ,DATA > { +#[doc(hidden)] +/// # Safety +/// +/// This function can only be called by expanding the `configfs_attrs` +/// macro. +pub const unsafe fn new () ->Self { +Self (UnsafeCell ::new ([core::ptr::null_mut ();N ]),PhantomData ) + } + +#[doc(hidden)] +/// # Safety +/// +/// This function can only be called by expanding the `configfs_attrs` +/// macro. +pub const unsafe fn add < +const I :usize , +const ID :u64 , +O :AttributeOperations <ID ,Data =DATA >, + >( + &'static self, + attribute: &'staticAttribute <ID ,O ,DATA >, + ) { +if I >=N -1 { + kernel::build_error!("Invalid attribute index" ); + } + +// SAFETY: This function is only called through `configfs_attrs`. This +// ensures that we are evaluating the function in const context when +// initializing a static. As such, the reference created below will be +// exclusive. +unsafe { + (&mut *self.0 .get ())[I ] = (attributeas *const Attribute <ID ,O ,DATA >) + .cast_mut () + .cast () + }; + } +} + +/// A representation of the attributes that will appear in a [`Group`]. +/// +/// Users should not directly instantiate objects of this type. Rather, they +/// should use the [`kernel::configfs_attrs`] macro to statically declare the +/// shape of a [`Group`]. +#[pin_data] +pub struct ItemType <DATA > { +#[pin] + item_type:Opaque <bindings::config_item_type >, + _p:PhantomData <DATA >, +} + +// SAFETY: We do not provide any operations on `ItemType` that need synchronization. +unsafe impl <DATA >Sync for ItemType <DATA > {} + +// SAFETY: Ownership of `ItemType` can safely be transferred to other threads. +unsafe impl <DATA >Send for ItemType <DATA > {} + +impl <DATA >ItemType <DATA > { +#[doc(hidden)] +pub const fn new_with_child_ctor <const N :usize ,PAR ,CHLD ,CPTR ,PCPTR >( + owner: &'staticThisModule , + attributes: &'staticAttributeList <N ,DATA >, + ) ->Self +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >, +CPTR :InPlaceInit <Group <CHLD >,PinnedSelf =PCPTR >, +PCPTR :ForeignOwnable <PointedTo =Group <CHLD >>, + { +Self { + item_type:Opaque ::new (bindings::config_item_type { + ct_owner: owner.as_ptr (), + ct_group_ops: (&GroupOperationsVTable ::<PAR ,CHLD ,CPTR ,PCPTR >::VTABLE as *const _ ) +as *mut _ , + ct_item_ops: core::ptr::null_mut (), + ct_attrs: attributesas *const _ as _ , + ct_bin_attrs: core::ptr::null_mut (), + }), + _p:PhantomData , + } + } + +#[doc(hidden)] +pub const fn new <const N :usize >( + owner: &'staticThisModule , + attributes: &'staticAttributeList <N ,DATA >, + ) ->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: core::ptr::null_mut (), + ct_attrs: attributesas *const _ as _ , + ct_bin_attrs: core::ptr::null_mut (), + }), + _p:PhantomData , + } + } +} + +impl <DATA >ItemType <DATA > { +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, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child (), + @no_child (x), + @attrs ($($name $attr)*), + @eat ($($name $attr,)*), + @assign (), + @cnt (0usize ), + ) + }; + ( + container: $container:ty, + child: $child:ty, + pointer: $pointer:ty, + pinned: $pinned:ty, + attributes: [ + $($name:ident: $attr:literal,)* + ], + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child ($child, $pointer, $pinned), + @no_child (), + @attrs ($($name $attr)*), + @eat ($($name $attr,)*), + @assign (), + @cnt (0usize ), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned: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), + ) => { + $crate::configfs_attrs!( + count: + @container ($container), + @child ($($child, $pointer, $pinned)?), + @no_child ($($no_child)?), + @attrs ($($aname $aattr)*), + @eat ($($rname $rattr,)*), + @assign ($($assign)* { +const N :usize = $cnt; +// SAFETY: We are expanding `configfs_attrs`. +unsafe { + $crate ::macros::paste!( [< $container:upper _ATTRS >]) + .add ::<N , $attr,_ >( + & $crate ::macros::paste!( [< $container:upper _ $name:upper _ATTR >]) + ) + }; + }), + @cnt (1usize + $cnt), + ) + }; + (count: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($aname:ident $aattr:literal)*), + @eat(), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) => + { + $crate::configfs_attrs!(final: + @container ($container), + @child ($($child, $pointer, $pinned)?), + @no_child ($($no_child)?), + @attrs ($($aname $aattr)*), + @assign ($($assign)*), + @cnt ($cnt), + ) + }; + (final: + @container($container:ty), + @child($($child:ty, $pointer:ty, $pinned:ty)?), + @no_child($($no_child:ident)?), + @attrs($($name:ident $attr:literal)*), + @assign($($assign:block)*), + @cnt($cnt:expr), + ) => + { + { + $( + $crate::macros::paste!{ +// SAFETY: We are expanding `configfs_attrs`. +static [< $container:upper _ $name:upper _ATTR >]: + $crate ::configfs::Attribute <$attr, $container, $container> = +unsafe { + $crate ::configfs::Attribute ::new (c_str! (::core::stringify!($name))) + }; + } + )* + + +const N :usize = $cnt +1usize ; + $crate::macros::paste!{ +// SAFETY: We are expanding `configfs_attrs`. +static [< $container:upper _ATTRS >]: + $crate ::configfs::AttributeList <N , $container> = +unsafe { $crate ::configfs::AttributeList ::new () }; + } + + $($assign)* + + $( + $crate ::macros::paste!{ +const [<$no_child:upper>]:bool =true ; + }; + + $crate ::macros::paste!{ +static [< $container:upper _TPE >] : $crate ::configfs::ItemType <$container> = + $crate ::configfs::ItemType ::new ::<N >( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + $( + $crate ::macros::paste!{ +static [< $container:upper _TPE >]: + $crate ::configfs::ItemType <$container> = + $crate ::configfs::ItemType ::new_with_child_ctor :: + <N , $container, $child, $pointer, $pinned>( + &THIS_MODULE, &[<$ container:upper _ATTRS >] + ); + } + )? + + &$crate ::macros::paste!( [< $container:upper _TPE >] ) + } + }; + +}rust/kernel/lib.rs +3
-0@@ -19,6 +19,7 @@#![cfg_attr(not( CONFIG_RUSTC_HAS_COERCE_POINTEE ), feature(unsize))] #![feature(inline_const)] #![feature(lint_reasons)] +#![cfg_attr(not( CONFIG_RUSTC_HAS_CONST_MUT_REFS_MERGED ), feature(const_mut_refs))] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. @@ -35,6 +36,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 error;samples/rust/Kconfig +11
-0@@ -30,6 +30,17 @@ config SAMPLE_RUST_PRINT If unsure, say N. +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_HOSTPROGS bool "Host programs" helpsamples/rust/Makefile +1
-0@@ -3,6 +3,7 @@ ccflags-y += -I$(src) # needed for trace events obj-$(CONFIG_SAMPLE_RUST_MINIMAL) += rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o +obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o rust_print-y := rust_print_main.o rust_print_events.osamples/rust/rust_configfs.rs new file +192
-0@@ -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::prelude::*; +use kernel::sync::Arc ; +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 <Configuration >, +} + +#[pin_data] +struct Configuration { + message: &'staticCStr , +#[pin] + bar:Mutex <(KBox <[u8 ;4096 ]>,usize )>, +} + +impl Configuration { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self { + message:c_str! ("Hello World\n" ), + bar <-new_mutex! ((KBox ::new ([0 ;4096 ], flags::GFP_KERNEL )?,0 )), + }) + } +} + +impl kernel::InPlaceModule for RustConfigfs { +fn init (_module: &'staticThisModule ) ->impl PinInit <Self ,Error > { +pr_info! ("Rust configfs sample (init)\n" ); + +let item_type =configfs_attrs! { + container:Configuration , + child:Child , + pointer:Arc <configfs::Group <Child >>, + pinned:Arc <configfs::Group <Child >>, + attributes: [ + message:0 , + bar:1 , + ], + }; + +try_pin_init! (Self { + config <- configfs::Subsystem ::new ( + kernel::c_str!("rust_configfs" ), item_type,Configuration ::new () + ), + }) + } +} + +#[vtable] +impl configfs::GroupOperations for Configuration { +type Parent =Self ; +type Child =Child ; +type ChildPointer =Arc <configfs::Group <Child >>; +type PinChildPointer =Arc <configfs::Group <Child >>; + +fn make_group ( + _this: &Self , + name: &CStr , + ) ->Result <impl PinInit <configfs::Group <Child >,Error >> { +let tpe =configfs_attrs! { + container:Child , + child:GrandChild , + pointer:Arc <configfs::Group <GrandChild >>, + pinned:Arc <configfs::Group <GrandChild >>, + attributes: [ + baz:0 , + ], + }; + +Ok (configfs::Group ::new (name.try_into ()?, tpe,Child ::new ())) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show message\n" ); +let data = container.message; + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +} + +#[vtable] +impl configfs::AttributeOperations <1 >for Configuration { +type Data =Configuration ; + +fn show (container: &Configuration , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show bar\n" ); +let guard = container.bar.lock (); +let data = guard.0 .as_slice (); +let len = 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 = container.bar.lock (); + guard.0 [0 ..page.len ()].copy_from_slice (page); + guard.1 = page.len (); +Ok (()) + } +} + +#[pin_data] +struct Child {} + +impl Child { +fn new () ->impl PinInit <Self ,Error > { +try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::GroupOperations for Child { +type Parent =Self ; +type Child =GrandChild ; +type ChildPointer =Arc <configfs::Group <GrandChild >>; +type PinChildPointer =Arc <configfs::Group <GrandChild >>; + +fn make_group ( + _this: &Self , + name: &CStr , + ) ->Result <impl PinInit <configfs::Group <GrandChild >,Error >> { +let tpe =configfs_attrs! { + container:GrandChild , + attributes: [ + gc:0 , + ], + }; + +Ok (configfs::Group ::new ( + name.try_into ()?, + tpe, +GrandChild ::new (), + )) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for Child { +type Data =Child ; + +fn show (_container: &Child , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show baz\n" ); +let data =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 <Self ,Error > { +try_pin_init! (Self {}) + } +} + +#[vtable] +impl configfs::AttributeOperations <0 >for GrandChild { +type Data =GrandChild ; + +fn show (_container: &GrandChild , page: &mut [u8 ;4096 ]) ->Result <usize > { +pr_info! ("Show baz\n" ); +let data =c"Hello GC\n" .to_bytes (); + page[0 ..data.len ()].copy_from_slice (data); +Ok (data.len ()) + } +}
Andreas Hindborg
maintainerRe: [PATCH 3/4] rust: configfs: introduce rust support for configfs
Quoted 2 lines · Fiona Behrens
Andreas Hindborg <[email protected]> writes:
[cut]
Quoted 4 lines
Quoted 4 lines
rust/kernel/configfs.rs new file +4
-0+/// A `configfs` subsystem. +/// +/// This is the top level entrypoint for a `configfs` hierarchy. Embed a field +/// of this type into a struct and implement [`HasSubsystem`] for the struct
Quoted 8 lines
rust/kernel/configfs.rs line 43
Quoted 5 lines
rust/kernel/configfs.rs new file +5
-0+/// with the [`kernel::impl_has_subsystem`] macro. Instantiate the subsystem with +/// [`Subsystem::register`]. +/// +/// A [`Subsystem`] is also a [`Group`], and implementing [`HasSubsystem`] for a +/// type will automatically implement [`HasGroup`] for the type. Rustdoc is unhappy about this (and other lines where
HasGroupis used) asHasGroupis private and therefore rustdoc cannot resolve this link.
Right, I'll remove this link.
Quoted 7 lines
rust/kernel/configfs.rs line 45
Quoted 3 lines
rust/kernel/configfs.rs new file +2
-0+#[pin_data( PinnedDrop )] +pub struct Subsystem <DATA > {I would favour this as PascalCase (so
Subsystem<Data>), as this is a generic type and not a generic const (I always see all uppercase for const generics).
Yea, that makes sense. I somehow thought all generics had to be screaming snake.
[cut]
Quoted 11 lines
rust/kernel/configfs.rs
Quoted 6 lines
rust/kernel/configfs.rs new file +6
-0+ +#[pinned_drop] +impl <DATA >PinnedDrop for Subsystem <DATA > { +fn drop (self:Pin <&mut Self >) { +// SAFETY: We registered `self.subsystem` in the initializer returned by `Self::new`. +unsafe { bindings::configfs_unregister_subsystem (self.subsystemget ()) };I see other users (e.g. gpio-virtuser[0]) to also destroy the mutex, is that a required action?
[0]: https://elixir.bootlin.com/linux/v6.13.1/source/drivers/gpio/gpio-virtuser.c#L1841
Referring to C null_blk, they do not destroy the mutex when tearing down. I am not sure what the correct thing to do is. Perhaps lockdep wants it destroyed? I'll investigate.
[cut]
Quoted 4 lines
Quoted 4 lines
rust/kernel/configfs.rs new file +4
-0+ +impl <PAR ,CHLD ,CPTR ,PCPTR >GroupOperationsVTable <PAR ,CHLD ,CPTR ,PCPTR > +where +PAR :GroupOperations <Child =CHLD ,ChildPointer =CPTR ,PinChildPointer =PCPTR >,
Quoted 8 lines
rust/kernel/configfs.rs line 246
Quoted 3 lines
rust/kernel/configfs.rs new file +3
-0+ CPTR: InPlaceInit<Group<CHLD>, PinnedSelf = PCPTR>, + PCPTR: ForeignOwnable<PointedTo = Group<CHLD>>, +{I usualy favour having struct and then impls for the functions direcly above each other. Here you have th
get_group_datafunction between that, maybe it makes sense to move that function either further up or down.
I agree, I'll move it 👍
Quoted 2 lines
So far this is all that I did direcly see.
Thanks!
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerRe: [PATCH 3/4] rust: configfs: introduce rust support for configfs
In reply to Andreas HindborgQuoted 12 lines · Andreas Hindborg
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_refsfeature 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 <[email protected]>---
[...]
Quoted 30 lines
rust/kernel/configfs.rs new file +30
-0+/// # Safety +/// +/// 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<PAR>`. +/// +/// 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<PAR>`. +/// +/// `item` must point to a `bindings::config_item` within a +/// `bindings::config_group` within a `Group<CHLD>`. +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 =unsafe {get_group_data (this) }; + +// SAFETY: By function safety requirements, `item` is embedded in a +// `config_group`. +let c_child_group_ptr = +unsafe { kernel::container_of!(item, bindings::config_group, cg_item) }; +// SAFETY: By function safety requirements, `c_child_group_ptr` is +// embedded within a `Group<CHLD>`. +let r_child_group_ptr =unsafe {Group ::<CHLD >::container_of (c_child_group_ptr) }; + +if PAR ::HAS_DROP_ITEM { + PAR::drop_item(
rust/kernel/configfs.rs line 330
Quoted 10 lines
rust/kernel/configfs.rs new file +10
-0+ parent_data, +// SAFETY: We called `into_foreign` to produce `r_child_group_ptr` in +// `make_group`. There are not other borrows of this pointer in existence. + unsafe { PCPTR::borrow(r_child_group_ptr.cast_mut()) }, + ); + } + +// SAFETY: By C API contract, `configfs` is not going to touch `item` +// again. +unsafe { bindings::config_item_put (item) };
This turned out to be wrong. We _do_ have to let go of a refcount here, but we are not allowed to free the item.
rust/kernel/configfs.rs line 335
Quoted 5 lines
rust/kernel/configfs.rs new file +5
-0+ +// SAFETY: We called `into_foreign` on `r_chilc_group_ptr` in +// `make_group`. +let pin_child:PCPTR =unsafe {PCPTR ::from_foreign (r_child_group_ptr.cast_mut ()) }; +drop (pin_child);
So this is wrong and will cause UAF. We have to wait for a call to ct_item_ops.release and do the cleanup there. I will address this in the next version. Removing directories is likely to cause trouble with this patch.
Best regards,
Andreas Hindborg
Andreas Hindborg
maintainerPATCH 4/4 MAINTAINERS: add entry for configfs Rust abstractions
In reply to Andreas HindborgUpdate MAINTAINERS with entry for Rust configfs abstractions.
--- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+)
MAINTAINERS +7 -0
@@ -5806,6 +5806,13 @@ F: fs/configfs/ F: include/linux/configfs.h F: samples/configfs/ +CONFIGFS [RUST] +M: Andreas Hindborg <[email protected]> +L: [email protected] +S: Supported +F: rust/kernel/configfs.rs +F: samples/rust/rust_configfs.rs + CONGATEC BOARD CONTROLLER MFD DRIVER M: Thomas Richard <[email protected]> S: Maintained
Signature · 1 line
2.47.0