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/module.h>
12 #include <linux/interrupt.h>
13 #include <linux/percpu.h>
14 #include <linux/init.h>
16 #include <linux/sysdev.h>
17 #include <linux/clocksource.h>
18 #include <linux/jiffies.h>
19 #include <linux/time.h>
20 #include <linux/tick.h>
21 #include <linux/stop_machine.h>
23 /* Structure holding internal timekeeping values. */
25 /* Current clocksource used for timekeeping. */
26 struct clocksource *clock;
27 /* The shift value of the current clocksource. */
30 /* Number of clock cycles in one NTP interval. */
31 cycle_t cycle_interval;
32 /* Number of clock shifted nano seconds in one NTP interval. */
34 /* Raw nano seconds accumulated per NTP interval. */
37 /* Clock shifted nano seconds remainder not stored in xtime.tv_nsec. */
39 /* Difference between accumulated time and NTP time in ntp
40 * shifted nano seconds. */
42 /* Shift conversion between clock shifted nano seconds and
43 * ntp shifted nano seconds. */
45 /* NTP adjusted clock multiplier */
49 struct timekeeper timekeeper;
52 * timekeeper_setup_internals - Set up internals to use clocksource clock.
54 * @clock: Pointer to clocksource.
56 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
57 * pair and interval request.
59 * Unless you're the timekeeping code, you should not be using this!
61 static void timekeeper_setup_internals(struct clocksource *clock)
66 timekeeper.clock = clock;
67 clock->cycle_last = clock->read(clock);
69 /* Do the ns -> cycle conversion first, using original mult */
70 tmp = NTP_INTERVAL_LENGTH;
73 do_div(tmp, clock->mult);
77 interval = (cycle_t) tmp;
78 timekeeper.cycle_interval = interval;
80 /* Go back from cycles -> shifted ns */
81 timekeeper.xtime_interval = (u64) interval * clock->mult;
82 timekeeper.raw_interval =
83 ((u64) interval * clock->mult) >> clock->shift;
85 timekeeper.xtime_nsec = 0;
86 timekeeper.shift = clock->shift;
88 timekeeper.ntp_error = 0;
89 timekeeper.ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
92 * The timekeeper keeps its own mult values for the currently
93 * active clocksource. These value will be adjusted via NTP
94 * to counteract clock drifting.
96 timekeeper.mult = clock->mult;
99 /* Timekeeper helper functions. */
100 static inline s64 timekeeping_get_ns(void)
102 cycle_t cycle_now, cycle_delta;
103 struct clocksource *clock;
105 /* read clocksource: */
106 clock = timekeeper.clock;
107 cycle_now = clock->read(clock);
109 /* calculate the delta since the last update_wall_time: */
110 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
112 /* return delta convert to nanoseconds using ntp adjusted mult. */
113 return clocksource_cyc2ns(cycle_delta, timekeeper.mult,
117 static inline s64 timekeeping_get_ns_raw(void)
119 cycle_t cycle_now, cycle_delta;
120 struct clocksource *clock;
122 /* read clocksource: */
123 clock = timekeeper.clock;
124 cycle_now = clock->read(clock);
126 /* calculate the delta since the last update_wall_time: */
127 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
129 /* return delta convert to nanoseconds using ntp adjusted mult. */
130 return clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
134 * This read-write spinlock protects us from races in SMP while
135 * playing with xtime.
137 __cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
142 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
143 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
144 * at zero at system boot time, so wall_to_monotonic will be negative,
145 * however, we will ALWAYS keep the tv_nsec part positive so we can use
146 * the usual normalization.
148 * wall_to_monotonic is moved after resume from suspend for the monotonic
149 * time not to jump. We need to add total_sleep_time to wall_to_monotonic
150 * to get the real boot based time offset.
152 * - wall_to_monotonic is no longer the boot time, getboottime must be
155 struct timespec xtime __attribute__ ((aligned (16)));
156 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
157 static struct timespec total_sleep_time;
160 * The raw monotonic time for the CLOCK_MONOTONIC_RAW posix clock.
162 struct timespec raw_time;
164 /* flag for if timekeeping is suspended */
165 int __read_mostly timekeeping_suspended;
167 /* must hold xtime_lock */
168 void timekeeping_leap_insert(int leapsecond)
170 xtime.tv_sec += leapsecond;
171 wall_to_monotonic.tv_sec -= leapsecond;
172 update_vsyscall(&xtime, timekeeper.clock);
175 #ifdef CONFIG_GENERIC_TIME
178 * timekeeping_forward_now - update clock to the current time
180 * Forward the current clock to update its state since the last call to
181 * update_wall_time(). This is useful before significant clock changes,
182 * as it avoids having to deal with this time offset explicitly.
184 static void timekeeping_forward_now(void)
186 cycle_t cycle_now, cycle_delta;
187 struct clocksource *clock;
190 clock = timekeeper.clock;
191 cycle_now = clock->read(clock);
192 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
193 clock->cycle_last = cycle_now;
195 nsec = clocksource_cyc2ns(cycle_delta, timekeeper.mult,
198 /* If arch requires, add in gettimeoffset() */
199 nsec += arch_gettimeoffset();
201 timespec_add_ns(&xtime, nsec);
203 nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
204 timespec_add_ns(&raw_time, nsec);
208 * getnstimeofday - Returns the time of day in a timespec
209 * @ts: pointer to the timespec to be set
211 * Returns the time of day in a timespec.
213 void getnstimeofday(struct timespec *ts)
218 WARN_ON(timekeeping_suspended);
221 seq = read_seqbegin(&xtime_lock);
224 nsecs = timekeeping_get_ns();
226 /* If arch requires, add in gettimeoffset() */
227 nsecs += arch_gettimeoffset();
229 } while (read_seqretry(&xtime_lock, seq));
231 timespec_add_ns(ts, nsecs);
234 EXPORT_SYMBOL(getnstimeofday);
236 ktime_t ktime_get(void)
241 WARN_ON(timekeeping_suspended);
244 seq = read_seqbegin(&xtime_lock);
245 secs = xtime.tv_sec + wall_to_monotonic.tv_sec;
246 nsecs = xtime.tv_nsec + wall_to_monotonic.tv_nsec;
247 nsecs += timekeeping_get_ns();
249 } while (read_seqretry(&xtime_lock, seq));
251 * Use ktime_set/ktime_add_ns to create a proper ktime on
252 * 32-bit architectures without CONFIG_KTIME_SCALAR.
254 return ktime_add_ns(ktime_set(secs, 0), nsecs);
256 EXPORT_SYMBOL_GPL(ktime_get);
259 * ktime_get_ts - get the monotonic clock in timespec format
260 * @ts: pointer to timespec variable
262 * The function calculates the monotonic clock from the realtime
263 * clock and the wall_to_monotonic offset and stores the result
264 * in normalized timespec format in the variable pointed to by @ts.
266 void ktime_get_ts(struct timespec *ts)
268 struct timespec tomono;
272 WARN_ON(timekeeping_suspended);
275 seq = read_seqbegin(&xtime_lock);
277 tomono = wall_to_monotonic;
278 nsecs = timekeeping_get_ns();
280 } while (read_seqretry(&xtime_lock, seq));
282 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
283 ts->tv_nsec + tomono.tv_nsec + nsecs);
285 EXPORT_SYMBOL_GPL(ktime_get_ts);
288 * do_gettimeofday - Returns the time of day in a timeval
289 * @tv: pointer to the timeval to be set
291 * NOTE: Users should be converted to using getnstimeofday()
293 void do_gettimeofday(struct timeval *tv)
297 getnstimeofday(&now);
298 tv->tv_sec = now.tv_sec;
299 tv->tv_usec = now.tv_nsec/1000;
302 EXPORT_SYMBOL(do_gettimeofday);
304 * do_settimeofday - Sets the time of day
305 * @tv: pointer to the timespec variable containing the new time
307 * Sets the time of day to the new time and update NTP and notify hrtimers
309 int do_settimeofday(struct timespec *tv)
311 struct timespec ts_delta;
314 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
317 write_seqlock_irqsave(&xtime_lock, flags);
319 timekeeping_forward_now();
321 ts_delta.tv_sec = tv->tv_sec - xtime.tv_sec;
322 ts_delta.tv_nsec = tv->tv_nsec - xtime.tv_nsec;
323 wall_to_monotonic = timespec_sub(wall_to_monotonic, ts_delta);
327 timekeeper.ntp_error = 0;
330 update_vsyscall(&xtime, timekeeper.clock);
332 write_sequnlock_irqrestore(&xtime_lock, flags);
334 /* signal hrtimers about time change */
340 EXPORT_SYMBOL(do_settimeofday);
343 * change_clocksource - Swaps clocksources if a new one is available
345 * Accumulates current time interval and initializes new clocksource
347 static int change_clocksource(void *data)
349 struct clocksource *new, *old;
351 new = (struct clocksource *) data;
353 timekeeping_forward_now();
354 if (!new->enable || new->enable(new) == 0) {
355 old = timekeeper.clock;
356 timekeeper_setup_internals(new);
364 * timekeeping_notify - Install a new clock source
365 * @clock: pointer to the clock source
367 * This function is called from clocksource.c after a new, better clock
368 * source has been registered. The caller holds the clocksource_mutex.
370 void timekeeping_notify(struct clocksource *clock)
372 if (timekeeper.clock == clock)
374 stop_machine(change_clocksource, clock, NULL);
378 #else /* GENERIC_TIME */
380 static inline void timekeeping_forward_now(void) { }
383 * ktime_get - get the monotonic time in ktime_t format
385 * returns the time in ktime_t format
387 ktime_t ktime_get(void)
393 return timespec_to_ktime(now);
395 EXPORT_SYMBOL_GPL(ktime_get);
398 * ktime_get_ts - get the monotonic clock in timespec format
399 * @ts: pointer to timespec variable
401 * The function calculates the monotonic clock from the realtime
402 * clock and the wall_to_monotonic offset and stores the result
403 * in normalized timespec format in the variable pointed to by @ts.
405 void ktime_get_ts(struct timespec *ts)
407 struct timespec tomono;
411 seq = read_seqbegin(&xtime_lock);
413 tomono = wall_to_monotonic;
415 } while (read_seqretry(&xtime_lock, seq));
417 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
418 ts->tv_nsec + tomono.tv_nsec);
420 EXPORT_SYMBOL_GPL(ktime_get_ts);
422 #endif /* !GENERIC_TIME */
425 * ktime_get_real - get the real (wall-) time in ktime_t format
427 * returns the time in ktime_t format
429 ktime_t ktime_get_real(void)
433 getnstimeofday(&now);
435 return timespec_to_ktime(now);
437 EXPORT_SYMBOL_GPL(ktime_get_real);
440 * getrawmonotonic - Returns the raw monotonic time in a timespec
441 * @ts: pointer to the timespec to be set
443 * Returns the raw monotonic time (completely un-modified by ntp)
445 void getrawmonotonic(struct timespec *ts)
451 seq = read_seqbegin(&xtime_lock);
452 nsecs = timekeeping_get_ns_raw();
455 } while (read_seqretry(&xtime_lock, seq));
457 timespec_add_ns(ts, nsecs);
459 EXPORT_SYMBOL(getrawmonotonic);
463 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
465 int timekeeping_valid_for_hres(void)
471 seq = read_seqbegin(&xtime_lock);
473 ret = timekeeper.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
475 } while (read_seqretry(&xtime_lock, seq));
481 * read_persistent_clock - Return time from the persistent clock.
483 * Weak dummy function for arches that do not yet support it.
484 * Reads the time from the battery backed persistent clock.
485 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
487 * XXX - Do be sure to remove it once all arches implement it.
489 void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
496 * read_boot_clock - Return time of the system start.
498 * Weak dummy function for arches that do not yet support it.
499 * Function to read the exact time the system has been started.
500 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
502 * XXX - Do be sure to remove it once all arches implement it.
504 void __attribute__((weak)) read_boot_clock(struct timespec *ts)
511 * timekeeping_init - Initializes the clocksource and common timekeeping values
513 void __init timekeeping_init(void)
515 struct clocksource *clock;
517 struct timespec now, boot;
519 read_persistent_clock(&now);
520 read_boot_clock(&boot);
522 write_seqlock_irqsave(&xtime_lock, flags);
526 clock = clocksource_default_clock();
528 clock->enable(clock);
529 timekeeper_setup_internals(clock);
531 xtime.tv_sec = now.tv_sec;
532 xtime.tv_nsec = now.tv_nsec;
534 raw_time.tv_nsec = 0;
535 if (boot.tv_sec == 0 && boot.tv_nsec == 0) {
536 boot.tv_sec = xtime.tv_sec;
537 boot.tv_nsec = xtime.tv_nsec;
539 set_normalized_timespec(&wall_to_monotonic,
540 -boot.tv_sec, -boot.tv_nsec);
541 total_sleep_time.tv_sec = 0;
542 total_sleep_time.tv_nsec = 0;
543 write_sequnlock_irqrestore(&xtime_lock, flags);
546 /* time in seconds when suspend began */
547 static struct timespec timekeeping_suspend_time;
550 * timekeeping_resume - Resumes the generic timekeeping subsystem.
553 * This is for the generic clocksource timekeeping.
554 * xtime/wall_to_monotonic/jiffies/etc are
555 * still managed by arch specific suspend/resume code.
557 static int timekeeping_resume(struct sys_device *dev)
562 read_persistent_clock(&ts);
564 clocksource_resume();
566 write_seqlock_irqsave(&xtime_lock, flags);
568 if (timespec_compare(&ts, &timekeeping_suspend_time) > 0) {
569 ts = timespec_sub(ts, timekeeping_suspend_time);
570 xtime = timespec_add_safe(xtime, ts);
571 wall_to_monotonic = timespec_sub(wall_to_monotonic, ts);
572 total_sleep_time = timespec_add_safe(total_sleep_time, ts);
574 /* re-base the last cycle value */
575 timekeeper.clock->cycle_last = timekeeper.clock->read(timekeeper.clock);
576 timekeeper.ntp_error = 0;
577 timekeeping_suspended = 0;
578 write_sequnlock_irqrestore(&xtime_lock, flags);
580 touch_softlockup_watchdog();
582 clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
584 /* Resume hrtimers */
585 hres_timers_resume();
590 static int timekeeping_suspend(struct sys_device *dev, pm_message_t state)
594 read_persistent_clock(&timekeeping_suspend_time);
596 write_seqlock_irqsave(&xtime_lock, flags);
597 timekeeping_forward_now();
598 timekeeping_suspended = 1;
599 write_sequnlock_irqrestore(&xtime_lock, flags);
601 clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
606 /* sysfs resume/suspend bits for timekeeping */
607 static struct sysdev_class timekeeping_sysclass = {
608 .name = "timekeeping",
609 .resume = timekeeping_resume,
610 .suspend = timekeeping_suspend,
613 static struct sys_device device_timer = {
615 .cls = &timekeeping_sysclass,
618 static int __init timekeeping_init_device(void)
620 int error = sysdev_class_register(&timekeeping_sysclass);
622 error = sysdev_register(&device_timer);
626 device_initcall(timekeeping_init_device);
629 * If the error is already larger, we look ahead even further
630 * to compensate for late or lost adjustments.
632 static __always_inline int timekeeping_bigadjust(s64 error, s64 *interval,
640 * Use the current error value to determine how much to look ahead.
641 * The larger the error the slower we adjust for it to avoid problems
642 * with losing too many ticks, otherwise we would overadjust and
643 * produce an even larger error. The smaller the adjustment the
644 * faster we try to adjust for it, as lost ticks can do less harm
645 * here. This is tuned so that an error of about 1 msec is adjusted
646 * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
648 error2 = timekeeper.ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
649 error2 = abs(error2);
650 for (look_ahead = 0; error2 > 0; look_ahead++)
654 * Now calculate the error in (1 << look_ahead) ticks, but first
655 * remove the single look ahead already included in the error.
657 tick_error = tick_length >> (timekeeper.ntp_error_shift + 1);
658 tick_error -= timekeeper.xtime_interval >> 1;
659 error = ((error - tick_error) >> look_ahead) + tick_error;
661 /* Finally calculate the adjustment shift value. */
666 *interval = -*interval;
670 for (adj = 0; error > i; adj++)
679 * Adjust the multiplier to reduce the error value,
680 * this is optimized for the most common adjustments of -1,0,1,
681 * for other values we can do a bit more work.
683 static void timekeeping_adjust(s64 offset)
685 s64 error, interval = timekeeper.cycle_interval;
688 error = timekeeper.ntp_error >> (timekeeper.ntp_error_shift - 1);
689 if (error > interval) {
691 if (likely(error <= interval))
694 adj = timekeeping_bigadjust(error, &interval, &offset);
695 } else if (error < -interval) {
697 if (likely(error >= -interval)) {
699 interval = -interval;
702 adj = timekeeping_bigadjust(error, &interval, &offset);
706 timekeeper.mult += adj;
707 timekeeper.xtime_interval += interval;
708 timekeeper.xtime_nsec -= offset;
709 timekeeper.ntp_error -= (interval - offset) <<
710 timekeeper.ntp_error_shift;
714 * logarithmic_accumulation - shifted accumulation of cycles
716 * This functions accumulates a shifted interval of cycles into
717 * into a shifted interval nanoseconds. Allows for O(log) accumulation
720 * Returns the unconsumed cycles.
722 static cycle_t logarithmic_accumulation(cycle_t offset, int shift)
724 u64 nsecps = (u64)NSEC_PER_SEC << timekeeper.shift;
726 /* If the offset is smaller then a shifted interval, do nothing */
727 if (offset < timekeeper.cycle_interval<<shift)
730 /* Accumulate one shifted interval */
731 offset -= timekeeper.cycle_interval << shift;
732 timekeeper.clock->cycle_last += timekeeper.cycle_interval << shift;
734 timekeeper.xtime_nsec += timekeeper.xtime_interval << shift;
735 while (timekeeper.xtime_nsec >= nsecps) {
736 timekeeper.xtime_nsec -= nsecps;
741 /* Accumulate into raw time */
742 raw_time.tv_nsec += timekeeper.raw_interval << shift;;
743 while (raw_time.tv_nsec >= NSEC_PER_SEC) {
744 raw_time.tv_nsec -= NSEC_PER_SEC;
748 /* Accumulate error between NTP and clock interval */
749 timekeeper.ntp_error += tick_length << shift;
750 timekeeper.ntp_error -= timekeeper.xtime_interval <<
751 (timekeeper.ntp_error_shift + shift);
757 * update_wall_time - Uses the current clocksource to increment the wall time
759 * Called from the timer interrupt, must hold a write on xtime_lock.
761 void update_wall_time(void)
763 struct clocksource *clock;
765 int shift = 0, maxshift;
767 /* Make sure we're fully resumed: */
768 if (unlikely(timekeeping_suspended))
771 clock = timekeeper.clock;
772 #ifdef CONFIG_GENERIC_TIME
773 offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
775 offset = timekeeper.cycle_interval;
777 timekeeper.xtime_nsec = (s64)xtime.tv_nsec << timekeeper.shift;
780 * With NO_HZ we may have to accumulate many cycle_intervals
781 * (think "ticks") worth of time at once. To do this efficiently,
782 * we calculate the largest doubling multiple of cycle_intervals
783 * that is smaller then the offset. We then accumulate that
784 * chunk in one go, and then try to consume the next smaller
787 shift = ilog2(offset) - ilog2(timekeeper.cycle_interval);
788 shift = max(0, shift);
789 /* Bound shift to one less then what overflows tick_length */
790 maxshift = (8*sizeof(tick_length) - (ilog2(tick_length)+1)) - 1;
791 shift = min(shift, maxshift);
792 while (offset >= timekeeper.cycle_interval) {
793 offset = logarithmic_accumulation(offset, shift);
797 /* correct the clock when NTP error is too big */
798 timekeeping_adjust(offset);
801 * Since in the loop above, we accumulate any amount of time
802 * in xtime_nsec over a second into xtime.tv_sec, its possible for
803 * xtime_nsec to be fairly small after the loop. Further, if we're
804 * slightly speeding the clocksource up in timekeeping_adjust(),
805 * its possible the required corrective factor to xtime_nsec could
806 * cause it to underflow.
808 * Now, we cannot simply roll the accumulated second back, since
809 * the NTP subsystem has been notified via second_overflow. So
810 * instead we push xtime_nsec forward by the amount we underflowed,
811 * and add that amount into the error.
813 * We'll correct this error next time through this function, when
814 * xtime_nsec is not as small.
816 if (unlikely((s64)timekeeper.xtime_nsec < 0)) {
817 s64 neg = -(s64)timekeeper.xtime_nsec;
818 timekeeper.xtime_nsec = 0;
819 timekeeper.ntp_error += neg << timekeeper.ntp_error_shift;
822 /* store full nanoseconds into xtime after rounding it up and
823 * add the remainder to the error difference.
825 xtime.tv_nsec = ((s64) timekeeper.xtime_nsec >> timekeeper.shift) + 1;
826 timekeeper.xtime_nsec -= (s64) xtime.tv_nsec << timekeeper.shift;
827 timekeeper.ntp_error += timekeeper.xtime_nsec <<
828 timekeeper.ntp_error_shift;
830 /* check to see if there is a new clocksource to use */
831 update_vsyscall(&xtime, timekeeper.clock);
835 * getboottime - Return the real time of system boot.
836 * @ts: pointer to the timespec to be set
838 * Returns the time of day in a timespec.
840 * This is based on the wall_to_monotonic offset and the total suspend
841 * time. Calls to settimeofday will affect the value returned (which
842 * basically means that however wrong your real time clock is at boot time,
843 * you get the right time here).
845 void getboottime(struct timespec *ts)
847 struct timespec boottime = {
848 .tv_sec = wall_to_monotonic.tv_sec + total_sleep_time.tv_sec,
849 .tv_nsec = wall_to_monotonic.tv_nsec + total_sleep_time.tv_nsec
852 set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
856 * monotonic_to_bootbased - Convert the monotonic time to boot based.
857 * @ts: pointer to the timespec to be converted
859 void monotonic_to_bootbased(struct timespec *ts)
861 *ts = timespec_add_safe(*ts, total_sleep_time);
864 unsigned long get_seconds(void)
868 EXPORT_SYMBOL(get_seconds);
870 struct timespec __current_kernel_time(void)
875 struct timespec current_kernel_time(void)
881 seq = read_seqbegin(&xtime_lock);
883 } while (read_seqretry(&xtime_lock, seq));
887 EXPORT_SYMBOL(current_kernel_time);
889 struct timespec get_monotonic_coarse(void)
891 struct timespec now, mono;
895 seq = read_seqbegin(&xtime_lock);
897 mono = wall_to_monotonic;
898 } while (read_seqretry(&xtime_lock, seq));
900 set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
901 now.tv_nsec + mono.tv_nsec);