blob: fc7b4f201c53faad4b735cfff67cf707aafaaebb [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/*
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/module.h>
12#include <linux/interrupt.h>
13#include <linux/percpu.h>
14#include <linux/init.h>
15#include <linux/mm.h>
16#include <linux/sched.h>
17#include <linux/syscore_ops.h>
18#include <linux/clocksource.h>
19#include <linux/jiffies.h>
20#include <linux/time.h>
21#include <linux/tick.h>
22#include <linux/stop_machine.h>
23
24/* Structure holding internal timekeeping values. */
25struct timekeeper {
26 /* Current clocksource used for timekeeping. */
27 struct clocksource *clock;
28 /* NTP adjusted clock multiplier */
29 u32 mult;
30 /* The shift value of the current clocksource. */
31 int shift;
32
33 /* Number of clock cycles in one NTP interval. */
34 cycle_t cycle_interval;
35 /* Number of clock shifted nano seconds in one NTP interval. */
36 u64 xtime_interval;
37 /* shifted nano seconds left over when rounding cycle_interval */
38 s64 xtime_remainder;
39 /* Raw nano seconds accumulated per NTP interval. */
40 u32 raw_interval;
41
42 /* Clock shifted nano seconds remainder not stored in xtime.tv_nsec. */
43 u64 xtime_nsec;
44 /* Difference between accumulated time and NTP time in ntp
45 * shifted nano seconds. */
46 s64 ntp_error;
47 /* Shift conversion between clock shifted nano seconds and
48 * ntp shifted nano seconds. */
49 int ntp_error_shift;
50
51 /* The current time */
52 struct timespec xtime;
53 /*
54 * wall_to_monotonic is what we need to add to xtime (or xtime corrected
55 * for sub jiffie times) to get to monotonic time. Monotonic is pegged
56 * at zero at system boot time, so wall_to_monotonic will be negative,
57 * however, we will ALWAYS keep the tv_nsec part positive so we can use
58 * the usual normalization.
59 *
60 * wall_to_monotonic is moved after resume from suspend for the
61 * monotonic time not to jump. We need to add total_sleep_time to
62 * wall_to_monotonic to get the real boot based time offset.
63 *
64 * - wall_to_monotonic is no longer the boot time, getboottime must be
65 * used instead.
66 */
67 struct timespec wall_to_monotonic;
68 /* time spent in suspend */
69 struct timespec total_sleep_time;
70 /* The raw monotonic time for the CLOCK_MONOTONIC_RAW posix clock. */
71 struct timespec raw_time;
72
73 /* Offset clock monotonic -> clock realtime */
74 ktime_t offs_real;
75
76 /* Offset clock monotonic -> clock boottime */
77 ktime_t offs_boot;
78
79 /* Open coded seqlock for all timekeeper values */
80 seqcount_t seq;
81 raw_spinlock_t lock;
82};
83
84static struct timekeeper timekeeper;
85
86/*
87 * This read-write spinlock protects us from races in SMP while
88 * playing with xtime.
89 */
90__cacheline_aligned_in_smp DEFINE_RAW_SPINLOCK(xtime_lock);
91seqcount_t xtime_seq;
92
93
94/* flag for if timekeeping is suspended */
95int __read_mostly timekeeping_suspended;
96
97
98
99/**
100 * timekeeper_setup_internals - Set up internals to use clocksource clock.
101 *
102 * @clock: Pointer to clocksource.
103 *
104 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
105 * pair and interval request.
106 *
107 * Unless you're the timekeeping code, you should not be using this!
108 */
109static void timekeeper_setup_internals(struct clocksource *clock)
110{
111 cycle_t interval;
112 u64 tmp, ntpinterval;
113
114 timekeeper.clock = clock;
115 clock->cycle_last = clock->read(clock);
116
117 /* Do the ns -> cycle conversion first, using original mult */
118 tmp = NTP_INTERVAL_LENGTH;
119 tmp <<= clock->shift;
120 ntpinterval = tmp;
121 tmp += clock->mult/2;
122 do_div(tmp, clock->mult);
123 if (tmp == 0)
124 tmp = 1;
125
126 interval = (cycle_t) tmp;
127 timekeeper.cycle_interval = interval;
128
129 /* Go back from cycles -> shifted ns */
130 timekeeper.xtime_interval = (u64) interval * clock->mult;
131 timekeeper.xtime_remainder = ntpinterval - timekeeper.xtime_interval;
132 timekeeper.raw_interval =
133 ((u64) interval * clock->mult) >> clock->shift;
134
135 timekeeper.xtime_nsec = 0;
136 timekeeper.shift = clock->shift;
137
138 timekeeper.ntp_error = 0;
139 timekeeper.ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
140
141 /*
142 * The timekeeper keeps its own mult values for the currently
143 * active clocksource. These value will be adjusted via NTP
144 * to counteract clock drifting.
145 */
146 timekeeper.mult = clock->mult;
147}
148
149/* Timekeeper helper functions. */
150static inline s64 timekeeping_get_ns(void)
151{
152 cycle_t cycle_now, cycle_delta;
153 struct clocksource *clock;
154
155 /* read clocksource: */
156 clock = timekeeper.clock;
157 cycle_now = clock->read(clock);
158
159 /* calculate the delta since the last update_wall_time: */
160 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
161
162 /* return delta convert to nanoseconds using ntp adjusted mult. */
163 return clocksource_cyc2ns(cycle_delta, timekeeper.mult,
164 timekeeper.shift);
165}
166
167static inline s64 timekeeping_get_ns_raw(void)
168{
169 cycle_t cycle_now, cycle_delta;
170 struct clocksource *clock;
171
172 /* read clocksource: */
173 clock = timekeeper.clock;
174 cycle_now = clock->read(clock);
175
176 /* calculate the delta since the last update_wall_time: */
177 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
178
179 /* return delta convert to nanoseconds. */
180 return clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
181}
182
183static void update_rt_offset(void)
184{
185 struct timespec tmp, *wtm = &timekeeper.wall_to_monotonic;
186
187 set_normalized_timespec(&tmp, -wtm->tv_sec, -wtm->tv_nsec);
188 timekeeper.offs_real = timespec_to_ktime(tmp);
189}
190
191/* must hold write on timekeeper.lock */
192static void timekeeping_update(bool clearntp)
193{
194 if (clearntp) {
195 timekeeper.ntp_error = 0;
196 ntp_clear();
197 }
198 update_rt_offset();
199 update_vsyscall(&timekeeper.xtime, &timekeeper.wall_to_monotonic,
200 timekeeper.clock, timekeeper.mult);
201}
202
203
204/**
205 * timekeeping_forward_now - update clock to the current time
206 *
207 * Forward the current clock to update its state since the last call to
208 * update_wall_time(). This is useful before significant clock changes,
209 * as it avoids having to deal with this time offset explicitly.
210 */
211static void timekeeping_forward_now(void)
212{
213 cycle_t cycle_now, cycle_delta;
214 struct clocksource *clock;
215 s64 nsec;
216
217 clock = timekeeper.clock;
218 cycle_now = clock->read(clock);
219 cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
220 clock->cycle_last = cycle_now;
221
222 nsec = clocksource_cyc2ns(cycle_delta, timekeeper.mult,
223 timekeeper.shift);
224
225 /* If arch requires, add in gettimeoffset() */
226 nsec += arch_gettimeoffset();
227
228 timespec_add_ns(&timekeeper.xtime, nsec);
229
230 nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
231 timespec_add_ns(&timekeeper.raw_time, nsec);
232}
233
234/**
235 * getnstimeofday - Returns the time of day in a timespec
236 * @ts: pointer to the timespec to be set
237 *
238 * Returns the time of day in a timespec.
239 */
240void getnstimeofday(struct timespec *ts)
241{
242 unsigned long seq;
243 s64 nsecs;
244
245 WARN_ON(timekeeping_suspended);
246
247 do {
248 seq = read_seqcount_begin(&timekeeper.seq);
249
250 *ts = timekeeper.xtime;
251 nsecs = timekeeping_get_ns();
252
253 /* If arch requires, add in gettimeoffset() */
254 nsecs += arch_gettimeoffset();
255
256 } while (read_seqcount_retry(&timekeeper.seq, seq));
257
258 timespec_add_ns(ts, nsecs);
259}
260
261EXPORT_SYMBOL(getnstimeofday);
262
263ktime_t ktime_get(void)
264{
265 unsigned int seq;
266 s64 secs, nsecs;
267
268 WARN_ON(timekeeping_suspended);
269
270 do {
271 seq = read_seqcount_begin(&timekeeper.seq);
272 secs = timekeeper.xtime.tv_sec +
273 timekeeper.wall_to_monotonic.tv_sec;
274 nsecs = timekeeper.xtime.tv_nsec +
275 timekeeper.wall_to_monotonic.tv_nsec;
276 nsecs += timekeeping_get_ns();
277 /* If arch requires, add in gettimeoffset() */
278 nsecs += arch_gettimeoffset();
279
280 } while (read_seqcount_retry(&timekeeper.seq, seq));
281 /*
282 * Use ktime_set/ktime_add_ns to create a proper ktime on
283 * 32-bit architectures without CONFIG_KTIME_SCALAR.
284 */
285 return ktime_add_ns(ktime_set(secs, 0), nsecs);
286}
287EXPORT_SYMBOL_GPL(ktime_get);
288
289/**
290 * ktime_get_ts - get the monotonic clock in timespec format
291 * @ts: pointer to timespec variable
292 *
293 * The function calculates the monotonic clock from the realtime
294 * clock and the wall_to_monotonic offset and stores the result
295 * in normalized timespec format in the variable pointed to by @ts.
296 */
297void ktime_get_ts(struct timespec *ts)
298{
299 struct timespec tomono;
300 unsigned int seq;
301 s64 nsecs;
302
303 WARN_ON(timekeeping_suspended);
304
305 do {
306 seq = read_seqcount_begin(&timekeeper.seq);
307 *ts = timekeeper.xtime;
308 tomono = timekeeper.wall_to_monotonic;
309 nsecs = timekeeping_get_ns();
310 /* If arch requires, add in gettimeoffset() */
311 nsecs += arch_gettimeoffset();
312
313 } while (read_seqcount_retry(&timekeeper.seq, seq));
314
315 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
316 ts->tv_nsec + tomono.tv_nsec + nsecs);
317}
318EXPORT_SYMBOL_GPL(ktime_get_ts);
319
320#ifdef CONFIG_NTP_PPS
321
322/**
323 * getnstime_raw_and_real - get day and raw monotonic time in timespec format
324 * @ts_raw: pointer to the timespec to be set to raw monotonic time
325 * @ts_real: pointer to the timespec to be set to the time of day
326 *
327 * This function reads both the time of day and raw monotonic time at the
328 * same time atomically and stores the resulting timestamps in timespec
329 * format.
330 */
331void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
332{
333 unsigned long seq;
334 s64 nsecs_raw, nsecs_real;
335
336 WARN_ON_ONCE(timekeeping_suspended);
337
338 do {
339 u32 arch_offset;
340
341 seq = read_seqcount_begin(&timekeeper.seq);
342
343 *ts_raw = timekeeper.raw_time;
344 *ts_real = timekeeper.xtime;
345
346 nsecs_raw = timekeeping_get_ns_raw();
347 nsecs_real = timekeeping_get_ns();
348
349 /* If arch requires, add in gettimeoffset() */
350 arch_offset = arch_gettimeoffset();
351 nsecs_raw += arch_offset;
352 nsecs_real += arch_offset;
353
354 } while (read_seqcount_retry(&timekeeper.seq, seq));
355
356 timespec_add_ns(ts_raw, nsecs_raw);
357 timespec_add_ns(ts_real, nsecs_real);
358}
359EXPORT_SYMBOL(getnstime_raw_and_real);
360
361#endif /* CONFIG_NTP_PPS */
362
363/**
364 * do_gettimeofday - Returns the time of day in a timeval
365 * @tv: pointer to the timeval to be set
366 *
367 * NOTE: Users should be converted to using getnstimeofday()
368 */
369void do_gettimeofday(struct timeval *tv)
370{
371 struct timespec now;
372
373 getnstimeofday(&now);
374 tv->tv_sec = now.tv_sec;
375 tv->tv_usec = now.tv_nsec/1000;
376}
377
378EXPORT_SYMBOL(do_gettimeofday);
379/**
380 * do_settimeofday - Sets the time of day
381 * @tv: pointer to the timespec variable containing the new time
382 *
383 * Sets the time of day to the new time and update NTP and notify hrtimers
384 */
385int do_settimeofday(const struct timespec *tv)
386{
387 struct timespec ts_delta;
388 unsigned long flags;
389
390 if (!timespec_valid_strict(tv))
391 return -EINVAL;
392
393 raw_spin_lock_irqsave(&timekeeper.lock, flags);
394 write_seqcount_begin(&timekeeper.seq);
395
396 timekeeping_forward_now();
397
398 ts_delta.tv_sec = tv->tv_sec - timekeeper.xtime.tv_sec;
399 ts_delta.tv_nsec = tv->tv_nsec - timekeeper.xtime.tv_nsec;
400 timekeeper.wall_to_monotonic =
401 timespec_sub(timekeeper.wall_to_monotonic, ts_delta);
402
403 timekeeper.xtime = *tv;
404 timekeeping_update(true);
405
406 write_seqcount_end(&timekeeper.seq);
407 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
408
409 /* signal hrtimers about time change */
410 clock_was_set();
411
412 return 0;
413}
414
415EXPORT_SYMBOL(do_settimeofday);
416
417
418/**
419 * timekeeping_inject_offset - Adds or subtracts from the current time.
420 * @tv: pointer to the timespec variable containing the offset
421 *
422 * Adds or subtracts an offset value from the current time.
423 */
424int timekeeping_inject_offset(struct timespec *ts)
425{
426 unsigned long flags;
427 struct timespec tmp;
428 int ret = 0;
429
430 if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
431 return -EINVAL;
432
433 raw_spin_lock_irqsave(&timekeeper.lock, flags);
434 write_seqcount_begin(&timekeeper.seq);
435
436 timekeeping_forward_now();
437
438 tmp = timespec_add(timekeeper.xtime, *ts);
439 if (!timespec_valid_strict(&tmp)) {
440 ret = -EINVAL;
441 goto error;
442 }
443
444 timekeeper.xtime = timespec_add(timekeeper.xtime, *ts);
445 timekeeper.wall_to_monotonic =
446 timespec_sub(timekeeper.wall_to_monotonic, *ts);
447
448error: /* even if we error out, we forwarded the time, so call update */
449 timekeeping_update(true);
450
451 write_seqcount_end(&timekeeper.seq);
452 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
453
454 /* signal hrtimers about time change */
455 clock_was_set();
456
457 return ret;
458}
459EXPORT_SYMBOL(timekeeping_inject_offset);
460
461/**
462 * change_clocksource - Swaps clocksources if a new one is available
463 *
464 * Accumulates current time interval and initializes new clocksource
465 */
466static int change_clocksource(void *data)
467{
468 struct clocksource *new, *old;
469 unsigned long flags;
470
471 new = (struct clocksource *) data;
472
473 raw_spin_lock_irqsave(&timekeeper.lock, flags);
474 write_seqcount_begin(&timekeeper.seq);
475
476 timekeeping_forward_now();
477 if (!new->enable || new->enable(new) == 0) {
478 old = timekeeper.clock;
479 timekeeper_setup_internals(new);
480 if (old->disable)
481 old->disable(old);
482 }
483 timekeeping_update(true);
484
485 write_seqcount_end(&timekeeper.seq);
486 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
487
488 return 0;
489}
490
491/**
492 * timekeeping_notify - Install a new clock source
493 * @clock: pointer to the clock source
494 *
495 * This function is called from clocksource.c after a new, better clock
496 * source has been registered. The caller holds the clocksource_mutex.
497 */
498void timekeeping_notify(struct clocksource *clock)
499{
500 if (timekeeper.clock == clock)
501 return;
502 stop_machine(change_clocksource, clock, NULL);
503 tick_clock_notify();
504}
505
506/**
507 * ktime_get_real - get the real (wall-) time in ktime_t format
508 *
509 * returns the time in ktime_t format
510 */
511ktime_t ktime_get_real(void)
512{
513 struct timespec now;
514
515 getnstimeofday(&now);
516
517 return timespec_to_ktime(now);
518}
519EXPORT_SYMBOL_GPL(ktime_get_real);
520
521/**
522 * getrawmonotonic - Returns the raw monotonic time in a timespec
523 * @ts: pointer to the timespec to be set
524 *
525 * Returns the raw monotonic time (completely un-modified by ntp)
526 */
527void getrawmonotonic(struct timespec *ts)
528{
529 unsigned long seq;
530 s64 nsecs;
531
532 do {
533 seq = read_seqcount_begin(&timekeeper.seq);
534 nsecs = timekeeping_get_ns_raw();
535 *ts = timekeeper.raw_time;
536
537 } while (read_seqcount_retry(&timekeeper.seq, seq));
538
539 timespec_add_ns(ts, nsecs);
540}
541EXPORT_SYMBOL(getrawmonotonic);
542
543
544/**
545 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
546 */
547int timekeeping_valid_for_hres(void)
548{
549 unsigned long seq;
550 int ret;
551
552 do {
553 seq = read_seqcount_begin(&timekeeper.seq);
554
555 ret = timekeeper.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
556
557 } while (read_seqcount_retry(&timekeeper.seq, seq));
558
559 return ret;
560}
561
562/**
563 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
564 */
565u64 timekeeping_max_deferment(void)
566{
567 unsigned long seq;
568 u64 ret;
569 do {
570 seq = read_seqcount_begin(&timekeeper.seq);
571
572 ret = timekeeper.clock->max_idle_ns;
573
574 } while (read_seqcount_retry(&timekeeper.seq, seq));
575
576 return ret;
577}
578
579/**
580 * read_persistent_clock - Return time from the persistent clock.
581 *
582 * Weak dummy function for arches that do not yet support it.
583 * Reads the time from the battery backed persistent clock.
584 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
585 *
586 * XXX - Do be sure to remove it once all arches implement it.
587 */
588void __attribute__((weak)) read_persistent_clock(struct timespec *ts)
589{
590 ts->tv_sec = 0;
591 ts->tv_nsec = 0;
592}
593
594/**
595 * read_boot_clock - Return time of the system start.
596 *
597 * Weak dummy function for arches that do not yet support it.
598 * Function to read the exact time the system has been started.
599 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
600 *
601 * XXX - Do be sure to remove it once all arches implement it.
602 */
603void __attribute__((weak)) read_boot_clock(struct timespec *ts)
604{
605 ts->tv_sec = 0;
606 ts->tv_nsec = 0;
607}
608
609/*
610 * timekeeping_init - Initializes the clocksource and common timekeeping values
611 */
612void __init timekeeping_init(void)
613{
614 struct clocksource *clock;
615 unsigned long flags;
616 struct timespec now, boot;
617
618 read_persistent_clock(&now);
619 if (!timespec_valid_strict(&now)) {
620 pr_warn("WARNING: Persistent clock returned invalid value!\n"
621 " Check your CMOS/BIOS settings.\n");
622 now.tv_sec = 0;
623 now.tv_nsec = 0;
624 }
625
626 read_boot_clock(&boot);
627 if (!timespec_valid_strict(&boot)) {
628 pr_warn("WARNING: Boot clock returned invalid value!\n"
629 " Check your CMOS/BIOS settings.\n");
630 boot.tv_sec = 0;
631 boot.tv_nsec = 0;
632 }
633
634 raw_spin_lock_init(&timekeeper.lock);
635 seqcount_init(&timekeeper.seq);
636
637 ntp_init();
638
639 raw_spin_lock_irqsave(&timekeeper.lock, flags);
640 write_seqcount_begin(&timekeeper.seq);
641 clock = clocksource_default_clock();
642 if (clock->enable)
643 clock->enable(clock);
644 timekeeper_setup_internals(clock);
645
646 timekeeper.xtime.tv_sec = now.tv_sec;
647 timekeeper.xtime.tv_nsec = now.tv_nsec;
648 timekeeper.raw_time.tv_sec = 0;
649 timekeeper.raw_time.tv_nsec = 0;
650 if (boot.tv_sec == 0 && boot.tv_nsec == 0) {
651 boot.tv_sec = timekeeper.xtime.tv_sec;
652 boot.tv_nsec = timekeeper.xtime.tv_nsec;
653 }
654 set_normalized_timespec(&timekeeper.wall_to_monotonic,
655 -boot.tv_sec, -boot.tv_nsec);
656 update_rt_offset();
657 timekeeper.total_sleep_time.tv_sec = 0;
658 timekeeper.total_sleep_time.tv_nsec = 0;
659 write_seqcount_end(&timekeeper.seq);
660 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
661}
662
663/* time in seconds when suspend began */
664static struct timespec timekeeping_suspend_time;
665
666static void update_sleep_time(struct timespec t)
667{
668 timekeeper.total_sleep_time = t;
669 timekeeper.offs_boot = timespec_to_ktime(t);
670}
671
672/**
673 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
674 * @delta: pointer to a timespec delta value
675 *
676 * Takes a timespec offset measuring a suspend interval and properly
677 * adds the sleep offset to the timekeeping variables.
678 */
679static void __timekeeping_inject_sleeptime(struct timespec *delta)
680{
681 if (!timespec_valid_strict(delta)) {
682 printk(KERN_WARNING "__timekeeping_inject_sleeptime: Invalid "
683 "sleep delta value!\n");
684 return;
685 }
686
687 timekeeper.xtime = timespec_add(timekeeper.xtime, *delta);
688 timekeeper.wall_to_monotonic =
689 timespec_sub(timekeeper.wall_to_monotonic, *delta);
690 update_sleep_time(timespec_add(timekeeper.total_sleep_time, *delta));
691}
692
693
694/**
695 * timekeeping_inject_sleeptime - Adds suspend interval to timeekeeping values
696 * @delta: pointer to a timespec delta value
697 *
698 * This hook is for architectures that cannot support read_persistent_clock
699 * because their RTC/persistent clock is only accessible when irqs are enabled.
700 *
701 * This function should only be called by rtc_resume(), and allows
702 * a suspend offset to be injected into the timekeeping values.
703 */
704void timekeeping_inject_sleeptime(struct timespec *delta)
705{
706 unsigned long flags;
707 struct timespec ts;
708
709 /* Make sure we don't set the clock twice */
710 read_persistent_clock(&ts);
711 if (!(ts.tv_sec == 0 && ts.tv_nsec == 0))
712 return;
713
714 raw_spin_lock_irqsave(&timekeeper.lock, flags);
715 write_seqcount_begin(&timekeeper.seq);
716
717 timekeeping_forward_now();
718
719 __timekeeping_inject_sleeptime(delta);
720
721 timekeeping_update(true);
722
723 write_seqcount_end(&timekeeper.seq);
724 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
725
726 /* signal hrtimers about time change */
727 clock_was_set();
728}
729
730
731/**
732 * timekeeping_resume - Resumes the generic timekeeping subsystem.
733 *
734 * This is for the generic clocksource timekeeping.
735 * xtime/wall_to_monotonic/jiffies/etc are
736 * still managed by arch specific suspend/resume code.
737 */
738static void timekeeping_resume(void)
739{
740 unsigned long flags;
741 struct timespec ts;
742
743 read_persistent_clock(&ts);
744
745 clocksource_resume();
746
747 raw_spin_lock_irqsave(&timekeeper.lock, flags);
748 write_seqcount_begin(&timekeeper.seq);
749
750 if (timespec_compare(&ts, &timekeeping_suspend_time) > 0) {
751 ts = timespec_sub(ts, timekeeping_suspend_time);
752 __timekeeping_inject_sleeptime(&ts);
753 }
754 /* re-base the last cycle value */
755 timekeeper.clock->cycle_last = timekeeper.clock->read(timekeeper.clock);
756 timekeeper.ntp_error = 0;
757 timekeeping_suspended = 0;
758 timekeeping_update(false);
759 write_seqcount_end(&timekeeper.seq);
760 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
761
762 touch_softlockup_watchdog();
763
764 clockevents_notify(CLOCK_EVT_NOTIFY_RESUME, NULL);
765
766 /* Resume hrtimers */
767 hrtimers_resume();
768}
769
770static int timekeeping_suspend(void)
771{
772 unsigned long flags;
773 struct timespec delta, delta_delta;
774 static struct timespec old_delta;
775
776 read_persistent_clock(&timekeeping_suspend_time);
777
778 raw_spin_lock_irqsave(&timekeeper.lock, flags);
779 write_seqcount_begin(&timekeeper.seq);
780 timekeeping_forward_now();
781 timekeeping_suspended = 1;
782
783 /*
784 * To avoid drift caused by repeated suspend/resumes,
785 * which each can add ~1 second drift error,
786 * try to compensate so the difference in system time
787 * and persistent_clock time stays close to constant.
788 */
789 delta = timespec_sub(timekeeper.xtime, timekeeping_suspend_time);
790 delta_delta = timespec_sub(delta, old_delta);
791 if (abs(delta_delta.tv_sec) >= 2) {
792 /*
793 * if delta_delta is too large, assume time correction
794 * has occured and set old_delta to the current delta.
795 */
796 old_delta = delta;
797 } else {
798 /* Otherwise try to adjust old_system to compensate */
799 timekeeping_suspend_time =
800 timespec_add(timekeeping_suspend_time, delta_delta);
801 }
802 write_seqcount_end(&timekeeper.seq);
803 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
804
805 clockevents_notify(CLOCK_EVT_NOTIFY_SUSPEND, NULL);
806 clocksource_suspend();
807
808 return 0;
809}
810
811/* sysfs resume/suspend bits for timekeeping */
812static struct syscore_ops timekeeping_syscore_ops = {
813 .resume = timekeeping_resume,
814 .suspend = timekeeping_suspend,
815};
816
817static int __init timekeeping_init_ops(void)
818{
819 register_syscore_ops(&timekeeping_syscore_ops);
820 return 0;
821}
822
823device_initcall(timekeeping_init_ops);
824
825/*
826 * If the error is already larger, we look ahead even further
827 * to compensate for late or lost adjustments.
828 */
829static __always_inline int timekeeping_bigadjust(s64 error, s64 *interval,
830 s64 *offset)
831{
832 s64 tick_error, i;
833 u32 look_ahead, adj;
834 s32 error2, mult;
835
836 /*
837 * Use the current error value to determine how much to look ahead.
838 * The larger the error the slower we adjust for it to avoid problems
839 * with losing too many ticks, otherwise we would overadjust and
840 * produce an even larger error. The smaller the adjustment the
841 * faster we try to adjust for it, as lost ticks can do less harm
842 * here. This is tuned so that an error of about 1 msec is adjusted
843 * within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
844 */
845 error2 = timekeeper.ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
846 error2 = abs(error2);
847 for (look_ahead = 0; error2 > 0; look_ahead++)
848 error2 >>= 2;
849
850 /*
851 * Now calculate the error in (1 << look_ahead) ticks, but first
852 * remove the single look ahead already included in the error.
853 */
854 tick_error = ntp_tick_length() >> (timekeeper.ntp_error_shift + 1);
855 tick_error -= timekeeper.xtime_interval >> 1;
856 error = ((error - tick_error) >> look_ahead) + tick_error;
857
858 /* Finally calculate the adjustment shift value. */
859 i = *interval;
860 mult = 1;
861 if (error < 0) {
862 error = -error;
863 *interval = -*interval;
864 *offset = -*offset;
865 mult = -1;
866 }
867 for (adj = 0; error > i; adj++)
868 error >>= 1;
869
870 *interval <<= adj;
871 *offset <<= adj;
872 return mult << adj;
873}
874
875/*
876 * Adjust the multiplier to reduce the error value,
877 * this is optimized for the most common adjustments of -1,0,1,
878 * for other values we can do a bit more work.
879 */
880static void timekeeping_adjust(s64 offset)
881{
882 s64 error, interval = timekeeper.cycle_interval;
883 int adj;
884
885 /*
886 * The point of this is to check if the error is greater than half
887 * an interval.
888 *
889 * First we shift it down from NTP_SHIFT to clocksource->shifted nsecs.
890 *
891 * Note we subtract one in the shift, so that error is really error*2.
892 * This "saves" dividing(shifting) interval twice, but keeps the
893 * (error > interval) comparison as still measuring if error is
894 * larger than half an interval.
895 *
896 * Note: It does not "save" on aggravation when reading the code.
897 */
898 error = timekeeper.ntp_error >> (timekeeper.ntp_error_shift - 1);
899 if (error > interval) {
900 /*
901 * We now divide error by 4(via shift), which checks if
902 * the error is greater than twice the interval.
903 * If it is greater, we need a bigadjust, if its smaller,
904 * we can adjust by 1.
905 */
906 error >>= 2;
907 /*
908 * XXX - In update_wall_time, we round up to the next
909 * nanosecond, and store the amount rounded up into
910 * the error. This causes the likely below to be unlikely.
911 *
912 * The proper fix is to avoid rounding up by using
913 * the high precision timekeeper.xtime_nsec instead of
914 * xtime.tv_nsec everywhere. Fixing this will take some
915 * time.
916 */
917 if (likely(error <= interval))
918 adj = 1;
919 else
920 adj = timekeeping_bigadjust(error, &interval, &offset);
921 } else if (error < -interval) {
922 /* See comment above, this is just switched for the negative */
923 error >>= 2;
924 if (likely(error >= -interval)) {
925 adj = -1;
926 interval = -interval;
927 offset = -offset;
928 } else
929 adj = timekeeping_bigadjust(error, &interval, &offset);
930 } else /* No adjustment needed */
931 return;
932
933 if (unlikely(timekeeper.clock->maxadj &&
934 (timekeeper.mult + adj >
935 timekeeper.clock->mult + timekeeper.clock->maxadj))) {
936 printk_once(KERN_WARNING
937 "Adjusting %s more than 11%% (%ld vs %ld)\n",
938 timekeeper.clock->name, (long)timekeeper.mult + adj,
939 (long)timekeeper.clock->mult +
940 timekeeper.clock->maxadj);
941 }
942 /*
943 * So the following can be confusing.
944 *
945 * To keep things simple, lets assume adj == 1 for now.
946 *
947 * When adj != 1, remember that the interval and offset values
948 * have been appropriately scaled so the math is the same.
949 *
950 * The basic idea here is that we're increasing the multiplier
951 * by one, this causes the xtime_interval to be incremented by
952 * one cycle_interval. This is because:
953 * xtime_interval = cycle_interval * mult
954 * So if mult is being incremented by one:
955 * xtime_interval = cycle_interval * (mult + 1)
956 * Its the same as:
957 * xtime_interval = (cycle_interval * mult) + cycle_interval
958 * Which can be shortened to:
959 * xtime_interval += cycle_interval
960 *
961 * So offset stores the non-accumulated cycles. Thus the current
962 * time (in shifted nanoseconds) is:
963 * now = (offset * adj) + xtime_nsec
964 * Now, even though we're adjusting the clock frequency, we have
965 * to keep time consistent. In other words, we can't jump back
966 * in time, and we also want to avoid jumping forward in time.
967 *
968 * So given the same offset value, we need the time to be the same
969 * both before and after the freq adjustment.
970 * now = (offset * adj_1) + xtime_nsec_1
971 * now = (offset * adj_2) + xtime_nsec_2
972 * So:
973 * (offset * adj_1) + xtime_nsec_1 =
974 * (offset * adj_2) + xtime_nsec_2
975 * And we know:
976 * adj_2 = adj_1 + 1
977 * So:
978 * (offset * adj_1) + xtime_nsec_1 =
979 * (offset * (adj_1+1)) + xtime_nsec_2
980 * (offset * adj_1) + xtime_nsec_1 =
981 * (offset * adj_1) + offset + xtime_nsec_2
982 * Canceling the sides:
983 * xtime_nsec_1 = offset + xtime_nsec_2
984 * Which gives us:
985 * xtime_nsec_2 = xtime_nsec_1 - offset
986 * Which simplfies to:
987 * xtime_nsec -= offset
988 *
989 * XXX - TODO: Doc ntp_error calculation.
990 */
991 timekeeper.mult += adj;
992 timekeeper.xtime_interval += interval;
993 timekeeper.xtime_nsec -= offset;
994 timekeeper.ntp_error -= (interval - offset) <<
995 timekeeper.ntp_error_shift;
996}
997
998
999/**
1000 * logarithmic_accumulation - shifted accumulation of cycles
1001 *
1002 * This functions accumulates a shifted interval of cycles into
1003 * into a shifted interval nanoseconds. Allows for O(log) accumulation
1004 * loop.
1005 *
1006 * Returns the unconsumed cycles.
1007 */
1008static cycle_t logarithmic_accumulation(cycle_t offset, int shift,
1009 unsigned int *clock_set)
1010{
1011 u64 nsecps = (u64)NSEC_PER_SEC << timekeeper.shift;
1012 u64 raw_nsecs;
1013
1014 /* If the offset is smaller than a shifted interval, do nothing */
1015 if (offset < timekeeper.cycle_interval<<shift)
1016 return offset;
1017
1018 /* Accumulate one shifted interval */
1019 offset -= timekeeper.cycle_interval << shift;
1020 timekeeper.clock->cycle_last += timekeeper.cycle_interval << shift;
1021
1022 timekeeper.xtime_nsec += timekeeper.xtime_interval << shift;
1023 while (timekeeper.xtime_nsec >= nsecps) {
1024 int leap;
1025 timekeeper.xtime_nsec -= nsecps;
1026 timekeeper.xtime.tv_sec++;
1027 leap = second_overflow(timekeeper.xtime.tv_sec);
1028 timekeeper.xtime.tv_sec += leap;
1029 timekeeper.wall_to_monotonic.tv_sec -= leap;
1030 if (leap)
1031 *clock_set = 1;
1032 }
1033
1034 /* Accumulate raw time */
1035 raw_nsecs = (u64)timekeeper.raw_interval << shift;
1036 raw_nsecs += timekeeper.raw_time.tv_nsec;
1037 if (raw_nsecs >= NSEC_PER_SEC) {
1038 u64 raw_secs = raw_nsecs;
1039 raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
1040 timekeeper.raw_time.tv_sec += raw_secs;
1041 }
1042 timekeeper.raw_time.tv_nsec = raw_nsecs;
1043
1044 /* Accumulate error between NTP and clock interval */
1045 timekeeper.ntp_error += ntp_tick_length() << shift;
1046 timekeeper.ntp_error -=
1047 (timekeeper.xtime_interval + timekeeper.xtime_remainder) <<
1048 (timekeeper.ntp_error_shift + shift);
1049
1050 return offset;
1051}
1052
1053
1054/**
1055 * update_wall_time - Uses the current clocksource to increment the wall time
1056 *
1057 */
1058static void update_wall_time(void)
1059{
1060 struct clocksource *clock;
1061 cycle_t offset;
1062 int shift = 0, maxshift;
1063 unsigned int clock_set = 0;
1064 unsigned long flags;
1065
1066 raw_spin_lock_irqsave(&timekeeper.lock, flags);
1067 write_seqcount_begin(&timekeeper.seq);
1068
1069 /* Make sure we're fully resumed: */
1070 if (unlikely(timekeeping_suspended))
1071 goto out;
1072
1073 clock = timekeeper.clock;
1074
1075#ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
1076 offset = timekeeper.cycle_interval;
1077#else
1078 offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
1079#endif
1080 /* Check if there's really nothing to do */
1081 if (offset < timekeeper.cycle_interval)
1082 goto out;
1083
1084 timekeeper.xtime_nsec = (s64)timekeeper.xtime.tv_nsec <<
1085 timekeeper.shift;
1086 /*
1087 * With NO_HZ we may have to accumulate many cycle_intervals
1088 * (think "ticks") worth of time at once. To do this efficiently,
1089 * we calculate the largest doubling multiple of cycle_intervals
1090 * that is smaller than the offset. We then accumulate that
1091 * chunk in one go, and then try to consume the next smaller
1092 * doubled multiple.
1093 */
1094 shift = ilog2(offset) - ilog2(timekeeper.cycle_interval);
1095 shift = max(0, shift);
1096 /* Bound shift to one less than what overflows tick_length */
1097 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1098 shift = min(shift, maxshift);
1099 while (offset >= timekeeper.cycle_interval) {
1100 offset = logarithmic_accumulation(offset, shift, &clock_set);
1101 if(offset < timekeeper.cycle_interval<<shift)
1102 shift--;
1103 }
1104
1105 /* correct the clock when NTP error is too big */
1106 timekeeping_adjust(offset);
1107
1108 /*
1109 * Since in the loop above, we accumulate any amount of time
1110 * in xtime_nsec over a second into xtime.tv_sec, its possible for
1111 * xtime_nsec to be fairly small after the loop. Further, if we're
1112 * slightly speeding the clocksource up in timekeeping_adjust(),
1113 * its possible the required corrective factor to xtime_nsec could
1114 * cause it to underflow.
1115 *
1116 * Now, we cannot simply roll the accumulated second back, since
1117 * the NTP subsystem has been notified via second_overflow. So
1118 * instead we push xtime_nsec forward by the amount we underflowed,
1119 * and add that amount into the error.
1120 *
1121 * We'll correct this error next time through this function, when
1122 * xtime_nsec is not as small.
1123 */
1124 if (unlikely((s64)timekeeper.xtime_nsec < 0)) {
1125 s64 neg = -(s64)timekeeper.xtime_nsec;
1126 timekeeper.xtime_nsec = 0;
1127 timekeeper.ntp_error += neg << timekeeper.ntp_error_shift;
1128 }
1129
1130
1131 /*
1132 * Store full nanoseconds into xtime after rounding it up and
1133 * add the remainder to the error difference.
1134 */
1135 timekeeper.xtime.tv_nsec = ((s64)timekeeper.xtime_nsec >>
1136 timekeeper.shift) + 1;
1137 timekeeper.xtime_nsec -= (s64)timekeeper.xtime.tv_nsec <<
1138 timekeeper.shift;
1139 timekeeper.ntp_error += timekeeper.xtime_nsec <<
1140 timekeeper.ntp_error_shift;
1141
1142 /*
1143 * Finally, make sure that after the rounding
1144 * xtime.tv_nsec isn't larger than NSEC_PER_SEC
1145 */
1146 if (unlikely(timekeeper.xtime.tv_nsec >= NSEC_PER_SEC)) {
1147 int leap;
1148 timekeeper.xtime.tv_nsec -= NSEC_PER_SEC;
1149 timekeeper.xtime.tv_sec++;
1150 leap = second_overflow(timekeeper.xtime.tv_sec);
1151 timekeeper.xtime.tv_sec += leap;
1152 timekeeper.wall_to_monotonic.tv_sec -= leap;
1153 if (leap)
1154 clock_set = 1;
1155 }
1156
1157 timekeeping_update(false);
1158
1159out:
1160 write_seqcount_end(&timekeeper.seq);
1161 raw_spin_unlock_irqrestore(&timekeeper.lock, flags);
1162
1163 if (clock_set)
1164 clock_was_set_delayed();
1165}
1166
1167/**
1168 * getboottime - Return the real time of system boot.
1169 * @ts: pointer to the timespec to be set
1170 *
1171 * Returns the wall-time of boot in a timespec.
1172 *
1173 * This is based on the wall_to_monotonic offset and the total suspend
1174 * time. Calls to settimeofday will affect the value returned (which
1175 * basically means that however wrong your real time clock is at boot time,
1176 * you get the right time here).
1177 */
1178void getboottime(struct timespec *ts)
1179{
1180 struct timespec boottime = {
1181 .tv_sec = timekeeper.wall_to_monotonic.tv_sec +
1182 timekeeper.total_sleep_time.tv_sec,
1183 .tv_nsec = timekeeper.wall_to_monotonic.tv_nsec +
1184 timekeeper.total_sleep_time.tv_nsec
1185 };
1186
1187 set_normalized_timespec(ts, -boottime.tv_sec, -boottime.tv_nsec);
1188}
1189EXPORT_SYMBOL_GPL(getboottime);
1190
1191
1192/**
1193 * get_monotonic_boottime - Returns monotonic time since boot
1194 * @ts: pointer to the timespec to be set
1195 *
1196 * Returns the monotonic time since boot in a timespec.
1197 *
1198 * This is similar to CLOCK_MONTONIC/ktime_get_ts, but also
1199 * includes the time spent in suspend.
1200 */
1201void get_monotonic_boottime(struct timespec *ts)
1202{
1203 struct timespec tomono, sleep;
1204 unsigned int seq;
1205 s64 nsecs;
1206
1207 WARN_ON(timekeeping_suspended);
1208
1209 do {
1210 seq = read_seqcount_begin(&timekeeper.seq);
1211 *ts = timekeeper.xtime;
1212 tomono = timekeeper.wall_to_monotonic;
1213 sleep = timekeeper.total_sleep_time;
1214 nsecs = timekeeping_get_ns();
1215
1216 } while (read_seqcount_retry(&timekeeper.seq, seq));
1217
1218 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec + sleep.tv_sec,
1219 (s64)ts->tv_nsec + tomono.tv_nsec + sleep.tv_nsec + nsecs);
1220}
1221EXPORT_SYMBOL_GPL(get_monotonic_boottime);
1222
1223/**
1224 * ktime_get_boottime - Returns monotonic time since boot in a ktime
1225 *
1226 * Returns the monotonic time since boot in a ktime
1227 *
1228 * This is similar to CLOCK_MONTONIC/ktime_get, but also
1229 * includes the time spent in suspend.
1230 */
1231ktime_t ktime_get_boottime(void)
1232{
1233 struct timespec ts;
1234
1235 get_monotonic_boottime(&ts);
1236 return timespec_to_ktime(ts);
1237}
1238EXPORT_SYMBOL_GPL(ktime_get_boottime);
1239
1240/**
1241 * monotonic_to_bootbased - Convert the monotonic time to boot based.
1242 * @ts: pointer to the timespec to be converted
1243 */
1244void monotonic_to_bootbased(struct timespec *ts)
1245{
1246 *ts = timespec_add(*ts, timekeeper.total_sleep_time);
1247}
1248EXPORT_SYMBOL_GPL(monotonic_to_bootbased);
1249
1250unsigned long get_seconds(void)
1251{
1252 return timekeeper.xtime.tv_sec;
1253}
1254EXPORT_SYMBOL(get_seconds);
1255
1256struct timespec __current_kernel_time(void)
1257{
1258 return timekeeper.xtime;
1259}
1260
1261struct timespec current_kernel_time(void)
1262{
1263 struct timespec now;
1264 unsigned long seq;
1265
1266 do {
1267 seq = read_seqcount_begin(&timekeeper.seq);
1268
1269 now = timekeeper.xtime;
1270 } while (read_seqcount_retry(&timekeeper.seq, seq));
1271
1272 return now;
1273}
1274EXPORT_SYMBOL(current_kernel_time);
1275
1276struct timespec get_monotonic_coarse(void)
1277{
1278 struct timespec now, mono;
1279 unsigned long seq;
1280
1281 do {
1282 seq = read_seqcount_begin(&timekeeper.seq);
1283
1284 now = timekeeper.xtime;
1285 mono = timekeeper.wall_to_monotonic;
1286 } while (read_seqcount_retry(&timekeeper.seq, seq));
1287
1288 set_normalized_timespec(&now, now.tv_sec + mono.tv_sec,
1289 now.tv_nsec + mono.tv_nsec);
1290 return now;
1291}
1292
1293/*
1294 * The 64-bit jiffies value is not atomic - you MUST NOT read it
1295 * without sampling the sequence number in xtime_lock.
1296 * jiffies is defined in the linker script...
1297 */
1298void do_timer(unsigned long ticks)
1299{
1300 jiffies_64 += ticks;
1301 update_wall_time();
1302 calc_global_load(ticks);
1303}
1304
1305/**
1306 * get_xtime_and_monotonic_and_sleep_offset() - get xtime, wall_to_monotonic,
1307 * and sleep offsets.
1308 * @xtim: pointer to timespec to be set with xtime
1309 * @wtom: pointer to timespec to be set with wall_to_monotonic
1310 * @sleep: pointer to timespec to be set with time in suspend
1311 */
1312void get_xtime_and_monotonic_and_sleep_offset(struct timespec *xtim,
1313 struct timespec *wtom, struct timespec *sleep)
1314{
1315 unsigned long seq;
1316
1317 do {
1318 seq = read_seqcount_begin(&timekeeper.seq);
1319 *xtim = timekeeper.xtime;
1320 *wtom = timekeeper.wall_to_monotonic;
1321 *sleep = timekeeper.total_sleep_time;
1322 } while (read_seqcount_retry(&timekeeper.seq, seq));
1323}
1324
1325#ifdef CONFIG_HIGH_RES_TIMERS
1326/**
1327 * ktime_get_update_offsets - hrtimer helper
1328 * @offs_real: pointer to storage for monotonic -> realtime offset
1329 * @offs_boot: pointer to storage for monotonic -> boottime offset
1330 *
1331 * Returns current monotonic time and updates the offsets
1332 * Called from hrtimer_interupt() or retrigger_next_event()
1333 */
1334ktime_t ktime_get_update_offsets(ktime_t *offs_real, ktime_t *offs_boot)
1335{
1336 ktime_t now;
1337 unsigned int seq;
1338 u64 secs, nsecs;
1339
1340 do {
1341 seq = read_seqcount_begin(&timekeeper.seq);
1342
1343 secs = timekeeper.xtime.tv_sec;
1344 nsecs = timekeeper.xtime.tv_nsec;
1345 nsecs += timekeeping_get_ns();
1346 /* If arch requires, add in gettimeoffset() */
1347 nsecs += arch_gettimeoffset();
1348
1349 *offs_real = timekeeper.offs_real;
1350 *offs_boot = timekeeper.offs_boot;
1351 } while (read_seqcount_retry(&timekeeper.seq, seq));
1352
1353 now = ktime_add_ns(ktime_set(secs, 0), nsecs);
1354 now = ktime_sub(now, *offs_real);
1355 return now;
1356}
1357#endif
1358
1359/**
1360 * ktime_get_monotonic_offset() - get wall_to_monotonic in ktime_t format
1361 */
1362ktime_t ktime_get_monotonic_offset(void)
1363{
1364 unsigned long seq;
1365 struct timespec wtom;
1366
1367 do {
1368 seq = read_seqcount_begin(&timekeeper.seq);
1369 wtom = timekeeper.wall_to_monotonic;
1370 } while (read_seqcount_retry(&timekeeper.seq, seq));
1371
1372 return timespec_to_ktime(wtom);
1373}
1374EXPORT_SYMBOL_GPL(ktime_get_monotonic_offset);
1375
1376
1377/**
1378 * xtime_update() - advances the timekeeping infrastructure
1379 * @ticks: number of ticks, that have elapsed since the last call.
1380 *
1381 * Must be called with interrupts disabled.
1382 */
1383void xtime_update(unsigned long ticks)
1384{
1385 raw_spin_lock(&xtime_lock);
1386 write_seqcount_begin(&xtime_seq);
1387 do_timer(ticks);
1388 write_seqcount_end(&xtime_seq);
1389 raw_spin_unlock(&xtime_lock);
1390}