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