kernel/time/hrtimer.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Intrusive high resolution timers.
4//!
5//! Allows running timer callbacks without doing allocations at the time of
6//! starting the timer. For now, only one timer per type is allowed.
7//!
8//! # Vocabulary
9//!
10//! States:
11//!
12//! - Stopped: initialized but not started, or cancelled, or not restarted.
13//! - Started: initialized and started or restarted.
14//! - Running: executing the callback.
15//!
16//! Operations:
17//!
18//! * Start
19//! * Cancel
20//! * Restart
21//!
22//! Events:
23//!
24//! * Expire
25//!
26//! ## State Diagram
27//!
28//! ```text
29//! Return NoRestart
30//! +---------------------------------------------------------------------+
31//! | |
32//! | |
33//! | |
34//! | Return Restart |
35//! | +------------------------+ |
36//! | | | |
37//! | | | |
38//! v v | |
39//! +-----------------+ Start +------------------+ +--------+-----+--+
40//! | +---------------->| | | |
41//! Init | | | | Expire | |
42//! --------->| Stopped | | Started +---------->| Running |
43//! | | Cancel | | | |
44//! | |<----------------+ | | |
45//! +-----------------+ +---------------+--+ +-----------------+
46//! ^ |
47//! | |
48//! +---------+
49//! Restart
50//! ```
51//!
52//!
53//! A timer is initialized in the **stopped** state. A stopped timer can be
54//! **started** by the `start` operation, with an **expiry** time. After the
55//! `start` operation, the timer is in the **started** state. When the timer
56//! **expires**, the timer enters the **running** state and the handler is
57//! executed. After the handler has returned, the timer may enter the
58//! **started* or **stopped** state, depending on the return value of the
59//! handler. A timer in the **started** or **running** state may be **canceled**
60//! by the `cancel` operation. A timer that is cancelled enters the **stopped**
61//! state.
62//!
63//! A `cancel` or `restart` operation on a timer in the **running** state takes
64//! effect after the handler has returned and the timer has transitioned
65//! out of the **running** state.
66//!
67//! A `restart` operation on a timer in the **stopped** state is equivalent to a
68//! `start` operation.
69//!
70//! When a type implements both `HrTimerPointer` and `Clone`, it is possible to
71//! issue the `start` operation while the timer is in the **started** state. In
72//! this case the `start` operation is equivalent to the `restart` operation.
73//!
74//! # Examples
75//!
76//! ## Using an intrusive timer living in a [`Box`]
77//!
78//! ```
79//! # use kernel::{
80//! # alloc::flags,
81//! # impl_has_hr_timer,
82//! # prelude::*,
83//! # sync::{
84//! # atomic::{ordering, Atomic},
85//! # completion::Completion,
86//! # Arc,
87//! # },
88//! # time::{
89//! # hrtimer::{
90//! # RelativeMode, HrTimer, HrTimerCallback, HrTimerPointer,
91//! # HrTimerRestart, HrTimerCallbackContext
92//! # },
93//! # Delta, Monotonic,
94//! # },
95//! # };
96//!
97//! #[pin_data]
98//! struct Shared {
99//! #[pin]
100//! flag: Atomic<u64>,
101//! #[pin]
102//! cond: Completion,
103//! }
104//!
105//! impl Shared {
106//! fn new() -> impl PinInit<Self> {
107//! pin_init!(Self {
108//! flag <- Atomic::new(0),
109//! cond <- Completion::new(),
110//! })
111//! }
112//! }
113//!
114//! #[pin_data]
115//! struct BoxIntrusiveHrTimer {
116//! #[pin]
117//! timer: HrTimer<Self>,
118//! shared: Arc<Shared>,
119//! }
120//!
121//! impl BoxIntrusiveHrTimer {
122//! fn new() -> impl PinInit<Self, kernel::error::Error> {
123//! try_pin_init!(Self {
124//! timer <- HrTimer::new(),
125//! shared: Arc::pin_init(Shared::new(), flags::GFP_KERNEL)?,
126//! })
127//! }
128//! }
129//!
130//! impl HrTimerCallback for BoxIntrusiveHrTimer {
131//! type Pointer<'a> = Pin<KBox<Self>>;
132//!
133//! fn run(this: Pin<&mut Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart {
134//! pr_info!("Timer called\n");
135//!
136//! let flag = this.shared.flag.fetch_add(1, ordering::Full);
137//! this.shared.cond.complete_all();
138//!
139//! if flag == 4 {
140//! HrTimerRestart::NoRestart
141//! } else {
142//! HrTimerRestart::Restart
143//! }
144//! }
145//! }
146//!
147//! impl_has_hr_timer! {
148//! impl HasHrTimer<Self> for BoxIntrusiveHrTimer {
149//! mode: RelativeMode<Monotonic>, field: self.timer
150//! }
151//! }
152//!
153//! let has_timer = Box::pin_init(BoxIntrusiveHrTimer::new(), GFP_KERNEL)?;
154//! let shared = has_timer.shared.clone();
155//! let _handle = has_timer.start(Delta::from_micros(200));
156//!
157//! while shared.flag.load(ordering::Relaxed) != 5 {
158//! shared.cond.wait_for_completion();
159//! }
160//!
161//! pr_info!("Counted to 5\n");
162//! # Ok::<(), kernel::error::Error>(())
163//! ```
164//!
165//! ## Using an intrusive timer in an [`Arc`]
166//!
167//! ```
168//! # use kernel::{
169//! # alloc::flags,
170//! # impl_has_hr_timer,
171//! # prelude::*,
172//! # sync::{
173//! # atomic::{ordering, Atomic},
174//! # completion::Completion,
175//! # Arc, ArcBorrow,
176//! # },
177//! # time::{
178//! # hrtimer::{
179//! # RelativeMode, HrTimer, HrTimerCallback, HrTimerPointer, HrTimerRestart,
180//! # HasHrTimer, HrTimerCallbackContext
181//! # },
182//! # Delta, Monotonic,
183//! # },
184//! # };
185//!
186//! #[pin_data]
187//! struct ArcIntrusiveHrTimer {
188//! #[pin]
189//! timer: HrTimer<Self>,
190//! #[pin]
191//! flag: Atomic<u64>,
192//! #[pin]
193//! cond: Completion,
194//! }
195//!
196//! impl ArcIntrusiveHrTimer {
197//! fn new() -> impl PinInit<Self> {
198//! pin_init!(Self {
199//! timer <- HrTimer::new(),
200//! flag <- Atomic::new(0),
201//! cond <- Completion::new(),
202//! })
203//! }
204//! }
205//!
206//! impl HrTimerCallback for ArcIntrusiveHrTimer {
207//! type Pointer<'a> = Arc<Self>;
208//!
209//! fn run(
210//! this: ArcBorrow<'_, Self>,
211//! _ctx: HrTimerCallbackContext<'_, Self>,
212//! ) -> HrTimerRestart {
213//! pr_info!("Timer called\n");
214//!
215//! let flag = this.flag.fetch_add(1, ordering::Full);
216//! this.cond.complete_all();
217//!
218//! if flag == 4 {
219//! HrTimerRestart::NoRestart
220//! } else {
221//! HrTimerRestart::Restart
222//! }
223//! }
224//! }
225//!
226//! impl_has_hr_timer! {
227//! impl HasHrTimer<Self> for ArcIntrusiveHrTimer {
228//! mode: RelativeMode<Monotonic>, field: self.timer
229//! }
230//! }
231//!
232//! let has_timer = Arc::pin_init(ArcIntrusiveHrTimer::new(), GFP_KERNEL)?;
233//! let _handle = has_timer.clone().start(Delta::from_micros(200));
234//!
235//! while has_timer.flag.load(ordering::Relaxed) != 5 {
236//! has_timer.cond.wait_for_completion();
237//! }
238//!
239//! pr_info!("Counted to 5\n");
240//! # Ok::<(), kernel::error::Error>(())
241//! ```
242//!
243//! ## Using a stack-based timer
244//!
245//! ```
246//! # use kernel::{
247//! # impl_has_hr_timer,
248//! # prelude::*,
249//! # sync::{
250//! # atomic::{ordering, Atomic},
251//! # completion::Completion,
252//! # },
253//! # time::{
254//! # hrtimer::{
255//! # ScopedHrTimerPointer, HrTimer, HrTimerCallback, HrTimerPointer, HrTimerRestart,
256//! # HasHrTimer, RelativeMode, HrTimerCallbackContext
257//! # },
258//! # Delta, Monotonic,
259//! # },
260//! # };
261//! # use pin_init::stack_pin_init;
262//!
263//! #[pin_data]
264//! struct IntrusiveHrTimer {
265//! #[pin]
266//! timer: HrTimer<Self>,
267//! #[pin]
268//! flag: Atomic<u64>,
269//! #[pin]
270//! cond: Completion,
271//! }
272//!
273//! impl IntrusiveHrTimer {
274//! fn new() -> impl PinInit<Self> {
275//! pin_init!(Self {
276//! timer <- HrTimer::new(),
277//! flag <- Atomic::new(0),
278//! cond <- Completion::new(),
279//! })
280//! }
281//! }
282//!
283//! impl HrTimerCallback for IntrusiveHrTimer {
284//! type Pointer<'a> = Pin<&'a Self>;
285//!
286//! fn run(this: Pin<&Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart {
287//! pr_info!("Timer called\n");
288//!
289//! this.flag.store(1, ordering::Release);
290//! this.cond.complete_all();
291//!
292//! HrTimerRestart::NoRestart
293//! }
294//! }
295//!
296//! impl_has_hr_timer! {
297//! impl HasHrTimer<Self> for IntrusiveHrTimer {
298//! mode: RelativeMode<Monotonic>, field: self.timer
299//! }
300//! }
301//!
302//! stack_pin_init!( let has_timer = IntrusiveHrTimer::new() );
303//! has_timer.as_ref().start_scoped(Delta::from_micros(200), || {
304//! while has_timer.flag.load(ordering::Relaxed) != 1 {
305//! has_timer.cond.wait_for_completion();
306//! }
307//! });
308//!
309//! pr_info!("Flag raised\n");
310//! # Ok::<(), kernel::error::Error>(())
311//! ```
312//!
313//! ## Using a mutable stack-based timer
314//!
315//! ```
316//! # use kernel::{
317//! # alloc::flags,
318//! # impl_has_hr_timer,
319//! # prelude::*,
320//! # sync::{
321//! # atomic::{ordering, Atomic},
322//! # completion::Completion,
323//! # Arc,
324//! # },
325//! # time::{
326//! # hrtimer::{
327//! # ScopedHrTimerPointer, HrTimer, HrTimerCallback, HrTimerPointer, HrTimerRestart,
328//! # HasHrTimer, RelativeMode, HrTimerCallbackContext
329//! # },
330//! # Delta, Monotonic,
331//! # },
332//! # };
333//! # use pin_init::stack_try_pin_init;
334//!
335//! #[pin_data]
336//! struct Shared {
337//! #[pin]
338//! flag: Atomic<u64>,
339//! #[pin]
340//! cond: Completion,
341//! }
342//!
343//! impl Shared {
344//! fn new() -> impl PinInit<Self> {
345//! pin_init!(Self {
346//! flag <- Atomic::new(0),
347//! cond <- Completion::new(),
348//! })
349//! }
350//! }
351//!
352//! #[pin_data]
353//! struct IntrusiveHrTimer {
354//! #[pin]
355//! timer: HrTimer<Self>,
356//! shared: Arc<Shared>,
357//! }
358//!
359//! impl IntrusiveHrTimer {
360//! fn new() -> impl PinInit<Self, kernel::error::Error> {
361//! try_pin_init!(Self {
362//! timer <- HrTimer::new(),
363//! shared: Arc::pin_init(Shared::new(), flags::GFP_KERNEL)?,
364//! })
365//! }
366//! }
367//!
368//! impl HrTimerCallback for IntrusiveHrTimer {
369//! type Pointer<'a> = Pin<&'a mut Self>;
370//!
371//! fn run(this: Pin<&mut Self>, _ctx: HrTimerCallbackContext<'_, Self>) -> HrTimerRestart {
372//! pr_info!("Timer called\n");
373//!
374//! let flag = this.shared.flag.fetch_add(1, ordering::Full);
375//! this.shared.cond.complete_all();
376//!
377//! if flag == 4 {
378//! HrTimerRestart::NoRestart
379//! } else {
380//! HrTimerRestart::Restart
381//! }
382//! }
383//! }
384//!
385//! impl_has_hr_timer! {
386//! impl HasHrTimer<Self> for IntrusiveHrTimer {
387//! mode: RelativeMode<Monotonic>, field: self.timer
388//! }
389//! }
390//!
391//! stack_try_pin_init!( let has_timer =? IntrusiveHrTimer::new() );
392//! let shared = has_timer.shared.clone();
393//!
394//! has_timer.as_mut().start_scoped(Delta::from_micros(200), || {
395//! while shared.flag.load(ordering::Relaxed) != 5 {
396//! shared.cond.wait_for_completion();
397//! }
398//! });
399//!
400//! pr_info!("Counted to 5\n");
401//! # Ok::<(), kernel::error::Error>(())
402//! ```
403//!
404//! [`Arc`]: kernel::sync::Arc
405// Implementation details
406//
407// The reasoning for adopting a handle based approach:
408// - If we explicitly drop the target of a timer callback in the timer callback, we
409// may get a dangling reference.
410// - If the callback owns the last reference to the target, target may be dropped
411// in non-sleepable context when the callback is finished.
412// - When dropping an object that is the target of an armed timer, we may drop
413// fields accessed by the timer callback before we cancel the timer (drop order).
414//
415// By using a handle, we can make the handle own the callback target and avoid these problems.
416
417use super::{ClockId, Delta, Instant};
418use crate::{prelude::*, types::Opaque};
419use core::{marker::PhantomData, ptr::NonNull};
420use pin_init::PinInit;
421
422/// A type-alias to refer to the [`Instant<C>`] for a given `T` from [`HrTimer<T>`].
423///
424/// Where `C` is the [`ClockId`] of the [`HrTimer`].
425pub type HrTimerInstant<T> = Instant<<<T as HasHrTimer<T>>::TimerMode as HrTimerMode>::Clock>;
426
427/// A timer backed by a C `struct hrtimer`.
428///
429/// # Invariants
430///
431/// * `self.timer` is initialized by `bindings::hrtimer_setup`.
432#[pin_data]
433#[repr(C)]
434pub struct HrTimer<T> {
435 #[pin]
436 timer: Opaque<bindings::hrtimer>,
437 _t: PhantomData<T>,
438}
439
440// SAFETY: Ownership of an `HrTimer` can be moved to other threads and
441// used/dropped from there.
442unsafe impl<T> Send for HrTimer<T> {}
443
444// SAFETY: Timer operations are locked on the C side, so it is safe to operate
445// on a timer from multiple threads.
446unsafe impl<T> Sync for HrTimer<T> {}
447
448impl<T> HrTimer<T> {
449 /// Return an initializer for a new timer instance.
450 pub fn new() -> impl PinInit<Self>
451 where
452 T: HrTimerCallback,
453 T: HasHrTimer<T>,
454 {
455 pin_init!(Self {
456 // INVARIANT: We initialize `timer` with `hrtimer_setup` below.
457 timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
458 // SAFETY: By design of `pin_init!`, `place` is a pointer to a
459 // live allocation. hrtimer_setup will initialize `place` and
460 // does not require `place` to be initialized prior to the call.
461 unsafe {
462 bindings::hrtimer_setup(
463 place,
464 Some(T::Pointer::run),
465 <<T as HasHrTimer<T>>::TimerMode as HrTimerMode>::Clock::ID,
466 <T as HasHrTimer<T>>::TimerMode::C_MODE,
467 );
468 }
469 }),
470 _t: PhantomData,
471 })
472 }
473
474 /// Get a pointer to the contained `bindings::hrtimer`.
475 ///
476 /// This function is useful to get access to the value without creating
477 /// intermediate references.
478 ///
479 /// # Safety
480 ///
481 /// `this` must point to a live allocation of at least the size of `Self`.
482 unsafe fn raw_get(this: *const Self) -> *mut bindings::hrtimer {
483 // SAFETY: The field projection to `timer` does not go out of bounds,
484 // because the caller of this function promises that `this` points to an
485 // allocation of at least the size of `Self`.
486 unsafe { Opaque::cast_into(core::ptr::addr_of!((*this).timer)) }
487 }
488
489 /// Cancel an initialized and potentially running timer.
490 ///
491 /// If the timer handler is running, this function will block until the
492 /// handler returns.
493 ///
494 /// Note that the timer might be started by a concurrent start operation. If
495 /// so, the timer might not be in the **stopped** state when this function
496 /// returns.
497 ///
498 /// Users of the `HrTimer` API would not usually call this method directly.
499 /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
500 /// returned when the timer was started.
501 ///
502 /// This function is useful to get access to the value without creating
503 /// intermediate references.
504 ///
505 /// # Safety
506 ///
507 /// `this` must point to a valid `Self`.
508 pub(crate) unsafe fn raw_cancel(this: *const Self) -> bool {
509 // SAFETY: `this` points to an allocation of at least `HrTimer` size.
510 let c_timer_ptr = unsafe { HrTimer::raw_get(this) };
511
512 // If the handler is running, this will wait for the handler to return
513 // before returning.
514 // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
515 // handled on the C side.
516 unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
517 }
518
519 /// Forward the timer expiry for a given timer pointer.
520 ///
521 /// # Safety
522 ///
523 /// - `self_ptr` must point to a valid `Self`.
524 /// - The caller must either have exclusive access to the data pointed at by `self_ptr`, or be
525 /// within the context of the timer callback.
526 #[inline]
527 unsafe fn raw_forward(self_ptr: *mut Self, now: HrTimerInstant<T>, interval: Delta) -> u64
528 where
529 T: HasHrTimer<T>,
530 {
531 // SAFETY:
532 // * The C API requirements for this function are fulfilled by our safety contract.
533 // * `self_ptr` is guaranteed to point to a valid `Self` via our safety contract
534 unsafe {
535 bindings::hrtimer_forward(Self::raw_get(self_ptr), now.as_nanos(), interval.as_nanos())
536 }
537 }
538
539 /// Conditionally forward the timer.
540 ///
541 /// If the timer expires after `now`, this function does nothing and returns 0. If the timer
542 /// expired at or before `now`, this function forwards the timer by `interval` until the timer
543 /// expires after `now` and then returns the number of times the timer was forwarded by
544 /// `interval`.
545 ///
546 /// This function is mainly useful for timer types which can provide exclusive access to the
547 /// timer when the timer is not running. For forwarding the timer from within the timer callback
548 /// context, see [`HrTimerCallbackContext::forward()`].
549 ///
550 /// Returns the number of overruns that occurred as a result of the timer expiry change.
551 pub fn forward(self: Pin<&mut Self>, now: HrTimerInstant<T>, interval: Delta) -> u64
552 where
553 T: HasHrTimer<T>,
554 {
555 // SAFETY: `raw_forward` does not move `Self`
556 let this = unsafe { self.get_unchecked_mut() };
557
558 // SAFETY: By existence of `Pin<&mut Self>`, the pointer passed to `raw_forward` points to a
559 // valid `Self` that we have exclusive access to.
560 unsafe { Self::raw_forward(this, now, interval) }
561 }
562
563 /// Conditionally forward the timer.
564 ///
565 /// This is a variant of [`forward()`](Self::forward) that uses an interval after the current
566 /// time of the base clock for the [`HrTimer`].
567 pub fn forward_now(self: Pin<&mut Self>, interval: Delta) -> u64
568 where
569 T: HasHrTimer<T>,
570 {
571 self.forward(HrTimerInstant::<T>::now(), interval)
572 }
573
574 /// Return the time expiry for this [`HrTimer`].
575 ///
576 /// This value should only be used as a snapshot, as the actual expiry time could change after
577 /// this function is called.
578 pub fn expires(&self) -> HrTimerInstant<T>
579 where
580 T: HasHrTimer<T>,
581 {
582 // SAFETY: `self` is an immutable reference and thus always points to a valid `HrTimer`.
583 let c_timer_ptr = unsafe { HrTimer::raw_get(self) };
584
585 // SAFETY:
586 // - Timers cannot have negative ktime_t values as their expiration time.
587 // - There's no actual locking here, a racy read is fine and expected
588 unsafe {
589 Instant::from_ktime(
590 // This `read_volatile` is intended to correspond to a READ_ONCE call.
591 // FIXME(read_once): Replace with `read_once` when available on the Rust side.
592 core::ptr::read_volatile(&raw const ((*c_timer_ptr).node.expires)),
593 )
594 }
595 }
596}
597
598/// Implemented by pointer types that point to structs that contain a [`HrTimer`].
599///
600/// `Self` must be [`Sync`] because it is passed to timer callbacks in another
601/// thread of execution (hard or soft interrupt context).
602///
603/// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
604/// the timer. Note that it is OK to call the start function repeatedly, and
605/// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
606/// exist. A timer can be manipulated through any of the handles, and a handle
607/// may represent a cancelled timer.
608pub trait HrTimerPointer: Sync + Sized {
609 /// The operational mode associated with this timer.
610 ///
611 /// This defines how the expiration value is interpreted.
612 type TimerMode: HrTimerMode;
613
614 /// A handle representing a started or restarted timer.
615 ///
616 /// If the timer is running or if the timer callback is executing when the
617 /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
618 /// until the timer is stopped and the callback has completed.
619 ///
620 /// Note: When implementing this trait, consider that it is not unsafe to
621 /// leak the handle.
622 type TimerHandle: HrTimerHandle;
623
624 /// Start the timer with expiry after `expires` time units. If the timer was
625 /// already running, it is restarted with the new expiry time.
626 fn start(self, expires: <Self::TimerMode as HrTimerMode>::Expires) -> Self::TimerHandle;
627}
628
629/// Unsafe version of [`HrTimerPointer`] for situations where leaking the
630/// [`HrTimerHandle`] returned by `start` would be unsound. This is the case for
631/// stack allocated timers.
632///
633/// Typical implementers are pinned references such as [`Pin<&T>`].
634///
635/// # Safety
636///
637/// Implementers of this trait must ensure that instances of types implementing
638/// [`UnsafeHrTimerPointer`] outlives any associated [`HrTimerPointer::TimerHandle`]
639/// instances.
640pub unsafe trait UnsafeHrTimerPointer: Sync + Sized {
641 /// The operational mode associated with this timer.
642 ///
643 /// This defines how the expiration value is interpreted.
644 type TimerMode: HrTimerMode;
645
646 /// A handle representing a running timer.
647 ///
648 /// # Safety
649 ///
650 /// If the timer is running, or if the timer callback is executing when the
651 /// handle is dropped, the drop method of [`Self::TimerHandle`] must not return
652 /// until the timer is stopped and the callback has completed.
653 type TimerHandle: HrTimerHandle;
654
655 /// Start the timer after `expires` time units. If the timer was already
656 /// running, it is restarted at the new expiry time.
657 ///
658 /// # Safety
659 ///
660 /// Caller promises keep the timer structure alive until the timer is dead.
661 /// Caller can ensure this by not leaking the returned [`Self::TimerHandle`].
662 unsafe fn start(self, expires: <Self::TimerMode as HrTimerMode>::Expires) -> Self::TimerHandle;
663}
664
665/// A trait for stack allocated timers.
666///
667/// # Safety
668///
669/// Implementers must ensure that `start_scoped` does not return until the
670/// timer is dead and the timer handler is not running.
671pub unsafe trait ScopedHrTimerPointer {
672 /// The operational mode associated with this timer.
673 ///
674 /// This defines how the expiration value is interpreted.
675 type TimerMode: HrTimerMode;
676
677 /// Start the timer to run after `expires` time units and immediately
678 /// after call `f`. When `f` returns, the timer is cancelled.
679 fn start_scoped<T, F>(self, expires: <Self::TimerMode as HrTimerMode>::Expires, f: F) -> T
680 where
681 F: FnOnce() -> T;
682}
683
684// SAFETY: By the safety requirement of [`UnsafeHrTimerPointer`], dropping the
685// handle returned by [`UnsafeHrTimerPointer::start`] ensures that the timer is
686// killed.
687unsafe impl<T> ScopedHrTimerPointer for T
688where
689 T: UnsafeHrTimerPointer,
690{
691 type TimerMode = T::TimerMode;
692
693 fn start_scoped<U, F>(
694 self,
695 expires: <<T as UnsafeHrTimerPointer>::TimerMode as HrTimerMode>::Expires,
696 f: F,
697 ) -> U
698 where
699 F: FnOnce() -> U,
700 {
701 // SAFETY: We drop the timer handle below before returning.
702 let handle = unsafe { UnsafeHrTimerPointer::start(self, expires) };
703 let t = f();
704 drop(handle);
705 t
706 }
707}
708
709/// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
710/// function to call.
711// This is split from `HrTimerPointer` to make it easier to specify trait bounds.
712pub trait RawHrTimerCallback {
713 /// Type of the parameter passed to [`HrTimerCallback::run`]. It may be
714 /// [`Self`], or a pointer type derived from [`Self`].
715 type CallbackTarget<'a>;
716
717 /// Callback to be called from C when timer fires.
718 ///
719 /// # Safety
720 ///
721 /// Only to be called by C code in the `hrtimer` subsystem. `this` must point
722 /// to the `bindings::hrtimer` structure that was used to start the timer.
723 unsafe extern "C" fn run(this: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
724}
725
726/// Implemented by structs that can be the target of a timer callback.
727pub trait HrTimerCallback {
728 /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
729 /// the timer expires.
730 type Pointer<'a>: RawHrTimerCallback;
731
732 /// Called by the timer logic when the timer fires.
733 fn run(
734 this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>,
735 ctx: HrTimerCallbackContext<'_, Self>,
736 ) -> HrTimerRestart
737 where
738 Self: Sized,
739 Self: HasHrTimer<Self>;
740}
741
742/// A handle representing a potentially running timer.
743///
744/// More than one handle representing the same timer might exist.
745///
746/// # Safety
747///
748/// When dropped, the timer represented by this handle must be cancelled, if it
749/// is running. If the timer handler is running when the handle is dropped, the
750/// drop method must wait for the handler to return before returning.
751///
752/// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
753/// the drop implementation for `Self.`
754pub unsafe trait HrTimerHandle {
755 /// Cancel the timer. If the timer is in the running state, block till the
756 /// handler has returned.
757 ///
758 /// Note that the timer might be started by a concurrent start operation. If
759 /// so, the timer might not be in the **stopped** state when this function
760 /// returns.
761 ///
762 /// Returns `true` if the timer was running.
763 fn cancel(&mut self) -> bool;
764}
765
766/// Implemented by structs that contain timer nodes.
767///
768/// Clients of the timer API would usually safely implement this trait by using
769/// the [`crate::impl_has_hr_timer`] macro.
770///
771/// # Safety
772///
773/// Implementers of this trait must ensure that the implementer has a
774/// [`HrTimer`] field and that all trait methods are implemented according to
775/// their documentation. All the methods of this trait must operate on the same
776/// field.
777pub unsafe trait HasHrTimer<T> {
778 /// The operational mode associated with this timer.
779 ///
780 /// This defines how the expiration value is interpreted.
781 type TimerMode: HrTimerMode;
782
783 /// Return a pointer to the [`HrTimer`] within `Self`.
784 ///
785 /// This function is useful to get access to the value without creating
786 /// intermediate references.
787 ///
788 /// # Safety
789 ///
790 /// `this` must be a valid pointer.
791 unsafe fn raw_get_timer(this: *const Self) -> *const HrTimer<T>;
792
793 /// Return a pointer to the struct that is containing the [`HrTimer`] pointed
794 /// to by `ptr`.
795 ///
796 /// This function is useful to get access to the value without creating
797 /// intermediate references.
798 ///
799 /// # Safety
800 ///
801 /// `ptr` must point to a [`HrTimer<T>`] field in a struct of type `Self`.
802 unsafe fn timer_container_of(ptr: *mut HrTimer<T>) -> *mut Self
803 where
804 Self: Sized;
805
806 /// Get pointer to the contained `bindings::hrtimer` struct.
807 ///
808 /// This function is useful to get access to the value without creating
809 /// intermediate references.
810 ///
811 /// # Safety
812 ///
813 /// `this` must be a valid pointer.
814 unsafe fn c_timer_ptr(this: *const Self) -> *const bindings::hrtimer {
815 // SAFETY: `this` is a valid pointer to a `Self`.
816 let timer_ptr = unsafe { Self::raw_get_timer(this) };
817
818 // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
819 unsafe { HrTimer::raw_get(timer_ptr) }
820 }
821
822 /// Start the timer contained in the `Self` pointed to by `self_ptr`. If
823 /// it is already running it is removed and inserted.
824 ///
825 /// # Safety
826 ///
827 /// - `this` must point to a valid `Self`.
828 /// - Caller must ensure that the pointee of `this` lives until the timer
829 /// fires or is canceled.
830 unsafe fn start(this: *const Self, expires: <Self::TimerMode as HrTimerMode>::Expires) {
831 // SAFETY: By function safety requirement, `this` is a valid `Self`.
832 unsafe {
833 bindings::hrtimer_start_range_ns(
834 Self::c_timer_ptr(this).cast_mut(),
835 expires.as_nanos(),
836 0,
837 <Self::TimerMode as HrTimerMode>::C_MODE,
838 );
839 }
840 }
841}
842
843/// Restart policy for timers.
844#[derive(Copy, Clone, PartialEq, Eq, Debug)]
845#[repr(u32)]
846pub enum HrTimerRestart {
847 /// Timer should not be restarted.
848 NoRestart = bindings::hrtimer_restart_HRTIMER_NORESTART,
849 /// Timer should be restarted.
850 Restart = bindings::hrtimer_restart_HRTIMER_RESTART,
851}
852
853impl HrTimerRestart {
854 fn into_c(self) -> bindings::hrtimer_restart {
855 self as bindings::hrtimer_restart
856 }
857}
858
859/// Time representations that can be used as expiration values in [`HrTimer`].
860pub trait HrTimerExpires {
861 /// Converts the expiration time into a nanosecond representation.
862 ///
863 /// This value corresponds to a raw ktime_t value, suitable for passing to kernel
864 /// timer functions. The interpretation (absolute vs relative) depends on the
865 /// associated [HrTimerMode] in use.
866 fn as_nanos(&self) -> i64;
867}
868
869impl<C: ClockId> HrTimerExpires for Instant<C> {
870 #[inline]
871 fn as_nanos(&self) -> i64 {
872 Instant::<C>::as_nanos(self)
873 }
874}
875
876impl HrTimerExpires for Delta {
877 #[inline]
878 fn as_nanos(&self) -> i64 {
879 Delta::as_nanos(*self)
880 }
881}
882
883mod private {
884 use crate::time::ClockId;
885
886 pub trait Sealed {}
887
888 impl<C: ClockId> Sealed for super::AbsoluteMode<C> {}
889 impl<C: ClockId> Sealed for super::RelativeMode<C> {}
890 impl<C: ClockId> Sealed for super::AbsolutePinnedMode<C> {}
891 impl<C: ClockId> Sealed for super::RelativePinnedMode<C> {}
892 impl<C: ClockId> Sealed for super::AbsoluteSoftMode<C> {}
893 impl<C: ClockId> Sealed for super::RelativeSoftMode<C> {}
894 impl<C: ClockId> Sealed for super::AbsolutePinnedSoftMode<C> {}
895 impl<C: ClockId> Sealed for super::RelativePinnedSoftMode<C> {}
896 impl<C: ClockId> Sealed for super::AbsoluteHardMode<C> {}
897 impl<C: ClockId> Sealed for super::RelativeHardMode<C> {}
898 impl<C: ClockId> Sealed for super::AbsolutePinnedHardMode<C> {}
899 impl<C: ClockId> Sealed for super::RelativePinnedHardMode<C> {}
900}
901
902/// Operational mode of [`HrTimer`].
903pub trait HrTimerMode: private::Sealed {
904 /// The C representation of hrtimer mode.
905 const C_MODE: bindings::hrtimer_mode;
906
907 /// Type representing the clock source.
908 type Clock: ClockId;
909
910 /// Type representing the expiration specification (absolute or relative time).
911 type Expires: HrTimerExpires;
912}
913
914/// Timer that expires at a fixed point in time.
915pub struct AbsoluteMode<C: ClockId>(PhantomData<C>);
916
917impl<C: ClockId> HrTimerMode for AbsoluteMode<C> {
918 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS;
919
920 type Clock = C;
921 type Expires = Instant<C>;
922}
923
924/// Timer that expires after a delay from now.
925pub struct RelativeMode<C: ClockId>(PhantomData<C>);
926
927impl<C: ClockId> HrTimerMode for RelativeMode<C> {
928 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL;
929
930 type Clock = C;
931 type Expires = Delta;
932}
933
934/// Timer with absolute expiration time, pinned to its current CPU.
935pub struct AbsolutePinnedMode<C: ClockId>(PhantomData<C>);
936impl<C: ClockId> HrTimerMode for AbsolutePinnedMode<C> {
937 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_PINNED;
938
939 type Clock = C;
940 type Expires = Instant<C>;
941}
942
943/// Timer with relative expiration time, pinned to its current CPU.
944pub struct RelativePinnedMode<C: ClockId>(PhantomData<C>);
945impl<C: ClockId> HrTimerMode for RelativePinnedMode<C> {
946 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_PINNED;
947
948 type Clock = C;
949 type Expires = Delta;
950}
951
952/// Timer with absolute expiration, handled in soft irq context.
953pub struct AbsoluteSoftMode<C: ClockId>(PhantomData<C>);
954impl<C: ClockId> HrTimerMode for AbsoluteSoftMode<C> {
955 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_SOFT;
956
957 type Clock = C;
958 type Expires = Instant<C>;
959}
960
961/// Timer with relative expiration, handled in soft irq context.
962pub struct RelativeSoftMode<C: ClockId>(PhantomData<C>);
963impl<C: ClockId> HrTimerMode for RelativeSoftMode<C> {
964 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_SOFT;
965
966 type Clock = C;
967 type Expires = Delta;
968}
969
970/// Timer with absolute expiration, pinned to CPU and handled in soft irq context.
971pub struct AbsolutePinnedSoftMode<C: ClockId>(PhantomData<C>);
972impl<C: ClockId> HrTimerMode for AbsolutePinnedSoftMode<C> {
973 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_PINNED_SOFT;
974
975 type Clock = C;
976 type Expires = Instant<C>;
977}
978
979/// Timer with absolute expiration, pinned to CPU and handled in soft irq context.
980pub struct RelativePinnedSoftMode<C: ClockId>(PhantomData<C>);
981impl<C: ClockId> HrTimerMode for RelativePinnedSoftMode<C> {
982 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_PINNED_SOFT;
983
984 type Clock = C;
985 type Expires = Delta;
986}
987
988/// Timer with absolute expiration, handled in hard irq context.
989pub struct AbsoluteHardMode<C: ClockId>(PhantomData<C>);
990impl<C: ClockId> HrTimerMode for AbsoluteHardMode<C> {
991 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_HARD;
992
993 type Clock = C;
994 type Expires = Instant<C>;
995}
996
997/// Timer with relative expiration, handled in hard irq context.
998pub struct RelativeHardMode<C: ClockId>(PhantomData<C>);
999impl<C: ClockId> HrTimerMode for RelativeHardMode<C> {
1000 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_HARD;
1001
1002 type Clock = C;
1003 type Expires = Delta;
1004}
1005
1006/// Timer with absolute expiration, pinned to CPU and handled in hard irq context.
1007pub struct AbsolutePinnedHardMode<C: ClockId>(PhantomData<C>);
1008impl<C: ClockId> HrTimerMode for AbsolutePinnedHardMode<C> {
1009 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_PINNED_HARD;
1010
1011 type Clock = C;
1012 type Expires = Instant<C>;
1013}
1014
1015/// Timer with relative expiration, pinned to CPU and handled in hard irq context.
1016pub struct RelativePinnedHardMode<C: ClockId>(PhantomData<C>);
1017impl<C: ClockId> HrTimerMode for RelativePinnedHardMode<C> {
1018 const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_PINNED_HARD;
1019
1020 type Clock = C;
1021 type Expires = Delta;
1022}
1023
1024/// Privileged smart-pointer for a [`HrTimer`] callback context.
1025///
1026/// Many [`HrTimer`] methods can only be called in two situations:
1027///
1028/// * When the caller has exclusive access to the `HrTimer` and the `HrTimer` is guaranteed not to
1029/// be running.
1030/// * From within the context of an `HrTimer`'s callback method.
1031///
1032/// This type provides access to said methods from within a timer callback context.
1033///
1034/// # Invariants
1035///
1036/// * The existence of this type means the caller is currently within the callback for an
1037/// [`HrTimer`].
1038/// * `self.0` always points to a live instance of [`HrTimer<T>`].
1039pub struct HrTimerCallbackContext<'a, T: HasHrTimer<T>>(NonNull<HrTimer<T>>, PhantomData<&'a ()>);
1040
1041impl<'a, T: HasHrTimer<T>> HrTimerCallbackContext<'a, T> {
1042 /// Create a new [`HrTimerCallbackContext`].
1043 ///
1044 /// # Safety
1045 ///
1046 /// This function relies on the caller being within the context of a timer callback, so it must
1047 /// not be used anywhere except for within implementations of [`RawHrTimerCallback::run`]. The
1048 /// caller promises that `timer` points to a valid initialized instance of
1049 /// [`bindings::hrtimer`].
1050 ///
1051 /// The returned `Self` must not outlive the function context of [`RawHrTimerCallback::run`]
1052 /// where this function is called.
1053 pub(crate) unsafe fn from_raw(timer: *mut HrTimer<T>) -> Self {
1054 // SAFETY: The caller guarantees `timer` is a valid pointer to an initialized
1055 // `bindings::hrtimer`
1056 // INVARIANT: Our safety contract ensures that we're within the context of a timer callback
1057 // and that `timer` points to a live instance of `HrTimer<T>`.
1058 Self(unsafe { NonNull::new_unchecked(timer) }, PhantomData)
1059 }
1060
1061 /// Conditionally forward the timer.
1062 ///
1063 /// This function is identical to [`HrTimer::forward()`] except that it may only be used from
1064 /// within the context of a [`HrTimer`] callback.
1065 pub fn forward(&mut self, now: HrTimerInstant<T>, interval: Delta) -> u64 {
1066 // SAFETY:
1067 // - We are guaranteed to be within the context of a timer callback by our type invariants
1068 // - By our type invariants, `self.0` always points to a valid `HrTimer<T>`
1069 unsafe { HrTimer::<T>::raw_forward(self.0.as_ptr(), now, interval) }
1070 }
1071
1072 /// Conditionally forward the timer.
1073 ///
1074 /// This is a variant of [`HrTimerCallbackContext::forward()`] that uses an interval after the
1075 /// current time of the base clock for the [`HrTimer`].
1076 pub fn forward_now(&mut self, duration: Delta) -> u64 {
1077 self.forward(HrTimerInstant::<T>::now(), duration)
1078 }
1079}
1080
1081/// Use to implement the [`HasHrTimer<T>`] trait.
1082///
1083/// See [`module`] documentation for an example.
1084///
1085/// [`module`]: crate::time::hrtimer
1086#[macro_export]
1087macro_rules! impl_has_hr_timer {
1088 (
1089 impl$({$($generics:tt)*})?
1090 HasHrTimer<$timer_type:ty>
1091 for $self:ty
1092 {
1093 mode : $mode:ty,
1094 field : self.$field:ident $(,)?
1095 }
1096 $($rest:tt)*
1097 ) => {
1098 // SAFETY: This implementation of `raw_get_timer` only compiles if the
1099 // field has the right type.
1100 unsafe impl$(<$($generics)*>)? $crate::time::hrtimer::HasHrTimer<$timer_type> for $self {
1101 type TimerMode = $mode;
1102
1103 #[inline]
1104 unsafe fn raw_get_timer(
1105 this: *const Self,
1106 ) -> *const $crate::time::hrtimer::HrTimer<$timer_type> {
1107 // SAFETY: The caller promises that the pointer is not dangling.
1108 unsafe { ::core::ptr::addr_of!((*this).$field) }
1109 }
1110
1111 #[inline]
1112 unsafe fn timer_container_of(
1113 ptr: *mut $crate::time::hrtimer::HrTimer<$timer_type>,
1114 ) -> *mut Self {
1115 // SAFETY: As per the safety requirement of this function, `ptr`
1116 // is pointing inside a `$timer_type`.
1117 unsafe { ::kernel::container_of!(ptr, $timer_type, $field) }
1118 }
1119 }
1120 }
1121}
1122
1123mod arc;
1124pub use arc::ArcHrTimerHandle;
1125mod pin;
1126pub use pin::PinHrTimerHandle;
1127mod pin_mut;
1128pub use pin_mut::PinMutHrTimerHandle;
1129// `box` is a reserved keyword, so prefix with `t` for timer
1130mod tbox;
1131pub use tbox::BoxHrTimerHandle;