]> Pileus Git - ~andy/linux/blob - kernel/time/timekeeping.c
power: Add option to log time spent in suspend
[~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 #include "ntp_internal.h"
28 #include "timekeeping_internal.h"
29
30 static struct timekeeper timekeeper;
31 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
32 static seqcount_t timekeeper_seq;
33 static struct timekeeper shadow_timekeeper;
34
35 /* flag for if timekeeping is suspended */
36 int __read_mostly timekeeping_suspended;
37
38 /* Flag for if there is a persistent clock on this platform */
39 bool __read_mostly persistent_clock_exist = false;
40
41 static inline void tk_normalize_xtime(struct timekeeper *tk)
42 {
43         while (tk->xtime_nsec >= ((u64)NSEC_PER_SEC << tk->shift)) {
44                 tk->xtime_nsec -= (u64)NSEC_PER_SEC << tk->shift;
45                 tk->xtime_sec++;
46         }
47 }
48
49 static void tk_set_xtime(struct timekeeper *tk, const struct timespec *ts)
50 {
51         tk->xtime_sec = ts->tv_sec;
52         tk->xtime_nsec = (u64)ts->tv_nsec << tk->shift;
53 }
54
55 static void tk_xtime_add(struct timekeeper *tk, const struct timespec *ts)
56 {
57         tk->xtime_sec += ts->tv_sec;
58         tk->xtime_nsec += (u64)ts->tv_nsec << tk->shift;
59         tk_normalize_xtime(tk);
60 }
61
62 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec wtm)
63 {
64         struct timespec tmp;
65
66         /*
67          * Verify consistency of: offset_real = -wall_to_monotonic
68          * before modifying anything
69          */
70         set_normalized_timespec(&tmp, -tk->wall_to_monotonic.tv_sec,
71                                         -tk->wall_to_monotonic.tv_nsec);
72         WARN_ON_ONCE(tk->offs_real.tv64 != timespec_to_ktime(tmp).tv64);
73         tk->wall_to_monotonic = wtm;
74         set_normalized_timespec(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
75         tk->offs_real = timespec_to_ktime(tmp);
76         tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tk->tai_offset, 0));
77 }
78
79 static void tk_set_sleep_time(struct timekeeper *tk, struct timespec t)
80 {
81         /* Verify consistency before modifying */
82         WARN_ON_ONCE(tk->offs_boot.tv64 != timespec_to_ktime(tk->total_sleep_time).tv64);
83
84         tk->total_sleep_time    = t;
85         tk->offs_boot           = timespec_to_ktime(t);
86 }
87
88 /**
89  * timekeeper_setup_internals - Set up internals to use clocksource clock.
90  *
91  * @clock:              Pointer to clocksource.
92  *
93  * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
94  * pair and interval request.
95  *
96  * Unless you're the timekeeping code, you should not be using this!
97  */
98 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
99 {
100         cycle_t interval;
101         u64 tmp, ntpinterval;
102         struct clocksource *old_clock;
103
104         old_clock = tk->clock;
105         tk->clock = clock;
106         tk->cycle_last = clock->cycle_last = clock->read(clock);
107
108         /* Do the ns -> cycle conversion first, using original mult */
109         tmp = NTP_INTERVAL_LENGTH;
110         tmp <<= clock->shift;
111         ntpinterval = tmp;
112         tmp += clock->mult/2;
113         do_div(tmp, clock->mult);
114         if (tmp == 0)
115                 tmp = 1;
116
117         interval = (cycle_t) tmp;
118         tk->cycle_interval = interval;
119
120         /* Go back from cycles -> shifted ns */
121         tk->xtime_interval = (u64) interval * clock->mult;
122         tk->xtime_remainder = ntpinterval - tk->xtime_interval;
123         tk->raw_interval =
124                 ((u64) interval * clock->mult) >> clock->shift;
125
126          /* if changing clocks, convert xtime_nsec shift units */
127         if (old_clock) {
128                 int shift_change = clock->shift - old_clock->shift;
129                 if (shift_change < 0)
130                         tk->xtime_nsec >>= -shift_change;
131                 else
132                         tk->xtime_nsec <<= shift_change;
133         }
134         tk->shift = clock->shift;
135
136         tk->ntp_error = 0;
137         tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
138
139         /*
140          * The timekeeper keeps its own mult values for the currently
141          * active clocksource. These value will be adjusted via NTP
142          * to counteract clock drifting.
143          */
144         tk->mult = clock->mult;
145 }
146
147 /* Timekeeper helper functions. */
148
149 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
150 u32 (*arch_gettimeoffset)(void);
151
152 u32 get_arch_timeoffset(void)
153 {
154         if (likely(arch_gettimeoffset))
155                 return arch_gettimeoffset();
156         return 0;
157 }
158 #else
159 static inline u32 get_arch_timeoffset(void) { return 0; }
160 #endif
161
162 static inline s64 timekeeping_get_ns(struct timekeeper *tk)
163 {
164         cycle_t cycle_now, cycle_delta;
165         struct clocksource *clock;
166         s64 nsec;
167
168         /* read clocksource: */
169         clock = tk->clock;
170         cycle_now = clock->read(clock);
171
172         /* calculate the delta since the last update_wall_time: */
173         cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
174
175         nsec = cycle_delta * tk->mult + tk->xtime_nsec;
176         nsec >>= tk->shift;
177
178         /* If arch requires, add in get_arch_timeoffset() */
179         return nsec + get_arch_timeoffset();
180 }
181
182 static inline s64 timekeeping_get_ns_raw(struct timekeeper *tk)
183 {
184         cycle_t cycle_now, cycle_delta;
185         struct clocksource *clock;
186         s64 nsec;
187
188         /* read clocksource: */
189         clock = tk->clock;
190         cycle_now = clock->read(clock);
191
192         /* calculate the delta since the last update_wall_time: */
193         cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
194
195         /* convert delta to nanoseconds. */
196         nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
197
198         /* If arch requires, add in get_arch_timeoffset() */
199         return nsec + get_arch_timeoffset();
200 }
201
202 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
203
204 static void update_pvclock_gtod(struct timekeeper *tk)
205 {
206         raw_notifier_call_chain(&pvclock_gtod_chain, 0, tk);
207 }
208
209 /**
210  * pvclock_gtod_register_notifier - register a pvclock timedata update listener
211  */
212 int pvclock_gtod_register_notifier(struct notifier_block *nb)
213 {
214         struct timekeeper *tk = &timekeeper;
215         unsigned long flags;
216         int ret;
217
218         raw_spin_lock_irqsave(&timekeeper_lock, flags);
219         ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
220         update_pvclock_gtod(tk);
221         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
222
223         return ret;
224 }
225 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
226
227 /**
228  * pvclock_gtod_unregister_notifier - unregister a pvclock
229  * timedata update listener
230  */
231 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
232 {
233         unsigned long flags;
234         int ret;
235
236         raw_spin_lock_irqsave(&timekeeper_lock, flags);
237         ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
238         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
239
240         return ret;
241 }
242 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
243
244 /* must hold timekeeper_lock */
245 static void timekeeping_update(struct timekeeper *tk, bool clearntp, bool mirror)
246 {
247         if (clearntp) {
248                 tk->ntp_error = 0;
249                 ntp_clear();
250         }
251         update_vsyscall(tk);
252         update_pvclock_gtod(tk);
253
254         if (mirror)
255                 memcpy(&shadow_timekeeper, &timekeeper, sizeof(timekeeper));
256 }
257
258 /**
259  * timekeeping_forward_now - update clock to the current time
260  *
261  * Forward the current clock to update its state since the last call to
262  * update_wall_time(). This is useful before significant clock changes,
263  * as it avoids having to deal with this time offset explicitly.
264  */
265 static void timekeeping_forward_now(struct timekeeper *tk)
266 {
267         cycle_t cycle_now, cycle_delta;
268         struct clocksource *clock;
269         s64 nsec;
270
271         clock = tk->clock;
272         cycle_now = clock->read(clock);
273         cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
274         tk->cycle_last = clock->cycle_last = cycle_now;
275
276         tk->xtime_nsec += cycle_delta * tk->mult;
277
278         /* If arch requires, add in get_arch_timeoffset() */
279         tk->xtime_nsec += (u64)get_arch_timeoffset() << tk->shift;
280
281         tk_normalize_xtime(tk);
282
283         nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
284         timespec_add_ns(&tk->raw_time, nsec);
285 }
286
287 /**
288  * __getnstimeofday - Returns the time of day in a timespec.
289  * @ts:         pointer to the timespec to be set
290  *
291  * Updates the time of day in the timespec.
292  * Returns 0 on success, or -ve when suspended (timespec will be undefined).
293  */
294 int __getnstimeofday(struct timespec *ts)
295 {
296         struct timekeeper *tk = &timekeeper;
297         unsigned long seq;
298         s64 nsecs = 0;
299
300         do {
301                 seq = read_seqcount_begin(&timekeeper_seq);
302
303                 ts->tv_sec = tk->xtime_sec;
304                 nsecs = timekeeping_get_ns(tk);
305
306         } while (read_seqcount_retry(&timekeeper_seq, seq));
307
308         ts->tv_nsec = 0;
309         timespec_add_ns(ts, nsecs);
310
311         /*
312          * Do not bail out early, in case there were callers still using
313          * the value, even in the face of the WARN_ON.
314          */
315         if (unlikely(timekeeping_suspended))
316                 return -EAGAIN;
317         return 0;
318 }
319 EXPORT_SYMBOL(__getnstimeofday);
320
321 /**
322  * getnstimeofday - Returns the time of day in a timespec.
323  * @ts:         pointer to the timespec to be set
324  *
325  * Returns the time of day in a timespec (WARN if suspended).
326  */
327 void getnstimeofday(struct timespec *ts)
328 {
329         WARN_ON(__getnstimeofday(ts));
330 }
331 EXPORT_SYMBOL(getnstimeofday);
332
333 ktime_t ktime_get(void)
334 {
335         struct timekeeper *tk = &timekeeper;
336         unsigned int seq;
337         s64 secs, nsecs;
338
339         WARN_ON(timekeeping_suspended);
340
341         do {
342                 seq = read_seqcount_begin(&timekeeper_seq);
343                 secs = tk->xtime_sec + tk->wall_to_monotonic.tv_sec;
344                 nsecs = timekeeping_get_ns(tk) + tk->wall_to_monotonic.tv_nsec;
345
346         } while (read_seqcount_retry(&timekeeper_seq, seq));
347         /*
348          * Use ktime_set/ktime_add_ns to create a proper ktime on
349          * 32-bit architectures without CONFIG_KTIME_SCALAR.
350          */
351         return ktime_add_ns(ktime_set(secs, 0), nsecs);
352 }
353 EXPORT_SYMBOL_GPL(ktime_get);
354
355 /**
356  * ktime_get_ts - get the monotonic clock in timespec format
357  * @ts:         pointer to timespec variable
358  *
359  * The function calculates the monotonic clock from the realtime
360  * clock and the wall_to_monotonic offset and stores the result
361  * in normalized timespec format in the variable pointed to by @ts.
362  */
363 void ktime_get_ts(struct timespec *ts)
364 {
365         struct timekeeper *tk = &timekeeper;
366         struct timespec tomono;
367         s64 nsec;
368         unsigned int seq;
369
370         WARN_ON(timekeeping_suspended);
371
372         do {
373                 seq = read_seqcount_begin(&timekeeper_seq);
374                 ts->tv_sec = tk->xtime_sec;
375                 nsec = timekeeping_get_ns(tk);
376                 tomono = tk->wall_to_monotonic;
377
378         } while (read_seqcount_retry(&timekeeper_seq, seq));
379
380         ts->tv_sec += tomono.tv_sec;
381         ts->tv_nsec = 0;
382         timespec_add_ns(ts, nsec + tomono.tv_nsec);
383 }
384 EXPORT_SYMBOL_GPL(ktime_get_ts);
385
386
387 /**
388  * timekeeping_clocktai - Returns the TAI time of day in a timespec
389  * @ts:         pointer to the timespec to be set
390  *
391  * Returns the time of day in a timespec.
392  */
393 void timekeeping_clocktai(struct timespec *ts)
394 {
395         struct timekeeper *tk = &timekeeper;
396         unsigned long seq;
397         u64 nsecs;
398
399         WARN_ON(timekeeping_suspended);
400
401         do {
402                 seq = read_seqcount_begin(&timekeeper_seq);
403
404                 ts->tv_sec = tk->xtime_sec + tk->tai_offset;
405                 nsecs = timekeeping_get_ns(tk);
406
407         } while (read_seqcount_retry(&timekeeper_seq, seq));
408
409         ts->tv_nsec = 0;
410         timespec_add_ns(ts, nsecs);
411
412 }
413 EXPORT_SYMBOL(timekeeping_clocktai);
414
415
416 /**
417  * ktime_get_clocktai - Returns the TAI time of day in a ktime
418  *
419  * Returns the time of day in a ktime.
420  */
421 ktime_t ktime_get_clocktai(void)
422 {
423         struct timespec ts;
424
425         timekeeping_clocktai(&ts);
426         return timespec_to_ktime(ts);
427 }
428 EXPORT_SYMBOL(ktime_get_clocktai);
429
430 #ifdef CONFIG_NTP_PPS
431
432 /**
433  * getnstime_raw_and_real - get day and raw monotonic time in timespec format
434  * @ts_raw:     pointer to the timespec to be set to raw monotonic time
435  * @ts_real:    pointer to the timespec to be set to the time of day
436  *
437  * This function reads both the time of day and raw monotonic time at the
438  * same time atomically and stores the resulting timestamps in timespec
439  * format.
440  */
441 void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
442 {
443         struct timekeeper *tk = &timekeeper;
444         unsigned long seq;
445         s64 nsecs_raw, nsecs_real;
446
447         WARN_ON_ONCE(timekeeping_suspended);
448
449         do {
450                 seq = read_seqcount_begin(&timekeeper_seq);
451
452                 *ts_raw = tk->raw_time;
453                 ts_real->tv_sec = tk->xtime_sec;
454                 ts_real->tv_nsec = 0;
455
456                 nsecs_raw = timekeeping_get_ns_raw(tk);
457                 nsecs_real = timekeeping_get_ns(tk);
458
459         } while (read_seqcount_retry(&timekeeper_seq, seq));
460
461         timespec_add_ns(ts_raw, nsecs_raw);
462         timespec_add_ns(ts_real, nsecs_real);
463 }
464 EXPORT_SYMBOL(getnstime_raw_and_real);
465
466 #endif /* CONFIG_NTP_PPS */
467
468 /**
469  * do_gettimeofday - Returns the time of day in a timeval
470  * @tv:         pointer to the timeval to be set
471  *
472  * NOTE: Users should be converted to using getnstimeofday()
473  */
474 void do_gettimeofday(struct timeval *tv)
475 {
476         struct timespec now;
477
478         getnstimeofday(&now);
479         tv->tv_sec = now.tv_sec;
480         tv->tv_usec = now.tv_nsec/1000;
481 }
482 EXPORT_SYMBOL(do_gettimeofday);
483
484 /**
485  * do_settimeofday - Sets the time of day
486  * @tv:         pointer to the timespec variable containing the new time
487  *
488  * Sets the time of day to the new time and update NTP and notify hrtimers
489  */
490 int do_settimeofday(const struct timespec *tv)
491 {
492         struct timekeeper *tk = &timekeeper;
493         struct timespec ts_delta, xt;
494         unsigned long flags;
495
496         if (!timespec_valid_strict(tv))
497                 return -EINVAL;
498
499         raw_spin_lock_irqsave(&timekeeper_lock, flags);
500         write_seqcount_begin(&timekeeper_seq);
501
502         timekeeping_forward_now(tk);
503
504         xt = tk_xtime(tk);
505         ts_delta.tv_sec = tv->tv_sec - xt.tv_sec;
506         ts_delta.tv_nsec = tv->tv_nsec - xt.tv_nsec;
507
508         tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, ts_delta));
509
510         tk_set_xtime(tk, tv);
511
512         timekeeping_update(tk, true, true);
513
514         write_seqcount_end(&timekeeper_seq);
515         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
516
517         /* signal hrtimers about time change */
518         clock_was_set();
519
520         return 0;
521 }
522 EXPORT_SYMBOL(do_settimeofday);
523
524 /**
525  * timekeeping_inject_offset - Adds or subtracts from the current time.
526  * @tv:         pointer to the timespec variable containing the offset
527  *
528  * Adds or subtracts an offset value from the current time.
529  */
530 int timekeeping_inject_offset(struct timespec *ts)
531 {
532         struct timekeeper *tk = &timekeeper;
533         unsigned long flags;
534         struct timespec tmp;
535         int ret = 0;
536
537         if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
538                 return -EINVAL;
539
540         raw_spin_lock_irqsave(&timekeeper_lock, flags);
541         write_seqcount_begin(&timekeeper_seq);
542
543         timekeeping_forward_now(tk);
544
545         /* Make sure the proposed value is valid */
546         tmp = timespec_add(tk_xtime(tk),  *ts);
547         if (!timespec_valid_strict(&tmp)) {
548                 ret = -EINVAL;
549                 goto error;
550         }
551
552         tk_xtime_add(tk, ts);
553         tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *ts));
554
555 error: /* even if we error out, we forwarded the time, so call update */
556         timekeeping_update(tk, true, true);
557
558         write_seqcount_end(&timekeeper_seq);
559         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
560
561         /* signal hrtimers about time change */
562         clock_was_set();
563
564         return ret;
565 }
566 EXPORT_SYMBOL(timekeeping_inject_offset);
567
568
569 /**
570  * timekeeping_get_tai_offset - Returns current TAI offset from UTC
571  *
572  */
573 s32 timekeeping_get_tai_offset(void)
574 {
575         struct timekeeper *tk = &timekeeper;
576         unsigned int seq;
577         s32 ret;
578
579         do {
580                 seq = read_seqcount_begin(&timekeeper_seq);
581                 ret = tk->tai_offset;
582         } while (read_seqcount_retry(&timekeeper_seq, seq));
583
584         return ret;
585 }
586
587 /**
588  * __timekeeping_set_tai_offset - Lock free worker function
589  *
590  */
591 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
592 {
593         tk->tai_offset = tai_offset;
594         tk->offs_tai = ktime_sub(tk->offs_real, ktime_set(tai_offset, 0));
595 }
596
597 /**
598  * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
599  *
600  */
601 void timekeeping_set_tai_offset(s32 tai_offset)
602 {
603         struct timekeeper *tk = &timekeeper;
604         unsigned long flags;
605
606         raw_spin_lock_irqsave(&timekeeper_lock, flags);
607         write_seqcount_begin(&timekeeper_seq);
608         __timekeeping_set_tai_offset(tk, tai_offset);
609         write_seqcount_end(&timekeeper_seq);
610         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
611         clock_was_set();
612 }
613
614 /**
615  * change_clocksource - Swaps clocksources if a new one is available
616  *
617  * Accumulates current time interval and initializes new clocksource
618  */
619 static int change_clocksource(void *data)
620 {
621         struct timekeeper *tk = &timekeeper;
622         struct clocksource *new, *old;
623         unsigned long flags;
624
625         new = (struct clocksource *) data;
626
627         raw_spin_lock_irqsave(&timekeeper_lock, flags);
628         write_seqcount_begin(&timekeeper_seq);
629
630         timekeeping_forward_now(tk);
631         /*
632          * If the cs is in module, get a module reference. Succeeds
633          * for built-in code (owner == NULL) as well.
634          */
635         if (try_module_get(new->owner)) {
636                 if (!new->enable || new->enable(new) == 0) {
637                         old = tk->clock;
638                         tk_setup_internals(tk, new);
639                         if (old->disable)
640                                 old->disable(old);
641                         module_put(old->owner);
642                 } else {
643                         module_put(new->owner);
644                 }
645         }
646         timekeeping_update(tk, true, true);
647
648         write_seqcount_end(&timekeeper_seq);
649         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
650
651         return 0;
652 }
653
654 /**
655  * timekeeping_notify - Install a new clock source
656  * @clock:              pointer to the clock source
657  *
658  * This function is called from clocksource.c after a new, better clock
659  * source has been registered. The caller holds the clocksource_mutex.
660  */
661 int timekeeping_notify(struct clocksource *clock)
662 {
663         struct timekeeper *tk = &timekeeper;
664
665         if (tk->clock == clock)
666                 return 0;
667         stop_machine(change_clocksource, clock, NULL);
668         tick_clock_notify();
669         return tk->clock == clock ? 0 : -1;
670 }
671
672 /**
673  * ktime_get_real - get the real (wall-) time in ktime_t format
674  *
675  * returns the time in ktime_t format
676  */
677 ktime_t ktime_get_real(void)
678 {
679         struct timespec now;
680
681         getnstimeofday(&now);
682
683         return timespec_to_ktime(now);
684 }
685 EXPORT_SYMBOL_GPL(ktime_get_real);
686
687 /**
688  * getrawmonotonic - Returns the raw monotonic time in a timespec
689  * @ts:         pointer to the timespec to be set
690  *
691  * Returns the raw monotonic time (completely un-modified by ntp)
692  */
693 void getrawmonotonic(struct timespec *ts)
694 {
695         struct timekeeper *tk = &timekeeper;
696         unsigned long seq;
697         s64 nsecs;
698
699         do {
700                 seq = read_seqcount_begin(&timekeeper_seq);
701                 nsecs = timekeeping_get_ns_raw(tk);
702                 *ts = tk->raw_time;
703
704         } while (read_seqcount_retry(&timekeeper_seq, seq));
705
706         timespec_add_ns(ts, nsecs);
707 }
708 EXPORT_SYMBOL(getrawmonotonic);
709
710 /**
711  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
712  */
713 int timekeeping_valid_for_hres(void)
714 {
715         struct timekeeper *tk = &timekeeper;
716         unsigned long seq;
717         int ret;
718
719         do {
720                 seq = read_seqcount_begin(&timekeeper_seq);
721
722                 ret = tk->clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
723
724         } while (read_seqcount_retry(&timekeeper_seq, seq));
725
726         return ret;
727 }
728
729 /**
730  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
731  */
732 u64 timekeeping_max_deferment(void)
733 {
734         struct timekeeper *tk = &timekeeper;
735         unsigned long seq;
736         u64 ret;
737
738         do {
739                 seq = read_seqcount_begin(&timekeeper_seq);
740
741                 ret = tk->clock->max_idle_ns;
742
743         } while (read_seqcount_retry(&timekeeper_seq, seq));
744
745         return ret;
746 }
747
748 /**
749  * read_persistent_clock -  Return time from the persistent clock.
750  *
751  * Weak dummy function for arches that do not yet support it.
752  * Reads the time from the battery backed persistent clock.
753  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
754  *
755  *  XXX - Do be sure to remove it once all arches implement it.
756  */
757 void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
758 {
759         ts->tv_sec = 0;
760         ts->tv_nsec = 0;
761 }
762
763 /**
764  * read_boot_clock -  Return time of the system start.
765  *
766  * Weak dummy function for arches that do not yet support it.
767  * Function to read the exact time the system has been started.
768  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
769  *
770  *  XXX - Do be sure to remove it once all arches implement it.
771  */
772 void __attribute__((weak)) read_boot_clock(struct timespec *ts)
773 {
774         ts->tv_sec = 0;
775         ts->tv_nsec = 0;
776 }
777
778 /*
779  * timekeeping_init - Initializes the clocksource and common timekeeping values
780  */
781 void __init timekeeping_init(void)
782 {
783         struct timekeeper *tk = &timekeeper;
784         struct clocksource *clock;
785         unsigned long flags;
786         struct timespec now, boot, tmp;
787
788         read_persistent_clock(&now);
789
790         if (!timespec_valid_strict(&now)) {
791                 pr_warn("WARNING: Persistent clock returned invalid value!\n"
792                         "         Check your CMOS/BIOS settings.\n");
793                 now.tv_sec = 0;
794                 now.tv_nsec = 0;
795         } else if (now.tv_sec || now.tv_nsec)
796                 persistent_clock_exist = true;
797
798         read_boot_clock(&boot);
799         if (!timespec_valid_strict(&boot)) {
800                 pr_warn("WARNING: Boot clock returned invalid value!\n"
801                         "         Check your CMOS/BIOS settings.\n");
802                 boot.tv_sec = 0;
803                 boot.tv_nsec = 0;
804         }
805
806         raw_spin_lock_irqsave(&timekeeper_lock, flags);
807         write_seqcount_begin(&timekeeper_seq);
808         ntp_init();
809
810         clock = clocksource_default_clock();
811         if (clock->enable)
812                 clock->enable(clock);
813         tk_setup_internals(tk, clock);
814
815         tk_set_xtime(tk, &now);
816         tk->raw_time.tv_sec = 0;
817         tk->raw_time.tv_nsec = 0;
818         if (boot.tv_sec == 0 && boot.tv_nsec == 0)
819                 boot = tk_xtime(tk);
820
821         set_normalized_timespec(&tmp, -boot.tv_sec, -boot.tv_nsec);
822         tk_set_wall_to_mono(tk, tmp);
823
824         tmp.tv_sec = 0;
825         tmp.tv_nsec = 0;
826         tk_set_sleep_time(tk, tmp);
827
828         memcpy(&shadow_timekeeper, &timekeeper, sizeof(timekeeper));
829
830         write_seqcount_end(&timekeeper_seq);
831         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
832 }
833
834 /* time in seconds when suspend began */
835 static struct timespec timekeeping_suspend_time;
836
837 /**
838  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
839  * @delta: pointer to a timespec delta value
840  *
841  * Takes a timespec offset measuring a suspend interval and properly
842  * adds the sleep offset to the timekeeping variables.
843  */
844 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
845                                                         struct timespec *delta)
846 {
847         if (!timespec_valid_strict(delta)) {
848                 printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
849                                         "sleep delta value!\n");
850                 return;
851         }
852         tk_xtime_add(tk, delta);
853         tk_set_wall_to_mono(tk, timespec_sub(tk->wall_to_monotonic, *delta));
854         tk_set_sleep_time(tk, timespec_add(tk->total_sleep_time, *delta));
855         tk_debug_account_sleep_time(delta);
856 }
857
858 /**
859  * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
860  * @delta: pointer to a timespec delta value
861  *
862  * This hook is for architectures that cannot support read_persistent_clock
863  * because their RTC/persistent clock is only accessible when irqs are enabled.
864  *
865  * This function should only be called by rtc_resume(), and allows
866  * a suspend offset to be injected into the timekeeping values.
867  */
868 void timekeeping_inject_sleeptime(struct timespec *delta)
869 {
870         struct timekeeper *tk = &timekeeper;
871         unsigned long flags;
872
873         /*
874          * Make sure we don't set the clock twice, as timekeeping_resume()
875          * already did it
876          */
877         if (has_persistent_clock())
878                 return;
879
880         raw_spin_lock_irqsave(&timekeeper_lock, flags);
881         write_seqcount_begin(&timekeeper_seq);
882
883         timekeeping_forward_now(tk);
884
885         __timekeeping_inject_sleeptime(tk, delta);
886
887         timekeeping_update(tk, true, true);
888
889         write_seqcount_end(&timekeeper_seq);
890         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
891
892         /* signal hrtimers about time change */
893         clock_was_set();
894 }
895
896 /**
897  * timekeeping_resume - Resumes the generic timekeeping subsystem.
898  *
899  * This is for the generic clocksource timekeeping.
900  * xtime/wall_to_monotonic/jiffies/etc are
901  * still managed by arch specific suspend/resume code.
902  */
903 static void timekeeping_resume(void)
904 {
905         struct timekeeper *tk = &timekeeper;
906         struct clocksource *clock = tk->clock;
907         unsigned long flags;
908         struct timespec ts_new, ts_delta;
909         cycle_t cycle_now, cycle_delta;
910         bool suspendtime_found = false;
911
912         read_persistent_clock(&ts_new);
913
914         clockevents_resume();
915         clocksource_resume();
916
917         raw_spin_lock_irqsave(&timekeeper_lock, flags);
918         write_seqcount_begin(&timekeeper_seq);
919
920         /*
921          * After system resumes, we need to calculate the suspended time and
922          * compensate it for the OS time. There are 3 sources that could be
923          * used: Nonstop clocksource during suspend, persistent clock and rtc
924          * device.
925          *
926          * One specific platform may have 1 or 2 or all of them, and the
927          * preference will be:
928          *      suspend-nonstop clocksource -> persistent clock -> rtc
929          * The less preferred source will only be tried if there is no better
930          * usable source. The rtc part is handled separately in rtc core code.
931          */
932         cycle_now = clock->read(clock);
933         if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
934                 cycle_now > clock->cycle_last) {
935                 u64 num, max = ULLONG_MAX;
936                 u32 mult = clock->mult;
937                 u32 shift = clock->shift;
938                 s64 nsec = 0;
939
940                 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
941
942                 /*
943                  * "cycle_delta * mutl" may cause 64 bits overflow, if the
944                  * suspended time is too long. In that case we need do the
945                  * 64 bits math carefully
946                  */
947                 do_div(max, mult);
948                 if (cycle_delta > max) {
949                         num = div64_u64(cycle_delta, max);
950                         nsec = (((u64) max * mult) >> shift) * num;
951                         cycle_delta -= num * max;
952                 }
953                 nsec += ((u64) cycle_delta * mult) >> shift;
954
955                 ts_delta = ns_to_timespec(nsec);
956                 suspendtime_found = true;
957         } else if (timespec_compare(&ts_new, &timekeeping_suspend_time) > 0) {
958                 ts_delta = timespec_sub(ts_new, timekeeping_suspend_time);
959                 suspendtime_found = true;
960         }
961
962         if (suspendtime_found)
963                 __timekeeping_inject_sleeptime(tk, &ts_delta);
964
965         /* Re-base the last cycle value */
966         tk->cycle_last = clock->cycle_last = cycle_now;
967         tk->ntp_error = 0;
968         timekeeping_suspended = 0;
969         timekeeping_update(tk, false, true);
970         write_seqcount_end(&timekeeper_seq);
971         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
972
973         touch_softlockup_watchdog();
974
975         clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
976
977         /* Resume hrtimers */
978         hrtimers_resume();
979 }
980
981 static int timekeeping_suspend(void)
982 {
983         struct timekeeper *tk = &timekeeper;
984         unsigned long flags;
985         struct timespec         delta, delta_delta;
986         static struct timespec  old_delta;
987
988         read_persistent_clock(&timekeeping_suspend_time);
989
990         raw_spin_lock_irqsave(&timekeeper_lock, flags);
991         write_seqcount_begin(&timekeeper_seq);
992         timekeeping_forward_now(tk);
993         timekeeping_suspended = 1;
994
995         /*
996          * To avoid drift caused by repeated suspend/resumes,
997          * which each can add ~1 second drift error,
998          * try to compensate so the difference in system time
999          * and persistent_clock time stays close to constant.
1000          */
1001         delta = timespec_sub(tk_xtime(tk), timekeeping_suspend_time);
1002         delta_delta = timespec_sub(delta, old_delta);
1003         if (abs(delta_delta.tv_sec)  >= 2) {
1004                 /*
1005                  * if delta_delta is too large, assume time correction
1006                  * has occured and set old_delta to the current delta.
1007                  */
1008                 old_delta = delta;
1009         } else {
1010                 /* Otherwise try to adjust old_system to compensate */
1011                 timekeeping_suspend_time =
1012                         timespec_add(timekeeping_suspend_time, delta_delta);
1013         }
1014         write_seqcount_end(&timekeeper_seq);
1015         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1016
1017         clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
1018         clocksource_suspend();
1019         clockevents_suspend();
1020
1021         return 0;
1022 }
1023
1024 /* sysfs resume/suspend bits for timekeeping */
1025 static struct syscore_ops timekeeping_syscore_ops = {
1026         .resume         = timekeeping_resume,
1027         .suspend        = timekeeping_suspend,
1028 };
1029
1030 static int __init timekeeping_init_ops(void)
1031 {
1032         register_syscore_ops(&timekeeping_syscore_ops);
1033         return 0;
1034 }
1035
1036 device_initcall(timekeeping_init_ops);
1037
1038 /*
1039  * If the error is already larger, we look ahead even further
1040  * to compensate for late or lost adjustments.
1041  */
1042 static __always_inline int timekeeping_bigadjust(struct timekeeper *tk,
1043                                                  s64 error, s64 *interval,
1044                                                  s64 *offset)
1045 {
1046         s64 tick_error, i;
1047         u32 look_ahead, adj;
1048         s32 error2, mult;
1049
1050         /*
1051          * Use the current error value to determine how much to look ahead.
1052          * The larger the error the slower we adjust for it to avoid problems
1053          * with losing too many ticks, otherwise we would overadjust and
1054          * produce an even larger error.  The smaller the adjustment the
1055          * faster we try to adjust for it, as lost ticks can do less harm
1056          * here.  This is tuned so that an error of about 1 msec is adjusted
1057          * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
1058          */
1059         error2 = tk->ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
1060         error2 = abs(error2);
1061         for (look_ahead = 0; error2 > 0; look_ahead++)
1062                 error2 >>= 2;
1063
1064         /*
1065          * Now calculate the error in (1 << look_ahead) ticks, but first
1066          * remove the single look ahead already included in the error.
1067          */
1068         tick_error = ntp_tick_length() >> (tk->ntp_error_shift + 1);
1069         tick_error -= tk->xtime_interval >> 1;
1070         error = ((error - tick_error) >> look_ahead) + tick_error;
1071
1072         /* Finally calculate the adjustment shift value.  */
1073         i = *interval;
1074         mult = 1;
1075         if (error < 0) {
1076                 error = -error;
1077                 *interval = -*interval;
1078                 *offset = -*offset;
1079                 mult = -1;
1080         }
1081         for (adj = 0; error > i; adj++)
1082                 error >>= 1;
1083
1084         *interval <<= adj;
1085         *offset <<= adj;
1086         return mult << adj;
1087 }
1088
1089 /*
1090  * Adjust the multiplier to reduce the error value,
1091  * this is optimized for the most common adjustments of -1,0,1,
1092  * for other values we can do a bit more work.
1093  */
1094 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1095 {
1096         s64 error, interval = tk->cycle_interval;
1097         int adj;
1098
1099         /*
1100          * The point of this is to check if the error is greater than half
1101          * an interval.
1102          *
1103          * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
1104          *
1105          * Note we subtract one in the shift, so that error is really error*2.
1106          * This "saves" dividing(shifting) interval twice, but keeps the
1107          * (error > interval) comparison as still measuring if error is
1108          * larger than half an interval.
1109          *
1110          * Note: It does not "save" on aggravation when reading the code.
1111          */
1112         error = tk->ntp_error >> (tk->ntp_error_shift - 1);
1113         if (error > interval) {
1114                 /*
1115                  * We now divide error by 4(via shift), which checks if
1116                  * the error is greater than twice the interval.
1117                  * If it is greater, we need a bigadjust, if its smaller,
1118                  * we can adjust by 1.
1119                  */
1120                 error >>= 2;
1121                 /*
1122                  * XXX - In update_wall_time, we round up to the next
1123                  * nanosecond, and store the amount rounded up into
1124                  * the error. This causes the likely below to be unlikely.
1125                  *
1126                  * The proper fix is to avoid rounding up by using
1127                  * the high precision tk->xtime_nsec instead of
1128                  * xtime.tv_nsec everywhere. Fixing this will take some
1129                  * time.
1130                  */
1131                 if (likely(error <= interval))
1132                         adj = 1;
1133                 else
1134                         adj = timekeeping_bigadjust(tk, error, &interval, &offset);
1135         } else {
1136                 if (error < -interval) {
1137                         /* See comment above, this is just switched for the negative */
1138                         error >>= 2;
1139                         if (likely(error >= -interval)) {
1140                                 adj = -1;
1141                                 interval = -interval;
1142                                 offset = -offset;
1143                         } else {
1144                                 adj = timekeeping_bigadjust(tk, error, &interval, &offset);
1145                         }
1146                 } else {
1147                         goto out_adjust;
1148                 }
1149         }
1150
1151         if (unlikely(tk->clock->maxadj &&
1152                 (tk->mult + adj > tk->clock->mult + tk->clock->maxadj))) {
1153                 printk_once(KERN_WARNING
1154                         "Adjusting %s more than 11%% (%ld vs %ld)\n",
1155                         tk->clock->name, (long)tk->mult + adj,
1156                         (long)tk->clock->mult + tk->clock->maxadj);
1157         }
1158         /*
1159          * So the following can be confusing.
1160          *
1161          * To keep things simple, lets assume adj == 1 for now.
1162          *
1163          * When adj != 1, remember that the interval and offset values
1164          * have been appropriately scaled so the math is the same.
1165          *
1166          * The basic idea here is that we're increasing the multiplier
1167          * by one, this causes the xtime_interval to be incremented by
1168          * one cycle_interval. This is because:
1169          *      xtime_interval = cycle_interval * mult
1170          * So if mult is being incremented by one:
1171          *      xtime_interval = cycle_interval * (mult + 1)
1172          * Its the same as:
1173          *      xtime_interval = (cycle_interval * mult) + cycle_interval
1174          * Which can be shortened to:
1175          *      xtime_interval += cycle_interval
1176          *
1177          * So offset stores the non-accumulated cycles. Thus the current
1178          * time (in shifted nanoseconds) is:
1179          *      now = (offset * adj) + xtime_nsec
1180          * Now, even though we're adjusting the clock frequency, we have
1181          * to keep time consistent. In other words, we can't jump back
1182          * in time, and we also want to avoid jumping forward in time.
1183          *
1184          * So given the same offset value, we need the time to be the same
1185          * both before and after the freq adjustment.
1186          *      now = (offset * adj_1) + xtime_nsec_1
1187          *      now = (offset * adj_2) + xtime_nsec_2
1188          * So:
1189          *      (offset * adj_1) + xtime_nsec_1 =
1190          *              (offset * adj_2) + xtime_nsec_2
1191          * And we know:
1192          *      adj_2 = adj_1 + 1
1193          * So:
1194          *      (offset * adj_1) + xtime_nsec_1 =
1195          *              (offset * (adj_1+1)) + xtime_nsec_2
1196          *      (offset * adj_1) + xtime_nsec_1 =
1197          *              (offset * adj_1) + offset + xtime_nsec_2
1198          * Canceling the sides:
1199          *      xtime_nsec_1 = offset + xtime_nsec_2
1200          * Which gives us:
1201          *      xtime_nsec_2 = xtime_nsec_1 - offset
1202          * Which simplfies to:
1203          *      xtime_nsec -= offset
1204          *
1205          * XXX - TODO: Doc ntp_error calculation.
1206          */
1207         tk->mult += adj;
1208         tk->xtime_interval += interval;
1209         tk->xtime_nsec -= offset;
1210         tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1211
1212 out_adjust:
1213         /*
1214          * It may be possible that when we entered this function, xtime_nsec
1215          * was very small.  Further, if we're slightly speeding the clocksource
1216          * in the code above, its possible the required corrective factor to
1217          * xtime_nsec could cause it to underflow.
1218          *
1219          * Now, since we already accumulated the second, cannot simply roll
1220          * the accumulated second back, since the NTP subsystem has been
1221          * notified via second_overflow. So instead we push xtime_nsec forward
1222          * by the amount we underflowed, and add that amount into the error.
1223          *
1224          * We'll correct this error next time through this function, when
1225          * xtime_nsec is not as small.
1226          */
1227         if (unlikely((s64)tk->xtime_nsec < 0)) {
1228                 s64 neg = -(s64)tk->xtime_nsec;
1229                 tk->xtime_nsec = 0;
1230                 tk->ntp_error += neg << tk->ntp_error_shift;
1231         }
1232
1233 }
1234
1235 /**
1236  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
1237  *
1238  * Helper function that accumulates a the nsecs greater then a second
1239  * from the xtime_nsec field to the xtime_secs field.
1240  * It also calls into the NTP code to handle leapsecond processing.
1241  *
1242  */
1243 static inline void accumulate_nsecs_to_secs(struct timekeeper *tk)
1244 {
1245         u64 nsecps = (u64)NSEC_PER_SEC << tk->shift;
1246
1247         while (tk->xtime_nsec >= nsecps) {
1248                 int leap;
1249
1250                 tk->xtime_nsec -= nsecps;
1251                 tk->xtime_sec++;
1252
1253                 /* Figure out if its a leap sec and apply if needed */
1254                 leap = second_overflow(tk->xtime_sec);
1255                 if (unlikely(leap)) {
1256                         struct timespec ts;
1257
1258                         tk->xtime_sec += leap;
1259
1260                         ts.tv_sec = leap;
1261                         ts.tv_nsec = 0;
1262                         tk_set_wall_to_mono(tk,
1263                                 timespec_sub(tk->wall_to_monotonic, ts));
1264
1265                         __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1266
1267                         clock_was_set_delayed();
1268                 }
1269         }
1270 }
1271
1272 /**
1273  * logarithmic_accumulation - shifted accumulation of cycles
1274  *
1275  * This functions accumulates a shifted interval of cycles into
1276  * into a shifted interval nanoseconds. Allows for O(log) accumulation
1277  * loop.
1278  *
1279  * Returns the unconsumed cycles.
1280  */
1281 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
1282                                                 u32 shift)
1283 {
1284         cycle_t interval = tk->cycle_interval << shift;
1285         u64 raw_nsecs;
1286
1287         /* If the offset is smaller then a shifted interval, do nothing */
1288         if (offset < interval)
1289                 return offset;
1290
1291         /* Accumulate one shifted interval */
1292         offset -= interval;
1293         tk->cycle_last += interval;
1294
1295         tk->xtime_nsec += tk->xtime_interval << shift;
1296         accumulate_nsecs_to_secs(tk);
1297
1298         /* Accumulate raw time */
1299         raw_nsecs = (u64)tk->raw_interval << shift;
1300         raw_nsecs += tk->raw_time.tv_nsec;
1301         if (raw_nsecs >= NSEC_PER_SEC) {
1302                 u64 raw_secs = raw_nsecs;
1303                 raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
1304                 tk->raw_time.tv_sec += raw_secs;
1305         }
1306         tk->raw_time.tv_nsec = raw_nsecs;
1307
1308         /* Accumulate error between NTP and clock interval */
1309         tk->ntp_error += ntp_tick_length() << shift;
1310         tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1311                                                 (tk->ntp_error_shift + shift);
1312
1313         return offset;
1314 }
1315
1316 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
1317 static inline void old_vsyscall_fixup(struct timekeeper *tk)
1318 {
1319         s64 remainder;
1320
1321         /*
1322         * Store only full nanoseconds into xtime_nsec after rounding
1323         * it up and add the remainder to the error difference.
1324         * XXX - This is necessary to avoid small 1ns inconsistnecies caused
1325         * by truncating the remainder in vsyscalls. However, it causes
1326         * additional work to be done in timekeeping_adjust(). Once
1327         * the vsyscall implementations are converted to use xtime_nsec
1328         * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
1329         * users are removed, this can be killed.
1330         */
1331         remainder = tk->xtime_nsec & ((1ULL << tk->shift) - 1);
1332         tk->xtime_nsec -= remainder;
1333         tk->xtime_nsec += 1ULL << tk->shift;
1334         tk->ntp_error += remainder << tk->ntp_error_shift;
1335
1336 }
1337 #else
1338 #define old_vsyscall_fixup(tk)
1339 #endif
1340
1341
1342
1343 /**
1344  * update_wall_time - Uses the current clocksource to increment the wall time
1345  *
1346  */
1347 static void update_wall_time(void)
1348 {
1349         struct clocksource *clock;
1350         struct timekeeper *real_tk = &timekeeper;
1351         struct timekeeper *tk = &shadow_timekeeper;
1352         cycle_t offset;
1353         int shift = 0, maxshift;
1354         unsigned long flags;
1355
1356         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1357
1358         /* Make sure we're fully resumed: */
1359         if (unlikely(timekeeping_suspended))
1360                 goto out;
1361
1362         clock = real_tk->clock;
1363
1364 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1365         offset = real_tk->cycle_interval;
1366 #else
1367         offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
1368 #endif
1369
1370         /* Check if there's really nothing to do */
1371         if (offset < real_tk->cycle_interval)
1372                 goto out;
1373
1374         /*
1375          * With NO_HZ we may have to accumulate many cycle_intervals
1376          * (think "ticks") worth of time at once. To do this efficiently,
1377          * we calculate the largest doubling multiple of cycle_intervals
1378          * that is smaller than the offset.  We then accumulate that
1379          * chunk in one go, and then try to consume the next smaller
1380          * doubled multiple.
1381          */
1382         shift = ilog2(offset) - ilog2(tk->cycle_interval);
1383         shift = max(0, shift);
1384         /* Bound shift to one less than what overflows tick_length */
1385         maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1386         shift = min(shift, maxshift);
1387         while (offset >= tk->cycle_interval) {
1388                 offset = logarithmic_accumulation(tk, offset, shift);
1389                 if (offset < tk->cycle_interval<<shift)
1390                         shift--;
1391         }
1392
1393         /* correct the clock when NTP error is too big */
1394         timekeeping_adjust(tk, offset);
1395
1396         /*
1397          * XXX This can be killed once everyone converts
1398          * to the new update_vsyscall.
1399          */
1400         old_vsyscall_fixup(tk);
1401
1402         /*
1403          * Finally, make sure that after the rounding
1404          * xtime_nsec isn't larger than NSEC_PER_SEC
1405          */
1406         accumulate_nsecs_to_secs(tk);
1407
1408         write_seqcount_begin(&timekeeper_seq);
1409         /* Update clock->cycle_last with the new value */
1410         clock->cycle_last = tk->cycle_last;
1411         /*
1412          * Update the real timekeeper.
1413          *
1414          * We could avoid this memcpy by switching pointers, but that
1415          * requires changes to all other timekeeper usage sites as
1416          * well, i.e. move the timekeeper pointer getter into the
1417          * spinlocked/seqcount protected sections. And we trade this
1418          * memcpy under the timekeeper_seq against one before we start
1419          * updating.
1420          */
1421         memcpy(real_tk, tk, sizeof(*tk));
1422         timekeeping_update(real_tk, false, false);
1423         write_seqcount_end(&timekeeper_seq);
1424 out:
1425         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1426 }
1427
1428 /**
1429  * getboottime - Return the real time of system boot.
1430  * @ts:         pointer to the timespec to be set
1431  *
1432  * Returns the wall-time of boot in a timespec.
1433  *
1434  * This is based on the wall_to_monotonic offset and the total suspend
1435  * time. Calls to settimeofday will affect the value returned (which
1436  * basically means that however wrong your real time clock is at boot time,
1437  * you get the right time here).
1438  */
1439 void getboottime(struct timespec *ts)
1440 {
1441         struct timekeeper *tk = &timekeeper;
1442         struct timespec boottime = {
1443                 .tv_sec = tk->wall_to_monotonic.tv_sec +
1444                                 tk->total_sleep_time.tv_sec,
1445                 .tv_nsec = tk->wall_to_monotonic.tv_nsec +
1446                                 tk->total_sleep_time.tv_nsec
1447         };
1448
1449         set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
1450 }
1451 EXPORT_SYMBOL_GPL(getboottime);
1452
1453 /**
1454  * get_monotonic_boottime - Returns monotonic time since boot
1455  * @ts:         pointer to the timespec to be set
1456  *
1457  * Returns the monotonic time since boot in a timespec.
1458  *
1459  * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
1460  * includes the time spent in suspend.
1461  */
1462 void get_monotonic_boottime(struct timespec *ts)
1463 {
1464         struct timekeeper *tk = &timekeeper;
1465         struct timespec tomono, sleep;
1466         s64 nsec;
1467         unsigned int seq;
1468
1469         WARN_ON(timekeeping_suspended);
1470
1471         do {
1472                 seq = read_seqcount_begin(&timekeeper_seq);
1473                 ts->tv_sec = tk->xtime_sec;
1474                 nsec = timekeeping_get_ns(tk);
1475                 tomono = tk->wall_to_monotonic;
1476                 sleep = tk->total_sleep_time;
1477
1478         } while (read_seqcount_retry(&timekeeper_seq, seq));
1479
1480         ts->tv_sec += tomono.tv_sec + sleep.tv_sec;
1481         ts->tv_nsec = 0;
1482         timespec_add_ns(ts, nsec + tomono.tv_nsec + sleep.tv_nsec);
1483 }
1484 EXPORT_SYMBOL_GPL(get_monotonic_boottime);
1485
1486 /**
1487  * ktime_get_boottime - Returns monotonic time since boot in a ktime
1488  *
1489  * Returns the monotonic time since boot in a ktime
1490  *
1491  * This is similar to CLOCK_MONTONIC/ktime_get, but also
1492  * includes the time spent in suspend.
1493  */
1494 ktime_t ktime_get_boottime(void)
1495 {
1496         struct timespec ts;
1497
1498         get_monotonic_boottime(&ts);
1499         return timespec_to_ktime(ts);
1500 }
1501 EXPORT_SYMBOL_GPL(ktime_get_boottime);
1502
1503 /**
1504  * monotonic_to_bootbased - Convert the monotonic time to boot based.
1505  * @ts:         pointer to the timespec to be converted
1506  */
1507 void monotonic_to_bootbased(struct timespec *ts)
1508 {
1509         struct timekeeper *tk = &timekeeper;
1510
1511         *ts = timespec_add(*ts, tk->total_sleep_time);
1512 }
1513 EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
1514
1515 unsigned long get_seconds(void)
1516 {
1517         struct timekeeper *tk = &timekeeper;
1518
1519         return tk->xtime_sec;
1520 }
1521 EXPORT_SYMBOL(get_seconds);
1522
1523 struct timespec __current_kernel_time(void)
1524 {
1525         struct timekeeper *tk = &timekeeper;
1526
1527         return tk_xtime(tk);
1528 }
1529
1530 struct timespec current_kernel_time(void)
1531 {
1532         struct timekeeper *tk = &timekeeper;
1533         struct timespec now;
1534         unsigned long seq;
1535
1536         do {
1537                 seq = read_seqcount_begin(&timekeeper_seq);
1538
1539                 now = tk_xtime(tk);
1540         } while (read_seqcount_retry(&timekeeper_seq, seq));
1541
1542         return now;
1543 }
1544 EXPORT_SYMBOL(current_kernel_time);
1545
1546 struct timespec get_monotonic_coarse(void)
1547 {
1548         struct timekeeper *tk = &timekeeper;
1549         struct timespec now, mono;
1550         unsigned long seq;
1551
1552         do {
1553                 seq = read_seqcount_begin(&timekeeper_seq);
1554
1555                 now = tk_xtime(tk);
1556                 mono = tk->wall_to_monotonic;
1557         } while (read_seqcount_retry(&timekeeper_seq, seq));
1558
1559         set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
1560                                 now.tv_nsec + mono.tv_nsec);
1561         return now;
1562 }
1563
1564 /*
1565  * Must hold jiffies_lock
1566  */
1567 void do_timer(unsigned long ticks)
1568 {
1569         jiffies_64 += ticks;
1570         update_wall_time();
1571         calc_global_load(ticks);
1572 }
1573
1574 /**
1575  * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
1576  *    and sleep offsets.
1577  * @xtim:       pointer to timespec to be set with xtime
1578  * @wtom:       pointer to timespec to be set with wall_to_monotonic
1579  * @sleep:      pointer to timespec to be set with time in suspend
1580  */
1581 void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
1582                                 struct timespec *wtom, struct timespec *sleep)
1583 {
1584         struct timekeeper *tk = &timekeeper;
1585         unsigned long seq;
1586
1587         do {
1588                 seq = read_seqcount_begin(&timekeeper_seq);
1589                 *xtim = tk_xtime(tk);
1590                 *wtom = tk->wall_to_monotonic;
1591                 *sleep = tk->total_sleep_time;
1592         } while (read_seqcount_retry(&timekeeper_seq, seq));
1593 }
1594
1595 #ifdef CONFIG_HIGH_RES_TIMERS
1596 /**
1597  * ktime_get_update_offsets - hrtimer helper
1598  * @offs_real:  pointer to storage for monotonic -> realtime offset
1599  * @offs_boot:  pointer to storage for monotonic -> boottime offset
1600  *
1601  * Returns current monotonic time and updates the offsets
1602  * Called from hrtimer_interupt() or retrigger_next_event()
1603  */
1604 ktime_t ktime_get_update_offsets(ktime_t *offs_real, ktime_t *offs_boot,
1605                                                         ktime_t *offs_tai)
1606 {
1607         struct timekeeper *tk = &timekeeper;
1608         ktime_t now;
1609         unsigned int seq;
1610         u64 secs, nsecs;
1611
1612         do {
1613                 seq = read_seqcount_begin(&timekeeper_seq);
1614
1615                 secs = tk->xtime_sec;
1616                 nsecs = timekeeping_get_ns(tk);
1617
1618                 *offs_real = tk->offs_real;
1619                 *offs_boot = tk->offs_boot;
1620                 *offs_tai = tk->offs_tai;
1621         } while (read_seqcount_retry(&timekeeper_seq, seq));
1622
1623         now = ktime_add_ns(ktime_set(secs, 0), nsecs);
1624         now = ktime_sub(now, *offs_real);
1625         return now;
1626 }
1627 #endif
1628
1629 /**
1630  * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
1631  */
1632 ktime_t ktime_get_monotonic_offset(void)
1633 {
1634         struct timekeeper *tk = &timekeeper;
1635         unsigned long seq;
1636         struct timespec wtom;
1637
1638         do {
1639                 seq = read_seqcount_begin(&timekeeper_seq);
1640                 wtom = tk->wall_to_monotonic;
1641         } while (read_seqcount_retry(&timekeeper_seq, seq));
1642
1643         return timespec_to_ktime(wtom);
1644 }
1645 EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
1646
1647 /**
1648  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
1649  */
1650 int do_adjtimex(struct timex *txc)
1651 {
1652         struct timekeeper *tk = &timekeeper;
1653         unsigned long flags;
1654         struct timespec ts;
1655         s32 orig_tai, tai;
1656         int ret;
1657
1658         /* Validate the data before disabling interrupts */
1659         ret = ntp_validate_timex(txc);
1660         if (ret)
1661                 return ret;
1662
1663         if (txc->modes & ADJ_SETOFFSET) {
1664                 struct timespec delta;
1665                 delta.tv_sec  = txc->time.tv_sec;
1666                 delta.tv_nsec = txc->time.tv_usec;
1667                 if (!(txc->modes & ADJ_NANO))
1668                         delta.tv_nsec *= 1000;
1669                 ret = timekeeping_inject_offset(&delta);
1670                 if (ret)
1671                         return ret;
1672         }
1673
1674         getnstimeofday(&ts);
1675
1676         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1677         write_seqcount_begin(&timekeeper_seq);
1678
1679         orig_tai = tai = tk->tai_offset;
1680         ret = __do_adjtimex(txc, &ts, &tai);
1681
1682         if (tai != orig_tai) {
1683                 __timekeeping_set_tai_offset(tk, tai);
1684                 clock_was_set_delayed();
1685         }
1686         write_seqcount_end(&timekeeper_seq);
1687         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1688
1689         return ret;
1690 }
1691
1692 #ifdef CONFIG_NTP_PPS
1693 /**
1694  * hardpps() - Accessor function to NTP __hardpps function
1695  */
1696 void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
1697 {
1698         unsigned long flags;
1699
1700         raw_spin_lock_irqsave(&timekeeper_lock, flags);
1701         write_seqcount_begin(&timekeeper_seq);
1702
1703         __hardpps(phase_ts, raw_ts);
1704
1705         write_seqcount_end(&timekeeper_seq);
1706         raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1707 }
1708 EXPORT_SYMBOL(hardpps);
1709 #endif
1710
1711 /**
1712  * xtime_update() - advances the timekeeping infrastructure
1713  * @ticks:      number of ticks, that have elapsed since the last call.
1714  *
1715  * Must be called with interrupts disabled.
1716  */
1717 void xtime_update(unsigned long ticks)
1718 {
1719         write_seqlock(&jiffies_lock);
1720         do_timer(ticks);
1721         write_sequnlock(&jiffies_lock);
1722 }