Rust atomics & locking changes for v6.19
Subsystems (5)
Hi Peter & Ingo,
Please pull this Rust atomics + locking changes for v6.19, it's fairly simple and small for this cycle ;-)
The following changes since commit b94d45b6bbb42571ec225d3be0e7457c8765a5b4:
seqlock: Allow KASAN to fail optimizing (2025-10-28 09:58:57 +0100)
are available in the Git repository at:
git://git.kernel.org/pub/scm/linux/kernel/git/boqun/linux.git tags/rust-locking.2025.11.13
for you to fetch changes up to 3572e2edc7b611d0b564c487bafda04b5dbb5134:
locking/mutex: Redo __mutex_init() (2025-11-12 08:56:42 -0800)
Regards,
Boqun
----------------------------------------------------------------
Rust atomic changes for v6.19:
- Replace Rust native atomics with LKMM atomics in debugfs
Locking changes for v6.19:
- Redo __mutex_init() to allow compiler removing unused parameters -----BEGIN PGP SIGNATURE-----
iQEzBAABCAAdFiEEj5IosQTPz8XU1wRHSXnow7UH+rgFAmkWw9wACgkQSXnow7UH +rjD+gf9Eri5Au1hyYD/UPmBBZWMgWRx32RMbJ261he1YEa1gTbHqitlHu0++vmf 8+B1VGU7ts6c9vyAR/7yAAuIjfnnunxcF7NnjsguGSywWG3uQpd75o2C+TiELwfz aJvkNTNUcX6IA7I2j4tdGh3likG+4viSb2LxQBRUkJ557LySRv+/XcBrpjWW6lit pIohp3UUVGApTjwP/UiBETUqZz9bnwYHhQvPaCwCUt93GiNrAQC8rmQIMFQj8RhN g28RsLXxN06ozGLsjfNFHVRTDRc8KsLgWsuQwWPwMY6CUE9AiyqX4B6IZ9ymtGNt ENbskYAiXLDqmShB7ASmjL4CST8LNQ==
=8JA2
-----END PGP SIGNATURE-----
----------------------------------------------------------------
Boqun Feng (3):
rust: sync: atomic: Make Atomic*Ops pub(crate)
rust: sync: atomic: Implement Debug for Atomic<Debug>
rust: debugfs: Replace the usage of Rust native atomics
Sebastian Andrzej Siewior (1):
locking/mutex: Redo __mutex_init()
include/linux/mutex.h | 45 ++++++++++++++++++++++++------- kernel/locking/mutex.c | 22 ++++++++++----- kernel/locking/rtmutex_api.c | 19 ++++++++++--- rust/kernel/debugfs/traits.rs | 53 ++++++++++++------------------------- rust/kernel/sync/atomic.rs | 12 ++++++++- samples/rust/rust_debugfs.rs | 12 ++++----- samples/rust/rust_debugfs_scoped.rs | 6 ++--- 7 files changed, 102 insertions(+), 67 deletions(-)
PATCH 1/4 rust: sync: atomic: Make Atomic*Ops pub(crate)
In order to write code over a generate Atomic<T> we need to make Atomic*Ops public so that functions like .load() and .store() are available. Make these pub(crate) at the beginning so the usage in kernel crate is supported.
--- rust/kernel/sync/atomic.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
rust/kernel/sync/atomic.rs +2 -1
@@ -22,9 +22,10 @@pub use internal::AtomicImpl ;pub use ordering::{Acquire ,Full ,Relaxed ,Release }; +pub (crate )use internal::{AtomicArithmeticOps ,AtomicBasicOps ,AtomicExchangeOps };use crate ::build_error; -use internal::{AtomicArithmeticOps ,AtomicBasicOps ,AtomicExchangeOps ,AtomicRepr }; +use internal::AtomicRepr ;use ordering::OrderingType ;/// A memory location which can be safely modified from multiple execution contexts.
Signature · 1 line
2.50.1 (Apple Git-155)
PATCH 2/4 rust: sync: atomic: Implement Debug for Atomic<Debug>
In reply to Boqun FengIf Atomic<T> is Debug then it's a debugfs::Writer, therefore make it so since 1) debugfs needs to support Atomic<T> and 2) it's rather trivial to implement Debug for Atomic<Debug>.
--- rust/kernel/sync/atomic.rs | 9 +++++++++ 1 file changed, 9 insertions(+)
rust/kernel/sync/atomic.rs +9 -0
@@ -307,6 +307,15 @@ pub fn store<Ordering: ordering::ReleaseOrRelaxed>(&self, v: T, _: Ordering) { } } +impl <T :AtomicType + core::fmt::Debug > core::fmt::Debug for Atomic <T > +where +T ::Repr :AtomicBasicOps , +{ +fn fmt (&self, f: &mut core::fmt::Formatter <'_>) -> core::fmt::Result { + core::fmt::Debug ::fmt (&self.load (Relaxed ), f) + } +} +impl <T :AtomicType >Atomic <T >where T ::Repr :AtomicExchangeOps ,
Signature · 1 line
2.50.1 (Apple Git-155)
PATCH 3/4 rust: debugfs: Replace the usage of Rust native atomics
In reply to Boqun FengRust native atomics are not allowed to use in kernel due to the mismatch of memory model with Linux kernel memory model, hence remove the usage of Rust native atomics in debufs.
--- rust/kernel/debugfs/traits.rs | 53 +++++++++-------------------- samples/rust/rust_debugfs.rs | 12 +++---- samples/rust/rust_debugfs_scoped.rs | 6 ++-- 3 files changed, 25 insertions(+), 46 deletions(-)
rust/kernel/debugfs/traits.rs +17 -36
@@ -4,14 +4,11 @@//! Traits for rendering or updating values exported to DebugFS. use crate ::prelude::*; +use crate ::sync::atomic::{Atomic ,AtomicBasicOps ,AtomicType ,Relaxed };use crate ::sync::Mutex ;use crate ::uaccess::UserSliceReader ;use core::fmt::{self,Debug ,Formatter };use core::str::FromStr ; -use core::sync::atomic::{ -AtomicI16 ,AtomicI32 ,AtomicI64 ,AtomicI8 ,AtomicIsize ,AtomicU16 ,AtomicU32 ,AtomicU64 , -AtomicU8 ,AtomicUsize ,Ordering , -};/// A trait for types that can be written into a string. ///
@@ -66,37 +63,21 @@ fn read_from_slice(&self, reader: &mut UserSliceReader) -> Result { } } -macro_rules! impl_reader_for_atomic { - ($(($atomic_type:ty, $int_type:ty)),*) => { - $( -impl Reader for $atomic_type { -fn read_from_slice (&self, reader: &mut UserSliceReader ) ->Result { -let mut buf = [0u8 ;21 ];// Enough for a 64-bit number. -if reader.len () > buf.len () { -return Err (EINVAL ); - } -let n = reader.len (); - reader.read_slice (&mut buf[..n])?; +impl <T :AtomicType +FromStr >Reader for Atomic <T > +where +T ::Repr :AtomicBasicOps , +{ +fn read_from_slice (&self, reader: &mut UserSliceReader ) ->Result { +let mut buf = [0u8 ;21 ];// Enough for a 64-bit number. +if reader.len () > buf.len () { +return Err (EINVAL ); + } +let n = reader.len (); + reader.read_slice (&mut buf[..n])?; -let s = core::str ::from_utf8 (&buf[..n]).map_err (|_|EINVAL )?; -let val = s.trim ().parse ::<$int_type>().map_err (|_|EINVAL )?; - self.store (val,Ordering ::Relaxed ); -Ok (()) - } - } - )* - }; +let s = core::str::from_utf8 (&buf[..n]).map_err (|_|EINVAL )?; +let val = s.trim ().parse ::<T >().map_err (|_|EINVAL )?; + self.store (val,Relaxed ); +Ok (()) + } } - -impl_reader_for_atomic! ( - (AtomicI16 ,i16 ), - (AtomicI32 ,i32 ), - (AtomicI64 ,i64 ), - (AtomicI8 ,i8 ), - (AtomicIsize ,isize ), - (AtomicU16 ,u16 ), - (AtomicU32 ,u32 ), - (AtomicU64 ,u64 ), - (AtomicU8 ,u8 ), - (AtomicUsize ,usize ) -);
samples/rust/rust_debugfs.rs +5 -7
@@ -32,14 +32,12 @@//! ``` use core::str::FromStr ; -use core::sync::atomic::AtomicUsize ; -use core::sync::atomic::Ordering ;use kernel::c_str;use kernel::debugfs::{Dir ,File };use kernel::new_mutex;use kernel::prelude::*; +use kernel::sync::atomic::{Atomic ,Relaxed };use kernel::sync::Mutex ; -use kernel::{acpi, device::Core , of, platform, str::CString , types::ARef }; kernel::module_platform_driver! {
@@ -59,7 +57,7 @@ struct RustDebugFs {#[pin] _compatible: File<CString>,#[pin] - counter: File<AtomicUsize>, + counter: File<Atomic<usize>>,#[pin] inner: File<Mutex<Inner>>, }
@@ -109,7 +107,7 @@ fn probe( ) -> Result<Pin<KBox<Self>>> {let result =KBox ::try_pin_init (RustDebugFs ::new (pdev),GFP_KERNEL )?;// We can still mutate fields through the files which are atomic or mutexed: - result.counter.store (91 ,Ordering ::Relaxed ); + result.counter.store (91 ,Relaxed ); {let mut guard = result.inner.lock (); guard.x = guard.y;
@@ -120,8 +118,8 @@ fn probe( }impl RustDebugFs { -fn build_counter (dir: &Dir ) ->impl PinInit <File <AtomicUsize >> + '_ { - dir.read_write_file (c_str! ("counter" ),AtomicUsize ::new (0 )) +fn build_counter (dir: &Dir ) ->impl PinInit <File <Atomic <usize >>> + '_ { + dir.read_write_file (c_str! ("counter" ),Atomic ::<usize >::new (0 )) }fn build_inner (dir: &Dir ) ->impl PinInit <File <Mutex <Inner >>> + '_ {
samples/rust/rust_debugfs_scoped.rs +3 -3
@@ -6,9 +6,9 @@//! `Scope::dir` to create a variety of files without the need to separately //! track them all. -use core::sync::atomic::AtomicUsize ;use kernel::debugfs::{Dir ,Scope };use kernel::prelude::*; +use kernel::sync::atomic::Atomic ;use kernel::sync::Mutex ;use kernel::{c_str, new_mutex, str::CString };
@@ -62,7 +62,7 @@ fn create_file_write(let file_name =CString ::try_from_fmt (fmt! ("{name_str}" ))?;for subin items { nums.push ( -AtomicUsize ::new (sub.parse ().map_err (|_|EINVAL )?), +Atomic ::<usize >::new (sub.parse ().map_err (|_|EINVAL )?),GFP_KERNEL , )?; }
@@ -109,7 +109,7 @@ fn init(device_dir: Dir) -> impl PinInit<Self> {struct DeviceData { name:CString , - nums:KVec <AtomicUsize >, + nums:KVec <Atomic <usize >>, }fn init_control (base_dir: &Dir , dyn_dirs:Dir ) ->impl PinInit <Scope <ModuleData >> + '_ {
Signature · 1 line
2.50.1 (Apple Git-155)
PATCH 4/4 locking/mutex: Redo __mutex_init()
In reply to Boqun FengFrom: Sebastian Andrzej Siewior <[email protected]>
mutex_init() invokes __mutex_init() providing the name of the lock and a pointer to a the lock class. With LOCKDEP enabled this information is useful but without LOCKDEP it not used at all. Passing the pointer information of the lock class might be considered negligible but the name of the lock is passed as well and the string is stored. This information is wasting storage.
Split __mutex_init() into a _genereic() variant doing the initialisation of the lock and a _lockdep() version which does _genereic() plus the lockdep bits. Restrict the lockdep version to lockdep enabled builds allowing the compiler to remove the unused parameter.
This results in the following size reduction:
text data bss dec filename | 30237599 8161430 1176624 39575653 vmlinux.defconfig | 30233269 8149142 1176560 39558971 vmlinux.defconfig.patched
-4.2KiB -12KiB
| 32455099 8471098 12934684 53860881 vmlinux.defconfig.lockdep | 32455100 8471098 12934684 53860882 vmlinux.defconfig.patched.lockdep
| 27152407 7191822 2068040 36412269 vmlinux.defconfig.preempt_rt | 27145937 7183630 2067976 36397543 vmlinux.defconfig.patched.preempt_rt
-6.3KiB -8KiB
| 29382020 7505742 13784608 50672370 vmlinux.defconfig.preempt_rt.lockdep | 29376229 7505742 13784544 50666515 vmlinux.defconfig.patched.preempt_rt.lockdep
-5.6KiB
--- include/linux/mutex.h | 45 ++++++++++++++++++++++++++++-------- kernel/locking/mutex.c | 22 +++++++++++++----- kernel/locking/rtmutex_api.c | 19 +++++++++++---- 3 files changed, 66 insertions(+), 20 deletions(-)
include/linux/mutex.h +35 -10
@@ -86,8 +86,23 @@ do { \#define DEFINE_MUTEX (mutexname) \ struct mutex mutexname = __MUTEX_INITIALIZER(mutexname) -extern void __mutex_init (struct mutex *lock,const char *name, -struct lock_class_key *key); +#ifdef CONFIG_DEBUG_LOCK_ALLOC +void mutex_init_lockep (struct mutex *lock,const char *name,struct lock_class_key *key); + +static inline void __mutex_init (struct mutex *lock,const char *name, +struct lock_class_key *key) +{ +mutex_init_lockep (lock, name, key); +} +#else +extern void mutex_init_generic (struct mutex *lock); + +static inline void __mutex_init (struct mutex *lock,const char *name, +struct lock_class_key *key) +{ +mutex_init_generic (lock); +} +#endif /* !CONFIG_DEBUG_LOCK_ALLOC */ /** * mutex_is_locked - is the mutex locked
@@ -111,17 +126,27 @@ extern bool mutex_is_locked(struct mutex *lock);#define DEFINE_MUTEX (mutexname) \ struct mutex mutexname = __MUTEX_INITIALIZER(mutexname) -extern void __mutex_rt_init (struct mutex *lock,const char *name, -struct lock_class_key *key); -#define mutex_is_locked (l) rt_mutex_base_is_locked(&(l)->rtmutex) -#define __mutex_init (mutex, name, key) \ -do { \ - rt_mutex_base_init(&(mutex)->rtmutex); \ - __mutex_rt_init((mutex), name, key); \ -} while (0) +#ifdef CONFIG_DEBUG_LOCK_ALLOC +extern void mutex_rt_init_lockdep (struct mutex *mutex,const char *name, +struct lock_class_key *key); + +static inline void __mutex_init (struct mutex *lock,const char *name, +struct lock_class_key *key) +{ +mutex_rt_init_lockdep (lock, name, key); +} +#else +extern void mutex_rt_init_generic (struct mutex *mutex); + +static inline void __mutex_init (struct mutex *lock,const char *name, +struct lock_class_key *key) +{ +mutex_rt_init_generic (lock); +} +#endif /* !CONFIG_LOCKDEP */ #endif /* CONFIG_PREEMPT_RT */ #ifdef CONFIG_DEBUG_MUTEXES
kernel/locking/mutex.c +16 -6
@@ -43,8 +43,7 @@# define MUTEX_WARN_ON (cond)#endif -void -__mutex_init (struct mutex *lock,const char *name,struct lock_class_key *key) +static void __mutex_init_generic (struct mutex *lock) {atomic_long_set (&lock->owner,0 );raw_spin_lock_init (&lock->wait_lock);
@@ -52,10 +51,7 @@ __mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key)#ifdef CONFIG_MUTEX_SPIN_ON_OWNER osq_lock_init (&lock->osq);#endif - -debug_mutex_init (lock, name, key); } -EXPORT_SYMBOL (__mutex_init);static inline struct task_struct *__owner_task (unsigned long owner) {
@@ -142,6 +138,11 @@ static inline bool __mutex_trylock(struct mutex *lock)* There is nothing that would stop spreading the lockdep annotations outwards * except more code. */ +void mutex_init_generic (struct mutex *lock) +{ +__mutex_init_generic (lock); +} +EXPORT_SYMBOL (mutex_init_generic);/* * Optimistic trylock that only works in the uncontended case. Make sure to
@@ -166,7 +167,16 @@ static __always_inline bool __mutex_unlock_fast(struct mutex *lock) return atomic_long_try_cmpxchg_release(&lock->owner, &curr, 0UL); } -#endif + +#else /* !CONFIG_DEBUG_LOCK_ALLOC */ + +void mutex_init_lockep (struct mutex *lock,const char *name,struct lock_class_key *key) +{ +__mutex_init_generic (lock); +debug_mutex_init (lock, name, key); +} +EXPORT_SYMBOL (mutex_init_lockep); +#endif /* !CONFIG_DEBUG_LOCK_ALLOC */ static inline void __mutex_set_flag (struct mutex *lock,unsigned long flag) {
kernel/locking/rtmutex_api.c +15 -4
@@ -515,13 +515,11 @@ void rt_mutex_debug_task_free(struct task_struct *task)#ifdef CONFIG_PREEMPT_RT /* Mutexes */ -void __mutex_rt_init (struct mutex *mutex,const char *name, -struct lock_class_key *key) +static void __mutex_rt_init_generic (struct mutex *mutex) { +rt_mutex_base_init (&mutex->rtmutex);debug_check_no_locks_freed ((void *)mutex,sizeof (*mutex)); -lockdep_init_map_wait (&mutex->dep_map, name, key,0 ,LD_WAIT_SLEEP ); } -EXPORT_SYMBOL (__mutex_rt_init); static __always_inline int __mutex_lock_common(struct mutex *lock, unsigned int state,
@@ -542,6 +540,13 @@ static __always_inline int __mutex_lock_common(struct mutex *lock, }#ifdef CONFIG_DEBUG_LOCK_ALLOC +void mutex_rt_init_lockdep (struct mutex *mutex,const char *name,struct lock_class_key *key) +{ +__mutex_rt_init_generic (mutex); +lockdep_init_map_wait (&mutex->dep_map, name, key,0 ,LD_WAIT_SLEEP ); +} +EXPORT_SYMBOL (mutex_rt_init_lockdep); + void __sched mutex_lock_nested(struct mutex *lock, unsigned int subclass) {__mutex_lock_common (lock,TASK_UNINTERRUPTIBLE , subclass,NULL , _RET_IP_);
@@ -598,6 +603,12 @@ int __sched _mutex_trylock_nest_lock(struct mutex *lock,EXPORT_SYMBOL_GPL (_mutex_trylock_nest_lock);#else /* CONFIG_DEBUG_LOCK_ALLOC */ +void mutex_rt_init_generic (struct mutex *mutex) +{ +__mutex_rt_init_generic (mutex); +} +EXPORT_SYMBOL (mutex_rt_init_generic); + void __sched mutex_lock(struct mutex *lock) {__mutex_lock_common (lock,TASK_UNINTERRUPTIBLE ,0 ,NULL , _RET_IP_);
Signature · 1 line
2.50.1 (Apple Git-155)
Peter Zijlstra
maintainerQuoted 7 lines · Boqun Feng
Boqun Feng (3):
rust: sync: atomic: Make Atomic*Ops pub(crate)
rust: sync: atomic: Implement Debug for Atomic<Debug>
rust: debugfs: Replace the usage of Rust native atomicsSebastian Andrzej Siewior (1):
locking/mutex: Redo__mutex_init()
Done, thanks!