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