xref: /linux/kernel/time/timekeeping.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
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/audit.h>
7 #include <linux/clocksource.h>
8 #include <linux/compiler.h>
9 #include <linux/jiffies.h>
10 #include <linux/kobject.h>
11 #include <linux/module.h>
12 #include <linux/nmi.h>
13 #include <linux/pvclock_gtod.h>
14 #include <linux/random.h>
15 #include <linux/sched/clock.h>
16 #include <linux/sched/loadavg.h>
17 #include <linux/security.h>
18 #include <linux/static_key.h>
19 #include <linux/stop_machine.h>
20 #include <linux/syscore_ops.h>
21 #include <linux/tick.h>
22 #include <linux/time.h>
23 #include <linux/timex.h>
24 #include <linux/timekeeper_internal.h>
25 
26 #include <vdso/auxclock.h>
27 
28 #include "tick-internal.h"
29 #include "timekeeping_internal.h"
30 #include "ntp_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 timekeeper_data[TIMEKEEPERS_MAX];
57 
58 /* The core timekeeper */
59 #define tk_core		(timekeeper_data[TIMEKEEPER_CORE])
60 
61 #ifdef CONFIG_POSIX_AUX_CLOCKS
62 static inline bool tk_get_aux_ts64(unsigned int tkid, struct timespec64 *ts)
63 {
64 	return ktime_get_aux_ts64(CLOCK_AUX + tkid - TIMEKEEPER_AUX_FIRST, ts);
65 }
66 
67 static inline bool tk_is_aux(const struct timekeeper *tk)
68 {
69 	return tk->id >= TIMEKEEPER_AUX_FIRST && tk->id <= TIMEKEEPER_AUX_LAST;
70 }
71 static inline struct tk_data *aux_get_tk_data(clockid_t id);
72 #else
73 static inline bool tk_get_aux_ts64(unsigned int tkid, struct timespec64 *ts)
74 {
75 	return false;
76 }
77 
78 static inline bool tk_is_aux(const struct timekeeper *tk)
79 {
80 	return false;
81 }
82 static inline struct tk_data *aux_get_tk_data(clockid_t id)
83 {
84 	return NULL;
85 }
86 #endif
87 
88 static inline void tk_update_aux_offs(struct timekeeper *tk, ktime_t offs)
89 {
90 	tk->offs_aux = offs;
91 	tk->monotonic_to_aux = ktime_to_timespec64(offs);
92 }
93 
94 /* flag for if timekeeping is suspended */
95 int __read_mostly timekeeping_suspended;
96 
97 /**
98  * struct tk_fast - NMI safe timekeeper
99  * @seq:	Sequence counter for protecting updates. The lowest bit
100  *		is the index for the tk_read_base array
101  * @base:	tk_read_base array. Access is indexed by the lowest bit of
102  *		@seq.
103  *
104  * See @update_fast_timekeeper() below.
105  */
106 struct tk_fast {
107 	seqcount_latch_t	seq;
108 	struct tk_read_base	base[2];
109 };
110 
111 /* Suspend-time cycles value for halted fast timekeeper. */
112 static u64 cycles_at_suspend;
113 
114 static u64 dummy_clock_read(struct clocksource *cs)
115 {
116 	if (timekeeping_suspended)
117 		return cycles_at_suspend;
118 	return local_clock();
119 }
120 
121 static struct clocksource dummy_clock = {
122 	.read = dummy_clock_read,
123 };
124 
125 /*
126  * Boot time initialization which allows local_clock() to be utilized
127  * during early boot when clocksources are not available. local_clock()
128  * returns nanoseconds already so no conversion is required, hence mult=1
129  * and shift=0. When the first proper clocksource is installed then
130  * the fast time keepers are updated with the correct values.
131  */
132 #define FAST_TK_INIT						\
133 	{							\
134 		.clock		= &dummy_clock,			\
135 		.mask		= CLOCKSOURCE_MASK(64),		\
136 		.mult		= 1,				\
137 		.shift		= 0,				\
138 	}
139 
140 static struct tk_fast tk_fast_mono ____cacheline_aligned = {
141 	.seq     = SEQCNT_LATCH_ZERO(tk_fast_mono.seq),
142 	.base[0] = FAST_TK_INIT,
143 	.base[1] = FAST_TK_INIT,
144 };
145 
146 static struct tk_fast tk_fast_raw  ____cacheline_aligned = {
147 	.seq     = SEQCNT_LATCH_ZERO(tk_fast_raw.seq),
148 	.base[0] = FAST_TK_INIT,
149 	.base[1] = FAST_TK_INIT,
150 };
151 
152 #ifdef CONFIG_POSIX_AUX_CLOCKS
153 static __init void tk_aux_setup(void);
154 static void tk_aux_update_clocksource(void);
155 static void tk_aux_advance(void);
156 #else
157 static inline void tk_aux_setup(void) { }
158 static inline void tk_aux_update_clocksource(void) { }
159 static inline void tk_aux_advance(void) { }
160 #endif
161 
162 unsigned long timekeeper_lock_irqsave(void)
163 {
164 	unsigned long flags;
165 
166 	raw_spin_lock_irqsave(&tk_core.lock, flags);
167 	return flags;
168 }
169 
170 void timekeeper_unlock_irqrestore(unsigned long flags)
171 {
172 	raw_spin_unlock_irqrestore(&tk_core.lock, flags);
173 }
174 
175 /*
176  * Multigrain timestamps require tracking the latest fine-grained timestamp
177  * that has been issued, and never returning a coarse-grained timestamp that is
178  * earlier than that value.
179  *
180  * mg_floor represents the latest fine-grained time that has been handed out as
181  * a file timestamp on the system. This is tracked as a monotonic ktime_t, and
182  * converted to a realtime clock value on an as-needed basis.
183  *
184  * Maintaining mg_floor ensures the multigrain interfaces never issue a
185  * timestamp earlier than one that has been previously issued.
186  *
187  * The exception to this rule is when there is a backward realtime clock jump. If
188  * such an event occurs, a timestamp can appear to be earlier than a previous one.
189  */
190 static __cacheline_aligned_in_smp atomic64_t mg_floor;
191 
192 static inline void tk_normalize_xtime(struct timekeeper *tk)
193 {
194 	while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
195 		tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
196 		tk->xtime_sec++;
197 	}
198 	while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
199 		tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
200 		tk->raw_sec++;
201 	}
202 }
203 
204 static inline struct timespec64 tk_xtime(const struct timekeeper *tk)
205 {
206 	struct timespec64 ts;
207 
208 	ts.tv_sec = tk->xtime_sec;
209 	ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
210 	return ts;
211 }
212 
213 static inline struct timespec64 tk_xtime_coarse(const struct timekeeper *tk)
214 {
215 	struct timespec64 ts;
216 
217 	ts.tv_sec = tk->xtime_sec;
218 	ts.tv_nsec = tk->coarse_nsec;
219 	return ts;
220 }
221 
222 /*
223  * Update the nanoseconds part for the coarse time keepers. They can't rely
224  * on xtime_nsec because xtime_nsec could be adjusted by a small negative
225  * amount when the multiplication factor of the clock is adjusted, which
226  * could cause the coarse clocks to go slightly backwards. See
227  * timekeeping_apply_adjustment(). Thus we keep a separate copy for the coarse
228  * clockids which only is updated when the clock has been set or  we have
229  * accumulated time.
230  */
231 static inline void tk_update_coarse_nsecs(struct timekeeper *tk)
232 {
233 	tk->coarse_nsec = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
234 }
235 
236 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
237 {
238 	tk->xtime_sec = ts->tv_sec;
239 	tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
240 	tk_update_coarse_nsecs(tk);
241 }
242 
243 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
244 {
245 	tk->xtime_sec += ts->tv_sec;
246 	tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
247 	tk_normalize_xtime(tk);
248 	tk_update_coarse_nsecs(tk);
249 }
250 
251 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
252 {
253 	struct timespec64 tmp;
254 
255 	/*
256 	 * Verify consistency of: offset_real = -wall_to_monotonic
257 	 * before modifying anything
258 	 */
259 	set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
260 					-tk->wall_to_monotonic.tv_nsec);
261 	WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
262 	tk->wall_to_monotonic = wtm;
263 	set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
264 	/* Paired with READ_ONCE() in ktime_mono_to_any() */
265 	WRITE_ONCE(tk->offs_real, timespec64_to_ktime(tmp));
266 	WRITE_ONCE(tk->offs_tai, ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0)));
267 }
268 
269 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
270 {
271 	/* Paired with READ_ONCE() in ktime_mono_to_any() */
272 	WRITE_ONCE(tk->offs_boot, ktime_add(tk->offs_boot, delta));
273 	/*
274 	 * Timespec representation for VDSO update to avoid 64bit division
275 	 * on every update.
276 	 */
277 	tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot);
278 }
279 
280 #ifdef CONFIG_ARCH_WANTS_CLOCKSOURCE_READ_INLINE
281 #include <asm/clock_inlined.h>
282 
283 static DEFINE_STATIC_KEY_FALSE(clocksource_read_inlined);
284 
285 /*
286  * tk_clock_read - atomic clocksource read() helper
287  *
288  * This helper is necessary to use in the read paths because, while the
289  * seqcount ensures we don't return a bad value while structures are updated,
290  * it doesn't protect from potential crashes. There is the possibility that
291  * the tkr's clocksource may change between the read reference, and the
292  * clock reference passed to the read function.  This can cause crashes if
293  * the wrong clocksource is passed to the wrong read function.
294  * This isn't necessary to use when holding the tk_core.lock or doing
295  * a read of the fast-timekeeper tkrs (which is protected by its own locking
296  * and update logic).
297  */
298 static __always_inline u64 tk_clock_read(const struct tk_read_base *tkr)
299 {
300 	struct clocksource *clock = READ_ONCE(tkr->clock);
301 
302 	if (static_branch_likely(&clocksource_read_inlined))
303 		return arch_inlined_clocksource_read(clock);
304 
305 	return clock->read(clock);
306 }
307 
308 static inline void clocksource_disable_inline_read(void)
309 {
310 	static_branch_disable(&clocksource_read_inlined);
311 }
312 
313 static inline void clocksource_enable_inline_read(void)
314 {
315 	static_branch_enable(&clocksource_read_inlined);
316 }
317 #else
318 static __always_inline u64 tk_clock_read(const struct tk_read_base *tkr)
319 {
320 	struct clocksource *clock = READ_ONCE(tkr->clock);
321 
322 	return clock->read(clock);
323 }
324 
325 static inline void clocksource_disable_inline_read(void) { }
326 static inline void clocksource_enable_inline_read(void) { }
327 #endif
328 
329 /**
330  * tk_setup_internals - Set up internals to use clocksource clock.
331  *
332  * @tk:		The target timekeeper to setup.
333  * @clock:		Pointer to clocksource.
334  *
335  * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
336  * pair and interval request.
337  *
338  * Unless you're the timekeeping code, you should not be using this!
339  */
340 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
341 {
342 	u64 interval;
343 	struct clocksource *old_clock;
344 
345 	++tk->cs_was_changed_seq;
346 	old_clock = tk->tkr_mono.clock;
347 	tk->tkr_mono.clock = clock;
348 	tk->tkr_mono.mask = clock->mask;
349 	tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
350 
351 	tk->tkr_raw.clock = clock;
352 	tk->tkr_raw.mask = clock->mask;
353 	tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
354 
355 	/* Do the ns -> cycle conversion first, using original mult */
356 	interval = (u64)NTP_INTERVAL_LENGTH << clock->shift;
357 	interval += clock->mult / 2;
358 	do_div(interval, clock->mult);
359 	if (interval == 0)
360 		interval = 1;
361 
362 	tk->cycle_interval = interval;
363 
364 	/* Go back from cycles -> shifted ns */
365 	tk->xtime_interval = interval * clock->mult;
366 	tk->raw_interval = interval * clock->mult;
367 
368 	 /* if changing clocks, convert xtime_nsec shift units */
369 	if (old_clock) {
370 		int shift_change = clock->shift - old_clock->shift;
371 		if (shift_change < 0) {
372 			tk->tkr_mono.xtime_nsec >>= -shift_change;
373 			tk->tkr_raw.xtime_nsec >>= -shift_change;
374 		} else {
375 			tk->tkr_mono.xtime_nsec <<= shift_change;
376 			tk->tkr_raw.xtime_nsec <<= shift_change;
377 		}
378 	}
379 
380 	tk->tkr_mono.shift = clock->shift;
381 	tk->tkr_raw.shift = clock->shift;
382 
383 	tk->ntp_error = 0;
384 	tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
385 
386 	/*
387 	 * ntp_tick is the tick length that NTP disciplines (its ±500 PPM
388 	 * scales only this part), in NTP-shifted ns: the real interval of
389 	 * a whole number of counter cycles. Because cycle_interval is
390 	 * rounded to an integer number of cycles, this ntp_tick differs
391 	 * from the true intended 1/HZ tick length by up to half a cycle
392 	 * period.
393 	 */
394 	tk->ntp_tick = (u64)tk->xtime_interval << tk->ntp_error_shift;
395 
396 	/*
397 	 * cs_tick_adj is the constant difference between the disciplined
398 	 * ntp_tick above and the true 1/HZ tick, expressed per-second to
399 	 * match the ntp_update_frequency() addends and handed to NTP via
400 	 * ntp_clear() to be explicitly included in its tick_length.
401 	 *
402 	 * Worked example: HZ=1000, ACPI PM timer at 3.579545 MHz, which
403 	 * has 3579.545 cycles in 1ms, rounded to cycle_interval = 3580.
404 	 *
405 	 * So ntp_tick is actually 1.000127ms, as that is the amount of
406 	 * time that 3580 cycles will take at the nominal frequency. This
407 	 * is the part that NTP disciplines, causing each 3580 counts to
408 	 * advance the clock by up to NTP's ±500PPM of that amount.
409 	 *
410 	 * The "extra" 127ns/tick is what's stored in cs_tick_adj and
411 	 * applied as a constant correction by ntp_update_frequency() so
412 	 * that NTP *believes* it's disciplining a 1ms tick.
413 	 */
414 	tk->cs_tick_adj = (s64)tk->ntp_tick -
415 			  ((s64)NTP_INTERVAL_LENGTH << NTP_SCALE_SHIFT);
416 	tk->cs_tick_adj *= NTP_INTERVAL_FREQ;
417 
418 	/*
419 	 * The timekeeper keeps its own mult values for the currently
420 	 * active clocksource. These value will be adjusted via NTP
421 	 * to counteract clock drifting.
422 	 */
423 	tk->tkr_mono.mult = clock->mult;
424 	tk->tkr_raw.mult = clock->mult;
425 	tk->ntp_err_mult = 0;
426 	tk->skip_second_overflow = 0;
427 	tk->skew_delta = 0;
428 
429 	tk->cs_id = clock->id;
430 
431 	/* Coupled clockevent data */
432 	if (IS_ENABLED(CONFIG_GENERIC_CLOCKEVENTS_COUPLED) &&
433 	    clock->flags & CLOCK_SOURCE_HAS_COUPLED_CLOCK_EVENT) {
434 		/*
435 		 * Aim for an one hour maximum delta and use KHz to handle
436 		 * clocksources with a frequency above 4GHz correctly as
437 		 * the frequency argument of clocks_calc_mult_shift() is u32.
438 		 */
439 		clocks_calc_mult_shift(&tk->cs_ns_to_cyc_mult, &tk->cs_ns_to_cyc_shift,
440 				       NSEC_PER_MSEC, clock->freq_khz, 3600 * 1000);
441 		/*
442 		 * Initialize the conversion limit as the previous clocksource
443 		 * might have the same shift/mult pair so the quick check in
444 		 * tk_update_ns_to_cyc() fails to update it after a clocksource
445 		 * change leaving it effectivly zero.
446 		 */
447 		tk->cs_ns_to_cyc_maxns = div_u64(clock->mask, tk->cs_ns_to_cyc_mult);
448 	}
449 }
450 
451 /* Timekeeper helper functions. */
452 static noinline u64 delta_to_ns_safe(const struct tk_read_base *tkr, u64 delta)
453 {
454 	return mul_u64_u32_add_u64_shr(delta, tkr->mult, tkr->xtime_nsec, tkr->shift);
455 }
456 
457 static __always_inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles)
458 {
459 	/* Calculate the delta since the last update_wall_time() */
460 	u64 mask = tkr->mask, delta = (cycles - tkr->cycle_last) & mask;
461 
462 	/*
463 	 * This detects both negative motion and the case where the delta
464 	 * overflows the multiplication with tkr->mult.
465 	 */
466 	if (unlikely(delta > tkr->clock->max_cycles)) {
467 		/*
468 		 * Handle clocksource inconsistency between CPUs to prevent
469 		 * time from going backwards by checking for the MSB of the
470 		 * mask being set in the delta.
471 		 */
472 		if (delta & ~(mask >> 1))
473 			return tkr->xtime_nsec >> tkr->shift;
474 
475 		return delta_to_ns_safe(tkr, delta);
476 	}
477 
478 	return ((delta * tkr->mult) + tkr->xtime_nsec) >> tkr->shift;
479 }
480 
481 static __always_inline u64 timekeeping_get_ns(const struct tk_read_base *tkr)
482 {
483 	return timekeeping_cycles_to_ns(tkr, tk_clock_read(tkr));
484 }
485 
486 /**
487  * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
488  * @tkr: Timekeeping readout base from which we take the update
489  * @tkf: Pointer to NMI safe timekeeper
490  *
491  * We want to use this from any context including NMI and tracing /
492  * instrumenting the timekeeping code itself.
493  *
494  * Employ the latch technique; see @write_seqcount_latch.
495  *
496  * So if a NMI hits the update of base[0] then it will use base[1]
497  * which is still consistent. In the worst case this can result is a
498  * slightly wrong timestamp (a few nanoseconds). See
499  * @ktime_get_mono_fast_ns.
500  */
501 static void update_fast_timekeeper(const struct tk_read_base *tkr,
502 				   struct tk_fast *tkf)
503 {
504 	struct tk_read_base *base = tkf->base;
505 
506 	/* Force readers off to base[1] */
507 	write_seqcount_latch_begin(&tkf->seq);
508 
509 	/* Update base[0] */
510 	memcpy(base, tkr, sizeof(*base));
511 
512 	/* Force readers back to base[0] */
513 	write_seqcount_latch(&tkf->seq);
514 
515 	/* Update base[1] */
516 	memcpy(base + 1, base, sizeof(*base));
517 
518 	write_seqcount_latch_end(&tkf->seq);
519 }
520 
521 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
522 {
523 	struct tk_read_base *tkr;
524 	unsigned int seq;
525 	u64 now;
526 
527 	do {
528 		seq = read_seqcount_latch(&tkf->seq);
529 		tkr = tkf->base + (seq & 0x01);
530 		now = ktime_to_ns(tkr->base);
531 		now += timekeeping_get_ns(tkr);
532 	} while (read_seqcount_latch_retry(&tkf->seq, seq));
533 
534 	return now;
535 }
536 
537 /**
538  * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
539  *
540  * This timestamp is not guaranteed to be monotonic across an update.
541  * The timestamp is calculated by:
542  *
543  *	now = base_mono + clock_delta * slope
544  *
545  * So if the update lowers the slope, readers who are forced to the
546  * not yet updated second array are still using the old steeper slope.
547  *
548  * tmono
549  * ^
550  * |    o  n
551  * |   o n
552  * |  u
553  * | o
554  * |o
555  * |12345678---> reader order
556  *
557  * o = old slope
558  * u = update
559  * n = new slope
560  *
561  * So reader 6 will observe time going backwards versus reader 5.
562  *
563  * While other CPUs are likely to be able to observe that, the only way
564  * for a CPU local observation is when an NMI hits in the middle of
565  * the update. Timestamps taken from that NMI context might be ahead
566  * of the following timestamps. Callers need to be aware of that and
567  * deal with it.
568  */
569 u64 notrace ktime_get_mono_fast_ns(void)
570 {
571 	return __ktime_get_fast_ns(&tk_fast_mono);
572 }
573 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
574 
575 /**
576  * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw
577  *
578  * Contrary to ktime_get_mono_fast_ns() this is always correct because the
579  * conversion factor is not affected by NTP/PTP correction.
580  */
581 u64 notrace ktime_get_raw_fast_ns(void)
582 {
583 	return __ktime_get_fast_ns(&tk_fast_raw);
584 }
585 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
586 
587 /**
588  * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
589  *
590  * To keep it NMI safe since we're accessing from tracing, we're not using a
591  * separate timekeeper with updates to monotonic clock and boot offset
592  * protected with seqcounts. This has the following minor side effects:
593  *
594  * (1) Its possible that a timestamp be taken after the boot offset is updated
595  * but before the timekeeper is updated. If this happens, the new boot offset
596  * is added to the old timekeeping making the clock appear to update slightly
597  * earlier:
598  *    CPU 0                                        CPU 1
599  *    timekeeping_inject_sleeptime64()
600  *    __timekeeping_inject_sleeptime(tk, delta);
601  *                                                 timestamp();
602  *    timekeeping_update_staged(tkd, TK_CLEAR_NTP...);
603  *
604  * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
605  * partially updated.  Since the tk->offs_boot update is a rare event, this
606  * should be a rare occurrence which postprocessing should be able to handle.
607  *
608  * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns()
609  * apply as well.
610  */
611 u64 notrace ktime_get_boot_fast_ns(void)
612 {
613 	struct timekeeper *tk = &tk_core.timekeeper;
614 
615 	return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot)));
616 }
617 EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
618 
619 /**
620  * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock.
621  *
622  * The same limitations as described for ktime_get_boot_fast_ns() apply. The
623  * mono time and the TAI offset are not read atomically which may yield wrong
624  * readouts. However, an update of the TAI offset is an rare event e.g., caused
625  * by settime or adjtimex with an offset. The user of this function has to deal
626  * with the possibility of wrong timestamps in post processing.
627  */
628 u64 notrace ktime_get_tai_fast_ns(void)
629 {
630 	struct timekeeper *tk = &tk_core.timekeeper;
631 
632 	return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai)));
633 }
634 EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns);
635 
636 /**
637  * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
638  *
639  * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering.
640  */
641 u64 ktime_get_real_fast_ns(void)
642 {
643 	struct tk_fast *tkf = &tk_fast_mono;
644 	struct tk_read_base *tkr;
645 	u64 baser, delta;
646 	unsigned int seq;
647 
648 	do {
649 		seq = raw_read_seqcount_latch(&tkf->seq);
650 		tkr = tkf->base + (seq & 0x01);
651 		baser = ktime_to_ns(tkr->base_real);
652 		delta = timekeeping_get_ns(tkr);
653 	} while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
654 
655 	return baser + delta;
656 }
657 EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
658 
659 /**
660  * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
661  * @tk: Timekeeper to snapshot.
662  *
663  * It generally is unsafe to access the clocksource after timekeeping has been
664  * suspended, so take a snapshot of the readout base of @tk and use it as the
665  * fast timekeeper's readout base while suspended.  It will return the same
666  * number of cycles every time until timekeeping is resumed at which time the
667  * proper readout base for the fast timekeeper will be restored automatically.
668  */
669 static void halt_fast_timekeeper(const struct timekeeper *tk)
670 {
671 	static struct tk_read_base tkr_dummy;
672 	const struct tk_read_base *tkr = &tk->tkr_mono;
673 
674 	memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
675 	cycles_at_suspend = tk_clock_read(tkr);
676 	tkr_dummy.clock = &dummy_clock;
677 	tkr_dummy.base_real = tkr->base + tk->offs_real;
678 	update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
679 
680 	tkr = &tk->tkr_raw;
681 	memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
682 	tkr_dummy.clock = &dummy_clock;
683 	update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
684 }
685 
686 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
687 
688 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
689 {
690 	raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
691 }
692 
693 /**
694  * pvclock_gtod_register_notifier - register a pvclock timedata update listener
695  * @nb: Pointer to the notifier block to register
696  */
697 int pvclock_gtod_register_notifier(struct notifier_block *nb)
698 {
699 	struct timekeeper *tk = &tk_core.timekeeper;
700 	int ret;
701 
702 	guard(raw_spinlock_irqsave)(&tk_core.lock);
703 	ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
704 	update_pvclock_gtod(tk, true);
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 	guard(raw_spinlock_irqsave)(&tk_core.lock);
718 	return raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
719 }
720 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
721 
722 /*
723  * tk_update_leap_state - helper to update the next_leap_ktime
724  */
725 static inline void tk_update_leap_state(struct timekeeper *tk)
726 {
727 	tk->next_leap_ktime = ntp_get_next_leap(tk->id);
728 	if (tk->next_leap_ktime != KTIME_MAX)
729 		/* Convert to monotonic time */
730 		tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
731 }
732 
733 /*
734  * Leap state update for both shadow and the real timekeeper
735  * Separate to spare a full memcpy() of the timekeeper.
736  */
737 static void tk_update_leap_state_all(struct tk_data *tkd)
738 {
739 	write_seqcount_begin(&tkd->seq);
740 	tk_update_leap_state(&tkd->shadow_timekeeper);
741 	tkd->timekeeper.next_leap_ktime = tkd->shadow_timekeeper.next_leap_ktime;
742 	write_seqcount_end(&tkd->seq);
743 }
744 
745 /*
746  * Update the ktime_t based scalar nsec members of the timekeeper
747  */
748 static inline void tk_update_ktime_data(struct timekeeper *tk)
749 {
750 	u64 seconds;
751 	u32 nsec;
752 
753 	/*
754 	 * The xtime based monotonic readout is:
755 	 *	nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
756 	 * The ktime based monotonic readout is:
757 	 *	nsec = base_mono + now();
758 	 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
759 	 */
760 	seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
761 	nsec = (u32) tk->wall_to_monotonic.tv_nsec;
762 	tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
763 
764 	/*
765 	 * The sum of the nanoseconds portions of xtime and
766 	 * wall_to_monotonic can be greater/equal one second. Take
767 	 * this into account before updating tk->ktime_sec.
768 	 */
769 	nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
770 	if (nsec >= NSEC_PER_SEC)
771 		seconds++;
772 	tk->ktime_sec = seconds;
773 
774 	/* Update the monotonic raw base */
775 	tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
776 }
777 
778 static inline void tk_update_ns_to_cyc(struct timekeeper *tks, struct timekeeper *tkc)
779 {
780 	struct tk_read_base *tkrs = &tks->tkr_mono;
781 	struct tk_read_base *tkrc = &tkc->tkr_mono;
782 	unsigned int shift;
783 
784 	if (!IS_ENABLED(CONFIG_GENERIC_CLOCKEVENTS_COUPLED) ||
785 	    !(tkrs->clock->flags & CLOCK_SOURCE_HAS_COUPLED_CLOCK_EVENT))
786 		return;
787 
788 	if (tkrs->mult == tkrc->mult && tkrs->shift == tkrc->shift)
789 		return;
790 	/*
791 	 * The conversion math is simple:
792 	 *
793 	 *      CS::MULT       (1 << NS_TO_CYC_SHIFT)
794 	 *   --------------- = ----------------------
795 	 *   (1 << CS:SHIFT)       NS_TO_CYC_MULT
796 	 *
797 	 * Ergo:
798 	 *
799 	 *   NS_TO_CYC_MULT = (1 << (CS::SHIFT + NS_TO_CYC_SHIFT)) / CS::MULT
800 	 *
801 	 * NS_TO_CYC_SHIFT has been set up in tk_setup_internals()
802 	 */
803 	shift = tkrs->shift + tks->cs_ns_to_cyc_shift;
804 	tks->cs_ns_to_cyc_mult = (u32)div_u64(1ULL << shift, tkrs->mult);
805 	tks->cs_ns_to_cyc_maxns = div_u64(tkrs->clock->mask, tks->cs_ns_to_cyc_mult);
806 }
807 
808 /*
809  * Restore the shadow timekeeper from the real timekeeper.
810  */
811 static void timekeeping_restore_shadow(struct tk_data *tkd)
812 {
813 	lockdep_assert_held(&tkd->lock);
814 	memcpy(&tkd->shadow_timekeeper, &tkd->timekeeper, sizeof(tkd->timekeeper));
815 }
816 
817 static void timekeeping_update_from_shadow(struct tk_data *tkd, unsigned int action)
818 {
819 	struct timekeeper *tk = &tkd->shadow_timekeeper;
820 
821 	lockdep_assert_held(&tkd->lock);
822 
823 	/*
824 	 * Block out readers before running the updates below because that
825 	 * updates VDSO and other time related infrastructure. Not blocking
826 	 * the readers might let a reader see time going backwards when
827 	 * reading from the VDSO after the VDSO update and then reading in
828 	 * the kernel from the timekeeper before that got updated.
829 	 */
830 	write_seqcount_begin(&tkd->seq);
831 
832 	if (action & TK_CLEAR_NTP) {
833 		tk->ntp_error = 0;
834 		ntp_clear(tk->id, tk->cs_tick_adj);
835 	}
836 
837 	tk_update_leap_state(tk);
838 	tk_update_ktime_data(tk);
839 	tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
840 
841 	if (tk->id == TIMEKEEPER_CORE) {
842 		tk_update_ns_to_cyc(tk, &tkd->timekeeper);
843 		update_vsyscall(tk);
844 		update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
845 
846 		update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
847 		update_fast_timekeeper(&tk->tkr_raw,  &tk_fast_raw);
848 	} else if (tk_is_aux(tk)) {
849 		vdso_time_update_aux(tk);
850 	}
851 
852 	if (action & TK_CLOCK_WAS_SET)
853 		tk->clock_was_set_seq++;
854 
855 	/*
856 	 * Update the real timekeeper.
857 	 *
858 	 * We could avoid this memcpy() by switching pointers, but that has
859 	 * the downside that the reader side does not longer benefit from
860 	 * the cacheline optimized data layout of the timekeeper and requires
861 	 * another indirection.
862 	 *
863 	 * Write xtime_sec first so that even if the memcpy() tears the store
864 	 * data integrity is provided for ktime_get_real_seconds().
865 	 * The same goes for ktime_sec and ktime_get_seconds().
866 	 */
867 	WRITE_ONCE(tkd->timekeeper.xtime_sec, tk->xtime_sec);
868 	WRITE_ONCE(tkd->timekeeper.ktime_sec, tk->ktime_sec);
869 	memcpy(&tkd->timekeeper, tk, sizeof(*tk));
870 	write_seqcount_end(&tkd->seq);
871 }
872 
873 /**
874  * timekeeping_forward_now - update clock to the current time
875  * @tk:		Pointer to the timekeeper to update
876  *
877  * Forward the current clock to update its state since the last call to
878  * update_wall_time(). This is useful before significant clock changes,
879  * as it avoids having to deal with this time offset explicitly.
880  */
881 static void timekeeping_forward_now(struct timekeeper *tk)
882 {
883 	u64 cycle_now, delta;
884 
885 	cycle_now = tk_clock_read(&tk->tkr_mono);
886 	delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
887 				  tk->tkr_mono.clock->max_raw_delta);
888 	tk->tkr_mono.cycle_last = cycle_now;
889 	tk->tkr_raw.cycle_last  = cycle_now;
890 
891 	while (delta > 0) {
892 		u64 max = tk->tkr_mono.clock->max_cycles;
893 		u64 incr = delta < max ? delta : max;
894 
895 		tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult;
896 		tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult;
897 		tk_normalize_xtime(tk);
898 		delta -= incr;
899 	}
900 	tk_update_coarse_nsecs(tk);
901 }
902 
903 /*
904  * ktime_expiry_to_cycles - Convert a expiry time to clocksource cycles
905  * @id:		Clocksource ID which is required for validity
906  * @expires_ns:	Absolute CLOCK_MONOTONIC expiry time (nsecs) to be converted
907  * @cycles:	Pointer to storage for corresponding absolute cycles value
908  *
909  * Convert a CLOCK_MONOTONIC based absolute expiry time to a cycles value
910  * based on the correlated clocksource of the clockevent device by using
911  * the base nanoseconds and cycles values of the last timekeeper update and
912  * converting the delta between @expires_ns and base nanoseconds to cycles.
913  *
914  * This only works for clockevent devices which are using a less than or
915  * equal comparator against the clocksource.
916  *
917  * Utilizing this avoids two clocksource reads for such devices, the
918  * ktime_get() in clockevents_program_event() to calculate the delta expiry
919  * value and the readout in the device::set_next_event() callback to
920  * convert the delta back to a absolute comparator value.
921  *
922  * Returns: True if @id matches the current clocksource ID, false otherwise
923  */
924 bool ktime_expiry_to_cycles(enum clocksource_ids id, ktime_t expires_ns, u64 *cycles)
925 {
926 	struct timekeeper *tk = &tk_core.timekeeper;
927 	struct tk_read_base *tkrm = &tk->tkr_mono;
928 	ktime_t base_ns, delta_ns, max_ns;
929 	u64 base_cycles, delta_cycles;
930 	unsigned int seq;
931 	u32 mult, shift;
932 
933 	/*
934 	 * Racy check to avoid the seqcount overhead when ID does not match. If
935 	 * the relevant clocksource is installed concurrently, then this will
936 	 * just delay the switch over to this mechanism until the next event is
937 	 * programmed. If the ID is not matching the clock events code will use
938 	 * the regular relative set_next_event() callback as before.
939 	 */
940 	if (data_race(tk->cs_id) != id)
941 		return false;
942 
943 	do {
944 		seq = read_seqcount_begin(&tk_core.seq);
945 
946 		if (tk->cs_id != id)
947 			return false;
948 
949 		base_cycles = tkrm->cycle_last;
950 		base_ns = tkrm->base + (tkrm->xtime_nsec >> tkrm->shift);
951 
952 		mult = tk->cs_ns_to_cyc_mult;
953 		shift = tk->cs_ns_to_cyc_shift;
954 		max_ns = tk->cs_ns_to_cyc_maxns;
955 
956 	} while (read_seqcount_retry(&tk_core.seq, seq));
957 
958 	/* Prevent negative deltas and multiplication overflows */
959 	delta_ns = min(expires_ns - base_ns, max_ns);
960 	delta_ns = max(delta_ns, 0);
961 
962 	/* Convert to cycles */
963 	delta_cycles = ((u64)delta_ns * mult) >> shift;
964 	*cycles = base_cycles + delta_cycles;
965 	return true;
966 }
967 
968 /**
969  * ktime_get_real_ts64 - Returns the time of day in a timespec64.
970  * @ts:		pointer to the timespec to be set
971  *
972  * Returns the time of day in a timespec64 (WARN if suspended).
973  */
974 void ktime_get_real_ts64(struct timespec64 *ts)
975 {
976 	struct timekeeper *tk = &tk_core.timekeeper;
977 	unsigned int seq;
978 	u64 nsecs;
979 
980 	WARN_ON(timekeeping_suspended);
981 
982 	do {
983 		seq = read_seqcount_begin(&tk_core.seq);
984 
985 		ts->tv_sec = tk->xtime_sec;
986 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
987 
988 	} while (read_seqcount_retry(&tk_core.seq, seq));
989 
990 	ts->tv_nsec = 0;
991 	timespec64_add_ns(ts, nsecs);
992 }
993 EXPORT_SYMBOL(ktime_get_real_ts64);
994 
995 ktime_t ktime_get(void)
996 {
997 	struct timekeeper *tk = &tk_core.timekeeper;
998 	unsigned int seq;
999 	ktime_t base;
1000 	u64 nsecs;
1001 
1002 	WARN_ON(timekeeping_suspended);
1003 
1004 	do {
1005 		seq = read_seqcount_begin(&tk_core.seq);
1006 		base = tk->tkr_mono.base;
1007 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
1008 
1009 	} while (read_seqcount_retry(&tk_core.seq, seq));
1010 
1011 	return ktime_add_ns(base, nsecs);
1012 }
1013 EXPORT_SYMBOL_GPL(ktime_get);
1014 
1015 u32 ktime_get_resolution_ns(void)
1016 {
1017 	struct timekeeper *tk = &tk_core.timekeeper;
1018 	unsigned int seq;
1019 	u32 nsecs;
1020 
1021 	WARN_ON(timekeeping_suspended);
1022 
1023 	do {
1024 		seq = read_seqcount_begin(&tk_core.seq);
1025 		nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
1026 	} while (read_seqcount_retry(&tk_core.seq, seq));
1027 
1028 	return nsecs;
1029 }
1030 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
1031 
1032 static const ktime_t *const offsets[TK_OFFS_MAX] = {
1033 	[TK_OFFS_REAL]	= &tk_core.timekeeper.offs_real,
1034 	[TK_OFFS_BOOT]	= &tk_core.timekeeper.offs_boot,
1035 	[TK_OFFS_TAI]	= &tk_core.timekeeper.offs_tai,
1036 };
1037 
1038 ktime_t ktime_get_with_offset(enum tk_offsets offs)
1039 {
1040 	struct timekeeper *tk = &tk_core.timekeeper;
1041 	const ktime_t *offset = offsets[offs];
1042 	unsigned int seq;
1043 	ktime_t base;
1044 	u64 nsecs;
1045 
1046 	WARN_ON(timekeeping_suspended);
1047 
1048 	do {
1049 		seq = read_seqcount_begin(&tk_core.seq);
1050 		base = ktime_add(tk->tkr_mono.base, *offset);
1051 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
1052 
1053 	} while (read_seqcount_retry(&tk_core.seq, seq));
1054 
1055 	return ktime_add_ns(base, nsecs);
1056 
1057 }
1058 EXPORT_SYMBOL_GPL(ktime_get_with_offset);
1059 
1060 ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
1061 {
1062 	struct timekeeper *tk = &tk_core.timekeeper;
1063 	const ktime_t *offset = offsets[offs];
1064 	unsigned int seq;
1065 	ktime_t base;
1066 	u64 nsecs;
1067 
1068 	WARN_ON(timekeeping_suspended);
1069 
1070 	do {
1071 		seq = read_seqcount_begin(&tk_core.seq);
1072 		base = ktime_add(tk->tkr_mono.base, *offset);
1073 		nsecs = tk->coarse_nsec;
1074 
1075 	} while (read_seqcount_retry(&tk_core.seq, seq));
1076 
1077 	return ktime_add_ns(base, nsecs);
1078 }
1079 EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
1080 
1081 /**
1082  * ktime_mono_to_any() - convert monotonic time to any other time
1083  * @tmono:	time to convert.
1084  * @offs:	which offset to use
1085  */
1086 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
1087 {
1088 	const ktime_t *offset = offsets[offs];
1089 	unsigned int seq;
1090 	ktime_t tconv;
1091 
1092 	if (IS_ENABLED(CONFIG_64BIT)) {
1093 		/*
1094 		 * Paired with WRITE_ONCE()s in tk_set_wall_to_mono() and
1095 		 * tk_update_sleep_time().
1096 		 */
1097 		return ktime_add(tmono, READ_ONCE(*offset));
1098 	}
1099 
1100 	do {
1101 		seq = read_seqcount_begin(&tk_core.seq);
1102 		tconv = ktime_add(tmono, *offset);
1103 	} while (read_seqcount_retry(&tk_core.seq, seq));
1104 
1105 	return tconv;
1106 }
1107 EXPORT_SYMBOL_GPL(ktime_mono_to_any);
1108 
1109 /**
1110  * ktime_get_raw - Returns the raw monotonic time in ktime_t format
1111  */
1112 ktime_t ktime_get_raw(void)
1113 {
1114 	struct timekeeper *tk = &tk_core.timekeeper;
1115 	unsigned int seq;
1116 	ktime_t base;
1117 	u64 nsecs;
1118 
1119 	do {
1120 		seq = read_seqcount_begin(&tk_core.seq);
1121 		base = tk->tkr_raw.base;
1122 		nsecs = timekeeping_get_ns(&tk->tkr_raw);
1123 
1124 	} while (read_seqcount_retry(&tk_core.seq, seq));
1125 
1126 	return ktime_add_ns(base, nsecs);
1127 }
1128 EXPORT_SYMBOL_GPL(ktime_get_raw);
1129 
1130 /**
1131  * ktime_get_ts64 - get the monotonic clock in timespec64 format
1132  * @ts:		pointer to timespec variable
1133  *
1134  * The function calculates the monotonic clock from the realtime
1135  * clock and the wall_to_monotonic offset and stores the result
1136  * in normalized timespec64 format in the variable pointed to by @ts.
1137  */
1138 void ktime_get_ts64(struct timespec64 *ts)
1139 {
1140 	struct timekeeper *tk = &tk_core.timekeeper;
1141 	struct timespec64 tomono;
1142 	unsigned int seq;
1143 	u64 nsec;
1144 
1145 	WARN_ON(timekeeping_suspended);
1146 
1147 	do {
1148 		seq = read_seqcount_begin(&tk_core.seq);
1149 		ts->tv_sec = tk->xtime_sec;
1150 		nsec = timekeeping_get_ns(&tk->tkr_mono);
1151 		tomono = tk->wall_to_monotonic;
1152 
1153 	} while (read_seqcount_retry(&tk_core.seq, seq));
1154 
1155 	ts->tv_sec += tomono.tv_sec;
1156 	ts->tv_nsec = 0;
1157 	timespec64_add_ns(ts, nsec + tomono.tv_nsec);
1158 }
1159 EXPORT_SYMBOL_GPL(ktime_get_ts64);
1160 
1161 /**
1162  * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
1163  *
1164  * Returns the seconds portion of CLOCK_MONOTONIC with a single non
1165  * serialized read. tk->ktime_sec is of type 'unsigned long' so this
1166  * works on both 32 and 64 bit systems. On 32 bit systems the readout
1167  * covers ~136 years of uptime which should be enough to prevent
1168  * premature wrap arounds.
1169  */
1170 time64_t ktime_get_seconds(void)
1171 {
1172 	struct timekeeper *tk = &tk_core.timekeeper;
1173 
1174 	WARN_ON(timekeeping_suspended);
1175 	return READ_ONCE(tk->ktime_sec);
1176 }
1177 EXPORT_SYMBOL_GPL(ktime_get_seconds);
1178 
1179 /**
1180  * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
1181  *
1182  * Returns the wall clock seconds since 1970.
1183  *
1184  * For 64bit systems the fast access to tk->xtime_sec is preserved. On
1185  * 32bit systems the access must be protected with the sequence
1186  * counter to provide "atomic" access to the 64bit tk->xtime_sec
1187  * value.
1188  */
1189 time64_t ktime_get_real_seconds(void)
1190 {
1191 	struct timekeeper *tk = &tk_core.timekeeper;
1192 	time64_t seconds;
1193 	unsigned int seq;
1194 
1195 	if (IS_ENABLED(CONFIG_64BIT))
1196 		return READ_ONCE(tk->xtime_sec);
1197 
1198 	do {
1199 		seq = read_seqcount_begin(&tk_core.seq);
1200 		seconds = READ_ONCE(tk->xtime_sec);
1201 
1202 	} while (read_seqcount_retry(&tk_core.seq, seq));
1203 
1204 	return seconds;
1205 }
1206 EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
1207 
1208 /**
1209  * __ktime_get_real_seconds - Unprotected access to CLOCK_REALTIME seconds
1210  *
1211  * The same as ktime_get_real_seconds() but without the sequence counter
1212  * protection. This function is used in restricted contexts like the x86 MCE
1213  * handler and in KGDB. It's unprotected on 32-bit vs. concurrent half
1214  * completed modification and only to be used for such critical contexts.
1215  *
1216  * Returns: Racy snapshot of the CLOCK_REALTIME seconds value
1217  */
1218 noinstr time64_t __ktime_get_real_seconds(void)
1219 {
1220 	struct timekeeper *tk = &tk_core.timekeeper;
1221 
1222 	return READ_ONCE(tk->xtime_sec);
1223 }
1224 
1225 static inline u64 tk_clock_read_snapshot(const struct tk_read_base *tkr,
1226 					 struct clocksource_hw_snapshot *chs)
1227 {
1228 	struct clocksource *clock = READ_ONCE(tkr->clock);
1229 
1230 	if (unlikely(clock->read_snapshot))
1231 		return clock->read_snapshot(clock, chs);
1232 
1233 	return clock->read(clock);
1234 }
1235 
1236 
1237 /**
1238  * ktime_get_snapshot_id -  Simultaneously snapshot a given clock ID with
1239  *			    the corresponding monotonic raw and the underlying
1240  *			    clocksource counter value.
1241  * @clock_id:		The clock ID to snapshot
1242  * @systime_snapshot:	Pointer to struct receiving the system time snapshot
1243  *
1244  * For the system time keeping clocks (REALTIME, MONOTONIC and BOOTTIME) the
1245  * monotonic raw clock is CLOCK_MONOTONIC_RAW. For AUX clocks this is the
1246  * monotonic raw clock related to the AUX clock. These AUX clock related
1247  * monotonic raw clocks have a strict linear offset to the system time
1248  * CLOCK_MONOTONIC_RAW:
1249  *
1250  *	MONOTONIC_RAW(AUX$N) = CLOCK_MONOTONIC_RAW(system) + offset(AUX$N)
1251  *
1252  * The offset is established when a AUX clock is initialized, but it is
1253  * currently not accessible.
1254  */
1255 void ktime_get_snapshot_id(clockid_t clock_id, struct system_time_snapshot *systime_snapshot)
1256 {
1257 	ktime_t base_raw, base_sys, offs_sys, *offs, offs_zero = 0;
1258 	u64 nsec_raw, nsec_sys, now;
1259 	struct timekeeper *tk;
1260 	struct tk_data *tkd;
1261 	unsigned int seq;
1262 
1263 	/* Invalidate the snapshot for all failure cases */
1264 	systime_snapshot->valid = false;
1265 
1266 	if (WARN_ON_ONCE(timekeeping_suspended))
1267 		return;
1268 
1269 	switch (clock_id) {
1270 	case CLOCK_REALTIME:
1271 		tkd = &tk_core;
1272 		offs = &tk_core.timekeeper.offs_real;
1273 		break;
1274 	/* Map RAW to MONOTONIC so the loop below is trivial */
1275 	case CLOCK_MONOTONIC_RAW:
1276 	case CLOCK_MONOTONIC:
1277 		tkd = &tk_core;
1278 		offs = &offs_zero;
1279 		break;
1280 	case CLOCK_BOOTTIME:
1281 		tkd = &tk_core;
1282 		offs = &tk_core.timekeeper.offs_boot;
1283 		break;
1284 	case CLOCK_AUX ... CLOCK_AUX_LAST:
1285 		tkd = aux_get_tk_data(clock_id);
1286 		if (!tkd)
1287 			return;
1288 		offs = &tkd->timekeeper.offs_aux;
1289 		break;
1290 	default:
1291 		WARN_ON_ONCE(1);
1292 		return;
1293 	}
1294 
1295 	tk = &tkd->timekeeper;
1296 
1297 	do {
1298 		struct clocksource_hw_snapshot chs = { };
1299 
1300 		seq = read_seqcount_begin(&tkd->seq);
1301 
1302 		/* Aux clocks can be invalid */
1303 		if (!tk->clock_valid)
1304 			return;
1305 
1306 		now = tk_clock_read_snapshot(&tk->tkr_mono, &chs);
1307 		systime_snapshot->cs_id = tk->tkr_mono.clock->id;
1308 
1309 		systime_snapshot->hw_cycles = chs.hw_cycles;
1310 		systime_snapshot->hw_csid = chs.hw_csid;
1311 
1312 		systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
1313 		systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
1314 
1315 		base_sys = tk->tkr_mono.base;
1316 		offs_sys = *offs;
1317 		base_raw = tk->tkr_raw.base;
1318 
1319 		nsec_sys = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
1320 		nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
1321 	} while (read_seqcount_retry(&tkd->seq, seq));
1322 
1323 	systime_snapshot->cycles = now;
1324 	systime_snapshot->systime = ktime_add_ns(base_sys, offs_sys + nsec_sys);
1325 	systime_snapshot->monoraw = ktime_add_ns(base_raw, nsec_raw);
1326 
1327 	/*
1328 	 * Special case for PTP. Just transfer the raw time into sys,
1329 	 * so the call sites can consistently use snap::systime.
1330 	 */
1331 	if (clock_id == CLOCK_MONOTONIC_RAW)
1332 		systime_snapshot->systime = systime_snapshot->monoraw;
1333 	/* Tell the consumer that this snapshot is valid */
1334 	systime_snapshot->valid = true;
1335 }
1336 EXPORT_SYMBOL_GPL(ktime_get_snapshot_id);
1337 
1338 /* Scale base by mult/div checking for overflow */
1339 static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
1340 {
1341 	u64 tmp, rem;
1342 
1343 	tmp = div64_u64_rem(*base, div, &rem);
1344 
1345 	if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
1346 	    ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
1347 		return -EOVERFLOW;
1348 	tmp *= mult;
1349 
1350 	rem = div64_u64(rem * mult, div);
1351 	*base = tmp + rem;
1352 	return 0;
1353 }
1354 
1355 /**
1356  * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
1357  * @history:			Snapshot representing start of history
1358  * @partial_history_cycles:	Cycle offset into history (fractional part)
1359  * @total_history_cycles:	Total history length in cycles
1360  * @discontinuity:		True indicates clock was set on history period
1361  * @ts:				Cross timestamp that should be adjusted using
1362  *	partial/total ratio
1363  *
1364  * Helper function used by get_device_system_crosststamp() to correct the
1365  * crosstimestamp corresponding to the start of the current interval to the
1366  * system counter value (timestamp point) provided by the driver. The
1367  * total_history_* quantities are the total history starting at the provided
1368  * reference point and ending at the start of the current interval. The cycle
1369  * count between the driver timestamp point and the start of the current
1370  * interval is partial_history_cycles.
1371  */
1372 static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1373 					 u64 partial_history_cycles,
1374 					 u64 total_history_cycles,
1375 					 bool discontinuity,
1376 					 struct system_device_crosststamp *ts)
1377 {
1378 	struct timekeeper *tk = &tk_core.timekeeper;
1379 	u64 corr_raw, corr_sys;
1380 	bool interp_forward;
1381 	int ret;
1382 
1383 	if (total_history_cycles == 0 || partial_history_cycles == 0)
1384 		return 0;
1385 
1386 	/* Interpolate shortest distance from beginning or end of history */
1387 	interp_forward = partial_history_cycles > total_history_cycles / 2;
1388 	partial_history_cycles = interp_forward ?
1389 		total_history_cycles - partial_history_cycles :
1390 		partial_history_cycles;
1391 
1392 	/*
1393 	 * Scale the monotonic raw time delta by:
1394 	 *	partial_history_cycles / total_history_cycles
1395 	 */
1396 	corr_raw = (u64)ktime_to_ns(ktime_sub(ts->sys_monoraw, history->monoraw));
1397 	ret = scale64_check_overflow(partial_history_cycles,
1398 				     total_history_cycles, &corr_raw);
1399 	if (ret)
1400 		return ret;
1401 
1402 	/*
1403 	 * If there is a discontinuity in the history, scale monotonic raw
1404 	 * correction by:
1405 	 *	mult(sys)/mult(raw) yielding the system time correction
1406 	 *
1407 	 * Otherwise, calculate the system time correction similar to monotonic
1408 	 * raw calculation
1409 	 */
1410 	if (discontinuity) {
1411 		corr_sys = mul_u64_u32_div(corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
1412 	} else {
1413 		corr_sys = (u64)ktime_to_ns(ktime_sub(ts->sys_systime, history->systime));
1414 		ret = scale64_check_overflow(partial_history_cycles, total_history_cycles,
1415 					     &corr_sys);
1416 		if (ret)
1417 			return ret;
1418 	}
1419 
1420 	/* Fixup monotonic raw and system time time values */
1421 	if (interp_forward) {
1422 		ts->sys_monoraw = ktime_add_ns(history->monoraw, corr_raw);
1423 		ts->sys_systime = ktime_add_ns(history->systime, corr_sys);
1424 	} else {
1425 		ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
1426 		ts->sys_systime = ktime_sub_ns(ts->sys_systime, corr_sys);
1427 	}
1428 
1429 	return 0;
1430 }
1431 
1432 /*
1433  * timestamp_in_interval - true if ts is chronologically in [start, end]
1434  *
1435  * True if ts occurs chronologically at or after start, and before or at end.
1436  */
1437 static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
1438 {
1439 	if (ts >= start && ts <= end)
1440 		return true;
1441 	if (start > end && (ts >= start || ts <= end))
1442 		return true;
1443 	return false;
1444 }
1445 
1446 static bool convert_clock(u64 *val, u32 numerator, u32 denominator)
1447 {
1448 	u64 rem, res;
1449 
1450 	if (!numerator || !denominator)
1451 		return false;
1452 
1453 	res = div64_u64_rem(*val, denominator, &rem) * numerator;
1454 	*val = res + div_u64(rem * numerator, denominator);
1455 	return true;
1456 }
1457 
1458 static bool convert_base_to_cs(struct system_counterval_t *scv)
1459 {
1460 	struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1461 	struct clocksource_base *base;
1462 	u32 num, den;
1463 
1464 	/* The timestamp was taken from the time keeper clock source */
1465 	if (cs->id == scv->cs_id)
1466 		return true;
1467 
1468 	/*
1469 	 * Check whether cs_id matches the base clock. Prevent the compiler from
1470 	 * re-evaluating @base as the clocksource might change concurrently.
1471 	 */
1472 	base = READ_ONCE(cs->base);
1473 	if (!base || base->id != scv->cs_id)
1474 		return false;
1475 
1476 	num = scv->use_nsecs ? cs->freq_khz : base->numerator;
1477 	den = scv->use_nsecs ? USEC_PER_SEC : base->denominator;
1478 
1479 	if (!convert_clock(&scv->cycles, num, den))
1480 		return false;
1481 
1482 	scv->cycles += base->offset;
1483 	/* Set the clocksource ID as scv::cycles is now clocksource based */
1484 	scv->cs_id = cs->id;
1485 	return true;
1486 }
1487 
1488 static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id)
1489 {
1490 	struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock;
1491 	struct clocksource_base *base;
1492 
1493 	/*
1494 	 * Check whether base_id matches the base clock. Prevent the compiler from
1495 	 * re-evaluating @base as the clocksource might change concurrently.
1496 	 */
1497 	base = READ_ONCE(cs->base);
1498 	if (!base || base->id != base_id)
1499 		return false;
1500 
1501 	*cycles -= base->offset;
1502 	if (!convert_clock(cycles, base->denominator, base->numerator))
1503 		return false;
1504 	return true;
1505 }
1506 
1507 static bool convert_ns_to_cs(u64 *delta)
1508 {
1509 	struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
1510 
1511 	if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta))
1512 		return false;
1513 
1514 	*delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult);
1515 	return true;
1516 }
1517 
1518 /**
1519  * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp
1520  * @treal:	CLOCK_REALTIME timestamp to convert
1521  * @base_id:	base clocksource id
1522  * @cycles:	pointer to store the converted base clock timestamp
1523  *
1524  * Converts a supplied, future realtime clock value to the corresponding base clock value.
1525  *
1526  * Return:  true if the conversion is successful, false otherwise.
1527  */
1528 bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles)
1529 {
1530 	struct timekeeper *tk = &tk_core.timekeeper;
1531 	unsigned int seq;
1532 	u64 delta;
1533 
1534 	do {
1535 		seq = read_seqcount_begin(&tk_core.seq);
1536 		if ((u64)treal < tk->tkr_mono.base_real)
1537 			return false;
1538 		delta = (u64)treal - tk->tkr_mono.base_real;
1539 		if (!convert_ns_to_cs(&delta))
1540 			return false;
1541 		*cycles = tk->tkr_mono.cycle_last + delta;
1542 		if (!convert_cs_to_base(cycles, base_id))
1543 			return false;
1544 	} while (read_seqcount_retry(&tk_core.seq, seq));
1545 
1546 	return true;
1547 }
1548 EXPORT_SYMBOL_GPL(ktime_real_to_base_clock);
1549 
1550 /**
1551  * get_device_system_crosststamp - Synchronously capture system/device timestamp
1552  * @get_time_fn:	Callback to get simultaneous device time and system counter
1553  *			from the device driver
1554  * @ctx:		Context passed to get_time_fn()
1555  * @history_begin:	Historical reference point used to interpolate system time when
1556  *			the counter value provided by the driver is before the current interval
1557  * @xtstamp:		Receives simultaneously captured system and device time
1558  *
1559  * Reads a timestamp from a device and correlates it to system time
1560  *
1561  * See documentation for ktime_get_snapshot_id() for information about the raw
1562  * monotonic time stamp which is used here.
1563  */
1564 int get_device_system_crosststamp(int (*get_time_fn)
1565 				  (ktime_t *device_time,
1566 				   struct system_counterval_t *sys_counterval,
1567 				   void *ctx),
1568 				  void *ctx,
1569 				  struct system_time_snapshot *history_begin,
1570 				  struct system_device_crosststamp *xtstamp)
1571 {
1572 	u64 syscnt_cycles, cycles, now, interval_start;
1573 	ktime_t base_sys, base_raw, *offs;
1574 	u32 clock_was_set_seq = 0;
1575 	u64 nsec_sys, nsec_raw;
1576 	u8 cs_was_changed_seq;
1577 	unsigned int seq;
1578 	bool do_interp;
1579 	struct timekeeper *tk;
1580 	struct tk_data *tkd;
1581 	int ret;
1582 
1583 	switch (xtstamp->clock_id) {
1584 	case CLOCK_REALTIME:
1585 		tkd = &tk_core;
1586 		offs = &tk_core.timekeeper.offs_real;
1587 		break;
1588 	case CLOCK_AUX ... CLOCK_AUX_LAST:
1589 		tkd = aux_get_tk_data(xtstamp->clock_id);
1590 		if (!tkd)
1591 			return -ENODEV;
1592 		offs = &tkd->timekeeper.offs_aux;
1593 		break;
1594 	default:
1595 		WARN_ON_ONCE(1);
1596 		return -ENODEV;
1597 	}
1598 
1599 	tk = &tkd->timekeeper;
1600 
1601 	do {
1602 		seq = read_seqcount_begin(&tkd->seq);
1603 		if (!tk->clock_valid)
1604 			return -ENODEV;
1605 
1606 		/*
1607 		 * Try to synchronously capture device time and a system
1608 		 * counter value calling back into the device driver
1609 		 */
1610 		ret = get_time_fn(&xtstamp->device, &xtstamp->sys_counter, ctx);
1611 		if (ret)
1612 			return ret;
1613 
1614 		/*
1615 		 * Verify that the clocksource ID associated with the captured
1616 		 * system counter value is the same as for the currently
1617 		 * installed timekeeper clocksource and convert to it.
1618 		 */
1619 		if (xtstamp->sys_counter.cs_id == CSID_GENERIC ||
1620 		    !convert_base_to_cs(&xtstamp->sys_counter))
1621 			return -ENODEV;
1622 
1623 		cycles = syscnt_cycles = xtstamp->sys_counter.cycles;
1624 
1625 		/*
1626 		 * Check whether the system counter value provided by the
1627 		 * device driver is on the current timekeeping interval.
1628 		 */
1629 		now = tk_clock_read(&tk->tkr_mono);
1630 		interval_start = tk->tkr_mono.cycle_last;
1631 		if (!timestamp_in_interval(interval_start, now, cycles)) {
1632 			clock_was_set_seq = tk->clock_was_set_seq;
1633 			cs_was_changed_seq = tk->cs_was_changed_seq;
1634 			cycles = interval_start;
1635 			do_interp = true;
1636 		} else {
1637 			do_interp = false;
1638 		}
1639 
1640 		base_sys = ktime_add(tk->tkr_mono.base, *offs);
1641 		base_raw = tk->tkr_raw.base;
1642 
1643 		nsec_sys = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
1644 		nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
1645 	} while (read_seqcount_retry(&tkd->seq, seq));
1646 
1647 	xtstamp->sys_systime = ktime_add_ns(base_sys, nsec_sys);
1648 	xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
1649 
1650 	/*
1651 	 * Interpolate if necessary, adjusting back from the start of the
1652 	 * current interval
1653 	 */
1654 	if (do_interp) {
1655 		u64 partial_history_cycles, total_history_cycles;
1656 		bool discontinuity;
1657 
1658 		/*
1659 		 * Check that the counter value is not before the provided
1660 		 * history reference and that the history doesn't cross a
1661 		 * clocksource change
1662 		 */
1663 		if (!history_begin ||
1664 		    !timestamp_in_interval(history_begin->cycles, cycles, syscnt_cycles) ||
1665 		    history_begin->cs_was_changed_seq != cs_was_changed_seq)
1666 			return -EINVAL;
1667 
1668 		partial_history_cycles = cycles - syscnt_cycles;
1669 		total_history_cycles = cycles - history_begin->cycles;
1670 		discontinuity = history_begin->clock_was_set_seq != clock_was_set_seq;
1671 
1672 		ret = adjust_historical_crosststamp(history_begin, partial_history_cycles,
1673 						    total_history_cycles, discontinuity, xtstamp);
1674 	}
1675 
1676 	return ret;
1677 }
1678 EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
1679 
1680 /**
1681  * timekeeping_clocksource_has_base - Check whether the current clocksource
1682  *				      is based on given a base clock
1683  * @id:		base clocksource ID
1684  *
1685  * Note:	The return value is a snapshot which can become invalid right
1686  *		after the function returns.
1687  *
1688  * Return:	true if the timekeeper clocksource has a base clock with @id,
1689  *		false otherwise
1690  */
1691 bool timekeeping_clocksource_has_base(enum clocksource_ids id)
1692 {
1693 	/*
1694 	 * This is a snapshot, so no point in using the sequence
1695 	 * count. Just prevent the compiler from re-evaluating @base as the
1696 	 * clocksource might change concurrently.
1697 	 */
1698 	struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base);
1699 
1700 	return base ? base->id == id : false;
1701 }
1702 EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base);
1703 
1704 /**
1705  * do_settimeofday64 - Sets the time of day.
1706  * @ts:     pointer to the timespec64 variable containing the new time
1707  *
1708  * Sets the time of day to the new time and update NTP and notify hrtimers
1709  */
1710 int do_settimeofday64(const struct timespec64 *ts)
1711 {
1712 	struct timespec64 ts_delta, xt;
1713 
1714 	if (!timespec64_valid_settod(ts))
1715 		return -EINVAL;
1716 
1717 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1718 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
1719 
1720 		timekeeping_forward_now(tks);
1721 
1722 		xt = tk_xtime(tks);
1723 		ts_delta = timespec64_sub(*ts, xt);
1724 
1725 		if (timespec64_compare(&tks->wall_to_monotonic, &ts_delta) > 0) {
1726 			timekeeping_restore_shadow(&tk_core);
1727 			return -EINVAL;
1728 		}
1729 
1730 		tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, ts_delta));
1731 		tk_set_xtime(tks, ts);
1732 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1733 	}
1734 
1735 	/* Signal hrtimers about time change */
1736 	clock_was_set(CLOCK_SET_WALL);
1737 
1738 	audit_tk_injoffset(ts_delta);
1739 	add_device_randomness(ts, sizeof(*ts));
1740 	return 0;
1741 }
1742 EXPORT_SYMBOL(do_settimeofday64);
1743 
1744 static inline bool timekeeper_is_core_tk(struct timekeeper *tk)
1745 {
1746 	return !IS_ENABLED(CONFIG_POSIX_AUX_CLOCKS) || tk->id == TIMEKEEPER_CORE;
1747 }
1748 
1749 /**
1750  * __timekeeping_inject_offset - Adds or subtracts from the current time.
1751  * @tkd:	Pointer to the timekeeper to modify
1752  * @ts:		Pointer to the timespec variable containing the offset
1753  *
1754  * Adds or subtracts an offset value from the current time.
1755  */
1756 static int __timekeeping_inject_offset(struct tk_data *tkd, const struct timespec64 *ts)
1757 {
1758 	struct timekeeper *tks = &tkd->shadow_timekeeper;
1759 	struct timespec64 tmp;
1760 
1761 	if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1762 		return -EINVAL;
1763 
1764 	timekeeping_forward_now(tks);
1765 
1766 	if (timekeeper_is_core_tk(tks)) {
1767 		/* Make sure the proposed value is valid */
1768 		tmp = timespec64_add(tk_xtime(tks), *ts);
1769 		if (timespec64_compare(&tks->wall_to_monotonic, ts) > 0 ||
1770 		    !timespec64_valid_settod(&tmp)) {
1771 			timekeeping_restore_shadow(tkd);
1772 			return -EINVAL;
1773 		}
1774 
1775 		tk_xtime_add(tks, ts);
1776 		tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, *ts));
1777 	} else {
1778 		struct tk_read_base *tkr_mono = &tks->tkr_mono;
1779 		ktime_t now, offs;
1780 
1781 		tk_update_ktime_data(tks);
1782 		/* Get the current time */
1783 		now = ktime_add_ns(tkr_mono->base, timekeeping_get_ns(tkr_mono));
1784 		/* Add the relative offset change */
1785 		offs = ktime_add(tks->offs_aux, timespec64_to_ktime(*ts));
1786 
1787 		/* Prevent that the resulting time becomes negative */
1788 		if (ktime_add(now, offs) < 0) {
1789 			timekeeping_restore_shadow(tkd);
1790 			return -EINVAL;
1791 		}
1792 		tk_update_aux_offs(tks, offs);
1793 	}
1794 
1795 	timekeeping_update_from_shadow(tkd, TK_UPDATE_ALL);
1796 	return 0;
1797 }
1798 
1799 static int timekeeping_inject_offset(const struct timespec64 *ts)
1800 {
1801 	int ret;
1802 
1803 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock)
1804 		ret = __timekeeping_inject_offset(&tk_core, ts);
1805 
1806 	/* Signal hrtimers about time change */
1807 	if (!ret)
1808 		clock_was_set(CLOCK_SET_WALL);
1809 	return ret;
1810 }
1811 
1812 /*
1813  * Indicates if there is an offset between the system clock and the hardware
1814  * clock/persistent clock/rtc.
1815  */
1816 int persistent_clock_is_local;
1817 
1818 /*
1819  * Adjust the time obtained from the CMOS to be UTC time instead of
1820  * local time.
1821  *
1822  * This is ugly, but preferable to the alternatives.  Otherwise we
1823  * would either need to write a program to do it in /etc/rc (and risk
1824  * confusion if the program gets run more than once; it would also be
1825  * hard to make the program warp the clock precisely n hours)  or
1826  * compile in the timezone information into the kernel.  Bad, bad....
1827  *
1828  *						- TYT, 1992-01-01
1829  *
1830  * The best thing to do is to keep the CMOS clock in universal time (UTC)
1831  * as real UNIX machines always do it. This avoids all headaches about
1832  * daylight saving times and warping kernel clocks.
1833  */
1834 void timekeeping_warp_clock(void)
1835 {
1836 	if (sys_tz.tz_minuteswest != 0) {
1837 		struct timespec64 adjust;
1838 
1839 		persistent_clock_is_local = 1;
1840 		adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1841 		adjust.tv_nsec = 0;
1842 		timekeeping_inject_offset(&adjust);
1843 	}
1844 }
1845 
1846 /*
1847  * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1848  */
1849 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1850 {
1851 	tk->tai_offset = tai_offset;
1852 	tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1853 }
1854 
1855 /*
1856  * change_clocksource - Swaps clocksources if a new one is available
1857  *
1858  * Accumulates current time interval and initializes new clocksource
1859  */
1860 static int change_clocksource(void *data)
1861 {
1862 	struct clocksource *new = data, *old = NULL;
1863 
1864 	/*
1865 	 * If the clocksource is in a module, get a module reference.
1866 	 * Succeeds for built-in code (owner == NULL) as well. Abort if the
1867 	 * reference can't be acquired.
1868 	 */
1869 	if (!try_module_get(new->owner))
1870 		return 0;
1871 
1872 	/* Abort if the device can't be enabled */
1873 	if (new->enable && new->enable(new) != 0) {
1874 		module_put(new->owner);
1875 		return 0;
1876 	}
1877 
1878 	scoped_guard (raw_spinlock_irqsave, &tk_core.lock) {
1879 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
1880 
1881 		timekeeping_forward_now(tks);
1882 		old = tks->tkr_mono.clock;
1883 		tk_setup_internals(tks, new);
1884 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
1885 	}
1886 
1887 	tk_aux_update_clocksource();
1888 
1889 	if (old) {
1890 		if (old->disable)
1891 			old->disable(old);
1892 		module_put(old->owner);
1893 	}
1894 
1895 	return 0;
1896 }
1897 
1898 /**
1899  * timekeeping_notify - Install a new clock source
1900  * @clock:		pointer to the clock source
1901  *
1902  * This function is called from clocksource.c after a new, better clock
1903  * source has been registered. The caller holds the clocksource_mutex.
1904  */
1905 int timekeeping_notify(struct clocksource *clock)
1906 {
1907 	struct timekeeper *tk = &tk_core.timekeeper;
1908 
1909 	if (tk->tkr_mono.clock == clock)
1910 		return 0;
1911 
1912 	/* Disable inlined reads accross the clocksource switch */
1913 	clocksource_disable_inline_read();
1914 
1915 	stop_machine(change_clocksource, clock, NULL);
1916 
1917 	/*
1918 	 * If the clocksource has been selected and supports inlined reads
1919 	 * enable the branch.
1920 	 */
1921 	if (tk->tkr_mono.clock == clock && clock->flags & CLOCK_SOURCE_CAN_INLINE_READ)
1922 		clocksource_enable_inline_read();
1923 
1924 	tick_clock_notify();
1925 	return tk->tkr_mono.clock == clock ? 0 : -1;
1926 }
1927 
1928 /**
1929  * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
1930  * @ts:		pointer to the timespec64 to be set
1931  *
1932  * Returns the raw monotonic time (completely un-modified by ntp)
1933  */
1934 void ktime_get_raw_ts64(struct timespec64 *ts)
1935 {
1936 	struct timekeeper *tk = &tk_core.timekeeper;
1937 	unsigned int seq;
1938 	u64 nsecs;
1939 
1940 	do {
1941 		seq = read_seqcount_begin(&tk_core.seq);
1942 		ts->tv_sec = tk->raw_sec;
1943 		nsecs = timekeeping_get_ns(&tk->tkr_raw);
1944 
1945 	} while (read_seqcount_retry(&tk_core.seq, seq));
1946 
1947 	ts->tv_nsec = 0;
1948 	timespec64_add_ns(ts, nsecs);
1949 }
1950 EXPORT_SYMBOL(ktime_get_raw_ts64);
1951 
1952 /**
1953  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
1954  */
1955 int timekeeping_valid_for_hres(void)
1956 {
1957 	struct timekeeper *tk = &tk_core.timekeeper;
1958 	unsigned int seq;
1959 	int ret;
1960 
1961 	do {
1962 		seq = read_seqcount_begin(&tk_core.seq);
1963 
1964 		ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
1965 
1966 	} while (read_seqcount_retry(&tk_core.seq, seq));
1967 
1968 	return ret;
1969 }
1970 
1971 /**
1972  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
1973  */
1974 u64 timekeeping_max_deferment(void)
1975 {
1976 	struct timekeeper *tk = &tk_core.timekeeper;
1977 	unsigned int seq;
1978 	u64 ret;
1979 
1980 	do {
1981 		seq = read_seqcount_begin(&tk_core.seq);
1982 
1983 		ret = tk->tkr_mono.clock->max_idle_ns;
1984 
1985 	} while (read_seqcount_retry(&tk_core.seq, seq));
1986 
1987 	return ret;
1988 }
1989 
1990 /**
1991  * read_persistent_clock64 -  Return time from the persistent clock.
1992  * @ts: Pointer to the storage for the readout value
1993  *
1994  * Weak dummy function for arches that do not yet support it.
1995  * Reads the time from the battery backed persistent clock.
1996  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
1997  *
1998  *  XXX - Do be sure to remove it once all arches implement it.
1999  */
2000 void __weak read_persistent_clock64(struct timespec64 *ts)
2001 {
2002 	ts->tv_sec = 0;
2003 	ts->tv_nsec = 0;
2004 }
2005 
2006 /**
2007  * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
2008  *                                        from the boot.
2009  * @wall_time:	  current time as returned by persistent clock
2010  * @boot_offset:  offset that is defined as wall_time - boot_time
2011  *
2012  * Weak dummy function for arches that do not yet support it.
2013  *
2014  * The default function calculates offset based on the current value of
2015  * local_clock(). This way architectures that support sched_clock() but don't
2016  * support dedicated boot time clock will provide the best estimate of the
2017  * boot time.
2018  */
2019 void __weak __init
2020 read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
2021 				     struct timespec64 *boot_offset)
2022 {
2023 	read_persistent_clock64(wall_time);
2024 	*boot_offset = ns_to_timespec64(local_clock());
2025 }
2026 
2027 static __init void tkd_basic_setup(struct tk_data *tkd, enum timekeeper_ids tk_id, bool valid)
2028 {
2029 	raw_spin_lock_init(&tkd->lock);
2030 	seqcount_raw_spinlock_init(&tkd->seq, &tkd->lock);
2031 	tkd->timekeeper.id = tkd->shadow_timekeeper.id = tk_id;
2032 	tkd->timekeeper.clock_valid = tkd->shadow_timekeeper.clock_valid = valid;
2033 }
2034 
2035 /*
2036  * Flag reflecting whether timekeeping_resume() has injected sleeptime.
2037  *
2038  * The flag starts of false and is only set when a suspend reaches
2039  * timekeeping_suspend(), timekeeping_resume() sets it to false when the
2040  * timekeeper clocksource is not stopping across suspend and has been
2041  * used to update sleep time. If the timekeeper clocksource has stopped
2042  * then the flag stays true and is used by the RTC resume code to decide
2043  * whether sleeptime must be injected and if so the flag gets false then.
2044  *
2045  * If a suspend fails before reaching timekeeping_resume() then the flag
2046  * stays false and prevents erroneous sleeptime injection.
2047  */
2048 static bool suspend_timing_needed;
2049 
2050 /* Flag for if there is a persistent clock on this platform */
2051 static bool persistent_clock_exists;
2052 
2053 /*
2054  * timekeeping_init - Initializes the clocksource and common timekeeping values
2055  */
2056 void __init timekeeping_init(void)
2057 {
2058 	struct timespec64 wall_time, boot_offset, wall_to_mono;
2059 	struct timekeeper *tks = &tk_core.shadow_timekeeper;
2060 	struct clocksource *clock;
2061 
2062 	tkd_basic_setup(&tk_core, TIMEKEEPER_CORE, true);
2063 	tk_aux_setup();
2064 
2065 	read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
2066 	if (timespec64_valid_settod(&wall_time) &&
2067 	    timespec64_to_ns(&wall_time) > 0) {
2068 		persistent_clock_exists = true;
2069 	} else if (timespec64_to_ns(&wall_time) != 0) {
2070 		pr_warn("Persistent clock returned invalid value");
2071 		wall_time = (struct timespec64){0};
2072 	}
2073 
2074 	if (timespec64_compare(&wall_time, &boot_offset) < 0)
2075 		boot_offset = (struct timespec64){0};
2076 
2077 	/*
2078 	 * We want set wall_to_mono, so the following is true:
2079 	 * wall time + wall_to_mono = boot time
2080 	 */
2081 	wall_to_mono = timespec64_sub(boot_offset, wall_time);
2082 
2083 	clock = clocksource_default_clock();
2084 	if (clock->enable)
2085 		clock->enable(clock);
2086 
2087 	guard(raw_spinlock_irqsave)(&tk_core.lock);
2088 
2089 	ntp_init();
2090 
2091 	tk_setup_internals(tks, clock);
2092 
2093 	tk_set_xtime(tks, &wall_time);
2094 	tks->raw_sec = 0;
2095 
2096 	tk_set_wall_to_mono(tks, wall_to_mono);
2097 
2098 	/*
2099 	 * Use TK_UPDATE_ALL so the NTP layer picks up the clocksource's
2100 	 * cs_tick_adj via ntp_clear(). Clearing NTP here is otherwise
2101 	 * redundant as ntp_init() already initialised it above.
2102 	 */
2103 	timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
2104 }
2105 
2106 /* time in seconds when suspend began for persistent clock */
2107 static struct timespec64 timekeeping_suspend_time;
2108 
2109 /**
2110  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
2111  * @tk:		Pointer to the timekeeper to be updated
2112  * @delta:	Pointer to the delta value in timespec64 format
2113  *
2114  * Takes a timespec offset measuring a suspend interval and properly
2115  * adds the sleep offset to the timekeeping variables.
2116  */
2117 static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
2118 					   const struct timespec64 *delta)
2119 {
2120 	if (!timespec64_valid_strict(delta)) {
2121 		printk_deferred(KERN_WARNING
2122 				"__timekeeping_inject_sleeptime: Invalid "
2123 				"sleep delta value!\n");
2124 		return;
2125 	}
2126 	tk_xtime_add(tk, delta);
2127 	tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
2128 	tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
2129 	tk_debug_account_sleep_time(delta);
2130 }
2131 
2132 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
2133 /*
2134  * We have three kinds of time sources to use for sleep time
2135  * injection, the preference order is:
2136  * 1) non-stop clocksource
2137  * 2) persistent clock (ie: RTC accessible when irqs are off)
2138  * 3) RTC
2139  *
2140  * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
2141  * If system has neither 1) nor 2), 3) will be used finally.
2142  *
2143  *
2144  * If timekeeping has injected sleeptime via either 1) or 2),
2145  * 3) becomes needless, so in this case we don't need to call
2146  * rtc_resume(), and this is what timekeeping_rtc_skipresume()
2147  * means.
2148  */
2149 bool timekeeping_rtc_skipresume(void)
2150 {
2151 	return !suspend_timing_needed;
2152 }
2153 
2154 /*
2155  * 1) can be determined whether to use or not only when doing
2156  * timekeeping_resume() which is invoked after rtc_suspend(),
2157  * so we can't skip rtc_suspend() surely if system has 1).
2158  *
2159  * But if system has 2), 2) will definitely be used, so in this
2160  * case we don't need to call rtc_suspend(), and this is what
2161  * timekeeping_rtc_skipsuspend() means.
2162  */
2163 bool timekeeping_rtc_skipsuspend(void)
2164 {
2165 	return persistent_clock_exists;
2166 }
2167 
2168 /**
2169  * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
2170  * @delta: pointer to a timespec64 delta value
2171  *
2172  * This hook is for architectures that cannot support read_persistent_clock64
2173  * because their RTC/persistent clock is only accessible when irqs are enabled.
2174  * and also don't have an effective nonstop clocksource.
2175  *
2176  * This function should only be called by rtc_resume(), and allows
2177  * a suspend offset to be injected into the timekeeping values.
2178  */
2179 void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
2180 {
2181 	scoped_guard(raw_spinlock_irqsave, &tk_core.lock) {
2182 		struct timekeeper *tks = &tk_core.shadow_timekeeper;
2183 
2184 		suspend_timing_needed = false;
2185 		timekeeping_forward_now(tks);
2186 		__timekeeping_inject_sleeptime(tks, delta);
2187 		timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL);
2188 	}
2189 
2190 	/* Signal hrtimers about time change */
2191 	clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
2192 }
2193 #endif
2194 
2195 /**
2196  * timekeeping_resume - Resumes the generic timekeeping subsystem.
2197  */
2198 void timekeeping_resume(void)
2199 {
2200 	struct timekeeper *tks = &tk_core.shadow_timekeeper;
2201 	struct clocksource *clock = tks->tkr_mono.clock;
2202 	struct timespec64 ts_new, ts_delta;
2203 	bool inject_sleeptime = false;
2204 	u64 cycle_now, nsec;
2205 	unsigned long flags;
2206 
2207 	read_persistent_clock64(&ts_new);
2208 
2209 	clockevents_resume();
2210 	clocksource_resume();
2211 
2212 	raw_spin_lock_irqsave(&tk_core.lock, flags);
2213 
2214 	/*
2215 	 * After system resumes, we need to calculate the suspended time and
2216 	 * compensate it for the OS time. There are 3 sources that could be
2217 	 * used: Nonstop clocksource during suspend, persistent clock and rtc
2218 	 * device.
2219 	 *
2220 	 * One specific platform may have 1 or 2 or all of them, and the
2221 	 * preference will be:
2222 	 *	suspend-nonstop clocksource -> persistent clock -> rtc
2223 	 * The less preferred source will only be tried if there is no better
2224 	 * usable source. The rtc part is handled separately in rtc core code.
2225 	 */
2226 	cycle_now = tk_clock_read(&tks->tkr_mono);
2227 	nsec = clocksource_stop_suspend_timing(clock, cycle_now);
2228 	if (nsec > 0) {
2229 		ts_delta = ns_to_timespec64(nsec);
2230 		inject_sleeptime = true;
2231 	} else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
2232 		ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
2233 		inject_sleeptime = true;
2234 	}
2235 
2236 	if (inject_sleeptime) {
2237 		suspend_timing_needed = false;
2238 		__timekeeping_inject_sleeptime(tks, &ts_delta);
2239 	}
2240 
2241 	/* Re-base the last cycle value */
2242 	tks->tkr_mono.cycle_last = cycle_now;
2243 	tks->tkr_raw.cycle_last  = cycle_now;
2244 
2245 	tks->ntp_error = 0;
2246 	timekeeping_suspended = 0;
2247 	timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET);
2248 	raw_spin_unlock_irqrestore(&tk_core.lock, flags);
2249 
2250 	touch_softlockup_watchdog();
2251 
2252 	/* Resume the clockevent device(s) and hrtimers */
2253 	tick_resume();
2254 	/* Notify timerfd as resume is equivalent to clock_was_set() */
2255 	timerfd_resume();
2256 }
2257 
2258 static void timekeeping_syscore_resume(void *data)
2259 {
2260 	timekeeping_resume();
2261 }
2262 
2263 int timekeeping_suspend(void)
2264 {
2265 	struct timekeeper *tks = &tk_core.shadow_timekeeper;
2266 	struct timespec64 delta, delta_delta;
2267 	static struct timespec64 old_delta;
2268 	struct clocksource *curr_clock;
2269 	unsigned long flags;
2270 	u64 cycle_now;
2271 
2272 	read_persistent_clock64(&timekeeping_suspend_time);
2273 
2274 	/*
2275 	 * On some systems the persistent_clock can not be detected at
2276 	 * timekeeping_init by its return value, so if we see a valid
2277 	 * value returned, update the persistent_clock_exists flag.
2278 	 */
2279 	if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
2280 		persistent_clock_exists = true;
2281 
2282 	suspend_timing_needed = true;
2283 
2284 	raw_spin_lock_irqsave(&tk_core.lock, flags);
2285 	timekeeping_forward_now(tks);
2286 	timekeeping_suspended = 1;
2287 
2288 	/*
2289 	 * Since we've called forward_now, cycle_last stores the value
2290 	 * just read from the current clocksource. Save this to potentially
2291 	 * use in suspend timing.
2292 	 */
2293 	curr_clock = tks->tkr_mono.clock;
2294 	cycle_now = tks->tkr_mono.cycle_last;
2295 	clocksource_start_suspend_timing(curr_clock, cycle_now);
2296 
2297 	if (persistent_clock_exists) {
2298 		/*
2299 		 * To avoid drift caused by repeated suspend/resumes,
2300 		 * which each can add ~1 second drift error,
2301 		 * try to compensate so the difference in system time
2302 		 * and persistent_clock time stays close to constant.
2303 		 */
2304 		delta = timespec64_sub(tk_xtime(tks), timekeeping_suspend_time);
2305 		delta_delta = timespec64_sub(delta, old_delta);
2306 		if (abs(delta_delta.tv_sec) >= 2) {
2307 			/*
2308 			 * if delta_delta is too large, assume time correction
2309 			 * has occurred and set old_delta to the current delta.
2310 			 */
2311 			old_delta = delta;
2312 		} else {
2313 			/* Otherwise try to adjust old_system to compensate */
2314 			timekeeping_suspend_time =
2315 				timespec64_add(timekeeping_suspend_time, delta_delta);
2316 		}
2317 	}
2318 
2319 	timekeeping_update_from_shadow(&tk_core, 0);
2320 	halt_fast_timekeeper(tks);
2321 	raw_spin_unlock_irqrestore(&tk_core.lock, flags);
2322 
2323 	tick_suspend();
2324 	clocksource_suspend();
2325 	clockevents_suspend();
2326 
2327 	return 0;
2328 }
2329 
2330 static int timekeeping_syscore_suspend(void *data)
2331 {
2332 	return timekeeping_suspend();
2333 }
2334 
2335 /* sysfs resume/suspend bits for timekeeping */
2336 static const struct syscore_ops timekeeping_syscore_ops = {
2337 	.resume		= timekeeping_syscore_resume,
2338 	.suspend	= timekeeping_syscore_suspend,
2339 };
2340 
2341 static struct syscore timekeeping_syscore = {
2342 	.ops = &timekeeping_syscore_ops,
2343 };
2344 
2345 static int __init timekeeping_init_ops(void)
2346 {
2347 	register_syscore(&timekeeping_syscore);
2348 	return 0;
2349 }
2350 device_initcall(timekeeping_init_ops);
2351 
2352 /*
2353  * Apply a multiplier adjustment to the timekeeper
2354  */
2355 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
2356 							 s64 offset,
2357 							 s32 mult_adj)
2358 {
2359 	s64 interval = tk->cycle_interval;
2360 
2361 	if (mult_adj == 0) {
2362 		return;
2363 	} else if (mult_adj == -1) {
2364 		interval = -interval;
2365 		offset = -offset;
2366 	} else if (mult_adj != 1) {
2367 		interval *= mult_adj;
2368 		offset *= mult_adj;
2369 	}
2370 
2371 	/*
2372 	 * So the following can be confusing.
2373 	 *
2374 	 * To keep things simple, lets assume mult_adj == 1 for now.
2375 	 *
2376 	 * When mult_adj != 1, remember that the interval and offset values
2377 	 * have been appropriately scaled so the math is the same.
2378 	 *
2379 	 * The basic idea here is that we're increasing the multiplier
2380 	 * by one, this causes the xtime_interval to be incremented by
2381 	 * one cycle_interval. This is because:
2382 	 *	xtime_interval = cycle_interval * mult
2383 	 * So if mult is being incremented by one:
2384 	 *	xtime_interval = cycle_interval * (mult + 1)
2385 	 * Its the same as:
2386 	 *	xtime_interval = (cycle_interval * mult) + cycle_interval
2387 	 * Which can be shortened to:
2388 	 *	xtime_interval += cycle_interval
2389 	 *
2390 	 * So offset stores the non-accumulated cycles. Thus the current
2391 	 * time (in shifted nanoseconds) is:
2392 	 *	now = (offset * adj) + xtime_nsec
2393 	 * Now, even though we're adjusting the clock frequency, we have
2394 	 * to keep time consistent. In other words, we can't jump back
2395 	 * in time, and we also want to avoid jumping forward in time.
2396 	 *
2397 	 * So given the same offset value, we need the time to be the same
2398 	 * both before and after the freq adjustment.
2399 	 *	now = (offset * adj_1) + xtime_nsec_1
2400 	 *	now = (offset * adj_2) + xtime_nsec_2
2401 	 * So:
2402 	 *	(offset * adj_1) + xtime_nsec_1 =
2403 	 *		(offset * adj_2) + xtime_nsec_2
2404 	 * And we know:
2405 	 *	adj_2 = adj_1 + 1
2406 	 * So:
2407 	 *	(offset * adj_1) + xtime_nsec_1 =
2408 	 *		(offset * (adj_1+1)) + xtime_nsec_2
2409 	 *	(offset * adj_1) + xtime_nsec_1 =
2410 	 *		(offset * adj_1) + offset + xtime_nsec_2
2411 	 * Canceling the sides:
2412 	 *	xtime_nsec_1 = offset + xtime_nsec_2
2413 	 * Which gives us:
2414 	 *	xtime_nsec_2 = xtime_nsec_1 - offset
2415 	 * Which simplifies to:
2416 	 *	xtime_nsec -= offset
2417 	 *
2418 	 * When subtracting offset from xtime_nsec, the same amount
2419 	 * (in appropriate units) has to be added to ntp_error, in
2420 	 * order to correctly track the delta between the time
2421 	 * reported in xtime_nsec, and the intended time.
2422 	 */
2423 	if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
2424 		/* NTP adjustment caused clocksource mult overflow */
2425 		WARN_ON_ONCE(1);
2426 		return;
2427 	}
2428 
2429 	tk->tkr_mono.mult += mult_adj;
2430 	tk->xtime_interval += interval;
2431 	tk->tkr_mono.xtime_nsec -= offset;
2432 	tk->ntp_error += offset << tk->ntp_error_shift;
2433 }
2434 
2435 /*
2436  * Adjust the timekeeper's multiplier to the correct frequency
2437  * and also to reduce the accumulated error value.
2438  */
2439 static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
2440 {
2441 	u64 ntp_tl = ntp_tick_length(tk->id);
2442 	s64 skew = ntp_get_skew_delta(tk->id);
2443 	u32 mult;
2444 
2445 	/*
2446 	 * Determine the multiplier from the current NTP tick length plus
2447 	 * skew_delta. The skew biases mult so that ±1 dithering can deliver
2448 	 * the time_offset slew rate. Recompute when either changes.
2449 	 */
2450 	if (likely(tk->ntp_tick == ntp_tl && tk->skew_delta == skew)) {
2451 		/* Revert to the base mult rate. */
2452 		mult = tk->tkr_mono.mult - tk->ntp_err_mult;
2453 	} else {
2454 		tk->ntp_tick = ntp_tl;
2455 		tk->skew_delta = skew;
2456 		/*
2457 		 * skew_delta is stored pre-divided by HZ (matching time_offset);
2458 		 * scale it back up to the full per-tick rate for the mult bias.
2459 		 */
2460 		skew *= NTP_INTERVAL_FREQ;
2461 		mult = div64_u64((tk->ntp_tick + skew) >> tk->ntp_error_shift,
2462 				 tk->cycle_interval);
2463 	}
2464 
2465 	/*
2466 	 * If the clock is behind the NTP time, increase the multiplier by 1
2467 	 * to catch up with it. If it's ahead and there was a remainder in the
2468 	 * tick division, the clock will slow down. Otherwise it will stay
2469 	 * ahead until the tick length changes to a non-divisible value.
2470 	 */
2471 	tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
2472 	mult += tk->ntp_err_mult;
2473 
2474 	timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
2475 
2476 	if (unlikely(tk->tkr_mono.clock->maxadj &&
2477 		(abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2478 			> tk->tkr_mono.clock->maxadj))) {
2479 		printk_once(KERN_WARNING
2480 			"Adjusting %s more than 11%% (%ld vs %ld)\n",
2481 			tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2482 			(long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
2483 	}
2484 
2485 	/*
2486 	 * It may be possible that when we entered this function, xtime_nsec
2487 	 * was very small.  Further, if we're slightly speeding the clocksource
2488 	 * in the code above, its possible the required corrective factor to
2489 	 * xtime_nsec could cause it to underflow.
2490 	 *
2491 	 * Now, since we have already accumulated the second and the NTP
2492 	 * subsystem has been notified via second_overflow(), we need to skip
2493 	 * the next update.
2494 	 */
2495 	if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
2496 		tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
2497 							tk->tkr_mono.shift;
2498 		tk->xtime_sec--;
2499 		tk->skip_second_overflow = 1;
2500 	}
2501 }
2502 
2503 /*
2504  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
2505  *
2506  * Helper function that accumulates the nsecs greater than a second
2507  * from the xtime_nsec field to the xtime_secs field.
2508  * It also calls into the NTP code to handle leapsecond processing.
2509  */
2510 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
2511 {
2512 	u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
2513 	unsigned int clock_set = 0;
2514 
2515 	while (tk->tkr_mono.xtime_nsec >= nsecps) {
2516 		int leap;
2517 
2518 		tk->tkr_mono.xtime_nsec -= nsecps;
2519 		tk->xtime_sec++;
2520 
2521 		/*
2522 		 * Skip NTP update if this second was accumulated before,
2523 		 * i.e. xtime_nsec underflowed in timekeeping_adjust()
2524 		 */
2525 		if (unlikely(tk->skip_second_overflow)) {
2526 			tk->skip_second_overflow = 0;
2527 			continue;
2528 		}
2529 
2530 		/* Figure out if its a leap sec and apply if needed */
2531 		leap = second_overflow(tk->id, tk->xtime_sec);
2532 		if (unlikely(leap)) {
2533 			struct timespec64 ts;
2534 
2535 			tk->xtime_sec += leap;
2536 
2537 			ts.tv_sec = leap;
2538 			ts.tv_nsec = 0;
2539 			tk_set_wall_to_mono(tk,
2540 				timespec64_sub(tk->wall_to_monotonic, ts));
2541 
2542 			__timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2543 
2544 			clock_set = TK_CLOCK_WAS_SET;
2545 		}
2546 	}
2547 	return clock_set;
2548 }
2549 
2550 /*
2551  * logarithmic_accumulation - shifted accumulation of cycles
2552  *
2553  * This functions accumulates a shifted interval of cycles into
2554  * a shifted interval nanoseconds. Allows for O(log) accumulation
2555  * loop.
2556  *
2557  * Returns the unconsumed cycles.
2558  */
2559 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2560 				    u32 shift, unsigned int *clock_set)
2561 {
2562 	u64 interval = tk->cycle_interval << shift;
2563 	u64 snsec_per_sec;
2564 
2565 	/* If the offset is smaller than a shifted interval, do nothing */
2566 	if (offset < interval)
2567 		return offset;
2568 
2569 	/* Accumulate one shifted interval */
2570 	offset -= interval;
2571 	tk->tkr_mono.cycle_last += interval;
2572 	tk->tkr_raw.cycle_last  += interval;
2573 
2574 	tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
2575 	*clock_set |= accumulate_nsecs_to_secs(tk);
2576 
2577 	/* Accumulate raw time */
2578 	tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
2579 	snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
2580 	while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
2581 		tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2582 		tk->raw_sec++;
2583 	}
2584 
2585 	/* Accumulate error between NTP and clock interval */
2586 	tk->ntp_error += tk->ntp_tick << shift;
2587 	tk->ntp_error -= tk->xtime_interval << (tk->ntp_error_shift + shift);
2588 
2589 	/*
2590 	 * When skewing, do so by adjusting ntp_error to impart an extra
2591 	 * target delta into ntp_error per tick, limited to what can be
2592 	 * drained from time_offset / time_adjust to avoid overshoot.
2593 	 *
2594 	 * The base 'mult' value was calculated with the skew taken into
2595 	 * account, such that the per-tick choice of 'mult' vs. 'mult+1'
2596 	 * allows for the desired effective rate and ntp_error does not
2597 	 * grow unbounded.
2598 	 *
2599 	 * Once the full desired phase offset is delivered, any remaining
2600 	 * skew imparted by the adjusted 'mult', accounted above, remains
2601 	 * in ntp_error and will be compensated by the dithering over time.
2602 	 */
2603 	if (tk->skew_delta)
2604 		tk->ntp_error += ntp_drain_skew(tk->id, tk->skew_delta << shift,
2605 						shift) * NTP_INTERVAL_FREQ;
2606 
2607 	return offset;
2608 }
2609 
2610 /*
2611  * timekeeping_advance - Updates the timekeeper to the current time and
2612  * current NTP tick length
2613  */
2614 static bool __timekeeping_advance(struct tk_data *tkd, enum timekeeping_adv_mode mode)
2615 {
2616 	struct timekeeper *tk = &tkd->shadow_timekeeper;
2617 	struct timekeeper *real_tk = &tkd->timekeeper;
2618 	unsigned int clock_set = 0;
2619 	int shift = 0, maxshift;
2620 	u64 offset, orig_offset;
2621 
2622 	/* Make sure we're fully resumed: */
2623 	if (unlikely(timekeeping_suspended))
2624 		return false;
2625 
2626 	offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2627 				   tk->tkr_mono.cycle_last, tk->tkr_mono.mask,
2628 				   tk->tkr_mono.clock->max_raw_delta);
2629 	orig_offset = offset;
2630 	/* Check if there's really nothing to do */
2631 	if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
2632 		return false;
2633 
2634 	/*
2635 	 * With NO_HZ we may have to accumulate many cycle_intervals
2636 	 * (think "ticks") worth of time at once. To do this efficiently,
2637 	 * we calculate the largest doubling multiple of cycle_intervals
2638 	 * that is smaller than the offset.  We then accumulate that
2639 	 * chunk in one go, and then try to consume the next smaller
2640 	 * doubled multiple.
2641 	 */
2642 	shift = ilog2(offset) - ilog2(tk->cycle_interval);
2643 	shift = max(0, shift);
2644 	/* Bound shift to one less than what overflows tick_length */
2645 	maxshift = (64 - (ilog2(ntp_tick_length(tk->id)) + 1)) - 1;
2646 	shift = min(shift, maxshift);
2647 	while (offset >= tk->cycle_interval) {
2648 		offset = logarithmic_accumulation(tk, offset, shift, &clock_set);
2649 		if (offset < tk->cycle_interval<<shift)
2650 			shift--;
2651 	}
2652 
2653 	/* Adjust the multiplier to correct NTP error */
2654 	timekeeping_adjust(tk, offset);
2655 
2656 	/*
2657 	 * Finally, make sure that after the rounding
2658 	 * xtime_nsec isn't larger than NSEC_PER_SEC
2659 	 */
2660 	clock_set |= accumulate_nsecs_to_secs(tk);
2661 
2662 	/*
2663 	 * To avoid inconsistencies caused adjtimex TK_ADV_FREQ calls
2664 	 * making small negative adjustments to the base xtime_nsec
2665 	 * value, only update the coarse clocks if we accumulated time
2666 	 */
2667 	if (orig_offset != offset)
2668 		tk_update_coarse_nsecs(tk);
2669 
2670 	timekeeping_update_from_shadow(tkd, clock_set);
2671 
2672 	return !!clock_set;
2673 }
2674 
2675 static bool timekeeping_advance(enum timekeeping_adv_mode mode)
2676 {
2677 	guard(raw_spinlock_irqsave)(&tk_core.lock);
2678 	return __timekeeping_advance(&tk_core, mode);
2679 }
2680 
2681 /**
2682  * update_wall_time - Uses the current clocksource to increment the wall time
2683  *
2684  * It also updates the enabled auxiliary clock timekeepers
2685  */
2686 void update_wall_time(void)
2687 {
2688 	if (timekeeping_advance(TK_ADV_TICK))
2689 		clock_was_set_delayed();
2690 	tk_aux_advance();
2691 }
2692 
2693 /**
2694  * getboottime64 - Return the real time of system boot.
2695  * @ts:		pointer to the timespec64 to be set
2696  *
2697  * Returns the wall-time of boot in a timespec64.
2698  *
2699  * This is based on the wall_to_monotonic offset and the total suspend
2700  * time. Calls to settimeofday will affect the value returned (which
2701  * basically means that however wrong your real time clock is at boot time,
2702  * you get the right time here).
2703  */
2704 void getboottime64(struct timespec64 *ts)
2705 {
2706 	struct timekeeper *tk = &tk_core.timekeeper;
2707 	unsigned int seq;
2708 	ktime_t t;
2709 
2710 	do {
2711 		seq = read_seqcount_begin(&tk_core.seq);
2712 		t = ktime_sub(tk->offs_real, tk->offs_boot);
2713 	} while (read_seqcount_retry(&tk_core.seq, seq));
2714 
2715 	*ts = ktime_to_timespec64(t);
2716 }
2717 EXPORT_SYMBOL_GPL(getboottime64);
2718 
2719 void ktime_get_coarse_real_ts64(struct timespec64 *ts)
2720 {
2721 	struct timekeeper *tk = &tk_core.timekeeper;
2722 	unsigned int seq;
2723 
2724 	do {
2725 		seq = read_seqcount_begin(&tk_core.seq);
2726 
2727 		*ts = tk_xtime_coarse(tk);
2728 	} while (read_seqcount_retry(&tk_core.seq, seq));
2729 }
2730 EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
2731 
2732 /**
2733  * ktime_get_coarse_real_ts64_mg - return latter of coarse grained time or floor
2734  * @ts:		timespec64 to be filled
2735  *
2736  * Fetch the global mg_floor value, convert it to realtime and compare it
2737  * to the current coarse-grained time. Fill @ts with whichever is
2738  * latest. Note that this is a filesystem-specific interface and should be
2739  * avoided outside of that context.
2740  */
2741 void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
2742 {
2743 	struct timekeeper *tk = &tk_core.timekeeper;
2744 	u64 floor = atomic64_read(&mg_floor);
2745 	ktime_t f_real, offset, coarse;
2746 	unsigned int seq;
2747 
2748 	do {
2749 		seq = read_seqcount_begin(&tk_core.seq);
2750 		*ts = tk_xtime_coarse(tk);
2751 		offset = tk_core.timekeeper.offs_real;
2752 	} while (read_seqcount_retry(&tk_core.seq, seq));
2753 
2754 	coarse = timespec64_to_ktime(*ts);
2755 	f_real = ktime_add(floor, offset);
2756 	if (ktime_after(f_real, coarse))
2757 		*ts = ktime_to_timespec64(f_real);
2758 }
2759 
2760 /**
2761  * ktime_get_real_ts64_mg - attempt to update floor value and return result
2762  * @ts:		pointer to the timespec to be set
2763  *
2764  * Get a monotonic fine-grained time value and attempt to swap it into
2765  * mg_floor. If that succeeds then accept the new floor value. If it fails
2766  * then another task raced in during the interim time and updated the
2767  * floor.  Since any update to the floor must be later than the previous
2768  * floor, either outcome is acceptable.
2769  *
2770  * Typically this will be called after calling ktime_get_coarse_real_ts64_mg(),
2771  * and determining that the resulting coarse-grained timestamp did not effect
2772  * a change in ctime. Any more recent floor value would effect a change to
2773  * ctime, so there is no need to retry the atomic64_try_cmpxchg() on failure.
2774  *
2775  * @ts will be filled with the latest floor value, regardless of the outcome of
2776  * the cmpxchg. Note that this is a filesystem specific interface and should be
2777  * avoided outside of that context.
2778  */
2779 void ktime_get_real_ts64_mg(struct timespec64 *ts)
2780 {
2781 	struct timekeeper *tk = &tk_core.timekeeper;
2782 	ktime_t old = atomic64_read(&mg_floor);
2783 	ktime_t offset, mono;
2784 	unsigned int seq;
2785 	u64 nsecs;
2786 
2787 	do {
2788 		seq = read_seqcount_begin(&tk_core.seq);
2789 
2790 		ts->tv_sec = tk->xtime_sec;
2791 		mono = tk->tkr_mono.base;
2792 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
2793 		offset = tk_core.timekeeper.offs_real;
2794 	} while (read_seqcount_retry(&tk_core.seq, seq));
2795 
2796 	mono = ktime_add_ns(mono, nsecs);
2797 
2798 	/*
2799 	 * Attempt to update the floor with the new time value. As any
2800 	 * update must be later then the existing floor, and would effect
2801 	 * a change to ctime from the perspective of the current task,
2802 	 * accept the resulting floor value regardless of the outcome of
2803 	 * the swap.
2804 	 */
2805 	if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
2806 		ts->tv_nsec = 0;
2807 		timespec64_add_ns(ts, nsecs);
2808 		timekeeping_inc_mg_floor_swaps();
2809 	} else {
2810 		/*
2811 		 * Another task changed mg_floor since "old" was fetched.
2812 		 * "old" has been updated with the latest value of "mg_floor".
2813 		 * That value is newer than the previous floor value, which
2814 		 * is enough to effect a change to ctime. Accept it.
2815 		 */
2816 		*ts = ktime_to_timespec64(ktime_add(old, offset));
2817 	}
2818 }
2819 
2820 void ktime_get_coarse_ts64(struct timespec64 *ts)
2821 {
2822 	struct timekeeper *tk = &tk_core.timekeeper;
2823 	struct timespec64 now, mono;
2824 	unsigned int seq;
2825 
2826 	do {
2827 		seq = read_seqcount_begin(&tk_core.seq);
2828 
2829 		now = tk_xtime_coarse(tk);
2830 		mono = tk->wall_to_monotonic;
2831 	} while (read_seqcount_retry(&tk_core.seq, seq));
2832 
2833 	set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
2834 				  now.tv_nsec + mono.tv_nsec);
2835 }
2836 EXPORT_SYMBOL(ktime_get_coarse_ts64);
2837 
2838 /*
2839  * Must hold jiffies_lock
2840  */
2841 void do_timer(unsigned long ticks)
2842 {
2843 	jiffies_64 += ticks;
2844 	calc_global_load();
2845 }
2846 
2847 /**
2848  * ktime_get_update_offsets_now - hrtimer helper
2849  * @cwsseq:	pointer to check and store the clock was set sequence number
2850  * @offs_real:	pointer to storage for monotonic -> realtime offset
2851  * @offs_boot:	pointer to storage for monotonic -> boottime offset
2852  * @offs_tai:	pointer to storage for monotonic -> clock tai offset
2853  *
2854  * Returns current monotonic time and updates the offsets if the
2855  * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2856  * different.
2857  *
2858  * Called from hrtimer_interrupt() or retrigger_next_event()
2859  */
2860 ktime_t ktime_get_update_offsets_now(u32 *cwsseq, ktime_t *offs_real,
2861 				     ktime_t *offs_boot, ktime_t *offs_tai)
2862 {
2863 	struct timekeeper *tk = &tk_core.timekeeper;
2864 	u32 cwsseq_orig = *cwsseq;
2865 	unsigned int seq;
2866 	ktime_t base;
2867 	u64 nsecs;
2868 
2869 	do {
2870 		seq = read_seqcount_begin(&tk_core.seq);
2871 
2872 		base = tk->tkr_mono.base;
2873 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
2874 		base = ktime_add_ns(base, nsecs);
2875 
2876 		if (cwsseq_orig != tk->clock_was_set_seq) {
2877 			*cwsseq = tk->clock_was_set_seq;
2878 			*offs_real = tk->offs_real;
2879 			*offs_boot = tk->offs_boot;
2880 			*offs_tai = tk->offs_tai;
2881 		}
2882 
2883 		/* Handle leapsecond insertion adjustments */
2884 		if (unlikely(base >= tk->next_leap_ktime))
2885 			*offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2886 
2887 	} while (read_seqcount_retry(&tk_core.seq, seq));
2888 
2889 	return base;
2890 }
2891 
2892 /*
2893  * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2894  */
2895 static int timekeeping_validate_timex(const struct __kernel_timex *txc, bool aux_clock)
2896 {
2897 	if (txc->modes & ADJ_ADJTIME) {
2898 		/* singleshot must not be used with any other mode bits */
2899 		if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2900 			return -EINVAL;
2901 		if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2902 		    !capable(CAP_SYS_TIME))
2903 			return -EPERM;
2904 	} else {
2905 		/* In order to modify anything, you gotta be super-user! */
2906 		if (txc->modes && !capable(CAP_SYS_TIME))
2907 			return -EPERM;
2908 		/*
2909 		 * if the quartz is off by more than 10% then
2910 		 * something is VERY wrong!
2911 		 */
2912 		if (txc->modes & ADJ_TICK &&
2913 		    (txc->tick <  900000/USER_HZ ||
2914 		     txc->tick > 1100000/USER_HZ))
2915 			return -EINVAL;
2916 	}
2917 
2918 	if (txc->modes & ADJ_SETOFFSET) {
2919 		/* In order to inject time, you gotta be super-user! */
2920 		if (!capable(CAP_SYS_TIME))
2921 			return -EPERM;
2922 
2923 		/*
2924 		 * Validate if a timespec/timeval used to inject a time
2925 		 * offset is valid.  Offsets can be positive or negative, so
2926 		 * we don't check tv_sec. The value of the timeval/timespec
2927 		 * is the sum of its fields,but *NOTE*:
2928 		 * The field tv_usec/tv_nsec must always be non-negative and
2929 		 * we can't have more nanoseconds/microseconds than a second.
2930 		 */
2931 		if (txc->time.tv_usec < 0)
2932 			return -EINVAL;
2933 
2934 		if (txc->modes & ADJ_NANO) {
2935 			if (txc->time.tv_usec >= NSEC_PER_SEC)
2936 				return -EINVAL;
2937 		} else {
2938 			if (txc->time.tv_usec >= USEC_PER_SEC)
2939 				return -EINVAL;
2940 		}
2941 	}
2942 
2943 	/*
2944 	 * Check for potential multiplication overflows that can
2945 	 * only happen on 64-bit systems:
2946 	 */
2947 	if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2948 		if (LLONG_MIN / PPM_SCALE > txc->freq)
2949 			return -EINVAL;
2950 		if (LLONG_MAX / PPM_SCALE < txc->freq)
2951 			return -EINVAL;
2952 	}
2953 
2954 	if (aux_clock) {
2955 		/* Auxiliary clocks are similar to TAI and do not have leap seconds */
2956 		if (txc->modes & ADJ_STATUS &&
2957 		    txc->status & (STA_INS | STA_DEL))
2958 			return -EINVAL;
2959 
2960 		/* No TAI offset setting */
2961 		if (txc->modes & ADJ_TAI)
2962 			return -EINVAL;
2963 
2964 		/* No PPS support either */
2965 		if (txc->modes & ADJ_STATUS &&
2966 		    txc->status & (STA_PPSFREQ | STA_PPSTIME))
2967 			return -EINVAL;
2968 	}
2969 
2970 	return 0;
2971 }
2972 
2973 /**
2974  * random_get_entropy_fallback - Returns the raw clock source value,
2975  * used by random.c for platforms with no valid random_get_entropy().
2976  */
2977 unsigned long random_get_entropy_fallback(void)
2978 {
2979 	struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
2980 	struct clocksource *clock = READ_ONCE(tkr->clock);
2981 
2982 	if (unlikely(timekeeping_suspended || !clock))
2983 		return 0;
2984 	return clock->read(clock);
2985 }
2986 EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
2987 
2988 struct adjtimex_result {
2989 	struct audit_ntp_data	ad;
2990 	struct timespec64	delta;
2991 	bool			clock_set;
2992 };
2993 
2994 static int __do_adjtimex(struct tk_data *tkd, struct __kernel_timex *txc,
2995 			 struct adjtimex_result *result)
2996 {
2997 	struct timekeeper *tks = &tkd->shadow_timekeeper;
2998 	bool aux_clock = !timekeeper_is_core_tk(tks);
2999 	struct timespec64 ts;
3000 	s32 orig_tai, tai;
3001 	int ret;
3002 
3003 	/* Validate the data before disabling interrupts */
3004 	ret = timekeeping_validate_timex(txc, aux_clock);
3005 	if (ret)
3006 		return ret;
3007 	add_device_randomness(txc, sizeof(*txc));
3008 
3009 	if (!aux_clock) {
3010 		ktime_get_real_ts64(&ts);
3011 	} else {
3012 		if (!tk_get_aux_ts64(tkd->timekeeper.id, &ts))
3013 			return -ENODEV;
3014 	}
3015 
3016 	add_device_randomness(&ts, sizeof(ts));
3017 
3018 	guard(raw_spinlock_irqsave)(&tkd->lock);
3019 
3020 	if (!tks->clock_valid)
3021 		return -ENODEV;
3022 
3023 	if (txc->modes & ADJ_SETOFFSET) {
3024 		result->delta.tv_sec  = txc->time.tv_sec;
3025 		result->delta.tv_nsec = txc->time.tv_usec;
3026 		if (!(txc->modes & ADJ_NANO))
3027 			result->delta.tv_nsec *= 1000;
3028 		ret = __timekeeping_inject_offset(tkd, &result->delta);
3029 		if (ret)
3030 			return ret;
3031 		result->clock_set = true;
3032 	}
3033 
3034 	orig_tai = tai = tks->tai_offset;
3035 	ret = ntp_adjtimex(tks->id, txc, &ts, &tai, &result->ad);
3036 
3037 	if (tai != orig_tai) {
3038 		__timekeeping_set_tai_offset(tks, tai);
3039 		timekeeping_update_from_shadow(tkd, TK_CLOCK_WAS_SET);
3040 		result->clock_set = true;
3041 	} else {
3042 		tk_update_leap_state_all(tkd);
3043 	}
3044 
3045 	/* Update the multiplier immediately if frequency was set directly */
3046 	if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
3047 		result->clock_set |= __timekeeping_advance(tkd, TK_ADV_FREQ);
3048 
3049 	return ret;
3050 }
3051 
3052 /**
3053  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
3054  * @txc:	Pointer to kernel_timex structure containing NTP parameters
3055  */
3056 int do_adjtimex(struct __kernel_timex *txc)
3057 {
3058 	struct adjtimex_result result = { };
3059 	int ret;
3060 
3061 	ret = __do_adjtimex(&tk_core, txc, &result);
3062 	if (ret < 0)
3063 		return ret;
3064 
3065 	if (txc->modes & ADJ_SETOFFSET)
3066 		audit_tk_injoffset(result.delta);
3067 
3068 	audit_ntp_log(&result.ad);
3069 
3070 	if (result.clock_set)
3071 		clock_was_set(CLOCK_SET_WALL);
3072 
3073 	ntp_notify_cmos_timer(result.delta.tv_sec != 0);
3074 
3075 	return ret;
3076 }
3077 
3078 /*
3079  * Invoked from NTP with the time keeper lock held, so lockless access is
3080  * fine.
3081  */
3082 long ktime_get_ntp_seconds(unsigned int id)
3083 {
3084 	return timekeeper_data[id].timekeeper.xtime_sec;
3085 }
3086 
3087 #ifdef CONFIG_NTP_PPS
3088 /**
3089  * hardpps() - Accessor function to NTP __hardpps function
3090  * @phase_ts:	Pointer to timespec64 structure representing phase timestamp
3091  * @raw_ts:	Pointer to timespec64 structure representing raw timestamp
3092  */
3093 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
3094 {
3095 	guard(raw_spinlock_irqsave)(&tk_core.lock);
3096 	__hardpps(phase_ts, raw_ts);
3097 }
3098 EXPORT_SYMBOL(hardpps);
3099 #endif /* CONFIG_NTP_PPS */
3100 
3101 #ifdef CONFIG_POSIX_AUX_CLOCKS
3102 #include "posix-timers.h"
3103 
3104 /*
3105  * Bitmap for the activated auxiliary timekeepers to allow lockless quick
3106  * checks in the hot paths without touching extra cache lines. If set, then
3107  * the state of the corresponding timekeeper has to be re-checked under
3108  * timekeeper::lock.
3109  */
3110 static unsigned long aux_timekeepers;
3111 
3112 static inline unsigned int clockid_to_tkid(unsigned int id)
3113 {
3114 	return TIMEKEEPER_AUX_FIRST + id - CLOCK_AUX;
3115 }
3116 
3117 static inline struct tk_data *aux_get_tk_data(clockid_t id)
3118 {
3119 	if (!clockid_is_aux_clock(id))
3120 		return NULL;
3121 	return &timekeeper_data[clockid_to_tkid(id)];
3122 }
3123 
3124 /* Invoked from timekeeping after a clocksource change */
3125 static void tk_aux_update_clocksource(void)
3126 {
3127 	unsigned long active = READ_ONCE(aux_timekeepers);
3128 	unsigned int id;
3129 
3130 	for_each_set_bit(id, &active, BITS_PER_LONG) {
3131 		struct tk_data *tkd = &timekeeper_data[id + TIMEKEEPER_AUX_FIRST];
3132 		struct timekeeper *tks = &tkd->shadow_timekeeper;
3133 
3134 		guard(raw_spinlock_irqsave)(&tkd->lock);
3135 		if (!tks->clock_valid)
3136 			continue;
3137 
3138 		timekeeping_forward_now(tks);
3139 		tk_setup_internals(tks, tk_core.timekeeper.tkr_raw.clock);
3140 		timekeeping_update_from_shadow(tkd, TK_UPDATE_ALL);
3141 	}
3142 }
3143 
3144 static void tk_aux_advance(void)
3145 {
3146 	unsigned long active = READ_ONCE(aux_timekeepers);
3147 	unsigned int id;
3148 
3149 	/* Lockless quick check to avoid extra cache lines */
3150 	for_each_set_bit(id, &active, BITS_PER_LONG) {
3151 		struct tk_data *aux_tkd = &timekeeper_data[id + TIMEKEEPER_AUX_FIRST];
3152 
3153 		guard(raw_spinlock)(&aux_tkd->lock);
3154 		if (aux_tkd->shadow_timekeeper.clock_valid)
3155 			__timekeeping_advance(aux_tkd, TK_ADV_TICK);
3156 	}
3157 }
3158 
3159 /**
3160  * ktime_get_aux - Get time for a AUX clock
3161  * @id:	ID of the clock to read (CLOCK_AUX...)
3162  * @kt:	Pointer to ktime_t to store the time stamp
3163  *
3164  * Returns: True if the timestamp is valid, false otherwise
3165  */
3166 bool ktime_get_aux(clockid_t id, ktime_t *kt)
3167 {
3168 	struct tk_data *aux_tkd = aux_get_tk_data(id);
3169 	struct timekeeper *aux_tk;
3170 	unsigned int seq;
3171 	ktime_t base;
3172 	u64 nsecs;
3173 
3174 	WARN_ON(timekeeping_suspended);
3175 
3176 	if (!aux_tkd)
3177 		return false;
3178 
3179 	aux_tk = &aux_tkd->timekeeper;
3180 	do {
3181 		seq = read_seqcount_begin(&aux_tkd->seq);
3182 		if (!aux_tk->clock_valid)
3183 			return false;
3184 
3185 		base = ktime_add(aux_tk->tkr_mono.base, aux_tk->offs_aux);
3186 		nsecs = timekeeping_get_ns(&aux_tk->tkr_mono);
3187 	} while (read_seqcount_retry(&aux_tkd->seq, seq));
3188 
3189 	*kt = ktime_add_ns(base, nsecs);
3190 	return true;
3191 }
3192 EXPORT_SYMBOL_GPL(ktime_get_aux);
3193 
3194 /**
3195  * ktime_get_aux_ts64 - Get time for a AUX clock
3196  * @id:	ID of the clock to read (CLOCK_AUX...)
3197  * @ts:	Pointer to timespec64 to store the time stamp
3198  *
3199  * Returns: True if the timestamp is valid, false otherwise
3200  */
3201 bool ktime_get_aux_ts64(clockid_t id, struct timespec64 *ts)
3202 {
3203 	ktime_t now;
3204 
3205 	if (!ktime_get_aux(id, &now))
3206 		return false;
3207 	*ts = ktime_to_timespec64(now);
3208 	return true;
3209 }
3210 EXPORT_SYMBOL_GPL(ktime_get_aux_ts64);
3211 
3212 static int aux_get_res(clockid_t id, struct timespec64 *tp)
3213 {
3214 	if (!clockid_is_aux_clock(id))
3215 		return -ENODEV;
3216 
3217 	tp->tv_sec = aux_clock_resolution_ns() / NSEC_PER_SEC;
3218 	tp->tv_nsec = aux_clock_resolution_ns() % NSEC_PER_SEC;
3219 	return 0;
3220 }
3221 
3222 static int aux_get_timespec(clockid_t id, struct timespec64 *tp)
3223 {
3224 	return ktime_get_aux_ts64(id, tp) ? 0 : -ENODEV;
3225 }
3226 
3227 static int aux_clock_set(const clockid_t id, const struct timespec64 *tnew)
3228 {
3229 	struct tk_data *aux_tkd = aux_get_tk_data(id);
3230 	struct timekeeper *aux_tks;
3231 	ktime_t tnow, nsecs;
3232 	int ret;
3233 
3234 	if (!timespec64_valid_settod(tnew))
3235 		return -EINVAL;
3236 	if (!aux_tkd)
3237 		return -ENODEV;
3238 	ret = security_settime64(tnew, NULL);
3239 	if (ret)
3240 		return ret;
3241 
3242 	aux_tks = &aux_tkd->shadow_timekeeper;
3243 
3244 	guard(raw_spinlock_irq)(&aux_tkd->lock);
3245 	if (!aux_tks->clock_valid)
3246 		return -ENODEV;
3247 
3248 	/* Forward the timekeeper base time */
3249 	timekeeping_forward_now(aux_tks);
3250 	/*
3251 	 * Get the updated base time. tkr_mono.base has not been
3252 	 * updated yet, so do that first. That makes the update
3253 	 * in timekeeping_update_from_shadow() redundant, but
3254 	 * that's harmless. After that @tnow can be calculated
3255 	 * by using tkr_mono::cycle_last, which has been set
3256 	 * by timekeeping_forward_now().
3257 	 */
3258 	tk_update_ktime_data(aux_tks);
3259 	nsecs = timekeeping_cycles_to_ns(&aux_tks->tkr_mono, aux_tks->tkr_mono.cycle_last);
3260 	tnow = ktime_add(aux_tks->tkr_mono.base, nsecs);
3261 
3262 	/*
3263 	 * Calculate the new AUX offset as delta to @tnow ("monotonic").
3264 	 * That avoids all the tk::xtime back and forth conversions as
3265 	 * xtime ("realtime") is not applicable for auxiliary clocks and
3266 	 * kept in sync with "monotonic".
3267 	 */
3268 	tk_update_aux_offs(aux_tks, ktime_sub(timespec64_to_ktime(*tnew), tnow));
3269 
3270 	timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL);
3271 	return 0;
3272 }
3273 
3274 static int aux_clock_adj(const clockid_t id, struct __kernel_timex *txc)
3275 {
3276 	struct tk_data *aux_tkd = aux_get_tk_data(id);
3277 	struct adjtimex_result result = { };
3278 
3279 	if (!aux_tkd)
3280 		return -ENODEV;
3281 
3282 	/*
3283 	 * @result is ignored for now as there are neither hrtimers nor a
3284 	 * RTC related to auxiliary clocks for now.
3285 	 */
3286 	return __do_adjtimex(aux_tkd, txc, &result);
3287 }
3288 
3289 const struct k_clock clock_aux = {
3290 	.clock_getres		= aux_get_res,
3291 	.clock_get_timespec	= aux_get_timespec,
3292 	.clock_set		= aux_clock_set,
3293 	.clock_adj		= aux_clock_adj,
3294 };
3295 
3296 static void aux_clock_enable(clockid_t id)
3297 {
3298 	struct tk_read_base *tkr_raw = &tk_core.timekeeper.tkr_raw;
3299 	struct tk_data *aux_tkd = aux_get_tk_data(id);
3300 	struct timekeeper *aux_tks = &aux_tkd->shadow_timekeeper;
3301 
3302 	/* Prevent the core timekeeper from changing. */
3303 	guard(raw_spinlock_irq)(&tk_core.lock);
3304 
3305 	/*
3306 	 * Setup the auxiliary clock assuming that the raw core timekeeper
3307 	 * clock frequency conversion is close enough. Userspace has to
3308 	 * adjust for the deviation via clock_adjtime(2).
3309 	 */
3310 	guard(raw_spinlock_nested)(&aux_tkd->lock);
3311 
3312 	/* Remove leftovers of a previous registration */
3313 	memset(aux_tks, 0, sizeof(*aux_tks));
3314 	/* Restore the timekeeper id */
3315 	aux_tks->id = aux_tkd->timekeeper.id;
3316 	/* Setup the timekeeper based on the current system clocksource */
3317 	tk_setup_internals(aux_tks, tkr_raw->clock);
3318 
3319 	/* Mark it valid and set it live */
3320 	aux_tks->clock_valid = true;
3321 	timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL);
3322 }
3323 
3324 static void aux_clock_disable(clockid_t id)
3325 {
3326 	struct tk_data *aux_tkd = aux_get_tk_data(id);
3327 
3328 	guard(raw_spinlock_irq)(&aux_tkd->lock);
3329 	aux_tkd->shadow_timekeeper.clock_valid = false;
3330 	timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL);
3331 }
3332 
3333 static DEFINE_MUTEX(aux_clock_mutex);
3334 
3335 static ssize_t aux_clock_enable_store(struct kobject *kobj, struct kobj_attribute *attr,
3336 				      const char *buf, size_t count)
3337 {
3338 	/* Lazy atoi() as name is "0..7" */
3339 	int id = kobj->name[0] & 0x7;
3340 	bool enable;
3341 
3342 	if (!capable(CAP_SYS_TIME))
3343 		return -EPERM;
3344 
3345 	if (kstrtobool(buf, &enable) < 0)
3346 		return -EINVAL;
3347 
3348 	guard(mutex)(&aux_clock_mutex);
3349 	if (enable == test_bit(id, &aux_timekeepers))
3350 		return count;
3351 
3352 	if (enable) {
3353 		aux_clock_enable(CLOCK_AUX + id);
3354 		set_bit(id, &aux_timekeepers);
3355 	} else {
3356 		aux_clock_disable(CLOCK_AUX + id);
3357 		clear_bit(id, &aux_timekeepers);
3358 	}
3359 	return count;
3360 }
3361 
3362 static ssize_t aux_clock_enable_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
3363 {
3364 	unsigned long active = READ_ONCE(aux_timekeepers);
3365 	/* Lazy atoi() as name is "0..7" */
3366 	int id = kobj->name[0] & 0x7;
3367 
3368 	return sysfs_emit(buf, "%d\n", test_bit(id, &active));
3369 }
3370 
3371 static struct kobj_attribute aux_clock_enable_attr = __ATTR_RW(aux_clock_enable);
3372 
3373 static struct attribute *aux_clock_enable_attrs[] = {
3374 	&aux_clock_enable_attr.attr,
3375 	NULL
3376 };
3377 
3378 static const struct attribute_group aux_clock_enable_attr_group = {
3379 	.attrs = aux_clock_enable_attrs,
3380 };
3381 
3382 static int __init tk_aux_sysfs_init(void)
3383 {
3384 	struct kobject *auxo, *tko = kobject_create_and_add("time", kernel_kobj);
3385 	struct kobject *clks[MAX_AUX_CLOCKS];
3386 	int ret = -ENOMEM;
3387 	int i;
3388 
3389 	if (!tko)
3390 		return ret;
3391 
3392 	auxo = kobject_create_and_add("aux_clocks", tko);
3393 	if (!auxo)
3394 		goto err_clean;
3395 
3396 	for (i = 0; i < MAX_AUX_CLOCKS; i++) {
3397 		char id[2] = { [0] = '0' + i, };
3398 		clks[i] = kobject_create_and_add(id, auxo);
3399 
3400 		if (!clks[i]) {
3401 			ret = -ENOMEM;
3402 			goto err_clks;
3403 		}
3404 
3405 		ret = sysfs_create_group(clks[i], &aux_clock_enable_attr_group);
3406 		if (ret)
3407 			goto err_clk;
3408 	}
3409 	return 0;
3410 
3411 err_clk:
3412 	kobject_put(clks[i]);
3413 err_clks:
3414 	while (--i >= 0) {
3415 		sysfs_remove_group(clks[i], &aux_clock_enable_attr_group);
3416 		kobject_put(clks[i]);
3417 	}
3418 err_clean:
3419 	kobject_put(auxo);
3420 	kobject_put(tko);
3421 	return ret;
3422 }
3423 late_initcall(tk_aux_sysfs_init);
3424 
3425 static __init void tk_aux_setup(void)
3426 {
3427 	for (int i = TIMEKEEPER_AUX_FIRST; i <= TIMEKEEPER_AUX_LAST; i++)
3428 		tkd_basic_setup(&timekeeper_data[i], i, false);
3429 }
3430 #endif /* CONFIG_POSIX_AUX_CLOCKS */
3431