Skip to contentSkip to conversation

rust: introduce DropGuard

PATCH In review Mohamed Osama 5 participants 13 messages Sep 27 – Oct 10

Subsystems (7)
lore
Share & tools
lore
#0 lore raw

v4 cover rust: introduce DropGuard

This series adds the Rust kernel DropGuard API and migrates existing cleanup guards in the block, serdev, and locking code to use it.

DropGuard is vendored from the Rust standard library and re-exported through kernel::mem.

Changes since v3:
- Vendor DropGuard in rust/kernel/std_vendor.rs and re-export it from kernel::mem, following Gary Guo's review.
- Remove the DropGuard KUnit tests and Kconfig option since the implementation is vendored from the standard library.
- Keep the existing ScopeGuard API unchanged.

Testing:
- make LLVM=1 rustfmtcheck
- make LLVM=1 -j$(nproc)

Mohamed Osama (4):
rust: mem: add DropGuard
rust: block: gen_disk: use DropGuard
rust: serdev: use DropGuard
rust: sync: lock: use DropGuard

 rust/kernel/block/mq/gen_disk.rs | 11 ++--
 rust/kernel/mem.rs               |  2 +
 rust/kernel/serdev.rs            | 10 ++--
 rust/kernel/std_vendor.rs        | 87 ++++++++++++++++++++++++++++++++
 rust/kernel/sync/lock.rs         |  5 +-
 5 files changed, 102 insertions(+), 13 deletions(-)
Signature · 1 line
2.43.0
#1 lore raw

PATCH v4 1/4 rust: mem: add DropGuard

Vendor DropGuard from the Rust standard library and re-export it from kernel::mem.

DropGuard runs a FnOnce callback when the guard is dropped and provides dismiss() to take ownership of the wrapped value without running the cleanup callback.

The kernel version removes unstable const-trait machinery from the upstream implementation and adds #[inline] where appropriate.

---
 rust/kernel/mem.rs        |  2 +
 rust/kernel/std_vendor.rs | 87 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 89 insertions(+)
rust/kernel/mem.rs +2 -0
index f2d4cdf87d00..7f8ddd96f907 100644
@@ -4,6 +4,8 @@
 
 use crate::prelude::*;
 
+pub use crate::std_vendor::DropGuard;
+
 /// Transmute between two types.
 ///
 /// Use this instead of [`core::mem::transmute`] when it is known that sizes are identical but this
rust/kernel/std_vendor.rs +87 -0

96 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH 1/4] rust: mem: add DropGuard

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] rust: import does not follow vertical import style --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] rust: import does not follow vertical import style
--

commit 4ef060000d9f83c4c9fca329ddeac4824d4432ca
Author: Mohamed Osama <[email protected]>

rust: mem: add DropGuard

Vendor DropGuard from the Rust standard library and re-export it from kernel::mem.

rust/kernel/std_vendor.rs line 11

Quoted 10 lines
rust/kernel/std_vendor.rs +2 -0
index abbab5050cc50..21a26b4eec71c 100644
@@ -7,6 +7,9 @@
 //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
 //! see <https://github.com/rust-lang/rust/blob/master/COPYRIGHT>.
 
+use core::mem::ManuallyDrop;
+use core::ops::{Deref, DerefMut};

[Severity: Low]
This isn't a bug, but does this import follow the vertical import style?

The kernel coding guidelines specify that when braces are used for importing multiple items from the same module, each item must go on its own line.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

PATCH v4 2/4 rust: block: gen_disk: use DropGuard

In reply to Mohamed Osama

Replace the ScopeGuard instances in the Rust block layer generic disk implementation with DropGuard.

DropGuard provides the same scope-exit cleanup behavior while using the new Rust kernel memory API.

---
 rust/kernel/block/mq/gen_disk.rs | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
rust/kernel/block/mq/gen_disk.rs +6 -5
index fc97dd873974..d9019fbbb361 100644
@@ -10,11 +10,12 @@
     block::mq::{Operations, TagSet},
     error::{self, from_err_ptr, Result},
     fmt::{self, Write},
+    mem::DropGuard,
     prelude::*,
     static_lock_class,
     str::NullTerminatedFormatter,
     sync::Arc,
-    types::{ForeignOwnable, ScopeGuard},
+    types::ForeignOwnable,
 };
 
 /// A builder for [`GenDisk`].
