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