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