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