[PATCH 1/6] rust: time: Add Ktime::from_ns()

Lyude Paul
2025-04-02T21:41:29Z

A simple function to turn the provided value in nanoseconds into a Ktime
value. We allow any type which implements Into<bindings::ktime_t>, which
resolves to Into<i64>.

This is useful for some of the older DRM APIs that never got moved to
Ktime.

Signed-off-by: Lyude Paul <lyude@redhat.com>
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
---
rust/kernel/time.rs | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index f509cb0eb71e0..c05afda07a05f 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -1,5 +1,4 @@
-// SPDX-License-Identifier: GPL-2.0
-
+// SPDX-License-Identifier: GPL-2.0
//! Time related primitives.
//!
//! This module contains the kernel APIs related to time and timers that
@@ -9,6 +8,7 @@
//! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h).

pub mod hrtimer;
+use core::convert::Into;

/// The number of nanoseconds per millisecond.
pub const NSEC_PER_MSEC: i64 = bindings::NSEC_PER_MSEC as i64;
@@ -65,6 +65,12 @@ pub fn to_ns(self) -> i64 {
pub fn to_ms(self) -> i64 {
self.divns_constant::<NSEC_PER_MSEC>()
}
+
+ /// Creates a new Ktime from the given duration in nanoseconds.
+ #[inline]
+ pub fn from_nanos(ns: impl Into<bindings::ktime_t>) -> Self {
+ Self { inner: ns.into() }
+ }
}

/// Returns the number of milliseconds between two ktimes.
--
2.48.1