]> git.ipfire.org Git - thirdparty/linux.git/blame - kernel/time/timekeeping.c
Merge tag 'probes-fixes-v6.16-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git...
[thirdparty/linux.git] / kernel / time / timekeeping.c
CommitLineData
35728b82 1// SPDX-License-Identifier: GPL-2.0
8524070b 2/*
58c5fc2b
TG
3 * Kernel timekeeping code and accessor functions. Based on code from
4 * timer.c, moved in commit 8524070b7982.
8524070b 5 */
d7b4202e 6#include <linux/timekeeper_internal.h>
8524070b
JS
7#include <linux/module.h>
8#include <linux/interrupt.h>
9#include <linux/percpu.h>
10#include <linux/init.h>
11#include <linux/mm.h>
38b8d208 12#include <linux/nmi.h>
d43c36dc 13#include <linux/sched.h>
4f17722c 14#include <linux/sched/loadavg.h>
3eca9937 15#include <linux/sched/clock.h>
e1a85b2c 16#include <linux/syscore_ops.h>
8524070b
JS
17#include <linux/clocksource.h>
18#include <linux/jiffies.h>
19#include <linux/time.h>
1366992e 20#include <linux/timex.h>
8524070b 21#include <linux/tick.h>
75c5158f 22#include <linux/stop_machine.h>
e0b306fe 23#include <linux/pvclock_gtod.h>
52f5684c 24#include <linux/compiler.h>
2d87a067 25#include <linux/audit.h>
b8ac29b4 26#include <linux/random.h>
8524070b 27
eb93e4d9 28#include "tick-internal.h"
aa6f9c59 29#include "ntp_internal.h"
5c83545f 30#include "timekeeping_internal.h"
155ec602 31
04397fe9 32#define TK_CLEAR_NTP (1 << 0)
0026766d 33#define TK_CLOCK_WAS_SET (1 << 1)
04397fe9 34
6b1ef640 35#define TK_UPDATE_ALL (TK_CLEAR_NTP | TK_CLOCK_WAS_SET)
04397fe9 36
b061c7a5
ML
37enum timekeeping_adv_mode {
38 /* Update timekeeper when a tick has passed */
39 TK_ADV_TICK,
40
41 /* Update timekeeper on a direct frequency change */
42 TK_ADV_FREQ
43};
44
3fdb14fd
TG
45/*
46 * The most important data for readout fits into a single 64 byte
47 * cache line.
48 */
10f7c178 49struct tk_data {
025e82bc 50 seqcount_raw_spinlock_t seq;
3fdb14fd 51 struct timekeeper timekeeper;
20c7b582 52 struct timekeeper shadow_timekeeper;
8c4799b1 53 raw_spinlock_t lock;
10f7c178 54} ____cacheline_aligned;
3fdb14fd 55
10f7c178 56static struct tk_data tk_core;
155ec602 57
71419b30
TG
58/* flag for if timekeeping is suspended */
59int __read_mostly timekeeping_suspended;
60
4396e058
TG
61/**
62 * struct tk_fast - NMI safe timekeeper
63 * @seq: Sequence counter for protecting updates. The lowest bit
64 * is the index for the tk_read_base array
65 * @base: tk_read_base array. Access is indexed by the lowest bit of
66 * @seq.
67 *
68 * See @update_fast_timekeeper() below.
69 */
70struct tk_fast {
249d0538 71 seqcount_latch_t seq;
4396e058
TG
72 struct tk_read_base base[2];
73};
74
5df32107
PB
75/* Suspend-time cycles value for halted fast timekeeper. */
76static u64 cycles_at_suspend;
77
78static u64 dummy_clock_read(struct clocksource *cs)
79{
71419b30
TG
80 if (timekeeping_suspended)
81 return cycles_at_suspend;
82 return local_clock();
5df32107
PB
83}
84
85static struct clocksource dummy_clock = {
86 .read = dummy_clock_read,
87};
88
71419b30
TG
89/*
90 * Boot time initialization which allows local_clock() to be utilized
91 * during early boot when clocksources are not available. local_clock()
92 * returns nanoseconds already so no conversion is required, hence mult=1
93 * and shift=0. When the first proper clocksource is installed then
94 * the fast time keepers are updated with the correct values.
95 */
96#define FAST_TK_INIT \
97 { \
98 .clock = &dummy_clock, \
99 .mask = CLOCKSOURCE_MASK(64), \
100 .mult = 1, \
101 .shift = 0, \
102 }
103
5df32107 104static struct tk_fast tk_fast_mono ____cacheline_aligned = {
249d0538 105 .seq = SEQCNT_LATCH_ZERO(tk_fast_mono.seq),
71419b30
TG
106 .base[0] = FAST_TK_INIT,
107 .base[1] = FAST_TK_INIT,
5df32107
PB
108};
109
110static struct tk_fast tk_fast_raw ____cacheline_aligned = {
249d0538 111 .seq = SEQCNT_LATCH_ZERO(tk_fast_raw.seq),
71419b30
TG
112 .base[0] = FAST_TK_INIT,
113 .base[1] = FAST_TK_INIT,
5df32107 114};
4396e058 115
dbdcf8c4
TG
116unsigned long timekeeper_lock_irqsave(void)
117{
118 unsigned long flags;
119
8c4799b1 120 raw_spin_lock_irqsave(&tk_core.lock, flags);
dbdcf8c4
TG
121 return flags;
122}
123
124void timekeeper_unlock_irqrestore(unsigned long flags)
125{
8c4799b1 126 raw_spin_unlock_irqrestore(&tk_core.lock, flags);
dbdcf8c4
TG
127}
128
ee3283c6
JL
129/*
130 * Multigrain timestamps require tracking the latest fine-grained timestamp
131 * that has been issued, and never returning a coarse-grained timestamp that is
132 * earlier than that value.
133 *
134 * mg_floor represents the latest fine-grained time that has been handed out as
135 * a file timestamp on the system. This is tracked as a monotonic ktime_t, and
136 * converted to a realtime clock value on an as-needed basis.
137 *
138 * Maintaining mg_floor ensures the multigrain interfaces never issue a
139 * timestamp earlier than one that has been previously issued.
140 *
141 * The exception to this rule is when there is a backward realtime clock jump. If
142 * such an event occurs, a timestamp can appear to be earlier than a previous one.
143 */
144static __cacheline_aligned_in_smp atomic64_t mg_floor;
145
1e75fa8b
JS
146static inline void tk_normalize_xtime(struct timekeeper *tk)
147{
876e7881
PZ
148 while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
149 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
1e75fa8b
JS
150 tk->xtime_sec++;
151 }
fc6eead7
JS
152 while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
153 tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
154 tk->raw_sec++;
155 }
1e75fa8b
JS
156}
157
985e6950 158static inline struct timespec64 tk_xtime(const struct timekeeper *tk)
c905fae4
TG
159{
160 struct timespec64 ts;
161
162 ts.tv_sec = tk->xtime_sec;
876e7881 163 ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
c905fae4
TG
164 return ts;
165}
166
b71f9804
TG
167static inline struct timespec64 tk_xtime_coarse(const struct timekeeper *tk)
168{
169 struct timespec64 ts;
170
171 ts.tv_sec = tk->xtime_sec;
172 ts.tv_nsec = tk->coarse_nsec;
173 return ts;
174}
175
176/*
177 * Update the nanoseconds part for the coarse time keepers. They can't rely
178 * on xtime_nsec because xtime_nsec could be adjusted by a small negative
179 * amount when the multiplication factor of the clock is adjusted, which
180 * could cause the coarse clocks to go slightly backwards. See
181 * timekeeping_apply_adjustment(). Thus we keep a separate copy for the coarse
182 * clockids which only is updated when the clock has been set or we have
183 * accumulated time.
184 */
185static inline void tk_update_coarse_nsecs(struct timekeeper *tk)
186{
187 tk->coarse_nsec = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
188}
189
7d489d15 190static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
1e75fa8b
JS
191{
192 tk->xtime_sec = ts->tv_sec;
876e7881 193 tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
b71f9804 194 tk_update_coarse_nsecs(tk);
1e75fa8b
JS
195}
196
7d489d15 197static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
1e75fa8b
JS
198{
199 tk->xtime_sec += ts->tv_sec;
876e7881 200 tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
784ffcbb 201 tk_normalize_xtime(tk);
b71f9804 202 tk_update_coarse_nsecs(tk);
1e75fa8b 203}
8fcce546 204
7d489d15 205static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
6d0ef903 206{
7d489d15 207 struct timespec64 tmp;
6d0ef903
JS
208
209 /*
210 * Verify consistency of: offset_real = -wall_to_monotonic
211 * before modifying anything
212 */
7d489d15 213 set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
6d0ef903 214 -tk->wall_to_monotonic.tv_nsec);
2456e855 215 WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
6d0ef903 216 tk->wall_to_monotonic = wtm;
7d489d15 217 set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
8c111f1b
JL
218 /* Paired with READ_ONCE() in ktime_mono_to_any() */
219 WRITE_ONCE(tk->offs_real, timespec64_to_ktime(tmp));
220 WRITE_ONCE(tk->offs_tai, ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0)));
6d0ef903
JS
221}
222
47da70d3 223static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
6d0ef903 224{
8c111f1b
JL
225 /* Paired with READ_ONCE() in ktime_mono_to_any() */
226 WRITE_ONCE(tk->offs_boot, ktime_add(tk->offs_boot, delta));
b99328a6
TG
227 /*
228 * Timespec representation for VDSO update to avoid 64bit division
229 * on every update.
230 */
231 tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot);
6d0ef903
JS
232}
233
ceea5e37
JS
234/*
235 * tk_clock_read - atomic clocksource read() helper
236 *
237 * This helper is necessary to use in the read paths because, while the
025e82bc 238 * seqcount ensures we don't return a bad value while structures are updated,
ceea5e37
JS
239 * it doesn't protect from potential crashes. There is the possibility that
240 * the tkr's clocksource may change between the read reference, and the
241 * clock reference passed to the read function. This can cause crashes if
242 * the wrong clocksource is passed to the wrong read function.
8c4799b1 243 * This isn't necessary to use when holding the tk_core.lock or doing
ceea5e37
JS
244 * a read of the fast-timekeeper tkrs (which is protected by its own locking
245 * and update logic).
246 */
985e6950 247static inline u64 tk_clock_read(const struct tk_read_base *tkr)
ceea5e37
JS
248{
249 struct clocksource *clock = READ_ONCE(tkr->clock);
250
251 return clock->read(clock);
252}
253
155ec602 254/**
d26e4fe0 255 * tk_setup_internals - Set up internals to use clocksource clock.
155ec602 256 *
d26e4fe0 257 * @tk: The target timekeeper to setup.
155ec602
MS
258 * @clock: Pointer to clocksource.
259 *
260 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
261 * pair and interval request.
262 *
263 * Unless you're the timekeeping code, you should not be using this!
264 */
f726a697 265static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
155ec602 266{
a5a1d1c2 267 u64 interval;
a386b5af 268 u64 tmp, ntpinterval;
1e75fa8b 269 struct clocksource *old_clock;
155ec602 270
2c756feb 271 ++tk->cs_was_changed_seq;
876e7881
PZ
272 old_clock = tk->tkr_mono.clock;
273 tk->tkr_mono.clock = clock;
876e7881 274 tk->tkr_mono.mask = clock->mask;
ceea5e37 275 tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
155ec602 276
4a4ad80d 277 tk->tkr_raw.clock = clock;
4a4ad80d
PZ
278 tk->tkr_raw.mask = clock->mask;
279 tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
280
155ec602
MS
281 /* Do the ns -> cycle conversion first, using original mult */
282 tmp = NTP_INTERVAL_LENGTH;
283 tmp <<= clock->shift;
a386b5af 284 ntpinterval = tmp;
0a544198
MS
285 tmp += clock->mult/2;
286 do_div(tmp, clock->mult);
155ec602
MS
287 if (tmp == 0)
288 tmp = 1;
289
a5a1d1c2 290 interval = (u64) tmp;
f726a697 291 tk->cycle_interval = interval;
155ec602
MS
292
293 /* Go back from cycles -> shifted ns */
cbd99e3b 294 tk->xtime_interval = interval * clock->mult;
f726a697 295 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
3d88d56c 296 tk->raw_interval = interval * clock->mult;
155ec602 297
1e75fa8b
JS
298 /* if changing clocks, convert xtime_nsec shift units */
299 if (old_clock) {
300 int shift_change = clock->shift - old_clock->shift;
fc6eead7 301 if (shift_change < 0) {
876e7881 302 tk->tkr_mono.xtime_nsec >>= -shift_change;
fc6eead7
JS
303 tk->tkr_raw.xtime_nsec >>= -shift_change;
304 } else {
876e7881 305 tk->tkr_mono.xtime_nsec <<= shift_change;
fc6eead7
JS
306 tk->tkr_raw.xtime_nsec <<= shift_change;
307 }
1e75fa8b 308 }
4a4ad80d 309
876e7881 310 tk->tkr_mono.shift = clock->shift;
4a4ad80d 311 tk->tkr_raw.shift = clock->shift;
155ec602 312
f726a697
JS
313 tk->ntp_error = 0;
314 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
375f45b5 315 tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
0a544198
MS
316
317 /*
318 * The timekeeper keeps its own mult values for the currently
319 * active clocksource. These value will be adjusted via NTP
320 * to counteract clock drifting.
321 */
876e7881 322 tk->tkr_mono.mult = clock->mult;
4a4ad80d 323 tk->tkr_raw.mult = clock->mult;
dc491596 324 tk->ntp_err_mult = 0;
78b98e3c 325 tk->skip_second_overflow = 0;
155ec602 326}
8524070b 327
2ba2a305 328/* Timekeeper helper functions. */
fcf190c3
AH
329static noinline u64 delta_to_ns_safe(const struct tk_read_base *tkr, u64 delta)
330{
331 return mul_u64_u32_add_u64_shr(delta, tkr->mult, tkr->xtime_nsec, tkr->shift);
332}
333
e98ab3d4 334static inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles)
2ba2a305 335{
9af4548e 336 /* Calculate the delta since the last update_wall_time() */
e809a80a
AH
337 u64 mask = tkr->mask, delta = (cycles - tkr->cycle_last) & mask;
338
fcf190c3 339 /*
135225a3
AH
340 * This detects both negative motion and the case where the delta
341 * overflows the multiplication with tkr->mult.
fcf190c3
AH
342 */
343 if (unlikely(delta > tkr->clock->max_cycles)) {
135225a3
AH
344 /*
345 * Handle clocksource inconsistency between CPUs to prevent
346 * time from going backwards by checking for the MSB of the
347 * mask being set in the delta.
348 */
349 if (delta & ~(mask >> 1))
350 return tkr->xtime_nsec >> tkr->shift;
fcf190c3
AH
351
352 return delta_to_ns_safe(tkr, delta);
e809a80a 353 }
2ba2a305 354
3094c6db 355 return ((delta * tkr->mult) + tkr->xtime_nsec) >> tkr->shift;
6bd58f09 356}
2ba2a305 357
d44d2698 358static __always_inline u64 timekeeping_get_ns(const struct tk_read_base *tkr)
6bd58f09 359{
670be12b 360 return timekeeping_cycles_to_ns(tkr, tk_clock_read(tkr));
2ba2a305
MS
361}
362
4396e058
TG
363/**
364 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
affe3e85 365 * @tkr: Timekeeping readout base from which we take the update
e025b031 366 * @tkf: Pointer to NMI safe timekeeper
4396e058
TG
367 *
368 * We want to use this from any context including NMI and tracing /
369 * instrumenting the timekeeping code itself.
370 *
93190bc3 371 * Employ the latch technique; see @write_seqcount_latch.
4396e058
TG
372 *
373 * So if a NMI hits the update of base[0] then it will use base[1]
374 * which is still consistent. In the worst case this can result is a
375 * slightly wrong timestamp (a few nanoseconds). See
376 * @ktime_get_mono_fast_ns.
377 */
985e6950
OM
378static void update_fast_timekeeper(const struct tk_read_base *tkr,
379 struct tk_fast *tkf)
4396e058 380{
4498e746 381 struct tk_read_base *base = tkf->base;
4396e058
TG
382
383 /* Force readers off to base[1] */
93190bc3 384 write_seqcount_latch_begin(&tkf->seq);
4396e058
TG
385
386 /* Update base[0] */
affe3e85 387 memcpy(base, tkr, sizeof(*base));
4396e058
TG
388
389 /* Force readers back to base[0] */
93190bc3 390 write_seqcount_latch(&tkf->seq);
4396e058
TG
391
392 /* Update base[1] */
393 memcpy(base + 1, base, sizeof(*base));
93190bc3
ME
394
395 write_seqcount_latch_end(&tkf->seq);
4396e058
TG
396}
397
c1ce406e
TG
398static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
399{
400 struct tk_read_base *tkr;
401 unsigned int seq;
402 u64 now;
403
404 do {
93190bc3 405 seq = read_seqcount_latch(&tkf->seq);
c1ce406e
TG
406 tkr = tkf->base + (seq & 0x01);
407 now = ktime_to_ns(tkr->base);
d44d2698 408 now += timekeeping_get_ns(tkr);
93190bc3 409 } while (read_seqcount_latch_retry(&tkf->seq, seq));
c1ce406e
TG
410
411 return now;
412}
413
4396e058
TG
414/**
415 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
416 *
417 * This timestamp is not guaranteed to be monotonic across an update.
418 * The timestamp is calculated by:
419 *
420 * now = base_mono + clock_delta * slope
421 *
422 * So if the update lowers the slope, readers who are forced to the
423 * not yet updated second array are still using the old steeper slope.
424 *
425 * tmono
426 * ^
427 * | o n
428 * | o n
429 * | u
430 * | o
431 * |o
432 * |12345678---> reader order
433 *
434 * o = old slope
435 * u = update
436 * n = new slope
437 *
438 * So reader 6 will observe time going backwards versus reader 5.
439 *
c1ce406e 440 * While other CPUs are likely to be able to observe that, the only way
4396e058
TG
441 * for a CPU local observation is when an NMI hits in the middle of
442 * the update. Timestamps taken from that NMI context might be ahead
443 * of the following timestamps. Callers need to be aware of that and
444 * deal with it.
445 */
2c33d775 446u64 notrace ktime_get_mono_fast_ns(void)
4498e746
PZ
447{
448 return __ktime_get_fast_ns(&tk_fast_mono);
449}
4396e058
TG
450EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
451
c1ce406e
TG
452/**
453 * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw
454 *
455 * Contrary to ktime_get_mono_fast_ns() this is always correct because the
456 * conversion factor is not affected by NTP/PTP correction.
457 */
2c33d775 458u64 notrace ktime_get_raw_fast_ns(void)
f09cb9a1
PZ
459{
460 return __ktime_get_fast_ns(&tk_fast_raw);
461}
462EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
463
a3ed0e43
TG
464/**
465 * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
466 *
467 * To keep it NMI safe since we're accessing from tracing, we're not using a
468 * separate timekeeper with updates to monotonic clock and boot offset
025e82bc 469 * protected with seqcounts. This has the following minor side effects:
a3ed0e43
TG
470 *
471 * (1) Its possible that a timestamp be taken after the boot offset is updated
472 * but before the timekeeper is updated. If this happens, the new boot offset
473 * is added to the old timekeeping making the clock appear to update slightly
474 * earlier:
475 * CPU 0 CPU 1
476 * timekeeping_inject_sleeptime64()
477 * __timekeeping_inject_sleeptime(tk, delta);
478 * timestamp();
147ba943 479 * timekeeping_update_staged(tkd, TK_CLEAR_NTP...);
a3ed0e43
TG
480 *
481 * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
482 * partially updated. Since the tk->offs_boot update is a rare event, this
483 * should be a rare occurrence which postprocessing should be able to handle.
c1ce406e 484 *
158009f1 485 * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns()
c1ce406e 486 * apply as well.
a3ed0e43
TG
487 */
488u64 notrace ktime_get_boot_fast_ns(void)
489{
490 struct timekeeper *tk = &tk_core.timekeeper;
491
eff4849f 492 return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot)));
a3ed0e43
TG
493}
494EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
495
3dc6ffae
KK
496/**
497 * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock.
498 *
499 * The same limitations as described for ktime_get_boot_fast_ns() apply. The
500 * mono time and the TAI offset are not read atomically which may yield wrong
501 * readouts. However, an update of the TAI offset is an rare event e.g., caused
502 * by settime or adjtimex with an offset. The user of this function has to deal
503 * with the possibility of wrong timestamps in post processing.
504 */
505u64 notrace ktime_get_tai_fast_ns(void)
506{
507 struct timekeeper *tk = &tk_core.timekeeper;
508
509 return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai)));
510}
511EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns);
512
2d2a46cf
DDAG
513/**
514 * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
515 *
516 * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering.
517 */
518u64 ktime_get_real_fast_ns(void)
4c3711d7 519{
2d2a46cf 520 struct tk_fast *tkf = &tk_fast_mono;
4c3711d7 521 struct tk_read_base *tkr;
2d2a46cf 522 u64 baser, delta;
4c3711d7 523 unsigned int seq;
4c3711d7
TG
524
525 do {
526 seq = raw_read_seqcount_latch(&tkf->seq);
527 tkr = tkf->base + (seq & 0x01);
e2d977c9 528 baser = ktime_to_ns(tkr->base_real);
d44d2698 529 delta = timekeeping_get_ns(tkr);
d16317de 530 } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
4c3711d7 531
e2d977c9 532 return baser + delta;
4c3711d7 533}
df27067e 534EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
4c3711d7 535
060407ae
RW
536/**
537 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
538 * @tk: Timekeeper to snapshot.
539 *
540 * It generally is unsafe to access the clocksource after timekeeping has been
541 * suspended, so take a snapshot of the readout base of @tk and use it as the
542 * fast timekeeper's readout base while suspended. It will return the same
543 * number of cycles every time until timekeeping is resumed at which time the
544 * proper readout base for the fast timekeeper will be restored automatically.
545 */
985e6950 546static void halt_fast_timekeeper(const struct timekeeper *tk)
060407ae
RW
547{
548 static struct tk_read_base tkr_dummy;
985e6950 549 const struct tk_read_base *tkr = &tk->tkr_mono;
060407ae
RW
550
551 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
ceea5e37
JS
552 cycles_at_suspend = tk_clock_read(tkr);
553 tkr_dummy.clock = &dummy_clock;
4c3711d7 554 tkr_dummy.base_real = tkr->base + tk->offs_real;
4498e746 555 update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
f09cb9a1
PZ
556
557 tkr = &tk->tkr_raw;
558 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
ceea5e37 559 tkr_dummy.clock = &dummy_clock;
f09cb9a1 560 update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
060407ae
RW
561}
562
e0b306fe
MT
563static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
564
780427f0 565static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
e0b306fe 566{
780427f0 567 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
e0b306fe
MT
568}
569
570/**
571 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
f27f7c3f 572 * @nb: Pointer to the notifier block to register
e0b306fe
MT
573 */
574int pvclock_gtod_register_notifier(struct notifier_block *nb)
575{
3fdb14fd 576 struct timekeeper *tk = &tk_core.timekeeper;
e0b306fe
MT
577 int ret;
578
8c4799b1 579 guard(raw_spinlock_irqsave)(&tk_core.lock);
e0b306fe 580 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
780427f0 581 update_pvclock_gtod(tk, true);
e0b306fe
MT
582
583 return ret;
584}
585EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
586
587/**
588 * pvclock_gtod_unregister_notifier - unregister a pvclock
589 * timedata update listener
f27f7c3f 590 * @nb: Pointer to the notifier block to unregister
e0b306fe
MT
591 */
592int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
593{
8c4799b1
AMB
594 guard(raw_spinlock_irqsave)(&tk_core.lock);
595 return raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
e0b306fe
MT
596}
597EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
598
833f32d7
JS
599/*
600 * tk_update_leap_state - helper to update the next_leap_ktime
601 */
602static inline void tk_update_leap_state(struct timekeeper *tk)
603{
604 tk->next_leap_ktime = ntp_get_next_leap();
2456e855 605 if (tk->next_leap_ktime != KTIME_MAX)
833f32d7
JS
606 /* Convert to monotonic time */
607 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
608}
609
ae455cb7
AMB
610/*
611 * Leap state update for both shadow and the real timekeeper
612 * Separate to spare a full memcpy() of the timekeeper.
613 */
614static void tk_update_leap_state_all(struct tk_data *tkd)
615{
616 write_seqcount_begin(&tkd->seq);
617 tk_update_leap_state(&tkd->shadow_timekeeper);
618 tkd->timekeeper.next_leap_ktime = tkd->shadow_timekeeper.next_leap_ktime;
619 write_seqcount_end(&tkd->seq);
620}
621
7c032df5
TG
622/*
623 * Update the ktime_t based scalar nsec members of the timekeeper
624 */
625static inline void tk_update_ktime_data(struct timekeeper *tk)
626{
9e3680b1
HS
627 u64 seconds;
628 u32 nsec;
7c032df5
TG
629
630 /*
631 * The xtime based monotonic readout is:
632 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
633 * The ktime based monotonic readout is:
634 * nsec = base_mono + now();
635 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
636 */
9e3680b1
HS
637 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
638 nsec = (u32) tk->wall_to_monotonic.tv_nsec;
876e7881 639 tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
f519b1a2 640
9e3680b1
HS
641 /*
642 * The sum of the nanoseconds portions of xtime and
643 * wall_to_monotonic can be greater/equal one second. Take
644 * this into account before updating tk->ktime_sec.
645 */
876e7881 646 nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
9e3680b1
HS
647 if (nsec >= NSEC_PER_SEC)
648 seconds++;
649 tk->ktime_sec = seconds;
fc6eead7
JS
650
651 /* Update the monotonic raw base */
0bcdc098 652 tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
7c032df5
TG
653}
654
97e53792
TG
655/*
656 * Restore the shadow timekeeper from the real timekeeper.
657 */
658static void timekeeping_restore_shadow(struct tk_data *tkd)
659{
660 lockdep_assert_held(&tkd->lock);
661 memcpy(&tkd->shadow_timekeeper, &tkd->timekeeper, sizeof(tkd->timekeeper));
662}
663
147ba943 664static void timekeeping_update_from_shadow(struct tk_data *tkd, unsigned int action)
cc06268c 665{
147ba943
AMB
666 struct timekeeper *tk = &tk_core.shadow_timekeeper;
667
1d72d7b5
AMB
668 lockdep_assert_held(&tkd->lock);
669
147ba943
AMB
670 /*
671 * Block out readers before running the updates below because that
672 * updates VDSO and other time related infrastructure. Not blocking
673 * the readers might let a reader see time going backwards when
674 * reading from the VDSO after the VDSO update and then reading in
675 * the kernel from the timekeeper before that got updated.
676 */
677 write_seqcount_begin(&tkd->seq);
678
04397fe9 679 if (action & TK_CLEAR_NTP) {
f726a697 680 tk->ntp_error = 0;
cc06268c
TG
681 ntp_clear();
682 }
48cdc135 683
833f32d7 684 tk_update_leap_state(tk);
7c032df5
TG
685 tk_update_ktime_data(tk);
686
9bf2419f
TG
687 update_vsyscall(tk);
688 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
689
4c3711d7 690 tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
4498e746 691 update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
f09cb9a1 692 update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
868a3e91
TG
693
694 if (action & TK_CLOCK_WAS_SET)
695 tk->clock_was_set_seq++;
5aa6c43e 696
d1518326 697 /*
5aa6c43e
AMB
698 * Update the real timekeeper.
699 *
700 * We could avoid this memcpy() by switching pointers, but that has
701 * the downside that the reader side does not longer benefit from
702 * the cacheline optimized data layout of the timekeeper and requires
703 * another indirection.
d1518326 704 */
147ba943 705 memcpy(&tkd->timekeeper, tk, sizeof(*tk));
5aa6c43e 706 write_seqcount_end(&tkd->seq);
cc06268c
TG
707}
708
8524070b 709/**
324a2219 710 * timekeeping_forward_now - update clock to the current time
6e5a9190 711 * @tk: Pointer to the timekeeper to update
8524070b 712 *
9a055117
RZ
713 * Forward the current clock to update its state since the last call to
714 * update_wall_time(). This is useful before significant clock changes,
715 * as it avoids having to deal with this time offset explicitly.
8524070b 716 */
324a2219 717static void timekeeping_forward_now(struct timekeeper *tk)
8524070b 718{
324a2219 719 u64 cycle_now, delta;
8524070b 720
324a2219
TG
721 cycle_now = tk_clock_read(&tk->tkr_mono);
722 delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
723 tk->tkr_mono.clock->max_raw_delta);
876e7881 724 tk->tkr_mono.cycle_last = cycle_now;
4a4ad80d 725 tk->tkr_raw.cycle_last = cycle_now;
8524070b 726
fcf190c3
AH
727 while (delta > 0) {
728 u64 max = tk->tkr_mono.clock->max_cycles;
729 u64 incr = delta < max ? delta : max;
fc6eead7 730
fcf190c3
AH
731 tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult;
732 tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult;
733 tk_normalize_xtime(tk);
734 delta -= incr;
735 }
b71f9804 736 tk_update_coarse_nsecs(tk);
8524070b
JS
737}
738
739/**
edca71fe 740 * ktime_get_real_ts64 - Returns the time of day in a timespec64.
8524070b
JS
741 * @ts: pointer to the timespec to be set
742 *
edca71fe 743 * Returns the time of day in a timespec64 (WARN if suspended).
8524070b 744 */
edca71fe 745void ktime_get_real_ts64(struct timespec64 *ts)
8524070b 746{
3fdb14fd 747 struct timekeeper *tk = &tk_core.timekeeper;
e1e41b6c 748 unsigned int seq;
acc89612 749 u64 nsecs;
8524070b 750
edca71fe
AB
751 WARN_ON(timekeeping_suspended);
752
8524070b 753 do {
3fdb14fd 754 seq = read_seqcount_begin(&tk_core.seq);
8524070b 755
4e250fdd 756 ts->tv_sec = tk->xtime_sec;
876e7881 757 nsecs = timekeeping_get_ns(&tk->tkr_mono);
8524070b 758
3fdb14fd 759 } while (read_seqcount_retry(&tk_core.seq, seq));
8524070b 760
ec145bab 761 ts->tv_nsec = 0;
d6d29896 762 timespec64_add_ns(ts, nsecs);
8524070b 763}
edca71fe 764EXPORT_SYMBOL(ktime_get_real_ts64);
8524070b 765
951ed4d3
MS
766ktime_t ktime_get(void)
767{
3fdb14fd 768 struct timekeeper *tk = &tk_core.timekeeper;
951ed4d3 769 unsigned int seq;
a016a5bd 770 ktime_t base;
acc89612 771 u64 nsecs;
951ed4d3
MS
772
773 WARN_ON(timekeeping_suspended);
774
775 do {
3fdb14fd 776 seq = read_seqcount_begin(&tk_core.seq);
876e7881
PZ
777 base = tk->tkr_mono.base;
778 nsecs = timekeeping_get_ns(&tk->tkr_mono);
951ed4d3 779
3fdb14fd 780 } while (read_seqcount_retry(&tk_core.seq, seq));
24e4a8c3 781
a016a5bd 782 return ktime_add_ns(base, nsecs);
951ed4d3
MS
783}
784EXPORT_SYMBOL_GPL(ktime_get);
785
6374f912
HG
786u32 ktime_get_resolution_ns(void)
787{
788 struct timekeeper *tk = &tk_core.timekeeper;
789 unsigned int seq;
790 u32 nsecs;
791
792 WARN_ON(timekeeping_suspended);
793
794 do {
795 seq = read_seqcount_begin(&tk_core.seq);
796 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
797 } while (read_seqcount_retry(&tk_core.seq, seq));
798
799 return nsecs;
800}
801EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
802
0077dc60
TG
803static ktime_t *offsets[TK_OFFS_MAX] = {
804 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
a3ed0e43 805 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
0077dc60
TG
806 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
807};
808
809ktime_t ktime_get_with_offset(enum tk_offsets offs)
810{
811 struct timekeeper *tk = &tk_core.timekeeper;
812 unsigned int seq;
813 ktime_t base, *offset = offsets[offs];
acc89612 814 u64 nsecs;
0077dc60
TG
815
816 WARN_ON(timekeeping_suspended);
817
818 do {
819 seq = read_seqcount_begin(&tk_core.seq);
876e7881
PZ
820 base = ktime_add(tk->tkr_mono.base, *offset);
821 nsecs = timekeeping_get_ns(&tk->tkr_mono);
0077dc60
TG
822
823 } while (read_seqcount_retry(&tk_core.seq, seq));
824
825 return ktime_add_ns(base, nsecs);
826
827}
828EXPORT_SYMBOL_GPL(ktime_get_with_offset);
829
b9ff604c
AB
830ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
831{
832 struct timekeeper *tk = &tk_core.timekeeper;
b9ff604c 833 ktime_t base, *offset = offsets[offs];
b71f9804 834 unsigned int seq;
e3ff9c36 835 u64 nsecs;
b9ff604c
AB
836
837 WARN_ON(timekeeping_suspended);
838
839 do {
840 seq = read_seqcount_begin(&tk_core.seq);
841 base = ktime_add(tk->tkr_mono.base, *offset);
b71f9804 842 nsecs = tk->coarse_nsec;
b9ff604c
AB
843
844 } while (read_seqcount_retry(&tk_core.seq, seq));
845
0354c1a3 846 return ktime_add_ns(base, nsecs);
b9ff604c
AB
847}
848EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
849
9a6b5197 850/**
4bf07f65 851 * ktime_mono_to_any() - convert monotonic time to any other time
9a6b5197
TG
852 * @tmono: time to convert.
853 * @offs: which offset to use
854 */
855ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
856{
857 ktime_t *offset = offsets[offs];
e1e41b6c 858 unsigned int seq;
9a6b5197
TG
859 ktime_t tconv;
860
8c111f1b
JL
861 if (IS_ENABLED(CONFIG_64BIT)) {
862 /*
863 * Paired with WRITE_ONCE()s in tk_set_wall_to_mono() and
864 * tk_update_sleep_time().
865 */
866 return ktime_add(tmono, READ_ONCE(*offset));
867 }
868
9a6b5197
TG
869 do {
870 seq = read_seqcount_begin(&tk_core.seq);
871 tconv = ktime_add(tmono, *offset);
872 } while (read_seqcount_retry(&tk_core.seq, seq));
873
874 return tconv;
875}
876EXPORT_SYMBOL_GPL(ktime_mono_to_any);
877
f519b1a2
TG
878/**
879 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
880 */
881ktime_t ktime_get_raw(void)
882{
883 struct timekeeper *tk = &tk_core.timekeeper;
884 unsigned int seq;
885 ktime_t base;
acc89612 886 u64 nsecs;
f519b1a2
TG
887
888 do {
889 seq = read_seqcount_begin(&tk_core.seq);
4a4ad80d
PZ
890 base = tk->tkr_raw.base;
891 nsecs = timekeeping_get_ns(&tk->tkr_raw);
f519b1a2
TG
892
893 } while (read_seqcount_retry(&tk_core.seq, seq));
894
895 return ktime_add_ns(base, nsecs);
896}
897EXPORT_SYMBOL_GPL(ktime_get_raw);
898
951ed4d3 899/**
d6d29896 900 * ktime_get_ts64 - get the monotonic clock in timespec64 format
951ed4d3
MS
901 * @ts: pointer to timespec variable
902 *
903 * The function calculates the monotonic clock from the realtime
904 * clock and the wall_to_monotonic offset and stores the result
5322e4c2 905 * in normalized timespec64 format in the variable pointed to by @ts.
951ed4d3 906 */
d6d29896 907void ktime_get_ts64(struct timespec64 *ts)
951ed4d3 908{
3fdb14fd 909 struct timekeeper *tk = &tk_core.timekeeper;
d6d29896 910 struct timespec64 tomono;
951ed4d3 911 unsigned int seq;
acc89612 912 u64 nsec;
951ed4d3
MS
913
914 WARN_ON(timekeeping_suspended);
915
916 do {
3fdb14fd 917 seq = read_seqcount_begin(&tk_core.seq);
d6d29896 918 ts->tv_sec = tk->xtime_sec;
876e7881 919 nsec = timekeeping_get_ns(&tk->tkr_mono);
4e250fdd 920 tomono = tk->wall_to_monotonic;
951ed4d3 921
3fdb14fd 922 } while (read_seqcount_retry(&tk_core.seq, seq));
951ed4d3 923
d6d29896
TG
924 ts->tv_sec += tomono.tv_sec;
925 ts->tv_nsec = 0;
926 timespec64_add_ns(ts, nsec + tomono.tv_nsec);
951ed4d3 927}
d6d29896 928EXPORT_SYMBOL_GPL(ktime_get_ts64);
951ed4d3 929
9e3680b1
HS
930/**
931 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
932 *
933 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
934 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
935 * works on both 32 and 64 bit systems. On 32 bit systems the readout
936 * covers ~136 years of uptime which should be enough to prevent
937 * premature wrap arounds.
938 */
939time64_t ktime_get_seconds(void)
940{
941 struct timekeeper *tk = &tk_core.timekeeper;
942
943 WARN_ON(timekeeping_suspended);
944 return tk->ktime_sec;
945}
946EXPORT_SYMBOL_GPL(ktime_get_seconds);
947
dbe7aa62
HS
948/**
949 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
950 *
aba428a0 951 * Returns the wall clock seconds since 1970.
dbe7aa62
HS
952 *
953 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
954 * 32bit systems the access must be protected with the sequence
955 * counter to provide "atomic" access to the 64bit tk->xtime_sec
956 * value.
957 */
958time64_t ktime_get_real_seconds(void)
959{
960 struct timekeeper *tk = &tk_core.timekeeper;
961 time64_t seconds;
962 unsigned int seq;
963
964 if (IS_ENABLED(CONFIG_64BIT))
965 return tk->xtime_sec;
966
967 do {
968 seq = read_seqcount_begin(&tk_core.seq);
969 seconds = tk->xtime_sec;
970
971 } while (read_seqcount_retry(&tk_core.seq, seq));
972
973 return seconds;
974}
975EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
976
dee36654
D
977/**
978 * __ktime_get_real_seconds - The same as ktime_get_real_seconds
979 * but without the sequence counter protect. This internal function
980 * is called just when timekeeping lock is already held.
981 */
865d3a9a 982noinstr time64_t __ktime_get_real_seconds(void)
dee36654
D
983{
984 struct timekeeper *tk = &tk_core.timekeeper;
985
986 return tk->xtime_sec;
987}
988
9da0f49c
CH
989/**
990 * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
991 * @systime_snapshot: pointer to struct receiving the system time snapshot
992 */
993void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
994{
995 struct timekeeper *tk = &tk_core.timekeeper;
e1e41b6c 996 unsigned int seq;
9da0f49c
CH
997 ktime_t base_raw;
998 ktime_t base_real;
8102c4da 999 ktime_t base_boot;
acc89612
TG
1000 u64 nsec_raw;
1001 u64 nsec_real;
a5a1d1c2 1002 u64 now;
9da0f49c 1003
ba26621e
CH
1004 WARN_ON_ONCE(timekeeping_suspended);
1005
9da0f49c
CH
1006 do {
1007 seq = read_seqcount_begin(&tk_core.seq);
ceea5e37 1008 now = tk_clock_read(&tk->tkr_mono);
b2c67cbe 1009 systime_snapshot->cs_id = tk->tkr_mono.clock->id;
2c756feb
CH
1010 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
1011 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
9da0f49c
CH
1012 base_real = ktime_add(tk->tkr_mono.base,
1013 tk_core.timekeeper.offs_real);
8102c4da
VD
1014 base_boot = ktime_add(tk->tkr_mono.base,
1015 tk_core.timekeeper.offs_boot);
9da0f49c
CH
1016 base_raw = tk->tkr_raw.base;
1017 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
1018 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
1019 } while (read_seqcount_retry(&tk_core.seq, seq));
1020
1021 systime_snapshot->cycles = now;
1022 systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
8102c4da 1023 systime_snapshot->boot = ktime_add_ns(base_boot, nsec_real);
9da0f49c
CH
1024 systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
1025}
1026EXPORT_SYMBOL_GPL(ktime_get_snapshot);
dee36654 1027
2c756feb
CH
1028/* Scale base by mult/div checking for overflow */
1029static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
1030{
1031 u64 tmp, rem;
1032
1033 tmp = div64_u64_rem(*base, div, &rem);
1034
1035 if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
1036 ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
1037 return -EOVERFLOW;
1038 tmp *= mult;
2c756feb 1039
4cbbc3a0 1040 rem = div64_u64(rem * mult, div);
2c756feb
CH
1041 *base = tmp + rem;
1042 return 0;
1043}
1044
1045/**
1046 * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1047 * @history: Snapshot representing start of history
1048 * @partial_history_cycles: Cycle offset into history (fractional part)
1049 * @total_history_cycles: Total history length in cycles
1050 * @discontinuity: True indicates clock was set on history period
1051 * @ts: Cross timestamp that should be adjusted using
1052 * partial/total ratio
1053 *
1054 * Helper function used by get_device_system_crosststamp() to correct the
1055 * crosstimestamp corresponding to the start of the current interval to the
1056 * system counter value (timestamp point) provided by the driver. The
1057 * total_history_* quantities are the total history starting at the provided
1058 * reference point and ending at the start of the current interval. The cycle
1059 * count between the driver timestamp point and the start of the current
1060 * interval is partial_history_cycles.
1061 */
1062static int adjust_historical_crosststamp(struct system_time_snapshot *history,
a5a1d1c2
TG
1063 u64 partial_history_cycles,
1064 u64 total_history_cycles,
2c756feb
CH
1065 bool discontinuity,
1066 struct system_device_crosststamp *ts)
1067{
1068 struct timekeeper *tk = &tk_core.timekeeper;
1069 u64 corr_raw, corr_real;
1070 bool interp_forward;
1071 int ret;
1072
1073 if (total_history_cycles == 0 || partial_history_cycles == 0)
1074 return 0;
1075
1076 /* Interpolate shortest distance from beginning or end of history */
5fc63f95 1077 interp_forward = partial_history_cycles > total_history_cycles / 2;
2c756feb
CH
1078 partial_history_cycles = interp_forward ?
1079 total_history_cycles - partial_history_cycles :
1080 partial_history_cycles;
1081
1082 /*
1083 * Scale the monotonic raw time delta by:
1084 * partial_history_cycles / total_history_cycles
1085 */
1086 corr_raw = (u64)ktime_to_ns(
1087 ktime_sub(ts->sys_monoraw, history->raw));
1088 ret = scale64_check_overflow(partial_history_cycles,
1089 total_history_cycles, &corr_raw);
1090 if (ret)
1091 return ret;
1092
1093 /*
1094 * If there is a discontinuity in the history, scale monotonic raw
1095 * correction by:
1096 * mult(real)/mult(raw) yielding the realtime correction
1097 * Otherwise, calculate the realtime correction similar to monotonic
1098 * raw calculation
1099 */
1100 if (discontinuity) {
1101 corr_real = mul_u64_u32_div
1102 (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1103 } else {
1104 corr_real = (u64)ktime_to_ns(
1105 ktime_sub(ts->sys_realtime, history->real));
1106 ret = scale64_check_overflow(partial_history_cycles,
1107 total_history_cycles, &corr_real);
1108 if (ret)
1109 return ret;
1110 }
1111
1112 /* Fixup monotonic raw and real time time values */
1113 if (interp_forward) {
1114 ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1115 ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1116 } else {
1117 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1118 ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1119 }
1120
1121 return 0;
1122}
1123
1124/*
87a41130
PH
1125 * timestamp_in_interval - true if ts is chronologically in [start, end]
1126 *
1127 * True if ts occurs chronologically at or after start, and before or at end.
2c756feb 1128 */
87a41130 1129static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
2c756feb 1130{
87a41130 1131 if (ts >= start && ts <= end)
2c756feb 1132 return true;
87a41130 1133 if (start > end && (ts >= start || ts <= end))
2c756feb
CH
1134 return true;
1135 return false;
1136}
1137
6b2e2997
LS
1138static bool convert_clock(u64 *val, u32 numerator, u32 denominator)
1139{
1140 u64 rem, res;
1141
1142 if (!numerator || !denominator)
1143 return false;
1144
1145 res = div64_u64_rem(*val, denominator, &rem) * numerator;
1146 *val = res + div_u64(rem * numerator, denominator);
1147 return true;
1148}
1149
1150static bool convert_base_to_cs(struct system_counterval_t *scv)
1151{
1152 struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1153 struct clocksource_base *base;
1154 u32 num, den;
1155
1156 /* The timestamp was taken from the time keeper clock source */
1157 if (cs->id == scv->cs_id)
1158 return true;
1159
1160 /*
1161 * Check whether cs_id matches the base clock. Prevent the compiler from
1162 * re-evaluating @base as the clocksource might change concurrently.
1163 */
1164 base = READ_ONCE(cs->base);
1165 if (!base || base->id != scv->cs_id)
1166 return false;
1167
1168 num = scv->use_nsecs ? cs->freq_khz : base->numerator;
1169 den = scv->use_nsecs ? USEC_PER_SEC : base->denominator;
1170
1171 if (!convert_clock(&scv->cycles, num, den))
1172 return false;
1173
1174 scv->cycles += base->offset;
1175 return true;
1176}
1177
02ecee07
LS
1178static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id)
1179{
1180 struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1181 struct clocksource_base *base;
1182
1183 /*
1184 * Check whether base_id matches the base clock. Prevent the compiler from
1185 * re-evaluating @base as the clocksource might change concurrently.
1186 */
1187 base = READ_ONCE(cs->base);
1188 if (!base || base->id != base_id)
1189 return false;
1190
1191 *cycles -= base->offset;
1192 if (!convert_clock(cycles, base->denominator, base->numerator))
1193 return false;
1194 return true;
1195}
1196
1197static bool convert_ns_to_cs(u64 *delta)
1198{
1199 struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
1200
1201 if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta))
1202 return false;
1203
1204 *delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult);
1205 return true;
1206}
1207
1208/**
1209 * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp
1210 * @treal: CLOCK_REALTIME timestamp to convert
1211 * @base_id: base clocksource id
1212 * @cycles: pointer to store the converted base clock timestamp
1213 *
1214 * Converts a supplied, future realtime clock value to the corresponding base clock value.
1215 *
1216 * Return: true if the conversion is successful, false otherwise.
1217 */
1218bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles)
1219{
1220 struct timekeeper *tk = &tk_core.timekeeper;
1221 unsigned int seq;
1222 u64 delta;
1223
1224 do {
1225 seq = read_seqcount_begin(&tk_core.seq);
1226 if ((u64)treal < tk->tkr_mono.base_real)
1227 return false;
1228 delta = (u64)treal - tk->tkr_mono.base_real;
1229 if (!convert_ns_to_cs(&delta))
1230 return false;
1231 *cycles = tk->tkr_mono.cycle_last + delta;
1232 if (!convert_cs_to_base(cycles, base_id))
1233 return false;
1234 } while (read_seqcount_retry(&tk_core.seq, seq));
1235
1236 return true;
1237}
1238EXPORT_SYMBOL_GPL(ktime_real_to_base_clock);
1239
8006c245
CH
1240/**
1241 * get_device_system_crosststamp - Synchronously capture system/device timestamp
2c756feb 1242 * @get_time_fn: Callback to get simultaneous device time and
8006c245 1243 * system counter from the device driver
2c756feb
CH
1244 * @ctx: Context passed to get_time_fn()
1245 * @history_begin: Historical reference point used to interpolate system
1246 * time when counter provided by the driver is before the current interval
8006c245
CH
1247 * @xtstamp: Receives simultaneously captured system and device time
1248 *
1249 * Reads a timestamp from a device and correlates it to system time
1250 */
1251int get_device_system_crosststamp(int (*get_time_fn)
1252 (ktime_t *device_time,
1253 struct system_counterval_t *sys_counterval,
1254 void *ctx),
1255 void *ctx,
2c756feb 1256 struct system_time_snapshot *history_begin,
8006c245
CH
1257 struct system_device_crosststamp *xtstamp)
1258{
1259 struct system_counterval_t system_counterval;
1260 struct timekeeper *tk = &tk_core.timekeeper;
a5a1d1c2 1261 u64 cycles, now, interval_start;
6436257b 1262 unsigned int clock_was_set_seq = 0;
8006c245 1263 ktime_t base_real, base_raw;
acc89612 1264 u64 nsec_real, nsec_raw;
2c756feb 1265 u8 cs_was_changed_seq;
e1e41b6c 1266 unsigned int seq;
2c756feb 1267 bool do_interp;
8006c245
CH
1268 int ret;
1269
1270 do {
1271 seq = read_seqcount_begin(&tk_core.seq);
1272 /*
1273 * Try to synchronously capture device time and a system
1274 * counter value calling back into the device driver
1275 */
1276 ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1277 if (ret)
1278 return ret;
1279
1280 /*
4b7f5212
PH
1281 * Verify that the clocksource ID associated with the captured
1282 * system counter value is the same as for the currently
1283 * installed timekeeper clocksource
8006c245 1284 */
4b7f5212 1285 if (system_counterval.cs_id == CSID_GENERIC ||
6b2e2997 1286 !convert_base_to_cs(&system_counterval))
8006c245 1287 return -ENODEV;
2c756feb
CH
1288 cycles = system_counterval.cycles;
1289
1290 /*
1291 * Check whether the system counter value provided by the
1292 * device driver is on the current timekeeping interval.
1293 */
ceea5e37 1294 now = tk_clock_read(&tk->tkr_mono);
2c756feb 1295 interval_start = tk->tkr_mono.cycle_last;
87a41130 1296 if (!timestamp_in_interval(interval_start, now, cycles)) {
2c756feb
CH
1297 clock_was_set_seq = tk->clock_was_set_seq;
1298 cs_was_changed_seq = tk->cs_was_changed_seq;
1299 cycles = interval_start;
1300 do_interp = true;
1301 } else {
1302 do_interp = false;
1303 }
8006c245
CH
1304
1305 base_real = ktime_add(tk->tkr_mono.base,
1306 tk_core.timekeeper.offs_real);
1307 base_raw = tk->tkr_raw.base;
1308
14274d0b
PH
1309 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
1310 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
8006c245
CH
1311 } while (read_seqcount_retry(&tk_core.seq, seq));
1312
1313 xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1314 xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
2c756feb
CH
1315
1316 /*
1317 * Interpolate if necessary, adjusting back from the start of the
1318 * current interval
1319 */
1320 if (do_interp) {
a5a1d1c2 1321 u64 partial_history_cycles, total_history_cycles;
2c756feb
CH
1322 bool discontinuity;
1323
1324 /*
87a41130 1325 * Check that the counter value is not before the provided
2c756feb
CH
1326 * history reference and that the history doesn't cross a
1327 * clocksource change
1328 */
1329 if (!history_begin ||
87a41130
PH
1330 !timestamp_in_interval(history_begin->cycles,
1331 cycles, system_counterval.cycles) ||
2c756feb
CH
1332 history_begin->cs_was_changed_seq != cs_was_changed_seq)
1333 return -EINVAL;
1334 partial_history_cycles = cycles - system_counterval.cycles;
1335 total_history_cycles = cycles - history_begin->cycles;
1336 discontinuity =
1337 history_begin->clock_was_set_seq != clock_was_set_seq;
1338
1339 ret = adjust_historical_crosststamp(history_begin,
1340 partial_history_cycles,
1341 total_history_cycles,
1342 discontinuity, xtstamp);
1343 if (ret)
1344 return ret;
1345 }
1346
8006c245
CH
1347 return 0;
1348}
1349EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1350
02ecee07
LS
1351/**
1352 * timekeeping_clocksource_has_base - Check whether the current clocksource
1353 * is based on given a base clock
1354 * @id: base clocksource ID
1355 *
1356 * Note: The return value is a snapshot which can become invalid right
1357 * after the function returns.
1358 *
1359 * Return: true if the timekeeper clocksource has a base clock with @id,
1360 * false otherwise
1361 */
1362bool timekeeping_clocksource_has_base(enum clocksource_ids id)
1363{
1364 /*
1365 * This is a snapshot, so no point in using the sequence
1366 * count. Just prevent the compiler from re-evaluating @base as the
1367 * clocksource might change concurrently.
1368 */
1369 struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base);
1370
1371 return base ? base->id == id : false;
1372}
1373EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base);
1374
8524070b 1375/**
21f7eca5 1376 * do_settimeofday64 - Sets the time of day.
1377 * @ts: pointer to the timespec64 variable containing the new time
8524070b
JS
1378 *
1379 * Sets the time of day to the new time and update NTP and notify hrtimers
1380 */
21f7eca5 1381int do_settimeofday64(const struct timespec64 *ts)
8524070b 1382{
21f7eca5 1383 struct timespec64 ts_delta, xt;
8524070b 1384
7a8e61f8 1385 if (!timespec64_valid_settod(ts))
8524070b
JS
1386 return -EINVAL;
1387
bba9898e
AMB
1388 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1389 struct timekeeper *tks = &tk_core.shadow_timekeeper;
9a055117 1390
bba9898e 1391 timekeeping_forward_now(tks);
1e75fa8b 1392
bba9898e
AMB
1393 xt = tk_xtime(tks);
1394 ts_delta = timespec64_sub(*ts, xt);
8524070b 1395
bba9898e
AMB
1396 if (timespec64_compare(&tks->wall_to_monotonic, &ts_delta) > 0) {
1397 timekeeping_restore_shadow(&tk_core);
1398 return -EINVAL;
1399 }
8524070b 1400
bba9898e
AMB
1401 tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, ts_delta));
1402 tk_set_xtime(tks, ts);
1403 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1404 }
8524070b 1405
17a1b882
TG
1406 /* Signal hrtimers about time change */
1407 clock_was_set(CLOCK_SET_WALL);
8524070b 1408
bba9898e
AMB
1409 audit_tk_injoffset(ts_delta);
1410 add_device_randomness(ts, sizeof(*ts));
1411 return 0;
8524070b 1412}
21f7eca5 1413EXPORT_SYMBOL(do_settimeofday64);
8524070b 1414
c528f7c6
JS
1415/**
1416 * timekeeping_inject_offset - Adds or subtracts from the current time.
6e5a9190 1417 * @ts: Pointer to the timespec variable containing the offset
c528f7c6
JS
1418 *
1419 * Adds or subtracts an offset value from the current time.
1420 */
985e6950 1421static int timekeeping_inject_offset(const struct timespec64 *ts)
c528f7c6 1422{
1572fa03 1423 if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
c528f7c6
JS
1424 return -EINVAL;
1425
82214756
AMB
1426 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1427 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1428 struct timespec64 tmp;
1e75fa8b 1429
82214756 1430 timekeeping_forward_now(tks);
c528f7c6 1431
82214756
AMB
1432 /* Make sure the proposed value is valid */
1433 tmp = timespec64_add(tk_xtime(tks), *ts);
1434 if (timespec64_compare(&tks->wall_to_monotonic, ts) > 0 ||
1435 !timespec64_valid_settod(&tmp)) {
1436 timekeeping_restore_shadow(&tk_core);
1437 return -EINVAL;
1438 }
c528f7c6 1439
82214756
AMB
1440 tk_xtime_add(tks, ts);
1441 tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, *ts));
1442 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1443 }
c528f7c6 1444
17a1b882
TG
1445 /* Signal hrtimers about time change */
1446 clock_was_set(CLOCK_SET_WALL);
82214756 1447 return 0;
c528f7c6 1448}
e0956dcc
AB
1449
1450/*
1451 * Indicates if there is an offset between the system clock and the hardware
1452 * clock/persistent clock/rtc.
1453 */
1454int persistent_clock_is_local;
1455
1456/*
1457 * Adjust the time obtained from the CMOS to be UTC time instead of
1458 * local time.
1459 *
1460 * This is ugly, but preferable to the alternatives. Otherwise we
1461 * would either need to write a program to do it in /etc/rc (and risk
1462 * confusion if the program gets run more than once; it would also be
1463 * hard to make the program warp the clock precisely n hours) or
1464 * compile in the timezone information into the kernel. Bad, bad....
1465 *
1466 * - TYT, 1992-01-01
1467 *
1468 * The best thing to do is to keep the CMOS clock in universal time (UTC)
1469 * as real UNIX machines always do it. This avoids all headaches about
1470 * daylight saving times and warping kernel clocks.
1471 */
1472void timekeeping_warp_clock(void)
1473{
1474 if (sys_tz.tz_minuteswest != 0) {
1572fa03 1475 struct timespec64 adjust;
e0956dcc
AB
1476
1477 persistent_clock_is_local = 1;
1478 adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1479 adjust.tv_nsec = 0;
1480 timekeeping_inject_offset(&adjust);
1481 }
1482}
c528f7c6 1483
199d280c 1484/*
40d9f827 1485 * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
cc244dda 1486 */
dd5d70e8 1487static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
cc244dda
JS
1488{
1489 tk->tai_offset = tai_offset;
04005f60 1490 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
cc244dda
JS
1491}
1492
199d280c 1493/*
8524070b
JS
1494 * change_clocksource - Swaps clocksources if a new one is available
1495 *
1496 * Accumulates current time interval and initializes new clocksource
1497 */
75c5158f 1498static int change_clocksource(void *data)
8524070b 1499{
1f7226b1 1500 struct clocksource *new = data, *old = NULL;
8524070b 1501
09ac369c 1502 /*
1f7226b1
TG
1503 * If the clocksource is in a module, get a module reference.
1504 * Succeeds for built-in code (owner == NULL) as well. Abort if the
1505 * reference can't be acquired.
09ac369c 1506 */
1f7226b1
TG
1507 if (!try_module_get(new->owner))
1508 return 0;
d4c7c288 1509
1f7226b1
TG
1510 /* Abort if the device can't be enabled */
1511 if (new->enable && new->enable(new) != 0) {
1512 module_put(new->owner);
1513 return 0;
d4c7c288
NS
1514 }
1515
351619fc
AMB
1516 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1517 struct timekeeper *tks = &tk_core.shadow_timekeeper;
f695cf94 1518
351619fc
AMB
1519 timekeeping_forward_now(tks);
1520 old = tks->tkr_mono.clock;
1521 tk_setup_internals(tks, new);
1522 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1523 }
f695cf94 1524
d4c7c288
NS
1525 if (old) {
1526 if (old->disable)
1527 old->disable(old);
d4c7c288
NS
1528 module_put(old->owner);
1529 }
1530
75c5158f
MS
1531 return 0;
1532}
8524070b 1533
75c5158f
MS
1534/**
1535 * timekeeping_notify - Install a new clock source
1536 * @clock: pointer to the clock source
1537 *
1538 * This function is called from clocksource.c after a new, better clock
1539 * source has been registered. The caller holds the clocksource_mutex.
1540 */
ba919d1c 1541int timekeeping_notify(struct clocksource *clock)
75c5158f 1542{
3fdb14fd 1543 struct timekeeper *tk = &tk_core.timekeeper;
4e250fdd 1544
876e7881 1545 if (tk->tkr_mono.clock == clock)
ba919d1c 1546 return 0;
75c5158f 1547 stop_machine(change_clocksource, clock, NULL);
8524070b 1548 tick_clock_notify();
876e7881 1549 return tk->tkr_mono.clock == clock ? 0 : -1;
8524070b 1550}
75c5158f 1551
2d42244a 1552/**
fb7fcc96 1553 * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
cdba2ec5 1554 * @ts: pointer to the timespec64 to be set
2d42244a
JS
1555 *
1556 * Returns the raw monotonic time (completely un-modified by ntp)
1557 */
fb7fcc96 1558void ktime_get_raw_ts64(struct timespec64 *ts)
2d42244a 1559{
3fdb14fd 1560 struct timekeeper *tk = &tk_core.timekeeper;
e1e41b6c 1561 unsigned int seq;
acc89612 1562 u64 nsecs;
2d42244a
JS
1563
1564 do {
3fdb14fd 1565 seq = read_seqcount_begin(&tk_core.seq);
fc6eead7 1566 ts->tv_sec = tk->raw_sec;
4a4ad80d 1567 nsecs = timekeeping_get_ns(&tk->tkr_raw);
2d42244a 1568
3fdb14fd 1569 } while (read_seqcount_retry(&tk_core.seq, seq));
2d42244a 1570
fc6eead7
JS
1571 ts->tv_nsec = 0;
1572 timespec64_add_ns(ts, nsecs);
2d42244a 1573}
fb7fcc96 1574EXPORT_SYMBOL(ktime_get_raw_ts64);
cdba2ec5 1575
2d42244a 1576
8524070b 1577/**
cf4fc6cb 1578 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
8524070b 1579 */
cf4fc6cb 1580int timekeeping_valid_for_hres(void)
8524070b 1581{
3fdb14fd 1582 struct timekeeper *tk = &tk_core.timekeeper;
e1e41b6c 1583 unsigned int seq;
8524070b
JS
1584 int ret;
1585
1586 do {
3fdb14fd 1587 seq = read_seqcount_begin(&tk_core.seq);
8524070b 1588
876e7881 1589 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
8524070b 1590
3fdb14fd 1591 } while (read_seqcount_retry(&tk_core.seq, seq));
8524070b
JS
1592
1593 return ret;
1594}
1595
98962465
JH
1596/**
1597 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
98962465
JH
1598 */
1599u64 timekeeping_max_deferment(void)
1600{
3fdb14fd 1601 struct timekeeper *tk = &tk_core.timekeeper;
e1e41b6c 1602 unsigned int seq;
70471f2f 1603 u64 ret;
42e71e81 1604
70471f2f 1605 do {
3fdb14fd 1606 seq = read_seqcount_begin(&tk_core.seq);
70471f2f 1607
876e7881 1608 ret = tk->tkr_mono.clock->max_idle_ns;
70471f2f 1609
3fdb14fd 1610 } while (read_seqcount_retry(&tk_core.seq, seq));
70471f2f
JS
1611
1612 return ret;
98962465
JH
1613}
1614
8524070b 1615/**
92661788 1616 * read_persistent_clock64 - Return time from the persistent clock.
6e5a9190 1617 * @ts: Pointer to the storage for the readout value
8524070b
JS
1618 *
1619 * Weak dummy function for arches that do not yet support it.
d4f587c6
MS
1620 * Reads the time from the battery backed persistent clock.
1621 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
8524070b
JS
1622 *
1623 * XXX - Do be sure to remove it once all arches implement it.
1624 */
92661788 1625void __weak read_persistent_clock64(struct timespec64 *ts)
8524070b 1626{
d4f587c6
MS
1627 ts->tv_sec = 0;
1628 ts->tv_nsec = 0;
8524070b
JS
1629}
1630
23970e38 1631/**
3eca9937
PT
1632 * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
1633 * from the boot.
f3cb8080
RD
1634 * @wall_time: current time as returned by persistent clock
1635 * @boot_offset: offset that is defined as wall_time - boot_time
23970e38
MS
1636 *
1637 * Weak dummy function for arches that do not yet support it.
29efc461 1638 *
4b1b7f80
PT
1639 * The default function calculates offset based on the current value of
1640 * local_clock(). This way architectures that support sched_clock() but don't
1641 * support dedicated boot time clock will provide the best estimate of the
1642 * boot time.
23970e38 1643 */
3eca9937
PT
1644void __weak __init
1645read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
1646 struct timespec64 *boot_offset)
23970e38 1647{
3eca9937 1648 read_persistent_clock64(wall_time);
4b1b7f80 1649 *boot_offset = ns_to_timespec64(local_clock());
23970e38
MS
1650}
1651
a5f9e4e4
AMB
1652static __init void tkd_basic_setup(struct tk_data *tkd)
1653{
1654 raw_spin_lock_init(&tkd->lock);
1655 seqcount_raw_spinlock_init(&tkd->seq, &tkd->lock);
1656}
1657
f473e5f4
MO
1658/*
1659 * Flag reflecting whether timekeeping_resume() has injected sleeptime.
1660 *
1661 * The flag starts of false and is only set when a suspend reaches
1662 * timekeeping_suspend(), timekeeping_resume() sets it to false when the
1663 * timekeeper clocksource is not stopping across suspend and has been
1664 * used to update sleep time. If the timekeeper clocksource has stopped
1665 * then the flag stays true and is used by the RTC resume code to decide
1666 * whether sleeptime must be injected and if so the flag gets false then.
1667 *
1668 * If a suspend fails before reaching timekeeping_resume() then the flag
1669 * stays false and prevents erroneous sleeptime injection.
1670 */
1671static bool suspend_timing_needed;
0fa88cb4
XP
1672
1673/* Flag for if there is a persistent clock on this platform */
1674static bool persistent_clock_exists;
1675
8524070b
JS
1676/*
1677 * timekeeping_init - Initializes the clocksource and common timekeeping values
1678 */
1679void __init timekeeping_init(void)
1680{
3eca9937 1681 struct timespec64 wall_time, boot_offset, wall_to_mono;
2cab490b 1682 struct timekeeper *tks = &tk_core.shadow_timekeeper;
155ec602 1683 struct clocksource *clock;
8c4799b1 1684
a5f9e4e4 1685 tkd_basic_setup(&tk_core);
4e8b1452 1686
3eca9937 1687 read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
7a8e61f8 1688 if (timespec64_valid_settod(&wall_time) &&
3eca9937
PT
1689 timespec64_to_ns(&wall_time) > 0) {
1690 persistent_clock_exists = true;
684ad537 1691 } else if (timespec64_to_ns(&wall_time) != 0) {
3eca9937
PT
1692 pr_warn("Persistent clock returned invalid value");
1693 wall_time = (struct timespec64){0};
4e8b1452 1694 }
8524070b 1695
3eca9937
PT
1696 if (timespec64_compare(&wall_time, &boot_offset) < 0)
1697 boot_offset = (struct timespec64){0};
1698
1699 /*
1700 * We want set wall_to_mono, so the following is true:
1701 * wall time + wall_to_mono = boot time
1702 */
1703 wall_to_mono = timespec64_sub(boot_offset, wall_time);
1704
8c4799b1 1705 guard(raw_spinlock_irqsave)(&tk_core.lock);
2cab490b 1706
06c017fd
JS
1707 ntp_init();
1708
f1b82746 1709 clock = clocksource_default_clock();
a0f7d48b
MS
1710 if (clock->enable)
1711 clock->enable(clock);
2cab490b 1712 tk_setup_internals(tks, clock);
1e75fa8b 1713
2cab490b
AMB
1714 tk_set_xtime(tks, &wall_time);
1715 tks->raw_sec = 0;
6d0ef903 1716
2cab490b 1717 tk_set_wall_to_mono(tks, wall_to_mono);
48cdc135 1718
2cab490b 1719 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
8524070b
JS
1720}
1721
264bb3f7 1722/* time in seconds when suspend began for persistent clock */
7d489d15 1723static struct timespec64 timekeeping_suspend_time;
8524070b 1724
304529b1
JS
1725/**
1726 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
6e5a9190
AS
1727 * @tk: Pointer to the timekeeper to be updated
1728 * @delta: Pointer to the delta value in timespec64 format
304529b1
JS
1729 *
1730 * Takes a timespec offset measuring a suspend interval and properly
1731 * adds the sleep offset to the timekeeping variables.
1732 */
f726a697 1733static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
985e6950 1734 const struct timespec64 *delta)
304529b1 1735{
7d489d15 1736 if (!timespec64_valid_strict(delta)) {
6d9bcb62
JS
1737 printk_deferred(KERN_WARNING
1738 "__timekeeping_inject_sleeptime: Invalid "
1739 "sleep delta value!\n");
cb5de2f8
JS
1740 return;
1741 }
f726a697 1742 tk_xtime_add(tk, delta);
a3ed0e43 1743 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
47da70d3 1744 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
5c83545f 1745 tk_debug_account_sleep_time(delta);
304529b1
JS
1746}
1747
7f298139 1748#if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
f3cb8080 1749/*
0fa88cb4
XP
1750 * We have three kinds of time sources to use for sleep time
1751 * injection, the preference order is:
1752 * 1) non-stop clocksource
1753 * 2) persistent clock (ie: RTC accessible when irqs are off)
1754 * 3) RTC
1755 *
1756 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1757 * If system has neither 1) nor 2), 3) will be used finally.
1758 *
1759 *
1760 * If timekeeping has injected sleeptime via either 1) or 2),
1761 * 3) becomes needless, so in this case we don't need to call
1762 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1763 * means.
1764 */
1765bool timekeeping_rtc_skipresume(void)
1766{
f473e5f4 1767 return !suspend_timing_needed;
0fa88cb4
XP
1768}
1769
f3cb8080 1770/*
0fa88cb4
XP
1771 * 1) can be determined whether to use or not only when doing
1772 * timekeeping_resume() which is invoked after rtc_suspend(),
1773 * so we can't skip rtc_suspend() surely if system has 1).
1774 *
1775 * But if system has 2), 2) will definitely be used, so in this
1776 * case we don't need to call rtc_suspend(), and this is what
1777 * timekeeping_rtc_skipsuspend() means.
1778 */
1779bool timekeeping_rtc_skipsuspend(void)
1780{
1781 return persistent_clock_exists;
1782}
1783
304529b1 1784/**
04d90890 1785 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1786 * @delta: pointer to a timespec64 delta value
304529b1 1787 *
2ee96632 1788 * This hook is for architectures that cannot support read_persistent_clock64
304529b1 1789 * because their RTC/persistent clock is only accessible when irqs are enabled.
0fa88cb4 1790 * and also don't have an effective nonstop clocksource.
304529b1
JS
1791 *
1792 * This function should only be called by rtc_resume(), and allows
1793 * a suspend offset to be injected into the timekeeping values.
1794 */
985e6950 1795void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
304529b1 1796{
2b473e65
AMB
1797 scoped_guard(raw_spinlock_irqsave, &tk_core.lock) {
1798 struct timekeeper *tks = &tk_core.shadow_timekeeper;
304529b1 1799
2b473e65
AMB
1800 suspend_timing_needed = false;
1801 timekeeping_forward_now(tks);
1802 __timekeeping_inject_sleeptime(tks, delta);
1803 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1804 }
304529b1 1805
17a1b882
TG
1806 /* Signal hrtimers about time change */
1807 clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
304529b1 1808}
7f298139 1809#endif
304529b1 1810
8524070b
JS
1811/**
1812 * timekeeping_resume - Resumes the generic timekeeping subsystem.
8524070b 1813 */
124cf911 1814void timekeeping_resume(void)
8524070b 1815{
b2350d95
AMB
1816 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1817 struct clocksource *clock = tks->tkr_mono.clock;
7d489d15 1818 struct timespec64 ts_new, ts_delta;
f473e5f4 1819 bool inject_sleeptime = false;
b2350d95
AMB
1820 u64 cycle_now, nsec;
1821 unsigned long flags;
d4f587c6 1822
2ee96632 1823 read_persistent_clock64(&ts_new);
8524070b 1824
adc78e6b 1825 clockevents_resume();
d10ff3fb
TG
1826 clocksource_resume();
1827
8c4799b1 1828 raw_spin_lock_irqsave(&tk_core.lock, flags);
8524070b 1829
e445cf1c
FT
1830 /*
1831 * After system resumes, we need to calculate the suspended time and
1832 * compensate it for the OS time. There are 3 sources that could be
1833 * used: Nonstop clocksource during suspend, persistent clock and rtc
1834 * device.
1835 *
1836 * One specific platform may have 1 or 2 or all of them, and the
1837 * preference will be:
1838 * suspend-nonstop clocksource -> persistent clock -> rtc
1839 * The less preferred source will only be tried if there is no better
1840 * usable source. The rtc part is handled separately in rtc core code.
1841 */
b2350d95 1842 cycle_now = tk_clock_read(&tks->tkr_mono);
39232ed5
BW
1843 nsec = clocksource_stop_suspend_timing(clock, cycle_now);
1844 if (nsec > 0) {
7d489d15 1845 ts_delta = ns_to_timespec64(nsec);
f473e5f4 1846 inject_sleeptime = true;
7d489d15
JS
1847 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1848 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
f473e5f4 1849 inject_sleeptime = true;
8524070b 1850 }
e445cf1c 1851
f473e5f4
MO
1852 if (inject_sleeptime) {
1853 suspend_timing_needed = false;
b2350d95 1854 __timekeeping_inject_sleeptime(tks, &ts_delta);
f473e5f4 1855 }
e445cf1c
FT
1856
1857 /* Re-base the last cycle value */
b2350d95
AMB
1858 tks->tkr_mono.cycle_last = cycle_now;
1859 tks->tkr_raw.cycle_last = cycle_now;
4a4ad80d 1860
b2350d95 1861 tks->ntp_error = 0;
8524070b 1862 timekeeping_suspended = 0;
b2350d95 1863 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
8c4799b1 1864 raw_spin_unlock_irqrestore(&tk_core.lock, flags);
8524070b
JS
1865
1866 touch_softlockup_watchdog();
1867
a761a67f 1868 /* Resume the clockevent device(s) and hrtimers */
4ffee521 1869 tick_resume();
a761a67f
TG
1870 /* Notify timerfd as resume is equivalent to clock_was_set() */
1871 timerfd_resume();
8524070b
JS
1872}
1873
124cf911 1874int timekeeping_suspend(void)
8524070b 1875{
d05eae87
AMB
1876 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1877 struct timespec64 delta, delta_delta;
1878 static struct timespec64 old_delta;
39232ed5 1879 struct clocksource *curr_clock;
d05eae87 1880 unsigned long flags;
39232ed5 1881 u64 cycle_now;
8524070b 1882
2ee96632 1883 read_persistent_clock64(&timekeeping_suspend_time);
3be90950 1884
0d6bd995
ZM
1885 /*
1886 * On some systems the persistent_clock can not be detected at
1887 * timekeeping_init by its return value, so if we see a valid
1888 * value returned, update the persistent_clock_exists flag.
1889 */
1890 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
0fa88cb4 1891 persistent_clock_exists = true;
0d6bd995 1892
f473e5f4
MO
1893 suspend_timing_needed = true;
1894
8c4799b1 1895 raw_spin_lock_irqsave(&tk_core.lock, flags);
d05eae87 1896 timekeeping_forward_now(tks);
8524070b 1897 timekeeping_suspended = 1;
cb33217b 1898
39232ed5
BW
1899 /*
1900 * Since we've called forward_now, cycle_last stores the value
1901 * just read from the current clocksource. Save this to potentially
1902 * use in suspend timing.
1903 */
d05eae87
AMB
1904 curr_clock = tks->tkr_mono.clock;
1905 cycle_now = tks->tkr_mono.cycle_last;
39232ed5
BW
1906 clocksource_start_suspend_timing(curr_clock, cycle_now);
1907
0fa88cb4 1908 if (persistent_clock_exists) {
cb33217b 1909 /*
264bb3f7
XP
1910 * To avoid drift caused by repeated suspend/resumes,
1911 * which each can add ~1 second drift error,
1912 * try to compensate so the difference in system time
1913 * and persistent_clock time stays close to constant.
cb33217b 1914 */
d05eae87 1915 delta = timespec64_sub(tk_xtime(tks), timekeeping_suspend_time);
264bb3f7
XP
1916 delta_delta = timespec64_sub(delta, old_delta);
1917 if (abs(delta_delta.tv_sec) >= 2) {
1918 /*
1919 * if delta_delta is too large, assume time correction
1920 * has occurred and set old_delta to the current delta.
1921 */
1922 old_delta = delta;
1923 } else {
1924 /* Otherwise try to adjust old_system to compensate */
1925 timekeeping_suspend_time =
1926 timespec64_add(timekeeping_suspend_time, delta_delta);
1927 }
cb33217b 1928 }
330a1617 1929
d05eae87
AMB
1930 timekeeping_update_from_shadow(&tk_core, 0);
1931 halt_fast_timekeeper(tks);
8c4799b1 1932 raw_spin_unlock_irqrestore(&tk_core.lock, flags);
8524070b 1933
4ffee521 1934 tick_suspend();
c54a42b1 1935 clocksource_suspend();
adc78e6b 1936 clockevents_suspend();
8524070b
JS
1937
1938 return 0;
1939}
1940
1941/* sysfs resume/suspend bits for timekeeping */
e1a85b2c 1942static struct syscore_ops timekeeping_syscore_ops = {
8524070b
JS
1943 .resume = timekeeping_resume,
1944 .suspend = timekeeping_suspend,
8524070b
JS
1945};
1946
e1a85b2c 1947static int __init timekeeping_init_ops(void)
8524070b 1948{
e1a85b2c
RW
1949 register_syscore_ops(&timekeeping_syscore_ops);
1950 return 0;
8524070b 1951}
e1a85b2c 1952device_initcall(timekeeping_init_ops);
8524070b
JS
1953
1954/*
dc491596 1955 * Apply a multiplier adjustment to the timekeeper
8524070b 1956 */
dc491596
JS
1957static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1958 s64 offset,
78b98e3c 1959 s32 mult_adj)
8524070b 1960{
dc491596 1961 s64 interval = tk->cycle_interval;
8524070b 1962
78b98e3c
ML
1963 if (mult_adj == 0) {
1964 return;
1965 } else if (mult_adj == -1) {
dc491596 1966 interval = -interval;
78b98e3c
ML
1967 offset = -offset;
1968 } else if (mult_adj != 1) {
1969 interval *= mult_adj;
1970 offset *= mult_adj;
1d17d174 1971 }
8524070b 1972
c2bc1111
JS
1973 /*
1974 * So the following can be confusing.
1975 *
dc491596 1976 * To keep things simple, lets assume mult_adj == 1 for now.
c2bc1111 1977 *
dc491596 1978 * When mult_adj != 1, remember that the interval and offset values
c2bc1111
JS
1979 * have been appropriately scaled so the math is the same.
1980 *
1981 * The basic idea here is that we're increasing the multiplier
1982 * by one, this causes the xtime_interval to be incremented by
1983 * one cycle_interval. This is because:
1984 * xtime_interval = cycle_interval * mult
1985 * So if mult is being incremented by one:
1986 * xtime_interval = cycle_interval * (mult + 1)
1987 * Its the same as:
1988 * xtime_interval = (cycle_interval * mult) + cycle_interval
1989 * Which can be shortened to:
1990 * xtime_interval += cycle_interval
1991 *
1992 * So offset stores the non-accumulated cycles. Thus the current
1993 * time (in shifted nanoseconds) is:
1994 * now = (offset * adj) + xtime_nsec
1995 * Now, even though we're adjusting the clock frequency, we have
1996 * to keep time consistent. In other words, we can't jump back
1997 * in time, and we also want to avoid jumping forward in time.
1998 *
1999 * So given the same offset value, we need the time to be the same
2000 * both before and after the freq adjustment.
2001 * now = (offset * adj_1) + xtime_nsec_1
2002 * now = (offset * adj_2) + xtime_nsec_2
2003 * So:
2004 * (offset * adj_1) + xtime_nsec_1 =
2005 * (offset * adj_2) + xtime_nsec_2
2006 * And we know:
2007 * adj_2 = adj_1 + 1
2008 * So:
2009 * (offset * adj_1) + xtime_nsec_1 =
2010 * (offset * (adj_1+1)) + xtime_nsec_2
2011 * (offset * adj_1) + xtime_nsec_1 =
2012 * (offset * adj_1) + offset + xtime_nsec_2
2013 * Canceling the sides:
2014 * xtime_nsec_1 = offset + xtime_nsec_2
2015 * Which gives us:
2016 * xtime_nsec_2 = xtime_nsec_1 - offset
4bf07f65 2017 * Which simplifies to:
c2bc1111 2018 * xtime_nsec -= offset
c2bc1111 2019 */
876e7881 2020 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
6067dc5a 2021 /* NTP adjustment caused clocksource mult overflow */
2022 WARN_ON_ONCE(1);
2023 return;
2024 }
2025
876e7881 2026 tk->tkr_mono.mult += mult_adj;
f726a697 2027 tk->xtime_interval += interval;
876e7881 2028 tk->tkr_mono.xtime_nsec -= offset;
dc491596
JS
2029}
2030
2031/*
78b98e3c
ML
2032 * Adjust the timekeeper's multiplier to the correct frequency
2033 * and also to reduce the accumulated error value.
dc491596 2034 */
78b98e3c 2035static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
dc491596 2036{
14f1e3b3 2037 u64 ntp_tl = ntp_tick_length();
78b98e3c 2038 u32 mult;
dc491596 2039
ec02b076 2040 /*
78b98e3c
ML
2041 * Determine the multiplier from the current NTP tick length.
2042 * Avoid expensive division when the tick length doesn't change.
ec02b076 2043 */
14f1e3b3 2044 if (likely(tk->ntp_tick == ntp_tl)) {
78b98e3c
ML
2045 mult = tk->tkr_mono.mult - tk->ntp_err_mult;
2046 } else {
14f1e3b3 2047 tk->ntp_tick = ntp_tl;
78b98e3c
ML
2048 mult = div64_u64((tk->ntp_tick >> tk->ntp_error_shift) -
2049 tk->xtime_remainder, tk->cycle_interval);
ec02b076 2050 }
dc491596 2051
78b98e3c
ML
2052 /*
2053 * If the clock is behind the NTP time, increase the multiplier by 1
2054 * to catch up with it. If it's ahead and there was a remainder in the
2055 * tick division, the clock will slow down. Otherwise it will stay
2056 * ahead until the tick length changes to a non-divisible value.
2057 */
2058 tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
2059 mult += tk->ntp_err_mult;
dc491596 2060
78b98e3c 2061 timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
dc491596 2062
876e7881
PZ
2063 if (unlikely(tk->tkr_mono.clock->maxadj &&
2064 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2065 > tk->tkr_mono.clock->maxadj))) {
dc491596
JS
2066 printk_once(KERN_WARNING
2067 "Adjusting %s more than 11%% (%ld vs %ld)\n",
876e7881
PZ
2068 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2069 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
dc491596 2070 }
2a8c0883
JS
2071
2072 /*
2073 * It may be possible that when we entered this function, xtime_nsec
2074 * was very small. Further, if we're slightly speeding the clocksource
2075 * in the code above, its possible the required corrective factor to
2076 * xtime_nsec could cause it to underflow.
2077 *
78b98e3c
ML
2078 * Now, since we have already accumulated the second and the NTP
2079 * subsystem has been notified via second_overflow(), we need to skip
2080 * the next update.
2a8c0883 2081 */
876e7881 2082 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
78b98e3c
ML
2083 tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
2084 tk->tkr_mono.shift;
2085 tk->xtime_sec--;
2086 tk->skip_second_overflow = 1;
2a8c0883 2087 }
8524070b
JS
2088}
2089
199d280c 2090/*
1f4f9487
JS
2091 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2092 *
571af55a 2093 * Helper function that accumulates the nsecs greater than a second
1f4f9487
JS
2094 * from the xtime_nsec field to the xtime_secs field.
2095 * It also calls into the NTP code to handle leapsecond processing.
1f4f9487 2096 */
780427f0 2097static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
1f4f9487 2098{
876e7881 2099 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
5258d3f2 2100 unsigned int clock_set = 0;
1f4f9487 2101
876e7881 2102 while (tk->tkr_mono.xtime_nsec >= nsecps) {
1f4f9487
JS
2103 int leap;
2104
876e7881 2105 tk->tkr_mono.xtime_nsec -= nsecps;
1f4f9487
JS
2106 tk->xtime_sec++;
2107
78b98e3c
ML
2108 /*
2109 * Skip NTP update if this second was accumulated before,
2110 * i.e. xtime_nsec underflowed in timekeeping_adjust()
2111 */
2112 if (unlikely(tk->skip_second_overflow)) {
2113 tk->skip_second_overflow = 0;
2114 continue;
2115 }
2116
1f4f9487
JS
2117 /* Figure out if its a leap sec and apply if needed */
2118 leap = second_overflow(tk->xtime_sec);
6d0ef903 2119 if (unlikely(leap)) {
7d489d15 2120 struct timespec64 ts;
6d0ef903
JS
2121
2122 tk->xtime_sec += leap;
1f4f9487 2123
6d0ef903
JS
2124 ts.tv_sec = leap;
2125 ts.tv_nsec = 0;
2126 tk_set_wall_to_mono(tk,
7d489d15 2127 timespec64_sub(tk->wall_to_monotonic, ts));
6d0ef903 2128
cc244dda
JS
2129 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2130
5258d3f2 2131 clock_set = TK_CLOCK_WAS_SET;
6d0ef903 2132 }
1f4f9487 2133 }
5258d3f2 2134 return clock_set;
1f4f9487
JS
2135}
2136
199d280c 2137/*
a092ff0f
JS
2138 * logarithmic_accumulation - shifted accumulation of cycles
2139 *
2140 * This functions accumulates a shifted interval of cycles into
b0294f30 2141 * a shifted interval nanoseconds. Allows for O(log) accumulation
a092ff0f
JS
2142 * loop.
2143 *
2144 * Returns the unconsumed cycles.
2145 */
a5a1d1c2
TG
2146static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2147 u32 shift, unsigned int *clock_set)
a092ff0f 2148{
a5a1d1c2 2149 u64 interval = tk->cycle_interval << shift;
3d88d56c 2150 u64 snsec_per_sec;
a092ff0f 2151
571af55a 2152 /* If the offset is smaller than a shifted interval, do nothing */
23a9537a 2153 if (offset < interval)
a092ff0f
JS
2154 return offset;
2155
2156 /* Accumulate one shifted interval */
23a9537a 2157 offset -= interval;
876e7881 2158 tk->tkr_mono.cycle_last += interval;
4a4ad80d 2159 tk->tkr_raw.cycle_last += interval;
a092ff0f 2160
876e7881 2161 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
5258d3f2 2162 *clock_set |= accumulate_nsecs_to_secs(tk);
a092ff0f 2163
deda2e81 2164 /* Accumulate raw time */
3d88d56c
JS
2165 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2166 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2167 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2168 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
fc6eead7 2169 tk->raw_sec++;
a092ff0f
JS
2170 }
2171
2172 /* Accumulate error between NTP and clock interval */
375f45b5 2173 tk->ntp_error += tk->ntp_tick << shift;
f726a697
JS
2174 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2175 (tk->ntp_error_shift + shift);
a092ff0f
JS
2176
2177 return offset;
2178}
2179
b061c7a5
ML
2180/*
2181 * timekeeping_advance - Updates the timekeeper to the current time and
2182 * current NTP tick length
8524070b 2183 */
1b267793 2184static bool timekeeping_advance(enum timekeeping_adv_mode mode)
8524070b 2185{
20c7b582 2186 struct timekeeper *tk = &tk_core.shadow_timekeeper;
3fdb14fd 2187 struct timekeeper *real_tk = &tk_core.timekeeper;
5258d3f2 2188 unsigned int clock_set = 0;
324a2219 2189 int shift = 0, maxshift;
b71f9804 2190 u64 offset, orig_offset;
70471f2f 2191
8c4799b1 2192 guard(raw_spinlock_irqsave)(&tk_core.lock);
8524070b
JS
2193
2194 /* Make sure we're fully resumed: */
2195 if (unlikely(timekeeping_suspended))
c2a32956 2196 return false;
8524070b 2197
ceea5e37 2198 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
76031d95
TG
2199 tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
2200 tk->tkr_mono.clock->max_raw_delta);
b71f9804 2201 orig_offset = offset;
bf2ac312 2202 /* Check if there's really nothing to do */
b061c7a5 2203 if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
c2a32956 2204 return false;
3c17ad19 2205
324a2219
TG
2206 /*
2207 * With NO_HZ we may have to accumulate many cycle_intervals
2208 * (think "ticks") worth of time at once. To do this efficiently,
2209 * we calculate the largest doubling multiple of cycle_intervals
2210 * that is smaller than the offset. We then accumulate that
2211 * chunk in one go, and then try to consume the next smaller
2212 * doubled multiple.
2213 */
2214 shift = ilog2(offset) - ilog2(tk->cycle_interval);
2215 shift = max(0, shift);
2216 /* Bound shift to one less than what overflows tick_length */
2217 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2218 shift = min(shift, maxshift);
2219 while (offset >= tk->cycle_interval) {
2220 offset = logarithmic_accumulation(tk, offset, shift, &clock_set);
2221 if (offset < tk->cycle_interval<<shift)
2222 shift--;
2223 }
8524070b 2224
78b98e3c 2225 /* Adjust the multiplier to correct NTP error */
4e250fdd 2226 timekeeping_adjust(tk, offset);
8524070b 2227
6a867a39
JS
2228 /*
2229 * Finally, make sure that after the rounding
1e75fa8b 2230 * xtime_nsec isn't larger than NSEC_PER_SEC
6a867a39 2231 */
5258d3f2 2232 clock_set |= accumulate_nsecs_to_secs(tk);
83f57a11 2233
b71f9804
TG
2234 /*
2235 * To avoid inconsistencies caused adjtimex TK_ADV_FREQ calls
2236 * making small negative adjustments to the base xtime_nsec
2237 * value, only update the coarse clocks if we accumulated time
2238 */
2239 if (orig_offset != offset)
2240 tk_update_coarse_nsecs(tk);
2241
5aa6c43e 2242 timekeeping_update_from_shadow(&tk_core, clock_set);
1b267793
TG
2243
2244 return !!clock_set;
8524070b 2245}
7c3f1a57 2246
b061c7a5
ML
2247/**
2248 * update_wall_time - Uses the current clocksource to increment the wall time
2249 *
2250 */
2251void update_wall_time(void)
2252{
1b267793
TG
2253 if (timekeeping_advance(TK_ADV_TICK))
2254 clock_was_set_delayed();
b061c7a5
ML
2255}
2256
7c3f1a57 2257/**
d08c0cdd
JS
2258 * getboottime64 - Return the real time of system boot.
2259 * @ts: pointer to the timespec64 to be set
7c3f1a57 2260 *
d08c0cdd 2261 * Returns the wall-time of boot in a timespec64.
7c3f1a57
TJ
2262 *
2263 * This is based on the wall_to_monotonic offset and the total suspend
2264 * time. Calls to settimeofday will affect the value returned (which
2265 * basically means that however wrong your real time clock is at boot time,
2266 * you get the right time here).
2267 */
d08c0cdd 2268void getboottime64(struct timespec64 *ts)
7c3f1a57 2269{
3fdb14fd 2270 struct timekeeper *tk = &tk_core.timekeeper;
a3ed0e43 2271 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
02cba159 2272
d08c0cdd 2273 *ts = ktime_to_timespec64(t);
7c3f1a57 2274}
d08c0cdd 2275EXPORT_SYMBOL_GPL(getboottime64);
7c3f1a57 2276
fb7fcc96 2277void ktime_get_coarse_real_ts64(struct timespec64 *ts)
2c6b47de 2278{
3fdb14fd 2279 struct timekeeper *tk = &tk_core.timekeeper;
e1e41b6c 2280 unsigned int seq;
2c6b47de
JS
2281
2282 do {
3fdb14fd 2283 seq = read_seqcount_begin(&tk_core.seq);
83f57a11 2284
b71f9804 2285 *ts = tk_xtime_coarse(tk);
3fdb14fd 2286 } while (read_seqcount_retry(&tk_core.seq, seq));
2c6b47de 2287}
fb7fcc96 2288EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
da15cfda 2289
ee3283c6
JL
2290/**
2291 * ktime_get_coarse_real_ts64_mg - return latter of coarse grained time or floor
2292 * @ts: timespec64 to be filled
2293 *
2294 * Fetch the global mg_floor value, convert it to realtime and compare it
2295 * to the current coarse-grained time. Fill @ts with whichever is
2296 * latest. Note that this is a filesystem-specific interface and should be
2297 * avoided outside of that context.
2298 */
2299void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
2300{
2301 struct timekeeper *tk = &tk_core.timekeeper;
2302 u64 floor = atomic64_read(&mg_floor);
2303 ktime_t f_real, offset, coarse;
2304 unsigned int seq;
2305
2306 do {
2307 seq = read_seqcount_begin(&tk_core.seq);
b71f9804 2308 *ts = tk_xtime_coarse(tk);
ee3283c6
JL
2309 offset = tk_core.timekeeper.offs_real;
2310 } while (read_seqcount_retry(&tk_core.seq, seq));
2311
2312 coarse = timespec64_to_ktime(*ts);
2313 f_real = ktime_add(floor, offset);
2314 if (ktime_after(f_real, coarse))
2315 *ts = ktime_to_timespec64(f_real);
2316}
2317
2318/**
2319 * ktime_get_real_ts64_mg - attempt to update floor value and return result
2320 * @ts: pointer to the timespec to be set
2321 *
2322 * Get a monotonic fine-grained time value and attempt to swap it into
2323 * mg_floor. If that succeeds then accept the new floor value. If it fails
2324 * then another task raced in during the interim time and updated the
2325 * floor. Since any update to the floor must be later than the previous
2326 * floor, either outcome is acceptable.
2327 *
2328 * Typically this will be called after calling ktime_get_coarse_real_ts64_mg(),
2329 * and determining that the resulting coarse-grained timestamp did not effect
2330 * a change in ctime. Any more recent floor value would effect a change to
2331 * ctime, so there is no need to retry the atomic64_try_cmpxchg() on failure.
2332 *
2333 * @ts will be filled with the latest floor value, regardless of the outcome of
2334 * the cmpxchg. Note that this is a filesystem specific interface and should be
2335 * avoided outside of that context.
2336 */
2337void ktime_get_real_ts64_mg(struct timespec64 *ts)
2338{
2339 struct timekeeper *tk = &tk_core.timekeeper;
2340 ktime_t old = atomic64_read(&mg_floor);
2341 ktime_t offset, mono;
2342 unsigned int seq;
2343 u64 nsecs;
2344
2345 do {
2346 seq = read_seqcount_begin(&tk_core.seq);
2347
2348 ts->tv_sec = tk->xtime_sec;
2349 mono = tk->tkr_mono.base;
2350 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2351 offset = tk_core.timekeeper.offs_real;
2352 } while (read_seqcount_retry(&tk_core.seq, seq));
2353
2354 mono = ktime_add_ns(mono, nsecs);
2355
2356 /*
2357 * Attempt to update the floor with the new time value. As any
2358 * update must be later then the existing floor, and would effect
2359 * a change to ctime from the perspective of the current task,
2360 * accept the resulting floor value regardless of the outcome of
2361 * the swap.
2362 */
2363 if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
2364 ts->tv_nsec = 0;
2365 timespec64_add_ns(ts, nsecs);
2a153857 2366 timekeeping_inc_mg_floor_swaps();
ee3283c6
JL
2367 } else {
2368 /*
2369 * Another task changed mg_floor since "old" was fetched.
2370 * "old" has been updated with the latest value of "mg_floor".
2371 * That value is newer than the previous floor value, which
2372 * is enough to effect a change to ctime. Accept it.
2373 */
2374 *ts = ktime_to_timespec64(ktime_add(old, offset));
2375 }
2376}
2377
fb7fcc96 2378void ktime_get_coarse_ts64(struct timespec64 *ts)
da15cfda 2379{
3fdb14fd 2380 struct timekeeper *tk = &tk_core.timekeeper;
7d489d15 2381 struct timespec64 now, mono;
e1e41b6c 2382 unsigned int seq;
da15cfda
JS
2383
2384 do {
3fdb14fd 2385 seq = read_seqcount_begin(&tk_core.seq);
83f57a11 2386
b71f9804 2387 now = tk_xtime_coarse(tk);
4e250fdd 2388 mono = tk->wall_to_monotonic;
3fdb14fd 2389 } while (read_seqcount_retry(&tk_core.seq, seq));
da15cfda 2390
fb7fcc96 2391 set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
b71f9804 2392 now.tv_nsec + mono.tv_nsec);
da15cfda 2393}
fb7fcc96 2394EXPORT_SYMBOL(ktime_get_coarse_ts64);
871cf1e5
TH
2395
2396/*
d6ad4187 2397 * Must hold jiffies_lock
871cf1e5
TH
2398 */
2399void do_timer(unsigned long ticks)
2400{
2401 jiffies_64 += ticks;
46132e3a 2402 calc_global_load();
871cf1e5 2403}
48cf76f7 2404
f6c06abf 2405/**
76f41088 2406 * ktime_get_update_offsets_now - hrtimer helper
868a3e91 2407 * @cwsseq: pointer to check and store the clock was set sequence number
f6c06abf 2408 * @offs_real: pointer to storage for monotonic -> realtime offset
a3ed0e43 2409 * @offs_boot: pointer to storage for monotonic -> boottime offset
b7bc50e4 2410 * @offs_tai: pointer to storage for monotonic -> clock tai offset
f6c06abf 2411 *
868a3e91
TG
2412 * Returns current monotonic time and updates the offsets if the
2413 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2414 * different.
2415 *
b7bc50e4 2416 * Called from hrtimer_interrupt() or retrigger_next_event()
f6c06abf 2417 */
868a3e91 2418ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
a3ed0e43 2419 ktime_t *offs_boot, ktime_t *offs_tai)
f6c06abf 2420{
3fdb14fd 2421 struct timekeeper *tk = &tk_core.timekeeper;
f6c06abf 2422 unsigned int seq;
a37c0aad
TG
2423 ktime_t base;
2424 u64 nsecs;
f6c06abf
TG
2425
2426 do {
3fdb14fd 2427 seq = read_seqcount_begin(&tk_core.seq);
f6c06abf 2428
876e7881
PZ
2429 base = tk->tkr_mono.base;
2430 nsecs = timekeeping_get_ns(&tk->tkr_mono);
833f32d7
JS
2431 base = ktime_add_ns(base, nsecs);
2432
868a3e91
TG
2433 if (*cwsseq != tk->clock_was_set_seq) {
2434 *cwsseq = tk->clock_was_set_seq;
2435 *offs_real = tk->offs_real;
a3ed0e43 2436 *offs_boot = tk->offs_boot;
868a3e91
TG
2437 *offs_tai = tk->offs_tai;
2438 }
833f32d7
JS
2439
2440 /* Handle leapsecond insertion adjustments */
2456e855 2441 if (unlikely(base >= tk->next_leap_ktime))
833f32d7
JS
2442 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2443
3fdb14fd 2444 } while (read_seqcount_retry(&tk_core.seq, seq));
f6c06abf 2445
833f32d7 2446 return base;
f6c06abf 2447}
f6c06abf 2448
199d280c 2449/*
1572fa03 2450 * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
e0956dcc 2451 */
ead25417 2452static int timekeeping_validate_timex(const struct __kernel_timex *txc)
e0956dcc
AB
2453{
2454 if (txc->modes & ADJ_ADJTIME) {
2455 /* singleshot must not be used with any other mode bits */
2456 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2457 return -EINVAL;
2458 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2459 !capable(CAP_SYS_TIME))
2460 return -EPERM;
2461 } else {
2462 /* In order to modify anything, you gotta be super-user! */
2463 if (txc->modes && !capable(CAP_SYS_TIME))
2464 return -EPERM;
2465 /*
2466 * if the quartz is off by more than 10% then
2467 * something is VERY wrong!
2468 */
2469 if (txc->modes & ADJ_TICK &&
2470 (txc->tick < 900000/USER_HZ ||
2471 txc->tick > 1100000/USER_HZ))
2472 return -EINVAL;
2473 }
2474
2475 if (txc->modes & ADJ_SETOFFSET) {
2476 /* In order to inject time, you gotta be super-user! */
2477 if (!capable(CAP_SYS_TIME))
2478 return -EPERM;
2479
1572fa03
AB
2480 /*
2481 * Validate if a timespec/timeval used to inject a time
4bf07f65 2482 * offset is valid. Offsets can be positive or negative, so
1572fa03
AB
2483 * we don't check tv_sec. The value of the timeval/timespec
2484 * is the sum of its fields,but *NOTE*:
2485 * The field tv_usec/tv_nsec must always be non-negative and
2486 * we can't have more nanoseconds/microseconds than a second.
2487 */
2488 if (txc->time.tv_usec < 0)
2489 return -EINVAL;
e0956dcc 2490
1572fa03
AB
2491 if (txc->modes & ADJ_NANO) {
2492 if (txc->time.tv_usec >= NSEC_PER_SEC)
e0956dcc 2493 return -EINVAL;
e0956dcc 2494 } else {
1572fa03 2495 if (txc->time.tv_usec >= USEC_PER_SEC)
e0956dcc
AB
2496 return -EINVAL;
2497 }
2498 }
2499
2500 /*
2501 * Check for potential multiplication overflows that can
2502 * only happen on 64-bit systems:
2503 */
2504 if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2505 if (LLONG_MIN / PPM_SCALE > txc->freq)
2506 return -EINVAL;
2507 if (LLONG_MAX / PPM_SCALE < txc->freq)
2508 return -EINVAL;
2509 }
2510
2511 return 0;
2512}
2513
1366992e
JD
2514/**
2515 * random_get_entropy_fallback - Returns the raw clock source value,
2516 * used by random.c for platforms with no valid random_get_entropy().
2517 */
2518unsigned long random_get_entropy_fallback(void)
2519{
2520 struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
2521 struct clocksource *clock = READ_ONCE(tkr->clock);
2522
2523 if (unlikely(timekeeping_suspended || !clock))
2524 return 0;
2525 return clock->read(clock);
2526}
2527EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
e0956dcc 2528
aa6f9c59
JS
2529/**
2530 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
e1b6a78b 2531 * @txc: Pointer to kernel_timex structure containing NTP parameters
aa6f9c59 2532 */
ead25417 2533int do_adjtimex(struct __kernel_timex *txc)
aa6f9c59 2534{
7e8eda73 2535 struct audit_ntp_data ad;
35b603f8 2536 bool offset_set = false;
1b267793 2537 bool clock_set = false;
7d489d15 2538 struct timespec64 ts;
e4085693
JS
2539 int ret;
2540
2541 /* Validate the data before disabling interrupts */
1572fa03 2542 ret = timekeeping_validate_timex(txc);
e4085693
JS
2543 if (ret)
2544 return ret;
b8ac29b4 2545 add_device_randomness(txc, sizeof(*txc));
e4085693 2546
cef90377 2547 if (txc->modes & ADJ_SETOFFSET) {
1572fa03 2548 struct timespec64 delta;
ae455cb7 2549
cef90377
JS
2550 delta.tv_sec = txc->time.tv_sec;
2551 delta.tv_nsec = txc->time.tv_usec;
2552 if (!(txc->modes & ADJ_NANO))
2553 delta.tv_nsec *= 1000;
2554 ret = timekeeping_inject_offset(&delta);
2555 if (ret)
2556 return ret;
2d87a067 2557
35b603f8 2558 offset_set = delta.tv_sec != 0;
2d87a067 2559 audit_tk_injoffset(delta);
cef90377
JS
2560 }
2561
7e8eda73
OM
2562 audit_ntp_init(&ad);
2563
d30faff9 2564 ktime_get_real_ts64(&ts);
b8ac29b4 2565 add_device_randomness(&ts, sizeof(ts));
87ace39b 2566
ae455cb7
AMB
2567 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
2568 struct timekeeper *tks = &tk_core.shadow_timekeeper;
2569 s32 orig_tai, tai;
06c017fd 2570
ae455cb7
AMB
2571 orig_tai = tai = tks->tai_offset;
2572 ret = __do_adjtimex(txc, &ts, &tai, &ad);
aa6f9c59 2573
ae455cb7
AMB
2574 if (tai != orig_tai) {
2575 __timekeeping_set_tai_offset(tks, tai);
2576 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
2577 clock_set = true;
2578 } else {
2579 tk_update_leap_state_all(&tk_core);
2580 }
4e8f8b34 2581 }
06c017fd 2582
7e8eda73
OM
2583 audit_ntp_log(&ad);
2584
b061c7a5
ML
2585 /* Update the multiplier immediately if frequency was set directly */
2586 if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
1b267793 2587 clock_set |= timekeeping_advance(TK_ADV_FREQ);
b061c7a5 2588
1b267793 2589 if (clock_set)
5916be8a 2590 clock_was_set(CLOCK_SET_WALL);
6fdda9a9 2591
35b603f8 2592 ntp_notify_cmos_timer(offset_set);
7bd36014 2593
87ace39b
JS
2594 return ret;
2595}
aa6f9c59
JS
2596
2597#ifdef CONFIG_NTP_PPS
2598/**
2599 * hardpps() - Accessor function to NTP __hardpps function
e1b6a78b
YL
2600 * @phase_ts: Pointer to timespec64 structure representing phase timestamp
2601 * @raw_ts: Pointer to timespec64 structure representing raw timestamp
aa6f9c59 2602 */
7ec88e4b 2603void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
aa6f9c59 2604{
8c4799b1 2605 guard(raw_spinlock_irqsave)(&tk_core.lock);
aa6f9c59
JS
2606 __hardpps(phase_ts, raw_ts);
2607}
2608EXPORT_SYMBOL(hardpps);
a2d81803 2609#endif /* CONFIG_NTP_PPS */