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