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>
26 #include "tick-internal.h"
28 static struct timekeeper timekeeper;
29 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
30 static seqcount_t timekeeper_seq;
32 /* flag for if timekeeping is suspended */
33 int __read_mostly timekeeping_suspended;
35 /* Flag for if there is a persistent clock on this platform */
36 bool __read_mostly persistent_clock_exist = false;
38 static inline void tk_normalize_xtime(struct timekeeper *tk)
40 while (tk->xtime_nsec >= ((u64)NSEC_PER_SEC << tk->shift)) {
41 tk->xtime_nsec -= (u64)NSEC_PER_SEC << tk->shift;
46 static void tk_set_xtime(struct timekeeper *tk, const struct timespec *ts)
48 tk->xtime_sec = ts->tv_sec;
49 tk->xtime_nsec = (u64)ts->tv_nsec << tk->shift;
52 static void tk_xtime_add(struct timekeeper *tk, const struct timespec *ts)
54 tk->xtime_sec += ts->tv_sec;
55 tk->xtime_nsec += (u64)ts->tv_nsec << tk->shift;
56 tk_normalize_xtime(tk);
59 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec wtm)
64 * Verify consistency of: offset_real = -wall_to_monotonic
65 * before modifying anything
67 set_normalized_timespec(&tmp, -tk->wall_to_monotonic.tv_sec,
68 -tk->wall_to_monotonic.tv_nsec);
69 WARN_ON_ONCE(tk->offs_real.tv64 != timespec_to_ktime(tmp).tv64);
70 tk->wall_to_monotonic = wtm;
71 set_normalized_timespec(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
72 tk->offs_real = timespec_to_ktime(tmp);
73 tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tk->tai_offset, 0));
76 static void tk_set_sleep_time(struct timekeeper *tk, struct timespec t)
78 /* Verify consistency before modifying */
79 WARN_ON_ONCE(tk->offs_boot.tv64 != timespec_to_ktime(tk->total_sleep_time).tv64);
81 tk->total_sleep_time = t;
82 tk->offs_boot = timespec_to_ktime(t);
86 * timekeeper_setup_internals - Set up internals to use clocksource clock.
88 * @clock: Pointer to clocksource.
90 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
91 * pair and interval request.
93 * Unless you're the timekeeping code, you should not be using this!
95 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
99 struct clocksource *old_clock;
101 old_clock = tk->clock;
103 clock->cycle_last = clock->read(clock);
105 /* Do the ns -> cycle conversion first, using original mult */
106 tmp = NTP_INTERVAL_LENGTH;
107 tmp <<= clock->shift;
109 tmp += clock->mult/2;
110 do_div(tmp, clock->mult);
114 interval = (cycle_t) tmp;
115 tk->cycle_interval = interval;
117 /* Go back from cycles -> shifted ns */
118 tk->xtime_interval = (u64) interval * clock->mult;
119 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
121 ((u64) interval * clock->mult) >> clock->shift;
123 /* if changing clocks, convert xtime_nsec shift units */
125 int shift_change = clock->shift - old_clock->shift;
126 if (shift_change < 0)
127 tk->xtime_nsec >>= -shift_change;
129 tk->xtime_nsec <<= shift_change;
131 tk->shift = clock->shift;
134 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
137 * The timekeeper keeps its own mult values for the currently
138 * active clocksource. These value will be adjusted via NTP
139 * to counteract clock drifting.
141 tk->mult = clock->mult;
144 /* Timekeeper helper functions. */
146 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
147 u32 (*arch_gettimeoffset)(void);
149 u32 get_arch_timeoffset(void)
151 if (likely(arch_gettimeoffset))
152 return arch_gettimeoffset();
156 static inline u32 get_arch_timeoffset(void) { return 0; }
159 static inline s64 timekeeping_get_ns(struct timekeeper *tk)
161 cycle_t cycle_now, cycle_delta;
162 struct clocksource *clock;
165 /* read clocksource: */
167 cycle_now = clock->read(clock);
169 /* calculate the delta since the last update_wall_time: */
170 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
172 nsec = cycle_delta * tk->mult + tk->xtime_nsec;
175 /* If arch requires, add in get_arch_timeoffset() */
176 return nsec + get_arch_timeoffset();
179 static inline s64 timekeeping_get_ns_raw(struct timekeeper *tk)
181 cycle_t cycle_now, cycle_delta;
182 struct clocksource *clock;
185 /* read clocksource: */
187 cycle_now = clock->read(clock);
189 /* calculate the delta since the last update_wall_time: */
190 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
192 /* convert delta to nanoseconds. */
193 nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
195 /* If arch requires, add in get_arch_timeoffset() */
196 return nsec + get_arch_timeoffset();
199 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
201 static void update_pvclock_gtod(struct timekeeper *tk)
203 raw_notifier_call_chain(&pvclock_gtod_chain, 0, tk);
207 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
209 int pvclock_gtod_register_notifier(struct notifier_block *nb)
211 struct timekeeper *tk = &timekeeper;
215 raw_spin_lock_irqsave(&timekeeper_lock, flags);
216 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
217 update_pvclock_gtod(tk);
218 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
222 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
225 * pvclock_gtod_unregister_notifier - unregister a pvclock
226 * timedata update listener
228 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
233 raw_spin_lock_irqsave(&timekeeper_lock, flags);
234 ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
235 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
239 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
241 /* must hold timekeeper_lock */
242 static void timekeeping_update(struct timekeeper *tk, bool clearntp)
249 update_pvclock_gtod(tk);
253 * timekeeping_forward_now - update clock to the current time
255 * Forward the current clock to update its state since the last call to
256 * update_wall_time(). This is useful before significant clock changes,
257 * as it avoids having to deal with this time offset explicitly.
259 static void timekeeping_forward_now(struct timekeeper *tk)
261 cycle_t cycle_now, cycle_delta;
262 struct clocksource *clock;
266 cycle_now = clock->read(clock);
267 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
268 clock->cycle_last = cycle_now;
270 tk->xtime_nsec += cycle_delta * tk->mult;
272 /* If arch requires, add in get_arch_timeoffset() */
273 tk->xtime_nsec += (u64)get_arch_timeoffset() << tk->shift;
275 tk_normalize_xtime(tk);
277 nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
278 timespec_add_ns(&tk->raw_time, nsec);
282 * __getnstimeofday - Returns the time of day in a timespec.
283 * @ts: pointer to the timespec to be set
285 * Updates the time of day in the timespec.
286 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
288 int __getnstimeofday(struct timespec *ts)
290 struct timekeeper *tk = &timekeeper;
295 seq = read_seqcount_begin(&timekeeper_seq);
297 ts->tv_sec = tk->xtime_sec;
298 nsecs = timekeeping_get_ns(tk);
300 } while (read_seqcount_retry(&timekeeper_seq, seq));
303 timespec_add_ns(ts, nsecs);
306 * Do not bail out early, in case there were callers still using
307 * the value, even in the face of the WARN_ON.
309 if (unlikely(timekeeping_suspended))
313 EXPORT_SYMBOL(__getnstimeofday);
316 * getnstimeofday - Returns the time of day in a timespec.
317 * @ts: pointer to the timespec to be set
319 * Returns the time of day in a timespec (WARN if suspended).
321 void getnstimeofday(struct timespec *ts)
323 WARN_ON(__getnstimeofday(ts));
325 EXPORT_SYMBOL(getnstimeofday);
327 ktime_t ktime_get(void)
329 struct timekeeper *tk = &timekeeper;
333 WARN_ON(timekeeping_suspended);
336 seq = read_seqcount_begin(&timekeeper_seq);
337 secs = tk->xtime_sec + tk->wall_to_monotonic.tv_sec;
338 nsecs = timekeeping_get_ns(tk) + tk->wall_to_monotonic.tv_nsec;
340 } while (read_seqcount_retry(&timekeeper_seq, seq));
342 * Use ktime_set/ktime_add_ns to create a proper ktime on
343 * 32-bit architectures without CONFIG_KTIME_SCALAR.
345 return ktime_add_ns(ktime_set(secs, 0), nsecs);
347 EXPORT_SYMBOL_GPL(ktime_get);
350 * ktime_get_ts - get the monotonic clock in timespec format
351 * @ts: pointer to timespec variable
353 * The function calculates the monotonic clock from the realtime
354 * clock and the wall_to_monotonic offset and stores the result
355 * in normalized timespec format in the variable pointed to by @ts.
357 void ktime_get_ts(struct timespec *ts)
359 struct timekeeper *tk = &timekeeper;
360 struct timespec tomono;
364 WARN_ON(timekeeping_suspended);
367 seq = read_seqcount_begin(&timekeeper_seq);
368 ts->tv_sec = tk->xtime_sec;
369 nsec = timekeeping_get_ns(tk);
370 tomono = tk->wall_to_monotonic;
372 } while (read_seqcount_retry(&timekeeper_seq, seq));
374 ts->tv_sec += tomono.tv_sec;
376 timespec_add_ns(ts, nsec + tomono.tv_nsec);
378 EXPORT_SYMBOL_GPL(ktime_get_ts);
382 * timekeeping_clocktai - Returns the TAI time of day in a timespec
383 * @ts: pointer to the timespec to be set
385 * Returns the time of day in a timespec.
387 void timekeeping_clocktai(struct timespec *ts)
389 struct timekeeper *tk = &timekeeper;
393 WARN_ON(timekeeping_suspended);
396 seq = read_seqcount_begin(&timekeeper_seq);
398 ts->tv_sec = tk->xtime_sec + tk->tai_offset;
399 nsecs = timekeeping_get_ns(tk);
401 } while (read_seqcount_retry(&timekeeper_seq, seq));
404 timespec_add_ns(ts, nsecs);
407 EXPORT_SYMBOL(timekeeping_clocktai);
411 * ktime_get_clocktai - Returns the TAI time of day in a ktime
413 * Returns the time of day in a ktime.
415 ktime_t ktime_get_clocktai(void)
419 timekeeping_clocktai(&ts);
420 return timespec_to_ktime(ts);
422 EXPORT_SYMBOL(ktime_get_clocktai);
424 #ifdef CONFIG_NTP_PPS
427 * getnstime_raw_and_real - get day and raw monotonic time in timespec format
428 * @ts_raw: pointer to the timespec to be set to raw monotonic time
429 * @ts_real: pointer to the timespec to be set to the time of day
431 * This function reads both the time of day and raw monotonic time at the
432 * same time atomically and stores the resulting timestamps in timespec
435 void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
437 struct timekeeper *tk = &timekeeper;
439 s64 nsecs_raw, nsecs_real;
441 WARN_ON_ONCE(timekeeping_suspended);
444 seq = read_seqcount_begin(&timekeeper_seq);
446 *ts_raw = tk->raw_time;
447 ts_real->tv_sec = tk->xtime_sec;
448 ts_real->tv_nsec = 0;
450 nsecs_raw = timekeeping_get_ns_raw(tk);
451 nsecs_real = timekeeping_get_ns(tk);
453 } while (read_seqcount_retry(&timekeeper_seq, seq));
455 timespec_add_ns(ts_raw, nsecs_raw);
456 timespec_add_ns(ts_real, nsecs_real);
458 EXPORT_SYMBOL(getnstime_raw_and_real);
460 #endif /* CONFIG_NTP_PPS */
463 * do_gettimeofday - Returns the time of day in a timeval
464 * @tv: pointer to the timeval to be set
466 * NOTE: Users should be converted to using getnstimeofday()
468 void do_gettimeofday(struct timeval *tv)
472 getnstimeofday(&now);
473 tv->tv_sec = now.tv_sec;
474 tv->tv_usec = now.tv_nsec/1000;
476 EXPORT_SYMBOL(do_gettimeofday);
479 * do_settimeofday - Sets the time of day
480 * @tv: pointer to the timespec variable containing the new time
482 * Sets the time of day to the new time and update NTP and notify hrtimers
484 int do_settimeofday(const struct timespec *tv)
486 struct timekeeper *tk = &timekeeper;
487 struct timespec ts_delta, xt;
490 if (!timespec_valid_strict(tv))
493 raw_spin_lock_irqsave(&timekeeper_lock, flags);
494 write_seqcount_begin(&timekeeper_seq);
496 timekeeping_forward_now(tk);
499 ts_delta.tv_sec = tv->tv_sec - xt.tv_sec;
500 ts_delta.tv_nsec = tv->tv_nsec - xt.tv_nsec;
502 tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, ts_delta));
504 tk_set_xtime(tk, tv);
506 timekeeping_update(tk, true);
508 write_seqcount_end(&timekeeper_seq);
509 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
511 /* signal hrtimers about time change */
516 EXPORT_SYMBOL(do_settimeofday);
519 * timekeeping_inject_offset - Adds or subtracts from the current time.
520 * @tv: pointer to the timespec variable containing the offset
522 * Adds or subtracts an offset value from the current time.
524 int timekeeping_inject_offset(struct timespec *ts)
526 struct timekeeper *tk = &timekeeper;
531 if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
534 raw_spin_lock_irqsave(&timekeeper_lock, flags);
535 write_seqcount_begin(&timekeeper_seq);
537 timekeeping_forward_now(tk);
539 /* Make sure the proposed value is valid */
540 tmp = timespec_add(tk_xtime(tk), *ts);
541 if (!timespec_valid_strict(&tmp)) {
546 tk_xtime_add(tk, ts);
547 tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *ts));
549 error: /* even if we error out, we forwarded the time, so call update */
550 timekeeping_update(tk, true);
552 write_seqcount_end(&timekeeper_seq);
553 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
555 /* signal hrtimers about time change */
560 EXPORT_SYMBOL(timekeeping_inject_offset);
564 * timekeeping_get_tai_offset - Returns current TAI offset from UTC
567 s32 timekeeping_get_tai_offset(void)
569 struct timekeeper *tk = &timekeeper;
574 seq = read_seqcount_begin(&timekeeper_seq);
575 ret = tk->tai_offset;
576 } while (read_seqcount_retry(&timekeeper_seq, seq));
582 * __timekeeping_set_tai_offset - Lock free worker function
585 void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
587 tk->tai_offset = tai_offset;
588 tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tai_offset, 0));
592 * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
595 void timekeeping_set_tai_offset(s32 tai_offset)
597 struct timekeeper *tk = &timekeeper;
600 raw_spin_lock_irqsave(&timekeeper_lock, flags);
601 write_seqcount_begin(&timekeeper_seq);
602 __timekeeping_set_tai_offset(tk, tai_offset);
603 write_seqcount_end(&timekeeper_seq);
604 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
608 * change_clocksource - Swaps clocksources if a new one is available
610 * Accumulates current time interval and initializes new clocksource
612 static int change_clocksource(void *data)
614 struct timekeeper *tk = &timekeeper;
615 struct clocksource *new, *old;
618 new = (struct clocksource *) data;
620 raw_spin_lock_irqsave(&timekeeper_lock, flags);
621 write_seqcount_begin(&timekeeper_seq);
623 timekeeping_forward_now(tk);
624 if (!new->enable || new->enable(new) == 0) {
626 tk_setup_internals(tk, new);
630 timekeeping_update(tk, true);
632 write_seqcount_end(&timekeeper_seq);
633 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
639 * timekeeping_notify - Install a new clock source
640 * @clock: pointer to the clock source
642 * This function is called from clocksource.c after a new, better clock
643 * source has been registered. The caller holds the clocksource_mutex.
645 void timekeeping_notify(struct clocksource *clock)
647 struct timekeeper *tk = &timekeeper;
649 if (tk->clock == clock)
651 stop_machine(change_clocksource, clock, NULL);
656 * ktime_get_real - get the real (wall-) time in ktime_t format
658 * returns the time in ktime_t format
660 ktime_t ktime_get_real(void)
664 getnstimeofday(&now);
666 return timespec_to_ktime(now);
668 EXPORT_SYMBOL_GPL(ktime_get_real);
671 * getrawmonotonic - Returns the raw monotonic time in a timespec
672 * @ts: pointer to the timespec to be set
674 * Returns the raw monotonic time (completely un-modified by ntp)
676 void getrawmonotonic(struct timespec *ts)
678 struct timekeeper *tk = &timekeeper;
683 seq = read_seqcount_begin(&timekeeper_seq);
684 nsecs = timekeeping_get_ns_raw(tk);
687 } while (read_seqcount_retry(&timekeeper_seq, seq));
689 timespec_add_ns(ts, nsecs);
691 EXPORT_SYMBOL(getrawmonotonic);
694 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
696 int timekeeping_valid_for_hres(void)
698 struct timekeeper *tk = &timekeeper;
703 seq = read_seqcount_begin(&timekeeper_seq);
705 ret = tk->clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
707 } while (read_seqcount_retry(&timekeeper_seq, seq));
713 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
715 u64 timekeeping_max_deferment(void)
717 struct timekeeper *tk = &timekeeper;
722 seq = read_seqcount_begin(&timekeeper_seq);
724 ret = tk->clock->max_idle_ns;
726 } while (read_seqcount_retry(&timekeeper_seq, seq));
732 * read_persistent_clock - Return time from the persistent clock.
734 * Weak dummy function for arches that do not yet support it.
735 * Reads the time from the battery backed persistent clock.
736 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
738 * XXX - Do be sure to remove it once all arches implement it.
740 void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
747 * read_boot_clock - Return time of the system start.
749 * Weak dummy function for arches that do not yet support it.
750 * Function to read the exact time the system has been started.
751 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
753 * XXX - Do be sure to remove it once all arches implement it.
755 void __attribute__((weak)) read_boot_clock(struct timespec *ts)
762 * timekeeping_init - Initializes the clocksource and common timekeeping values
764 void __init timekeeping_init(void)
766 struct timekeeper *tk = &timekeeper;
767 struct clocksource *clock;
769 struct timespec now, boot, tmp;
771 read_persistent_clock(&now);
773 if (!timespec_valid_strict(&now)) {
774 pr_warn("WARNING: Persistent clock returned invalid value!\n"
775 " Check your CMOS/BIOS settings.\n");
778 } else if (now.tv_sec || now.tv_nsec)
779 persistent_clock_exist = true;
781 read_boot_clock(&boot);
782 if (!timespec_valid_strict(&boot)) {
783 pr_warn("WARNING: Boot clock returned invalid value!\n"
784 " Check your CMOS/BIOS settings.\n");
791 raw_spin_lock_irqsave(&timekeeper_lock, flags);
792 write_seqcount_begin(&timekeeper_seq);
793 clock = clocksource_default_clock();
795 clock->enable(clock);
796 tk_setup_internals(tk, clock);
798 tk_set_xtime(tk, &now);
799 tk->raw_time.tv_sec = 0;
800 tk->raw_time.tv_nsec = 0;
801 if (boot.tv_sec == 0 && boot.tv_nsec == 0)
804 set_normalized_timespec(&tmp, -boot.tv_sec, -boot.tv_nsec);
805 tk_set_wall_to_mono(tk, tmp);
809 tk_set_sleep_time(tk, tmp);
811 write_seqcount_end(&timekeeper_seq);
812 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
815 /* time in seconds when suspend began */
816 static struct timespec timekeeping_suspend_time;
819 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
820 * @delta: pointer to a timespec delta value
822 * Takes a timespec offset measuring a suspend interval and properly
823 * adds the sleep offset to the timekeeping variables.
825 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
826 struct timespec *delta)
828 if (!timespec_valid_strict(delta)) {
829 printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
830 "sleep delta value!\n");
833 tk_xtime_add(tk, delta);
834 tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *delta));
835 tk_set_sleep_time(tk, timespec_add(tk->total_sleep_time, *delta));
839 * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
840 * @delta: pointer to a timespec delta value
842 * This hook is for architectures that cannot support read_persistent_clock
843 * because their RTC/persistent clock is only accessible when irqs are enabled.
845 * This function should only be called by rtc_resume(), and allows
846 * a suspend offset to be injected into the timekeeping values.
848 void timekeeping_inject_sleeptime(struct timespec *delta)
850 struct timekeeper *tk = &timekeeper;
854 * Make sure we don't set the clock twice, as timekeeping_resume()
857 if (has_persistent_clock())
860 raw_spin_lock_irqsave(&timekeeper_lock, flags);
861 write_seqcount_begin(&timekeeper_seq);
863 timekeeping_forward_now(tk);
865 __timekeeping_inject_sleeptime(tk, delta);
867 timekeeping_update(tk, true);
869 write_seqcount_end(&timekeeper_seq);
870 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
872 /* signal hrtimers about time change */
877 * timekeeping_resume - Resumes the generic timekeeping subsystem.
879 * This is for the generic clocksource timekeeping.
880 * xtime/wall_to_monotonic/jiffies/etc are
881 * still managed by arch specific suspend/resume code.
883 static void timekeeping_resume(void)
885 struct timekeeper *tk = &timekeeper;
886 struct clocksource *clock = tk->clock;
888 struct timespec ts_new, ts_delta;
889 cycle_t cycle_now, cycle_delta;
890 bool suspendtime_found = false;
892 read_persistent_clock(&ts_new);
894 clockevents_resume();
895 clocksource_resume();
897 raw_spin_lock_irqsave(&timekeeper_lock, flags);
898 write_seqcount_begin(&timekeeper_seq);
901 * After system resumes, we need to calculate the suspended time and
902 * compensate it for the OS time. There are 3 sources that could be
903 * used: Nonstop clocksource during suspend, persistent clock and rtc
906 * One specific platform may have 1 or 2 or all of them, and the
907 * preference will be:
908 * suspend-nonstop clocksource -> persistent clock -> rtc
909 * The less preferred source will only be tried if there is no better
910 * usable source. The rtc part is handled separately in rtc core code.
912 cycle_now = clock->read(clock);
913 if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
914 cycle_now > clock->cycle_last) {
915 u64 num, max = ULLONG_MAX;
916 u32 mult = clock->mult;
917 u32 shift = clock->shift;
920 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
923 * "cycle_delta * mutl" may cause 64 bits overflow, if the
924 * suspended time is too long. In that case we need do the
925 * 64 bits math carefully
928 if (cycle_delta > max) {
929 num = div64_u64(cycle_delta, max);
930 nsec = (((u64) max * mult) >> shift) * num;
931 cycle_delta -= num * max;
933 nsec += ((u64) cycle_delta * mult) >> shift;
935 ts_delta = ns_to_timespec(nsec);
936 suspendtime_found = true;
937 } else if (timespec_compare(&ts_new, &timekeeping_suspend_time) > 0) {
938 ts_delta = timespec_sub(ts_new, timekeeping_suspend_time);
939 suspendtime_found = true;
942 if (suspendtime_found)
943 __timekeeping_inject_sleeptime(tk, &ts_delta);
945 /* Re-base the last cycle value */
946 clock->cycle_last = cycle_now;
948 timekeeping_suspended = 0;
949 timekeeping_update(tk, false);
950 write_seqcount_end(&timekeeper_seq);
951 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
953 touch_softlockup_watchdog();
955 clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
957 /* Resume hrtimers */
961 static int timekeeping_suspend(void)
963 struct timekeeper *tk = &timekeeper;
965 struct timespec delta, delta_delta;
966 static struct timespec old_delta;
968 read_persistent_clock(&timekeeping_suspend_time);
970 raw_spin_lock_irqsave(&timekeeper_lock, flags);
971 write_seqcount_begin(&timekeeper_seq);
972 timekeeping_forward_now(tk);
973 timekeeping_suspended = 1;
976 * To avoid drift caused by repeated suspend/resumes,
977 * which each can add ~1 second drift error,
978 * try to compensate so the difference in system time
979 * and persistent_clock time stays close to constant.
981 delta = timespec_sub(tk_xtime(tk), timekeeping_suspend_time);
982 delta_delta = timespec_sub(delta, old_delta);
983 if (abs(delta_delta.tv_sec) >= 2) {
985 * if delta_delta is too large, assume time correction
986 * has occured and set old_delta to the current delta.
990 /* Otherwise try to adjust old_system to compensate */
991 timekeeping_suspend_time =
992 timespec_add(timekeeping_suspend_time, delta_delta);
994 write_seqcount_end(&timekeeper_seq);
995 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
997 clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
998 clocksource_suspend();
999 clockevents_suspend();
1004 /* sysfs resume/suspend bits for timekeeping */
1005 static struct syscore_ops timekeeping_syscore_ops = {
1006 .resume = timekeeping_resume,
1007 .suspend = timekeeping_suspend,
1010 static int __init timekeeping_init_ops(void)
1012 register_syscore_ops(&timekeeping_syscore_ops);
1016 device_initcall(timekeeping_init_ops);
1019 * If the error is already larger, we look ahead even further
1020 * to compensate for late or lost adjustments.
1022 static __always_inline int timekeeping_bigadjust(struct timekeeper *tk,
1023 s64 error, s64 *interval,
1027 u32 look_ahead, adj;
1031 * Use the current error value to determine how much to look ahead.
1032 * The larger the error the slower we adjust for it to avoid problems
1033 * with losing too many ticks, otherwise we would overadjust and
1034 * produce an even larger error. The smaller the adjustment the
1035 * faster we try to adjust for it, as lost ticks can do less harm
1036 * here. This is tuned so that an error of about 1 msec is adjusted
1037 * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
1039 error2 = tk->ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
1040 error2 = abs(error2);
1041 for (look_ahead = 0; error2 > 0; look_ahead++)
1045 * Now calculate the error in (1 << look_ahead) ticks, but first
1046 * remove the single look ahead already included in the error.
1048 tick_error = ntp_tick_length() >> (tk->ntp_error_shift + 1);
1049 tick_error -= tk->xtime_interval >> 1;
1050 error = ((error - tick_error) >> look_ahead) + tick_error;
1052 /* Finally calculate the adjustment shift value. */
1057 *interval = -*interval;
1061 for (adj = 0; error > i; adj++)
1070 * Adjust the multiplier to reduce the error value,
1071 * this is optimized for the most common adjustments of -1,0,1,
1072 * for other values we can do a bit more work.
1074 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1076 s64 error, interval = tk->cycle_interval;
1080 * The point of this is to check if the error is greater than half
1083 * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
1085 * Note we subtract one in the shift, so that error is really error*2.
1086 * This "saves" dividing(shifting) interval twice, but keeps the
1087 * (error > interval) comparison as still measuring if error is
1088 * larger than half an interval.
1090 * Note: It does not "save" on aggravation when reading the code.
1092 error = tk->ntp_error >> (tk->ntp_error_shift - 1);
1093 if (error > interval) {
1095 * We now divide error by 4(via shift), which checks if
1096 * the error is greater than twice the interval.
1097 * If it is greater, we need a bigadjust, if its smaller,
1098 * we can adjust by 1.
1102 * XXX - In update_wall_time, we round up to the next
1103 * nanosecond, and store the amount rounded up into
1104 * the error. This causes the likely below to be unlikely.
1106 * The proper fix is to avoid rounding up by using
1107 * the high precision tk->xtime_nsec instead of
1108 * xtime.tv_nsec everywhere. Fixing this will take some
1111 if (likely(error <= interval))
1114 adj = timekeeping_bigadjust(tk, error, &interval, &offset);
1116 if (error < -interval) {
1117 /* See comment above, this is just switched for the negative */
1119 if (likely(error >= -interval)) {
1121 interval = -interval;
1124 adj = timekeeping_bigadjust(tk, error, &interval, &offset);
1131 if (unlikely(tk->clock->maxadj &&
1132 (tk->mult + adj > tk->clock->mult + tk->clock->maxadj))) {
1133 printk_once(KERN_WARNING
1134 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1135 tk->clock->name, (long)tk->mult + adj,
1136 (long)tk->clock->mult + tk->clock->maxadj);
1139 * So the following can be confusing.
1141 * To keep things simple, lets assume adj == 1 for now.
1143 * When adj != 1, remember that the interval and offset values
1144 * have been appropriately scaled so the math is the same.
1146 * The basic idea here is that we're increasing the multiplier
1147 * by one, this causes the xtime_interval to be incremented by
1148 * one cycle_interval. This is because:
1149 * xtime_interval = cycle_interval * mult
1150 * So if mult is being incremented by one:
1151 * xtime_interval = cycle_interval * (mult + 1)
1153 * xtime_interval = (cycle_interval * mult) + cycle_interval
1154 * Which can be shortened to:
1155 * xtime_interval += cycle_interval
1157 * So offset stores the non-accumulated cycles. Thus the current
1158 * time (in shifted nanoseconds) is:
1159 * now = (offset * adj) + xtime_nsec
1160 * Now, even though we're adjusting the clock frequency, we have
1161 * to keep time consistent. In other words, we can't jump back
1162 * in time, and we also want to avoid jumping forward in time.
1164 * So given the same offset value, we need the time to be the same
1165 * both before and after the freq adjustment.
1166 * now = (offset * adj_1) + xtime_nsec_1
1167 * now = (offset * adj_2) + xtime_nsec_2
1169 * (offset * adj_1) + xtime_nsec_1 =
1170 * (offset * adj_2) + xtime_nsec_2
1174 * (offset * adj_1) + xtime_nsec_1 =
1175 * (offset * (adj_1+1)) + xtime_nsec_2
1176 * (offset * adj_1) + xtime_nsec_1 =
1177 * (offset * adj_1) + offset + xtime_nsec_2
1178 * Canceling the sides:
1179 * xtime_nsec_1 = offset + xtime_nsec_2
1181 * xtime_nsec_2 = xtime_nsec_1 - offset
1182 * Which simplfies to:
1183 * xtime_nsec -= offset
1185 * XXX - TODO: Doc ntp_error calculation.
1188 tk->xtime_interval += interval;
1189 tk->xtime_nsec -= offset;
1190 tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1194 * It may be possible that when we entered this function, xtime_nsec
1195 * was very small. Further, if we're slightly speeding the clocksource
1196 * in the code above, its possible the required corrective factor to
1197 * xtime_nsec could cause it to underflow.
1199 * Now, since we already accumulated the second, cannot simply roll
1200 * the accumulated second back, since the NTP subsystem has been
1201 * notified via second_overflow. So instead we push xtime_nsec forward
1202 * by the amount we underflowed, and add that amount into the error.
1204 * We'll correct this error next time through this function, when
1205 * xtime_nsec is not as small.
1207 if (unlikely((s64)tk->xtime_nsec < 0)) {
1208 s64 neg = -(s64)tk->xtime_nsec;
1210 tk->ntp_error += neg << tk->ntp_error_shift;
1216 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1218 * Helper function that accumulates a the nsecs greater then a second
1219 * from the xtime_nsec field to the xtime_secs field.
1220 * It also calls into the NTP code to handle leapsecond processing.
1223 static inline void accumulate_nsecs_to_secs(struct timekeeper *tk)
1225 u64 nsecps = (u64)NSEC_PER_SEC << tk->shift;
1227 while (tk->xtime_nsec >= nsecps) {
1230 tk->xtime_nsec -= nsecps;
1233 /* Figure out if its a leap sec and apply if needed */
1234 leap = second_overflow(tk->xtime_sec);
1235 if (unlikely(leap)) {
1238 tk->xtime_sec += leap;
1242 tk_set_wall_to_mono(tk,
1243 timespec_sub(tk->wall_to_monotonic, ts));
1245 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1247 clock_was_set_delayed();
1253 * logarithmic_accumulation - shifted accumulation of cycles
1255 * This functions accumulates a shifted interval of cycles into
1256 * into a shifted interval nanoseconds. Allows for O(log) accumulation
1259 * Returns the unconsumed cycles.
1261 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1264 cycle_t interval = tk->cycle_interval << shift;
1267 /* If the offset is smaller then a shifted interval, do nothing */
1268 if (offset < interval)
1271 /* Accumulate one shifted interval */
1273 tk->clock->cycle_last += interval;
1275 tk->xtime_nsec += tk->xtime_interval << shift;
1276 accumulate_nsecs_to_secs(tk);
1278 /* Accumulate raw time */
1279 raw_nsecs = (u64)tk->raw_interval << shift;
1280 raw_nsecs += tk->raw_time.tv_nsec;
1281 if (raw_nsecs >= NSEC_PER_SEC) {
1282 u64 raw_secs = raw_nsecs;
1283 raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
1284 tk->raw_time.tv_sec += raw_secs;
1286 tk->raw_time.tv_nsec = raw_nsecs;
1288 /* Accumulate error between NTP and clock interval */
1289 tk->ntp_error += ntp_tick_length() << shift;
1290 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1291 (tk->ntp_error_shift + shift);
1296 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
1297 static inline void old_vsyscall_fixup(struct timekeeper *tk)
1302 * Store only full nanoseconds into xtime_nsec after rounding
1303 * it up and add the remainder to the error difference.
1304 * XXX - This is necessary to avoid small 1ns inconsistnecies caused
1305 * by truncating the remainder in vsyscalls. However, it causes
1306 * additional work to be done in timekeeping_adjust(). Once
1307 * the vsyscall implementations are converted to use xtime_nsec
1308 * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
1309 * users are removed, this can be killed.
1311 remainder = tk->xtime_nsec & ((1ULL << tk->shift) - 1);
1312 tk->xtime_nsec -= remainder;
1313 tk->xtime_nsec += 1ULL << tk->shift;
1314 tk->ntp_error += remainder << tk->ntp_error_shift;
1318 #define old_vsyscall_fixup(tk)
1324 * update_wall_time - Uses the current clocksource to increment the wall time
1327 static void update_wall_time(void)
1329 struct clocksource *clock;
1330 struct timekeeper *tk = &timekeeper;
1332 int shift = 0, maxshift;
1333 unsigned long flags;
1335 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1336 write_seqcount_begin(&timekeeper_seq);
1338 /* Make sure we're fully resumed: */
1339 if (unlikely(timekeeping_suspended))
1344 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1345 offset = tk->cycle_interval;
1347 offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
1350 /* Check if there's really nothing to do */
1351 if (offset < tk->cycle_interval)
1355 * With NO_HZ we may have to accumulate many cycle_intervals
1356 * (think "ticks") worth of time at once. To do this efficiently,
1357 * we calculate the largest doubling multiple of cycle_intervals
1358 * that is smaller than the offset. We then accumulate that
1359 * chunk in one go, and then try to consume the next smaller
1362 shift = ilog2(offset) - ilog2(tk->cycle_interval);
1363 shift = max(0, shift);
1364 /* Bound shift to one less than what overflows tick_length */
1365 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1366 shift = min(shift, maxshift);
1367 while (offset >= tk->cycle_interval) {
1368 offset = logarithmic_accumulation(tk, offset, shift);
1369 if (offset < tk->cycle_interval<<shift)
1373 /* correct the clock when NTP error is too big */
1374 timekeeping_adjust(tk, offset);
1377 * XXX This can be killed once everyone converts
1378 * to the new update_vsyscall.
1380 old_vsyscall_fixup(tk);
1383 * Finally, make sure that after the rounding
1384 * xtime_nsec isn't larger than NSEC_PER_SEC
1386 accumulate_nsecs_to_secs(tk);
1388 timekeeping_update(tk, false);
1391 write_seqcount_end(&timekeeper_seq);
1392 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1397 * getboottime - Return the real time of system boot.
1398 * @ts: pointer to the timespec to be set
1400 * Returns the wall-time of boot in a timespec.
1402 * This is based on the wall_to_monotonic offset and the total suspend
1403 * time. Calls to settimeofday will affect the value returned (which
1404 * basically means that however wrong your real time clock is at boot time,
1405 * you get the right time here).
1407 void getboottime(struct timespec *ts)
1409 struct timekeeper *tk = &timekeeper;
1410 struct timespec boottime = {
1411 .tv_sec = tk->wall_to_monotonic.tv_sec +
1412 tk->total_sleep_time.tv_sec,
1413 .tv_nsec = tk->wall_to_monotonic.tv_nsec +
1414 tk->total_sleep_time.tv_nsec
1417 set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
1419 EXPORT_SYMBOL_GPL(getboottime);
1422 * get_monotonic_boottime - Returns monotonic time since boot
1423 * @ts: pointer to the timespec to be set
1425 * Returns the monotonic time since boot in a timespec.
1427 * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
1428 * includes the time spent in suspend.
1430 void get_monotonic_boottime(struct timespec *ts)
1432 struct timekeeper *tk = &timekeeper;
1433 struct timespec tomono, sleep;
1437 WARN_ON(timekeeping_suspended);
1440 seq = read_seqcount_begin(&timekeeper_seq);
1441 ts->tv_sec = tk->xtime_sec;
1442 nsec = timekeeping_get_ns(tk);
1443 tomono = tk->wall_to_monotonic;
1444 sleep = tk->total_sleep_time;
1446 } while (read_seqcount_retry(&timekeeper_seq, seq));
1448 ts->tv_sec += tomono.tv_sec + sleep.tv_sec;
1450 timespec_add_ns(ts, nsec + tomono.tv_nsec + sleep.tv_nsec);
1452 EXPORT_SYMBOL_GPL(get_monotonic_boottime);
1455 * ktime_get_boottime - Returns monotonic time since boot in a ktime
1457 * Returns the monotonic time since boot in a ktime
1459 * This is similar to CLOCK_MONTONIC/ktime_get, but also
1460 * includes the time spent in suspend.
1462 ktime_t ktime_get_boottime(void)
1466 get_monotonic_boottime(&ts);
1467 return timespec_to_ktime(ts);
1469 EXPORT_SYMBOL_GPL(ktime_get_boottime);
1472 * monotonic_to_bootbased - Convert the monotonic time to boot based.
1473 * @ts: pointer to the timespec to be converted
1475 void monotonic_to_bootbased(struct timespec *ts)
1477 struct timekeeper *tk = &timekeeper;
1479 *ts = timespec_add(*ts, tk->total_sleep_time);
1481 EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
1483 unsigned long get_seconds(void)
1485 struct timekeeper *tk = &timekeeper;
1487 return tk->xtime_sec;
1489 EXPORT_SYMBOL(get_seconds);
1491 struct timespec __current_kernel_time(void)
1493 struct timekeeper *tk = &timekeeper;
1495 return tk_xtime(tk);
1498 struct timespec current_kernel_time(void)
1500 struct timekeeper *tk = &timekeeper;
1501 struct timespec now;
1505 seq = read_seqcount_begin(&timekeeper_seq);
1508 } while (read_seqcount_retry(&timekeeper_seq, seq));
1512 EXPORT_SYMBOL(current_kernel_time);
1514 struct timespec get_monotonic_coarse(void)
1516 struct timekeeper *tk = &timekeeper;
1517 struct timespec now, mono;
1521 seq = read_seqcount_begin(&timekeeper_seq);
1524 mono = tk->wall_to_monotonic;
1525 } while (read_seqcount_retry(&timekeeper_seq, seq));
1527 set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
1528 now.tv_nsec + mono.tv_nsec);
1533 * Must hold jiffies_lock
1535 void do_timer(unsigned long ticks)
1537 jiffies_64 += ticks;
1539 calc_global_load(ticks);
1543 * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
1544 * and sleep offsets.
1545 * @xtim: pointer to timespec to be set with xtime
1546 * @wtom: pointer to timespec to be set with wall_to_monotonic
1547 * @sleep: pointer to timespec to be set with time in suspend
1549 void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
1550 struct timespec *wtom, struct timespec *sleep)
1552 struct timekeeper *tk = &timekeeper;
1556 seq = read_seqcount_begin(&timekeeper_seq);
1557 *xtim = tk_xtime(tk);
1558 *wtom = tk->wall_to_monotonic;
1559 *sleep = tk->total_sleep_time;
1560 } while (read_seqcount_retry(&timekeeper_seq, seq));
1563 #ifdef CONFIG_HIGH_RES_TIMERS
1565 * ktime_get_update_offsets - hrtimer helper
1566 * @offs_real: pointer to storage for monotonic -> realtime offset
1567 * @offs_boot: pointer to storage for monotonic -> boottime offset
1569 * Returns current monotonic time and updates the offsets
1570 * Called from hrtimer_interupt() or retrigger_next_event()
1572 ktime_t ktime_get_update_offsets(ktime_t *offs_real, ktime_t *offs_boot,
1575 struct timekeeper *tk = &timekeeper;
1581 seq = read_seqcount_begin(&timekeeper_seq);
1583 secs = tk->xtime_sec;
1584 nsecs = timekeeping_get_ns(tk);
1586 *offs_real = tk->offs_real;
1587 *offs_boot = tk->offs_boot;
1588 *offs_tai = tk->offs_tai;
1589 } while (read_seqcount_retry(&timekeeper_seq, seq));
1591 now = ktime_add_ns(ktime_set(secs, 0), nsecs);
1592 now = ktime_sub(now, *offs_real);
1598 * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
1600 ktime_t ktime_get_monotonic_offset(void)
1602 struct timekeeper *tk = &timekeeper;
1604 struct timespec wtom;
1607 seq = read_seqcount_begin(&timekeeper_seq);
1608 wtom = tk->wall_to_monotonic;
1609 } while (read_seqcount_retry(&timekeeper_seq, seq));
1611 return timespec_to_ktime(wtom);
1613 EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
1616 * xtime_update() - advances the timekeeping infrastructure
1617 * @ticks: number of ticks, that have elapsed since the last call.
1619 * Must be called with interrupts disabled.
1621 void xtime_update(unsigned long ticks)
1623 write_seqlock(&jiffies_lock);
1625 write_sequnlock(&jiffies_lock);