Re: [PATCH] rust: time: New module for timekeeping functions

From: Thomas Gleixner
Date: Tue Feb 21 2023 - 11:02:49 EST


On Tue, Feb 21 2023 at 06:06, Boqun Feng wrote:
> On Tue, Feb 21, 2023 at 01:32:51PM +0100, Thomas Gleixner wrote:
>> Similar to 'Instant' 'SystemTime' is strictly bound to CLOCK_REALTIME
>> by specification and there is no way to read CLOCK_TAI.
>>
> ..'Instant' and 'SystemTime' are in Rust std, we cannot use them
> directly, similar as we cannot use userspace libc.

Sure. Was Rust std defined based on SysV from 30 years ago? :)

> To me, there seems two options to provide Rust types for kernel time
> management:
>
> * Use KTime which maps to ktime_t, then we have the similar
> semantics around it: sometimes it's a duration, sometimes it's
> a point of time.. but I know "this is a safe language, you
> should do more" ;-)
>
> * Introduce kernel's own types, e.g. BootTime, RawTime, TAI,
> RealTime, and make them play with Duration (actually I'd prefer
> we have own Duration, because Rust core::time::Duration takes
> more than u64), something like below:
>
>
> pub struct BootTime {
> d: Duration
> }
>
> impl BootTime {
> fn now() -> Self {
> unsafe { BootTime { d: ktime_to_duration(ktime_get_boottime())} }
> }
> fn add(self, d: Duration) -> Self {
> <Add a duration, similar to ktime_add>
> }
> fn sub(self, other: Self) -> Duration {
> ...
> }

I'm not rusty enough, but you really want two types:

timestamp and timedelta

timestamp is an absolute time on a specific clock which is read via
now() and you can add time deltas to it. The latter is required for
arming an absolute timer on the clock.

timedelta is a relative time and completely independent of any
clock. That's what you get when you subtract two timestamps, but you can
also initialize it from a constant or some other source. timedelta can
be used to arm a relative timer on any clock.

Playing games with a single type is neither safe nor intuitive, right?

Thanks,

tglx