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;
44 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
45 static struct timekeeper shadow_timekeeper;
48 * struct tk_fast - NMI safe timekeeper
49 * @seq: Sequence counter for protecting updates. The lowest bit
50 * is the index for the tk_read_base array
51 * @base: tk_read_base array. Access is indexed by the lowest bit of
54 * See @update_fast_timekeeper() below.
58 struct tk_read_base base[2];
61 static struct tk_fast tk_fast_mono ____cacheline_aligned;
63 /* flag for if timekeeping is suspended */
64 int __read_mostly timekeeping_suspended;
66 /* Flag for if there is a persistent clock on this platform */
67 bool __read_mostly persistent_clock_exist = false;
69 static inline void tk_normalize_xtime(struct timekeeper *tk)
71 while (tk->tkr.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr.shift)) {
72 tk->tkr.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr.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.xtime_nsec >> tk->tkr.shift);
86 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
88 tk->xtime_sec = ts->tv_sec;
89 tk->tkr.xtime_nsec = (u64)ts->tv_nsec << tk->tkr.shift;
92 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
94 tk->xtime_sec += ts->tv_sec;
95 tk->tkr.xtime_nsec += (u64)ts->tv_nsec << tk->tkr.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);
121 #ifdef CONFIG_DEBUG_TIMEKEEPING
122 #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
124 * These simple flag variables are managed
125 * without locks, which is racy, but ok since
126 * we don't really care about being super
127 * precise about how many events were seen,
128 * just that a problem was observed.
130 static int timekeeping_underflow_seen;
131 static int timekeeping_overflow_seen;
133 /* last_warning is only modified under the timekeeping lock */
134 static long timekeeping_last_warning;
136 static void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
139 cycle_t max_cycles = tk->tkr.clock->max_cycles;
140 const char *name = tk->tkr.clock->name;
142 if (offset > max_cycles) {
143 printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
144 offset, name, max_cycles);
145 printk_deferred(" timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
147 if (offset > (max_cycles >> 1)) {
148 printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the the '%s' clock's 50%% safety margin (%lld)\n",
149 offset, name, max_cycles >> 1);
150 printk_deferred(" timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
154 if (timekeeping_underflow_seen) {
155 if (jiffies - timekeeping_last_warning > WARNING_FREQ) {
156 printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
157 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
158 printk_deferred(" Your kernel is probably still fine.\n");
159 timekeeping_last_warning = jiffies;
161 timekeeping_underflow_seen = 0;
164 if (timekeeping_overflow_seen) {
165 if (jiffies - timekeeping_last_warning > WARNING_FREQ) {
166 printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
167 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
168 printk_deferred(" Your kernel is probably still fine.\n");
169 timekeeping_last_warning = jiffies;
171 timekeeping_overflow_seen = 0;
175 static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
177 cycle_t now, last, mask, max, delta;
181 * Since we're called holding a seqlock, the data may shift
182 * under us while we're doing the calculation. This can cause
183 * false positives, since we'd note a problem but throw the
184 * results away. So nest another seqlock here to atomically
185 * grab the points we are checking with.
188 seq = read_seqcount_begin(&tk_core.seq);
189 now = tkr->read(tkr->clock);
190 last = tkr->cycle_last;
192 max = tkr->clock->max_cycles;
193 } while (read_seqcount_retry(&tk_core.seq, seq));
195 delta = clocksource_delta(now, last, mask);
198 * Try to catch underflows by checking if we are seeing small
199 * mask-relative negative values.
201 if (unlikely((~delta & mask) < (mask >> 3))) {
202 timekeeping_underflow_seen = 1;
206 /* Cap delta value to the max_cycles values to avoid mult overflows */
207 if (unlikely(delta > max)) {
208 timekeeping_overflow_seen = 1;
209 delta = tkr->clock->max_cycles;
215 static inline void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
218 static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
220 cycle_t cycle_now, delta;
222 /* read clocksource */
223 cycle_now = tkr->read(tkr->clock);
225 /* calculate the delta since the last update_wall_time */
226 delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
233 * tk_setup_internals - Set up internals to use clocksource clock.
235 * @tk: The target timekeeper to setup.
236 * @clock: Pointer to clocksource.
238 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
239 * pair and interval request.
241 * Unless you're the timekeeping code, you should not be using this!
243 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
246 u64 tmp, ntpinterval;
247 struct clocksource *old_clock;
249 old_clock = tk->tkr.clock;
250 tk->tkr.clock = clock;
251 tk->tkr.read = clock->read;
252 tk->tkr.mask = clock->mask;
253 tk->tkr.cycle_last = tk->tkr.read(clock);
255 /* Do the ns -> cycle conversion first, using original mult */
256 tmp = NTP_INTERVAL_LENGTH;
257 tmp <<= clock->shift;
259 tmp += clock->mult/2;
260 do_div(tmp, clock->mult);
264 interval = (cycle_t) tmp;
265 tk->cycle_interval = interval;
267 /* Go back from cycles -> shifted ns */
268 tk->xtime_interval = (u64) interval * clock->mult;
269 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
271 ((u64) interval * clock->mult) >> clock->shift;
273 /* if changing clocks, convert xtime_nsec shift units */
275 int shift_change = clock->shift - old_clock->shift;
276 if (shift_change < 0)
277 tk->tkr.xtime_nsec >>= -shift_change;
279 tk->tkr.xtime_nsec <<= shift_change;
281 tk->tkr.shift = clock->shift;
284 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
285 tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
288 * The timekeeper keeps its own mult values for the currently
289 * active clocksource. These value will be adjusted via NTP
290 * to counteract clock drifting.
292 tk->tkr.mult = clock->mult;
293 tk->ntp_err_mult = 0;
296 /* Timekeeper helper functions. */
298 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
299 static u32 default_arch_gettimeoffset(void) { return 0; }
300 u32 (*arch_gettimeoffset)(void) = default_arch_gettimeoffset;
302 static inline u32 arch_gettimeoffset(void) { return 0; }
305 static inline s64 timekeeping_get_ns(struct tk_read_base *tkr)
310 delta = timekeeping_get_delta(tkr);
312 nsec = delta * tkr->mult + tkr->xtime_nsec;
315 /* If arch requires, add in get_arch_timeoffset() */
316 return nsec + arch_gettimeoffset();
319 static inline s64 timekeeping_get_ns_raw(struct timekeeper *tk)
321 struct clocksource *clock = tk->tkr.clock;
325 delta = timekeeping_get_delta(&tk->tkr);
327 /* convert delta to nanoseconds. */
328 nsec = clocksource_cyc2ns(delta, clock->mult, clock->shift);
330 /* If arch requires, add in get_arch_timeoffset() */
331 return nsec + arch_gettimeoffset();
335 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
336 * @tkr: Timekeeping readout base from which we take the update
338 * We want to use this from any context including NMI and tracing /
339 * instrumenting the timekeeping code itself.
341 * So we handle this differently than the other timekeeping accessor
342 * functions which retry when the sequence count has changed. The
345 * smp_wmb(); <- Ensure that the last base[1] update is visible
347 * smp_wmb(); <- Ensure that the seqcount update is visible
348 * update(tkf->base[0], tkr);
349 * smp_wmb(); <- Ensure that the base[0] update is visible
351 * smp_wmb(); <- Ensure that the seqcount update is visible
352 * update(tkf->base[1], tkr);
354 * The reader side does:
360 * now = now(tkf->base[idx]);
362 * } while (seq != tkf->seq)
364 * As long as we update base[0] readers are forced off to
365 * base[1]. Once base[0] is updated readers are redirected to base[0]
366 * and the base[1] update takes place.
368 * So if a NMI hits the update of base[0] then it will use base[1]
369 * which is still consistent. In the worst case this can result is a
370 * slightly wrong timestamp (a few nanoseconds). See
371 * @ktime_get_mono_fast_ns.
373 static void update_fast_timekeeper(struct tk_read_base *tkr)
375 struct tk_read_base *base = tk_fast_mono.base;
377 /* Force readers off to base[1] */
378 raw_write_seqcount_latch(&tk_fast_mono.seq);
381 memcpy(base, tkr, sizeof(*base));
383 /* Force readers back to base[0] */
384 raw_write_seqcount_latch(&tk_fast_mono.seq);
387 memcpy(base + 1, base, sizeof(*base));
391 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
393 * This timestamp is not guaranteed to be monotonic across an update.
394 * The timestamp is calculated by:
396 * now = base_mono + clock_delta * slope
398 * So if the update lowers the slope, readers who are forced to the
399 * not yet updated second array are still using the old steeper slope.
408 * |12345678---> reader order
414 * So reader 6 will observe time going backwards versus reader 5.
416 * While other CPUs are likely to be able observe that, the only way
417 * for a CPU local observation is when an NMI hits in the middle of
418 * the update. Timestamps taken from that NMI context might be ahead
419 * of the following timestamps. Callers need to be aware of that and
422 u64 notrace ktime_get_mono_fast_ns(void)
424 struct tk_read_base *tkr;
429 seq = raw_read_seqcount(&tk_fast_mono.seq);
430 tkr = tk_fast_mono.base + (seq & 0x01);
431 now = ktime_to_ns(tkr->base_mono) + timekeeping_get_ns(tkr);
433 } while (read_seqcount_retry(&tk_fast_mono.seq, seq));
436 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
438 /* Suspend-time cycles value for halted fast timekeeper. */
439 static cycle_t cycles_at_suspend;
441 static cycle_t dummy_clock_read(struct clocksource *cs)
443 return cycles_at_suspend;
447 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
448 * @tk: Timekeeper to snapshot.
450 * It generally is unsafe to access the clocksource after timekeeping has been
451 * suspended, so take a snapshot of the readout base of @tk and use it as the
452 * fast timekeeper's readout base while suspended. It will return the same
453 * number of cycles every time until timekeeping is resumed at which time the
454 * proper readout base for the fast timekeeper will be restored automatically.
456 static void halt_fast_timekeeper(struct timekeeper *tk)
458 static struct tk_read_base tkr_dummy;
459 struct tk_read_base *tkr = &tk->tkr;
461 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
462 cycles_at_suspend = tkr->read(tkr->clock);
463 tkr_dummy.read = dummy_clock_read;
464 update_fast_timekeeper(&tkr_dummy);
467 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
469 static inline void update_vsyscall(struct timekeeper *tk)
471 struct timespec xt, wm;
473 xt = timespec64_to_timespec(tk_xtime(tk));
474 wm = timespec64_to_timespec(tk->wall_to_monotonic);
475 update_vsyscall_old(&xt, &wm, tk->tkr.clock, tk->tkr.mult,
479 static inline void old_vsyscall_fixup(struct timekeeper *tk)
484 * Store only full nanoseconds into xtime_nsec after rounding
485 * it up and add the remainder to the error difference.
486 * XXX - This is necessary to avoid small 1ns inconsistnecies caused
487 * by truncating the remainder in vsyscalls. However, it causes
488 * additional work to be done in timekeeping_adjust(). Once
489 * the vsyscall implementations are converted to use xtime_nsec
490 * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
491 * users are removed, this can be killed.
493 remainder = tk->tkr.xtime_nsec & ((1ULL << tk->tkr.shift) - 1);
494 tk->tkr.xtime_nsec -= remainder;
495 tk->tkr.xtime_nsec += 1ULL << tk->tkr.shift;
496 tk->ntp_error += remainder << tk->ntp_error_shift;
497 tk->ntp_error -= (1ULL << tk->tkr.shift) << tk->ntp_error_shift;
500 #define old_vsyscall_fixup(tk)
503 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
505 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
507 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
511 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
513 int pvclock_gtod_register_notifier(struct notifier_block *nb)
515 struct timekeeper *tk = &tk_core.timekeeper;
519 raw_spin_lock_irqsave(&timekeeper_lock, flags);
520 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
521 update_pvclock_gtod(tk, true);
522 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
526 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
529 * pvclock_gtod_unregister_notifier - unregister a pvclock
530 * timedata update listener
532 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
537 raw_spin_lock_irqsave(&timekeeper_lock, flags);
538 ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
539 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
543 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
546 * Update the ktime_t based scalar nsec members of the timekeeper
548 static inline void tk_update_ktime_data(struct timekeeper *tk)
554 * The xtime based monotonic readout is:
555 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
556 * The ktime based monotonic readout is:
557 * nsec = base_mono + now();
558 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
560 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
561 nsec = (u32) tk->wall_to_monotonic.tv_nsec;
562 tk->tkr.base_mono = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
564 /* Update the monotonic raw base */
565 tk->base_raw = timespec64_to_ktime(tk->raw_time);
568 * The sum of the nanoseconds portions of xtime and
569 * wall_to_monotonic can be greater/equal one second. Take
570 * this into account before updating tk->ktime_sec.
572 nsec += (u32)(tk->tkr.xtime_nsec >> tk->tkr.shift);
573 if (nsec >= NSEC_PER_SEC)
575 tk->ktime_sec = seconds;
578 /* must hold timekeeper_lock */
579 static void timekeeping_update(struct timekeeper *tk, unsigned int action)
581 if (action & TK_CLEAR_NTP) {
586 tk_update_ktime_data(tk);
589 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
591 if (action & TK_MIRROR)
592 memcpy(&shadow_timekeeper, &tk_core.timekeeper,
593 sizeof(tk_core.timekeeper));
595 update_fast_timekeeper(&tk->tkr);
599 * timekeeping_forward_now - update clock to the current time
601 * Forward the current clock to update its state since the last call to
602 * update_wall_time(). This is useful before significant clock changes,
603 * as it avoids having to deal with this time offset explicitly.
605 static void timekeeping_forward_now(struct timekeeper *tk)
607 struct clocksource *clock = tk->tkr.clock;
608 cycle_t cycle_now, delta;
611 cycle_now = tk->tkr.read(clock);
612 delta = clocksource_delta(cycle_now, tk->tkr.cycle_last, tk->tkr.mask);
613 tk->tkr.cycle_last = cycle_now;
615 tk->tkr.xtime_nsec += delta * tk->tkr.mult;
617 /* If arch requires, add in get_arch_timeoffset() */
618 tk->tkr.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr.shift;
620 tk_normalize_xtime(tk);
622 nsec = clocksource_cyc2ns(delta, clock->mult, clock->shift);
623 timespec64_add_ns(&tk->raw_time, nsec);
627 * __getnstimeofday64 - Returns the time of day in a timespec64.
628 * @ts: pointer to the timespec to be set
630 * Updates the time of day in the timespec.
631 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
633 int __getnstimeofday64(struct timespec64 *ts)
635 struct timekeeper *tk = &tk_core.timekeeper;
640 seq = read_seqcount_begin(&tk_core.seq);
642 ts->tv_sec = tk->xtime_sec;
643 nsecs = timekeeping_get_ns(&tk->tkr);
645 } while (read_seqcount_retry(&tk_core.seq, seq));
648 timespec64_add_ns(ts, nsecs);
651 * Do not bail out early, in case there were callers still using
652 * the value, even in the face of the WARN_ON.
654 if (unlikely(timekeeping_suspended))
658 EXPORT_SYMBOL(__getnstimeofday64);
661 * getnstimeofday64 - Returns the time of day in a timespec64.
662 * @ts: pointer to the timespec64 to be set
664 * Returns the time of day in a timespec64 (WARN if suspended).
666 void getnstimeofday64(struct timespec64 *ts)
668 WARN_ON(__getnstimeofday64(ts));
670 EXPORT_SYMBOL(getnstimeofday64);
672 ktime_t ktime_get(void)
674 struct timekeeper *tk = &tk_core.timekeeper;
679 WARN_ON(timekeeping_suspended);
682 seq = read_seqcount_begin(&tk_core.seq);
683 base = tk->tkr.base_mono;
684 nsecs = timekeeping_get_ns(&tk->tkr);
686 } while (read_seqcount_retry(&tk_core.seq, seq));
688 return ktime_add_ns(base, nsecs);
690 EXPORT_SYMBOL_GPL(ktime_get);
692 static ktime_t *offsets[TK_OFFS_MAX] = {
693 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
694 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
695 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
698 ktime_t ktime_get_with_offset(enum tk_offsets offs)
700 struct timekeeper *tk = &tk_core.timekeeper;
702 ktime_t base, *offset = offsets[offs];
705 WARN_ON(timekeeping_suspended);
708 seq = read_seqcount_begin(&tk_core.seq);
709 base = ktime_add(tk->tkr.base_mono, *offset);
710 nsecs = timekeeping_get_ns(&tk->tkr);
712 } while (read_seqcount_retry(&tk_core.seq, seq));
714 return ktime_add_ns(base, nsecs);
717 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
720 * ktime_mono_to_any() - convert mononotic time to any other time
721 * @tmono: time to convert.
722 * @offs: which offset to use
724 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
726 ktime_t *offset = offsets[offs];
731 seq = read_seqcount_begin(&tk_core.seq);
732 tconv = ktime_add(tmono, *offset);
733 } while (read_seqcount_retry(&tk_core.seq, seq));
737 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
740 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
742 ktime_t ktime_get_raw(void)
744 struct timekeeper *tk = &tk_core.timekeeper;
750 seq = read_seqcount_begin(&tk_core.seq);
752 nsecs = timekeeping_get_ns_raw(tk);
754 } while (read_seqcount_retry(&tk_core.seq, seq));
756 return ktime_add_ns(base, nsecs);
758 EXPORT_SYMBOL_GPL(ktime_get_raw);
761 * ktime_get_ts64 - get the monotonic clock in timespec64 format
762 * @ts: pointer to timespec variable
764 * The function calculates the monotonic clock from the realtime
765 * clock and the wall_to_monotonic offset and stores the result
766 * in normalized timespec64 format in the variable pointed to by @ts.
768 void ktime_get_ts64(struct timespec64 *ts)
770 struct timekeeper *tk = &tk_core.timekeeper;
771 struct timespec64 tomono;
775 WARN_ON(timekeeping_suspended);
778 seq = read_seqcount_begin(&tk_core.seq);
779 ts->tv_sec = tk->xtime_sec;
780 nsec = timekeeping_get_ns(&tk->tkr);
781 tomono = tk->wall_to_monotonic;
783 } while (read_seqcount_retry(&tk_core.seq, seq));
785 ts->tv_sec += tomono.tv_sec;
787 timespec64_add_ns(ts, nsec + tomono.tv_nsec);
789 EXPORT_SYMBOL_GPL(ktime_get_ts64);
792 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
794 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
795 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
796 * works on both 32 and 64 bit systems. On 32 bit systems the readout
797 * covers ~136 years of uptime which should be enough to prevent
798 * premature wrap arounds.
800 time64_t ktime_get_seconds(void)
802 struct timekeeper *tk = &tk_core.timekeeper;
804 WARN_ON(timekeeping_suspended);
805 return tk->ktime_sec;
807 EXPORT_SYMBOL_GPL(ktime_get_seconds);
810 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
812 * Returns the wall clock seconds since 1970. This replaces the
813 * get_seconds() interface which is not y2038 safe on 32bit systems.
815 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
816 * 32bit systems the access must be protected with the sequence
817 * counter to provide "atomic" access to the 64bit tk->xtime_sec
820 time64_t ktime_get_real_seconds(void)
822 struct timekeeper *tk = &tk_core.timekeeper;
826 if (IS_ENABLED(CONFIG_64BIT))
827 return tk->xtime_sec;
830 seq = read_seqcount_begin(&tk_core.seq);
831 seconds = tk->xtime_sec;
833 } while (read_seqcount_retry(&tk_core.seq, seq));
837 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
839 #ifdef CONFIG_NTP_PPS
842 * getnstime_raw_and_real - get day and raw monotonic time in timespec format
843 * @ts_raw: pointer to the timespec to be set to raw monotonic time
844 * @ts_real: pointer to the timespec to be set to the time of day
846 * This function reads both the time of day and raw monotonic time at the
847 * same time atomically and stores the resulting timestamps in timespec
850 void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
852 struct timekeeper *tk = &tk_core.timekeeper;
854 s64 nsecs_raw, nsecs_real;
856 WARN_ON_ONCE(timekeeping_suspended);
859 seq = read_seqcount_begin(&tk_core.seq);
861 *ts_raw = timespec64_to_timespec(tk->raw_time);
862 ts_real->tv_sec = tk->xtime_sec;
863 ts_real->tv_nsec = 0;
865 nsecs_raw = timekeeping_get_ns_raw(tk);
866 nsecs_real = timekeeping_get_ns(&tk->tkr);
868 } while (read_seqcount_retry(&tk_core.seq, seq));
870 timespec_add_ns(ts_raw, nsecs_raw);
871 timespec_add_ns(ts_real, nsecs_real);
873 EXPORT_SYMBOL(getnstime_raw_and_real);
875 #endif /* CONFIG_NTP_PPS */
878 * do_gettimeofday - Returns the time of day in a timeval
879 * @tv: pointer to the timeval to be set
881 * NOTE: Users should be converted to using getnstimeofday()
883 void do_gettimeofday(struct timeval *tv)
885 struct timespec64 now;
887 getnstimeofday64(&now);
888 tv->tv_sec = now.tv_sec;
889 tv->tv_usec = now.tv_nsec/1000;
891 EXPORT_SYMBOL(do_gettimeofday);
894 * do_settimeofday64 - Sets the time of day.
895 * @ts: pointer to the timespec64 variable containing the new time
897 * Sets the time of day to the new time and update NTP and notify hrtimers
899 int do_settimeofday64(const struct timespec64 *ts)
901 struct timekeeper *tk = &tk_core.timekeeper;
902 struct timespec64 ts_delta, xt;
905 if (!timespec64_valid_strict(ts))
908 raw_spin_lock_irqsave(&timekeeper_lock, flags);
909 write_seqcount_begin(&tk_core.seq);
911 timekeeping_forward_now(tk);
914 ts_delta.tv_sec = ts->tv_sec - xt.tv_sec;
915 ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
917 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
919 tk_set_xtime(tk, ts);
921 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
923 write_seqcount_end(&tk_core.seq);
924 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
926 /* signal hrtimers about time change */
931 EXPORT_SYMBOL(do_settimeofday64);
934 * timekeeping_inject_offset - Adds or subtracts from the current time.
935 * @tv: pointer to the timespec variable containing the offset
937 * Adds or subtracts an offset value from the current time.
939 int timekeeping_inject_offset(struct timespec *ts)
941 struct timekeeper *tk = &tk_core.timekeeper;
943 struct timespec64 ts64, tmp;
946 if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
949 ts64 = timespec_to_timespec64(*ts);
951 raw_spin_lock_irqsave(&timekeeper_lock, flags);
952 write_seqcount_begin(&tk_core.seq);
954 timekeeping_forward_now(tk);
956 /* Make sure the proposed value is valid */
957 tmp = timespec64_add(tk_xtime(tk), ts64);
958 if (!timespec64_valid_strict(&tmp)) {
963 tk_xtime_add(tk, &ts64);
964 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
966 error: /* even if we error out, we forwarded the time, so call update */
967 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
969 write_seqcount_end(&tk_core.seq);
970 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
972 /* signal hrtimers about time change */
977 EXPORT_SYMBOL(timekeeping_inject_offset);
981 * timekeeping_get_tai_offset - Returns current TAI offset from UTC
984 s32 timekeeping_get_tai_offset(void)
986 struct timekeeper *tk = &tk_core.timekeeper;
991 seq = read_seqcount_begin(&tk_core.seq);
992 ret = tk->tai_offset;
993 } while (read_seqcount_retry(&tk_core.seq, seq));
999 * __timekeeping_set_tai_offset - Lock free worker function
1002 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1004 tk->tai_offset = tai_offset;
1005 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1009 * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
1012 void timekeeping_set_tai_offset(s32 tai_offset)
1014 struct timekeeper *tk = &tk_core.timekeeper;
1015 unsigned long flags;
1017 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1018 write_seqcount_begin(&tk_core.seq);
1019 __timekeeping_set_tai_offset(tk, tai_offset);
1020 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1021 write_seqcount_end(&tk_core.seq);
1022 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1027 * change_clocksource - Swaps clocksources if a new one is available
1029 * Accumulates current time interval and initializes new clocksource
1031 static int change_clocksource(void *data)
1033 struct timekeeper *tk = &tk_core.timekeeper;
1034 struct clocksource *new, *old;
1035 unsigned long flags;
1037 new = (struct clocksource *) data;
1039 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1040 write_seqcount_begin(&tk_core.seq);
1042 timekeeping_forward_now(tk);
1044 * If the cs is in module, get a module reference. Succeeds
1045 * for built-in code (owner == NULL) as well.
1047 if (try_module_get(new->owner)) {
1048 if (!new->enable || new->enable(new) == 0) {
1049 old = tk->tkr.clock;
1050 tk_setup_internals(tk, new);
1053 module_put(old->owner);
1055 module_put(new->owner);
1058 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1060 write_seqcount_end(&tk_core.seq);
1061 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1067 * timekeeping_notify - Install a new clock source
1068 * @clock: pointer to the clock source
1070 * This function is called from clocksource.c after a new, better clock
1071 * source has been registered. The caller holds the clocksource_mutex.
1073 int timekeeping_notify(struct clocksource *clock)
1075 struct timekeeper *tk = &tk_core.timekeeper;
1077 if (tk->tkr.clock == clock)
1079 stop_machine(change_clocksource, clock, NULL);
1080 tick_clock_notify();
1081 return tk->tkr.clock == clock ? 0 : -1;
1085 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1086 * @ts: pointer to the timespec64 to be set
1088 * Returns the raw monotonic time (completely un-modified by ntp)
1090 void getrawmonotonic64(struct timespec64 *ts)
1092 struct timekeeper *tk = &tk_core.timekeeper;
1093 struct timespec64 ts64;
1098 seq = read_seqcount_begin(&tk_core.seq);
1099 nsecs = timekeeping_get_ns_raw(tk);
1100 ts64 = tk->raw_time;
1102 } while (read_seqcount_retry(&tk_core.seq, seq));
1104 timespec64_add_ns(&ts64, nsecs);
1107 EXPORT_SYMBOL(getrawmonotonic64);
1111 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1113 int timekeeping_valid_for_hres(void)
1115 struct timekeeper *tk = &tk_core.timekeeper;
1120 seq = read_seqcount_begin(&tk_core.seq);
1122 ret = tk->tkr.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1124 } while (read_seqcount_retry(&tk_core.seq, seq));
1130 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1132 u64 timekeeping_max_deferment(void)
1134 struct timekeeper *tk = &tk_core.timekeeper;
1139 seq = read_seqcount_begin(&tk_core.seq);
1141 ret = tk->tkr.clock->max_idle_ns;
1143 } while (read_seqcount_retry(&tk_core.seq, seq));
1149 * read_persistent_clock - Return time from the persistent clock.
1151 * Weak dummy function for arches that do not yet support it.
1152 * Reads the time from the battery backed persistent clock.
1153 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1155 * XXX - Do be sure to remove it once all arches implement it.
1157 void __weak read_persistent_clock(struct timespec *ts)
1164 * read_boot_clock - Return time of the system start.
1166 * Weak dummy function for arches that do not yet support it.
1167 * Function to read the exact time the system has been started.
1168 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1170 * XXX - Do be sure to remove it once all arches implement it.
1172 void __weak read_boot_clock(struct timespec *ts)
1179 * timekeeping_init - Initializes the clocksource and common timekeeping values
1181 void __init timekeeping_init(void)
1183 struct timekeeper *tk = &tk_core.timekeeper;
1184 struct clocksource *clock;
1185 unsigned long flags;
1186 struct timespec64 now, boot, tmp;
1189 read_persistent_clock(&ts);
1190 now = timespec_to_timespec64(ts);
1191 if (!timespec64_valid_strict(&now)) {
1192 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1193 " Check your CMOS/BIOS settings.\n");
1196 } else if (now.tv_sec || now.tv_nsec)
1197 persistent_clock_exist = true;
1199 read_boot_clock(&ts);
1200 boot = timespec_to_timespec64(ts);
1201 if (!timespec64_valid_strict(&boot)) {
1202 pr_warn("WARNING: Boot clock returned invalid value!\n"
1203 " Check your CMOS/BIOS settings.\n");
1208 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1209 write_seqcount_begin(&tk_core.seq);
1212 clock = clocksource_default_clock();
1214 clock->enable(clock);
1215 tk_setup_internals(tk, clock);
1217 tk_set_xtime(tk, &now);
1218 tk->raw_time.tv_sec = 0;
1219 tk->raw_time.tv_nsec = 0;
1220 tk->base_raw.tv64 = 0;
1221 if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1222 boot = tk_xtime(tk);
1224 set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1225 tk_set_wall_to_mono(tk, tmp);
1227 timekeeping_update(tk, TK_MIRROR);
1229 write_seqcount_end(&tk_core.seq);
1230 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1233 /* time in seconds when suspend began */
1234 static struct timespec64 timekeeping_suspend_time;
1237 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1238 * @delta: pointer to a timespec delta value
1240 * Takes a timespec offset measuring a suspend interval and properly
1241 * adds the sleep offset to the timekeeping variables.
1243 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1244 struct timespec64 *delta)
1246 if (!timespec64_valid_strict(delta)) {
1247 printk_deferred(KERN_WARNING
1248 "__timekeeping_inject_sleeptime: Invalid "
1249 "sleep delta value!\n");
1252 tk_xtime_add(tk, delta);
1253 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1254 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1255 tk_debug_account_sleep_time(delta);
1259 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1260 * @delta: pointer to a timespec64 delta value
1262 * This hook is for architectures that cannot support read_persistent_clock
1263 * because their RTC/persistent clock is only accessible when irqs are enabled.
1265 * This function should only be called by rtc_resume(), and allows
1266 * a suspend offset to be injected into the timekeeping values.
1268 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1270 struct timekeeper *tk = &tk_core.timekeeper;
1271 unsigned long flags;
1274 * Make sure we don't set the clock twice, as timekeeping_resume()
1277 if (has_persistent_clock())
1280 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1281 write_seqcount_begin(&tk_core.seq);
1283 timekeeping_forward_now(tk);
1285 __timekeeping_inject_sleeptime(tk, delta);
1287 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1289 write_seqcount_end(&tk_core.seq);
1290 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1292 /* signal hrtimers about time change */
1297 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1299 * This is for the generic clocksource timekeeping.
1300 * xtime/wall_to_monotonic/jiffies/etc are
1301 * still managed by arch specific suspend/resume code.
1303 void timekeeping_resume(void)
1305 struct timekeeper *tk = &tk_core.timekeeper;
1306 struct clocksource *clock = tk->tkr.clock;
1307 unsigned long flags;
1308 struct timespec64 ts_new, ts_delta;
1309 struct timespec tmp;
1310 cycle_t cycle_now, cycle_delta;
1311 bool suspendtime_found = false;
1313 read_persistent_clock(&tmp);
1314 ts_new = timespec_to_timespec64(tmp);
1316 clockevents_resume();
1317 clocksource_resume();
1319 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1320 write_seqcount_begin(&tk_core.seq);
1323 * After system resumes, we need to calculate the suspended time and
1324 * compensate it for the OS time. There are 3 sources that could be
1325 * used: Nonstop clocksource during suspend, persistent clock and rtc
1328 * One specific platform may have 1 or 2 or all of them, and the
1329 * preference will be:
1330 * suspend-nonstop clocksource -> persistent clock -> rtc
1331 * The less preferred source will only be tried if there is no better
1332 * usable source. The rtc part is handled separately in rtc core code.
1334 cycle_now = tk->tkr.read(clock);
1335 if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1336 cycle_now > tk->tkr.cycle_last) {
1337 u64 num, max = ULLONG_MAX;
1338 u32 mult = clock->mult;
1339 u32 shift = clock->shift;
1342 cycle_delta = clocksource_delta(cycle_now, tk->tkr.cycle_last,
1346 * "cycle_delta * mutl" may cause 64 bits overflow, if the
1347 * suspended time is too long. In that case we need do the
1348 * 64 bits math carefully
1351 if (cycle_delta > max) {
1352 num = div64_u64(cycle_delta, max);
1353 nsec = (((u64) max * mult) >> shift) * num;
1354 cycle_delta -= num * max;
1356 nsec += ((u64) cycle_delta * mult) >> shift;
1358 ts_delta = ns_to_timespec64(nsec);
1359 suspendtime_found = true;
1360 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1361 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1362 suspendtime_found = true;
1365 if (suspendtime_found)
1366 __timekeeping_inject_sleeptime(tk, &ts_delta);
1368 /* Re-base the last cycle value */
1369 tk->tkr.cycle_last = cycle_now;
1371 timekeeping_suspended = 0;
1372 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1373 write_seqcount_end(&tk_core.seq);
1374 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1376 touch_softlockup_watchdog();
1378 clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
1380 /* Resume hrtimers */
1384 int timekeeping_suspend(void)
1386 struct timekeeper *tk = &tk_core.timekeeper;
1387 unsigned long flags;
1388 struct timespec64 delta, delta_delta;
1389 static struct timespec64 old_delta;
1390 struct timespec tmp;
1392 read_persistent_clock(&tmp);
1393 timekeeping_suspend_time = timespec_to_timespec64(tmp);
1396 * On some systems the persistent_clock can not be detected at
1397 * timekeeping_init by its return value, so if we see a valid
1398 * value returned, update the persistent_clock_exists flag.
1400 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1401 persistent_clock_exist = true;
1403 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1404 write_seqcount_begin(&tk_core.seq);
1405 timekeeping_forward_now(tk);
1406 timekeeping_suspended = 1;
1409 * To avoid drift caused by repeated suspend/resumes,
1410 * which each can add ~1 second drift error,
1411 * try to compensate so the difference in system time
1412 * and persistent_clock time stays close to constant.
1414 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1415 delta_delta = timespec64_sub(delta, old_delta);
1416 if (abs(delta_delta.tv_sec) >= 2) {
1418 * if delta_delta is too large, assume time correction
1419 * has occured and set old_delta to the current delta.
1423 /* Otherwise try to adjust old_system to compensate */
1424 timekeeping_suspend_time =
1425 timespec64_add(timekeeping_suspend_time, delta_delta);
1428 timekeeping_update(tk, TK_MIRROR);
1429 halt_fast_timekeeper(tk);
1430 write_seqcount_end(&tk_core.seq);
1431 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1433 clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
1434 clocksource_suspend();
1435 clockevents_suspend();
1440 /* sysfs resume/suspend bits for timekeeping */
1441 static struct syscore_ops timekeeping_syscore_ops = {
1442 .resume = timekeeping_resume,
1443 .suspend = timekeeping_suspend,
1446 static int __init timekeeping_init_ops(void)
1448 register_syscore_ops(&timekeeping_syscore_ops);
1451 device_initcall(timekeeping_init_ops);
1454 * Apply a multiplier adjustment to the timekeeper
1456 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1461 s64 interval = tk->cycle_interval;
1465 mult_adj = -mult_adj;
1466 interval = -interval;
1469 mult_adj <<= adj_scale;
1470 interval <<= adj_scale;
1471 offset <<= adj_scale;
1474 * So the following can be confusing.
1476 * To keep things simple, lets assume mult_adj == 1 for now.
1478 * When mult_adj != 1, remember that the interval and offset values
1479 * have been appropriately scaled so the math is the same.
1481 * The basic idea here is that we're increasing the multiplier
1482 * by one, this causes the xtime_interval to be incremented by
1483 * one cycle_interval. This is because:
1484 * xtime_interval = cycle_interval * mult
1485 * So if mult is being incremented by one:
1486 * xtime_interval = cycle_interval * (mult + 1)
1488 * xtime_interval = (cycle_interval * mult) + cycle_interval
1489 * Which can be shortened to:
1490 * xtime_interval += cycle_interval
1492 * So offset stores the non-accumulated cycles. Thus the current
1493 * time (in shifted nanoseconds) is:
1494 * now = (offset * adj) + xtime_nsec
1495 * Now, even though we're adjusting the clock frequency, we have
1496 * to keep time consistent. In other words, we can't jump back
1497 * in time, and we also want to avoid jumping forward in time.
1499 * So given the same offset value, we need the time to be the same
1500 * both before and after the freq adjustment.
1501 * now = (offset * adj_1) + xtime_nsec_1
1502 * now = (offset * adj_2) + xtime_nsec_2
1504 * (offset * adj_1) + xtime_nsec_1 =
1505 * (offset * adj_2) + xtime_nsec_2
1509 * (offset * adj_1) + xtime_nsec_1 =
1510 * (offset * (adj_1+1)) + xtime_nsec_2
1511 * (offset * adj_1) + xtime_nsec_1 =
1512 * (offset * adj_1) + offset + xtime_nsec_2
1513 * Canceling the sides:
1514 * xtime_nsec_1 = offset + xtime_nsec_2
1516 * xtime_nsec_2 = xtime_nsec_1 - offset
1517 * Which simplfies to:
1518 * xtime_nsec -= offset
1520 * XXX - TODO: Doc ntp_error calculation.
1522 if ((mult_adj > 0) && (tk->tkr.mult + mult_adj < mult_adj)) {
1523 /* NTP adjustment caused clocksource mult overflow */
1528 tk->tkr.mult += mult_adj;
1529 tk->xtime_interval += interval;
1530 tk->tkr.xtime_nsec -= offset;
1531 tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1535 * Calculate the multiplier adjustment needed to match the frequency
1538 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1541 s64 interval = tk->cycle_interval;
1542 s64 xinterval = tk->xtime_interval;
1547 /* Remove any current error adj from freq calculation */
1548 if (tk->ntp_err_mult)
1549 xinterval -= tk->cycle_interval;
1551 tk->ntp_tick = ntp_tick_length();
1553 /* Calculate current error per tick */
1554 tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1555 tick_error -= (xinterval + tk->xtime_remainder);
1557 /* Don't worry about correcting it if its small */
1558 if (likely((tick_error >= 0) && (tick_error <= interval)))
1561 /* preserve the direction of correction */
1562 negative = (tick_error < 0);
1564 /* Sort out the magnitude of the correction */
1565 tick_error = abs(tick_error);
1566 for (adj = 0; tick_error > interval; adj++)
1569 /* scale the corrections */
1570 timekeeping_apply_adjustment(tk, offset, negative, adj);
1574 * Adjust the timekeeper's multiplier to the correct frequency
1575 * and also to reduce the accumulated error value.
1577 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1579 /* Correct for the current frequency error */
1580 timekeeping_freqadjust(tk, offset);
1582 /* Next make a small adjustment to fix any cumulative error */
1583 if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1584 tk->ntp_err_mult = 1;
1585 timekeeping_apply_adjustment(tk, offset, 0, 0);
1586 } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1587 /* Undo any existing error adjustment */
1588 timekeeping_apply_adjustment(tk, offset, 1, 0);
1589 tk->ntp_err_mult = 0;
1592 if (unlikely(tk->tkr.clock->maxadj &&
1593 (abs(tk->tkr.mult - tk->tkr.clock->mult)
1594 > tk->tkr.clock->maxadj))) {
1595 printk_once(KERN_WARNING
1596 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1597 tk->tkr.clock->name, (long)tk->tkr.mult,
1598 (long)tk->tkr.clock->mult + tk->tkr.clock->maxadj);
1602 * It may be possible that when we entered this function, xtime_nsec
1603 * was very small. Further, if we're slightly speeding the clocksource
1604 * in the code above, its possible the required corrective factor to
1605 * xtime_nsec could cause it to underflow.
1607 * Now, since we already accumulated the second, cannot simply roll
1608 * the accumulated second back, since the NTP subsystem has been
1609 * notified via second_overflow. So instead we push xtime_nsec forward
1610 * by the amount we underflowed, and add that amount into the error.
1612 * We'll correct this error next time through this function, when
1613 * xtime_nsec is not as small.
1615 if (unlikely((s64)tk->tkr.xtime_nsec < 0)) {
1616 s64 neg = -(s64)tk->tkr.xtime_nsec;
1617 tk->tkr.xtime_nsec = 0;
1618 tk->ntp_error += neg << tk->ntp_error_shift;
1623 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1625 * Helper function that accumulates a the nsecs greater then a second
1626 * from the xtime_nsec field to the xtime_secs field.
1627 * It also calls into the NTP code to handle leapsecond processing.
1630 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
1632 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr.shift;
1633 unsigned int clock_set = 0;
1635 while (tk->tkr.xtime_nsec >= nsecps) {
1638 tk->tkr.xtime_nsec -= nsecps;
1641 /* Figure out if its a leap sec and apply if needed */
1642 leap = second_overflow(tk->xtime_sec);
1643 if (unlikely(leap)) {
1644 struct timespec64 ts;
1646 tk->xtime_sec += leap;
1650 tk_set_wall_to_mono(tk,
1651 timespec64_sub(tk->wall_to_monotonic, ts));
1653 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1655 clock_set = TK_CLOCK_WAS_SET;
1662 * logarithmic_accumulation - shifted accumulation of cycles
1664 * This functions accumulates a shifted interval of cycles into
1665 * into a shifted interval nanoseconds. Allows for O(log) accumulation
1668 * Returns the unconsumed cycles.
1670 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1672 unsigned int *clock_set)
1674 cycle_t interval = tk->cycle_interval << shift;
1677 /* If the offset is smaller then a shifted interval, do nothing */
1678 if (offset < interval)
1681 /* Accumulate one shifted interval */
1683 tk->tkr.cycle_last += interval;
1685 tk->tkr.xtime_nsec += tk->xtime_interval << shift;
1686 *clock_set |= accumulate_nsecs_to_secs(tk);
1688 /* Accumulate raw time */
1689 raw_nsecs = (u64)tk->raw_interval << shift;
1690 raw_nsecs += tk->raw_time.tv_nsec;
1691 if (raw_nsecs >= NSEC_PER_SEC) {
1692 u64 raw_secs = raw_nsecs;
1693 raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
1694 tk->raw_time.tv_sec += raw_secs;
1696 tk->raw_time.tv_nsec = raw_nsecs;
1698 /* Accumulate error between NTP and clock interval */
1699 tk->ntp_error += tk->ntp_tick << shift;
1700 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1701 (tk->ntp_error_shift + shift);
1707 * update_wall_time - Uses the current clocksource to increment the wall time
1710 void update_wall_time(void)
1712 struct timekeeper *real_tk = &tk_core.timekeeper;
1713 struct timekeeper *tk = &shadow_timekeeper;
1715 int shift = 0, maxshift;
1716 unsigned int clock_set = 0;
1717 unsigned long flags;
1719 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1721 /* Make sure we're fully resumed: */
1722 if (unlikely(timekeeping_suspended))
1725 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1726 offset = real_tk->cycle_interval;
1728 offset = clocksource_delta(tk->tkr.read(tk->tkr.clock),
1729 tk->tkr.cycle_last, tk->tkr.mask);
1732 /* Check if there's really nothing to do */
1733 if (offset < real_tk->cycle_interval)
1736 /* Do some additional sanity checking */
1737 timekeeping_check_update(real_tk, offset);
1740 * With NO_HZ we may have to accumulate many cycle_intervals
1741 * (think "ticks") worth of time at once. To do this efficiently,
1742 * we calculate the largest doubling multiple of cycle_intervals
1743 * that is smaller than the offset. We then accumulate that
1744 * chunk in one go, and then try to consume the next smaller
1747 shift = ilog2(offset) - ilog2(tk->cycle_interval);
1748 shift = max(0, shift);
1749 /* Bound shift to one less than what overflows tick_length */
1750 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1751 shift = min(shift, maxshift);
1752 while (offset >= tk->cycle_interval) {
1753 offset = logarithmic_accumulation(tk, offset, shift,
1755 if (offset < tk->cycle_interval<<shift)
1759 /* correct the clock when NTP error is too big */
1760 timekeeping_adjust(tk, offset);
1763 * XXX This can be killed once everyone converts
1764 * to the new update_vsyscall.
1766 old_vsyscall_fixup(tk);
1769 * Finally, make sure that after the rounding
1770 * xtime_nsec isn't larger than NSEC_PER_SEC
1772 clock_set |= accumulate_nsecs_to_secs(tk);
1774 write_seqcount_begin(&tk_core.seq);
1776 * Update the real timekeeper.
1778 * We could avoid this memcpy by switching pointers, but that
1779 * requires changes to all other timekeeper usage sites as
1780 * well, i.e. move the timekeeper pointer getter into the
1781 * spinlocked/seqcount protected sections. And we trade this
1782 * memcpy under the tk_core.seq against one before we start
1785 memcpy(real_tk, tk, sizeof(*tk));
1786 timekeeping_update(real_tk, clock_set);
1787 write_seqcount_end(&tk_core.seq);
1789 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1791 /* Have to call _delayed version, since in irq context*/
1792 clock_was_set_delayed();
1796 * getboottime64 - Return the real time of system boot.
1797 * @ts: pointer to the timespec64 to be set
1799 * Returns the wall-time of boot in a timespec64.
1801 * This is based on the wall_to_monotonic offset and the total suspend
1802 * time. Calls to settimeofday will affect the value returned (which
1803 * basically means that however wrong your real time clock is at boot time,
1804 * you get the right time here).
1806 void getboottime64(struct timespec64 *ts)
1808 struct timekeeper *tk = &tk_core.timekeeper;
1809 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
1811 *ts = ktime_to_timespec64(t);
1813 EXPORT_SYMBOL_GPL(getboottime64);
1815 unsigned long get_seconds(void)
1817 struct timekeeper *tk = &tk_core.timekeeper;
1819 return tk->xtime_sec;
1821 EXPORT_SYMBOL(get_seconds);
1823 struct timespec __current_kernel_time(void)
1825 struct timekeeper *tk = &tk_core.timekeeper;
1827 return timespec64_to_timespec(tk_xtime(tk));
1830 struct timespec current_kernel_time(void)
1832 struct timekeeper *tk = &tk_core.timekeeper;
1833 struct timespec64 now;
1837 seq = read_seqcount_begin(&tk_core.seq);
1840 } while (read_seqcount_retry(&tk_core.seq, seq));
1842 return timespec64_to_timespec(now);
1844 EXPORT_SYMBOL(current_kernel_time);
1846 struct timespec64 get_monotonic_coarse64(void)
1848 struct timekeeper *tk = &tk_core.timekeeper;
1849 struct timespec64 now, mono;
1853 seq = read_seqcount_begin(&tk_core.seq);
1856 mono = tk->wall_to_monotonic;
1857 } while (read_seqcount_retry(&tk_core.seq, seq));
1859 set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
1860 now.tv_nsec + mono.tv_nsec);
1866 * Must hold jiffies_lock
1868 void do_timer(unsigned long ticks)
1870 jiffies_64 += ticks;
1871 calc_global_load(ticks);
1875 * ktime_get_update_offsets_tick - hrtimer helper
1876 * @offs_real: pointer to storage for monotonic -> realtime offset
1877 * @offs_boot: pointer to storage for monotonic -> boottime offset
1878 * @offs_tai: pointer to storage for monotonic -> clock tai offset
1880 * Returns monotonic time at last tick and various offsets
1882 ktime_t ktime_get_update_offsets_tick(ktime_t *offs_real, ktime_t *offs_boot,
1885 struct timekeeper *tk = &tk_core.timekeeper;
1891 seq = read_seqcount_begin(&tk_core.seq);
1893 base = tk->tkr.base_mono;
1894 nsecs = tk->tkr.xtime_nsec >> tk->tkr.shift;
1896 *offs_real = tk->offs_real;
1897 *offs_boot = tk->offs_boot;
1898 *offs_tai = tk->offs_tai;
1899 } while (read_seqcount_retry(&tk_core.seq, seq));
1901 return ktime_add_ns(base, nsecs);
1904 #ifdef CONFIG_HIGH_RES_TIMERS
1906 * ktime_get_update_offsets_now - hrtimer helper
1907 * @offs_real: pointer to storage for monotonic -> realtime offset
1908 * @offs_boot: pointer to storage for monotonic -> boottime offset
1909 * @offs_tai: pointer to storage for monotonic -> clock tai offset
1911 * Returns current monotonic time and updates the offsets
1912 * Called from hrtimer_interrupt() or retrigger_next_event()
1914 ktime_t ktime_get_update_offsets_now(ktime_t *offs_real, ktime_t *offs_boot,
1917 struct timekeeper *tk = &tk_core.timekeeper;
1923 seq = read_seqcount_begin(&tk_core.seq);
1925 base = tk->tkr.base_mono;
1926 nsecs = timekeeping_get_ns(&tk->tkr);
1928 *offs_real = tk->offs_real;
1929 *offs_boot = tk->offs_boot;
1930 *offs_tai = tk->offs_tai;
1931 } while (read_seqcount_retry(&tk_core.seq, seq));
1933 return ktime_add_ns(base, nsecs);
1938 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
1940 int do_adjtimex(struct timex *txc)
1942 struct timekeeper *tk = &tk_core.timekeeper;
1943 unsigned long flags;
1944 struct timespec64 ts;
1948 /* Validate the data before disabling interrupts */
1949 ret = ntp_validate_timex(txc);
1953 if (txc->modes & ADJ_SETOFFSET) {
1954 struct timespec delta;
1955 delta.tv_sec = txc->time.tv_sec;
1956 delta.tv_nsec = txc->time.tv_usec;
1957 if (!(txc->modes & ADJ_NANO))
1958 delta.tv_nsec *= 1000;
1959 ret = timekeeping_inject_offset(&delta);
1964 getnstimeofday64(&ts);
1966 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1967 write_seqcount_begin(&tk_core.seq);
1969 orig_tai = tai = tk->tai_offset;
1970 ret = __do_adjtimex(txc, &ts, &tai);
1972 if (tai != orig_tai) {
1973 __timekeeping_set_tai_offset(tk, tai);
1974 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1976 write_seqcount_end(&tk_core.seq);
1977 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1979 if (tai != orig_tai)
1982 ntp_notify_cmos_timer();
1987 #ifdef CONFIG_NTP_PPS
1989 * hardpps() - Accessor function to NTP __hardpps function
1991 void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
1993 unsigned long flags;
1995 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1996 write_seqcount_begin(&tk_core.seq);
1998 __hardpps(phase_ts, raw_ts);
2000 write_seqcount_end(&tk_core.seq);
2001 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2003 EXPORT_SYMBOL(hardpps);
2007 * xtime_update() - advances the timekeeping infrastructure
2008 * @ticks: number of ticks, that have elapsed since the last call.
2010 * Must be called with interrupts disabled.
2012 void xtime_update(unsigned long ticks)
2014 write_seqlock(&jiffies_lock);
2016 write_sequnlock(&jiffies_lock);