xref: /linux/rust/kernel/time/hrtimer.rs (revision 3f2a5ba784b808109cac0aac921213e43143a216)
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 use super::{ClockSource, Delta, Instant};
71 use crate::{prelude::*, types::Opaque};
72 use core::{marker::PhantomData, ptr::NonNull};
73 use pin_init::PinInit;
74 
75 /// A type-alias to refer to the [`Instant<C>`] for a given `T` from [`HrTimer<T>`].
76 ///
77 /// Where `C` is the [`ClockSource`] of the [`HrTimer`].
78 pub type HrTimerInstant<T> = Instant<<<T as HasHrTimer<T>>::TimerMode as HrTimerMode>::Clock>;
79 
80 /// A timer backed by a C `struct hrtimer`.
81 ///
82 /// # Invariants
83 ///
84 /// * `self.timer` is initialized by `bindings::hrtimer_setup`.
85 #[pin_data]
86 #[repr(C)]
87 pub struct HrTimer<T> {
88     #[pin]
89     timer: Opaque<bindings::hrtimer>,
90     _t: PhantomData<T>,
91 }
92 
93 // SAFETY: Ownership of an `HrTimer` can be moved to other threads and
94 // used/dropped from there.
95 unsafe impl<T> Send for HrTimer<T> {}
96 
97 // SAFETY: Timer operations are locked on the C side, so it is safe to operate
98 // on a timer from multiple threads.
99 unsafe impl<T> Sync for HrTimer<T> {}
100 
101 impl<T> HrTimer<T> {
102     /// Return an initializer for a new timer instance.
103     pub fn new() -> impl PinInit<Self>
104     where
105         T: HrTimerCallback,
106         T: HasHrTimer<T>,
107     {
108         pin_init!(Self {
109             // INVARIANT: We initialize `timer` with `hrtimer_setup` below.
110             timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
111                 // SAFETY: By design of `pin_init!`, `place` is a pointer to a
112                 // live allocation. hrtimer_setup will initialize `place` and
113                 // does not require `place` to be initialized prior to the call.
114                 unsafe {
115                     bindings::hrtimer_setup(
116                         place,
117                         Some(T::Pointer::run),
118                         <<T as HasHrTimer<T>>::TimerMode as HrTimerMode>::Clock::ID,
119                         <T as HasHrTimer<T>>::TimerMode::C_MODE,
120                     );
121                 }
122             }),
123             _t: PhantomData,
124         })
125     }
126 
127     /// Get a pointer to the contained `bindings::hrtimer`.
128     ///
129     /// This function is useful to get access to the value without creating
130     /// intermediate references.
131     ///
132     /// # Safety
133     ///
134     /// `this` must point to a live allocation of at least the size of `Self`.
135     unsafe fn raw_get(this: *const Self) -> *mut bindings::hrtimer {
136         // SAFETY: The field projection to `timer` does not go out of bounds,
137         // because the caller of this function promises that `this` points to an
138         // allocation of at least the size of `Self`.
139         unsafe { Opaque::cast_into(core::ptr::addr_of!((*this).timer)) }
140     }
141 
142     /// Cancel an initialized and potentially running timer.
143     ///
144     /// If the timer handler is running, this function will block until the
145     /// handler returns.
146     ///
147     /// Note that the timer might be started by a concurrent start operation. If
148     /// so, the timer might not be in the **stopped** state when this function
149     /// returns.
150     ///
151     /// Users of the `HrTimer` API would not usually call this method directly.
152     /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
153     /// returned when the timer was started.
154     ///
155     /// This function is useful to get access to the value without creating
156     /// intermediate references.
157     ///
158     /// # Safety
159     ///
160     /// `this` must point to a valid `Self`.
161     pub(crate) unsafe fn raw_cancel(this: *const Self) -> bool {
162         // SAFETY: `this` points to an allocation of at least `HrTimer` size.
163         let c_timer_ptr = unsafe { HrTimer::raw_get(this) };
164 
165         // If the handler is running, this will wait for the handler to return
166         // before returning.
167         // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
168         // handled on the C side.
169         unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
170     }
171 
172     /// Forward the timer expiry for a given timer pointer.
173     ///
174     /// # Safety
175     ///
176     /// - `self_ptr` must point to a valid `Self`.
177     /// - The caller must either have exclusive access to the data pointed at by `self_ptr`, or be
178     ///   within the context of the timer callback.
179     #[inline]
180     unsafe fn raw_forward(self_ptr: *mut Self, now: HrTimerInstant<T>, interval: Delta) -> u64
181     where
182         T: HasHrTimer<T>,
183     {
184         // SAFETY:
185         // * The C API requirements for this function are fulfilled by our safety contract.
186         // * `self_ptr` is guaranteed to point to a valid `Self` via our safety contract
187         unsafe {
188             bindings::hrtimer_forward(Self::raw_get(self_ptr), now.as_nanos(), interval.as_nanos())
189         }
190     }
191 
192     /// Conditionally forward the timer.
193     ///
194     /// If the timer expires after `now`, this function does nothing and returns 0. If the timer
195     /// expired at or before `now`, this function forwards the timer by `interval` until the timer
196     /// expires after `now` and then returns the number of times the timer was forwarded by
197     /// `interval`.
198     ///
199     /// This function is mainly useful for timer types which can provide exclusive access to the
200     /// timer when the timer is not running. For forwarding the timer from within the timer callback
201     /// context, see [`HrTimerCallbackContext::forward()`].
202     ///
203     /// Returns the number of overruns that occurred as a result of the timer expiry change.
204     pub fn forward(self: Pin<&mut Self>, now: HrTimerInstant<T>, interval: Delta) -> u64
205     where
206         T: HasHrTimer<T>,
207     {
208         // SAFETY: `raw_forward` does not move `Self`
209         let this = unsafe { self.get_unchecked_mut() };
210 
211         // SAFETY: By existence of `Pin<&mut Self>`, the pointer passed to `raw_forward` points to a
212         // valid `Self` that we have exclusive access to.
213         unsafe { Self::raw_forward(this, now, interval) }
214     }
215 }
216 
217 /// Implemented by pointer types that point to structs that contain a [`HrTimer`].
218 ///
219 /// `Self` must be [`Sync`] because it is passed to timer callbacks in another
220 /// thread of execution (hard or soft interrupt context).
221 ///
222 /// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
223 /// the timer. Note that it is OK to call the start function repeatedly, and
224 /// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
225 /// exist. A timer can be manipulated through any of the handles, and a handle
226 /// may represent a cancelled timer.
227 pub trait HrTimerPointer: Sync + Sized {
228     /// The operational mode associated with this timer.
229     ///
230     /// This defines how the expiration value is interpreted.
231     type TimerMode: HrTimerMode;
232 
233     /// A handle representing a started or restarted timer.
234     ///
235     /// If the timer is running or if the timer callback is executing when the
236     /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
237     /// until the timer is stopped and the callback has completed.
238     ///
239     /// Note: When implementing this trait, consider that it is not unsafe to
240     /// leak the handle.
241     type TimerHandle: HrTimerHandle;
242 
243     /// Start the timer with expiry after `expires` time units. If the timer was
244     /// already running, it is restarted with the new expiry time.
245     fn start(self, expires: <Self::TimerMode as HrTimerMode>::Expires) -> Self::TimerHandle;
246 }
247 
248 /// Unsafe version of [`HrTimerPointer`] for situations where leaking the
249 /// [`HrTimerHandle`] returned by `start` would be unsound. This is the case for
250 /// stack allocated timers.
251 ///
252 /// Typical implementers are pinned references such as [`Pin<&T>`].
253 ///
254 /// # Safety
255 ///
256 /// Implementers of this trait must ensure that instances of types implementing
257 /// [`UnsafeHrTimerPointer`] outlives any associated [`HrTimerPointer::TimerHandle`]
258 /// instances.
259 pub unsafe trait UnsafeHrTimerPointer: Sync + Sized {
260     /// The operational mode associated with this timer.
261     ///
262     /// This defines how the expiration value is interpreted.
263     type TimerMode: HrTimerMode;
264 
265     /// A handle representing a running timer.
266     ///
267     /// # Safety
268     ///
269     /// If the timer is running, or if the timer callback is executing when the
270     /// handle is dropped, the drop method of [`Self::TimerHandle`] must not return
271     /// until the timer is stopped and the callback has completed.
272     type TimerHandle: HrTimerHandle;
273 
274     /// Start the timer after `expires` time units. If the timer was already
275     /// running, it is restarted at the new expiry time.
276     ///
277     /// # Safety
278     ///
279     /// Caller promises keep the timer structure alive until the timer is dead.
280     /// Caller can ensure this by not leaking the returned [`Self::TimerHandle`].
281     unsafe fn start(self, expires: <Self::TimerMode as HrTimerMode>::Expires) -> Self::TimerHandle;
282 }
283 
284 /// A trait for stack allocated timers.
285 ///
286 /// # Safety
287 ///
288 /// Implementers must ensure that `start_scoped` does not return until the
289 /// timer is dead and the timer handler is not running.
290 pub unsafe trait ScopedHrTimerPointer {
291     /// The operational mode associated with this timer.
292     ///
293     /// This defines how the expiration value is interpreted.
294     type TimerMode: HrTimerMode;
295 
296     /// Start the timer to run after `expires` time units and immediately
297     /// after call `f`. When `f` returns, the timer is cancelled.
298     fn start_scoped<T, F>(self, expires: <Self::TimerMode as HrTimerMode>::Expires, f: F) -> T
299     where
300         F: FnOnce() -> T;
301 }
302 
303 // SAFETY: By the safety requirement of [`UnsafeHrTimerPointer`], dropping the
304 // handle returned by [`UnsafeHrTimerPointer::start`] ensures that the timer is
305 // killed.
306 unsafe impl<T> ScopedHrTimerPointer for T
307 where
308     T: UnsafeHrTimerPointer,
309 {
310     type TimerMode = T::TimerMode;
311 
312     fn start_scoped<U, F>(
313         self,
314         expires: <<T as UnsafeHrTimerPointer>::TimerMode as HrTimerMode>::Expires,
315         f: F,
316     ) -> U
317     where
318         F: FnOnce() -> U,
319     {
320         // SAFETY: We drop the timer handle below before returning.
321         let handle = unsafe { UnsafeHrTimerPointer::start(self, expires) };
322         let t = f();
323         drop(handle);
324         t
325     }
326 }
327 
328 /// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
329 /// function to call.
330 // This is split from `HrTimerPointer` to make it easier to specify trait bounds.
331 pub trait RawHrTimerCallback {
332     /// Type of the parameter passed to [`HrTimerCallback::run`]. It may be
333     /// [`Self`], or a pointer type derived from [`Self`].
334     type CallbackTarget<'a>;
335 
336     /// Callback to be called from C when timer fires.
337     ///
338     /// # Safety
339     ///
340     /// Only to be called by C code in the `hrtimer` subsystem. `this` must point
341     /// to the `bindings::hrtimer` structure that was used to start the timer.
342     unsafe extern "C" fn run(this: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
343 }
344 
345 /// Implemented by structs that can be the target of a timer callback.
346 pub trait HrTimerCallback {
347     /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
348     /// the timer expires.
349     type Pointer<'a>: RawHrTimerCallback;
350 
351     /// Called by the timer logic when the timer fires.
352     fn run(
353         this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>,
354         ctx: HrTimerCallbackContext<'_, Self>,
355     ) -> HrTimerRestart
356     where
357         Self: Sized,
358         Self: HasHrTimer<Self>;
359 }
360 
361 /// A handle representing a potentially running timer.
362 ///
363 /// More than one handle representing the same timer might exist.
364 ///
365 /// # Safety
366 ///
367 /// When dropped, the timer represented by this handle must be cancelled, if it
368 /// is running. If the timer handler is running when the handle is dropped, the
369 /// drop method must wait for the handler to return before returning.
370 ///
371 /// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
372 /// the drop implementation for `Self.`
373 pub unsafe trait HrTimerHandle {
374     /// Cancel the timer. If the timer is in the running state, block till the
375     /// handler has returned.
376     ///
377     /// Note that the timer might be started by a concurrent start operation. If
378     /// so, the timer might not be in the **stopped** state when this function
379     /// returns.
380     ///
381     /// Returns `true` if the timer was running.
382     fn cancel(&mut self) -> bool;
383 }
384 
385 /// Implemented by structs that contain timer nodes.
386 ///
387 /// Clients of the timer API would usually safely implement this trait by using
388 /// the [`crate::impl_has_hr_timer`] macro.
389 ///
390 /// # Safety
391 ///
392 /// Implementers of this trait must ensure that the implementer has a
393 /// [`HrTimer`] field and that all trait methods are implemented according to
394 /// their documentation. All the methods of this trait must operate on the same
395 /// field.
396 pub unsafe trait HasHrTimer<T> {
397     /// The operational mode associated with this timer.
398     ///
399     /// This defines how the expiration value is interpreted.
400     type TimerMode: HrTimerMode;
401 
402     /// Return a pointer to the [`HrTimer`] within `Self`.
403     ///
404     /// This function is useful to get access to the value without creating
405     /// intermediate references.
406     ///
407     /// # Safety
408     ///
409     /// `this` must be a valid pointer.
410     unsafe fn raw_get_timer(this: *const Self) -> *const HrTimer<T>;
411 
412     /// Return a pointer to the struct that is containing the [`HrTimer`] pointed
413     /// to by `ptr`.
414     ///
415     /// This function is useful to get access to the value without creating
416     /// intermediate references.
417     ///
418     /// # Safety
419     ///
420     /// `ptr` must point to a [`HrTimer<T>`] field in a struct of type `Self`.
421     unsafe fn timer_container_of(ptr: *mut HrTimer<T>) -> *mut Self
422     where
423         Self: Sized;
424 
425     /// Get pointer to the contained `bindings::hrtimer` struct.
426     ///
427     /// This function is useful to get access to the value without creating
428     /// intermediate references.
429     ///
430     /// # Safety
431     ///
432     /// `this` must be a valid pointer.
433     unsafe fn c_timer_ptr(this: *const Self) -> *const bindings::hrtimer {
434         // SAFETY: `this` is a valid pointer to a `Self`.
435         let timer_ptr = unsafe { Self::raw_get_timer(this) };
436 
437         // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
438         unsafe { HrTimer::raw_get(timer_ptr) }
439     }
440 
441     /// Start the timer contained in the `Self` pointed to by `self_ptr`. If
442     /// it is already running it is removed and inserted.
443     ///
444     /// # Safety
445     ///
446     /// - `this` must point to a valid `Self`.
447     /// - Caller must ensure that the pointee of `this` lives until the timer
448     ///   fires or is canceled.
449     unsafe fn start(this: *const Self, expires: <Self::TimerMode as HrTimerMode>::Expires) {
450         // SAFETY: By function safety requirement, `this` is a valid `Self`.
451         unsafe {
452             bindings::hrtimer_start_range_ns(
453                 Self::c_timer_ptr(this).cast_mut(),
454                 expires.as_nanos(),
455                 0,
456                 <Self::TimerMode as HrTimerMode>::C_MODE,
457             );
458         }
459     }
460 }
461 
462 /// Restart policy for timers.
463 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
464 #[repr(u32)]
465 pub enum HrTimerRestart {
466     /// Timer should not be restarted.
467     NoRestart = bindings::hrtimer_restart_HRTIMER_NORESTART,
468     /// Timer should be restarted.
469     Restart = bindings::hrtimer_restart_HRTIMER_RESTART,
470 }
471 
472 impl HrTimerRestart {
473     fn into_c(self) -> bindings::hrtimer_restart {
474         self as bindings::hrtimer_restart
475     }
476 }
477 
478 /// Time representations that can be used as expiration values in [`HrTimer`].
479 pub trait HrTimerExpires {
480     /// Converts the expiration time into a nanosecond representation.
481     ///
482     /// This value corresponds to a raw ktime_t value, suitable for passing to kernel
483     /// timer functions. The interpretation (absolute vs relative) depends on the
484     /// associated [HrTimerMode] in use.
485     fn as_nanos(&self) -> i64;
486 }
487 
488 impl<C: ClockSource> HrTimerExpires for Instant<C> {
489     #[inline]
490     fn as_nanos(&self) -> i64 {
491         Instant::<C>::as_nanos(self)
492     }
493 }
494 
495 impl HrTimerExpires for Delta {
496     #[inline]
497     fn as_nanos(&self) -> i64 {
498         Delta::as_nanos(*self)
499     }
500 }
501 
502 mod private {
503     use crate::time::ClockSource;
504 
505     pub trait Sealed {}
506 
507     impl<C: ClockSource> Sealed for super::AbsoluteMode<C> {}
508     impl<C: ClockSource> Sealed for super::RelativeMode<C> {}
509     impl<C: ClockSource> Sealed for super::AbsolutePinnedMode<C> {}
510     impl<C: ClockSource> Sealed for super::RelativePinnedMode<C> {}
511     impl<C: ClockSource> Sealed for super::AbsoluteSoftMode<C> {}
512     impl<C: ClockSource> Sealed for super::RelativeSoftMode<C> {}
513     impl<C: ClockSource> Sealed for super::AbsolutePinnedSoftMode<C> {}
514     impl<C: ClockSource> Sealed for super::RelativePinnedSoftMode<C> {}
515     impl<C: ClockSource> Sealed for super::AbsoluteHardMode<C> {}
516     impl<C: ClockSource> Sealed for super::RelativeHardMode<C> {}
517     impl<C: ClockSource> Sealed for super::AbsolutePinnedHardMode<C> {}
518     impl<C: ClockSource> Sealed for super::RelativePinnedHardMode<C> {}
519 }
520 
521 /// Operational mode of [`HrTimer`].
522 pub trait HrTimerMode: private::Sealed {
523     /// The C representation of hrtimer mode.
524     const C_MODE: bindings::hrtimer_mode;
525 
526     /// Type representing the clock source.
527     type Clock: ClockSource;
528 
529     /// Type representing the expiration specification (absolute or relative time).
530     type Expires: HrTimerExpires;
531 }
532 
533 /// Timer that expires at a fixed point in time.
534 pub struct AbsoluteMode<C: ClockSource>(PhantomData<C>);
535 
536 impl<C: ClockSource> HrTimerMode for AbsoluteMode<C> {
537     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS;
538 
539     type Clock = C;
540     type Expires = Instant<C>;
541 }
542 
543 /// Timer that expires after a delay from now.
544 pub struct RelativeMode<C: ClockSource>(PhantomData<C>);
545 
546 impl<C: ClockSource> HrTimerMode for RelativeMode<C> {
547     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL;
548 
549     type Clock = C;
550     type Expires = Delta;
551 }
552 
553 /// Timer with absolute expiration time, pinned to its current CPU.
554 pub struct AbsolutePinnedMode<C: ClockSource>(PhantomData<C>);
555 impl<C: ClockSource> HrTimerMode for AbsolutePinnedMode<C> {
556     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_PINNED;
557 
558     type Clock = C;
559     type Expires = Instant<C>;
560 }
561 
562 /// Timer with relative expiration time, pinned to its current CPU.
563 pub struct RelativePinnedMode<C: ClockSource>(PhantomData<C>);
564 impl<C: ClockSource> HrTimerMode for RelativePinnedMode<C> {
565     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_PINNED;
566 
567     type Clock = C;
568     type Expires = Delta;
569 }
570 
571 /// Timer with absolute expiration, handled in soft irq context.
572 pub struct AbsoluteSoftMode<C: ClockSource>(PhantomData<C>);
573 impl<C: ClockSource> HrTimerMode for AbsoluteSoftMode<C> {
574     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_SOFT;
575 
576     type Clock = C;
577     type Expires = Instant<C>;
578 }
579 
580 /// Timer with relative expiration, handled in soft irq context.
581 pub struct RelativeSoftMode<C: ClockSource>(PhantomData<C>);
582 impl<C: ClockSource> HrTimerMode for RelativeSoftMode<C> {
583     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_SOFT;
584 
585     type Clock = C;
586     type Expires = Delta;
587 }
588 
589 /// Timer with absolute expiration, pinned to CPU and handled in soft irq context.
590 pub struct AbsolutePinnedSoftMode<C: ClockSource>(PhantomData<C>);
591 impl<C: ClockSource> HrTimerMode for AbsolutePinnedSoftMode<C> {
592     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_PINNED_SOFT;
593 
594     type Clock = C;
595     type Expires = Instant<C>;
596 }
597 
598 /// Timer with absolute expiration, pinned to CPU and handled in soft irq context.
599 pub struct RelativePinnedSoftMode<C: ClockSource>(PhantomData<C>);
600 impl<C: ClockSource> HrTimerMode for RelativePinnedSoftMode<C> {
601     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_PINNED_SOFT;
602 
603     type Clock = C;
604     type Expires = Delta;
605 }
606 
607 /// Timer with absolute expiration, handled in hard irq context.
608 pub struct AbsoluteHardMode<C: ClockSource>(PhantomData<C>);
609 impl<C: ClockSource> HrTimerMode for AbsoluteHardMode<C> {
610     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_HARD;
611 
612     type Clock = C;
613     type Expires = Instant<C>;
614 }
615 
616 /// Timer with relative expiration, handled in hard irq context.
617 pub struct RelativeHardMode<C: ClockSource>(PhantomData<C>);
618 impl<C: ClockSource> HrTimerMode for RelativeHardMode<C> {
619     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_HARD;
620 
621     type Clock = C;
622     type Expires = Delta;
623 }
624 
625 /// Timer with absolute expiration, pinned to CPU and handled in hard irq context.
626 pub struct AbsolutePinnedHardMode<C: ClockSource>(PhantomData<C>);
627 impl<C: ClockSource> HrTimerMode for AbsolutePinnedHardMode<C> {
628     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_ABS_PINNED_HARD;
629 
630     type Clock = C;
631     type Expires = Instant<C>;
632 }
633 
634 /// Timer with relative expiration, pinned to CPU and handled in hard irq context.
635 pub struct RelativePinnedHardMode<C: ClockSource>(PhantomData<C>);
636 impl<C: ClockSource> HrTimerMode for RelativePinnedHardMode<C> {
637     const C_MODE: bindings::hrtimer_mode = bindings::hrtimer_mode_HRTIMER_MODE_REL_PINNED_HARD;
638 
639     type Clock = C;
640     type Expires = Delta;
641 }
642 
643 /// Privileged smart-pointer for a [`HrTimer`] callback context.
644 ///
645 /// Many [`HrTimer`] methods can only be called in two situations:
646 ///
647 /// * When the caller has exclusive access to the `HrTimer` and the `HrTimer` is guaranteed not to
648 ///   be running.
649 /// * From within the context of an `HrTimer`'s callback method.
650 ///
651 /// This type provides access to said methods from within a timer callback context.
652 ///
653 /// # Invariants
654 ///
655 /// * The existence of this type means the caller is currently within the callback for an
656 ///   [`HrTimer`].
657 /// * `self.0` always points to a live instance of [`HrTimer<T>`].
658 pub struct HrTimerCallbackContext<'a, T: HasHrTimer<T>>(NonNull<HrTimer<T>>, PhantomData<&'a ()>);
659 
660 impl<'a, T: HasHrTimer<T>> HrTimerCallbackContext<'a, T> {
661     /// Create a new [`HrTimerCallbackContext`].
662     ///
663     /// # Safety
664     ///
665     /// This function relies on the caller being within the context of a timer callback, so it must
666     /// not be used anywhere except for within implementations of [`RawHrTimerCallback::run`]. The
667     /// caller promises that `timer` points to a valid initialized instance of
668     /// [`bindings::hrtimer`].
669     ///
670     /// The returned `Self` must not outlive the function context of [`RawHrTimerCallback::run`]
671     /// where this function is called.
672     pub(crate) unsafe fn from_raw(timer: *mut HrTimer<T>) -> Self {
673         // SAFETY: The caller guarantees `timer` is a valid pointer to an initialized
674         // `bindings::hrtimer`
675         // INVARIANT: Our safety contract ensures that we're within the context of a timer callback
676         // and that `timer` points to a live instance of `HrTimer<T>`.
677         Self(unsafe { NonNull::new_unchecked(timer) }, PhantomData)
678     }
679 
680     /// Conditionally forward the timer.
681     ///
682     /// This function is identical to [`HrTimer::forward()`] except that it may only be used from
683     /// within the context of a [`HrTimer`] callback.
684     pub fn forward(&mut self, now: HrTimerInstant<T>, interval: Delta) -> u64 {
685         // SAFETY:
686         // - We are guaranteed to be within the context of a timer callback by our type invariants
687         // - By our type invariants, `self.0` always points to a valid `HrTimer<T>`
688         unsafe { HrTimer::<T>::raw_forward(self.0.as_ptr(), now, interval) }
689     }
690 }
691 
692 /// Use to implement the [`HasHrTimer<T>`] trait.
693 ///
694 /// See [`module`] documentation for an example.
695 ///
696 /// [`module`]: crate::time::hrtimer
697 #[macro_export]
698 macro_rules! impl_has_hr_timer {
699     (
700         impl$({$($generics:tt)*})?
701             HasHrTimer<$timer_type:ty>
702             for $self:ty
703         {
704             mode : $mode:ty,
705             field : self.$field:ident $(,)?
706         }
707         $($rest:tt)*
708     ) => {
709         // SAFETY: This implementation of `raw_get_timer` only compiles if the
710         // field has the right type.
711         unsafe impl$(<$($generics)*>)? $crate::time::hrtimer::HasHrTimer<$timer_type> for $self {
712             type TimerMode = $mode;
713 
714             #[inline]
715             unsafe fn raw_get_timer(
716                 this: *const Self,
717             ) -> *const $crate::time::hrtimer::HrTimer<$timer_type> {
718                 // SAFETY: The caller promises that the pointer is not dangling.
719                 unsafe { ::core::ptr::addr_of!((*this).$field) }
720             }
721 
722             #[inline]
723             unsafe fn timer_container_of(
724                 ptr: *mut $crate::time::hrtimer::HrTimer<$timer_type>,
725             ) -> *mut Self {
726                 // SAFETY: As per the safety requirement of this function, `ptr`
727                 // is pointing inside a `$timer_type`.
728                 unsafe { ::kernel::container_of!(ptr, $timer_type, $field) }
729             }
730         }
731     }
732 }
733 
734 mod arc;
735 pub use arc::ArcHrTimerHandle;
736 mod pin;
737 pub use pin::PinHrTimerHandle;
738 mod pin_mut;
739 pub use pin_mut::PinMutHrTimerHandle;
740 // `box` is a reserved keyword, so prefix with `t` for timer
741 mod tbox;
742 pub use tbox::BoxHrTimerHandle;
743