xref: /linux-6.15/rust/kernel/time/hrtimer.rs (revision f93b0d83)
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 crate::{init::PinInit, prelude::*, time::Ktime, types::Opaque};
71 use core::marker::PhantomData;
72 
73 /// A timer backed by a C `struct hrtimer`.
74 ///
75 /// # Invariants
76 ///
77 /// * `self.timer` is initialized by `bindings::hrtimer_setup`.
78 #[pin_data]
79 #[repr(C)]
80 pub struct HrTimer<T> {
81     #[pin]
82     timer: Opaque<bindings::hrtimer>,
83     _t: PhantomData<T>,
84 }
85 
86 // SAFETY: Ownership of an `HrTimer` can be moved to other threads and
87 // used/dropped from there.
88 unsafe impl<T> Send for HrTimer<T> {}
89 
90 // SAFETY: Timer operations are locked on the C side, so it is safe to operate
91 // on a timer from multiple threads.
92 unsafe impl<T> Sync for HrTimer<T> {}
93 
94 impl<T> HrTimer<T> {
95     /// Return an initializer for a new timer instance.
96     pub fn new() -> impl PinInit<Self>
97     where
98         T: HrTimerCallback,
99     {
100         pin_init!(Self {
101             // INVARIANT: We initialize `timer` with `hrtimer_setup` below.
102             timer <- Opaque::ffi_init(move |place: *mut bindings::hrtimer| {
103                 // SAFETY: By design of `pin_init!`, `place` is a pointer to a
104                 // live allocation. hrtimer_setup will initialize `place` and
105                 // does not require `place` to be initialized prior to the call.
106                 unsafe {
107                     bindings::hrtimer_setup(
108                         place,
109                         Some(T::Pointer::run),
110                         bindings::CLOCK_MONOTONIC as i32,
111                         bindings::hrtimer_mode_HRTIMER_MODE_REL,
112                     );
113                 }
114             }),
115             _t: PhantomData,
116         })
117     }
118 
119     /// Get a pointer to the contained `bindings::hrtimer`.
120     ///
121     /// This function is useful to get access to the value without creating
122     /// intermediate references.
123     ///
124     /// # Safety
125     ///
126     /// `this` must point to a live allocation of at least the size of `Self`.
127     unsafe fn raw_get(this: *const Self) -> *mut bindings::hrtimer {
128         // SAFETY: The field projection to `timer` does not go out of bounds,
129         // because the caller of this function promises that `this` points to an
130         // allocation of at least the size of `Self`.
131         unsafe { Opaque::raw_get(core::ptr::addr_of!((*this).timer)) }
132     }
133 
134     /// Cancel an initialized and potentially running timer.
135     ///
136     /// If the timer handler is running, this function will block until the
137     /// handler returns.
138     ///
139     /// Note that the timer might be started by a concurrent start operation. If
140     /// so, the timer might not be in the **stopped** state when this function
141     /// returns.
142     ///
143     /// Users of the `HrTimer` API would not usually call this method directly.
144     /// Instead they would use the safe [`HrTimerHandle::cancel`] on the handle
145     /// returned when the timer was started.
146     ///
147     /// This function is useful to get access to the value without creating
148     /// intermediate references.
149     ///
150     /// # Safety
151     ///
152     /// `this` must point to a valid `Self`.
153     pub(crate) unsafe fn raw_cancel(this: *const Self) -> bool {
154         // SAFETY: `this` points to an allocation of at least `HrTimer` size.
155         let c_timer_ptr = unsafe { HrTimer::raw_get(this) };
156 
157         // If the handler is running, this will wait for the handler to return
158         // before returning.
159         // SAFETY: `c_timer_ptr` is initialized and valid. Synchronization is
160         // handled on the C side.
161         unsafe { bindings::hrtimer_cancel(c_timer_ptr) != 0 }
162     }
163 }
164 
165 /// Implemented by pointer types that point to structs that contain a [`HrTimer`].
166 ///
167 /// `Self` must be [`Sync`] because it is passed to timer callbacks in another
168 /// thread of execution (hard or soft interrupt context).
169 ///
170 /// Starting a timer returns a [`HrTimerHandle`] that can be used to manipulate
171 /// the timer. Note that it is OK to call the start function repeatedly, and
172 /// that more than one [`HrTimerHandle`] associated with a [`HrTimerPointer`] may
173 /// exist. A timer can be manipulated through any of the handles, and a handle
174 /// may represent a cancelled timer.
175 pub trait HrTimerPointer: Sync + Sized {
176     /// A handle representing a started or restarted timer.
177     ///
178     /// If the timer is running or if the timer callback is executing when the
179     /// handle is dropped, the drop method of [`HrTimerHandle`] should not return
180     /// until the timer is stopped and the callback has completed.
181     ///
182     /// Note: When implementing this trait, consider that it is not unsafe to
183     /// leak the handle.
184     type TimerHandle: HrTimerHandle;
185 
186     /// Start the timer with expiry after `expires` time units. If the timer was
187     /// already running, it is restarted with the new expiry time.
188     fn start(self, expires: Ktime) -> Self::TimerHandle;
189 }
190 
191 /// Unsafe version of [`HrTimerPointer`] for situations where leaking the
192 /// [`HrTimerHandle`] returned by `start` would be unsound. This is the case for
193 /// stack allocated timers.
194 ///
195 /// Typical implementers are pinned references such as [`Pin<&T>`].
196 ///
197 /// # Safety
198 ///
199 /// Implementers of this trait must ensure that instances of types implementing
200 /// [`UnsafeHrTimerPointer`] outlives any associated [`HrTimerPointer::TimerHandle`]
201 /// instances.
202 pub unsafe trait UnsafeHrTimerPointer: Sync + Sized {
203     /// A handle representing a running timer.
204     ///
205     /// # Safety
206     ///
207     /// If the timer is running, or if the timer callback is executing when the
208     /// handle is dropped, the drop method of [`Self::TimerHandle`] must not return
209     /// until the timer is stopped and the callback has completed.
210     type TimerHandle: HrTimerHandle;
211 
212     /// Start the timer after `expires` time units. If the timer was already
213     /// running, it is restarted at the new expiry time.
214     ///
215     /// # Safety
216     ///
217     /// Caller promises keep the timer structure alive until the timer is dead.
218     /// Caller can ensure this by not leaking the returned [`Self::TimerHandle`].
219     unsafe fn start(self, expires: Ktime) -> Self::TimerHandle;
220 }
221 
222 /// A trait for stack allocated timers.
223 ///
224 /// # Safety
225 ///
226 /// Implementers must ensure that `start_scoped` does not return until the
227 /// timer is dead and the timer handler is not running.
228 pub unsafe trait ScopedHrTimerPointer {
229     /// Start the timer to run after `expires` time units and immediately
230     /// after call `f`. When `f` returns, the timer is cancelled.
231     fn start_scoped<T, F>(self, expires: Ktime, f: F) -> T
232     where
233         F: FnOnce() -> T;
234 }
235 
236 // SAFETY: By the safety requirement of [`UnsafeHrTimerPointer`], dropping the
237 // handle returned by [`UnsafeHrTimerPointer::start`] ensures that the timer is
238 // killed.
239 unsafe impl<T> ScopedHrTimerPointer for T
240 where
241     T: UnsafeHrTimerPointer,
242 {
243     fn start_scoped<U, F>(self, expires: Ktime, f: F) -> U
244     where
245         F: FnOnce() -> U,
246     {
247         // SAFETY: We drop the timer handle below before returning.
248         let handle = unsafe { UnsafeHrTimerPointer::start(self, expires) };
249         let t = f();
250         drop(handle);
251         t
252     }
253 }
254 
255 /// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a
256 /// function to call.
257 // This is split from `HrTimerPointer` to make it easier to specify trait bounds.
258 pub trait RawHrTimerCallback {
259     /// Type of the parameter passed to [`HrTimerCallback::run`]. It may be
260     /// [`Self`], or a pointer type derived from [`Self`].
261     type CallbackTarget<'a>;
262 
263     /// Callback to be called from C when timer fires.
264     ///
265     /// # Safety
266     ///
267     /// Only to be called by C code in the `hrtimer` subsystem. `this` must point
268     /// to the `bindings::hrtimer` structure that was used to start the timer.
269     unsafe extern "C" fn run(this: *mut bindings::hrtimer) -> bindings::hrtimer_restart;
270 }
271 
272 /// Implemented by structs that can be the target of a timer callback.
273 pub trait HrTimerCallback {
274     /// The type whose [`RawHrTimerCallback::run`] method will be invoked when
275     /// the timer expires.
276     type Pointer<'a>: RawHrTimerCallback;
277 
278     /// Called by the timer logic when the timer fires.
279     fn run(this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>) -> HrTimerRestart
280     where
281         Self: Sized;
282 }
283 
284 /// A handle representing a potentially running timer.
285 ///
286 /// More than one handle representing the same timer might exist.
287 ///
288 /// # Safety
289 ///
290 /// When dropped, the timer represented by this handle must be cancelled, if it
291 /// is running. If the timer handler is running when the handle is dropped, the
292 /// drop method must wait for the handler to return before returning.
293 ///
294 /// Note: One way to satisfy the safety requirement is to call `Self::cancel` in
295 /// the drop implementation for `Self.`
296 pub unsafe trait HrTimerHandle {
297     /// Cancel the timer. If the timer is in the running state, block till the
298     /// handler has returned.
299     ///
300     /// Note that the timer might be started by a concurrent start operation. If
301     /// so, the timer might not be in the **stopped** state when this function
302     /// returns.
303     fn cancel(&mut self) -> bool;
304 }
305 
306 /// Implemented by structs that contain timer nodes.
307 ///
308 /// Clients of the timer API would usually safely implement this trait by using
309 /// the [`crate::impl_has_hr_timer`] macro.
310 ///
311 /// # Safety
312 ///
313 /// Implementers of this trait must ensure that the implementer has a
314 /// [`HrTimer`] field and that all trait methods are implemented according to
315 /// their documentation. All the methods of this trait must operate on the same
316 /// field.
317 pub unsafe trait HasHrTimer<T> {
318     /// Return a pointer to the [`HrTimer`] within `Self`.
319     ///
320     /// This function is useful to get access to the value without creating
321     /// intermediate references.
322     ///
323     /// # Safety
324     ///
325     /// `this` must be a valid pointer.
326     unsafe fn raw_get_timer(this: *const Self) -> *const HrTimer<T>;
327 
328     /// Return a pointer to the struct that is containing the [`HrTimer`] pointed
329     /// to by `ptr`.
330     ///
331     /// This function is useful to get access to the value without creating
332     /// intermediate references.
333     ///
334     /// # Safety
335     ///
336     /// `ptr` must point to a [`HrTimer<T>`] field in a struct of type `Self`.
337     unsafe fn timer_container_of(ptr: *mut HrTimer<T>) -> *mut Self
338     where
339         Self: Sized;
340 
341     /// Get pointer to the contained `bindings::hrtimer` struct.
342     ///
343     /// This function is useful to get access to the value without creating
344     /// intermediate references.
345     ///
346     /// # Safety
347     ///
348     /// `this` must be a valid pointer.
349     unsafe fn c_timer_ptr(this: *const Self) -> *const bindings::hrtimer {
350         // SAFETY: `this` is a valid pointer to a `Self`.
351         let timer_ptr = unsafe { Self::raw_get_timer(this) };
352 
353         // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size.
354         unsafe { HrTimer::raw_get(timer_ptr) }
355     }
356 
357     /// Start the timer contained in the `Self` pointed to by `self_ptr`. If
358     /// it is already running it is removed and inserted.
359     ///
360     /// # Safety
361     ///
362     /// - `this` must point to a valid `Self`.
363     /// - Caller must ensure that the pointee of `this` lives until the timer
364     ///   fires or is canceled.
365     unsafe fn start(this: *const Self, expires: Ktime) {
366         // SAFETY: By function safety requirement, `this` is a valid `Self`.
367         unsafe {
368             bindings::hrtimer_start_range_ns(
369                 Self::c_timer_ptr(this).cast_mut(),
370                 expires.to_ns(),
371                 0,
372                 bindings::hrtimer_mode_HRTIMER_MODE_REL,
373             );
374         }
375     }
376 }
377 
378 /// Restart policy for timers.
379 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
380 #[repr(u32)]
381 pub enum HrTimerRestart {
382     /// Timer should not be restarted.
383     #[allow(clippy::unnecessary_cast)]
384     NoRestart = bindings::hrtimer_restart_HRTIMER_NORESTART as u32,
385     /// Timer should be restarted.
386     #[allow(clippy::unnecessary_cast)]
387     Restart = bindings::hrtimer_restart_HRTIMER_RESTART as u32,
388 }
389 
390 impl HrTimerRestart {
391     fn into_c(self) -> bindings::hrtimer_restart {
392         self as bindings::hrtimer_restart
393     }
394 }
395 
396 /// Use to implement the [`HasHrTimer<T>`] trait.
397 ///
398 /// See [`module`] documentation for an example.
399 ///
400 /// [`module`]: crate::time::hrtimer
401 #[macro_export]
402 macro_rules! impl_has_hr_timer {
403     (
404         impl$({$($generics:tt)*})?
405             HasHrTimer<$timer_type:ty>
406             for $self:ty
407         { self.$field:ident }
408         $($rest:tt)*
409     ) => {
410         // SAFETY: This implementation of `raw_get_timer` only compiles if the
411         // field has the right type.
412         unsafe impl$(<$($generics)*>)? $crate::time::hrtimer::HasHrTimer<$timer_type> for $self {
413 
414             #[inline]
415             unsafe fn raw_get_timer(
416                 this: *const Self,
417             ) -> *const $crate::time::hrtimer::HrTimer<$timer_type> {
418                 // SAFETY: The caller promises that the pointer is not dangling.
419                 unsafe { ::core::ptr::addr_of!((*this).$field) }
420             }
421 
422             #[inline]
423             unsafe fn timer_container_of(
424                 ptr: *mut $crate::time::hrtimer::HrTimer<$timer_type>,
425             ) -> *mut Self {
426                 // SAFETY: As per the safety requirement of this function, `ptr`
427                 // is pointing inside a `$timer_type`.
428                 unsafe { ::kernel::container_of!(ptr, $timer_type, $field).cast_mut() }
429             }
430         }
431     }
432 }
433 
434 mod arc;
435 pub use arc::ArcHrTimerHandle;
436