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