axplat/time.rs
1//! Time-related operations.
2
3pub use core::time::Duration;
4
5/// A measurement of the system clock.
6///
7/// Currently, it reuses the [`core::time::Duration`] type. But it does not
8/// represent a duration, but a clock time.
9pub type TimeValue = Duration;
10
11/// Number of milliseconds in a second.
12pub const MILLIS_PER_SEC: u64 = 1_000;
13/// Number of microseconds in a second.
14pub const MICROS_PER_SEC: u64 = 1_000_000;
15/// Number of nanoseconds in a second.
16pub const NANOS_PER_SEC: u64 = 1_000_000_000;
17/// Number of nanoseconds in a millisecond.
18pub const NANOS_PER_MILLIS: u64 = 1_000_000;
19/// Number of nanoseconds in a microsecond.
20pub const NANOS_PER_MICROS: u64 = 1_000;
21
22/// Time-related interfaces.
23#[def_plat_interface]
24pub trait TimeIf {
25 /// Returns the current clock time in hardware ticks.
26 fn current_ticks() -> u64;
27
28 /// Converts hardware ticks to nanoseconds.
29 fn ticks_to_nanos(ticks: u64) -> u64;
30
31 /// Converts nanoseconds to hardware ticks.
32 fn nanos_to_ticks(nanos: u64) -> u64;
33
34 /// Return epoch offset in nanoseconds (wall time offset to monotonic
35 /// clock start).
36 fn epochoffset_nanos() -> u64;
37
38 /// Set a one-shot timer.
39 ///
40 /// A timer interrupt will be triggered at the specified monotonic time
41 /// deadline (in nanoseconds).
42 #[cfg(feature = "irq")]
43 fn set_oneshot_timer(deadline_ns: u64);
44}
45
46/// Returns nanoseconds elapsed since system boot.
47pub fn monotonic_time_nanos() -> u64 {
48 ticks_to_nanos(current_ticks())
49}
50
51/// Returns the time elapsed since system boot in [`TimeValue`].
52pub fn monotonic_time() -> TimeValue {
53 TimeValue::from_nanos(monotonic_time_nanos())
54}
55
56/// Returns nanoseconds elapsed since epoch (also known as realtime).
57pub fn wall_time_nanos() -> u64 {
58 monotonic_time_nanos() + epochoffset_nanos()
59}
60
61/// Returns the time elapsed since epoch (also known as realtime) in [`TimeValue`].
62pub fn wall_time() -> TimeValue {
63 TimeValue::from_nanos(monotonic_time_nanos() + epochoffset_nanos())
64}
65
66/// Busy waiting for the given duration.
67pub fn busy_wait(dur: Duration) {
68 busy_wait_until(wall_time() + dur);
69}
70
71/// Busy waiting until reaching the given deadline.
72pub fn busy_wait_until(deadline: TimeValue) {
73 while wall_time() < deadline {
74 core::hint::spin_loop();
75 }
76}