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