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