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/nmi.h>
18 #include <linux/sched.h>
19 #include <linux/sched/loadavg.h>
20 #include <linux/syscore_ops.h>
21 #include <linux/clocksource.h>
22 #include <linux/jiffies.h>
23 #include <linux/time.h>
24 #include <linux/tick.h>
25 #include <linux/stop_machine.h>
26 #include <linux/pvclock_gtod.h>
27 #include <linux/compiler.h>
29 #include "tick-internal.h"
30 #include "ntp_internal.h"
31 #include "timekeeping_internal.h"
33 #define TK_CLEAR_NTP (1 << 0)
34 #define TK_MIRROR (1 << 1)
35 #define TK_CLOCK_WAS_SET (1 << 2)
38 * The most important data for readout fits into a single 64 byte
43 struct timekeeper timekeeper;
44 } tk_core ____cacheline_aligned;
46 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
47 static struct timekeeper shadow_timekeeper;
50 * struct tk_fast - NMI safe timekeeper
51 * @seq: Sequence counter for protecting updates. The lowest bit
52 * is the index for the tk_read_base array
53 * @base: tk_read_base array. Access is indexed by the lowest bit of
56 * See @update_fast_timekeeper() below.
60 struct tk_read_base base[2];
63 /* Suspend-time cycles value for halted fast timekeeper. */
64 static u64 cycles_at_suspend;
66 static u64 dummy_clock_read(struct clocksource *cs)
68 return cycles_at_suspend;
71 static struct clocksource dummy_clock = {
72 .read = dummy_clock_read,
75 static struct tk_fast tk_fast_mono ____cacheline_aligned = {
76 .base[0] = { .clock = &dummy_clock, },
77 .base[1] = { .clock = &dummy_clock, },
80 static struct tk_fast tk_fast_raw ____cacheline_aligned = {
81 .base[0] = { .clock = &dummy_clock, },
82 .base[1] = { .clock = &dummy_clock, },
85 /* flag for if timekeeping is suspended */
86 int __read_mostly timekeeping_suspended;
88 static inline void tk_normalize_xtime(struct timekeeper *tk)
90 while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
91 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
94 while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
95 tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
100 static inline struct timespec64 tk_xtime(struct timekeeper *tk)
102 struct timespec64 ts;
104 ts.tv_sec = tk->xtime_sec;
105 ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
109 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
111 tk->xtime_sec = ts->tv_sec;
112 tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
115 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
117 tk->xtime_sec += ts->tv_sec;
118 tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
119 tk_normalize_xtime(tk);
122 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
124 struct timespec64 tmp;
127 * Verify consistency of: offset_real = -wall_to_monotonic
128 * before modifying anything
130 set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
131 -tk->wall_to_monotonic.tv_nsec);
132 WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
133 tk->wall_to_monotonic = wtm;
134 set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
135 tk->offs_real = timespec64_to_ktime(tmp);
136 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
139 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
141 tk->offs_boot = ktime_add(tk->offs_boot, delta);
145 * tk_clock_read - atomic clocksource read() helper
147 * This helper is necessary to use in the read paths because, while the
148 * seqlock ensures we don't return a bad value while structures are updated,
149 * it doesn't protect from potential crashes. There is the possibility that
150 * the tkr's clocksource may change between the read reference, and the
151 * clock reference passed to the read function. This can cause crashes if
152 * the wrong clocksource is passed to the wrong read function.
153 * This isn't necessary to use when holding the timekeeper_lock or doing
154 * a read of the fast-timekeeper tkrs (which is protected by its own locking
157 static inline u64 tk_clock_read(struct tk_read_base *tkr)
159 struct clocksource *clock = READ_ONCE(tkr->clock);
161 return clock->read(clock);
164 #ifdef CONFIG_DEBUG_TIMEKEEPING
165 #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
167 static void timekeeping_check_update(struct timekeeper *tk, u64 offset)
170 u64 max_cycles = tk->tkr_mono.clock->max_cycles;
171 const char *name = tk->tkr_mono.clock->name;
173 if (offset > max_cycles) {
174 printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
175 offset, name, max_cycles);
176 printk_deferred(" timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
178 if (offset > (max_cycles >> 1)) {
179 printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the '%s' clock's 50%% safety margin (%lld)\n",
180 offset, name, max_cycles >> 1);
181 printk_deferred(" timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
185 if (tk->underflow_seen) {
186 if (jiffies - tk->last_warning > WARNING_FREQ) {
187 printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
188 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
189 printk_deferred(" Your kernel is probably still fine.\n");
190 tk->last_warning = jiffies;
192 tk->underflow_seen = 0;
195 if (tk->overflow_seen) {
196 if (jiffies - tk->last_warning > WARNING_FREQ) {
197 printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
198 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
199 printk_deferred(" Your kernel is probably still fine.\n");
200 tk->last_warning = jiffies;
202 tk->overflow_seen = 0;
206 static inline u64 timekeeping_get_delta(struct tk_read_base *tkr)
208 struct timekeeper *tk = &tk_core.timekeeper;
209 u64 now, last, mask, max, delta;
213 * Since we're called holding a seqlock, the data may shift
214 * under us while we're doing the calculation. This can cause
215 * false positives, since we'd note a problem but throw the
216 * results away. So nest another seqlock here to atomically
217 * grab the points we are checking with.
220 seq = read_seqcount_begin(&tk_core.seq);
221 now = tk_clock_read(tkr);
222 last = tkr->cycle_last;
224 max = tkr->clock->max_cycles;
225 } while (read_seqcount_retry(&tk_core.seq, seq));
227 delta = clocksource_delta(now, last, mask);
230 * Try to catch underflows by checking if we are seeing small
231 * mask-relative negative values.
233 if (unlikely((~delta & mask) < (mask >> 3))) {
234 tk->underflow_seen = 1;
238 /* Cap delta value to the max_cycles values to avoid mult overflows */
239 if (unlikely(delta > max)) {
240 tk->overflow_seen = 1;
241 delta = tkr->clock->max_cycles;
247 static inline void timekeeping_check_update(struct timekeeper *tk, u64 offset)
250 static inline u64 timekeeping_get_delta(struct tk_read_base *tkr)
252 u64 cycle_now, delta;
254 /* read clocksource */
255 cycle_now = tk_clock_read(tkr);
257 /* calculate the delta since the last update_wall_time */
258 delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
265 * tk_setup_internals - Set up internals to use clocksource clock.
267 * @tk: The target timekeeper to setup.
268 * @clock: Pointer to clocksource.
270 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
271 * pair and interval request.
273 * Unless you're the timekeeping code, you should not be using this!
275 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
278 u64 tmp, ntpinterval;
279 struct clocksource *old_clock;
281 ++tk->cs_was_changed_seq;
282 old_clock = tk->tkr_mono.clock;
283 tk->tkr_mono.clock = clock;
284 tk->tkr_mono.mask = clock->mask;
285 tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
287 tk->tkr_raw.clock = clock;
288 tk->tkr_raw.mask = clock->mask;
289 tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
291 /* Do the ns -> cycle conversion first, using original mult */
292 tmp = NTP_INTERVAL_LENGTH;
293 tmp <<= clock->shift;
295 tmp += clock->mult/2;
296 do_div(tmp, clock->mult);
300 interval = (u64) tmp;
301 tk->cycle_interval = interval;
303 /* Go back from cycles -> shifted ns */
304 tk->xtime_interval = interval * clock->mult;
305 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
306 tk->raw_interval = interval * clock->mult;
308 /* if changing clocks, convert xtime_nsec shift units */
310 int shift_change = clock->shift - old_clock->shift;
311 if (shift_change < 0) {
312 tk->tkr_mono.xtime_nsec >>= -shift_change;
313 tk->tkr_raw.xtime_nsec >>= -shift_change;
315 tk->tkr_mono.xtime_nsec <<= shift_change;
316 tk->tkr_raw.xtime_nsec <<= shift_change;
320 tk->tkr_mono.shift = clock->shift;
321 tk->tkr_raw.shift = clock->shift;
324 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
325 tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
328 * The timekeeper keeps its own mult values for the currently
329 * active clocksource. These value will be adjusted via NTP
330 * to counteract clock drifting.
332 tk->tkr_mono.mult = clock->mult;
333 tk->tkr_raw.mult = clock->mult;
334 tk->ntp_err_mult = 0;
337 /* Timekeeper helper functions. */
339 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
340 static u32 default_arch_gettimeoffset(void) { return 0; }
341 u32 (*arch_gettimeoffset)(void) = default_arch_gettimeoffset;
343 static inline u32 arch_gettimeoffset(void) { return 0; }
346 static inline u64 timekeeping_delta_to_ns(struct tk_read_base *tkr, u64 delta)
350 nsec = delta * tkr->mult + tkr->xtime_nsec;
353 /* If arch requires, add in get_arch_timeoffset() */
354 return nsec + arch_gettimeoffset();
357 static inline u64 timekeeping_get_ns(struct tk_read_base *tkr)
361 delta = timekeeping_get_delta(tkr);
362 return timekeeping_delta_to_ns(tkr, delta);
365 static inline u64 timekeeping_cycles_to_ns(struct tk_read_base *tkr, u64 cycles)
369 /* calculate the delta since the last update_wall_time */
370 delta = clocksource_delta(cycles, tkr->cycle_last, tkr->mask);
371 return timekeeping_delta_to_ns(tkr, delta);
375 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
376 * @tkr: Timekeeping readout base from which we take the update
378 * We want to use this from any context including NMI and tracing /
379 * instrumenting the timekeeping code itself.
381 * Employ the latch technique; see @raw_write_seqcount_latch.
383 * So if a NMI hits the update of base[0] then it will use base[1]
384 * which is still consistent. In the worst case this can result is a
385 * slightly wrong timestamp (a few nanoseconds). See
386 * @ktime_get_mono_fast_ns.
388 static void update_fast_timekeeper(struct tk_read_base *tkr, struct tk_fast *tkf)
390 struct tk_read_base *base = tkf->base;
392 /* Force readers off to base[1] */
393 raw_write_seqcount_latch(&tkf->seq);
396 memcpy(base, tkr, sizeof(*base));
398 /* Force readers back to base[0] */
399 raw_write_seqcount_latch(&tkf->seq);
402 memcpy(base + 1, base, sizeof(*base));
406 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
408 * This timestamp is not guaranteed to be monotonic across an update.
409 * The timestamp is calculated by:
411 * now = base_mono + clock_delta * slope
413 * So if the update lowers the slope, readers who are forced to the
414 * not yet updated second array are still using the old steeper slope.
423 * |12345678---> reader order
429 * So reader 6 will observe time going backwards versus reader 5.
431 * While other CPUs are likely to be able observe that, the only way
432 * for a CPU local observation is when an NMI hits in the middle of
433 * the update. Timestamps taken from that NMI context might be ahead
434 * of the following timestamps. Callers need to be aware of that and
437 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
439 struct tk_read_base *tkr;
444 seq = raw_read_seqcount_latch(&tkf->seq);
445 tkr = tkf->base + (seq & 0x01);
446 now = ktime_to_ns(tkr->base);
448 now += timekeeping_delta_to_ns(tkr,
453 } while (read_seqcount_retry(&tkf->seq, seq));
458 u64 ktime_get_mono_fast_ns(void)
460 return __ktime_get_fast_ns(&tk_fast_mono);
462 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
464 u64 ktime_get_raw_fast_ns(void)
466 return __ktime_get_fast_ns(&tk_fast_raw);
468 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
471 * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
473 * To keep it NMI safe since we're accessing from tracing, we're not using a
474 * separate timekeeper with updates to monotonic clock and boot offset
475 * protected with seqlocks. This has the following minor side effects:
477 * (1) Its possible that a timestamp be taken after the boot offset is updated
478 * but before the timekeeper is updated. If this happens, the new boot offset
479 * is added to the old timekeeping making the clock appear to update slightly
482 * timekeeping_inject_sleeptime64()
483 * __timekeeping_inject_sleeptime(tk, delta);
485 * timekeeping_update(tk, TK_CLEAR_NTP...);
487 * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
488 * partially updated. Since the tk->offs_boot update is a rare event, this
489 * should be a rare occurrence which postprocessing should be able to handle.
491 u64 notrace ktime_get_boot_fast_ns(void)
493 struct timekeeper *tk = &tk_core.timekeeper;
495 return (ktime_get_mono_fast_ns() + ktime_to_ns(tk->offs_boot));
497 EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
501 * See comment for __ktime_get_fast_ns() vs. timestamp ordering
503 static __always_inline u64 __ktime_get_real_fast_ns(struct tk_fast *tkf)
505 struct tk_read_base *tkr;
510 seq = raw_read_seqcount_latch(&tkf->seq);
511 tkr = tkf->base + (seq & 0x01);
512 now = ktime_to_ns(tkr->base_real);
514 now += timekeeping_delta_to_ns(tkr,
519 } while (read_seqcount_retry(&tkf->seq, seq));
525 * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
527 u64 ktime_get_real_fast_ns(void)
529 return __ktime_get_real_fast_ns(&tk_fast_mono);
531 EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
534 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
535 * @tk: Timekeeper to snapshot.
537 * It generally is unsafe to access the clocksource after timekeeping has been
538 * suspended, so take a snapshot of the readout base of @tk and use it as the
539 * fast timekeeper's readout base while suspended. It will return the same
540 * number of cycles every time until timekeeping is resumed at which time the
541 * proper readout base for the fast timekeeper will be restored automatically.
543 static void halt_fast_timekeeper(struct timekeeper *tk)
545 static struct tk_read_base tkr_dummy;
546 struct tk_read_base *tkr = &tk->tkr_mono;
548 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
549 cycles_at_suspend = tk_clock_read(tkr);
550 tkr_dummy.clock = &dummy_clock;
551 tkr_dummy.base_real = tkr->base + tk->offs_real;
552 update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
555 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
556 tkr_dummy.clock = &dummy_clock;
557 update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
560 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
561 #warning Please contact your maintainers, as GENERIC_TIME_VSYSCALL_OLD compatibity will disappear soon.
563 static inline void update_vsyscall(struct timekeeper *tk)
565 struct timespec xt, wm;
567 xt = timespec64_to_timespec(tk_xtime(tk));
568 wm = timespec64_to_timespec(tk->wall_to_monotonic);
569 update_vsyscall_old(&xt, &wm, tk->tkr_mono.clock, tk->tkr_mono.mult,
570 tk->tkr_mono.cycle_last);
573 static inline void old_vsyscall_fixup(struct timekeeper *tk)
578 * Store only full nanoseconds into xtime_nsec after rounding
579 * it up and add the remainder to the error difference.
580 * XXX - This is necessary to avoid small 1ns inconsistnecies caused
581 * by truncating the remainder in vsyscalls. However, it causes
582 * additional work to be done in timekeeping_adjust(). Once
583 * the vsyscall implementations are converted to use xtime_nsec
584 * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
585 * users are removed, this can be killed.
587 remainder = tk->tkr_mono.xtime_nsec & ((1ULL << tk->tkr_mono.shift) - 1);
588 if (remainder != 0) {
589 tk->tkr_mono.xtime_nsec -= remainder;
590 tk->tkr_mono.xtime_nsec += 1ULL << tk->tkr_mono.shift;
591 tk->ntp_error += remainder << tk->ntp_error_shift;
592 tk->ntp_error -= (1ULL << tk->tkr_mono.shift) << tk->ntp_error_shift;
596 #define old_vsyscall_fixup(tk)
599 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
601 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
603 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
607 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
609 int pvclock_gtod_register_notifier(struct notifier_block *nb)
611 struct timekeeper *tk = &tk_core.timekeeper;
615 raw_spin_lock_irqsave(&timekeeper_lock, flags);
616 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
617 update_pvclock_gtod(tk, true);
618 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
622 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
625 * pvclock_gtod_unregister_notifier - unregister a pvclock
626 * timedata update listener
628 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
633 raw_spin_lock_irqsave(&timekeeper_lock, flags);
634 ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
635 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
639 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
642 * tk_update_leap_state - helper to update the next_leap_ktime
644 static inline void tk_update_leap_state(struct timekeeper *tk)
646 tk->next_leap_ktime = ntp_get_next_leap();
647 if (tk->next_leap_ktime != KTIME_MAX)
648 /* Convert to monotonic time */
649 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
653 * Update the ktime_t based scalar nsec members of the timekeeper
655 static inline void tk_update_ktime_data(struct timekeeper *tk)
661 * The xtime based monotonic readout is:
662 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
663 * The ktime based monotonic readout is:
664 * nsec = base_mono + now();
665 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
667 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
668 nsec = (u32) tk->wall_to_monotonic.tv_nsec;
669 tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
672 * The sum of the nanoseconds portions of xtime and
673 * wall_to_monotonic can be greater/equal one second. Take
674 * this into account before updating tk->ktime_sec.
676 nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
677 if (nsec >= NSEC_PER_SEC)
679 tk->ktime_sec = seconds;
681 /* Update the monotonic raw base */
682 tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
685 /* must hold timekeeper_lock */
686 static void timekeeping_update(struct timekeeper *tk, unsigned int action)
688 if (action & TK_CLEAR_NTP) {
693 tk_update_leap_state(tk);
694 tk_update_ktime_data(tk);
697 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
699 tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
700 update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
701 update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
703 if (action & TK_CLOCK_WAS_SET)
704 tk->clock_was_set_seq++;
706 * The mirroring of the data to the shadow-timekeeper needs
707 * to happen last here to ensure we don't over-write the
708 * timekeeper structure on the next update with stale data
710 if (action & TK_MIRROR)
711 memcpy(&shadow_timekeeper, &tk_core.timekeeper,
712 sizeof(tk_core.timekeeper));
716 * timekeeping_forward_now - update clock to the current time
718 * Forward the current clock to update its state since the last call to
719 * update_wall_time(). This is useful before significant clock changes,
720 * as it avoids having to deal with this time offset explicitly.
722 static void timekeeping_forward_now(struct timekeeper *tk)
724 u64 cycle_now, delta;
726 cycle_now = tk_clock_read(&tk->tkr_mono);
727 delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
728 tk->tkr_mono.cycle_last = cycle_now;
729 tk->tkr_raw.cycle_last = cycle_now;
731 tk->tkr_mono.xtime_nsec += delta * tk->tkr_mono.mult;
733 /* If arch requires, add in get_arch_timeoffset() */
734 tk->tkr_mono.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_mono.shift;
737 tk->tkr_raw.xtime_nsec += delta * tk->tkr_raw.mult;
739 /* If arch requires, add in get_arch_timeoffset() */
740 tk->tkr_raw.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_raw.shift;
742 tk_normalize_xtime(tk);
746 * __getnstimeofday64 - Returns the time of day in a timespec64.
747 * @ts: pointer to the timespec to be set
749 * Updates the time of day in the timespec.
750 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
752 int __getnstimeofday64(struct timespec64 *ts)
754 struct timekeeper *tk = &tk_core.timekeeper;
759 seq = read_seqcount_begin(&tk_core.seq);
761 ts->tv_sec = tk->xtime_sec;
762 nsecs = timekeeping_get_ns(&tk->tkr_mono);
764 } while (read_seqcount_retry(&tk_core.seq, seq));
767 timespec64_add_ns(ts, nsecs);
770 * Do not bail out early, in case there were callers still using
771 * the value, even in the face of the WARN_ON.
773 if (unlikely(timekeeping_suspended))
777 EXPORT_SYMBOL(__getnstimeofday64);
780 * getnstimeofday64 - Returns the time of day in a timespec64.
781 * @ts: pointer to the timespec64 to be set
783 * Returns the time of day in a timespec64 (WARN if suspended).
785 void getnstimeofday64(struct timespec64 *ts)
787 WARN_ON(__getnstimeofday64(ts));
789 EXPORT_SYMBOL(getnstimeofday64);
791 ktime_t ktime_get(void)
793 struct timekeeper *tk = &tk_core.timekeeper;
798 WARN_ON(timekeeping_suspended);
801 seq = read_seqcount_begin(&tk_core.seq);
802 base = tk->tkr_mono.base;
803 nsecs = timekeeping_get_ns(&tk->tkr_mono);
805 } while (read_seqcount_retry(&tk_core.seq, seq));
807 return ktime_add_ns(base, nsecs);
809 EXPORT_SYMBOL_GPL(ktime_get);
811 u32 ktime_get_resolution_ns(void)
813 struct timekeeper *tk = &tk_core.timekeeper;
817 WARN_ON(timekeeping_suspended);
820 seq = read_seqcount_begin(&tk_core.seq);
821 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
822 } while (read_seqcount_retry(&tk_core.seq, seq));
826 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
828 static ktime_t *offsets[TK_OFFS_MAX] = {
829 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
830 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
831 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
834 ktime_t ktime_get_with_offset(enum tk_offsets offs)
836 struct timekeeper *tk = &tk_core.timekeeper;
838 ktime_t base, *offset = offsets[offs];
841 WARN_ON(timekeeping_suspended);
844 seq = read_seqcount_begin(&tk_core.seq);
845 base = ktime_add(tk->tkr_mono.base, *offset);
846 nsecs = timekeeping_get_ns(&tk->tkr_mono);
848 } while (read_seqcount_retry(&tk_core.seq, seq));
850 return ktime_add_ns(base, nsecs);
853 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
856 * ktime_mono_to_any() - convert mononotic time to any other time
857 * @tmono: time to convert.
858 * @offs: which offset to use
860 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
862 ktime_t *offset = offsets[offs];
867 seq = read_seqcount_begin(&tk_core.seq);
868 tconv = ktime_add(tmono, *offset);
869 } while (read_seqcount_retry(&tk_core.seq, seq));
873 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
876 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
878 ktime_t ktime_get_raw(void)
880 struct timekeeper *tk = &tk_core.timekeeper;
886 seq = read_seqcount_begin(&tk_core.seq);
887 base = tk->tkr_raw.base;
888 nsecs = timekeeping_get_ns(&tk->tkr_raw);
890 } while (read_seqcount_retry(&tk_core.seq, seq));
892 return ktime_add_ns(base, nsecs);
894 EXPORT_SYMBOL_GPL(ktime_get_raw);
897 * ktime_get_ts64 - get the monotonic clock in timespec64 format
898 * @ts: pointer to timespec variable
900 * The function calculates the monotonic clock from the realtime
901 * clock and the wall_to_monotonic offset and stores the result
902 * in normalized timespec64 format in the variable pointed to by @ts.
904 void ktime_get_ts64(struct timespec64 *ts)
906 struct timekeeper *tk = &tk_core.timekeeper;
907 struct timespec64 tomono;
911 WARN_ON(timekeeping_suspended);
914 seq = read_seqcount_begin(&tk_core.seq);
915 ts->tv_sec = tk->xtime_sec;
916 nsec = timekeeping_get_ns(&tk->tkr_mono);
917 tomono = tk->wall_to_monotonic;
919 } while (read_seqcount_retry(&tk_core.seq, seq));
921 ts->tv_sec += tomono.tv_sec;
923 timespec64_add_ns(ts, nsec + tomono.tv_nsec);
925 EXPORT_SYMBOL_GPL(ktime_get_ts64);
928 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
930 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
931 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
932 * works on both 32 and 64 bit systems. On 32 bit systems the readout
933 * covers ~136 years of uptime which should be enough to prevent
934 * premature wrap arounds.
936 time64_t ktime_get_seconds(void)
938 struct timekeeper *tk = &tk_core.timekeeper;
940 WARN_ON(timekeeping_suspended);
941 return tk->ktime_sec;
943 EXPORT_SYMBOL_GPL(ktime_get_seconds);
946 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
948 * Returns the wall clock seconds since 1970. This replaces the
949 * get_seconds() interface which is not y2038 safe on 32bit systems.
951 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
952 * 32bit systems the access must be protected with the sequence
953 * counter to provide "atomic" access to the 64bit tk->xtime_sec
956 time64_t ktime_get_real_seconds(void)
958 struct timekeeper *tk = &tk_core.timekeeper;
962 if (IS_ENABLED(CONFIG_64BIT))
963 return tk->xtime_sec;
966 seq = read_seqcount_begin(&tk_core.seq);
967 seconds = tk->xtime_sec;
969 } while (read_seqcount_retry(&tk_core.seq, seq));
973 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
976 * __ktime_get_real_seconds - The same as ktime_get_real_seconds
977 * but without the sequence counter protect. This internal function
978 * is called just when timekeeping lock is already held.
980 time64_t __ktime_get_real_seconds(void)
982 struct timekeeper *tk = &tk_core.timekeeper;
984 return tk->xtime_sec;
988 * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
989 * @systime_snapshot: pointer to struct receiving the system time snapshot
991 void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
993 struct timekeeper *tk = &tk_core.timekeeper;
1001 WARN_ON_ONCE(timekeeping_suspended);
1004 seq = read_seqcount_begin(&tk_core.seq);
1005 now = tk_clock_read(&tk->tkr_mono);
1006 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
1007 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
1008 base_real = ktime_add(tk->tkr_mono.base,
1009 tk_core.timekeeper.offs_real);
1010 base_raw = tk->tkr_raw.base;
1011 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
1012 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
1013 } while (read_seqcount_retry(&tk_core.seq, seq));
1015 systime_snapshot->cycles = now;
1016 systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
1017 systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
1019 EXPORT_SYMBOL_GPL(ktime_get_snapshot);
1021 /* Scale base by mult/div checking for overflow */
1022 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
1026 tmp = div64_u64_rem(*base, div, &rem);
1028 if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
1029 ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
1040 * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1041 * @history: Snapshot representing start of history
1042 * @partial_history_cycles: Cycle offset into history (fractional part)
1043 * @total_history_cycles: Total history length in cycles
1044 * @discontinuity: True indicates clock was set on history period
1045 * @ts: Cross timestamp that should be adjusted using
1046 * partial/total ratio
1048 * Helper function used by get_device_system_crosststamp() to correct the
1049 * crosstimestamp corresponding to the start of the current interval to the
1050 * system counter value (timestamp point) provided by the driver. The
1051 * total_history_* quantities are the total history starting at the provided
1052 * reference point and ending at the start of the current interval. The cycle
1053 * count between the driver timestamp point and the start of the current
1054 * interval is partial_history_cycles.
1056 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1057 u64 partial_history_cycles,
1058 u64 total_history_cycles,
1060 struct system_device_crosststamp *ts)
1062 struct timekeeper *tk = &tk_core.timekeeper;
1063 u64 corr_raw, corr_real;
1064 bool interp_forward;
1067 if (total_history_cycles == 0 || partial_history_cycles == 0)
1070 /* Interpolate shortest distance from beginning or end of history */
1071 interp_forward = partial_history_cycles > total_history_cycles / 2;
1072 partial_history_cycles = interp_forward ?
1073 total_history_cycles - partial_history_cycles :
1074 partial_history_cycles;
1077 * Scale the monotonic raw time delta by:
1078 * partial_history_cycles / total_history_cycles
1080 corr_raw = (u64)ktime_to_ns(
1081 ktime_sub(ts->sys_monoraw, history->raw));
1082 ret = scale64_check_overflow(partial_history_cycles,
1083 total_history_cycles, &corr_raw);
1088 * If there is a discontinuity in the history, scale monotonic raw
1090 * mult(real)/mult(raw) yielding the realtime correction
1091 * Otherwise, calculate the realtime correction similar to monotonic
1094 if (discontinuity) {
1095 corr_real = mul_u64_u32_div
1096 (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1098 corr_real = (u64)ktime_to_ns(
1099 ktime_sub(ts->sys_realtime, history->real));
1100 ret = scale64_check_overflow(partial_history_cycles,
1101 total_history_cycles, &corr_real);
1106 /* Fixup monotonic raw and real time time values */
1107 if (interp_forward) {
1108 ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1109 ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1111 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1112 ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1119 * cycle_between - true if test occurs chronologically between before and after
1121 static bool cycle_between(u64 before, u64 test, u64 after)
1123 if (test > before && test < after)
1125 if (test < before && before > after)
1131 * get_device_system_crosststamp - Synchronously capture system/device timestamp
1132 * @get_time_fn: Callback to get simultaneous device time and
1133 * system counter from the device driver
1134 * @ctx: Context passed to get_time_fn()
1135 * @history_begin: Historical reference point used to interpolate system
1136 * time when counter provided by the driver is before the current interval
1137 * @xtstamp: Receives simultaneously captured system and device time
1139 * Reads a timestamp from a device and correlates it to system time
1141 int get_device_system_crosststamp(int (*get_time_fn)
1142 (ktime_t *device_time,
1143 struct system_counterval_t *sys_counterval,
1146 struct system_time_snapshot *history_begin,
1147 struct system_device_crosststamp *xtstamp)
1149 struct system_counterval_t system_counterval;
1150 struct timekeeper *tk = &tk_core.timekeeper;
1151 u64 cycles, now, interval_start;
1152 unsigned int clock_was_set_seq = 0;
1153 ktime_t base_real, base_raw;
1154 u64 nsec_real, nsec_raw;
1155 u8 cs_was_changed_seq;
1161 seq = read_seqcount_begin(&tk_core.seq);
1163 * Try to synchronously capture device time and a system
1164 * counter value calling back into the device driver
1166 ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1171 * Verify that the clocksource associated with the captured
1172 * system counter value is the same as the currently installed
1173 * timekeeper clocksource
1175 if (tk->tkr_mono.clock != system_counterval.cs)
1177 cycles = system_counterval.cycles;
1180 * Check whether the system counter value provided by the
1181 * device driver is on the current timekeeping interval.
1183 now = tk_clock_read(&tk->tkr_mono);
1184 interval_start = tk->tkr_mono.cycle_last;
1185 if (!cycle_between(interval_start, cycles, now)) {
1186 clock_was_set_seq = tk->clock_was_set_seq;
1187 cs_was_changed_seq = tk->cs_was_changed_seq;
1188 cycles = interval_start;
1194 base_real = ktime_add(tk->tkr_mono.base,
1195 tk_core.timekeeper.offs_real);
1196 base_raw = tk->tkr_raw.base;
1198 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono,
1199 system_counterval.cycles);
1200 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw,
1201 system_counterval.cycles);
1202 } while (read_seqcount_retry(&tk_core.seq, seq));
1204 xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1205 xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1208 * Interpolate if necessary, adjusting back from the start of the
1212 u64 partial_history_cycles, total_history_cycles;
1216 * Check that the counter value occurs after the provided
1217 * history reference and that the history doesn't cross a
1218 * clocksource change
1220 if (!history_begin ||
1221 !cycle_between(history_begin->cycles,
1222 system_counterval.cycles, cycles) ||
1223 history_begin->cs_was_changed_seq != cs_was_changed_seq)
1225 partial_history_cycles = cycles - system_counterval.cycles;
1226 total_history_cycles = cycles - history_begin->cycles;
1228 history_begin->clock_was_set_seq != clock_was_set_seq;
1230 ret = adjust_historical_crosststamp(history_begin,
1231 partial_history_cycles,
1232 total_history_cycles,
1233 discontinuity, xtstamp);
1240 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1243 * do_gettimeofday - Returns the time of day in a timeval
1244 * @tv: pointer to the timeval to be set
1246 * NOTE: Users should be converted to using getnstimeofday()
1248 void do_gettimeofday(struct timeval *tv)
1250 struct timespec64 now;
1252 getnstimeofday64(&now);
1253 tv->tv_sec = now.tv_sec;
1254 tv->tv_usec = now.tv_nsec/1000;
1256 EXPORT_SYMBOL(do_gettimeofday);
1259 * do_settimeofday64 - Sets the time of day.
1260 * @ts: pointer to the timespec64 variable containing the new time
1262 * Sets the time of day to the new time and update NTP and notify hrtimers
1264 int do_settimeofday64(const struct timespec64 *ts)
1266 struct timekeeper *tk = &tk_core.timekeeper;
1267 struct timespec64 ts_delta, xt;
1268 unsigned long flags;
1271 if (!timespec64_valid_strict(ts))
1274 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1275 write_seqcount_begin(&tk_core.seq);
1277 timekeeping_forward_now(tk);
1280 ts_delta.tv_sec = ts->tv_sec - xt.tv_sec;
1281 ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
1283 if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
1288 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
1290 tk_set_xtime(tk, ts);
1292 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1294 write_seqcount_end(&tk_core.seq);
1295 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1297 /* signal hrtimers about time change */
1302 EXPORT_SYMBOL(do_settimeofday64);
1305 * timekeeping_inject_offset - Adds or subtracts from the current time.
1306 * @tv: pointer to the timespec variable containing the offset
1308 * Adds or subtracts an offset value from the current time.
1310 static int timekeeping_inject_offset(struct timespec64 *ts)
1312 struct timekeeper *tk = &tk_core.timekeeper;
1313 unsigned long flags;
1314 struct timespec64 tmp;
1317 if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1320 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1321 write_seqcount_begin(&tk_core.seq);
1323 timekeeping_forward_now(tk);
1325 /* Make sure the proposed value is valid */
1326 tmp = timespec64_add(tk_xtime(tk), *ts);
1327 if (timespec64_compare(&tk->wall_to_monotonic, ts) > 0 ||
1328 !timespec64_valid_strict(&tmp)) {
1333 tk_xtime_add(tk, ts);
1334 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *ts));
1336 error: /* even if we error out, we forwarded the time, so call update */
1337 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1339 write_seqcount_end(&tk_core.seq);
1340 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1342 /* signal hrtimers about time change */
1349 * Indicates if there is an offset between the system clock and the hardware
1350 * clock/persistent clock/rtc.
1352 int persistent_clock_is_local;
1355 * Adjust the time obtained from the CMOS to be UTC time instead of
1358 * This is ugly, but preferable to the alternatives. Otherwise we
1359 * would either need to write a program to do it in /etc/rc (and risk
1360 * confusion if the program gets run more than once; it would also be
1361 * hard to make the program warp the clock precisely n hours) or
1362 * compile in the timezone information into the kernel. Bad, bad....
1366 * The best thing to do is to keep the CMOS clock in universal time (UTC)
1367 * as real UNIX machines always do it. This avoids all headaches about
1368 * daylight saving times and warping kernel clocks.
1370 void timekeeping_warp_clock(void)
1372 if (sys_tz.tz_minuteswest != 0) {
1373 struct timespec64 adjust;
1375 persistent_clock_is_local = 1;
1376 adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1378 timekeeping_inject_offset(&adjust);
1383 * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1386 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1388 tk->tai_offset = tai_offset;
1389 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1393 * change_clocksource - Swaps clocksources if a new one is available
1395 * Accumulates current time interval and initializes new clocksource
1397 static int change_clocksource(void *data)
1399 struct timekeeper *tk = &tk_core.timekeeper;
1400 struct clocksource *new, *old;
1401 unsigned long flags;
1403 new = (struct clocksource *) data;
1405 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1406 write_seqcount_begin(&tk_core.seq);
1408 timekeeping_forward_now(tk);
1410 * If the cs is in module, get a module reference. Succeeds
1411 * for built-in code (owner == NULL) as well.
1413 if (try_module_get(new->owner)) {
1414 if (!new->enable || new->enable(new) == 0) {
1415 old = tk->tkr_mono.clock;
1416 tk_setup_internals(tk, new);
1419 module_put(old->owner);
1421 module_put(new->owner);
1424 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1426 write_seqcount_end(&tk_core.seq);
1427 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1433 * timekeeping_notify - Install a new clock source
1434 * @clock: pointer to the clock source
1436 * This function is called from clocksource.c after a new, better clock
1437 * source has been registered. The caller holds the clocksource_mutex.
1439 int timekeeping_notify(struct clocksource *clock)
1441 struct timekeeper *tk = &tk_core.timekeeper;
1443 if (tk->tkr_mono.clock == clock)
1445 stop_machine(change_clocksource, clock, NULL);
1446 tick_clock_notify();
1447 return tk->tkr_mono.clock == clock ? 0 : -1;
1451 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1452 * @ts: pointer to the timespec64 to be set
1454 * Returns the raw monotonic time (completely un-modified by ntp)
1456 void getrawmonotonic64(struct timespec64 *ts)
1458 struct timekeeper *tk = &tk_core.timekeeper;
1463 seq = read_seqcount_begin(&tk_core.seq);
1464 ts->tv_sec = tk->raw_sec;
1465 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1467 } while (read_seqcount_retry(&tk_core.seq, seq));
1470 timespec64_add_ns(ts, nsecs);
1472 EXPORT_SYMBOL(getrawmonotonic64);
1476 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1478 int timekeeping_valid_for_hres(void)
1480 struct timekeeper *tk = &tk_core.timekeeper;
1485 seq = read_seqcount_begin(&tk_core.seq);
1487 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1489 } while (read_seqcount_retry(&tk_core.seq, seq));
1495 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1497 u64 timekeeping_max_deferment(void)
1499 struct timekeeper *tk = &tk_core.timekeeper;
1504 seq = read_seqcount_begin(&tk_core.seq);
1506 ret = tk->tkr_mono.clock->max_idle_ns;
1508 } while (read_seqcount_retry(&tk_core.seq, seq));
1514 * read_persistent_clock - Return time from the persistent clock.
1516 * Weak dummy function for arches that do not yet support it.
1517 * Reads the time from the battery backed persistent clock.
1518 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1520 * XXX - Do be sure to remove it once all arches implement it.
1522 void __weak read_persistent_clock(struct timespec *ts)
1528 void __weak read_persistent_clock64(struct timespec64 *ts64)
1532 read_persistent_clock(&ts);
1533 *ts64 = timespec_to_timespec64(ts);
1537 * read_boot_clock64 - Return time of the system start.
1539 * Weak dummy function for arches that do not yet support it.
1540 * Function to read the exact time the system has been started.
1541 * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1543 * XXX - Do be sure to remove it once all arches implement it.
1545 void __weak read_boot_clock64(struct timespec64 *ts)
1551 /* Flag for if timekeeping_resume() has injected sleeptime */
1552 static bool sleeptime_injected;
1554 /* Flag for if there is a persistent clock on this platform */
1555 static bool persistent_clock_exists;
1558 * timekeeping_init - Initializes the clocksource and common timekeeping values
1560 void __init timekeeping_init(void)
1562 struct timekeeper *tk = &tk_core.timekeeper;
1563 struct clocksource *clock;
1564 unsigned long flags;
1565 struct timespec64 now, boot, tmp;
1567 read_persistent_clock64(&now);
1568 if (!timespec64_valid_strict(&now)) {
1569 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1570 " Check your CMOS/BIOS settings.\n");
1573 } else if (now.tv_sec || now.tv_nsec)
1574 persistent_clock_exists = true;
1576 read_boot_clock64(&boot);
1577 if (!timespec64_valid_strict(&boot)) {
1578 pr_warn("WARNING: Boot clock returned invalid value!\n"
1579 " Check your CMOS/BIOS settings.\n");
1584 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1585 write_seqcount_begin(&tk_core.seq);
1588 clock = clocksource_default_clock();
1590 clock->enable(clock);
1591 tk_setup_internals(tk, clock);
1593 tk_set_xtime(tk, &now);
1595 if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1596 boot = tk_xtime(tk);
1598 set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1599 tk_set_wall_to_mono(tk, tmp);
1601 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1603 write_seqcount_end(&tk_core.seq);
1604 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1607 /* time in seconds when suspend began for persistent clock */
1608 static struct timespec64 timekeeping_suspend_time;
1611 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1612 * @delta: pointer to a timespec delta value
1614 * Takes a timespec offset measuring a suspend interval and properly
1615 * adds the sleep offset to the timekeeping variables.
1617 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1618 struct timespec64 *delta)
1620 if (!timespec64_valid_strict(delta)) {
1621 printk_deferred(KERN_WARNING
1622 "__timekeeping_inject_sleeptime: Invalid "
1623 "sleep delta value!\n");
1626 tk_xtime_add(tk, delta);
1627 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1628 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1629 tk_debug_account_sleep_time(delta);
1632 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1634 * We have three kinds of time sources to use for sleep time
1635 * injection, the preference order is:
1636 * 1) non-stop clocksource
1637 * 2) persistent clock (ie: RTC accessible when irqs are off)
1640 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1641 * If system has neither 1) nor 2), 3) will be used finally.
1644 * If timekeeping has injected sleeptime via either 1) or 2),
1645 * 3) becomes needless, so in this case we don't need to call
1646 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1649 bool timekeeping_rtc_skipresume(void)
1651 return sleeptime_injected;
1655 * 1) can be determined whether to use or not only when doing
1656 * timekeeping_resume() which is invoked after rtc_suspend(),
1657 * so we can't skip rtc_suspend() surely if system has 1).
1659 * But if system has 2), 2) will definitely be used, so in this
1660 * case we don't need to call rtc_suspend(), and this is what
1661 * timekeeping_rtc_skipsuspend() means.
1663 bool timekeeping_rtc_skipsuspend(void)
1665 return persistent_clock_exists;
1669 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1670 * @delta: pointer to a timespec64 delta value
1672 * This hook is for architectures that cannot support read_persistent_clock64
1673 * because their RTC/persistent clock is only accessible when irqs are enabled.
1674 * and also don't have an effective nonstop clocksource.
1676 * This function should only be called by rtc_resume(), and allows
1677 * a suspend offset to be injected into the timekeeping values.
1679 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1681 struct timekeeper *tk = &tk_core.timekeeper;
1682 unsigned long flags;
1684 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1685 write_seqcount_begin(&tk_core.seq);
1687 timekeeping_forward_now(tk);
1689 __timekeeping_inject_sleeptime(tk, delta);
1691 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1693 write_seqcount_end(&tk_core.seq);
1694 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1696 /* signal hrtimers about time change */
1702 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1704 void timekeeping_resume(void)
1706 struct timekeeper *tk = &tk_core.timekeeper;
1707 struct clocksource *clock = tk->tkr_mono.clock;
1708 unsigned long flags;
1709 struct timespec64 ts_new, ts_delta;
1712 sleeptime_injected = false;
1713 read_persistent_clock64(&ts_new);
1715 clockevents_resume();
1716 clocksource_resume();
1718 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1719 write_seqcount_begin(&tk_core.seq);
1722 * After system resumes, we need to calculate the suspended time and
1723 * compensate it for the OS time. There are 3 sources that could be
1724 * used: Nonstop clocksource during suspend, persistent clock and rtc
1727 * One specific platform may have 1 or 2 or all of them, and the
1728 * preference will be:
1729 * suspend-nonstop clocksource -> persistent clock -> rtc
1730 * The less preferred source will only be tried if there is no better
1731 * usable source. The rtc part is handled separately in rtc core code.
1733 cycle_now = tk_clock_read(&tk->tkr_mono);
1734 if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1735 cycle_now > tk->tkr_mono.cycle_last) {
1736 u64 nsec, cyc_delta;
1738 cyc_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1740 nsec = mul_u64_u32_shr(cyc_delta, clock->mult, clock->shift);
1741 ts_delta = ns_to_timespec64(nsec);
1742 sleeptime_injected = true;
1743 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1744 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1745 sleeptime_injected = true;
1748 if (sleeptime_injected)
1749 __timekeeping_inject_sleeptime(tk, &ts_delta);
1751 /* Re-base the last cycle value */
1752 tk->tkr_mono.cycle_last = cycle_now;
1753 tk->tkr_raw.cycle_last = cycle_now;
1756 timekeeping_suspended = 0;
1757 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1758 write_seqcount_end(&tk_core.seq);
1759 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1761 touch_softlockup_watchdog();
1767 int timekeeping_suspend(void)
1769 struct timekeeper *tk = &tk_core.timekeeper;
1770 unsigned long flags;
1771 struct timespec64 delta, delta_delta;
1772 static struct timespec64 old_delta;
1774 read_persistent_clock64(&timekeeping_suspend_time);
1777 * On some systems the persistent_clock can not be detected at
1778 * timekeeping_init by its return value, so if we see a valid
1779 * value returned, update the persistent_clock_exists flag.
1781 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1782 persistent_clock_exists = true;
1784 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1785 write_seqcount_begin(&tk_core.seq);
1786 timekeeping_forward_now(tk);
1787 timekeeping_suspended = 1;
1789 if (persistent_clock_exists) {
1791 * To avoid drift caused by repeated suspend/resumes,
1792 * which each can add ~1 second drift error,
1793 * try to compensate so the difference in system time
1794 * and persistent_clock time stays close to constant.
1796 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1797 delta_delta = timespec64_sub(delta, old_delta);
1798 if (abs(delta_delta.tv_sec) >= 2) {
1800 * if delta_delta is too large, assume time correction
1801 * has occurred and set old_delta to the current delta.
1805 /* Otherwise try to adjust old_system to compensate */
1806 timekeeping_suspend_time =
1807 timespec64_add(timekeeping_suspend_time, delta_delta);
1811 timekeeping_update(tk, TK_MIRROR);
1812 halt_fast_timekeeper(tk);
1813 write_seqcount_end(&tk_core.seq);
1814 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1817 clocksource_suspend();
1818 clockevents_suspend();
1823 /* sysfs resume/suspend bits for timekeeping */
1824 static struct syscore_ops timekeeping_syscore_ops = {
1825 .resume = timekeeping_resume,
1826 .suspend = timekeeping_suspend,
1829 static int __init timekeeping_init_ops(void)
1831 register_syscore_ops(&timekeeping_syscore_ops);
1834 device_initcall(timekeeping_init_ops);
1837 * Apply a multiplier adjustment to the timekeeper
1839 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1844 s64 interval = tk->cycle_interval;
1848 mult_adj = -mult_adj;
1849 interval = -interval;
1852 mult_adj <<= adj_scale;
1853 interval <<= adj_scale;
1854 offset <<= adj_scale;
1857 * So the following can be confusing.
1859 * To keep things simple, lets assume mult_adj == 1 for now.
1861 * When mult_adj != 1, remember that the interval and offset values
1862 * have been appropriately scaled so the math is the same.
1864 * The basic idea here is that we're increasing the multiplier
1865 * by one, this causes the xtime_interval to be incremented by
1866 * one cycle_interval. This is because:
1867 * xtime_interval = cycle_interval * mult
1868 * So if mult is being incremented by one:
1869 * xtime_interval = cycle_interval * (mult + 1)
1871 * xtime_interval = (cycle_interval * mult) + cycle_interval
1872 * Which can be shortened to:
1873 * xtime_interval += cycle_interval
1875 * So offset stores the non-accumulated cycles. Thus the current
1876 * time (in shifted nanoseconds) is:
1877 * now = (offset * adj) + xtime_nsec
1878 * Now, even though we're adjusting the clock frequency, we have
1879 * to keep time consistent. In other words, we can't jump back
1880 * in time, and we also want to avoid jumping forward in time.
1882 * So given the same offset value, we need the time to be the same
1883 * both before and after the freq adjustment.
1884 * now = (offset * adj_1) + xtime_nsec_1
1885 * now = (offset * adj_2) + xtime_nsec_2
1887 * (offset * adj_1) + xtime_nsec_1 =
1888 * (offset * adj_2) + xtime_nsec_2
1892 * (offset * adj_1) + xtime_nsec_1 =
1893 * (offset * (adj_1+1)) + xtime_nsec_2
1894 * (offset * adj_1) + xtime_nsec_1 =
1895 * (offset * adj_1) + offset + xtime_nsec_2
1896 * Canceling the sides:
1897 * xtime_nsec_1 = offset + xtime_nsec_2
1899 * xtime_nsec_2 = xtime_nsec_1 - offset
1900 * Which simplfies to:
1901 * xtime_nsec -= offset
1903 * XXX - TODO: Doc ntp_error calculation.
1905 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1906 /* NTP adjustment caused clocksource mult overflow */
1911 tk->tkr_mono.mult += mult_adj;
1912 tk->xtime_interval += interval;
1913 tk->tkr_mono.xtime_nsec -= offset;
1914 tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1918 * Calculate the multiplier adjustment needed to match the frequency
1921 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1924 s64 interval = tk->cycle_interval;
1925 s64 xinterval = tk->xtime_interval;
1926 u32 base = tk->tkr_mono.clock->mult;
1927 u32 max = tk->tkr_mono.clock->maxadj;
1928 u32 cur_adj = tk->tkr_mono.mult;
1933 /* Remove any current error adj from freq calculation */
1934 if (tk->ntp_err_mult)
1935 xinterval -= tk->cycle_interval;
1937 tk->ntp_tick = ntp_tick_length();
1939 /* Calculate current error per tick */
1940 tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1941 tick_error -= (xinterval + tk->xtime_remainder);
1943 /* Don't worry about correcting it if its small */
1944 if (likely((tick_error >= 0) && (tick_error <= interval)))
1947 /* preserve the direction of correction */
1948 negative = (tick_error < 0);
1950 /* If any adjustment would pass the max, just return */
1951 if (negative && (cur_adj - 1) <= (base - max))
1953 if (!negative && (cur_adj + 1) >= (base + max))
1956 * Sort out the magnitude of the correction, but
1957 * avoid making so large a correction that we go
1958 * over the max adjustment.
1961 tick_error = abs(tick_error);
1962 while (tick_error > interval) {
1963 u32 adj = 1 << (adj_scale + 1);
1965 /* Check if adjustment gets us within 1 unit from the max */
1966 if (negative && (cur_adj - adj) <= (base - max))
1968 if (!negative && (cur_adj + adj) >= (base + max))
1975 /* scale the corrections */
1976 timekeeping_apply_adjustment(tk, offset, negative, adj_scale);
1980 * Adjust the timekeeper's multiplier to the correct frequency
1981 * and also to reduce the accumulated error value.
1983 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1985 /* Correct for the current frequency error */
1986 timekeeping_freqadjust(tk, offset);
1988 /* Next make a small adjustment to fix any cumulative error */
1989 if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1990 tk->ntp_err_mult = 1;
1991 timekeeping_apply_adjustment(tk, offset, 0, 0);
1992 } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1993 /* Undo any existing error adjustment */
1994 timekeeping_apply_adjustment(tk, offset, 1, 0);
1995 tk->ntp_err_mult = 0;
1998 if (unlikely(tk->tkr_mono.clock->maxadj &&
1999 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2000 > tk->tkr_mono.clock->maxadj))) {
2001 printk_once(KERN_WARNING
2002 "Adjusting %s more than 11%% (%ld vs %ld)\n",
2003 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2004 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
2008 * It may be possible that when we entered this function, xtime_nsec
2009 * was very small. Further, if we're slightly speeding the clocksource
2010 * in the code above, its possible the required corrective factor to
2011 * xtime_nsec could cause it to underflow.
2013 * Now, since we already accumulated the second, cannot simply roll
2014 * the accumulated second back, since the NTP subsystem has been
2015 * notified via second_overflow. So instead we push xtime_nsec forward
2016 * by the amount we underflowed, and add that amount into the error.
2018 * We'll correct this error next time through this function, when
2019 * xtime_nsec is not as small.
2021 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
2022 s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
2023 tk->tkr_mono.xtime_nsec = 0;
2024 tk->ntp_error += neg << tk->ntp_error_shift;
2029 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2031 * Helper function that accumulates the nsecs greater than a second
2032 * from the xtime_nsec field to the xtime_secs field.
2033 * It also calls into the NTP code to handle leapsecond processing.
2036 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
2038 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2039 unsigned int clock_set = 0;
2041 while (tk->tkr_mono.xtime_nsec >= nsecps) {
2044 tk->tkr_mono.xtime_nsec -= nsecps;
2047 /* Figure out if its a leap sec and apply if needed */
2048 leap = second_overflow(tk->xtime_sec);
2049 if (unlikely(leap)) {
2050 struct timespec64 ts;
2052 tk->xtime_sec += leap;
2056 tk_set_wall_to_mono(tk,
2057 timespec64_sub(tk->wall_to_monotonic, ts));
2059 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2061 clock_set = TK_CLOCK_WAS_SET;
2068 * logarithmic_accumulation - shifted accumulation of cycles
2070 * This functions accumulates a shifted interval of cycles into
2071 * into a shifted interval nanoseconds. Allows for O(log) accumulation
2074 * Returns the unconsumed cycles.
2076 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2077 u32 shift, unsigned int *clock_set)
2079 u64 interval = tk->cycle_interval << shift;
2082 /* If the offset is smaller than a shifted interval, do nothing */
2083 if (offset < interval)
2086 /* Accumulate one shifted interval */
2088 tk->tkr_mono.cycle_last += interval;
2089 tk->tkr_raw.cycle_last += interval;
2091 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2092 *clock_set |= accumulate_nsecs_to_secs(tk);
2094 /* Accumulate raw time */
2095 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2096 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2097 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2098 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2102 /* Accumulate error between NTP and clock interval */
2103 tk->ntp_error += tk->ntp_tick << shift;
2104 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2105 (tk->ntp_error_shift + shift);
2111 * update_wall_time - Uses the current clocksource to increment the wall time
2114 void update_wall_time(void)
2116 struct timekeeper *real_tk = &tk_core.timekeeper;
2117 struct timekeeper *tk = &shadow_timekeeper;
2119 int shift = 0, maxshift;
2120 unsigned int clock_set = 0;
2121 unsigned long flags;
2123 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2125 /* Make sure we're fully resumed: */
2126 if (unlikely(timekeeping_suspended))
2129 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
2130 offset = real_tk->cycle_interval;
2132 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2133 tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
2136 /* Check if there's really nothing to do */
2137 if (offset < real_tk->cycle_interval)
2140 /* Do some additional sanity checking */
2141 timekeeping_check_update(tk, offset);
2144 * With NO_HZ we may have to accumulate many cycle_intervals
2145 * (think "ticks") worth of time at once. To do this efficiently,
2146 * we calculate the largest doubling multiple of cycle_intervals
2147 * that is smaller than the offset. We then accumulate that
2148 * chunk in one go, and then try to consume the next smaller
2151 shift = ilog2(offset) - ilog2(tk->cycle_interval);
2152 shift = max(0, shift);
2153 /* Bound shift to one less than what overflows tick_length */
2154 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2155 shift = min(shift, maxshift);
2156 while (offset >= tk->cycle_interval) {
2157 offset = logarithmic_accumulation(tk, offset, shift,
2159 if (offset < tk->cycle_interval<<shift)
2163 /* correct the clock when NTP error is too big */
2164 timekeeping_adjust(tk, offset);
2167 * XXX This can be killed once everyone converts
2168 * to the new update_vsyscall.
2170 old_vsyscall_fixup(tk);
2173 * Finally, make sure that after the rounding
2174 * xtime_nsec isn't larger than NSEC_PER_SEC
2176 clock_set |= accumulate_nsecs_to_secs(tk);
2178 write_seqcount_begin(&tk_core.seq);
2180 * Update the real timekeeper.
2182 * We could avoid this memcpy by switching pointers, but that
2183 * requires changes to all other timekeeper usage sites as
2184 * well, i.e. move the timekeeper pointer getter into the
2185 * spinlocked/seqcount protected sections. And we trade this
2186 * memcpy under the tk_core.seq against one before we start
2189 timekeeping_update(tk, clock_set);
2190 memcpy(real_tk, tk, sizeof(*tk));
2191 /* The memcpy must come last. Do not put anything here! */
2192 write_seqcount_end(&tk_core.seq);
2194 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2196 /* Have to call _delayed version, since in irq context*/
2197 clock_was_set_delayed();
2201 * getboottime64 - Return the real time of system boot.
2202 * @ts: pointer to the timespec64 to be set
2204 * Returns the wall-time of boot in a timespec64.
2206 * This is based on the wall_to_monotonic offset and the total suspend
2207 * time. Calls to settimeofday will affect the value returned (which
2208 * basically means that however wrong your real time clock is at boot time,
2209 * you get the right time here).
2211 void getboottime64(struct timespec64 *ts)
2213 struct timekeeper *tk = &tk_core.timekeeper;
2214 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2216 *ts = ktime_to_timespec64(t);
2218 EXPORT_SYMBOL_GPL(getboottime64);
2220 unsigned long get_seconds(void)
2222 struct timekeeper *tk = &tk_core.timekeeper;
2224 return tk->xtime_sec;
2226 EXPORT_SYMBOL(get_seconds);
2228 struct timespec __current_kernel_time(void)
2230 struct timekeeper *tk = &tk_core.timekeeper;
2232 return timespec64_to_timespec(tk_xtime(tk));
2235 struct timespec64 current_kernel_time64(void)
2237 struct timekeeper *tk = &tk_core.timekeeper;
2238 struct timespec64 now;
2242 seq = read_seqcount_begin(&tk_core.seq);
2245 } while (read_seqcount_retry(&tk_core.seq, seq));
2249 EXPORT_SYMBOL(current_kernel_time64);
2251 struct timespec64 get_monotonic_coarse64(void)
2253 struct timekeeper *tk = &tk_core.timekeeper;
2254 struct timespec64 now, mono;
2258 seq = read_seqcount_begin(&tk_core.seq);
2261 mono = tk->wall_to_monotonic;
2262 } while (read_seqcount_retry(&tk_core.seq, seq));
2264 set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
2265 now.tv_nsec + mono.tv_nsec);
2269 EXPORT_SYMBOL(get_monotonic_coarse64);
2272 * Must hold jiffies_lock
2274 void do_timer(unsigned long ticks)
2276 jiffies_64 += ticks;
2277 calc_global_load(ticks);
2281 * ktime_get_update_offsets_now - hrtimer helper
2282 * @cwsseq: pointer to check and store the clock was set sequence number
2283 * @offs_real: pointer to storage for monotonic -> realtime offset
2284 * @offs_boot: pointer to storage for monotonic -> boottime offset
2285 * @offs_tai: pointer to storage for monotonic -> clock tai offset
2287 * Returns current monotonic time and updates the offsets if the
2288 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2291 * Called from hrtimer_interrupt() or retrigger_next_event()
2293 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2294 ktime_t *offs_boot, ktime_t *offs_tai)
2296 struct timekeeper *tk = &tk_core.timekeeper;
2302 seq = read_seqcount_begin(&tk_core.seq);
2304 base = tk->tkr_mono.base;
2305 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2306 base = ktime_add_ns(base, nsecs);
2308 if (*cwsseq != tk->clock_was_set_seq) {
2309 *cwsseq = tk->clock_was_set_seq;
2310 *offs_real = tk->offs_real;
2311 *offs_boot = tk->offs_boot;
2312 *offs_tai = tk->offs_tai;
2315 /* Handle leapsecond insertion adjustments */
2316 if (unlikely(base >= tk->next_leap_ktime))
2317 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2319 } while (read_seqcount_retry(&tk_core.seq, seq));
2325 * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2327 static int timekeeping_validate_timex(struct timex *txc)
2329 if (txc->modes & ADJ_ADJTIME) {
2330 /* singleshot must not be used with any other mode bits */
2331 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2333 if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2334 !capable(CAP_SYS_TIME))
2337 /* In order to modify anything, you gotta be super-user! */
2338 if (txc->modes && !capable(CAP_SYS_TIME))
2341 * if the quartz is off by more than 10% then
2342 * something is VERY wrong!
2344 if (txc->modes & ADJ_TICK &&
2345 (txc->tick < 900000/USER_HZ ||
2346 txc->tick > 1100000/USER_HZ))
2350 if (txc->modes & ADJ_SETOFFSET) {
2351 /* In order to inject time, you gotta be super-user! */
2352 if (!capable(CAP_SYS_TIME))
2356 * Validate if a timespec/timeval used to inject a time
2357 * offset is valid. Offsets can be postive or negative, so
2358 * we don't check tv_sec. The value of the timeval/timespec
2359 * is the sum of its fields,but *NOTE*:
2360 * The field tv_usec/tv_nsec must always be non-negative and
2361 * we can't have more nanoseconds/microseconds than a second.
2363 if (txc->time.tv_usec < 0)
2366 if (txc->modes & ADJ_NANO) {
2367 if (txc->time.tv_usec >= NSEC_PER_SEC)
2370 if (txc->time.tv_usec >= USEC_PER_SEC)
2376 * Check for potential multiplication overflows that can
2377 * only happen on 64-bit systems:
2379 if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2380 if (LLONG_MIN / PPM_SCALE > txc->freq)
2382 if (LLONG_MAX / PPM_SCALE < txc->freq)
2391 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2393 int do_adjtimex(struct timex *txc)
2395 struct timekeeper *tk = &tk_core.timekeeper;
2396 unsigned long flags;
2397 struct timespec64 ts;
2401 /* Validate the data before disabling interrupts */
2402 ret = timekeeping_validate_timex(txc);
2406 if (txc->modes & ADJ_SETOFFSET) {
2407 struct timespec64 delta;
2408 delta.tv_sec = txc->time.tv_sec;
2409 delta.tv_nsec = txc->time.tv_usec;
2410 if (!(txc->modes & ADJ_NANO))
2411 delta.tv_nsec *= 1000;
2412 ret = timekeeping_inject_offset(&delta);
2417 getnstimeofday64(&ts);
2419 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2420 write_seqcount_begin(&tk_core.seq);
2422 orig_tai = tai = tk->tai_offset;
2423 ret = __do_adjtimex(txc, &ts, &tai);
2425 if (tai != orig_tai) {
2426 __timekeeping_set_tai_offset(tk, tai);
2427 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2429 tk_update_leap_state(tk);
2431 write_seqcount_end(&tk_core.seq);
2432 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2434 if (tai != orig_tai)
2437 ntp_notify_cmos_timer();
2442 #ifdef CONFIG_NTP_PPS
2444 * hardpps() - Accessor function to NTP __hardpps function
2446 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2448 unsigned long flags;
2450 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2451 write_seqcount_begin(&tk_core.seq);
2453 __hardpps(phase_ts, raw_ts);
2455 write_seqcount_end(&tk_core.seq);
2456 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2458 EXPORT_SYMBOL(hardpps);
2459 #endif /* CONFIG_NTP_PPS */
2462 * xtime_update() - advances the timekeeping infrastructure
2463 * @ticks: number of ticks, that have elapsed since the last call.
2465 * Must be called with interrupts disabled.
2467 void xtime_update(unsigned long ticks)
2469 write_seqlock(&jiffies_lock);
2471 write_sequnlock(&jiffies_lock);