[PATCH 4/5] rust: time: Support reading CLOCK_MONOTONIC

From: Boqun Feng
Date: Sun Mar 24 2024 - 18:35:25 EST


Rust Binder will need to read CLOCK_MONOTONIC to compute how many
milliseconds a transaction has been active for when dumping the current
state of the Binder driver. This replicates the logic in C Binder [1].

For a usage example in Rust Binder, see [2].

Hence add the support for CLOCK_MONOTONIC read.

The `ktime_get` method cannot be safely called in NMI context. This
requirement is not checked by these abstractions, but it is intended
that klint [3] or a similar tool will be used to check it in the future.

Link: https://lore.kernel.org/lkml/5ac8c0d09392290be789423f0dd78a520b830fab.1682333709.git.zhangchuang3@xxxxxxxxxx/ [1]
Link: https://r.android.com/3004103 [2]
Link: https://rust-for-linux.com/klint [3]
Co-developed-by: Heghedus Razvan <heghedus.razvan@xxxxxxxxxxxxxx>
Signed-off-by: Heghedus Razvan <heghedus.razvan@xxxxxxxxxxxxxx>
Co-developed-by: Asahi Lina <lina@xxxxxxxxxxxxx>
Signed-off-by: Asahi Lina <lina@xxxxxxxxxxxxx>
Co-developed-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
Signed-off-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
Signed-off-by: Boqun Feng <boqun.feng@xxxxxxxxx>
---
@Alice, I still put the link to the usage of Android binder here, if you
want to remove that, please let me know.

rust/kernel/time.rs | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)

diff --git a/rust/kernel/time.rs b/rust/kernel/time.rs
index 0f9f5605ed48..5cd669cbea01 100644
--- a/rust/kernel/time.rs
+++ b/rust/kernel/time.rs
@@ -113,3 +113,22 @@ fn sub(self, other: Self) -> Self::Output {
Duration::new(self.inner.wrapping_sub(other.inner))
}
}
+
+/// Contains the various clock source types available to the kernel.
+pub mod clock {
+ use super::*;
+
+ /// A clock representing the default kernel time source (`CLOCK_MONOTONIC`).
+ pub struct KernelTime;
+
+ /// `CLOCK_MONOTONIC` is monotonic.
+ impl Monotonic for KernelTime {}
+
+ impl Clock for KernelTime {
+ #[inline]
+ fn now() -> Instant<Self> {
+ // SAFETY: It is always safe to call `ktime_get` outside of NMI context.
+ Instant::<Self>::new(unsafe { bindings::ktime_get() })
+ }
+ }
+}
--
2.44.0