]> asedeno.scripts.mit.edu Git - linux.git/blob - kernel/time/timekeeping.c
Merge tag 'v4.15-rc1' into drm-misc-fixes
[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 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         tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
661         update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
662         update_fast_timekeeper(&tk->tkr_raw,  &tk_fast_raw);
663
664         if (action & TK_CLOCK_WAS_SET)
665                 tk->clock_was_set_seq++;
666         /*
667          * The mirroring of the data to the shadow-timekeeper needs
668          * to happen last here to ensure we don't over-write the
669          * timekeeper structure on the next update with stale data
670          */
671         if (action & TK_MIRROR)
672                 memcpy(&shadow_timekeeper, &tk_core.timekeeper,
673                        sizeof(tk_core.timekeeper));
674 }
675
676 /**
677  * timekeeping_forward_now - update clock to the current time
678  *
679  * Forward the current clock to update its state since the last call to
680  * update_wall_time(). This is useful before significant clock changes,
681  * as it avoids having to deal with this time offset explicitly.
682  */
683 static void timekeeping_forward_now(struct timekeeper *tk)
684 {
685         u64 cycle_now, delta;
686
687         cycle_now = tk_clock_read(&tk->tkr_mono);
688         delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
689         tk->tkr_mono.cycle_last = cycle_now;
690         tk->tkr_raw.cycle_last  = cycle_now;
691
692         tk->tkr_mono.xtime_nsec += delta * tk->tkr_mono.mult;
693
694         /* If arch requires, add in get_arch_timeoffset() */
695         tk->tkr_mono.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_mono.shift;
696
697
698         tk->tkr_raw.xtime_nsec += delta * tk->tkr_raw.mult;
699
700         /* If arch requires, add in get_arch_timeoffset() */
701         tk->tkr_raw.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_raw.shift;
702
703         tk_normalize_xtime(tk);
704 }
705
706 /**
707  * __getnstimeofday64 - Returns the time of day in a timespec64.
708  * @ts:         pointer to the timespec to be set
709  *
710  * Updates the time of day in the timespec.
711  * Returns 0 on success, or -ve when suspended (timespec will be undefined).
712  */
713 int __getnstimeofday64(struct timespec64 *ts)
714 {
715         struct timekeeper *tk = &tk_core.timekeeper;
716         unsigned long seq;
717         u64 nsecs;
718
719         do {
720                 seq = read_seqcount_begin(&tk_core.seq);
721
722                 ts->tv_sec = tk->xtime_sec;
723                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
724
725         } while (read_seqcount_retry(&tk_core.seq, seq));
726
727         ts->tv_nsec = 0;
728         timespec64_add_ns(ts, nsecs);
729
730         /*
731          * Do not bail out early, in case there were callers still using
732          * the value, even in the face of the WARN_ON.
733          */
734         if (unlikely(timekeeping_suspended))
735                 return -EAGAIN;
736         return 0;
737 }
738 EXPORT_SYMBOL(__getnstimeofday64);
739
740 /**
741  * getnstimeofday64 - Returns the time of day in a timespec64.
742  * @ts:         pointer to the timespec64 to be set
743  *
744  * Returns the time of day in a timespec64 (WARN if suspended).
745  */
746 void getnstimeofday64(struct timespec64 *ts)
747 {
748         WARN_ON(__getnstimeofday64(ts));
749 }
750 EXPORT_SYMBOL(getnstimeofday64);
751
752 ktime_t ktime_get(void)
753 {
754         struct timekeeper *tk = &tk_core.timekeeper;
755         unsigned int seq;
756         ktime_t base;
757         u64 nsecs;
758
759         WARN_ON(timekeeping_suspended);
760
761         do {
762                 seq = read_seqcount_begin(&tk_core.seq);
763                 base = tk->tkr_mono.base;
764                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
765
766         } while (read_seqcount_retry(&tk_core.seq, seq));
767
768         return ktime_add_ns(base, nsecs);
769 }
770 EXPORT_SYMBOL_GPL(ktime_get);
771
772 u32 ktime_get_resolution_ns(void)
773 {
774         struct timekeeper *tk = &tk_core.timekeeper;
775         unsigned int seq;
776         u32 nsecs;
777
778         WARN_ON(timekeeping_suspended);
779
780         do {
781                 seq = read_seqcount_begin(&tk_core.seq);
782                 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
783         } while (read_seqcount_retry(&tk_core.seq, seq));
784
785         return nsecs;
786 }
787 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
788
789 static ktime_t *offsets[TK_OFFS_MAX] = {
790         [TK_OFFS_REAL]  = &tk_core.timekeeper.offs_real,
791         [TK_OFFS_BOOT]  = &tk_core.timekeeper.offs_boot,
792         [TK_OFFS_TAI]   = &tk_core.timekeeper.offs_tai,
793 };
794
795 ktime_t ktime_get_with_offset(enum tk_offsets offs)
796 {
797         struct timekeeper *tk = &tk_core.timekeeper;
798         unsigned int seq;
799         ktime_t base, *offset = offsets[offs];
800         u64 nsecs;
801
802         WARN_ON(timekeeping_suspended);
803
804         do {
805                 seq = read_seqcount_begin(&tk_core.seq);
806                 base = ktime_add(tk->tkr_mono.base, *offset);
807                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
808
809         } while (read_seqcount_retry(&tk_core.seq, seq));
810
811         return ktime_add_ns(base, nsecs);
812
813 }
814 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
815
816 /**
817  * ktime_mono_to_any() - convert mononotic time to any other time
818  * @tmono:      time to convert.
819  * @offs:       which offset to use
820  */
821 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
822 {
823         ktime_t *offset = offsets[offs];
824         unsigned long seq;
825         ktime_t tconv;
826
827         do {
828                 seq = read_seqcount_begin(&tk_core.seq);
829                 tconv = ktime_add(tmono, *offset);
830         } while (read_seqcount_retry(&tk_core.seq, seq));
831
832         return tconv;
833 }
834 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
835
836 /**
837  * ktime_get_raw - Returns the raw monotonic time in ktime_t format
838  */
839 ktime_t ktime_get_raw(void)
840 {
841         struct timekeeper *tk = &tk_core.timekeeper;
842         unsigned int seq;
843         ktime_t base;
844         u64 nsecs;
845
846         do {
847                 seq = read_seqcount_begin(&tk_core.seq);
848                 base = tk->tkr_raw.base;
849                 nsecs = timekeeping_get_ns(&tk->tkr_raw);
850
851         } while (read_seqcount_retry(&tk_core.seq, seq));
852
853         return ktime_add_ns(base, nsecs);
854 }
855 EXPORT_SYMBOL_GPL(ktime_get_raw);
856
857 /**
858  * ktime_get_ts64 - get the monotonic clock in timespec64 format
859  * @ts:         pointer to timespec variable
860  *
861  * The function calculates the monotonic clock from the realtime
862  * clock and the wall_to_monotonic offset and stores the result
863  * in normalized timespec64 format in the variable pointed to by @ts.
864  */
865 void ktime_get_ts64(struct timespec64 *ts)
866 {
867         struct timekeeper *tk = &tk_core.timekeeper;
868         struct timespec64 tomono;
869         unsigned int seq;
870         u64 nsec;
871
872         WARN_ON(timekeeping_suspended);
873
874         do {
875                 seq = read_seqcount_begin(&tk_core.seq);
876                 ts->tv_sec = tk->xtime_sec;
877                 nsec = timekeeping_get_ns(&tk->tkr_mono);
878                 tomono = tk->wall_to_monotonic;
879
880         } while (read_seqcount_retry(&tk_core.seq, seq));
881
882         ts->tv_sec += tomono.tv_sec;
883         ts->tv_nsec = 0;
884         timespec64_add_ns(ts, nsec + tomono.tv_nsec);
885 }
886 EXPORT_SYMBOL_GPL(ktime_get_ts64);
887
888 /**
889  * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
890  *
891  * Returns the seconds portion of CLOCK_MONOTONIC with a single non
892  * serialized read. tk->ktime_sec is of type 'unsigned long' so this
893  * works on both 32 and 64 bit systems. On 32 bit systems the readout
894  * covers ~136 years of uptime which should be enough to prevent
895  * premature wrap arounds.
896  */
897 time64_t ktime_get_seconds(void)
898 {
899         struct timekeeper *tk = &tk_core.timekeeper;
900
901         WARN_ON(timekeeping_suspended);
902         return tk->ktime_sec;
903 }
904 EXPORT_SYMBOL_GPL(ktime_get_seconds);
905
906 /**
907  * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
908  *
909  * Returns the wall clock seconds since 1970. This replaces the
910  * get_seconds() interface which is not y2038 safe on 32bit systems.
911  *
912  * For 64bit systems the fast access to tk->xtime_sec is preserved. On
913  * 32bit systems the access must be protected with the sequence
914  * counter to provide "atomic" access to the 64bit tk->xtime_sec
915  * value.
916  */
917 time64_t ktime_get_real_seconds(void)
918 {
919         struct timekeeper *tk = &tk_core.timekeeper;
920         time64_t seconds;
921         unsigned int seq;
922
923         if (IS_ENABLED(CONFIG_64BIT))
924                 return tk->xtime_sec;
925
926         do {
927                 seq = read_seqcount_begin(&tk_core.seq);
928                 seconds = tk->xtime_sec;
929
930         } while (read_seqcount_retry(&tk_core.seq, seq));
931
932         return seconds;
933 }
934 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
935
936 /**
937  * __ktime_get_real_seconds - The same as ktime_get_real_seconds
938  * but without the sequence counter protect. This internal function
939  * is called just when timekeeping lock is already held.
940  */
941 time64_t __ktime_get_real_seconds(void)
942 {
943         struct timekeeper *tk = &tk_core.timekeeper;
944
945         return tk->xtime_sec;
946 }
947
948 /**
949  * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
950  * @systime_snapshot:   pointer to struct receiving the system time snapshot
951  */
952 void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
953 {
954         struct timekeeper *tk = &tk_core.timekeeper;
955         unsigned long seq;
956         ktime_t base_raw;
957         ktime_t base_real;
958         u64 nsec_raw;
959         u64 nsec_real;
960         u64 now;
961
962         WARN_ON_ONCE(timekeeping_suspended);
963
964         do {
965                 seq = read_seqcount_begin(&tk_core.seq);
966                 now = tk_clock_read(&tk->tkr_mono);
967                 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
968                 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
969                 base_real = ktime_add(tk->tkr_mono.base,
970                                       tk_core.timekeeper.offs_real);
971                 base_raw = tk->tkr_raw.base;
972                 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
973                 nsec_raw  = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
974         } while (read_seqcount_retry(&tk_core.seq, seq));
975
976         systime_snapshot->cycles = now;
977         systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
978         systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
979 }
980 EXPORT_SYMBOL_GPL(ktime_get_snapshot);
981
982 /* Scale base by mult/div checking for overflow */
983 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
984 {
985         u64 tmp, rem;
986
987         tmp = div64_u64_rem(*base, div, &rem);
988
989         if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
990             ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
991                 return -EOVERFLOW;
992         tmp *= mult;
993         rem *= mult;
994
995         do_div(rem, div);
996         *base = tmp + rem;
997         return 0;
998 }
999
1000 /**
1001  * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1002  * @history:                    Snapshot representing start of history
1003  * @partial_history_cycles:     Cycle offset into history (fractional part)
1004  * @total_history_cycles:       Total history length in cycles
1005  * @discontinuity:              True indicates clock was set on history period
1006  * @ts:                         Cross timestamp that should be adjusted using
1007  *      partial/total ratio
1008  *
1009  * Helper function used by get_device_system_crosststamp() to correct the
1010  * crosstimestamp corresponding to the start of the current interval to the
1011  * system counter value (timestamp point) provided by the driver. The
1012  * total_history_* quantities are the total history starting at the provided
1013  * reference point and ending at the start of the current interval. The cycle
1014  * count between the driver timestamp point and the start of the current
1015  * interval is partial_history_cycles.
1016  */
1017 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1018                                          u64 partial_history_cycles,
1019                                          u64 total_history_cycles,
1020                                          bool discontinuity,
1021                                          struct system_device_crosststamp *ts)
1022 {
1023         struct timekeeper *tk = &tk_core.timekeeper;
1024         u64 corr_raw, corr_real;
1025         bool interp_forward;
1026         int ret;
1027
1028         if (total_history_cycles == 0 || partial_history_cycles == 0)
1029                 return 0;
1030
1031         /* Interpolate shortest distance from beginning or end of history */
1032         interp_forward = partial_history_cycles > total_history_cycles / 2;
1033         partial_history_cycles = interp_forward ?
1034                 total_history_cycles - partial_history_cycles :
1035                 partial_history_cycles;
1036
1037         /*
1038          * Scale the monotonic raw time delta by:
1039          *      partial_history_cycles / total_history_cycles
1040          */
1041         corr_raw = (u64)ktime_to_ns(
1042                 ktime_sub(ts->sys_monoraw, history->raw));
1043         ret = scale64_check_overflow(partial_history_cycles,
1044                                      total_history_cycles, &corr_raw);
1045         if (ret)
1046                 return ret;
1047
1048         /*
1049          * If there is a discontinuity in the history, scale monotonic raw
1050          *      correction by:
1051          *      mult(real)/mult(raw) yielding the realtime correction
1052          * Otherwise, calculate the realtime correction similar to monotonic
1053          *      raw calculation
1054          */
1055         if (discontinuity) {
1056                 corr_real = mul_u64_u32_div
1057                         (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1058         } else {
1059                 corr_real = (u64)ktime_to_ns(
1060                         ktime_sub(ts->sys_realtime, history->real));
1061                 ret = scale64_check_overflow(partial_history_cycles,
1062                                              total_history_cycles, &corr_real);
1063                 if (ret)
1064                         return ret;
1065         }
1066
1067         /* Fixup monotonic raw and real time time values */
1068         if (interp_forward) {
1069                 ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1070                 ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1071         } else {
1072                 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1073                 ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1074         }
1075
1076         return 0;
1077 }
1078
1079 /*
1080  * cycle_between - true if test occurs chronologically between before and after
1081  */
1082 static bool cycle_between(u64 before, u64 test, u64 after)
1083 {
1084         if (test > before && test < after)
1085                 return true;
1086         if (test < before && before > after)
1087                 return true;
1088         return false;
1089 }
1090
1091 /**
1092  * get_device_system_crosststamp - Synchronously capture system/device timestamp
1093  * @get_time_fn:        Callback to get simultaneous device time and
1094  *      system counter from the device driver
1095  * @ctx:                Context passed to get_time_fn()
1096  * @history_begin:      Historical reference point used to interpolate system
1097  *      time when counter provided by the driver is before the current interval
1098  * @xtstamp:            Receives simultaneously captured system and device time
1099  *
1100  * Reads a timestamp from a device and correlates it to system time
1101  */
1102 int get_device_system_crosststamp(int (*get_time_fn)
1103                                   (ktime_t *device_time,
1104                                    struct system_counterval_t *sys_counterval,
1105                                    void *ctx),
1106                                   void *ctx,
1107                                   struct system_time_snapshot *history_begin,
1108                                   struct system_device_crosststamp *xtstamp)
1109 {
1110         struct system_counterval_t system_counterval;
1111         struct timekeeper *tk = &tk_core.timekeeper;
1112         u64 cycles, now, interval_start;
1113         unsigned int clock_was_set_seq = 0;
1114         ktime_t base_real, base_raw;
1115         u64 nsec_real, nsec_raw;
1116         u8 cs_was_changed_seq;
1117         unsigned long seq;
1118         bool do_interp;
1119         int ret;
1120
1121         do {
1122                 seq = read_seqcount_begin(&tk_core.seq);
1123                 /*
1124                  * Try to synchronously capture device time and a system
1125                  * counter value calling back into the device driver
1126                  */
1127                 ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1128                 if (ret)
1129                         return ret;
1130
1131                 /*
1132                  * Verify that the clocksource associated with the captured
1133                  * system counter value is the same as the currently installed
1134                  * timekeeper clocksource
1135                  */
1136                 if (tk->tkr_mono.clock != system_counterval.cs)
1137                         return -ENODEV;
1138                 cycles = system_counterval.cycles;
1139
1140                 /*
1141                  * Check whether the system counter value provided by the
1142                  * device driver is on the current timekeeping interval.
1143                  */
1144                 now = tk_clock_read(&tk->tkr_mono);
1145                 interval_start = tk->tkr_mono.cycle_last;
1146                 if (!cycle_between(interval_start, cycles, now)) {
1147                         clock_was_set_seq = tk->clock_was_set_seq;
1148                         cs_was_changed_seq = tk->cs_was_changed_seq;
1149                         cycles = interval_start;
1150                         do_interp = true;
1151                 } else {
1152                         do_interp = false;
1153                 }
1154
1155                 base_real = ktime_add(tk->tkr_mono.base,
1156                                       tk_core.timekeeper.offs_real);
1157                 base_raw = tk->tkr_raw.base;
1158
1159                 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono,
1160                                                      system_counterval.cycles);
1161                 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw,
1162                                                     system_counterval.cycles);
1163         } while (read_seqcount_retry(&tk_core.seq, seq));
1164
1165         xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1166         xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1167
1168         /*
1169          * Interpolate if necessary, adjusting back from the start of the
1170          * current interval
1171          */
1172         if (do_interp) {
1173                 u64 partial_history_cycles, total_history_cycles;
1174                 bool discontinuity;
1175
1176                 /*
1177                  * Check that the counter value occurs after the provided
1178                  * history reference and that the history doesn't cross a
1179                  * clocksource change
1180                  */
1181                 if (!history_begin ||
1182                     !cycle_between(history_begin->cycles,
1183                                    system_counterval.cycles, cycles) ||
1184                     history_begin->cs_was_changed_seq != cs_was_changed_seq)
1185                         return -EINVAL;
1186                 partial_history_cycles = cycles - system_counterval.cycles;
1187                 total_history_cycles = cycles - history_begin->cycles;
1188                 discontinuity =
1189                         history_begin->clock_was_set_seq != clock_was_set_seq;
1190
1191                 ret = adjust_historical_crosststamp(history_begin,
1192                                                     partial_history_cycles,
1193                                                     total_history_cycles,
1194                                                     discontinuity, xtstamp);
1195                 if (ret)
1196                         return ret;
1197         }
1198
1199         return 0;
1200 }
1201 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1202
1203 /**
1204  * do_gettimeofday - Returns the time of day in a timeval
1205  * @tv:         pointer to the timeval to be set
1206  *
1207  * NOTE: Users should be converted to using getnstimeofday()
1208  */
1209 void do_gettimeofday(struct timeval *tv)
1210 {
1211         struct timespec64 now;
1212
1213         getnstimeofday64(&now);
1214         tv->tv_sec = now.tv_sec;
1215         tv->tv_usec = now.tv_nsec/1000;
1216 }
1217 EXPORT_SYMBOL(do_gettimeofday);
1218
1219 /**
1220  * do_settimeofday64 - Sets the time of day.
1221  * @ts:     pointer to the timespec64 variable containing the new time
1222  *
1223  * Sets the time of day to the new time and update NTP and notify hrtimers
1224  */
1225 int do_settimeofday64(const struct timespec64 *ts)
1226 {
1227         struct timekeeper *tk = &tk_core.timekeeper;
1228         struct timespec64 ts_delta, xt;
1229         unsigned long flags;
1230         int ret = 0;
1231
1232         if (!timespec64_valid_strict(ts))
1233                 return -EINVAL;
1234
1235         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1236         write_seqcount_begin(&tk_core.seq);
1237
1238         timekeeping_forward_now(tk);
1239
1240         xt = tk_xtime(tk);
1241         ts_delta.tv_sec = ts->tv_sec - xt.tv_sec;
1242         ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
1243
1244         if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
1245                 ret = -EINVAL;
1246                 goto out;
1247         }
1248
1249         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
1250
1251         tk_set_xtime(tk, ts);
1252 out:
1253         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1254
1255         write_seqcount_end(&tk_core.seq);
1256         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1257
1258         /* signal hrtimers about time change */
1259         clock_was_set();
1260
1261         return ret;
1262 }
1263 EXPORT_SYMBOL(do_settimeofday64);
1264
1265 /**
1266  * timekeeping_inject_offset - Adds or subtracts from the current time.
1267  * @tv:         pointer to the timespec variable containing the offset
1268  *
1269  * Adds or subtracts an offset value from the current time.
1270  */
1271 static int timekeeping_inject_offset(struct timespec64 *ts)
1272 {
1273         struct timekeeper *tk = &tk_core.timekeeper;
1274         unsigned long flags;
1275         struct timespec64 tmp;
1276         int ret = 0;
1277
1278         if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1279                 return -EINVAL;
1280
1281         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1282         write_seqcount_begin(&tk_core.seq);
1283
1284         timekeeping_forward_now(tk);
1285
1286         /* Make sure the proposed value is valid */
1287         tmp = timespec64_add(tk_xtime(tk), *ts);
1288         if (timespec64_compare(&tk->wall_to_monotonic, ts) > 0 ||
1289             !timespec64_valid_strict(&tmp)) {
1290                 ret = -EINVAL;
1291                 goto error;
1292         }
1293
1294         tk_xtime_add(tk, ts);
1295         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *ts));
1296
1297 error: /* even if we error out, we forwarded the time, so call update */
1298         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1299
1300         write_seqcount_end(&tk_core.seq);
1301         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1302
1303         /* signal hrtimers about time change */
1304         clock_was_set();
1305
1306         return ret;
1307 }
1308
1309 /*
1310  * Indicates if there is an offset between the system clock and the hardware
1311  * clock/persistent clock/rtc.
1312  */
1313 int persistent_clock_is_local;
1314
1315 /*
1316  * Adjust the time obtained from the CMOS to be UTC time instead of
1317  * local time.
1318  *
1319  * This is ugly, but preferable to the alternatives.  Otherwise we
1320  * would either need to write a program to do it in /etc/rc (and risk
1321  * confusion if the program gets run more than once; it would also be
1322  * hard to make the program warp the clock precisely n hours)  or
1323  * compile in the timezone information into the kernel.  Bad, bad....
1324  *
1325  *                                              - TYT, 1992-01-01
1326  *
1327  * The best thing to do is to keep the CMOS clock in universal time (UTC)
1328  * as real UNIX machines always do it. This avoids all headaches about
1329  * daylight saving times and warping kernel clocks.
1330  */
1331 void timekeeping_warp_clock(void)
1332 {
1333         if (sys_tz.tz_minuteswest != 0) {
1334                 struct timespec64 adjust;
1335
1336                 persistent_clock_is_local = 1;
1337                 adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1338                 adjust.tv_nsec = 0;
1339                 timekeeping_inject_offset(&adjust);
1340         }
1341 }
1342
1343 /**
1344  * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1345  *
1346  */
1347 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1348 {
1349         tk->tai_offset = tai_offset;
1350         tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1351 }
1352
1353 /**
1354  * change_clocksource - Swaps clocksources if a new one is available
1355  *
1356  * Accumulates current time interval and initializes new clocksource
1357  */
1358 static int change_clocksource(void *data)
1359 {
1360         struct timekeeper *tk = &tk_core.timekeeper;
1361         struct clocksource *new, *old;
1362         unsigned long flags;
1363
1364         new = (struct clocksource *) data;
1365
1366         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1367         write_seqcount_begin(&tk_core.seq);
1368
1369         timekeeping_forward_now(tk);
1370         /*
1371          * If the cs is in module, get a module reference. Succeeds
1372          * for built-in code (owner == NULL) as well.
1373          */
1374         if (try_module_get(new->owner)) {
1375                 if (!new->enable || new->enable(new) == 0) {
1376                         old = tk->tkr_mono.clock;
1377                         tk_setup_internals(tk, new);
1378                         if (old->disable)
1379                                 old->disable(old);
1380                         module_put(old->owner);
1381                 } else {
1382                         module_put(new->owner);
1383                 }
1384         }
1385         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1386
1387         write_seqcount_end(&tk_core.seq);
1388         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1389
1390         return 0;
1391 }
1392
1393 /**
1394  * timekeeping_notify - Install a new clock source
1395  * @clock:              pointer to the clock source
1396  *
1397  * This function is called from clocksource.c after a new, better clock
1398  * source has been registered. The caller holds the clocksource_mutex.
1399  */
1400 int timekeeping_notify(struct clocksource *clock)
1401 {
1402         struct timekeeper *tk = &tk_core.timekeeper;
1403
1404         if (tk->tkr_mono.clock == clock)
1405                 return 0;
1406         stop_machine(change_clocksource, clock, NULL);
1407         tick_clock_notify();
1408         return tk->tkr_mono.clock == clock ? 0 : -1;
1409 }
1410
1411 /**
1412  * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1413  * @ts:         pointer to the timespec64 to be set
1414  *
1415  * Returns the raw monotonic time (completely un-modified by ntp)
1416  */
1417 void getrawmonotonic64(struct timespec64 *ts)
1418 {
1419         struct timekeeper *tk = &tk_core.timekeeper;
1420         unsigned long seq;
1421         u64 nsecs;
1422
1423         do {
1424                 seq = read_seqcount_begin(&tk_core.seq);
1425                 ts->tv_sec = tk->raw_sec;
1426                 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1427
1428         } while (read_seqcount_retry(&tk_core.seq, seq));
1429
1430         ts->tv_nsec = 0;
1431         timespec64_add_ns(ts, nsecs);
1432 }
1433 EXPORT_SYMBOL(getrawmonotonic64);
1434
1435
1436 /**
1437  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1438  */
1439 int timekeeping_valid_for_hres(void)
1440 {
1441         struct timekeeper *tk = &tk_core.timekeeper;
1442         unsigned long seq;
1443         int ret;
1444
1445         do {
1446                 seq = read_seqcount_begin(&tk_core.seq);
1447
1448                 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1449
1450         } while (read_seqcount_retry(&tk_core.seq, seq));
1451
1452         return ret;
1453 }
1454
1455 /**
1456  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1457  */
1458 u64 timekeeping_max_deferment(void)
1459 {
1460         struct timekeeper *tk = &tk_core.timekeeper;
1461         unsigned long seq;
1462         u64 ret;
1463
1464         do {
1465                 seq = read_seqcount_begin(&tk_core.seq);
1466
1467                 ret = tk->tkr_mono.clock->max_idle_ns;
1468
1469         } while (read_seqcount_retry(&tk_core.seq, seq));
1470
1471         return ret;
1472 }
1473
1474 /**
1475  * read_persistent_clock -  Return time from the persistent clock.
1476  *
1477  * Weak dummy function for arches that do not yet support it.
1478  * Reads the time from the battery backed persistent clock.
1479  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1480  *
1481  *  XXX - Do be sure to remove it once all arches implement it.
1482  */
1483 void __weak read_persistent_clock(struct timespec *ts)
1484 {
1485         ts->tv_sec = 0;
1486         ts->tv_nsec = 0;
1487 }
1488
1489 void __weak read_persistent_clock64(struct timespec64 *ts64)
1490 {
1491         struct timespec ts;
1492
1493         read_persistent_clock(&ts);
1494         *ts64 = timespec_to_timespec64(ts);
1495 }
1496
1497 /**
1498  * read_boot_clock64 -  Return time of the system start.
1499  *
1500  * Weak dummy function for arches that do not yet support it.
1501  * Function to read the exact time the system has been started.
1502  * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1503  *
1504  *  XXX - Do be sure to remove it once all arches implement it.
1505  */
1506 void __weak read_boot_clock64(struct timespec64 *ts)
1507 {
1508         ts->tv_sec = 0;
1509         ts->tv_nsec = 0;
1510 }
1511
1512 /* Flag for if timekeeping_resume() has injected sleeptime */
1513 static bool sleeptime_injected;
1514
1515 /* Flag for if there is a persistent clock on this platform */
1516 static bool persistent_clock_exists;
1517
1518 /*
1519  * timekeeping_init - Initializes the clocksource and common timekeeping values
1520  */
1521 void __init timekeeping_init(void)
1522 {
1523         struct timekeeper *tk = &tk_core.timekeeper;
1524         struct clocksource *clock;
1525         unsigned long flags;
1526         struct timespec64 now, boot, tmp;
1527
1528         read_persistent_clock64(&now);
1529         if (!timespec64_valid_strict(&now)) {
1530                 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1531                         "         Check your CMOS/BIOS settings.\n");
1532                 now.tv_sec = 0;
1533                 now.tv_nsec = 0;
1534         } else if (now.tv_sec || now.tv_nsec)
1535                 persistent_clock_exists = true;
1536
1537         read_boot_clock64(&boot);
1538         if (!timespec64_valid_strict(&boot)) {
1539                 pr_warn("WARNING: Boot clock returned invalid value!\n"
1540                         "         Check your CMOS/BIOS settings.\n");
1541                 boot.tv_sec = 0;
1542                 boot.tv_nsec = 0;
1543         }
1544
1545         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1546         write_seqcount_begin(&tk_core.seq);
1547         ntp_init();
1548
1549         clock = clocksource_default_clock();
1550         if (clock->enable)
1551                 clock->enable(clock);
1552         tk_setup_internals(tk, clock);
1553
1554         tk_set_xtime(tk, &now);
1555         tk->raw_sec = 0;
1556         if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1557                 boot = tk_xtime(tk);
1558
1559         set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1560         tk_set_wall_to_mono(tk, tmp);
1561
1562         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1563
1564         write_seqcount_end(&tk_core.seq);
1565         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1566 }
1567
1568 /* time in seconds when suspend began for persistent clock */
1569 static struct timespec64 timekeeping_suspend_time;
1570
1571 /**
1572  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1573  * @delta: pointer to a timespec delta value
1574  *
1575  * Takes a timespec offset measuring a suspend interval and properly
1576  * adds the sleep offset to the timekeeping variables.
1577  */
1578 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1579                                            struct timespec64 *delta)
1580 {
1581         if (!timespec64_valid_strict(delta)) {
1582                 printk_deferred(KERN_WARNING
1583                                 "__timekeeping_inject_sleeptime: Invalid "
1584                                 "sleep delta value!\n");
1585                 return;
1586         }
1587         tk_xtime_add(tk, delta);
1588         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1589         tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1590         tk_debug_account_sleep_time(delta);
1591 }
1592
1593 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1594 /**
1595  * We have three kinds of time sources to use for sleep time
1596  * injection, the preference order is:
1597  * 1) non-stop clocksource
1598  * 2) persistent clock (ie: RTC accessible when irqs are off)
1599  * 3) RTC
1600  *
1601  * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1602  * If system has neither 1) nor 2), 3) will be used finally.
1603  *
1604  *
1605  * If timekeeping has injected sleeptime via either 1) or 2),
1606  * 3) becomes needless, so in this case we don't need to call
1607  * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1608  * means.
1609  */
1610 bool timekeeping_rtc_skipresume(void)
1611 {
1612         return sleeptime_injected;
1613 }
1614
1615 /**
1616  * 1) can be determined whether to use or not only when doing
1617  * timekeeping_resume() which is invoked after rtc_suspend(),
1618  * so we can't skip rtc_suspend() surely if system has 1).
1619  *
1620  * But if system has 2), 2) will definitely be used, so in this
1621  * case we don't need to call rtc_suspend(), and this is what
1622  * timekeeping_rtc_skipsuspend() means.
1623  */
1624 bool timekeeping_rtc_skipsuspend(void)
1625 {
1626         return persistent_clock_exists;
1627 }
1628
1629 /**
1630  * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1631  * @delta: pointer to a timespec64 delta value
1632  *
1633  * This hook is for architectures that cannot support read_persistent_clock64
1634  * because their RTC/persistent clock is only accessible when irqs are enabled.
1635  * and also don't have an effective nonstop clocksource.
1636  *
1637  * This function should only be called by rtc_resume(), and allows
1638  * a suspend offset to be injected into the timekeeping values.
1639  */
1640 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1641 {
1642         struct timekeeper *tk = &tk_core.timekeeper;
1643         unsigned long flags;
1644
1645         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1646         write_seqcount_begin(&tk_core.seq);
1647
1648         timekeeping_forward_now(tk);
1649
1650         __timekeeping_inject_sleeptime(tk, delta);
1651
1652         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1653
1654         write_seqcount_end(&tk_core.seq);
1655         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1656
1657         /* signal hrtimers about time change */
1658         clock_was_set();
1659 }
1660 #endif
1661
1662 /**
1663  * timekeeping_resume - Resumes the generic timekeeping subsystem.
1664  */
1665 void timekeeping_resume(void)
1666 {
1667         struct timekeeper *tk = &tk_core.timekeeper;
1668         struct clocksource *clock = tk->tkr_mono.clock;
1669         unsigned long flags;
1670         struct timespec64 ts_new, ts_delta;
1671         u64 cycle_now;
1672
1673         sleeptime_injected = false;
1674         read_persistent_clock64(&ts_new);
1675
1676         clockevents_resume();
1677         clocksource_resume();
1678
1679         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1680         write_seqcount_begin(&tk_core.seq);
1681
1682         /*
1683          * After system resumes, we need to calculate the suspended time and
1684          * compensate it for the OS time. There are 3 sources that could be
1685          * used: Nonstop clocksource during suspend, persistent clock and rtc
1686          * device.
1687          *
1688          * One specific platform may have 1 or 2 or all of them, and the
1689          * preference will be:
1690          *      suspend-nonstop clocksource -> persistent clock -> rtc
1691          * The less preferred source will only be tried if there is no better
1692          * usable source. The rtc part is handled separately in rtc core code.
1693          */
1694         cycle_now = tk_clock_read(&tk->tkr_mono);
1695         if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1696                 cycle_now > tk->tkr_mono.cycle_last) {
1697                 u64 nsec, cyc_delta;
1698
1699                 cyc_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1700                                               tk->tkr_mono.mask);
1701                 nsec = mul_u64_u32_shr(cyc_delta, clock->mult, clock->shift);
1702                 ts_delta = ns_to_timespec64(nsec);
1703                 sleeptime_injected = true;
1704         } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1705                 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1706                 sleeptime_injected = true;
1707         }
1708
1709         if (sleeptime_injected)
1710                 __timekeeping_inject_sleeptime(tk, &ts_delta);
1711
1712         /* Re-base the last cycle value */
1713         tk->tkr_mono.cycle_last = cycle_now;
1714         tk->tkr_raw.cycle_last  = cycle_now;
1715
1716         tk->ntp_error = 0;
1717         timekeeping_suspended = 0;
1718         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1719         write_seqcount_end(&tk_core.seq);
1720         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1721
1722         touch_softlockup_watchdog();
1723
1724         tick_resume();
1725         hrtimers_resume();
1726 }
1727
1728 int timekeeping_suspend(void)
1729 {
1730         struct timekeeper *tk = &tk_core.timekeeper;
1731         unsigned long flags;
1732         struct timespec64               delta, delta_delta;
1733         static struct timespec64        old_delta;
1734
1735         read_persistent_clock64(&timekeeping_suspend_time);
1736
1737         /*
1738          * On some systems the persistent_clock can not be detected at
1739          * timekeeping_init by its return value, so if we see a valid
1740          * value returned, update the persistent_clock_exists flag.
1741          */
1742         if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1743                 persistent_clock_exists = true;
1744
1745         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1746         write_seqcount_begin(&tk_core.seq);
1747         timekeeping_forward_now(tk);
1748         timekeeping_suspended = 1;
1749
1750         if (persistent_clock_exists) {
1751                 /*
1752                  * To avoid drift caused by repeated suspend/resumes,
1753                  * which each can add ~1 second drift error,
1754                  * try to compensate so the difference in system time
1755                  * and persistent_clock time stays close to constant.
1756                  */
1757                 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1758                 delta_delta = timespec64_sub(delta, old_delta);
1759                 if (abs(delta_delta.tv_sec) >= 2) {
1760                         /*
1761                          * if delta_delta is too large, assume time correction
1762                          * has occurred and set old_delta to the current delta.
1763                          */
1764                         old_delta = delta;
1765                 } else {
1766                         /* Otherwise try to adjust old_system to compensate */
1767                         timekeeping_suspend_time =
1768                                 timespec64_add(timekeeping_suspend_time, delta_delta);
1769                 }
1770         }
1771
1772         timekeeping_update(tk, TK_MIRROR);
1773         halt_fast_timekeeper(tk);
1774         write_seqcount_end(&tk_core.seq);
1775         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1776
1777         tick_suspend();
1778         clocksource_suspend();
1779         clockevents_suspend();
1780
1781         return 0;
1782 }
1783
1784 /* sysfs resume/suspend bits for timekeeping */
1785 static struct syscore_ops timekeeping_syscore_ops = {
1786         .resume         = timekeeping_resume,
1787         .suspend        = timekeeping_suspend,
1788 };
1789
1790 static int __init timekeeping_init_ops(void)
1791 {
1792         register_syscore_ops(&timekeeping_syscore_ops);
1793         return 0;
1794 }
1795 device_initcall(timekeeping_init_ops);
1796
1797 /*
1798  * Apply a multiplier adjustment to the timekeeper
1799  */
1800 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1801                                                          s64 offset,
1802                                                          bool negative,
1803                                                          int adj_scale)
1804 {
1805         s64 interval = tk->cycle_interval;
1806         s32 mult_adj = 1;
1807
1808         if (negative) {
1809                 mult_adj = -mult_adj;
1810                 interval = -interval;
1811                 offset  = -offset;
1812         }
1813         mult_adj <<= adj_scale;
1814         interval <<= adj_scale;
1815         offset <<= adj_scale;
1816
1817         /*
1818          * So the following can be confusing.
1819          *
1820          * To keep things simple, lets assume mult_adj == 1 for now.
1821          *
1822          * When mult_adj != 1, remember that the interval and offset values
1823          * have been appropriately scaled so the math is the same.
1824          *
1825          * The basic idea here is that we're increasing the multiplier
1826          * by one, this causes the xtime_interval to be incremented by
1827          * one cycle_interval. This is because:
1828          *      xtime_interval = cycle_interval * mult
1829          * So if mult is being incremented by one:
1830          *      xtime_interval = cycle_interval * (mult + 1)
1831          * Its the same as:
1832          *      xtime_interval = (cycle_interval * mult) + cycle_interval
1833          * Which can be shortened to:
1834          *      xtime_interval += cycle_interval
1835          *
1836          * So offset stores the non-accumulated cycles. Thus the current
1837          * time (in shifted nanoseconds) is:
1838          *      now = (offset * adj) + xtime_nsec
1839          * Now, even though we're adjusting the clock frequency, we have
1840          * to keep time consistent. In other words, we can't jump back
1841          * in time, and we also want to avoid jumping forward in time.
1842          *
1843          * So given the same offset value, we need the time to be the same
1844          * both before and after the freq adjustment.
1845          *      now = (offset * adj_1) + xtime_nsec_1
1846          *      now = (offset * adj_2) + xtime_nsec_2
1847          * So:
1848          *      (offset * adj_1) + xtime_nsec_1 =
1849          *              (offset * adj_2) + xtime_nsec_2
1850          * And we know:
1851          *      adj_2 = adj_1 + 1
1852          * So:
1853          *      (offset * adj_1) + xtime_nsec_1 =
1854          *              (offset * (adj_1+1)) + xtime_nsec_2
1855          *      (offset * adj_1) + xtime_nsec_1 =
1856          *              (offset * adj_1) + offset + xtime_nsec_2
1857          * Canceling the sides:
1858          *      xtime_nsec_1 = offset + xtime_nsec_2
1859          * Which gives us:
1860          *      xtime_nsec_2 = xtime_nsec_1 - offset
1861          * Which simplfies to:
1862          *      xtime_nsec -= offset
1863          *
1864          * XXX - TODO: Doc ntp_error calculation.
1865          */
1866         if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1867                 /* NTP adjustment caused clocksource mult overflow */
1868                 WARN_ON_ONCE(1);
1869                 return;
1870         }
1871
1872         tk->tkr_mono.mult += mult_adj;
1873         tk->xtime_interval += interval;
1874         tk->tkr_mono.xtime_nsec -= offset;
1875         tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1876 }
1877
1878 /*
1879  * Calculate the multiplier adjustment needed to match the frequency
1880  * specified by NTP
1881  */
1882 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1883                                                         s64 offset)
1884 {
1885         s64 interval = tk->cycle_interval;
1886         s64 xinterval = tk->xtime_interval;
1887         u32 base = tk->tkr_mono.clock->mult;
1888         u32 max = tk->tkr_mono.clock->maxadj;
1889         u32 cur_adj = tk->tkr_mono.mult;
1890         s64 tick_error;
1891         bool negative;
1892         u32 adj_scale;
1893
1894         /* Remove any current error adj from freq calculation */
1895         if (tk->ntp_err_mult)
1896                 xinterval -= tk->cycle_interval;
1897
1898         tk->ntp_tick = ntp_tick_length();
1899
1900         /* Calculate current error per tick */
1901         tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1902         tick_error -= (xinterval + tk->xtime_remainder);
1903
1904         /* Don't worry about correcting it if its small */
1905         if (likely((tick_error >= 0) && (tick_error <= interval)))
1906                 return;
1907
1908         /* preserve the direction of correction */
1909         negative = (tick_error < 0);
1910
1911         /* If any adjustment would pass the max, just return */
1912         if (negative && (cur_adj - 1) <= (base - max))
1913                 return;
1914         if (!negative && (cur_adj + 1) >= (base + max))
1915                 return;
1916         /*
1917          * Sort out the magnitude of the correction, but
1918          * avoid making so large a correction that we go
1919          * over the max adjustment.
1920          */
1921         adj_scale = 0;
1922         tick_error = abs(tick_error);
1923         while (tick_error > interval) {
1924                 u32 adj = 1 << (adj_scale + 1);
1925
1926                 /* Check if adjustment gets us within 1 unit from the max */
1927                 if (negative && (cur_adj - adj) <= (base - max))
1928                         break;
1929                 if (!negative && (cur_adj + adj) >= (base + max))
1930                         break;
1931
1932                 adj_scale++;
1933                 tick_error >>= 1;
1934         }
1935
1936         /* scale the corrections */
1937         timekeeping_apply_adjustment(tk, offset, negative, adj_scale);
1938 }
1939
1940 /*
1941  * Adjust the timekeeper's multiplier to the correct frequency
1942  * and also to reduce the accumulated error value.
1943  */
1944 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1945 {
1946         /* Correct for the current frequency error */
1947         timekeeping_freqadjust(tk, offset);
1948
1949         /* Next make a small adjustment to fix any cumulative error */
1950         if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1951                 tk->ntp_err_mult = 1;
1952                 timekeeping_apply_adjustment(tk, offset, 0, 0);
1953         } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1954                 /* Undo any existing error adjustment */
1955                 timekeeping_apply_adjustment(tk, offset, 1, 0);
1956                 tk->ntp_err_mult = 0;
1957         }
1958
1959         if (unlikely(tk->tkr_mono.clock->maxadj &&
1960                 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
1961                         > tk->tkr_mono.clock->maxadj))) {
1962                 printk_once(KERN_WARNING
1963                         "Adjusting %s more than 11%% (%ld vs %ld)\n",
1964                         tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
1965                         (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
1966         }
1967
1968         /*
1969          * It may be possible that when we entered this function, xtime_nsec
1970          * was very small.  Further, if we're slightly speeding the clocksource
1971          * in the code above, its possible the required corrective factor to
1972          * xtime_nsec could cause it to underflow.
1973          *
1974          * Now, since we already accumulated the second, cannot simply roll
1975          * the accumulated second back, since the NTP subsystem has been
1976          * notified via second_overflow. So instead we push xtime_nsec forward
1977          * by the amount we underflowed, and add that amount into the error.
1978          *
1979          * We'll correct this error next time through this function, when
1980          * xtime_nsec is not as small.
1981          */
1982         if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
1983                 s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
1984                 tk->tkr_mono.xtime_nsec = 0;
1985                 tk->ntp_error += neg << tk->ntp_error_shift;
1986         }
1987 }
1988
1989 /**
1990  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1991  *
1992  * Helper function that accumulates the nsecs greater than a second
1993  * from the xtime_nsec field to the xtime_secs field.
1994  * It also calls into the NTP code to handle leapsecond processing.
1995  *
1996  */
1997 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
1998 {
1999         u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2000         unsigned int clock_set = 0;
2001
2002         while (tk->tkr_mono.xtime_nsec >= nsecps) {
2003                 int leap;
2004
2005                 tk->tkr_mono.xtime_nsec -= nsecps;
2006                 tk->xtime_sec++;
2007
2008                 /* Figure out if its a leap sec and apply if needed */
2009                 leap = second_overflow(tk->xtime_sec);
2010                 if (unlikely(leap)) {
2011                         struct timespec64 ts;
2012
2013                         tk->xtime_sec += leap;
2014
2015                         ts.tv_sec = leap;
2016                         ts.tv_nsec = 0;
2017                         tk_set_wall_to_mono(tk,
2018                                 timespec64_sub(tk->wall_to_monotonic, ts));
2019
2020                         __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2021
2022                         clock_set = TK_CLOCK_WAS_SET;
2023                 }
2024         }
2025         return clock_set;
2026 }
2027
2028 /**
2029  * logarithmic_accumulation - shifted accumulation of cycles
2030  *
2031  * This functions accumulates a shifted interval of cycles into
2032  * into a shifted interval nanoseconds. Allows for O(log) accumulation
2033  * loop.
2034  *
2035  * Returns the unconsumed cycles.
2036  */
2037 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2038                                     u32 shift, unsigned int *clock_set)
2039 {
2040         u64 interval = tk->cycle_interval << shift;
2041         u64 snsec_per_sec;
2042
2043         /* If the offset is smaller than a shifted interval, do nothing */
2044         if (offset < interval)
2045                 return offset;
2046
2047         /* Accumulate one shifted interval */
2048         offset -= interval;
2049         tk->tkr_mono.cycle_last += interval;
2050         tk->tkr_raw.cycle_last  += interval;
2051
2052         tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2053         *clock_set |= accumulate_nsecs_to_secs(tk);
2054
2055         /* Accumulate raw time */
2056         tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2057         snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2058         while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2059                 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2060                 tk->raw_sec++;
2061         }
2062
2063         /* Accumulate error between NTP and clock interval */
2064         tk->ntp_error += tk->ntp_tick << shift;
2065         tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2066                                                 (tk->ntp_error_shift + shift);
2067
2068         return offset;
2069 }
2070
2071 /**
2072  * update_wall_time - Uses the current clocksource to increment the wall time
2073  *
2074  */
2075 void update_wall_time(void)
2076 {
2077         struct timekeeper *real_tk = &tk_core.timekeeper;
2078         struct timekeeper *tk = &shadow_timekeeper;
2079         u64 offset;
2080         int shift = 0, maxshift;
2081         unsigned int clock_set = 0;
2082         unsigned long flags;
2083
2084         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2085
2086         /* Make sure we're fully resumed: */
2087         if (unlikely(timekeeping_suspended))
2088                 goto out;
2089
2090 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
2091         offset = real_tk->cycle_interval;
2092 #else
2093         offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2094                                    tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
2095 #endif
2096
2097         /* Check if there's really nothing to do */
2098         if (offset < real_tk->cycle_interval)
2099                 goto out;
2100
2101         /* Do some additional sanity checking */
2102         timekeeping_check_update(tk, offset);
2103
2104         /*
2105          * With NO_HZ we may have to accumulate many cycle_intervals
2106          * (think "ticks") worth of time at once. To do this efficiently,
2107          * we calculate the largest doubling multiple of cycle_intervals
2108          * that is smaller than the offset.  We then accumulate that
2109          * chunk in one go, and then try to consume the next smaller
2110          * doubled multiple.
2111          */
2112         shift = ilog2(offset) - ilog2(tk->cycle_interval);
2113         shift = max(0, shift);
2114         /* Bound shift to one less than what overflows tick_length */
2115         maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2116         shift = min(shift, maxshift);
2117         while (offset >= tk->cycle_interval) {
2118                 offset = logarithmic_accumulation(tk, offset, shift,
2119                                                         &clock_set);
2120                 if (offset < tk->cycle_interval<<shift)
2121                         shift--;
2122         }
2123
2124         /* correct the clock when NTP error is too big */
2125         timekeeping_adjust(tk, offset);
2126
2127         /*
2128          * Finally, make sure that after the rounding
2129          * xtime_nsec isn't larger than NSEC_PER_SEC
2130          */
2131         clock_set |= accumulate_nsecs_to_secs(tk);
2132
2133         write_seqcount_begin(&tk_core.seq);
2134         /*
2135          * Update the real timekeeper.
2136          *
2137          * We could avoid this memcpy by switching pointers, but that
2138          * requires changes to all other timekeeper usage sites as
2139          * well, i.e. move the timekeeper pointer getter into the
2140          * spinlocked/seqcount protected sections. And we trade this
2141          * memcpy under the tk_core.seq against one before we start
2142          * updating.
2143          */
2144         timekeeping_update(tk, clock_set);
2145         memcpy(real_tk, tk, sizeof(*tk));
2146         /* The memcpy must come last. Do not put anything here! */
2147         write_seqcount_end(&tk_core.seq);
2148 out:
2149         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2150         if (clock_set)
2151                 /* Have to call _delayed version, since in irq context*/
2152                 clock_was_set_delayed();
2153 }
2154
2155 /**
2156  * getboottime64 - Return the real time of system boot.
2157  * @ts:         pointer to the timespec64 to be set
2158  *
2159  * Returns the wall-time of boot in a timespec64.
2160  *
2161  * This is based on the wall_to_monotonic offset and the total suspend
2162  * time. Calls to settimeofday will affect the value returned (which
2163  * basically means that however wrong your real time clock is at boot time,
2164  * you get the right time here).
2165  */
2166 void getboottime64(struct timespec64 *ts)
2167 {
2168         struct timekeeper *tk = &tk_core.timekeeper;
2169         ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2170
2171         *ts = ktime_to_timespec64(t);
2172 }
2173 EXPORT_SYMBOL_GPL(getboottime64);
2174
2175 unsigned long get_seconds(void)
2176 {
2177         struct timekeeper *tk = &tk_core.timekeeper;
2178
2179         return tk->xtime_sec;
2180 }
2181 EXPORT_SYMBOL(get_seconds);
2182
2183 struct timespec __current_kernel_time(void)
2184 {
2185         struct timekeeper *tk = &tk_core.timekeeper;
2186
2187         return timespec64_to_timespec(tk_xtime(tk));
2188 }
2189
2190 struct timespec64 current_kernel_time64(void)
2191 {
2192         struct timekeeper *tk = &tk_core.timekeeper;
2193         struct timespec64 now;
2194         unsigned long seq;
2195
2196         do {
2197                 seq = read_seqcount_begin(&tk_core.seq);
2198
2199                 now = tk_xtime(tk);
2200         } while (read_seqcount_retry(&tk_core.seq, seq));
2201
2202         return now;
2203 }
2204 EXPORT_SYMBOL(current_kernel_time64);
2205
2206 struct timespec64 get_monotonic_coarse64(void)
2207 {
2208         struct timekeeper *tk = &tk_core.timekeeper;
2209         struct timespec64 now, mono;
2210         unsigned long seq;
2211
2212         do {
2213                 seq = read_seqcount_begin(&tk_core.seq);
2214
2215                 now = tk_xtime(tk);
2216                 mono = tk->wall_to_monotonic;
2217         } while (read_seqcount_retry(&tk_core.seq, seq));
2218
2219         set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
2220                                 now.tv_nsec + mono.tv_nsec);
2221
2222         return now;
2223 }
2224 EXPORT_SYMBOL(get_monotonic_coarse64);
2225
2226 /*
2227  * Must hold jiffies_lock
2228  */
2229 void do_timer(unsigned long ticks)
2230 {
2231         jiffies_64 += ticks;
2232         calc_global_load(ticks);
2233 }
2234
2235 /**
2236  * ktime_get_update_offsets_now - hrtimer helper
2237  * @cwsseq:     pointer to check and store the clock was set sequence number
2238  * @offs_real:  pointer to storage for monotonic -> realtime offset
2239  * @offs_boot:  pointer to storage for monotonic -> boottime offset
2240  * @offs_tai:   pointer to storage for monotonic -> clock tai offset
2241  *
2242  * Returns current monotonic time and updates the offsets if the
2243  * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2244  * different.
2245  *
2246  * Called from hrtimer_interrupt() or retrigger_next_event()
2247  */
2248 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2249                                      ktime_t *offs_boot, ktime_t *offs_tai)
2250 {
2251         struct timekeeper *tk = &tk_core.timekeeper;
2252         unsigned int seq;
2253         ktime_t base;
2254         u64 nsecs;
2255
2256         do {
2257                 seq = read_seqcount_begin(&tk_core.seq);
2258
2259                 base = tk->tkr_mono.base;
2260                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2261                 base = ktime_add_ns(base, nsecs);
2262
2263                 if (*cwsseq != tk->clock_was_set_seq) {
2264                         *cwsseq = tk->clock_was_set_seq;
2265                         *offs_real = tk->offs_real;
2266                         *offs_boot = tk->offs_boot;
2267                         *offs_tai = tk->offs_tai;
2268                 }
2269
2270                 /* Handle leapsecond insertion adjustments */
2271                 if (unlikely(base >= tk->next_leap_ktime))
2272                         *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2273
2274         } while (read_seqcount_retry(&tk_core.seq, seq));
2275
2276         return base;
2277 }
2278
2279 /**
2280  * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2281  */
2282 static int timekeeping_validate_timex(struct timex *txc)
2283 {
2284         if (txc->modes & ADJ_ADJTIME) {
2285                 /* singleshot must not be used with any other mode bits */
2286                 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2287                         return -EINVAL;
2288                 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2289                     !capable(CAP_SYS_TIME))
2290                         return -EPERM;
2291         } else {
2292                 /* In order to modify anything, you gotta be super-user! */
2293                 if (txc->modes && !capable(CAP_SYS_TIME))
2294                         return -EPERM;
2295                 /*
2296                  * if the quartz is off by more than 10% then
2297                  * something is VERY wrong!
2298                  */
2299                 if (txc->modes & ADJ_TICK &&
2300                     (txc->tick <  900000/USER_HZ ||
2301                      txc->tick > 1100000/USER_HZ))
2302                         return -EINVAL;
2303         }
2304
2305         if (txc->modes & ADJ_SETOFFSET) {
2306                 /* In order to inject time, you gotta be super-user! */
2307                 if (!capable(CAP_SYS_TIME))
2308                         return -EPERM;
2309
2310                 /*
2311                  * Validate if a timespec/timeval used to inject a time
2312                  * offset is valid.  Offsets can be postive or negative, so
2313                  * we don't check tv_sec. The value of the timeval/timespec
2314                  * is the sum of its fields,but *NOTE*:
2315                  * The field tv_usec/tv_nsec must always be non-negative and
2316                  * we can't have more nanoseconds/microseconds than a second.
2317                  */
2318                 if (txc->time.tv_usec < 0)
2319                         return -EINVAL;
2320
2321                 if (txc->modes & ADJ_NANO) {
2322                         if (txc->time.tv_usec >= NSEC_PER_SEC)
2323                                 return -EINVAL;
2324                 } else {
2325                         if (txc->time.tv_usec >= USEC_PER_SEC)
2326                                 return -EINVAL;
2327                 }
2328         }
2329
2330         /*
2331          * Check for potential multiplication overflows that can
2332          * only happen on 64-bit systems:
2333          */
2334         if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2335                 if (LLONG_MIN / PPM_SCALE > txc->freq)
2336                         return -EINVAL;
2337                 if (LLONG_MAX / PPM_SCALE < txc->freq)
2338                         return -EINVAL;
2339         }
2340
2341         return 0;
2342 }
2343
2344
2345 /**
2346  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2347  */
2348 int do_adjtimex(struct timex *txc)
2349 {
2350         struct timekeeper *tk = &tk_core.timekeeper;
2351         unsigned long flags;
2352         struct timespec64 ts;
2353         s32 orig_tai, tai;
2354         int ret;
2355
2356         /* Validate the data before disabling interrupts */
2357         ret = timekeeping_validate_timex(txc);
2358         if (ret)
2359                 return ret;
2360
2361         if (txc->modes & ADJ_SETOFFSET) {
2362                 struct timespec64 delta;
2363                 delta.tv_sec  = txc->time.tv_sec;
2364                 delta.tv_nsec = txc->time.tv_usec;
2365                 if (!(txc->modes & ADJ_NANO))
2366                         delta.tv_nsec *= 1000;
2367                 ret = timekeeping_inject_offset(&delta);
2368                 if (ret)
2369                         return ret;
2370         }
2371
2372         getnstimeofday64(&ts);
2373
2374         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2375         write_seqcount_begin(&tk_core.seq);
2376
2377         orig_tai = tai = tk->tai_offset;
2378         ret = __do_adjtimex(txc, &ts, &tai);
2379
2380         if (tai != orig_tai) {
2381                 __timekeeping_set_tai_offset(tk, tai);
2382                 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2383         }
2384         tk_update_leap_state(tk);
2385
2386         write_seqcount_end(&tk_core.seq);
2387         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2388
2389         if (tai != orig_tai)
2390                 clock_was_set();
2391
2392         ntp_notify_cmos_timer();
2393
2394         return ret;
2395 }
2396
2397 #ifdef CONFIG_NTP_PPS
2398 /**
2399  * hardpps() - Accessor function to NTP __hardpps function
2400  */
2401 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2402 {
2403         unsigned long flags;
2404
2405         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2406         write_seqcount_begin(&tk_core.seq);
2407
2408         __hardpps(phase_ts, raw_ts);
2409
2410         write_seqcount_end(&tk_core.seq);
2411         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2412 }
2413 EXPORT_SYMBOL(hardpps);
2414 #endif /* CONFIG_NTP_PPS */
2415
2416 /**
2417  * xtime_update() - advances the timekeeping infrastructure
2418  * @ticks:      number of ticks, that have elapsed since the last call.
2419  *
2420  * Must be called with interrupts disabled.
2421  */
2422 void xtime_update(unsigned long ticks)
2423 {
2424         write_seqlock(&jiffies_lock);
2425         do_timer(ticks);
2426         write_sequnlock(&jiffies_lock);
2427         update_wall_time();
2428 }