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