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