@@ -102,7 +103,7 @@ pub fn build<T: Operations>(
         queue_data: T::QueueData,
     ) -> Result<GenDisk<T>> {
         let data = queue_data.into_foreign();
-        let recover_data = ScopeGuard::new(|| {
+        let recover_data = DropGuard::new((), |_| {
             // SAFETY: T::QueueData was created by the call to `into_foreign()` above
             drop(unsafe { T::QueueData::from_foreign(data) });
         });
@@ -150,7 +151,7 @@ pub fn build<T: Operations>(
         // SAFETY: `gendisk` is a valid pointer as we initialized it above
         unsafe { (*gendisk).fops = &TABLE };
 
-        let cleanup_failure = ScopeGuard::new_with_data((gendisk, data), |(gendisk, data)| {
+        let cleanup_failure = DropGuard::new((gendisk, data), |(gendisk, data)| {
             // SAFETY: `gendisk` came from `__blk_mq_alloc_disk()` above and
             // has not been added to the VFS on this cleanup path.
             unsafe { bindings::put_disk(gendisk) };
@@ -161,7 +162,7 @@ pub fn build<T: Operations>(
 
         // The failure guard now owns both pieces of cleanup; the early guard
         // must not run on this path anymore.
-        recover_data.dismiss();
+        DropGuard::dismiss(recover_data);
 
         let mut writer = NullTerminatedFormatter::new(
             // SAFETY: `gendisk` points to a valid and initialized instance. We
@@ -185,7 +186,7 @@ pub fn build<T: Operations>(
             },
         )?;
 
-        cleanup_failure.dismiss();
+        DropGuard::dismiss(cleanup_failure);
 
         // INVARIANT: `gendisk` was initialized above.
         // INVARIANT: `gendisk` was added to the VFS via `device_add_disk` above.
Signature · 1 line
2.43.0
#4 lore raw

Re: [PATCH 2/4] rust: block: gen_disk: use DropGuard

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines

Replace the ScopeGuard instances in the Rust block layer generic disk implementation with DropGuard.

DropGuard provides the same scope-exit cleanup behavior while using the new Rust kernel memory API.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#5 lore raw

PATCH v4 3/4 rust: serdev: use DropGuard

In reply to Mohamed Osama

Replace the ScopeGuard usage in the serial device bus implementation with DropGuard.

Use DropGuard::dismiss() when ownership of the private data needs to be transferred without running the cleanup callback.

---
 rust/kernel/serdev.rs | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
rust/kernel/serdev.rs +4 -6
index 17ca504b7f8d..dd43b159b461 100644
@@ -13,6 +13,7 @@
         to_result,
         VTABLE_DEFAULT_ERROR, //
     },
+    mem::DropGuard,
     new_mutex,
     of,
     prelude::*,
@@ -21,10 +22,7 @@
         Mutex, //
     },
     time::Jiffies,
-    types::{
-        Opaque,
-        ScopeGuard, //
-    }, //
+    types::Opaque, //
 };
 
 use core::{
@@ -174,7 +172,7 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
             }))?;
             // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
             let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
-            let private_data = ScopeGuard::new_with_data(private_data, |_| {
+            let private_data = DropGuard::new(private_data, |_| {
                 // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
                 drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
             });
@@ -204,7 +202,7 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
             drop(active);
 
             result.map(|()| {
-                private_data.dismiss();
+                DropGuard::dismiss(private_data);
                 0
             })
         })
Signature · 1 line
2.43.0
#6 lore raw

Re: [PATCH 3/4] rust: serdev: use DropGuard

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines

Replace the ScopeGuard usage in the serial device bus implementation with DropGuard.

Use DropGuard::dismiss() when ownership of the private data needs to be transferred without running the cleanup callback.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
maintainer
#7 lore raw

Re: [PATCH 3/4] rust: serdev: use DropGuard

In reply to Mohamed Osama
Quoted 45 lines · Mohamed Osama

Replace the ScopeGuard usage in the serial device bus implementation with DropGuard.

Use DropGuard::dismiss() when ownership of the private data needs to be transferred without running the cleanup callback.

---
 rust/kernel/serdev.rs | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
rust/kernel/serdev.rs +3 -5
index 17ca504b7f8d..dd43b159b461 100644
@@ -13,6 +13,7 @@
         to_result,
         VTABLE_DEFAULT_ERROR, //
     },
+    mem::DropGuard,
     new_mutex,
     of,
     prelude::*,
@@ -21,10 +22,7 @@
         Mutex, //
     },
     time::Jiffies,
-    types::{
-        Opaque,
-        ScopeGuard, //
-    }, //
+    types::Opaque, //
 };
 
 use core::{
@@ -174,7 +172,7 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
             }))?;
             // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
             let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
