~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/kernel/time/timekeeping.c

Version: ~ [ linux-6.11.5 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.58 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.114 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.169 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.228 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.284 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.322 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 // SPDX-License-Identifier: GPL-2.0
  2 /*
  3  *  Kernel timekeeping code and accessor functions. Based on code from
  4  *  timer.c, moved in commit 8524070b7982.
  5  */
  6 #include <linux/timekeeper_internal.h>
  7 #include <linux/module.h>
  8 #include <linux/interrupt.h>
  9 #include <linux/percpu.h>
 10 #include <linux/init.h>
 11 #include <linux/mm.h>
 12 #include <linux/nmi.h>
 13 #include <linux/sched.h>
 14 #include <linux/sched/loadavg.h>
 15 #include <linux/sched/clock.h>
 16 #include <linux/syscore_ops.h>
 17 #include <linux/clocksource.h>
 18 #include <linux/jiffies.h>
 19 #include <linux/time.h>
 20 #include <linux/timex.h>
 21 #include <linux/tick.h>
 22 #include <linux/stop_machine.h>
 23 #include <linux/pvclock_gtod.h>
 24 #include <linux/compiler.h>
 25 #include <linux/audit.h>
 26 #include <linux/random.h>
 27 #include <linux/ccsecurity.h>
 28 
 29 #include "tick-internal.h"
 30 #include "ntp_internal.h"
 31 #include "timekeeping_internal.h"
 32 
 33 #define TK_CLEAR_NTP            (1 << 0)
 34 #define TK_MIRROR               (1 << 1)
 35 #define TK_CLOCK_WAS_SET        (1 << 2)
 36 
 37 enum timekeeping_adv_mode {
 38         /* Update timekeeper when a tick has passed */
 39         TK_ADV_TICK,
 40 
 41         /* Update timekeeper on a direct frequency change */
 42         TK_ADV_FREQ
 43 };
 44 
 45 DEFINE_RAW_SPINLOCK(timekeeper_lock);
 46 
 47 /*
 48  * The most important data for readout fits into a single 64 byte
 49  * cache line.
 50  */
 51 static struct {
 52         seqcount_raw_spinlock_t seq;
 53         struct timekeeper       timekeeper;
 54 } tk_core ____cacheline_aligned = {
 55         .seq = SEQCNT_RAW_SPINLOCK_ZERO(tk_core.seq, &timekeeper_lock),
 56 };
 57 
 58 static struct timekeeper shadow_timekeeper;
 59 
 60 /* flag for if timekeeping is suspended */
 61 int __read_mostly timekeeping_suspended;
 62 
 63 /**
 64  * struct tk_fast - NMI safe timekeeper
 65  * @seq:        Sequence counter for protecting updates. The lowest bit
 66  *              is the index for the tk_read_base array
 67  * @base:       tk_read_base array. Access is indexed by the lowest bit of
 68  *              @seq.
 69  *
 70  * See @update_fast_timekeeper() below.
 71  */
 72 struct tk_fast {
 73         seqcount_latch_t        seq;
 74         struct tk_read_base     base[2];
 75 };
 76 
 77 /* Suspend-time cycles value for halted fast timekeeper. */
 78 static u64 cycles_at_suspend;
 79 
 80 static u64 dummy_clock_read(struct clocksource *cs)
 81 {
 82         if (timekeeping_suspended)
 83                 return cycles_at_suspend;
 84         return local_clock();
 85 }
 86 
 87 static struct clocksource dummy_clock = {
 88         .read = dummy_clock_read,
 89 };
 90 
 91 /*
 92  * Boot time initialization which allows local_clock() to be utilized
 93  * during early boot when clocksources are not available. local_clock()
 94  * returns nanoseconds already so no conversion is required, hence mult=1
 95  * and shift=0. When the first proper clocksource is installed then
 96  * the fast time keepers are updated with the correct values.
 97  */
 98 #define FAST_TK_INIT                                            \
 99         {                                                       \
100                 .clock          = &dummy_clock,                 \
101                 .mask           = CLOCKSOURCE_MASK(64),         \
102                 .mult           = 1,                            \
103                 .shift          = 0,                            \
104         }
105 
106 static struct tk_fast tk_fast_mono ____cacheline_aligned = {
107         .seq     = SEQCNT_LATCH_ZERO(tk_fast_mono.seq),
108         .base[0] = FAST_TK_INIT,
109         .base[1] = FAST_TK_INIT,
110 };
111 
112 static struct tk_fast tk_fast_raw  ____cacheline_aligned = {
113         .seq     = SEQCNT_LATCH_ZERO(tk_fast_raw.seq),
114         .base[0] = FAST_TK_INIT,
115         .base[1] = FAST_TK_INIT,
116 };
117 
118 static inline void tk_normalize_xtime(struct timekeeper *tk)
119 {
120         while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
121                 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
122                 tk->xtime_sec++;
123         }
124         while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
125                 tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
126                 tk->raw_sec++;
127         }
128 }
129 
130 static inline struct timespec64 tk_xtime(const struct timekeeper *tk)
131 {
132         struct timespec64 ts;
133 
134         ts.tv_sec = tk->xtime_sec;
135         ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
136         return ts;
137 }
138 
139 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
140 {
141         tk->xtime_sec = ts->tv_sec;
142         tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
143 }
144 
145 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
146 {
147         tk->xtime_sec += ts->tv_sec;
148         tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
149         tk_normalize_xtime(tk);
150 }
151 
152 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
153 {
154         struct timespec64 tmp;
155 
156         /*
157          * Verify consistency of: offset_real = -wall_to_monotonic
158          * before modifying anything
159          */
160         set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
161                                         -tk->wall_to_monotonic.tv_nsec);
162         WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
163         tk->wall_to_monotonic = wtm;
164         set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
165         tk->offs_real = timespec64_to_ktime(tmp);
166         tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
167 }
168 
169 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
170 {
171         tk->offs_boot = ktime_add(tk->offs_boot, delta);
172         /*
173          * Timespec representation for VDSO update to avoid 64bit division
174          * on every update.
175          */
176         tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot);
177 }
178 
179 /*
180  * tk_clock_read - atomic clocksource read() helper
181  *
182  * This helper is necessary to use in the read paths because, while the
183  * seqcount ensures we don't return a bad value while structures are updated,
184  * it doesn't protect from potential crashes. There is the possibility that
185  * the tkr's clocksource may change between the read reference, and the
186  * clock reference passed to the read function.  This can cause crashes if
187  * the wrong clocksource is passed to the wrong read function.
188  * This isn't necessary to use when holding the timekeeper_lock or doing
189  * a read of the fast-timekeeper tkrs (which is protected by its own locking
190  * and update logic).
191  */
192 static inline u64 tk_clock_read(const struct tk_read_base *tkr)
193 {
194         struct clocksource *clock = READ_ONCE(tkr->clock);
195 
196         return clock->read(clock);
197 }
198 
199 #ifdef CONFIG_DEBUG_TIMEKEEPING
200 #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
201 
202 static void timekeeping_check_update(struct timekeeper *tk, u64 offset)
203 {
204 
205         u64 max_cycles = tk->tkr_mono.clock->max_cycles;
206         const char *name = tk->tkr_mono.clock->name;
207 
208         if (offset > max_cycles) {
209                 printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
210                                 offset, name, max_cycles);
211                 printk_deferred("         timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
212         } else {
213                 if (offset > (max_cycles >> 1)) {
214                         printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the '%s' clock's 50%% safety margin (%lld)\n",
215                                         offset, name, max_cycles >> 1);
216                         printk_deferred("      timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
217                 }
218         }
219 
220         if (tk->underflow_seen) {
221                 if (jiffies - tk->last_warning > WARNING_FREQ) {
222                         printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
223                         printk_deferred("         Please report this, consider using a different clocksource, if possible.\n");
224                         printk_deferred("         Your kernel is probably still fine.\n");
225                         tk->last_warning = jiffies;
226                 }
227                 tk->underflow_seen = 0;
228         }
229 
230         if (tk->overflow_seen) {
231                 if (jiffies - tk->last_warning > WARNING_FREQ) {
232                         printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
233                         printk_deferred("         Please report this, consider using a different clocksource, if possible.\n");
234                         printk_deferred("         Your kernel is probably still fine.\n");
235                         tk->last_warning = jiffies;
236                 }
237                 tk->overflow_seen = 0;
238         }
239 }
240 
241 static inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles);
242 
243 static inline u64 timekeeping_debug_get_ns(const struct tk_read_base *tkr)
244 {
245         struct timekeeper *tk = &tk_core.timekeeper;
246         u64 now, last, mask, max, delta;
247         unsigned int seq;
248 
249         /*
250          * Since we're called holding a seqcount, the data may shift
251          * under us while we're doing the calculation. This can cause
252          * false positives, since we'd note a problem but throw the
253          * results away. So nest another seqcount here to atomically
254          * grab the points we are checking with.
255          */
256         do {
257                 seq = read_seqcount_begin(&tk_core.seq);
258                 now = tk_clock_read(tkr);
259                 last = tkr->cycle_last;
260                 mask = tkr->mask;
261                 max = tkr->clock->max_cycles;
262         } while (read_seqcount_retry(&tk_core.seq, seq));
263 
264         delta = clocksource_delta(now, last, mask);
265 
266         /*
267          * Try to catch underflows by checking if we are seeing small
268          * mask-relative negative values.
269          */
270         if (unlikely((~delta & mask) < (mask >> 3)))
271                 tk->underflow_seen = 1;
272 
273         /* Check for multiplication overflows */
274         if (unlikely(delta > max))
275                 tk->overflow_seen = 1;
276 
277         /* timekeeping_cycles_to_ns() handles both under and overflow */
278         return timekeeping_cycles_to_ns(tkr, now);
279 }
280 #else
281 static inline void timekeeping_check_update(struct timekeeper *tk, u64 offset)
282 {
283 }
284 static inline u64 timekeeping_debug_get_ns(const struct tk_read_base *tkr)
285 {
286         BUG();
287 }
288 #endif
289 
290 /**
291  * tk_setup_internals - Set up internals to use clocksource clock.
292  *
293  * @tk:         The target timekeeper to setup.
294  * @clock:              Pointer to clocksource.
295  *
296  * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
297  * pair and interval request.
298  *
299  * Unless you're the timekeeping code, you should not be using this!
300  */
301 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
302 {
303         u64 interval;
304         u64 tmp, ntpinterval;
305         struct clocksource *old_clock;
306 
307         ++tk->cs_was_changed_seq;
308         old_clock = tk->tkr_mono.clock;
309         tk->tkr_mono.clock = clock;
310         tk->tkr_mono.mask = clock->mask;
311         tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
312 
313         tk->tkr_raw.clock = clock;
314         tk->tkr_raw.mask = clock->mask;
315         tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
316 
317         /* Do the ns -> cycle conversion first, using original mult */
318         tmp = NTP_INTERVAL_LENGTH;
319         tmp <<= clock->shift;
320         ntpinterval = tmp;
321         tmp += clock->mult/2;
322         do_div(tmp, clock->mult);
323         if (tmp == 0)
324                 tmp = 1;
325 
326         interval = (u64) tmp;
327         tk->cycle_interval = interval;
328 
329         /* Go back from cycles -> shifted ns */
330         tk->xtime_interval = interval * clock->mult;
331         tk->xtime_remainder = ntpinterval - tk->xtime_interval;
332         tk->raw_interval = interval * clock->mult;
333 
334          /* if changing clocks, convert xtime_nsec shift units */
335         if (old_clock) {
336                 int shift_change = clock->shift - old_clock->shift;
337                 if (shift_change < 0) {
338                         tk->tkr_mono.xtime_nsec >>= -shift_change;
339                         tk->tkr_raw.xtime_nsec >>= -shift_change;
340                 } else {
341                         tk->tkr_mono.xtime_nsec <<= shift_change;
342                         tk->tkr_raw.xtime_nsec <<= shift_change;
343                 }
344         }
345 
346         tk->tkr_mono.shift = clock->shift;
347         tk->tkr_raw.shift = clock->shift;
348 
349         tk->ntp_error = 0;
350         tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
351         tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
352 
353         /*
354          * The timekeeper keeps its own mult values for the currently
355          * active clocksource. These value will be adjusted via NTP
356          * to counteract clock drifting.
357          */
358         tk->tkr_mono.mult = clock->mult;
359         tk->tkr_raw.mult = clock->mult;
360         tk->ntp_err_mult = 0;
361         tk->skip_second_overflow = 0;
362 }
363 
364 /* Timekeeper helper functions. */
365 static noinline u64 delta_to_ns_safe(const struct tk_read_base *tkr, u64 delta)
366 {
367         return mul_u64_u32_add_u64_shr(delta, tkr->mult, tkr->xtime_nsec, tkr->shift);
368 }
369 
370 static inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles)
371 {
372         /* Calculate the delta since the last update_wall_time() */
373         u64 mask = tkr->mask, delta = (cycles - tkr->cycle_last) & mask;
374 
375         /*
376          * This detects both negative motion and the case where the delta
377          * overflows the multiplication with tkr->mult.
378          */
379         if (unlikely(delta > tkr->clock->max_cycles)) {
380                 /*
381                  * Handle clocksource inconsistency between CPUs to prevent
382                  * time from going backwards by checking for the MSB of the
383                  * mask being set in the delta.
384                  */
385                 if (delta & ~(mask >> 1))
386                         return tkr->xtime_nsec >> tkr->shift;
387 
388                 return delta_to_ns_safe(tkr, delta);
389         }
390 
391         return ((delta * tkr->mult) + tkr->xtime_nsec) >> tkr->shift;
392 }
393 
394 static __always_inline u64 __timekeeping_get_ns(const struct tk_read_base *tkr)
395 {
396         return timekeeping_cycles_to_ns(tkr, tk_clock_read(tkr));
397 }
398 
399 static inline u64 timekeeping_get_ns(const struct tk_read_base *tkr)
400 {
401         if (IS_ENABLED(CONFIG_DEBUG_TIMEKEEPING))
402                 return timekeeping_debug_get_ns(tkr);
403 
404         return __timekeeping_get_ns(tkr);
405 }
406 
407 /**
408  * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
409  * @tkr: Timekeeping readout base from which we take the update
410  * @tkf: Pointer to NMI safe timekeeper
411  *
412  * We want to use this from any context including NMI and tracing /
413  * instrumenting the timekeeping code itself.
414  *
415  * Employ the latch technique; see @raw_write_seqcount_latch.
416  *
417  * So if a NMI hits the update of base[0] then it will use base[1]
418  * which is still consistent. In the worst case this can result is a
419  * slightly wrong timestamp (a few nanoseconds). See
420  * @ktime_get_mono_fast_ns.
421  */
422 static void update_fast_timekeeper(const struct tk_read_base *tkr,
423                                    struct tk_fast *tkf)
424 {
425         struct tk_read_base *base = tkf->base;
426 
427         /* Force readers off to base[1] */
428         raw_write_seqcount_latch(&tkf->seq);
429 
430         /* Update base[0] */
431         memcpy(base, tkr, sizeof(*base));
432 
433         /* Force readers back to base[0] */
434         raw_write_seqcount_latch(&tkf->seq);
435 
436         /* Update base[1] */
437         memcpy(base + 1, base, sizeof(*base));
438 }
439 
440 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
441 {
442         struct tk_read_base *tkr;
443         unsigned int seq;
444         u64 now;
445 
446         do {
447                 seq = raw_read_seqcount_latch(&tkf->seq);
448                 tkr = tkf->base + (seq & 0x01);
449                 now = ktime_to_ns(tkr->base);
450                 now += __timekeeping_get_ns(tkr);
451         } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
452 
453         return now;
454 }
455 
456 /**
457  * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
458  *
459  * This timestamp is not guaranteed to be monotonic across an update.
460  * The timestamp is calculated by:
461  *
462  *      now = base_mono + clock_delta * slope
463  *
464  * So if the update lowers the slope, readers who are forced to the
465  * not yet updated second array are still using the old steeper slope.
466  *
467  * tmono
468  * ^
469  * |    o  n
470  * |   o n
471  * |  u
472  * | o
473  * |o
474  * |12345678---> reader order
475  *
476  * o = old slope
477  * u = update
478  * n = new slope
479  *
480  * So reader 6 will observe time going backwards versus reader 5.
481  *
482  * While other CPUs are likely to be able to observe that, the only way
483  * for a CPU local observation is when an NMI hits in the middle of
484  * the update. Timestamps taken from that NMI context might be ahead
485  * of the following timestamps. Callers need to be aware of that and
486  * deal with it.
487  */
488 u64 notrace ktime_get_mono_fast_ns(void)
489 {
490         return __ktime_get_fast_ns(&tk_fast_mono);
491 }
492 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
493 
494 /**
495  * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw
496  *
497  * Contrary to ktime_get_mono_fast_ns() this is always correct because the
498  * conversion factor is not affected by NTP/PTP correction.
499  */
500 u64 notrace ktime_get_raw_fast_ns(void)
501 {
502         return __ktime_get_fast_ns(&tk_fast_raw);
503 }
504 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
505 
506 /**
507  * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
508  *
509  * To keep it NMI safe since we're accessing from tracing, we're not using a
510  * separate timekeeper with updates to monotonic clock and boot offset
511  * protected with seqcounts. This has the following minor side effects:
512  *
513  * (1) Its possible that a timestamp be taken after the boot offset is updated
514  * but before the timekeeper is updated. If this happens, the new boot offset
515  * is added to the old timekeeping making the clock appear to update slightly
516  * earlier:
517  *    CPU 0                                        CPU 1
518  *    timekeeping_inject_sleeptime64()
519  *    __timekeeping_inject_sleeptime(tk, delta);
520  *                                                 timestamp();
521  *    timekeeping_update(tk, TK_CLEAR_NTP...);
522  *
523  * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
524  * partially updated.  Since the tk->offs_boot update is a rare event, this
525  * should be a rare occurrence which postprocessing should be able to handle.
526  *
527  * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns()
528  * apply as well.
529  */
530 u64 notrace ktime_get_boot_fast_ns(void)
531 {
532         struct timekeeper *tk = &tk_core.timekeeper;
533 
534         return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot)));
535 }
536 EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
537 
538 /**
539  * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock.
540  *
541  * The same limitations as described for ktime_get_boot_fast_ns() apply. The
542  * mono time and the TAI offset are not read atomically which may yield wrong
543  * readouts. However, an update of the TAI offset is an rare event e.g., caused
544  * by settime or adjtimex with an offset. The user of this function has to deal
545  * with the possibility of wrong timestamps in post processing.
546  */
547 u64 notrace ktime_get_tai_fast_ns(void)
548 {
549         struct timekeeper *tk = &tk_core.timekeeper;
550 
551         return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai)));
552 }
553 EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns);
554 
555 static __always_inline u64 __ktime_get_real_fast(struct tk_fast *tkf, u64 *mono)
556 {
557         struct tk_read_base *tkr;
558         u64 basem, baser, delta;
559         unsigned int seq;
560 
561         do {
562                 seq = raw_read_seqcount_latch(&tkf->seq);
563                 tkr = tkf->base + (seq & 0x01);
564                 basem = ktime_to_ns(tkr->base);
565                 baser = ktime_to_ns(tkr->base_real);
566                 delta = __timekeeping_get_ns(tkr);
567         } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
568 
569         if (mono)
570                 *mono = basem + delta;
571         return baser + delta;
572 }
573 
574 /**
575  * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
576  *
577  * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering.
578  */
579 u64 ktime_get_real_fast_ns(void)
580 {
581         return __ktime_get_real_fast(&tk_fast_mono, NULL);
582 }
583 EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
584 
585 /**
586  * ktime_get_fast_timestamps: - NMI safe timestamps
587  * @snapshot:   Pointer to timestamp storage
588  *
589  * Stores clock monotonic, boottime and realtime timestamps.
590  *
591  * Boot time is a racy access on 32bit systems if the sleep time injection
592  * happens late during resume and not in timekeeping_resume(). That could
593  * be avoided by expanding struct tk_read_base with boot offset for 32bit
594  * and adding more overhead to the update. As this is a hard to observe
595  * once per resume event which can be filtered with reasonable effort using
596  * the accurate mono/real timestamps, it's probably not worth the trouble.
597  *
598  * Aside of that it might be possible on 32 and 64 bit to observe the
599  * following when the sleep time injection happens late:
600  *
601  * CPU 0                                CPU 1
602  * timekeeping_resume()
603  * ktime_get_fast_timestamps()
604  *      mono, real = __ktime_get_real_fast()
605  *                                      inject_sleep_time()
606  *                                         update boot offset
607  *      boot = mono + bootoffset;
608  *
609  * That means that boot time already has the sleep time adjustment, but
610  * real time does not. On the next readout both are in sync again.
611  *
612  * Preventing this for 64bit is not really feasible without destroying the
613  * careful cache layout of the timekeeper because the sequence count and
614  * struct tk_read_base would then need two cache lines instead of one.
615  *
616  * Access to the time keeper clock source is disabled across the innermost
617  * steps of suspend/resume. The accessors still work, but the timestamps
618  * are frozen until time keeping is resumed which happens very early.
619  *
620  * For regular suspend/resume there is no observable difference vs. sched
621  * clock, but it might affect some of the nasty low level debug printks.
622  *
623  * OTOH, access to sched clock is not guaranteed across suspend/resume on
624  * all systems either so it depends on the hardware in use.
625  *
626  * If that turns out to be a real problem then this could be mitigated by
627  * using sched clock in a similar way as during early boot. But it's not as
628  * trivial as on early boot because it needs some careful protection
629  * against the clock monotonic timestamp jumping backwards on resume.
630  */
631 void ktime_get_fast_timestamps(struct ktime_timestamps *snapshot)
632 {
633         struct timekeeper *tk = &tk_core.timekeeper;
634 
635         snapshot->real = __ktime_get_real_fast(&tk_fast_mono, &snapshot->mono);
636         snapshot->boot = snapshot->mono + ktime_to_ns(data_race(tk->offs_boot));
637 }
638 
639 /**
640  * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
641  * @tk: Timekeeper to snapshot.
642  *
643  * It generally is unsafe to access the clocksource after timekeeping has been
644  * suspended, so take a snapshot of the readout base of @tk and use it as the
645  * fast timekeeper's readout base while suspended.  It will return the same
646  * number of cycles every time until timekeeping is resumed at which time the
647  * proper readout base for the fast timekeeper will be restored automatically.
648  */
649 static void halt_fast_timekeeper(const struct timekeeper *tk)
650 {
651         static struct tk_read_base tkr_dummy;
652         const struct tk_read_base *tkr = &tk->tkr_mono;
653 
654         memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
655         cycles_at_suspend = tk_clock_read(tkr);
656         tkr_dummy.clock = &dummy_clock;
657         tkr_dummy.base_real = tkr->base + tk->offs_real;
658         update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
659 
660         tkr = &tk->tkr_raw;
661         memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
662         tkr_dummy.clock = &dummy_clock;
663         update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
664 }
665 
666 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
667 
668 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
669 {
670         raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
671 }
672 
673 /**
674  * pvclock_gtod_register_notifier - register a pvclock timedata update listener
675  * @nb: Pointer to the notifier block to register
676  */
677 int pvclock_gtod_register_notifier(struct notifier_block *nb)
678 {
679         struct timekeeper *tk = &tk_core.timekeeper;
680         unsigned long flags;
681         int ret;
682 
683         raw_spin_lock_irqsave(&timekeeper_lock, flags);
684         ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
685         update_pvclock_gtod(tk, true);
686         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
687 
688         return ret;
689 }
690 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
691 
692 /**
693  * pvclock_gtod_unregister_notifier - unregister a pvclock
694  * timedata update listener
695  * @nb: Pointer to the notifier block to unregister
696  */
697 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
698 {
699         unsigned long flags;
700         int ret;
701 
702         raw_spin_lock_irqsave(&timekeeper_lock, flags);
703         ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
704         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
705 
706         return ret;
707 }
708 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
709 
710 /*
711  * tk_update_leap_state - helper to update the next_leap_ktime
712  */
713 static inline void tk_update_leap_state(struct timekeeper *tk)
714 {
715         tk->next_leap_ktime = ntp_get_next_leap();
716         if (tk->next_leap_ktime != KTIME_MAX)
717                 /* Convert to monotonic time */
718                 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
719 }
720 
721 /*
722  * Update the ktime_t based scalar nsec members of the timekeeper
723  */
724 static inline void tk_update_ktime_data(struct timekeeper *tk)
725 {
726         u64 seconds;
727         u32 nsec;
728 
729         /*
730          * The xtime based monotonic readout is:
731          *      nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
732          * The ktime based monotonic readout is:
733          *      nsec = base_mono + now();
734          * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
735          */
736         seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
737         nsec = (u32) tk->wall_to_monotonic.tv_nsec;
738         tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
739 
740         /*
741          * The sum of the nanoseconds portions of xtime and
742          * wall_to_monotonic can be greater/equal one second. Take
743          * this into account before updating tk->ktime_sec.
744          */
745         nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
746         if (nsec >= NSEC_PER_SEC)
747                 seconds++;
748         tk->ktime_sec = seconds;
749 
750         /* Update the monotonic raw base */
751         tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
752 }
753 
754 /* must hold timekeeper_lock */
755 static void timekeeping_update(struct timekeeper *tk, unsigned int action)
756 {
757         if (action & TK_CLEAR_NTP) {
758                 tk->ntp_error = 0;
759                 ntp_clear();
760         }
761 
762         tk_update_leap_state(tk);
763         tk_update_ktime_data(tk);
764 
765         update_vsyscall(tk);
766         update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
767 
768         tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
769         update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
770         update_fast_timekeeper(&tk->tkr_raw,  &tk_fast_raw);
771 
772         if (action & TK_CLOCK_WAS_SET)
773                 tk->clock_was_set_seq++;
774         /*
775          * The mirroring of the data to the shadow-timekeeper needs
776          * to happen last here to ensure we don't over-write the
777          * timekeeper structure on the next update with stale data
778          */
779         if (action & TK_MIRROR)
780                 memcpy(&shadow_timekeeper, &tk_core.timekeeper,
781                        sizeof(tk_core.timekeeper));
782 }
783 
784 /**
785  * timekeeping_forward_now - update clock to the current time
786  * @tk:         Pointer to the timekeeper to update
787  *
788  * Forward the current clock to update its state since the last call to
789  * update_wall_time(). This is useful before significant clock changes,
790  * as it avoids having to deal with this time offset explicitly.
791  */
792 static void timekeeping_forward_now(struct timekeeper *tk)
793 {
794         u64 cycle_now, delta;
795 
796         cycle_now = tk_clock_read(&tk->tkr_mono);
797         delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
798         tk->tkr_mono.cycle_last = cycle_now;
799         tk->tkr_raw.cycle_last  = cycle_now;
800 
801         while (delta > 0) {
802                 u64 max = tk->tkr_mono.clock->max_cycles;
803                 u64 incr = delta < max ? delta : max;
804 
805                 tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult;
806                 tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult;
807                 tk_normalize_xtime(tk);
808                 delta -= incr;
809         }
810 }
811 
812 /**
813  * ktime_get_real_ts64 - Returns the time of day in a timespec64.
814  * @ts:         pointer to the timespec to be set
815  *
816  * Returns the time of day in a timespec64 (WARN if suspended).
817  */
818 void ktime_get_real_ts64(struct timespec64 *ts)
819 {
820         struct timekeeper *tk = &tk_core.timekeeper;
821         unsigned int seq;
822         u64 nsecs;
823 
824         WARN_ON(timekeeping_suspended);
825 
826         do {
827                 seq = read_seqcount_begin(&tk_core.seq);
828 
829                 ts->tv_sec = tk->xtime_sec;
830                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
831 
832         } while (read_seqcount_retry(&tk_core.seq, seq));
833 
834         ts->tv_nsec = 0;
835         timespec64_add_ns(ts, nsecs);
836 }
837 EXPORT_SYMBOL(ktime_get_real_ts64);
838 
839 ktime_t ktime_get(void)
840 {
841         struct timekeeper *tk = &tk_core.timekeeper;
842         unsigned int seq;
843         ktime_t base;
844         u64 nsecs;
845 
846         WARN_ON(timekeeping_suspended);
847 
848         do {
849                 seq = read_seqcount_begin(&tk_core.seq);
850                 base = tk->tkr_mono.base;
851                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
852 
853         } while (read_seqcount_retry(&tk_core.seq, seq));
854 
855         return ktime_add_ns(base, nsecs);
856 }
857 EXPORT_SYMBOL_GPL(ktime_get);
858 
859 u32 ktime_get_resolution_ns(void)
860 {
861         struct timekeeper *tk = &tk_core.timekeeper;
862         unsigned int seq;
863         u32 nsecs;
864 
865         WARN_ON(timekeeping_suspended);
866 
867         do {
868                 seq = read_seqcount_begin(&tk_core.seq);
869                 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
870         } while (read_seqcount_retry(&tk_core.seq, seq));
871 
872         return nsecs;
873 }
874 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
875 
876 static ktime_t *offsets[TK_OFFS_MAX] = {
877         [TK_OFFS_REAL]  = &tk_core.timekeeper.offs_real,
878         [TK_OFFS_BOOT]  = &tk_core.timekeeper.offs_boot,
879         [TK_OFFS_TAI]   = &tk_core.timekeeper.offs_tai,
880 };
881 
882 ktime_t ktime_get_with_offset(enum tk_offsets offs)
883 {
884         struct timekeeper *tk = &tk_core.timekeeper;
885         unsigned int seq;
886         ktime_t base, *offset = offsets[offs];
887         u64 nsecs;
888 
889         WARN_ON(timekeeping_suspended);
890 
891         do {
892                 seq = read_seqcount_begin(&tk_core.seq);
893                 base = ktime_add(tk->tkr_mono.base, *offset);
894                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
895 
896         } while (read_seqcount_retry(&tk_core.seq, seq));
897 
898         return ktime_add_ns(base, nsecs);
899 
900 }
901 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
902 
903 ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
904 {
905         struct timekeeper *tk = &tk_core.timekeeper;
906         unsigned int seq;
907         ktime_t base, *offset = offsets[offs];
908         u64 nsecs;
909 
910         WARN_ON(timekeeping_suspended);
911 
912         do {
913                 seq = read_seqcount_begin(&tk_core.seq);
914                 base = ktime_add(tk->tkr_mono.base, *offset);
915                 nsecs = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
916 
917         } while (read_seqcount_retry(&tk_core.seq, seq));
918 
919         return ktime_add_ns(base, nsecs);
920 }
921 EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
922 
923 /**
924  * ktime_mono_to_any() - convert monotonic time to any other time
925  * @tmono:      time to convert.
926  * @offs:       which offset to use
927  */
928 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
929 {
930         ktime_t *offset = offsets[offs];
931         unsigned int seq;
932         ktime_t tconv;
933 
934         do {
935                 seq = read_seqcount_begin(&tk_core.seq);
936                 tconv = ktime_add(tmono, *offset);
937         } while (read_seqcount_retry(&tk_core.seq, seq));
938 
939         return tconv;
940 }
941 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
942 
943 /**
944  * ktime_get_raw - Returns the raw monotonic time in ktime_t format
945  */
946 ktime_t ktime_get_raw(void)
947 {
948         struct timekeeper *tk = &tk_core.timekeeper;
949         unsigned int seq;
950         ktime_t base;
951         u64 nsecs;
952 
953         do {
954                 seq = read_seqcount_begin(&tk_core.seq);
955                 base = tk->tkr_raw.base;
956                 nsecs = timekeeping_get_ns(&tk->tkr_raw);
957 
958         } while (read_seqcount_retry(&tk_core.seq, seq));
959 
960         return ktime_add_ns(base, nsecs);
961 }
962 EXPORT_SYMBOL_GPL(ktime_get_raw);
963 
964 /**
965  * ktime_get_ts64 - get the monotonic clock in timespec64 format
966  * @ts:         pointer to timespec variable
967  *
968  * The function calculates the monotonic clock from the realtime
969  * clock and the wall_to_monotonic offset and stores the result
970  * in normalized timespec64 format in the variable pointed to by @ts.
971  */
972 void ktime_get_ts64(struct timespec64 *ts)
973 {
974         struct timekeeper *tk = &tk_core.timekeeper;
975         struct timespec64 tomono;
976         unsigned int seq;
977         u64 nsec;
978 
979         WARN_ON(timekeeping_suspended);
980 
981         do {
982                 seq = read_seqcount_begin(&tk_core.seq);
983                 ts->tv_sec = tk->xtime_sec;
984                 nsec = timekeeping_get_ns(&tk->tkr_mono);
985                 tomono = tk->wall_to_monotonic;
986 
987         } while (read_seqcount_retry(&tk_core.seq, seq));
988 
989         ts->tv_sec += tomono.tv_sec;
990         ts->tv_nsec = 0;
991         timespec64_add_ns(ts, nsec + tomono.tv_nsec);
992 }
993 EXPORT_SYMBOL_GPL(ktime_get_ts64);
994 
995 /**
996  * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
997  *
998  * Returns the seconds portion of CLOCK_MONOTONIC with a single non
999  * serialized read. tk->ktime_sec is of type 'unsigned long' so this
1000  * works on both 32 and 64 bit systems. On 32 bit systems the readout
1001  * covers ~136 years of uptime which should be enough to prevent
1002  * premature wrap arounds.
1003  */
1004 time64_t ktime_get_seconds(void)
1005 {
1006         struct timekeeper *tk = &tk_core.timekeeper;
1007 
1008         WARN_ON(timekeeping_suspended);
1009         return tk->ktime_sec;
1010 }
1011 EXPORT_SYMBOL_GPL(ktime_get_seconds);
1012 
1013 /**
1014  * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
1015  *
1016  * Returns the wall clock seconds since 1970.
1017  *
1018  * For 64bit systems the fast access to tk->xtime_sec is preserved. On
1019  * 32bit systems the access must be protected with the sequence
1020  * counter to provide "atomic" access to the 64bit tk->xtime_sec
1021  * value.
1022  */
1023 time64_t ktime_get_real_seconds(void)
1024 {
1025         struct timekeeper *tk = &tk_core.timekeeper;
1026         time64_t seconds;
1027         unsigned int seq;
1028 
1029         if (IS_ENABLED(CONFIG_64BIT))
1030                 return tk->xtime_sec;
1031 
1032         do {
1033                 seq = read_seqcount_begin(&tk_core.seq);
1034                 seconds = tk->xtime_sec;
1035 
1036         } while (read_seqcount_retry(&tk_core.seq, seq));
1037 
1038         return seconds;
1039 }
1040 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
1041 
1042 /**
1043  * __ktime_get_real_seconds - The same as ktime_get_real_seconds
1044  * but without the sequence counter protect. This internal function
1045  * is called just when timekeeping lock is already held.
1046  */
1047 noinstr time64_t __ktime_get_real_seconds(void)
1048 {
1049         struct timekeeper *tk = &tk_core.timekeeper;
1050 
1051         return tk->xtime_sec;
1052 }
1053 
1054 /**
1055  * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
1056  * @systime_snapshot:   pointer to struct receiving the system time snapshot
1057  */
1058 void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
1059 {
1060         struct timekeeper *tk = &tk_core.timekeeper;
1061         unsigned int seq;
1062         ktime_t base_raw;
1063         ktime_t base_real;
1064         u64 nsec_raw;
1065         u64 nsec_real;
1066         u64 now;
1067 
1068         WARN_ON_ONCE(timekeeping_suspended);
1069 
1070         do {
1071                 seq = read_seqcount_begin(&tk_core.seq);
1072                 now = tk_clock_read(&tk->tkr_mono);
1073                 systime_snapshot->cs_id = tk->tkr_mono.clock->id;
1074                 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
1075                 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
1076                 base_real = ktime_add(tk->tkr_mono.base,
1077                                       tk_core.timekeeper.offs_real);
1078                 base_raw = tk->tkr_raw.base;
1079                 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
1080                 nsec_raw  = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
1081         } while (read_seqcount_retry(&tk_core.seq, seq));
1082 
1083         systime_snapshot->cycles = now;
1084         systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
1085         systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
1086 }
1087 EXPORT_SYMBOL_GPL(ktime_get_snapshot);
1088 
1089 /* Scale base by mult/div checking for overflow */
1090 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
1091 {
1092         u64 tmp, rem;
1093 
1094         tmp = div64_u64_rem(*base, div, &rem);
1095 
1096         if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
1097             ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
1098                 return -EOVERFLOW;
1099         tmp *= mult;
1100 
1101         rem = div64_u64(rem * mult, div);
1102         *base = tmp + rem;
1103         return 0;
1104 }
1105 
1106 /**
1107  * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1108  * @history:                    Snapshot representing start of history
1109  * @partial_history_cycles:     Cycle offset into history (fractional part)
1110  * @total_history_cycles:       Total history length in cycles
1111  * @discontinuity:              True indicates clock was set on history period
1112  * @ts:                         Cross timestamp that should be adjusted using
1113  *      partial/total ratio
1114  *
1115  * Helper function used by get_device_system_crosststamp() to correct the
1116  * crosstimestamp corresponding to the start of the current interval to the
1117  * system counter value (timestamp point) provided by the driver. The
1118  * total_history_* quantities are the total history starting at the provided
1119  * reference point and ending at the start of the current interval. The cycle
1120  * count between the driver timestamp point and the start of the current
1121  * interval is partial_history_cycles.
1122  */
1123 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1124                                          u64 partial_history_cycles,
1125                                          u64 total_history_cycles,
1126                                          bool discontinuity,
1127                                          struct system_device_crosststamp *ts)
1128 {
1129         struct timekeeper *tk = &tk_core.timekeeper;
1130         u64 corr_raw, corr_real;
1131         bool interp_forward;
1132         int ret;
1133 
1134         if (total_history_cycles == 0 || partial_history_cycles == 0)
1135                 return 0;
1136 
1137         /* Interpolate shortest distance from beginning or end of history */
1138         interp_forward = partial_history_cycles > total_history_cycles / 2;
1139         partial_history_cycles = interp_forward ?
1140                 total_history_cycles - partial_history_cycles :
1141                 partial_history_cycles;
1142 
1143         /*
1144          * Scale the monotonic raw time delta by:
1145          *      partial_history_cycles / total_history_cycles
1146          */
1147         corr_raw = (u64)ktime_to_ns(
1148                 ktime_sub(ts->sys_monoraw, history->raw));
1149         ret = scale64_check_overflow(partial_history_cycles,
1150                                      total_history_cycles, &corr_raw);
1151         if (ret)
1152                 return ret;
1153 
1154         /*
1155          * If there is a discontinuity in the history, scale monotonic raw
1156          *      correction by:
1157          *      mult(real)/mult(raw) yielding the realtime correction
1158          * Otherwise, calculate the realtime correction similar to monotonic
1159          *      raw calculation
1160          */
1161         if (discontinuity) {
1162                 corr_real = mul_u64_u32_div
1163                         (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1164         } else {
1165                 corr_real = (u64)ktime_to_ns(
1166                         ktime_sub(ts->sys_realtime, history->real));
1167                 ret = scale64_check_overflow(partial_history_cycles,
1168                                              total_history_cycles, &corr_real);
1169                 if (ret)
1170                         return ret;
1171         }
1172 
1173         /* Fixup monotonic raw and real time time values */
1174         if (interp_forward) {
1175                 ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1176                 ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1177         } else {
1178                 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1179                 ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1180         }
1181 
1182         return 0;
1183 }
1184 
1185 /*
1186  * timestamp_in_interval - true if ts is chronologically in [start, end]
1187  *
1188  * True if ts occurs chronologically at or after start, and before or at end.
1189  */
1190 static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
1191 {
1192         if (ts >= start && ts <= end)
1193                 return true;
1194         if (start > end && (ts >= start || ts <= end))
1195                 return true;
1196         return false;
1197 }
1198 
1199 static bool convert_clock(u64 *val, u32 numerator, u32 denominator)
1200 {
1201         u64 rem, res;
1202 
1203         if (!numerator || !denominator)
1204                 return false;
1205 
1206         res = div64_u64_rem(*val, denominator, &rem) * numerator;
1207         *val = res + div_u64(rem * numerator, denominator);
1208         return true;
1209 }
1210 
1211 static bool convert_base_to_cs(struct system_counterval_t *scv)
1212 {
1213         struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1214         struct clocksource_base *base;
1215         u32 num, den;
1216 
1217         /* The timestamp was taken from the time keeper clock source */
1218         if (cs->id == scv->cs_id)
1219                 return true;
1220 
1221         /*
1222          * Check whether cs_id matches the base clock. Prevent the compiler from
1223          * re-evaluating @base as the clocksource might change concurrently.
1224          */
1225         base = READ_ONCE(cs->base);
1226         if (!base || base->id != scv->cs_id)
1227                 return false;
1228 
1229         num = scv->use_nsecs ? cs->freq_khz : base->numerator;
1230         den = scv->use_nsecs ? USEC_PER_SEC : base->denominator;
1231 
1232         if (!convert_clock(&scv->cycles, num, den))
1233                 return false;
1234 
1235         scv->cycles += base->offset;
1236         return true;
1237 }
1238 
1239 static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id)
1240 {
1241         struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1242         struct clocksource_base *base;
1243 
1244         /*
1245          * Check whether base_id matches the base clock. Prevent the compiler from
1246          * re-evaluating @base as the clocksource might change concurrently.
1247          */
1248         base = READ_ONCE(cs->base);
1249         if (!base || base->id != base_id)
1250                 return false;
1251 
1252         *cycles -= base->offset;
1253         if (!convert_clock(cycles, base->denominator, base->numerator))
1254                 return false;
1255         return true;
1256 }
1257 
1258 static bool convert_ns_to_cs(u64 *delta)
1259 {
1260         struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
1261 
1262         if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta))
1263                 return false;
1264 
1265         *delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult);
1266         return true;
1267 }
1268 
1269 /**
1270  * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp
1271  * @treal:      CLOCK_REALTIME timestamp to convert
1272  * @base_id:    base clocksource id
1273  * @cycles:     pointer to store the converted base clock timestamp
1274  *
1275  * Converts a supplied, future realtime clock value to the corresponding base clock value.
1276  *
1277  * Return:  true if the conversion is successful, false otherwise.
1278  */
1279 bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles)
1280 {
1281         struct timekeeper *tk = &tk_core.timekeeper;
1282         unsigned int seq;
1283         u64 delta;
1284 
1285         do {
1286                 seq = read_seqcount_begin(&tk_core.seq);
1287                 if ((u64)treal < tk->tkr_mono.base_real)
1288                         return false;
1289                 delta = (u64)treal - tk->tkr_mono.base_real;
1290                 if (!convert_ns_to_cs(&delta))
1291                         return false;
1292                 *cycles = tk->tkr_mono.cycle_last + delta;
1293                 if (!convert_cs_to_base(cycles, base_id))
1294                         return false;
1295         } while (read_seqcount_retry(&tk_core.seq, seq));
1296 
1297         return true;
1298 }
1299 EXPORT_SYMBOL_GPL(ktime_real_to_base_clock);
1300 
1301 /**
1302  * get_device_system_crosststamp - Synchronously capture system/device timestamp
1303  * @get_time_fn:        Callback to get simultaneous device time and
1304  *      system counter from the device driver
1305  * @ctx:                Context passed to get_time_fn()
1306  * @history_begin:      Historical reference point used to interpolate system
1307  *      time when counter provided by the driver is before the current interval
1308  * @xtstamp:            Receives simultaneously captured system and device time
1309  *
1310  * Reads a timestamp from a device and correlates it to system time
1311  */
1312 int get_device_system_crosststamp(int (*get_time_fn)
1313                                   (ktime_t *device_time,
1314                                    struct system_counterval_t *sys_counterval,
1315                                    void *ctx),
1316                                   void *ctx,
1317                                   struct system_time_snapshot *history_begin,
1318                                   struct system_device_crosststamp *xtstamp)
1319 {
1320         struct system_counterval_t system_counterval;
1321         struct timekeeper *tk = &tk_core.timekeeper;
1322         u64 cycles, now, interval_start;
1323         unsigned int clock_was_set_seq = 0;
1324         ktime_t base_real, base_raw;
1325         u64 nsec_real, nsec_raw;
1326         u8 cs_was_changed_seq;
1327         unsigned int seq;
1328         bool do_interp;
1329         int ret;
1330 
1331         do {
1332                 seq = read_seqcount_begin(&tk_core.seq);
1333                 /*
1334                  * Try to synchronously capture device time and a system
1335                  * counter value calling back into the device driver
1336                  */
1337                 ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1338                 if (ret)
1339                         return ret;
1340 
1341                 /*
1342                  * Verify that the clocksource ID associated with the captured
1343                  * system counter value is the same as for the currently
1344                  * installed timekeeper clocksource
1345                  */
1346                 if (system_counterval.cs_id == CSID_GENERIC ||
1347                     !convert_base_to_cs(&system_counterval))
1348                         return -ENODEV;
1349                 cycles = system_counterval.cycles;
1350 
1351                 /*
1352                  * Check whether the system counter value provided by the
1353                  * device driver is on the current timekeeping interval.
1354                  */
1355                 now = tk_clock_read(&tk->tkr_mono);
1356                 interval_start = tk->tkr_mono.cycle_last;
1357                 if (!timestamp_in_interval(interval_start, now, cycles)) {
1358                         clock_was_set_seq = tk->clock_was_set_seq;
1359                         cs_was_changed_seq = tk->cs_was_changed_seq;
1360                         cycles = interval_start;
1361                         do_interp = true;
1362                 } else {
1363                         do_interp = false;
1364                 }
1365 
1366                 base_real = ktime_add(tk->tkr_mono.base,
1367                                       tk_core.timekeeper.offs_real);
1368                 base_raw = tk->tkr_raw.base;
1369 
1370                 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
1371                 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
1372         } while (read_seqcount_retry(&tk_core.seq, seq));
1373 
1374         xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1375         xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1376 
1377         /*
1378          * Interpolate if necessary, adjusting back from the start of the
1379          * current interval
1380          */
1381         if (do_interp) {
1382                 u64 partial_history_cycles, total_history_cycles;
1383                 bool discontinuity;
1384 
1385                 /*
1386                  * Check that the counter value is not before the provided
1387                  * history reference and that the history doesn't cross a
1388                  * clocksource change
1389                  */
1390                 if (!history_begin ||
1391                     !timestamp_in_interval(history_begin->cycles,
1392                                            cycles, system_counterval.cycles) ||
1393                     history_begin->cs_was_changed_seq != cs_was_changed_seq)
1394                         return -EINVAL;
1395                 partial_history_cycles = cycles - system_counterval.cycles;
1396                 total_history_cycles = cycles - history_begin->cycles;
1397                 discontinuity =
1398                         history_begin->clock_was_set_seq != clock_was_set_seq;
1399 
1400                 ret = adjust_historical_crosststamp(history_begin,
1401                                                     partial_history_cycles,
1402                                                     total_history_cycles,
1403                                                     discontinuity, xtstamp);
1404                 if (ret)
1405                         return ret;
1406         }
1407 
1408         return 0;
1409 }
1410 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1411 
1412 /**
1413  * timekeeping_clocksource_has_base - Check whether the current clocksource
1414  *                                    is based on given a base clock
1415  * @id:         base clocksource ID
1416  *
1417  * Note:        The return value is a snapshot which can become invalid right
1418  *              after the function returns.
1419  *
1420  * Return:      true if the timekeeper clocksource has a base clock with @id,
1421  *              false otherwise
1422  */
1423 bool timekeeping_clocksource_has_base(enum clocksource_ids id)
1424 {
1425         /*
1426          * This is a snapshot, so no point in using the sequence
1427          * count. Just prevent the compiler from re-evaluating @base as the
1428          * clocksource might change concurrently.
1429          */
1430         struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base);
1431 
1432         return base ? base->id == id : false;
1433 }
1434 EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base);
1435 
1436 /**
1437  * do_settimeofday64 - Sets the time of day.
1438  * @ts:     pointer to the timespec64 variable containing the new time
1439  *
1440  * Sets the time of day to the new time and update NTP and notify hrtimers
1441  */
1442 int do_settimeofday64(const struct timespec64 *ts)
1443 {
1444         struct timekeeper *tk = &tk_core.timekeeper;
1445         struct timespec64 ts_delta, xt;
1446         unsigned long flags;
1447         int ret = 0;
1448 
1449         if (!timespec64_valid_settod(ts))
1450                 return -EINVAL;
1451 
1452         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1453         write_seqcount_begin(&tk_core.seq);
1454 
1455         timekeeping_forward_now(tk);
1456 
1457         xt = tk_xtime(tk);
1458         ts_delta = timespec64_sub(*ts, xt);
1459 
1460         if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
1461                 ret = -EINVAL;
1462                 goto out;
1463         }
1464 
1465         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
1466 
1467         tk_set_xtime(tk, ts);
1468 out:
1469         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1470 
1471         write_seqcount_end(&tk_core.seq);
1472         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1473 
1474         /* Signal hrtimers about time change */
1475         clock_was_set(CLOCK_SET_WALL);
1476 
1477         if (!ret) {
1478                 audit_tk_injoffset(ts_delta);
1479                 add_device_randomness(ts, sizeof(*ts));
1480         }
1481 
1482         return ret;
1483 }
1484 EXPORT_SYMBOL(do_settimeofday64);
1485 
1486 /**
1487  * timekeeping_inject_offset - Adds or subtracts from the current time.
1488  * @ts:         Pointer to the timespec variable containing the offset
1489  *
1490  * Adds or subtracts an offset value from the current time.
1491  */
1492 static int timekeeping_inject_offset(const struct timespec64 *ts)
1493 {
1494         struct timekeeper *tk = &tk_core.timekeeper;
1495         unsigned long flags;
1496         struct timespec64 tmp;
1497         int ret = 0;
1498 
1499         if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1500                 return -EINVAL;
1501 
1502         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1503         write_seqcount_begin(&tk_core.seq);
1504 
1505         timekeeping_forward_now(tk);
1506 
1507         /* Make sure the proposed value is valid */
1508         tmp = timespec64_add(tk_xtime(tk), *ts);
1509         if (timespec64_compare(&tk->wall_to_monotonic, ts) > 0 ||
1510             !timespec64_valid_settod(&tmp)) {
1511                 ret = -EINVAL;
1512                 goto error;
1513         }
1514 
1515         tk_xtime_add(tk, ts);
1516         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *ts));
1517 
1518 error: /* even if we error out, we forwarded the time, so call update */
1519         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1520 
1521         write_seqcount_end(&tk_core.seq);
1522         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1523 
1524         /* Signal hrtimers about time change */
1525         clock_was_set(CLOCK_SET_WALL);
1526 
1527         return ret;
1528 }
1529 
1530 /*
1531  * Indicates if there is an offset between the system clock and the hardware
1532  * clock/persistent clock/rtc.
1533  */
1534 int persistent_clock_is_local;
1535 
1536 /*
1537  * Adjust the time obtained from the CMOS to be UTC time instead of
1538  * local time.
1539  *
1540  * This is ugly, but preferable to the alternatives.  Otherwise we
1541  * would either need to write a program to do it in /etc/rc (and risk
1542  * confusion if the program gets run more than once; it would also be
1543  * hard to make the program warp the clock precisely n hours)  or
1544  * compile in the timezone information into the kernel.  Bad, bad....
1545  *
1546  *                                              - TYT, 1992-01-01
1547  *
1548  * The best thing to do is to keep the CMOS clock in universal time (UTC)
1549  * as real UNIX machines always do it. This avoids all headaches about
1550  * daylight saving times and warping kernel clocks.
1551  */
1552 void timekeeping_warp_clock(void)
1553 {
1554         if (sys_tz.tz_minuteswest != 0) {
1555                 struct timespec64 adjust;
1556 
1557                 persistent_clock_is_local = 1;
1558                 adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1559                 adjust.tv_nsec = 0;
1560                 timekeeping_inject_offset(&adjust);
1561         }
1562 }
1563 
1564 /*
1565  * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1566  */
1567 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1568 {
1569         tk->tai_offset = tai_offset;
1570         tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1571 }
1572 
1573 /*
1574  * change_clocksource - Swaps clocksources if a new one is available
1575  *
1576  * Accumulates current time interval and initializes new clocksource
1577  */
1578 static int change_clocksource(void *data)
1579 {
1580         struct timekeeper *tk = &tk_core.timekeeper;
1581         struct clocksource *new, *old = NULL;
1582         unsigned long flags;
1583         bool change = false;
1584 
1585         new = (struct clocksource *) data;
1586 
1587         /*
1588          * If the cs is in module, get a module reference. Succeeds
1589          * for built-in code (owner == NULL) as well.
1590          */
1591         if (try_module_get(new->owner)) {
1592                 if (!new->enable || new->enable(new) == 0)
1593                         change = true;
1594                 else
1595                         module_put(new->owner);
1596         }
1597 
1598         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1599         write_seqcount_begin(&tk_core.seq);
1600 
1601         timekeeping_forward_now(tk);
1602 
1603         if (change) {
1604                 old = tk->tkr_mono.clock;
1605                 tk_setup_internals(tk, new);
1606         }
1607 
1608         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1609 
1610         write_seqcount_end(&tk_core.seq);
1611         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1612 
1613         if (old) {
1614                 if (old->disable)
1615                         old->disable(old);
1616 
1617                 module_put(old->owner);
1618         }
1619 
1620         return 0;
1621 }
1622 
1623 /**
1624  * timekeeping_notify - Install a new clock source
1625  * @clock:              pointer to the clock source
1626  *
1627  * This function is called from clocksource.c after a new, better clock
1628  * source has been registered. The caller holds the clocksource_mutex.
1629  */
1630 int timekeeping_notify(struct clocksource *clock)
1631 {
1632         struct timekeeper *tk = &tk_core.timekeeper;
1633 
1634         if (tk->tkr_mono.clock == clock)
1635                 return 0;
1636         stop_machine(change_clocksource, clock, NULL);
1637         tick_clock_notify();
1638         return tk->tkr_mono.clock == clock ? 0 : -1;
1639 }
1640 
1641 /**
1642  * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
1643  * @ts:         pointer to the timespec64 to be set
1644  *
1645  * Returns the raw monotonic time (completely un-modified by ntp)
1646  */
1647 void ktime_get_raw_ts64(struct timespec64 *ts)
1648 {
1649         struct timekeeper *tk = &tk_core.timekeeper;
1650         unsigned int seq;
1651         u64 nsecs;
1652 
1653         do {
1654                 seq = read_seqcount_begin(&tk_core.seq);
1655                 ts->tv_sec = tk->raw_sec;
1656                 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1657 
1658         } while (read_seqcount_retry(&tk_core.seq, seq));
1659 
1660         ts->tv_nsec = 0;
1661         timespec64_add_ns(ts, nsecs);
1662 }
1663 EXPORT_SYMBOL(ktime_get_raw_ts64);
1664 
1665 
1666 /**
1667  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1668  */
1669 int timekeeping_valid_for_hres(void)
1670 {
1671         struct timekeeper *tk = &tk_core.timekeeper;
1672         unsigned int seq;
1673         int ret;
1674 
1675         do {
1676                 seq = read_seqcount_begin(&tk_core.seq);
1677 
1678                 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1679 
1680         } while (read_seqcount_retry(&tk_core.seq, seq));
1681 
1682         return ret;
1683 }
1684 
1685 /**
1686  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1687  */
1688 u64 timekeeping_max_deferment(void)
1689 {
1690         struct timekeeper *tk = &tk_core.timekeeper;
1691         unsigned int seq;
1692         u64 ret;
1693 
1694         do {
1695                 seq = read_seqcount_begin(&tk_core.seq);
1696 
1697                 ret = tk->tkr_mono.clock->max_idle_ns;
1698 
1699         } while (read_seqcount_retry(&tk_core.seq, seq));
1700 
1701         return ret;
1702 }
1703 
1704 /**
1705  * read_persistent_clock64 -  Return time from the persistent clock.
1706  * @ts: Pointer to the storage for the readout value
1707  *
1708  * Weak dummy function for arches that do not yet support it.
1709  * Reads the time from the battery backed persistent clock.
1710  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1711  *
1712  *  XXX - Do be sure to remove it once all arches implement it.
1713  */
1714 void __weak read_persistent_clock64(struct timespec64 *ts)
1715 {
1716         ts->tv_sec = 0;
1717         ts->tv_nsec = 0;
1718 }
1719 
1720 /**
1721  * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
1722  *                                        from the boot.
1723  * @wall_time:    current time as returned by persistent clock
1724  * @boot_offset:  offset that is defined as wall_time - boot_time
1725  *
1726  * Weak dummy function for arches that do not yet support it.
1727  *
1728  * The default function calculates offset based on the current value of
1729  * local_clock(). This way architectures that support sched_clock() but don't
1730  * support dedicated boot time clock will provide the best estimate of the
1731  * boot time.
1732  */
1733 void __weak __init
1734 read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
1735                                      struct timespec64 *boot_offset)
1736 {
1737         read_persistent_clock64(wall_time);
1738         *boot_offset = ns_to_timespec64(local_clock());
1739 }
1740 
1741 /*
1742  * Flag reflecting whether timekeeping_resume() has injected sleeptime.
1743  *
1744  * The flag starts of false and is only set when a suspend reaches
1745  * timekeeping_suspend(), timekeeping_resume() sets it to false when the
1746  * timekeeper clocksource is not stopping across suspend and has been
1747  * used to update sleep time. If the timekeeper clocksource has stopped
1748  * then the flag stays true and is used by the RTC resume code to decide
1749  * whether sleeptime must be injected and if so the flag gets false then.
1750  *
1751  * If a suspend fails before reaching timekeeping_resume() then the flag
1752  * stays false and prevents erroneous sleeptime injection.
1753  */
1754 static bool suspend_timing_needed;
1755 
1756 /* Flag for if there is a persistent clock on this platform */
1757 static bool persistent_clock_exists;
1758 
1759 /*
1760  * timekeeping_init - Initializes the clocksource and common timekeeping values
1761  */
1762 void __init timekeeping_init(void)
1763 {
1764         struct timespec64 wall_time, boot_offset, wall_to_mono;
1765         struct timekeeper *tk = &tk_core.timekeeper;
1766         struct clocksource *clock;
1767         unsigned long flags;
1768 
1769         read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
1770         if (timespec64_valid_settod(&wall_time) &&
1771             timespec64_to_ns(&wall_time) > 0) {
1772                 persistent_clock_exists = true;
1773         } else if (timespec64_to_ns(&wall_time) != 0) {
1774                 pr_warn("Persistent clock returned invalid value");
1775                 wall_time = (struct timespec64){0};
1776         }
1777 
1778         if (timespec64_compare(&wall_time, &boot_offset) < 0)
1779                 boot_offset = (struct timespec64){0};
1780 
1781         /*
1782          * We want set wall_to_mono, so the following is true:
1783          * wall time + wall_to_mono = boot time
1784          */
1785         wall_to_mono = timespec64_sub(boot_offset, wall_time);
1786 
1787         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1788         write_seqcount_begin(&tk_core.seq);
1789         ntp_init();
1790 
1791         clock = clocksource_default_clock();
1792         if (clock->enable)
1793                 clock->enable(clock);
1794         tk_setup_internals(tk, clock);
1795 
1796         tk_set_xtime(tk, &wall_time);
1797         tk->raw_sec = 0;
1798 
1799         tk_set_wall_to_mono(tk, wall_to_mono);
1800 
1801         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1802 
1803         write_seqcount_end(&tk_core.seq);
1804         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1805 }
1806 
1807 /* time in seconds when suspend began for persistent clock */
1808 static struct timespec64 timekeeping_suspend_time;
1809 
1810 /**
1811  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1812  * @tk:         Pointer to the timekeeper to be updated
1813  * @delta:      Pointer to the delta value in timespec64 format
1814  *
1815  * Takes a timespec offset measuring a suspend interval and properly
1816  * adds the sleep offset to the timekeeping variables.
1817  */
1818 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1819                                            const struct timespec64 *delta)
1820 {
1821         if (!timespec64_valid_strict(delta)) {
1822                 printk_deferred(KERN_WARNING
1823                                 "__timekeeping_inject_sleeptime: Invalid "
1824                                 "sleep delta value!\n");
1825                 return;
1826         }
1827         tk_xtime_add(tk, delta);
1828         tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1829         tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1830         tk_debug_account_sleep_time(delta);
1831 }
1832 
1833 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1834 /*
1835  * We have three kinds of time sources to use for sleep time
1836  * injection, the preference order is:
1837  * 1) non-stop clocksource
1838  * 2) persistent clock (ie: RTC accessible when irqs are off)
1839  * 3) RTC
1840  *
1841  * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1842  * If system has neither 1) nor 2), 3) will be used finally.
1843  *
1844  *
1845  * If timekeeping has injected sleeptime via either 1) or 2),
1846  * 3) becomes needless, so in this case we don't need to call
1847  * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1848  * means.
1849  */
1850 bool timekeeping_rtc_skipresume(void)
1851 {
1852         return !suspend_timing_needed;
1853 }
1854 
1855 /*
1856  * 1) can be determined whether to use or not only when doing
1857  * timekeeping_resume() which is invoked after rtc_suspend(),
1858  * so we can't skip rtc_suspend() surely if system has 1).
1859  *
1860  * But if system has 2), 2) will definitely be used, so in this
1861  * case we don't need to call rtc_suspend(), and this is what
1862  * timekeeping_rtc_skipsuspend() means.
1863  */
1864 bool timekeeping_rtc_skipsuspend(void)
1865 {
1866         return persistent_clock_exists;
1867 }
1868 
1869 /**
1870  * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1871  * @delta: pointer to a timespec64 delta value
1872  *
1873  * This hook is for architectures that cannot support read_persistent_clock64
1874  * because their RTC/persistent clock is only accessible when irqs are enabled.
1875  * and also don't have an effective nonstop clocksource.
1876  *
1877  * This function should only be called by rtc_resume(), and allows
1878  * a suspend offset to be injected into the timekeeping values.
1879  */
1880 void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
1881 {
1882         struct timekeeper *tk = &tk_core.timekeeper;
1883         unsigned long flags;
1884 
1885         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1886         write_seqcount_begin(&tk_core.seq);
1887 
1888         suspend_timing_needed = false;
1889 
1890         timekeeping_forward_now(tk);
1891 
1892         __timekeeping_inject_sleeptime(tk, delta);
1893 
1894         timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1895 
1896         write_seqcount_end(&tk_core.seq);
1897         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1898 
1899         /* Signal hrtimers about time change */
1900         clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
1901 }
1902 #endif
1903 
1904 /**
1905  * timekeeping_resume - Resumes the generic timekeeping subsystem.
1906  */
1907 void timekeeping_resume(void)
1908 {
1909         struct timekeeper *tk = &tk_core.timekeeper;
1910         struct clocksource *clock = tk->tkr_mono.clock;
1911         unsigned long flags;
1912         struct timespec64 ts_new, ts_delta;
1913         u64 cycle_now, nsec;
1914         bool inject_sleeptime = false;
1915 
1916         read_persistent_clock64(&ts_new);
1917 
1918         clockevents_resume();
1919         clocksource_resume();
1920 
1921         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1922         write_seqcount_begin(&tk_core.seq);
1923 
1924         /*
1925          * After system resumes, we need to calculate the suspended time and
1926          * compensate it for the OS time. There are 3 sources that could be
1927          * used: Nonstop clocksource during suspend, persistent clock and rtc
1928          * device.
1929          *
1930          * One specific platform may have 1 or 2 or all of them, and the
1931          * preference will be:
1932          *      suspend-nonstop clocksource -> persistent clock -> rtc
1933          * The less preferred source will only be tried if there is no better
1934          * usable source. The rtc part is handled separately in rtc core code.
1935          */
1936         cycle_now = tk_clock_read(&tk->tkr_mono);
1937         nsec = clocksource_stop_suspend_timing(clock, cycle_now);
1938         if (nsec > 0) {
1939                 ts_delta = ns_to_timespec64(nsec);
1940                 inject_sleeptime = true;
1941         } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1942                 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1943                 inject_sleeptime = true;
1944         }
1945 
1946         if (inject_sleeptime) {
1947                 suspend_timing_needed = false;
1948                 __timekeeping_inject_sleeptime(tk, &ts_delta);
1949         }
1950 
1951         /* Re-base the last cycle value */
1952         tk->tkr_mono.cycle_last = cycle_now;
1953         tk->tkr_raw.cycle_last  = cycle_now;
1954 
1955         tk->ntp_error = 0;
1956         timekeeping_suspended = 0;
1957         timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1958         write_seqcount_end(&tk_core.seq);
1959         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1960 
1961         touch_softlockup_watchdog();
1962 
1963         /* Resume the clockevent device(s) and hrtimers */
1964         tick_resume();
1965         /* Notify timerfd as resume is equivalent to clock_was_set() */
1966         timerfd_resume();
1967 }
1968 
1969 int timekeeping_suspend(void)
1970 {
1971         struct timekeeper *tk = &tk_core.timekeeper;
1972         unsigned long flags;
1973         struct timespec64               delta, delta_delta;
1974         static struct timespec64        old_delta;
1975         struct clocksource *curr_clock;
1976         u64 cycle_now;
1977 
1978         read_persistent_clock64(&timekeeping_suspend_time);
1979 
1980         /*
1981          * On some systems the persistent_clock can not be detected at
1982          * timekeeping_init by its return value, so if we see a valid
1983          * value returned, update the persistent_clock_exists flag.
1984          */
1985         if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1986                 persistent_clock_exists = true;
1987 
1988         suspend_timing_needed = true;
1989 
1990         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1991         write_seqcount_begin(&tk_core.seq);
1992         timekeeping_forward_now(tk);
1993         timekeeping_suspended = 1;
1994 
1995         /*
1996          * Since we've called forward_now, cycle_last stores the value
1997          * just read from the current clocksource. Save this to potentially
1998          * use in suspend timing.
1999          */
2000         curr_clock = tk->tkr_mono.clock;
2001         cycle_now = tk->tkr_mono.cycle_last;
2002         clocksource_start_suspend_timing(curr_clock, cycle_now);
2003 
2004         if (persistent_clock_exists) {
2005                 /*
2006                  * To avoid drift caused by repeated suspend/resumes,
2007                  * which each can add ~1 second drift error,
2008                  * try to compensate so the difference in system time
2009                  * and persistent_clock time stays close to constant.
2010                  */
2011                 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
2012                 delta_delta = timespec64_sub(delta, old_delta);
2013                 if (abs(delta_delta.tv_sec) >= 2) {
2014                         /*
2015                          * if delta_delta is too large, assume time correction
2016                          * has occurred and set old_delta to the current delta.
2017                          */
2018                         old_delta = delta;
2019                 } else {
2020                         /* Otherwise try to adjust old_system to compensate */
2021                         timekeeping_suspend_time =
2022                                 timespec64_add(timekeeping_suspend_time, delta_delta);
2023                 }
2024         }
2025 
2026         timekeeping_update(tk, TK_MIRROR);
2027         halt_fast_timekeeper(tk);
2028         write_seqcount_end(&tk_core.seq);
2029         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2030 
2031         tick_suspend();
2032         clocksource_suspend();
2033         clockevents_suspend();
2034 
2035         return 0;
2036 }
2037 
2038 /* sysfs resume/suspend bits for timekeeping */
2039 static struct syscore_ops timekeeping_syscore_ops = {
2040         .resume         = timekeeping_resume,
2041         .suspend        = timekeeping_suspend,
2042 };
2043 
2044 static int __init timekeeping_init_ops(void)
2045 {
2046         register_syscore_ops(&timekeeping_syscore_ops);
2047         return 0;
2048 }
2049 device_initcall(timekeeping_init_ops);
2050 
2051 /*
2052  * Apply a multiplier adjustment to the timekeeper
2053  */
2054 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
2055                                                          s64 offset,
2056                                                          s32 mult_adj)
2057 {
2058         s64 interval = tk->cycle_interval;
2059 
2060         if (mult_adj == 0) {
2061                 return;
2062         } else if (mult_adj == -1) {
2063                 interval = -interval;
2064                 offset = -offset;
2065         } else if (mult_adj != 1) {
2066                 interval *= mult_adj;
2067                 offset *= mult_adj;
2068         }
2069 
2070         /*
2071          * So the following can be confusing.
2072          *
2073          * To keep things simple, lets assume mult_adj == 1 for now.
2074          *
2075          * When mult_adj != 1, remember that the interval and offset values
2076          * have been appropriately scaled so the math is the same.
2077          *
2078          * The basic idea here is that we're increasing the multiplier
2079          * by one, this causes the xtime_interval to be incremented by
2080          * one cycle_interval. This is because:
2081          *      xtime_interval = cycle_interval * mult
2082          * So if mult is being incremented by one:
2083          *      xtime_interval = cycle_interval * (mult + 1)
2084          * Its the same as:
2085          *      xtime_interval = (cycle_interval * mult) + cycle_interval
2086          * Which can be shortened to:
2087          *      xtime_interval += cycle_interval
2088          *
2089          * So offset stores the non-accumulated cycles. Thus the current
2090          * time (in shifted nanoseconds) is:
2091          *      now = (offset * adj) + xtime_nsec
2092          * Now, even though we're adjusting the clock frequency, we have
2093          * to keep time consistent. In other words, we can't jump back
2094          * in time, and we also want to avoid jumping forward in time.
2095          *
2096          * So given the same offset value, we need the time to be the same
2097          * both before and after the freq adjustment.
2098          *      now = (offset * adj_1) + xtime_nsec_1
2099          *      now = (offset * adj_2) + xtime_nsec_2
2100          * So:
2101          *      (offset * adj_1) + xtime_nsec_1 =
2102          *              (offset * adj_2) + xtime_nsec_2
2103          * And we know:
2104          *      adj_2 = adj_1 + 1
2105          * So:
2106          *      (offset * adj_1) + xtime_nsec_1 =
2107          *              (offset * (adj_1+1)) + xtime_nsec_2
2108          *      (offset * adj_1) + xtime_nsec_1 =
2109          *              (offset * adj_1) + offset + xtime_nsec_2
2110          * Canceling the sides:
2111          *      xtime_nsec_1 = offset + xtime_nsec_2
2112          * Which gives us:
2113          *      xtime_nsec_2 = xtime_nsec_1 - offset
2114          * Which simplifies to:
2115          *      xtime_nsec -= offset
2116          */
2117         if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
2118                 /* NTP adjustment caused clocksource mult overflow */
2119                 WARN_ON_ONCE(1);
2120                 return;
2121         }
2122 
2123         tk->tkr_mono.mult += mult_adj;
2124         tk->xtime_interval += interval;
2125         tk->tkr_mono.xtime_nsec -= offset;
2126 }
2127 
2128 /*
2129  * Adjust the timekeeper's multiplier to the correct frequency
2130  * and also to reduce the accumulated error value.
2131  */
2132 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
2133 {
2134         u32 mult;
2135 
2136         /*
2137          * Determine the multiplier from the current NTP tick length.
2138          * Avoid expensive division when the tick length doesn't change.
2139          */
2140         if (likely(tk->ntp_tick == ntp_tick_length())) {
2141                 mult = tk->tkr_mono.mult - tk->ntp_err_mult;
2142         } else {
2143                 tk->ntp_tick = ntp_tick_length();
2144                 mult = div64_u64((tk->ntp_tick >> tk->ntp_error_shift) -
2145                                  tk->xtime_remainder, tk->cycle_interval);
2146         }
2147 
2148         /*
2149          * If the clock is behind the NTP time, increase the multiplier by 1
2150          * to catch up with it. If it's ahead and there was a remainder in the
2151          * tick division, the clock will slow down. Otherwise it will stay
2152          * ahead until the tick length changes to a non-divisible value.
2153          */
2154         tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
2155         mult += tk->ntp_err_mult;
2156 
2157         timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
2158 
2159         if (unlikely(tk->tkr_mono.clock->maxadj &&
2160                 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2161                         > tk->tkr_mono.clock->maxadj))) {
2162                 printk_once(KERN_WARNING
2163                         "Adjusting %s more than 11%% (%ld vs %ld)\n",
2164                         tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2165                         (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
2166         }
2167 
2168         /*
2169          * It may be possible that when we entered this function, xtime_nsec
2170          * was very small.  Further, if we're slightly speeding the clocksource
2171          * in the code above, its possible the required corrective factor to
2172          * xtime_nsec could cause it to underflow.
2173          *
2174          * Now, since we have already accumulated the second and the NTP
2175          * subsystem has been notified via second_overflow(), we need to skip
2176          * the next update.
2177          */
2178         if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
2179                 tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
2180                                                         tk->tkr_mono.shift;
2181                 tk->xtime_sec--;
2182                 tk->skip_second_overflow = 1;
2183         }
2184 }
2185 
2186 /*
2187  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2188  *
2189  * Helper function that accumulates the nsecs greater than a second
2190  * from the xtime_nsec field to the xtime_secs field.
2191  * It also calls into the NTP code to handle leapsecond processing.
2192  */
2193 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
2194 {
2195         u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2196         unsigned int clock_set = 0;
2197 
2198         while (tk->tkr_mono.xtime_nsec >= nsecps) {
2199                 int leap;
2200 
2201                 tk->tkr_mono.xtime_nsec -= nsecps;
2202                 tk->xtime_sec++;
2203 
2204                 /*
2205                  * Skip NTP update if this second was accumulated before,
2206                  * i.e. xtime_nsec underflowed in timekeeping_adjust()
2207                  */
2208                 if (unlikely(tk->skip_second_overflow)) {
2209                         tk->skip_second_overflow = 0;
2210                         continue;
2211                 }
2212 
2213                 /* Figure out if its a leap sec and apply if needed */
2214                 leap = second_overflow(tk->xtime_sec);
2215                 if (unlikely(leap)) {
2216                         struct timespec64 ts;
2217 
2218                         tk->xtime_sec += leap;
2219 
2220                         ts.tv_sec = leap;
2221                         ts.tv_nsec = 0;
2222                         tk_set_wall_to_mono(tk,
2223                                 timespec64_sub(tk->wall_to_monotonic, ts));
2224 
2225                         __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2226 
2227                         clock_set = TK_CLOCK_WAS_SET;
2228                 }
2229         }
2230         return clock_set;
2231 }
2232 
2233 /*
2234  * logarithmic_accumulation - shifted accumulation of cycles
2235  *
2236  * This functions accumulates a shifted interval of cycles into
2237  * a shifted interval nanoseconds. Allows for O(log) accumulation
2238  * loop.
2239  *
2240  * Returns the unconsumed cycles.
2241  */
2242 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2243                                     u32 shift, unsigned int *clock_set)
2244 {
2245         u64 interval = tk->cycle_interval << shift;
2246         u64 snsec_per_sec;
2247 
2248         /* If the offset is smaller than a shifted interval, do nothing */
2249         if (offset < interval)
2250                 return offset;
2251 
2252         /* Accumulate one shifted interval */
2253         offset -= interval;
2254         tk->tkr_mono.cycle_last += interval;
2255         tk->tkr_raw.cycle_last  += interval;
2256 
2257         tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2258         *clock_set |= accumulate_nsecs_to_secs(tk);
2259 
2260         /* Accumulate raw time */
2261         tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2262         snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2263         while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2264                 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2265                 tk->raw_sec++;
2266         }
2267 
2268         /* Accumulate error between NTP and clock interval */
2269         tk->ntp_error += tk->ntp_tick << shift;
2270         tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2271                                                 (tk->ntp_error_shift + shift);
2272 
2273         return offset;
2274 }
2275 
2276 /*
2277  * timekeeping_advance - Updates the timekeeper to the current time and
2278  * current NTP tick length
2279  */
2280 static bool timekeeping_advance(enum timekeeping_adv_mode mode)
2281 {
2282         struct timekeeper *real_tk = &tk_core.timekeeper;
2283         struct timekeeper *tk = &shadow_timekeeper;
2284         u64 offset;
2285         int shift = 0, maxshift;
2286         unsigned int clock_set = 0;
2287         unsigned long flags;
2288 
2289         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2290 
2291         /* Make sure we're fully resumed: */
2292         if (unlikely(timekeeping_suspended))
2293                 goto out;
2294 
2295         offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2296                                    tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
2297 
2298         /* Check if there's really nothing to do */
2299         if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
2300                 goto out;
2301 
2302         /* Do some additional sanity checking */
2303         timekeeping_check_update(tk, offset);
2304 
2305         /*
2306          * With NO_HZ we may have to accumulate many cycle_intervals
2307          * (think "ticks") worth of time at once. To do this efficiently,
2308          * we calculate the largest doubling multiple of cycle_intervals
2309          * that is smaller than the offset.  We then accumulate that
2310          * chunk in one go, and then try to consume the next smaller
2311          * doubled multiple.
2312          */
2313         shift = ilog2(offset) - ilog2(tk->cycle_interval);
2314         shift = max(0, shift);
2315         /* Bound shift to one less than what overflows tick_length */
2316         maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2317         shift = min(shift, maxshift);
2318         while (offset >= tk->cycle_interval) {
2319                 offset = logarithmic_accumulation(tk, offset, shift,
2320                                                         &clock_set);
2321                 if (offset < tk->cycle_interval<<shift)
2322                         shift--;
2323         }
2324 
2325         /* Adjust the multiplier to correct NTP error */
2326         timekeeping_adjust(tk, offset);
2327 
2328         /*
2329          * Finally, make sure that after the rounding
2330          * xtime_nsec isn't larger than NSEC_PER_SEC
2331          */
2332         clock_set |= accumulate_nsecs_to_secs(tk);
2333 
2334         write_seqcount_begin(&tk_core.seq);
2335         /*
2336          * Update the real timekeeper.
2337          *
2338          * We could avoid this memcpy by switching pointers, but that
2339          * requires changes to all other timekeeper usage sites as
2340          * well, i.e. move the timekeeper pointer getter into the
2341          * spinlocked/seqcount protected sections. And we trade this
2342          * memcpy under the tk_core.seq against one before we start
2343          * updating.
2344          */
2345         timekeeping_update(tk, clock_set);
2346         memcpy(real_tk, tk, sizeof(*tk));
2347         /* The memcpy must come last. Do not put anything here! */
2348         write_seqcount_end(&tk_core.seq);
2349 out:
2350         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2351 
2352         return !!clock_set;
2353 }
2354 
2355 /**
2356  * update_wall_time - Uses the current clocksource to increment the wall time
2357  *
2358  */
2359 void update_wall_time(void)
2360 {
2361         if (timekeeping_advance(TK_ADV_TICK))
2362                 clock_was_set_delayed();
2363 }
2364 
2365 /**
2366  * getboottime64 - Return the real time of system boot.
2367  * @ts:         pointer to the timespec64 to be set
2368  *
2369  * Returns the wall-time of boot in a timespec64.
2370  *
2371  * This is based on the wall_to_monotonic offset and the total suspend
2372  * time. Calls to settimeofday will affect the value returned (which
2373  * basically means that however wrong your real time clock is at boot time,
2374  * you get the right time here).
2375  */
2376 void getboottime64(struct timespec64 *ts)
2377 {
2378         struct timekeeper *tk = &tk_core.timekeeper;
2379         ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2380 
2381         *ts = ktime_to_timespec64(t);
2382 }
2383 EXPORT_SYMBOL_GPL(getboottime64);
2384 
2385 void ktime_get_coarse_real_ts64(struct timespec64 *ts)
2386 {
2387         struct timekeeper *tk = &tk_core.timekeeper;
2388         unsigned int seq;
2389 
2390         do {
2391                 seq = read_seqcount_begin(&tk_core.seq);
2392 
2393                 *ts = tk_xtime(tk);
2394         } while (read_seqcount_retry(&tk_core.seq, seq));
2395 }
2396 EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
2397 
2398 void ktime_get_coarse_ts64(struct timespec64 *ts)
2399 {
2400         struct timekeeper *tk = &tk_core.timekeeper;
2401         struct timespec64 now, mono;
2402         unsigned int seq;
2403 
2404         do {
2405                 seq = read_seqcount_begin(&tk_core.seq);
2406 
2407                 now = tk_xtime(tk);
2408                 mono = tk->wall_to_monotonic;
2409         } while (read_seqcount_retry(&tk_core.seq, seq));
2410 
2411         set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
2412                                 now.tv_nsec + mono.tv_nsec);
2413 }
2414 EXPORT_SYMBOL(ktime_get_coarse_ts64);
2415 
2416 /*
2417  * Must hold jiffies_lock
2418  */
2419 void do_timer(unsigned long ticks)
2420 {
2421         jiffies_64 += ticks;
2422         calc_global_load();
2423 }
2424 
2425 /**
2426  * ktime_get_update_offsets_now - hrtimer helper
2427  * @cwsseq:     pointer to check and store the clock was set sequence number
2428  * @offs_real:  pointer to storage for monotonic -> realtime offset
2429  * @offs_boot:  pointer to storage for monotonic -> boottime offset
2430  * @offs_tai:   pointer to storage for monotonic -> clock tai offset
2431  *
2432  * Returns current monotonic time and updates the offsets if the
2433  * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2434  * different.
2435  *
2436  * Called from hrtimer_interrupt() or retrigger_next_event()
2437  */
2438 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2439                                      ktime_t *offs_boot, ktime_t *offs_tai)
2440 {
2441         struct timekeeper *tk = &tk_core.timekeeper;
2442         unsigned int seq;
2443         ktime_t base;
2444         u64 nsecs;
2445 
2446         do {
2447                 seq = read_seqcount_begin(&tk_core.seq);
2448 
2449                 base = tk->tkr_mono.base;
2450                 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2451                 base = ktime_add_ns(base, nsecs);
2452 
2453                 if (*cwsseq != tk->clock_was_set_seq) {
2454                         *cwsseq = tk->clock_was_set_seq;
2455                         *offs_real = tk->offs_real;
2456                         *offs_boot = tk->offs_boot;
2457                         *offs_tai = tk->offs_tai;
2458                 }
2459 
2460                 /* Handle leapsecond insertion adjustments */
2461                 if (unlikely(base >= tk->next_leap_ktime))
2462                         *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2463 
2464         } while (read_seqcount_retry(&tk_core.seq, seq));
2465 
2466         return base;
2467 }
2468 
2469 /*
2470  * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2471  */
2472 static int timekeeping_validate_timex(const struct __kernel_timex *txc)
2473 {
2474         if (txc->modes & ADJ_ADJTIME) {
2475                 /* singleshot must not be used with any other mode bits */
2476                 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2477                         return -EINVAL;
2478                 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2479                     !capable(CAP_SYS_TIME))
2480                         return -EPERM;
2481                 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2482                     !ccs_capable(CCS_SYS_SETTIME))
2483                         return -EPERM;
2484         } else {
2485                 /* In order to modify anything, you gotta be super-user! */
2486                 if (txc->modes && !capable(CAP_SYS_TIME))
2487                         return -EPERM;
2488                 if (txc->modes && !ccs_capable(CCS_SYS_SETTIME))
2489                         return -EPERM;
2490                 /*
2491                  * if the quartz is off by more than 10% then
2492                  * something is VERY wrong!
2493                  */
2494                 if (txc->modes & ADJ_TICK &&
2495                     (txc->tick <  900000/USER_HZ ||
2496                      txc->tick > 1100000/USER_HZ))
2497                         return -EINVAL;
2498         }
2499 
2500         if (txc->modes & ADJ_SETOFFSET) {
2501                 /* In order to inject time, you gotta be super-user! */
2502                 if (!capable(CAP_SYS_TIME))
2503                         return -EPERM;
2504                 if (!ccs_capable(CCS_SYS_SETTIME))
2505                         return -EPERM;
2506 
2507                 /*
2508                  * Validate if a timespec/timeval used to inject a time
2509                  * offset is valid.  Offsets can be positive or negative, so
2510                  * we don't check tv_sec. The value of the timeval/timespec
2511                  * is the sum of its fields,but *NOTE*:
2512                  * The field tv_usec/tv_nsec must always be non-negative and
2513                  * we can't have more nanoseconds/microseconds than a second.
2514                  */
2515                 if (txc->time.tv_usec < 0)
2516                         return -EINVAL;
2517 
2518                 if (txc->modes & ADJ_NANO) {
2519                         if (txc->time.tv_usec >= NSEC_PER_SEC)
2520                                 return -EINVAL;
2521                 } else {
2522                         if (txc->time.tv_usec >= USEC_PER_SEC)
2523                                 return -EINVAL;
2524                 }
2525         }
2526 
2527         /*
2528          * Check for potential multiplication overflows that can
2529          * only happen on 64-bit systems:
2530          */
2531         if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2532                 if (LLONG_MIN / PPM_SCALE > txc->freq)
2533                         return -EINVAL;
2534                 if (LLONG_MAX / PPM_SCALE < txc->freq)
2535                         return -EINVAL;
2536         }
2537 
2538         return 0;
2539 }
2540 
2541 /**
2542  * random_get_entropy_fallback - Returns the raw clock source value,
2543  * used by random.c for platforms with no valid random_get_entropy().
2544  */
2545 unsigned long random_get_entropy_fallback(void)
2546 {
2547         struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
2548         struct clocksource *clock = READ_ONCE(tkr->clock);
2549 
2550         if (unlikely(timekeeping_suspended || !clock))
2551                 return 0;
2552         return clock->read(clock);
2553 }
2554 EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
2555 
2556 /**
2557  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2558  * @txc:        Pointer to kernel_timex structure containing NTP parameters
2559  */
2560 int do_adjtimex(struct __kernel_timex *txc)
2561 {
2562         struct timekeeper *tk = &tk_core.timekeeper;
2563         struct audit_ntp_data ad;
2564         bool clock_set = false;
2565         struct timespec64 ts;
2566         unsigned long flags;
2567         s32 orig_tai, tai;
2568         int ret;
2569 
2570         /* Validate the data before disabling interrupts */
2571         ret = timekeeping_validate_timex(txc);
2572         if (ret)
2573                 return ret;
2574         add_device_randomness(txc, sizeof(*txc));
2575 
2576         if (txc->modes & ADJ_SETOFFSET) {
2577                 struct timespec64 delta;
2578                 delta.tv_sec  = txc->time.tv_sec;
2579                 delta.tv_nsec = txc->time.tv_usec;
2580                 if (!(txc->modes & ADJ_NANO))
2581                         delta.tv_nsec *= 1000;
2582                 ret = timekeeping_inject_offset(&delta);
2583                 if (ret)
2584                         return ret;
2585 
2586                 audit_tk_injoffset(delta);
2587         }
2588 
2589         audit_ntp_init(&ad);
2590 
2591         ktime_get_real_ts64(&ts);
2592         add_device_randomness(&ts, sizeof(ts));
2593 
2594         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2595         write_seqcount_begin(&tk_core.seq);
2596 
2597         orig_tai = tai = tk->tai_offset;
2598         ret = __do_adjtimex(txc, &ts, &tai, &ad);
2599 
2600         if (tai != orig_tai) {
2601                 __timekeeping_set_tai_offset(tk, tai);
2602                 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2603                 clock_set = true;
2604         }
2605         tk_update_leap_state(tk);
2606 
2607         write_seqcount_end(&tk_core.seq);
2608         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2609 
2610         audit_ntp_log(&ad);
2611 
2612         /* Update the multiplier immediately if frequency was set directly */
2613         if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
2614                 clock_set |= timekeeping_advance(TK_ADV_FREQ);
2615 
2616         if (clock_set)
2617                 clock_was_set(CLOCK_SET_WALL);
2618 
2619         ntp_notify_cmos_timer();
2620 
2621         return ret;
2622 }
2623 
2624 #ifdef CONFIG_NTP_PPS
2625 /**
2626  * hardpps() - Accessor function to NTP __hardpps function
2627  * @phase_ts:   Pointer to timespec64 structure representing phase timestamp
2628  * @raw_ts:     Pointer to timespec64 structure representing raw timestamp
2629  */
2630 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2631 {
2632         unsigned long flags;
2633 
2634         raw_spin_lock_irqsave(&timekeeper_lock, flags);
2635         write_seqcount_begin(&tk_core.seq);
2636 
2637         __hardpps(phase_ts, raw_ts);
2638 
2639         write_seqcount_end(&tk_core.seq);
2640         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2641 }
2642 EXPORT_SYMBOL(hardpps);
2643 #endif /* CONFIG_NTP_PPS */
2644 

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php