Rust for Linux List
 help / color / mirror / Atom feed
* [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell
@ 2026-11-27 12:06 Bilal Hashim
  0 siblings, 0 replies; only message 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] only message in thread

only message in thread, other threads:[~2026-11-27 12:07 UTC | newest]

Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-27 12:06 [PATCH] rust: configfs: initialize AttributeList at compile time without UnsafeCell Bilal Hashim

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox