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 #include <linux/compiler.h>
26
27 #include "tick-internal.h"
28 #include "ntp_internal.h"
29 #include "timekeeping_internal.h"
30
31 #define TK_CLEAR_NTP (1 << 0)
32 #define TK_MIRROR (1 << 1)
33 #define TK_CLOCK_WAS_SET (1 << 2)
34
35 /*
36 * The most important data for readout fits into a single 64 byte
37 * cache line.
38 */
39 static struct {
40 seqcount_t seq;
41 struct timekeeper timekeeper;
42 } tk_core ____cacheline_aligned;
43
44 static DEFINE_RAW_SPINLOCK(timekeeper_lock);
45 static struct timekeeper shadow_timekeeper;
46
47 /**
48 * struct tk_fast - NMI safe timekeeper
49 * @seq: Sequence counter for protecting updates. The lowest bit
50 * is the index for the tk_read_base array
51 * @base: tk_read_base array. Access is indexed by the lowest bit of
52 * @seq.
53 *
54 * See @update_fast_timekeeper() below.
55 */
56 struct tk_fast {
57 seqcount_t seq;
58 struct tk_read_base base[2];
59 };
60
61 static struct tk_fast tk_fast_mono ____cacheline_aligned;
62 static struct tk_fast tk_fast_raw ____cacheline_aligned;
63
64 /* flag for if timekeeping is suspended */
65 int __read_mostly timekeeping_suspended;
66
tk_normalize_xtime(struct timekeeper * tk)67 static inline void tk_normalize_xtime(struct timekeeper *tk)
68 {
69 while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
70 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
71 tk->xtime_sec++;
72 }
73 while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
74 tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
75 tk->raw_sec++;
76 }
77 }
78
tk_xtime(struct timekeeper * tk)79 static inline struct timespec64 tk_xtime(struct timekeeper *tk)
80 {
81 struct timespec64 ts;
82
83 ts.tv_sec = tk->xtime_sec;
84 ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
85 return ts;
86 }
87
tk_set_xtime(struct timekeeper * tk,const struct timespec64 * ts)88 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
89 {
90 tk->xtime_sec = ts->tv_sec;
91 tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
92 }
93
tk_xtime_add(struct timekeeper * tk,const struct timespec64 * ts)94 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
95 {
96 tk->xtime_sec += ts->tv_sec;
97 tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
98 tk_normalize_xtime(tk);
99 }
100
tk_set_wall_to_mono(struct timekeeper * tk,struct timespec64 wtm)101 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
102 {
103 struct timespec64 tmp;
104
105 /*
106 * Verify consistency of: offset_real = -wall_to_monotonic
107 * before modifying anything
108 */
109 set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
110 -tk->wall_to_monotonic.tv_nsec);
111 WARN_ON_ONCE(tk->offs_real.tv64 != timespec64_to_ktime(tmp).tv64);
112 tk->wall_to_monotonic = wtm;
113 set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
114 tk->offs_real = timespec64_to_ktime(tmp);
115 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
116 }
117
tk_update_sleep_time(struct timekeeper * tk,ktime_t delta)118 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
119 {
120 tk->offs_boot = ktime_add(tk->offs_boot, delta);
121 }
122
123 /*
124 * tk_clock_read - atomic clocksource read() helper
125 *
126 * This helper is necessary to use in the read paths because, while the
127 * seqlock ensures we don't return a bad value while structures are updated,
128 * it doesn't protect from potential crashes. There is the possibility that
129 * the tkr's clocksource may change between the read reference, and the
130 * clock reference passed to the read function. This can cause crashes if
131 * the wrong clocksource is passed to the wrong read function.
132 * This isn't necessary to use when holding the timekeeper_lock or doing
133 * a read of the fast-timekeeper tkrs (which is protected by its own locking
134 * and update logic).
135 */
tk_clock_read(struct tk_read_base * tkr)136 static inline u64 tk_clock_read(struct tk_read_base *tkr)
137 {
138 struct clocksource *clock = READ_ONCE(tkr->clock);
139
140 return clock->read(clock);
141 }
142
143 #ifdef CONFIG_DEBUG_TIMEKEEPING
144 #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
145
timekeeping_check_update(struct timekeeper * tk,cycle_t offset)146 static void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
147 {
148
149 cycle_t max_cycles = tk->tkr_mono.clock->max_cycles;
150 const char *name = tk->tkr_mono.clock->name;
151
152 if (offset > max_cycles) {
153 printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
154 offset, name, max_cycles);
155 printk_deferred(" timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
156 } else {
157 if (offset > (max_cycles >> 1)) {
158 printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the '%s' clock's 50%% safety margin (%lld)\n",
159 offset, name, max_cycles >> 1);
160 printk_deferred(" timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
161 }
162 }
163
164 if (tk->underflow_seen) {
165 if (jiffies - tk->last_warning > WARNING_FREQ) {
166 printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
167 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
168 printk_deferred(" Your kernel is probably still fine.\n");
169 tk->last_warning = jiffies;
170 }
171 tk->underflow_seen = 0;
172 }
173
174 if (tk->overflow_seen) {
175 if (jiffies - tk->last_warning > WARNING_FREQ) {
176 printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
177 printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
178 printk_deferred(" Your kernel is probably still fine.\n");
179 tk->last_warning = jiffies;
180 }
181 tk->overflow_seen = 0;
182 }
183 }
184
timekeeping_get_delta(struct tk_read_base * tkr)185 static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
186 {
187 struct timekeeper *tk = &tk_core.timekeeper;
188 cycle_t now, last, mask, max, delta;
189 unsigned int seq;
190
191 /*
192 * Since we're called holding a seqlock, the data may shift
193 * under us while we're doing the calculation. This can cause
194 * false positives, since we'd note a problem but throw the
195 * results away. So nest another seqlock here to atomically
196 * grab the points we are checking with.
197 */
198 do {
199 seq = read_seqcount_begin(&tk_core.seq);
200 now = tk_clock_read(tkr);
201 last = tkr->cycle_last;
202 mask = tkr->mask;
203 max = tkr->clock->max_cycles;
204 } while (read_seqcount_retry(&tk_core.seq, seq));
205
206 delta = clocksource_delta(now, last, mask);
207
208 /*
209 * Try to catch underflows by checking if we are seeing small
210 * mask-relative negative values.
211 */
212 if (unlikely((~delta & mask) < (mask >> 3))) {
213 tk->underflow_seen = 1;
214 delta = 0;
215 }
216
217 /* Cap delta value to the max_cycles values to avoid mult overflows */
218 if (unlikely(delta > max)) {
219 tk->overflow_seen = 1;
220 delta = tkr->clock->max_cycles;
221 }
222
223 return delta;
224 }
225 #else
timekeeping_check_update(struct timekeeper * tk,cycle_t offset)226 static inline void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
227 {
228 }
timekeeping_get_delta(struct tk_read_base * tkr)229 static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
230 {
231 cycle_t cycle_now, delta;
232
233 /* read clocksource */
234 cycle_now = tk_clock_read(tkr);
235
236 /* calculate the delta since the last update_wall_time */
237 delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
238
239 return delta;
240 }
241 #endif
242
243 /**
244 * tk_setup_internals - Set up internals to use clocksource clock.
245 *
246 * @tk: The target timekeeper to setup.
247 * @clock: Pointer to clocksource.
248 *
249 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
250 * pair and interval request.
251 *
252 * Unless you're the timekeeping code, you should not be using this!
253 */
tk_setup_internals(struct timekeeper * tk,struct clocksource * clock)254 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
255 {
256 cycle_t interval;
257 u64 tmp, ntpinterval;
258 struct clocksource *old_clock;
259
260 ++tk->cs_was_changed_seq;
261 old_clock = tk->tkr_mono.clock;
262 tk->tkr_mono.clock = clock;
263 tk->tkr_mono.mask = clock->mask;
264 tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
265
266 tk->tkr_raw.clock = clock;
267 tk->tkr_raw.mask = clock->mask;
268 tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
269
270 /* Do the ns -> cycle conversion first, using original mult */
271 tmp = NTP_INTERVAL_LENGTH;
272 tmp <<= clock->shift;
273 ntpinterval = tmp;
274 tmp += clock->mult/2;
275 do_div(tmp, clock->mult);
276 if (tmp == 0)
277 tmp = 1;
278
279 interval = (cycle_t) tmp;
280 tk->cycle_interval = interval;
281
282 /* Go back from cycles -> shifted ns */
283 tk->xtime_interval = (u64) interval * clock->mult;
284 tk->xtime_remainder = ntpinterval - tk->xtime_interval;
285 tk->raw_interval = interval * clock->mult;
286
287 /* if changing clocks, convert xtime_nsec shift units */
288 if (old_clock) {
289 int shift_change = clock->shift - old_clock->shift;
290 if (shift_change < 0) {
291 tk->tkr_mono.xtime_nsec >>= -shift_change;
292 tk->tkr_raw.xtime_nsec >>= -shift_change;
293 } else {
294 tk->tkr_mono.xtime_nsec <<= shift_change;
295 tk->tkr_raw.xtime_nsec <<= shift_change;
296 }
297 }
298
299 tk->tkr_mono.shift = clock->shift;
300 tk->tkr_raw.shift = clock->shift;
301
302 tk->ntp_error = 0;
303 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
304 tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
305
306 /*
307 * The timekeeper keeps its own mult values for the currently
308 * active clocksource. These value will be adjusted via NTP
309 * to counteract clock drifting.
310 */
311 tk->tkr_mono.mult = clock->mult;
312 tk->tkr_raw.mult = clock->mult;
313 tk->ntp_err_mult = 0;
314 }
315
316 /* Timekeeper helper functions. */
317
318 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
default_arch_gettimeoffset(void)319 static u32 default_arch_gettimeoffset(void) { return 0; }
320 u32 (*arch_gettimeoffset)(void) = default_arch_gettimeoffset;
321 #else
arch_gettimeoffset(void)322 static inline u32 arch_gettimeoffset(void) { return 0; }
323 #endif
324
timekeeping_delta_to_ns(struct tk_read_base * tkr,cycle_t delta)325 static inline u64 timekeeping_delta_to_ns(struct tk_read_base *tkr,
326 cycle_t delta)
327 {
328 u64 nsec;
329
330 nsec = delta * tkr->mult + tkr->xtime_nsec;
331 nsec >>= tkr->shift;
332
333 /* If arch requires, add in get_arch_timeoffset() */
334 return nsec + arch_gettimeoffset();
335 }
336
timekeeping_get_ns(struct tk_read_base * tkr)337 static inline s64 timekeeping_get_ns(struct tk_read_base *tkr)
338 {
339 cycle_t delta;
340
341 delta = timekeeping_get_delta(tkr);
342 return timekeeping_delta_to_ns(tkr, delta);
343 }
344
timekeeping_cycles_to_ns(struct tk_read_base * tkr,cycle_t cycles)345 static inline s64 timekeeping_cycles_to_ns(struct tk_read_base *tkr,
346 cycle_t cycles)
347 {
348 cycle_t delta;
349
350 /* calculate the delta since the last update_wall_time */
351 delta = clocksource_delta(cycles, tkr->cycle_last, tkr->mask);
352 return timekeeping_delta_to_ns(tkr, delta);
353 }
354
355 /**
356 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
357 * @tkr: Timekeeping readout base from which we take the update
358 *
359 * We want to use this from any context including NMI and tracing /
360 * instrumenting the timekeeping code itself.
361 *
362 * Employ the latch technique; see @raw_write_seqcount_latch.
363 *
364 * So if a NMI hits the update of base[0] then it will use base[1]
365 * which is still consistent. In the worst case this can result is a
366 * slightly wrong timestamp (a few nanoseconds). See
367 * @ktime_get_mono_fast_ns.
368 */
update_fast_timekeeper(struct tk_read_base * tkr,struct tk_fast * tkf)369 static void update_fast_timekeeper(struct tk_read_base *tkr, struct tk_fast *tkf)
370 {
371 struct tk_read_base *base = tkf->base;
372
373 /* Force readers off to base[1] */
374 raw_write_seqcount_latch(&tkf->seq);
375
376 /* Update base[0] */
377 memcpy(base, tkr, sizeof(*base));
378
379 /* Force readers back to base[0] */
380 raw_write_seqcount_latch(&tkf->seq);
381
382 /* Update base[1] */
383 memcpy(base + 1, base, sizeof(*base));
384 }
385
386 /**
387 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
388 *
389 * This timestamp is not guaranteed to be monotonic across an update.
390 * The timestamp is calculated by:
391 *
392 * now = base_mono + clock_delta * slope
393 *
394 * So if the update lowers the slope, readers who are forced to the
395 * not yet updated second array are still using the old steeper slope.
396 *
397 * tmono
398 * ^
399 * | o n
400 * | o n
401 * | u
402 * | o
403 * |o
404 * |12345678---> reader order
405 *
406 * o = old slope
407 * u = update
408 * n = new slope
409 *
410 * So reader 6 will observe time going backwards versus reader 5.
411 *
412 * While other CPUs are likely to be able observe that, the only way
413 * for a CPU local observation is when an NMI hits in the middle of
414 * the update. Timestamps taken from that NMI context might be ahead
415 * of the following timestamps. Callers need to be aware of that and
416 * deal with it.
417 */
__ktime_get_fast_ns(struct tk_fast * tkf)418 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
419 {
420 struct tk_read_base *tkr;
421 unsigned int seq;
422 u64 now;
423
424 do {
425 seq = raw_read_seqcount_latch(&tkf->seq);
426 tkr = tkf->base + (seq & 0x01);
427 now = ktime_to_ns(tkr->base);
428
429 now += timekeeping_delta_to_ns(tkr,
430 clocksource_delta(
431 tk_clock_read(tkr),
432 tkr->cycle_last,
433 tkr->mask));
434 } while (read_seqcount_retry(&tkf->seq, seq));
435
436 return now;
437 }
438
ktime_get_mono_fast_ns(void)439 u64 ktime_get_mono_fast_ns(void)
440 {
441 return __ktime_get_fast_ns(&tk_fast_mono);
442 }
443 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
444
ktime_get_raw_fast_ns(void)445 u64 ktime_get_raw_fast_ns(void)
446 {
447 return __ktime_get_fast_ns(&tk_fast_raw);
448 }
449 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
450
451 /**
452 * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
453 *
454 * To keep it NMI safe since we're accessing from tracing, we're not using a
455 * separate timekeeper with updates to monotonic clock and boot offset
456 * protected with seqlocks. This has the following minor side effects:
457 *
458 * (1) Its possible that a timestamp be taken after the boot offset is updated
459 * but before the timekeeper is updated. If this happens, the new boot offset
460 * is added to the old timekeeping making the clock appear to update slightly
461 * earlier:
462 * CPU 0 CPU 1
463 * timekeeping_inject_sleeptime64()
464 * __timekeeping_inject_sleeptime(tk, delta);
465 * timestamp();
466 * timekeeping_update(tk, TK_CLEAR_NTP...);
467 *
468 * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
469 * partially updated. Since the tk->offs_boot update is a rare event, this
470 * should be a rare occurrence which postprocessing should be able to handle.
471 */
ktime_get_boot_fast_ns(void)472 u64 notrace ktime_get_boot_fast_ns(void)
473 {
474 struct timekeeper *tk = &tk_core.timekeeper;
475
476 return (ktime_get_mono_fast_ns() + ktime_to_ns(tk->offs_boot));
477 }
478 EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
479
480 /* Suspend-time cycles value for halted fast timekeeper. */
481 static cycle_t cycles_at_suspend;
482
dummy_clock_read(struct clocksource * cs)483 static cycle_t dummy_clock_read(struct clocksource *cs)
484 {
485 return cycles_at_suspend;
486 }
487
488 static struct clocksource dummy_clock = {
489 .read = dummy_clock_read,
490 };
491
492 /**
493 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
494 * @tk: Timekeeper to snapshot.
495 *
496 * It generally is unsafe to access the clocksource after timekeeping has been
497 * suspended, so take a snapshot of the readout base of @tk and use it as the
498 * fast timekeeper's readout base while suspended. It will return the same
499 * number of cycles every time until timekeeping is resumed at which time the
500 * proper readout base for the fast timekeeper will be restored automatically.
501 */
halt_fast_timekeeper(struct timekeeper * tk)502 static void halt_fast_timekeeper(struct timekeeper *tk)
503 {
504 static struct tk_read_base tkr_dummy;
505 struct tk_read_base *tkr = &tk->tkr_mono;
506
507 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
508 cycles_at_suspend = tk_clock_read(tkr);
509 tkr_dummy.clock = &dummy_clock;
510 update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
511
512 tkr = &tk->tkr_raw;
513 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
514 tkr_dummy.clock = &dummy_clock;
515 update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
516 }
517
518 #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
519
update_vsyscall(struct timekeeper * tk)520 static inline void update_vsyscall(struct timekeeper *tk)
521 {
522 struct timespec xt, wm;
523
524 xt = timespec64_to_timespec(tk_xtime(tk));
525 wm = timespec64_to_timespec(tk->wall_to_monotonic);
526 update_vsyscall_old(&xt, &wm, tk->tkr_mono.clock, tk->tkr_mono.mult,
527 tk->tkr_mono.cycle_last);
528 }
529
old_vsyscall_fixup(struct timekeeper * tk)530 static inline void old_vsyscall_fixup(struct timekeeper *tk)
531 {
532 s64 remainder;
533
534 /*
535 * Store only full nanoseconds into xtime_nsec after rounding
536 * it up and add the remainder to the error difference.
537 * XXX - This is necessary to avoid small 1ns inconsistnecies caused
538 * by truncating the remainder in vsyscalls. However, it causes
539 * additional work to be done in timekeeping_adjust(). Once
540 * the vsyscall implementations are converted to use xtime_nsec
541 * (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
542 * users are removed, this can be killed.
543 */
544 remainder = tk->tkr_mono.xtime_nsec & ((1ULL << tk->tkr_mono.shift) - 1);
545 if (remainder != 0) {
546 tk->tkr_mono.xtime_nsec -= remainder;
547 tk->tkr_mono.xtime_nsec += 1ULL << tk->tkr_mono.shift;
548 tk->ntp_error += remainder << tk->ntp_error_shift;
549 tk->ntp_error -= (1ULL << tk->tkr_mono.shift) << tk->ntp_error_shift;
550 }
551 }
552 #else
553 #define old_vsyscall_fixup(tk)
554 #endif
555
556 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
557
update_pvclock_gtod(struct timekeeper * tk,bool was_set)558 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
559 {
560 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
561 }
562
563 /**
564 * pvclock_gtod_register_notifier - register a pvclock timedata update listener
565 */
pvclock_gtod_register_notifier(struct notifier_block * nb)566 int pvclock_gtod_register_notifier(struct notifier_block *nb)
567 {
568 struct timekeeper *tk = &tk_core.timekeeper;
569 unsigned long flags;
570 int ret;
571
572 raw_spin_lock_irqsave(&timekeeper_lock, flags);
573 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
574 update_pvclock_gtod(tk, true);
575 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
576
577 return ret;
578 }
579 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
580
581 /**
582 * pvclock_gtod_unregister_notifier - unregister a pvclock
583 * timedata update listener
584 */
pvclock_gtod_unregister_notifier(struct notifier_block * nb)585 int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
586 {
587 unsigned long flags;
588 int ret;
589
590 raw_spin_lock_irqsave(&timekeeper_lock, flags);
591 ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
592 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
593
594 return ret;
595 }
596 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
597
598 /*
599 * tk_update_leap_state - helper to update the next_leap_ktime
600 */
tk_update_leap_state(struct timekeeper * tk)601 static inline void tk_update_leap_state(struct timekeeper *tk)
602 {
603 tk->next_leap_ktime = ntp_get_next_leap();
604 if (tk->next_leap_ktime.tv64 != KTIME_MAX)
605 /* Convert to monotonic time */
606 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
607 }
608
609 /*
610 * Update the ktime_t based scalar nsec members of the timekeeper
611 */
tk_update_ktime_data(struct timekeeper * tk)612 static inline void tk_update_ktime_data(struct timekeeper *tk)
613 {
614 u64 seconds;
615 u32 nsec;
616
617 /*
618 * The xtime based monotonic readout is:
619 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
620 * The ktime based monotonic readout is:
621 * nsec = base_mono + now();
622 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
623 */
624 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
625 nsec = (u32) tk->wall_to_monotonic.tv_nsec;
626 tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
627
628 /*
629 * The sum of the nanoseconds portions of xtime and
630 * wall_to_monotonic can be greater/equal one second. Take
631 * this into account before updating tk->ktime_sec.
632 */
633 nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
634 if (nsec >= NSEC_PER_SEC)
635 seconds++;
636 tk->ktime_sec = seconds;
637
638 /* Update the monotonic raw base */
639 tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
640 }
641
642 /* must hold timekeeper_lock */
timekeeping_update(struct timekeeper * tk,unsigned int action)643 static void timekeeping_update(struct timekeeper *tk, unsigned int action)
644 {
645 if (action & TK_CLEAR_NTP) {
646 tk->ntp_error = 0;
647 ntp_clear();
648 }
649
650 tk_update_leap_state(tk);
651 tk_update_ktime_data(tk);
652
653 update_vsyscall(tk);
654 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
655
656 update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
657 update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
658
659 if (action & TK_CLOCK_WAS_SET)
660 tk->clock_was_set_seq++;
661 /*
662 * The mirroring of the data to the shadow-timekeeper needs
663 * to happen last here to ensure we don't over-write the
664 * timekeeper structure on the next update with stale data
665 */
666 if (action & TK_MIRROR)
667 memcpy(&shadow_timekeeper, &tk_core.timekeeper,
668 sizeof(tk_core.timekeeper));
669 }
670
671 /**
672 * timekeeping_forward_now - update clock to the current time
673 *
674 * Forward the current clock to update its state since the last call to
675 * update_wall_time(). This is useful before significant clock changes,
676 * as it avoids having to deal with this time offset explicitly.
677 */
timekeeping_forward_now(struct timekeeper * tk)678 static void timekeeping_forward_now(struct timekeeper *tk)
679 {
680 cycle_t cycle_now, delta;
681
682 cycle_now = tk_clock_read(&tk->tkr_mono);
683 delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
684 tk->tkr_mono.cycle_last = cycle_now;
685 tk->tkr_raw.cycle_last = cycle_now;
686
687 tk->tkr_mono.xtime_nsec += delta * tk->tkr_mono.mult;
688
689 /* If arch requires, add in get_arch_timeoffset() */
690 tk->tkr_mono.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_mono.shift;
691
692
693 tk->tkr_raw.xtime_nsec += delta * tk->tkr_raw.mult;
694
695 /* If arch requires, add in get_arch_timeoffset() */
696 tk->tkr_raw.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_raw.shift;
697
698 tk_normalize_xtime(tk);
699 }
700
701 /**
702 * __getnstimeofday64 - Returns the time of day in a timespec64.
703 * @ts: pointer to the timespec to be set
704 *
705 * Updates the time of day in the timespec.
706 * Returns 0 on success, or -ve when suspended (timespec will be undefined).
707 */
__getnstimeofday64(struct timespec64 * ts)708 int __getnstimeofday64(struct timespec64 *ts)
709 {
710 struct timekeeper *tk = &tk_core.timekeeper;
711 unsigned long seq;
712 s64 nsecs = 0;
713
714 do {
715 seq = read_seqcount_begin(&tk_core.seq);
716
717 ts->tv_sec = tk->xtime_sec;
718 nsecs = timekeeping_get_ns(&tk->tkr_mono);
719
720 } while (read_seqcount_retry(&tk_core.seq, seq));
721
722 ts->tv_nsec = 0;
723 timespec64_add_ns(ts, nsecs);
724
725 /*
726 * Do not bail out early, in case there were callers still using
727 * the value, even in the face of the WARN_ON.
728 */
729 if (unlikely(timekeeping_suspended))
730 return -EAGAIN;
731 return 0;
732 }
733 EXPORT_SYMBOL(__getnstimeofday64);
734
735 /**
736 * getnstimeofday64 - Returns the time of day in a timespec64.
737 * @ts: pointer to the timespec64 to be set
738 *
739 * Returns the time of day in a timespec64 (WARN if suspended).
740 */
getnstimeofday64(struct timespec64 * ts)741 void getnstimeofday64(struct timespec64 *ts)
742 {
743 WARN_ON(__getnstimeofday64(ts));
744 }
745 EXPORT_SYMBOL(getnstimeofday64);
746
ktime_get(void)747 ktime_t ktime_get(void)
748 {
749 struct timekeeper *tk = &tk_core.timekeeper;
750 unsigned int seq;
751 ktime_t base;
752 s64 nsecs;
753
754 WARN_ON(timekeeping_suspended);
755
756 do {
757 seq = read_seqcount_begin(&tk_core.seq);
758 base = tk->tkr_mono.base;
759 nsecs = timekeeping_get_ns(&tk->tkr_mono);
760
761 } while (read_seqcount_retry(&tk_core.seq, seq));
762
763 return ktime_add_ns(base, nsecs);
764 }
765 EXPORT_SYMBOL_GPL(ktime_get);
766
ktime_get_resolution_ns(void)767 u32 ktime_get_resolution_ns(void)
768 {
769 struct timekeeper *tk = &tk_core.timekeeper;
770 unsigned int seq;
771 u32 nsecs;
772
773 WARN_ON(timekeeping_suspended);
774
775 do {
776 seq = read_seqcount_begin(&tk_core.seq);
777 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
778 } while (read_seqcount_retry(&tk_core.seq, seq));
779
780 return nsecs;
781 }
782 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
783
784 static ktime_t *offsets[TK_OFFS_MAX] = {
785 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
786 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
787 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
788 };
789
ktime_get_with_offset(enum tk_offsets offs)790 ktime_t ktime_get_with_offset(enum tk_offsets offs)
791 {
792 struct timekeeper *tk = &tk_core.timekeeper;
793 unsigned int seq;
794 ktime_t base, *offset = offsets[offs];
795 s64 nsecs;
796
797 WARN_ON(timekeeping_suspended);
798
799 do {
800 seq = read_seqcount_begin(&tk_core.seq);
801 base = ktime_add(tk->tkr_mono.base, *offset);
802 nsecs = timekeeping_get_ns(&tk->tkr_mono);
803
804 } while (read_seqcount_retry(&tk_core.seq, seq));
805
806 return ktime_add_ns(base, nsecs);
807
808 }
809 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
810
811 /**
812 * ktime_mono_to_any() - convert mononotic time to any other time
813 * @tmono: time to convert.
814 * @offs: which offset to use
815 */
ktime_mono_to_any(ktime_t tmono,enum tk_offsets offs)816 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
817 {
818 ktime_t *offset = offsets[offs];
819 unsigned long seq;
820 ktime_t tconv;
821
822 do {
823 seq = read_seqcount_begin(&tk_core.seq);
824 tconv = ktime_add(tmono, *offset);
825 } while (read_seqcount_retry(&tk_core.seq, seq));
826
827 return tconv;
828 }
829 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
830
831 /**
832 * ktime_get_raw - Returns the raw monotonic time in ktime_t format
833 */
ktime_get_raw(void)834 ktime_t ktime_get_raw(void)
835 {
836 struct timekeeper *tk = &tk_core.timekeeper;
837 unsigned int seq;
838 ktime_t base;
839 s64 nsecs;
840
841 do {
842 seq = read_seqcount_begin(&tk_core.seq);
843 base = tk->tkr_raw.base;
844 nsecs = timekeeping_get_ns(&tk->tkr_raw);
845
846 } while (read_seqcount_retry(&tk_core.seq, seq));
847
848 return ktime_add_ns(base, nsecs);
849 }
850 EXPORT_SYMBOL_GPL(ktime_get_raw);
851
852 /**
853 * ktime_get_ts64 - get the monotonic clock in timespec64 format
854 * @ts: pointer to timespec variable
855 *
856 * The function calculates the monotonic clock from the realtime
857 * clock and the wall_to_monotonic offset and stores the result
858 * in normalized timespec64 format in the variable pointed to by @ts.
859 */
ktime_get_ts64(struct timespec64 * ts)860 void ktime_get_ts64(struct timespec64 *ts)
861 {
862 struct timekeeper *tk = &tk_core.timekeeper;
863 struct timespec64 tomono;
864 s64 nsec;
865 unsigned int seq;
866
867 WARN_ON(timekeeping_suspended);
868
869 do {
870 seq = read_seqcount_begin(&tk_core.seq);
871 ts->tv_sec = tk->xtime_sec;
872 nsec = timekeeping_get_ns(&tk->tkr_mono);
873 tomono = tk->wall_to_monotonic;
874
875 } while (read_seqcount_retry(&tk_core.seq, seq));
876
877 ts->tv_sec += tomono.tv_sec;
878 ts->tv_nsec = 0;
879 timespec64_add_ns(ts, nsec + tomono.tv_nsec);
880 }
881 EXPORT_SYMBOL_GPL(ktime_get_ts64);
882
883 /**
884 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
885 *
886 * Returns the seconds portion of CLOCK_MONOTONIC with a single non
887 * serialized read. tk->ktime_sec is of type 'unsigned long' so this
888 * works on both 32 and 64 bit systems. On 32 bit systems the readout
889 * covers ~136 years of uptime which should be enough to prevent
890 * premature wrap arounds.
891 */
ktime_get_seconds(void)892 time64_t ktime_get_seconds(void)
893 {
894 struct timekeeper *tk = &tk_core.timekeeper;
895
896 WARN_ON(timekeeping_suspended);
897 return tk->ktime_sec;
898 }
899 EXPORT_SYMBOL_GPL(ktime_get_seconds);
900
901 /**
902 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
903 *
904 * Returns the wall clock seconds since 1970. This replaces the
905 * get_seconds() interface which is not y2038 safe on 32bit systems.
906 *
907 * For 64bit systems the fast access to tk->xtime_sec is preserved. On
908 * 32bit systems the access must be protected with the sequence
909 * counter to provide "atomic" access to the 64bit tk->xtime_sec
910 * value.
911 */
ktime_get_real_seconds(void)912 time64_t ktime_get_real_seconds(void)
913 {
914 struct timekeeper *tk = &tk_core.timekeeper;
915 time64_t seconds;
916 unsigned int seq;
917
918 if (IS_ENABLED(CONFIG_64BIT))
919 return tk->xtime_sec;
920
921 do {
922 seq = read_seqcount_begin(&tk_core.seq);
923 seconds = tk->xtime_sec;
924
925 } while (read_seqcount_retry(&tk_core.seq, seq));
926
927 return seconds;
928 }
929 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
930
931 /**
932 * __ktime_get_real_seconds - The same as ktime_get_real_seconds
933 * but without the sequence counter protect. This internal function
934 * is called just when timekeeping lock is already held.
935 */
__ktime_get_real_seconds(void)936 time64_t __ktime_get_real_seconds(void)
937 {
938 struct timekeeper *tk = &tk_core.timekeeper;
939
940 return tk->xtime_sec;
941 }
942
943 /**
944 * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
945 * @systime_snapshot: pointer to struct receiving the system time snapshot
946 */
ktime_get_snapshot(struct system_time_snapshot * systime_snapshot)947 void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
948 {
949 struct timekeeper *tk = &tk_core.timekeeper;
950 unsigned long seq;
951 ktime_t base_raw;
952 ktime_t base_real;
953 s64 nsec_raw;
954 s64 nsec_real;
955 cycle_t now;
956
957 WARN_ON_ONCE(timekeeping_suspended);
958
959 do {
960 seq = read_seqcount_begin(&tk_core.seq);
961 now = tk_clock_read(&tk->tkr_mono);
962 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
963 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
964 base_real = ktime_add(tk->tkr_mono.base,
965 tk_core.timekeeper.offs_real);
966 base_raw = tk->tkr_raw.base;
967 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
968 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
969 } while (read_seqcount_retry(&tk_core.seq, seq));
970
971 systime_snapshot->cycles = now;
972 systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
973 systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
974 }
975 EXPORT_SYMBOL_GPL(ktime_get_snapshot);
976
977 /* Scale base by mult/div checking for overflow */
scale64_check_overflow(u64 mult,u64 div,u64 * base)978 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
979 {
980 u64 tmp, rem;
981
982 tmp = div64_u64_rem(*base, div, &rem);
983
984 if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
985 ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
986 return -EOVERFLOW;
987 tmp *= mult;
988 rem *= mult;
989
990 do_div(rem, div);
991 *base = tmp + rem;
992 return 0;
993 }
994
995 /**
996 * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
997 * @history: Snapshot representing start of history
998 * @partial_history_cycles: Cycle offset into history (fractional part)
999 * @total_history_cycles: Total history length in cycles
1000 * @discontinuity: True indicates clock was set on history period
1001 * @ts: Cross timestamp that should be adjusted using
1002 * partial/total ratio
1003 *
1004 * Helper function used by get_device_system_crosststamp() to correct the
1005 * crosstimestamp corresponding to the start of the current interval to the
1006 * system counter value (timestamp point) provided by the driver. The
1007 * total_history_* quantities are the total history starting at the provided
1008 * reference point and ending at the start of the current interval. The cycle
1009 * count between the driver timestamp point and the start of the current
1010 * interval is partial_history_cycles.
1011 */
adjust_historical_crosststamp(struct system_time_snapshot * history,cycle_t partial_history_cycles,cycle_t total_history_cycles,bool discontinuity,struct system_device_crosststamp * ts)1012 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1013 cycle_t partial_history_cycles,
1014 cycle_t total_history_cycles,
1015 bool discontinuity,
1016 struct system_device_crosststamp *ts)
1017 {
1018 struct timekeeper *tk = &tk_core.timekeeper;
1019 u64 corr_raw, corr_real;
1020 bool interp_forward;
1021 int ret;
1022
1023 if (total_history_cycles == 0 || partial_history_cycles == 0)
1024 return 0;
1025
1026 /* Interpolate shortest distance from beginning or end of history */
1027 interp_forward = partial_history_cycles > total_history_cycles/2 ?
1028 true : false;
1029 partial_history_cycles = interp_forward ?
1030 total_history_cycles - partial_history_cycles :
1031 partial_history_cycles;
1032
1033 /*
1034 * Scale the monotonic raw time delta by:
1035 * partial_history_cycles / total_history_cycles
1036 */
1037 corr_raw = (u64)ktime_to_ns(
1038 ktime_sub(ts->sys_monoraw, history->raw));
1039 ret = scale64_check_overflow(partial_history_cycles,
1040 total_history_cycles, &corr_raw);
1041 if (ret)
1042 return ret;
1043
1044 /*
1045 * If there is a discontinuity in the history, scale monotonic raw
1046 * correction by:
1047 * mult(real)/mult(raw) yielding the realtime correction
1048 * Otherwise, calculate the realtime correction similar to monotonic
1049 * raw calculation
1050 */
1051 if (discontinuity) {
1052 corr_real = mul_u64_u32_div
1053 (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1054 } else {
1055 corr_real = (u64)ktime_to_ns(
1056 ktime_sub(ts->sys_realtime, history->real));
1057 ret = scale64_check_overflow(partial_history_cycles,
1058 total_history_cycles, &corr_real);
1059 if (ret)
1060 return ret;
1061 }
1062
1063 /* Fixup monotonic raw and real time time values */
1064 if (interp_forward) {
1065 ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1066 ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1067 } else {
1068 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1069 ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1070 }
1071
1072 return 0;
1073 }
1074
1075 /*
1076 * cycle_between - true if test occurs chronologically between before and after
1077 */
cycle_between(cycle_t before,cycle_t test,cycle_t after)1078 static bool cycle_between(cycle_t before, cycle_t test, cycle_t after)
1079 {
1080 if (test > before && test < after)
1081 return true;
1082 if (test < before && before > after)
1083 return true;
1084 return false;
1085 }
1086
1087 /**
1088 * get_device_system_crosststamp - Synchronously capture system/device timestamp
1089 * @get_time_fn: Callback to get simultaneous device time and
1090 * system counter from the device driver
1091 * @ctx: Context passed to get_time_fn()
1092 * @history_begin: Historical reference point used to interpolate system
1093 * time when counter provided by the driver is before the current interval
1094 * @xtstamp: Receives simultaneously captured system and device time
1095 *
1096 * Reads a timestamp from a device and correlates it to system time
1097 */
get_device_system_crosststamp(int (* get_time_fn)(ktime_t * device_time,struct system_counterval_t * sys_counterval,void * ctx),void * ctx,struct system_time_snapshot * history_begin,struct system_device_crosststamp * xtstamp)1098 int get_device_system_crosststamp(int (*get_time_fn)
1099 (ktime_t *device_time,
1100 struct system_counterval_t *sys_counterval,
1101 void *ctx),
1102 void *ctx,
1103 struct system_time_snapshot *history_begin,
1104 struct system_device_crosststamp *xtstamp)
1105 {
1106 struct system_counterval_t system_counterval;
1107 struct timekeeper *tk = &tk_core.timekeeper;
1108 cycle_t cycles, now, interval_start;
1109 unsigned int clock_was_set_seq = 0;
1110 ktime_t base_real, base_raw;
1111 s64 nsec_real, nsec_raw;
1112 u8 cs_was_changed_seq;
1113 unsigned long seq;
1114 bool do_interp;
1115 int ret;
1116
1117 do {
1118 seq = read_seqcount_begin(&tk_core.seq);
1119 /*
1120 * Try to synchronously capture device time and a system
1121 * counter value calling back into the device driver
1122 */
1123 ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1124 if (ret)
1125 return ret;
1126
1127 /*
1128 * Verify that the clocksource associated with the captured
1129 * system counter value is the same as the currently installed
1130 * timekeeper clocksource
1131 */
1132 if (tk->tkr_mono.clock != system_counterval.cs)
1133 return -ENODEV;
1134 cycles = system_counterval.cycles;
1135
1136 /*
1137 * Check whether the system counter value provided by the
1138 * device driver is on the current timekeeping interval.
1139 */
1140 now = tk_clock_read(&tk->tkr_mono);
1141 interval_start = tk->tkr_mono.cycle_last;
1142 if (!cycle_between(interval_start, cycles, now)) {
1143 clock_was_set_seq = tk->clock_was_set_seq;
1144 cs_was_changed_seq = tk->cs_was_changed_seq;
1145 cycles = interval_start;
1146 do_interp = true;
1147 } else {
1148 do_interp = false;
1149 }
1150
1151 base_real = ktime_add(tk->tkr_mono.base,
1152 tk_core.timekeeper.offs_real);
1153 base_raw = tk->tkr_raw.base;
1154
1155 nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono,
1156 system_counterval.cycles);
1157 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw,
1158 system_counterval.cycles);
1159 } while (read_seqcount_retry(&tk_core.seq, seq));
1160
1161 xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1162 xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1163
1164 /*
1165 * Interpolate if necessary, adjusting back from the start of the
1166 * current interval
1167 */
1168 if (do_interp) {
1169 cycle_t partial_history_cycles, total_history_cycles;
1170 bool discontinuity;
1171
1172 /*
1173 * Check that the counter value occurs after the provided
1174 * history reference and that the history doesn't cross a
1175 * clocksource change
1176 */
1177 if (!history_begin ||
1178 !cycle_between(history_begin->cycles,
1179 system_counterval.cycles, cycles) ||
1180 history_begin->cs_was_changed_seq != cs_was_changed_seq)
1181 return -EINVAL;
1182 partial_history_cycles = cycles - system_counterval.cycles;
1183 total_history_cycles = cycles - history_begin->cycles;
1184 discontinuity =
1185 history_begin->clock_was_set_seq != clock_was_set_seq;
1186
1187 ret = adjust_historical_crosststamp(history_begin,
1188 partial_history_cycles,
1189 total_history_cycles,
1190 discontinuity, xtstamp);
1191 if (ret)
1192 return ret;
1193 }
1194
1195 return 0;
1196 }
1197 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1198
1199 /**
1200 * do_gettimeofday - Returns the time of day in a timeval
1201 * @tv: pointer to the timeval to be set
1202 *
1203 * NOTE: Users should be converted to using getnstimeofday()
1204 */
do_gettimeofday(struct timeval * tv)1205 void do_gettimeofday(struct timeval *tv)
1206 {
1207 struct timespec64 now;
1208
1209 getnstimeofday64(&now);
1210 tv->tv_sec = now.tv_sec;
1211 tv->tv_usec = now.tv_nsec/1000;
1212 }
1213 EXPORT_SYMBOL(do_gettimeofday);
1214
1215 /**
1216 * do_settimeofday64 - Sets the time of day.
1217 * @ts: pointer to the timespec64 variable containing the new time
1218 *
1219 * Sets the time of day to the new time and update NTP and notify hrtimers
1220 */
do_settimeofday64(const struct timespec64 * ts)1221 int do_settimeofday64(const struct timespec64 *ts)
1222 {
1223 struct timekeeper *tk = &tk_core.timekeeper;
1224 struct timespec64 ts_delta, xt;
1225 unsigned long flags;
1226 int ret = 0;
1227
1228 if (!timespec64_valid_strict(ts))
1229 return -EINVAL;
1230
1231 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1232 write_seqcount_begin(&tk_core.seq);
1233
1234 timekeeping_forward_now(tk);
1235
1236 xt = tk_xtime(tk);
1237 ts_delta.tv_sec = ts->tv_sec - xt.tv_sec;
1238 ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
1239
1240 if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
1241 ret = -EINVAL;
1242 goto out;
1243 }
1244
1245 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
1246
1247 tk_set_xtime(tk, ts);
1248 out:
1249 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1250
1251 write_seqcount_end(&tk_core.seq);
1252 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1253
1254 /* signal hrtimers about time change */
1255 clock_was_set();
1256
1257 return ret;
1258 }
1259 EXPORT_SYMBOL(do_settimeofday64);
1260
1261 /**
1262 * timekeeping_inject_offset - Adds or subtracts from the current time.
1263 * @tv: pointer to the timespec variable containing the offset
1264 *
1265 * Adds or subtracts an offset value from the current time.
1266 */
timekeeping_inject_offset(struct timespec * ts)1267 int timekeeping_inject_offset(struct timespec *ts)
1268 {
1269 struct timekeeper *tk = &tk_core.timekeeper;
1270 unsigned long flags;
1271 struct timespec64 ts64, tmp;
1272 int ret = 0;
1273
1274 if (!timespec_inject_offset_valid(ts))
1275 return -EINVAL;
1276
1277 ts64 = timespec_to_timespec64(*ts);
1278
1279 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1280 write_seqcount_begin(&tk_core.seq);
1281
1282 timekeeping_forward_now(tk);
1283
1284 /* Make sure the proposed value is valid */
1285 tmp = timespec64_add(tk_xtime(tk), ts64);
1286 if (timespec64_compare(&tk->wall_to_monotonic, &ts64) > 0 ||
1287 !timespec64_valid_strict(&tmp)) {
1288 ret = -EINVAL;
1289 goto error;
1290 }
1291
1292 tk_xtime_add(tk, &ts64);
1293 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
1294
1295 error: /* even if we error out, we forwarded the time, so call update */
1296 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1297
1298 write_seqcount_end(&tk_core.seq);
1299 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1300
1301 /* signal hrtimers about time change */
1302 clock_was_set();
1303
1304 return ret;
1305 }
1306 EXPORT_SYMBOL(timekeeping_inject_offset);
1307
1308
1309 /**
1310 * timekeeping_get_tai_offset - Returns current TAI offset from UTC
1311 *
1312 */
timekeeping_get_tai_offset(void)1313 s32 timekeeping_get_tai_offset(void)
1314 {
1315 struct timekeeper *tk = &tk_core.timekeeper;
1316 unsigned int seq;
1317 s32 ret;
1318
1319 do {
1320 seq = read_seqcount_begin(&tk_core.seq);
1321 ret = tk->tai_offset;
1322 } while (read_seqcount_retry(&tk_core.seq, seq));
1323
1324 return ret;
1325 }
1326
1327 /**
1328 * __timekeeping_set_tai_offset - Lock free worker function
1329 *
1330 */
__timekeeping_set_tai_offset(struct timekeeper * tk,s32 tai_offset)1331 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1332 {
1333 tk->tai_offset = tai_offset;
1334 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1335 }
1336
1337 /**
1338 * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
1339 *
1340 */
timekeeping_set_tai_offset(s32 tai_offset)1341 void timekeeping_set_tai_offset(s32 tai_offset)
1342 {
1343 struct timekeeper *tk = &tk_core.timekeeper;
1344 unsigned long flags;
1345
1346 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1347 write_seqcount_begin(&tk_core.seq);
1348 __timekeeping_set_tai_offset(tk, tai_offset);
1349 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1350 write_seqcount_end(&tk_core.seq);
1351 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1352 clock_was_set();
1353 }
1354
1355 /**
1356 * change_clocksource - Swaps clocksources if a new one is available
1357 *
1358 * Accumulates current time interval and initializes new clocksource
1359 */
change_clocksource(void * data)1360 static int change_clocksource(void *data)
1361 {
1362 struct timekeeper *tk = &tk_core.timekeeper;
1363 struct clocksource *new, *old;
1364 unsigned long flags;
1365
1366 new = (struct clocksource *) data;
1367
1368 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1369 write_seqcount_begin(&tk_core.seq);
1370
1371 timekeeping_forward_now(tk);
1372 /*
1373 * If the cs is in module, get a module reference. Succeeds
1374 * for built-in code (owner == NULL) as well.
1375 */
1376 if (try_module_get(new->owner)) {
1377 if (!new->enable || new->enable(new) == 0) {
1378 old = tk->tkr_mono.clock;
1379 tk_setup_internals(tk, new);
1380 if (old->disable)
1381 old->disable(old);
1382 module_put(old->owner);
1383 } else {
1384 module_put(new->owner);
1385 }
1386 }
1387 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1388
1389 write_seqcount_end(&tk_core.seq);
1390 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1391
1392 return 0;
1393 }
1394
1395 /**
1396 * timekeeping_notify - Install a new clock source
1397 * @clock: pointer to the clock source
1398 *
1399 * This function is called from clocksource.c after a new, better clock
1400 * source has been registered. The caller holds the clocksource_mutex.
1401 */
timekeeping_notify(struct clocksource * clock)1402 int timekeeping_notify(struct clocksource *clock)
1403 {
1404 struct timekeeper *tk = &tk_core.timekeeper;
1405
1406 if (tk->tkr_mono.clock == clock)
1407 return 0;
1408 stop_machine(change_clocksource, clock, NULL);
1409 tick_clock_notify();
1410 return tk->tkr_mono.clock == clock ? 0 : -1;
1411 }
1412
1413 /**
1414 * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1415 * @ts: pointer to the timespec64 to be set
1416 *
1417 * Returns the raw monotonic time (completely un-modified by ntp)
1418 */
getrawmonotonic64(struct timespec64 * ts)1419 void getrawmonotonic64(struct timespec64 *ts)
1420 {
1421 struct timekeeper *tk = &tk_core.timekeeper;
1422 unsigned long seq;
1423 s64 nsecs;
1424
1425 do {
1426 seq = read_seqcount_begin(&tk_core.seq);
1427 ts->tv_sec = tk->raw_sec;
1428 nsecs = timekeeping_get_ns(&tk->tkr_raw);
1429
1430 } while (read_seqcount_retry(&tk_core.seq, seq));
1431
1432 ts->tv_nsec = 0;
1433 timespec64_add_ns(ts, nsecs);
1434 }
1435 EXPORT_SYMBOL(getrawmonotonic64);
1436
1437
1438 /**
1439 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1440 */
timekeeping_valid_for_hres(void)1441 int timekeeping_valid_for_hres(void)
1442 {
1443 struct timekeeper *tk = &tk_core.timekeeper;
1444 unsigned long seq;
1445 int ret;
1446
1447 do {
1448 seq = read_seqcount_begin(&tk_core.seq);
1449
1450 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1451
1452 } while (read_seqcount_retry(&tk_core.seq, seq));
1453
1454 return ret;
1455 }
1456
1457 /**
1458 * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1459 */
timekeeping_max_deferment(void)1460 u64 timekeeping_max_deferment(void)
1461 {
1462 struct timekeeper *tk = &tk_core.timekeeper;
1463 unsigned long seq;
1464 u64 ret;
1465
1466 do {
1467 seq = read_seqcount_begin(&tk_core.seq);
1468
1469 ret = tk->tkr_mono.clock->max_idle_ns;
1470
1471 } while (read_seqcount_retry(&tk_core.seq, seq));
1472
1473 return ret;
1474 }
1475
1476 /**
1477 * read_persistent_clock - Return time from the persistent clock.
1478 *
1479 * Weak dummy function for arches that do not yet support it.
1480 * Reads the time from the battery backed persistent clock.
1481 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1482 *
1483 * XXX - Do be sure to remove it once all arches implement it.
1484 */
read_persistent_clock(struct timespec * ts)1485 void __weak read_persistent_clock(struct timespec *ts)
1486 {
1487 ts->tv_sec = 0;
1488 ts->tv_nsec = 0;
1489 }
1490
read_persistent_clock64(struct timespec64 * ts64)1491 void __weak read_persistent_clock64(struct timespec64 *ts64)
1492 {
1493 struct timespec ts;
1494
1495 read_persistent_clock(&ts);
1496 *ts64 = timespec_to_timespec64(ts);
1497 }
1498
1499 /**
1500 * read_boot_clock64 - Return time of the system start.
1501 *
1502 * Weak dummy function for arches that do not yet support it.
1503 * Function to read the exact time the system has been started.
1504 * Returns a timespec64 with tv_sec=0 and tv_nsec=0 if unsupported.
1505 *
1506 * XXX - Do be sure to remove it once all arches implement it.
1507 */
read_boot_clock64(struct timespec64 * ts)1508 void __weak read_boot_clock64(struct timespec64 *ts)
1509 {
1510 ts->tv_sec = 0;
1511 ts->tv_nsec = 0;
1512 }
1513
1514 /* Flag for if timekeeping_resume() has injected sleeptime */
1515 static bool sleeptime_injected;
1516
1517 /* Flag for if there is a persistent clock on this platform */
1518 static bool persistent_clock_exists;
1519
1520 /*
1521 * timekeeping_init - Initializes the clocksource and common timekeeping values
1522 */
timekeeping_init(void)1523 void __init timekeeping_init(void)
1524 {
1525 struct timekeeper *tk = &tk_core.timekeeper;
1526 struct clocksource *clock;
1527 unsigned long flags;
1528 struct timespec64 now, boot, tmp;
1529
1530 read_persistent_clock64(&now);
1531 if (!timespec64_valid_strict(&now)) {
1532 pr_warn("WARNING: Persistent clock returned invalid value!\n"
1533 " Check your CMOS/BIOS settings.\n");
1534 now.tv_sec = 0;
1535 now.tv_nsec = 0;
1536 } else if (now.tv_sec || now.tv_nsec)
1537 persistent_clock_exists = true;
1538
1539 read_boot_clock64(&boot);
1540 if (!timespec64_valid_strict(&boot)) {
1541 pr_warn("WARNING: Boot clock returned invalid value!\n"
1542 " Check your CMOS/BIOS settings.\n");
1543 boot.tv_sec = 0;
1544 boot.tv_nsec = 0;
1545 }
1546
1547 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1548 write_seqcount_begin(&tk_core.seq);
1549 ntp_init();
1550
1551 clock = clocksource_default_clock();
1552 if (clock->enable)
1553 clock->enable(clock);
1554 tk_setup_internals(tk, clock);
1555
1556 tk_set_xtime(tk, &now);
1557 tk->raw_sec = 0;
1558 if (boot.tv_sec == 0 && boot.tv_nsec == 0)
1559 boot = tk_xtime(tk);
1560
1561 set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
1562 tk_set_wall_to_mono(tk, tmp);
1563
1564 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1565
1566 write_seqcount_end(&tk_core.seq);
1567 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1568 }
1569
1570 /* time in seconds when suspend began for persistent clock */
1571 static struct timespec64 timekeeping_suspend_time;
1572
1573 /**
1574 * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1575 * @delta: pointer to a timespec delta value
1576 *
1577 * Takes a timespec offset measuring a suspend interval and properly
1578 * adds the sleep offset to the timekeeping variables.
1579 */
__timekeeping_inject_sleeptime(struct timekeeper * tk,struct timespec64 * delta)1580 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1581 struct timespec64 *delta)
1582 {
1583 if (!timespec64_valid_strict(delta)) {
1584 printk_deferred(KERN_WARNING
1585 "__timekeeping_inject_sleeptime: Invalid "
1586 "sleep delta value!\n");
1587 return;
1588 }
1589 tk_xtime_add(tk, delta);
1590 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1591 tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1592 tk_debug_account_sleep_time(delta);
1593 }
1594
1595 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1596 /**
1597 * We have three kinds of time sources to use for sleep time
1598 * injection, the preference order is:
1599 * 1) non-stop clocksource
1600 * 2) persistent clock (ie: RTC accessible when irqs are off)
1601 * 3) RTC
1602 *
1603 * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1604 * If system has neither 1) nor 2), 3) will be used finally.
1605 *
1606 *
1607 * If timekeeping has injected sleeptime via either 1) or 2),
1608 * 3) becomes needless, so in this case we don't need to call
1609 * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1610 * means.
1611 */
timekeeping_rtc_skipresume(void)1612 bool timekeeping_rtc_skipresume(void)
1613 {
1614 return sleeptime_injected;
1615 }
1616
1617 /**
1618 * 1) can be determined whether to use or not only when doing
1619 * timekeeping_resume() which is invoked after rtc_suspend(),
1620 * so we can't skip rtc_suspend() surely if system has 1).
1621 *
1622 * But if system has 2), 2) will definitely be used, so in this
1623 * case we don't need to call rtc_suspend(), and this is what
1624 * timekeeping_rtc_skipsuspend() means.
1625 */
timekeeping_rtc_skipsuspend(void)1626 bool timekeeping_rtc_skipsuspend(void)
1627 {
1628 return persistent_clock_exists;
1629 }
1630
1631 /**
1632 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1633 * @delta: pointer to a timespec64 delta value
1634 *
1635 * This hook is for architectures that cannot support read_persistent_clock64
1636 * because their RTC/persistent clock is only accessible when irqs are enabled.
1637 * and also don't have an effective nonstop clocksource.
1638 *
1639 * This function should only be called by rtc_resume(), and allows
1640 * a suspend offset to be injected into the timekeeping values.
1641 */
timekeeping_inject_sleeptime64(struct timespec64 * delta)1642 void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1643 {
1644 struct timekeeper *tk = &tk_core.timekeeper;
1645 unsigned long flags;
1646
1647 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1648 write_seqcount_begin(&tk_core.seq);
1649
1650 timekeeping_forward_now(tk);
1651
1652 __timekeeping_inject_sleeptime(tk, delta);
1653
1654 timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1655
1656 write_seqcount_end(&tk_core.seq);
1657 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1658
1659 /* signal hrtimers about time change */
1660 clock_was_set();
1661 }
1662 #endif
1663
1664 /**
1665 * timekeeping_resume - Resumes the generic timekeeping subsystem.
1666 */
timekeeping_resume(void)1667 void timekeeping_resume(void)
1668 {
1669 struct timekeeper *tk = &tk_core.timekeeper;
1670 struct clocksource *clock = tk->tkr_mono.clock;
1671 unsigned long flags;
1672 struct timespec64 ts_new, ts_delta;
1673 cycle_t cycle_now, cycle_delta;
1674
1675 sleeptime_injected = false;
1676 read_persistent_clock64(&ts_new);
1677
1678 clockevents_resume();
1679 clocksource_resume();
1680
1681 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1682 write_seqcount_begin(&tk_core.seq);
1683
1684 /*
1685 * After system resumes, we need to calculate the suspended time and
1686 * compensate it for the OS time. There are 3 sources that could be
1687 * used: Nonstop clocksource during suspend, persistent clock and rtc
1688 * device.
1689 *
1690 * One specific platform may have 1 or 2 or all of them, and the
1691 * preference will be:
1692 * suspend-nonstop clocksource -> persistent clock -> rtc
1693 * The less preferred source will only be tried if there is no better
1694 * usable source. The rtc part is handled separately in rtc core code.
1695 */
1696 cycle_now = tk_clock_read(&tk->tkr_mono);
1697 if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1698 cycle_now > tk->tkr_mono.cycle_last) {
1699 u64 num, max = ULLONG_MAX;
1700 u32 mult = clock->mult;
1701 u32 shift = clock->shift;
1702 s64 nsec = 0;
1703
1704 cycle_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1705 tk->tkr_mono.mask);
1706
1707 /*
1708 * "cycle_delta * mutl" may cause 64 bits overflow, if the
1709 * suspended time is too long. In that case we need do the
1710 * 64 bits math carefully
1711 */
1712 do_div(max, mult);
1713 if (cycle_delta > max) {
1714 num = div64_u64(cycle_delta, max);
1715 nsec = (((u64) max * mult) >> shift) * num;
1716 cycle_delta -= num * max;
1717 }
1718 nsec += ((u64) cycle_delta * mult) >> shift;
1719
1720 ts_delta = ns_to_timespec64(nsec);
1721 sleeptime_injected = true;
1722 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1723 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1724 sleeptime_injected = true;
1725 }
1726
1727 if (sleeptime_injected)
1728 __timekeeping_inject_sleeptime(tk, &ts_delta);
1729
1730 /* Re-base the last cycle value */
1731 tk->tkr_mono.cycle_last = cycle_now;
1732 tk->tkr_raw.cycle_last = cycle_now;
1733
1734 tk->ntp_error = 0;
1735 timekeeping_suspended = 0;
1736 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
1737 write_seqcount_end(&tk_core.seq);
1738 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1739
1740 touch_softlockup_watchdog();
1741
1742 tick_resume();
1743 hrtimers_resume();
1744 }
1745
timekeeping_suspend(void)1746 int timekeeping_suspend(void)
1747 {
1748 struct timekeeper *tk = &tk_core.timekeeper;
1749 unsigned long flags;
1750 struct timespec64 delta, delta_delta;
1751 static struct timespec64 old_delta;
1752
1753 read_persistent_clock64(&timekeeping_suspend_time);
1754
1755 /*
1756 * On some systems the persistent_clock can not be detected at
1757 * timekeeping_init by its return value, so if we see a valid
1758 * value returned, update the persistent_clock_exists flag.
1759 */
1760 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1761 persistent_clock_exists = true;
1762
1763 raw_spin_lock_irqsave(&timekeeper_lock, flags);
1764 write_seqcount_begin(&tk_core.seq);
1765 timekeeping_forward_now(tk);
1766 timekeeping_suspended = 1;
1767
1768 if (persistent_clock_exists) {
1769 /*
1770 * To avoid drift caused by repeated suspend/resumes,
1771 * which each can add ~1 second drift error,
1772 * try to compensate so the difference in system time
1773 * and persistent_clock time stays close to constant.
1774 */
1775 delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
1776 delta_delta = timespec64_sub(delta, old_delta);
1777 if (abs(delta_delta.tv_sec) >= 2) {
1778 /*
1779 * if delta_delta is too large, assume time correction
1780 * has occurred and set old_delta to the current delta.
1781 */
1782 old_delta = delta;
1783 } else {
1784 /* Otherwise try to adjust old_system to compensate */
1785 timekeeping_suspend_time =
1786 timespec64_add(timekeeping_suspend_time, delta_delta);
1787 }
1788 }
1789
1790 timekeeping_update(tk, TK_MIRROR);
1791 halt_fast_timekeeper(tk);
1792 write_seqcount_end(&tk_core.seq);
1793 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1794
1795 tick_suspend();
1796 clocksource_suspend();
1797 clockevents_suspend();
1798
1799 return 0;
1800 }
1801
1802 /* sysfs resume/suspend bits for timekeeping */
1803 static struct syscore_ops timekeeping_syscore_ops = {
1804 .resume = timekeeping_resume,
1805 .suspend = timekeeping_suspend,
1806 };
1807
timekeeping_init_ops(void)1808 static int __init timekeeping_init_ops(void)
1809 {
1810 register_syscore_ops(&timekeeping_syscore_ops);
1811 return 0;
1812 }
1813 device_initcall(timekeeping_init_ops);
1814
1815 /*
1816 * Apply a multiplier adjustment to the timekeeper
1817 */
timekeeping_apply_adjustment(struct timekeeper * tk,s64 offset,bool negative,int adj_scale)1818 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1819 s64 offset,
1820 bool negative,
1821 int adj_scale)
1822 {
1823 s64 interval = tk->cycle_interval;
1824 s32 mult_adj = 1;
1825
1826 if (negative) {
1827 mult_adj = -mult_adj;
1828 interval = -interval;
1829 offset = -offset;
1830 }
1831 mult_adj <<= adj_scale;
1832 interval <<= adj_scale;
1833 offset <<= adj_scale;
1834
1835 /*
1836 * So the following can be confusing.
1837 *
1838 * To keep things simple, lets assume mult_adj == 1 for now.
1839 *
1840 * When mult_adj != 1, remember that the interval and offset values
1841 * have been appropriately scaled so the math is the same.
1842 *
1843 * The basic idea here is that we're increasing the multiplier
1844 * by one, this causes the xtime_interval to be incremented by
1845 * one cycle_interval. This is because:
1846 * xtime_interval = cycle_interval * mult
1847 * So if mult is being incremented by one:
1848 * xtime_interval = cycle_interval * (mult + 1)
1849 * Its the same as:
1850 * xtime_interval = (cycle_interval * mult) + cycle_interval
1851 * Which can be shortened to:
1852 * xtime_interval += cycle_interval
1853 *
1854 * So offset stores the non-accumulated cycles. Thus the current
1855 * time (in shifted nanoseconds) is:
1856 * now = (offset * adj) + xtime_nsec
1857 * Now, even though we're adjusting the clock frequency, we have
1858 * to keep time consistent. In other words, we can't jump back
1859 * in time, and we also want to avoid jumping forward in time.
1860 *
1861 * So given the same offset value, we need the time to be the same
1862 * both before and after the freq adjustment.
1863 * now = (offset * adj_1) + xtime_nsec_1
1864 * now = (offset * adj_2) + xtime_nsec_2
1865 * So:
1866 * (offset * adj_1) + xtime_nsec_1 =
1867 * (offset * adj_2) + xtime_nsec_2
1868 * And we know:
1869 * adj_2 = adj_1 + 1
1870 * So:
1871 * (offset * adj_1) + xtime_nsec_1 =
1872 * (offset * (adj_1+1)) + xtime_nsec_2
1873 * (offset * adj_1) + xtime_nsec_1 =
1874 * (offset * adj_1) + offset + xtime_nsec_2
1875 * Canceling the sides:
1876 * xtime_nsec_1 = offset + xtime_nsec_2
1877 * Which gives us:
1878 * xtime_nsec_2 = xtime_nsec_1 - offset
1879 * Which simplfies to:
1880 * xtime_nsec -= offset
1881 *
1882 * XXX - TODO: Doc ntp_error calculation.
1883 */
1884 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1885 /* NTP adjustment caused clocksource mult overflow */
1886 WARN_ON_ONCE(1);
1887 return;
1888 }
1889
1890 tk->tkr_mono.mult += mult_adj;
1891 tk->xtime_interval += interval;
1892 tk->tkr_mono.xtime_nsec -= offset;
1893 tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1894 }
1895
1896 /*
1897 * Calculate the multiplier adjustment needed to match the frequency
1898 * specified by NTP
1899 */
timekeeping_freqadjust(struct timekeeper * tk,s64 offset)1900 static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1901 s64 offset)
1902 {
1903 s64 interval = tk->cycle_interval;
1904 s64 xinterval = tk->xtime_interval;
1905 u32 base = tk->tkr_mono.clock->mult;
1906 u32 max = tk->tkr_mono.clock->maxadj;
1907 u32 cur_adj = tk->tkr_mono.mult;
1908 s64 tick_error;
1909 bool negative;
1910 u32 adj_scale;
1911
1912 /* Remove any current error adj from freq calculation */
1913 if (tk->ntp_err_mult)
1914 xinterval -= tk->cycle_interval;
1915
1916 tk->ntp_tick = ntp_tick_length();
1917
1918 /* Calculate current error per tick */
1919 tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1920 tick_error -= (xinterval + tk->xtime_remainder);
1921
1922 /* Don't worry about correcting it if its small */
1923 if (likely((tick_error >= 0) && (tick_error <= interval)))
1924 return;
1925
1926 /* preserve the direction of correction */
1927 negative = (tick_error < 0);
1928
1929 /* If any adjustment would pass the max, just return */
1930 if (negative && (cur_adj - 1) <= (base - max))
1931 return;
1932 if (!negative && (cur_adj + 1) >= (base + max))
1933 return;
1934 /*
1935 * Sort out the magnitude of the correction, but
1936 * avoid making so large a correction that we go
1937 * over the max adjustment.
1938 */
1939 adj_scale = 0;
1940 tick_error = abs(tick_error);
1941 while (tick_error > interval) {
1942 u32 adj = 1 << (adj_scale + 1);
1943
1944 /* Check if adjustment gets us within 1 unit from the max */
1945 if (negative && (cur_adj - adj) <= (base - max))
1946 break;
1947 if (!negative && (cur_adj + adj) >= (base + max))
1948 break;
1949
1950 adj_scale++;
1951 tick_error >>= 1;
1952 }
1953
1954 /* scale the corrections */
1955 timekeeping_apply_adjustment(tk, offset, negative, adj_scale);
1956 }
1957
1958 /*
1959 * Adjust the timekeeper's multiplier to the correct frequency
1960 * and also to reduce the accumulated error value.
1961 */
timekeeping_adjust(struct timekeeper * tk,s64 offset)1962 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1963 {
1964 /* Correct for the current frequency error */
1965 timekeeping_freqadjust(tk, offset);
1966
1967 /* Next make a small adjustment to fix any cumulative error */
1968 if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1969 tk->ntp_err_mult = 1;
1970 timekeeping_apply_adjustment(tk, offset, 0, 0);
1971 } else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1972 /* Undo any existing error adjustment */
1973 timekeeping_apply_adjustment(tk, offset, 1, 0);
1974 tk->ntp_err_mult = 0;
1975 }
1976
1977 if (unlikely(tk->tkr_mono.clock->maxadj &&
1978 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
1979 > tk->tkr_mono.clock->maxadj))) {
1980 printk_once(KERN_WARNING
1981 "Adjusting %s more than 11%% (%ld vs %ld)\n",
1982 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
1983 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
1984 }
1985
1986 /*
1987 * It may be possible that when we entered this function, xtime_nsec
1988 * was very small. Further, if we're slightly speeding the clocksource
1989 * in the code above, its possible the required corrective factor to
1990 * xtime_nsec could cause it to underflow.
1991 *
1992 * Now, since we already accumulated the second, cannot simply roll
1993 * the accumulated second back, since the NTP subsystem has been
1994 * notified via second_overflow. So instead we push xtime_nsec forward
1995 * by the amount we underflowed, and add that amount into the error.
1996 *
1997 * We'll correct this error next time through this function, when
1998 * xtime_nsec is not as small.
1999 */
2000 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
2001 s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
2002 tk->tkr_mono.xtime_nsec = 0;
2003 tk->ntp_error += neg << tk->ntp_error_shift;
2004 }
2005 }
2006
2007 /**
2008 * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2009 *
2010 * Helper function that accumulates the nsecs greater than a second
2011 * from the xtime_nsec field to the xtime_secs field.
2012 * It also calls into the NTP code to handle leapsecond processing.
2013 *
2014 */
accumulate_nsecs_to_secs(struct timekeeper * tk)2015 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
2016 {
2017 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2018 unsigned int clock_set = 0;
2019
2020 while (tk->tkr_mono.xtime_nsec >= nsecps) {
2021 int leap;
2022
2023 tk->tkr_mono.xtime_nsec -= nsecps;
2024 tk->xtime_sec++;
2025
2026 /* Figure out if its a leap sec and apply if needed */
2027 leap = second_overflow(tk->xtime_sec);
2028 if (unlikely(leap)) {
2029 struct timespec64 ts;
2030
2031 tk->xtime_sec += leap;
2032
2033 ts.tv_sec = leap;
2034 ts.tv_nsec = 0;
2035 tk_set_wall_to_mono(tk,
2036 timespec64_sub(tk->wall_to_monotonic, ts));
2037
2038 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2039
2040 clock_set = TK_CLOCK_WAS_SET;
2041 }
2042 }
2043 return clock_set;
2044 }
2045
2046 /**
2047 * logarithmic_accumulation - shifted accumulation of cycles
2048 *
2049 * This functions accumulates a shifted interval of cycles into
2050 * into a shifted interval nanoseconds. Allows for O(log) accumulation
2051 * loop.
2052 *
2053 * Returns the unconsumed cycles.
2054 */
logarithmic_accumulation(struct timekeeper * tk,cycle_t offset,u32 shift,unsigned int * clock_set)2055 static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
2056 u32 shift,
2057 unsigned int *clock_set)
2058 {
2059 cycle_t interval = tk->cycle_interval << shift;
2060 u64 snsec_per_sec;
2061
2062 /* If the offset is smaller than a shifted interval, do nothing */
2063 if (offset < interval)
2064 return offset;
2065
2066 /* Accumulate one shifted interval */
2067 offset -= interval;
2068 tk->tkr_mono.cycle_last += interval;
2069 tk->tkr_raw.cycle_last += interval;
2070
2071 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2072 *clock_set |= accumulate_nsecs_to_secs(tk);
2073
2074 /* Accumulate raw time */
2075 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2076 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2077 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2078 tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2079 tk->raw_sec++;
2080 }
2081
2082 /* Accumulate error between NTP and clock interval */
2083 tk->ntp_error += tk->ntp_tick << shift;
2084 tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2085 (tk->ntp_error_shift + shift);
2086
2087 return offset;
2088 }
2089
2090 /**
2091 * update_wall_time - Uses the current clocksource to increment the wall time
2092 *
2093 */
update_wall_time(void)2094 void update_wall_time(void)
2095 {
2096 struct timekeeper *real_tk = &tk_core.timekeeper;
2097 struct timekeeper *tk = &shadow_timekeeper;
2098 cycle_t offset;
2099 int shift = 0, maxshift;
2100 unsigned int clock_set = 0;
2101 unsigned long flags;
2102
2103 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2104
2105 /* Make sure we're fully resumed: */
2106 if (unlikely(timekeeping_suspended))
2107 goto out;
2108
2109 #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
2110 offset = real_tk->cycle_interval;
2111 #else
2112 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2113 tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
2114 #endif
2115
2116 /* Check if there's really nothing to do */
2117 if (offset < real_tk->cycle_interval)
2118 goto out;
2119
2120 /* Do some additional sanity checking */
2121 timekeeping_check_update(real_tk, offset);
2122
2123 /*
2124 * With NO_HZ we may have to accumulate many cycle_intervals
2125 * (think "ticks") worth of time at once. To do this efficiently,
2126 * we calculate the largest doubling multiple of cycle_intervals
2127 * that is smaller than the offset. We then accumulate that
2128 * chunk in one go, and then try to consume the next smaller
2129 * doubled multiple.
2130 */
2131 shift = ilog2(offset) - ilog2(tk->cycle_interval);
2132 shift = max(0, shift);
2133 /* Bound shift to one less than what overflows tick_length */
2134 maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2135 shift = min(shift, maxshift);
2136 while (offset >= tk->cycle_interval) {
2137 offset = logarithmic_accumulation(tk, offset, shift,
2138 &clock_set);
2139 if (offset < tk->cycle_interval<<shift)
2140 shift--;
2141 }
2142
2143 /* correct the clock when NTP error is too big */
2144 timekeeping_adjust(tk, offset);
2145
2146 /*
2147 * XXX This can be killed once everyone converts
2148 * to the new update_vsyscall.
2149 */
2150 old_vsyscall_fixup(tk);
2151
2152 /*
2153 * Finally, make sure that after the rounding
2154 * xtime_nsec isn't larger than NSEC_PER_SEC
2155 */
2156 clock_set |= accumulate_nsecs_to_secs(tk);
2157
2158 write_seqcount_begin(&tk_core.seq);
2159 /*
2160 * Update the real timekeeper.
2161 *
2162 * We could avoid this memcpy by switching pointers, but that
2163 * requires changes to all other timekeeper usage sites as
2164 * well, i.e. move the timekeeper pointer getter into the
2165 * spinlocked/seqcount protected sections. And we trade this
2166 * memcpy under the tk_core.seq against one before we start
2167 * updating.
2168 */
2169 timekeeping_update(tk, clock_set);
2170 memcpy(real_tk, tk, sizeof(*tk));
2171 /* The memcpy must come last. Do not put anything here! */
2172 write_seqcount_end(&tk_core.seq);
2173 out:
2174 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2175 if (clock_set)
2176 /* Have to call _delayed version, since in irq context*/
2177 clock_was_set_delayed();
2178 }
2179
2180 /**
2181 * getboottime64 - Return the real time of system boot.
2182 * @ts: pointer to the timespec64 to be set
2183 *
2184 * Returns the wall-time of boot in a timespec64.
2185 *
2186 * This is based on the wall_to_monotonic offset and the total suspend
2187 * time. Calls to settimeofday will affect the value returned (which
2188 * basically means that however wrong your real time clock is at boot time,
2189 * you get the right time here).
2190 */
getboottime64(struct timespec64 * ts)2191 void getboottime64(struct timespec64 *ts)
2192 {
2193 struct timekeeper *tk = &tk_core.timekeeper;
2194 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2195
2196 *ts = ktime_to_timespec64(t);
2197 }
2198 EXPORT_SYMBOL_GPL(getboottime64);
2199
get_seconds(void)2200 unsigned long get_seconds(void)
2201 {
2202 struct timekeeper *tk = &tk_core.timekeeper;
2203
2204 return tk->xtime_sec;
2205 }
2206 EXPORT_SYMBOL(get_seconds);
2207
__current_kernel_time(void)2208 struct timespec __current_kernel_time(void)
2209 {
2210 struct timekeeper *tk = &tk_core.timekeeper;
2211
2212 return timespec64_to_timespec(tk_xtime(tk));
2213 }
2214
current_kernel_time64(void)2215 struct timespec64 current_kernel_time64(void)
2216 {
2217 struct timekeeper *tk = &tk_core.timekeeper;
2218 struct timespec64 now;
2219 unsigned long seq;
2220
2221 do {
2222 seq = read_seqcount_begin(&tk_core.seq);
2223
2224 now = tk_xtime(tk);
2225 } while (read_seqcount_retry(&tk_core.seq, seq));
2226
2227 return now;
2228 }
2229 EXPORT_SYMBOL(current_kernel_time64);
2230
get_monotonic_coarse64(void)2231 struct timespec64 get_monotonic_coarse64(void)
2232 {
2233 struct timekeeper *tk = &tk_core.timekeeper;
2234 struct timespec64 now, mono;
2235 unsigned long seq;
2236
2237 do {
2238 seq = read_seqcount_begin(&tk_core.seq);
2239
2240 now = tk_xtime(tk);
2241 mono = tk->wall_to_monotonic;
2242 } while (read_seqcount_retry(&tk_core.seq, seq));
2243
2244 set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
2245 now.tv_nsec + mono.tv_nsec);
2246
2247 return now;
2248 }
2249 EXPORT_SYMBOL(get_monotonic_coarse64);
2250
2251 /*
2252 * Must hold jiffies_lock
2253 */
do_timer(unsigned long ticks)2254 void do_timer(unsigned long ticks)
2255 {
2256 jiffies_64 += ticks;
2257 calc_global_load(ticks);
2258 }
2259
2260 /**
2261 * ktime_get_update_offsets_now - hrtimer helper
2262 * @cwsseq: pointer to check and store the clock was set sequence number
2263 * @offs_real: pointer to storage for monotonic -> realtime offset
2264 * @offs_boot: pointer to storage for monotonic -> boottime offset
2265 * @offs_tai: pointer to storage for monotonic -> clock tai offset
2266 *
2267 * Returns current monotonic time and updates the offsets if the
2268 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2269 * different.
2270 *
2271 * Called from hrtimer_interrupt() or retrigger_next_event()
2272 */
ktime_get_update_offsets_now(unsigned int * cwsseq,ktime_t * offs_real,ktime_t * offs_boot,ktime_t * offs_tai)2273 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2274 ktime_t *offs_boot, ktime_t *offs_tai)
2275 {
2276 struct timekeeper *tk = &tk_core.timekeeper;
2277 unsigned int seq;
2278 ktime_t base;
2279 u64 nsecs;
2280
2281 do {
2282 seq = read_seqcount_begin(&tk_core.seq);
2283
2284 base = tk->tkr_mono.base;
2285 nsecs = timekeeping_get_ns(&tk->tkr_mono);
2286 base = ktime_add_ns(base, nsecs);
2287
2288 if (*cwsseq != tk->clock_was_set_seq) {
2289 *cwsseq = tk->clock_was_set_seq;
2290 *offs_real = tk->offs_real;
2291 *offs_boot = tk->offs_boot;
2292 *offs_tai = tk->offs_tai;
2293 }
2294
2295 /* Handle leapsecond insertion adjustments */
2296 if (unlikely(base.tv64 >= tk->next_leap_ktime.tv64))
2297 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2298
2299 } while (read_seqcount_retry(&tk_core.seq, seq));
2300
2301 return base;
2302 }
2303
2304 /**
2305 * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2306 */
do_adjtimex(struct timex * txc)2307 int do_adjtimex(struct timex *txc)
2308 {
2309 struct timekeeper *tk = &tk_core.timekeeper;
2310 unsigned long flags;
2311 struct timespec64 ts;
2312 s32 orig_tai, tai;
2313 int ret;
2314
2315 /* Validate the data before disabling interrupts */
2316 ret = ntp_validate_timex(txc);
2317 if (ret)
2318 return ret;
2319
2320 if (txc->modes & ADJ_SETOFFSET) {
2321 struct timespec delta;
2322 delta.tv_sec = txc->time.tv_sec;
2323 delta.tv_nsec = txc->time.tv_usec;
2324 if (!(txc->modes & ADJ_NANO))
2325 delta.tv_nsec *= 1000;
2326 ret = timekeeping_inject_offset(&delta);
2327 if (ret)
2328 return ret;
2329 }
2330
2331 getnstimeofday64(&ts);
2332
2333 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2334 write_seqcount_begin(&tk_core.seq);
2335
2336 orig_tai = tai = tk->tai_offset;
2337 ret = __do_adjtimex(txc, &ts, &tai);
2338
2339 if (tai != orig_tai) {
2340 __timekeeping_set_tai_offset(tk, tai);
2341 timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
2342 }
2343 tk_update_leap_state(tk);
2344
2345 write_seqcount_end(&tk_core.seq);
2346 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2347
2348 if (tai != orig_tai)
2349 clock_was_set();
2350
2351 ntp_notify_cmos_timer();
2352
2353 return ret;
2354 }
2355
2356 #ifdef CONFIG_NTP_PPS
2357 /**
2358 * hardpps() - Accessor function to NTP __hardpps function
2359 */
hardpps(const struct timespec64 * phase_ts,const struct timespec64 * raw_ts)2360 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2361 {
2362 unsigned long flags;
2363
2364 raw_spin_lock_irqsave(&timekeeper_lock, flags);
2365 write_seqcount_begin(&tk_core.seq);
2366
2367 __hardpps(phase_ts, raw_ts);
2368
2369 write_seqcount_end(&tk_core.seq);
2370 raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2371 }
2372 EXPORT_SYMBOL(hardpps);
2373 #endif
2374
2375 /**
2376 * xtime_update() - advances the timekeeping infrastructure
2377 * @ticks: number of ticks, that have elapsed since the last call.
2378 *
2379 * Must be called with interrupts disabled.
2380 */
xtime_update(unsigned long ticks)2381 void xtime_update(unsigned long ticks)
2382 {
2383 write_seqlock(&jiffies_lock);
2384 do_timer(ticks);
2385 write_sequnlock(&jiffies_lock);
2386 update_wall_time();
2387 }
2388