-            let private_data = ScopeGuard::new_with_data(private_data, |_| {
+            let private_data = DropGuard::new(private_data, |_| {
                 // SAFETY: We just set drvdata to `PrivateData<'_, T>`.
                 drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
             });

rust/kernel/serdev.rs extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi: · line 208

Quoted 8 lines
rust/kernel/serdev.rs +1 -1
@@ -204,7 +202,7 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
             drop(active);
 
             result.map(|()| {
-                private_data.dismiss();
+                DropGuard::dismiss(private_data);
                 0
             })
         })

I am surprised to not find myself on CC. I only look loosly on the linux-serial mailing list, so please add me to CC.

This patch will be redundant once
https://lore.kernel.org/linux-serial/[email protected]/
get merged. Not sure if it gets merged this cycle though.

Also I am not sure on which base this should be applied to? Applying to v7.3-rc6 or next-20261009 fails.

Thanks
- Markus Probst

#8 lore raw

PATCH v4 4/4 rust: sync: lock: use DropGuard

In reply to Mohamed Osama

Replace the ScopeGuard usage in the Rust locking implementation with DropGuard.

The guard preserves the existing scope-exit cleanup behavior while using the DropGuard API from the Rust kernel memory module.

---
 rust/kernel/sync/lock.rs | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
rust/kernel/sync/lock.rs +3 -2
index 10b6b5e9b024..15f9cbe76c8d 100644
@@ -7,8 +7,9 @@
 
 use super::LockClassKey;
 use crate::{
+    mem::DropGuard,
     str::{CStr, CStrExt as _},
-    types::{NotThreadSafe, Opaque, ScopeGuard},
+    types::{NotThreadSafe, Opaque},
 };
 use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
 use pin_init::{pin_data, pin_init, PinInit, Wrapper};
@@ -242,7 +243,7 @@ pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U {
         // SAFETY: The caller owns the lock, so it is safe to unlock it.
         unsafe { B::unlock(self.lock.state.get(), &self.state) };
 
-        let _relock = ScopeGuard::new(||
+        let _relock = DropGuard::new((), |_|
                 // SAFETY: The lock was just unlocked above and is being relocked now.
                 unsafe { B::relock(self.lock.state.get(), &mut self.state) });
 
Signature · 1 line
2.43.0
#9 lore raw

Re: [PATCH 4/4] rust: sync: lock: use DropGuard

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] rust: sync: horizontal import style used in touched import block --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] rust: sync: horizontal import style used in touched import block
--

commit 67d0667c81a937f6d37a9c9023076060bd4316d7
Author: Mohamed Osama <[email protected]>

rust: sync: lock: use DropGuard

Replace the ScopeGuard usage in the Rust locking implementation with DropGuard. The guard preserves the existing scope-exit cleanup behavior while using the DropGuard API from the Rust kernel memory module.

rust/kernel/sync/lock.rs line 12

Quoted 11 lines
rust/kernel/sync/lock.rs +2 -1
@@ -7,8 +7,9 @@
 
 use super::LockClassKey;
 use crate::{
+    mem::DropGuard,
     str::{CStr, CStrExt as _},
-    types::{NotThreadSafe, Opaque, ScopeGuard},
+    types::{NotThreadSafe, Opaque},

[Severity: Low]
This isn't a bug, but since this patch modifies the import block here, shouldn't it be updated to follow the kernel vertical import style?

The modified crate::types import leaves the items grouped horizontally instead of formatting them vertically with one item per line.

Quoted 1 line
rust/kernel/sync/lock.rs +0 -0
 };
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
maintainer Reviewed-by on v4 4/4
#10 lore raw

Re: [PATCH 4/4] rust: sync: lock: use DropGuard

In reply to Mohamed Osama
Quoted 7 lines · Mohamed Osama

Replace the ScopeGuard usage in the Rust locking implementation with DropGuard.

The guard preserves the existing scope-exit cleanup behavior while using the DropGuard API from the Rust kernel memory module.

Regards,
Boqun

Quoted 31 lines
---
 rust/kernel/sync/lock.rs | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
