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