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