1 // SPDX-License-Identifier: GPL-2.0
3 * Kernel timekeeping code and accessor functions. Based on code from
4 * timer.c, moved in commit 8524070b7982.
6 #include <linux/timekeeper_internal.h>
7 #include <linux/module.h>
8 #include <linux/interrupt.h>
9 #include <linux/percpu.h>
10 #include <linux/init.h>
12 #include <linux/nmi.h>
13 #include <linux/sched.h>
14 #include <linux/sched/loadavg.h>
15 #include <linux/sched/clock.h>
16 #include <linux/syscore_ops.h>
17 #include <linux/clocksource.h>
18 #include <linux/jiffies.h>
19 #include <linux/time.h>
20 #include <linux/timex.h>
21 #include <linux/tick.h>
22 #include <linux/stop_machine.h>
23 #include <linux/pvclock_gtod.h>
24 #include <linux/compiler.h>
25 #include <linux/audit.h>
26 #include <linux/random.h>
28 #include "tick-internal.h"
29 #include "ntp_internal.h"
30 #include "timekeeping_internal.h"
32 #define TK_CLEAR_NTP (1 << 0)
33 #define TK_CLOCK_WAS_SET (1 << 1)
35 #define TK_UPDATE_ALL (TK_CLEAR_NTP | TK_CLOCK_WAS_SET)
37 enum timekeeping_adv_mode {
38 /* Update timekeeper when a tick has passed */
41 /* Update timekeeper on a direct frequency change */
46 * The most important data for readout fits into a single 64 byte
50 seqcount_raw_spinlock_t seq;
51 struct timekeeper timekeeper;
52 struct timekeeper shadow_timekeeper;
54 } ____cacheline_aligned;
56 static struct tk_data tk_core;
58 /* flag for if timekeeping is suspended */
59 int __read_mostly timekeeping_suspended;
62 * struct tk_fast - NMI safe timekeeper
63 * @seq: Sequence counter for protecting updates. The lowest bit
64 * is the index for the tk_read_base array
65 * @base: tk_read_base array. Access is indexed by the lowest bit of
68 * See @update_fast_timekeeper() below.
72 struct tk_read_base base[2];
75 /* Suspend-time cycles value for halted fast timekeeper. */
76 static u64 cycles_at_suspend;
78 static u64 dummy_clock_read(struct clocksource *cs)
80 if (timekeeping_suspended)
81 return cycles_at_suspend;
85 static struct clocksource dummy_clock = {
86 .read = dummy_clock_read,
90 * Boot time initialization which allows local_clock() to be utilized
91 * during early boot when clocksources are not available. local_clock()
92 * returns nanoseconds already so no conversion is required, hence mult=1
93 * and shift=0. When the first proper clocksource is installed then
94 * the fast time keepers are updated with the correct values.
96 #define FAST_TK_INIT \
98 .clock = &dummy_clock, \
99 .mask = CLOCKSOURCE_MASK(64), \
104 static struct tk_fast tk_fast_mono ____cacheline_aligned = {
105 .seq = SEQCNT_LATCH_ZERO(tk_fast_mono.seq),
106 .base[0] = FAST_TK_INIT,
107 .base[1] = FAST_TK_INIT,
110 static struct tk_fast tk_fast_raw ____cacheline_aligned = {
111 .seq = SEQCNT_LATCH_ZERO(tk_fast_raw.seq),
112 .base[0] = FAST_TK_INIT,
113 .base[1] = FAST_TK_INIT,
116 unsigned long timekeeper_lock_irqsave(void)
120 raw_spin_lock_irqsave(&tk_core.lock, flags);
124 void timekeeper_unlock_irqrestore(unsigned long flags)
126 raw_spin_unlock_irqrestore(&tk_core.lock, flags);
130 * Multigrain timestamps require tracking the latest fine-grained timestamp
131 * that has been issued, and never returning a coarse-grained timestamp that is
132 * earlier than that value.
134 * mg_floor represents the latest fine-grained time that has been handed out as
135 * a file timestamp on the system. This is tracked as a monotonic ktime_t, and
136 * converted to a realtime clock value on an as-needed basis.
138 * Maintaining mg_floor ensures the multigrain interfaces never issue a
139 * timestamp earlier than one that has been previously issued.
141 * The exception to this rule is when there is a backward realtime clock jump. If
142 * such an event occurs, a timestamp can appear to be earlier than a previous one.
144 static __cacheline_aligned_in_smp atomic64_t mg_floor;
146 static inline void tk_normalize_xtime(struct timekeeper *tk)
148 while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
149 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
152 while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
153 tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
158 static inline struct timespec64 tk_xtime(const struct timekeeper *tk)
160 struct timespec64 ts;
162 ts.tv_sec = tk->xtime_sec;
163 ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
167 static inline struct timespec64 tk_xtime_coarse(const struct timekeeper *tk)
169 struct timespec64 ts;
171 ts.tv_sec = tk->xtime_sec;
172 ts.tv_nsec = tk->coarse_nsec;
177 * Update the nanoseconds part for the coarse time keepers. They can't rely
178 * on xtime_nsec because xtime_nsec could be adjusted by a small negative
179 * amount when the multiplication factor of the clock is adjusted, which
180 * could cause the coarse clocks to go slightly backwards. See
181 * timekeeping_apply_adjustment(). Thus we keep a separate copy for the coarse
182 * clockids which only is updated when the clock has been set or we have
185 static inline void tk_update_coarse_nsecs(struct timekeeper *tk)
187 tk->coarse_nsec = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
190 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
192 tk->xtime_sec = ts->tv_sec;
193 tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
194 tk_update_coarse_nsecs(tk);
197 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
199 tk->xtime_sec += ts->tv_sec;
200 tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
201 tk_normalize_xtime(tk);
202 tk_update_coarse_nsecs(tk);
205 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
207 struct timespec64 tmp;
210 * Verify consistency of: offset_real = -wall_to_monotonic
211 * before modifying anything
213 set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
214 -tk->wall_to_monotonic.tv_nsec);
215 WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
216 tk->wall_to_monotonic = wtm;
217 set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
218 /* Paired with READ_ONCE() in ktime_mono_to_any() */
219 WRITE_ONCE(tk->offs_real, timespec64_to_ktime(tmp));
220 WRITE_ONCE(tk->offs_tai, ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0)));
223 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
225 /* Paired with READ_ONCE() in ktime_mono_to_any() */
226 WRITE_ONCE(tk->offs_boot, ktime_add(tk->offs_boot, delta));
228 * Timespec representation for VDSO update to avoid 64bit division
231 tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot);
235 * tk_clock_read - atomic clocksource read() helper
237 * This helper is necessary to use in the read paths because, while the
238 * seqcount ensures we don't return a bad value while structures are updated,
239 * it doesn't protect from potential crashes. There is the possibility that
240 * the tkr's clocksource may change between the read reference, and the
241 * clock reference passed to the read function. This can cause crashes if
242 * the wrong clocksource is passed to the wrong read function.
243 * This isn't necessary to use when holding the tk_core.lock or doing
244 * a read of the fast-timekeeper tkrs (which is protected by its own locking
247 static inline u64 tk_clock_read(const struct tk_read_base *tkr)
249 struct clocksource *clock = READ_ONCE(tkr->clock);
251 return clock->read(clock);
255 * tk_setup_internals - Set up internals to use clocksource clock.
257 * @tk: The target timekeeper to setup.
258 * @clock: Pointer to clocksource.
260 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
261 * pair and interval request.
263 * Unless you're the timekeeping code, you should not be using this!
265 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
268 u64 tmp, ntpinterval;
269 struct clocksource *old_clock;
271 ++tk->cs_was_changed_seq;
272 old_clock = tk->tkr_mono.clock;
273 tk->tkr_mono.clock = clock;
274 tk->tkr_mono.mask = clock->mask;
275 tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
277 tk->tkr_raw.clock = clock;
278 tk->tkr_raw.mask = clock->mask;
279 tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
281 /* Do the ns -> cycle conversion first, using original mult */
282 tmp = NTP_INTERVAL_LENGTH;
283 tmp <<= clock->shift;
285 tmp += clock->mult/2;
286 do_div(tmp, clock->mult);
290 interval = (u64) tmp;
291 tk->cycle_interval = interval;
293 /* Go back from cycles -> shifted ns */
294 tk->xtime_interval = interval * clock->mult;
295 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
296 tk->raw_interval = interval * clock->mult;
298 /* if changing clocks, convert xtime_nsec shift units */
300 int shift_change = clock->shift - old_clock->shift;
301 if (shift_change < 0) {
302 tk->tkr_mono.xtime_nsec >>= -shift_change;
303 tk->tkr_raw.xtime_nsec >>= -shift_change;
305 tk->tkr_mono.xtime_nsec <<= shift_change;
306 tk->tkr_raw.xtime_nsec <<= shift_change;
310 tk->tkr_mono.shift = clock->shift;
311 tk->tkr_raw.shift = clock->shift;
314 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
315 tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
318 * The timekeeper keeps its own mult values for the currently
319 * active clocksource. These value will be adjusted via NTP
320 * to counteract clock drifting.
322 tk->tkr_mono.mult = clock->mult;
323 tk->tkr_raw.mult = clock->mult;
324 tk->ntp_err_mult = 0;
325 tk->skip_second_overflow = 0;
328 /* Timekeeper helper functions. */
329 static noinline u64 delta_to_ns_safe(const struct tk_read_base *tkr, u64 delta)
331 return mul_u64_u32_add_u64_shr(delta, tkr->mult, tkr->xtime_nsec, tkr->shift);
334 static inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles)
336 /* Calculate the delta since the last update_wall_time() */
337 u64 mask = tkr->mask, delta = (cycles - tkr->cycle_last) & mask;
340 * This detects both negative motion and the case where the delta
341 * overflows the multiplication with tkr->mult.
343 if (unlikely(delta > tkr->clock->max_cycles)) {
345 * Handle clocksource inconsistency between CPUs to prevent
346 * time from going backwards by checking for the MSB of the
347 * mask being set in the delta.
349 if (delta & ~(mask >> 1))
350 return tkr->xtime_nsec >> tkr->shift;
352 return delta_to_ns_safe(tkr, delta);
355 return ((delta * tkr->mult) + tkr->xtime_nsec) >> tkr->shift;
358 static __always_inline u64 timekeeping_get_ns(const struct tk_read_base *tkr)
360 return timekeeping_cycles_to_ns(tkr, tk_clock_read(tkr));
364 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
365 * @tkr: Timekeeping readout base from which we take the update
366 * @tkf: Pointer to NMI safe timekeeper
368 * We want to use this from any context including NMI and tracing /
369 * instrumenting the timekeeping code itself.
371 * Employ the latch technique; see @write_seqcount_latch.
373 * So if a NMI hits the update of base[0] then it will use base[1]
374 * which is still consistent. In the worst case this can result is a
375 * slightly wrong timestamp (a few nanoseconds). See
376 * @ktime_get_mono_fast_ns.
378 static void update_fast_timekeeper(const struct tk_read_base *tkr,
381 struct tk_read_base *base = tkf->base;
383 /* Force readers off to base[1] */
384 write_seqcount_latch_begin(&tkf->seq);
387 memcpy(base, tkr, sizeof(*base));
389 /* Force readers back to base[0] */
390 write_seqcount_latch(&tkf->seq);
393 memcpy(base + 1, base, sizeof(*base));
395 write_seqcount_latch_end(&tkf->seq);
398 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
400 struct tk_read_base *tkr;
405 seq = read_seqcount_latch(&tkf->seq);
406 tkr = tkf->base + (seq & 0x01);
407 now = ktime_to_ns(tkr->base);
408 now += timekeeping_get_ns(tkr);
409 } while (read_seqcount_latch_retry(&tkf->seq, seq));
415 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
417 * This timestamp is not guaranteed to be monotonic across an update.
418 * The timestamp is calculated by:
420 * now = base_mono + clock_delta * slope
422 * So if the update lowers the slope, readers who are forced to the
423 * not yet updated second array are still using the old steeper slope.
432 * |12345678---> reader order
438 * So reader 6 will observe time going backwards versus reader 5.
440 * While other CPUs are likely to be able to observe that, the only way
441 * for a CPU local observation is when an NMI hits in the middle of
442 * the update. Timestamps taken from that NMI context might be ahead
443 * of the following timestamps. Callers need to be aware of that and
446 u64 notrace ktime_get_mono_fast_ns(void)
448 return __ktime_get_fast_ns(&tk_fast_mono);
450 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
453 * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw
455 * Contrary to ktime_get_mono_fast_ns() this is always correct because the
456 * conversion factor is not affected by NTP/PTP correction.
458 u64 notrace ktime_get_raw_fast_ns(void)
460 return __ktime_get_fast_ns(&tk_fast_raw);
462 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
465 * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
467 * To keep it NMI safe since we're accessing from tracing, we're not using a
468 * separate timekeeper with updates to monotonic clock and boot offset
469 * protected with seqcounts. This has the following minor side effects:
471 * (1) Its possible that a timestamp be taken after the boot offset is updated
472 * but before the timekeeper is updated. If this happens, the new boot offset
473 * is added to the old timekeeping making the clock appear to update slightly
476 * timekeeping_inject_sleeptime64()
477 * __timekeeping_inject_sleeptime(tk, delta);
479 * timekeeping_update_staged(tkd, TK_CLEAR_NTP...);
481 * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
482 * partially updated. Since the tk->offs_boot update is a rare event, this
483 * should be a rare occurrence which postprocessing should be able to handle.
485 * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns()
488 u64 notrace ktime_get_boot_fast_ns(void)
490 struct timekeeper *tk = &tk_core.timekeeper;
492 return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot)));
494 EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
497 * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock.
499 * The same limitations as described for ktime_get_boot_fast_ns() apply. The
500 * mono time and the TAI offset are not read atomically which may yield wrong
501 * readouts. However, an update of the TAI offset is an rare event e.g., caused
502 * by settime or adjtimex with an offset. The user of this function has to deal
503 * with the possibility of wrong timestamps in post processing.
505 u64 notrace ktime_get_tai_fast_ns(void)
507 struct timekeeper *tk = &tk_core.timekeeper;
509 return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai)));
511 EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns);
514 * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
516 * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering.
518 u64 ktime_get_real_fast_ns(void)
520 struct tk_fast *tkf = &tk_fast_mono;
521 struct tk_read_base *tkr;
526 seq = raw_read_seqcount_latch(&tkf->seq);
527 tkr = tkf->base + (seq & 0x01);
528 baser = ktime_to_ns(tkr->base_real);
529 delta = timekeeping_get_ns(tkr);
530 } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
532 return baser + delta;
534 EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
537 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
538 * @tk: Timekeeper to snapshot.
540 * It generally is unsafe to access the clocksource after timekeeping has been
541 * suspended, so take a snapshot of the readout base of @tk and use it as the
542 * fast timekeeper's readout base while suspended. It will return the same
543 * number of cycles every time until timekeeping is resumed at which time the
544 * proper readout base for the fast timekeeper will be restored automatically.
546 static void halt_fast_timekeeper(const struct timekeeper *tk)
548 static struct tk_read_base tkr_dummy;
549 const struct tk_read_base *tkr = &tk->tkr_mono;
551 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
552 cycles_at_suspend = tk_clock_read(tkr);
553 tkr_dummy.clock = &dummy_clock;
554 tkr_dummy.base_real = tkr->base + tk->offs_real;
555 update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
558 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
559 tkr_dummy.clock = &dummy_clock;
560 update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
563 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
565 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
567 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
571 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
572 * @nb: Pointer to the notifier block to register
574 int pvclock_gtod_register_notifier(struct notifier_block *nb)
576 struct timekeeper *tk = &tk_core.timekeeper;
579 guard(raw_spinlock_irqsave)(&tk_core.lock);
580 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
581 update_pvclock_gtod(tk, true);
585 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
588 * pvclock_gtod_unregister_notifier - unregister a pvclock
589 * timedata update listener
590 * @nb: Pointer to the notifier block to unregister
592 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
594 guard(raw_spinlock_irqsave)(&tk_core.lock);
595 return raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
597 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
600 * tk_update_leap_state - helper to update the next_leap_ktime
602 static inline void tk_update_leap_state(struct timekeeper *tk)
604 tk->next_leap_ktime = ntp_get_next_leap();
605 if (tk->next_leap_ktime != KTIME_MAX)
606 /* Convert to monotonic time */
607 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
611 * Leap state update for both shadow and the real timekeeper
612 * Separate to spare a full memcpy() of the timekeeper.
614 static void tk_update_leap_state_all(struct tk_data *tkd)
616 write_seqcount_begin(&tkd->seq);
617 tk_update_leap_state(&tkd->shadow_timekeeper);
618 tkd->timekeeper.next_leap_ktime = tkd->shadow_timekeeper.next_leap_ktime;
619 write_seqcount_end(&tkd->seq);
623 * Update the ktime_t based scalar nsec members of the timekeeper
625 static inline void tk_update_ktime_data(struct timekeeper *tk)
631 * The xtime based monotonic readout is:
632 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
633 * The ktime based monotonic readout is:
634 * nsec = base_mono + now();
635 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
637 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
638 nsec = (u32) tk->wall_to_monotonic.tv_nsec;
639 tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
642 * The sum of the nanoseconds portions of xtime and
643 * wall_to_monotonic can be greater/equal one second. Take
644 * this into account before updating tk->ktime_sec.
646 nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
647 if (nsec >= NSEC_PER_SEC)
649 tk->ktime_sec = seconds;
651 /* Update the monotonic raw base */
652 tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
656 * Restore the shadow timekeeper from the real timekeeper.
658 static void timekeeping_restore_shadow(struct tk_data *tkd)
660 lockdep_assert_held(&tkd->lock);
661 memcpy(&tkd->shadow_timekeeper, &tkd->timekeeper, sizeof(tkd->timekeeper));
664 static void timekeeping_update_from_shadow(struct tk_data *tkd, unsigned int action)
666 struct timekeeper *tk = &tk_core.shadow_timekeeper;
668 lockdep_assert_held(&tkd->lock);
671 * Block out readers before running the updates below because that
672 * updates VDSO and other time related infrastructure. Not blocking
673 * the readers might let a reader see time going backwards when
674 * reading from the VDSO after the VDSO update and then reading in
675 * the kernel from the timekeeper before that got updated.
677 write_seqcount_begin(&tkd->seq);
679 if (action & TK_CLEAR_NTP) {
684 tk_update_leap_state(tk);
685 tk_update_ktime_data(tk);
688 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
690 tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
691 update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
692 update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
694 if (action & TK_CLOCK_WAS_SET)
695 tk->clock_was_set_seq++;
698 * Update the real timekeeper.
700 * We could avoid this memcpy() by switching pointers, but that has
701 * the downside that the reader side does not longer benefit from
702 * the cacheline optimized data layout of the timekeeper and requires
703 * another indirection.
705 memcpy(&tkd->timekeeper, tk, sizeof(*tk));
706 write_seqcount_end(&tkd->seq);
710 * timekeeping_forward_now - update clock to the current time
711 * @tk: Pointer to the timekeeper to update
713 * Forward the current clock to update its state since the last call to
714 * update_wall_time(). This is useful before significant clock changes,
715 * as it avoids having to deal with this time offset explicitly.
717 static void timekeeping_forward_now(struct timekeeper *tk)
719 u64 cycle_now, delta;
721 cycle_now = tk_clock_read(&tk->tkr_mono);
722 delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
723 tk->tkr_mono.clock->max_raw_delta);
724 tk->tkr_mono.cycle_last = cycle_now;
725 tk->tkr_raw.cycle_last = cycle_now;
728 u64 max = tk->tkr_mono.clock->max_cycles;
729 u64 incr = delta < max ? delta : max;
731 tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult;
732 tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult;
733 tk_normalize_xtime(tk);
736 tk_update_coarse_nsecs(tk);
740 * ktime_get_real_ts64 - Returns the time of day in a timespec64.
741 * @ts: pointer to the timespec to be set
743 * Returns the time of day in a timespec64 (WARN if suspended).
745 void ktime_get_real_ts64(struct timespec64 *ts)
747 struct timekeeper *tk = &tk_core.timekeeper;
751 WARN_ON(timekeeping_suspended);
754 seq = read_seqcount_begin(&tk_core.seq);
756 ts->tv_sec = tk->xtime_sec;
757 nsecs = timekeeping_get_ns(&tk->tkr_mono);
759 } while (read_seqcount_retry(&tk_core.seq, seq));
762 timespec64_add_ns(ts, nsecs);
764 EXPORT_SYMBOL(ktime_get_real_ts64);
766 ktime_t ktime_get(void)
768 struct timekeeper *tk = &tk_core.timekeeper;
773 WARN_ON(timekeeping_suspended);
776 seq = read_seqcount_begin(&tk_core.seq);
777 base = tk->tkr_mono.base;
778 nsecs = timekeeping_get_ns(&tk->tkr_mono);
780 } while (read_seqcount_retry(&tk_core.seq, seq));
782 return ktime_add_ns(base, nsecs);
784 EXPORT_SYMBOL_GPL(ktime_get);
786 u32 ktime_get_resolution_ns(void)
788 struct timekeeper *tk = &tk_core.timekeeper;
792 WARN_ON(timekeeping_suspended);
795 seq = read_seqcount_begin(&tk_core.seq);
796 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
797 } while (read_seqcount_retry(&tk_core.seq, seq));
801 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
803 static ktime_t *offsets[TK_OFFS_MAX] = {
804 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
805 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
806 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
809 ktime_t ktime_get_with_offset(enum tk_offsets offs)
811 struct timekeeper *tk = &tk_core.timekeeper;
813 ktime_t base, *offset = offsets[offs];
816 WARN_ON(timekeeping_suspended);
819 seq = read_seqcount_begin(&tk_core.seq);
820 base = ktime_add(tk->tkr_mono.base, *offset);
821 nsecs = timekeeping_get_ns(&tk->tkr_mono);
823 } while (read_seqcount_retry(&tk_core.seq, seq));
825 return ktime_add_ns(base, nsecs);
828 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
830 ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
832 struct timekeeper *tk = &tk_core.timekeeper;
833 ktime_t base, *offset = offsets[offs];
837 WARN_ON(timekeeping_suspended);
840 seq = read_seqcount_begin(&tk_core.seq);
841 base = ktime_add(tk->tkr_mono.base, *offset);
842 nsecs = tk->coarse_nsec;
844 } while (read_seqcount_retry(&tk_core.seq, seq));
846 return ktime_add_ns(base, nsecs);
848 EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
851 * ktime_mono_to_any() - convert monotonic time to any other time
852 * @tmono: time to convert.
853 * @offs: which offset to use
855 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
857 ktime_t *offset = offsets[offs];
861 if (IS_ENABLED(CONFIG_64BIT)) {
863 * Paired with WRITE_ONCE()s in tk_set_wall_to_mono() and
864 * tk_update_sleep_time().
866 return ktime_add(tmono, READ_ONCE(*offset));
870 seq = read_seqcount_begin(&tk_core.seq);
871 tconv = ktime_add(tmono, *offset);
872 } while (read_seqcount_retry(&tk_core.seq, seq));
876 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
879 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
881 ktime_t ktime_get_raw(void)
883 struct timekeeper *tk = &tk_core.timekeeper;
889 seq = read_seqcount_begin(&tk_core.seq);
890 base = tk->tkr_raw.base;
891 nsecs = timekeeping_get_ns(&tk->tkr_raw);
893 } while (read_seqcount_retry(&tk_core.seq, seq));
895 return ktime_add_ns(base, nsecs);
897 EXPORT_SYMBOL_GPL(ktime_get_raw);
900 * ktime_get_ts64 - get the monotonic clock in timespec64 format
901 * @ts: pointer to timespec variable
903 * The function calculates the monotonic clock from the realtime
904 * clock and the wall_to_monotonic offset and stores the result
905 * in normalized timespec64 format in the variable pointed to by @ts.
907 void ktime_get_ts64(struct timespec64 *ts)
909 struct timekeeper *tk = &tk_core.timekeeper;
910 struct timespec64 tomono;
914 WARN_ON(timekeeping_suspended);
917 seq = read_seqcount_begin(&tk_core.seq);
918 ts->tv_sec = tk->xtime_sec;
919 nsec = timekeeping_get_ns(&tk->tkr_mono);
920 tomono = tk->wall_to_monotonic;
922 } while (read_seqcount_retry(&tk_core.seq, seq));
924 ts->tv_sec += tomono.tv_sec;
926 timespec64_add_ns(ts, nsec + tomono.tv_nsec);
928 EXPORT_SYMBOL_GPL(ktime_get_ts64);
931 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
933 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
934 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
935 * works on both 32 and 64 bit systems. On 32 bit systems the readout
936 * covers ~136 years of uptime which should be enough to prevent
937 * premature wrap arounds.
939 time64_t ktime_get_seconds(void)
941 struct timekeeper *tk = &tk_core.timekeeper;
943 WARN_ON(timekeeping_suspended);
944 return tk->ktime_sec;
946 EXPORT_SYMBOL_GPL(ktime_get_seconds);
949 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
951 * Returns the wall clock seconds since 1970.
953 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
954 * 32bit systems the access must be protected with the sequence
955 * counter to provide "atomic" access to the 64bit tk->xtime_sec
958 time64_t ktime_get_real_seconds(void)
960 struct timekeeper *tk = &tk_core.timekeeper;
964 if (IS_ENABLED(CONFIG_64BIT))
965 return tk->xtime_sec;
968 seq = read_seqcount_begin(&tk_core.seq);
969 seconds = tk->xtime_sec;
971 } while (read_seqcount_retry(&tk_core.seq, seq));
975 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
978 * __ktime_get_real_seconds - The same as ktime_get_real_seconds
979 * but without the sequence counter protect. This internal function
980 * is called just when timekeeping lock is already held.
982 noinstr time64_t __ktime_get_real_seconds(void)
984 struct timekeeper *tk = &tk_core.timekeeper;
986 return tk->xtime_sec;
990 * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
991 * @systime_snapshot: pointer to struct receiving the system time snapshot
993 void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
995 struct timekeeper *tk = &tk_core.timekeeper;
1004 WARN_ON_ONCE(timekeeping_suspended);
1007 seq = read_seqcount_begin(&tk_core.seq);
1008 now = tk_clock_read(&tk->tkr_mono);
1009 systime_snapshot->cs_id = tk->tkr_mono.clock->id;
1010 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
1011 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
1012 base_real = ktime_add(tk->tkr_mono.base,
1013 tk_core.timekeeper.offs_real);
1014 base_boot = ktime_add(tk->tkr_mono.base,
1015 tk_core.timekeeper.offs_boot);
1016 base_raw = tk->tkr_raw.base;
1017 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
1018 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
1019 } while (read_seqcount_retry(&tk_core.seq, seq));
1021 systime_snapshot->cycles = now;
1022 systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
1023 systime_snapshot->boot = ktime_add_ns(base_boot, nsec_real);
1024 systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
1026 EXPORT_SYMBOL_GPL(ktime_get_snapshot);
1028 /* Scale base by mult/div checking for overflow */
1029 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
1033 tmp = div64_u64_rem(*base, div, &rem);
1035 if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
1036 ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
1040 rem = div64_u64(rem * mult, div);
1046 * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1047 * @history: Snapshot representing start of history
1048 * @partial_history_cycles: Cycle offset into history (fractional part)
1049 * @total_history_cycles: Total history length in cycles
1050 * @discontinuity: True indicates clock was set on history period
1051 * @ts: Cross timestamp that should be adjusted using
1052 * partial/total ratio
1054 * Helper function used by get_device_system_crosststamp() to correct the
1055 * crosstimestamp corresponding to the start of the current interval to the
1056 * system counter value (timestamp point) provided by the driver. The
1057 * total_history_* quantities are the total history starting at the provided
1058 * reference point and ending at the start of the current interval. The cycle
1059 * count between the driver timestamp point and the start of the current
1060 * interval is partial_history_cycles.
1062 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1063 u64 partial_history_cycles,
1064 u64 total_history_cycles,
1066 struct system_device_crosststamp *ts)
1068 struct timekeeper *tk = &tk_core.timekeeper;
1069 u64 corr_raw, corr_real;
1070 bool interp_forward;
1073 if (total_history_cycles == 0 || partial_history_cycles == 0)
1076 /* Interpolate shortest distance from beginning or end of history */
1077 interp_forward = partial_history_cycles > total_history_cycles / 2;
1078 partial_history_cycles = interp_forward ?
1079 total_history_cycles - partial_history_cycles :
1080 partial_history_cycles;
1083 * Scale the monotonic raw time delta by:
1084 * partial_history_cycles / total_history_cycles
1086 corr_raw = (u64)ktime_to_ns(
1087 ktime_sub(ts->sys_monoraw, history->raw));
1088 ret = scale64_check_overflow(partial_history_cycles,
1089 total_history_cycles, &corr_raw);
1094 * If there is a discontinuity in the history, scale monotonic raw
1096 * mult(real)/mult(raw) yielding the realtime correction
1097 * Otherwise, calculate the realtime correction similar to monotonic
1100 if (discontinuity) {
1101 corr_real = mul_u64_u32_div
1102 (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1104 corr_real = (u64)ktime_to_ns(
1105 ktime_sub(ts->sys_realtime, history->real));
1106 ret = scale64_check_overflow(partial_history_cycles,
1107 total_history_cycles, &corr_real);
1112 /* Fixup monotonic raw and real time time values */
1113 if (interp_forward) {
1114 ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1115 ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1117 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1118 ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1125 * timestamp_in_interval - true if ts is chronologically in [start, end]
1127 * True if ts occurs chronologically at or after start, and before or at end.
1129 static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
1131 if (ts >= start && ts <= end)
1133 if (start > end && (ts >= start || ts <= end))
1138 static bool convert_clock(u64 *val, u32 numerator, u32 denominator)
1142 if (!numerator || !denominator)
1145 res = div64_u64_rem(*val, denominator, &rem) * numerator;
1146 *val = res + div_u64(rem * numerator, denominator);
1150 static bool convert_base_to_cs(struct system_counterval_t *scv)
1152 struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1153 struct clocksource_base *base;
1156 /* The timestamp was taken from the time keeper clock source */
1157 if (cs->id == scv->cs_id)
1161 * Check whether cs_id matches the base clock. Prevent the compiler from
1162 * re-evaluating @base as the clocksource might change concurrently.
1164 base = READ_ONCE(cs->base);
1165 if (!base || base->id != scv->cs_id)
1168 num = scv->use_nsecs ? cs->freq_khz : base->numerator;
1169 den = scv->use_nsecs ? USEC_PER_SEC : base->denominator;
1171 if (!convert_clock(&scv->cycles, num, den))
1174 scv->cycles += base->offset;
1178 static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id)
1180 struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1181 struct clocksource_base *base;
1184 * Check whether base_id matches the base clock. Prevent the compiler from
1185 * re-evaluating @base as the clocksource might change concurrently.
1187 base = READ_ONCE(cs->base);
1188 if (!base || base->id != base_id)
1191 *cycles -= base->offset;
1192 if (!convert_clock(cycles, base->denominator, base->numerator))
1197 static bool convert_ns_to_cs(u64 *delta)
1199 struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
1201 if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta))
1204 *delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult);
1209 * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp
1210 * @treal: CLOCK_REALTIME timestamp to convert
1211 * @base_id: base clocksource id
1212 * @cycles: pointer to store the converted base clock timestamp
1214 * Converts a supplied, future realtime clock value to the corresponding base clock value.
1216 * Return: true if the conversion is successful, false otherwise.
1218 bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles)
1220 struct timekeeper *tk = &tk_core.timekeeper;
1225 seq = read_seqcount_begin(&tk_core.seq);
1226 if ((u64)treal < tk->tkr_mono.base_real)
1228 delta = (u64)treal - tk->tkr_mono.base_real;
1229 if (!convert_ns_to_cs(&delta))
1231 *cycles = tk->tkr_mono.cycle_last + delta;
1232 if (!convert_cs_to_base(cycles, base_id))
1234 } while (read_seqcount_retry(&tk_core.seq, seq));
1238 EXPORT_SYMBOL_GPL(ktime_real_to_base_clock);
1241 * get_device_system_crosststamp - Synchronously capture system/device timestamp
1242 * @get_time_fn: Callback to get simultaneous device time and
1243 * system counter from the device driver
1244 * @ctx: Context passed to get_time_fn()
1245 * @history_begin: Historical reference point used to interpolate system
1246 * time when counter provided by the driver is before the current interval
1247 * @xtstamp: Receives simultaneously captured system and device time
1249 * Reads a timestamp from a device and correlates it to system time
1251 int get_device_system_crosststamp(int (*get_time_fn)
1252 (ktime_t *device_time,
1253 struct system_counterval_t *sys_counterval,
1256 struct system_time_snapshot *history_begin,
1257 struct system_device_crosststamp *xtstamp)
1259 struct system_counterval_t system_counterval;
1260 struct timekeeper *tk = &tk_core.timekeeper;
1261 u64 cycles, now, interval_start;
1262 unsigned int clock_was_set_seq = 0;
1263 ktime_t base_real, base_raw;
1264 u64 nsec_real, nsec_raw;
1265 u8 cs_was_changed_seq;
1271 seq = read_seqcount_begin(&tk_core.seq);
1273 * Try to synchronously capture device time and a system
1274 * counter value calling back into the device driver
1276 ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1281 * Verify that the clocksource ID associated with the captured
1282 * system counter value is the same as for the currently
1283 * installed timekeeper clocksource
1285 if (system_counterval.cs_id == CSID_GENERIC ||
1286 !convert_base_to_cs(&system_counterval))
1288 cycles = system_counterval.cycles;
1291 * Check whether the system counter value provided by the
1292 * device driver is on the current timekeeping interval.
1294 now = tk_clock_read(&tk->tkr_mono);
1295 interval_start = tk->tkr_mono.cycle_last;
1296 if (!timestamp_in_interval(interval_start, now, cycles)) {
1297 clock_was_set_seq = tk->clock_was_set_seq;
1298 cs_was_changed_seq = tk->cs_was_changed_seq;
1299 cycles = interval_start;
1305 base_real = ktime_add(tk->tkr_mono.base,
1306 tk_core.timekeeper.offs_real);
1307 base_raw = tk->tkr_raw.base;
1309 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
1310 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
1311 } while (read_seqcount_retry(&tk_core.seq, seq));
1313 xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1314 xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1317 * Interpolate if necessary, adjusting back from the start of the
1321 u64 partial_history_cycles, total_history_cycles;
1325 * Check that the counter value is not before the provided
1326 * history reference and that the history doesn't cross a
1327 * clocksource change
1329 if (!history_begin ||
1330 !timestamp_in_interval(history_begin->cycles,
1331 cycles, system_counterval.cycles) ||
1332 history_begin->cs_was_changed_seq != cs_was_changed_seq)
1334 partial_history_cycles = cycles - system_counterval.cycles;
1335 total_history_cycles = cycles - history_begin->cycles;
1337 history_begin->clock_was_set_seq != clock_was_set_seq;
1339 ret = adjust_historical_crosststamp(history_begin,
1340 partial_history_cycles,
1341 total_history_cycles,
1342 discontinuity, xtstamp);
1349 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1352 * timekeeping_clocksource_has_base - Check whether the current clocksource
1353 * is based on given a base clock
1354 * @id: base clocksource ID
1356 * Note: The return value is a snapshot which can become invalid right
1357 * after the function returns.
1359 * Return: true if the timekeeper clocksource has a base clock with @id,
1362 bool timekeeping_clocksource_has_base(enum clocksource_ids id)
1365 * This is a snapshot, so no point in using the sequence
1366 * count. Just prevent the compiler from re-evaluating @base as the
1367 * clocksource might change concurrently.
1369 struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base);
1371 return base ? base->id == id : false;
1373 EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base);
1376 * do_settimeofday64 - Sets the time of day.
1377 * @ts: pointer to the timespec64 variable containing the new time
1379 * Sets the time of day to the new time and update NTP and notify hrtimers
1381 int do_settimeofday64(const struct timespec64 *ts)
1383 struct timespec64 ts_delta, xt;
1385 if (!timespec64_valid_settod(ts))
1388 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1389 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1391 timekeeping_forward_now(tks);
1394 ts_delta = timespec64_sub(*ts, xt);
1396 if (timespec64_compare(&tks->wall_to_monotonic, &ts_delta) > 0) {
1397 timekeeping_restore_shadow(&tk_core);
1401 tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, ts_delta));
1402 tk_set_xtime(tks, ts);
1403 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1406 /* Signal hrtimers about time change */
1407 clock_was_set(CLOCK_SET_WALL);
1409 audit_tk_injoffset(ts_delta);
1410 add_device_randomness(ts, sizeof(*ts));
1413 EXPORT_SYMBOL(do_settimeofday64);
1416 * timekeeping_inject_offset - Adds or subtracts from the current time.
1417 * @ts: Pointer to the timespec variable containing the offset
1419 * Adds or subtracts an offset value from the current time.
1421 static int timekeeping_inject_offset(const struct timespec64 *ts)
1423 if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1426 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1427 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1428 struct timespec64 tmp;
1430 timekeeping_forward_now(tks);
1432 /* Make sure the proposed value is valid */
1433 tmp = timespec64_add(tk_xtime(tks), *ts);
1434 if (timespec64_compare(&tks->wall_to_monotonic, ts) > 0 ||
1435 !timespec64_valid_settod(&tmp)) {
1436 timekeeping_restore_shadow(&tk_core);
1440 tk_xtime_add(tks, ts);
1441 tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, *ts));
1442 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1445 /* Signal hrtimers about time change */
1446 clock_was_set(CLOCK_SET_WALL);
1451 * Indicates if there is an offset between the system clock and the hardware
1452 * clock/persistent clock/rtc.
1454 int persistent_clock_is_local;
1457 * Adjust the time obtained from the CMOS to be UTC time instead of
1460 * This is ugly, but preferable to the alternatives. Otherwise we
1461 * would either need to write a program to do it in /etc/rc (and risk
1462 * confusion if the program gets run more than once; it would also be
1463 * hard to make the program warp the clock precisely n hours) or
1464 * compile in the timezone information into the kernel. Bad, bad....
1468 * The best thing to do is to keep the CMOS clock in universal time (UTC)
1469 * as real UNIX machines always do it. This avoids all headaches about
1470 * daylight saving times and warping kernel clocks.
1472 void timekeeping_warp_clock(void)
1474 if (sys_tz.tz_minuteswest != 0) {
1475 struct timespec64 adjust;
1477 persistent_clock_is_local = 1;
1478 adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1480 timekeeping_inject_offset(&adjust);
1485 * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1487 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1489 tk->tai_offset = tai_offset;
1490 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1494 * change_clocksource - Swaps clocksources if a new one is available
1496 * Accumulates current time interval and initializes new clocksource
1498 static int change_clocksource(void *data)
1500 struct clocksource *new = data, *old = NULL;
1503 * If the clocksource is in a module, get a module reference.
1504 * Succeeds for built-in code (owner == NULL) as well. Abort if the
1505 * reference can't be acquired.
1507 if (!try_module_get(new->owner))
1510 /* Abort if the device can't be enabled */
1511 if (new->enable && new->enable(new) != 0) {
1512 module_put(new->owner);
1516 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1517 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1519 timekeeping_forward_now(tks);
1520 old = tks->tkr_mono.clock;
1521 tk_setup_internals(tks, new);
1522 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1528 module_put(old->owner);
1535 * timekeeping_notify - Install a new clock source
1536 * @clock: pointer to the clock source
1538 * This function is called from clocksource.c after a new, better clock
1539 * source has been registered. The caller holds the clocksource_mutex.
1541 int timekeeping_notify(struct clocksource *clock)
1543 struct timekeeper *tk = &tk_core.timekeeper;
1545 if (tk->tkr_mono.clock == clock)
1547 stop_machine(change_clocksource, clock, NULL);
1548 tick_clock_notify();
1549 return tk->tkr_mono.clock == clock ? 0 : -1;
1553 * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
1554 * @ts: pointer to the timespec64 to be set
1556 * Returns the raw monotonic time (completely un-modified by ntp)
1558 void ktime_get_raw_ts64(struct timespec64 *ts)
1560 struct timekeeper *tk = &tk_core.timekeeper;
1565 seq = read_seqcount_begin(&tk_core.seq);
1566 ts->tv_sec = tk->raw_sec;
1567 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1569 } while (read_seqcount_retry(&tk_core.seq, seq));
1572 timespec64_add_ns(ts, nsecs);
1574 EXPORT_SYMBOL(ktime_get_raw_ts64);
1578 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1580 int timekeeping_valid_for_hres(void)
1582 struct timekeeper *tk = &tk_core.timekeeper;
1587 seq = read_seqcount_begin(&tk_core.seq);
1589 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1591 } while (read_seqcount_retry(&tk_core.seq, seq));
1597 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1599 u64 timekeeping_max_deferment(void)
1601 struct timekeeper *tk = &tk_core.timekeeper;
1606 seq = read_seqcount_begin(&tk_core.seq);
1608 ret = tk->tkr_mono.clock->max_idle_ns;
1610 } while (read_seqcount_retry(&tk_core.seq, seq));
1616 * read_persistent_clock64 - Return time from the persistent clock.
1617 * @ts: Pointer to the storage for the readout value
1619 * Weak dummy function for arches that do not yet support it.
1620 * Reads the time from the battery backed persistent clock.
1621 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1623 * XXX - Do be sure to remove it once all arches implement it.
1625 void __weak read_persistent_clock64(struct timespec64 *ts)
1632 * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
1634 * @wall_time: current time as returned by persistent clock
1635 * @boot_offset: offset that is defined as wall_time - boot_time
1637 * Weak dummy function for arches that do not yet support it.
1639 * The default function calculates offset based on the current value of
1640 * local_clock(). This way architectures that support sched_clock() but don't
1641 * support dedicated boot time clock will provide the best estimate of the
1645 read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
1646 struct timespec64 *boot_offset)
1648 read_persistent_clock64(wall_time);
1649 *boot_offset = ns_to_timespec64(local_clock());
1652 static __init void tkd_basic_setup(struct tk_data *tkd)
1654 raw_spin_lock_init(&tkd->lock);
1655 seqcount_raw_spinlock_init(&tkd->seq, &tkd->lock);
1659 * Flag reflecting whether timekeeping_resume() has injected sleeptime.
1661 * The flag starts of false and is only set when a suspend reaches
1662 * timekeeping_suspend(), timekeeping_resume() sets it to false when the
1663 * timekeeper clocksource is not stopping across suspend and has been
1664 * used to update sleep time. If the timekeeper clocksource has stopped
1665 * then the flag stays true and is used by the RTC resume code to decide
1666 * whether sleeptime must be injected and if so the flag gets false then.
1668 * If a suspend fails before reaching timekeeping_resume() then the flag
1669 * stays false and prevents erroneous sleeptime injection.
1671 static bool suspend_timing_needed;
1673 /* Flag for if there is a persistent clock on this platform */
1674 static bool persistent_clock_exists;
1677 * timekeeping_init - Initializes the clocksource and common timekeeping values
1679 void __init timekeeping_init(void)
1681 struct timespec64 wall_time, boot_offset, wall_to_mono;
1682 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1683 struct clocksource *clock;
1685 tkd_basic_setup(&tk_core);
1687 read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
1688 if (timespec64_valid_settod(&wall_time) &&
1689 timespec64_to_ns(&wall_time) > 0) {
1690 persistent_clock_exists = true;
1691 } else if (timespec64_to_ns(&wall_time) != 0) {
1692 pr_warn("Persistent clock returned invalid value");
1693 wall_time = (struct timespec64){0};
1696 if (timespec64_compare(&wall_time, &boot_offset) < 0)
1697 boot_offset = (struct timespec64){0};
1700 * We want set wall_to_mono, so the following is true:
1701 * wall time + wall_to_mono = boot time
1703 wall_to_mono = timespec64_sub(boot_offset, wall_time);
1705 guard(raw_spinlock_irqsave)(&tk_core.lock);
1709 clock = clocksource_default_clock();
1711 clock->enable(clock);
1712 tk_setup_internals(tks, clock);
1714 tk_set_xtime(tks, &wall_time);
1717 tk_set_wall_to_mono(tks, wall_to_mono);
1719 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
1722 /* time in seconds when suspend began for persistent clock */
1723 static struct timespec64 timekeeping_suspend_time;
1726 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1727 * @tk: Pointer to the timekeeper to be updated
1728 * @delta: Pointer to the delta value in timespec64 format
1730 * Takes a timespec offset measuring a suspend interval and properly
1731 * adds the sleep offset to the timekeeping variables.
1733 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1734 const struct timespec64 *delta)
1736 if (!timespec64_valid_strict(delta)) {
1737 printk_deferred(KERN_WARNING
1738 "__timekeeping_inject_sleeptime: Invalid "
1739 "sleep delta value!\n");
1742 tk_xtime_add(tk, delta);
1743 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1744 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1745 tk_debug_account_sleep_time(delta);
1748 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1750 * We have three kinds of time sources to use for sleep time
1751 * injection, the preference order is:
1752 * 1) non-stop clocksource
1753 * 2) persistent clock (ie: RTC accessible when irqs are off)
1756 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1757 * If system has neither 1) nor 2), 3) will be used finally.
1760 * If timekeeping has injected sleeptime via either 1) or 2),
1761 * 3) becomes needless, so in this case we don't need to call
1762 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1765 bool timekeeping_rtc_skipresume(void)
1767 return !suspend_timing_needed;
1771 * 1) can be determined whether to use or not only when doing
1772 * timekeeping_resume() which is invoked after rtc_suspend(),
1773 * so we can't skip rtc_suspend() surely if system has 1).
1775 * But if system has 2), 2) will definitely be used, so in this
1776 * case we don't need to call rtc_suspend(), and this is what
1777 * timekeeping_rtc_skipsuspend() means.
1779 bool timekeeping_rtc_skipsuspend(void)
1781 return persistent_clock_exists;
1785 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1786 * @delta: pointer to a timespec64 delta value
1788 * This hook is for architectures that cannot support read_persistent_clock64
1789 * because their RTC/persistent clock is only accessible when irqs are enabled.
1790 * and also don't have an effective nonstop clocksource.
1792 * This function should only be called by rtc_resume(), and allows
1793 * a suspend offset to be injected into the timekeeping values.
1795 void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
1797 scoped_guard(raw_spinlock_irqsave, &tk_core.lock) {
1798 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1800 suspend_timing_needed = false;
1801 timekeeping_forward_now(tks);
1802 __timekeeping_inject_sleeptime(tks, delta);
1803 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1806 /* Signal hrtimers about time change */
1807 clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
1812 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1814 void timekeeping_resume(void)
1816 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1817 struct clocksource *clock = tks->tkr_mono.clock;
1818 struct timespec64 ts_new, ts_delta;
1819 bool inject_sleeptime = false;
1820 u64 cycle_now, nsec;
1821 unsigned long flags;
1823 read_persistent_clock64(&ts_new);
1825 clockevents_resume();
1826 clocksource_resume();
1828 raw_spin_lock_irqsave(&tk_core.lock, flags);
1831 * After system resumes, we need to calculate the suspended time and
1832 * compensate it for the OS time. There are 3 sources that could be
1833 * used: Nonstop clocksource during suspend, persistent clock and rtc
1836 * One specific platform may have 1 or 2 or all of them, and the
1837 * preference will be:
1838 * suspend-nonstop clocksource -> persistent clock -> rtc
1839 * The less preferred source will only be tried if there is no better
1840 * usable source. The rtc part is handled separately in rtc core code.
1842 cycle_now = tk_clock_read(&tks->tkr_mono);
1843 nsec = clocksource_stop_suspend_timing(clock, cycle_now);
1845 ts_delta = ns_to_timespec64(nsec);
1846 inject_sleeptime = true;
1847 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1848 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1849 inject_sleeptime = true;
1852 if (inject_sleeptime) {
1853 suspend_timing_needed = false;
1854 __timekeeping_inject_sleeptime(tks, &ts_delta);
1857 /* Re-base the last cycle value */
1858 tks->tkr_mono.cycle_last = cycle_now;
1859 tks->tkr_raw.cycle_last = cycle_now;
1862 timekeeping_suspended = 0;
1863 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
1864 raw_spin_unlock_irqrestore(&tk_core.lock, flags);
1866 touch_softlockup_watchdog();
1868 /* Resume the clockevent device(s) and hrtimers */
1870 /* Notify timerfd as resume is equivalent to clock_was_set() */
1874 int timekeeping_suspend(void)
1876 struct timekeeper *tks = &tk_core.shadow_timekeeper;
1877 struct timespec64 delta, delta_delta;
1878 static struct timespec64 old_delta;
1879 struct clocksource *curr_clock;
1880 unsigned long flags;
1883 read_persistent_clock64(&timekeeping_suspend_time);
1886 * On some systems the persistent_clock can not be detected at
1887 * timekeeping_init by its return value, so if we see a valid
1888 * value returned, update the persistent_clock_exists flag.
1890 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1891 persistent_clock_exists = true;
1893 suspend_timing_needed = true;
1895 raw_spin_lock_irqsave(&tk_core.lock, flags);
1896 timekeeping_forward_now(tks);
1897 timekeeping_suspended = 1;
1900 * Since we've called forward_now, cycle_last stores the value
1901 * just read from the current clocksource. Save this to potentially
1902 * use in suspend timing.
1904 curr_clock = tks->tkr_mono.clock;
1905 cycle_now = tks->tkr_mono.cycle_last;
1906 clocksource_start_suspend_timing(curr_clock, cycle_now);
1908 if (persistent_clock_exists) {
1910 * To avoid drift caused by repeated suspend/resumes,
1911 * which each can add ~1 second drift error,
1912 * try to compensate so the difference in system time
1913 * and persistent_clock time stays close to constant.
1915 delta = timespec64_sub(tk_xtime(tks), timekeeping_suspend_time);
1916 delta_delta = timespec64_sub(delta, old_delta);
1917 if (abs(delta_delta.tv_sec) >= 2) {
1919 * if delta_delta is too large, assume time correction
1920 * has occurred and set old_delta to the current delta.
1924 /* Otherwise try to adjust old_system to compensate */
1925 timekeeping_suspend_time =
1926 timespec64_add(timekeeping_suspend_time, delta_delta);
1930 timekeeping_update_from_shadow(&tk_core, 0);
1931 halt_fast_timekeeper(tks);
1932 raw_spin_unlock_irqrestore(&tk_core.lock, flags);
1935 clocksource_suspend();
1936 clockevents_suspend();
1941 /* sysfs resume/suspend bits for timekeeping */
1942 static struct syscore_ops timekeeping_syscore_ops = {
1943 .resume = timekeeping_resume,
1944 .suspend = timekeeping_suspend,
1947 static int __init timekeeping_init_ops(void)
1949 register_syscore_ops(&timekeeping_syscore_ops);
1952 device_initcall(timekeeping_init_ops);
1955 * Apply a multiplier adjustment to the timekeeper
1957 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1961 s64 interval = tk->cycle_interval;
1963 if (mult_adj == 0) {
1965 } else if (mult_adj == -1) {
1966 interval = -interval;
1968 } else if (mult_adj != 1) {
1969 interval *= mult_adj;
1974 * So the following can be confusing.
1976 * To keep things simple, lets assume mult_adj == 1 for now.
1978 * When mult_adj != 1, remember that the interval and offset values
1979 * have been appropriately scaled so the math is the same.
1981 * The basic idea here is that we're increasing the multiplier
1982 * by one, this causes the xtime_interval to be incremented by
1983 * one cycle_interval. This is because:
1984 * xtime_interval = cycle_interval * mult
1985 * So if mult is being incremented by one:
1986 * xtime_interval = cycle_interval * (mult + 1)
1988 * xtime_interval = (cycle_interval * mult) + cycle_interval
1989 * Which can be shortened to:
1990 * xtime_interval += cycle_interval
1992 * So offset stores the non-accumulated cycles. Thus the current
1993 * time (in shifted nanoseconds) is:
1994 * now = (offset * adj) + xtime_nsec
1995 * Now, even though we're adjusting the clock frequency, we have
1996 * to keep time consistent. In other words, we can't jump back
1997 * in time, and we also want to avoid jumping forward in time.
1999 * So given the same offset value, we need the time to be the same
2000 * both before and after the freq adjustment.
2001 * now = (offset * adj_1) + xtime_nsec_1
2002 * now = (offset * adj_2) + xtime_nsec_2
2004 * (offset * adj_1) + xtime_nsec_1 =
2005 * (offset * adj_2) + xtime_nsec_2
2009 * (offset * adj_1) + xtime_nsec_1 =
2010 * (offset * (adj_1+1)) + xtime_nsec_2
2011 * (offset * adj_1) + xtime_nsec_1 =
2012 * (offset * adj_1) + offset + xtime_nsec_2
2013 * Canceling the sides:
2014 * xtime_nsec_1 = offset + xtime_nsec_2
2016 * xtime_nsec_2 = xtime_nsec_1 - offset
2017 * Which simplifies to:
2018 * xtime_nsec -= offset
2020 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
2021 /* NTP adjustment caused clocksource mult overflow */
2026 tk->tkr_mono.mult += mult_adj;
2027 tk->xtime_interval += interval;
2028 tk->tkr_mono.xtime_nsec -= offset;
2032 * Adjust the timekeeper's multiplier to the correct frequency
2033 * and also to reduce the accumulated error value.
2035 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
2037 u64 ntp_tl = ntp_tick_length();
2041 * Determine the multiplier from the current NTP tick length.
2042 * Avoid expensive division when the tick length doesn't change.
2044 if (likely(tk->ntp_tick == ntp_tl)) {
2045 mult = tk->tkr_mono.mult - tk->ntp_err_mult;
2047 tk->ntp_tick = ntp_tl;
2048 mult = div64_u64((tk->ntp_tick >> tk->ntp_error_shift) -
2049 tk->xtime_remainder, tk->cycle_interval);
2053 * If the clock is behind the NTP time, increase the multiplier by 1
2054 * to catch up with it. If it's ahead and there was a remainder in the
2055 * tick division, the clock will slow down. Otherwise it will stay
2056 * ahead until the tick length changes to a non-divisible value.
2058 tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
2059 mult += tk->ntp_err_mult;
2061 timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
2063 if (unlikely(tk->tkr_mono.clock->maxadj &&
2064 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2065 > tk->tkr_mono.clock->maxadj))) {
2066 printk_once(KERN_WARNING
2067 "Adjusting %s more than 11%% (%ld vs %ld)\n",
2068 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2069 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
2073 * It may be possible that when we entered this function, xtime_nsec
2074 * was very small. Further, if we're slightly speeding the clocksource
2075 * in the code above, its possible the required corrective factor to
2076 * xtime_nsec could cause it to underflow.
2078 * Now, since we have already accumulated the second and the NTP
2079 * subsystem has been notified via second_overflow(), we need to skip
2082 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
2083 tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
2086 tk->skip_second_overflow = 1;
2091 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2093 * Helper function that accumulates the nsecs greater than a second
2094 * from the xtime_nsec field to the xtime_secs field.
2095 * It also calls into the NTP code to handle leapsecond processing.
2097 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
2099 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2100 unsigned int clock_set = 0;
2102 while (tk->tkr_mono.xtime_nsec >= nsecps) {
2105 tk->tkr_mono.xtime_nsec -= nsecps;
2109 * Skip NTP update if this second was accumulated before,
2110 * i.e. xtime_nsec underflowed in timekeeping_adjust()
2112 if (unlikely(tk->skip_second_overflow)) {
2113 tk->skip_second_overflow = 0;
2117 /* Figure out if its a leap sec and apply if needed */
2118 leap = second_overflow(tk->xtime_sec);
2119 if (unlikely(leap)) {
2120 struct timespec64 ts;
2122 tk->xtime_sec += leap;
2126 tk_set_wall_to_mono(tk,
2127 timespec64_sub(tk->wall_to_monotonic, ts));
2129 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2131 clock_set = TK_CLOCK_WAS_SET;
2138 * logarithmic_accumulation - shifted accumulation of cycles
2140 * This functions accumulates a shifted interval of cycles into
2141 * a shifted interval nanoseconds. Allows for O(log) accumulation
2144 * Returns the unconsumed cycles.
2146 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2147 u32 shift, unsigned int *clock_set)
2149 u64 interval = tk->cycle_interval << shift;
2152 /* If the offset is smaller than a shifted interval, do nothing */
2153 if (offset < interval)
2156 /* Accumulate one shifted interval */
2158 tk->tkr_mono.cycle_last += interval;
2159 tk->tkr_raw.cycle_last += interval;
2161 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2162 *clock_set |= accumulate_nsecs_to_secs(tk);
2164 /* Accumulate raw time */
2165 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2166 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2167 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2168 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2172 /* Accumulate error between NTP and clock interval */
2173 tk->ntp_error += tk->ntp_tick << shift;
2174 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2175 (tk->ntp_error_shift + shift);
2181 * timekeeping_advance - Updates the timekeeper to the current time and
2182 * current NTP tick length
2184 static bool timekeeping_advance(enum timekeeping_adv_mode mode)
2186 struct timekeeper *tk = &tk_core.shadow_timekeeper;
2187 struct timekeeper *real_tk = &tk_core.timekeeper;
2188 unsigned int clock_set = 0;
2189 int shift = 0, maxshift;
2190 u64 offset, orig_offset;
2192 guard(raw_spinlock_irqsave)(&tk_core.lock);
2194 /* Make sure we're fully resumed: */
2195 if (unlikely(timekeeping_suspended))
2198 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2199 tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
2200 tk->tkr_mono.clock->max_raw_delta);
2201 orig_offset = offset;
2202 /* Check if there's really nothing to do */
2203 if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
2207 * With NO_HZ we may have to accumulate many cycle_intervals
2208 * (think "ticks") worth of time at once. To do this efficiently,
2209 * we calculate the largest doubling multiple of cycle_intervals
2210 * that is smaller than the offset. We then accumulate that
2211 * chunk in one go, and then try to consume the next smaller
2214 shift = ilog2(offset) - ilog2(tk->cycle_interval);
2215 shift = max(0, shift);
2216 /* Bound shift to one less than what overflows tick_length */
2217 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2218 shift = min(shift, maxshift);
2219 while (offset >= tk->cycle_interval) {
2220 offset = logarithmic_accumulation(tk, offset, shift, &clock_set);
2221 if (offset < tk->cycle_interval<<shift)
2225 /* Adjust the multiplier to correct NTP error */
2226 timekeeping_adjust(tk, offset);
2229 * Finally, make sure that after the rounding
2230 * xtime_nsec isn't larger than NSEC_PER_SEC
2232 clock_set |= accumulate_nsecs_to_secs(tk);
2235 * To avoid inconsistencies caused adjtimex TK_ADV_FREQ calls
2236 * making small negative adjustments to the base xtime_nsec
2237 * value, only update the coarse clocks if we accumulated time
2239 if (orig_offset != offset)
2240 tk_update_coarse_nsecs(tk);
2242 timekeeping_update_from_shadow(&tk_core, clock_set);
2248 * update_wall_time - Uses the current clocksource to increment the wall time
2251 void update_wall_time(void)
2253 if (timekeeping_advance(TK_ADV_TICK))
2254 clock_was_set_delayed();
2258 * getboottime64 - Return the real time of system boot.
2259 * @ts: pointer to the timespec64 to be set
2261 * Returns the wall-time of boot in a timespec64.
2263 * This is based on the wall_to_monotonic offset and the total suspend
2264 * time. Calls to settimeofday will affect the value returned (which
2265 * basically means that however wrong your real time clock is at boot time,
2266 * you get the right time here).
2268 void getboottime64(struct timespec64 *ts)
2270 struct timekeeper *tk = &tk_core.timekeeper;
2271 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2273 *ts = ktime_to_timespec64(t);
2275 EXPORT_SYMBOL_GPL(getboottime64);
2277 void ktime_get_coarse_real_ts64(struct timespec64 *ts)
2279 struct timekeeper *tk = &tk_core.timekeeper;
2283 seq = read_seqcount_begin(&tk_core.seq);
2285 *ts = tk_xtime_coarse(tk);
2286 } while (read_seqcount_retry(&tk_core.seq, seq));
2288 EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
2291 * ktime_get_coarse_real_ts64_mg - return latter of coarse grained time or floor
2292 * @ts: timespec64 to be filled
2294 * Fetch the global mg_floor value, convert it to realtime and compare it
2295 * to the current coarse-grained time. Fill @ts with whichever is
2296 * latest. Note that this is a filesystem-specific interface and should be
2297 * avoided outside of that context.
2299 void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
2301 struct timekeeper *tk = &tk_core.timekeeper;
2302 u64 floor = atomic64_read(&mg_floor);
2303 ktime_t f_real, offset, coarse;
2307 seq = read_seqcount_begin(&tk_core.seq);
2308 *ts = tk_xtime_coarse(tk);
2309 offset = tk_core.timekeeper.offs_real;
2310 } while (read_seqcount_retry(&tk_core.seq, seq));
2312 coarse = timespec64_to_ktime(*ts);
2313 f_real = ktime_add(floor, offset);
2314 if (ktime_after(f_real, coarse))
2315 *ts = ktime_to_timespec64(f_real);
2319 * ktime_get_real_ts64_mg - attempt to update floor value and return result
2320 * @ts: pointer to the timespec to be set
2322 * Get a monotonic fine-grained time value and attempt to swap it into
2323 * mg_floor. If that succeeds then accept the new floor value. If it fails
2324 * then another task raced in during the interim time and updated the
2325 * floor. Since any update to the floor must be later than the previous
2326 * floor, either outcome is acceptable.
2328 * Typically this will be called after calling ktime_get_coarse_real_ts64_mg(),
2329 * and determining that the resulting coarse-grained timestamp did not effect
2330 * a change in ctime. Any more recent floor value would effect a change to
2331 * ctime, so there is no need to retry the atomic64_try_cmpxchg() on failure.
2333 * @ts will be filled with the latest floor value, regardless of the outcome of
2334 * the cmpxchg. Note that this is a filesystem specific interface and should be
2335 * avoided outside of that context.
2337 void ktime_get_real_ts64_mg(struct timespec64 *ts)
2339 struct timekeeper *tk = &tk_core.timekeeper;
2340 ktime_t old = atomic64_read(&mg_floor);
2341 ktime_t offset, mono;
2346 seq = read_seqcount_begin(&tk_core.seq);
2348 ts->tv_sec = tk->xtime_sec;
2349 mono = tk->tkr_mono.base;
2350 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2351 offset = tk_core.timekeeper.offs_real;
2352 } while (read_seqcount_retry(&tk_core.seq, seq));
2354 mono = ktime_add_ns(mono, nsecs);
2357 * Attempt to update the floor with the new time value. As any
2358 * update must be later then the existing floor, and would effect
2359 * a change to ctime from the perspective of the current task,
2360 * accept the resulting floor value regardless of the outcome of
2363 if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
2365 timespec64_add_ns(ts, nsecs);
2366 timekeeping_inc_mg_floor_swaps();
2369 * Another task changed mg_floor since "old" was fetched.
2370 * "old" has been updated with the latest value of "mg_floor".
2371 * That value is newer than the previous floor value, which
2372 * is enough to effect a change to ctime. Accept it.
2374 *ts = ktime_to_timespec64(ktime_add(old, offset));
2378 void ktime_get_coarse_ts64(struct timespec64 *ts)
2380 struct timekeeper *tk = &tk_core.timekeeper;
2381 struct timespec64 now, mono;
2385 seq = read_seqcount_begin(&tk_core.seq);
2387 now = tk_xtime_coarse(tk);
2388 mono = tk->wall_to_monotonic;
2389 } while (read_seqcount_retry(&tk_core.seq, seq));
2391 set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
2392 now.tv_nsec + mono.tv_nsec);
2394 EXPORT_SYMBOL(ktime_get_coarse_ts64);
2397 * Must hold jiffies_lock
2399 void do_timer(unsigned long ticks)
2401 jiffies_64 += ticks;
2406 * ktime_get_update_offsets_now - hrtimer helper
2407 * @cwsseq: pointer to check and store the clock was set sequence number
2408 * @offs_real: pointer to storage for monotonic -> realtime offset
2409 * @offs_boot: pointer to storage for monotonic -> boottime offset
2410 * @offs_tai: pointer to storage for monotonic -> clock tai offset
2412 * Returns current monotonic time and updates the offsets if the
2413 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2416 * Called from hrtimer_interrupt() or retrigger_next_event()
2418 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2419 ktime_t *offs_boot, ktime_t *offs_tai)
2421 struct timekeeper *tk = &tk_core.timekeeper;
2427 seq = read_seqcount_begin(&tk_core.seq);
2429 base = tk->tkr_mono.base;
2430 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2431 base = ktime_add_ns(base, nsecs);
2433 if (*cwsseq != tk->clock_was_set_seq) {
2434 *cwsseq = tk->clock_was_set_seq;
2435 *offs_real = tk->offs_real;
2436 *offs_boot = tk->offs_boot;
2437 *offs_tai = tk->offs_tai;
2440 /* Handle leapsecond insertion adjustments */
2441 if (unlikely(base >= tk->next_leap_ktime))
2442 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2444 } while (read_seqcount_retry(&tk_core.seq, seq));
2450 * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2452 static int timekeeping_validate_timex(const struct __kernel_timex *txc)
2454 if (txc->modes & ADJ_ADJTIME) {
2455 /* singleshot must not be used with any other mode bits */
2456 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2458 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2459 !capable(CAP_SYS_TIME))
2462 /* In order to modify anything, you gotta be super-user! */
2463 if (txc->modes && !capable(CAP_SYS_TIME))
2466 * if the quartz is off by more than 10% then
2467 * something is VERY wrong!
2469 if (txc->modes & ADJ_TICK &&
2470 (txc->tick < 900000/USER_HZ ||
2471 txc->tick > 1100000/USER_HZ))
2475 if (txc->modes & ADJ_SETOFFSET) {
2476 /* In order to inject time, you gotta be super-user! */
2477 if (!capable(CAP_SYS_TIME))
2481 * Validate if a timespec/timeval used to inject a time
2482 * offset is valid. Offsets can be positive or negative, so
2483 * we don't check tv_sec. The value of the timeval/timespec
2484 * is the sum of its fields,but *NOTE*:
2485 * The field tv_usec/tv_nsec must always be non-negative and
2486 * we can't have more nanoseconds/microseconds than a second.
2488 if (txc->time.tv_usec < 0)
2491 if (txc->modes & ADJ_NANO) {
2492 if (txc->time.tv_usec >= NSEC_PER_SEC)
2495 if (txc->time.tv_usec >= USEC_PER_SEC)
2501 * Check for potential multiplication overflows that can
2502 * only happen on 64-bit systems:
2504 if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2505 if (LLONG_MIN / PPM_SCALE > txc->freq)
2507 if (LLONG_MAX / PPM_SCALE < txc->freq)
2515 * random_get_entropy_fallback - Returns the raw clock source value,
2516 * used by random.c for platforms with no valid random_get_entropy().
2518 unsigned long random_get_entropy_fallback(void)
2520 struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
2521 struct clocksource *clock = READ_ONCE(tkr->clock);
2523 if (unlikely(timekeeping_suspended || !clock))
2525 return clock->read(clock);
2527 EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
2530 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2531 * @txc: Pointer to kernel_timex structure containing NTP parameters
2533 int do_adjtimex(struct __kernel_timex *txc)
2535 struct audit_ntp_data ad;
2536 bool offset_set = false;
2537 bool clock_set = false;
2538 struct timespec64 ts;
2541 /* Validate the data before disabling interrupts */
2542 ret = timekeeping_validate_timex(txc);
2545 add_device_randomness(txc, sizeof(*txc));
2547 if (txc->modes & ADJ_SETOFFSET) {
2548 struct timespec64 delta;
2550 delta.tv_sec = txc->time.tv_sec;
2551 delta.tv_nsec = txc->time.tv_usec;
2552 if (!(txc->modes & ADJ_NANO))
2553 delta.tv_nsec *= 1000;
2554 ret = timekeeping_inject_offset(&delta);
2558 offset_set = delta.tv_sec != 0;
2559 audit_tk_injoffset(delta);
2562 audit_ntp_init(&ad);
2564 ktime_get_real_ts64(&ts);
2565 add_device_randomness(&ts, sizeof(ts));
2567 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
2568 struct timekeeper *tks = &tk_core.shadow_timekeeper;
2571 orig_tai = tai = tks->tai_offset;
2572 ret = __do_adjtimex(txc, &ts, &tai, &ad);
2574 if (tai != orig_tai) {
2575 __timekeeping_set_tai_offset(tks, tai);
2576 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
2579 tk_update_leap_state_all(&tk_core);
2585 /* Update the multiplier immediately if frequency was set directly */
2586 if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
2587 clock_set |= timekeeping_advance(TK_ADV_FREQ);
2590 clock_was_set(CLOCK_SET_WALL);
2592 ntp_notify_cmos_timer(offset_set);
2597 #ifdef CONFIG_NTP_PPS
2599 * hardpps() - Accessor function to NTP __hardpps function
2600 * @phase_ts: Pointer to timespec64 structure representing phase timestamp
2601 * @raw_ts: Pointer to timespec64 structure representing raw timestamp
2603 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2605 guard(raw_spinlock_irqsave)(&tk_core.lock);
2606 __hardpps(phase_ts, raw_ts);
2608 EXPORT_SYMBOL(hardpps);
2609 #endif /* CONFIG_NTP_PPS */