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