| 1 | # coreboot Timers, Stopwatch, Delays, and Associated Callbacks |
| 2 | |
| 3 | ## Introduction |
| 4 | |
| 5 | coreboot provides several mechanisms for handling time, including |
| 6 | high-precision stopwatches for profiling, simple delay functions for |
| 7 | hardware timing, and a monotonic timer system that forms the foundation |
| 8 | for these features. It also supports scheduling timer callbacks for |
| 9 | deferred execution. These tools are crucial for performance |
| 10 | optimization, debugging, ensuring proper hardware timing, and managing |
| 11 | asynchronous events during the boot process. |
| 12 | |
| 13 | This document describes the core monotonic timer, the delay functions |
| 14 | (`udelay`, `mdelay`, `delay`), the stopwatch API (`struct stopwatch`), |
| 15 | and the timer callback mechanism. |
| 16 | |
| 17 | |
| 18 | ## Architecture Overview |
| 19 | |
| 20 | The timing facilities are layered: |
| 21 | |
| 22 | - **Platform Timer:** Hardware-specific implementations provide a raw |
| 23 | time source (e.g., LAPIC timer, Time Base register). These are often |
| 24 | abstracted by `timer_monotonic_get()`. |
| 25 | - **Monotonic Timer:** (`src/include/timer.h`, `src/lib/timer.c`) |
| 26 | Provides a consistent time source (`struct mono_time`) counting |
| 27 | microseconds since timer initialization. Requires |
| 28 | `CONFIG(HAVE_MONOTONIC_TIMER)`. |
| 29 | - **Delay Functions:** (`src/include/delay.h`, `src/lib/delay.c`, |
| 30 | `src/lib/timer.c`) Simple blocking delays (`udelay`, `mdelay`, |
| 31 | `delay`). The generic `udelay` uses the stopwatch API if yielding via |
| 32 | `thread_yield_microseconds()` is not performed. |
| 33 | - **Stopwatch API:** (`src/include/timer.h`) A lightweight wrapper |
| 34 | around the monotonic timer for measuring durations and handling |
| 35 | timeouts (`struct stopwatch`,`wait_us`,`wait_ms`). |
| 36 | - **Timer Callbacks:** (`src/include/timer.h`) Allows scheduling |
| 37 | functions to be called after a specified delay |
| 38 | (`struct timeout_callback`, `timer_sched_callback()`, `timers_run()`). |
| 39 | |
| 40 | These APIs are generally designed to be thread-safe and usable across |
| 41 | different boot stages. |
| 42 | |
| 43 | |
| 44 | ## Core Monotonic Timer |
| 45 | |
| 46 | The foundation is the monotonic timer, enabled by |
| 47 | `CONFIG(HAVE_MONOTONIC_TIMER)`. It provides a time source that |
| 48 | continuously increases from an arbitrary starting point (usually near |
| 49 | timer initialization). |
| 50 | |
| 51 | ### Data Structures |
| 52 | |
| 53 | #### struct mono_time |
| 54 | |
| 55 | ```c |
| 56 | struct mono_time { |
| 57 | uint64_t microseconds; // Time in microseconds since timer init |
| 58 | }; |
| 59 | ``` |
| 60 | Represents a point in monotonic time. Direct field access outside core |
| 61 | timer code is discouraged; use helper functions. |
| 62 | |
| 63 | ### API Functions |
| 64 | |
| 65 | #### timer_monotonic_get |
| 66 | |
| 67 | ```c |
| 68 | void timer_monotonic_get(struct mono_time *mt); |
| 69 | ``` |
| 70 | Retrieves the current monotonic time. |
| 71 | |
| 72 | **Parameters:** |
| 73 | - `mt`: Pointer to a `struct mono_time` to store the current time. |
| 74 | |
| 75 | **Preconditions:** |
| 76 | - `CONFIG(HAVE_MONOTONIC_TIMER)` must be enabled. |
| 77 | - The underlying platform timer must be functional. Platform |
| 78 | implementations may require an `init_timer()` call. |
| 79 | |
| 80 | **Postconditions:** |
| 81 | - `mt` contains the current monotonic time in microseconds. |
| 82 | |
| 83 | **Note:** If `CONFIG(HAVE_MONOTONIC_TIMER)` is *not* enabled, functions |
| 84 | relying on it (like stopwatch functions) will generally fall back to |
| 85 | basic behavior (e.g., returning 0 durations, immediate expiration |
| 86 | checks). |
| 87 | |
| 88 | #### init_timer |
| 89 | |
| 90 | ```c |
| 91 | void init_timer(void); |
| 92 | ``` |
| 93 | |
| 94 | Platform-specific timer initialization. The generic version in |
| 95 | `src/lib/timer.c` is a weak empty function |
| 96 | `__weak void init_timer(void) { /* do nothing */ }`. Platforms needing |
| 97 | explicit timer setup (e.g., configuring frequency, enabling the |
| 98 | counter) must provide their own strong implementation. Check platform |
| 99 | code (`src/cpu/`, `src/soc/`) for details. |
| 100 | |
| 101 | #### `mono_time` Helper Functions |
| 102 | |
| 103 | `src/include/timer.h` also provides several inline helper functions for |
| 104 | manipulating `struct mono_time` values: |
| 105 | - `mono_time_set_usecs()`, `mono_time_set_msecs()`: Set time. |
| 106 | - `mono_time_add_usecs()`, `mono_time_add_msecs()`: Add duration. |
| 107 | - `mono_time_cmp()`: Compare two times. |
| 108 | - `mono_time_after()`, `mono_time_before()`: Check time ordering. |
| 109 | - `mono_time_diff_microseconds()`: Calculate difference between two |
| 110 | times. |
| 111 | |
| 112 | Refer to `src/include/timer.h` for their exact definitions. |
| 113 | |
| 114 | |
| 115 | ## Delay Functions |
| 116 | |
| 117 | coreboot provides simple functions for introducing delays. |
| 118 | |
| 119 | ### udelay |
| 120 | |
| 121 | ```c |
| 122 | void udelay(unsigned int usecs); |
| 123 | ``` |
| 124 | Delays execution for *at least* the specified number of microseconds. |
| 125 | |
| 126 | **Parameters:** |
| 127 | - `usecs`: Number of microseconds to delay. |
| 128 | |
| 129 | **Implementation Notes:** |
| 130 | - The generic implementation in `src/lib/timer.c` first attempts to |
| 131 | yield using `thread_yield_microseconds()` if `CONFIG(HAS_THREADS)` is |
| 132 | enabled. If yielding handles the required delay (function returns 0), |
| 133 | `udelay` returns immediately, allowing other threads to run. |
| 134 | - If `thread_yield_microseconds()` does not handle the delay (returns |
| 135 | non-zero), or if threading is disabled, the generic `udelay` falls |
| 136 | back to a busy-wait using the stopwatch API |
| 137 | (`stopwatch_init_usecs_expire()` and |
| 138 | `stopwatch_wait_until_expired()`). |
| 139 | - Architecture-specific implementations (e.g., in `src/arch/`) may |
| 140 | override the generic one for better precision or efficiency. |
| 141 | - Adds 1 microsecond internally to ensure the delay is *at least* the |
| 142 | requested duration. |
| 143 | |
| 144 | **Preconditions:** |
| 145 | - If relying on the stopwatch fallback, |
| 146 | `CONFIG(HAVE_MONOTONIC_TIMER)` is needed. |
| 147 | - Underlying timer (if used) must be initialized (potentially via a |
| 148 | platform `init_timer()`). |
| 149 | - The delay value should be reasonable (overly large values might cause |
| 150 | issues or unexpected behavior depending on the implementation). |
| 151 | |
| 152 | **Example:** |
| 153 | ```c |
| 154 | #include <delay.h> |
| 155 | |
| 156 | // Wait for 100 microseconds |
| 157 | udelay(100); |
| 158 | ``` |
| 159 | |
| 160 | ### mdelay |
| 161 | |
| 162 | ```c |
| 163 | void mdelay(unsigned int msecs); |
| 164 | ``` |
| 165 | Delays execution for *at least* the specified number of milliseconds. |
| 166 | |
| 167 | **Parameters:** |
| 168 | - `msecs`: Number of milliseconds to delay. |
| 169 | |
| 170 | **Implementation Notes:** |
| 171 | - The generic implementation in `src/lib/delay.c` simply calls |
| 172 | `udelay(1000)` in a loop `msecs` times. |
| 173 | - Therefore, it inherits the behavior of `udelay`, including the attempt |
| 174 | to yield first if `udelay` supports it. |
| 175 | |
| 176 | **Preconditions:** |
| 177 | - Same as `udelay`. |
| 178 | |
| 179 | **Example:** |
| 180 | ```c |
| 181 | #include <delay.h> |
| 182 | |
| 183 | // Wait for 50 milliseconds |
| 184 | mdelay(50); |
| 185 | ``` |
| 186 | |
| 187 | ### delay |
| 188 | |
| 189 | ```c |
| 190 | void delay(unsigned int secs); |
| 191 | ``` |
| 192 | Delays execution for *at least* the specified number of seconds. |
| 193 | |
| 194 | **Parameters:** |
| 195 | - `secs`: Number of seconds to delay. |
| 196 | |
| 197 | **Implementation Notes:** |
| 198 | - The generic implementation in `src/lib/delay.c` simply calls |
| 199 | `mdelay(1000)` in a loop `secs` times. |
| 200 | - Inherits the behavior of `mdelay` and `udelay`. |
| 201 | |
| 202 | **Preconditions:** |
| 203 | - Same as `udelay`. |
| 204 | |
| 205 | **Example:** |
| 206 | ```c |
| 207 | #include <delay.h> |
| 208 | |
| 209 | // Wait for 2 seconds |
| 210 | delay(2); |
| 211 | ``` |
| 212 | |
| 213 | |
| 214 | ## Stopwatch API |
| 215 | |
| 216 | The stopwatch API provides a convenient way to measure time durations |
| 217 | and implement timeouts based on the monotonic timer. |
| 218 | |
| 219 | ### Data Structures |
| 220 | |
| 221 | #### struct stopwatch |
| 222 | |
| 223 | ```c |
| 224 | #include <timer.h> // For struct stopwatch and struct mono_time |
| 225 | |
| 226 | struct stopwatch { |
| 227 | struct mono_time start; // Time when stopwatch was started or initialized |
| 228 | struct mono_time current; // Time when stopwatch was last ticked |
| 229 | struct mono_time expires; // Expiration time for timeout operations |
| 230 | }; |
| 231 | ``` |
| 232 | Holds the state for a stopwatch instance. |
| 233 | |
| 234 | ### API Functions |
| 235 | |
| 236 | #### Initialization Functions |
| 237 | |
| 238 | ##### stopwatch_init |
| 239 | |
| 240 | ```c |
| 241 | #include <timer.h> |
| 242 | |
| 243 | static inline void stopwatch_init(struct stopwatch *sw); |
| 244 | ``` |
| 245 | Initializes a stopwatch structure. `start`, `current`, and `expires` are |
| 246 | all set to the current monotonic time. Use this when you only need to |
| 247 | measure elapsed duration from initialization. |
| 248 | |
| 249 | **Parameters:** |
| 250 | - `sw`: Pointer to the stopwatch structure to initialize. |
| 251 | |
| 252 | **Preconditions:** |
| 253 | - `sw` must point to valid memory. |
| 254 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled for meaningful |
| 255 | timing. |
| 256 | |
| 257 | **Postconditions:** |
| 258 | - The stopwatch is initialized. |
| 259 | |
| 260 | |
| 261 | ##### stopwatch_init_usecs_expire |
| 262 | |
| 263 | ```c |
| 264 | #include <timer.h> |
| 265 | |
| 266 | static inline void stopwatch_init_usecs_expire(struct stopwatch *sw, uint64_t us); |
| 267 | ``` |
| 268 | Initializes a stopwatch and sets an expiration time `us` microseconds |
| 269 | from now. |
| 270 | |
| 271 | **Parameters:** |
| 272 | - `sw`: Pointer to the stopwatch structure. |
| 273 | - `us`: Timeout duration in microseconds. |
| 274 | |
| 275 | **Preconditions:** |
| 276 | - `sw` must point to valid memory. |
| 277 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 278 | |
| 279 | **Postconditions:** |
| 280 | - The stopwatch is initialized, and `expires` is set `us` microseconds |
| 281 | after `start`. |
| 282 | |
| 283 | |
| 284 | ##### stopwatch_init_msecs_expire |
| 285 | |
| 286 | ```c |
| 287 | #include <timer.h> |
| 288 | |
| 289 | static inline void stopwatch_init_msecs_expire(struct stopwatch *sw, uint64_t ms); |
| 290 | ``` |
| 291 | Initializes a stopwatch and sets an expiration time `ms` milliseconds |
| 292 | from now. |
| 293 | |
| 294 | **Parameters:** |
| 295 | - `sw`: Pointer to the stopwatch structure. |
| 296 | - `ms`: Timeout duration in milliseconds. |
| 297 | |
| 298 | **Preconditions:** |
| 299 | - `sw` must point to valid memory. |
| 300 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 301 | |
| 302 | **Postconditions:** |
| 303 | - The stopwatch is initialized, and `expires` is set `ms` milliseconds |
| 304 | after `start`. |
| 305 | |
| 306 | |
| 307 | #### Time Measurement Functions |
| 308 | |
| 309 | ##### stopwatch_tick |
| 310 | |
| 311 | ```c |
| 312 | #include <timer.h> |
| 313 | |
| 314 | static inline void stopwatch_tick(struct stopwatch *sw); |
| 315 | ``` |
| 316 | Updates the `current` time field in the stopwatch structure to the |
| 317 | current monotonic time. This is often called implicitly by other |
| 318 | stopwatch functions like `stopwatch_expired()` and |
| 319 | `stopwatch_duration_usecs()`. |
| 320 | |
| 321 | **Parameters:** |
| 322 | - `sw`: Pointer to the stopwatch structure. |
| 323 | |
| 324 | **Preconditions:** |
| 325 | - The stopwatch must be initialized. |
| 326 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 327 | |
| 328 | |
| 329 | ##### stopwatch_expired |
| 330 | |
| 331 | ```c |
| 332 | #include <timer.h> |
| 333 | |
| 334 | static inline int stopwatch_expired(struct stopwatch *sw); |
| 335 | ``` |
| 336 | Checks if the stopwatch's expiration time (`expires`) has passed. It |
| 337 | implicitly calls `stopwatch_tick()` to get the current time for |
| 338 | comparison. |
| 339 | |
| 340 | **Parameters:** |
| 341 | - `sw`: Pointer to the stopwatch structure. |
| 342 | |
| 343 | **Returns:** |
| 344 | - Non-zero (true) if `current` time >= `expires` time. |
| 345 | - Zero (false) otherwise. |
| 346 | |
| 347 | **Preconditions:** |
| 348 | - The stopwatch must be initialized (preferably with an expiration |
| 349 | time). |
| 350 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 351 | |
| 352 | |
| 353 | ##### stopwatch_wait_until_expired |
| 354 | |
| 355 | ```c |
| 356 | #include <timer.h> |
| 357 | |
| 358 | static inline void stopwatch_wait_until_expired(struct stopwatch *sw); |
| 359 | ``` |
| 360 | Blocks (busy-waits) until the stopwatch expires by repeatedly calling |
| 361 | `stopwatch_expired()`. |
| 362 | |
| 363 | **Parameters:** |
| 364 | - `sw`: Pointer to the stopwatch structure. |
| 365 | |
| 366 | **Preconditions:** |
| 367 | - The stopwatch must be initialized with an expiration time. |
| 368 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 369 | |
| 370 | **Postconditions:** |
| 371 | - The function returns only after the stopwatch has expired. |
| 372 | |
| 373 | |
| 374 | #### Duration Measurement Functions |
| 375 | |
| 376 | ##### stopwatch_duration_usecs |
| 377 | |
| 378 | ```c |
| 379 | #include <timer.h> |
| 380 | |
| 381 | static inline int64_t stopwatch_duration_usecs(struct stopwatch *sw); |
| 382 | ``` |
| 383 | Returns the elapsed time in microseconds between `start` and `current`. |
| 384 | If `current` hasn't been updated since `stopwatch_init`, it implicitly |
| 385 | calls `stopwatch_tick()` first. |
| 386 | |
| 387 | **Parameters:** |
| 388 | - `sw`: Pointer to the stopwatch structure. |
| 389 | |
| 390 | **Returns:** |
| 391 | - Elapsed time in microseconds (`current` - `start`). |
| 392 | |
| 393 | **Preconditions:** |
| 394 | - The stopwatch must be initialized. |
| 395 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled for a meaningful |
| 396 | duration. |
| 397 | |
| 398 | |
| 399 | ##### stopwatch_duration_msecs |
| 400 | |
| 401 | ```c |
| 402 | #include <timer.h> |
| 403 | |
| 404 | static inline int64_t stopwatch_duration_msecs(struct stopwatch *sw); |
| 405 | ``` |
| 406 | Returns the elapsed time in milliseconds since the stopwatch was |
| 407 | started. It calls `stopwatch_duration_usecs()` and divides by 1000. |
| 408 | |
| 409 | **Parameters:** |
| 410 | - `sw`: Pointer to the stopwatch structure. |
| 411 | |
| 412 | **Returns:** |
| 413 | - Elapsed time in milliseconds. |
| 414 | |
| 415 | **Preconditions:** |
| 416 | - The stopwatch must be initialized. |
| 417 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 418 | |
| 419 | |
| 420 | ### Utility Macros |
| 421 | |
| 422 | These macros combine stopwatch initialization and expiration checking with |
| 423 | a user-provided condition. |
| 424 | |
| 425 | #### wait_us |
| 426 | |
| 427 | ```c |
| 428 | #include <timer.h> |
| 429 | |
| 430 | #define wait_us(timeout_us, condition) ... |
| 431 | ``` |
| 432 | Waits until a condition becomes true or a timeout elapses, whichever |
| 433 | comes first. Internally uses a `struct stopwatch`. |
| 434 | |
| 435 | **Parameters:** |
| 436 | - `timeout_us`: Timeout duration in microseconds. |
| 437 | - `condition`: A C expression that evaluates to true or false. The loop |
| 438 | continues as long as the condition is false and the timeout has not |
| 439 | expired. |
| 440 | |
| 441 | **Returns:** |
| 442 | - 0: If the condition was still false when the timeout expired. |
| 443 | - >0: If the condition became true before the timeout. The return value |
| 444 | is the approximate number of microseconds waited (at least 1). |
| 445 | |
| 446 | **Preconditions:** |
| 447 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 448 | |
| 449 | |
| 450 | #### wait_ms |
| 451 | |
| 452 | ```c |
| 453 | #include <timer.h> |
| 454 | |
| 455 | #define wait_ms(timeout_ms, condition) ... |
| 456 | ``` |
| 457 | Similar to `wait_us`, but the timeout is specified in milliseconds. |
| 458 | |
| 459 | **Parameters:** |
| 460 | - `timeout_ms`: Timeout duration in milliseconds. |
| 461 | - `condition`: C expression to wait for. |
| 462 | |
| 463 | **Returns:** |
| 464 | - 0: If the condition was still false after the timeout. |
| 465 | - >0: If the condition became true before the timeout. The return value |
| 466 | is the approximate number of milliseconds waited (rounded up, at |
| 467 | least 1). |
| 468 | |
| 469 | **Preconditions:** |
| 470 | - `CONFIG(HAVE_MONOTONIC_TIMER)` should be enabled. |
| 471 | |
| 472 | |
| 473 | ## Key differences between `mdelay` and `wait_ms` |
| 474 | |
| 475 | While both can be used to wait, they serve different purposes: |
| 476 | |
| 477 | ### Purpose and Use Case |
| 478 | |
| 479 | - `mdelay`: Provides an *unconditional* delay for a fixed duration. The |
| 480 | generic implementation attempts to yield to other threads first (if |
| 481 | `CONFIG(HAS_THREADS)` is enabled via `udelay`), but it always waits |
| 482 | for (at least) the specified time, potentially using a busy-wait if |
| 483 | yielding doesn't occur. Primarily used for hardware timing |
| 484 | requirements or pacing operations. |
| 485 | |
| 486 | - `wait_ms`: Provides a *conditional* wait. It waits for a specific C |
| 487 | expression (`condition`) to become true, but *only up to* a maximum |
| 488 | timeout duration. Used when polling for a status change or event, with |
| 489 | a safeguard against waiting indefinitely. |
| 490 | |
| 491 | ### When to Use Which |
| 492 | |
| 493 | #### Use `mdelay` when: |
| 494 | |
| 495 | - You need a guaranteed minimum delay (e.g., waiting for hardware to |
| 496 | settle after a register write). |
| 497 | - You are implementing a hardware initialization sequence with specific |
| 498 | timing requirements between steps. |
| 499 | - You want a simple pause, potentially allowing other threads to run if |
| 500 | the underlying `udelay` yields. |
| 501 | |
| 502 | **Example:** |
| 503 | ```c |
| 504 | #include <delay.h> |
| 505 | #include <arch/io.h> // For write_reg hypothetical function |
| 506 | |
| 507 | // Initialize hardware with specific timing requirements |
| 508 | write_reg(REG_A, value); |
| 509 | mdelay(10); // Must wait (at least) 10ms after writing REG_A |
| 510 | write_reg(REG_B, another_value); |
| 511 | ``` |
| 512 | |
| 513 | #### Use `wait_ms` when: |
| 514 | |
| 515 | - You are waiting for a hardware status bit to change or a condition to |
| 516 | become true. |
| 517 | - You need to implement a timeout for an operation that might fail or |
| 518 | take too long. |
| 519 | - You want to know approximately how long you waited for the condition |
| 520 | to become true (via the return value). |
| 521 | |
| 522 | **Example:** |
| 523 | ```c |
| 524 | #include <timer.h> |
| 525 | #include <console/console.h> |
| 526 | #include <arch/io.h> // For read_reg hypothetical function |
| 527 | |
| 528 | // Wait for hardware to become ready, but not forever |
| 529 | #define STATUS_REG 0x100 |
| 530 | #define READY_BIT (1 << 0) |
| 531 | int64_t waited_ms = wait_ms(100, (read_reg(STATUS_REG) & READY_BIT)); |
| 532 | |
| 533 | if (waited_ms > 0) { |
| 534 | printk(BIOS_INFO, "Hardware ready after ~%lld ms\n", waited_ms); |
| 535 | } else { |
| 536 | printk(BIOS_ERR, "Timeout: Hardware failed to become ready within 100 ms\n"); |
| 537 | } |
| 538 | ``` |
| 539 | |
| 540 | ### Performance Considerations |
| 541 | |
| 542 | - `mdelay`: Generally simpler if the underlying `udelay` performs a |
| 543 | busy-wait. If it yields (`thread_yield_microseconds`), overhead depends |
| 544 | on the scheduler. Always waits for the full duration (approximately). |
| 545 | - `wait_ms`: Involves repeated condition checking and stopwatch |
| 546 | management (`stopwatch_expired`, which calls `timer_monotonic_get`), |
| 547 | adding overhead within the loop. However, it can return early if the |
| 548 | condition becomes true, potentially saving time compared to a fixed |
| 549 | `mdelay`. |
| 550 | |
| 551 | ### Error Handling / Feedback |
| 552 | |
| 553 | - `mdelay`: Provides no feedback. It simply waits. |
| 554 | - `wait_ms`: Returns whether the condition was met within the timeout |
| 555 | and provides the approximate wait time if successful. This allows for |
| 556 | explicit timeout handling. |
| 557 | |
| 558 | ### Summary |
| 559 | |
| 560 | Use `mdelay` for fixed, unconditional delays, potentially allowing |
| 561 | thread yielding. Use `wait_ms` for conditional waits with a timeout and |
| 562 | feedback on success or failure. Choose based on whether you need to poll |
| 563 | for a condition or simply need to pause execution. |
| 564 | |
| 565 | |
| 566 | ## Timer Callbacks |
| 567 | |
| 568 | coreboot provides a mechanism to schedule functions (callbacks) to be |
| 569 | executed after a certain time has elapsed. This requires |
| 570 | `CONFIG(TIMER_QUEUE)`. |
| 571 | |
| 572 | ### Data Structures |
| 573 | |
| 574 | #### struct timeout_callback |
| 575 | |
| 576 | ```c |
| 577 | #include <timer.h> |
| 578 | |
| 579 | struct timeout_callback { |
| 580 | void *priv; // Private data for the callback |
| 581 | void (*callback)(struct timeout_callback *tocb); // Function to call |
| 582 | /* Internal use by timer library: */ |
| 583 | struct mono_time expiration; // Calculated expiration time |
| 584 | }; |
| 585 | ``` |
| 586 | |
| 587 | Represents a scheduled callback. The user initializes `priv` and |
| 588 | `callback`. |
| 589 | |
| 590 | ### API Functions |
| 591 | |
| 592 | #### timer_sched_callback |
| 593 | |
| 594 | ```c |
| 595 | #include <timer.h> |
| 596 | |
| 597 | int timer_sched_callback(struct timeout_callback *tocb, uint64_t us); |
| 598 | ``` |
| 599 | Schedules a callback function to run after a specified delay. |
| 600 | |
| 601 | **Parameters:** |
| 602 | - `tocb`: Pointer to a `struct timeout_callback`. The `priv` and |
| 603 | `callback` fields must be set by the caller. The structure must |
| 604 | persist until the callback runs or is canceled (cancellation not |
| 605 | directly supported by API). |
| 606 | - `us`: Delay in microseconds from the time of this call until the |
| 607 | callback should run. |
| 608 | |
| 609 | **Returns:** |
| 610 | - 0: Success. |
| 611 | - <0: Error (e.g., timer queue full, invalid arguments). |
| 612 | |
| 613 | **Preconditions:** |
| 614 | - `CONFIG(TIMER_QUEUE)` and `CONFIG(HAVE_MONOTONIC_TIMER)` must be |
| 615 | enabled. |
| 616 | - `tocb` must point to a valid structure with `callback` assigned. |
| 617 | |
| 618 | **Postconditions:** |
| 619 | - The callback is added to a queue, to be executed when `timers_run()` |
| 620 | is called after the expiration time. |
| 621 | |
| 622 | |
| 623 | #### timers_run |
| 624 | |
| 625 | ```c |
| 626 | #include <timer.h> |
| 627 | |
| 628 | int timers_run(void); |
| 629 | ``` |
| 630 | |
| 631 | Checks the timer callback queue and executes any callbacks whose |
| 632 | expiration time has passed. This function needs to be called |
| 633 | periodically from the main execution flow (e.g., in a boot state loop |
| 634 | or idle task) for callbacks to be processed. |
| 635 | |
| 636 | **Returns:** |
| 637 | - 1: If callbacks were run or are still pending in the queue. |
| 638 | - 0: If the queue is empty and no callbacks were run. |
| 639 | |
| 640 | **Preconditions:** |
| 641 | - `CONFIG(TIMER_QUEUE)` and `CONFIG(HAVE_MONOTONIC_TIMER)` must be |
| 642 | enabled. |
| 643 | |
| 644 | **Usage:** |
| 645 | Typically called in loops where deferred work might need processing: |
| 646 | ```c |
| 647 | #include <timer.h> |
| 648 | |
| 649 | // Example main loop structure |
| 650 | while (some_condition) { |
| 651 | // ... do other work ... |
| 652 | |
| 653 | // Process any expired timer callbacks |
| 654 | timers_run(); |
| 655 | |
| 656 | // ... potentially yield or sleep ... |
| 657 | } |
| 658 | ``` |
| 659 | |
| 660 | |
| 661 | ## Usage Examples |
| 662 | |
| 663 | ### Basic Timing Measurement Example |
| 664 | |
| 665 | ```c |
| 666 | #include <timer.h> |
| 667 | #include <console/console.h> |
| 668 | |
| 669 | struct stopwatch sw; |
| 670 | stopwatch_init(&sw); |
| 671 | |
| 672 | // ---> Code section to measure start |
| 673 | // ... perform some operations ... |
| 674 | // ---> Code section to measure end |
| 675 | |
| 676 | // stopwatch_duration_usecs implicitly ticks the stopwatch if needed |
| 677 | int64_t duration_us = stopwatch_duration_usecs(&sw); |
| 678 | printk(BIOS_INFO, "Operation took %lld microseconds\n", duration_us); |
| 679 | |
| 680 | // Or in milliseconds |
| 681 | int64_t duration_ms = stopwatch_duration_msecs(&sw); |
| 682 | printk(BIOS_INFO, "Operation took %lld milliseconds\n", duration_ms); |
| 683 | ``` |
| 684 | |
| 685 | |
| 686 | ### Timeout Operation (Polling) Example |
| 687 | |
| 688 | ```c |
| 689 | #include <timer.h> |
| 690 | #include <console/console.h> |
| 691 | #include <stdint.h> // For uint8_t example |
| 692 | |
| 693 | // Hypothetical hardware status check |
| 694 | extern uint8_t check_hardware_status(void); |
| 695 | #define HW_READY (1 << 0) |
| 696 | |
| 697 | struct stopwatch sw; |
| 698 | // Initialize stopwatch with a 100 millisecond timeout |
| 699 | stopwatch_init_msecs_expire(&sw, 100); |
| 700 | |
| 701 | uint8_t status = 0; |
| 702 | while (!(status & HW_READY)) { |
| 703 | status = check_hardware_status(); |
| 704 | |
| 705 | if (stopwatch_expired(&sw)) { |
| 706 | printk(BIOS_ERR, "Operation timed out waiting for HW_READY\n"); |
| 707 | // Handle timeout error... |
| 708 | status = 0; // Indicate failure perhaps |
| 709 | break; |
| 710 | } |
| 711 | // Optional: Add a small delay here to avoid busy-spinning the CPU excessively |
| 712 | // udelay(10); // e.g., wait 10us between checks |
| 713 | } |
| 714 | |
| 715 | if (status & HW_READY) { |
| 716 | printk(BIOS_DEBUG, "Hardware became ready.\n"); |
| 717 | // Continue with operation... |
| 718 | } |
| 719 | ``` |
| 720 | |
| 721 | |
| 722 | ### Waiting for a Condition (Using `wait_ms`) Example |
| 723 | |
| 724 | ```c |
| 725 | #include <timer.h> |
| 726 | #include <console/console.h> |
| 727 | #include <stdint.h> // For uint8_t example |
| 728 | |
| 729 | // Hypothetical hardware status check |
| 730 | extern uint8_t check_hardware_status(void); |
| 731 | #define HW_READY (1 << 0) |
| 732 | |
| 733 | // Wait up to 100ms for the HW_READY bit |
| 734 | int64_t waited_ms = wait_ms(100, (check_hardware_status() & HW_READY)); |
| 735 | |
| 736 | if (waited_ms > 0) { |
| 737 | printk(BIOS_INFO, "Condition met: HW_READY asserted after ~%lld ms\n", waited_ms); |
| 738 | // Continue... |
| 739 | } else { |
| 740 | printk(BIOS_ERR, "Timeout: HW_READY not asserted within 100 ms\n"); |
| 741 | // Handle timeout error... |
| 742 | } |
| 743 | ``` |
| 744 | |
| 745 | ### Scheduling a Timer Callback Example |
| 746 | |
| 747 | ```c |
| 748 | #include <timer.h> |
| 749 | #include <console/console.h> |
| 750 | |
| 751 | // Data structure for our callback context |
| 752 | struct my_callback_data { |
| 753 | int counter; |
| 754 | const char *message; |
| 755 | }; |
| 756 | |
| 757 | // The callback function |
| 758 | static void my_callback_handler(struct timeout_callback *tocb) |
| 759 | { |
| 760 | struct my_callback_data *data = tocb->priv; |
| 761 | printk(BIOS_INFO, "Callback executed! Message: %s, Counter: %d\n", |
| 762 | data->message, data->counter); |
| 763 | // Note: 'tocb' can be reused here to reschedule if needed, |
| 764 | // or the memory it points to can be freed if dynamically allocated. |
| 765 | } |
| 766 | |
| 767 | // Somewhere in initialization code: |
| 768 | static struct timeout_callback my_timer; |
| 769 | static struct my_callback_data my_data; |
| 770 | |
| 771 | void schedule_my_task(void) |
| 772 | { |
| 773 | my_data.counter = 42; |
| 774 | my_data.message = "Hello from timer"; |
| 775 | |
| 776 | my_timer.priv = &my_data; |
| 777 | my_timer.callback = my_callback_handler; |
| 778 | |
| 779 | // Schedule the callback to run after 500 milliseconds (500,000 us) |
| 780 | int rc = timer_sched_callback(&my_timer, 500 * 1000); |
| 781 | if (rc == 0) { |
| 782 | printk(BIOS_DEBUG, "Scheduled my_callback_handler successfully.\n"); |
| 783 | } else { |
| 784 | printk(BIOS_ERR, "Failed to schedule callback!\n"); |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | // Remember that timers_run() must be called periodically elsewhere |
| 789 | // for the callback to actually execute after the delay. |
| 790 | ``` |
| 791 | |
| 792 | ## Best Practices |
| 793 | |
| 794 | 1. **Enable Monotonic Timer:** For accurate timing and stopwatch |
| 795 | functionality, ensure `CONFIG(HAVE_MONOTONIC_TIMER)` is enabled and a |
| 796 | suitable platform timer is configured. |
| 797 | 2. **Minimize Stopwatch Overhead:** While lightweight, frequent calls, |
| 798 | especially `timer_monotonic_get()` implicitly called by stopwatch |
| 799 | functions, can add up. Measure larger, significant code blocks rather |
| 800 | than tiny ones in tight loops unless absolutely necessary. |
| 801 | 3. **Use Appropriate Time Units:** Choose `usecs` or `msecs` variants |
| 802 | based on the scale of time you are dealing with. |
| 803 | 4. **Handle Timeouts Gracefully:** When using expiration or |
| 804 | `wait_ms`/`wait_us`, always check the result and handle the timeout |
| 805 | case appropriately. Don't assume success. |
| 806 | 5. **Process Timer Callbacks:** If using `timer_sched_callback`, ensure |
| 807 | `timers_run()` is called regularly in your main processing loops or |
| 808 | idle states. |
| 809 | 6. **Avoid `mdelay` for Polling:** Prefer `wait_ms` or manual polling |
| 810 | with `stopwatch_expired` when waiting for conditions, as `mdelay` |
| 811 | offers no timeout handling or feedback. |
| 812 | 7. **Consider Platform Accuracy:** Timer resolution and accuracy vary |
| 813 | between platforms. Don't assume microsecond precision unless verified |
| 814 | for the target hardware. |
| 815 | |
| 816 | |
| 817 | ## Limitations |
| 818 | |
| 819 | 1. **Monotonic Timer Dependence:** Stopwatch and timer callbacks rely |
| 820 | heavily on `CONFIG(HAVE_MONOTONIC_TIMER)`. Without it, their |
| 821 | behavior is limited. |
| 822 | 2. **Timer Resolution:** Accuracy is limited by the underlying platform |
| 823 | timer's resolution and the frequency of `timer_monotonic_get()` |
| 824 | updates internally. |
| 825 | 3. **64-bit Microsecond Counter:** While large, the |
| 826 | `uint64_t microseconds` counter will eventually wrap around |
| 827 | (after ~584,000 years), though this is not a practical concern for |
| 828 | boot times. More relevant is the potential rollover of the |
| 829 | *underlying hardware counter* between `timer_monotonic_get` calls, |
| 830 | which the implementation must handle correctly (typically ok for |
| 831 | intervals up to several seconds). |
| 832 | 4. **Busy Waiting:** `stopwatch_wait_until_expired` and the internal |
| 833 | loops of `wait_us`/`wait_ms` (and potentially the fallback in |
| 834 | `udelay`/`mdelay`) perform busy-waits, consuming CPU cycles. Consider |
| 835 | alternatives like interrupt-driven timers or yielding |
| 836 | (`thread_yield_microseconds`) if power consumption or concurrency is |
| 837 | critical. |
| 838 | 5. **Callback Queue Size:** The timer callback queue has a fixed size |
| 839 | defined by `CONFIG(TIMER_QUEUE_SIZE)`, limiting the number of pending |
| 840 | callbacks. |
| 841 | |
| 842 | |
| 843 | ## Troubleshooting |
| 844 | |
| 845 | Common issues and solutions: |
| 846 | |
| 847 | 1. **Inaccurate Timing / Durations are Zero:** |
| 848 | - Verify `CONFIG(HAVE_MONOTONIC_TIMER)` is enabled. |
| 849 | - Check if a platform-specific `init_timer()` is required and being |
| 850 | called. |
| 851 | - Ensure the platform timer frequency is correctly configured. |
| 852 | - Check for potential timer hardware issues or conflicts. |
| 853 | |
| 854 | 2. **Timeouts Not Working / `wait_ms` Never Returns > 0:** |
| 855 | - Verify the timeout value is appropriate (not too short). |
| 856 | - Double-check the `condition` logic in `wait_ms`/`wait_us`. Is it |
| 857 | actually capable of becoming true? |
| 858 | - Ensure the stopwatch (`sw` or the internal one in `wait_ms`) is |
| 859 | properly initialized before the check loop. |
| 860 | - Confirm `CONFIG(HAVE_MONOTONIC_TIMER)` is enabled. |
| 861 | |
| 862 | 3. **Timer Callbacks Not Running:** |
| 863 | - Verify `CONFIG(TIMER_QUEUE)` is enabled. |
| 864 | - Ensure `timer_sched_callback()` returned success (0). |
| 865 | - **Crucially:** Check that `timers_run()` is being called |
| 866 | periodically in a suitable loop after the callback was scheduled. |
| 867 | - Make sure the `struct timeout_callback` structure persists in memory |
| 868 | until the callback runs. |
| 869 | |
| 870 | 4. **Performance Impact:** |
| 871 | - Reduce frequency of stopwatch checks or `wait_ms`/`wait_us` calls if |
| 872 | possible. |
| 873 | - Measure larger code blocks. |
| 874 | - Investigate if the underlying `udelay` implementation is |
| 875 | busy-waiting excessively; yielding (`thread_yield_microseconds`) |
| 876 | might be preferable if available and appropriate. |
| 877 | |
| 878 | |
| 879 | ## Platform-Specific Considerations |
| 880 | |
| 881 | The core APIs are generic, but the underlying implementation relies on |
| 882 | platform code: |
| 883 | - **Timer Source:** Platforms implement `timer_monotonic_get` (often |
| 884 | weakly linked) or provide the necessary hooks for it, using hardware |
| 885 | like the APIC timer (x86), Time Base (PPC), architectural timers |
| 886 | (ARM), etc. |
| 887 | - **`init_timer()`:** Platforms may need a custom `init_timer` to set up |
| 888 | clocks, dividers, or enable the timer hardware. |
| 889 | - **`udelay`:** Platforms might provide optimized `udelay` |
| 890 | implementations. |
| 891 | |
| 892 | Refer to the documentation and code within specific `src/soc/`, |
| 893 | `src/cpu/`, or `src/arch/` directories for platform details. |
| 894 | |
| 895 | |
| 896 | ## References |
| 897 | |
| 898 | - `src/include/timer.h`: Monotonic timer, stopwatch, and callback |
| 899 | declarations. |
| 900 | - `src/include/delay.h`: `udelay`, `mdelay`, `delay` declarations. |
| 901 | - `src/lib/timer.c`: Generic `udelay` (using stopwatch/yield), weak |
| 902 | `init_timer`. |
| 903 | - `src/lib/delay.c`: Generic `mdelay` and `delay` implementations |
| 904 | (calling `udelay`). |
| 905 | - `src/lib/hardwaremain.c`: Example usage of `timers_run()` in boot |
| 906 | state machine. |
| 907 | - Platform timer implementations: Search for `timer_monotonic_get` or |
| 908 | `init_timer` in `src/cpu/`, `src/soc/`, `src/arch/` directories |
| 909 | (e.g., `src/cpu/x86/lapic/apic_timer.c`, |
| 910 | `src/arch/arm64/timer.c`). |