[PATCH v3 2/2] rust: task: Add Rust version of might_sleep()

From: Boqun Feng
Date: Mon Jun 16 2025 - 11:36:56 EST


From: FUJITA Tomonori <fujita.tomonori@xxxxxxxxx>

Add a helper function equivalent to the C's might_sleep(), which
serves as a debugging aid and a potential scheduling point.

Note that this function can only be used in a nonatomic context.

This will be used by Rust version of read_poll_timeout().

[boqun: Use file_from_location() to get a C string instead of changing
__might_sleep()]

Signed-off-by: FUJITA Tomonori <fujita.tomonori@xxxxxxxxx>
Reviewed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
Signed-off-by: Boqun Feng <boqun.feng@xxxxxxxxx>
---
rust/helpers/task.c | 6 ++++++
rust/kernel/task.rs | 22 ++++++++++++++++++++++
2 files changed, 28 insertions(+)

diff --git a/rust/helpers/task.c b/rust/helpers/task.c
index 31c33ea2dce6..2c85bbc2727e 100644
--- a/rust/helpers/task.c
+++ b/rust/helpers/task.c
@@ -1,7 +1,13 @@
// SPDX-License-Identifier: GPL-2.0

+#include <linux/kernel.h>
#include <linux/sched/task.h>

+void rust_helper_might_resched(void)
+{
+ might_resched();
+}
+
struct task_struct *rust_helper_get_current(void)
{
return current;
diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs
index 834368313088..518c42beaad1 100644
--- a/rust/kernel/task.rs
+++ b/rust/kernel/task.rs
@@ -400,3 +400,25 @@ fn eq(&self, other: &Kuid) -> bool {
}

impl Eq for Kuid {}
+
+/// Annotation for functions that can sleep.
+///
+/// Equivalent to the C side [`might_sleep()`], this function serves as
+/// a debugging aid and a potential scheduling point.
+///
+/// This function can only be used in a nonatomic context.
+#[track_caller]
+#[inline]
+pub fn might_sleep() {
+ #[cfg(CONFIG_DEBUG_ATOMIC_SLEEP)]
+ {
+ let loc = core::panic::Location::caller();
+ let file = kernel::file_from_location(loc);
+
+ // SAFETY: `file.as_ptr()` is valid for reading and guaranteed to be nul-terminated.
+ unsafe { crate::bindings::__might_sleep(file.as_ptr().cast(), loc.line() as i32) }
+ }
+
+ // SAFETY: Always safe to call.
+ unsafe { crate::bindings::might_resched() }
+}
--
2.39.5 (Apple Git-154)