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