diff options
author | Andreas Hindborg <a.hindborg@kernel.org> | 2025-03-09 16:18:57 +0100 |
---|---|---|
committer | Andreas Hindborg <a.hindborg@kernel.org> | 2025-03-22 12:08:54 +0100 |
commit | f93b0d8360e5e690ca82c3236ba7f7f9d6a6b5e7 (patch) | |
tree | 7aef6a7c6292e514600b5c23e89b6cba903dad29 /rust | |
parent | a6968ce3769660658e5c956987dc9e75b369d4b6 (diff) |
rust: hrtimer: add `hrtimer::ScopedHrTimerPointer`
Add the trait `ScopedHrTimerPointer` to allow safe use of stack allocated
timers. Safety is achieved by pinning the stack in place while timers are
running.
Implement the trait for all types that implement `UnsafeHrTimerPointer`.
Acked-by: Frederic Weisbecker <frederic@kernel.org>
Acked-by: Thomas Gleixner <tglx@linutronix.de>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Lyude Paul <lyude@redhat.com>
Link: https://lore.kernel.org/r/20250309-hrtimer-v3-v6-12-rc2-v12-6-73586e2bd5f1@kernel.org
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Diffstat (limited to 'rust')
-rw-r--r-- | rust/kernel/time/hrtimer.rs | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/rust/kernel/time/hrtimer.rs b/rust/kernel/time/hrtimer.rs index e1b29cd40397..5c35982f9dcb 100644 --- a/rust/kernel/time/hrtimer.rs +++ b/rust/kernel/time/hrtimer.rs @@ -219,6 +219,39 @@ pub unsafe trait UnsafeHrTimerPointer: Sync + Sized { unsafe fn start(self, expires: Ktime) -> Self::TimerHandle; } +/// A trait for stack allocated timers. +/// +/// # Safety +/// +/// Implementers must ensure that `start_scoped` does not return until the +/// timer is dead and the timer handler is not running. +pub unsafe trait ScopedHrTimerPointer { + /// Start the timer to run after `expires` time units and immediately + /// after call `f`. When `f` returns, the timer is cancelled. + fn start_scoped<T, F>(self, expires: Ktime, f: F) -> T + where + F: FnOnce() -> T; +} + +// SAFETY: By the safety requirement of [`UnsafeHrTimerPointer`], dropping the +// handle returned by [`UnsafeHrTimerPointer::start`] ensures that the timer is +// killed. +unsafe impl<T> ScopedHrTimerPointer for T +where + T: UnsafeHrTimerPointer, +{ + fn start_scoped<U, F>(self, expires: Ktime, f: F) -> U + where + F: FnOnce() -> U, + { + // SAFETY: We drop the timer handle below before returning. + let handle = unsafe { UnsafeHrTimerPointer::start(self, expires) }; + let t = f(); + drop(handle); + t + } +} + /// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a /// function to call. // This is split from `HrTimerPointer` to make it easier to specify trait bounds. |