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 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain
);
562 static void update_pvclock_gtod(struct timekeeper
*tk
, bool was_set
)
564 raw_notifier_call_chain(&pvclock_gtod_chain
, was_set
, tk
);
568 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
570 int pvclock_gtod_register_notifier(struct notifier_block
*nb
)
572 struct timekeeper
*tk
= &tk_core
.timekeeper
;
576 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
577 ret
= raw_notifier_chain_register(&pvclock_gtod_chain
, nb
);
578 update_pvclock_gtod(tk
, true);
579 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
583 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier
);
586 * pvclock_gtod_unregister_notifier - unregister a pvclock
587 * timedata update listener
589 int pvclock_gtod_unregister_notifier(struct notifier_block
*nb
)
594 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
595 ret
= raw_notifier_chain_unregister(&pvclock_gtod_chain
, nb
);
596 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
600 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier
);
603 * tk_update_leap_state - helper to update the next_leap_ktime
605 static inline void tk_update_leap_state(struct timekeeper
*tk
)
607 tk
->next_leap_ktime
= ntp_get_next_leap();
608 if (tk
->next_leap_ktime
!= KTIME_MAX
)
609 /* Convert to monotonic time */
610 tk
->next_leap_ktime
= ktime_sub(tk
->next_leap_ktime
, tk
->offs_real
);
614 * Update the ktime_t based scalar nsec members of the timekeeper
616 static inline void tk_update_ktime_data(struct timekeeper
*tk
)
622 * The xtime based monotonic readout is:
623 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
624 * The ktime based monotonic readout is:
625 * nsec = base_mono + now();
626 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
628 seconds
= (u64
)(tk
->xtime_sec
+ tk
->wall_to_monotonic
.tv_sec
);
629 nsec
= (u32
) tk
->wall_to_monotonic
.tv_nsec
;
630 tk
->tkr_mono
.base
= ns_to_ktime(seconds
* NSEC_PER_SEC
+ nsec
);
633 * The sum of the nanoseconds portions of xtime and
634 * wall_to_monotonic can be greater/equal one second. Take
635 * this into account before updating tk->ktime_sec.
637 nsec
+= (u32
)(tk
->tkr_mono
.xtime_nsec
>> tk
->tkr_mono
.shift
);
638 if (nsec
>= NSEC_PER_SEC
)
640 tk
->ktime_sec
= seconds
;
642 /* Update the monotonic raw base */
643 tk
->tkr_raw
.base
= ns_to_ktime(tk
->raw_sec
* NSEC_PER_SEC
);
646 /* must hold timekeeper_lock */
647 static void timekeeping_update(struct timekeeper
*tk
, unsigned int action
)
649 if (action
& TK_CLEAR_NTP
) {
654 tk_update_leap_state(tk
);
655 tk_update_ktime_data(tk
);
658 update_pvclock_gtod(tk
, action
& TK_CLOCK_WAS_SET
);
660 tk
->tkr_mono
.base_real
= tk
->tkr_mono
.base
+ tk
->offs_real
;
661 update_fast_timekeeper(&tk
->tkr_mono
, &tk_fast_mono
);
662 update_fast_timekeeper(&tk
->tkr_raw
, &tk_fast_raw
);
664 if (action
& TK_CLOCK_WAS_SET
)
665 tk
->clock_was_set_seq
++;
667 * The mirroring of the data to the shadow-timekeeper needs
668 * to happen last here to ensure we don't over-write the
669 * timekeeper structure on the next update with stale data
671 if (action
& TK_MIRROR
)
672 memcpy(&shadow_timekeeper
, &tk_core
.timekeeper
,
673 sizeof(tk_core
.timekeeper
));
677 * timekeeping_forward_now - update clock to the current time
679 * Forward the current clock to update its state since the last call to
680 * update_wall_time(). This is useful before significant clock changes,
681 * as it avoids having to deal with this time offset explicitly.
683 static void timekeeping_forward_now(struct timekeeper
*tk
)
685 u64 cycle_now
, delta
;
687 cycle_now
= tk_clock_read(&tk
->tkr_mono
);
688 delta
= clocksource_delta(cycle_now
, tk
->tkr_mono
.cycle_last
, tk
->tkr_mono
.mask
);
689 tk
->tkr_mono
.cycle_last
= cycle_now
;
690 tk
->tkr_raw
.cycle_last
= cycle_now
;
692 tk
->tkr_mono
.xtime_nsec
+= delta
* tk
->tkr_mono
.mult
;
694 /* If arch requires, add in get_arch_timeoffset() */
695 tk
->tkr_mono
.xtime_nsec
+= (u64
)arch_gettimeoffset() << tk
->tkr_mono
.shift
;
698 tk
->tkr_raw
.xtime_nsec
+= delta
* tk
->tkr_raw
.mult
;
700 /* If arch requires, add in get_arch_timeoffset() */
701 tk
->tkr_raw
.xtime_nsec
+= (u64
)arch_gettimeoffset() << tk
->tkr_raw
.shift
;
703 tk_normalize_xtime(tk
);
707 * __getnstimeofday64 - Returns the time of day in a timespec64.
708 * @ts: pointer to the timespec to be set
710 * Updates the time of day in the timespec.
711 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
713 int __getnstimeofday64(struct timespec64
*ts
)
715 struct timekeeper
*tk
= &tk_core
.timekeeper
;
720 seq
= read_seqcount_begin(&tk_core
.seq
);
722 ts
->tv_sec
= tk
->xtime_sec
;
723 nsecs
= timekeeping_get_ns(&tk
->tkr_mono
);
725 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
728 timespec64_add_ns(ts
, nsecs
);
731 * Do not bail out early, in case there were callers still using
732 * the value, even in the face of the WARN_ON.
734 if (unlikely(timekeeping_suspended
))
738 EXPORT_SYMBOL(__getnstimeofday64
);
741 * getnstimeofday64 - Returns the time of day in a timespec64.
742 * @ts: pointer to the timespec64 to be set
744 * Returns the time of day in a timespec64 (WARN if suspended).
746 void getnstimeofday64(struct timespec64
*ts
)
748 WARN_ON(__getnstimeofday64(ts
));
750 EXPORT_SYMBOL(getnstimeofday64
);
752 ktime_t
ktime_get(void)
754 struct timekeeper
*tk
= &tk_core
.timekeeper
;
759 WARN_ON(timekeeping_suspended
);
762 seq
= read_seqcount_begin(&tk_core
.seq
);
763 base
= tk
->tkr_mono
.base
;
764 nsecs
= timekeeping_get_ns(&tk
->tkr_mono
);
766 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
768 return ktime_add_ns(base
, nsecs
);
770 EXPORT_SYMBOL_GPL(ktime_get
);
772 u32
ktime_get_resolution_ns(void)
774 struct timekeeper
*tk
= &tk_core
.timekeeper
;
778 WARN_ON(timekeeping_suspended
);
781 seq
= read_seqcount_begin(&tk_core
.seq
);
782 nsecs
= tk
->tkr_mono
.mult
>> tk
->tkr_mono
.shift
;
783 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
787 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns
);
789 static ktime_t
*offsets
[TK_OFFS_MAX
] = {
790 [TK_OFFS_REAL
] = &tk_core
.timekeeper
.offs_real
,
791 [TK_OFFS_BOOT
] = &tk_core
.timekeeper
.offs_boot
,
792 [TK_OFFS_TAI
] = &tk_core
.timekeeper
.offs_tai
,
795 ktime_t
ktime_get_with_offset(enum tk_offsets offs
)
797 struct timekeeper
*tk
= &tk_core
.timekeeper
;
799 ktime_t base
, *offset
= offsets
[offs
];
802 WARN_ON(timekeeping_suspended
);
805 seq
= read_seqcount_begin(&tk_core
.seq
);
806 base
= ktime_add(tk
->tkr_mono
.base
, *offset
);
807 nsecs
= timekeeping_get_ns(&tk
->tkr_mono
);
809 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
811 return ktime_add_ns(base
, nsecs
);
814 EXPORT_SYMBOL_GPL(ktime_get_with_offset
);
817 * ktime_mono_to_any() - convert mononotic time to any other time
818 * @tmono: time to convert.
819 * @offs: which offset to use
821 ktime_t
ktime_mono_to_any(ktime_t tmono
, enum tk_offsets offs
)
823 ktime_t
*offset
= offsets
[offs
];
828 seq
= read_seqcount_begin(&tk_core
.seq
);
829 tconv
= ktime_add(tmono
, *offset
);
830 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
834 EXPORT_SYMBOL_GPL(ktime_mono_to_any
);
837 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
839 ktime_t
ktime_get_raw(void)
841 struct timekeeper
*tk
= &tk_core
.timekeeper
;
847 seq
= read_seqcount_begin(&tk_core
.seq
);
848 base
= tk
->tkr_raw
.base
;
849 nsecs
= timekeeping_get_ns(&tk
->tkr_raw
);
851 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
853 return ktime_add_ns(base
, nsecs
);
855 EXPORT_SYMBOL_GPL(ktime_get_raw
);
858 * ktime_get_ts64 - get the monotonic clock in timespec64 format
859 * @ts: pointer to timespec variable
861 * The function calculates the monotonic clock from the realtime
862 * clock and the wall_to_monotonic offset and stores the result
863 * in normalized timespec64 format in the variable pointed to by @ts.
865 void ktime_get_ts64(struct timespec64
*ts
)
867 struct timekeeper
*tk
= &tk_core
.timekeeper
;
868 struct timespec64 tomono
;
872 WARN_ON(timekeeping_suspended
);
875 seq
= read_seqcount_begin(&tk_core
.seq
);
876 ts
->tv_sec
= tk
->xtime_sec
;
877 nsec
= timekeeping_get_ns(&tk
->tkr_mono
);
878 tomono
= tk
->wall_to_monotonic
;
880 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
882 ts
->tv_sec
+= tomono
.tv_sec
;
884 timespec64_add_ns(ts
, nsec
+ tomono
.tv_nsec
);
886 EXPORT_SYMBOL_GPL(ktime_get_ts64
);
889 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
891 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
892 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
893 * works on both 32 and 64 bit systems. On 32 bit systems the readout
894 * covers ~136 years of uptime which should be enough to prevent
895 * premature wrap arounds.
897 time64_t
ktime_get_seconds(void)
899 struct timekeeper
*tk
= &tk_core
.timekeeper
;
901 WARN_ON(timekeeping_suspended
);
902 return tk
->ktime_sec
;
904 EXPORT_SYMBOL_GPL(ktime_get_seconds
);
907 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
909 * Returns the wall clock seconds since 1970. This replaces the
910 * get_seconds() interface which is not y2038 safe on 32bit systems.
912 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
913 * 32bit systems the access must be protected with the sequence
914 * counter to provide "atomic" access to the 64bit tk->xtime_sec
917 time64_t
ktime_get_real_seconds(void)
919 struct timekeeper
*tk
= &tk_core
.timekeeper
;
923 if (IS_ENABLED(CONFIG_64BIT
))
924 return tk
->xtime_sec
;
927 seq
= read_seqcount_begin(&tk_core
.seq
);
928 seconds
= tk
->xtime_sec
;
930 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
934 EXPORT_SYMBOL_GPL(ktime_get_real_seconds
);
937 * __ktime_get_real_seconds - The same as ktime_get_real_seconds
938 * but without the sequence counter protect. This internal function
939 * is called just when timekeeping lock is already held.
941 time64_t
__ktime_get_real_seconds(void)
943 struct timekeeper
*tk
= &tk_core
.timekeeper
;
945 return tk
->xtime_sec
;
949 * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
950 * @systime_snapshot: pointer to struct receiving the system time snapshot
952 void ktime_get_snapshot(struct system_time_snapshot
*systime_snapshot
)
954 struct timekeeper
*tk
= &tk_core
.timekeeper
;
962 WARN_ON_ONCE(timekeeping_suspended
);
965 seq
= read_seqcount_begin(&tk_core
.seq
);
966 now
= tk_clock_read(&tk
->tkr_mono
);
967 systime_snapshot
->cs_was_changed_seq
= tk
->cs_was_changed_seq
;
968 systime_snapshot
->clock_was_set_seq
= tk
->clock_was_set_seq
;
969 base_real
= ktime_add(tk
->tkr_mono
.base
,
970 tk_core
.timekeeper
.offs_real
);
971 base_raw
= tk
->tkr_raw
.base
;
972 nsec_real
= timekeeping_cycles_to_ns(&tk
->tkr_mono
, now
);
973 nsec_raw
= timekeeping_cycles_to_ns(&tk
->tkr_raw
, now
);
974 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
976 systime_snapshot
->cycles
= now
;
977 systime_snapshot
->real
= ktime_add_ns(base_real
, nsec_real
);
978 systime_snapshot
->raw
= ktime_add_ns(base_raw
, nsec_raw
);
980 EXPORT_SYMBOL_GPL(ktime_get_snapshot
);
982 /* Scale base by mult/div checking for overflow */
983 static int scale64_check_overflow(u64 mult
, u64 div
, u64
*base
)
987 tmp
= div64_u64_rem(*base
, div
, &rem
);
989 if (((int)sizeof(u64
)*8 - fls64(mult
) < fls64(tmp
)) ||
990 ((int)sizeof(u64
)*8 - fls64(mult
) < fls64(rem
)))
1001 * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1002 * @history: Snapshot representing start of history
1003 * @partial_history_cycles: Cycle offset into history (fractional part)
1004 * @total_history_cycles: Total history length in cycles
1005 * @discontinuity: True indicates clock was set on history period
1006 * @ts: Cross timestamp that should be adjusted using
1007 * partial/total ratio
1009 * Helper function used by get_device_system_crosststamp() to correct the
1010 * crosstimestamp corresponding to the start of the current interval to the
1011 * system counter value (timestamp point) provided by the driver. The
1012 * total_history_* quantities are the total history starting at the provided
1013 * reference point and ending at the start of the current interval. The cycle
1014 * count between the driver timestamp point and the start of the current
1015 * interval is partial_history_cycles.
1017 static int adjust_historical_crosststamp(struct system_time_snapshot
*history
,
1018 u64 partial_history_cycles
,
1019 u64 total_history_cycles
,
1021 struct system_device_crosststamp
*ts
)
1023 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1024 u64 corr_raw
, corr_real
;
1025 bool interp_forward
;
1028 if (total_history_cycles
== 0 || partial_history_cycles
== 0)
1031 /* Interpolate shortest distance from beginning or end of history */
1032 interp_forward
= partial_history_cycles
> total_history_cycles
/ 2;
1033 partial_history_cycles
= interp_forward
?
1034 total_history_cycles
- partial_history_cycles
:
1035 partial_history_cycles
;
1038 * Scale the monotonic raw time delta by:
1039 * partial_history_cycles / total_history_cycles
1041 corr_raw
= (u64
)ktime_to_ns(
1042 ktime_sub(ts
->sys_monoraw
, history
->raw
));
1043 ret
= scale64_check_overflow(partial_history_cycles
,
1044 total_history_cycles
, &corr_raw
);
1049 * If there is a discontinuity in the history, scale monotonic raw
1051 * mult(real)/mult(raw) yielding the realtime correction
1052 * Otherwise, calculate the realtime correction similar to monotonic
1055 if (discontinuity
) {
1056 corr_real
= mul_u64_u32_div
1057 (corr_raw
, tk
->tkr_mono
.mult
, tk
->tkr_raw
.mult
);
1059 corr_real
= (u64
)ktime_to_ns(
1060 ktime_sub(ts
->sys_realtime
, history
->real
));
1061 ret
= scale64_check_overflow(partial_history_cycles
,
1062 total_history_cycles
, &corr_real
);
1067 /* Fixup monotonic raw and real time time values */
1068 if (interp_forward
) {
1069 ts
->sys_monoraw
= ktime_add_ns(history
->raw
, corr_raw
);
1070 ts
->sys_realtime
= ktime_add_ns(history
->real
, corr_real
);
1072 ts
->sys_monoraw
= ktime_sub_ns(ts
->sys_monoraw
, corr_raw
);
1073 ts
->sys_realtime
= ktime_sub_ns(ts
->sys_realtime
, corr_real
);
1080 * cycle_between - true if test occurs chronologically between before and after
1082 static bool cycle_between(u64 before
, u64 test
, u64 after
)
1084 if (test
> before
&& test
< after
)
1086 if (test
< before
&& before
> after
)
1092 * get_device_system_crosststamp - Synchronously capture system/device timestamp
1093 * @get_time_fn: Callback to get simultaneous device time and
1094 * system counter from the device driver
1095 * @ctx: Context passed to get_time_fn()
1096 * @history_begin: Historical reference point used to interpolate system
1097 * time when counter provided by the driver is before the current interval
1098 * @xtstamp: Receives simultaneously captured system and device time
1100 * Reads a timestamp from a device and correlates it to system time
1102 int get_device_system_crosststamp(int (*get_time_fn
)
1103 (ktime_t
*device_time
,
1104 struct system_counterval_t
*sys_counterval
,
1107 struct system_time_snapshot
*history_begin
,
1108 struct system_device_crosststamp
*xtstamp
)
1110 struct system_counterval_t system_counterval
;
1111 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1112 u64 cycles
, now
, interval_start
;
1113 unsigned int clock_was_set_seq
= 0;
1114 ktime_t base_real
, base_raw
;
1115 u64 nsec_real
, nsec_raw
;
1116 u8 cs_was_changed_seq
;
1122 seq
= read_seqcount_begin(&tk_core
.seq
);
1124 * Try to synchronously capture device time and a system
1125 * counter value calling back into the device driver
1127 ret
= get_time_fn(&xtstamp
->device
, &system_counterval
, ctx
);
1132 * Verify that the clocksource associated with the captured
1133 * system counter value is the same as the currently installed
1134 * timekeeper clocksource
1136 if (tk
->tkr_mono
.clock
!= system_counterval
.cs
)
1138 cycles
= system_counterval
.cycles
;
1141 * Check whether the system counter value provided by the
1142 * device driver is on the current timekeeping interval.
1144 now
= tk_clock_read(&tk
->tkr_mono
);
1145 interval_start
= tk
->tkr_mono
.cycle_last
;
1146 if (!cycle_between(interval_start
, cycles
, now
)) {
1147 clock_was_set_seq
= tk
->clock_was_set_seq
;
1148 cs_was_changed_seq
= tk
->cs_was_changed_seq
;
1149 cycles
= interval_start
;
1155 base_real
= ktime_add(tk
->tkr_mono
.base
,
1156 tk_core
.timekeeper
.offs_real
);
1157 base_raw
= tk
->tkr_raw
.base
;
1159 nsec_real
= timekeeping_cycles_to_ns(&tk
->tkr_mono
,
1160 system_counterval
.cycles
);
1161 nsec_raw
= timekeeping_cycles_to_ns(&tk
->tkr_raw
,
1162 system_counterval
.cycles
);
1163 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1165 xtstamp
->sys_realtime
= ktime_add_ns(base_real
, nsec_real
);
1166 xtstamp
->sys_monoraw
= ktime_add_ns(base_raw
, nsec_raw
);
1169 * Interpolate if necessary, adjusting back from the start of the
1173 u64 partial_history_cycles
, total_history_cycles
;
1177 * Check that the counter value occurs after the provided
1178 * history reference and that the history doesn't cross a
1179 * clocksource change
1181 if (!history_begin
||
1182 !cycle_between(history_begin
->cycles
,
1183 system_counterval
.cycles
, cycles
) ||
1184 history_begin
->cs_was_changed_seq
!= cs_was_changed_seq
)
1186 partial_history_cycles
= cycles
- system_counterval
.cycles
;
1187 total_history_cycles
= cycles
- history_begin
->cycles
;
1189 history_begin
->clock_was_set_seq
!= clock_was_set_seq
;
1191 ret
= adjust_historical_crosststamp(history_begin
,
1192 partial_history_cycles
,
1193 total_history_cycles
,
1194 discontinuity
, xtstamp
);
1201 EXPORT_SYMBOL_GPL(get_device_system_crosststamp
);
1204 * do_gettimeofday - Returns the time of day in a timeval
1205 * @tv: pointer to the timeval to be set
1207 * NOTE: Users should be converted to using getnstimeofday()
1209 void do_gettimeofday(struct timeval
*tv
)
1211 struct timespec64 now
;
1213 getnstimeofday64(&now
);
1214 tv
->tv_sec
= now
.tv_sec
;
1215 tv
->tv_usec
= now
.tv_nsec
/1000;
1217 EXPORT_SYMBOL(do_gettimeofday
);
1220 * do_settimeofday64 - Sets the time of day.
1221 * @ts: pointer to the timespec64 variable containing the new time
1223 * Sets the time of day to the new time and update NTP and notify hrtimers
1225 int do_settimeofday64(const struct timespec64
*ts
)
1227 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1228 struct timespec64 ts_delta
, xt
;
1229 unsigned long flags
;
1232 if (!timespec64_valid_strict(ts
))
1235 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1236 write_seqcount_begin(&tk_core
.seq
);
1238 timekeeping_forward_now(tk
);
1241 ts_delta
.tv_sec
= ts
->tv_sec
- xt
.tv_sec
;
1242 ts_delta
.tv_nsec
= ts
->tv_nsec
- xt
.tv_nsec
;
1244 if (timespec64_compare(&tk
->wall_to_monotonic
, &ts_delta
) > 0) {
1249 tk_set_wall_to_mono(tk
, timespec64_sub(tk
->wall_to_monotonic
, ts_delta
));
1251 tk_set_xtime(tk
, ts
);
1253 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
1255 write_seqcount_end(&tk_core
.seq
);
1256 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1258 /* signal hrtimers about time change */
1263 EXPORT_SYMBOL(do_settimeofday64
);
1266 * timekeeping_inject_offset - Adds or subtracts from the current time.
1267 * @tv: pointer to the timespec variable containing the offset
1269 * Adds or subtracts an offset value from the current time.
1271 static int timekeeping_inject_offset(struct timespec64
*ts
)
1273 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1274 unsigned long flags
;
1275 struct timespec64 tmp
;
1278 if (ts
->tv_nsec
< 0 || ts
->tv_nsec
>= NSEC_PER_SEC
)
1281 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1282 write_seqcount_begin(&tk_core
.seq
);
1284 timekeeping_forward_now(tk
);
1286 /* Make sure the proposed value is valid */
1287 tmp
= timespec64_add(tk_xtime(tk
), *ts
);
1288 if (timespec64_compare(&tk
->wall_to_monotonic
, ts
) > 0 ||
1289 !timespec64_valid_strict(&tmp
)) {
1294 tk_xtime_add(tk
, ts
);
1295 tk_set_wall_to_mono(tk
, timespec64_sub(tk
->wall_to_monotonic
, *ts
));
1297 error
: /* even if we error out, we forwarded the time, so call update */
1298 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
1300 write_seqcount_end(&tk_core
.seq
);
1301 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1303 /* signal hrtimers about time change */
1310 * Indicates if there is an offset between the system clock and the hardware
1311 * clock/persistent clock/rtc.
1313 int persistent_clock_is_local
;
1316 * Adjust the time obtained from the CMOS to be UTC time instead of
1319 * This is ugly, but preferable to the alternatives. Otherwise we
1320 * would either need to write a program to do it in /etc/rc (and risk
1321 * confusion if the program gets run more than once; it would also be
1322 * hard to make the program warp the clock precisely n hours) or
1323 * compile in the timezone information into the kernel. Bad, bad....
1327 * The best thing to do is to keep the CMOS clock in universal time (UTC)
1328 * as real UNIX machines always do it. This avoids all headaches about
1329 * daylight saving times and warping kernel clocks.
1331 void timekeeping_warp_clock(void)
1333 if (sys_tz
.tz_minuteswest
!= 0) {
1334 struct timespec64 adjust
;
1336 persistent_clock_is_local
= 1;
1337 adjust
.tv_sec
= sys_tz
.tz_minuteswest
* 60;
1339 timekeeping_inject_offset(&adjust
);
1344 * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1347 static void __timekeeping_set_tai_offset(struct timekeeper
*tk
, s32 tai_offset
)
1349 tk
->tai_offset
= tai_offset
;
1350 tk
->offs_tai
= ktime_add(tk
->offs_real
, ktime_set(tai_offset
, 0));
1354 * change_clocksource - Swaps clocksources if a new one is available
1356 * Accumulates current time interval and initializes new clocksource
1358 static int change_clocksource(void *data
)
1360 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1361 struct clocksource
*new, *old
;
1362 unsigned long flags
;
1364 new = (struct clocksource
*) data
;
1366 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1367 write_seqcount_begin(&tk_core
.seq
);
1369 timekeeping_forward_now(tk
);
1371 * If the cs is in module, get a module reference. Succeeds
1372 * for built-in code (owner == NULL) as well.
1374 if (try_module_get(new->owner
)) {
1375 if (!new->enable
|| new->enable(new) == 0) {
1376 old
= tk
->tkr_mono
.clock
;
1377 tk_setup_internals(tk
, new);
1380 module_put(old
->owner
);
1382 module_put(new->owner
);
1385 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
1387 write_seqcount_end(&tk_core
.seq
);
1388 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1394 * timekeeping_notify - Install a new clock source
1395 * @clock: pointer to the clock source
1397 * This function is called from clocksource.c after a new, better clock
1398 * source has been registered. The caller holds the clocksource_mutex.
1400 int timekeeping_notify(struct clocksource
*clock
)
1402 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1404 if (tk
->tkr_mono
.clock
== clock
)
1406 stop_machine(change_clocksource
, clock
, NULL
);
1407 tick_clock_notify();
1408 return tk
->tkr_mono
.clock
== clock
? 0 : -1;
1412 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1413 * @ts: pointer to the timespec64 to be set
1415 * Returns the raw monotonic time (completely un-modified by ntp)
1417 void getrawmonotonic64(struct timespec64
*ts
)
1419 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1424 seq
= read_seqcount_begin(&tk_core
.seq
);
1425 ts
->tv_sec
= tk
->raw_sec
;
1426 nsecs
= timekeeping_get_ns(&tk
->tkr_raw
);
1428 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1431 timespec64_add_ns(ts
, nsecs
);
1433 EXPORT_SYMBOL(getrawmonotonic64
);
1437 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1439 int timekeeping_valid_for_hres(void)
1441 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1446 seq
= read_seqcount_begin(&tk_core
.seq
);
1448 ret
= tk
->tkr_mono
.clock
->flags
& CLOCK_SOURCE_VALID_FOR_HRES
;
1450 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1456 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1458 u64
timekeeping_max_deferment(void)
1460 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1465 seq
= read_seqcount_begin(&tk_core
.seq
);
1467 ret
= tk
->tkr_mono
.clock
->max_idle_ns
;
1469 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1475 * read_persistent_clock - Return time from the persistent clock.
1477 * Weak dummy function for arches that do not yet support it.
1478 * Reads the time from the battery backed persistent clock.
1479 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1481 * XXX - Do be sure to remove it once all arches implement it.
1483 void __weak
read_persistent_clock(struct timespec
*ts
)
1489 void __weak
read_persistent_clock64(struct timespec64
*ts64
)
1493 read_persistent_clock(&ts
);
1494 *ts64
= timespec_to_timespec64(ts
);
1498 * read_boot_clock64 - Return time of the system start.
1500 * Weak dummy function for arches that do not yet support it.
1501 * Function to read the exact time the system has been started.
1502 * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1504 * XXX - Do be sure to remove it once all arches implement it.
1506 void __weak
read_boot_clock64(struct timespec64
*ts
)
1512 /* Flag for if timekeeping_resume() has injected sleeptime */
1513 static bool sleeptime_injected
;
1515 /* Flag for if there is a persistent clock on this platform */
1516 static bool persistent_clock_exists
;
1519 * timekeeping_init - Initializes the clocksource and common timekeeping values
1521 void __init
timekeeping_init(void)
1523 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1524 struct clocksource
*clock
;
1525 unsigned long flags
;
1526 struct timespec64 now
, boot
, tmp
;
1528 read_persistent_clock64(&now
);
1529 if (!timespec64_valid_strict(&now
)) {
1530 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1531 " Check your CMOS/BIOS settings.\n");
1534 } else if (now
.tv_sec
|| now
.tv_nsec
)
1535 persistent_clock_exists
= true;
1537 read_boot_clock64(&boot
);
1538 if (!timespec64_valid_strict(&boot
)) {
1539 pr_warn("WARNING: Boot clock returned invalid value!\n"
1540 " Check your CMOS/BIOS settings.\n");
1545 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1546 write_seqcount_begin(&tk_core
.seq
);
1549 clock
= clocksource_default_clock();
1551 clock
->enable(clock
);
1552 tk_setup_internals(tk
, clock
);
1554 tk_set_xtime(tk
, &now
);
1556 if (boot
.tv_sec
== 0 && boot
.tv_nsec
== 0)
1557 boot
= tk_xtime(tk
);
1559 set_normalized_timespec64(&tmp
, -boot
.tv_sec
, -boot
.tv_nsec
);
1560 tk_set_wall_to_mono(tk
, tmp
);
1562 timekeeping_update(tk
, TK_MIRROR
| TK_CLOCK_WAS_SET
);
1564 write_seqcount_end(&tk_core
.seq
);
1565 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1568 /* time in seconds when suspend began for persistent clock */
1569 static struct timespec64 timekeeping_suspend_time
;
1572 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1573 * @delta: pointer to a timespec delta value
1575 * Takes a timespec offset measuring a suspend interval and properly
1576 * adds the sleep offset to the timekeeping variables.
1578 static void __timekeeping_inject_sleeptime(struct timekeeper
*tk
,
1579 struct timespec64
*delta
)
1581 if (!timespec64_valid_strict(delta
)) {
1582 printk_deferred(KERN_WARNING
1583 "__timekeeping_inject_sleeptime: Invalid "
1584 "sleep delta value!\n");
1587 tk_xtime_add(tk
, delta
);
1588 tk_set_wall_to_mono(tk
, timespec64_sub(tk
->wall_to_monotonic
, *delta
));
1589 tk_update_sleep_time(tk
, timespec64_to_ktime(*delta
));
1590 tk_debug_account_sleep_time(delta
);
1593 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1595 * We have three kinds of time sources to use for sleep time
1596 * injection, the preference order is:
1597 * 1) non-stop clocksource
1598 * 2) persistent clock (ie: RTC accessible when irqs are off)
1601 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1602 * If system has neither 1) nor 2), 3) will be used finally.
1605 * If timekeeping has injected sleeptime via either 1) or 2),
1606 * 3) becomes needless, so in this case we don't need to call
1607 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1610 bool timekeeping_rtc_skipresume(void)
1612 return sleeptime_injected
;
1616 * 1) can be determined whether to use or not only when doing
1617 * timekeeping_resume() which is invoked after rtc_suspend(),
1618 * so we can't skip rtc_suspend() surely if system has 1).
1620 * But if system has 2), 2) will definitely be used, so in this
1621 * case we don't need to call rtc_suspend(), and this is what
1622 * timekeeping_rtc_skipsuspend() means.
1624 bool timekeeping_rtc_skipsuspend(void)
1626 return persistent_clock_exists
;
1630 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1631 * @delta: pointer to a timespec64 delta value
1633 * This hook is for architectures that cannot support read_persistent_clock64
1634 * because their RTC/persistent clock is only accessible when irqs are enabled.
1635 * and also don't have an effective nonstop clocksource.
1637 * This function should only be called by rtc_resume(), and allows
1638 * a suspend offset to be injected into the timekeeping values.
1640 void timekeeping_inject_sleeptime64(struct timespec64
*delta
)
1642 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1643 unsigned long flags
;
1645 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1646 write_seqcount_begin(&tk_core
.seq
);
1648 timekeeping_forward_now(tk
);
1650 __timekeeping_inject_sleeptime(tk
, delta
);
1652 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
1654 write_seqcount_end(&tk_core
.seq
);
1655 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1657 /* signal hrtimers about time change */
1663 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1665 void timekeeping_resume(void)
1667 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1668 struct clocksource
*clock
= tk
->tkr_mono
.clock
;
1669 unsigned long flags
;
1670 struct timespec64 ts_new
, ts_delta
;
1673 sleeptime_injected
= false;
1674 read_persistent_clock64(&ts_new
);
1676 clockevents_resume();
1677 clocksource_resume();
1679 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1680 write_seqcount_begin(&tk_core
.seq
);
1683 * After system resumes, we need to calculate the suspended time and
1684 * compensate it for the OS time. There are 3 sources that could be
1685 * used: Nonstop clocksource during suspend, persistent clock and rtc
1688 * One specific platform may have 1 or 2 or all of them, and the
1689 * preference will be:
1690 * suspend-nonstop clocksource -> persistent clock -> rtc
1691 * The less preferred source will only be tried if there is no better
1692 * usable source. The rtc part is handled separately in rtc core code.
1694 cycle_now
= tk_clock_read(&tk
->tkr_mono
);
1695 if ((clock
->flags
& CLOCK_SOURCE_SUSPEND_NONSTOP
) &&
1696 cycle_now
> tk
->tkr_mono
.cycle_last
) {
1697 u64 nsec
, cyc_delta
;
1699 cyc_delta
= clocksource_delta(cycle_now
, tk
->tkr_mono
.cycle_last
,
1701 nsec
= mul_u64_u32_shr(cyc_delta
, clock
->mult
, clock
->shift
);
1702 ts_delta
= ns_to_timespec64(nsec
);
1703 sleeptime_injected
= true;
1704 } else if (timespec64_compare(&ts_new
, &timekeeping_suspend_time
) > 0) {
1705 ts_delta
= timespec64_sub(ts_new
, timekeeping_suspend_time
);
1706 sleeptime_injected
= true;
1709 if (sleeptime_injected
)
1710 __timekeeping_inject_sleeptime(tk
, &ts_delta
);
1712 /* Re-base the last cycle value */
1713 tk
->tkr_mono
.cycle_last
= cycle_now
;
1714 tk
->tkr_raw
.cycle_last
= cycle_now
;
1717 timekeeping_suspended
= 0;
1718 timekeeping_update(tk
, TK_MIRROR
| TK_CLOCK_WAS_SET
);
1719 write_seqcount_end(&tk_core
.seq
);
1720 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1722 touch_softlockup_watchdog();
1728 int timekeeping_suspend(void)
1730 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1731 unsigned long flags
;
1732 struct timespec64 delta
, delta_delta
;
1733 static struct timespec64 old_delta
;
1735 read_persistent_clock64(&timekeeping_suspend_time
);
1738 * On some systems the persistent_clock can not be detected at
1739 * timekeeping_init by its return value, so if we see a valid
1740 * value returned, update the persistent_clock_exists flag.
1742 if (timekeeping_suspend_time
.tv_sec
|| timekeeping_suspend_time
.tv_nsec
)
1743 persistent_clock_exists
= true;
1745 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1746 write_seqcount_begin(&tk_core
.seq
);
1747 timekeeping_forward_now(tk
);
1748 timekeeping_suspended
= 1;
1750 if (persistent_clock_exists
) {
1752 * To avoid drift caused by repeated suspend/resumes,
1753 * which each can add ~1 second drift error,
1754 * try to compensate so the difference in system time
1755 * and persistent_clock time stays close to constant.
1757 delta
= timespec64_sub(tk_xtime(tk
), timekeeping_suspend_time
);
1758 delta_delta
= timespec64_sub(delta
, old_delta
);
1759 if (abs(delta_delta
.tv_sec
) >= 2) {
1761 * if delta_delta is too large, assume time correction
1762 * has occurred and set old_delta to the current delta.
1766 /* Otherwise try to adjust old_system to compensate */
1767 timekeeping_suspend_time
=
1768 timespec64_add(timekeeping_suspend_time
, delta_delta
);
1772 timekeeping_update(tk
, TK_MIRROR
);
1773 halt_fast_timekeeper(tk
);
1774 write_seqcount_end(&tk_core
.seq
);
1775 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1778 clocksource_suspend();
1779 clockevents_suspend();
1784 /* sysfs resume/suspend bits for timekeeping */
1785 static struct syscore_ops timekeeping_syscore_ops
= {
1786 .resume
= timekeeping_resume
,
1787 .suspend
= timekeeping_suspend
,
1790 static int __init
timekeeping_init_ops(void)
1792 register_syscore_ops(&timekeeping_syscore_ops
);
1795 device_initcall(timekeeping_init_ops
);
1798 * Apply a multiplier adjustment to the timekeeper
1800 static __always_inline
void timekeeping_apply_adjustment(struct timekeeper
*tk
,
1805 s64 interval
= tk
->cycle_interval
;
1809 mult_adj
= -mult_adj
;
1810 interval
= -interval
;
1813 mult_adj
<<= adj_scale
;
1814 interval
<<= adj_scale
;
1815 offset
<<= adj_scale
;
1818 * So the following can be confusing.
1820 * To keep things simple, lets assume mult_adj == 1 for now.
1822 * When mult_adj != 1, remember that the interval and offset values
1823 * have been appropriately scaled so the math is the same.
1825 * The basic idea here is that we're increasing the multiplier
1826 * by one, this causes the xtime_interval to be incremented by
1827 * one cycle_interval. This is because:
1828 * xtime_interval = cycle_interval * mult
1829 * So if mult is being incremented by one:
1830 * xtime_interval = cycle_interval * (mult + 1)
1832 * xtime_interval = (cycle_interval * mult) + cycle_interval
1833 * Which can be shortened to:
1834 * xtime_interval += cycle_interval
1836 * So offset stores the non-accumulated cycles. Thus the current
1837 * time (in shifted nanoseconds) is:
1838 * now = (offset * adj) + xtime_nsec
1839 * Now, even though we're adjusting the clock frequency, we have
1840 * to keep time consistent. In other words, we can't jump back
1841 * in time, and we also want to avoid jumping forward in time.
1843 * So given the same offset value, we need the time to be the same
1844 * both before and after the freq adjustment.
1845 * now = (offset * adj_1) + xtime_nsec_1
1846 * now = (offset * adj_2) + xtime_nsec_2
1848 * (offset * adj_1) + xtime_nsec_1 =
1849 * (offset * adj_2) + xtime_nsec_2
1853 * (offset * adj_1) + xtime_nsec_1 =
1854 * (offset * (adj_1+1)) + xtime_nsec_2
1855 * (offset * adj_1) + xtime_nsec_1 =
1856 * (offset * adj_1) + offset + xtime_nsec_2
1857 * Canceling the sides:
1858 * xtime_nsec_1 = offset + xtime_nsec_2
1860 * xtime_nsec_2 = xtime_nsec_1 - offset
1861 * Which simplfies to:
1862 * xtime_nsec -= offset
1864 * XXX - TODO: Doc ntp_error calculation.
1866 if ((mult_adj
> 0) && (tk
->tkr_mono
.mult
+ mult_adj
< mult_adj
)) {
1867 /* NTP adjustment caused clocksource mult overflow */
1872 tk
->tkr_mono
.mult
+= mult_adj
;
1873 tk
->xtime_interval
+= interval
;
1874 tk
->tkr_mono
.xtime_nsec
-= offset
;
1875 tk
->ntp_error
-= (interval
- offset
) << tk
->ntp_error_shift
;
1879 * Calculate the multiplier adjustment needed to match the frequency
1882 static __always_inline
void timekeeping_freqadjust(struct timekeeper
*tk
,
1885 s64 interval
= tk
->cycle_interval
;
1886 s64 xinterval
= tk
->xtime_interval
;
1887 u32 base
= tk
->tkr_mono
.clock
->mult
;
1888 u32 max
= tk
->tkr_mono
.clock
->maxadj
;
1889 u32 cur_adj
= tk
->tkr_mono
.mult
;
1894 /* Remove any current error adj from freq calculation */
1895 if (tk
->ntp_err_mult
)
1896 xinterval
-= tk
->cycle_interval
;
1898 tk
->ntp_tick
= ntp_tick_length();
1900 /* Calculate current error per tick */
1901 tick_error
= ntp_tick_length() >> tk
->ntp_error_shift
;
1902 tick_error
-= (xinterval
+ tk
->xtime_remainder
);
1904 /* Don't worry about correcting it if its small */
1905 if (likely((tick_error
>= 0) && (tick_error
<= interval
)))
1908 /* preserve the direction of correction */
1909 negative
= (tick_error
< 0);
1911 /* If any adjustment would pass the max, just return */
1912 if (negative
&& (cur_adj
- 1) <= (base
- max
))
1914 if (!negative
&& (cur_adj
+ 1) >= (base
+ max
))
1917 * Sort out the magnitude of the correction, but
1918 * avoid making so large a correction that we go
1919 * over the max adjustment.
1922 tick_error
= abs(tick_error
);
1923 while (tick_error
> interval
) {
1924 u32 adj
= 1 << (adj_scale
+ 1);
1926 /* Check if adjustment gets us within 1 unit from the max */
1927 if (negative
&& (cur_adj
- adj
) <= (base
- max
))
1929 if (!negative
&& (cur_adj
+ adj
) >= (base
+ max
))
1936 /* scale the corrections */
1937 timekeeping_apply_adjustment(tk
, offset
, negative
, adj_scale
);
1941 * Adjust the timekeeper's multiplier to the correct frequency
1942 * and also to reduce the accumulated error value.
1944 static void timekeeping_adjust(struct timekeeper
*tk
, s64 offset
)
1946 /* Correct for the current frequency error */
1947 timekeeping_freqadjust(tk
, offset
);
1949 /* Next make a small adjustment to fix any cumulative error */
1950 if (!tk
->ntp_err_mult
&& (tk
->ntp_error
> 0)) {
1951 tk
->ntp_err_mult
= 1;
1952 timekeeping_apply_adjustment(tk
, offset
, 0, 0);
1953 } else if (tk
->ntp_err_mult
&& (tk
->ntp_error
<= 0)) {
1954 /* Undo any existing error adjustment */
1955 timekeeping_apply_adjustment(tk
, offset
, 1, 0);
1956 tk
->ntp_err_mult
= 0;
1959 if (unlikely(tk
->tkr_mono
.clock
->maxadj
&&
1960 (abs(tk
->tkr_mono
.mult
- tk
->tkr_mono
.clock
->mult
)
1961 > tk
->tkr_mono
.clock
->maxadj
))) {
1962 printk_once(KERN_WARNING
1963 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1964 tk
->tkr_mono
.clock
->name
, (long)tk
->tkr_mono
.mult
,
1965 (long)tk
->tkr_mono
.clock
->mult
+ tk
->tkr_mono
.clock
->maxadj
);
1969 * It may be possible that when we entered this function, xtime_nsec
1970 * was very small. Further, if we're slightly speeding the clocksource
1971 * in the code above, its possible the required corrective factor to
1972 * xtime_nsec could cause it to underflow.
1974 * Now, since we already accumulated the second, cannot simply roll
1975 * the accumulated second back, since the NTP subsystem has been
1976 * notified via second_overflow. So instead we push xtime_nsec forward
1977 * by the amount we underflowed, and add that amount into the error.
1979 * We'll correct this error next time through this function, when
1980 * xtime_nsec is not as small.
1982 if (unlikely((s64
)tk
->tkr_mono
.xtime_nsec
< 0)) {
1983 s64 neg
= -(s64
)tk
->tkr_mono
.xtime_nsec
;
1984 tk
->tkr_mono
.xtime_nsec
= 0;
1985 tk
->ntp_error
+= neg
<< tk
->ntp_error_shift
;
1990 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1992 * Helper function that accumulates the nsecs greater than a second
1993 * from the xtime_nsec field to the xtime_secs field.
1994 * It also calls into the NTP code to handle leapsecond processing.
1997 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper
*tk
)
1999 u64 nsecps
= (u64
)NSEC_PER_SEC
<< tk
->tkr_mono
.shift
;
2000 unsigned int clock_set
= 0;
2002 while (tk
->tkr_mono
.xtime_nsec
>= nsecps
) {
2005 tk
->tkr_mono
.xtime_nsec
-= nsecps
;
2008 /* Figure out if its a leap sec and apply if needed */
2009 leap
= second_overflow(tk
->xtime_sec
);
2010 if (unlikely(leap
)) {
2011 struct timespec64 ts
;
2013 tk
->xtime_sec
+= leap
;
2017 tk_set_wall_to_mono(tk
,
2018 timespec64_sub(tk
->wall_to_monotonic
, ts
));
2020 __timekeeping_set_tai_offset(tk
, tk
->tai_offset
- leap
);
2022 clock_set
= TK_CLOCK_WAS_SET
;
2029 * logarithmic_accumulation - shifted accumulation of cycles
2031 * This functions accumulates a shifted interval of cycles into
2032 * into a shifted interval nanoseconds. Allows for O(log) accumulation
2035 * Returns the unconsumed cycles.
2037 static u64
logarithmic_accumulation(struct timekeeper
*tk
, u64 offset
,
2038 u32 shift
, unsigned int *clock_set
)
2040 u64 interval
= tk
->cycle_interval
<< shift
;
2043 /* If the offset is smaller than a shifted interval, do nothing */
2044 if (offset
< interval
)
2047 /* Accumulate one shifted interval */
2049 tk
->tkr_mono
.cycle_last
+= interval
;
2050 tk
->tkr_raw
.cycle_last
+= interval
;
2052 tk
->tkr_mono
.xtime_nsec
+= tk
->xtime_interval
<< shift
;
2053 *clock_set
|= accumulate_nsecs_to_secs(tk
);
2055 /* Accumulate raw time */
2056 tk
->tkr_raw
.xtime_nsec
+= tk
->raw_interval
<< shift
;
2057 snsec_per_sec
= (u64
)NSEC_PER_SEC
<< tk
->tkr_raw
.shift
;
2058 while (tk
->tkr_raw
.xtime_nsec
>= snsec_per_sec
) {
2059 tk
->tkr_raw
.xtime_nsec
-= snsec_per_sec
;
2063 /* Accumulate error between NTP and clock interval */
2064 tk
->ntp_error
+= tk
->ntp_tick
<< shift
;
2065 tk
->ntp_error
-= (tk
->xtime_interval
+ tk
->xtime_remainder
) <<
2066 (tk
->ntp_error_shift
+ shift
);
2072 * update_wall_time - Uses the current clocksource to increment the wall time
2075 void update_wall_time(void)
2077 struct timekeeper
*real_tk
= &tk_core
.timekeeper
;
2078 struct timekeeper
*tk
= &shadow_timekeeper
;
2080 int shift
= 0, maxshift
;
2081 unsigned int clock_set
= 0;
2082 unsigned long flags
;
2084 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
2086 /* Make sure we're fully resumed: */
2087 if (unlikely(timekeeping_suspended
))
2090 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
2091 offset
= real_tk
->cycle_interval
;
2093 offset
= clocksource_delta(tk_clock_read(&tk
->tkr_mono
),
2094 tk
->tkr_mono
.cycle_last
, tk
->tkr_mono
.mask
);
2097 /* Check if there's really nothing to do */
2098 if (offset
< real_tk
->cycle_interval
)
2101 /* Do some additional sanity checking */
2102 timekeeping_check_update(tk
, offset
);
2105 * With NO_HZ we may have to accumulate many cycle_intervals
2106 * (think "ticks") worth of time at once. To do this efficiently,
2107 * we calculate the largest doubling multiple of cycle_intervals
2108 * that is smaller than the offset. We then accumulate that
2109 * chunk in one go, and then try to consume the next smaller
2112 shift
= ilog2(offset
) - ilog2(tk
->cycle_interval
);
2113 shift
= max(0, shift
);
2114 /* Bound shift to one less than what overflows tick_length */
2115 maxshift
= (64 - (ilog2(ntp_tick_length())+1)) - 1;
2116 shift
= min(shift
, maxshift
);
2117 while (offset
>= tk
->cycle_interval
) {
2118 offset
= logarithmic_accumulation(tk
, offset
, shift
,
2120 if (offset
< tk
->cycle_interval
<<shift
)
2124 /* correct the clock when NTP error is too big */
2125 timekeeping_adjust(tk
, offset
);
2128 * Finally, make sure that after the rounding
2129 * xtime_nsec isn't larger than NSEC_PER_SEC
2131 clock_set
|= accumulate_nsecs_to_secs(tk
);
2133 write_seqcount_begin(&tk_core
.seq
);
2135 * Update the real timekeeper.
2137 * We could avoid this memcpy by switching pointers, but that
2138 * requires changes to all other timekeeper usage sites as
2139 * well, i.e. move the timekeeper pointer getter into the
2140 * spinlocked/seqcount protected sections. And we trade this
2141 * memcpy under the tk_core.seq against one before we start
2144 timekeeping_update(tk
, clock_set
);
2145 memcpy(real_tk
, tk
, sizeof(*tk
));
2146 /* The memcpy must come last. Do not put anything here! */
2147 write_seqcount_end(&tk_core
.seq
);
2149 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
2151 /* Have to call _delayed version, since in irq context*/
2152 clock_was_set_delayed();
2156 * getboottime64 - Return the real time of system boot.
2157 * @ts: pointer to the timespec64 to be set
2159 * Returns the wall-time of boot in a timespec64.
2161 * This is based on the wall_to_monotonic offset and the total suspend
2162 * time. Calls to settimeofday will affect the value returned (which
2163 * basically means that however wrong your real time clock is at boot time,
2164 * you get the right time here).
2166 void getboottime64(struct timespec64
*ts
)
2168 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2169 ktime_t t
= ktime_sub(tk
->offs_real
, tk
->offs_boot
);
2171 *ts
= ktime_to_timespec64(t
);
2173 EXPORT_SYMBOL_GPL(getboottime64
);
2175 unsigned long get_seconds(void)
2177 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2179 return tk
->xtime_sec
;
2181 EXPORT_SYMBOL(get_seconds
);
2183 struct timespec
__current_kernel_time(void)
2185 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2187 return timespec64_to_timespec(tk_xtime(tk
));
2190 struct timespec64
current_kernel_time64(void)
2192 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2193 struct timespec64 now
;
2197 seq
= read_seqcount_begin(&tk_core
.seq
);
2200 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
2204 EXPORT_SYMBOL(current_kernel_time64
);
2206 struct timespec64
get_monotonic_coarse64(void)
2208 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2209 struct timespec64 now
, mono
;
2213 seq
= read_seqcount_begin(&tk_core
.seq
);
2216 mono
= tk
->wall_to_monotonic
;
2217 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
2219 set_normalized_timespec64(&now
, now
.tv_sec
+ mono
.tv_sec
,
2220 now
.tv_nsec
+ mono
.tv_nsec
);
2224 EXPORT_SYMBOL(get_monotonic_coarse64
);
2227 * Must hold jiffies_lock
2229 void do_timer(unsigned long ticks
)
2231 jiffies_64
+= ticks
;
2232 calc_global_load(ticks
);
2236 * ktime_get_update_offsets_now - hrtimer helper
2237 * @cwsseq: pointer to check and store the clock was set sequence number
2238 * @offs_real: pointer to storage for monotonic -> realtime offset
2239 * @offs_boot: pointer to storage for monotonic -> boottime offset
2240 * @offs_tai: pointer to storage for monotonic -> clock tai offset
2242 * Returns current monotonic time and updates the offsets if the
2243 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2246 * Called from hrtimer_interrupt() or retrigger_next_event()
2248 ktime_t
ktime_get_update_offsets_now(unsigned int *cwsseq
, ktime_t
*offs_real
,
2249 ktime_t
*offs_boot
, ktime_t
*offs_tai
)
2251 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2257 seq
= read_seqcount_begin(&tk_core
.seq
);
2259 base
= tk
->tkr_mono
.base
;
2260 nsecs
= timekeeping_get_ns(&tk
->tkr_mono
);
2261 base
= ktime_add_ns(base
, nsecs
);
2263 if (*cwsseq
!= tk
->clock_was_set_seq
) {
2264 *cwsseq
= tk
->clock_was_set_seq
;
2265 *offs_real
= tk
->offs_real
;
2266 *offs_boot
= tk
->offs_boot
;
2267 *offs_tai
= tk
->offs_tai
;
2270 /* Handle leapsecond insertion adjustments */
2271 if (unlikely(base
>= tk
->next_leap_ktime
))
2272 *offs_real
= ktime_sub(tk
->offs_real
, ktime_set(1, 0));
2274 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
2280 * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2282 static int timekeeping_validate_timex(struct timex
*txc
)
2284 if (txc
->modes
& ADJ_ADJTIME
) {
2285 /* singleshot must not be used with any other mode bits */
2286 if (!(txc
->modes
& ADJ_OFFSET_SINGLESHOT
))
2288 if (!(txc
->modes
& ADJ_OFFSET_READONLY
) &&
2289 !capable(CAP_SYS_TIME
))
2292 /* In order to modify anything, you gotta be super-user! */
2293 if (txc
->modes
&& !capable(CAP_SYS_TIME
))
2296 * if the quartz is off by more than 10% then
2297 * something is VERY wrong!
2299 if (txc
->modes
& ADJ_TICK
&&
2300 (txc
->tick
< 900000/USER_HZ
||
2301 txc
->tick
> 1100000/USER_HZ
))
2305 if (txc
->modes
& ADJ_SETOFFSET
) {
2306 /* In order to inject time, you gotta be super-user! */
2307 if (!capable(CAP_SYS_TIME
))
2311 * Validate if a timespec/timeval used to inject a time
2312 * offset is valid. Offsets can be postive or negative, so
2313 * we don't check tv_sec. The value of the timeval/timespec
2314 * is the sum of its fields,but *NOTE*:
2315 * The field tv_usec/tv_nsec must always be non-negative and
2316 * we can't have more nanoseconds/microseconds than a second.
2318 if (txc
->time
.tv_usec
< 0)
2321 if (txc
->modes
& ADJ_NANO
) {
2322 if (txc
->time
.tv_usec
>= NSEC_PER_SEC
)
2325 if (txc
->time
.tv_usec
>= USEC_PER_SEC
)
2331 * Check for potential multiplication overflows that can
2332 * only happen on 64-bit systems:
2334 if ((txc
->modes
& ADJ_FREQUENCY
) && (BITS_PER_LONG
== 64)) {
2335 if (LLONG_MIN
/ PPM_SCALE
> txc
->freq
)
2337 if (LLONG_MAX
/ PPM_SCALE
< txc
->freq
)
2346 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2348 int do_adjtimex(struct timex
*txc
)
2350 struct timekeeper
*tk
= &tk_core
.timekeeper
;
2351 unsigned long flags
;
2352 struct timespec64 ts
;
2356 /* Validate the data before disabling interrupts */
2357 ret
= timekeeping_validate_timex(txc
);
2361 if (txc
->modes
& ADJ_SETOFFSET
) {
2362 struct timespec64 delta
;
2363 delta
.tv_sec
= txc
->time
.tv_sec
;
2364 delta
.tv_nsec
= txc
->time
.tv_usec
;
2365 if (!(txc
->modes
& ADJ_NANO
))
2366 delta
.tv_nsec
*= 1000;
2367 ret
= timekeeping_inject_offset(&delta
);
2372 getnstimeofday64(&ts
);
2374 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
2375 write_seqcount_begin(&tk_core
.seq
);
2377 orig_tai
= tai
= tk
->tai_offset
;
2378 ret
= __do_adjtimex(txc
, &ts
, &tai
);
2380 if (tai
!= orig_tai
) {
2381 __timekeeping_set_tai_offset(tk
, tai
);
2382 timekeeping_update(tk
, TK_MIRROR
| TK_CLOCK_WAS_SET
);
2384 tk_update_leap_state(tk
);
2386 write_seqcount_end(&tk_core
.seq
);
2387 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
2389 if (tai
!= orig_tai
)
2392 ntp_notify_cmos_timer();
2397 #ifdef CONFIG_NTP_PPS
2399 * hardpps() - Accessor function to NTP __hardpps function
2401 void hardpps(const struct timespec64
*phase_ts
, const struct timespec64
*raw_ts
)
2403 unsigned long flags
;
2405 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
2406 write_seqcount_begin(&tk_core
.seq
);
2408 __hardpps(phase_ts
, raw_ts
);
2410 write_seqcount_end(&tk_core
.seq
);
2411 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
2413 EXPORT_SYMBOL(hardpps
);
2414 #endif /* CONFIG_NTP_PPS */
2417 * xtime_update() - advances the timekeeping infrastructure
2418 * @ticks: number of ticks, that have elapsed since the last call.
2420 * Must be called with interrupts disabled.
2422 void xtime_update(unsigned long ticks
)
2424 write_seqlock(&jiffies_lock
);
2426 write_sequnlock(&jiffies_lock
);