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