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