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