From: Andreas Hindborg <a.hindborg@kernel.org>
To: Bilal Hashim <AeeSec@126.com>, Miguel Ojeda <ojeda@kernel.org>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
Bilal Hashim <AeeSec@126.com>
Subject: Re: [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell
Date: Mon, 30 Nov 2026 16:53:10 +0100 [thread overview]
Message-ID: <87y0aas4d5.fsf@t14s.mail-host-address-is-not-set> (raw)
In-Reply-To: <20261127120646.664-1-AeeSec@126.com>
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
next prev parent reply other threads:[~2026-11-30 15:53 UTC|newest]
Thread overview: 3+ messages / expand[flat|nested] mbox.gz Atom feed top
[not found] <NXvOf3zl4DgB-JlcZcWAvbuWb0188vJIT62ksFA84ON5lyL7Gay3LqY2i0kzLg_hwQqUw4qGcaWUaAsS93vtWA==@protonmail.internalid>
2026-11-27 12:06 ` Bilal Hashim
2026-11-30 15:53 ` Andreas Hindborg [this message]
2026-11-30 16:00 ` Andreas Hindborg
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=87y0aas4d5.fsf@t14s.mail-host-address-is-not-set \
--to=a.hindborg@kernel.org \
--cc=AeeSec@126.com \
--cc=linux-kernel@vger.kernel.org \
--cc=ojeda@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
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®