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 /// Implemented by [`HrTimerPointer`] implementers to give the C timer callback a 192 /// function to call. 193 // This is split from `HrTimerPointer` to make it easier to specify trait bounds. 194 pub trait RawHrTimerCallback { 195 /// Type of the parameter passed to [`HrTimerCallback::run`]. It may be 196 /// [`Self`], or a pointer type derived from [`Self`]. 197 type CallbackTarget<'a>; 198 199 /// Callback to be called from C when timer fires. 200 /// 201 /// # Safety 202 /// 203 /// Only to be called by C code in the `hrtimer` subsystem. `this` must point 204 /// to the `bindings::hrtimer` structure that was used to start the timer. 205 unsafe extern "C" fn run(this: *mut bindings::hrtimer) -> bindings::hrtimer_restart; 206 } 207 208 /// Implemented by structs that can be the target of a timer callback. 209 pub trait HrTimerCallback { 210 /// The type whose [`RawHrTimerCallback::run`] method will be invoked when 211 /// the timer expires. 212 type Pointer<'a>: RawHrTimerCallback; 213 214 /// Called by the timer logic when the timer fires. 215 fn run(this: <Self::Pointer<'_> as RawHrTimerCallback>::CallbackTarget<'_>) 216 where 217 Self: Sized; 218 } 219 220 /// A handle representing a potentially running timer. 221 /// 222 /// More than one handle representing the same timer might exist. 223 /// 224 /// # Safety 225 /// 226 /// When dropped, the timer represented by this handle must be cancelled, if it 227 /// is running. If the timer handler is running when the handle is dropped, the 228 /// drop method must wait for the handler to return before returning. 229 /// 230 /// Note: One way to satisfy the safety requirement is to call `Self::cancel` in 231 /// the drop implementation for `Self.` 232 pub unsafe trait HrTimerHandle { 233 /// Cancel the timer. If the timer is in the running state, block till the 234 /// handler has returned. 235 /// 236 /// Note that the timer might be started by a concurrent start operation. If 237 /// so, the timer might not be in the **stopped** state when this function 238 /// returns. 239 fn cancel(&mut self) -> bool; 240 } 241 242 /// Implemented by structs that contain timer nodes. 243 /// 244 /// Clients of the timer API would usually safely implement this trait by using 245 /// the [`crate::impl_has_hr_timer`] macro. 246 /// 247 /// # Safety 248 /// 249 /// Implementers of this trait must ensure that the implementer has a 250 /// [`HrTimer`] field and that all trait methods are implemented according to 251 /// their documentation. All the methods of this trait must operate on the same 252 /// field. 253 pub unsafe trait HasHrTimer<T> { 254 /// Return a pointer to the [`HrTimer`] within `Self`. 255 /// 256 /// This function is useful to get access to the value without creating 257 /// intermediate references. 258 /// 259 /// # Safety 260 /// 261 /// `this` must be a valid pointer. 262 unsafe fn raw_get_timer(this: *const Self) -> *const HrTimer<T>; 263 264 /// Return a pointer to the struct that is containing the [`HrTimer`] pointed 265 /// to by `ptr`. 266 /// 267 /// This function is useful to get access to the value without creating 268 /// intermediate references. 269 /// 270 /// # Safety 271 /// 272 /// `ptr` must point to a [`HrTimer<T>`] field in a struct of type `Self`. 273 unsafe fn timer_container_of(ptr: *mut HrTimer<T>) -> *mut Self 274 where 275 Self: Sized; 276 277 /// Get pointer to the contained `bindings::hrtimer` struct. 278 /// 279 /// This function is useful to get access to the value without creating 280 /// intermediate references. 281 /// 282 /// # Safety 283 /// 284 /// `this` must be a valid pointer. 285 unsafe fn c_timer_ptr(this: *const Self) -> *const bindings::hrtimer { 286 // SAFETY: `this` is a valid pointer to a `Self`. 287 let timer_ptr = unsafe { Self::raw_get_timer(this) }; 288 289 // SAFETY: timer_ptr points to an allocation of at least `HrTimer` size. 290 unsafe { HrTimer::raw_get(timer_ptr) } 291 } 292 293 /// Start the timer contained in the `Self` pointed to by `self_ptr`. If 294 /// it is already running it is removed and inserted. 295 /// 296 /// # Safety 297 /// 298 /// - `this` must point to a valid `Self`. 299 /// - Caller must ensure that the pointee of `this` lives until the timer 300 /// fires or is canceled. 301 unsafe fn start(this: *const Self, expires: Ktime) { 302 // SAFETY: By function safety requirement, `this` is a valid `Self`. 303 unsafe { 304 bindings::hrtimer_start_range_ns( 305 Self::c_timer_ptr(this).cast_mut(), 306 expires.to_ns(), 307 0, 308 bindings::hrtimer_mode_HRTIMER_MODE_REL, 309 ); 310 } 311 } 312 } 313 314 /// Use to implement the [`HasHrTimer<T>`] trait. 315 /// 316 /// See [`module`] documentation for an example. 317 /// 318 /// [`module`]: crate::time::hrtimer 319 #[macro_export] 320 macro_rules! impl_has_hr_timer { 321 ( 322 impl$({$($generics:tt)*})? 323 HasHrTimer<$timer_type:ty> 324 for $self:ty 325 { self.$field:ident } 326 $($rest:tt)* 327 ) => { 328 // SAFETY: This implementation of `raw_get_timer` only compiles if the 329 // field has the right type. 330 unsafe impl$(<$($generics)*>)? $crate::time::hrtimer::HasHrTimer<$timer_type> for $self { 331 332 #[inline] 333 unsafe fn raw_get_timer( 334 this: *const Self, 335 ) -> *const $crate::time::hrtimer::HrTimer<$timer_type> { 336 // SAFETY: The caller promises that the pointer is not dangling. 337 unsafe { ::core::ptr::addr_of!((*this).$field) } 338 } 339 340 #[inline] 341 unsafe fn timer_container_of( 342 ptr: *mut $crate::time::hrtimer::HrTimer<$timer_type>, 343 ) -> *mut Self { 344 // SAFETY: As per the safety requirement of this function, `ptr` 345 // is pointing inside a `$timer_type`. 346 unsafe { ::kernel::container_of!(ptr, $timer_type, $field).cast_mut() } 347 } 348 } 349 } 350 } 351 352 mod arc; 353 pub use arc::ArcHrTimerHandle; 354