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

From: Asahi Lina
Date: Tue Feb 21 2023 - 11:31:52 EST


On 22/02/2023 01.02, Thomas Gleixner wrote:
> On Tue, Feb 21 2023 at 06:06, Boqun Feng wrote:
>> 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.

If all clocks end up as the same `timestamp` though, then this isn't
fully safe, because you could subtract `timestamp`s that came from
different clocks and the result would be meaningless. That's why the
Rust std Instant is specifically tied to one and only one system clock
on each platform.

~~ Lina