1 // SPDX-License-Identifier: GPL-2.0
3 //! Time related primitives.
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.
8 //! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h).
9 //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h).
11 /// The number of nanoseconds per millisecond.
12 pub const NSEC_PER_MSEC: i64 = bindings::NSEC_PER_MSEC as i64;
14 /// The time unit of Linux kernel. One jiffy equals (1/HZ) second.
15 pub type Jiffies = core::ffi::c_ulong;
17 /// The millisecond time unit.
18 pub type Msecs = core::ffi::c_uint;
20 /// Converts milliseconds to jiffies.
22 pub fn msecs_to_jiffies(msecs: Msecs) -> Jiffies {
23 // SAFETY: The `__msecs_to_jiffies` function is always safe to call no
24 // matter what the argument is.
25 unsafe { bindings::__msecs_to_jiffies(msecs) }
28 /// A Rust wrapper around a `ktime_t`.
30 #[derive(Copy, Clone)]
32 inner: bindings::ktime_t,
36 /// Create a `Ktime` from a raw `ktime_t`.
38 pub fn from_raw(inner: bindings::ktime_t) -> Self {
42 /// Get the current time using `CLOCK_MONOTONIC`.
44 pub fn ktime_get() -> Self {
45 // SAFETY: It is always safe to call `ktime_get` outside of NMI context.
46 Self::from_raw(unsafe { bindings::ktime_get() })
49 /// Divide the number of nanoseconds by a compile-time constant.
51 fn divns_constant<const DIV: i64>(self) -> i64 {
55 /// Returns the number of nanoseconds.
57 pub fn to_ns(self) -> i64 {
61 /// Returns the number of milliseconds.
63 pub fn to_ms(self) -> i64 {
64 self.divns_constant::<NSEC_PER_MSEC>()
68 /// Returns the number of milliseconds between two ktimes.
70 pub fn ktime_ms_delta(later: Ktime, earlier: Ktime) -> i64 {
71 (later - earlier).to_ms()
74 impl core::ops::Sub for Ktime {
78 fn sub(self, other: Ktime) -> Ktime {
80 inner: self.inner - other.inner,