time.rs 2.2 KB

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