xref: /linux/rust/kernel/time.rs (revision d7bf4786b5250b0e490a937d1f8a16ee3a54adbe)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Time related primitives.
4 //!
5 //! This module contains the kernel APIs related to time and timers that
6 //! have been ported or wrapped for usage by Rust code in the kernel.
7 //!
8 //! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h).
9 //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h).
10 
11 pub mod hrtimer;
12 
13 /// The number of nanoseconds per millisecond.
14 pub const NSEC_PER_MSEC: i64 = bindings::NSEC_PER_MSEC as i64;
15 
16 /// The time unit of Linux kernel. One jiffy equals (1/HZ) second.
17 pub type Jiffies = crate::ffi::c_ulong;
18 
19 /// The millisecond time unit.
20 pub type Msecs = crate::ffi::c_uint;
21 
22 /// Converts milliseconds to jiffies.
23 #[inline]
24 pub fn msecs_to_jiffies(msecs: Msecs) -> Jiffies {
25     // SAFETY: The `__msecs_to_jiffies` function is always safe to call no
26     // matter what the argument is.
27     unsafe { bindings::__msecs_to_jiffies(msecs) }
28 }
29 
30 /// A Rust wrapper around a `ktime_t`.
31 #[repr(transparent)]
32 #[derive(Copy, Clone)]
33 pub struct Ktime {
34     inner: bindings::ktime_t,
35 }
36 
37 impl Ktime {
38     /// Create a `Ktime` from a raw `ktime_t`.
39     #[inline]
40     pub fn from_raw(inner: bindings::ktime_t) -> Self {
41         Self { inner }
42     }
43 
44     /// Get the current time using `CLOCK_MONOTONIC`.
45     #[inline]
46     pub fn ktime_get() -> Self {
47         // SAFETY: It is always safe to call `ktime_get` outside of NMI context.
48         Self::from_raw(unsafe { bindings::ktime_get() })
49     }
50 
51     /// Divide the number of nanoseconds by a compile-time constant.
52     #[inline]
53     fn divns_constant<const DIV: i64>(self) -> i64 {
54         self.to_ns() / DIV
55     }
56 
57     /// Returns the number of nanoseconds.
58     #[inline]
59     pub fn to_ns(self) -> i64 {
60         self.inner
61     }
62 
63     /// Returns the number of milliseconds.
64     #[inline]
65     pub fn to_ms(self) -> i64 {
66         self.divns_constant::<NSEC_PER_MSEC>()
67     }
68 }
69 
70 /// Returns the number of milliseconds between two ktimes.
71 #[inline]
72 pub fn ktime_ms_delta(later: Ktime, earlier: Ktime) -> i64 {
73     (later - earlier).to_ms()
74 }
75 
76 impl core::ops::Sub for Ktime {
77     type Output = Ktime;
78 
79     #[inline]
80     fn sub(self, other: Ktime) -> Ktime {
81         Self {
82             inner: self.inner - other.inner,
83         }
84     }
85 }
86