From: FUJITA Tomonori Date: Tue, 10 Jun 2025 09:32:55 +0000 (+0900) Subject: rust: time: Make Instant generic over ClockSource X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=768dfbfc98e26cfad45f7165a1801d188f3cbd81;p=thirdparty%2Fkernel%2Flinux.git rust: time: Make Instant generic over ClockSource Refactor the Instant type to be generic over a ClockSource type parameter, enabling static enforcement of clock correctness across APIs that deal with time. Previously, the clock source was implicitly fixed (typically CLOCK_MONOTONIC), and developers had to ensure compatibility manually. This design eliminates runtime mismatches between clock sources, and enables stronger type-level guarantees throughout the timer subsystem. Reviewed-by: Andreas Hindborg Reviewed-by: Boqun Feng Signed-off-by: FUJITA Tomonori Link: https://lore.kernel.org/r/20250610093258.3435874-3-fujita.tomonori@gmail.com Signed-off-by: Andreas Hindborg --- diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs index 1d2600288ed1f..3bc76f75bfd02 100644 --- a/rust/kernel/time.rs +++ b/rust/kernel/time.rs @@ -24,6 +24,8 @@ //! C header: [`include/linux/jiffies.h`](srctree/include/linux/jiffies.h). //! C header: [`include/linux/ktime.h`](srctree/include/linux/ktime.h). +use core::marker::PhantomData; + pub mod hrtimer; /// The number of nanoseconds per microsecond. @@ -136,12 +138,21 @@ impl ClockSource for Tai { /// /// The `inner` value is in the range from 0 to `KTIME_MAX`. #[repr(transparent)] -#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)] -pub struct Instant { +#[derive(PartialEq, PartialOrd, Eq, Ord)] +pub struct Instant { inner: bindings::ktime_t, + _c: PhantomData, } -impl Instant { +impl Clone for Instant { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Instant {} + +impl Instant { /// Get the current time using `CLOCK_MONOTONIC`. #[inline] pub fn now() -> Self { @@ -150,6 +161,7 @@ impl Instant { Self { // SAFETY: It is always safe to call `ktime_get()` outside of NMI context. inner: unsafe { bindings::ktime_get() }, + _c: PhantomData, } } @@ -160,12 +172,12 @@ impl Instant { } } -impl core::ops::Sub for Instant { +impl core::ops::Sub for Instant { type Output = Delta; // By the type invariant, it never overflows. #[inline] - fn sub(self, other: Instant) -> Delta { + fn sub(self, other: Instant) -> Delta { Delta { nanos: self.inner - other.inner, }