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