Skip to contentSkip to conversation

Rust locking changes for v6.18

GIT PULL New Boqun Feng 1 participant 7 messages Sep 19, 2025 – Oct 15, 2025

Subsystems (5)
lore
Share & tools
lore

Boqun Feng

author
#0 lore raw

Hi Peter & Ingo,

Please pull this (mostly) Rust locking changes to tip. It's a bit late than usual because I was at Kangrejos conference this week, however the changes are relatively small and simple, so I think it's Ok for v6.18. I also try using "git notes" for submission links as Thomas suggests, let see how it goes ;-)

The following changes since commit 17d9f8eaa87d40a2ff66598875a43363e37a909b:

MAINTAINERS: update atomic infrastructure entry to include Rust (2025-09-15 09:38:36 +0200)

are available in the Git repository at:

https://git.kernel.org/pub/scm/linux/kernel/git/boqun/linux.git/ tags/rust-locking.2025.09.19a

for you to fetch changes up to 9622209360c25d78a81048a9db72f1efef7fbc58:

rust: lock: Add a Pin<&mut T> accessor (2025-09-15 22:28:35 -0400)

Regards,
Boqun

----------------------------------------------------------------
Locking changes for v6.18:

- Fix a data-race in do_raw_write_lock reported by KCSAN

Rust locking changes for v6.18

- Make data in Lock structurally pinned.

Previously the data field of a Lock<T> is not structurally pinned, and it's impossible to initialize the data field with a pin-initializer, hence e.g. a Lock<T> where T is a pin-initialized type is not supported. This encourages workarounds like Lock<Pin<KBox<T>>, which is more complicated and less efficient. Therefore make the data field in Lock structurally pinned to support pin-initialized types in a Lock<T>.

Since the data field is structurally pinned, make Guard<T, ...> only DerefMut is T is Unpin, otherwise Guard::as_mut() is added to provide a Pin<&mut T>. This is different than normal Rust standand library locks.
-----BEGIN PGP SIGNATURE-----

iQEzBAABCAAdFiEEj5IosQTPz8XU1wRHSXnow7UH+rgFAmjNGoEACgkQSXnow7UH +riU8ggAnRUTBam8NTmHJpZfVbbNSfx1ndaARxd9Wb/MLEh8OHYKbVRPJwvWGge+ dafO0VYULku7ho1SeIlLXp4Bbjy3YC6o/J6xOpr9xMmysUky7RHi+Ys0y9gKaSmW daPurQEOS8TBUWu5yVxNAfWoRgPEiPULovbzgANKKAV7QsljyoEg7mQCPxLftPze Hr22HxU+lr6SDH5Efc8ihGqXJAvwunk+0mkJymZbjWo3ZF3cuhXlTMcIlu1SK14a R1VQu5UoX8S5y0T0gkJ84UJ11e0wrSZyT0EqmHWSpVBnyGgWk8H1u284hDiGG2iG FvwoSQ9iVuxLhxjhPUSOjq30DzmFfg==
=MZj4
-----END PGP SIGNATURE-----

----------------------------------------------------------------
Alexander Sverdlin (1):
locking/spinlock/debug: Fix data-race in do_raw_write_lock

Daniel Almeida (3):
rust: lock: guard: Add T: Unpin bound to DerefMut
rust: lock: Pin the inner data
rust: lock: Add a Pin<&mut T> accessor

 kernel/locking/spinlock_debug.c |  4 ++--
 rust/kernel/sync/lock.rs        | 41 +++++++++++++++++++++++++++++++++++++----
 rust/kernel/sync/lock/global.rs |  5 ++++-
 3 files changed, 43 insertions(+), 7 deletions(-)
author
#1 lore raw

PATCH 1/4 locking/spinlock/debug: Fix data-race in do_raw_write_lock

From: Alexander Sverdlin <[email protected]>

KCSAN reports:

BUG: KCSAN: data-race in do_raw_write_lock / do_raw_write_lock

