Skip to content

Commit f93b0d8

Browse files
author
Andreas Hindborg
committed
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>
1 parent a6968ce commit f93b0d8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

rust/kernel/time/hrtimer.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,39 @@ pub unsafe trait UnsafeHrTimerPointer: Sync + Sized {
219219
unsafe fn start(self, expires: Ktime) -> Self::TimerHandle;
220220
}
221221

222+
/// A trait for stack allocated timers.
223+
///
224+
/// # Safety
225+
///
226+
/// Implementers must ensure that `start_scoped` does not return until the
227+
/// timer is dead and the timer handler is not running.
228+
pub unsafe trait ScopedHrTimerPointer {
229+
/// Start the timer to run after `expires` time units and immediately
230+
/// after call `f`. When `f` returns, the timer is cancelled.
231+
fn start_scoped<T, F>(self, expires: Ktime, f: F) -> T
232+
where
233+
F: FnOnce() -> T;
234+
}
235+
236+
// SAFETY: By the safety requirement of [`UnsafeHrTimerPointer`], dropping the
237+
// handle returned by [`UnsafeHrTimerPointer::start`] ensures that the timer is
238+
// killed.
239+
unsafe impl<T> ScopedHrTimerPointer for T
240+
where
241+
T: UnsafeHrTimerPointer,
242+
{
243+
fn start_scoped<U, F>(self, expires: Ktime, f: F) -> U
244+
where
245+
F: FnOnce() -> U,
246+
{
247+
// SAFETY: We drop the timer handle below before returning.
248+
let handle = unsafe { UnsafeHrTimerPointer::start(self, expires) };
249+
let t = f();
250+
drop(handle);
251+
t
252+
}
253+
}
254+
222255
/// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
223256
/// function to call.
224257
// This is split from `HrTimerPointer` to make it easier to specify trait bounds.

0 commit comments

Comments
 (0)