GNU Linux-libre 4.4.289-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.tv_sec = ts->tv_sec - xt.tv_sec;
970         ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
971
972         if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
973                 ret = -EINVAL;
974                 goto out;
975         }
976
977         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
978
979         tk_set_xtime(tk, ts);
980 out:
981         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
982
983         write_seqcount_end(&tk_core.seq);
984         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
985
986         /* signal hrtimers about time change */
987         clock_was_set();
988
989         return ret;
990 }
991 EXPORT_SYMBOL(do_settimeofday64);
992
993 /**
994  * timekeeping_inject_offset - Adds or subtracts from the current time.
995  * @tv:         pointer to the timespec variable containing the offset
996  *
997  * Adds or subtracts an offset value from the current time.
998  */
999 int timekeeping_inject_offset(struct timespec *ts)
1000 {
1001         struct timekeeper *tk = &tk_core.timekeeper;
1002         unsigned long flags;
1003         struct timespec64 ts64, tmp;
1004         int ret = 0;
1005
1006         if (!timespec_inject_offset_valid(ts))
1007                 return -EINVAL;
1008
1009         ts64 = timespec_to_timespec64(*ts);
1010
1011         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1012         write_seqcount_begin(&tk_core.seq);
1013
1014         timekeeping_forward_now(tk);
1015
1016         /* Make sure the proposed value is valid */
1017         tmp = timespec64_add(tk_xtime(tk),  ts64);
1018         if (timespec64_compare(&tk->wall_to_monotonic, &ts64) > 0 ||
1019             !timespec64_valid_strict(&tmp)) {
1020                 ret = -EINVAL;
1021                 goto error;
1022         }
1023
1024         tk_xtime_add(tk, &ts64);
1025         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
1026
1027 error: /* even if we error out, we forwarded the time, so call update */
1028         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1029
1030         write_seqcount_end(&tk_core.seq);
1031         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1032
1033         /* signal hrtimers about time change */
1034         clock_was_set();
1035
1036         return ret;
1037 }
1038 EXPORT_SYMBOL(timekeeping_inject_offset);
1039
1040
1041 /**
1042  * timekeeping_get_tai_offset - Returns current TAI offset from UTC
1043  *
1044  */
1045 s32 timekeeping_get_tai_offset(void)
1046 {
1047         struct timekeeper *tk = &tk_core.timekeeper;
1048         unsigned int seq;
1049         s32 ret;
1050
1051         do {
1052                 seq = read_seqcount_begin(&tk_core.seq);
1053                 ret = tk->tai_offset;
1054         } while (read_seqcount_retry(&tk_core.seq, seq));
1055
1056         return ret;
1057 }
1058
1059 /**
1060  * __timekeeping_set_tai_offset - Lock free worker function
1061  *
1062  */
1063 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1064 {
1065         tk->tai_offset = tai_offset;
1066         tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1067 }
1068
1069 /**
1070  * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
1071  *
1072  */
1073 void timekeeping_set_tai_offset(s32 tai_offset)
1074 {
1075         struct timekeeper *tk = &tk_core.timekeeper;
1076         unsigned long flags;
1077
1078         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1079         write_seqcount_begin(&tk_core.seq);
1080         __timekeeping_set_tai_offset(tk, tai_offset);
1081         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1082         write_seqcount_end(&tk_core.seq);
1083         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1084         clock_was_set();
1085 }
1086
1087 /**
1088  * change_clocksource - Swaps clocksources if a new one is available
1089  *
1090  * Accumulates current time interval and initializes new clocksource
1091  */
1092 static int change_clocksource(void *data)
1093 {
1094         struct timekeeper *tk = &tk_core.timekeeper;
1095         struct clocksource *new, *old;
1096         unsigned long flags;
1097
1098         new = (struct clocksource *) data;
1099
1100         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1101         write_seqcount_begin(&tk_core.seq);
1102
1103         timekeeping_forward_now(tk);
1104         /*
1105          * If the cs is in module, get a module reference. Succeeds
1106          * for built-in code (owner == NULL) as well.
1107          */
1108         if (try_module_get(new->owner)) {
1109                 if (!new->enable || new->enable(new) == 0) {
1110                         old = tk->tkr_mono.clock;
1111                         tk_setup_internals(tk, new);
1112                         if (old->disable)
1113                                 old->disable(old);
1114                         module_put(old->owner);
1115                 } else {
1116                         module_put(new->owner);
1117                 }
1118         }
1119         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1120
1121         write_seqcount_end(&tk_core.seq);
1122         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1123
1124         return 0;
1125 }
1126
1127 /**
1128  * timekeeping_notify - Install a new clock source
1129  * @clock:              pointer to the clock source
1130  *
1131  * This function is called from clocksource.c after a new, better clock
1132  * source has been registered. The caller holds the clocksource_mutex.
1133  */
1134 int timekeeping_notify(struct clocksource *clock)
1135 {
1136         struct timekeeper *tk = &tk_core.timekeeper;
1137
1138         if (tk->tkr_mono.clock == clock)
1139                 return 0;
1140         stop_machine(change_clocksource, clock, NULL);
1141         tick_clock_notify();
1142         return tk->tkr_mono.clock == clock ? 0 : -1;
1143 }
1144
1145 /**
1146  * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1147  * @ts:         pointer to the timespec64 to be set
1148  *
1149  * Returns the raw monotonic time (completely un-modified by ntp)
1150  */
1151 void getrawmonotonic64(struct timespec64 *ts)
1152 {
1153         struct timekeeper *tk = &tk_core.timekeeper;
1154         struct timespec64 ts64;
1155         unsigned long seq;
1156         s64 nsecs;
1157
1158         do {
1159                 seq = read_seqcount_begin(&tk_core.seq);
1160                 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1161                 ts64 = tk->raw_time;
1162
1163         } while (read_seqcount_retry(&tk_core.seq, seq));
1164
1165         timespec64_add_ns(&ts64, nsecs);
1166         *ts = ts64;
1167 }
1168 EXPORT_SYMBOL(getrawmonotonic64);
1169
1170
1171 /**
1172  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1173  */
1174 int timekeeping_valid_for_hres(void)
1175 {
1176         struct timekeeper *tk = &tk_core.timekeeper;
1177         unsigned long seq;
1178         int ret;
1179
1180         do {
1181                 seq = read_seqcount_begin(&tk_core.seq);
1182
1183                 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1184
1185         } while (read_seqcount_retry(&tk_core.seq, seq));
1186
1187         return ret;
1188 }
1189
1190 /**
1191  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1192  */
1193 u64 timekeeping_max_deferment(void)
1194 {
1195         struct timekeeper *tk = &tk_core.timekeeper;
1196         unsigned long seq;
1197         u64 ret;
1198
1199         do {
1200                 seq = read_seqcount_begin(&tk_core.seq);
1201
1202                 ret = tk->tkr_mono.clock->max_idle_ns;
1203
1204         } while (read_seqcount_retry(&tk_core.seq, seq));
1205
1206         return ret;
1207 }
1208
1209 /**
1210  * read_persistent_clock -  Return time from the persistent clock.
1211  *
1212  * Weak dummy function for arches that do not yet support it.
1213  * Reads the time from the battery backed persistent clock.
1214  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1215  *
1216  *  XXX - Do be sure to remove it once all arches implement it.
1217  */
1218 void __weak read_persistent_clock(struct timespec *ts)
1219 {
1220         ts->tv_sec = 0;
1221         ts->tv_nsec = 0;
1222 }
1223
1224 void __weak read_persistent_clock64(struct timespec64 *ts64)
1225 {
1226         struct timespec ts;
1227
1228         read_persistent_clock(&ts);
1229         *ts64 = timespec_to_timespec64(ts);
1230 }
1231
1232 /**
1233  * read_boot_clock64 -  Return time of the system start.
1234  *
1235  * Weak dummy function for arches that do not yet support it.
1236  * Function to read the exact time the system has been started.
1237  * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1238  *
1239  *  XXX - Do be sure to remove it once all arches implement it.
1240  */
1241 void __weak read_boot_clock64(struct timespec64 *ts)
1242 {
1243         ts->tv_sec = 0;
1244         ts->tv_nsec = 0;
1245 }
1246
1247 /* Flag for if timekeeping_resume() has injected sleeptime */
1248 static bool sleeptime_injected;
1249
1250 /* Flag for if there is a persistent clock on this platform */
1251 static bool persistent_clock_exists;
1252
1253 /*
1254  * timekeeping_init - Initializes the clocksource and common timekeeping values
1255  */
1256 void __init timekeeping_init(void)
1257 {
1258         struct timekeeper *tk = &tk_core.timekeeper;
1259         struct clocksource *clock;
1260         unsigned long flags;
1261         struct timespec64 now, boot, tmp;
1262
1263         read_persistent_clock64(&now);
1264         if (!timespec64_valid_strict(&now)) {
1265                 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1266                         "         Check your CMOS/BIOS settings.\n");
1267                 now.tv_sec = 0;
1268                 now.tv_nsec = 0;
1269         } else if (now.tv_sec || now.tv_nsec)
1270                 persistent_clock_exists = true;
1271
1272         read_boot_clock64(&boot);
1273         if (!timespec64_valid_strict(&boot)) {
1274                 pr_warn("WARNING: Boot clock returned invalid value!\n"
1275                         "         Check your CMOS/BIOS settings.\n");
1276                 boot.tv_sec = 0;
1277                 boot.tv_nsec = 0;
1278         }
1279
1280         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1281         write_seqcount_begin(&tk_core.seq);
1282         ntp_init();
1283
1284         clock = clocksource_default_clock();
1285         if (clock->enable)
1286                 clock->enable(clock);
1287         tk_setup_internals(tk, clock);
1288
1289         tk_set_xtime(tk, &now);
1290         tk->raw_time.tv_sec = 0;
1291         tk->raw_time.tv_nsec = 0;
1292         if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1293                 boot = tk_xtime(tk);
1294
1295         set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1296         tk_set_wall_to_mono(tk, tmp);
1297
1298         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1299
1300         write_seqcount_end(&tk_core.seq);
1301         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1302 }
1303
1304 /* time in seconds when suspend began for persistent clock */
1305 static struct timespec64 timekeeping_suspend_time;
1306
1307 /**
1308  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1309  * @delta: pointer to a timespec delta value
1310  *
1311  * Takes a timespec offset measuring a suspend interval and properly
1312  * adds the sleep offset to the timekeeping variables.
1313  */
1314 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1315                                            struct timespec64 *delta)
1316 {
1317         if (!timespec64_valid_strict(delta)) {
1318                 printk_deferred(KERN_WARNING
1319                                 "__timekeeping_inject_sleeptime: Invalid "
1320                                 "sleep delta value!\n");
1321                 return;
1322         }
1323         tk_xtime_add(tk, delta);
1324         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1325         tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1326         tk_debug_account_sleep_time(delta);
1327 }
1328
1329 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1330 /**
1331  * We have three kinds of time sources to use for sleep time
1332  * injection, the preference order is:
1333  * 1) non-stop clocksource
1334  * 2) persistent clock (ie: RTC accessible when irqs are off)
1335  * 3) RTC
1336  *
1337  * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1338  * If system has neither 1) nor 2), 3) will be used finally.
1339  *
1340  *
1341  * If timekeeping has injected sleeptime via either 1) or 2),
1342  * 3) becomes needless, so in this case we don't need to call
1343  * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1344  * means.
1345  */
1346 bool timekeeping_rtc_skipresume(void)
1347 {
1348         return sleeptime_injected;
1349 }
1350
1351 /**
1352  * 1) can be determined whether to use or not only when doing
1353  * timekeeping_resume() which is invoked after rtc_suspend(),
1354  * so we can't skip rtc_suspend() surely if system has 1).
1355  *
1356  * But if system has 2), 2) will definitely be used, so in this
1357  * case we don't need to call rtc_suspend(), and this is what
1358  * timekeeping_rtc_skipsuspend() means.
1359  */
1360 bool timekeeping_rtc_skipsuspend(void)
1361 {
1362         return persistent_clock_exists;
1363 }
1364
1365 /**
1366  * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1367  * @delta: pointer to a timespec64 delta value
1368  *
1369  * This hook is for architectures that cannot support read_persistent_clock64
1370  * because their RTC/persistent clock is only accessible when irqs are enabled.
1371  * and also don't have an effective nonstop clocksource.
1372  *
1373  * This function should only be called by rtc_resume(), and allows
1374  * a suspend offset to be injected into the timekeeping values.
1375  */
1376 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1377 {
1378         struct timekeeper *tk = &tk_core.timekeeper;
1379         unsigned long flags;
1380
1381         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1382         write_seqcount_begin(&tk_core.seq);
1383
1384         timekeeping_forward_now(tk);
1385
1386         __timekeeping_inject_sleeptime(tk, delta);
1387
1388         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1389
1390         write_seqcount_end(&tk_core.seq);
1391         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1392
1393         /* signal hrtimers about time change */
1394         clock_was_set();
1395 }
1396 #endif
1397
1398 /**
1399  * timekeeping_resume - Resumes the generic timekeeping subsystem.
1400  */
1401 void timekeeping_resume(void)
1402 {
1403         struct timekeeper *tk = &tk_core.timekeeper;
1404         struct clocksource *clock = tk->tkr_mono.clock;
1405         unsigned long flags;
1406         struct timespec64 ts_new, ts_delta;
1407         cycle_t cycle_now, cycle_delta;
1408
1409         sleeptime_injected = false;
1410         read_persistent_clock64(&ts_new);
1411
1412         clockevents_resume();
1413         clocksource_resume();
1414
1415         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1416         write_seqcount_begin(&tk_core.seq);
1417
1418         /*
1419          * After system resumes, we need to calculate the suspended time and
1420          * compensate it for the OS time. There are 3 sources that could be
1421          * used: Nonstop clocksource during suspend, persistent clock and rtc
1422          * device.
1423          *
1424          * One specific platform may have 1 or 2 or all of them, and the
1425          * preference will be:
1426          *      suspend-nonstop clocksource -> persistent clock -> rtc
1427          * The less preferred source will only be tried if there is no better
1428          * usable source. The rtc part is handled separately in rtc core code.
1429          */
1430         cycle_now = tk_clock_read(&tk->tkr_mono);
1431         if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1432                 cycle_now > tk->tkr_mono.cycle_last) {
1433                 u64 num, max = ULLONG_MAX;
1434                 u32 mult = clock->mult;
1435                 u32 shift = clock->shift;
1436                 s64 nsec = 0;
1437
1438                 cycle_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1439                                                 tk->tkr_mono.mask);
1440
1441                 /*
1442                  * "cycle_delta * mutl" may cause 64 bits overflow, if the
1443                  * suspended time is too long. In that case we need do the
1444                  * 64 bits math carefully
1445                  */
1446                 do_div(max, mult);
1447                 if (cycle_delta > max) {
1448                         num = div64_u64(cycle_delta, max);
1449                         nsec = (((u64) max * mult) >> shift) * num;
1450                         cycle_delta -= num * max;
1451                 }
1452                 nsec += ((u64) cycle_delta * mult) >> shift;
1453
1454                 ts_delta = ns_to_timespec64(nsec);
1455                 sleeptime_injected = true;
1456         } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1457                 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1458                 sleeptime_injected = true;
1459         }
1460
1461         if (sleeptime_injected)
1462                 __timekeeping_inject_sleeptime(tk, &ts_delta);
1463
1464         /* Re-base the last cycle value */
1465         tk->tkr_mono.cycle_last = cycle_now;
1466         tk->tkr_raw.cycle_last  = cycle_now;
1467
1468         tk->ntp_error = 0;
1469         timekeeping_suspended = 0;
1470         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1471         write_seqcount_end(&tk_core.seq);
1472         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1473
1474         touch_softlockup_watchdog();
1475
1476         tick_resume();
1477         hrtimers_resume();
1478 }
1479
1480 int timekeeping_suspend(void)
1481 {
1482         struct timekeeper *tk = &tk_core.timekeeper;
1483         unsigned long flags;
1484         struct timespec64               delta, delta_delta;
1485         static struct timespec64        old_delta;
1486
1487         read_persistent_clock64(&timekeeping_suspend_time);
1488
1489         /*
1490          * On some systems the persistent_clock can not be detected at
1491          * timekeeping_init by its return value, so if we see a valid
1492          * value returned, update the persistent_clock_exists flag.
1493          */
1494         if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1495                 persistent_clock_exists = true;
1496
1497         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1498         write_seqcount_begin(&tk_core.seq);
1499         timekeeping_forward_now(tk);
1500         timekeeping_suspended = 1;
1501
1502         if (persistent_clock_exists) {
1503                 /*
1504                  * To avoid drift caused by repeated suspend/resumes,
1505                  * which each can add ~1 second drift error,
1506                  * try to compensate so the difference in system time
1507                  * and persistent_clock time stays close to constant.
1508                  */
1509                 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1510                 delta_delta = timespec64_sub(delta, old_delta);
1511                 if (abs(delta_delta.tv_sec) >= 2) {
1512                         /*
1513                          * if delta_delta is too large, assume time correction
1514                          * has occurred and set old_delta to the current delta.
1515                          */
1516                         old_delta = delta;
1517                 } else {
1518                         /* Otherwise try to adjust old_system to compensate */
1519                         timekeeping_suspend_time =
1520                                 timespec64_add(timekeeping_suspend_time, delta_delta);
1521                 }
1522         }
1523
1524         timekeeping_update(tk, TK_MIRROR);
1525         halt_fast_timekeeper(tk);
1526         write_seqcount_end(&tk_core.seq);
1527         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1528
1529         tick_suspend();
1530         clocksource_suspend();
1531         clockevents_suspend();
1532
1533         return 0;
1534 }
1535
1536 /* sysfs resume/suspend bits for timekeeping */
1537 static struct syscore_ops timekeeping_syscore_ops = {
1538         .resume         = timekeeping_resume,
1539         .suspend        = timekeeping_suspend,
1540 };
1541
1542 static int __init timekeeping_init_ops(void)
1543 {
1544         register_syscore_ops(&timekeeping_syscore_ops);
1545         return 0;
1546 }
1547 device_initcall(timekeeping_init_ops);
1548
1549 /*
1550  * Apply a multiplier adjustment to the timekeeper
1551  */
1552 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1553                                                          s64 offset,
1554                                                          bool negative,
1555                                                          int adj_scale)
1556 {
1557         s64 interval = tk->cycle_interval;
1558         s32 mult_adj = 1;
1559
1560         if (negative) {
1561                 mult_adj = -mult_adj;
1562                 interval = -interval;
1563                 offset  = -offset;
1564         }
1565         mult_adj <<= adj_scale;
1566         interval <<= adj_scale;
1567         offset <<= adj_scale;
1568
1569         /*
1570          * So the following can be confusing.
1571          *
1572          * To keep things simple, lets assume mult_adj == 1 for now.
1573          *
1574          * When mult_adj != 1, remember that the interval and offset values
1575          * have been appropriately scaled so the math is the same.
1576          *
1577          * The basic idea here is that we're increasing the multiplier
1578          * by one, this causes the xtime_interval to be incremented by
1579          * one cycle_interval. This is because:
1580          *      xtime_interval = cycle_interval * mult
1581          * So if mult is being incremented by one:
1582          *      xtime_interval = cycle_interval * (mult + 1)
1583          * Its the same as:
1584          *      xtime_interval = (cycle_interval * mult) + cycle_interval
1585          * Which can be shortened to:
1586          *      xtime_interval += cycle_interval
1587          *
1588          * So offset stores the non-accumulated cycles. Thus the current
1589          * time (in shifted nanoseconds) is:
1590          *      now = (offset * adj) + xtime_nsec
1591          * Now, even though we're adjusting the clock frequency, we have
1592          * to keep time consistent. In other words, we can't jump back
1593          * in time, and we also want to avoid jumping forward in time.
1594          *
1595          * So given the same offset value, we need the time to be the same
1596          * both before and after the freq adjustment.
1597          *      now = (offset * adj_1) + xtime_nsec_1
1598          *      now = (offset * adj_2) + xtime_nsec_2
1599          * So:
1600          *      (offset * adj_1) + xtime_nsec_1 =
1601          *              (offset * adj_2) + xtime_nsec_2
1602          * And we know:
1603          *      adj_2 = adj_1 + 1
1604          * So:
1605          *      (offset * adj_1) + xtime_nsec_1 =
1606          *              (offset * (adj_1+1)) + xtime_nsec_2
1607          *      (offset * adj_1) + xtime_nsec_1 =
1608          *              (offset * adj_1) + offset + xtime_nsec_2
1609          * Canceling the sides:
1610          *      xtime_nsec_1 = offset + xtime_nsec_2
1611          * Which gives us:
1612          *      xtime_nsec_2 = xtime_nsec_1 - offset
1613          * Which simplfies to:
1614          *      xtime_nsec -= offset
1615          *
1616          * XXX - TODO: Doc ntp_error calculation.
1617          */
1618         if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1619                 /* NTP adjustment caused clocksource mult overflow */
1620                 WARN_ON_ONCE(1);
1621                 return;
1622         }
1623
1624         tk->tkr_mono.mult += mult_adj;
1625         tk->xtime_interval += interval;
1626         tk->tkr_mono.xtime_nsec -= offset;
1627         tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1628 }
1629
1630 /*
1631  * Calculate the multiplier adjustment needed to match the frequency
1632  * specified by NTP
1633  */
1634 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1635                                                         s64 offset)
1636 {
1637         s64 interval = tk->cycle_interval;
1638         s64 xinterval = tk->xtime_interval;
1639         s64 tick_error;
1640         bool negative;
1641         u32 adj;
1642
1643         /* Remove any current error adj from freq calculation */
1644         if (tk->ntp_err_mult)
1645                 xinterval -= tk->cycle_interval;
1646
1647         tk->ntp_tick = ntp_tick_length();
1648
1649         /* Calculate current error per tick */
1650         tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1651         tick_error -= (xinterval + tk->xtime_remainder);
1652
1653         /* Don't worry about correcting it if its small */
1654         if (likely((tick_error >= 0) && (tick_error <= interval)))
1655                 return;
1656
1657         /* preserve the direction of correction */
1658         negative = (tick_error < 0);
1659
1660         /* Sort out the magnitude of the correction */
1661         tick_error = abs(tick_error);
1662         for (adj = 0; tick_error > interval; adj++)
1663                 tick_error >>= 1;
1664
1665         /* scale the corrections */
1666         timekeeping_apply_adjustment(tk, offset, negative, adj);
1667 }
1668
1669 /*
1670  * Adjust the timekeeper's multiplier to the correct frequency
1671  * and also to reduce the accumulated error value.
1672  */
1673 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1674 {
1675         /* Correct for the current frequency error */
1676         timekeeping_freqadjust(tk, offset);
1677
1678         /* Next make a small adjustment to fix any cumulative error */
1679         if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1680                 tk->ntp_err_mult = 1;
1681                 timekeeping_apply_adjustment(tk, offset, 0, 0);
1682         } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1683                 /* Undo any existing error adjustment */
1684                 timekeeping_apply_adjustment(tk, offset, 1, 0);
1685                 tk->ntp_err_mult = 0;
1686         }
1687
1688         if (unlikely(tk->tkr_mono.clock->maxadj &&
1689                 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
1690                         > tk->tkr_mono.clock->maxadj))) {
1691                 printk_once(KERN_WARNING
1692                         "Adjusting %s more than 11%% (%ld vs %ld)\n",
1693                         tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
1694                         (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
1695         }
1696
1697         /*
1698          * It may be possible that when we entered this function, xtime_nsec
1699          * was very small.  Further, if we're slightly speeding the clocksource
1700          * in the code above, its possible the required corrective factor to
1701          * xtime_nsec could cause it to underflow.
1702          *
1703          * Now, since we already accumulated the second, cannot simply roll
1704          * the accumulated second back, since the NTP subsystem has been
1705          * notified via second_overflow. So instead we push xtime_nsec forward
1706          * by the amount we underflowed, and add that amount into the error.
1707          *
1708          * We'll correct this error next time through this function, when
1709          * xtime_nsec is not as small.
1710          */
1711         if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
1712                 s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
1713                 tk->tkr_mono.xtime_nsec = 0;
1714                 tk->ntp_error += neg << tk->ntp_error_shift;
1715         }
1716 }
1717
1718 /**
1719  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1720  *
1721  * Helper function that accumulates the nsecs greater than a second
1722  * from the xtime_nsec field to the xtime_secs field.
1723  * It also calls into the NTP code to handle leapsecond processing.
1724  *
1725  */
1726 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
1727 {
1728         u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
1729         unsigned int clock_set = 0;
1730
1731         while (tk->tkr_mono.xtime_nsec >= nsecps) {
1732                 int leap;
1733
1734                 tk->tkr_mono.xtime_nsec -= nsecps;
1735                 tk->xtime_sec++;
1736
1737                 /* Figure out if its a leap sec and apply if needed */
1738                 leap = second_overflow(tk->xtime_sec);
1739                 if (unlikely(leap)) {
1740                         struct timespec64 ts;
1741
1742                         tk->xtime_sec += leap;
1743
1744                         ts.tv_sec = leap;
1745                         ts.tv_nsec = 0;
1746                         tk_set_wall_to_mono(tk,
1747                                 timespec64_sub(tk->wall_to_monotonic, ts));
1748
1749                         __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1750
1751                         clock_set = TK_CLOCK_WAS_SET;
1752                 }
1753         }
1754         return clock_set;
1755 }
1756
1757 /**
1758  * logarithmic_accumulation - shifted accumulation of cycles
1759  *
1760  * This functions accumulates a shifted interval of cycles into
1761  * into a shifted interval nanoseconds. Allows for O(log) accumulation
1762  * loop.
1763  *
1764  * Returns the unconsumed cycles.
1765  */
1766 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1767                                                 u32 shift,
1768                                                 unsigned int *clock_set)
1769 {
1770         cycle_t interval = tk->cycle_interval << shift;
1771         u64 snsec_per_sec;
1772
1773         /* If the offset is smaller than a shifted interval, do nothing */
1774         if (offset < interval)
1775                 return offset;
1776
1777         /* Accumulate one shifted interval */
1778         offset -= interval;
1779         tk->tkr_mono.cycle_last += interval;
1780         tk->tkr_raw.cycle_last  += interval;
1781
1782         tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
1783         *clock_set |= accumulate_nsecs_to_secs(tk);
1784
1785         /* Accumulate raw time */
1786         tk->tkr_raw.xtime_nsec += (u64)tk->raw_time.tv_nsec << tk->tkr_raw.shift;
1787         tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
1788         snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
1789         while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
1790                 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
1791                 tk->raw_time.tv_sec++;
1792         }
1793         tk->raw_time.tv_nsec = tk->tkr_raw.xtime_nsec >> tk->tkr_raw.shift;
1794         tk->tkr_raw.xtime_nsec -= (u64)tk->raw_time.tv_nsec << tk->tkr_raw.shift;
1795
1796         /* Accumulate error between NTP and clock interval */
1797         tk->ntp_error += tk->ntp_tick << shift;
1798         tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1799                                                 (tk->ntp_error_shift + shift);
1800
1801         return offset;
1802 }
1803
1804 /**
1805  * update_wall_time - Uses the current clocksource to increment the wall time
1806  *
1807  */
1808 void update_wall_time(void)
1809 {
1810         struct timekeeper *real_tk = &tk_core.timekeeper;
1811         struct timekeeper *tk = &shadow_timekeeper;
1812         cycle_t offset;
1813         int shift = 0, maxshift;
1814         unsigned int clock_set = 0;
1815         unsigned long flags;
1816
1817         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1818
1819         /* Make sure we're fully resumed: */
1820         if (unlikely(timekeeping_suspended))
1821                 goto out;
1822
1823 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1824         offset = real_tk->cycle_interval;
1825 #else
1826         offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
1827                                    tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
1828 #endif
1829
1830         /* Check if there's really nothing to do */
1831         if (offset < real_tk->cycle_interval)
1832                 goto out;
1833
1834         /* Do some additional sanity checking */
1835         timekeeping_check_update(real_tk, offset);
1836
1837         /*
1838          * With NO_HZ we may have to accumulate many cycle_intervals
1839          * (think "ticks") worth of time at once. To do this efficiently,
1840          * we calculate the largest doubling multiple of cycle_intervals
1841          * that is smaller than the offset.  We then accumulate that
1842          * chunk in one go, and then try to consume the next smaller
1843          * doubled multiple.
1844          */
1845         shift = ilog2(offset) - ilog2(tk->cycle_interval);
1846         shift = max(0, shift);
1847         /* Bound shift to one less than what overflows tick_length */
1848         maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1849         shift = min(shift, maxshift);
1850         while (offset >= tk->cycle_interval) {
1851                 offset = logarithmic_accumulation(tk, offset, shift,
1852                                                         &clock_set);
1853                 if (offset < tk->cycle_interval<<shift)
1854                         shift--;
1855         }
1856
1857         /* correct the clock when NTP error is too big */
1858         timekeeping_adjust(tk, offset);
1859
1860         /*
1861          * XXX This can be killed once everyone converts
1862          * to the new update_vsyscall.
1863          */
1864         old_vsyscall_fixup(tk);
1865
1866         /*
1867          * Finally, make sure that after the rounding
1868          * xtime_nsec isn't larger than NSEC_PER_SEC
1869          */
1870         clock_set |= accumulate_nsecs_to_secs(tk);
1871
1872         write_seqcount_begin(&tk_core.seq);
1873         /*
1874          * Update the real timekeeper.
1875          *
1876          * We could avoid this memcpy by switching pointers, but that
1877          * requires changes to all other timekeeper usage sites as
1878          * well, i.e. move the timekeeper pointer getter into the
1879          * spinlocked/seqcount protected sections. And we trade this
1880          * memcpy under the tk_core.seq against one before we start
1881          * updating.
1882          */
1883         timekeeping_update(tk, clock_set);
1884         memcpy(real_tk, tk, sizeof(*tk));
1885         /* The memcpy must come last. Do not put anything here! */
1886         write_seqcount_end(&tk_core.seq);
1887 out:
1888         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1889         if (clock_set)
1890                 /* Have to call _delayed version, since in irq context*/
1891                 clock_was_set_delayed();
1892 }
1893
1894 /**
1895  * getboottime64 - Return the real time of system boot.
1896  * @ts:         pointer to the timespec64 to be set
1897  *
1898  * Returns the wall-time of boot in a timespec64.
1899  *
1900  * This is based on the wall_to_monotonic offset and the total suspend
1901  * time. Calls to settimeofday will affect the value returned (which
1902  * basically means that however wrong your real time clock is at boot time,
1903  * you get the right time here).
1904  */
1905 void getboottime64(struct timespec64 *ts)
1906 {
1907         struct timekeeper *tk = &tk_core.timekeeper;
1908         ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
1909
1910         *ts = ktime_to_timespec64(t);
1911 }
1912 EXPORT_SYMBOL_GPL(getboottime64);
1913
1914 unsigned long get_seconds(void)
1915 {
1916         struct timekeeper *tk = &tk_core.timekeeper;
1917
1918         return tk->xtime_sec;
1919 }
1920 EXPORT_SYMBOL(get_seconds);
1921
1922 struct timespec __current_kernel_time(void)
1923 {
1924         struct timekeeper *tk = &tk_core.timekeeper;
1925
1926         return timespec64_to_timespec(tk_xtime(tk));
1927 }
1928
1929 struct timespec64 current_kernel_time64(void)
1930 {
1931         struct timekeeper *tk = &tk_core.timekeeper;
1932         struct timespec64 now;
1933         unsigned long seq;
1934
1935         do {
1936                 seq = read_seqcount_begin(&tk_core.seq);
1937
1938                 now = tk_xtime(tk);
1939         } while (read_seqcount_retry(&tk_core.seq, seq));
1940
1941         return now;
1942 }
1943 EXPORT_SYMBOL(current_kernel_time64);
1944
1945 struct timespec64 get_monotonic_coarse64(void)
1946 {
1947         struct timekeeper *tk = &tk_core.timekeeper;
1948         struct timespec64 now, mono;
1949         unsigned long seq;
1950
1951         do {
1952                 seq = read_seqcount_begin(&tk_core.seq);
1953
1954                 now = tk_xtime(tk);
1955                 mono = tk->wall_to_monotonic;
1956         } while (read_seqcount_retry(&tk_core.seq, seq));
1957
1958         set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
1959                                 now.tv_nsec + mono.tv_nsec);
1960
1961         return now;
1962 }
1963
1964 /*
1965  * Must hold jiffies_lock
1966  */
1967 void do_timer(unsigned long ticks)
1968 {
1969         jiffies_64 += ticks;
1970         calc_global_load(ticks);
1971 }
1972
1973 /**
1974  * ktime_get_update_offsets_now - hrtimer helper
1975  * @cwsseq:     pointer to check and store the clock was set sequence number
1976  * @offs_real:  pointer to storage for monotonic -> realtime offset
1977  * @offs_boot:  pointer to storage for monotonic -> boottime offset
1978  * @offs_tai:   pointer to storage for monotonic -> clock tai offset
1979  *
1980  * Returns current monotonic time and updates the offsets if the
1981  * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
1982  * different.
1983  *
1984  * Called from hrtimer_interrupt() or retrigger_next_event()
1985  */
1986 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
1987                                      ktime_t *offs_boot, ktime_t *offs_tai)
1988 {
1989         struct timekeeper *tk = &tk_core.timekeeper;
1990         unsigned int seq;
1991         ktime_t base;
1992         u64 nsecs;
1993
1994         do {
1995                 seq = read_seqcount_begin(&tk_core.seq);
1996
1997                 base = tk->tkr_mono.base;
1998                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
1999                 base = ktime_add_ns(base, nsecs);
2000
2001                 if (*cwsseq != tk->clock_was_set_seq) {
2002                         *cwsseq = tk->clock_was_set_seq;
2003                         *offs_real = tk->offs_real;
2004                         *offs_boot = tk->offs_boot;
2005                         *offs_tai = tk->offs_tai;
2006                 }
2007
2008                 /* Handle leapsecond insertion adjustments */
2009                 if (unlikely(base.tv64 >= tk->next_leap_ktime.tv64))
2010                         *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2011
2012         } while (read_seqcount_retry(&tk_core.seq, seq));
2013
2014         return base;
2015 }
2016
2017 /**
2018  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2019  */
2020 int do_adjtimex(struct timex *txc)
2021 {
2022         struct timekeeper *tk = &tk_core.timekeeper;
2023         unsigned long flags;
2024         struct timespec64 ts;
2025         s32 orig_tai, tai;
2026         int ret;
2027
2028         /* Validate the data before disabling interrupts */
2029         ret = ntp_validate_timex(txc);
2030         if (ret)
2031                 return ret;
2032
2033         if (txc->modes & ADJ_SETOFFSET) {
2034                 struct timespec delta;
2035                 delta.tv_sec  = txc->time.tv_sec;
2036                 delta.tv_nsec = txc->time.tv_usec;
2037                 if (!(txc->modes & ADJ_NANO))
2038                         delta.tv_nsec *= 1000;
2039                 ret = timekeeping_inject_offset(&delta);
2040                 if (ret)
2041                         return ret;
2042         }
2043
2044         getnstimeofday64(&ts);
2045
2046         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2047         write_seqcount_begin(&tk_core.seq);
2048
2049         orig_tai = tai = tk->tai_offset;
2050         ret = __do_adjtimex(txc, &ts, &tai);
2051
2052         if (tai != orig_tai) {
2053                 __timekeeping_set_tai_offset(tk, tai);
2054                 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2055         }
2056         tk_update_leap_state(tk);
2057
2058         write_seqcount_end(&tk_core.seq);
2059         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2060
2061         if (tai != orig_tai)
2062                 clock_was_set();
2063
2064         ntp_notify_cmos_timer();
2065
2066         return ret;
2067 }
2068
2069 #ifdef CONFIG_NTP_PPS
2070 /**
2071  * hardpps() - Accessor function to NTP __hardpps function
2072  */
2073 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2074 {
2075         unsigned long flags;
2076
2077         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2078         write_seqcount_begin(&tk_core.seq);
2079
2080         __hardpps(phase_ts, raw_ts);
2081
2082         write_seqcount_end(&tk_core.seq);
2083         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2084 }
2085 EXPORT_SYMBOL(hardpps);
2086 #endif
2087
2088 /**
2089  * xtime_update() - advances the timekeeping infrastructure
2090  * @ticks:      number of ticks, that have elapsed since the last call.
2091  *
2092  * Must be called with interrupts disabled.
2093  */
2094 void xtime_update(unsigned long ticks)
2095 {
2096         write_seqlock(&jiffies_lock);
2097         do_timer(ticks);
2098         write_sequnlock(&jiffies_lock);
2099         update_wall_time();
2100 }