xref: /linux/kernel/time/timekeeping.c (revision 442bc81bd344dc52c37d8f80b854cc6da062b2d0)
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_now - update clock to the current time
686  * @tk:		Pointer to the timekeeper to update
687  *
688  * Forward the current clock to update its state since the last call to
689  * update_wall_time(). This is useful before significant clock changes,
690  * as it avoids having to deal with this time offset explicitly.
691  */
timekeeping_forward_now(struct timekeeper * tk)692 static void timekeeping_forward_now(struct timekeeper *tk)
693 {
694 	u64 cycle_now, delta;
695 
696 	cycle_now = tk_clock_read(&tk->tkr_mono);
697 	delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
698 				  tk->tkr_mono.clock->max_raw_delta);
699 	tk->tkr_mono.cycle_last = cycle_now;
700 	tk->tkr_raw.cycle_last  = cycle_now;
701 
702 	while (delta > 0) {
703 		u64 max = tk->tkr_mono.clock->max_cycles;
704 		u64 incr = delta < max ? delta : max;
705 
706 		tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult;
707 		tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult;
708 		tk_normalize_xtime(tk);
709 		delta -= incr;
710 	}
711 }
712 
713 /**
714  * ktime_get_real_ts64 - Returns the time of day in a timespec64.
715  * @ts:		pointer to the timespec to be set
716  *
717  * Returns the time of day in a timespec64 (WARN if suspended).
718  */
ktime_get_real_ts64(struct timespec64 * ts)719 void ktime_get_real_ts64(struct timespec64 *ts)
720 {
721 	struct timekeeper *tk = &tk_core.timekeeper;
722 	unsigned int seq;
723 	u64 nsecs;
724 
725 	WARN_ON(timekeeping_suspended);
726 
727 	do {
728 		seq = read_seqcount_begin(&tk_core.seq);
729 
730 		ts->tv_sec = tk->xtime_sec;
731 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
732 
733 	} while (read_seqcount_retry(&tk_core.seq, seq));
734 
735 	ts->tv_nsec = 0;
736 	timespec64_add_ns(ts, nsecs);
737 }
738 EXPORT_SYMBOL(ktime_get_real_ts64);
739 
ktime_get(void)740 ktime_t ktime_get(void)
741 {
742 	struct timekeeper *tk = &tk_core.timekeeper;
743 	unsigned int seq;
744 	ktime_t base;
745 	u64 nsecs;
746 
747 	WARN_ON(timekeeping_suspended);
748 
749 	do {
750 		seq = read_seqcount_begin(&tk_core.seq);
751 		base = tk->tkr_mono.base;
752 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
753 
754 	} while (read_seqcount_retry(&tk_core.seq, seq));
755 
756 	return ktime_add_ns(base, nsecs);
757 }
758 EXPORT_SYMBOL_GPL(ktime_get);
759 
ktime_get_resolution_ns(void)760 u32 ktime_get_resolution_ns(void)
761 {
762 	struct timekeeper *tk = &tk_core.timekeeper;
763 	unsigned int seq;
764 	u32 nsecs;
765 
766 	WARN_ON(timekeeping_suspended);
767 
768 	do {
769 		seq = read_seqcount_begin(&tk_core.seq);
770 		nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
771 	} while (read_seqcount_retry(&tk_core.seq, seq));
772 
773 	return nsecs;
774 }
775 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
776 
777 static ktime_t *offsets[TK_OFFS_MAX] = {
778 	[TK_OFFS_REAL]	= &tk_core.timekeeper.offs_real,
779 	[TK_OFFS_BOOT]	= &tk_core.timekeeper.offs_boot,
780 	[TK_OFFS_TAI]	= &tk_core.timekeeper.offs_tai,
781 };
782 
ktime_get_with_offset(enum tk_offsets offs)783 ktime_t ktime_get_with_offset(enum tk_offsets offs)
784 {
785 	struct timekeeper *tk = &tk_core.timekeeper;
786 	unsigned int seq;
787 	ktime_t base, *offset = offsets[offs];
788 	u64 nsecs;
789 
790 	WARN_ON(timekeeping_suspended);
791 
792 	do {
793 		seq = read_seqcount_begin(&tk_core.seq);
794 		base = ktime_add(tk->tkr_mono.base, *offset);
795 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
796 
797 	} while (read_seqcount_retry(&tk_core.seq, seq));
798 
799 	return ktime_add_ns(base, nsecs);
800 
801 }
802 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
803 
ktime_get_coarse_with_offset(enum tk_offsets offs)804 ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
805 {
806 	struct timekeeper *tk = &tk_core.timekeeper;
807 	unsigned int seq;
808 	ktime_t base, *offset = offsets[offs];
809 	u64 nsecs;
810 
811 	WARN_ON(timekeeping_suspended);
812 
813 	do {
814 		seq = read_seqcount_begin(&tk_core.seq);
815 		base = ktime_add(tk->tkr_mono.base, *offset);
816 		nsecs = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
817 
818 	} while (read_seqcount_retry(&tk_core.seq, seq));
819 
820 	return ktime_add_ns(base, nsecs);
821 }
822 EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
823 
824 /**
825  * ktime_mono_to_any() - convert monotonic time to any other time
826  * @tmono:	time to convert.
827  * @offs:	which offset to use
828  */
ktime_mono_to_any(ktime_t tmono,enum tk_offsets offs)829 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
830 {
831 	ktime_t *offset = offsets[offs];
832 	unsigned int seq;
833 	ktime_t tconv;
834 
835 	if (IS_ENABLED(CONFIG_64BIT)) {
836 		/*
837 		 * Paired with WRITE_ONCE()s in tk_set_wall_to_mono() and
838 		 * tk_update_sleep_time().
839 		 */
840 		return ktime_add(tmono, READ_ONCE(*offset));
841 	}
842 
843 	do {
844 		seq = read_seqcount_begin(&tk_core.seq);
845 		tconv = ktime_add(tmono, *offset);
846 	} while (read_seqcount_retry(&tk_core.seq, seq));
847 
848 	return tconv;
849 }
850 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
851 
852 /**
853  * ktime_get_raw - Returns the raw monotonic time in ktime_t format
854  */
ktime_get_raw(void)855 ktime_t ktime_get_raw(void)
856 {
857 	struct timekeeper *tk = &tk_core.timekeeper;
858 	unsigned int seq;
859 	ktime_t base;
860 	u64 nsecs;
861 
862 	do {
863 		seq = read_seqcount_begin(&tk_core.seq);
864 		base = tk->tkr_raw.base;
865 		nsecs = timekeeping_get_ns(&tk->tkr_raw);
866 
867 	} while (read_seqcount_retry(&tk_core.seq, seq));
868 
869 	return ktime_add_ns(base, nsecs);
870 }
871 EXPORT_SYMBOL_GPL(ktime_get_raw);
872 
873 /**
874  * ktime_get_ts64 - get the monotonic clock in timespec64 format
875  * @ts:		pointer to timespec variable
876  *
877  * The function calculates the monotonic clock from the realtime
878  * clock and the wall_to_monotonic offset and stores the result
879  * in normalized timespec64 format in the variable pointed to by @ts.
880  */
ktime_get_ts64(struct timespec64 * ts)881 void ktime_get_ts64(struct timespec64 *ts)
882 {
883 	struct timekeeper *tk = &tk_core.timekeeper;
884 	struct timespec64 tomono;
885 	unsigned int seq;
886 	u64 nsec;
887 
888 	WARN_ON(timekeeping_suspended);
889 
890 	do {
891 		seq = read_seqcount_begin(&tk_core.seq);
892 		ts->tv_sec = tk->xtime_sec;
893 		nsec = timekeeping_get_ns(&tk->tkr_mono);
894 		tomono = tk->wall_to_monotonic;
895 
896 	} while (read_seqcount_retry(&tk_core.seq, seq));
897 
898 	ts->tv_sec += tomono.tv_sec;
899 	ts->tv_nsec = 0;
900 	timespec64_add_ns(ts, nsec + tomono.tv_nsec);
901 }
902 EXPORT_SYMBOL_GPL(ktime_get_ts64);
903 
904 /**
905  * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
906  *
907  * Returns the seconds portion of CLOCK_MONOTONIC with a single non
908  * serialized read. tk->ktime_sec is of type 'unsigned long' so this
909  * works on both 32 and 64 bit systems. On 32 bit systems the readout
910  * covers ~136 years of uptime which should be enough to prevent
911  * premature wrap arounds.
912  */
ktime_get_seconds(void)913 time64_t ktime_get_seconds(void)
914 {
915 	struct timekeeper *tk = &tk_core.timekeeper;
916 
917 	WARN_ON(timekeeping_suspended);
918 	return tk->ktime_sec;
919 }
920 EXPORT_SYMBOL_GPL(ktime_get_seconds);
921 
922 /**
923  * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
924  *
925  * Returns the wall clock seconds since 1970.
926  *
927  * For 64bit systems the fast access to tk->xtime_sec is preserved. On
928  * 32bit systems the access must be protected with the sequence
929  * counter to provide "atomic" access to the 64bit tk->xtime_sec
930  * value.
931  */
ktime_get_real_seconds(void)932 time64_t ktime_get_real_seconds(void)
933 {
934 	struct timekeeper *tk = &tk_core.timekeeper;
935 	time64_t seconds;
936 	unsigned int seq;
937 
938 	if (IS_ENABLED(CONFIG_64BIT))
939 		return tk->xtime_sec;
940 
941 	do {
942 		seq = read_seqcount_begin(&tk_core.seq);
943 		seconds = tk->xtime_sec;
944 
945 	} while (read_seqcount_retry(&tk_core.seq, seq));
946 
947 	return seconds;
948 }
949 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
950 
951 /**
952  * __ktime_get_real_seconds - The same as ktime_get_real_seconds
953  * but without the sequence counter protect. This internal function
954  * is called just when timekeeping lock is already held.
955  */
__ktime_get_real_seconds(void)956 noinstr time64_t __ktime_get_real_seconds(void)
957 {
958 	struct timekeeper *tk = &tk_core.timekeeper;
959 
960 	return tk->xtime_sec;
961 }
962 
963 /**
964  * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
965  * @systime_snapshot:	pointer to struct receiving the system time snapshot
966  */
ktime_get_snapshot(struct system_time_snapshot * systime_snapshot)967 void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
968 {
969 	struct timekeeper *tk = &tk_core.timekeeper;
970 	unsigned int seq;
971 	ktime_t base_raw;
972 	ktime_t base_real;
973 	ktime_t base_boot;
974 	u64 nsec_raw;
975 	u64 nsec_real;
976 	u64 now;
977 
978 	WARN_ON_ONCE(timekeeping_suspended);
979 
980 	do {
981 		seq = read_seqcount_begin(&tk_core.seq);
982 		now = tk_clock_read(&tk->tkr_mono);
983 		systime_snapshot->cs_id = tk->tkr_mono.clock->id;
984 		systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
985 		systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
986 		base_real = ktime_add(tk->tkr_mono.base,
987 				      tk_core.timekeeper.offs_real);
988 		base_boot = ktime_add(tk->tkr_mono.base,
989 				      tk_core.timekeeper.offs_boot);
990 		base_raw = tk->tkr_raw.base;
991 		nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
992 		nsec_raw  = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
993 	} while (read_seqcount_retry(&tk_core.seq, seq));
994 
995 	systime_snapshot->cycles = now;
996 	systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
997 	systime_snapshot->boot = ktime_add_ns(base_boot, nsec_real);
998 	systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
999 }
1000 EXPORT_SYMBOL_GPL(ktime_get_snapshot);
1001 
1002 /* Scale base by mult/div checking for overflow */
scale64_check_overflow(u64 mult,u64 div,u64 * base)1003 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
1004 {
1005 	u64 tmp, rem;
1006 
1007 	tmp = div64_u64_rem(*base, div, &rem);
1008 
1009 	if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
1010 	    ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
1011 		return -EOVERFLOW;
1012 	tmp *= mult;
1013 
1014 	rem = div64_u64(rem * mult, div);
1015 	*base = tmp + rem;
1016 	return 0;
1017 }
1018 
1019 /**
1020  * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1021  * @history:			Snapshot representing start of history
1022  * @partial_history_cycles:	Cycle offset into history (fractional part)
1023  * @total_history_cycles:	Total history length in cycles
1024  * @discontinuity:		True indicates clock was set on history period
1025  * @ts:				Cross timestamp that should be adjusted using
1026  *	partial/total ratio
1027  *
1028  * Helper function used by get_device_system_crosststamp() to correct the
1029  * crosstimestamp corresponding to the start of the current interval to the
1030  * system counter value (timestamp point) provided by the driver. The
1031  * total_history_* quantities are the total history starting at the provided
1032  * reference point and ending at the start of the current interval. The cycle
1033  * count between the driver timestamp point and the start of the current
1034  * interval is partial_history_cycles.
1035  */
adjust_historical_crosststamp(struct system_time_snapshot * history,u64 partial_history_cycles,u64 total_history_cycles,bool discontinuity,struct system_device_crosststamp * ts)1036 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1037 					 u64 partial_history_cycles,
1038 					 u64 total_history_cycles,
1039 					 bool discontinuity,
1040 					 struct system_device_crosststamp *ts)
1041 {
1042 	struct timekeeper *tk = &tk_core.timekeeper;
1043 	u64 corr_raw, corr_real;
1044 	bool interp_forward;
1045 	int ret;
1046 
1047 	if (total_history_cycles == 0 || partial_history_cycles == 0)
1048 		return 0;
1049 
1050 	/* Interpolate shortest distance from beginning or end of history */
1051 	interp_forward = partial_history_cycles > total_history_cycles / 2;
1052 	partial_history_cycles = interp_forward ?
1053 		total_history_cycles - partial_history_cycles :
1054 		partial_history_cycles;
1055 
1056 	/*
1057 	 * Scale the monotonic raw time delta by:
1058 	 *	partial_history_cycles / total_history_cycles
1059 	 */
1060 	corr_raw = (u64)ktime_to_ns(
1061 		ktime_sub(ts->sys_monoraw, history->raw));
1062 	ret = scale64_check_overflow(partial_history_cycles,
1063 				     total_history_cycles, &corr_raw);
1064 	if (ret)
1065 		return ret;
1066 
1067 	/*
1068 	 * If there is a discontinuity in the history, scale monotonic raw
1069 	 *	correction by:
1070 	 *	mult(real)/mult(raw) yielding the realtime correction
1071 	 * Otherwise, calculate the realtime correction similar to monotonic
1072 	 *	raw calculation
1073 	 */
1074 	if (discontinuity) {
1075 		corr_real = mul_u64_u32_div
1076 			(corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1077 	} else {
1078 		corr_real = (u64)ktime_to_ns(
1079 			ktime_sub(ts->sys_realtime, history->real));
1080 		ret = scale64_check_overflow(partial_history_cycles,
1081 					     total_history_cycles, &corr_real);
1082 		if (ret)
1083 			return ret;
1084 	}
1085 
1086 	/* Fixup monotonic raw and real time time values */
1087 	if (interp_forward) {
1088 		ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
1089 		ts->sys_realtime = ktime_add_ns(history->real, corr_real);
1090 	} else {
1091 		ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1092 		ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
1093 	}
1094 
1095 	return 0;
1096 }
1097 
1098 /*
1099  * timestamp_in_interval - true if ts is chronologically in [start, end]
1100  *
1101  * True if ts occurs chronologically at or after start, and before or at end.
1102  */
timestamp_in_interval(u64 start,u64 end,u64 ts)1103 static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
1104 {
1105 	if (ts >= start && ts <= end)
1106 		return true;
1107 	if (start > end && (ts >= start || ts <= end))
1108 		return true;
1109 	return false;
1110 }
1111 
convert_clock(u64 * val,u32 numerator,u32 denominator)1112 static bool convert_clock(u64 *val, u32 numerator, u32 denominator)
1113 {
1114 	u64 rem, res;
1115 
1116 	if (!numerator || !denominator)
1117 		return false;
1118 
1119 	res = div64_u64_rem(*val, denominator, &rem) * numerator;
1120 	*val = res + div_u64(rem * numerator, denominator);
1121 	return true;
1122 }
1123 
convert_base_to_cs(struct system_counterval_t * scv)1124 static bool convert_base_to_cs(struct system_counterval_t *scv)
1125 {
1126 	struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1127 	struct clocksource_base *base;
1128 	u32 num, den;
1129 
1130 	/* The timestamp was taken from the time keeper clock source */
1131 	if (cs->id == scv->cs_id)
1132 		return true;
1133 
1134 	/*
1135 	 * Check whether cs_id matches the base clock. Prevent the compiler from
1136 	 * re-evaluating @base as the clocksource might change concurrently.
1137 	 */
1138 	base = READ_ONCE(cs->base);
1139 	if (!base || base->id != scv->cs_id)
1140 		return false;
1141 
1142 	num = scv->use_nsecs ? cs->freq_khz : base->numerator;
1143 	den = scv->use_nsecs ? USEC_PER_SEC : base->denominator;
1144 
1145 	if (!convert_clock(&scv->cycles, num, den))
1146 		return false;
1147 
1148 	scv->cycles += base->offset;
1149 	return true;
1150 }
1151 
convert_cs_to_base(u64 * cycles,enum clocksource_ids base_id)1152 static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id)
1153 {
1154 	struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1155 	struct clocksource_base *base;
1156 
1157 	/*
1158 	 * Check whether base_id matches the base clock. Prevent the compiler from
1159 	 * re-evaluating @base as the clocksource might change concurrently.
1160 	 */
1161 	base = READ_ONCE(cs->base);
1162 	if (!base || base->id != base_id)
1163 		return false;
1164 
1165 	*cycles -= base->offset;
1166 	if (!convert_clock(cycles, base->denominator, base->numerator))
1167 		return false;
1168 	return true;
1169 }
1170 
convert_ns_to_cs(u64 * delta)1171 static bool convert_ns_to_cs(u64 *delta)
1172 {
1173 	struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
1174 
1175 	if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta))
1176 		return false;
1177 
1178 	*delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult);
1179 	return true;
1180 }
1181 
1182 /**
1183  * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp
1184  * @treal:	CLOCK_REALTIME timestamp to convert
1185  * @base_id:	base clocksource id
1186  * @cycles:	pointer to store the converted base clock timestamp
1187  *
1188  * Converts a supplied, future realtime clock value to the corresponding base clock value.
1189  *
1190  * Return:  true if the conversion is successful, false otherwise.
1191  */
ktime_real_to_base_clock(ktime_t treal,enum clocksource_ids base_id,u64 * cycles)1192 bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles)
1193 {
1194 	struct timekeeper *tk = &tk_core.timekeeper;
1195 	unsigned int seq;
1196 	u64 delta;
1197 
1198 	do {
1199 		seq = read_seqcount_begin(&tk_core.seq);
1200 		if ((u64)treal < tk->tkr_mono.base_real)
1201 			return false;
1202 		delta = (u64)treal - tk->tkr_mono.base_real;
1203 		if (!convert_ns_to_cs(&delta))
1204 			return false;
1205 		*cycles = tk->tkr_mono.cycle_last + delta;
1206 		if (!convert_cs_to_base(cycles, base_id))
1207 			return false;
1208 	} while (read_seqcount_retry(&tk_core.seq, seq));
1209 
1210 	return true;
1211 }
1212 EXPORT_SYMBOL_GPL(ktime_real_to_base_clock);
1213 
1214 /**
1215  * get_device_system_crosststamp - Synchronously capture system/device timestamp
1216  * @get_time_fn:	Callback to get simultaneous device time and
1217  *	system counter from the device driver
1218  * @ctx:		Context passed to get_time_fn()
1219  * @history_begin:	Historical reference point used to interpolate system
1220  *	time when counter provided by the driver is before the current interval
1221  * @xtstamp:		Receives simultaneously captured system and device time
1222  *
1223  * Reads a timestamp from a device and correlates it to system time
1224  */
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)1225 int get_device_system_crosststamp(int (*get_time_fn)
1226 				  (ktime_t *device_time,
1227 				   struct system_counterval_t *sys_counterval,
1228 				   void *ctx),
1229 				  void *ctx,
1230 				  struct system_time_snapshot *history_begin,
1231 				  struct system_device_crosststamp *xtstamp)
1232 {
1233 	struct system_counterval_t system_counterval;
1234 	struct timekeeper *tk = &tk_core.timekeeper;
1235 	u64 cycles, now, interval_start;
1236 	unsigned int clock_was_set_seq = 0;
1237 	ktime_t base_real, base_raw;
1238 	u64 nsec_real, nsec_raw;
1239 	u8 cs_was_changed_seq;
1240 	unsigned int seq;
1241 	bool do_interp;
1242 	int ret;
1243 
1244 	do {
1245 		seq = read_seqcount_begin(&tk_core.seq);
1246 		/*
1247 		 * Try to synchronously capture device time and a system
1248 		 * counter value calling back into the device driver
1249 		 */
1250 		ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
1251 		if (ret)
1252 			return ret;
1253 
1254 		/*
1255 		 * Verify that the clocksource ID associated with the captured
1256 		 * system counter value is the same as for the currently
1257 		 * installed timekeeper clocksource
1258 		 */
1259 		if (system_counterval.cs_id == CSID_GENERIC ||
1260 		    !convert_base_to_cs(&system_counterval))
1261 			return -ENODEV;
1262 		cycles = system_counterval.cycles;
1263 
1264 		/*
1265 		 * Check whether the system counter value provided by the
1266 		 * device driver is on the current timekeeping interval.
1267 		 */
1268 		now = tk_clock_read(&tk->tkr_mono);
1269 		interval_start = tk->tkr_mono.cycle_last;
1270 		if (!timestamp_in_interval(interval_start, now, cycles)) {
1271 			clock_was_set_seq = tk->clock_was_set_seq;
1272 			cs_was_changed_seq = tk->cs_was_changed_seq;
1273 			cycles = interval_start;
1274 			do_interp = true;
1275 		} else {
1276 			do_interp = false;
1277 		}
1278 
1279 		base_real = ktime_add(tk->tkr_mono.base,
1280 				      tk_core.timekeeper.offs_real);
1281 		base_raw = tk->tkr_raw.base;
1282 
1283 		nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
1284 		nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
1285 	} while (read_seqcount_retry(&tk_core.seq, seq));
1286 
1287 	xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
1288 	xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1289 
1290 	/*
1291 	 * Interpolate if necessary, adjusting back from the start of the
1292 	 * current interval
1293 	 */
1294 	if (do_interp) {
1295 		u64 partial_history_cycles, total_history_cycles;
1296 		bool discontinuity;
1297 
1298 		/*
1299 		 * Check that the counter value is not before the provided
1300 		 * history reference and that the history doesn't cross a
1301 		 * clocksource change
1302 		 */
1303 		if (!history_begin ||
1304 		    !timestamp_in_interval(history_begin->cycles,
1305 					   cycles, system_counterval.cycles) ||
1306 		    history_begin->cs_was_changed_seq != cs_was_changed_seq)
1307 			return -EINVAL;
1308 		partial_history_cycles = cycles - system_counterval.cycles;
1309 		total_history_cycles = cycles - history_begin->cycles;
1310 		discontinuity =
1311 			history_begin->clock_was_set_seq != clock_was_set_seq;
1312 
1313 		ret = adjust_historical_crosststamp(history_begin,
1314 						    partial_history_cycles,
1315 						    total_history_cycles,
1316 						    discontinuity, xtstamp);
1317 		if (ret)
1318 			return ret;
1319 	}
1320 
1321 	return 0;
1322 }
1323 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1324 
1325 /**
1326  * timekeeping_clocksource_has_base - Check whether the current clocksource
1327  *				      is based on given a base clock
1328  * @id:		base clocksource ID
1329  *
1330  * Note:	The return value is a snapshot which can become invalid right
1331  *		after the function returns.
1332  *
1333  * Return:	true if the timekeeper clocksource has a base clock with @id,
1334  *		false otherwise
1335  */
timekeeping_clocksource_has_base(enum clocksource_ids id)1336 bool timekeeping_clocksource_has_base(enum clocksource_ids id)
1337 {
1338 	/*
1339 	 * This is a snapshot, so no point in using the sequence
1340 	 * count. Just prevent the compiler from re-evaluating @base as the
1341 	 * clocksource might change concurrently.
1342 	 */
1343 	struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base);
1344 
1345 	return base ? base->id == id : false;
1346 }
1347 EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base);
1348 
1349 /**
1350  * do_settimeofday64 - Sets the time of day.
1351  * @ts:     pointer to the timespec64 variable containing the new time
1352  *
1353  * Sets the time of day to the new time and update NTP and notify hrtimers
1354  */
do_settimeofday64(const struct timespec64 * ts)1355 int do_settimeofday64(const struct timespec64 *ts)
1356 {
1357 	struct timespec64 ts_delta, xt;
1358 
1359 	if (!timespec64_valid_settod(ts))
1360 		return -EINVAL;
1361 
1362 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1363 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
1364 
1365 		timekeeping_forward_now(tks);
1366 
1367 		xt = tk_xtime(tks);
1368 		ts_delta = timespec64_sub(*ts, xt);
1369 
1370 		if (timespec64_compare(&tks->wall_to_monotonic, &ts_delta) > 0) {
1371 			timekeeping_restore_shadow(&tk_core);
1372 			return -EINVAL;
1373 		}
1374 
1375 		tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, ts_delta));
1376 		tk_set_xtime(tks, ts);
1377 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1378 	}
1379 
1380 	/* Signal hrtimers about time change */
1381 	clock_was_set(CLOCK_SET_WALL);
1382 
1383 	audit_tk_injoffset(ts_delta);
1384 	add_device_randomness(ts, sizeof(*ts));
1385 	return 0;
1386 }
1387 EXPORT_SYMBOL(do_settimeofday64);
1388 
1389 /**
1390  * timekeeping_inject_offset - Adds or subtracts from the current time.
1391  * @ts:		Pointer to the timespec variable containing the offset
1392  *
1393  * Adds or subtracts an offset value from the current time.
1394  */
timekeeping_inject_offset(const struct timespec64 * ts)1395 static int timekeeping_inject_offset(const struct timespec64 *ts)
1396 {
1397 	if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1398 		return -EINVAL;
1399 
1400 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1401 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
1402 		struct timespec64 tmp;
1403 
1404 		timekeeping_forward_now(tks);
1405 
1406 		/* Make sure the proposed value is valid */
1407 		tmp = timespec64_add(tk_xtime(tks), *ts);
1408 		if (timespec64_compare(&tks->wall_to_monotonic, ts) > 0 ||
1409 		    !timespec64_valid_settod(&tmp)) {
1410 			timekeeping_restore_shadow(&tk_core);
1411 			return -EINVAL;
1412 		}
1413 
1414 		tk_xtime_add(tks, ts);
1415 		tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, *ts));
1416 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1417 	}
1418 
1419 	/* Signal hrtimers about time change */
1420 	clock_was_set(CLOCK_SET_WALL);
1421 	return 0;
1422 }
1423 
1424 /*
1425  * Indicates if there is an offset between the system clock and the hardware
1426  * clock/persistent clock/rtc.
1427  */
1428 int persistent_clock_is_local;
1429 
1430 /*
1431  * Adjust the time obtained from the CMOS to be UTC time instead of
1432  * local time.
1433  *
1434  * This is ugly, but preferable to the alternatives.  Otherwise we
1435  * would either need to write a program to do it in /etc/rc (and risk
1436  * confusion if the program gets run more than once; it would also be
1437  * hard to make the program warp the clock precisely n hours)  or
1438  * compile in the timezone information into the kernel.  Bad, bad....
1439  *
1440  *						- TYT, 1992-01-01
1441  *
1442  * The best thing to do is to keep the CMOS clock in universal time (UTC)
1443  * as real UNIX machines always do it. This avoids all headaches about
1444  * daylight saving times and warping kernel clocks.
1445  */
timekeeping_warp_clock(void)1446 void timekeeping_warp_clock(void)
1447 {
1448 	if (sys_tz.tz_minuteswest != 0) {
1449 		struct timespec64 adjust;
1450 
1451 		persistent_clock_is_local = 1;
1452 		adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1453 		adjust.tv_nsec = 0;
1454 		timekeeping_inject_offset(&adjust);
1455 	}
1456 }
1457 
1458 /*
1459  * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1460  */
__timekeeping_set_tai_offset(struct timekeeper * tk,s32 tai_offset)1461 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1462 {
1463 	tk->tai_offset = tai_offset;
1464 	tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1465 }
1466 
1467 /*
1468  * change_clocksource - Swaps clocksources if a new one is available
1469  *
1470  * Accumulates current time interval and initializes new clocksource
1471  */
change_clocksource(void * data)1472 static int change_clocksource(void *data)
1473 {
1474 	struct clocksource *new = data, *old = NULL;
1475 
1476 	/*
1477 	 * If the clocksource is in a module, get a module reference.
1478 	 * Succeeds for built-in code (owner == NULL) as well. Abort if the
1479 	 * reference can't be acquired.
1480 	 */
1481 	if (!try_module_get(new->owner))
1482 		return 0;
1483 
1484 	/* Abort if the device can't be enabled */
1485 	if (new->enable && new->enable(new) != 0) {
1486 		module_put(new->owner);
1487 		return 0;
1488 	}
1489 
1490 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1491 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
1492 
1493 		timekeeping_forward_now(tks);
1494 		old = tks->tkr_mono.clock;
1495 		tk_setup_internals(tks, new);
1496 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1497 	}
1498 
1499 	if (old) {
1500 		if (old->disable)
1501 			old->disable(old);
1502 		module_put(old->owner);
1503 	}
1504 
1505 	return 0;
1506 }
1507 
1508 /**
1509  * timekeeping_notify - Install a new clock source
1510  * @clock:		pointer to the clock source
1511  *
1512  * This function is called from clocksource.c after a new, better clock
1513  * source has been registered. The caller holds the clocksource_mutex.
1514  */
timekeeping_notify(struct clocksource * clock)1515 int timekeeping_notify(struct clocksource *clock)
1516 {
1517 	struct timekeeper *tk = &tk_core.timekeeper;
1518 
1519 	if (tk->tkr_mono.clock == clock)
1520 		return 0;
1521 	stop_machine(change_clocksource, clock, NULL);
1522 	tick_clock_notify();
1523 	return tk->tkr_mono.clock == clock ? 0 : -1;
1524 }
1525 
1526 /**
1527  * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
1528  * @ts:		pointer to the timespec64 to be set
1529  *
1530  * Returns the raw monotonic time (completely un-modified by ntp)
1531  */
ktime_get_raw_ts64(struct timespec64 * ts)1532 void ktime_get_raw_ts64(struct timespec64 *ts)
1533 {
1534 	struct timekeeper *tk = &tk_core.timekeeper;
1535 	unsigned int seq;
1536 	u64 nsecs;
1537 
1538 	do {
1539 		seq = read_seqcount_begin(&tk_core.seq);
1540 		ts->tv_sec = tk->raw_sec;
1541 		nsecs = timekeeping_get_ns(&tk->tkr_raw);
1542 
1543 	} while (read_seqcount_retry(&tk_core.seq, seq));
1544 
1545 	ts->tv_nsec = 0;
1546 	timespec64_add_ns(ts, nsecs);
1547 }
1548 EXPORT_SYMBOL(ktime_get_raw_ts64);
1549 
1550 
1551 /**
1552  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1553  */
timekeeping_valid_for_hres(void)1554 int timekeeping_valid_for_hres(void)
1555 {
1556 	struct timekeeper *tk = &tk_core.timekeeper;
1557 	unsigned int seq;
1558 	int ret;
1559 
1560 	do {
1561 		seq = read_seqcount_begin(&tk_core.seq);
1562 
1563 		ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1564 
1565 	} while (read_seqcount_retry(&tk_core.seq, seq));
1566 
1567 	return ret;
1568 }
1569 
1570 /**
1571  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1572  */
timekeeping_max_deferment(void)1573 u64 timekeeping_max_deferment(void)
1574 {
1575 	struct timekeeper *tk = &tk_core.timekeeper;
1576 	unsigned int seq;
1577 	u64 ret;
1578 
1579 	do {
1580 		seq = read_seqcount_begin(&tk_core.seq);
1581 
1582 		ret = tk->tkr_mono.clock->max_idle_ns;
1583 
1584 	} while (read_seqcount_retry(&tk_core.seq, seq));
1585 
1586 	return ret;
1587 }
1588 
1589 /**
1590  * read_persistent_clock64 -  Return time from the persistent clock.
1591  * @ts: Pointer to the storage for the readout value
1592  *
1593  * Weak dummy function for arches that do not yet support it.
1594  * Reads the time from the battery backed persistent clock.
1595  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1596  *
1597  *  XXX - Do be sure to remove it once all arches implement it.
1598  */
read_persistent_clock64(struct timespec64 * ts)1599 void __weak read_persistent_clock64(struct timespec64 *ts)
1600 {
1601 	ts->tv_sec = 0;
1602 	ts->tv_nsec = 0;
1603 }
1604 
1605 /**
1606  * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
1607  *                                        from the boot.
1608  * @wall_time:	  current time as returned by persistent clock
1609  * @boot_offset:  offset that is defined as wall_time - boot_time
1610  *
1611  * Weak dummy function for arches that do not yet support it.
1612  *
1613  * The default function calculates offset based on the current value of
1614  * local_clock(). This way architectures that support sched_clock() but don't
1615  * support dedicated boot time clock will provide the best estimate of the
1616  * boot time.
1617  */
1618 void __weak __init
read_persistent_wall_and_boot_offset(struct timespec64 * wall_time,struct timespec64 * boot_offset)1619 read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
1620 				     struct timespec64 *boot_offset)
1621 {
1622 	read_persistent_clock64(wall_time);
1623 	*boot_offset = ns_to_timespec64(local_clock());
1624 }
1625 
tkd_basic_setup(struct tk_data * tkd)1626 static __init void tkd_basic_setup(struct tk_data *tkd)
1627 {
1628 	raw_spin_lock_init(&tkd->lock);
1629 	seqcount_raw_spinlock_init(&tkd->seq, &tkd->lock);
1630 }
1631 
1632 /*
1633  * Flag reflecting whether timekeeping_resume() has injected sleeptime.
1634  *
1635  * The flag starts of false and is only set when a suspend reaches
1636  * timekeeping_suspend(), timekeeping_resume() sets it to false when the
1637  * timekeeper clocksource is not stopping across suspend and has been
1638  * used to update sleep time. If the timekeeper clocksource has stopped
1639  * then the flag stays true and is used by the RTC resume code to decide
1640  * whether sleeptime must be injected and if so the flag gets false then.
1641  *
1642  * If a suspend fails before reaching timekeeping_resume() then the flag
1643  * stays false and prevents erroneous sleeptime injection.
1644  */
1645 static bool suspend_timing_needed;
1646 
1647 /* Flag for if there is a persistent clock on this platform */
1648 static bool persistent_clock_exists;
1649 
1650 /*
1651  * timekeeping_init - Initializes the clocksource and common timekeeping values
1652  */
timekeeping_init(void)1653 void __init timekeeping_init(void)
1654 {
1655 	struct timespec64 wall_time, boot_offset, wall_to_mono;
1656 	struct timekeeper *tks = &tk_core.shadow_timekeeper;
1657 	struct clocksource *clock;
1658 
1659 	tkd_basic_setup(&tk_core);
1660 
1661 	read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
1662 	if (timespec64_valid_settod(&wall_time) &&
1663 	    timespec64_to_ns(&wall_time) > 0) {
1664 		persistent_clock_exists = true;
1665 	} else if (timespec64_to_ns(&wall_time) != 0) {
1666 		pr_warn("Persistent clock returned invalid value");
1667 		wall_time = (struct timespec64){0};
1668 	}
1669 
1670 	if (timespec64_compare(&wall_time, &boot_offset) < 0)
1671 		boot_offset = (struct timespec64){0};
1672 
1673 	/*
1674 	 * We want set wall_to_mono, so the following is true:
1675 	 * wall time + wall_to_mono = boot time
1676 	 */
1677 	wall_to_mono = timespec64_sub(boot_offset, wall_time);
1678 
1679 	guard(raw_spinlock_irqsave)(&tk_core.lock);
1680 
1681 	ntp_init();
1682 
1683 	clock = clocksource_default_clock();
1684 	if (clock->enable)
1685 		clock->enable(clock);
1686 	tk_setup_internals(tks, clock);
1687 
1688 	tk_set_xtime(tks, &wall_time);
1689 	tks->raw_sec = 0;
1690 
1691 	tk_set_wall_to_mono(tks, wall_to_mono);
1692 
1693 	timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
1694 }
1695 
1696 /* time in seconds when suspend began for persistent clock */
1697 static struct timespec64 timekeeping_suspend_time;
1698 
1699 /**
1700  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1701  * @tk:		Pointer to the timekeeper to be updated
1702  * @delta:	Pointer to the delta value in timespec64 format
1703  *
1704  * Takes a timespec offset measuring a suspend interval and properly
1705  * adds the sleep offset to the timekeeping variables.
1706  */
__timekeeping_inject_sleeptime(struct timekeeper * tk,const struct timespec64 * delta)1707 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1708 					   const struct timespec64 *delta)
1709 {
1710 	if (!timespec64_valid_strict(delta)) {
1711 		printk_deferred(KERN_WARNING
1712 				"__timekeeping_inject_sleeptime: Invalid "
1713 				"sleep delta value!\n");
1714 		return;
1715 	}
1716 	tk_xtime_add(tk, delta);
1717 	tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
1718 	tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
1719 	tk_debug_account_sleep_time(delta);
1720 }
1721 
1722 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1723 /*
1724  * We have three kinds of time sources to use for sleep time
1725  * injection, the preference order is:
1726  * 1) non-stop clocksource
1727  * 2) persistent clock (ie: RTC accessible when irqs are off)
1728  * 3) RTC
1729  *
1730  * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
1731  * If system has neither 1) nor 2), 3) will be used finally.
1732  *
1733  *
1734  * If timekeeping has injected sleeptime via either 1) or 2),
1735  * 3) becomes needless, so in this case we don't need to call
1736  * rtc_resume(), and this is what timekeeping_rtc_skipresume()
1737  * means.
1738  */
timekeeping_rtc_skipresume(void)1739 bool timekeeping_rtc_skipresume(void)
1740 {
1741 	return !suspend_timing_needed;
1742 }
1743 
1744 /*
1745  * 1) can be determined whether to use or not only when doing
1746  * timekeeping_resume() which is invoked after rtc_suspend(),
1747  * so we can't skip rtc_suspend() surely if system has 1).
1748  *
1749  * But if system has 2), 2) will definitely be used, so in this
1750  * case we don't need to call rtc_suspend(), and this is what
1751  * timekeeping_rtc_skipsuspend() means.
1752  */
timekeeping_rtc_skipsuspend(void)1753 bool timekeeping_rtc_skipsuspend(void)
1754 {
1755 	return persistent_clock_exists;
1756 }
1757 
1758 /**
1759  * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
1760  * @delta: pointer to a timespec64 delta value
1761  *
1762  * This hook is for architectures that cannot support read_persistent_clock64
1763  * because their RTC/persistent clock is only accessible when irqs are enabled.
1764  * and also don't have an effective nonstop clocksource.
1765  *
1766  * This function should only be called by rtc_resume(), and allows
1767  * a suspend offset to be injected into the timekeeping values.
1768  */
timekeeping_inject_sleeptime64(const struct timespec64 * delta)1769 void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
1770 {
1771 	scoped_guard(raw_spinlock_irqsave, &tk_core.lock) {
1772 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
1773 
1774 		suspend_timing_needed = false;
1775 		timekeeping_forward_now(tks);
1776 		__timekeeping_inject_sleeptime(tks, delta);
1777 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1778 	}
1779 
1780 	/* Signal hrtimers about time change */
1781 	clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
1782 }
1783 #endif
1784 
1785 /**
1786  * timekeeping_resume - Resumes the generic timekeeping subsystem.
1787  */
timekeeping_resume(void)1788 void timekeeping_resume(void)
1789 {
1790 	struct timekeeper *tks = &tk_core.shadow_timekeeper;
1791 	struct clocksource *clock = tks->tkr_mono.clock;
1792 	struct timespec64 ts_new, ts_delta;
1793 	bool inject_sleeptime = false;
1794 	u64 cycle_now, nsec;
1795 	unsigned long flags;
1796 
1797 	read_persistent_clock64(&ts_new);
1798 
1799 	clockevents_resume();
1800 	clocksource_resume();
1801 
1802 	raw_spin_lock_irqsave(&tk_core.lock, flags);
1803 
1804 	/*
1805 	 * After system resumes, we need to calculate the suspended time and
1806 	 * compensate it for the OS time. There are 3 sources that could be
1807 	 * used: Nonstop clocksource during suspend, persistent clock and rtc
1808 	 * device.
1809 	 *
1810 	 * One specific platform may have 1 or 2 or all of them, and the
1811 	 * preference will be:
1812 	 *	suspend-nonstop clocksource -> persistent clock -> rtc
1813 	 * The less preferred source will only be tried if there is no better
1814 	 * usable source. The rtc part is handled separately in rtc core code.
1815 	 */
1816 	cycle_now = tk_clock_read(&tks->tkr_mono);
1817 	nsec = clocksource_stop_suspend_timing(clock, cycle_now);
1818 	if (nsec > 0) {
1819 		ts_delta = ns_to_timespec64(nsec);
1820 		inject_sleeptime = true;
1821 	} else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
1822 		ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1823 		inject_sleeptime = true;
1824 	}
1825 
1826 	if (inject_sleeptime) {
1827 		suspend_timing_needed = false;
1828 		__timekeeping_inject_sleeptime(tks, &ts_delta);
1829 	}
1830 
1831 	/* Re-base the last cycle value */
1832 	tks->tkr_mono.cycle_last = cycle_now;
1833 	tks->tkr_raw.cycle_last  = cycle_now;
1834 
1835 	tks->ntp_error = 0;
1836 	timekeeping_suspended = 0;
1837 	timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
1838 	raw_spin_unlock_irqrestore(&tk_core.lock, flags);
1839 
1840 	touch_softlockup_watchdog();
1841 
1842 	/* Resume the clockevent device(s) and hrtimers */
1843 	tick_resume();
1844 	/* Notify timerfd as resume is equivalent to clock_was_set() */
1845 	timerfd_resume();
1846 }
1847 
timekeeping_suspend(void)1848 int timekeeping_suspend(void)
1849 {
1850 	struct timekeeper *tks = &tk_core.shadow_timekeeper;
1851 	struct timespec64 delta, delta_delta;
1852 	static struct timespec64 old_delta;
1853 	struct clocksource *curr_clock;
1854 	unsigned long flags;
1855 	u64 cycle_now;
1856 
1857 	read_persistent_clock64(&timekeeping_suspend_time);
1858 
1859 	/*
1860 	 * On some systems the persistent_clock can not be detected at
1861 	 * timekeeping_init by its return value, so if we see a valid
1862 	 * value returned, update the persistent_clock_exists flag.
1863 	 */
1864 	if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
1865 		persistent_clock_exists = true;
1866 
1867 	suspend_timing_needed = true;
1868 
1869 	raw_spin_lock_irqsave(&tk_core.lock, flags);
1870 	timekeeping_forward_now(tks);
1871 	timekeeping_suspended = 1;
1872 
1873 	/*
1874 	 * Since we've called forward_now, cycle_last stores the value
1875 	 * just read from the current clocksource. Save this to potentially
1876 	 * use in suspend timing.
1877 	 */
1878 	curr_clock = tks->tkr_mono.clock;
1879 	cycle_now = tks->tkr_mono.cycle_last;
1880 	clocksource_start_suspend_timing(curr_clock, cycle_now);
1881 
1882 	if (persistent_clock_exists) {
1883 		/*
1884 		 * To avoid drift caused by repeated suspend/resumes,
1885 		 * which each can add ~1 second drift error,
1886 		 * try to compensate so the difference in system time
1887 		 * and persistent_clock time stays close to constant.
1888 		 */
1889 		delta = timespec64_sub(tk_xtime(tks), timekeeping_suspend_time);
1890 		delta_delta = timespec64_sub(delta, old_delta);
1891 		if (abs(delta_delta.tv_sec) >= 2) {
1892 			/*
1893 			 * if delta_delta is too large, assume time correction
1894 			 * has occurred and set old_delta to the current delta.
1895 			 */
1896 			old_delta = delta;
1897 		} else {
1898 			/* Otherwise try to adjust old_system to compensate */
1899 			timekeeping_suspend_time =
1900 				timespec64_add(timekeeping_suspend_time, delta_delta);
1901 		}
1902 	}
1903 
1904 	timekeeping_update_from_shadow(&tk_core, 0);
1905 	halt_fast_timekeeper(tks);
1906 	raw_spin_unlock_irqrestore(&tk_core.lock, flags);
1907 
1908 	tick_suspend();
1909 	clocksource_suspend();
1910 	clockevents_suspend();
1911 
1912 	return 0;
1913 }
1914 
1915 /* sysfs resume/suspend bits for timekeeping */
1916 static struct syscore_ops timekeeping_syscore_ops = {
1917 	.resume		= timekeeping_resume,
1918 	.suspend	= timekeeping_suspend,
1919 };
1920 
timekeeping_init_ops(void)1921 static int __init timekeeping_init_ops(void)
1922 {
1923 	register_syscore_ops(&timekeeping_syscore_ops);
1924 	return 0;
1925 }
1926 device_initcall(timekeeping_init_ops);
1927 
1928 /*
1929  * Apply a multiplier adjustment to the timekeeper
1930  */
timekeeping_apply_adjustment(struct timekeeper * tk,s64 offset,s32 mult_adj)1931 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1932 							 s64 offset,
1933 							 s32 mult_adj)
1934 {
1935 	s64 interval = tk->cycle_interval;
1936 
1937 	if (mult_adj == 0) {
1938 		return;
1939 	} else if (mult_adj == -1) {
1940 		interval = -interval;
1941 		offset = -offset;
1942 	} else if (mult_adj != 1) {
1943 		interval *= mult_adj;
1944 		offset *= mult_adj;
1945 	}
1946 
1947 	/*
1948 	 * So the following can be confusing.
1949 	 *
1950 	 * To keep things simple, lets assume mult_adj == 1 for now.
1951 	 *
1952 	 * When mult_adj != 1, remember that the interval and offset values
1953 	 * have been appropriately scaled so the math is the same.
1954 	 *
1955 	 * The basic idea here is that we're increasing the multiplier
1956 	 * by one, this causes the xtime_interval to be incremented by
1957 	 * one cycle_interval. This is because:
1958 	 *	xtime_interval = cycle_interval * mult
1959 	 * So if mult is being incremented by one:
1960 	 *	xtime_interval = cycle_interval * (mult + 1)
1961 	 * Its the same as:
1962 	 *	xtime_interval = (cycle_interval * mult) + cycle_interval
1963 	 * Which can be shortened to:
1964 	 *	xtime_interval += cycle_interval
1965 	 *
1966 	 * So offset stores the non-accumulated cycles. Thus the current
1967 	 * time (in shifted nanoseconds) is:
1968 	 *	now = (offset * adj) + xtime_nsec
1969 	 * Now, even though we're adjusting the clock frequency, we have
1970 	 * to keep time consistent. In other words, we can't jump back
1971 	 * in time, and we also want to avoid jumping forward in time.
1972 	 *
1973 	 * So given the same offset value, we need the time to be the same
1974 	 * both before and after the freq adjustment.
1975 	 *	now = (offset * adj_1) + xtime_nsec_1
1976 	 *	now = (offset * adj_2) + xtime_nsec_2
1977 	 * So:
1978 	 *	(offset * adj_1) + xtime_nsec_1 =
1979 	 *		(offset * adj_2) + xtime_nsec_2
1980 	 * And we know:
1981 	 *	adj_2 = adj_1 + 1
1982 	 * So:
1983 	 *	(offset * adj_1) + xtime_nsec_1 =
1984 	 *		(offset * (adj_1+1)) + xtime_nsec_2
1985 	 *	(offset * adj_1) + xtime_nsec_1 =
1986 	 *		(offset * adj_1) + offset + xtime_nsec_2
1987 	 * Canceling the sides:
1988 	 *	xtime_nsec_1 = offset + xtime_nsec_2
1989 	 * Which gives us:
1990 	 *	xtime_nsec_2 = xtime_nsec_1 - offset
1991 	 * Which simplifies to:
1992 	 *	xtime_nsec -= offset
1993 	 */
1994 	if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
1995 		/* NTP adjustment caused clocksource mult overflow */
1996 		WARN_ON_ONCE(1);
1997 		return;
1998 	}
1999 
2000 	tk->tkr_mono.mult += mult_adj;
2001 	tk->xtime_interval += interval;
2002 	tk->tkr_mono.xtime_nsec -= offset;
2003 }
2004 
2005 /*
2006  * Adjust the timekeeper's multiplier to the correct frequency
2007  * and also to reduce the accumulated error value.
2008  */
timekeeping_adjust(struct timekeeper * tk,s64 offset)2009 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
2010 {
2011 	u64 ntp_tl = ntp_tick_length();
2012 	u32 mult;
2013 
2014 	/*
2015 	 * Determine the multiplier from the current NTP tick length.
2016 	 * Avoid expensive division when the tick length doesn't change.
2017 	 */
2018 	if (likely(tk->ntp_tick == ntp_tl)) {
2019 		mult = tk->tkr_mono.mult - tk->ntp_err_mult;
2020 	} else {
2021 		tk->ntp_tick = ntp_tl;
2022 		mult = div64_u64((tk->ntp_tick >> tk->ntp_error_shift) -
2023 				 tk->xtime_remainder, tk->cycle_interval);
2024 	}
2025 
2026 	/*
2027 	 * If the clock is behind the NTP time, increase the multiplier by 1
2028 	 * to catch up with it. If it's ahead and there was a remainder in the
2029 	 * tick division, the clock will slow down. Otherwise it will stay
2030 	 * ahead until the tick length changes to a non-divisible value.
2031 	 */
2032 	tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
2033 	mult += tk->ntp_err_mult;
2034 
2035 	timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
2036 
2037 	if (unlikely(tk->tkr_mono.clock->maxadj &&
2038 		(abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2039 			> tk->tkr_mono.clock->maxadj))) {
2040 		printk_once(KERN_WARNING
2041 			"Adjusting %s more than 11%% (%ld vs %ld)\n",
2042 			tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2043 			(long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
2044 	}
2045 
2046 	/*
2047 	 * It may be possible that when we entered this function, xtime_nsec
2048 	 * was very small.  Further, if we're slightly speeding the clocksource
2049 	 * in the code above, its possible the required corrective factor to
2050 	 * xtime_nsec could cause it to underflow.
2051 	 *
2052 	 * Now, since we have already accumulated the second and the NTP
2053 	 * subsystem has been notified via second_overflow(), we need to skip
2054 	 * the next update.
2055 	 */
2056 	if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
2057 		tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
2058 							tk->tkr_mono.shift;
2059 		tk->xtime_sec--;
2060 		tk->skip_second_overflow = 1;
2061 	}
2062 }
2063 
2064 /*
2065  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2066  *
2067  * Helper function that accumulates the nsecs greater than a second
2068  * from the xtime_nsec field to the xtime_secs field.
2069  * It also calls into the NTP code to handle leapsecond processing.
2070  */
accumulate_nsecs_to_secs(struct timekeeper * tk)2071 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
2072 {
2073 	u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2074 	unsigned int clock_set = 0;
2075 
2076 	while (tk->tkr_mono.xtime_nsec >= nsecps) {
2077 		int leap;
2078 
2079 		tk->tkr_mono.xtime_nsec -= nsecps;
2080 		tk->xtime_sec++;
2081 
2082 		/*
2083 		 * Skip NTP update if this second was accumulated before,
2084 		 * i.e. xtime_nsec underflowed in timekeeping_adjust()
2085 		 */
2086 		if (unlikely(tk->skip_second_overflow)) {
2087 			tk->skip_second_overflow = 0;
2088 			continue;
2089 		}
2090 
2091 		/* Figure out if its a leap sec and apply if needed */
2092 		leap = second_overflow(tk->xtime_sec);
2093 		if (unlikely(leap)) {
2094 			struct timespec64 ts;
2095 
2096 			tk->xtime_sec += leap;
2097 
2098 			ts.tv_sec = leap;
2099 			ts.tv_nsec = 0;
2100 			tk_set_wall_to_mono(tk,
2101 				timespec64_sub(tk->wall_to_monotonic, ts));
2102 
2103 			__timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2104 
2105 			clock_set = TK_CLOCK_WAS_SET;
2106 		}
2107 	}
2108 	return clock_set;
2109 }
2110 
2111 /*
2112  * logarithmic_accumulation - shifted accumulation of cycles
2113  *
2114  * This functions accumulates a shifted interval of cycles into
2115  * a shifted interval nanoseconds. Allows for O(log) accumulation
2116  * loop.
2117  *
2118  * Returns the unconsumed cycles.
2119  */
logarithmic_accumulation(struct timekeeper * tk,u64 offset,u32 shift,unsigned int * clock_set)2120 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2121 				    u32 shift, unsigned int *clock_set)
2122 {
2123 	u64 interval = tk->cycle_interval << shift;
2124 	u64 snsec_per_sec;
2125 
2126 	/* If the offset is smaller than a shifted interval, do nothing */
2127 	if (offset < interval)
2128 		return offset;
2129 
2130 	/* Accumulate one shifted interval */
2131 	offset -= interval;
2132 	tk->tkr_mono.cycle_last += interval;
2133 	tk->tkr_raw.cycle_last  += interval;
2134 
2135 	tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2136 	*clock_set |= accumulate_nsecs_to_secs(tk);
2137 
2138 	/* Accumulate raw time */
2139 	tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2140 	snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2141 	while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2142 		tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2143 		tk->raw_sec++;
2144 	}
2145 
2146 	/* Accumulate error between NTP and clock interval */
2147 	tk->ntp_error += tk->ntp_tick << shift;
2148 	tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2149 						(tk->ntp_error_shift + shift);
2150 
2151 	return offset;
2152 }
2153 
2154 /*
2155  * timekeeping_advance - Updates the timekeeper to the current time and
2156  * current NTP tick length
2157  */
timekeeping_advance(enum timekeeping_adv_mode mode)2158 static bool timekeeping_advance(enum timekeeping_adv_mode mode)
2159 {
2160 	struct timekeeper *tk = &tk_core.shadow_timekeeper;
2161 	struct timekeeper *real_tk = &tk_core.timekeeper;
2162 	unsigned int clock_set = 0;
2163 	int shift = 0, maxshift;
2164 	u64 offset;
2165 
2166 	guard(raw_spinlock_irqsave)(&tk_core.lock);
2167 
2168 	/* Make sure we're fully resumed: */
2169 	if (unlikely(timekeeping_suspended))
2170 		return false;
2171 
2172 	offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2173 				   tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
2174 				   tk->tkr_mono.clock->max_raw_delta);
2175 
2176 	/* Check if there's really nothing to do */
2177 	if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
2178 		return false;
2179 
2180 	/*
2181 	 * With NO_HZ we may have to accumulate many cycle_intervals
2182 	 * (think "ticks") worth of time at once. To do this efficiently,
2183 	 * we calculate the largest doubling multiple of cycle_intervals
2184 	 * that is smaller than the offset.  We then accumulate that
2185 	 * chunk in one go, and then try to consume the next smaller
2186 	 * doubled multiple.
2187 	 */
2188 	shift = ilog2(offset) - ilog2(tk->cycle_interval);
2189 	shift = max(0, shift);
2190 	/* Bound shift to one less than what overflows tick_length */
2191 	maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2192 	shift = min(shift, maxshift);
2193 	while (offset >= tk->cycle_interval) {
2194 		offset = logarithmic_accumulation(tk, offset, shift, &clock_set);
2195 		if (offset < tk->cycle_interval<<shift)
2196 			shift--;
2197 	}
2198 
2199 	/* Adjust the multiplier to correct NTP error */
2200 	timekeeping_adjust(tk, offset);
2201 
2202 	/*
2203 	 * Finally, make sure that after the rounding
2204 	 * xtime_nsec isn't larger than NSEC_PER_SEC
2205 	 */
2206 	clock_set |= accumulate_nsecs_to_secs(tk);
2207 
2208 	timekeeping_update_from_shadow(&tk_core, clock_set);
2209 
2210 	return !!clock_set;
2211 }
2212 
2213 /**
2214  * update_wall_time - Uses the current clocksource to increment the wall time
2215  *
2216  */
update_wall_time(void)2217 void update_wall_time(void)
2218 {
2219 	if (timekeeping_advance(TK_ADV_TICK))
2220 		clock_was_set_delayed();
2221 }
2222 
2223 /**
2224  * getboottime64 - Return the real time of system boot.
2225  * @ts:		pointer to the timespec64 to be set
2226  *
2227  * Returns the wall-time of boot in a timespec64.
2228  *
2229  * This is based on the wall_to_monotonic offset and the total suspend
2230  * time. Calls to settimeofday will affect the value returned (which
2231  * basically means that however wrong your real time clock is at boot time,
2232  * you get the right time here).
2233  */
getboottime64(struct timespec64 * ts)2234 void getboottime64(struct timespec64 *ts)
2235 {
2236 	struct timekeeper *tk = &tk_core.timekeeper;
2237 	ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2238 
2239 	*ts = ktime_to_timespec64(t);
2240 }
2241 EXPORT_SYMBOL_GPL(getboottime64);
2242 
ktime_get_coarse_real_ts64(struct timespec64 * ts)2243 void ktime_get_coarse_real_ts64(struct timespec64 *ts)
2244 {
2245 	struct timekeeper *tk = &tk_core.timekeeper;
2246 	unsigned int seq;
2247 
2248 	do {
2249 		seq = read_seqcount_begin(&tk_core.seq);
2250 
2251 		*ts = tk_xtime(tk);
2252 	} while (read_seqcount_retry(&tk_core.seq, seq));
2253 }
2254 EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
2255 
2256 /**
2257  * ktime_get_coarse_real_ts64_mg - return latter of coarse grained time or floor
2258  * @ts:		timespec64 to be filled
2259  *
2260  * Fetch the global mg_floor value, convert it to realtime and compare it
2261  * to the current coarse-grained time. Fill @ts with whichever is
2262  * latest. Note that this is a filesystem-specific interface and should be
2263  * avoided outside of that context.
2264  */
ktime_get_coarse_real_ts64_mg(struct timespec64 * ts)2265 void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
2266 {
2267 	struct timekeeper *tk = &tk_core.timekeeper;
2268 	u64 floor = atomic64_read(&mg_floor);
2269 	ktime_t f_real, offset, coarse;
2270 	unsigned int seq;
2271 
2272 	do {
2273 		seq = read_seqcount_begin(&tk_core.seq);
2274 		*ts = tk_xtime(tk);
2275 		offset = tk_core.timekeeper.offs_real;
2276 	} while (read_seqcount_retry(&tk_core.seq, seq));
2277 
2278 	coarse = timespec64_to_ktime(*ts);
2279 	f_real = ktime_add(floor, offset);
2280 	if (ktime_after(f_real, coarse))
2281 		*ts = ktime_to_timespec64(f_real);
2282 }
2283 
2284 /**
2285  * ktime_get_real_ts64_mg - attempt to update floor value and return result
2286  * @ts:		pointer to the timespec to be set
2287  *
2288  * Get a monotonic fine-grained time value and attempt to swap it into
2289  * mg_floor. If that succeeds then accept the new floor value. If it fails
2290  * then another task raced in during the interim time and updated the
2291  * floor.  Since any update to the floor must be later than the previous
2292  * floor, either outcome is acceptable.
2293  *
2294  * Typically this will be called after calling ktime_get_coarse_real_ts64_mg(),
2295  * and determining that the resulting coarse-grained timestamp did not effect
2296  * a change in ctime. Any more recent floor value would effect a change to
2297  * ctime, so there is no need to retry the atomic64_try_cmpxchg() on failure.
2298  *
2299  * @ts will be filled with the latest floor value, regardless of the outcome of
2300  * the cmpxchg. Note that this is a filesystem specific interface and should be
2301  * avoided outside of that context.
2302  */
ktime_get_real_ts64_mg(struct timespec64 * ts)2303 void ktime_get_real_ts64_mg(struct timespec64 *ts)
2304 {
2305 	struct timekeeper *tk = &tk_core.timekeeper;
2306 	ktime_t old = atomic64_read(&mg_floor);
2307 	ktime_t offset, mono;
2308 	unsigned int seq;
2309 	u64 nsecs;
2310 
2311 	do {
2312 		seq = read_seqcount_begin(&tk_core.seq);
2313 
2314 		ts->tv_sec = tk->xtime_sec;
2315 		mono = tk->tkr_mono.base;
2316 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
2317 		offset = tk_core.timekeeper.offs_real;
2318 	} while (read_seqcount_retry(&tk_core.seq, seq));
2319 
2320 	mono = ktime_add_ns(mono, nsecs);
2321 
2322 	/*
2323 	 * Attempt to update the floor with the new time value. As any
2324 	 * update must be later then the existing floor, and would effect
2325 	 * a change to ctime from the perspective of the current task,
2326 	 * accept the resulting floor value regardless of the outcome of
2327 	 * the swap.
2328 	 */
2329 	if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
2330 		ts->tv_nsec = 0;
2331 		timespec64_add_ns(ts, nsecs);
2332 		timekeeping_inc_mg_floor_swaps();
2333 	} else {
2334 		/*
2335 		 * Another task changed mg_floor since "old" was fetched.
2336 		 * "old" has been updated with the latest value of "mg_floor".
2337 		 * That value is newer than the previous floor value, which
2338 		 * is enough to effect a change to ctime. Accept it.
2339 		 */
2340 		*ts = ktime_to_timespec64(ktime_add(old, offset));
2341 	}
2342 }
2343 
ktime_get_coarse_ts64(struct timespec64 * ts)2344 void ktime_get_coarse_ts64(struct timespec64 *ts)
2345 {
2346 	struct timekeeper *tk = &tk_core.timekeeper;
2347 	struct timespec64 now, mono;
2348 	unsigned int seq;
2349 
2350 	do {
2351 		seq = read_seqcount_begin(&tk_core.seq);
2352 
2353 		now = tk_xtime(tk);
2354 		mono = tk->wall_to_monotonic;
2355 	} while (read_seqcount_retry(&tk_core.seq, seq));
2356 
2357 	set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
2358 				now.tv_nsec + mono.tv_nsec);
2359 }
2360 EXPORT_SYMBOL(ktime_get_coarse_ts64);
2361 
2362 /*
2363  * Must hold jiffies_lock
2364  */
do_timer(unsigned long ticks)2365 void do_timer(unsigned long ticks)
2366 {
2367 	jiffies_64 += ticks;
2368 	calc_global_load();
2369 }
2370 
2371 /**
2372  * ktime_get_update_offsets_now - hrtimer helper
2373  * @cwsseq:	pointer to check and store the clock was set sequence number
2374  * @offs_real:	pointer to storage for monotonic -> realtime offset
2375  * @offs_boot:	pointer to storage for monotonic -> boottime offset
2376  * @offs_tai:	pointer to storage for monotonic -> clock tai offset
2377  *
2378  * Returns current monotonic time and updates the offsets if the
2379  * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2380  * different.
2381  *
2382  * Called from hrtimer_interrupt() or retrigger_next_event()
2383  */
ktime_get_update_offsets_now(unsigned int * cwsseq,ktime_t * offs_real,ktime_t * offs_boot,ktime_t * offs_tai)2384 ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2385 				     ktime_t *offs_boot, ktime_t *offs_tai)
2386 {
2387 	struct timekeeper *tk = &tk_core.timekeeper;
2388 	unsigned int seq;
2389 	ktime_t base;
2390 	u64 nsecs;
2391 
2392 	do {
2393 		seq = read_seqcount_begin(&tk_core.seq);
2394 
2395 		base = tk->tkr_mono.base;
2396 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
2397 		base = ktime_add_ns(base, nsecs);
2398 
2399 		if (*cwsseq != tk->clock_was_set_seq) {
2400 			*cwsseq = tk->clock_was_set_seq;
2401 			*offs_real = tk->offs_real;
2402 			*offs_boot = tk->offs_boot;
2403 			*offs_tai = tk->offs_tai;
2404 		}
2405 
2406 		/* Handle leapsecond insertion adjustments */
2407 		if (unlikely(base >= tk->next_leap_ktime))
2408 			*offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2409 
2410 	} while (read_seqcount_retry(&tk_core.seq, seq));
2411 
2412 	return base;
2413 }
2414 
2415 /*
2416  * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2417  */
timekeeping_validate_timex(const struct __kernel_timex * txc)2418 static int timekeeping_validate_timex(const struct __kernel_timex *txc)
2419 {
2420 	if (txc->modes & ADJ_ADJTIME) {
2421 		/* singleshot must not be used with any other mode bits */
2422 		if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2423 			return -EINVAL;
2424 		if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2425 		    !capable(CAP_SYS_TIME))
2426 			return -EPERM;
2427 	} else {
2428 		/* In order to modify anything, you gotta be super-user! */
2429 		if (txc->modes && !capable(CAP_SYS_TIME))
2430 			return -EPERM;
2431 		/*
2432 		 * if the quartz is off by more than 10% then
2433 		 * something is VERY wrong!
2434 		 */
2435 		if (txc->modes & ADJ_TICK &&
2436 		    (txc->tick <  900000/USER_HZ ||
2437 		     txc->tick > 1100000/USER_HZ))
2438 			return -EINVAL;
2439 	}
2440 
2441 	if (txc->modes & ADJ_SETOFFSET) {
2442 		/* In order to inject time, you gotta be super-user! */
2443 		if (!capable(CAP_SYS_TIME))
2444 			return -EPERM;
2445 
2446 		/*
2447 		 * Validate if a timespec/timeval used to inject a time
2448 		 * offset is valid.  Offsets can be positive or negative, so
2449 		 * we don't check tv_sec. The value of the timeval/timespec
2450 		 * is the sum of its fields,but *NOTE*:
2451 		 * The field tv_usec/tv_nsec must always be non-negative and
2452 		 * we can't have more nanoseconds/microseconds than a second.
2453 		 */
2454 		if (txc->time.tv_usec < 0)
2455 			return -EINVAL;
2456 
2457 		if (txc->modes & ADJ_NANO) {
2458 			if (txc->time.tv_usec >= NSEC_PER_SEC)
2459 				return -EINVAL;
2460 		} else {
2461 			if (txc->time.tv_usec >= USEC_PER_SEC)
2462 				return -EINVAL;
2463 		}
2464 	}
2465 
2466 	/*
2467 	 * Check for potential multiplication overflows that can
2468 	 * only happen on 64-bit systems:
2469 	 */
2470 	if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2471 		if (LLONG_MIN / PPM_SCALE > txc->freq)
2472 			return -EINVAL;
2473 		if (LLONG_MAX / PPM_SCALE < txc->freq)
2474 			return -EINVAL;
2475 	}
2476 
2477 	return 0;
2478 }
2479 
2480 /**
2481  * random_get_entropy_fallback - Returns the raw clock source value,
2482  * used by random.c for platforms with no valid random_get_entropy().
2483  */
random_get_entropy_fallback(void)2484 unsigned long random_get_entropy_fallback(void)
2485 {
2486 	struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
2487 	struct clocksource *clock = READ_ONCE(tkr->clock);
2488 
2489 	if (unlikely(timekeeping_suspended || !clock))
2490 		return 0;
2491 	return clock->read(clock);
2492 }
2493 EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
2494 
2495 /**
2496  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2497  * @txc:	Pointer to kernel_timex structure containing NTP parameters
2498  */
do_adjtimex(struct __kernel_timex * txc)2499 int do_adjtimex(struct __kernel_timex *txc)
2500 {
2501 	struct audit_ntp_data ad;
2502 	bool offset_set = false;
2503 	bool clock_set = false;
2504 	struct timespec64 ts;
2505 	int ret;
2506 
2507 	/* Validate the data before disabling interrupts */
2508 	ret = timekeeping_validate_timex(txc);
2509 	if (ret)
2510 		return ret;
2511 	add_device_randomness(txc, sizeof(*txc));
2512 
2513 	if (txc->modes & ADJ_SETOFFSET) {
2514 		struct timespec64 delta;
2515 
2516 		delta.tv_sec  = txc->time.tv_sec;
2517 		delta.tv_nsec = txc->time.tv_usec;
2518 		if (!(txc->modes & ADJ_NANO))
2519 			delta.tv_nsec *= 1000;
2520 		ret = timekeeping_inject_offset(&delta);
2521 		if (ret)
2522 			return ret;
2523 
2524 		offset_set = delta.tv_sec != 0;
2525 		audit_tk_injoffset(delta);
2526 	}
2527 
2528 	audit_ntp_init(&ad);
2529 
2530 	ktime_get_real_ts64(&ts);
2531 	add_device_randomness(&ts, sizeof(ts));
2532 
2533 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
2534 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
2535 		s32 orig_tai, tai;
2536 
2537 		orig_tai = tai = tks->tai_offset;
2538 		ret = __do_adjtimex(txc, &ts, &tai, &ad);
2539 
2540 		if (tai != orig_tai) {
2541 			__timekeeping_set_tai_offset(tks, tai);
2542 			timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
2543 			clock_set = true;
2544 		} else {
2545 			tk_update_leap_state_all(&tk_core);
2546 		}
2547 	}
2548 
2549 	audit_ntp_log(&ad);
2550 
2551 	/* Update the multiplier immediately if frequency was set directly */
2552 	if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
2553 		clock_set |= timekeeping_advance(TK_ADV_FREQ);
2554 
2555 	if (clock_set)
2556 		clock_was_set(CLOCK_SET_WALL);
2557 
2558 	ntp_notify_cmos_timer(offset_set);
2559 
2560 	return ret;
2561 }
2562 
2563 #ifdef CONFIG_NTP_PPS
2564 /**
2565  * hardpps() - Accessor function to NTP __hardpps function
2566  * @phase_ts:	Pointer to timespec64 structure representing phase timestamp
2567  * @raw_ts:	Pointer to timespec64 structure representing raw timestamp
2568  */
hardpps(const struct timespec64 * phase_ts,const struct timespec64 * raw_ts)2569 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2570 {
2571 	guard(raw_spinlock_irqsave)(&tk_core.lock);
2572 	__hardpps(phase_ts, raw_ts);
2573 }
2574 EXPORT_SYMBOL(hardpps);
2575 #endif /* CONFIG_NTP_PPS */
2576