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