Skip to content

Commit 4e3e396

Browse files
Andreas Hindborgfbq
authored andcommitted
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 <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Signed-off-by: Andreas Hindborg <[email protected]> Reviewed-by: Lyude Paul <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent 95ba6ba commit 4e3e396

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
@@ -212,6 +212,39 @@ pub unsafe trait UnsafeHrTimerPointer: Sync + Sized {
212212
unsafe fn start(self, expires: Ktime) -> Self::TimerHandle;
213213
}
214214

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

0 commit comments

Comments
 (0)