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