write (marked) to 0xffff800009cf504c of 4 bytes by task 1102 on cpu 1:

 do_raw_write_lock+0x120/0x204
 _raw_write_lock_irq
 do_exit
 call_usermodehelper_exec_async
 ret_from_fork

read to 0xffff800009cf504c of 4 bytes by task 1103 on cpu 0:

 do_raw_write_lock+0x88/0x204
 _raw_write_lock_irq
 do_exit
 call_usermodehelper_exec_async
 ret_from_fork

value changed: 0xffffffff -> 0x00000001

Reported by Kernel Concurrency Sanitizer on:

CPU: 0 PID: 1103 Comm: kworker/u4:1 6.1.111

Commit 1a365e822372 ("locking/spinlock/debug: Fix various data races") has adressed most of these races, but seems to be not consistent/not complete.

From do_raw_write_lock() only debug_write_lock_after() part has been converted to WRITE_ONCE(), but not debug_write_lock_before() part. Do it now.

Fixes 1a365e822372 ("locking/spinlock/debug: Fix various data races")

---

Notes:

    SubmissionLink: https://lore.kernel.org/all/[email protected]/
 kernel/locking/spinlock_debug.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/locking/spinlock_debug.c +2 -2
index 87b03d2e41db..2338b3adfb55 100644
@@ -184,8 +184,8 @@ void do_raw_read_unlock(rwlock_t *lock)
 static inline void debug_write_lock_before(rwlock_t *lock)
 {
 	RWLOCK_BUG_ON(lock->magic != RWLOCK_MAGIC, lock, "bad magic");
-	RWLOCK_BUG_ON(lock->owner == current, lock, "recursion");
-	RWLOCK_BUG_ON(lock->owner_cpu == raw_smp_processor_id(),
+	RWLOCK_BUG_ON(READ_ONCE(lock->owner) == current, lock, "recursion");
+	RWLOCK_BUG_ON(READ_ONCE(lock->owner_cpu) == raw_smp_processor_id(),
 							lock, "cpu recursion");
 }
 
Signature · 1 line
2.51.0
author
#2 lore raw

PATCH 2/4 rust: lock: guard: Add T: Unpin bound to DerefMut

In reply to Boqun Feng

From: Daniel Almeida <[email protected]>

A core property of pinned types is not handing a mutable reference to the inner data in safe code, as this trivially allows that data to be moved.

Enforce this condition by adding a bound on lock::Guard's DerefMut implementation, so that it's only implemented for pinning-agnostic types.

---

Notes:

    SubmissionLink: https://lore.kernel.org/all/[email protected]/
 rust/kernel/sync/lock.rs        | 5 ++++-
 rust/kernel/sync/lock/global.rs | 5 ++++-
 2 files changed, 8 insertions(+), 2 deletions(-)
rust/kernel/sync/lock.rs +4 -1
index 27202beef90c..b482f34bf0ce 100644
@@ -251,7 +251,10 @@ fn deref(&self) -> &Self::Target {
     }
 }
 
