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