]> Pileus Git - ~andy/linux/blob - kernel/time/timekeeping.c
ntp: Split out timex validation from do_adjtimex
[~andy/linux] / kernel / time / timekeeping.c
1 /*
2  *  linux/kernel/time/timekeeping.c
3  *
4  *  Kernel timekeeping code and accessor functions
5  *
6  *  This code was moved from linux/kernel/timer.c.
7  *  Please see that file for copyright and history logs.
8  *
9  */
10
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>
16 #include <linux/mm.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
26 #include "tick-internal.h"
27
28 static struct timekeeper timekeeper;
29 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
30 static seqcount_t timekeeper_seq;
31
32 /* flag for if timekeeping is suspended */
33 int __read_mostly timekeeping_suspended;
34
35 /* Flag for if there is a persistent clock on this platform */
36 bool __read_mostly persistent_clock_exist = false;
37
38 static inline void tk_normalize_xtime(struct timekeeper *tk)
39 {
40         while (tk->xtime_nsec >= ((u64)NSEC_PER_SEC << tk->shift)) {
41                 tk->xtime_nsec -= (u64)NSEC_PER_SEC << tk->shift;
42                 tk->xtime_sec++;
43         }
44 }
45
46 static void tk_set_xtime(struct timekeeper *tk, const struct timespec *ts)
47 {
48         tk->xtime_sec = ts->tv_sec;
49         tk->xtime_nsec = (u64)ts->tv_nsec << tk->shift;
50 }
51
52 static void tk_xtime_add(struct timekeeper *tk, const struct timespec *ts)
53 {
54         tk->xtime_sec += ts->tv_sec;
55         tk->xtime_nsec += (u64)ts->tv_nsec << tk->shift;
56         tk_normalize_xtime(tk);
57 }
58
59 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec wtm)
60 {
61         struct timespec tmp;
62
63         /*
64          * Verify consistency of: offset_real = -wall_to_monotonic
65          * before modifying anything
66          */
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));
74 }
75
76 static void tk_set_sleep_time(struct timekeeper *tk, struct timespec t)
77 {
78         /* Verify consistency before modifying */
79         WARN_ON_ONCE(tk->offs_boot.tv64 != timespec_to_ktime(tk->total_sleep_time).tv64);
80
81         tk->total_sleep_time    = t;
82         tk->offs_boot           = timespec_to_ktime(t);
83 }
84
85 /**
86  * timekeeper_setup_internals - Set up internals to use clocksource clock.
87  *
88  * @clock:              Pointer to clocksource.
89  *
90  * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
91  * pair and interval request.
92  *
93  * Unless you're the timekeeping code, you should not be using this!
94  */
95 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
96 {
97         cycle_t interval;
98         u64 tmp, ntpinterval;
99         struct clocksource *old_clock;
100
101         old_clock = tk->clock;
102         tk->clock = clock;
103         clock->cycle_last = clock->read(clock);
104
105         /* Do the ns -> cycle conversion first, using original mult */
106         tmp = NTP_INTERVAL_LENGTH;
107         tmp <<= clock->shift;
108         ntpinterval = tmp;
109         tmp += clock->mult/2;
110         do_div(tmp, clock->mult);
111         if (tmp == 0)
112                 tmp = 1;
113
114         interval = (cycle_t) tmp;
115         tk->cycle_interval = interval;
116
117         /* Go back from cycles -> shifted ns */
118         tk->xtime_interval = (u64) interval * clock->mult;
119         tk->xtime_remainder = ntpinterval - tk->xtime_interval;
120         tk->raw_interval =
121                 ((u64) interval * clock->mult) >> clock->shift;
122
123          /* if changing clocks, convert xtime_nsec shift units */
124         if (old_clock) {
125                 int shift_change = clock->shift - old_clock->shift;
126                 if (shift_change < 0)
127                         tk->xtime_nsec >>= -shift_change;
128                 else
129                         tk->xtime_nsec <<= shift_change;
130         }
131         tk->shift = clock->shift;
132
133         tk->ntp_error = 0;
134         tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
135
136         /*
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.
140          */
141         tk->mult = clock->mult;
142 }
143
144 /* Timekeeper helper functions. */
145
146 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
147 u32 (*arch_gettimeoffset)(void);
148
149 u32 get_arch_timeoffset(void)
150 {
151         if (likely(arch_gettimeoffset))
152                 return arch_gettimeoffset();
153         return 0;
154 }
155 #else
156 static inline u32 get_arch_timeoffset(void) { return 0; }
157 #endif
158
159 static inline s64 timekeeping_get_ns(struct timekeeper *tk)
160 {
161         cycle_t cycle_now, cycle_delta;
162         struct clocksource *clock;
163         s64 nsec;
164
165         /* read clocksource: */
166         clock = tk->clock;
167         cycle_now = clock->read(clock);
168
169         /* calculate the delta since the last update_wall_time: */
170         cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
171
172         nsec = cycle_delta * tk->mult + tk->xtime_nsec;
173         nsec >>= tk->shift;
174
175         /* If arch requires, add in get_arch_timeoffset() */
176         return nsec + get_arch_timeoffset();
177 }
178
179 static inline s64 timekeeping_get_ns_raw(struct timekeeper *tk)
180 {
181         cycle_t cycle_now, cycle_delta;
182         struct clocksource *clock;
183         s64 nsec;
184
185         /* read clocksource: */
186         clock = tk->clock;
187         cycle_now = clock->read(clock);
188
189         /* calculate the delta since the last update_wall_time: */
190         cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
191
192         /* convert delta to nanoseconds. */
193         nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
194
195         /* If arch requires, add in get_arch_timeoffset() */
196         return nsec + get_arch_timeoffset();
197 }
198
199 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
200
201 static void update_pvclock_gtod(struct timekeeper *tk)
202 {
203         raw_notifier_call_chain(&pvclock_gtod_chain, 0, tk);
204 }
205
206 /**
207  * pvclock_gtod_register_notifier - register a pvclock timedata update listener
208  */
209 int pvclock_gtod_register_notifier(struct notifier_block *nb)
210 {
211         struct timekeeper *tk = &timekeeper;
212         unsigned long flags;
213         int ret;
214
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);
219
220         return ret;
221 }
222 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
223
224 /**
225  * pvclock_gtod_unregister_notifier - unregister a pvclock
226  * timedata update listener
227  */
228 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
229 {
230         unsigned long flags;
231         int ret;
232
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);
236
237         return ret;
238 }
239 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
240
241 /* must hold timekeeper_lock */
242 static void timekeeping_update(struct timekeeper *tk, bool clearntp)
243 {
244         if (clearntp) {
245                 tk->ntp_error = 0;
246                 ntp_clear();
247         }
248         update_vsyscall(tk);
249         update_pvclock_gtod(tk);
250 }
251
252 /**
253  * timekeeping_forward_now - update clock to the current time
254  *
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.
258  */
259 static void timekeeping_forward_now(struct timekeeper *tk)
260 {
261         cycle_t cycle_now, cycle_delta;
262         struct clocksource *clock;
263         s64 nsec;
264
265         clock = tk->clock;
266         cycle_now = clock->read(clock);
267         cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
268         clock->cycle_last = cycle_now;
269
270         tk->xtime_nsec += cycle_delta * tk->mult;
271
272         /* If arch requires, add in get_arch_timeoffset() */
273         tk->xtime_nsec += (u64)get_arch_timeoffset() << tk->shift;
274
275         tk_normalize_xtime(tk);
276
277         nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
278         timespec_add_ns(&tk->raw_time, nsec);
279 }
280
281 /**
282  * __getnstimeofday - Returns the time of day in a timespec.
283  * @ts:         pointer to the timespec to be set
284  *
285  * Updates the time of day in the timespec.
286  * Returns 0 on success, or -ve when suspended (timespec will be undefined).
287  */
288 int __getnstimeofday(struct timespec *ts)
289 {
290         struct timekeeper *tk = &timekeeper;
291         unsigned long seq;
292         s64 nsecs = 0;
293
294         do {
295                 seq = read_seqcount_begin(&timekeeper_seq);
296
297                 ts->tv_sec = tk->xtime_sec;
298                 nsecs = timekeeping_get_ns(tk);
299
300         } while (read_seqcount_retry(&timekeeper_seq, seq));
301
302         ts->tv_nsec = 0;
303         timespec_add_ns(ts, nsecs);
304
305         /*
306          * Do not bail out early, in case there were callers still using
307          * the value, even in the face of the WARN_ON.
308          */
309         if (unlikely(timekeeping_suspended))
310                 return -EAGAIN;
311         return 0;
312 }
313 EXPORT_SYMBOL(__getnstimeofday);
314
315 /**
316  * getnstimeofday - Returns the time of day in a timespec.
317  * @ts:         pointer to the timespec to be set
318  *
319  * Returns the time of day in a timespec (WARN if suspended).
320  */
321 void getnstimeofday(struct timespec *ts)
322 {
323         WARN_ON(__getnstimeofday(ts));
324 }
325 EXPORT_SYMBOL(getnstimeofday);
326
327 ktime_t ktime_get(void)
328 {
329         struct timekeeper *tk = &timekeeper;
330         unsigned int seq;
331         s64 secs, nsecs;
332
333         WARN_ON(timekeeping_suspended);
334
335         do {
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;
339
340         } while (read_seqcount_retry(&timekeeper_seq, seq));
341         /*
342          * Use ktime_set/ktime_add_ns to create a proper ktime on
343          * 32-bit architectures without CONFIG_KTIME_SCALAR.
344          */
345         return ktime_add_ns(ktime_set(secs, 0), nsecs);
346 }
347 EXPORT_SYMBOL_GPL(ktime_get);
348
349 /**
350  * ktime_get_ts - get the monotonic clock in timespec format
351  * @ts:         pointer to timespec variable
352  *
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.
356  */
357 void ktime_get_ts(struct timespec *ts)
358 {
359         struct timekeeper *tk = &timekeeper;
360         struct timespec tomono;
361         s64 nsec;
362         unsigned int seq;
363
364         WARN_ON(timekeeping_suspended);
365
366         do {
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;
371
372         } while (read_seqcount_retry(&timekeeper_seq, seq));
373
374         ts->tv_sec += tomono.tv_sec;
375         ts->tv_nsec = 0;
376         timespec_add_ns(ts, nsec + tomono.tv_nsec);
377 }
378 EXPORT_SYMBOL_GPL(ktime_get_ts);
379
380
381 /**
382  * timekeeping_clocktai - Returns the TAI time of day in a timespec
383  * @ts:         pointer to the timespec to be set
384  *
385  * Returns the time of day in a timespec.
386  */
387 void timekeeping_clocktai(struct timespec *ts)
388 {
389         struct timekeeper *tk = &timekeeper;
390         unsigned long seq;
391         u64 nsecs;
392
393         WARN_ON(timekeeping_suspended);
394
395         do {
396                 seq = read_seqcount_begin(&timekeeper_seq);
397
398                 ts->tv_sec = tk->xtime_sec + tk->tai_offset;
399                 nsecs = timekeeping_get_ns(tk);
400
401         } while (read_seqcount_retry(&timekeeper_seq, seq));
402
403         ts->tv_nsec = 0;
404         timespec_add_ns(ts, nsecs);
405
406 }
407 EXPORT_SYMBOL(timekeeping_clocktai);
408
409
410 /**
411  * ktime_get_clocktai - Returns the TAI time of day in a ktime
412  *
413  * Returns the time of day in a ktime.
414  */
415 ktime_t ktime_get_clocktai(void)
416 {
417         struct timespec ts;
418
419         timekeeping_clocktai(&ts);
420         return timespec_to_ktime(ts);
421 }
422 EXPORT_SYMBOL(ktime_get_clocktai);
423
424 #ifdef CONFIG_NTP_PPS
425
426 /**
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
430  *
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
433  * format.
434  */
435 void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
436 {
437         struct timekeeper *tk = &timekeeper;
438         unsigned long seq;
439         s64 nsecs_raw, nsecs_real;
440
441         WARN_ON_ONCE(timekeeping_suspended);
442
443         do {
444                 seq = read_seqcount_begin(&timekeeper_seq);
445
446                 *ts_raw = tk->raw_time;
447                 ts_real->tv_sec = tk->xtime_sec;
448                 ts_real->tv_nsec = 0;
449
450                 nsecs_raw = timekeeping_get_ns_raw(tk);
451                 nsecs_real = timekeeping_get_ns(tk);
452
453         } while (read_seqcount_retry(&timekeeper_seq, seq));
454
455         timespec_add_ns(ts_raw, nsecs_raw);
456         timespec_add_ns(ts_real, nsecs_real);
457 }
458 EXPORT_SYMBOL(getnstime_raw_and_real);
459
460 #endif /* CONFIG_NTP_PPS */
461
462 /**
463  * do_gettimeofday - Returns the time of day in a timeval
464  * @tv:         pointer to the timeval to be set
465  *
466  * NOTE: Users should be converted to using getnstimeofday()
467  */
468 void do_gettimeofday(struct timeval *tv)
469 {
470         struct timespec now;
471
472         getnstimeofday(&now);
473         tv->tv_sec = now.tv_sec;
474         tv->tv_usec = now.tv_nsec/1000;
475 }
476 EXPORT_SYMBOL(do_gettimeofday);
477
478 /**
479  * do_settimeofday - Sets the time of day
480  * @tv:         pointer to the timespec variable containing the new time
481  *
482  * Sets the time of day to the new time and update NTP and notify hrtimers
483  */
484 int do_settimeofday(const struct timespec *tv)
485 {
486         struct timekeeper *tk = &timekeeper;
487         struct timespec ts_delta, xt;
488         unsigned long flags;
489
490         if (!timespec_valid_strict(tv))
491                 return -EINVAL;
492
493         raw_spin_lock_irqsave(&timekeeper_lock, flags);
494         write_seqcount_begin(&timekeeper_seq);
495
496         timekeeping_forward_now(tk);
497
498         xt = tk_xtime(tk);
499         ts_delta.tv_sec = tv->tv_sec - xt.tv_sec;
500         ts_delta.tv_nsec = tv->tv_nsec - xt.tv_nsec;
501
502         tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, ts_delta));
503
504         tk_set_xtime(tk, tv);
505
506         timekeeping_update(tk, true);
507
508         write_seqcount_end(&timekeeper_seq);
509         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
510
511         /* signal hrtimers about time change */
512         clock_was_set();
513
514         return 0;
515 }
516 EXPORT_SYMBOL(do_settimeofday);
517
518 /**
519  * timekeeping_inject_offset - Adds or subtracts from the current time.
520  * @tv:         pointer to the timespec variable containing the offset
521  *
522  * Adds or subtracts an offset value from the current time.
523  */
524 int timekeeping_inject_offset(struct timespec *ts)
525 {
526         struct timekeeper *tk = &timekeeper;
527         unsigned long flags;
528         struct timespec tmp;
529         int ret = 0;
530
531         if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
532                 return -EINVAL;
533
534         raw_spin_lock_irqsave(&timekeeper_lock, flags);
535         write_seqcount_begin(&timekeeper_seq);
536
537         timekeeping_forward_now(tk);
538
539         /* Make sure the proposed value is valid */
540         tmp = timespec_add(tk_xtime(tk),  *ts);
541         if (!timespec_valid_strict(&tmp)) {
542                 ret = -EINVAL;
543                 goto error;
544         }
545
546         tk_xtime_add(tk, ts);
547         tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *ts));
548
549 error: /* even if we error out, we forwarded the time, so call update */
550         timekeeping_update(tk, true);
551
552         write_seqcount_end(&timekeeper_seq);
553         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
554
555         /* signal hrtimers about time change */
556         clock_was_set();
557
558         return ret;
559 }
560 EXPORT_SYMBOL(timekeeping_inject_offset);
561
562
563 /**
564  * timekeeping_get_tai_offset - Returns current TAI offset from UTC
565  *
566  */
567 s32 timekeeping_get_tai_offset(void)
568 {
569         struct timekeeper *tk = &timekeeper;
570         unsigned int seq;
571         s32 ret;
572
573         do {
574                 seq = read_seqcount_begin(&timekeeper_seq);
575                 ret = tk->tai_offset;
576         } while (read_seqcount_retry(&timekeeper_seq, seq));
577
578         return ret;
579 }
580
581 /**
582  * __timekeeping_set_tai_offset - Lock free worker function
583  *
584  */
585 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
586 {
587         tk->tai_offset = tai_offset;
588         tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tai_offset, 0));
589 }
590
591 /**
592  * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
593  *
594  */
595 void timekeeping_set_tai_offset(s32 tai_offset)
596 {
597         struct timekeeper *tk = &timekeeper;
598         unsigned long flags;
599
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);
605 }
606
607 /**
608  * change_clocksource - Swaps clocksources if a new one is available
609  *
610  * Accumulates current time interval and initializes new clocksource
611  */
612 static int change_clocksource(void *data)
613 {
614         struct timekeeper *tk = &timekeeper;
615         struct clocksource *new, *old;
616         unsigned long flags;
617
618         new = (struct clocksource *) data;
619
620         raw_spin_lock_irqsave(&timekeeper_lock, flags);
621         write_seqcount_begin(&timekeeper_seq);
622
623         timekeeping_forward_now(tk);
624         if (!new->enable || new->enable(new) == 0) {
625                 old = tk->clock;
626                 tk_setup_internals(tk, new);
627                 if (old->disable)
628                         old->disable(old);
629         }
630         timekeeping_update(tk, true);
631
632         write_seqcount_end(&timekeeper_seq);
633         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
634
635         return 0;
636 }
637
638 /**
639  * timekeeping_notify - Install a new clock source
640  * @clock:              pointer to the clock source
641  *
642  * This function is called from clocksource.c after a new, better clock
643  * source has been registered. The caller holds the clocksource_mutex.
644  */
645 void timekeeping_notify(struct clocksource *clock)
646 {
647         struct timekeeper *tk = &timekeeper;
648
649         if (tk->clock == clock)
650                 return;
651         stop_machine(change_clocksource, clock, NULL);
652         tick_clock_notify();
653 }
654
655 /**
656  * ktime_get_real - get the real (wall-) time in ktime_t format
657  *
658  * returns the time in ktime_t format
659  */
660 ktime_t ktime_get_real(void)
661 {
662         struct timespec now;
663
664         getnstimeofday(&now);
665
666         return timespec_to_ktime(now);
667 }
668 EXPORT_SYMBOL_GPL(ktime_get_real);
669
670 /**
671  * getrawmonotonic - Returns the raw monotonic time in a timespec
672  * @ts:         pointer to the timespec to be set
673  *
674  * Returns the raw monotonic time (completely un-modified by ntp)
675  */
676 void getrawmonotonic(struct timespec *ts)
677 {
678         struct timekeeper *tk = &timekeeper;
679         unsigned long seq;
680         s64 nsecs;
681
682         do {
683                 seq = read_seqcount_begin(&timekeeper_seq);
684                 nsecs = timekeeping_get_ns_raw(tk);
685                 *ts = tk->raw_time;
686
687         } while (read_seqcount_retry(&timekeeper_seq, seq));
688
689         timespec_add_ns(ts, nsecs);
690 }
691 EXPORT_SYMBOL(getrawmonotonic);
692
693 /**
694  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
695  */
696 int timekeeping_valid_for_hres(void)
697 {
698         struct timekeeper *tk = &timekeeper;
699         unsigned long seq;
700         int ret;
701
702         do {
703                 seq = read_seqcount_begin(&timekeeper_seq);
704
705                 ret = tk->clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
706
707         } while (read_seqcount_retry(&timekeeper_seq, seq));
708
709         return ret;
710 }
711
712 /**
713  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
714  */
715 u64 timekeeping_max_deferment(void)
716 {
717         struct timekeeper *tk = &timekeeper;
718         unsigned long seq;
719         u64 ret;
720
721         do {
722                 seq = read_seqcount_begin(&timekeeper_seq);
723
724                 ret = tk->clock->max_idle_ns;
725
726         } while (read_seqcount_retry(&timekeeper_seq, seq));
727
728         return ret;
729 }
730
731 /**
732  * read_persistent_clock -  Return time from the persistent clock.
733  *
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.
737  *
738  *  XXX - Do be sure to remove it once all arches implement it.
739  */
740 void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
741 {
742         ts->tv_sec = 0;
743         ts->tv_nsec = 0;
744 }
745
746 /**
747  * read_boot_clock -  Return time of the system start.
748  *
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.
752  *
753  *  XXX - Do be sure to remove it once all arches implement it.
754  */
755 void __attribute__((weak)) read_boot_clock(struct timespec *ts)
756 {
757         ts->tv_sec = 0;
758         ts->tv_nsec = 0;
759 }
760
761 /*
762  * timekeeping_init - Initializes the clocksource and common timekeeping values
763  */
764 void __init timekeeping_init(void)
765 {
766         struct timekeeper *tk = &timekeeper;
767         struct clocksource *clock;
768         unsigned long flags;
769         struct timespec now, boot, tmp;
770
771         read_persistent_clock(&now);
772
773         if (!timespec_valid_strict(&now)) {
774                 pr_warn("WARNING: Persistent clock returned invalid value!\n"
775                         "         Check your CMOS/BIOS settings.\n");
776                 now.tv_sec = 0;
777                 now.tv_nsec = 0;
778         } else if (now.tv_sec || now.tv_nsec)
779                 persistent_clock_exist = true;
780
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");
785                 boot.tv_sec = 0;
786                 boot.tv_nsec = 0;
787         }
788
789         ntp_init();
790
791         raw_spin_lock_irqsave(&timekeeper_lock, flags);
792         write_seqcount_begin(&timekeeper_seq);
793         clock = clocksource_default_clock();
794         if (clock->enable)
795                 clock->enable(clock);
796         tk_setup_internals(tk, clock);
797
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)
802                 boot = tk_xtime(tk);
803
804         set_normalized_timespec(&tmp, -boot.tv_sec, -boot.tv_nsec);
805         tk_set_wall_to_mono(tk, tmp);
806
807         tmp.tv_sec = 0;
808         tmp.tv_nsec = 0;
809         tk_set_sleep_time(tk, tmp);
810
811         write_seqcount_end(&timekeeper_seq);
812         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
813 }
814
815 /* time in seconds when suspend began */
816 static struct timespec timekeeping_suspend_time;
817
818 /**
819  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
820  * @delta: pointer to a timespec delta value
821  *
822  * Takes a timespec offset measuring a suspend interval and properly
823  * adds the sleep offset to the timekeeping variables.
824  */
825 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
826                                                         struct timespec *delta)
827 {
828         if (!timespec_valid_strict(delta)) {
829                 printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
830                                         "sleep delta value!\n");
831                 return;
832         }
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));
836 }
837
838 /**
839  * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
840  * @delta: pointer to a timespec delta value
841  *
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.
844  *
845  * This function should only be called by rtc_resume(), and allows
846  * a suspend offset to be injected into the timekeeping values.
847  */
848 void timekeeping_inject_sleeptime(struct timespec *delta)
849 {
850         struct timekeeper *tk = &timekeeper;
851         unsigned long flags;
852
853         /*
854          * Make sure we don't set the clock twice, as timekeeping_resume()
855          * already did it
856          */
857         if (has_persistent_clock())
858                 return;
859
860         raw_spin_lock_irqsave(&timekeeper_lock, flags);
861         write_seqcount_begin(&timekeeper_seq);
862
863         timekeeping_forward_now(tk);
864
865         __timekeeping_inject_sleeptime(tk, delta);
866
867         timekeeping_update(tk, true);
868
869         write_seqcount_end(&timekeeper_seq);
870         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
871
872         /* signal hrtimers about time change */
873         clock_was_set();
874 }
875
876 /**
877  * timekeeping_resume - Resumes the generic timekeeping subsystem.
878  *
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.
882  */
883 static void timekeeping_resume(void)
884 {
885         struct timekeeper *tk = &timekeeper;
886         struct clocksource *clock = tk->clock;
887         unsigned long flags;
888         struct timespec ts_new, ts_delta;
889         cycle_t cycle_now, cycle_delta;
890         bool suspendtime_found = false;
891
892         read_persistent_clock(&ts_new);
893
894         clockevents_resume();
895         clocksource_resume();
896
897         raw_spin_lock_irqsave(&timekeeper_lock, flags);
898         write_seqcount_begin(&timekeeper_seq);
899
900         /*
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
904          * device.
905          *
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.
911          */
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;
918                 s64 nsec = 0;
919
920                 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
921
922                 /*
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
926                  */
927                 do_div(max, mult);
928                 if (cycle_delta > max) {
929                         num = div64_u64(cycle_delta, max);
930                         nsec = (((u64) max * mult) >> shift) * num;
931                         cycle_delta -= num * max;
932                 }
933                 nsec += ((u64) cycle_delta * mult) >> shift;
934
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;
940         }
941
942         if (suspendtime_found)
943                 __timekeeping_inject_sleeptime(tk, &ts_delta);
944
945         /* Re-base the last cycle value */
946         clock->cycle_last = cycle_now;
947         tk->ntp_error = 0;
948         timekeeping_suspended = 0;
949         timekeeping_update(tk, false);
950         write_seqcount_end(&timekeeper_seq);
951         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
952
953         touch_softlockup_watchdog();
954
955         clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
956
957         /* Resume hrtimers */
958         hrtimers_resume();
959 }
960
961 static int timekeeping_suspend(void)
962 {
963         struct timekeeper *tk = &timekeeper;
964         unsigned long flags;
965         struct timespec         delta, delta_delta;
966         static struct timespec  old_delta;
967
968         read_persistent_clock(&timekeeping_suspend_time);
969
970         raw_spin_lock_irqsave(&timekeeper_lock, flags);
971         write_seqcount_begin(&timekeeper_seq);
972         timekeeping_forward_now(tk);
973         timekeeping_suspended = 1;
974
975         /*
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.
980          */
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) {
984                 /*
985                  * if delta_delta is too large, assume time correction
986                  * has occured and set old_delta to the current delta.
987                  */
988                 old_delta = delta;
989         } else {
990                 /* Otherwise try to adjust old_system to compensate */
991                 timekeeping_suspend_time =
992                         timespec_add(timekeeping_suspend_time, delta_delta);
993         }
994         write_seqcount_end(&timekeeper_seq);
995         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
996
997         clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
998         clocksource_suspend();
999         clockevents_suspend();
1000
1001         return 0;
1002 }
1003
1004 /* sysfs resume/suspend bits for timekeeping */
1005 static struct syscore_ops timekeeping_syscore_ops = {
1006         .resume         = timekeeping_resume,
1007         .suspend        = timekeeping_suspend,
1008 };
1009
1010 static int __init timekeeping_init_ops(void)
1011 {
1012         register_syscore_ops(&timekeeping_syscore_ops);
1013         return 0;
1014 }
1015
1016 device_initcall(timekeeping_init_ops);
1017
1018 /*
1019  * If the error is already larger, we look ahead even further
1020  * to compensate for late or lost adjustments.
1021  */
1022 static __always_inline int timekeeping_bigadjust(struct timekeeper *tk,
1023                                                  s64 error, s64 *interval,
1024                                                  s64 *offset)
1025 {
1026         s64 tick_error, i;
1027         u32 look_ahead, adj;
1028         s32 error2, mult;
1029
1030         /*
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).
1038          */
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++)
1042                 error2 >>= 2;
1043
1044         /*
1045          * Now calculate the error in (1 << look_ahead) ticks, but first
1046          * remove the single look ahead already included in the error.
1047          */
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;
1051
1052         /* Finally calculate the adjustment shift value.  */
1053         i = *interval;
1054         mult = 1;
1055         if (error < 0) {
1056                 error = -error;
1057                 *interval = -*interval;
1058                 *offset = -*offset;
1059                 mult = -1;
1060         }
1061         for (adj = 0; error > i; adj++)
1062                 error >>= 1;
1063
1064         *interval <<= adj;
1065         *offset <<= adj;
1066         return mult << adj;
1067 }
1068
1069 /*
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.
1073  */
1074 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1075 {
1076         s64 error, interval = tk->cycle_interval;
1077         int adj;
1078
1079         /*
1080          * The point of this is to check if the error is greater than half
1081          * an interval.
1082          *
1083          * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
1084          *
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.
1089          *
1090          * Note: It does not "save" on aggravation when reading the code.
1091          */
1092         error = tk->ntp_error >> (tk->ntp_error_shift - 1);
1093         if (error > interval) {
1094                 /*
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.
1099                  */
1100                 error >>= 2;
1101                 /*
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.
1105                  *
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
1109                  * time.
1110                  */
1111                 if (likely(error <= interval))
1112                         adj = 1;
1113                 else
1114                         adj = timekeeping_bigadjust(tk, error, &interval, &offset);
1115         } else {
1116                 if (error < -interval) {
1117                         /* See comment above, this is just switched for the negative */
1118                         error >>= 2;
1119                         if (likely(error >= -interval)) {
1120                                 adj = -1;
1121                                 interval = -interval;
1122                                 offset = -offset;
1123                         } else {
1124                                 adj = timekeeping_bigadjust(tk, error, &interval, &offset);
1125                         }
1126                 } else {
1127                         goto out_adjust;
1128                 }
1129         }
1130
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);
1137         }
1138         /*
1139          * So the following can be confusing.
1140          *
1141          * To keep things simple, lets assume adj == 1 for now.
1142          *
1143          * When adj != 1, remember that the interval and offset values
1144          * have been appropriately scaled so the math is the same.
1145          *
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)
1152          * Its the same as:
1153          *      xtime_interval = (cycle_interval * mult) + cycle_interval
1154          * Which can be shortened to:
1155          *      xtime_interval += cycle_interval
1156          *
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.
1163          *
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
1168          * So:
1169          *      (offset * adj_1) + xtime_nsec_1 =
1170          *              (offset * adj_2) + xtime_nsec_2
1171          * And we know:
1172          *      adj_2 = adj_1 + 1
1173          * So:
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
1180          * Which gives us:
1181          *      xtime_nsec_2 = xtime_nsec_1 - offset
1182          * Which simplfies to:
1183          *      xtime_nsec -= offset
1184          *
1185          * XXX - TODO: Doc ntp_error calculation.
1186          */
1187         tk->mult += adj;
1188         tk->xtime_interval += interval;
1189         tk->xtime_nsec -= offset;
1190         tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1191
1192 out_adjust:
1193         /*
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.
1198          *
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.
1203          *
1204          * We'll correct this error next time through this function, when
1205          * xtime_nsec is not as small.
1206          */
1207         if (unlikely((s64)tk->xtime_nsec < 0)) {
1208                 s64 neg = -(s64)tk->xtime_nsec;
1209                 tk->xtime_nsec = 0;
1210                 tk->ntp_error += neg << tk->ntp_error_shift;
1211         }
1212
1213 }
1214
1215 /**
1216  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1217  *
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.
1221  *
1222  */
1223 static inline void accumulate_nsecs_to_secs(struct timekeeper *tk)
1224 {
1225         u64 nsecps = (u64)NSEC_PER_SEC << tk->shift;
1226
1227         while (tk->xtime_nsec >= nsecps) {
1228                 int leap;
1229
1230                 tk->xtime_nsec -= nsecps;
1231                 tk->xtime_sec++;
1232
1233                 /* Figure out if its a leap sec and apply if needed */
1234                 leap = second_overflow(tk->xtime_sec);
1235                 if (unlikely(leap)) {
1236                         struct timespec ts;
1237
1238                         tk->xtime_sec += leap;
1239
1240                         ts.tv_sec = leap;
1241                         ts.tv_nsec = 0;
1242                         tk_set_wall_to_mono(tk,
1243                                 timespec_sub(tk->wall_to_monotonic, ts));
1244
1245                         __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1246
1247                         clock_was_set_delayed();
1248                 }
1249         }
1250 }
1251
1252 /**
1253  * logarithmic_accumulation - shifted accumulation of cycles
1254  *
1255  * This functions accumulates a shifted interval of cycles into
1256  * into a shifted interval nanoseconds. Allows for O(log) accumulation
1257  * loop.
1258  *
1259  * Returns the unconsumed cycles.
1260  */
1261 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1262                                                 u32 shift)
1263 {
1264         cycle_t interval = tk->cycle_interval << shift;
1265         u64 raw_nsecs;
1266
1267         /* If the offset is smaller then a shifted interval, do nothing */
1268         if (offset < interval)
1269                 return offset;
1270
1271         /* Accumulate one shifted interval */
1272         offset -= interval;
1273         tk->clock->cycle_last += interval;
1274
1275         tk->xtime_nsec += tk->xtime_interval << shift;
1276         accumulate_nsecs_to_secs(tk);
1277
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;
1285         }
1286         tk->raw_time.tv_nsec = raw_nsecs;
1287
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);
1292
1293         return offset;
1294 }
1295
1296 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
1297 static inline void old_vsyscall_fixup(struct timekeeper *tk)
1298 {
1299         s64 remainder;
1300
1301         /*
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.
1310         */
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;
1315
1316 }
1317 #else
1318 #define old_vsyscall_fixup(tk)
1319 #endif
1320
1321
1322
1323 /**
1324  * update_wall_time - Uses the current clocksource to increment the wall time
1325  *
1326  */
1327 static void update_wall_time(void)
1328 {
1329         struct clocksource *clock;
1330         struct timekeeper *tk = &timekeeper;
1331         cycle_t offset;
1332         int shift = 0, maxshift;
1333         unsigned long flags;
1334
1335         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1336         write_seqcount_begin(&timekeeper_seq);
1337
1338         /* Make sure we're fully resumed: */
1339         if (unlikely(timekeeping_suspended))
1340                 goto out;
1341
1342         clock = tk->clock;
1343
1344 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1345         offset = tk->cycle_interval;
1346 #else
1347         offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
1348 #endif
1349
1350         /* Check if there's really nothing to do */
1351         if (offset < tk->cycle_interval)
1352                 goto out;
1353
1354         /*
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
1360          * doubled multiple.
1361          */
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)
1370                         shift--;
1371         }
1372
1373         /* correct the clock when NTP error is too big */
1374         timekeeping_adjust(tk, offset);
1375
1376         /*
1377          * XXX This can be killed once everyone converts
1378          * to the new update_vsyscall.
1379          */
1380         old_vsyscall_fixup(tk);
1381
1382         /*
1383          * Finally, make sure that after the rounding
1384          * xtime_nsec isn't larger than NSEC_PER_SEC
1385          */
1386         accumulate_nsecs_to_secs(tk);
1387
1388         timekeeping_update(tk, false);
1389
1390 out:
1391         write_seqcount_end(&timekeeper_seq);
1392         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1393
1394 }
1395
1396 /**
1397  * getboottime - Return the real time of system boot.
1398  * @ts:         pointer to the timespec to be set
1399  *
1400  * Returns the wall-time of boot in a timespec.
1401  *
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).
1406  */
1407 void getboottime(struct timespec *ts)
1408 {
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
1415         };
1416
1417         set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
1418 }
1419 EXPORT_SYMBOL_GPL(getboottime);
1420
1421 /**
1422  * get_monotonic_boottime - Returns monotonic time since boot
1423  * @ts:         pointer to the timespec to be set
1424  *
1425  * Returns the monotonic time since boot in a timespec.
1426  *
1427  * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
1428  * includes the time spent in suspend.
1429  */
1430 void get_monotonic_boottime(struct timespec *ts)
1431 {
1432         struct timekeeper *tk = &timekeeper;
1433         struct timespec tomono, sleep;
1434         s64 nsec;
1435         unsigned int seq;
1436
1437         WARN_ON(timekeeping_suspended);
1438
1439         do {
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;
1445
1446         } while (read_seqcount_retry(&timekeeper_seq, seq));
1447
1448         ts->tv_sec += tomono.tv_sec + sleep.tv_sec;
1449         ts->tv_nsec = 0;
1450         timespec_add_ns(ts, nsec + tomono.tv_nsec + sleep.tv_nsec);
1451 }
1452 EXPORT_SYMBOL_GPL(get_monotonic_boottime);
1453
1454 /**
1455  * ktime_get_boottime - Returns monotonic time since boot in a ktime
1456  *
1457  * Returns the monotonic time since boot in a ktime
1458  *
1459  * This is similar to CLOCK_MONTONIC/ktime_get, but also
1460  * includes the time spent in suspend.
1461  */
1462 ktime_t ktime_get_boottime(void)
1463 {
1464         struct timespec ts;
1465
1466         get_monotonic_boottime(&ts);
1467         return timespec_to_ktime(ts);
1468 }
1469 EXPORT_SYMBOL_GPL(ktime_get_boottime);
1470
1471 /**
1472  * monotonic_to_bootbased - Convert the monotonic time to boot based.
1473  * @ts:         pointer to the timespec to be converted
1474  */
1475 void monotonic_to_bootbased(struct timespec *ts)
1476 {
1477         struct timekeeper *tk = &timekeeper;
1478
1479         *ts = timespec_add(*ts, tk->total_sleep_time);
1480 }
1481 EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
1482
1483 unsigned long get_seconds(void)
1484 {
1485         struct timekeeper *tk = &timekeeper;
1486
1487         return tk->xtime_sec;
1488 }
1489 EXPORT_SYMBOL(get_seconds);
1490
1491 struct timespec __current_kernel_time(void)
1492 {
1493         struct timekeeper *tk = &timekeeper;
1494
1495         return tk_xtime(tk);
1496 }
1497
1498 struct timespec current_kernel_time(void)
1499 {
1500         struct timekeeper *tk = &timekeeper;
1501         struct timespec now;
1502         unsigned long seq;
1503
1504         do {
1505                 seq = read_seqcount_begin(&timekeeper_seq);
1506
1507                 now = tk_xtime(tk);
1508         } while (read_seqcount_retry(&timekeeper_seq, seq));
1509
1510         return now;
1511 }
1512 EXPORT_SYMBOL(current_kernel_time);
1513
1514 struct timespec get_monotonic_coarse(void)
1515 {
1516         struct timekeeper *tk = &timekeeper;
1517         struct timespec now, mono;
1518         unsigned long seq;
1519
1520         do {
1521                 seq = read_seqcount_begin(&timekeeper_seq);
1522
1523                 now = tk_xtime(tk);
1524                 mono = tk->wall_to_monotonic;
1525         } while (read_seqcount_retry(&timekeeper_seq, seq));
1526
1527         set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
1528                                 now.tv_nsec + mono.tv_nsec);
1529         return now;
1530 }
1531
1532 /*
1533  * Must hold jiffies_lock
1534  */
1535 void do_timer(unsigned long ticks)
1536 {
1537         jiffies_64 += ticks;
1538         update_wall_time();
1539         calc_global_load(ticks);
1540 }
1541
1542 /**
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
1548  */
1549 void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
1550                                 struct timespec *wtom, struct timespec *sleep)
1551 {
1552         struct timekeeper *tk = &timekeeper;
1553         unsigned long seq;
1554
1555         do {
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));
1561 }
1562
1563 #ifdef CONFIG_HIGH_RES_TIMERS
1564 /**
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
1568  *
1569  * Returns current monotonic time and updates the offsets
1570  * Called from hrtimer_interupt() or retrigger_next_event()
1571  */
1572 ktime_t ktime_get_update_offsets(ktime_t *offs_real, ktime_t *offs_boot,
1573                                                         ktime_t *offs_tai)
1574 {
1575         struct timekeeper *tk = &timekeeper;
1576         ktime_t now;
1577         unsigned int seq;
1578         u64 secs, nsecs;
1579
1580         do {
1581                 seq = read_seqcount_begin(&timekeeper_seq);
1582
1583                 secs = tk->xtime_sec;
1584                 nsecs = timekeeping_get_ns(tk);
1585
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));
1590
1591         now = ktime_add_ns(ktime_set(secs, 0), nsecs);
1592         now = ktime_sub(now, *offs_real);
1593         return now;
1594 }
1595 #endif
1596
1597 /**
1598  * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
1599  */
1600 ktime_t ktime_get_monotonic_offset(void)
1601 {
1602         struct timekeeper *tk = &timekeeper;
1603         unsigned long seq;
1604         struct timespec wtom;
1605
1606         do {
1607                 seq = read_seqcount_begin(&timekeeper_seq);
1608                 wtom = tk->wall_to_monotonic;
1609         } while (read_seqcount_retry(&timekeeper_seq, seq));
1610
1611         return timespec_to_ktime(wtom);
1612 }
1613 EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
1614
1615 /**
1616  * xtime_update() - advances the timekeeping infrastructure
1617  * @ticks:      number of ticks, that have elapsed since the last call.
1618  *
1619  * Must be called with interrupts disabled.
1620  */
1621 void xtime_update(unsigned long ticks)
1622 {
1623         write_seqlock(&jiffies_lock);
1624         do_timer(ticks);
1625         write_sequnlock(&jiffies_lock);
1626 }