2 * linux/kernel/time/timekeeping.c
4 * Kernel timekeeping code and accessor functions
6 * This code was moved from linux/kernel/timer.c.
7 * Please see that file for copyright and history logs.
11 #include <linux/timekeeper_internal.h>
12 #include <linux/module.h>
13 #include <linux/interrupt.h>
14 #include <linux/percpu.h>
15 #include <linux/init.h>
17 #include <linux/sched.h>
18 #include <linux/syscore_ops.h>
19 #include <linux/clocksource.h>
20 #include <linux/jiffies.h>
21 #include <linux/time.h>
22 #include <linux/tick.h>
23 #include <linux/stop_machine.h>
24 #include <linux/pvclock_gtod.h>
25 #include <linux/compiler.h>
27 #include "tick-internal.h"
28 #include "ntp_internal.h"
29 #include "timekeeping_internal.h"
31 #define TK_CLEAR_NTP (1 << 0)
32 #define TK_MIRROR (1 << 1)
33 #define TK_CLOCK_WAS_SET (1 << 2)
36 * The most important data for readout fits into a single 64 byte
41 struct timekeeper timekeeper;
42 } tk_core ____cacheline_aligned = {
43 .seq = SEQCNT_ZERO(tk_core.seq),
46 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
47 static struct timekeeper shadow_timekeeper;
50 * struct tk_fast - NMI safe timekeeper
51 * @seq: Sequence counter for protecting updates. The lowest bit
52 * is the index for the tk_read_base array
53 * @base: tk_read_base array. Access is indexed by the lowest bit of
56 * See @update_fast_timekeeper() below.
60 struct tk_read_base base[2];
63 static struct tk_fast tk_fast_mono ____cacheline_aligned;
64 static struct tk_fast tk_fast_raw ____cacheline_aligned;
66 /* flag for if timekeeping is suspended */
67 int __read_mostly timekeeping_suspended;
69 static inline void tk_normalize_xtime(struct timekeeper *tk)
71 while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
72 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
77 static inline struct timespec64 tk_xtime(struct timekeeper *tk)
81 ts.tv_sec = tk->xtime_sec;
82 ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
86 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
88 tk->xtime_sec = ts->tv_sec;
89 tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
92 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
94 tk->xtime_sec += ts->tv_sec;
95 tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
96 tk_normalize_xtime(tk);
99 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
101 struct timespec64 tmp;
104 * Verify consistency of: offset_real = -wall_to_monotonic
105 * before modifying anything
107 set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
108 -tk->wall_to_monotonic.tv_nsec);
109 WARN_ON_ONCE(tk->offs_real.tv64 != timespec64_to_ktime(tmp).tv64);
110 tk->wall_to_monotonic = wtm;
111 set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
112 tk->offs_real = timespec64_to_ktime(tmp);
113 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
116 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
118 tk->offs_boot = ktime_add(tk->offs_boot, delta);
122 * tk_clock_read - atomic clocksource read() helper
124 * This helper is necessary to use in the read paths because, while the
125 * seqlock ensures we don't return a bad value while structures are updated,
126 * it doesn't protect from potential crashes. There is the possibility that
127 * the tkr's clocksource may change between the read reference, and the
128 * clock reference passed to the read function. This can cause crashes if
129 * the wrong clocksource is passed to the wrong read function.
130 * This isn't necessary to use when holding the timekeeper_lock or doing
131 * a read of the fast-timekeeper tkrs (which is protected by its own locking
134 static inline u64 tk_clock_read(struct tk_read_base *tkr)
136 struct clocksource *clock = READ_ONCE(tkr->clock);
138 return clock->read(clock);
141 #ifdef CONFIG_DEBUG_TIMEKEEPING
142 #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
144 static void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
147 cycle_t max_cycles = tk->tkr_mono.clock->max_cycles;
148 const char *name = tk->tkr_mono.clock->name;
150 if (offset > max_cycles) {
151 printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
152 offset, name, max_cycles);
153 printk_deferred(" timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
155 if (offset > (max_cycles >> 1)) {
156 printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the the '%s' clock's 50%% safety margin (%lld)\n",
157 offset, name, max_cycles >> 1);
158 printk_deferred(" timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
162 if (tk->underflow_seen) {
163 if (jiffies - tk->last_warning > WARNING_FREQ) {
164 printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
165 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
166 printk_deferred(" Your kernel is probably still fine.\n");
167 tk->last_warning = jiffies;
169 tk->underflow_seen = 0;
172 if (tk->overflow_seen) {
173 if (jiffies - tk->last_warning > WARNING_FREQ) {
174 printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
175 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
176 printk_deferred(" Your kernel is probably still fine.\n");
177 tk->last_warning = jiffies;
179 tk->overflow_seen = 0;
183 static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
185 struct timekeeper *tk = &tk_core.timekeeper;
186 cycle_t now, last, mask, max, delta;
190 * Since we're called holding a seqlock, the data may shift
191 * under us while we're doing the calculation. This can cause
192 * false positives, since we'd note a problem but throw the
193 * results away. So nest another seqlock here to atomically
194 * grab the points we are checking with.
197 seq = read_seqcount_begin(&tk_core.seq);
198 now = tk_clock_read(tkr);
199 last = tkr->cycle_last;
201 max = tkr->clock->max_cycles;
202 } while (read_seqcount_retry(&tk_core.seq, seq));
204 delta = clocksource_delta(now, last, mask);
207 * Try to catch underflows by checking if we are seeing small
208 * mask-relative negative values.
210 if (unlikely((~delta & mask) < (mask >> 3))) {
211 tk->underflow_seen = 1;
215 /* Cap delta value to the max_cycles values to avoid mult overflows */
216 if (unlikely(delta > max)) {
217 tk->overflow_seen = 1;
218 delta = tkr->clock->max_cycles;
224 static inline void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
227 static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
229 cycle_t cycle_now, delta;
231 /* read clocksource */
232 cycle_now = tk_clock_read(tkr);
234 /* calculate the delta since the last update_wall_time */
235 delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
242 * tk_setup_internals - Set up internals to use clocksource clock.
244 * @tk: The target timekeeper to setup.
245 * @clock: Pointer to clocksource.
247 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
248 * pair and interval request.
250 * Unless you're the timekeeping code, you should not be using this!
252 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
255 u64 tmp, ntpinterval;
256 struct clocksource *old_clock;
258 old_clock = tk->tkr_mono.clock;
259 tk->tkr_mono.clock = clock;
260 tk->tkr_mono.mask = clock->mask;
261 tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
263 tk->tkr_raw.clock = clock;
264 tk->tkr_raw.mask = clock->mask;
265 tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
267 /* Do the ns -> cycle conversion first, using original mult */
268 tmp = NTP_INTERVAL_LENGTH;
269 tmp <<= clock->shift;
271 tmp += clock->mult/2;
272 do_div(tmp, clock->mult);
276 interval = (cycle_t) tmp;
277 tk->cycle_interval = interval;
279 /* Go back from cycles -> shifted ns */
280 tk->xtime_interval = (u64) interval * clock->mult;
281 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
282 tk->raw_interval = interval * clock->mult;
284 /* if changing clocks, convert xtime_nsec shift units */
286 int shift_change = clock->shift - old_clock->shift;
287 if (shift_change < 0)
288 tk->tkr_mono.xtime_nsec >>= -shift_change;
290 tk->tkr_mono.xtime_nsec <<= shift_change;
292 tk->tkr_raw.xtime_nsec = 0;
294 tk->tkr_mono.shift = clock->shift;
295 tk->tkr_raw.shift = clock->shift;
298 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
299 tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
302 * The timekeeper keeps its own mult values for the currently
303 * active clocksource. These value will be adjusted via NTP
304 * to counteract clock drifting.
306 tk->tkr_mono.mult = clock->mult;
307 tk->tkr_raw.mult = clock->mult;
308 tk->ntp_err_mult = 0;
311 /* Timekeeper helper functions. */
313 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
314 static u32 default_arch_gettimeoffset(void) { return 0; }
315 u32 (*arch_gettimeoffset)(void) = default_arch_gettimeoffset;
317 static inline u32 arch_gettimeoffset(void) { return 0; }
320 static inline u64 timekeeping_delta_to_ns(struct tk_read_base *tkr,
325 nsec = delta * tkr->mult + tkr->xtime_nsec;
328 /* If arch requires, add in get_arch_timeoffset() */
329 return nsec + arch_gettimeoffset();
332 static inline s64 timekeeping_get_ns(struct tk_read_base *tkr)
336 delta = timekeeping_get_delta(tkr);
337 return timekeeping_delta_to_ns(tkr, delta);
340 static inline s64 timekeeping_cycles_to_ns(struct tk_read_base *tkr,
345 /* calculate the delta since the last update_wall_time */
346 delta = clocksource_delta(cycles, tkr->cycle_last, tkr->mask);
347 return timekeeping_delta_to_ns(tkr, delta);
351 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
352 * @tkr: Timekeeping readout base from which we take the update
354 * We want to use this from any context including NMI and tracing /
355 * instrumenting the timekeeping code itself.
357 * Employ the latch technique; see @raw_write_seqcount_latch.
359 * So if a NMI hits the update of base[0] then it will use base[1]
360 * which is still consistent. In the worst case this can result is a
361 * slightly wrong timestamp (a few nanoseconds). See
362 * @ktime_get_mono_fast_ns.
364 static void update_fast_timekeeper(struct tk_read_base *tkr, struct tk_fast *tkf)
366 struct tk_read_base *base = tkf->base;
368 /* Force readers off to base[1] */
369 raw_write_seqcount_latch(&tkf->seq);
372 memcpy(base, tkr, sizeof(*base));
374 /* Force readers back to base[0] */
375 raw_write_seqcount_latch(&tkf->seq);
378 memcpy(base + 1, base, sizeof(*base));
382 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
384 * This timestamp is not guaranteed to be monotonic across an update.
385 * The timestamp is calculated by:
387 * now = base_mono + clock_delta * slope
389 * So if the update lowers the slope, readers who are forced to the
390 * not yet updated second array are still using the old steeper slope.
399 * |12345678---> reader order
405 * So reader 6 will observe time going backwards versus reader 5.
407 * While other CPUs are likely to be able observe that, the only way
408 * for a CPU local observation is when an NMI hits in the middle of
409 * the update. Timestamps taken from that NMI context might be ahead
410 * of the following timestamps. Callers need to be aware of that and
413 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
415 struct tk_read_base *tkr;
420 seq = raw_read_seqcount_latch(&tkf->seq);
421 tkr = tkf->base + (seq & 0x01);
422 now = ktime_to_ns(tkr->base);
424 now += timekeeping_delta_to_ns(tkr,
429 } while (read_seqcount_retry(&tkf->seq, seq));
434 u64 ktime_get_mono_fast_ns(void)
436 return __ktime_get_fast_ns(&tk_fast_mono);
438 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
440 u64 ktime_get_raw_fast_ns(void)
442 return __ktime_get_fast_ns(&tk_fast_raw);
444 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
446 /* Suspend-time cycles value for halted fast timekeeper. */
447 static cycle_t cycles_at_suspend;
449 static cycle_t dummy_clock_read(struct clocksource *cs)
451 return cycles_at_suspend;
454 static struct clocksource dummy_clock = {
455 .read = dummy_clock_read,
459 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
460 * @tk: Timekeeper to snapshot.
462 * It generally is unsafe to access the clocksource after timekeeping has been
463 * suspended, so take a snapshot of the readout base of @tk and use it as the
464 * fast timekeeper's readout base while suspended. It will return the same
465 * number of cycles every time until timekeeping is resumed at which time the
466 * proper readout base for the fast timekeeper will be restored automatically.
468 static void halt_fast_timekeeper(struct timekeeper *tk)
470 static struct tk_read_base tkr_dummy;
471 struct tk_read_base *tkr = &tk->tkr_mono;
473 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
474 cycles_at_suspend = tk_clock_read(tkr);
475 tkr_dummy.clock = &dummy_clock;
476 update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
479 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
480 tkr_dummy.clock = &dummy_clock;
481 update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
484 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
486 static inline void update_vsyscall(struct timekeeper *tk)
488 struct timespec xt, wm;
490 xt = timespec64_to_timespec(tk_xtime(tk));
491 wm = timespec64_to_timespec(tk->wall_to_monotonic);
492 update_vsyscall_old(&xt, &wm, tk->tkr_mono.clock, tk->tkr_mono.mult,
493 tk->tkr_mono.cycle_last);
496 static inline void old_vsyscall_fixup(struct timekeeper *tk)
501 * Store only full nanoseconds into xtime_nsec after rounding
502 * it up and add the remainder to the error difference.
503 * XXX - This is necessary to avoid small 1ns inconsistnecies caused
504 * by truncating the remainder in vsyscalls. However, it causes
505 * additional work to be done in timekeeping_adjust(). Once
506 * the vsyscall implementations are converted to use xtime_nsec
507 * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
508 * users are removed, this can be killed.
510 remainder = tk->tkr_mono.xtime_nsec & ((1ULL << tk->tkr_mono.shift) - 1);
511 tk->tkr_mono.xtime_nsec -= remainder;
512 tk->tkr_mono.xtime_nsec += 1ULL << tk->tkr_mono.shift;
513 tk->ntp_error += remainder << tk->ntp_error_shift;
514 tk->ntp_error -= (1ULL << tk->tkr_mono.shift) << tk->ntp_error_shift;
517 #define old_vsyscall_fixup(tk)
520 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
522 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
524 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
528 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
530 int pvclock_gtod_register_notifier(struct notifier_block *nb)
532 struct timekeeper *tk = &tk_core.timekeeper;
536 raw_spin_lock_irqsave(&timekeeper_lock, flags);
537 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
538 update_pvclock_gtod(tk, true);
539 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
543 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
546 * pvclock_gtod_unregister_notifier - unregister a pvclock
547 * timedata update listener
549 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
554 raw_spin_lock_irqsave(&timekeeper_lock, flags);
555 ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
556 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
560 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
563 * tk_update_leap_state - helper to update the next_leap_ktime
565 static inline void tk_update_leap_state(struct timekeeper *tk)
567 tk->next_leap_ktime = ntp_get_next_leap();
568 if (tk->next_leap_ktime.tv64 != KTIME_MAX)
569 /* Convert to monotonic time */
570 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
574 * Update the ktime_t based scalar nsec members of the timekeeper
576 static inline void tk_update_ktime_data(struct timekeeper *tk)
582 * The xtime based monotonic readout is:
583 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
584 * The ktime based monotonic readout is:
585 * nsec = base_mono + now();
586 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
588 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
589 nsec = (u32) tk->wall_to_monotonic.tv_nsec;
590 tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
592 /* Update the monotonic raw base */
593 tk->tkr_raw.base = timespec64_to_ktime(tk->raw_time);
596 * The sum of the nanoseconds portions of xtime and
597 * wall_to_monotonic can be greater/equal one second. Take
598 * this into account before updating tk->ktime_sec.
600 nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
601 if (nsec >= NSEC_PER_SEC)
603 tk->ktime_sec = seconds;
606 /* must hold timekeeper_lock */
607 static void timekeeping_update(struct timekeeper *tk, unsigned int action)
609 if (action & TK_CLEAR_NTP) {
614 tk_update_leap_state(tk);
615 tk_update_ktime_data(tk);
618 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
620 update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
621 update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
623 if (action & TK_CLOCK_WAS_SET)
624 tk->clock_was_set_seq++;
626 * The mirroring of the data to the shadow-timekeeper needs
627 * to happen last here to ensure we don't over-write the
628 * timekeeper structure on the next update with stale data
630 if (action & TK_MIRROR)
631 memcpy(&shadow_timekeeper, &tk_core.timekeeper,
632 sizeof(tk_core.timekeeper));
636 * timekeeping_forward_now - update clock to the current time
638 * Forward the current clock to update its state since the last call to
639 * update_wall_time(). This is useful before significant clock changes,
640 * as it avoids having to deal with this time offset explicitly.
642 static void timekeeping_forward_now(struct timekeeper *tk)
644 cycle_t cycle_now, delta;
647 cycle_now = tk_clock_read(&tk->tkr_mono);
648 delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
649 tk->tkr_mono.cycle_last = cycle_now;
650 tk->tkr_raw.cycle_last = cycle_now;
652 tk->tkr_mono.xtime_nsec += delta * tk->tkr_mono.mult;
654 /* If arch requires, add in get_arch_timeoffset() */
655 tk->tkr_mono.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_mono.shift;
657 tk_normalize_xtime(tk);
659 nsec = clocksource_cyc2ns(delta, tk->tkr_raw.mult, tk->tkr_raw.shift);
660 timespec64_add_ns(&tk->raw_time, nsec);
664 * __getnstimeofday64 - Returns the time of day in a timespec64.
665 * @ts: pointer to the timespec to be set
667 * Updates the time of day in the timespec.
668 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
670 int __getnstimeofday64(struct timespec64 *ts)
672 struct timekeeper *tk = &tk_core.timekeeper;
677 seq = read_seqcount_begin(&tk_core.seq);
679 ts->tv_sec = tk->xtime_sec;
680 nsecs = timekeeping_get_ns(&tk->tkr_mono);
682 } while (read_seqcount_retry(&tk_core.seq, seq));
685 timespec64_add_ns(ts, nsecs);
688 * Do not bail out early, in case there were callers still using
689 * the value, even in the face of the WARN_ON.
691 if (unlikely(timekeeping_suspended))
695 EXPORT_SYMBOL(__getnstimeofday64);
698 * getnstimeofday64 - Returns the time of day in a timespec64.
699 * @ts: pointer to the timespec64 to be set
701 * Returns the time of day in a timespec64 (WARN if suspended).
703 void getnstimeofday64(struct timespec64 *ts)
705 WARN_ON(__getnstimeofday64(ts));
707 EXPORT_SYMBOL(getnstimeofday64);
709 ktime_t ktime_get(void)
711 struct timekeeper *tk = &tk_core.timekeeper;
716 WARN_ON(timekeeping_suspended);
719 seq = read_seqcount_begin(&tk_core.seq);
720 base = tk->tkr_mono.base;
721 nsecs = timekeeping_get_ns(&tk->tkr_mono);
723 } while (read_seqcount_retry(&tk_core.seq, seq));
725 return ktime_add_ns(base, nsecs);
727 EXPORT_SYMBOL_GPL(ktime_get);
729 u32 ktime_get_resolution_ns(void)
731 struct timekeeper *tk = &tk_core.timekeeper;
735 WARN_ON(timekeeping_suspended);
738 seq = read_seqcount_begin(&tk_core.seq);
739 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
740 } while (read_seqcount_retry(&tk_core.seq, seq));
744 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
746 static ktime_t *offsets[TK_OFFS_MAX] = {
747 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
748 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
749 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
752 ktime_t ktime_get_with_offset(enum tk_offsets offs)
754 struct timekeeper *tk = &tk_core.timekeeper;
756 ktime_t base, *offset = offsets[offs];
759 WARN_ON(timekeeping_suspended);
762 seq = read_seqcount_begin(&tk_core.seq);
763 base = ktime_add(tk->tkr_mono.base, *offset);
764 nsecs = timekeeping_get_ns(&tk->tkr_mono);
766 } while (read_seqcount_retry(&tk_core.seq, seq));
768 return ktime_add_ns(base, nsecs);
771 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
774 * ktime_mono_to_any() - convert mononotic time to any other time
775 * @tmono: time to convert.
776 * @offs: which offset to use
778 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
780 ktime_t *offset = offsets[offs];
785 seq = read_seqcount_begin(&tk_core.seq);
786 tconv = ktime_add(tmono, *offset);
787 } while (read_seqcount_retry(&tk_core.seq, seq));
791 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
794 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
796 ktime_t ktime_get_raw(void)
798 struct timekeeper *tk = &tk_core.timekeeper;
804 seq = read_seqcount_begin(&tk_core.seq);
805 base = tk->tkr_raw.base;
806 nsecs = timekeeping_get_ns(&tk->tkr_raw);
808 } while (read_seqcount_retry(&tk_core.seq, seq));
810 return ktime_add_ns(base, nsecs);
812 EXPORT_SYMBOL_GPL(ktime_get_raw);
815 * ktime_get_ts64 - get the monotonic clock in timespec64 format
816 * @ts: pointer to timespec variable
818 * The function calculates the monotonic clock from the realtime
819 * clock and the wall_to_monotonic offset and stores the result
820 * in normalized timespec64 format in the variable pointed to by @ts.
822 void ktime_get_ts64(struct timespec64 *ts)
824 struct timekeeper *tk = &tk_core.timekeeper;
825 struct timespec64 tomono;
829 WARN_ON(timekeeping_suspended);
832 seq = read_seqcount_begin(&tk_core.seq);
833 ts->tv_sec = tk->xtime_sec;
834 nsec = timekeeping_get_ns(&tk->tkr_mono);
835 tomono = tk->wall_to_monotonic;
837 } while (read_seqcount_retry(&tk_core.seq, seq));
839 ts->tv_sec += tomono.tv_sec;
841 timespec64_add_ns(ts, nsec + tomono.tv_nsec);
843 EXPORT_SYMBOL_GPL(ktime_get_ts64);
846 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
848 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
849 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
850 * works on both 32 and 64 bit systems. On 32 bit systems the readout
851 * covers ~136 years of uptime which should be enough to prevent
852 * premature wrap arounds.
854 time64_t ktime_get_seconds(void)
856 struct timekeeper *tk = &tk_core.timekeeper;
858 WARN_ON(timekeeping_suspended);
859 return tk->ktime_sec;
861 EXPORT_SYMBOL_GPL(ktime_get_seconds);
864 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
866 * Returns the wall clock seconds since 1970. This replaces the
867 * get_seconds() interface which is not y2038 safe on 32bit systems.
869 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
870 * 32bit systems the access must be protected with the sequence
871 * counter to provide "atomic" access to the 64bit tk->xtime_sec
874 time64_t ktime_get_real_seconds(void)
876 struct timekeeper *tk = &tk_core.timekeeper;
880 if (IS_ENABLED(CONFIG_64BIT))
881 return tk->xtime_sec;
884 seq = read_seqcount_begin(&tk_core.seq);
885 seconds = tk->xtime_sec;
887 } while (read_seqcount_retry(&tk_core.seq, seq));
891 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
893 #ifdef CONFIG_NTP_PPS
896 * ktime_get_raw_and_real_ts64 - get day and raw monotonic time in timespec format
897 * @ts_raw: pointer to the timespec to be set to raw monotonic time
898 * @ts_real: pointer to the timespec to be set to the time of day
900 * This function reads both the time of day and raw monotonic time at the
901 * same time atomically and stores the resulting timestamps in timespec
904 void ktime_get_raw_and_real_ts64(struct timespec64 *ts_raw, struct timespec64 *ts_real)
906 struct timekeeper *tk = &tk_core.timekeeper;
908 s64 nsecs_raw, nsecs_real;
910 WARN_ON_ONCE(timekeeping_suspended);
913 seq = read_seqcount_begin(&tk_core.seq);
915 *ts_raw = tk->raw_time;
916 ts_real->tv_sec = tk->xtime_sec;
917 ts_real->tv_nsec = 0;
919 nsecs_raw = timekeeping_get_ns(&tk->tkr_raw);
920 nsecs_real = timekeeping_get_ns(&tk->tkr_mono);
922 } while (read_seqcount_retry(&tk_core.seq, seq));
924 timespec64_add_ns(ts_raw, nsecs_raw);
925 timespec64_add_ns(ts_real, nsecs_real);
927 EXPORT_SYMBOL(ktime_get_raw_and_real_ts64);
929 #endif /* CONFIG_NTP_PPS */
932 * do_gettimeofday - Returns the time of day in a timeval
933 * @tv: pointer to the timeval to be set
935 * NOTE: Users should be converted to using getnstimeofday()
937 void do_gettimeofday(struct timeval *tv)
939 struct timespec64 now;
941 getnstimeofday64(&now);
942 tv->tv_sec = now.tv_sec;
943 tv->tv_usec = now.tv_nsec/1000;
945 EXPORT_SYMBOL(do_gettimeofday);
948 * do_settimeofday64 - Sets the time of day.
949 * @ts: pointer to the timespec64 variable containing the new time
951 * Sets the time of day to the new time and update NTP and notify hrtimers
953 int do_settimeofday64(const struct timespec64 *ts)
955 struct timekeeper *tk = &tk_core.timekeeper;
956 struct timespec64 ts_delta, xt;
960 if (!timespec64_valid_strict(ts))
963 raw_spin_lock_irqsave(&timekeeper_lock, flags);
964 write_seqcount_begin(&tk_core.seq);
966 timekeeping_forward_now(tk);
969 ts_delta.tv_sec = ts->tv_sec - xt.tv_sec;
970 ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
972 if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
977 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
979 tk_set_xtime(tk, ts);
981 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
983 write_seqcount_end(&tk_core.seq);
984 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
986 /* signal hrtimers about time change */
991 EXPORT_SYMBOL(do_settimeofday64);
994 * timekeeping_inject_offset - Adds or subtracts from the current time.
995 * @tv: pointer to the timespec variable containing the offset
997 * Adds or subtracts an offset value from the current time.
999 int timekeeping_inject_offset(struct timespec *ts)
1001 struct timekeeper *tk = &tk_core.timekeeper;
1002 unsigned long flags;
1003 struct timespec64 ts64, tmp;
1006 if (!timespec_inject_offset_valid(ts))
1009 ts64 = timespec_to_timespec64(*ts);
1011 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1012 write_seqcount_begin(&tk_core.seq);
1014 timekeeping_forward_now(tk);
1016 /* Make sure the proposed value is valid */
1017 tmp = timespec64_add(tk_xtime(tk), ts64);
1018 if (timespec64_compare(&tk->wall_to_monotonic, &ts64) > 0 ||
1019 !timespec64_valid_strict(&tmp)) {
1024 tk_xtime_add(tk, &ts64);
1025 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
1027 error: /* even if we error out, we forwarded the time, so call update */
1028 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1030 write_seqcount_end(&tk_core.seq);
1031 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1033 /* signal hrtimers about time change */
1038 EXPORT_SYMBOL(timekeeping_inject_offset);
1042 * timekeeping_get_tai_offset - Returns current TAI offset from UTC
1045 s32 timekeeping_get_tai_offset(void)
1047 struct timekeeper *tk = &tk_core.timekeeper;
1052 seq = read_seqcount_begin(&tk_core.seq);
1053 ret = tk->tai_offset;
1054 } while (read_seqcount_retry(&tk_core.seq, seq));
1060 * __timekeeping_set_tai_offset - Lock free worker function
1063 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1065 tk->tai_offset = tai_offset;
1066 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1070 * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
1073 void timekeeping_set_tai_offset(s32 tai_offset)
1075 struct timekeeper *tk = &tk_core.timekeeper;
1076 unsigned long flags;
1078 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1079 write_seqcount_begin(&tk_core.seq);
1080 __timekeeping_set_tai_offset(tk, tai_offset);
1081 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1082 write_seqcount_end(&tk_core.seq);
1083 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1088 * change_clocksource - Swaps clocksources if a new one is available
1090 * Accumulates current time interval and initializes new clocksource
1092 static int change_clocksource(void *data)
1094 struct timekeeper *tk = &tk_core.timekeeper;
1095 struct clocksource *new, *old;
1096 unsigned long flags;
1098 new = (struct clocksource *) data;
1100 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1101 write_seqcount_begin(&tk_core.seq);
1103 timekeeping_forward_now(tk);
1105 * If the cs is in module, get a module reference. Succeeds
1106 * for built-in code (owner == NULL) as well.
1108 if (try_module_get(new->owner)) {
1109 if (!new->enable || new->enable(new) == 0) {
1110 old = tk->tkr_mono.clock;
1111 tk_setup_internals(tk, new);
1114 module_put(old->owner);
1116 module_put(new->owner);
1119 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1121 write_seqcount_end(&tk_core.seq);
1122 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1128 * timekeeping_notify - Install a new clock source
1129 * @clock: pointer to the clock source
1131 * This function is called from clocksource.c after a new, better clock
1132 * source has been registered. The caller holds the clocksource_mutex.
1134 int timekeeping_notify(struct clocksource *clock)
1136 struct timekeeper *tk = &tk_core.timekeeper;
1138 if (tk->tkr_mono.clock == clock)
1140 stop_machine(change_clocksource, clock, NULL);
1141 tick_clock_notify();
1142 return tk->tkr_mono.clock == clock ? 0 : -1;
1146 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1147 * @ts: pointer to the timespec64 to be set
1149 * Returns the raw monotonic time (completely un-modified by ntp)
1151 void getrawmonotonic64(struct timespec64 *ts)
1153 struct timekeeper *tk = &tk_core.timekeeper;
1154 struct timespec64 ts64;
1159 seq = read_seqcount_begin(&tk_core.seq);
1160 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1161 ts64 = tk->raw_time;
1163 } while (read_seqcount_retry(&tk_core.seq, seq));
1165 timespec64_add_ns(&ts64, nsecs);
1168 EXPORT_SYMBOL(getrawmonotonic64);
1172 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1174 int timekeeping_valid_for_hres(void)
1176 struct timekeeper *tk = &tk_core.timekeeper;
1181 seq = read_seqcount_begin(&tk_core.seq);
1183 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1185 } while (read_seqcount_retry(&tk_core.seq, seq));
1191 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1193 u64 timekeeping_max_deferment(void)
1195 struct timekeeper *tk = &tk_core.timekeeper;
1200 seq = read_seqcount_begin(&tk_core.seq);
1202 ret = tk->tkr_mono.clock->max_idle_ns;
1204 } while (read_seqcount_retry(&tk_core.seq, seq));
1210 * read_persistent_clock - Return time from the persistent clock.
1212 * Weak dummy function for arches that do not yet support it.
1213 * Reads the time from the battery backed persistent clock.
1214 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1216 * XXX - Do be sure to remove it once all arches implement it.
1218 void __weak read_persistent_clock(struct timespec *ts)
1224 void __weak read_persistent_clock64(struct timespec64 *ts64)
1228 read_persistent_clock(&ts);
1229 *ts64 = timespec_to_timespec64(ts);
1233 * read_boot_clock64 - Return time of the system start.
1235 * Weak dummy function for arches that do not yet support it.
1236 * Function to read the exact time the system has been started.
1237 * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1239 * XXX - Do be sure to remove it once all arches implement it.
1241 void __weak read_boot_clock64(struct timespec64 *ts)
1247 /* Flag for if timekeeping_resume() has injected sleeptime */
1248 static bool sleeptime_injected;
1250 /* Flag for if there is a persistent clock on this platform */
1251 static bool persistent_clock_exists;
1254 * timekeeping_init - Initializes the clocksource and common timekeeping values
1256 void __init timekeeping_init(void)
1258 struct timekeeper *tk = &tk_core.timekeeper;
1259 struct clocksource *clock;
1260 unsigned long flags;
1261 struct timespec64 now, boot, tmp;
1263 read_persistent_clock64(&now);
1264 if (!timespec64_valid_strict(&now)) {
1265 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1266 " Check your CMOS/BIOS settings.\n");
1269 } else if (now.tv_sec || now.tv_nsec)
1270 persistent_clock_exists = true;
1272 read_boot_clock64(&boot);
1273 if (!timespec64_valid_strict(&boot)) {
1274 pr_warn("WARNING: Boot clock returned invalid value!\n"
1275 " Check your CMOS/BIOS settings.\n");
1280 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1281 write_seqcount_begin(&tk_core.seq);
1284 clock = clocksource_default_clock();
1286 clock->enable(clock);
1287 tk_setup_internals(tk, clock);
1289 tk_set_xtime(tk, &now);
1290 tk->raw_time.tv_sec = 0;
1291 tk->raw_time.tv_nsec = 0;
1292 if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1293 boot = tk_xtime(tk);
1295 set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1296 tk_set_wall_to_mono(tk, tmp);
1298 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1300 write_seqcount_end(&tk_core.seq);
1301 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1304 /* time in seconds when suspend began for persistent clock */
1305 static struct timespec64 timekeeping_suspend_time;
1308 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1309 * @delta: pointer to a timespec delta value
1311 * Takes a timespec offset measuring a suspend interval and properly
1312 * adds the sleep offset to the timekeeping variables.
1314 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1315 struct timespec64 *delta)
1317 if (!timespec64_valid_strict(delta)) {
1318 printk_deferred(KERN_WARNING
1319 "__timekeeping_inject_sleeptime: Invalid "
1320 "sleep delta value!\n");
1323 tk_xtime_add(tk, delta);
1324 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1325 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1326 tk_debug_account_sleep_time(delta);
1329 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1331 * We have three kinds of time sources to use for sleep time
1332 * injection, the preference order is:
1333 * 1) non-stop clocksource
1334 * 2) persistent clock (ie: RTC accessible when irqs are off)
1337 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1338 * If system has neither 1) nor 2), 3) will be used finally.
1341 * If timekeeping has injected sleeptime via either 1) or 2),
1342 * 3) becomes needless, so in this case we don't need to call
1343 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1346 bool timekeeping_rtc_skipresume(void)
1348 return sleeptime_injected;
1352 * 1) can be determined whether to use or not only when doing
1353 * timekeeping_resume() which is invoked after rtc_suspend(),
1354 * so we can't skip rtc_suspend() surely if system has 1).
1356 * But if system has 2), 2) will definitely be used, so in this
1357 * case we don't need to call rtc_suspend(), and this is what
1358 * timekeeping_rtc_skipsuspend() means.
1360 bool timekeeping_rtc_skipsuspend(void)
1362 return persistent_clock_exists;
1366 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1367 * @delta: pointer to a timespec64 delta value
1369 * This hook is for architectures that cannot support read_persistent_clock64
1370 * because their RTC/persistent clock is only accessible when irqs are enabled.
1371 * and also don't have an effective nonstop clocksource.
1373 * This function should only be called by rtc_resume(), and allows
1374 * a suspend offset to be injected into the timekeeping values.
1376 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1378 struct timekeeper *tk = &tk_core.timekeeper;
1379 unsigned long flags;
1381 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1382 write_seqcount_begin(&tk_core.seq);
1384 timekeeping_forward_now(tk);
1386 __timekeeping_inject_sleeptime(tk, delta);
1388 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1390 write_seqcount_end(&tk_core.seq);
1391 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1393 /* signal hrtimers about time change */
1399 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1401 void timekeeping_resume(void)
1403 struct timekeeper *tk = &tk_core.timekeeper;
1404 struct clocksource *clock = tk->tkr_mono.clock;
1405 unsigned long flags;
1406 struct timespec64 ts_new, ts_delta;
1407 cycle_t cycle_now, cycle_delta;
1409 sleeptime_injected = false;
1410 read_persistent_clock64(&ts_new);
1412 clockevents_resume();
1413 clocksource_resume();
1415 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1416 write_seqcount_begin(&tk_core.seq);
1419 * After system resumes, we need to calculate the suspended time and
1420 * compensate it for the OS time. There are 3 sources that could be
1421 * used: Nonstop clocksource during suspend, persistent clock and rtc
1424 * One specific platform may have 1 or 2 or all of them, and the
1425 * preference will be:
1426 * suspend-nonstop clocksource -> persistent clock -> rtc
1427 * The less preferred source will only be tried if there is no better
1428 * usable source. The rtc part is handled separately in rtc core code.
1430 cycle_now = tk_clock_read(&tk->tkr_mono);
1431 if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1432 cycle_now > tk->tkr_mono.cycle_last) {
1433 u64 num, max = ULLONG_MAX;
1434 u32 mult = clock->mult;
1435 u32 shift = clock->shift;
1438 cycle_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1442 * "cycle_delta * mutl" may cause 64 bits overflow, if the
1443 * suspended time is too long. In that case we need do the
1444 * 64 bits math carefully
1447 if (cycle_delta > max) {
1448 num = div64_u64(cycle_delta, max);
1449 nsec = (((u64) max * mult) >> shift) * num;
1450 cycle_delta -= num * max;
1452 nsec += ((u64) cycle_delta * mult) >> shift;
1454 ts_delta = ns_to_timespec64(nsec);
1455 sleeptime_injected = true;
1456 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1457 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1458 sleeptime_injected = true;
1461 if (sleeptime_injected)
1462 __timekeeping_inject_sleeptime(tk, &ts_delta);
1464 /* Re-base the last cycle value */
1465 tk->tkr_mono.cycle_last = cycle_now;
1466 tk->tkr_raw.cycle_last = cycle_now;
1469 timekeeping_suspended = 0;
1470 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1471 write_seqcount_end(&tk_core.seq);
1472 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1474 touch_softlockup_watchdog();
1480 int timekeeping_suspend(void)
1482 struct timekeeper *tk = &tk_core.timekeeper;
1483 unsigned long flags;
1484 struct timespec64 delta, delta_delta;
1485 static struct timespec64 old_delta;
1487 read_persistent_clock64(&timekeeping_suspend_time);
1490 * On some systems the persistent_clock can not be detected at
1491 * timekeeping_init by its return value, so if we see a valid
1492 * value returned, update the persistent_clock_exists flag.
1494 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1495 persistent_clock_exists = true;
1497 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1498 write_seqcount_begin(&tk_core.seq);
1499 timekeeping_forward_now(tk);
1500 timekeeping_suspended = 1;
1502 if (persistent_clock_exists) {
1504 * To avoid drift caused by repeated suspend/resumes,
1505 * which each can add ~1 second drift error,
1506 * try to compensate so the difference in system time
1507 * and persistent_clock time stays close to constant.
1509 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1510 delta_delta = timespec64_sub(delta, old_delta);
1511 if (abs(delta_delta.tv_sec) >= 2) {
1513 * if delta_delta is too large, assume time correction
1514 * has occurred and set old_delta to the current delta.
1518 /* Otherwise try to adjust old_system to compensate */
1519 timekeeping_suspend_time =
1520 timespec64_add(timekeeping_suspend_time, delta_delta);
1524 timekeeping_update(tk, TK_MIRROR);
1525 halt_fast_timekeeper(tk);
1526 write_seqcount_end(&tk_core.seq);
1527 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1530 clocksource_suspend();
1531 clockevents_suspend();
1536 /* sysfs resume/suspend bits for timekeeping */
1537 static struct syscore_ops timekeeping_syscore_ops = {
1538 .resume = timekeeping_resume,
1539 .suspend = timekeeping_suspend,
1542 static int __init timekeeping_init_ops(void)
1544 register_syscore_ops(&timekeeping_syscore_ops);
1547 device_initcall(timekeeping_init_ops);
1550 * Apply a multiplier adjustment to the timekeeper
1552 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1557 s64 interval = tk->cycle_interval;
1561 mult_adj = -mult_adj;
1562 interval = -interval;
1565 mult_adj <<= adj_scale;
1566 interval <<= adj_scale;
1567 offset <<= adj_scale;
1570 * So the following can be confusing.
1572 * To keep things simple, lets assume mult_adj == 1 for now.
1574 * When mult_adj != 1, remember that the interval and offset values
1575 * have been appropriately scaled so the math is the same.
1577 * The basic idea here is that we're increasing the multiplier
1578 * by one, this causes the xtime_interval to be incremented by
1579 * one cycle_interval. This is because:
1580 * xtime_interval = cycle_interval * mult
1581 * So if mult is being incremented by one:
1582 * xtime_interval = cycle_interval * (mult + 1)
1584 * xtime_interval = (cycle_interval * mult) + cycle_interval
1585 * Which can be shortened to:
1586 * xtime_interval += cycle_interval
1588 * So offset stores the non-accumulated cycles. Thus the current
1589 * time (in shifted nanoseconds) is:
1590 * now = (offset * adj) + xtime_nsec
1591 * Now, even though we're adjusting the clock frequency, we have
1592 * to keep time consistent. In other words, we can't jump back
1593 * in time, and we also want to avoid jumping forward in time.
1595 * So given the same offset value, we need the time to be the same
1596 * both before and after the freq adjustment.
1597 * now = (offset * adj_1) + xtime_nsec_1
1598 * now = (offset * adj_2) + xtime_nsec_2
1600 * (offset * adj_1) + xtime_nsec_1 =
1601 * (offset * adj_2) + xtime_nsec_2
1605 * (offset * adj_1) + xtime_nsec_1 =
1606 * (offset * (adj_1+1)) + xtime_nsec_2
1607 * (offset * adj_1) + xtime_nsec_1 =
1608 * (offset * adj_1) + offset + xtime_nsec_2
1609 * Canceling the sides:
1610 * xtime_nsec_1 = offset + xtime_nsec_2
1612 * xtime_nsec_2 = xtime_nsec_1 - offset
1613 * Which simplfies to:
1614 * xtime_nsec -= offset
1616 * XXX - TODO: Doc ntp_error calculation.
1618 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1619 /* NTP adjustment caused clocksource mult overflow */
1624 tk->tkr_mono.mult += mult_adj;
1625 tk->xtime_interval += interval;
1626 tk->tkr_mono.xtime_nsec -= offset;
1627 tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1631 * Calculate the multiplier adjustment needed to match the frequency
1634 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1637 s64 interval = tk->cycle_interval;
1638 s64 xinterval = tk->xtime_interval;
1643 /* Remove any current error adj from freq calculation */
1644 if (tk->ntp_err_mult)
1645 xinterval -= tk->cycle_interval;
1647 tk->ntp_tick = ntp_tick_length();
1649 /* Calculate current error per tick */
1650 tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1651 tick_error -= (xinterval + tk->xtime_remainder);
1653 /* Don't worry about correcting it if its small */
1654 if (likely((tick_error >= 0) && (tick_error <= interval)))
1657 /* preserve the direction of correction */
1658 negative = (tick_error < 0);
1660 /* Sort out the magnitude of the correction */
1661 tick_error = abs(tick_error);
1662 for (adj = 0; tick_error > interval; adj++)
1665 /* scale the corrections */
1666 timekeeping_apply_adjustment(tk, offset, negative, adj);
1670 * Adjust the timekeeper's multiplier to the correct frequency
1671 * and also to reduce the accumulated error value.
1673 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1675 /* Correct for the current frequency error */
1676 timekeeping_freqadjust(tk, offset);
1678 /* Next make a small adjustment to fix any cumulative error */
1679 if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1680 tk->ntp_err_mult = 1;
1681 timekeeping_apply_adjustment(tk, offset, 0, 0);
1682 } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1683 /* Undo any existing error adjustment */
1684 timekeeping_apply_adjustment(tk, offset, 1, 0);
1685 tk->ntp_err_mult = 0;
1688 if (unlikely(tk->tkr_mono.clock->maxadj &&
1689 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
1690 > tk->tkr_mono.clock->maxadj))) {
1691 printk_once(KERN_WARNING
1692 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1693 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
1694 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
1698 * It may be possible that when we entered this function, xtime_nsec
1699 * was very small. Further, if we're slightly speeding the clocksource
1700 * in the code above, its possible the required corrective factor to
1701 * xtime_nsec could cause it to underflow.
1703 * Now, since we already accumulated the second, cannot simply roll
1704 * the accumulated second back, since the NTP subsystem has been
1705 * notified via second_overflow. So instead we push xtime_nsec forward
1706 * by the amount we underflowed, and add that amount into the error.
1708 * We'll correct this error next time through this function, when
1709 * xtime_nsec is not as small.
1711 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
1712 s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
1713 tk->tkr_mono.xtime_nsec = 0;
1714 tk->ntp_error += neg << tk->ntp_error_shift;
1719 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1721 * Helper function that accumulates the nsecs greater than a second
1722 * from the xtime_nsec field to the xtime_secs field.
1723 * It also calls into the NTP code to handle leapsecond processing.
1726 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
1728 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
1729 unsigned int clock_set = 0;
1731 while (tk->tkr_mono.xtime_nsec >= nsecps) {
1734 tk->tkr_mono.xtime_nsec -= nsecps;
1737 /* Figure out if its a leap sec and apply if needed */
1738 leap = second_overflow(tk->xtime_sec);
1739 if (unlikely(leap)) {
1740 struct timespec64 ts;
1742 tk->xtime_sec += leap;
1746 tk_set_wall_to_mono(tk,
1747 timespec64_sub(tk->wall_to_monotonic, ts));
1749 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1751 clock_set = TK_CLOCK_WAS_SET;
1758 * logarithmic_accumulation - shifted accumulation of cycles
1760 * This functions accumulates a shifted interval of cycles into
1761 * into a shifted interval nanoseconds. Allows for O(log) accumulation
1764 * Returns the unconsumed cycles.
1766 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1768 unsigned int *clock_set)
1770 cycle_t interval = tk->cycle_interval << shift;
1773 /* If the offset is smaller than a shifted interval, do nothing */
1774 if (offset < interval)
1777 /* Accumulate one shifted interval */
1779 tk->tkr_mono.cycle_last += interval;
1780 tk->tkr_raw.cycle_last += interval;
1782 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
1783 *clock_set |= accumulate_nsecs_to_secs(tk);
1785 /* Accumulate raw time */
1786 tk->tkr_raw.xtime_nsec += (u64)tk->raw_time.tv_nsec << tk->tkr_raw.shift;
1787 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
1788 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
1789 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
1790 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
1791 tk->raw_time.tv_sec++;
1793 tk->raw_time.tv_nsec = tk->tkr_raw.xtime_nsec >> tk->tkr_raw.shift;
1794 tk->tkr_raw.xtime_nsec -= (u64)tk->raw_time.tv_nsec << tk->tkr_raw.shift;
1796 /* Accumulate error between NTP and clock interval */
1797 tk->ntp_error += tk->ntp_tick << shift;
1798 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1799 (tk->ntp_error_shift + shift);
1805 * update_wall_time - Uses the current clocksource to increment the wall time
1808 void update_wall_time(void)
1810 struct timekeeper *real_tk = &tk_core.timekeeper;
1811 struct timekeeper *tk = &shadow_timekeeper;
1813 int shift = 0, maxshift;
1814 unsigned int clock_set = 0;
1815 unsigned long flags;
1817 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1819 /* Make sure we're fully resumed: */
1820 if (unlikely(timekeeping_suspended))
1823 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1824 offset = real_tk->cycle_interval;
1826 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
1827 tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
1830 /* Check if there's really nothing to do */
1831 if (offset < real_tk->cycle_interval)
1834 /* Do some additional sanity checking */
1835 timekeeping_check_update(real_tk, offset);
1838 * With NO_HZ we may have to accumulate many cycle_intervals
1839 * (think "ticks") worth of time at once. To do this efficiently,
1840 * we calculate the largest doubling multiple of cycle_intervals
1841 * that is smaller than the offset. We then accumulate that
1842 * chunk in one go, and then try to consume the next smaller
1845 shift = ilog2(offset) - ilog2(tk->cycle_interval);
1846 shift = max(0, shift);
1847 /* Bound shift to one less than what overflows tick_length */
1848 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1849 shift = min(shift, maxshift);
1850 while (offset >= tk->cycle_interval) {
1851 offset = logarithmic_accumulation(tk, offset, shift,
1853 if (offset < tk->cycle_interval<<shift)
1857 /* correct the clock when NTP error is too big */
1858 timekeeping_adjust(tk, offset);
1861 * XXX This can be killed once everyone converts
1862 * to the new update_vsyscall.
1864 old_vsyscall_fixup(tk);
1867 * Finally, make sure that after the rounding
1868 * xtime_nsec isn't larger than NSEC_PER_SEC
1870 clock_set |= accumulate_nsecs_to_secs(tk);
1872 write_seqcount_begin(&tk_core.seq);
1874 * Update the real timekeeper.
1876 * We could avoid this memcpy by switching pointers, but that
1877 * requires changes to all other timekeeper usage sites as
1878 * well, i.e. move the timekeeper pointer getter into the
1879 * spinlocked/seqcount protected sections. And we trade this
1880 * memcpy under the tk_core.seq against one before we start
1883 timekeeping_update(tk, clock_set);
1884 memcpy(real_tk, tk, sizeof(*tk));
1885 /* The memcpy must come last. Do not put anything here! */
1886 write_seqcount_end(&tk_core.seq);
1888 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1890 /* Have to call _delayed version, since in irq context*/
1891 clock_was_set_delayed();
1895 * getboottime64 - Return the real time of system boot.
1896 * @ts: pointer to the timespec64 to be set
1898 * Returns the wall-time of boot in a timespec64.
1900 * This is based on the wall_to_monotonic offset and the total suspend
1901 * time. Calls to settimeofday will affect the value returned (which
1902 * basically means that however wrong your real time clock is at boot time,
1903 * you get the right time here).
1905 void getboottime64(struct timespec64 *ts)
1907 struct timekeeper *tk = &tk_core.timekeeper;
1908 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
1910 *ts = ktime_to_timespec64(t);
1912 EXPORT_SYMBOL_GPL(getboottime64);
1914 unsigned long get_seconds(void)
1916 struct timekeeper *tk = &tk_core.timekeeper;
1918 return tk->xtime_sec;
1920 EXPORT_SYMBOL(get_seconds);
1922 struct timespec __current_kernel_time(void)
1924 struct timekeeper *tk = &tk_core.timekeeper;
1926 return timespec64_to_timespec(tk_xtime(tk));
1929 struct timespec64 current_kernel_time64(void)
1931 struct timekeeper *tk = &tk_core.timekeeper;
1932 struct timespec64 now;
1936 seq = read_seqcount_begin(&tk_core.seq);
1939 } while (read_seqcount_retry(&tk_core.seq, seq));
1943 EXPORT_SYMBOL(current_kernel_time64);
1945 struct timespec64 get_monotonic_coarse64(void)
1947 struct timekeeper *tk = &tk_core.timekeeper;
1948 struct timespec64 now, mono;
1952 seq = read_seqcount_begin(&tk_core.seq);
1955 mono = tk->wall_to_monotonic;
1956 } while (read_seqcount_retry(&tk_core.seq, seq));
1958 set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
1959 now.tv_nsec + mono.tv_nsec);
1965 * Must hold jiffies_lock
1967 void do_timer(unsigned long ticks)
1969 jiffies_64 += ticks;
1970 calc_global_load(ticks);
1974 * ktime_get_update_offsets_now - hrtimer helper
1975 * @cwsseq: pointer to check and store the clock was set sequence number
1976 * @offs_real: pointer to storage for monotonic -> realtime offset
1977 * @offs_boot: pointer to storage for monotonic -> boottime offset
1978 * @offs_tai: pointer to storage for monotonic -> clock tai offset
1980 * Returns current monotonic time and updates the offsets if the
1981 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
1984 * Called from hrtimer_interrupt() or retrigger_next_event()
1986 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
1987 ktime_t *offs_boot, ktime_t *offs_tai)
1989 struct timekeeper *tk = &tk_core.timekeeper;
1995 seq = read_seqcount_begin(&tk_core.seq);
1997 base = tk->tkr_mono.base;
1998 nsecs = timekeeping_get_ns(&tk->tkr_mono);
1999 base = ktime_add_ns(base, nsecs);
2001 if (*cwsseq != tk->clock_was_set_seq) {
2002 *cwsseq = tk->clock_was_set_seq;
2003 *offs_real = tk->offs_real;
2004 *offs_boot = tk->offs_boot;
2005 *offs_tai = tk->offs_tai;
2008 /* Handle leapsecond insertion adjustments */
2009 if (unlikely(base.tv64 >= tk->next_leap_ktime.tv64))
2010 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2012 } while (read_seqcount_retry(&tk_core.seq, seq));
2018 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2020 int do_adjtimex(struct timex *txc)
2022 struct timekeeper *tk = &tk_core.timekeeper;
2023 unsigned long flags;
2024 struct timespec64 ts;
2028 /* Validate the data before disabling interrupts */
2029 ret = ntp_validate_timex(txc);
2033 if (txc->modes & ADJ_SETOFFSET) {
2034 struct timespec delta;
2035 delta.tv_sec = txc->time.tv_sec;
2036 delta.tv_nsec = txc->time.tv_usec;
2037 if (!(txc->modes & ADJ_NANO))
2038 delta.tv_nsec *= 1000;
2039 ret = timekeeping_inject_offset(&delta);
2044 getnstimeofday64(&ts);
2046 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2047 write_seqcount_begin(&tk_core.seq);
2049 orig_tai = tai = tk->tai_offset;
2050 ret = __do_adjtimex(txc, &ts, &tai);
2052 if (tai != orig_tai) {
2053 __timekeeping_set_tai_offset(tk, tai);
2054 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2056 tk_update_leap_state(tk);
2058 write_seqcount_end(&tk_core.seq);
2059 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2061 if (tai != orig_tai)
2064 ntp_notify_cmos_timer();
2069 #ifdef CONFIG_NTP_PPS
2071 * hardpps() - Accessor function to NTP __hardpps function
2073 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2075 unsigned long flags;
2077 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2078 write_seqcount_begin(&tk_core.seq);
2080 __hardpps(phase_ts, raw_ts);
2082 write_seqcount_end(&tk_core.seq);
2083 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2085 EXPORT_SYMBOL(hardpps);
2089 * xtime_update() - advances the timekeeping infrastructure
2090 * @ticks: number of ticks, that have elapsed since the last call.
2092 * Must be called with interrupts disabled.
2094 void xtime_update(unsigned long ticks)
2096 write_seqlock(&jiffies_lock);
2098 write_sequnlock(&jiffies_lock);