RE: [tip: timers/urgent] time: Handle negative seconds correctly in timespec64_to_ns()

From: Thomas Gleixner
Date: Wed Sep 08 2021 - 16:12:02 EST


David,

On Wed, Sep 08 2021 at 16:01, David Laight wrote:
>> + if (ts->tv_sec <= KTIME_SEC_MIN)
>> + return KTIME_MIN;
>> +
>> return ((s64) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
>> }
>
> Adding tv_nsec can still overflow - even if tv_nsec is bounded to +/- 1 second.
> This is no more 'garbage in' => 'garbage out' than the code without the
> multiply under/overflow check.

In kernel timespecs are always normalized: 0 < tv_nsec < 1e9 - 1

Let's do the math:

KTIME_SEC_MAX = KTIME_MAX / NSEC_PER_SEC

The overflow prevention does:

if PSVAL >= KTIME_SEC_MAX:
return KTIME_MAX

so the largest positive seconds value which passes the above is:

PSMAX = KTIME_SEC_MAX - 1

ergo:

PSMAX * NSEC_PER_SEC + (NSEC_PER_SEC - 1) < KTIME_SEC_MAX < KTIME_MAX

I leave the proof for negative values as an excercise for the reader.

Thanks,

tglx
---
"Math is hard, let's go shopping!" - John Stultz