-impl<T: ?Sized, B: Backend> core::ops::DerefMut for Guard<'_, T, B> {
+impl<T: ?Sized, B: Backend> core::ops::DerefMut for Guard<'_, T, B>
+where
+    T: Unpin,
+{
     fn deref_mut(&mut self) -> &mut Self::Target {
         // SAFETY: The caller owns the lock, so it is safe to deref the protected data.
         unsafe { &mut *self.lock.data.get() }
rust/kernel/sync/lock/global.rs +4 -1
index d65f94b5caf2..38b448032799 100644
@@ -106,7 +106,10 @@ fn deref(&self) -> &Self::Target {
     }
 }
 
-impl<B: GlobalLockBackend> core::ops::DerefMut for GlobalGuard<B> {
+impl<B: GlobalLockBackend> core::ops::DerefMut for GlobalGuard<B>
+where
+    B::Item: Unpin,
+{
     fn deref_mut(&mut self) -> &mut Self::Target {
         &mut self.inner
     }
Signature · 1 line
2.51.0
author
#3 lore raw

PATCH 3/4 rust: lock: Pin the inner data

In reply to Boqun Feng

From: Daniel Almeida <[email protected]>

In preparation to support Lock<T> where T is pinned, the first thing that needs to be done is to structurally pin the 'data' member. This switches the 't' parameter in Lock<T>::new() to take in an impl PinInit<T> instead of a plain T. This in turn uses the blanket implementation "impl PinInit<T> for T".

Subsequent patches will touch on Guard<T>.

---

Notes:

    SubmissionLink: https://lore.kernel.org/all/[email protected]/
 rust/kernel/sync/lock.rs | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
rust/kernel/sync/lock.rs +8 -3
index b482f34bf0ce..9242790d15db 100644
@@ -11,7 +11,7 @@
     types::{NotThreadSafe, Opaque, ScopeGuard},
 };
 use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
-use pin_init::{pin_data, pin_init, PinInit};
+use pin_init::{pin_data, pin_init, PinInit, Wrapper};
 
 pub mod mutex;
 pub mod spinlock;
@@ -115,6 +115,7 @@ pub struct Lock<T: ?Sized, B: Backend> {
     _pin: PhantomPinned,
 
     /// The data protected by the lock.
+    #[pin]
     pub(crate) data: UnsafeCell<T>,
 }
 
@@ -127,9 +128,13 @@ unsafe impl<T: ?Sized + Send, B: Backend> Sync for Lock<T, B> {}
 
 impl<T, B: Backend> Lock<T, B> {
     /// Constructs a new lock initialiser.
-    pub fn new(t: T, name: &'static CStr, key: Pin<&'static LockClassKey>) -> impl PinInit<Self> {
+    pub fn new(
+        t: impl PinInit<T>,
+        name: &'static CStr,
+        key: Pin<&'static LockClassKey>,
+    ) -> impl PinInit<Self> {
         pin_init!(Self {
-            data: UnsafeCell::new(t),
+            data <- UnsafeCell::pin_init(t),
             _pin: PhantomPinned,
             // SAFETY: `slot` is valid while the closure is called and both `name` and `key` have
             // static lifetimes so they live indefinitely.
Signature · 1 line
2.51.0
author
#4 lore raw

PATCH 4/4 rust: lock: Add a Pin<&mut T> accessor

In reply to Boqun Feng

From: Daniel Almeida <[email protected]>

In order for callers to be able to access the inner T safely if T:
!Unpin, there needs to be a way to get a Pin<&mut T>. Add this accessor and a corresponding example to tell users how it works.

This requires the pin projection functionality [1] for better ergonomic.

[boqun: Apply Daniel's fix to the code example, add the reference to pin projection patch and remove out-of-date part in the commit log]

---

Notes:

    SubmissionLink: https://lore.kernel.org/all/[email protected]/
 rust/kernel/sync/lock.rs | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
rust/kernel/sync/lock.rs +25 -0
index 9242790d15db..cb00fdb94ffd 100644
@@ -245,6 +245,31 @@ pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U {
 
         cb()
     }
+
+    /// Returns a pinned mutable reference to the protected data.
+    ///
+    /// The guard implements [`DerefMut`] when `T: Unpin`, so for [`Unpin`]
+    /// types [`DerefMut`] should be used instead of this function.
+    ///
+    /// [`DerefMut`]: core::ops::DerefMut
+    /// [`Unpin`]: core::marker::Unpin
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::sync::{Mutex, MutexGuard};
+    /// # use core::{pin::Pin, marker::PhantomPinned};
+    /// struct Data(PhantomPinned);
+    ///
+    /// fn example(mutex: &Mutex<Data>) {
+    ///     let mut data: MutexGuard<'_, Data> = mutex.lock();
+    ///     let mut data: Pin<&mut Data> = data.as_mut();
+    /// }
+    /// ```
+    pub fn as_mut(&mut self) -> Pin<&mut T> {
+        // SAFETY: `self.lock.data` is structurally pinned.
+        unsafe { Pin::new_unchecked(&mut *self.lock.data.get()) }
+    }
 }
 
 impl<T: ?Sized, B: Backend> core::ops::Deref for Guard<'_, T, B> {
Signature · 1 line
2.51.0
author
#5 lore raw
In reply to Boqun Feng

[Fixed Peter's email address...]

Quoted 2 lines · Boqun Feng

Hi Peter & Ingo,

Peter, I somehow had a typo in the "To:" field of your email address, but you should be still Cced correctly, sorry about that :(

Regards,
Boqun

Quoted 67 lines

Please pull this (mostly) Rust locking changes to tip. It's a bit late than usual because I was at Kangrejos conference this week, however the changes are relatively small and simple, so I think it's Ok for v6.18. I also try using "git notes" for submission links as Thomas suggests, let see how it goes ;-)

The following changes since commit 17d9f8eaa87d40a2ff66598875a43363e37a909b:

MAINTAINERS: update atomic infrastructure entry to include Rust (2025-09-15 09:38:36 +0200)

are available in the Git repository at:

https://git.kernel.org/pub/scm/linux/kernel/git/boqun/linux.git/ tags/rust-locking.2025.09.19a

for you to fetch changes up to 9622209360c25d78a81048a9db72f1efef7fbc58:

rust: lock: Add a Pin<&mut T> accessor (2025-09-15 22:28:35 -0400)

Regards,
Boqun

----------------------------------------------------------------
Locking changes for v6.18:

- Fix a data-race in do_raw_write_lock reported by KCSAN

Rust locking changes for v6.18

- Make data in Lock structurally pinned.

Previously the data field of a Lock<T> is not structurally pinned, and it's impossible to initialize the data field with a pin-initializer, hence e.g. a Lock<T> where T is a pin-initialized type is not supported. This encourages workarounds like Lock<Pin<KBox<T>>, which is more complicated and less efficient. Therefore make the data field in Lock structurally pinned to support pin-initialized types in a Lock<T>.

Since the data field is structurally pinned, make Guard<T, ...> only DerefMut is T is Unpin, otherwise Guard::as_mut() is added to provide a Pin<&mut T>. This is different than normal Rust standand library locks.
-----BEGIN PGP SIGNATURE-----

iQEzBAABCAAdFiEEj5IosQTPz8XU1wRHSXnow7UH+rgFAmjNGoEACgkQSXnow7UH +riU8ggAnRUTBam8NTmHJpZfVbbNSfx1ndaARxd9Wb/MLEh8OHYKbVRPJwvWGge+ dafO0VYULku7ho1SeIlLXp4Bbjy3YC6o/J6xOpr9xMmysUky7RHi+Ys0y9gKaSmW daPurQEOS8TBUWu5yVxNAfWoRgPEiPULovbzgANKKAV7QsljyoEg7mQCPxLftPze Hr22HxU+lr6SDH5Efc8ihGqXJAvwunk+0mkJymZbjWo3ZF3cuhXlTMcIlu1SK14a R1VQu5UoX8S5y0T0gkJ84UJ11e0wrSZyT0EqmHWSpVBnyGgWk8H1u284hDiGG2iG FvwoSQ9iVuxLhxjhPUSOjq30DzmFfg==
=MZj4
-----END PGP SIGNATURE-----

----------------------------------------------------------------
Alexander Sverdlin (1):
locking/spinlock/debug: Fix data-race in do_raw_write_lock

Daniel Almeida (3):
rust: lock: guard: Add T: Unpin bound to DerefMut
rust: lock: Pin the inner data
rust: lock: Add a Pin<&mut T> accessor

 kernel/locking/spinlock_debug.c |  4 ++--
 rust/kernel/sync/lock.rs        | 41 +++++++++++++++++++++++++++++++++++++----
 rust/kernel/sync/lock/global.rs |  5 ++++-
 3 files changed, 43 insertions(+), 7 deletions(-)
author
#6 lore raw
In reply to Boqun Feng
Quoted 2 lines · Boqun Feng

Hi Peter & Ingo,

Peter, this pull request was missed during last cycle, and I want to push it in this cycle, and I have two options:

* I can wait and add more locking patches in this cycle and send a PR in -rc4 or -rc5.

* or I can send a PR as it is at the moment (as a "part 1" of locking changes), and rest locking patches could be in a different PR.

Let me know which one you guys prefer, thanks!

Regards,
Boqun

Quoted 67 lines

Please pull this (mostly) Rust locking changes to tip. It's a bit late than usual because I was at Kangrejos conference this week, however the changes are relatively small and simple, so I think it's Ok for v6.18. I also try using "git notes" for submission links as Thomas suggests, let see how it goes ;-)

The following changes since commit 17d9f8eaa87d40a2ff66598875a43363e37a909b:

MAINTAINERS: update atomic infrastructure entry to include Rust (2025-09-15 09:38:36 +0200)

are available in the Git repository at:

https://git.kernel.org/pub/scm/linux/kernel/git/boqun/linux.git/ tags/rust-locking.2025.09.19a

for you to fetch changes up to 9622209360c25d78a81048a9db72f1efef7fbc58:

rust: lock: Add a Pin<&mut T> accessor (2025-09-15 22:28:35 -0400)

Regards,
Boqun

----------------------------------------------------------------
Locking changes for v6.18:

- Fix a data-race in do_raw_write_lock reported by KCSAN

Rust locking changes for v6.18

- Make data in Lock structurally pinned.

Previously the data field of a Lock<T> is not structurally pinned, and it's impossible to initialize the data field with a pin-initializer, hence e.g. a Lock<T> where T is a pin-initialized type is not supported. This encourages workarounds like Lock<Pin<KBox<T>>, which is more complicated and less efficient. Therefore make the data field in Lock structurally pinned to support pin-initialized types in a Lock<T>.

Since the data field is structurally pinned, make Guard<T, ...> only DerefMut is T is Unpin, otherwise Guard::as_mut() is added to provide a Pin<&mut T>. This is different than normal Rust standand library locks.
-----BEGIN PGP SIGNATURE-----

iQEzBAABCAAdFiEEj5IosQTPz8XU1wRHSXnow7UH+rgFAmjNGoEACgkQSXnow7UH +riU8ggAnRUTBam8NTmHJpZfVbbNSfx1ndaARxd9Wb/MLEh8OHYKbVRPJwvWGge+ dafO0VYULku7ho1SeIlLXp4Bbjy3YC6o/J6xOpr9xMmysUky7RHi+Ys0y9gKaSmW daPurQEOS8TBUWu5yVxNAfWoRgPEiPULovbzgANKKAV7QsljyoEg7mQCPxLftPze Hr22HxU+lr6SDH5Efc8ihGqXJAvwunk+0mkJymZbjWo3ZF3cuhXlTMcIlu1SK14a R1VQu5UoX8S5y0T0gkJ84UJ11e0wrSZyT0EqmHWSpVBnyGgWk8H1u284hDiGG2iG FvwoSQ9iVuxLhxjhPUSOjq30DzmFfg==
=MZj4
-----END PGP SIGNATURE-----

----------------------------------------------------------------
Alexander Sverdlin (1):
locking/spinlock/debug: Fix data-race in do_raw_write_lock

Daniel Almeida (3):
rust: lock: guard: Add T: Unpin bound to DerefMut
rust: lock: Pin the inner data
rust: lock: Add a Pin<&mut T> accessor

 kernel/locking/spinlock_debug.c |  4 ++--
 rust/kernel/sync/lock.rs        | 41 +++++++++++++++++++++++++++++++++++++----
 rust/kernel/sync/lock/global.rs |  5 ++++-
 3 files changed, 43 insertions(+), 7 deletions(-)