* [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell
@ 2026-11-27 12:06 ` Bilal Hashim
2026-11-30 15:53 ` Andreas Hindborg
0 siblings, 1 reply; 3+ messages in thread
From: Bilal Hashim @ 2026-11-27 12:06 UTC (permalink / raw)
To: Andreas Hindborg, Miguel Ojeda; +Cc: rust-for-linux, linux-kernel, Bilal Hashim
The configfs_attrs! macro currently declares a global static AttributeList
wrapping an UnsafeCell<[*mut c_void; N]> and populates it at runtime via
AttributeList::add() on every macro invocation.
Although the static identifier is lexically scoped inside the macro block,
the static storage is globally shared across all invocations and threads.
When a function invoking configfs_attrs! (such as make_group() in
drivers/block/rnull/configfs.rs) executes concurrently on multiple
threads, or while C configfs concurrently reads ct_attrs_const, the
unsynchronized &mut writes into the static UnsafeCell cause aliasing UB
and a data race.
Replace UnsafeCell and the runtime AttributeList::add() calls with a pure
const AttributeList initialized at compile time inside the static item.
This eliminates the data race, removes the runtime pointer stores from
make_group(), and allows the attribute table to reside in read-only
memory.
Tested with LLVM=-22 (verified zero runtime stores to DEVICECONFIG_ATTRS
in LLVM IR) and booted in QEMU with CONFIG_PROVE_LOCKING=y, exercising
/sys/kernel/config/rnull mkdir/read/rmdir and 372/372 Rust KUnit
doctests.
Signed-off-by: Bilal Hashim <AeeSec@126.com>
---
--- a/rust/kernel/configfs.rs
+++ b/rust/kernel/configfs.rs
@@ -117,7 +117,6 @@
use crate::sync::Arc;
use crate::sync::ArcBorrow;
use crate::types::Opaque;
-use core::cell::UnsafeCell;
use core::marker::PhantomData;
/// A configfs subsystem.
@@ -714,43 +713,32 @@
pub struct AttributeList<const N: usize, Data>(
/// Null terminated Array of pointers to [`Attribute`]. The type is [`c_void`]
/// to conform to the C API.
- UnsafeCell<[*mut kernel::ffi::c_void; N]>,
+ [*const 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.
+// SAFETY: `AttributeList` is immutable after compile-time construction.
unsafe impl<const N: usize, Data> Sync for AttributeList<N, Data> {}
impl<const N: usize, Data> AttributeList<N, Data> {
- /// # Safety
- ///
- /// This function must only be called by the [`kernel::configfs_attrs`]
- /// macro.
+ /// Create a compile-time constant attribute list.
#[doc(hidden)]
- pub const unsafe fn new() -> Self {
- Self(UnsafeCell::new([core::ptr::null_mut(); N]), PhantomData)
+ pub const fn new(attrs: [*const kernel::ffi::c_void; N]) -> Self {
+ Self(attrs, PhantomData)
}
- /// # Safety
- ///
- /// The caller must ensure that there are no other concurrent accesses to
- /// `self`. That is, the caller has exclusive access to `self.`
+ /// Convert a static `Attribute` reference into a raw pointer for the list.
#[doc(hidden)]
- pub const unsafe fn add<const I: usize, const ID: u64, O>(
- &'static self,
+ pub const fn attr_ptr<const ID: u64, O>(
attribute: &'static Attribute<ID, O, Data>,
- ) where
+ ) -> *const kernel::ffi::c_void
+ where
O: AttributeOperations<ID, Data = Data>,
{
- // We need a space at the end of our list for a null terminator.
- const { assert!(I < N - 1, "Invalid attribute index") };
-
- // SAFETY: By function safety requirements, we have exclusive access to
- // `self` and the reference created below will be exclusive.
- unsafe { (&mut *self.0.get())[I] = core::ptr::from_ref(attribute).cast_mut().cast() };
+ core::ptr::from_ref(attribute).cast()
}
}
@@ -984,22 +972,7 @@
@no_child($($no_child)?),
@attrs($($aname $aattr)*),
@eat($($rname $rattr,)*),
- @assign($($assign)* {
- const N: usize = $cnt;
- // The following macro text expands to a call to `Attribute::add`.
-
- // SAFETY: By design of this macro, the name of the variable we
- // invoke the `add` method on below, is not visible outside of
- // the macro expansion. The macro does not operate concurrently
- // on this variable, and thus we have exclusive access to the
- // variable.
- unsafe {
- $crate::macros::paste!(
- [< $data:upper _ATTRS >]
- .add::<N, $attr, _>(&[< $data:upper _ $name:upper _ATTR >])
- )
- };
- }),
+ @assign($($assign)*),
@cnt(1usize + $cnt),
)
};
@@ -1052,12 +1025,16 @@
// We need space for a null terminator.
const N: usize = $cnt + 1usize;
- // SAFETY: We are expanding `configfs_attrs`.
static [< $data:upper _ATTRS >]:
$crate::configfs::AttributeList<N, $data> =
- unsafe { $crate::configfs::AttributeList::new() };
-
- $($assign)*
+ $crate::configfs::AttributeList::new([
+ $(
+ $crate::configfs::AttributeList::<N, $data>::attr_ptr(
+ &[< $data:upper _ $name:upper _ATTR >]
+ ),
+ )*
+ ::core::ptr::null(),
+ ]);
$(
const [<$no_child:upper>]: bool = true;
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell
2026-11-27 12:06 ` [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell Bilal Hashim
@ 2026-11-30 15:53 ` Andreas Hindborg
2026-11-30 16:00 ` Andreas Hindborg
0 siblings, 1 reply; 3+ messages in thread
From: Andreas Hindborg @ 2026-11-30 15:53 UTC (permalink / raw)
To: Bilal Hashim, Miguel Ojeda; +Cc: rust-for-linux, linux-kernel, Bilal Hashim
Hi Bilal,
"Bilal Hashim" <AeeSec@126.com> writes:
> The configfs_attrs! macro currently declares a global static AttributeList
> wrapping an UnsafeCell<[*mut c_void; N]> and populates it at runtime via
> AttributeList::add() on every macro invocation.
>
> Although the static identifier is lexically scoped inside the macro block,
> the static storage is globally shared across all invocations and threads.
> When a function invoking configfs_attrs! (such as make_group() in
> drivers/block/rnull/configfs.rs) executes concurrently on multiple
> threads, or while C configfs concurrently reads ct_attrs_const, the
> unsynchronized &mut writes into the static UnsafeCell cause aliasing UB
> and a data race.
>
> Replace UnsafeCell and the runtime AttributeList::add() calls with a pure
> const AttributeList initialized at compile time inside the static item.
> This eliminates the data race, removes the runtime pointer stores from
> make_group(), and allows the attribute table to reside in read-only
> memory.
Thanks for the patch!
When you submit a fix you need to add the "Fixes:" trailer, see [1].
Fixes: 446cafc295bf ("rust: configfs: introduce rust support for configfs")
I can confirm there is a soundness problem, but not as described. C
configfs calls `make_group` with `subsys->su_mutex` held, and child
groups inherit the subsystem of their parent, so as far as I can tell,
`make_group` does not run concurrently within one subsystem.
There are two ways to get a race:
1) If the same `GroupOperations` implementation is used for two
subsystems, the two `make_group` calls take different mutexes and can
write the list concurrently.
2) `populate_attrs()` reads the list after `su_mutex` is dropped, with
only the parent directory inode lock held. With nested groups, a mkdir
in one directory can read the list while a mkdir in another directory of
the same subsystem writes it in `make_group`. `GrandChild` in
samples/rust/rust_configfs.rs has this shape.
In both cases every write stores the same value. Please update the
commit message accordingly.
Please update the documentation that shows the expansion of the macro.
In general I think, your approach for fixing the issue is good. An
alternative would be a synchronized check if the list is already
initialized before calling `add`. But handling the situation at compile
time is better.
See below for comments more detailed comments.
>
> Tested with LLVM=-22 (verified zero runtime stores to DEVICECONFIG_ATTRS
> in LLVM IR) and booted in QEMU with CONFIG_PROVE_LOCKING=y, exercising
> /sys/kernel/config/rnull mkdir/read/rmdir and 372/372 Rust KUnit
> doctests.
>
> Signed-off-by: Bilal Hashim <AeeSec@126.com>
> ---
> --- a/rust/kernel/configfs.rs
> +++ b/rust/kernel/configfs.rs
> @@ -117,7 +117,6 @@
> use crate::sync::Arc;
> use crate::sync::ArcBorrow;
> use crate::types::Opaque;
> -use core::cell::UnsafeCell;
> use core::marker::PhantomData;
>
> /// A configfs subsystem.
> @@ -714,43 +713,32 @@
> pub struct AttributeList<const N: usize, Data>(
> /// Null terminated Array of pointers to [`Attribute`]. The type is [`c_void`]
> /// to conform to the C API.
> - UnsafeCell<[*mut kernel::ffi::c_void; N]>,
> + [*const 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.
> +// SAFETY: `AttributeList` is immutable after compile-time construction.
You don't need the compile-time construction part. Just state that
`AttributeList` is immutable after construction.
> unsafe impl<const N: usize, Data> Sync for AttributeList<N, Data> {}
>
> impl<const N: usize, Data> AttributeList<N, Data> {
> - /// # Safety
> - ///
> - /// This function must only be called by the [`kernel::configfs_attrs`]
> - /// macro.
> + /// Create a compile-time constant attribute list.
> #[doc(hidden)]
> - pub const unsafe fn new() -> Self {
> - Self(UnsafeCell::new([core::ptr::null_mut(); N]), PhantomData)
> + pub const fn new(attrs: [*const kernel::ffi::c_void; N]) -> Self {
This needs to be unsafe with a requirement that `attrs` is the shape we
expect.
We should also add this as an invariant `AttributeList` so we can rely
on it in `ItemType::new`, but that is orthogonal to this patch.
> + Self(attrs, PhantomData)
> }
>
> - /// # Safety
> - ///
> - /// The caller must ensure that there are no other concurrent accesses to
> - /// `self`. That is, the caller has exclusive access to `self.`
> + /// Convert a static `Attribute` reference into a raw pointer for the list.
> #[doc(hidden)]
> - pub const unsafe fn add<const I: usize, const ID: u64, O>(
> - &'static self,
> + pub const fn attr_ptr<const ID: u64, O>(
> attribute: &'static Attribute<ID, O, Data>,
> - ) where
> + ) -> *const kernel::ffi::c_void
> + where
> O: AttributeOperations<ID, Data = Data>,
> {
> - // We need a space at the end of our list for a null terminator.
> - const { assert!(I < N - 1, "Invalid attribute index") };
> -
> - // SAFETY: By function safety requirements, we have exclusive access to
> - // `self` and the reference created below will be exclusive.
> - unsafe { (&mut *self.0.get())[I] = core::ptr::from_ref(attribute).cast_mut().cast() };
> + core::ptr::from_ref(attribute).cast()
I'm uncertain that having this function brings us anything. Could we
open code this line instead?
> }
> }
>
> @@ -984,22 +972,7 @@
> @no_child($($no_child)?),
> @attrs($($aname $aattr)*),
> @eat($($rname $rattr,)*),
> - @assign($($assign)* {
> - const N: usize = $cnt;
> - // The following macro text expands to a call to `Attribute::add`.
> -
> - // SAFETY: By design of this macro, the name of the variable we
> - // invoke the `add` method on below, is not visible outside of
> - // the macro expansion. The macro does not operate concurrently
> - // on this variable, and thus we have exclusive access to the
> - // variable.
> - unsafe {
> - $crate::macros::paste!(
> - [< $data:upper _ATTRS >]
> - .add::<N, $attr, _>(&[< $data:upper _ $name:upper _ATTR >])
> - )
> - };
> - }),
> + @assign($($assign)*),
Is @assign dead code now? I think we can remove it.
> @cnt(1usize + $cnt),
> )
> };
> @@ -1052,12 +1025,16 @@
> // We need space for a null terminator.
> const N: usize = $cnt + 1usize;
>
> - // SAFETY: We are expanding `configfs_attrs`.
> static [< $data:upper _ATTRS >]:
> $crate::configfs::AttributeList<N, $data> =
> - unsafe { $crate::configfs::AttributeList::new() };
> -
> - $($assign)*
> + $crate::configfs::AttributeList::new([
> + $(
> + $crate::configfs::AttributeList::<N, $data>::attr_ptr(
> + &[< $data:upper _ $name:upper _ATTR >]
> + ),
> + )*
> + ::core::ptr::null(),
> + ]);
>
> $(
> const [<$no_child:upper>]: bool = true;
Best regards,
Andreas Hindborg
[1] https://docs.kernel.org/process/submitting-patches.html#describe-your-changes
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell
2026-11-30 15:53 ` Andreas Hindborg
@ 2026-11-30 16:00 ` Andreas Hindborg
0 siblings, 0 replies; 3+ messages in thread
From: Andreas Hindborg @ 2026-11-30 16:00 UTC (permalink / raw)
To: Bilal Hashim, Miguel Ojeda; +Cc: rust-for-linux, linux-kernel, Bilal Hashim
Andreas Hindborg <a.hindborg@kernel.org> writes:
> Hi Bilal,
>
> "Bilal Hashim" <AeeSec@126.com> writes:
>
>> The configfs_attrs! macro currently declares a global static AttributeList
>> wrapping an UnsafeCell<[*mut c_void; N]> and populates it at runtime via
>> AttributeList::add() on every macro invocation.
>>
>> Although the static identifier is lexically scoped inside the macro block,
>> the static storage is globally shared across all invocations and threads.
>> When a function invoking configfs_attrs! (such as make_group() in
>> drivers/block/rnull/configfs.rs) executes concurrently on multiple
>> threads, or while C configfs concurrently reads ct_attrs_const, the
>> unsynchronized &mut writes into the static UnsafeCell cause aliasing UB
>> and a data race.
>>
>> Replace UnsafeCell and the runtime AttributeList::add() calls with a pure
>> const AttributeList initialized at compile time inside the static item.
>> This eliminates the data race, removes the runtime pointer stores from
>> make_group(), and allows the attribute table to reside in read-only
>> memory.
>
> Thanks for the patch!
You should also include these people in the Cc list:
Boqun Feng <boqun@kernel.org> (reviewer:RUST)
Gary Guo <gary@garyguo.net> (reviewer:RUST)
"Björn Roy Baron" <bjorn3_gh@protonmail.com> (reviewer:RUST)
Benno Lossin <lossin@kernel.org> (reviewer:RUST)
Alice Ryhl <aliceryhl@google.com> (reviewer:RUST)
Trevor Gross <tmgross@umich.edu> (reviewer:RUST)
Danilo Krummrich <dakr@kernel.org> (reviewer:RUST)
Daniel Almeida <daniel.almeida@collabora.com> (reviewer:RUST)
Tamir Duberstein <tamird@kernel.org> (reviewer:RUST)
Alexandre Courbot <acourbot@nvidia.com> (reviewer:RUST)
"Onur Özkan" <work@onurozkan.dev> (reviewer:RUST)
You can use scripts/get_maintainer.pl to get the list.
I would encourage you to use the `b4` tool to submit patches. It
automates a lot of the stuff that people often get wrong [1].
Best regards,
Andreas Hindborg
[1] https://b4.docs.kernel.org/en/latest/
^ permalink raw reply [flat|nested] 3+ messages in thread
end of thread, other threads:[~2026-11-30 16:00 UTC | newest]
Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
[not found] <NXvOf3zl4DgB-JlcZcWAvbuWb0188vJIT62ksFA84ON5lyL7Gay3LqY2i0kzLg_hwQqUw4qGcaWUaAsS93vtWA==@protonmail.internalid>
2026-11-27 12:06 ` [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell Bilal Hashim
2026-11-30 15:53 ` Andreas Hindborg
2026-11-30 16:00 ` Andreas Hindborg
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®