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>
22 /* Structure holding internal timekeeping values. */
24 /* Current clocksource used for timekeeping. */
25 struct clocksource *clock;
26 /* The shift value of the current clocksource. */
29 /* Number of clock cycles in one NTP interval. */
30 cycle_t cycle_interval;
31 /* Number of clock shifted nano seconds in one NTP interval. */
33 /* Raw nano seconds accumulated per NTP interval. */
36 /* Clock shifted nano seconds remainder not stored in xtime.tv_nsec. */
38 /* Difference between accumulated time and NTP time in ntp
39 * shifted nano seconds. */
41 /* Shift conversion between clock shifted nano seconds and
42 * ntp shifted nano seconds. */
46 struct timekeeper timekeeper;
49 * timekeeper_setup_internals - Set up internals to use clocksource clock.
51 * @clock: Pointer to clocksource.
53 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
54 * pair and interval request.
56 * Unless you're the timekeeping code, you should not be using this!
58 static void timekeeper_setup_internals(struct clocksource *clock)
63 timekeeper.clock = clock;
64 clock->cycle_last = clock->read(clock);
66 /* Do the ns -> cycle conversion first, using original mult */
67 tmp = NTP_INTERVAL_LENGTH;
69 tmp += clock->mult_orig/2;
70 do_div(tmp, clock->mult_orig);
74 interval = (cycle_t) tmp;
75 timekeeper.cycle_interval = interval;
77 /* Go back from cycles -> shifted ns */
78 timekeeper.xtime_interval = (u64) interval * clock->mult;
79 timekeeper.raw_interval =
80 ((u64) interval * clock->mult_orig) >> clock->shift;
82 timekeeper.xtime_nsec = 0;
83 timekeeper.shift = clock->shift;
85 timekeeper.ntp_error = 0;
86 timekeeper.ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
90 * This read-write spinlock protects us from races in SMP while
93 __cacheline_aligned_in_smp DEFINE_SEQLOCK(xtime_lock);
98 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
99 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
100 * at zero at system boot time, so wall_to_monotonic will be negative,
101 * however, we will ALWAYS keep the tv_nsec part positive so we can use
102 * the usual normalization.
104 * wall_to_monotonic is moved after resume from suspend for the monotonic
105 * time not to jump. We need to add total_sleep_time to wall_to_monotonic
106 * to get the real boot based time offset.
108 * - wall_to_monotonic is no longer the boot time, getboottime must be
111 struct timespec xtime __attribute__ ((aligned (16)));
112 struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
113 static unsigned long total_sleep_time; /* seconds */
116 * The raw monotonic time for the CLOCK_MONOTONIC_RAW posix clock.
118 struct timespec raw_time;
120 /* flag for if timekeeping is suspended */
121 int __read_mostly timekeeping_suspended;
123 static struct timespec xtime_cache __attribute__ ((aligned (16)));
124 void update_xtime_cache(u64 nsec)
127 timespec_add_ns(&xtime_cache, nsec);
130 /* must hold xtime_lock */
131 void timekeeping_leap_insert(int leapsecond)
133 xtime.tv_sec += leapsecond;
134 wall_to_monotonic.tv_sec -= leapsecond;
135 update_vsyscall(&xtime, timekeeper.clock);
138 #ifdef CONFIG_GENERIC_TIME
140 * timekeeping_forward_now - update clock to the current time
142 * Forward the current clock to update its state since the last call to
143 * update_wall_time(). This is useful before significant clock changes,
144 * as it avoids having to deal with this time offset explicitly.
146 static void timekeeping_forward_now(void)
148 cycle_t cycle_now, cycle_delta;
149 struct clocksource *clock;
152 clock = timekeeper.clock;
153 cycle_now = clock->read(clock);
154 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
155 clock->cycle_last = cycle_now;
157 nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
159 /* If arch requires, add in gettimeoffset() */
160 nsec += arch_gettimeoffset();
162 timespec_add_ns(&xtime, nsec);
164 nsec = clocksource_cyc2ns(cycle_delta, clock->mult_orig, clock->shift);
165 timespec_add_ns(&raw_time, nsec);
169 * getnstimeofday - Returns the time of day in a timespec
170 * @ts: pointer to the timespec to be set
172 * Returns the time of day in a timespec.
174 void getnstimeofday(struct timespec *ts)
176 cycle_t cycle_now, cycle_delta;
177 struct clocksource *clock;
181 WARN_ON(timekeeping_suspended);
184 seq = read_seqbegin(&xtime_lock);
188 /* read clocksource: */
189 clock = timekeeper.clock;
190 cycle_now = clock->read(clock);
192 /* calculate the delta since the last update_wall_time: */
193 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
195 /* convert to nanoseconds: */
196 nsecs = clocksource_cyc2ns(cycle_delta, clock->mult,
199 /* If arch requires, add in gettimeoffset() */
200 nsecs += arch_gettimeoffset();
202 } while (read_seqretry(&xtime_lock, seq));
204 timespec_add_ns(ts, nsecs);
207 EXPORT_SYMBOL(getnstimeofday);
209 ktime_t ktime_get(void)
211 cycle_t cycle_now, cycle_delta;
212 struct clocksource *clock;
216 WARN_ON(timekeeping_suspended);
219 seq = read_seqbegin(&xtime_lock);
220 secs = xtime.tv_sec + wall_to_monotonic.tv_sec;
221 nsecs = xtime.tv_nsec + wall_to_monotonic.tv_nsec;
223 /* read clocksource: */
224 clock = timekeeper.clock;
225 cycle_now = clock->read(clock);
227 /* calculate the delta since the last update_wall_time: */
228 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
230 /* convert to nanoseconds: */
231 nsecs += clocksource_cyc2ns(cycle_delta, clock->mult,
234 } while (read_seqretry(&xtime_lock, seq));
236 * Use ktime_set/ktime_add_ns to create a proper ktime on
237 * 32-bit architectures without CONFIG_KTIME_SCALAR.
239 return ktime_add_ns(ktime_set(secs, 0), nsecs);
241 EXPORT_SYMBOL_GPL(ktime_get);
244 * ktime_get_ts - get the monotonic clock in timespec format
245 * @ts: pointer to timespec variable
247 * The function calculates the monotonic clock from the realtime
248 * clock and the wall_to_monotonic offset and stores the result
249 * in normalized timespec format in the variable pointed to by @ts.
251 void ktime_get_ts(struct timespec *ts)
253 cycle_t cycle_now, cycle_delta;
254 struct clocksource *clock;
255 struct timespec tomono;
259 WARN_ON(timekeeping_suspended);
262 seq = read_seqbegin(&xtime_lock);
264 tomono = wall_to_monotonic;
266 /* read clocksource: */
267 clock = timekeeper.clock;
268 cycle_now = clock->read(clock);
270 /* calculate the delta since the last update_wall_time: */
271 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
273 /* convert to nanoseconds: */
274 nsecs = clocksource_cyc2ns(cycle_delta, clock->mult,
277 } while (read_seqretry(&xtime_lock, seq));
279 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
280 ts->tv_nsec + tomono.tv_nsec + nsecs);
282 EXPORT_SYMBOL_GPL(ktime_get_ts);
285 * do_gettimeofday - Returns the time of day in a timeval
286 * @tv: pointer to the timeval to be set
288 * NOTE: Users should be converted to using getnstimeofday()
290 void do_gettimeofday(struct timeval *tv)
294 getnstimeofday(&now);
295 tv->tv_sec = now.tv_sec;
296 tv->tv_usec = now.tv_nsec/1000;
299 EXPORT_SYMBOL(do_gettimeofday);
301 * do_settimeofday - Sets the time of day
302 * @tv: pointer to the timespec variable containing the new time
304 * Sets the time of day to the new time and update NTP and notify hrtimers
306 int do_settimeofday(struct timespec *tv)
308 struct timespec ts_delta;
311 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
314 write_seqlock_irqsave(&xtime_lock, flags);
316 timekeeping_forward_now();
318 ts_delta.tv_sec = tv->tv_sec - xtime.tv_sec;
319 ts_delta.tv_nsec = tv->tv_nsec - xtime.tv_nsec;
320 wall_to_monotonic = timespec_sub(wall_to_monotonic, ts_delta);
324 update_xtime_cache(0);
326 timekeeper.ntp_error = 0;
329 update_vsyscall(&xtime, timekeeper.clock);
331 write_sequnlock_irqrestore(&xtime_lock, flags);
333 /* signal hrtimers about time change */
339 EXPORT_SYMBOL(do_settimeofday);
342 * change_clocksource - Swaps clocksources if a new one is available
344 * Accumulates current time interval and initializes new clocksource
346 static void change_clocksource(void)
348 struct clocksource *new, *old;
350 new = clocksource_get_next();
352 if (!new || timekeeper.clock == new)
355 timekeeping_forward_now();
357 if (new->enable && !new->enable(new))
360 * The frequency may have changed while the clocksource
361 * was disabled. If so the code in ->enable() must update
362 * the mult value to reflect the new frequency. Make sure
363 * mult_orig follows this change.
365 new->mult_orig = new->mult;
367 old = timekeeper.clock;
368 timekeeper_setup_internals(new);
371 * Save mult_orig in mult so that the value can be restored
372 * regardless if ->enable() updates the value of mult or not.
374 old->mult = old->mult_orig;
380 #else /* GENERIC_TIME */
381 static inline void timekeeping_forward_now(void) { }
382 static inline void change_clocksource(void) { }
385 * ktime_get - get the monotonic time in ktime_t format
387 * returns the time in ktime_t format
389 ktime_t ktime_get(void)
395 return timespec_to_ktime(now);
397 EXPORT_SYMBOL_GPL(ktime_get);
400 * ktime_get_ts - get the monotonic clock in timespec format
401 * @ts: pointer to timespec variable
403 * The function calculates the monotonic clock from the realtime
404 * clock and the wall_to_monotonic offset and stores the result
405 * in normalized timespec format in the variable pointed to by @ts.
407 void ktime_get_ts(struct timespec *ts)
409 struct timespec tomono;
413 seq = read_seqbegin(&xtime_lock);
415 tomono = wall_to_monotonic;
417 } while (read_seqretry(&xtime_lock, seq));
419 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
420 ts->tv_nsec + tomono.tv_nsec);
422 EXPORT_SYMBOL_GPL(ktime_get_ts);
423 #endif /* !GENERIC_TIME */
426 * ktime_get_real - get the real (wall-) time in ktime_t format
428 * returns the time in ktime_t format
430 ktime_t ktime_get_real(void)
434 getnstimeofday(&now);
436 return timespec_to_ktime(now);
438 EXPORT_SYMBOL_GPL(ktime_get_real);
441 * getrawmonotonic - Returns the raw monotonic time in a timespec
442 * @ts: pointer to the timespec to be set
444 * Returns the raw monotonic time (completely un-modified by ntp)
446 void getrawmonotonic(struct timespec *ts)
450 cycle_t cycle_now, cycle_delta;
451 struct clocksource *clock;
454 seq = read_seqbegin(&xtime_lock);
456 /* read clocksource: */
457 clock = timekeeper.clock;
458 cycle_now = clock->read(clock);
460 /* calculate the delta since the last update_wall_time: */
461 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
463 /* convert to nanoseconds: */
464 nsecs = clocksource_cyc2ns(cycle_delta, clock->mult_orig,
469 } while (read_seqretry(&xtime_lock, seq));
471 timespec_add_ns(ts, nsecs);
473 EXPORT_SYMBOL(getrawmonotonic);
477 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
479 int timekeeping_valid_for_hres(void)
485 seq = read_seqbegin(&xtime_lock);
487 ret = timekeeper.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
489 } while (read_seqretry(&xtime_lock, seq));
495 * read_persistent_clock - Return time in seconds from the persistent clock.
497 * Weak dummy function for arches that do not yet support it.
498 * Returns seconds from epoch using the battery backed persistent clock.
499 * Returns zero if unsupported.
501 * XXX - Do be sure to remove it once all arches implement it.
503 unsigned long __attribute__((weak)) read_persistent_clock(void)
509 * timekeeping_init - Initializes the clocksource and common timekeeping values
511 void __init timekeeping_init(void)
513 struct clocksource *clock;
515 unsigned long sec = read_persistent_clock();
517 write_seqlock_irqsave(&xtime_lock, flags);
521 clock = clocksource_default_clock();
523 clock->enable(clock);
524 /* set mult_orig on enable */
525 clock->mult_orig = clock->mult;
527 timekeeper_setup_internals(clock);
532 raw_time.tv_nsec = 0;
533 set_normalized_timespec(&wall_to_monotonic,
534 -xtime.tv_sec, -xtime.tv_nsec);
535 update_xtime_cache(0);
536 total_sleep_time = 0;
537 write_sequnlock_irqrestore(&xtime_lock, flags);
540 /* time in seconds when suspend began */
541 static unsigned long timekeeping_suspend_time;
544 * timekeeping_resume - Resumes the generic timekeeping subsystem.
547 * This is for the generic clocksource timekeeping.
548 * xtime/wall_to_monotonic/jiffies/etc are
549 * still managed by arch specific suspend/resume code.
551 static int timekeeping_resume(struct sys_device *dev)
554 unsigned long now = read_persistent_clock();
556 clocksource_resume();
558 write_seqlock_irqsave(&xtime_lock, flags);
560 if (now && (now > timekeeping_suspend_time)) {
561 unsigned long sleep_length = now - timekeeping_suspend_time;
563 xtime.tv_sec += sleep_length;
564 wall_to_monotonic.tv_sec -= sleep_length;
565 total_sleep_time += sleep_length;
567 update_xtime_cache(0);
568 /* re-base the last cycle value */
569 timekeeper.clock->cycle_last = timekeeper.clock->read(timekeeper.clock);
570 timekeeper.ntp_error = 0;
571 timekeeping_suspended = 0;
572 write_sequnlock_irqrestore(&xtime_lock, flags);
574 touch_softlockup_watchdog();
576 clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
578 /* Resume hrtimers */
579 hres_timers_resume();
584 static int timekeeping_suspend(struct sys_device *dev, pm_message_t state)
588 timekeeping_suspend_time = read_persistent_clock();
590 write_seqlock_irqsave(&xtime_lock, flags);
591 timekeeping_forward_now();
592 timekeeping_suspended = 1;
593 write_sequnlock_irqrestore(&xtime_lock, flags);
595 clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
600 /* sysfs resume/suspend bits for timekeeping */
601 static struct sysdev_class timekeeping_sysclass = {
602 .name = "timekeeping",
603 .resume = timekeeping_resume,
604 .suspend = timekeeping_suspend,
607 static struct sys_device device_timer = {
609 .cls = &timekeeping_sysclass,
612 static int __init timekeeping_init_device(void)
614 int error = sysdev_class_register(&timekeeping_sysclass);
616 error = sysdev_register(&device_timer);
620 device_initcall(timekeeping_init_device);
623 * If the error is already larger, we look ahead even further
624 * to compensate for late or lost adjustments.
626 static __always_inline int timekeeping_bigadjust(s64 error, s64 *interval,
634 * Use the current error value to determine how much to look ahead.
635 * The larger the error the slower we adjust for it to avoid problems
636 * with losing too many ticks, otherwise we would overadjust and
637 * produce an even larger error. The smaller the adjustment the
638 * faster we try to adjust for it, as lost ticks can do less harm
639 * here. This is tuned so that an error of about 1 msec is adjusted
640 * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
642 error2 = timekeeper.ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
643 error2 = abs(error2);
644 for (look_ahead = 0; error2 > 0; look_ahead++)
648 * Now calculate the error in (1 << look_ahead) ticks, but first
649 * remove the single look ahead already included in the error.
651 tick_error = tick_length >> (timekeeper.ntp_error_shift + 1);
652 tick_error -= timekeeper.xtime_interval >> 1;
653 error = ((error - tick_error) >> look_ahead) + tick_error;
655 /* Finally calculate the adjustment shift value. */
660 *interval = -*interval;
664 for (adj = 0; error > i; adj++)
673 * Adjust the multiplier to reduce the error value,
674 * this is optimized for the most common adjustments of -1,0,1,
675 * for other values we can do a bit more work.
677 static void timekeeping_adjust(s64 offset)
679 s64 error, interval = timekeeper.cycle_interval;
682 error = timekeeper.ntp_error >> (timekeeper.ntp_error_shift - 1);
683 if (error > interval) {
685 if (likely(error <= interval))
688 adj = timekeeping_bigadjust(error, &interval, &offset);
689 } else if (error < -interval) {
691 if (likely(error >= -interval)) {
693 interval = -interval;
696 adj = timekeeping_bigadjust(error, &interval, &offset);
700 timekeeper.clock->mult += adj;
701 timekeeper.xtime_interval += interval;
702 timekeeper.xtime_nsec -= offset;
703 timekeeper.ntp_error -= (interval - offset) <<
704 timekeeper.ntp_error_shift;
708 * update_wall_time - Uses the current clocksource to increment the wall time
710 * Called from the timer interrupt, must hold a write on xtime_lock.
712 void update_wall_time(void)
714 struct clocksource *clock;
718 /* Make sure we're fully resumed: */
719 if (unlikely(timekeeping_suspended))
722 clock = timekeeper.clock;
723 #ifdef CONFIG_GENERIC_TIME
724 offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
726 offset = timekeeper.cycle_interval;
728 timekeeper.xtime_nsec = (s64)xtime.tv_nsec << timekeeper.shift;
730 /* normally this loop will run just once, however in the
731 * case of lost or late ticks, it will accumulate correctly.
733 while (offset >= timekeeper.cycle_interval) {
734 u64 nsecps = (u64)NSEC_PER_SEC << timekeeper.shift;
736 /* accumulate one interval */
737 offset -= timekeeper.cycle_interval;
738 clock->cycle_last += timekeeper.cycle_interval;
740 timekeeper.xtime_nsec += timekeeper.xtime_interval;
741 if (timekeeper.xtime_nsec >= nsecps) {
742 timekeeper.xtime_nsec -= nsecps;
747 raw_time.tv_nsec += timekeeper.raw_interval;
748 if (raw_time.tv_nsec >= NSEC_PER_SEC) {
749 raw_time.tv_nsec -= NSEC_PER_SEC;
753 /* accumulate error between NTP and clock interval */
754 timekeeper.ntp_error += tick_length;
755 timekeeper.ntp_error -= timekeeper.xtime_interval <<
756 timekeeper.ntp_error_shift;
759 /* correct the clock when NTP error is too big */
760 timekeeping_adjust(offset);
763 * Since in the loop above, we accumulate any amount of time
764 * in xtime_nsec over a second into xtime.tv_sec, its possible for
765 * xtime_nsec to be fairly small after the loop. Further, if we're
766 * slightly speeding the clocksource up in timekeeping_adjust(),
767 * its possible the required corrective factor to xtime_nsec could
768 * cause it to underflow.
770 * Now, we cannot simply roll the accumulated second back, since
771 * the NTP subsystem has been notified via second_overflow. So
772 * instead we push xtime_nsec forward by the amount we underflowed,
773 * and add that amount into the error.
775 * We'll correct this error next time through this function, when
776 * xtime_nsec is not as small.
778 if (unlikely((s64)timekeeper.xtime_nsec < 0)) {
779 s64 neg = -(s64)timekeeper.xtime_nsec;
780 timekeeper.xtime_nsec = 0;
781 timekeeper.ntp_error += neg << timekeeper.ntp_error_shift;
784 /* store full nanoseconds into xtime after rounding it up and
785 * add the remainder to the error difference.
787 xtime.tv_nsec = ((s64) timekeeper.xtime_nsec >> timekeeper.shift) + 1;
788 timekeeper.xtime_nsec -= (s64) xtime.tv_nsec << timekeeper.shift;
789 timekeeper.ntp_error += timekeeper.xtime_nsec <<
790 timekeeper.ntp_error_shift;
792 nsecs = clocksource_cyc2ns(offset, clock->mult, clock->shift);
793 update_xtime_cache(nsecs);
795 /* check to see if there is a new clocksource to use */
796 change_clocksource();
797 update_vsyscall(&xtime, timekeeper.clock);
801 * getboottime - Return the real time of system boot.
802 * @ts: pointer to the timespec to be set
804 * Returns the time of day in a timespec.
806 * This is based on the wall_to_monotonic offset and the total suspend
807 * time. Calls to settimeofday will affect the value returned (which
808 * basically means that however wrong your real time clock is at boot time,
809 * you get the right time here).
811 void getboottime(struct timespec *ts)
813 set_normalized_timespec(ts,
814 - (wall_to_monotonic.tv_sec + total_sleep_time),
815 - wall_to_monotonic.tv_nsec);
819 * monotonic_to_bootbased - Convert the monotonic time to boot based.
820 * @ts: pointer to the timespec to be converted
822 void monotonic_to_bootbased(struct timespec *ts)
824 ts->tv_sec += total_sleep_time;
827 unsigned long get_seconds(void)
829 return xtime_cache.tv_sec;
831 EXPORT_SYMBOL(get_seconds);
834 struct timespec current_kernel_time(void)
840 seq = read_seqbegin(&xtime_lock);
843 } while (read_seqretry(&xtime_lock, seq));
847 EXPORT_SYMBOL(current_kernel_time);