2 * linux/kernel/time/timekeeping.c
4 * Kernel timekeeping code and accessor functions
6 * This code was moved from linux/kernel/timer.c.
7 * Please see that file for copyright and history logs.
11 #include <linux/timekeeper_internal.h>
12 #include <linux/module.h>
13 #include <linux/interrupt.h>
14 #include <linux/percpu.h>
15 #include <linux/init.h>
17 #include <linux/sched.h>
18 #include <linux/syscore_ops.h>
19 #include <linux/clocksource.h>
20 #include <linux/jiffies.h>
21 #include <linux/time.h>
22 #include <linux/tick.h>
23 #include <linux/stop_machine.h>
24 #include <linux/pvclock_gtod.h>
25 #include <linux/compiler.h>
27 #include "tick-internal.h"
28 #include "ntp_internal.h"
29 #include "timekeeping_internal.h"
31 #define TK_CLEAR_NTP (1 << 0)
32 #define TK_MIRROR (1 << 1)
33 #define TK_CLOCK_WAS_SET (1 << 2)
36 * The most important data for readout fits into a single 64 byte
41 struct timekeeper timekeeper
;
42 } tk_core ____cacheline_aligned
;
44 static DEFINE_RAW_SPINLOCK(timekeeper_lock
);
45 static struct timekeeper shadow_timekeeper
;
48 * struct tk_fast - NMI safe timekeeper
49 * @seq: Sequence counter for protecting updates. The lowest bit
50 * is the index for the tk_read_base array
51 * @base: tk_read_base array. Access is indexed by the lowest bit of
54 * See @update_fast_timekeeper() below.
58 struct tk_read_base base
[2];
61 static struct tk_fast tk_fast_mono ____cacheline_aligned
;
63 /* flag for if timekeeping is suspended */
64 int __read_mostly timekeeping_suspended
;
66 /* Flag for if there is a persistent clock on this platform */
67 bool __read_mostly persistent_clock_exist
= false;
69 static inline void tk_normalize_xtime(struct timekeeper
*tk
)
71 while (tk
->tkr
.xtime_nsec
>= ((u64
)NSEC_PER_SEC
<< tk
->tkr
.shift
)) {
72 tk
->tkr
.xtime_nsec
-= (u64
)NSEC_PER_SEC
<< tk
->tkr
.shift
;
77 static inline struct timespec64
tk_xtime(struct timekeeper
*tk
)
81 ts
.tv_sec
= tk
->xtime_sec
;
82 ts
.tv_nsec
= (long)(tk
->tkr
.xtime_nsec
>> tk
->tkr
.shift
);
86 static void tk_set_xtime(struct timekeeper
*tk
, const struct timespec64
*ts
)
88 tk
->xtime_sec
= ts
->tv_sec
;
89 tk
->tkr
.xtime_nsec
= (u64
)ts
->tv_nsec
<< tk
->tkr
.shift
;
92 static void tk_xtime_add(struct timekeeper
*tk
, const struct timespec64
*ts
)
94 tk
->xtime_sec
+= ts
->tv_sec
;
95 tk
->tkr
.xtime_nsec
+= (u64
)ts
->tv_nsec
<< tk
->tkr
.shift
;
96 tk_normalize_xtime(tk
);
99 static void tk_set_wall_to_mono(struct timekeeper
*tk
, struct timespec64 wtm
)
101 struct timespec64 tmp
;
104 * Verify consistency of: offset_real = -wall_to_monotonic
105 * before modifying anything
107 set_normalized_timespec64(&tmp
, -tk
->wall_to_monotonic
.tv_sec
,
108 -tk
->wall_to_monotonic
.tv_nsec
);
109 WARN_ON_ONCE(tk
->offs_real
.tv64
!= timespec64_to_ktime(tmp
).tv64
);
110 tk
->wall_to_monotonic
= wtm
;
111 set_normalized_timespec64(&tmp
, -wtm
.tv_sec
, -wtm
.tv_nsec
);
112 tk
->offs_real
= timespec64_to_ktime(tmp
);
113 tk
->offs_tai
= ktime_add(tk
->offs_real
, ktime_set(tk
->tai_offset
, 0));
116 static inline void tk_update_sleep_time(struct timekeeper
*tk
, ktime_t delta
)
118 tk
->offs_boot
= ktime_add(tk
->offs_boot
, delta
);
121 #ifdef CONFIG_DEBUG_TIMEKEEPING
122 static void timekeeping_check_update(struct timekeeper
*tk
, cycle_t offset
)
125 cycle_t max_cycles
= tk
->tkr
.clock
->max_cycles
;
126 const char *name
= tk
->tkr
.clock
->name
;
128 if (offset
> max_cycles
) {
129 printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow\n",
130 offset
, name
, max_cycles
);
131 printk_deferred(" timekeeping: Your kernel is sick, but tries to cope\n");
133 if (offset
> (max_cycles
>> 1)) {
134 printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the the '%s' clock's 50%% safety margin (%lld)\n",
135 offset
, name
, max_cycles
>> 1);
136 printk_deferred(" timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
141 static inline void timekeeping_check_update(struct timekeeper
*tk
, cycle_t offset
)
147 * tk_setup_internals - Set up internals to use clocksource clock.
149 * @tk: The target timekeeper to setup.
150 * @clock: Pointer to clocksource.
152 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
153 * pair and interval request.
155 * Unless you're the timekeeping code, you should not be using this!
157 static void tk_setup_internals(struct timekeeper
*tk
, struct clocksource
*clock
)
160 u64 tmp
, ntpinterval
;
161 struct clocksource
*old_clock
;
163 old_clock
= tk
->tkr
.clock
;
164 tk
->tkr
.clock
= clock
;
165 tk
->tkr
.read
= clock
->read
;
166 tk
->tkr
.mask
= clock
->mask
;
167 tk
->tkr
.cycle_last
= tk
->tkr
.read(clock
);
169 /* Do the ns -> cycle conversion first, using original mult */
170 tmp
= NTP_INTERVAL_LENGTH
;
171 tmp
<<= clock
->shift
;
173 tmp
+= clock
->mult
/2;
174 do_div(tmp
, clock
->mult
);
178 interval
= (cycle_t
) tmp
;
179 tk
->cycle_interval
= interval
;
181 /* Go back from cycles -> shifted ns */
182 tk
->xtime_interval
= (u64
) interval
* clock
->mult
;
183 tk
->xtime_remainder
= ntpinterval
- tk
->xtime_interval
;
185 ((u64
) interval
* clock
->mult
) >> clock
->shift
;
187 /* if changing clocks, convert xtime_nsec shift units */
189 int shift_change
= clock
->shift
- old_clock
->shift
;
190 if (shift_change
< 0)
191 tk
->tkr
.xtime_nsec
>>= -shift_change
;
193 tk
->tkr
.xtime_nsec
<<= shift_change
;
195 tk
->tkr
.shift
= clock
->shift
;
198 tk
->ntp_error_shift
= NTP_SCALE_SHIFT
- clock
->shift
;
199 tk
->ntp_tick
= ntpinterval
<< tk
->ntp_error_shift
;
202 * The timekeeper keeps its own mult values for the currently
203 * active clocksource. These value will be adjusted via NTP
204 * to counteract clock drifting.
206 tk
->tkr
.mult
= clock
->mult
;
207 tk
->ntp_err_mult
= 0;
210 /* Timekeeper helper functions. */
212 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
213 static u32
default_arch_gettimeoffset(void) { return 0; }
214 u32 (*arch_gettimeoffset
)(void) = default_arch_gettimeoffset
;
216 static inline u32
arch_gettimeoffset(void) { return 0; }
219 static inline s64
timekeeping_get_ns(struct tk_read_base
*tkr
)
221 cycle_t cycle_now
, delta
;
224 /* read clocksource: */
225 cycle_now
= tkr
->read(tkr
->clock
);
227 /* calculate the delta since the last update_wall_time: */
228 delta
= clocksource_delta(cycle_now
, tkr
->cycle_last
, tkr
->mask
);
230 nsec
= delta
* tkr
->mult
+ tkr
->xtime_nsec
;
233 /* If arch requires, add in get_arch_timeoffset() */
234 return nsec
+ arch_gettimeoffset();
237 static inline s64
timekeeping_get_ns_raw(struct timekeeper
*tk
)
239 struct clocksource
*clock
= tk
->tkr
.clock
;
240 cycle_t cycle_now
, delta
;
243 /* read clocksource: */
244 cycle_now
= tk
->tkr
.read(clock
);
246 /* calculate the delta since the last update_wall_time: */
247 delta
= clocksource_delta(cycle_now
, tk
->tkr
.cycle_last
, tk
->tkr
.mask
);
249 /* convert delta to nanoseconds. */
250 nsec
= clocksource_cyc2ns(delta
, clock
->mult
, clock
->shift
);
252 /* If arch requires, add in get_arch_timeoffset() */
253 return nsec
+ arch_gettimeoffset();
257 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
258 * @tkr: Timekeeping readout base from which we take the update
260 * We want to use this from any context including NMI and tracing /
261 * instrumenting the timekeeping code itself.
263 * So we handle this differently than the other timekeeping accessor
264 * functions which retry when the sequence count has changed. The
267 * smp_wmb(); <- Ensure that the last base[1] update is visible
269 * smp_wmb(); <- Ensure that the seqcount update is visible
270 * update(tkf->base[0], tkr);
271 * smp_wmb(); <- Ensure that the base[0] update is visible
273 * smp_wmb(); <- Ensure that the seqcount update is visible
274 * update(tkf->base[1], tkr);
276 * The reader side does:
282 * now = now(tkf->base[idx]);
284 * } while (seq != tkf->seq)
286 * As long as we update base[0] readers are forced off to
287 * base[1]. Once base[0] is updated readers are redirected to base[0]
288 * and the base[1] update takes place.
290 * So if a NMI hits the update of base[0] then it will use base[1]
291 * which is still consistent. In the worst case this can result is a
292 * slightly wrong timestamp (a few nanoseconds). See
293 * @ktime_get_mono_fast_ns.
295 static void update_fast_timekeeper(struct tk_read_base
*tkr
)
297 struct tk_read_base
*base
= tk_fast_mono
.base
;
299 /* Force readers off to base[1] */
300 raw_write_seqcount_latch(&tk_fast_mono
.seq
);
303 memcpy(base
, tkr
, sizeof(*base
));
305 /* Force readers back to base[0] */
306 raw_write_seqcount_latch(&tk_fast_mono
.seq
);
309 memcpy(base
+ 1, base
, sizeof(*base
));
313 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
315 * This timestamp is not guaranteed to be monotonic across an update.
316 * The timestamp is calculated by:
318 * now = base_mono + clock_delta * slope
320 * So if the update lowers the slope, readers who are forced to the
321 * not yet updated second array are still using the old steeper slope.
330 * |12345678---> reader order
336 * So reader 6 will observe time going backwards versus reader 5.
338 * While other CPUs are likely to be able observe that, the only way
339 * for a CPU local observation is when an NMI hits in the middle of
340 * the update. Timestamps taken from that NMI context might be ahead
341 * of the following timestamps. Callers need to be aware of that and
344 u64 notrace
ktime_get_mono_fast_ns(void)
346 struct tk_read_base
*tkr
;
351 seq
= raw_read_seqcount(&tk_fast_mono
.seq
);
352 tkr
= tk_fast_mono
.base
+ (seq
& 0x01);
353 now
= ktime_to_ns(tkr
->base_mono
) + timekeeping_get_ns(tkr
);
355 } while (read_seqcount_retry(&tk_fast_mono
.seq
, seq
));
358 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns
);
360 /* Suspend-time cycles value for halted fast timekeeper. */
361 static cycle_t cycles_at_suspend
;
363 static cycle_t
dummy_clock_read(struct clocksource
*cs
)
365 return cycles_at_suspend
;
369 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
370 * @tk: Timekeeper to snapshot.
372 * It generally is unsafe to access the clocksource after timekeeping has been
373 * suspended, so take a snapshot of the readout base of @tk and use it as the
374 * fast timekeeper's readout base while suspended. It will return the same
375 * number of cycles every time until timekeeping is resumed at which time the
376 * proper readout base for the fast timekeeper will be restored automatically.
378 static void halt_fast_timekeeper(struct timekeeper
*tk
)
380 static struct tk_read_base tkr_dummy
;
381 struct tk_read_base
*tkr
= &tk
->tkr
;
383 memcpy(&tkr_dummy
, tkr
, sizeof(tkr_dummy
));
384 cycles_at_suspend
= tkr
->read(tkr
->clock
);
385 tkr_dummy
.read
= dummy_clock_read
;
386 update_fast_timekeeper(&tkr_dummy
);
389 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
391 static inline void update_vsyscall(struct timekeeper
*tk
)
393 struct timespec xt
, wm
;
395 xt
= timespec64_to_timespec(tk_xtime(tk
));
396 wm
= timespec64_to_timespec(tk
->wall_to_monotonic
);
397 update_vsyscall_old(&xt
, &wm
, tk
->tkr
.clock
, tk
->tkr
.mult
,
401 static inline void old_vsyscall_fixup(struct timekeeper
*tk
)
406 * Store only full nanoseconds into xtime_nsec after rounding
407 * it up and add the remainder to the error difference.
408 * XXX - This is necessary to avoid small 1ns inconsistnecies caused
409 * by truncating the remainder in vsyscalls. However, it causes
410 * additional work to be done in timekeeping_adjust(). Once
411 * the vsyscall implementations are converted to use xtime_nsec
412 * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
413 * users are removed, this can be killed.
415 remainder
= tk
->tkr
.xtime_nsec
& ((1ULL << tk
->tkr
.shift
) - 1);
416 tk
->tkr
.xtime_nsec
-= remainder
;
417 tk
->tkr
.xtime_nsec
+= 1ULL << tk
->tkr
.shift
;
418 tk
->ntp_error
+= remainder
<< tk
->ntp_error_shift
;
419 tk
->ntp_error
-= (1ULL << tk
->tkr
.shift
) << tk
->ntp_error_shift
;
422 #define old_vsyscall_fixup(tk)
425 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain
);
427 static void update_pvclock_gtod(struct timekeeper
*tk
, bool was_set
)
429 raw_notifier_call_chain(&pvclock_gtod_chain
, was_set
, tk
);
433 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
435 int pvclock_gtod_register_notifier(struct notifier_block
*nb
)
437 struct timekeeper
*tk
= &tk_core
.timekeeper
;
441 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
442 ret
= raw_notifier_chain_register(&pvclock_gtod_chain
, nb
);
443 update_pvclock_gtod(tk
, true);
444 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
448 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier
);
451 * pvclock_gtod_unregister_notifier - unregister a pvclock
452 * timedata update listener
454 int pvclock_gtod_unregister_notifier(struct notifier_block
*nb
)
459 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
460 ret
= raw_notifier_chain_unregister(&pvclock_gtod_chain
, nb
);
461 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
465 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier
);
468 * Update the ktime_t based scalar nsec members of the timekeeper
470 static inline void tk_update_ktime_data(struct timekeeper
*tk
)
476 * The xtime based monotonic readout is:
477 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
478 * The ktime based monotonic readout is:
479 * nsec = base_mono + now();
480 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
482 seconds
= (u64
)(tk
->xtime_sec
+ tk
->wall_to_monotonic
.tv_sec
);
483 nsec
= (u32
) tk
->wall_to_monotonic
.tv_nsec
;
484 tk
->tkr
.base_mono
= ns_to_ktime(seconds
* NSEC_PER_SEC
+ nsec
);
486 /* Update the monotonic raw base */
487 tk
->base_raw
= timespec64_to_ktime(tk
->raw_time
);
490 * The sum of the nanoseconds portions of xtime and
491 * wall_to_monotonic can be greater/equal one second. Take
492 * this into account before updating tk->ktime_sec.
494 nsec
+= (u32
)(tk
->tkr
.xtime_nsec
>> tk
->tkr
.shift
);
495 if (nsec
>= NSEC_PER_SEC
)
497 tk
->ktime_sec
= seconds
;
500 /* must hold timekeeper_lock */
501 static void timekeeping_update(struct timekeeper
*tk
, unsigned int action
)
503 if (action
& TK_CLEAR_NTP
) {
508 tk_update_ktime_data(tk
);
511 update_pvclock_gtod(tk
, action
& TK_CLOCK_WAS_SET
);
513 if (action
& TK_MIRROR
)
514 memcpy(&shadow_timekeeper
, &tk_core
.timekeeper
,
515 sizeof(tk_core
.timekeeper
));
517 update_fast_timekeeper(&tk
->tkr
);
521 * timekeeping_forward_now - update clock to the current time
523 * Forward the current clock to update its state since the last call to
524 * update_wall_time(). This is useful before significant clock changes,
525 * as it avoids having to deal with this time offset explicitly.
527 static void timekeeping_forward_now(struct timekeeper
*tk
)
529 struct clocksource
*clock
= tk
->tkr
.clock
;
530 cycle_t cycle_now
, delta
;
533 cycle_now
= tk
->tkr
.read(clock
);
534 delta
= clocksource_delta(cycle_now
, tk
->tkr
.cycle_last
, tk
->tkr
.mask
);
535 tk
->tkr
.cycle_last
= cycle_now
;
537 tk
->tkr
.xtime_nsec
+= delta
* tk
->tkr
.mult
;
539 /* If arch requires, add in get_arch_timeoffset() */
540 tk
->tkr
.xtime_nsec
+= (u64
)arch_gettimeoffset() << tk
->tkr
.shift
;
542 tk_normalize_xtime(tk
);
544 nsec
= clocksource_cyc2ns(delta
, clock
->mult
, clock
->shift
);
545 timespec64_add_ns(&tk
->raw_time
, nsec
);
549 * __getnstimeofday64 - Returns the time of day in a timespec64.
550 * @ts: pointer to the timespec to be set
552 * Updates the time of day in the timespec.
553 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
555 int __getnstimeofday64(struct timespec64
*ts
)
557 struct timekeeper
*tk
= &tk_core
.timekeeper
;
562 seq
= read_seqcount_begin(&tk_core
.seq
);
564 ts
->tv_sec
= tk
->xtime_sec
;
565 nsecs
= timekeeping_get_ns(&tk
->tkr
);
567 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
570 timespec64_add_ns(ts
, nsecs
);
573 * Do not bail out early, in case there were callers still using
574 * the value, even in the face of the WARN_ON.
576 if (unlikely(timekeeping_suspended
))
580 EXPORT_SYMBOL(__getnstimeofday64
);
583 * getnstimeofday64 - Returns the time of day in a timespec64.
584 * @ts: pointer to the timespec64 to be set
586 * Returns the time of day in a timespec64 (WARN if suspended).
588 void getnstimeofday64(struct timespec64
*ts
)
590 WARN_ON(__getnstimeofday64(ts
));
592 EXPORT_SYMBOL(getnstimeofday64
);
594 ktime_t
ktime_get(void)
596 struct timekeeper
*tk
= &tk_core
.timekeeper
;
601 WARN_ON(timekeeping_suspended
);
604 seq
= read_seqcount_begin(&tk_core
.seq
);
605 base
= tk
->tkr
.base_mono
;
606 nsecs
= timekeeping_get_ns(&tk
->tkr
);
608 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
610 return ktime_add_ns(base
, nsecs
);
612 EXPORT_SYMBOL_GPL(ktime_get
);
614 static ktime_t
*offsets
[TK_OFFS_MAX
] = {
615 [TK_OFFS_REAL
] = &tk_core
.timekeeper
.offs_real
,
616 [TK_OFFS_BOOT
] = &tk_core
.timekeeper
.offs_boot
,
617 [TK_OFFS_TAI
] = &tk_core
.timekeeper
.offs_tai
,
620 ktime_t
ktime_get_with_offset(enum tk_offsets offs
)
622 struct timekeeper
*tk
= &tk_core
.timekeeper
;
624 ktime_t base
, *offset
= offsets
[offs
];
627 WARN_ON(timekeeping_suspended
);
630 seq
= read_seqcount_begin(&tk_core
.seq
);
631 base
= ktime_add(tk
->tkr
.base_mono
, *offset
);
632 nsecs
= timekeeping_get_ns(&tk
->tkr
);
634 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
636 return ktime_add_ns(base
, nsecs
);
639 EXPORT_SYMBOL_GPL(ktime_get_with_offset
);
642 * ktime_mono_to_any() - convert mononotic time to any other time
643 * @tmono: time to convert.
644 * @offs: which offset to use
646 ktime_t
ktime_mono_to_any(ktime_t tmono
, enum tk_offsets offs
)
648 ktime_t
*offset
= offsets
[offs
];
653 seq
= read_seqcount_begin(&tk_core
.seq
);
654 tconv
= ktime_add(tmono
, *offset
);
655 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
659 EXPORT_SYMBOL_GPL(ktime_mono_to_any
);
662 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
664 ktime_t
ktime_get_raw(void)
666 struct timekeeper
*tk
= &tk_core
.timekeeper
;
672 seq
= read_seqcount_begin(&tk_core
.seq
);
674 nsecs
= timekeeping_get_ns_raw(tk
);
676 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
678 return ktime_add_ns(base
, nsecs
);
680 EXPORT_SYMBOL_GPL(ktime_get_raw
);
683 * ktime_get_ts64 - get the monotonic clock in timespec64 format
684 * @ts: pointer to timespec variable
686 * The function calculates the monotonic clock from the realtime
687 * clock and the wall_to_monotonic offset and stores the result
688 * in normalized timespec64 format in the variable pointed to by @ts.
690 void ktime_get_ts64(struct timespec64
*ts
)
692 struct timekeeper
*tk
= &tk_core
.timekeeper
;
693 struct timespec64 tomono
;
697 WARN_ON(timekeeping_suspended
);
700 seq
= read_seqcount_begin(&tk_core
.seq
);
701 ts
->tv_sec
= tk
->xtime_sec
;
702 nsec
= timekeeping_get_ns(&tk
->tkr
);
703 tomono
= tk
->wall_to_monotonic
;
705 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
707 ts
->tv_sec
+= tomono
.tv_sec
;
709 timespec64_add_ns(ts
, nsec
+ tomono
.tv_nsec
);
711 EXPORT_SYMBOL_GPL(ktime_get_ts64
);
714 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
716 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
717 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
718 * works on both 32 and 64 bit systems. On 32 bit systems the readout
719 * covers ~136 years of uptime which should be enough to prevent
720 * premature wrap arounds.
722 time64_t
ktime_get_seconds(void)
724 struct timekeeper
*tk
= &tk_core
.timekeeper
;
726 WARN_ON(timekeeping_suspended
);
727 return tk
->ktime_sec
;
729 EXPORT_SYMBOL_GPL(ktime_get_seconds
);
732 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
734 * Returns the wall clock seconds since 1970. This replaces the
735 * get_seconds() interface which is not y2038 safe on 32bit systems.
737 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
738 * 32bit systems the access must be protected with the sequence
739 * counter to provide "atomic" access to the 64bit tk->xtime_sec
742 time64_t
ktime_get_real_seconds(void)
744 struct timekeeper
*tk
= &tk_core
.timekeeper
;
748 if (IS_ENABLED(CONFIG_64BIT
))
749 return tk
->xtime_sec
;
752 seq
= read_seqcount_begin(&tk_core
.seq
);
753 seconds
= tk
->xtime_sec
;
755 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
759 EXPORT_SYMBOL_GPL(ktime_get_real_seconds
);
761 #ifdef CONFIG_NTP_PPS
764 * getnstime_raw_and_real - get day and raw monotonic time in timespec format
765 * @ts_raw: pointer to the timespec to be set to raw monotonic time
766 * @ts_real: pointer to the timespec to be set to the time of day
768 * This function reads both the time of day and raw monotonic time at the
769 * same time atomically and stores the resulting timestamps in timespec
772 void getnstime_raw_and_real(struct timespec
*ts_raw
, struct timespec
*ts_real
)
774 struct timekeeper
*tk
= &tk_core
.timekeeper
;
776 s64 nsecs_raw
, nsecs_real
;
778 WARN_ON_ONCE(timekeeping_suspended
);
781 seq
= read_seqcount_begin(&tk_core
.seq
);
783 *ts_raw
= timespec64_to_timespec(tk
->raw_time
);
784 ts_real
->tv_sec
= tk
->xtime_sec
;
785 ts_real
->tv_nsec
= 0;
787 nsecs_raw
= timekeeping_get_ns_raw(tk
);
788 nsecs_real
= timekeeping_get_ns(&tk
->tkr
);
790 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
792 timespec_add_ns(ts_raw
, nsecs_raw
);
793 timespec_add_ns(ts_real
, nsecs_real
);
795 EXPORT_SYMBOL(getnstime_raw_and_real
);
797 #endif /* CONFIG_NTP_PPS */
800 * do_gettimeofday - Returns the time of day in a timeval
801 * @tv: pointer to the timeval to be set
803 * NOTE: Users should be converted to using getnstimeofday()
805 void do_gettimeofday(struct timeval
*tv
)
807 struct timespec64 now
;
809 getnstimeofday64(&now
);
810 tv
->tv_sec
= now
.tv_sec
;
811 tv
->tv_usec
= now
.tv_nsec
/1000;
813 EXPORT_SYMBOL(do_gettimeofday
);
816 * do_settimeofday64 - Sets the time of day.
817 * @ts: pointer to the timespec64 variable containing the new time
819 * Sets the time of day to the new time and update NTP and notify hrtimers
821 int do_settimeofday64(const struct timespec64
*ts
)
823 struct timekeeper
*tk
= &tk_core
.timekeeper
;
824 struct timespec64 ts_delta
, xt
;
827 if (!timespec64_valid_strict(ts
))
830 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
831 write_seqcount_begin(&tk_core
.seq
);
833 timekeeping_forward_now(tk
);
836 ts_delta
.tv_sec
= ts
->tv_sec
- xt
.tv_sec
;
837 ts_delta
.tv_nsec
= ts
->tv_nsec
- xt
.tv_nsec
;
839 tk_set_wall_to_mono(tk
, timespec64_sub(tk
->wall_to_monotonic
, ts_delta
));
841 tk_set_xtime(tk
, ts
);
843 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
845 write_seqcount_end(&tk_core
.seq
);
846 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
848 /* signal hrtimers about time change */
853 EXPORT_SYMBOL(do_settimeofday64
);
856 * timekeeping_inject_offset - Adds or subtracts from the current time.
857 * @tv: pointer to the timespec variable containing the offset
859 * Adds or subtracts an offset value from the current time.
861 int timekeeping_inject_offset(struct timespec
*ts
)
863 struct timekeeper
*tk
= &tk_core
.timekeeper
;
865 struct timespec64 ts64
, tmp
;
868 if ((unsigned long)ts
->tv_nsec
>= NSEC_PER_SEC
)
871 ts64
= timespec_to_timespec64(*ts
);
873 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
874 write_seqcount_begin(&tk_core
.seq
);
876 timekeeping_forward_now(tk
);
878 /* Make sure the proposed value is valid */
879 tmp
= timespec64_add(tk_xtime(tk
), ts64
);
880 if (!timespec64_valid_strict(&tmp
)) {
885 tk_xtime_add(tk
, &ts64
);
886 tk_set_wall_to_mono(tk
, timespec64_sub(tk
->wall_to_monotonic
, ts64
));
888 error
: /* even if we error out, we forwarded the time, so call update */
889 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
891 write_seqcount_end(&tk_core
.seq
);
892 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
894 /* signal hrtimers about time change */
899 EXPORT_SYMBOL(timekeeping_inject_offset
);
903 * timekeeping_get_tai_offset - Returns current TAI offset from UTC
906 s32
timekeeping_get_tai_offset(void)
908 struct timekeeper
*tk
= &tk_core
.timekeeper
;
913 seq
= read_seqcount_begin(&tk_core
.seq
);
914 ret
= tk
->tai_offset
;
915 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
921 * __timekeeping_set_tai_offset - Lock free worker function
924 static void __timekeeping_set_tai_offset(struct timekeeper
*tk
, s32 tai_offset
)
926 tk
->tai_offset
= tai_offset
;
927 tk
->offs_tai
= ktime_add(tk
->offs_real
, ktime_set(tai_offset
, 0));
931 * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
934 void timekeeping_set_tai_offset(s32 tai_offset
)
936 struct timekeeper
*tk
= &tk_core
.timekeeper
;
939 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
940 write_seqcount_begin(&tk_core
.seq
);
941 __timekeeping_set_tai_offset(tk
, tai_offset
);
942 timekeeping_update(tk
, TK_MIRROR
| TK_CLOCK_WAS_SET
);
943 write_seqcount_end(&tk_core
.seq
);
944 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
949 * change_clocksource - Swaps clocksources if a new one is available
951 * Accumulates current time interval and initializes new clocksource
953 static int change_clocksource(void *data
)
955 struct timekeeper
*tk
= &tk_core
.timekeeper
;
956 struct clocksource
*new, *old
;
959 new = (struct clocksource
*) data
;
961 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
962 write_seqcount_begin(&tk_core
.seq
);
964 timekeeping_forward_now(tk
);
966 * If the cs is in module, get a module reference. Succeeds
967 * for built-in code (owner == NULL) as well.
969 if (try_module_get(new->owner
)) {
970 if (!new->enable
|| new->enable(new) == 0) {
972 tk_setup_internals(tk
, new);
975 module_put(old
->owner
);
977 module_put(new->owner
);
980 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
982 write_seqcount_end(&tk_core
.seq
);
983 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
989 * timekeeping_notify - Install a new clock source
990 * @clock: pointer to the clock source
992 * This function is called from clocksource.c after a new, better clock
993 * source has been registered. The caller holds the clocksource_mutex.
995 int timekeeping_notify(struct clocksource
*clock
)
997 struct timekeeper
*tk
= &tk_core
.timekeeper
;
999 if (tk
->tkr
.clock
== clock
)
1001 stop_machine(change_clocksource
, clock
, NULL
);
1002 tick_clock_notify();
1003 return tk
->tkr
.clock
== clock
? 0 : -1;
1007 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1008 * @ts: pointer to the timespec64 to be set
1010 * Returns the raw monotonic time (completely un-modified by ntp)
1012 void getrawmonotonic64(struct timespec64
*ts
)
1014 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1015 struct timespec64 ts64
;
1020 seq
= read_seqcount_begin(&tk_core
.seq
);
1021 nsecs
= timekeeping_get_ns_raw(tk
);
1022 ts64
= tk
->raw_time
;
1024 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1026 timespec64_add_ns(&ts64
, nsecs
);
1029 EXPORT_SYMBOL(getrawmonotonic64
);
1033 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1035 int timekeeping_valid_for_hres(void)
1037 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1042 seq
= read_seqcount_begin(&tk_core
.seq
);
1044 ret
= tk
->tkr
.clock
->flags
& CLOCK_SOURCE_VALID_FOR_HRES
;
1046 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1052 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1054 u64
timekeeping_max_deferment(void)
1056 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1061 seq
= read_seqcount_begin(&tk_core
.seq
);
1063 ret
= tk
->tkr
.clock
->max_idle_ns
;
1065 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1071 * read_persistent_clock - Return time from the persistent clock.
1073 * Weak dummy function for arches that do not yet support it.
1074 * Reads the time from the battery backed persistent clock.
1075 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1077 * XXX - Do be sure to remove it once all arches implement it.
1079 void __weak
read_persistent_clock(struct timespec
*ts
)
1086 * read_boot_clock - Return time of the system start.
1088 * Weak dummy function for arches that do not yet support it.
1089 * Function to read the exact time the system has been started.
1090 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1092 * XXX - Do be sure to remove it once all arches implement it.
1094 void __weak
read_boot_clock(struct timespec
*ts
)
1101 * timekeeping_init - Initializes the clocksource and common timekeeping values
1103 void __init
timekeeping_init(void)
1105 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1106 struct clocksource
*clock
;
1107 unsigned long flags
;
1108 struct timespec64 now
, boot
, tmp
;
1111 read_persistent_clock(&ts
);
1112 now
= timespec_to_timespec64(ts
);
1113 if (!timespec64_valid_strict(&now
)) {
1114 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1115 " Check your CMOS/BIOS settings.\n");
1118 } else if (now
.tv_sec
|| now
.tv_nsec
)
1119 persistent_clock_exist
= true;
1121 read_boot_clock(&ts
);
1122 boot
= timespec_to_timespec64(ts
);
1123 if (!timespec64_valid_strict(&boot
)) {
1124 pr_warn("WARNING: Boot clock returned invalid value!\n"
1125 " Check your CMOS/BIOS settings.\n");
1130 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1131 write_seqcount_begin(&tk_core
.seq
);
1134 clock
= clocksource_default_clock();
1136 clock
->enable(clock
);
1137 tk_setup_internals(tk
, clock
);
1139 tk_set_xtime(tk
, &now
);
1140 tk
->raw_time
.tv_sec
= 0;
1141 tk
->raw_time
.tv_nsec
= 0;
1142 tk
->base_raw
.tv64
= 0;
1143 if (boot
.tv_sec
== 0 && boot
.tv_nsec
== 0)
1144 boot
= tk_xtime(tk
);
1146 set_normalized_timespec64(&tmp
, -boot
.tv_sec
, -boot
.tv_nsec
);
1147 tk_set_wall_to_mono(tk
, tmp
);
1149 timekeeping_update(tk
, TK_MIRROR
);
1151 write_seqcount_end(&tk_core
.seq
);
1152 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1155 /* time in seconds when suspend began */
1156 static struct timespec64 timekeeping_suspend_time
;
1159 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1160 * @delta: pointer to a timespec delta value
1162 * Takes a timespec offset measuring a suspend interval and properly
1163 * adds the sleep offset to the timekeeping variables.
1165 static void __timekeeping_inject_sleeptime(struct timekeeper
*tk
,
1166 struct timespec64
*delta
)
1168 if (!timespec64_valid_strict(delta
)) {
1169 printk_deferred(KERN_WARNING
1170 "__timekeeping_inject_sleeptime: Invalid "
1171 "sleep delta value!\n");
1174 tk_xtime_add(tk
, delta
);
1175 tk_set_wall_to_mono(tk
, timespec64_sub(tk
->wall_to_monotonic
, *delta
));
1176 tk_update_sleep_time(tk
, timespec64_to_ktime(*delta
));
1177 tk_debug_account_sleep_time(delta
);
1181 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1182 * @delta: pointer to a timespec64 delta value
1184 * This hook is for architectures that cannot support read_persistent_clock
1185 * because their RTC/persistent clock is only accessible when irqs are enabled.
1187 * This function should only be called by rtc_resume(), and allows
1188 * a suspend offset to be injected into the timekeeping values.
1190 void timekeeping_inject_sleeptime64(struct timespec64
*delta
)
1192 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1193 unsigned long flags
;
1196 * Make sure we don't set the clock twice, as timekeeping_resume()
1199 if (has_persistent_clock())
1202 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1203 write_seqcount_begin(&tk_core
.seq
);
1205 timekeeping_forward_now(tk
);
1207 __timekeeping_inject_sleeptime(tk
, delta
);
1209 timekeeping_update(tk
, TK_CLEAR_NTP
| TK_MIRROR
| TK_CLOCK_WAS_SET
);
1211 write_seqcount_end(&tk_core
.seq
);
1212 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1214 /* signal hrtimers about time change */
1219 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1221 * This is for the generic clocksource timekeeping.
1222 * xtime/wall_to_monotonic/jiffies/etc are
1223 * still managed by arch specific suspend/resume code.
1225 void timekeeping_resume(void)
1227 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1228 struct clocksource
*clock
= tk
->tkr
.clock
;
1229 unsigned long flags
;
1230 struct timespec64 ts_new
, ts_delta
;
1231 struct timespec tmp
;
1232 cycle_t cycle_now
, cycle_delta
;
1233 bool suspendtime_found
= false;
1235 read_persistent_clock(&tmp
);
1236 ts_new
= timespec_to_timespec64(tmp
);
1238 clockevents_resume();
1239 clocksource_resume();
1241 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1242 write_seqcount_begin(&tk_core
.seq
);
1245 * After system resumes, we need to calculate the suspended time and
1246 * compensate it for the OS time. There are 3 sources that could be
1247 * used: Nonstop clocksource during suspend, persistent clock and rtc
1250 * One specific platform may have 1 or 2 or all of them, and the
1251 * preference will be:
1252 * suspend-nonstop clocksource -> persistent clock -> rtc
1253 * The less preferred source will only be tried if there is no better
1254 * usable source. The rtc part is handled separately in rtc core code.
1256 cycle_now
= tk
->tkr
.read(clock
);
1257 if ((clock
->flags
& CLOCK_SOURCE_SUSPEND_NONSTOP
) &&
1258 cycle_now
> tk
->tkr
.cycle_last
) {
1259 u64 num
, max
= ULLONG_MAX
;
1260 u32 mult
= clock
->mult
;
1261 u32 shift
= clock
->shift
;
1264 cycle_delta
= clocksource_delta(cycle_now
, tk
->tkr
.cycle_last
,
1268 * "cycle_delta * mutl" may cause 64 bits overflow, if the
1269 * suspended time is too long. In that case we need do the
1270 * 64 bits math carefully
1273 if (cycle_delta
> max
) {
1274 num
= div64_u64(cycle_delta
, max
);
1275 nsec
= (((u64
) max
* mult
) >> shift
) * num
;
1276 cycle_delta
-= num
* max
;
1278 nsec
+= ((u64
) cycle_delta
* mult
) >> shift
;
1280 ts_delta
= ns_to_timespec64(nsec
);
1281 suspendtime_found
= true;
1282 } else if (timespec64_compare(&ts_new
, &timekeeping_suspend_time
) > 0) {
1283 ts_delta
= timespec64_sub(ts_new
, timekeeping_suspend_time
);
1284 suspendtime_found
= true;
1287 if (suspendtime_found
)
1288 __timekeeping_inject_sleeptime(tk
, &ts_delta
);
1290 /* Re-base the last cycle value */
1291 tk
->tkr
.cycle_last
= cycle_now
;
1293 timekeeping_suspended
= 0;
1294 timekeeping_update(tk
, TK_MIRROR
| TK_CLOCK_WAS_SET
);
1295 write_seqcount_end(&tk_core
.seq
);
1296 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1298 touch_softlockup_watchdog();
1300 clockevents_notify(CLOCK_EVT_NOTIFY_RESUME
, NULL
);
1302 /* Resume hrtimers */
1306 int timekeeping_suspend(void)
1308 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1309 unsigned long flags
;
1310 struct timespec64 delta
, delta_delta
;
1311 static struct timespec64 old_delta
;
1312 struct timespec tmp
;
1314 read_persistent_clock(&tmp
);
1315 timekeeping_suspend_time
= timespec_to_timespec64(tmp
);
1318 * On some systems the persistent_clock can not be detected at
1319 * timekeeping_init by its return value, so if we see a valid
1320 * value returned, update the persistent_clock_exists flag.
1322 if (timekeeping_suspend_time
.tv_sec
|| timekeeping_suspend_time
.tv_nsec
)
1323 persistent_clock_exist
= true;
1325 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1326 write_seqcount_begin(&tk_core
.seq
);
1327 timekeeping_forward_now(tk
);
1328 timekeeping_suspended
= 1;
1331 * To avoid drift caused by repeated suspend/resumes,
1332 * which each can add ~1 second drift error,
1333 * try to compensate so the difference in system time
1334 * and persistent_clock time stays close to constant.
1336 delta
= timespec64_sub(tk_xtime(tk
), timekeeping_suspend_time
);
1337 delta_delta
= timespec64_sub(delta
, old_delta
);
1338 if (abs(delta_delta
.tv_sec
) >= 2) {
1340 * if delta_delta is too large, assume time correction
1341 * has occured and set old_delta to the current delta.
1345 /* Otherwise try to adjust old_system to compensate */
1346 timekeeping_suspend_time
=
1347 timespec64_add(timekeeping_suspend_time
, delta_delta
);
1350 timekeeping_update(tk
, TK_MIRROR
);
1351 halt_fast_timekeeper(tk
);
1352 write_seqcount_end(&tk_core
.seq
);
1353 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1355 clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND
, NULL
);
1356 clocksource_suspend();
1357 clockevents_suspend();
1362 /* sysfs resume/suspend bits for timekeeping */
1363 static struct syscore_ops timekeeping_syscore_ops
= {
1364 .resume
= timekeeping_resume
,
1365 .suspend
= timekeeping_suspend
,
1368 static int __init
timekeeping_init_ops(void)
1370 register_syscore_ops(&timekeeping_syscore_ops
);
1373 device_initcall(timekeeping_init_ops
);
1376 * Apply a multiplier adjustment to the timekeeper
1378 static __always_inline
void timekeeping_apply_adjustment(struct timekeeper
*tk
,
1383 s64 interval
= tk
->cycle_interval
;
1387 mult_adj
= -mult_adj
;
1388 interval
= -interval
;
1391 mult_adj
<<= adj_scale
;
1392 interval
<<= adj_scale
;
1393 offset
<<= adj_scale
;
1396 * So the following can be confusing.
1398 * To keep things simple, lets assume mult_adj == 1 for now.
1400 * When mult_adj != 1, remember that the interval and offset values
1401 * have been appropriately scaled so the math is the same.
1403 * The basic idea here is that we're increasing the multiplier
1404 * by one, this causes the xtime_interval to be incremented by
1405 * one cycle_interval. This is because:
1406 * xtime_interval = cycle_interval * mult
1407 * So if mult is being incremented by one:
1408 * xtime_interval = cycle_interval * (mult + 1)
1410 * xtime_interval = (cycle_interval * mult) + cycle_interval
1411 * Which can be shortened to:
1412 * xtime_interval += cycle_interval
1414 * So offset stores the non-accumulated cycles. Thus the current
1415 * time (in shifted nanoseconds) is:
1416 * now = (offset * adj) + xtime_nsec
1417 * Now, even though we're adjusting the clock frequency, we have
1418 * to keep time consistent. In other words, we can't jump back
1419 * in time, and we also want to avoid jumping forward in time.
1421 * So given the same offset value, we need the time to be the same
1422 * both before and after the freq adjustment.
1423 * now = (offset * adj_1) + xtime_nsec_1
1424 * now = (offset * adj_2) + xtime_nsec_2
1426 * (offset * adj_1) + xtime_nsec_1 =
1427 * (offset * adj_2) + xtime_nsec_2
1431 * (offset * adj_1) + xtime_nsec_1 =
1432 * (offset * (adj_1+1)) + xtime_nsec_2
1433 * (offset * adj_1) + xtime_nsec_1 =
1434 * (offset * adj_1) + offset + xtime_nsec_2
1435 * Canceling the sides:
1436 * xtime_nsec_1 = offset + xtime_nsec_2
1438 * xtime_nsec_2 = xtime_nsec_1 - offset
1439 * Which simplfies to:
1440 * xtime_nsec -= offset
1442 * XXX - TODO: Doc ntp_error calculation.
1444 if ((mult_adj
> 0) && (tk
->tkr
.mult
+ mult_adj
< mult_adj
)) {
1445 /* NTP adjustment caused clocksource mult overflow */
1450 tk
->tkr
.mult
+= mult_adj
;
1451 tk
->xtime_interval
+= interval
;
1452 tk
->tkr
.xtime_nsec
-= offset
;
1453 tk
->ntp_error
-= (interval
- offset
) << tk
->ntp_error_shift
;
1457 * Calculate the multiplier adjustment needed to match the frequency
1460 static __always_inline
void timekeeping_freqadjust(struct timekeeper
*tk
,
1463 s64 interval
= tk
->cycle_interval
;
1464 s64 xinterval
= tk
->xtime_interval
;
1469 /* Remove any current error adj from freq calculation */
1470 if (tk
->ntp_err_mult
)
1471 xinterval
-= tk
->cycle_interval
;
1473 tk
->ntp_tick
= ntp_tick_length();
1475 /* Calculate current error per tick */
1476 tick_error
= ntp_tick_length() >> tk
->ntp_error_shift
;
1477 tick_error
-= (xinterval
+ tk
->xtime_remainder
);
1479 /* Don't worry about correcting it if its small */
1480 if (likely((tick_error
>= 0) && (tick_error
<= interval
)))
1483 /* preserve the direction of correction */
1484 negative
= (tick_error
< 0);
1486 /* Sort out the magnitude of the correction */
1487 tick_error
= abs(tick_error
);
1488 for (adj
= 0; tick_error
> interval
; adj
++)
1491 /* scale the corrections */
1492 timekeeping_apply_adjustment(tk
, offset
, negative
, adj
);
1496 * Adjust the timekeeper's multiplier to the correct frequency
1497 * and also to reduce the accumulated error value.
1499 static void timekeeping_adjust(struct timekeeper
*tk
, s64 offset
)
1501 /* Correct for the current frequency error */
1502 timekeeping_freqadjust(tk
, offset
);
1504 /* Next make a small adjustment to fix any cumulative error */
1505 if (!tk
->ntp_err_mult
&& (tk
->ntp_error
> 0)) {
1506 tk
->ntp_err_mult
= 1;
1507 timekeeping_apply_adjustment(tk
, offset
, 0, 0);
1508 } else if (tk
->ntp_err_mult
&& (tk
->ntp_error
<= 0)) {
1509 /* Undo any existing error adjustment */
1510 timekeeping_apply_adjustment(tk
, offset
, 1, 0);
1511 tk
->ntp_err_mult
= 0;
1514 if (unlikely(tk
->tkr
.clock
->maxadj
&&
1515 (abs(tk
->tkr
.mult
- tk
->tkr
.clock
->mult
)
1516 > tk
->tkr
.clock
->maxadj
))) {
1517 printk_once(KERN_WARNING
1518 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1519 tk
->tkr
.clock
->name
, (long)tk
->tkr
.mult
,
1520 (long)tk
->tkr
.clock
->mult
+ tk
->tkr
.clock
->maxadj
);
1524 * It may be possible that when we entered this function, xtime_nsec
1525 * was very small. Further, if we're slightly speeding the clocksource
1526 * in the code above, its possible the required corrective factor to
1527 * xtime_nsec could cause it to underflow.
1529 * Now, since we already accumulated the second, cannot simply roll
1530 * the accumulated second back, since the NTP subsystem has been
1531 * notified via second_overflow. So instead we push xtime_nsec forward
1532 * by the amount we underflowed, and add that amount into the error.
1534 * We'll correct this error next time through this function, when
1535 * xtime_nsec is not as small.
1537 if (unlikely((s64
)tk
->tkr
.xtime_nsec
< 0)) {
1538 s64 neg
= -(s64
)tk
->tkr
.xtime_nsec
;
1539 tk
->tkr
.xtime_nsec
= 0;
1540 tk
->ntp_error
+= neg
<< tk
->ntp_error_shift
;
1545 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1547 * Helper function that accumulates a the nsecs greater then a second
1548 * from the xtime_nsec field to the xtime_secs field.
1549 * It also calls into the NTP code to handle leapsecond processing.
1552 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper
*tk
)
1554 u64 nsecps
= (u64
)NSEC_PER_SEC
<< tk
->tkr
.shift
;
1555 unsigned int clock_set
= 0;
1557 while (tk
->tkr
.xtime_nsec
>= nsecps
) {
1560 tk
->tkr
.xtime_nsec
-= nsecps
;
1563 /* Figure out if its a leap sec and apply if needed */
1564 leap
= second_overflow(tk
->xtime_sec
);
1565 if (unlikely(leap
)) {
1566 struct timespec64 ts
;
1568 tk
->xtime_sec
+= leap
;
1572 tk_set_wall_to_mono(tk
,
1573 timespec64_sub(tk
->wall_to_monotonic
, ts
));
1575 __timekeeping_set_tai_offset(tk
, tk
->tai_offset
- leap
);
1577 clock_set
= TK_CLOCK_WAS_SET
;
1584 * logarithmic_accumulation - shifted accumulation of cycles
1586 * This functions accumulates a shifted interval of cycles into
1587 * into a shifted interval nanoseconds. Allows for O(log) accumulation
1590 * Returns the unconsumed cycles.
1592 static cycle_t
logarithmic_accumulation(struct timekeeper
*tk
, cycle_t offset
,
1594 unsigned int *clock_set
)
1596 cycle_t interval
= tk
->cycle_interval
<< shift
;
1599 /* If the offset is smaller then a shifted interval, do nothing */
1600 if (offset
< interval
)
1603 /* Accumulate one shifted interval */
1605 tk
->tkr
.cycle_last
+= interval
;
1607 tk
->tkr
.xtime_nsec
+= tk
->xtime_interval
<< shift
;
1608 *clock_set
|= accumulate_nsecs_to_secs(tk
);
1610 /* Accumulate raw time */
1611 raw_nsecs
= (u64
)tk
->raw_interval
<< shift
;
1612 raw_nsecs
+= tk
->raw_time
.tv_nsec
;
1613 if (raw_nsecs
>= NSEC_PER_SEC
) {
1614 u64 raw_secs
= raw_nsecs
;
1615 raw_nsecs
= do_div(raw_secs
, NSEC_PER_SEC
);
1616 tk
->raw_time
.tv_sec
+= raw_secs
;
1618 tk
->raw_time
.tv_nsec
= raw_nsecs
;
1620 /* Accumulate error between NTP and clock interval */
1621 tk
->ntp_error
+= tk
->ntp_tick
<< shift
;
1622 tk
->ntp_error
-= (tk
->xtime_interval
+ tk
->xtime_remainder
) <<
1623 (tk
->ntp_error_shift
+ shift
);
1629 * update_wall_time - Uses the current clocksource to increment the wall time
1632 void update_wall_time(void)
1634 struct timekeeper
*real_tk
= &tk_core
.timekeeper
;
1635 struct timekeeper
*tk
= &shadow_timekeeper
;
1637 int shift
= 0, maxshift
;
1638 unsigned int clock_set
= 0;
1639 unsigned long flags
;
1641 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1643 /* Make sure we're fully resumed: */
1644 if (unlikely(timekeeping_suspended
))
1647 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1648 offset
= real_tk
->cycle_interval
;
1650 offset
= clocksource_delta(tk
->tkr
.read(tk
->tkr
.clock
),
1651 tk
->tkr
.cycle_last
, tk
->tkr
.mask
);
1654 /* Check if there's really nothing to do */
1655 if (offset
< real_tk
->cycle_interval
)
1658 /* Do some additional sanity checking */
1659 timekeeping_check_update(real_tk
, offset
);
1662 * With NO_HZ we may have to accumulate many cycle_intervals
1663 * (think "ticks") worth of time at once. To do this efficiently,
1664 * we calculate the largest doubling multiple of cycle_intervals
1665 * that is smaller than the offset. We then accumulate that
1666 * chunk in one go, and then try to consume the next smaller
1669 shift
= ilog2(offset
) - ilog2(tk
->cycle_interval
);
1670 shift
= max(0, shift
);
1671 /* Bound shift to one less than what overflows tick_length */
1672 maxshift
= (64 - (ilog2(ntp_tick_length())+1)) - 1;
1673 shift
= min(shift
, maxshift
);
1674 while (offset
>= tk
->cycle_interval
) {
1675 offset
= logarithmic_accumulation(tk
, offset
, shift
,
1677 if (offset
< tk
->cycle_interval
<<shift
)
1681 /* correct the clock when NTP error is too big */
1682 timekeeping_adjust(tk
, offset
);
1685 * XXX This can be killed once everyone converts
1686 * to the new update_vsyscall.
1688 old_vsyscall_fixup(tk
);
1691 * Finally, make sure that after the rounding
1692 * xtime_nsec isn't larger than NSEC_PER_SEC
1694 clock_set
|= accumulate_nsecs_to_secs(tk
);
1696 write_seqcount_begin(&tk_core
.seq
);
1698 * Update the real timekeeper.
1700 * We could avoid this memcpy by switching pointers, but that
1701 * requires changes to all other timekeeper usage sites as
1702 * well, i.e. move the timekeeper pointer getter into the
1703 * spinlocked/seqcount protected sections. And we trade this
1704 * memcpy under the tk_core.seq against one before we start
1707 memcpy(real_tk
, tk
, sizeof(*tk
));
1708 timekeeping_update(real_tk
, clock_set
);
1709 write_seqcount_end(&tk_core
.seq
);
1711 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1713 /* Have to call _delayed version, since in irq context*/
1714 clock_was_set_delayed();
1718 * getboottime64 - Return the real time of system boot.
1719 * @ts: pointer to the timespec64 to be set
1721 * Returns the wall-time of boot in a timespec64.
1723 * This is based on the wall_to_monotonic offset and the total suspend
1724 * time. Calls to settimeofday will affect the value returned (which
1725 * basically means that however wrong your real time clock is at boot time,
1726 * you get the right time here).
1728 void getboottime64(struct timespec64
*ts
)
1730 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1731 ktime_t t
= ktime_sub(tk
->offs_real
, tk
->offs_boot
);
1733 *ts
= ktime_to_timespec64(t
);
1735 EXPORT_SYMBOL_GPL(getboottime64
);
1737 unsigned long get_seconds(void)
1739 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1741 return tk
->xtime_sec
;
1743 EXPORT_SYMBOL(get_seconds
);
1745 struct timespec
__current_kernel_time(void)
1747 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1749 return timespec64_to_timespec(tk_xtime(tk
));
1752 struct timespec
current_kernel_time(void)
1754 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1755 struct timespec64 now
;
1759 seq
= read_seqcount_begin(&tk_core
.seq
);
1762 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1764 return timespec64_to_timespec(now
);
1766 EXPORT_SYMBOL(current_kernel_time
);
1768 struct timespec64
get_monotonic_coarse64(void)
1770 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1771 struct timespec64 now
, mono
;
1775 seq
= read_seqcount_begin(&tk_core
.seq
);
1778 mono
= tk
->wall_to_monotonic
;
1779 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1781 set_normalized_timespec64(&now
, now
.tv_sec
+ mono
.tv_sec
,
1782 now
.tv_nsec
+ mono
.tv_nsec
);
1788 * Must hold jiffies_lock
1790 void do_timer(unsigned long ticks
)
1792 jiffies_64
+= ticks
;
1793 calc_global_load(ticks
);
1797 * ktime_get_update_offsets_tick - hrtimer helper
1798 * @offs_real: pointer to storage for monotonic -> realtime offset
1799 * @offs_boot: pointer to storage for monotonic -> boottime offset
1800 * @offs_tai: pointer to storage for monotonic -> clock tai offset
1802 * Returns monotonic time at last tick and various offsets
1804 ktime_t
ktime_get_update_offsets_tick(ktime_t
*offs_real
, ktime_t
*offs_boot
,
1807 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1813 seq
= read_seqcount_begin(&tk_core
.seq
);
1815 base
= tk
->tkr
.base_mono
;
1816 nsecs
= tk
->tkr
.xtime_nsec
>> tk
->tkr
.shift
;
1818 *offs_real
= tk
->offs_real
;
1819 *offs_boot
= tk
->offs_boot
;
1820 *offs_tai
= tk
->offs_tai
;
1821 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1823 return ktime_add_ns(base
, nsecs
);
1826 #ifdef CONFIG_HIGH_RES_TIMERS
1828 * ktime_get_update_offsets_now - hrtimer helper
1829 * @offs_real: pointer to storage for monotonic -> realtime offset
1830 * @offs_boot: pointer to storage for monotonic -> boottime offset
1831 * @offs_tai: pointer to storage for monotonic -> clock tai offset
1833 * Returns current monotonic time and updates the offsets
1834 * Called from hrtimer_interrupt() or retrigger_next_event()
1836 ktime_t
ktime_get_update_offsets_now(ktime_t
*offs_real
, ktime_t
*offs_boot
,
1839 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1845 seq
= read_seqcount_begin(&tk_core
.seq
);
1847 base
= tk
->tkr
.base_mono
;
1848 nsecs
= timekeeping_get_ns(&tk
->tkr
);
1850 *offs_real
= tk
->offs_real
;
1851 *offs_boot
= tk
->offs_boot
;
1852 *offs_tai
= tk
->offs_tai
;
1853 } while (read_seqcount_retry(&tk_core
.seq
, seq
));
1855 return ktime_add_ns(base
, nsecs
);
1860 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
1862 int do_adjtimex(struct timex
*txc
)
1864 struct timekeeper
*tk
= &tk_core
.timekeeper
;
1865 unsigned long flags
;
1866 struct timespec64 ts
;
1870 /* Validate the data before disabling interrupts */
1871 ret
= ntp_validate_timex(txc
);
1875 if (txc
->modes
& ADJ_SETOFFSET
) {
1876 struct timespec delta
;
1877 delta
.tv_sec
= txc
->time
.tv_sec
;
1878 delta
.tv_nsec
= txc
->time
.tv_usec
;
1879 if (!(txc
->modes
& ADJ_NANO
))
1880 delta
.tv_nsec
*= 1000;
1881 ret
= timekeeping_inject_offset(&delta
);
1886 getnstimeofday64(&ts
);
1888 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1889 write_seqcount_begin(&tk_core
.seq
);
1891 orig_tai
= tai
= tk
->tai_offset
;
1892 ret
= __do_adjtimex(txc
, &ts
, &tai
);
1894 if (tai
!= orig_tai
) {
1895 __timekeeping_set_tai_offset(tk
, tai
);
1896 timekeeping_update(tk
, TK_MIRROR
| TK_CLOCK_WAS_SET
);
1898 write_seqcount_end(&tk_core
.seq
);
1899 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1901 if (tai
!= orig_tai
)
1904 ntp_notify_cmos_timer();
1909 #ifdef CONFIG_NTP_PPS
1911 * hardpps() - Accessor function to NTP __hardpps function
1913 void hardpps(const struct timespec
*phase_ts
, const struct timespec
*raw_ts
)
1915 unsigned long flags
;
1917 raw_spin_lock_irqsave(&timekeeper_lock
, flags
);
1918 write_seqcount_begin(&tk_core
.seq
);
1920 __hardpps(phase_ts
, raw_ts
);
1922 write_seqcount_end(&tk_core
.seq
);
1923 raw_spin_unlock_irqrestore(&timekeeper_lock
, flags
);
1925 EXPORT_SYMBOL(hardpps
);
1929 * xtime_update() - advances the timekeeping infrastructure
1930 * @ticks: number of ticks, that have elapsed since the last call.
1932 * Must be called with interrupts disabled.
1934 void xtime_update(unsigned long ticks
)
1936 write_seqlock(&jiffies_lock
);
1938 write_sequnlock(&jiffies_lock
);