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 = timespec64_sub(*ts, xt);
971 if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
976 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
978 tk_set_xtime(tk, ts);
980 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
982 write_seqcount_end(&tk_core.seq);
983 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
985 /* signal hrtimers about time change */
990 EXPORT_SYMBOL(do_settimeofday64);
993 * timekeeping_inject_offset - Adds or subtracts from the current time.
994 * @tv: pointer to the timespec variable containing the offset
996 * Adds or subtracts an offset value from the current time.
998 int timekeeping_inject_offset(struct timespec *ts)
1000 struct timekeeper *tk = &tk_core.timekeeper;
1001 unsigned long flags;
1002 struct timespec64 ts64, tmp;
1005 if (!timespec_inject_offset_valid(ts))
1008 ts64 = timespec_to_timespec64(*ts);
1010 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1011 write_seqcount_begin(&tk_core.seq);
1013 timekeeping_forward_now(tk);
1015 /* Make sure the proposed value is valid */
1016 tmp = timespec64_add(tk_xtime(tk), ts64);
1017 if (timespec64_compare(&tk->wall_to_monotonic, &ts64) > 0 ||
1018 !timespec64_valid_strict(&tmp)) {
1023 tk_xtime_add(tk, &ts64);
1024 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
1026 error: /* even if we error out, we forwarded the time, so call update */
1027 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1029 write_seqcount_end(&tk_core.seq);
1030 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1032 /* signal hrtimers about time change */
1037 EXPORT_SYMBOL(timekeeping_inject_offset);
1041 * timekeeping_get_tai_offset - Returns current TAI offset from UTC
1044 s32 timekeeping_get_tai_offset(void)
1046 struct timekeeper *tk = &tk_core.timekeeper;
1051 seq = read_seqcount_begin(&tk_core.seq);
1052 ret = tk->tai_offset;
1053 } while (read_seqcount_retry(&tk_core.seq, seq));
1059 * __timekeeping_set_tai_offset - Lock free worker function
1062 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1064 tk->tai_offset = tai_offset;
1065 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1069 * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
1072 void timekeeping_set_tai_offset(s32 tai_offset)
1074 struct timekeeper *tk = &tk_core.timekeeper;
1075 unsigned long flags;
1077 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1078 write_seqcount_begin(&tk_core.seq);
1079 __timekeeping_set_tai_offset(tk, tai_offset);
1080 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1081 write_seqcount_end(&tk_core.seq);
1082 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1087 * change_clocksource - Swaps clocksources if a new one is available
1089 * Accumulates current time interval and initializes new clocksource
1091 static int change_clocksource(void *data)
1093 struct timekeeper *tk = &tk_core.timekeeper;
1094 struct clocksource *new, *old;
1095 unsigned long flags;
1097 new = (struct clocksource *) data;
1099 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1100 write_seqcount_begin(&tk_core.seq);
1102 timekeeping_forward_now(tk);
1104 * If the cs is in module, get a module reference. Succeeds
1105 * for built-in code (owner == NULL) as well.
1107 if (try_module_get(new->owner)) {
1108 if (!new->enable || new->enable(new) == 0) {
1109 old = tk->tkr_mono.clock;
1110 tk_setup_internals(tk, new);
1113 module_put(old->owner);
1115 module_put(new->owner);
1118 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1120 write_seqcount_end(&tk_core.seq);
1121 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1127 * timekeeping_notify - Install a new clock source
1128 * @clock: pointer to the clock source
1130 * This function is called from clocksource.c after a new, better clock
1131 * source has been registered. The caller holds the clocksource_mutex.
1133 int timekeeping_notify(struct clocksource *clock)
1135 struct timekeeper *tk = &tk_core.timekeeper;
1137 if (tk->tkr_mono.clock == clock)
1139 stop_machine(change_clocksource, clock, NULL);
1140 tick_clock_notify();
1141 return tk->tkr_mono.clock == clock ? 0 : -1;
1145 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1146 * @ts: pointer to the timespec64 to be set
1148 * Returns the raw monotonic time (completely un-modified by ntp)
1150 void getrawmonotonic64(struct timespec64 *ts)
1152 struct timekeeper *tk = &tk_core.timekeeper;
1153 struct timespec64 ts64;
1158 seq = read_seqcount_begin(&tk_core.seq);
1159 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1160 ts64 = tk->raw_time;
1162 } while (read_seqcount_retry(&tk_core.seq, seq));
1164 timespec64_add_ns(&ts64, nsecs);
1167 EXPORT_SYMBOL(getrawmonotonic64);
1171 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1173 int timekeeping_valid_for_hres(void)
1175 struct timekeeper *tk = &tk_core.timekeeper;
1180 seq = read_seqcount_begin(&tk_core.seq);
1182 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1184 } while (read_seqcount_retry(&tk_core.seq, seq));
1190 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1192 u64 timekeeping_max_deferment(void)
1194 struct timekeeper *tk = &tk_core.timekeeper;
1199 seq = read_seqcount_begin(&tk_core.seq);
1201 ret = tk->tkr_mono.clock->max_idle_ns;
1203 } while (read_seqcount_retry(&tk_core.seq, seq));
1209 * read_persistent_clock - Return time from the persistent clock.
1211 * Weak dummy function for arches that do not yet support it.
1212 * Reads the time from the battery backed persistent clock.
1213 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1215 * XXX - Do be sure to remove it once all arches implement it.
1217 void __weak read_persistent_clock(struct timespec *ts)
1223 void __weak read_persistent_clock64(struct timespec64 *ts64)
1227 read_persistent_clock(&ts);
1228 *ts64 = timespec_to_timespec64(ts);
1232 * read_boot_clock64 - Return time of the system start.
1234 * Weak dummy function for arches that do not yet support it.
1235 * Function to read the exact time the system has been started.
1236 * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1238 * XXX - Do be sure to remove it once all arches implement it.
1240 void __weak read_boot_clock64(struct timespec64 *ts)
1246 /* Flag for if timekeeping_resume() has injected sleeptime */
1247 static bool sleeptime_injected;
1249 /* Flag for if there is a persistent clock on this platform */
1250 static bool persistent_clock_exists;
1253 * timekeeping_init - Initializes the clocksource and common timekeeping values
1255 void __init timekeeping_init(void)
1257 struct timekeeper *tk = &tk_core.timekeeper;
1258 struct clocksource *clock;
1259 unsigned long flags;
1260 struct timespec64 now, boot, tmp;
1262 read_persistent_clock64(&now);
1263 if (!timespec64_valid_strict(&now)) {
1264 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1265 " Check your CMOS/BIOS settings.\n");
1268 } else if (now.tv_sec || now.tv_nsec)
1269 persistent_clock_exists = true;
1271 read_boot_clock64(&boot);
1272 if (!timespec64_valid_strict(&boot)) {
1273 pr_warn("WARNING: Boot clock returned invalid value!\n"
1274 " Check your CMOS/BIOS settings.\n");
1279 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1280 write_seqcount_begin(&tk_core.seq);
1283 clock = clocksource_default_clock();
1285 clock->enable(clock);
1286 tk_setup_internals(tk, clock);
1288 tk_set_xtime(tk, &now);
1289 tk->raw_time.tv_sec = 0;
1290 tk->raw_time.tv_nsec = 0;
1291 if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1292 boot = tk_xtime(tk);
1294 set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1295 tk_set_wall_to_mono(tk, tmp);
1297 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1299 write_seqcount_end(&tk_core.seq);
1300 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1303 /* time in seconds when suspend began for persistent clock */
1304 static struct timespec64 timekeeping_suspend_time;
1307 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1308 * @delta: pointer to a timespec delta value
1310 * Takes a timespec offset measuring a suspend interval and properly
1311 * adds the sleep offset to the timekeeping variables.
1313 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1314 struct timespec64 *delta)
1316 if (!timespec64_valid_strict(delta)) {
1317 printk_deferred(KERN_WARNING
1318 "__timekeeping_inject_sleeptime: Invalid "
1319 "sleep delta value!\n");
1322 tk_xtime_add(tk, delta);
1323 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1324 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1325 tk_debug_account_sleep_time(delta);
1328 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1330 * We have three kinds of time sources to use for sleep time
1331 * injection, the preference order is:
1332 * 1) non-stop clocksource
1333 * 2) persistent clock (ie: RTC accessible when irqs are off)
1336 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1337 * If system has neither 1) nor 2), 3) will be used finally.
1340 * If timekeeping has injected sleeptime via either 1) or 2),
1341 * 3) becomes needless, so in this case we don't need to call
1342 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1345 bool timekeeping_rtc_skipresume(void)
1347 return sleeptime_injected;
1351 * 1) can be determined whether to use or not only when doing
1352 * timekeeping_resume() which is invoked after rtc_suspend(),
1353 * so we can't skip rtc_suspend() surely if system has 1).
1355 * But if system has 2), 2) will definitely be used, so in this
1356 * case we don't need to call rtc_suspend(), and this is what
1357 * timekeeping_rtc_skipsuspend() means.
1359 bool timekeeping_rtc_skipsuspend(void)
1361 return persistent_clock_exists;
1365 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1366 * @delta: pointer to a timespec64 delta value
1368 * This hook is for architectures that cannot support read_persistent_clock64
1369 * because their RTC/persistent clock is only accessible when irqs are enabled.
1370 * and also don't have an effective nonstop clocksource.
1372 * This function should only be called by rtc_resume(), and allows
1373 * a suspend offset to be injected into the timekeeping values.
1375 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1377 struct timekeeper *tk = &tk_core.timekeeper;
1378 unsigned long flags;
1380 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1381 write_seqcount_begin(&tk_core.seq);
1383 timekeeping_forward_now(tk);
1385 __timekeeping_inject_sleeptime(tk, delta);
1387 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1389 write_seqcount_end(&tk_core.seq);
1390 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1392 /* signal hrtimers about time change */
1398 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1400 void timekeeping_resume(void)
1402 struct timekeeper *tk = &tk_core.timekeeper;
1403 struct clocksource *clock = tk->tkr_mono.clock;
1404 unsigned long flags;
1405 struct timespec64 ts_new, ts_delta;
1406 cycle_t cycle_now, cycle_delta;
1408 sleeptime_injected = false;
1409 read_persistent_clock64(&ts_new);
1411 clockevents_resume();
1412 clocksource_resume();
1414 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1415 write_seqcount_begin(&tk_core.seq);
1418 * After system resumes, we need to calculate the suspended time and
1419 * compensate it for the OS time. There are 3 sources that could be
1420 * used: Nonstop clocksource during suspend, persistent clock and rtc
1423 * One specific platform may have 1 or 2 or all of them, and the
1424 * preference will be:
1425 * suspend-nonstop clocksource -> persistent clock -> rtc
1426 * The less preferred source will only be tried if there is no better
1427 * usable source. The rtc part is handled separately in rtc core code.
1429 cycle_now = tk_clock_read(&tk->tkr_mono);
1430 if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1431 cycle_now > tk->tkr_mono.cycle_last) {
1432 u64 num, max = ULLONG_MAX;
1433 u32 mult = clock->mult;
1434 u32 shift = clock->shift;
1437 cycle_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1441 * "cycle_delta * mutl" may cause 64 bits overflow, if the
1442 * suspended time is too long. In that case we need do the
1443 * 64 bits math carefully
1446 if (cycle_delta > max) {
1447 num = div64_u64(cycle_delta, max);
1448 nsec = (((u64) max * mult) >> shift) * num;
1449 cycle_delta -= num * max;
1451 nsec += ((u64) cycle_delta * mult) >> shift;
1453 ts_delta = ns_to_timespec64(nsec);
1454 sleeptime_injected = true;
1455 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1456 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1457 sleeptime_injected = true;
1460 if (sleeptime_injected)
1461 __timekeeping_inject_sleeptime(tk, &ts_delta);
1463 /* Re-base the last cycle value */
1464 tk->tkr_mono.cycle_last = cycle_now;
1465 tk->tkr_raw.cycle_last = cycle_now;
1468 timekeeping_suspended = 0;
1469 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1470 write_seqcount_end(&tk_core.seq);
1471 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1473 touch_softlockup_watchdog();
1479 int timekeeping_suspend(void)
1481 struct timekeeper *tk = &tk_core.timekeeper;
1482 unsigned long flags;
1483 struct timespec64 delta, delta_delta;
1484 static struct timespec64 old_delta;
1486 read_persistent_clock64(&timekeeping_suspend_time);
1489 * On some systems the persistent_clock can not be detected at
1490 * timekeeping_init by its return value, so if we see a valid
1491 * value returned, update the persistent_clock_exists flag.
1493 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1494 persistent_clock_exists = true;
1496 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1497 write_seqcount_begin(&tk_core.seq);
1498 timekeeping_forward_now(tk);
1499 timekeeping_suspended = 1;
1501 if (persistent_clock_exists) {
1503 * To avoid drift caused by repeated suspend/resumes,
1504 * which each can add ~1 second drift error,
1505 * try to compensate so the difference in system time
1506 * and persistent_clock time stays close to constant.
1508 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1509 delta_delta = timespec64_sub(delta, old_delta);
1510 if (abs(delta_delta.tv_sec) >= 2) {
1512 * if delta_delta is too large, assume time correction
1513 * has occurred and set old_delta to the current delta.
1517 /* Otherwise try to adjust old_system to compensate */
1518 timekeeping_suspend_time =
1519 timespec64_add(timekeeping_suspend_time, delta_delta);
1523 timekeeping_update(tk, TK_MIRROR);
1524 halt_fast_timekeeper(tk);
1525 write_seqcount_end(&tk_core.seq);
1526 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1529 clocksource_suspend();
1530 clockevents_suspend();
1535 /* sysfs resume/suspend bits for timekeeping */
1536 static struct syscore_ops timekeeping_syscore_ops = {
1537 .resume = timekeeping_resume,
1538 .suspend = timekeeping_suspend,
1541 static int __init timekeeping_init_ops(void)
1543 register_syscore_ops(&timekeeping_syscore_ops);
1546 device_initcall(timekeeping_init_ops);
1549 * Apply a multiplier adjustment to the timekeeper
1551 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1556 s64 interval = tk->cycle_interval;
1560 mult_adj = -mult_adj;
1561 interval = -interval;
1564 mult_adj <<= adj_scale;
1565 interval <<= adj_scale;
1566 offset <<= adj_scale;
1569 * So the following can be confusing.
1571 * To keep things simple, lets assume mult_adj == 1 for now.
1573 * When mult_adj != 1, remember that the interval and offset values
1574 * have been appropriately scaled so the math is the same.
1576 * The basic idea here is that we're increasing the multiplier
1577 * by one, this causes the xtime_interval to be incremented by
1578 * one cycle_interval. This is because:
1579 * xtime_interval = cycle_interval * mult
1580 * So if mult is being incremented by one:
1581 * xtime_interval = cycle_interval * (mult + 1)
1583 * xtime_interval = (cycle_interval * mult) + cycle_interval
1584 * Which can be shortened to:
1585 * xtime_interval += cycle_interval
1587 * So offset stores the non-accumulated cycles. Thus the current
1588 * time (in shifted nanoseconds) is:
1589 * now = (offset * adj) + xtime_nsec
1590 * Now, even though we're adjusting the clock frequency, we have
1591 * to keep time consistent. In other words, we can't jump back
1592 * in time, and we also want to avoid jumping forward in time.
1594 * So given the same offset value, we need the time to be the same
1595 * both before and after the freq adjustment.
1596 * now = (offset * adj_1) + xtime_nsec_1
1597 * now = (offset * adj_2) + xtime_nsec_2
1599 * (offset * adj_1) + xtime_nsec_1 =
1600 * (offset * adj_2) + xtime_nsec_2
1604 * (offset * adj_1) + xtime_nsec_1 =
1605 * (offset * (adj_1+1)) + xtime_nsec_2
1606 * (offset * adj_1) + xtime_nsec_1 =
1607 * (offset * adj_1) + offset + xtime_nsec_2
1608 * Canceling the sides:
1609 * xtime_nsec_1 = offset + xtime_nsec_2
1611 * xtime_nsec_2 = xtime_nsec_1 - offset
1612 * Which simplfies to:
1613 * xtime_nsec -= offset
1615 * XXX - TODO: Doc ntp_error calculation.
1617 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1618 /* NTP adjustment caused clocksource mult overflow */
1623 tk->tkr_mono.mult += mult_adj;
1624 tk->xtime_interval += interval;
1625 tk->tkr_mono.xtime_nsec -= offset;
1626 tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1630 * Calculate the multiplier adjustment needed to match the frequency
1633 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1636 s64 interval = tk->cycle_interval;
1637 s64 xinterval = tk->xtime_interval;
1642 /* Remove any current error adj from freq calculation */
1643 if (tk->ntp_err_mult)
1644 xinterval -= tk->cycle_interval;
1646 tk->ntp_tick = ntp_tick_length();
1648 /* Calculate current error per tick */
1649 tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1650 tick_error -= (xinterval + tk->xtime_remainder);
1652 /* Don't worry about correcting it if its small */
1653 if (likely((tick_error >= 0) && (tick_error <= interval)))
1656 /* preserve the direction of correction */
1657 negative = (tick_error < 0);
1659 /* Sort out the magnitude of the correction */
1660 tick_error = abs(tick_error);
1661 for (adj = 0; tick_error > interval; adj++)
1664 /* scale the corrections */
1665 timekeeping_apply_adjustment(tk, offset, negative, adj);
1669 * Adjust the timekeeper's multiplier to the correct frequency
1670 * and also to reduce the accumulated error value.
1672 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1674 /* Correct for the current frequency error */
1675 timekeeping_freqadjust(tk, offset);
1677 /* Next make a small adjustment to fix any cumulative error */
1678 if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1679 tk->ntp_err_mult = 1;
1680 timekeeping_apply_adjustment(tk, offset, 0, 0);
1681 } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1682 /* Undo any existing error adjustment */
1683 timekeeping_apply_adjustment(tk, offset, 1, 0);
1684 tk->ntp_err_mult = 0;
1687 if (unlikely(tk->tkr_mono.clock->maxadj &&
1688 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
1689 > tk->tkr_mono.clock->maxadj))) {
1690 printk_once(KERN_WARNING
1691 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1692 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
1693 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
1697 * It may be possible that when we entered this function, xtime_nsec
1698 * was very small. Further, if we're slightly speeding the clocksource
1699 * in the code above, its possible the required corrective factor to
1700 * xtime_nsec could cause it to underflow.
1702 * Now, since we already accumulated the second, cannot simply roll
1703 * the accumulated second back, since the NTP subsystem has been
1704 * notified via second_overflow. So instead we push xtime_nsec forward
1705 * by the amount we underflowed, and add that amount into the error.
1707 * We'll correct this error next time through this function, when
1708 * xtime_nsec is not as small.
1710 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
1711 s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
1712 tk->tkr_mono.xtime_nsec = 0;
1713 tk->ntp_error += neg << tk->ntp_error_shift;
1718 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1720 * Helper function that accumulates the nsecs greater than a second
1721 * from the xtime_nsec field to the xtime_secs field.
1722 * It also calls into the NTP code to handle leapsecond processing.
1725 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
1727 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
1728 unsigned int clock_set = 0;
1730 while (tk->tkr_mono.xtime_nsec >= nsecps) {
1733 tk->tkr_mono.xtime_nsec -= nsecps;
1736 /* Figure out if its a leap sec and apply if needed */
1737 leap = second_overflow(tk->xtime_sec);
1738 if (unlikely(leap)) {
1739 struct timespec64 ts;
1741 tk->xtime_sec += leap;
1745 tk_set_wall_to_mono(tk,
1746 timespec64_sub(tk->wall_to_monotonic, ts));
1748 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1750 clock_set = TK_CLOCK_WAS_SET;
1757 * logarithmic_accumulation - shifted accumulation of cycles
1759 * This functions accumulates a shifted interval of cycles into
1760 * into a shifted interval nanoseconds. Allows for O(log) accumulation
1763 * Returns the unconsumed cycles.
1765 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1767 unsigned int *clock_set)
1769 cycle_t interval = tk->cycle_interval << shift;
1772 /* If the offset is smaller than a shifted interval, do nothing */
1773 if (offset < interval)
1776 /* Accumulate one shifted interval */
1778 tk->tkr_mono.cycle_last += interval;
1779 tk->tkr_raw.cycle_last += interval;
1781 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
1782 *clock_set |= accumulate_nsecs_to_secs(tk);
1784 /* Accumulate raw time */
1785 tk->tkr_raw.xtime_nsec += (u64)tk->raw_time.tv_nsec << tk->tkr_raw.shift;
1786 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
1787 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
1788 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
1789 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
1790 tk->raw_time.tv_sec++;
1792 tk->raw_time.tv_nsec = tk->tkr_raw.xtime_nsec >> tk->tkr_raw.shift;
1793 tk->tkr_raw.xtime_nsec -= (u64)tk->raw_time.tv_nsec << tk->tkr_raw.shift;
1795 /* Accumulate error between NTP and clock interval */
1796 tk->ntp_error += tk->ntp_tick << shift;
1797 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1798 (tk->ntp_error_shift + shift);
1804 * update_wall_time - Uses the current clocksource to increment the wall time
1807 void update_wall_time(void)
1809 struct timekeeper *real_tk = &tk_core.timekeeper;
1810 struct timekeeper *tk = &shadow_timekeeper;
1812 int shift = 0, maxshift;
1813 unsigned int clock_set = 0;
1814 unsigned long flags;
1816 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1818 /* Make sure we're fully resumed: */
1819 if (unlikely(timekeeping_suspended))
1822 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1823 offset = real_tk->cycle_interval;
1825 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
1826 tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
1829 /* Check if there's really nothing to do */
1830 if (offset < real_tk->cycle_interval)
1833 /* Do some additional sanity checking */
1834 timekeeping_check_update(real_tk, offset);
1837 * With NO_HZ we may have to accumulate many cycle_intervals
1838 * (think "ticks") worth of time at once. To do this efficiently,
1839 * we calculate the largest doubling multiple of cycle_intervals
1840 * that is smaller than the offset. We then accumulate that
1841 * chunk in one go, and then try to consume the next smaller
1844 shift = ilog2(offset) - ilog2(tk->cycle_interval);
1845 shift = max(0, shift);
1846 /* Bound shift to one less than what overflows tick_length */
1847 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1848 shift = min(shift, maxshift);
1849 while (offset >= tk->cycle_interval) {
1850 offset = logarithmic_accumulation(tk, offset, shift,
1852 if (offset < tk->cycle_interval<<shift)
1856 /* correct the clock when NTP error is too big */
1857 timekeeping_adjust(tk, offset);
1860 * XXX This can be killed once everyone converts
1861 * to the new update_vsyscall.
1863 old_vsyscall_fixup(tk);
1866 * Finally, make sure that after the rounding
1867 * xtime_nsec isn't larger than NSEC_PER_SEC
1869 clock_set |= accumulate_nsecs_to_secs(tk);
1871 write_seqcount_begin(&tk_core.seq);
1873 * Update the real timekeeper.
1875 * We could avoid this memcpy by switching pointers, but that
1876 * requires changes to all other timekeeper usage sites as
1877 * well, i.e. move the timekeeper pointer getter into the
1878 * spinlocked/seqcount protected sections. And we trade this
1879 * memcpy under the tk_core.seq against one before we start
1882 timekeeping_update(tk, clock_set);
1883 memcpy(real_tk, tk, sizeof(*tk));
1884 /* The memcpy must come last. Do not put anything here! */
1885 write_seqcount_end(&tk_core.seq);
1887 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1889 /* Have to call _delayed version, since in irq context*/
1890 clock_was_set_delayed();
1894 * getboottime64 - Return the real time of system boot.
1895 * @ts: pointer to the timespec64 to be set
1897 * Returns the wall-time of boot in a timespec64.
1899 * This is based on the wall_to_monotonic offset and the total suspend
1900 * time. Calls to settimeofday will affect the value returned (which
1901 * basically means that however wrong your real time clock is at boot time,
1902 * you get the right time here).
1904 void getboottime64(struct timespec64 *ts)
1906 struct timekeeper *tk = &tk_core.timekeeper;
1907 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
1909 *ts = ktime_to_timespec64(t);
1911 EXPORT_SYMBOL_GPL(getboottime64);
1913 unsigned long get_seconds(void)
1915 struct timekeeper *tk = &tk_core.timekeeper;
1917 return tk->xtime_sec;
1919 EXPORT_SYMBOL(get_seconds);
1921 struct timespec __current_kernel_time(void)
1923 struct timekeeper *tk = &tk_core.timekeeper;
1925 return timespec64_to_timespec(tk_xtime(tk));
1928 struct timespec64 current_kernel_time64(void)
1930 struct timekeeper *tk = &tk_core.timekeeper;
1931 struct timespec64 now;
1935 seq = read_seqcount_begin(&tk_core.seq);
1938 } while (read_seqcount_retry(&tk_core.seq, seq));
1942 EXPORT_SYMBOL(current_kernel_time64);
1944 struct timespec64 get_monotonic_coarse64(void)
1946 struct timekeeper *tk = &tk_core.timekeeper;
1947 struct timespec64 now, mono;
1951 seq = read_seqcount_begin(&tk_core.seq);
1954 mono = tk->wall_to_monotonic;
1955 } while (read_seqcount_retry(&tk_core.seq, seq));
1957 set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
1958 now.tv_nsec + mono.tv_nsec);
1964 * Must hold jiffies_lock
1966 void do_timer(unsigned long ticks)
1968 jiffies_64 += ticks;
1969 calc_global_load(ticks);
1973 * ktime_get_update_offsets_now - hrtimer helper
1974 * @cwsseq: pointer to check and store the clock was set sequence number
1975 * @offs_real: pointer to storage for monotonic -> realtime offset
1976 * @offs_boot: pointer to storage for monotonic -> boottime offset
1977 * @offs_tai: pointer to storage for monotonic -> clock tai offset
1979 * Returns current monotonic time and updates the offsets if the
1980 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
1983 * Called from hrtimer_interrupt() or retrigger_next_event()
1985 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
1986 ktime_t *offs_boot, ktime_t *offs_tai)
1988 struct timekeeper *tk = &tk_core.timekeeper;
1994 seq = read_seqcount_begin(&tk_core.seq);
1996 base = tk->tkr_mono.base;
1997 nsecs = timekeeping_get_ns(&tk->tkr_mono);
1998 base = ktime_add_ns(base, nsecs);
2000 if (*cwsseq != tk->clock_was_set_seq) {
2001 *cwsseq = tk->clock_was_set_seq;
2002 *offs_real = tk->offs_real;
2003 *offs_boot = tk->offs_boot;
2004 *offs_tai = tk->offs_tai;
2007 /* Handle leapsecond insertion adjustments */
2008 if (unlikely(base.tv64 >= tk->next_leap_ktime.tv64))
2009 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2011 } while (read_seqcount_retry(&tk_core.seq, seq));
2017 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2019 int do_adjtimex(struct timex *txc)
2021 struct timekeeper *tk = &tk_core.timekeeper;
2022 unsigned long flags;
2023 struct timespec64 ts;
2027 /* Validate the data before disabling interrupts */
2028 ret = ntp_validate_timex(txc);
2032 if (txc->modes & ADJ_SETOFFSET) {
2033 struct timespec delta;
2034 delta.tv_sec = txc->time.tv_sec;
2035 delta.tv_nsec = txc->time.tv_usec;
2036 if (!(txc->modes & ADJ_NANO))
2037 delta.tv_nsec *= 1000;
2038 ret = timekeeping_inject_offset(&delta);
2043 getnstimeofday64(&ts);
2045 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2046 write_seqcount_begin(&tk_core.seq);
2048 orig_tai = tai = tk->tai_offset;
2049 ret = __do_adjtimex(txc, &ts, &tai);
2051 if (tai != orig_tai) {
2052 __timekeeping_set_tai_offset(tk, tai);
2053 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2055 tk_update_leap_state(tk);
2057 write_seqcount_end(&tk_core.seq);
2058 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2060 if (tai != orig_tai)
2063 ntp_notify_cmos_timer();
2068 #ifdef CONFIG_NTP_PPS
2070 * hardpps() - Accessor function to NTP __hardpps function
2072 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2074 unsigned long flags;
2076 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2077 write_seqcount_begin(&tk_core.seq);
2079 __hardpps(phase_ts, raw_ts);
2081 write_seqcount_end(&tk_core.seq);
2082 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2084 EXPORT_SYMBOL(hardpps);
2088 * xtime_update() - advances the timekeeping infrastructure
2089 * @ticks: number of ticks, that have elapsed since the last call.
2091 * Must be called with interrupts disabled.
2093 void xtime_update(unsigned long ticks)
2095 write_seqlock(&jiffies_lock);
2097 write_sequnlock(&jiffies_lock);