rust/kernel/sync/lock.rs +3 -2
index 10b6b5e9b024..15f9cbe76c8d 100644
@@ -7,8 +7,9 @@
 
 use super::LockClassKey;
 use crate::{
+    mem::DropGuard,
     str::{CStr, CStrExt as _},
-    types::{NotThreadSafe, Opaque, ScopeGuard},
+    types::{NotThreadSafe, Opaque},
 };
 use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
 use pin_init::{pin_data, pin_init, PinInit, Wrapper};
@@ -242,7 +243,7 @@ pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U {
         // SAFETY: The caller owns the lock, so it is safe to unlock it.
         unsafe { B::unlock(self.lock.state.get(), &self.state) };
 
-        let _relock = ScopeGuard::new(||
+        let _relock = DropGuard::new((), |_|
                 // SAFETY: The lock was just unlocked above and is being relocked now.
                 unsafe { B::relock(self.lock.state.get(), &mut self.state) });
 
Signature · 1 line
2.43.0
maintainer
#11 lore raw
In reply to Mohamed Osama
Quoted 6 lines · Mohamed Osama

This series adds the Rust kernel DropGuard API and migrates existing cleanup guards in the block, serdev, and locking code to use it.

DropGuard is vendored from the Rust standard library and re-exported through kernel::mem.

Quoted 6 lines

Changes since v3:
- Vendor DropGuard in rust/kernel/std_vendor.rs and re-export it from kernel::mem, following Gary Guo's review.
- Remove the DropGuard KUnit tests and Kconfig option since the implementation is vendored from the standard library.
- Keep the existing ScopeGuard API unchanged.

Could you allow for at least 24 hours to pass between new versions of your patches?

40 mins. ago [10/10] Mohamed Osama, [email protected], Boqun Feng [PATCH 4/4] rust: sync: lock: use DropGuard (in 🛠️ ur)
Yest. 01:53 [12/12] Mohamed Osama, [email protected], Gary Guo [PATCH v3 2/5] rust: mem: add DropGuard (in 🛠️ ur)

    Sat. 18:46 [11/11] Mohamed Osama, [email protected]    [PATCH v2 2/5] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH v3] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH v2] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH v1] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH] rust: mem: add DropGuard (in 🛠️ ur)

I'm confused about your versioning scheme.

Could you include links to earlier version of the series when you send a new version?

The b4 tool handles most of this for you. I would recommend checking it out [1].

The first v1 has a link to a github issue. Could you please keep including this link? It is helpful for context.

Best regards,
Andreas Hindborg

[1] https://b4.docs.kernel.org/en/latest/contributor/prep.html

maintainer
#12 lore raw
Quoted 35 lines · Andreas Hindborg
Quoted 6 lines · Mohamed Osama

This series adds the Rust kernel DropGuard API and migrates existing cleanup guards in the block, serdev, and locking code to use it.

DropGuard is vendored from the Rust standard library and re-exported through kernel::mem.

Quoted 6 lines

Changes since v3:
- Vendor DropGuard in rust/kernel/std_vendor.rs and re-export it from kernel::mem, following Gary Guo's review.
- Remove the DropGuard KUnit tests and Kconfig option since the implementation is vendored from the standard library.
- Keep the existing ScopeGuard API unchanged.

Could you allow for at least 24 hours to pass between new versions of your patches?

40 mins. ago [10/10] Mohamed Osama, [email protected], Boqun Feng [PATCH 4/4] rust: sync: lock: use DropGuard (in 🛠️ ur)
Yest. 01:53 [12/12] Mohamed Osama, [email protected], Gary Guo [PATCH v3 2/5] rust: mem: add DropGuard (in 🛠️ ur)

    Sat. 18:46 [11/11] Mohamed Osama, [email protected]    [PATCH v2 2/5] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH v3] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH v2] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH v1] rust: mem: add DropGuard (in 🛠️ ur)
  September 16 [2/2]   Mohamed Osama, [email protected]    [PATCH] rust: mem: add DropGuard (in 🛠️ ur)

I'm confused about your versioning scheme.

Could you include links to earlier version of the series when you send a new version?

The b4 tool handles most of this for you. I would recommend checking it out [1].

Quoted 7 lines

The first v1 has a link to a github issue. Could you please keep including this link? It is helpful for context.

Best regards,
Andreas Hindborg

[1] https://b4.docs.kernel.org/en/latest/contributor/prep.html

Also please include the rationale for the change in the cover letter and commit message. Something along the lines of what is in the github issue would be fine.

Best regards,
Andreas Hindborg