Re: infinite loop in read_hpet from ktime_get_boot_fast_ns

Thomas Gleixner
2019-06-13T19:53:14Z

On Thu, 13 Jun 2019, Jason A. Donenfeld wrote:

> On Thu, Jun 13, 2019 at 6:26 PM Thomas Gleixner <tglx@linutronix.de> wrote:
> > That does not make sense. The coarse time getters use
> > tk->tkr_mono.base. base is updated every tick (or if the machine is
> > completely idle right when the first CPU wakes up again).
>
> Sense or not, it seems to be happening, at least on 5.2-rc4:

Bah. Seems I had paged out all the subtle parts of timekeeping and answered
from my blurred memory while traveling. Stared at it for a while and of
course base is only updated every second. The nsec part uses the
accumulated nsecs (< 1sec) plus the time delta read from the hardware. So
yes, the ktime_get_coarse* stuff has been broken from day one.

Fix below.

Thanks,

tglx

8<------------------
Subject: timekeeping: Repair ktime_get_coarse*() granularity
From: Thomas Gleixner <tglx@linutronix.de>
Date: Thu, 13 Jun 2019 21:40:45 +0200

Jason reported that the coarse ktime based time getters advance only once
per second and not once per tick as advertised.

The code reads only the monotonic base time, which advances once per
second. The nanoseconds are accumulated on every tick in xtime_nsec up to
a second and the regular time getters take this nanoseconds offset into
account, but the ktime_get_coarse*() implementation fails to do so.

Add the accumulated xtime_nsec value to the monotonic base time to get the
proper per tick advancing coarse tinme.

Fixes: b9ff604cff11 ("timekeeping: Add ktime_get_coarse_with_offset")
Reported-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Thomas Gleixner <tglx@linutronix.de>
Cc: stable@vger.kernel.org
---
kernel/time/timekeeping.c | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)

--- a/kernel/time/timekeeping.c
+++ b/kernel/time/timekeeping.c
@@ -810,17 +810,18 @@ ktime_t ktime_get_coarse_with_offset(enu
struct timekeeper *tk = &tk_core.timekeeper;
unsigned int seq;
ktime_t base, *offset = offsets[offs];
+ u64 nsecs;

WARN_ON(timekeeping_suspended);

do {
seq = read_seqcount_begin(&tk_core.seq);
base = ktime_add(tk->tkr_mono.base, *offset);
+ nsecs = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;

} while (read_seqcount_retry(&tk_core.seq, seq));

- return base;
-
+ return base + nsecs;
}
EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);