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