OSDN Git Service

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