ostd/timer/
jiffies.rs

1// SPDX-License-Identifier: MPL-2.0
2
3use core::{
4    sync::atomic::{AtomicU64, Ordering},
5    time::Duration,
6};
7
8use super::TIMER_FREQ;
9
10/// Jiffies is a term used to denote the units of time measurement by the kernel.
11///
12/// A jiffy represents one tick of the system timer interrupt,
13/// whose frequency is equal to [`TIMER_FREQ`] Hz.
14#[derive(Copy, Clone, Debug)]
15pub struct Jiffies(u64);
16
17pub(crate) static ELAPSED: AtomicU64 = AtomicU64::new(0);
18
19impl Jiffies {
20    /// The maximum value of [`Jiffies`].
21    pub const MAX: Self = Self(u64::MAX);
22
23    /// Creates a new instance.
24    pub fn new(value: u64) -> Self {
25        Self(value)
26    }
27
28    /// Returns the elapsed time since the system boots up.
29    pub fn elapsed() -> Self {
30        Self::new(ELAPSED.load(Ordering::Relaxed))
31    }
32
33    /// Gets the number of jiffies.
34    pub fn as_u64(self) -> u64 {
35        self.0
36    }
37
38    /// Adds the given number of jiffies, saturating at [`Jiffies::MAX`] on overflow.
39    pub fn add(&mut self, jiffies: u64) {
40        self.0 = self.0.saturating_add(jiffies);
41    }
42
43    /// Gets the [`Duration`] calculated from the jiffies counts.
44    pub fn as_duration(self) -> Duration {
45        let secs = self.0 / TIMER_FREQ;
46        let nanos = ((self.0 % TIMER_FREQ) * 1_000_000_000) / TIMER_FREQ;
47        Duration::new(secs, nanos as u32)
48    }
49}
50
51impl From<Jiffies> for Duration {
52    fn from(value: Jiffies) -> Self {
53        value.as_duration()
54    }
55}