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