xref: /openbmc/linux/kernel/time/timekeeping.c (revision 57d05a93ada77c4f8a6112cbc867a2948dce7991)
18524070bSjohn stultz /*
28524070bSjohn stultz  *  linux/kernel/time/timekeeping.c
38524070bSjohn stultz  *
48524070bSjohn stultz  *  Kernel timekeeping code and accessor functions
58524070bSjohn stultz  *
68524070bSjohn stultz  *  This code was moved from linux/kernel/timer.c.
78524070bSjohn stultz  *  Please see that file for copyright and history logs.
88524070bSjohn stultz  *
98524070bSjohn stultz  */
108524070bSjohn stultz 
11d7b4202eSJohn Stultz #include <linux/timekeeper_internal.h>
128524070bSjohn stultz #include <linux/module.h>
138524070bSjohn stultz #include <linux/interrupt.h>
148524070bSjohn stultz #include <linux/percpu.h>
158524070bSjohn stultz #include <linux/init.h>
168524070bSjohn stultz #include <linux/mm.h>
17d43c36dcSAlexey Dobriyan #include <linux/sched.h>
18e1a85b2cSRafael J. Wysocki #include <linux/syscore_ops.h>
198524070bSjohn stultz #include <linux/clocksource.h>
208524070bSjohn stultz #include <linux/jiffies.h>
218524070bSjohn stultz #include <linux/time.h>
228524070bSjohn stultz #include <linux/tick.h>
2375c5158fSMartin Schwidefsky #include <linux/stop_machine.h>
24e0b306feSMarcelo Tosatti #include <linux/pvclock_gtod.h>
2552f5684cSGideon Israel Dsouza #include <linux/compiler.h>
268524070bSjohn stultz 
27eb93e4d9SThomas Gleixner #include "tick-internal.h"
28aa6f9c59SJohn Stultz #include "ntp_internal.h"
295c83545fSColin Cross #include "timekeeping_internal.h"
30155ec602SMartin Schwidefsky 
3104397fe9SDavid Vrabel #define TK_CLEAR_NTP		(1 << 0)
3204397fe9SDavid Vrabel #define TK_MIRROR		(1 << 1)
33780427f0SDavid Vrabel #define TK_CLOCK_WAS_SET	(1 << 2)
3404397fe9SDavid Vrabel 
353fdb14fdSThomas Gleixner /*
363fdb14fdSThomas Gleixner  * The most important data for readout fits into a single 64 byte
373fdb14fdSThomas Gleixner  * cache line.
383fdb14fdSThomas Gleixner  */
393fdb14fdSThomas Gleixner static struct {
403fdb14fdSThomas Gleixner 	seqcount_t		seq;
413fdb14fdSThomas Gleixner 	struct timekeeper	timekeeper;
423fdb14fdSThomas Gleixner } tk_core ____cacheline_aligned;
433fdb14fdSThomas Gleixner 
449a7a71b1SThomas Gleixner static DEFINE_RAW_SPINLOCK(timekeeper_lock);
4548cdc135SThomas Gleixner static struct timekeeper shadow_timekeeper;
46155ec602SMartin Schwidefsky 
474396e058SThomas Gleixner /**
484396e058SThomas Gleixner  * struct tk_fast - NMI safe timekeeper
494396e058SThomas Gleixner  * @seq:	Sequence counter for protecting updates. The lowest bit
504396e058SThomas Gleixner  *		is the index for the tk_read_base array
514396e058SThomas Gleixner  * @base:	tk_read_base array. Access is indexed by the lowest bit of
524396e058SThomas Gleixner  *		@seq.
534396e058SThomas Gleixner  *
544396e058SThomas Gleixner  * See @update_fast_timekeeper() below.
554396e058SThomas Gleixner  */
564396e058SThomas Gleixner struct tk_fast {
574396e058SThomas Gleixner 	seqcount_t		seq;
584396e058SThomas Gleixner 	struct tk_read_base	base[2];
594396e058SThomas Gleixner };
604396e058SThomas Gleixner 
614396e058SThomas Gleixner static struct tk_fast tk_fast_mono ____cacheline_aligned;
62f09cb9a1SPeter Zijlstra static struct tk_fast tk_fast_raw  ____cacheline_aligned;
634396e058SThomas Gleixner 
648fcce546SJohn Stultz /* flag for if timekeeping is suspended */
658fcce546SJohn Stultz int __read_mostly timekeeping_suspended;
668fcce546SJohn Stultz 
671e75fa8bSJohn Stultz static inline void tk_normalize_xtime(struct timekeeper *tk)
681e75fa8bSJohn Stultz {
69876e7881SPeter Zijlstra 	while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
70876e7881SPeter Zijlstra 		tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
711e75fa8bSJohn Stultz 		tk->xtime_sec++;
721e75fa8bSJohn Stultz 	}
731e75fa8bSJohn Stultz }
748fcce546SJohn Stultz 
75c905fae4SThomas Gleixner static inline struct timespec64 tk_xtime(struct timekeeper *tk)
76c905fae4SThomas Gleixner {
77c905fae4SThomas Gleixner 	struct timespec64 ts;
78c905fae4SThomas Gleixner 
79c905fae4SThomas Gleixner 	ts.tv_sec = tk->xtime_sec;
80876e7881SPeter Zijlstra 	ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
81c905fae4SThomas Gleixner 	return ts;
82c905fae4SThomas Gleixner }
83c905fae4SThomas Gleixner 
847d489d15SJohn Stultz static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
851e75fa8bSJohn Stultz {
861e75fa8bSJohn Stultz 	tk->xtime_sec = ts->tv_sec;
87876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
881e75fa8bSJohn Stultz }
891e75fa8bSJohn Stultz 
907d489d15SJohn Stultz static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
911e75fa8bSJohn Stultz {
921e75fa8bSJohn Stultz 	tk->xtime_sec += ts->tv_sec;
93876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
94784ffcbbSJohn Stultz 	tk_normalize_xtime(tk);
951e75fa8bSJohn Stultz }
968fcce546SJohn Stultz 
977d489d15SJohn Stultz static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
986d0ef903SJohn Stultz {
997d489d15SJohn Stultz 	struct timespec64 tmp;
1006d0ef903SJohn Stultz 
1016d0ef903SJohn Stultz 	/*
1026d0ef903SJohn Stultz 	 * Verify consistency of: offset_real = -wall_to_monotonic
1036d0ef903SJohn Stultz 	 * before modifying anything
1046d0ef903SJohn Stultz 	 */
1057d489d15SJohn Stultz 	set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
1066d0ef903SJohn Stultz 					-tk->wall_to_monotonic.tv_nsec);
1077d489d15SJohn Stultz 	WARN_ON_ONCE(tk->offs_real.tv64 != timespec64_to_ktime(tmp).tv64);
1086d0ef903SJohn Stultz 	tk->wall_to_monotonic = wtm;
1097d489d15SJohn Stultz 	set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
1107d489d15SJohn Stultz 	tk->offs_real = timespec64_to_ktime(tmp);
11104005f60SJohn Stultz 	tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
1126d0ef903SJohn Stultz }
1136d0ef903SJohn Stultz 
11447da70d3SThomas Gleixner static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
1156d0ef903SJohn Stultz {
11647da70d3SThomas Gleixner 	tk->offs_boot = ktime_add(tk->offs_boot, delta);
1176d0ef903SJohn Stultz }
1186d0ef903SJohn Stultz 
1193c17ad19SJohn Stultz #ifdef CONFIG_DEBUG_TIMEKEEPING
1204ca22c26SJohn Stultz #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
1214ca22c26SJohn Stultz 
1223c17ad19SJohn Stultz static void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
1233c17ad19SJohn Stultz {
1243c17ad19SJohn Stultz 
125876e7881SPeter Zijlstra 	cycle_t max_cycles = tk->tkr_mono.clock->max_cycles;
126876e7881SPeter Zijlstra 	const char *name = tk->tkr_mono.clock->name;
1273c17ad19SJohn Stultz 
1283c17ad19SJohn Stultz 	if (offset > max_cycles) {
129a558cd02SJohn Stultz 		printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
1303c17ad19SJohn Stultz 				offset, name, max_cycles);
131a558cd02SJohn Stultz 		printk_deferred("         timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
1323c17ad19SJohn Stultz 	} else {
1333c17ad19SJohn Stultz 		if (offset > (max_cycles >> 1)) {
1343c17ad19SJohn Stultz 			printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the the '%s' clock's 50%% safety margin (%lld)\n",
1353c17ad19SJohn Stultz 					offset, name, max_cycles >> 1);
1363c17ad19SJohn Stultz 			printk_deferred("      timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
1373c17ad19SJohn Stultz 		}
1383c17ad19SJohn Stultz 	}
1394ca22c26SJohn Stultz 
140*57d05a93SJohn Stultz 	if (tk->underflow_seen) {
141*57d05a93SJohn Stultz 		if (jiffies - tk->last_warning > WARNING_FREQ) {
1424ca22c26SJohn Stultz 			printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
1434ca22c26SJohn Stultz 			printk_deferred("         Please report this, consider using a different clocksource, if possible.\n");
1444ca22c26SJohn Stultz 			printk_deferred("         Your kernel is probably still fine.\n");
145*57d05a93SJohn Stultz 			tk->last_warning = jiffies;
1464ca22c26SJohn Stultz 		}
147*57d05a93SJohn Stultz 		tk->underflow_seen = 0;
1484ca22c26SJohn Stultz 	}
1494ca22c26SJohn Stultz 
150*57d05a93SJohn Stultz 	if (tk->overflow_seen) {
151*57d05a93SJohn Stultz 		if (jiffies - tk->last_warning > WARNING_FREQ) {
1524ca22c26SJohn Stultz 			printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
1534ca22c26SJohn Stultz 			printk_deferred("         Please report this, consider using a different clocksource, if possible.\n");
1544ca22c26SJohn Stultz 			printk_deferred("         Your kernel is probably still fine.\n");
155*57d05a93SJohn Stultz 			tk->last_warning = jiffies;
1564ca22c26SJohn Stultz 		}
157*57d05a93SJohn Stultz 		tk->overflow_seen = 0;
1584ca22c26SJohn Stultz 	}
1593c17ad19SJohn Stultz }
160a558cd02SJohn Stultz 
161a558cd02SJohn Stultz static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
162a558cd02SJohn Stultz {
163*57d05a93SJohn Stultz 	struct timekeeper *tk = &tk_core.timekeeper;
1644ca22c26SJohn Stultz 	cycle_t now, last, mask, max, delta;
1654ca22c26SJohn Stultz 	unsigned int seq;
166a558cd02SJohn Stultz 
1674ca22c26SJohn Stultz 	/*
1684ca22c26SJohn Stultz 	 * Since we're called holding a seqlock, the data may shift
1694ca22c26SJohn Stultz 	 * under us while we're doing the calculation. This can cause
1704ca22c26SJohn Stultz 	 * false positives, since we'd note a problem but throw the
1714ca22c26SJohn Stultz 	 * results away. So nest another seqlock here to atomically
1724ca22c26SJohn Stultz 	 * grab the points we are checking with.
1734ca22c26SJohn Stultz 	 */
1744ca22c26SJohn Stultz 	do {
1754ca22c26SJohn Stultz 		seq = read_seqcount_begin(&tk_core.seq);
1764ca22c26SJohn Stultz 		now = tkr->read(tkr->clock);
1774ca22c26SJohn Stultz 		last = tkr->cycle_last;
1784ca22c26SJohn Stultz 		mask = tkr->mask;
1794ca22c26SJohn Stultz 		max = tkr->clock->max_cycles;
1804ca22c26SJohn Stultz 	} while (read_seqcount_retry(&tk_core.seq, seq));
181a558cd02SJohn Stultz 
1824ca22c26SJohn Stultz 	delta = clocksource_delta(now, last, mask);
183a558cd02SJohn Stultz 
184057b87e3SJohn Stultz 	/*
185057b87e3SJohn Stultz 	 * Try to catch underflows by checking if we are seeing small
186057b87e3SJohn Stultz 	 * mask-relative negative values.
187057b87e3SJohn Stultz 	 */
1884ca22c26SJohn Stultz 	if (unlikely((~delta & mask) < (mask >> 3))) {
189*57d05a93SJohn Stultz 		tk->underflow_seen = 1;
190057b87e3SJohn Stultz 		delta = 0;
1914ca22c26SJohn Stultz 	}
192057b87e3SJohn Stultz 
193a558cd02SJohn Stultz 	/* Cap delta value to the max_cycles values to avoid mult overflows */
1944ca22c26SJohn Stultz 	if (unlikely(delta > max)) {
195*57d05a93SJohn Stultz 		tk->overflow_seen = 1;
196a558cd02SJohn Stultz 		delta = tkr->clock->max_cycles;
1974ca22c26SJohn Stultz 	}
198a558cd02SJohn Stultz 
199a558cd02SJohn Stultz 	return delta;
200a558cd02SJohn Stultz }
2013c17ad19SJohn Stultz #else
2023c17ad19SJohn Stultz static inline void timekeeping_check_update(struct timekeeper *tk, cycle_t offset)
2033c17ad19SJohn Stultz {
2043c17ad19SJohn Stultz }
205a558cd02SJohn Stultz static inline cycle_t timekeeping_get_delta(struct tk_read_base *tkr)
206a558cd02SJohn Stultz {
207a558cd02SJohn Stultz 	cycle_t cycle_now, delta;
208a558cd02SJohn Stultz 
209a558cd02SJohn Stultz 	/* read clocksource */
210a558cd02SJohn Stultz 	cycle_now = tkr->read(tkr->clock);
211a558cd02SJohn Stultz 
212a558cd02SJohn Stultz 	/* calculate the delta since the last update_wall_time */
213a558cd02SJohn Stultz 	delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
214a558cd02SJohn Stultz 
215a558cd02SJohn Stultz 	return delta;
216a558cd02SJohn Stultz }
2173c17ad19SJohn Stultz #endif
2183c17ad19SJohn Stultz 
219155ec602SMartin Schwidefsky /**
220d26e4fe0SYijing Wang  * tk_setup_internals - Set up internals to use clocksource clock.
221155ec602SMartin Schwidefsky  *
222d26e4fe0SYijing Wang  * @tk:		The target timekeeper to setup.
223155ec602SMartin Schwidefsky  * @clock:		Pointer to clocksource.
224155ec602SMartin Schwidefsky  *
225155ec602SMartin Schwidefsky  * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
226155ec602SMartin Schwidefsky  * pair and interval request.
227155ec602SMartin Schwidefsky  *
228155ec602SMartin Schwidefsky  * Unless you're the timekeeping code, you should not be using this!
229155ec602SMartin Schwidefsky  */
230f726a697SJohn Stultz static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
231155ec602SMartin Schwidefsky {
232155ec602SMartin Schwidefsky 	cycle_t interval;
233a386b5afSKasper Pedersen 	u64 tmp, ntpinterval;
2341e75fa8bSJohn Stultz 	struct clocksource *old_clock;
235155ec602SMartin Schwidefsky 
236876e7881SPeter Zijlstra 	old_clock = tk->tkr_mono.clock;
237876e7881SPeter Zijlstra 	tk->tkr_mono.clock = clock;
238876e7881SPeter Zijlstra 	tk->tkr_mono.read = clock->read;
239876e7881SPeter Zijlstra 	tk->tkr_mono.mask = clock->mask;
240876e7881SPeter Zijlstra 	tk->tkr_mono.cycle_last = tk->tkr_mono.read(clock);
241155ec602SMartin Schwidefsky 
2424a4ad80dSPeter Zijlstra 	tk->tkr_raw.clock = clock;
2434a4ad80dSPeter Zijlstra 	tk->tkr_raw.read = clock->read;
2444a4ad80dSPeter Zijlstra 	tk->tkr_raw.mask = clock->mask;
2454a4ad80dSPeter Zijlstra 	tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
2464a4ad80dSPeter Zijlstra 
247155ec602SMartin Schwidefsky 	/* Do the ns -> cycle conversion first, using original mult */
248155ec602SMartin Schwidefsky 	tmp = NTP_INTERVAL_LENGTH;
249155ec602SMartin Schwidefsky 	tmp <<= clock->shift;
250a386b5afSKasper Pedersen 	ntpinterval = tmp;
2510a544198SMartin Schwidefsky 	tmp += clock->mult/2;
2520a544198SMartin Schwidefsky 	do_div(tmp, clock->mult);
253155ec602SMartin Schwidefsky 	if (tmp == 0)
254155ec602SMartin Schwidefsky 		tmp = 1;
255155ec602SMartin Schwidefsky 
256155ec602SMartin Schwidefsky 	interval = (cycle_t) tmp;
257f726a697SJohn Stultz 	tk->cycle_interval = interval;
258155ec602SMartin Schwidefsky 
259155ec602SMartin Schwidefsky 	/* Go back from cycles -> shifted ns */
260f726a697SJohn Stultz 	tk->xtime_interval = (u64) interval * clock->mult;
261f726a697SJohn Stultz 	tk->xtime_remainder = ntpinterval - tk->xtime_interval;
262f726a697SJohn Stultz 	tk->raw_interval =
2630a544198SMartin Schwidefsky 		((u64) interval * clock->mult) >> clock->shift;
264155ec602SMartin Schwidefsky 
2651e75fa8bSJohn Stultz 	 /* if changing clocks, convert xtime_nsec shift units */
2661e75fa8bSJohn Stultz 	if (old_clock) {
2671e75fa8bSJohn Stultz 		int shift_change = clock->shift - old_clock->shift;
2681e75fa8bSJohn Stultz 		if (shift_change < 0)
269876e7881SPeter Zijlstra 			tk->tkr_mono.xtime_nsec >>= -shift_change;
2701e75fa8bSJohn Stultz 		else
271876e7881SPeter Zijlstra 			tk->tkr_mono.xtime_nsec <<= shift_change;
2721e75fa8bSJohn Stultz 	}
2734a4ad80dSPeter Zijlstra 	tk->tkr_raw.xtime_nsec = 0;
2744a4ad80dSPeter Zijlstra 
275876e7881SPeter Zijlstra 	tk->tkr_mono.shift = clock->shift;
2764a4ad80dSPeter Zijlstra 	tk->tkr_raw.shift = clock->shift;
277155ec602SMartin Schwidefsky 
278f726a697SJohn Stultz 	tk->ntp_error = 0;
279f726a697SJohn Stultz 	tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
280375f45b5SJohn Stultz 	tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
2810a544198SMartin Schwidefsky 
2820a544198SMartin Schwidefsky 	/*
2830a544198SMartin Schwidefsky 	 * The timekeeper keeps its own mult values for the currently
2840a544198SMartin Schwidefsky 	 * active clocksource. These value will be adjusted via NTP
2850a544198SMartin Schwidefsky 	 * to counteract clock drifting.
2860a544198SMartin Schwidefsky 	 */
287876e7881SPeter Zijlstra 	tk->tkr_mono.mult = clock->mult;
2884a4ad80dSPeter Zijlstra 	tk->tkr_raw.mult = clock->mult;
289dc491596SJohn Stultz 	tk->ntp_err_mult = 0;
290155ec602SMartin Schwidefsky }
2918524070bSjohn stultz 
2922ba2a305SMartin Schwidefsky /* Timekeeper helper functions. */
2937b1f6207SStephen Warren 
2947b1f6207SStephen Warren #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
295e06fde37SThomas Gleixner static u32 default_arch_gettimeoffset(void) { return 0; }
296e06fde37SThomas Gleixner u32 (*arch_gettimeoffset)(void) = default_arch_gettimeoffset;
2977b1f6207SStephen Warren #else
298e06fde37SThomas Gleixner static inline u32 arch_gettimeoffset(void) { return 0; }
2997b1f6207SStephen Warren #endif
3007b1f6207SStephen Warren 
3010e5ac3a8SThomas Gleixner static inline s64 timekeeping_get_ns(struct tk_read_base *tkr)
3022ba2a305SMartin Schwidefsky {
303a558cd02SJohn Stultz 	cycle_t delta;
3041e75fa8bSJohn Stultz 	s64 nsec;
3052ba2a305SMartin Schwidefsky 
306a558cd02SJohn Stultz 	delta = timekeeping_get_delta(tkr);
3072ba2a305SMartin Schwidefsky 
3080e5ac3a8SThomas Gleixner 	nsec = delta * tkr->mult + tkr->xtime_nsec;
3090e5ac3a8SThomas Gleixner 	nsec >>= tkr->shift;
310f2a5a085SJohn Stultz 
3117b1f6207SStephen Warren 	/* If arch requires, add in get_arch_timeoffset() */
312e06fde37SThomas Gleixner 	return nsec + arch_gettimeoffset();
3132ba2a305SMartin Schwidefsky }
3142ba2a305SMartin Schwidefsky 
3154396e058SThomas Gleixner /**
3164396e058SThomas Gleixner  * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
317affe3e85SRafael J. Wysocki  * @tkr: Timekeeping readout base from which we take the update
3184396e058SThomas Gleixner  *
3194396e058SThomas Gleixner  * We want to use this from any context including NMI and tracing /
3204396e058SThomas Gleixner  * instrumenting the timekeeping code itself.
3214396e058SThomas Gleixner  *
3224396e058SThomas Gleixner  * So we handle this differently than the other timekeeping accessor
3234396e058SThomas Gleixner  * functions which retry when the sequence count has changed. The
3244396e058SThomas Gleixner  * update side does:
3254396e058SThomas Gleixner  *
3264396e058SThomas Gleixner  * smp_wmb();	<- Ensure that the last base[1] update is visible
3274396e058SThomas Gleixner  * tkf->seq++;
3284396e058SThomas Gleixner  * smp_wmb();	<- Ensure that the seqcount update is visible
329affe3e85SRafael J. Wysocki  * update(tkf->base[0], tkr);
3304396e058SThomas Gleixner  * smp_wmb();	<- Ensure that the base[0] update is visible
3314396e058SThomas Gleixner  * tkf->seq++;
3324396e058SThomas Gleixner  * smp_wmb();	<- Ensure that the seqcount update is visible
333affe3e85SRafael J. Wysocki  * update(tkf->base[1], tkr);
3344396e058SThomas Gleixner  *
3354396e058SThomas Gleixner  * The reader side does:
3364396e058SThomas Gleixner  *
3374396e058SThomas Gleixner  * do {
3384396e058SThomas Gleixner  *	seq = tkf->seq;
3394396e058SThomas Gleixner  *	smp_rmb();
3404396e058SThomas Gleixner  *	idx = seq & 0x01;
3414396e058SThomas Gleixner  *	now = now(tkf->base[idx]);
3424396e058SThomas Gleixner  *	smp_rmb();
3434396e058SThomas Gleixner  * } while (seq != tkf->seq)
3444396e058SThomas Gleixner  *
3454396e058SThomas Gleixner  * As long as we update base[0] readers are forced off to
3464396e058SThomas Gleixner  * base[1]. Once base[0] is updated readers are redirected to base[0]
3474396e058SThomas Gleixner  * and the base[1] update takes place.
3484396e058SThomas Gleixner  *
3494396e058SThomas Gleixner  * So if a NMI hits the update of base[0] then it will use base[1]
3504396e058SThomas Gleixner  * which is still consistent. In the worst case this can result is a
3514396e058SThomas Gleixner  * slightly wrong timestamp (a few nanoseconds). See
3524396e058SThomas Gleixner  * @ktime_get_mono_fast_ns.
3534396e058SThomas Gleixner  */
3544498e746SPeter Zijlstra static void update_fast_timekeeper(struct tk_read_base *tkr, struct tk_fast *tkf)
3554396e058SThomas Gleixner {
3564498e746SPeter Zijlstra 	struct tk_read_base *base = tkf->base;
3574396e058SThomas Gleixner 
3584396e058SThomas Gleixner 	/* Force readers off to base[1] */
3594498e746SPeter Zijlstra 	raw_write_seqcount_latch(&tkf->seq);
3604396e058SThomas Gleixner 
3614396e058SThomas Gleixner 	/* Update base[0] */
362affe3e85SRafael J. Wysocki 	memcpy(base, tkr, sizeof(*base));
3634396e058SThomas Gleixner 
3644396e058SThomas Gleixner 	/* Force readers back to base[0] */
3654498e746SPeter Zijlstra 	raw_write_seqcount_latch(&tkf->seq);
3664396e058SThomas Gleixner 
3674396e058SThomas Gleixner 	/* Update base[1] */
3684396e058SThomas Gleixner 	memcpy(base + 1, base, sizeof(*base));
3694396e058SThomas Gleixner }
3704396e058SThomas Gleixner 
3714396e058SThomas Gleixner /**
3724396e058SThomas Gleixner  * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
3734396e058SThomas Gleixner  *
3744396e058SThomas Gleixner  * This timestamp is not guaranteed to be monotonic across an update.
3754396e058SThomas Gleixner  * The timestamp is calculated by:
3764396e058SThomas Gleixner  *
3774396e058SThomas Gleixner  *	now = base_mono + clock_delta * slope
3784396e058SThomas Gleixner  *
3794396e058SThomas Gleixner  * So if the update lowers the slope, readers who are forced to the
3804396e058SThomas Gleixner  * not yet updated second array are still using the old steeper slope.
3814396e058SThomas Gleixner  *
3824396e058SThomas Gleixner  * tmono
3834396e058SThomas Gleixner  * ^
3844396e058SThomas Gleixner  * |    o  n
3854396e058SThomas Gleixner  * |   o n
3864396e058SThomas Gleixner  * |  u
3874396e058SThomas Gleixner  * | o
3884396e058SThomas Gleixner  * |o
3894396e058SThomas Gleixner  * |12345678---> reader order
3904396e058SThomas Gleixner  *
3914396e058SThomas Gleixner  * o = old slope
3924396e058SThomas Gleixner  * u = update
3934396e058SThomas Gleixner  * n = new slope
3944396e058SThomas Gleixner  *
3954396e058SThomas Gleixner  * So reader 6 will observe time going backwards versus reader 5.
3964396e058SThomas Gleixner  *
3974396e058SThomas Gleixner  * While other CPUs are likely to be able observe that, the only way
3984396e058SThomas Gleixner  * for a CPU local observation is when an NMI hits in the middle of
3994396e058SThomas Gleixner  * the update. Timestamps taken from that NMI context might be ahead
4004396e058SThomas Gleixner  * of the following timestamps. Callers need to be aware of that and
4014396e058SThomas Gleixner  * deal with it.
4024396e058SThomas Gleixner  */
4034498e746SPeter Zijlstra static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
4044396e058SThomas Gleixner {
4054396e058SThomas Gleixner 	struct tk_read_base *tkr;
4064396e058SThomas Gleixner 	unsigned int seq;
4074396e058SThomas Gleixner 	u64 now;
4084396e058SThomas Gleixner 
4094396e058SThomas Gleixner 	do {
4104498e746SPeter Zijlstra 		seq = raw_read_seqcount(&tkf->seq);
4114498e746SPeter Zijlstra 		tkr = tkf->base + (seq & 0x01);
412876e7881SPeter Zijlstra 		now = ktime_to_ns(tkr->base) + timekeeping_get_ns(tkr);
4134498e746SPeter Zijlstra 	} while (read_seqcount_retry(&tkf->seq, seq));
4144396e058SThomas Gleixner 
4154396e058SThomas Gleixner 	return now;
4164396e058SThomas Gleixner }
4174498e746SPeter Zijlstra 
4184498e746SPeter Zijlstra u64 ktime_get_mono_fast_ns(void)
4194498e746SPeter Zijlstra {
4204498e746SPeter Zijlstra 	return __ktime_get_fast_ns(&tk_fast_mono);
4214498e746SPeter Zijlstra }
4224396e058SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
4234396e058SThomas Gleixner 
424f09cb9a1SPeter Zijlstra u64 ktime_get_raw_fast_ns(void)
425f09cb9a1SPeter Zijlstra {
426f09cb9a1SPeter Zijlstra 	return __ktime_get_fast_ns(&tk_fast_raw);
427f09cb9a1SPeter Zijlstra }
428f09cb9a1SPeter Zijlstra EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
429f09cb9a1SPeter Zijlstra 
430060407aeSRafael J. Wysocki /* Suspend-time cycles value for halted fast timekeeper. */
431060407aeSRafael J. Wysocki static cycle_t cycles_at_suspend;
432060407aeSRafael J. Wysocki 
433060407aeSRafael J. Wysocki static cycle_t dummy_clock_read(struct clocksource *cs)
434060407aeSRafael J. Wysocki {
435060407aeSRafael J. Wysocki 	return cycles_at_suspend;
436060407aeSRafael J. Wysocki }
437060407aeSRafael J. Wysocki 
438060407aeSRafael J. Wysocki /**
439060407aeSRafael J. Wysocki  * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
440060407aeSRafael J. Wysocki  * @tk: Timekeeper to snapshot.
441060407aeSRafael J. Wysocki  *
442060407aeSRafael J. Wysocki  * It generally is unsafe to access the clocksource after timekeeping has been
443060407aeSRafael J. Wysocki  * suspended, so take a snapshot of the readout base of @tk and use it as the
444060407aeSRafael J. Wysocki  * fast timekeeper's readout base while suspended.  It will return the same
445060407aeSRafael J. Wysocki  * number of cycles every time until timekeeping is resumed at which time the
446060407aeSRafael J. Wysocki  * proper readout base for the fast timekeeper will be restored automatically.
447060407aeSRafael J. Wysocki  */
448060407aeSRafael J. Wysocki static void halt_fast_timekeeper(struct timekeeper *tk)
449060407aeSRafael J. Wysocki {
450060407aeSRafael J. Wysocki 	static struct tk_read_base tkr_dummy;
451876e7881SPeter Zijlstra 	struct tk_read_base *tkr = &tk->tkr_mono;
452060407aeSRafael J. Wysocki 
453060407aeSRafael J. Wysocki 	memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
454060407aeSRafael J. Wysocki 	cycles_at_suspend = tkr->read(tkr->clock);
455060407aeSRafael J. Wysocki 	tkr_dummy.read = dummy_clock_read;
4564498e746SPeter Zijlstra 	update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
457f09cb9a1SPeter Zijlstra 
458f09cb9a1SPeter Zijlstra 	tkr = &tk->tkr_raw;
459f09cb9a1SPeter Zijlstra 	memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
460f09cb9a1SPeter Zijlstra 	tkr_dummy.read = dummy_clock_read;
461f09cb9a1SPeter Zijlstra 	update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
462060407aeSRafael J. Wysocki }
463060407aeSRafael J. Wysocki 
464c905fae4SThomas Gleixner #ifdef CONFIG_GENERIC_TIME_VSYSCALL_OLD
465c905fae4SThomas Gleixner 
466c905fae4SThomas Gleixner static inline void update_vsyscall(struct timekeeper *tk)
467c905fae4SThomas Gleixner {
4680680eb1fSJohn Stultz 	struct timespec xt, wm;
469c905fae4SThomas Gleixner 
470e2dff1ecSJohn Stultz 	xt = timespec64_to_timespec(tk_xtime(tk));
4710680eb1fSJohn Stultz 	wm = timespec64_to_timespec(tk->wall_to_monotonic);
472876e7881SPeter Zijlstra 	update_vsyscall_old(&xt, &wm, tk->tkr_mono.clock, tk->tkr_mono.mult,
473876e7881SPeter Zijlstra 			    tk->tkr_mono.cycle_last);
474c905fae4SThomas Gleixner }
475c905fae4SThomas Gleixner 
476c905fae4SThomas Gleixner static inline void old_vsyscall_fixup(struct timekeeper *tk)
477c905fae4SThomas Gleixner {
478c905fae4SThomas Gleixner 	s64 remainder;
479c905fae4SThomas Gleixner 
480c905fae4SThomas Gleixner 	/*
481c905fae4SThomas Gleixner 	* Store only full nanoseconds into xtime_nsec after rounding
482c905fae4SThomas Gleixner 	* it up and add the remainder to the error difference.
483c905fae4SThomas Gleixner 	* XXX - This is necessary to avoid small 1ns inconsistnecies caused
484c905fae4SThomas Gleixner 	* by truncating the remainder in vsyscalls. However, it causes
485c905fae4SThomas Gleixner 	* additional work to be done in timekeeping_adjust(). Once
486c905fae4SThomas Gleixner 	* the vsyscall implementations are converted to use xtime_nsec
487c905fae4SThomas Gleixner 	* (shifted nanoseconds), and CONFIG_GENERIC_TIME_VSYSCALL_OLD
488c905fae4SThomas Gleixner 	* users are removed, this can be killed.
489c905fae4SThomas Gleixner 	*/
490876e7881SPeter Zijlstra 	remainder = tk->tkr_mono.xtime_nsec & ((1ULL << tk->tkr_mono.shift) - 1);
491876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec -= remainder;
492876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec += 1ULL << tk->tkr_mono.shift;
493c905fae4SThomas Gleixner 	tk->ntp_error += remainder << tk->ntp_error_shift;
494876e7881SPeter Zijlstra 	tk->ntp_error -= (1ULL << tk->tkr_mono.shift) << tk->ntp_error_shift;
495c905fae4SThomas Gleixner }
496c905fae4SThomas Gleixner #else
497c905fae4SThomas Gleixner #define old_vsyscall_fixup(tk)
498c905fae4SThomas Gleixner #endif
499c905fae4SThomas Gleixner 
500e0b306feSMarcelo Tosatti static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
501e0b306feSMarcelo Tosatti 
502780427f0SDavid Vrabel static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
503e0b306feSMarcelo Tosatti {
504780427f0SDavid Vrabel 	raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
505e0b306feSMarcelo Tosatti }
506e0b306feSMarcelo Tosatti 
507e0b306feSMarcelo Tosatti /**
508e0b306feSMarcelo Tosatti  * pvclock_gtod_register_notifier - register a pvclock timedata update listener
509e0b306feSMarcelo Tosatti  */
510e0b306feSMarcelo Tosatti int pvclock_gtod_register_notifier(struct notifier_block *nb)
511e0b306feSMarcelo Tosatti {
5123fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
513e0b306feSMarcelo Tosatti 	unsigned long flags;
514e0b306feSMarcelo Tosatti 	int ret;
515e0b306feSMarcelo Tosatti 
5169a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
517e0b306feSMarcelo Tosatti 	ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
518780427f0SDavid Vrabel 	update_pvclock_gtod(tk, true);
5199a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
520e0b306feSMarcelo Tosatti 
521e0b306feSMarcelo Tosatti 	return ret;
522e0b306feSMarcelo Tosatti }
523e0b306feSMarcelo Tosatti EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
524e0b306feSMarcelo Tosatti 
525e0b306feSMarcelo Tosatti /**
526e0b306feSMarcelo Tosatti  * pvclock_gtod_unregister_notifier - unregister a pvclock
527e0b306feSMarcelo Tosatti  * timedata update listener
528e0b306feSMarcelo Tosatti  */
529e0b306feSMarcelo Tosatti int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
530e0b306feSMarcelo Tosatti {
531e0b306feSMarcelo Tosatti 	unsigned long flags;
532e0b306feSMarcelo Tosatti 	int ret;
533e0b306feSMarcelo Tosatti 
5349a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
535e0b306feSMarcelo Tosatti 	ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
5369a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
537e0b306feSMarcelo Tosatti 
538e0b306feSMarcelo Tosatti 	return ret;
539e0b306feSMarcelo Tosatti }
540e0b306feSMarcelo Tosatti EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
541e0b306feSMarcelo Tosatti 
5427c032df5SThomas Gleixner /*
5437c032df5SThomas Gleixner  * Update the ktime_t based scalar nsec members of the timekeeper
5447c032df5SThomas Gleixner  */
5457c032df5SThomas Gleixner static inline void tk_update_ktime_data(struct timekeeper *tk)
5467c032df5SThomas Gleixner {
5479e3680b1SHeena Sirwani 	u64 seconds;
5489e3680b1SHeena Sirwani 	u32 nsec;
5497c032df5SThomas Gleixner 
5507c032df5SThomas Gleixner 	/*
5517c032df5SThomas Gleixner 	 * The xtime based monotonic readout is:
5527c032df5SThomas Gleixner 	 *	nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
5537c032df5SThomas Gleixner 	 * The ktime based monotonic readout is:
5547c032df5SThomas Gleixner 	 *	nsec = base_mono + now();
5557c032df5SThomas Gleixner 	 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
5567c032df5SThomas Gleixner 	 */
5579e3680b1SHeena Sirwani 	seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
5589e3680b1SHeena Sirwani 	nsec = (u32) tk->wall_to_monotonic.tv_nsec;
559876e7881SPeter Zijlstra 	tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
560f519b1a2SThomas Gleixner 
561f519b1a2SThomas Gleixner 	/* Update the monotonic raw base */
5624a4ad80dSPeter Zijlstra 	tk->tkr_raw.base = timespec64_to_ktime(tk->raw_time);
5639e3680b1SHeena Sirwani 
5649e3680b1SHeena Sirwani 	/*
5659e3680b1SHeena Sirwani 	 * The sum of the nanoseconds portions of xtime and
5669e3680b1SHeena Sirwani 	 * wall_to_monotonic can be greater/equal one second. Take
5679e3680b1SHeena Sirwani 	 * this into account before updating tk->ktime_sec.
5689e3680b1SHeena Sirwani 	 */
569876e7881SPeter Zijlstra 	nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
5709e3680b1SHeena Sirwani 	if (nsec >= NSEC_PER_SEC)
5719e3680b1SHeena Sirwani 		seconds++;
5729e3680b1SHeena Sirwani 	tk->ktime_sec = seconds;
5737c032df5SThomas Gleixner }
5747c032df5SThomas Gleixner 
5759a7a71b1SThomas Gleixner /* must hold timekeeper_lock */
57604397fe9SDavid Vrabel static void timekeeping_update(struct timekeeper *tk, unsigned int action)
577cc06268cSThomas Gleixner {
57804397fe9SDavid Vrabel 	if (action & TK_CLEAR_NTP) {
579f726a697SJohn Stultz 		tk->ntp_error = 0;
580cc06268cSThomas Gleixner 		ntp_clear();
581cc06268cSThomas Gleixner 	}
58248cdc135SThomas Gleixner 
5837c032df5SThomas Gleixner 	tk_update_ktime_data(tk);
5847c032df5SThomas Gleixner 
5859bf2419fSThomas Gleixner 	update_vsyscall(tk);
5869bf2419fSThomas Gleixner 	update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
5879bf2419fSThomas Gleixner 
58804397fe9SDavid Vrabel 	if (action & TK_MIRROR)
5893fdb14fdSThomas Gleixner 		memcpy(&shadow_timekeeper, &tk_core.timekeeper,
5903fdb14fdSThomas Gleixner 		       sizeof(tk_core.timekeeper));
5914396e058SThomas Gleixner 
5924498e746SPeter Zijlstra 	update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
593f09cb9a1SPeter Zijlstra 	update_fast_timekeeper(&tk->tkr_raw,  &tk_fast_raw);
594868a3e91SThomas Gleixner 
595868a3e91SThomas Gleixner 	if (action & TK_CLOCK_WAS_SET)
596868a3e91SThomas Gleixner 		tk->clock_was_set_seq++;
597cc06268cSThomas Gleixner }
598cc06268cSThomas Gleixner 
5998524070bSjohn stultz /**
600155ec602SMartin Schwidefsky  * timekeeping_forward_now - update clock to the current time
6018524070bSjohn stultz  *
6029a055117SRoman Zippel  * Forward the current clock to update its state since the last call to
6039a055117SRoman Zippel  * update_wall_time(). This is useful before significant clock changes,
6049a055117SRoman Zippel  * as it avoids having to deal with this time offset explicitly.
6058524070bSjohn stultz  */
606f726a697SJohn Stultz static void timekeeping_forward_now(struct timekeeper *tk)
6078524070bSjohn stultz {
608876e7881SPeter Zijlstra 	struct clocksource *clock = tk->tkr_mono.clock;
6093a978377SThomas Gleixner 	cycle_t cycle_now, delta;
6109a055117SRoman Zippel 	s64 nsec;
6118524070bSjohn stultz 
612876e7881SPeter Zijlstra 	cycle_now = tk->tkr_mono.read(clock);
613876e7881SPeter Zijlstra 	delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
614876e7881SPeter Zijlstra 	tk->tkr_mono.cycle_last = cycle_now;
6154a4ad80dSPeter Zijlstra 	tk->tkr_raw.cycle_last  = cycle_now;
6168524070bSjohn stultz 
617876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec += delta * tk->tkr_mono.mult;
6187d27558cSjohn stultz 
6197b1f6207SStephen Warren 	/* If arch requires, add in get_arch_timeoffset() */
620876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec += (u64)arch_gettimeoffset() << tk->tkr_mono.shift;
6217d27558cSjohn stultz 
622f726a697SJohn Stultz 	tk_normalize_xtime(tk);
6232d42244aSJohn Stultz 
6244a4ad80dSPeter Zijlstra 	nsec = clocksource_cyc2ns(delta, tk->tkr_raw.mult, tk->tkr_raw.shift);
6257d489d15SJohn Stultz 	timespec64_add_ns(&tk->raw_time, nsec);
6268524070bSjohn stultz }
6278524070bSjohn stultz 
6288524070bSjohn stultz /**
629d6d29896SThomas Gleixner  * __getnstimeofday64 - Returns the time of day in a timespec64.
6308524070bSjohn stultz  * @ts:		pointer to the timespec to be set
6318524070bSjohn stultz  *
6321e817fb6SKees Cook  * Updates the time of day in the timespec.
6331e817fb6SKees Cook  * Returns 0 on success, or -ve when suspended (timespec will be undefined).
6348524070bSjohn stultz  */
635d6d29896SThomas Gleixner int __getnstimeofday64(struct timespec64 *ts)
6368524070bSjohn stultz {
6373fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
6388524070bSjohn stultz 	unsigned long seq;
6391e75fa8bSJohn Stultz 	s64 nsecs = 0;
6408524070bSjohn stultz 
6418524070bSjohn stultz 	do {
6423fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
6438524070bSjohn stultz 
6444e250fddSJohn Stultz 		ts->tv_sec = tk->xtime_sec;
645876e7881SPeter Zijlstra 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
6468524070bSjohn stultz 
6473fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
6488524070bSjohn stultz 
649ec145babSJohn Stultz 	ts->tv_nsec = 0;
650d6d29896SThomas Gleixner 	timespec64_add_ns(ts, nsecs);
6511e817fb6SKees Cook 
6521e817fb6SKees Cook 	/*
6531e817fb6SKees Cook 	 * Do not bail out early, in case there were callers still using
6541e817fb6SKees Cook 	 * the value, even in the face of the WARN_ON.
6551e817fb6SKees Cook 	 */
6561e817fb6SKees Cook 	if (unlikely(timekeeping_suspended))
6571e817fb6SKees Cook 		return -EAGAIN;
6581e817fb6SKees Cook 	return 0;
6591e817fb6SKees Cook }
660d6d29896SThomas Gleixner EXPORT_SYMBOL(__getnstimeofday64);
6611e817fb6SKees Cook 
6621e817fb6SKees Cook /**
663d6d29896SThomas Gleixner  * getnstimeofday64 - Returns the time of day in a timespec64.
6645322e4c2SJohn Stultz  * @ts:		pointer to the timespec64 to be set
6651e817fb6SKees Cook  *
6665322e4c2SJohn Stultz  * Returns the time of day in a timespec64 (WARN if suspended).
6671e817fb6SKees Cook  */
668d6d29896SThomas Gleixner void getnstimeofday64(struct timespec64 *ts)
6691e817fb6SKees Cook {
670d6d29896SThomas Gleixner 	WARN_ON(__getnstimeofday64(ts));
6718524070bSjohn stultz }
672d6d29896SThomas Gleixner EXPORT_SYMBOL(getnstimeofday64);
6738524070bSjohn stultz 
674951ed4d3SMartin Schwidefsky ktime_t ktime_get(void)
675951ed4d3SMartin Schwidefsky {
6763fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
677951ed4d3SMartin Schwidefsky 	unsigned int seq;
678a016a5bdSThomas Gleixner 	ktime_t base;
679a016a5bdSThomas Gleixner 	s64 nsecs;
680951ed4d3SMartin Schwidefsky 
681951ed4d3SMartin Schwidefsky 	WARN_ON(timekeeping_suspended);
682951ed4d3SMartin Schwidefsky 
683951ed4d3SMartin Schwidefsky 	do {
6843fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
685876e7881SPeter Zijlstra 		base = tk->tkr_mono.base;
686876e7881SPeter Zijlstra 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
687951ed4d3SMartin Schwidefsky 
6883fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
68924e4a8c3SJohn Stultz 
690a016a5bdSThomas Gleixner 	return ktime_add_ns(base, nsecs);
691951ed4d3SMartin Schwidefsky }
692951ed4d3SMartin Schwidefsky EXPORT_SYMBOL_GPL(ktime_get);
693951ed4d3SMartin Schwidefsky 
6946374f912SHarald Geyer u32 ktime_get_resolution_ns(void)
6956374f912SHarald Geyer {
6966374f912SHarald Geyer 	struct timekeeper *tk = &tk_core.timekeeper;
6976374f912SHarald Geyer 	unsigned int seq;
6986374f912SHarald Geyer 	u32 nsecs;
6996374f912SHarald Geyer 
7006374f912SHarald Geyer 	WARN_ON(timekeeping_suspended);
7016374f912SHarald Geyer 
7026374f912SHarald Geyer 	do {
7036374f912SHarald Geyer 		seq = read_seqcount_begin(&tk_core.seq);
7046374f912SHarald Geyer 		nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
7056374f912SHarald Geyer 	} while (read_seqcount_retry(&tk_core.seq, seq));
7066374f912SHarald Geyer 
7076374f912SHarald Geyer 	return nsecs;
7086374f912SHarald Geyer }
7096374f912SHarald Geyer EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
7106374f912SHarald Geyer 
7110077dc60SThomas Gleixner static ktime_t *offsets[TK_OFFS_MAX] = {
7120077dc60SThomas Gleixner 	[TK_OFFS_REAL]	= &tk_core.timekeeper.offs_real,
7130077dc60SThomas Gleixner 	[TK_OFFS_BOOT]	= &tk_core.timekeeper.offs_boot,
7140077dc60SThomas Gleixner 	[TK_OFFS_TAI]	= &tk_core.timekeeper.offs_tai,
7150077dc60SThomas Gleixner };
7160077dc60SThomas Gleixner 
7170077dc60SThomas Gleixner ktime_t ktime_get_with_offset(enum tk_offsets offs)
7180077dc60SThomas Gleixner {
7190077dc60SThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
7200077dc60SThomas Gleixner 	unsigned int seq;
7210077dc60SThomas Gleixner 	ktime_t base, *offset = offsets[offs];
7220077dc60SThomas Gleixner 	s64 nsecs;
7230077dc60SThomas Gleixner 
7240077dc60SThomas Gleixner 	WARN_ON(timekeeping_suspended);
7250077dc60SThomas Gleixner 
7260077dc60SThomas Gleixner 	do {
7270077dc60SThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
728876e7881SPeter Zijlstra 		base = ktime_add(tk->tkr_mono.base, *offset);
729876e7881SPeter Zijlstra 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
7300077dc60SThomas Gleixner 
7310077dc60SThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
7320077dc60SThomas Gleixner 
7330077dc60SThomas Gleixner 	return ktime_add_ns(base, nsecs);
7340077dc60SThomas Gleixner 
7350077dc60SThomas Gleixner }
7360077dc60SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_with_offset);
7370077dc60SThomas Gleixner 
738951ed4d3SMartin Schwidefsky /**
7399a6b5197SThomas Gleixner  * ktime_mono_to_any() - convert mononotic time to any other time
7409a6b5197SThomas Gleixner  * @tmono:	time to convert.
7419a6b5197SThomas Gleixner  * @offs:	which offset to use
7429a6b5197SThomas Gleixner  */
7439a6b5197SThomas Gleixner ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
7449a6b5197SThomas Gleixner {
7459a6b5197SThomas Gleixner 	ktime_t *offset = offsets[offs];
7469a6b5197SThomas Gleixner 	unsigned long seq;
7479a6b5197SThomas Gleixner 	ktime_t tconv;
7489a6b5197SThomas Gleixner 
7499a6b5197SThomas Gleixner 	do {
7509a6b5197SThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
7519a6b5197SThomas Gleixner 		tconv = ktime_add(tmono, *offset);
7529a6b5197SThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
7539a6b5197SThomas Gleixner 
7549a6b5197SThomas Gleixner 	return tconv;
7559a6b5197SThomas Gleixner }
7569a6b5197SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_mono_to_any);
7579a6b5197SThomas Gleixner 
7589a6b5197SThomas Gleixner /**
759f519b1a2SThomas Gleixner  * ktime_get_raw - Returns the raw monotonic time in ktime_t format
760f519b1a2SThomas Gleixner  */
761f519b1a2SThomas Gleixner ktime_t ktime_get_raw(void)
762f519b1a2SThomas Gleixner {
763f519b1a2SThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
764f519b1a2SThomas Gleixner 	unsigned int seq;
765f519b1a2SThomas Gleixner 	ktime_t base;
766f519b1a2SThomas Gleixner 	s64 nsecs;
767f519b1a2SThomas Gleixner 
768f519b1a2SThomas Gleixner 	do {
769f519b1a2SThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
7704a4ad80dSPeter Zijlstra 		base = tk->tkr_raw.base;
7714a4ad80dSPeter Zijlstra 		nsecs = timekeeping_get_ns(&tk->tkr_raw);
772f519b1a2SThomas Gleixner 
773f519b1a2SThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
774f519b1a2SThomas Gleixner 
775f519b1a2SThomas Gleixner 	return ktime_add_ns(base, nsecs);
776f519b1a2SThomas Gleixner }
777f519b1a2SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_raw);
778f519b1a2SThomas Gleixner 
779f519b1a2SThomas Gleixner /**
780d6d29896SThomas Gleixner  * ktime_get_ts64 - get the monotonic clock in timespec64 format
781951ed4d3SMartin Schwidefsky  * @ts:		pointer to timespec variable
782951ed4d3SMartin Schwidefsky  *
783951ed4d3SMartin Schwidefsky  * The function calculates the monotonic clock from the realtime
784951ed4d3SMartin Schwidefsky  * clock and the wall_to_monotonic offset and stores the result
7855322e4c2SJohn Stultz  * in normalized timespec64 format in the variable pointed to by @ts.
786951ed4d3SMartin Schwidefsky  */
787d6d29896SThomas Gleixner void ktime_get_ts64(struct timespec64 *ts)
788951ed4d3SMartin Schwidefsky {
7893fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
790d6d29896SThomas Gleixner 	struct timespec64 tomono;
791ec145babSJohn Stultz 	s64 nsec;
792951ed4d3SMartin Schwidefsky 	unsigned int seq;
793951ed4d3SMartin Schwidefsky 
794951ed4d3SMartin Schwidefsky 	WARN_ON(timekeeping_suspended);
795951ed4d3SMartin Schwidefsky 
796951ed4d3SMartin Schwidefsky 	do {
7973fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
798d6d29896SThomas Gleixner 		ts->tv_sec = tk->xtime_sec;
799876e7881SPeter Zijlstra 		nsec = timekeeping_get_ns(&tk->tkr_mono);
8004e250fddSJohn Stultz 		tomono = tk->wall_to_monotonic;
801951ed4d3SMartin Schwidefsky 
8023fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
803951ed4d3SMartin Schwidefsky 
804d6d29896SThomas Gleixner 	ts->tv_sec += tomono.tv_sec;
805d6d29896SThomas Gleixner 	ts->tv_nsec = 0;
806d6d29896SThomas Gleixner 	timespec64_add_ns(ts, nsec + tomono.tv_nsec);
807951ed4d3SMartin Schwidefsky }
808d6d29896SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_ts64);
809951ed4d3SMartin Schwidefsky 
8109e3680b1SHeena Sirwani /**
8119e3680b1SHeena Sirwani  * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
8129e3680b1SHeena Sirwani  *
8139e3680b1SHeena Sirwani  * Returns the seconds portion of CLOCK_MONOTONIC with a single non
8149e3680b1SHeena Sirwani  * serialized read. tk->ktime_sec is of type 'unsigned long' so this
8159e3680b1SHeena Sirwani  * works on both 32 and 64 bit systems. On 32 bit systems the readout
8169e3680b1SHeena Sirwani  * covers ~136 years of uptime which should be enough to prevent
8179e3680b1SHeena Sirwani  * premature wrap arounds.
8189e3680b1SHeena Sirwani  */
8199e3680b1SHeena Sirwani time64_t ktime_get_seconds(void)
8209e3680b1SHeena Sirwani {
8219e3680b1SHeena Sirwani 	struct timekeeper *tk = &tk_core.timekeeper;
8229e3680b1SHeena Sirwani 
8239e3680b1SHeena Sirwani 	WARN_ON(timekeeping_suspended);
8249e3680b1SHeena Sirwani 	return tk->ktime_sec;
8259e3680b1SHeena Sirwani }
8269e3680b1SHeena Sirwani EXPORT_SYMBOL_GPL(ktime_get_seconds);
8279e3680b1SHeena Sirwani 
828dbe7aa62SHeena Sirwani /**
829dbe7aa62SHeena Sirwani  * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
830dbe7aa62SHeena Sirwani  *
831dbe7aa62SHeena Sirwani  * Returns the wall clock seconds since 1970. This replaces the
832dbe7aa62SHeena Sirwani  * get_seconds() interface which is not y2038 safe on 32bit systems.
833dbe7aa62SHeena Sirwani  *
834dbe7aa62SHeena Sirwani  * For 64bit systems the fast access to tk->xtime_sec is preserved. On
835dbe7aa62SHeena Sirwani  * 32bit systems the access must be protected with the sequence
836dbe7aa62SHeena Sirwani  * counter to provide "atomic" access to the 64bit tk->xtime_sec
837dbe7aa62SHeena Sirwani  * value.
838dbe7aa62SHeena Sirwani  */
839dbe7aa62SHeena Sirwani time64_t ktime_get_real_seconds(void)
840dbe7aa62SHeena Sirwani {
841dbe7aa62SHeena Sirwani 	struct timekeeper *tk = &tk_core.timekeeper;
842dbe7aa62SHeena Sirwani 	time64_t seconds;
843dbe7aa62SHeena Sirwani 	unsigned int seq;
844dbe7aa62SHeena Sirwani 
845dbe7aa62SHeena Sirwani 	if (IS_ENABLED(CONFIG_64BIT))
846dbe7aa62SHeena Sirwani 		return tk->xtime_sec;
847dbe7aa62SHeena Sirwani 
848dbe7aa62SHeena Sirwani 	do {
849dbe7aa62SHeena Sirwani 		seq = read_seqcount_begin(&tk_core.seq);
850dbe7aa62SHeena Sirwani 		seconds = tk->xtime_sec;
851dbe7aa62SHeena Sirwani 
852dbe7aa62SHeena Sirwani 	} while (read_seqcount_retry(&tk_core.seq, seq));
853dbe7aa62SHeena Sirwani 
854dbe7aa62SHeena Sirwani 	return seconds;
855dbe7aa62SHeena Sirwani }
856dbe7aa62SHeena Sirwani EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
857dbe7aa62SHeena Sirwani 
858e2c18e49SAlexander Gordeev #ifdef CONFIG_NTP_PPS
859e2c18e49SAlexander Gordeev 
860e2c18e49SAlexander Gordeev /**
861e2c18e49SAlexander Gordeev  * getnstime_raw_and_real - get day and raw monotonic time in timespec format
862e2c18e49SAlexander Gordeev  * @ts_raw:	pointer to the timespec to be set to raw monotonic time
863e2c18e49SAlexander Gordeev  * @ts_real:	pointer to the timespec to be set to the time of day
864e2c18e49SAlexander Gordeev  *
865e2c18e49SAlexander Gordeev  * This function reads both the time of day and raw monotonic time at the
866e2c18e49SAlexander Gordeev  * same time atomically and stores the resulting timestamps in timespec
867e2c18e49SAlexander Gordeev  * format.
868e2c18e49SAlexander Gordeev  */
869e2c18e49SAlexander Gordeev void getnstime_raw_and_real(struct timespec *ts_raw, struct timespec *ts_real)
870e2c18e49SAlexander Gordeev {
8713fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
872e2c18e49SAlexander Gordeev 	unsigned long seq;
873e2c18e49SAlexander Gordeev 	s64 nsecs_raw, nsecs_real;
874e2c18e49SAlexander Gordeev 
875e2c18e49SAlexander Gordeev 	WARN_ON_ONCE(timekeeping_suspended);
876e2c18e49SAlexander Gordeev 
877e2c18e49SAlexander Gordeev 	do {
8783fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
879e2c18e49SAlexander Gordeev 
8807d489d15SJohn Stultz 		*ts_raw = timespec64_to_timespec(tk->raw_time);
8814e250fddSJohn Stultz 		ts_real->tv_sec = tk->xtime_sec;
8821e75fa8bSJohn Stultz 		ts_real->tv_nsec = 0;
883e2c18e49SAlexander Gordeev 
8844a4ad80dSPeter Zijlstra 		nsecs_raw  = timekeeping_get_ns(&tk->tkr_raw);
885876e7881SPeter Zijlstra 		nsecs_real = timekeeping_get_ns(&tk->tkr_mono);
886e2c18e49SAlexander Gordeev 
8873fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
888e2c18e49SAlexander Gordeev 
889e2c18e49SAlexander Gordeev 	timespec_add_ns(ts_raw, nsecs_raw);
890e2c18e49SAlexander Gordeev 	timespec_add_ns(ts_real, nsecs_real);
891e2c18e49SAlexander Gordeev }
892e2c18e49SAlexander Gordeev EXPORT_SYMBOL(getnstime_raw_and_real);
893e2c18e49SAlexander Gordeev 
894e2c18e49SAlexander Gordeev #endif /* CONFIG_NTP_PPS */
895e2c18e49SAlexander Gordeev 
8968524070bSjohn stultz /**
8978524070bSjohn stultz  * do_gettimeofday - Returns the time of day in a timeval
8988524070bSjohn stultz  * @tv:		pointer to the timeval to be set
8998524070bSjohn stultz  *
900efd9ac86SGeert Uytterhoeven  * NOTE: Users should be converted to using getnstimeofday()
9018524070bSjohn stultz  */
9028524070bSjohn stultz void do_gettimeofday(struct timeval *tv)
9038524070bSjohn stultz {
904d6d29896SThomas Gleixner 	struct timespec64 now;
9058524070bSjohn stultz 
906d6d29896SThomas Gleixner 	getnstimeofday64(&now);
9078524070bSjohn stultz 	tv->tv_sec = now.tv_sec;
9088524070bSjohn stultz 	tv->tv_usec = now.tv_nsec/1000;
9098524070bSjohn stultz }
9108524070bSjohn stultz EXPORT_SYMBOL(do_gettimeofday);
911d239f49dSRichard Cochran 
9128524070bSjohn stultz /**
91321f7eca5Spang.xunlei  * do_settimeofday64 - Sets the time of day.
91421f7eca5Spang.xunlei  * @ts:     pointer to the timespec64 variable containing the new time
9158524070bSjohn stultz  *
9168524070bSjohn stultz  * Sets the time of day to the new time and update NTP and notify hrtimers
9178524070bSjohn stultz  */
91821f7eca5Spang.xunlei int do_settimeofday64(const struct timespec64 *ts)
9198524070bSjohn stultz {
9203fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
92121f7eca5Spang.xunlei 	struct timespec64 ts_delta, xt;
92292c1d3edSJohn Stultz 	unsigned long flags;
9238524070bSjohn stultz 
92421f7eca5Spang.xunlei 	if (!timespec64_valid_strict(ts))
9258524070bSjohn stultz 		return -EINVAL;
9268524070bSjohn stultz 
9279a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
9283fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
9298524070bSjohn stultz 
9304e250fddSJohn Stultz 	timekeeping_forward_now(tk);
9318524070bSjohn stultz 
9324e250fddSJohn Stultz 	xt = tk_xtime(tk);
93321f7eca5Spang.xunlei 	ts_delta.tv_sec = ts->tv_sec - xt.tv_sec;
93421f7eca5Spang.xunlei 	ts_delta.tv_nsec = ts->tv_nsec - xt.tv_nsec;
9351e75fa8bSJohn Stultz 
9367d489d15SJohn Stultz 	tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
9378524070bSjohn stultz 
93821f7eca5Spang.xunlei 	tk_set_xtime(tk, ts);
9391e75fa8bSJohn Stultz 
940780427f0SDavid Vrabel 	timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
9418524070bSjohn stultz 
9423fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
9439a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
9448524070bSjohn stultz 
9458524070bSjohn stultz 	/* signal hrtimers about time change */
9468524070bSjohn stultz 	clock_was_set();
9478524070bSjohn stultz 
9488524070bSjohn stultz 	return 0;
9498524070bSjohn stultz }
95021f7eca5Spang.xunlei EXPORT_SYMBOL(do_settimeofday64);
9518524070bSjohn stultz 
952c528f7c6SJohn Stultz /**
953c528f7c6SJohn Stultz  * timekeeping_inject_offset - Adds or subtracts from the current time.
954c528f7c6SJohn Stultz  * @tv:		pointer to the timespec variable containing the offset
955c528f7c6SJohn Stultz  *
956c528f7c6SJohn Stultz  * Adds or subtracts an offset value from the current time.
957c528f7c6SJohn Stultz  */
958c528f7c6SJohn Stultz int timekeeping_inject_offset(struct timespec *ts)
959c528f7c6SJohn Stultz {
9603fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
96192c1d3edSJohn Stultz 	unsigned long flags;
9627d489d15SJohn Stultz 	struct timespec64 ts64, tmp;
9634e8b1452SJohn Stultz 	int ret = 0;
964c528f7c6SJohn Stultz 
965c528f7c6SJohn Stultz 	if ((unsigned long)ts->tv_nsec >= NSEC_PER_SEC)
966c528f7c6SJohn Stultz 		return -EINVAL;
967c528f7c6SJohn Stultz 
9687d489d15SJohn Stultz 	ts64 = timespec_to_timespec64(*ts);
9697d489d15SJohn Stultz 
9709a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
9713fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
972c528f7c6SJohn Stultz 
9734e250fddSJohn Stultz 	timekeeping_forward_now(tk);
974c528f7c6SJohn Stultz 
9754e8b1452SJohn Stultz 	/* Make sure the proposed value is valid */
9767d489d15SJohn Stultz 	tmp = timespec64_add(tk_xtime(tk),  ts64);
9777d489d15SJohn Stultz 	if (!timespec64_valid_strict(&tmp)) {
9784e8b1452SJohn Stultz 		ret = -EINVAL;
9794e8b1452SJohn Stultz 		goto error;
9804e8b1452SJohn Stultz 	}
9811e75fa8bSJohn Stultz 
9827d489d15SJohn Stultz 	tk_xtime_add(tk, &ts64);
9837d489d15SJohn Stultz 	tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts64));
984c528f7c6SJohn Stultz 
9854e8b1452SJohn Stultz error: /* even if we error out, we forwarded the time, so call update */
986780427f0SDavid Vrabel 	timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
987c528f7c6SJohn Stultz 
9883fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
9899a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
990c528f7c6SJohn Stultz 
991c528f7c6SJohn Stultz 	/* signal hrtimers about time change */
992c528f7c6SJohn Stultz 	clock_was_set();
993c528f7c6SJohn Stultz 
9944e8b1452SJohn Stultz 	return ret;
995c528f7c6SJohn Stultz }
996c528f7c6SJohn Stultz EXPORT_SYMBOL(timekeeping_inject_offset);
997c528f7c6SJohn Stultz 
998cc244ddaSJohn Stultz 
999cc244ddaSJohn Stultz /**
1000cc244ddaSJohn Stultz  * timekeeping_get_tai_offset - Returns current TAI offset from UTC
1001cc244ddaSJohn Stultz  *
1002cc244ddaSJohn Stultz  */
1003cc244ddaSJohn Stultz s32 timekeeping_get_tai_offset(void)
1004cc244ddaSJohn Stultz {
10053fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
1006cc244ddaSJohn Stultz 	unsigned int seq;
1007cc244ddaSJohn Stultz 	s32 ret;
1008cc244ddaSJohn Stultz 
1009cc244ddaSJohn Stultz 	do {
10103fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
1011cc244ddaSJohn Stultz 		ret = tk->tai_offset;
10123fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
1013cc244ddaSJohn Stultz 
1014cc244ddaSJohn Stultz 	return ret;
1015cc244ddaSJohn Stultz }
1016cc244ddaSJohn Stultz 
1017cc244ddaSJohn Stultz /**
1018cc244ddaSJohn Stultz  * __timekeeping_set_tai_offset - Lock free worker function
1019cc244ddaSJohn Stultz  *
1020cc244ddaSJohn Stultz  */
1021dd5d70e8SFengguang Wu static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1022cc244ddaSJohn Stultz {
1023cc244ddaSJohn Stultz 	tk->tai_offset = tai_offset;
102404005f60SJohn Stultz 	tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1025cc244ddaSJohn Stultz }
1026cc244ddaSJohn Stultz 
1027cc244ddaSJohn Stultz /**
1028cc244ddaSJohn Stultz  * timekeeping_set_tai_offset - Sets the current TAI offset from UTC
1029cc244ddaSJohn Stultz  *
1030cc244ddaSJohn Stultz  */
1031cc244ddaSJohn Stultz void timekeeping_set_tai_offset(s32 tai_offset)
1032cc244ddaSJohn Stultz {
10333fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
1034cc244ddaSJohn Stultz 	unsigned long flags;
1035cc244ddaSJohn Stultz 
10369a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
10373fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
1038cc244ddaSJohn Stultz 	__timekeeping_set_tai_offset(tk, tai_offset);
1039f55c0760SJohn Stultz 	timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
10403fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
10419a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
10424e8f8b34SJohn Stultz 	clock_was_set();
1043cc244ddaSJohn Stultz }
1044cc244ddaSJohn Stultz 
10458524070bSjohn stultz /**
10468524070bSjohn stultz  * change_clocksource - Swaps clocksources if a new one is available
10478524070bSjohn stultz  *
10488524070bSjohn stultz  * Accumulates current time interval and initializes new clocksource
10498524070bSjohn stultz  */
105075c5158fSMartin Schwidefsky static int change_clocksource(void *data)
10518524070bSjohn stultz {
10523fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
10534614e6adSMagnus Damm 	struct clocksource *new, *old;
1054f695cf94SJohn Stultz 	unsigned long flags;
10558524070bSjohn stultz 
105675c5158fSMartin Schwidefsky 	new = (struct clocksource *) data;
10578524070bSjohn stultz 
10589a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
10593fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
1060f695cf94SJohn Stultz 
10614e250fddSJohn Stultz 	timekeeping_forward_now(tk);
106209ac369cSThomas Gleixner 	/*
106309ac369cSThomas Gleixner 	 * If the cs is in module, get a module reference. Succeeds
106409ac369cSThomas Gleixner 	 * for built-in code (owner == NULL) as well.
106509ac369cSThomas Gleixner 	 */
106609ac369cSThomas Gleixner 	if (try_module_get(new->owner)) {
106775c5158fSMartin Schwidefsky 		if (!new->enable || new->enable(new) == 0) {
1068876e7881SPeter Zijlstra 			old = tk->tkr_mono.clock;
10694e250fddSJohn Stultz 			tk_setup_internals(tk, new);
1070a0f7d48bSMartin Schwidefsky 			if (old->disable)
1071a0f7d48bSMartin Schwidefsky 				old->disable(old);
107209ac369cSThomas Gleixner 			module_put(old->owner);
107309ac369cSThomas Gleixner 		} else {
107409ac369cSThomas Gleixner 			module_put(new->owner);
107509ac369cSThomas Gleixner 		}
107675c5158fSMartin Schwidefsky 	}
1077780427f0SDavid Vrabel 	timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1078f695cf94SJohn Stultz 
10793fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
10809a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1081f695cf94SJohn Stultz 
108275c5158fSMartin Schwidefsky 	return 0;
108375c5158fSMartin Schwidefsky }
10844614e6adSMagnus Damm 
108575c5158fSMartin Schwidefsky /**
108675c5158fSMartin Schwidefsky  * timekeeping_notify - Install a new clock source
108775c5158fSMartin Schwidefsky  * @clock:		pointer to the clock source
108875c5158fSMartin Schwidefsky  *
108975c5158fSMartin Schwidefsky  * This function is called from clocksource.c after a new, better clock
109075c5158fSMartin Schwidefsky  * source has been registered. The caller holds the clocksource_mutex.
109175c5158fSMartin Schwidefsky  */
1092ba919d1cSThomas Gleixner int timekeeping_notify(struct clocksource *clock)
109375c5158fSMartin Schwidefsky {
10943fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
10954e250fddSJohn Stultz 
1096876e7881SPeter Zijlstra 	if (tk->tkr_mono.clock == clock)
1097ba919d1cSThomas Gleixner 		return 0;
109875c5158fSMartin Schwidefsky 	stop_machine(change_clocksource, clock, NULL);
10998524070bSjohn stultz 	tick_clock_notify();
1100876e7881SPeter Zijlstra 	return tk->tkr_mono.clock == clock ? 0 : -1;
11018524070bSjohn stultz }
110275c5158fSMartin Schwidefsky 
1103a40f262cSThomas Gleixner /**
1104cdba2ec5SJohn Stultz  * getrawmonotonic64 - Returns the raw monotonic time in a timespec
1105cdba2ec5SJohn Stultz  * @ts:		pointer to the timespec64 to be set
11062d42244aSJohn Stultz  *
11072d42244aSJohn Stultz  * Returns the raw monotonic time (completely un-modified by ntp)
11082d42244aSJohn Stultz  */
1109cdba2ec5SJohn Stultz void getrawmonotonic64(struct timespec64 *ts)
11102d42244aSJohn Stultz {
11113fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
11127d489d15SJohn Stultz 	struct timespec64 ts64;
11132d42244aSJohn Stultz 	unsigned long seq;
11142d42244aSJohn Stultz 	s64 nsecs;
11152d42244aSJohn Stultz 
11162d42244aSJohn Stultz 	do {
11173fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
11184a4ad80dSPeter Zijlstra 		nsecs = timekeeping_get_ns(&tk->tkr_raw);
11197d489d15SJohn Stultz 		ts64 = tk->raw_time;
11202d42244aSJohn Stultz 
11213fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
11222d42244aSJohn Stultz 
11237d489d15SJohn Stultz 	timespec64_add_ns(&ts64, nsecs);
1124cdba2ec5SJohn Stultz 	*ts = ts64;
11252d42244aSJohn Stultz }
1126cdba2ec5SJohn Stultz EXPORT_SYMBOL(getrawmonotonic64);
1127cdba2ec5SJohn Stultz 
11282d42244aSJohn Stultz 
11292d42244aSJohn Stultz /**
1130cf4fc6cbSLi Zefan  * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
11318524070bSjohn stultz  */
1132cf4fc6cbSLi Zefan int timekeeping_valid_for_hres(void)
11338524070bSjohn stultz {
11343fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
11358524070bSjohn stultz 	unsigned long seq;
11368524070bSjohn stultz 	int ret;
11378524070bSjohn stultz 
11388524070bSjohn stultz 	do {
11393fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
11408524070bSjohn stultz 
1141876e7881SPeter Zijlstra 		ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
11428524070bSjohn stultz 
11433fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
11448524070bSjohn stultz 
11458524070bSjohn stultz 	return ret;
11468524070bSjohn stultz }
11478524070bSjohn stultz 
11488524070bSjohn stultz /**
114998962465SJon Hunter  * timekeeping_max_deferment - Returns max time the clocksource can be deferred
115098962465SJon Hunter  */
115198962465SJon Hunter u64 timekeeping_max_deferment(void)
115298962465SJon Hunter {
11533fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
115470471f2fSJohn Stultz 	unsigned long seq;
115570471f2fSJohn Stultz 	u64 ret;
115642e71e81SJohn Stultz 
115770471f2fSJohn Stultz 	do {
11583fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
115970471f2fSJohn Stultz 
1160876e7881SPeter Zijlstra 		ret = tk->tkr_mono.clock->max_idle_ns;
116170471f2fSJohn Stultz 
11623fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
116370471f2fSJohn Stultz 
116470471f2fSJohn Stultz 	return ret;
116598962465SJon Hunter }
116698962465SJon Hunter 
116798962465SJon Hunter /**
1168d4f587c6SMartin Schwidefsky  * read_persistent_clock -  Return time from the persistent clock.
11698524070bSjohn stultz  *
11708524070bSjohn stultz  * Weak dummy function for arches that do not yet support it.
1171d4f587c6SMartin Schwidefsky  * Reads the time from the battery backed persistent clock.
1172d4f587c6SMartin Schwidefsky  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
11738524070bSjohn stultz  *
11748524070bSjohn stultz  *  XXX - Do be sure to remove it once all arches implement it.
11758524070bSjohn stultz  */
117652f5684cSGideon Israel Dsouza void __weak read_persistent_clock(struct timespec *ts)
11778524070bSjohn stultz {
1178d4f587c6SMartin Schwidefsky 	ts->tv_sec = 0;
1179d4f587c6SMartin Schwidefsky 	ts->tv_nsec = 0;
11808524070bSjohn stultz }
11818524070bSjohn stultz 
11822ee96632SXunlei Pang void __weak read_persistent_clock64(struct timespec64 *ts64)
11832ee96632SXunlei Pang {
11842ee96632SXunlei Pang 	struct timespec ts;
11852ee96632SXunlei Pang 
11862ee96632SXunlei Pang 	read_persistent_clock(&ts);
11872ee96632SXunlei Pang 	*ts64 = timespec_to_timespec64(ts);
11882ee96632SXunlei Pang }
11892ee96632SXunlei Pang 
119023970e38SMartin Schwidefsky /**
119123970e38SMartin Schwidefsky  * read_boot_clock -  Return time of the system start.
119223970e38SMartin Schwidefsky  *
119323970e38SMartin Schwidefsky  * Weak dummy function for arches that do not yet support it.
119423970e38SMartin Schwidefsky  * Function to read the exact time the system has been started.
119523970e38SMartin Schwidefsky  * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
119623970e38SMartin Schwidefsky  *
119723970e38SMartin Schwidefsky  *  XXX - Do be sure to remove it once all arches implement it.
119823970e38SMartin Schwidefsky  */
119952f5684cSGideon Israel Dsouza void __weak read_boot_clock(struct timespec *ts)
120023970e38SMartin Schwidefsky {
120123970e38SMartin Schwidefsky 	ts->tv_sec = 0;
120223970e38SMartin Schwidefsky 	ts->tv_nsec = 0;
120323970e38SMartin Schwidefsky }
120423970e38SMartin Schwidefsky 
12059a806ddbSXunlei Pang void __weak read_boot_clock64(struct timespec64 *ts64)
12069a806ddbSXunlei Pang {
12079a806ddbSXunlei Pang 	struct timespec ts;
12089a806ddbSXunlei Pang 
12099a806ddbSXunlei Pang 	read_boot_clock(&ts);
12109a806ddbSXunlei Pang 	*ts64 = timespec_to_timespec64(ts);
12119a806ddbSXunlei Pang }
12129a806ddbSXunlei Pang 
12130fa88cb4SXunlei Pang /* Flag for if timekeeping_resume() has injected sleeptime */
12140fa88cb4SXunlei Pang static bool sleeptime_injected;
12150fa88cb4SXunlei Pang 
12160fa88cb4SXunlei Pang /* Flag for if there is a persistent clock on this platform */
12170fa88cb4SXunlei Pang static bool persistent_clock_exists;
12180fa88cb4SXunlei Pang 
12198524070bSjohn stultz /*
12208524070bSjohn stultz  * timekeeping_init - Initializes the clocksource and common timekeeping values
12218524070bSjohn stultz  */
12228524070bSjohn stultz void __init timekeeping_init(void)
12238524070bSjohn stultz {
12243fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
1225155ec602SMartin Schwidefsky 	struct clocksource *clock;
12268524070bSjohn stultz 	unsigned long flags;
12277d489d15SJohn Stultz 	struct timespec64 now, boot, tmp;
1228d4f587c6SMartin Schwidefsky 
12292ee96632SXunlei Pang 	read_persistent_clock64(&now);
12307d489d15SJohn Stultz 	if (!timespec64_valid_strict(&now)) {
12314e8b1452SJohn Stultz 		pr_warn("WARNING: Persistent clock returned invalid value!\n"
12324e8b1452SJohn Stultz 			"         Check your CMOS/BIOS settings.\n");
12334e8b1452SJohn Stultz 		now.tv_sec = 0;
12344e8b1452SJohn Stultz 		now.tv_nsec = 0;
123531ade306SFeng Tang 	} else if (now.tv_sec || now.tv_nsec)
12360fa88cb4SXunlei Pang 		persistent_clock_exists = true;
12374e8b1452SJohn Stultz 
12389a806ddbSXunlei Pang 	read_boot_clock64(&boot);
12397d489d15SJohn Stultz 	if (!timespec64_valid_strict(&boot)) {
12404e8b1452SJohn Stultz 		pr_warn("WARNING: Boot clock returned invalid value!\n"
12414e8b1452SJohn Stultz 			"         Check your CMOS/BIOS settings.\n");
12424e8b1452SJohn Stultz 		boot.tv_sec = 0;
12434e8b1452SJohn Stultz 		boot.tv_nsec = 0;
12444e8b1452SJohn Stultz 	}
12458524070bSjohn stultz 
12469a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
12473fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
124806c017fdSJohn Stultz 	ntp_init();
124906c017fdSJohn Stultz 
1250f1b82746SMartin Schwidefsky 	clock = clocksource_default_clock();
1251a0f7d48bSMartin Schwidefsky 	if (clock->enable)
1252a0f7d48bSMartin Schwidefsky 		clock->enable(clock);
12534e250fddSJohn Stultz 	tk_setup_internals(tk, clock);
12548524070bSjohn stultz 
12554e250fddSJohn Stultz 	tk_set_xtime(tk, &now);
12564e250fddSJohn Stultz 	tk->raw_time.tv_sec = 0;
12574e250fddSJohn Stultz 	tk->raw_time.tv_nsec = 0;
12581e75fa8bSJohn Stultz 	if (boot.tv_sec == 0 && boot.tv_nsec == 0)
12594e250fddSJohn Stultz 		boot = tk_xtime(tk);
12601e75fa8bSJohn Stultz 
12617d489d15SJohn Stultz 	set_normalized_timespec64(&tmp, -boot.tv_sec, -boot.tv_nsec);
12624e250fddSJohn Stultz 	tk_set_wall_to_mono(tk, tmp);
12636d0ef903SJohn Stultz 
1264f111adfdSThomas Gleixner 	timekeeping_update(tk, TK_MIRROR);
126548cdc135SThomas Gleixner 
12663fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
12679a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
12688524070bSjohn stultz }
12698524070bSjohn stultz 
1270264bb3f7SXunlei Pang /* time in seconds when suspend began for persistent clock */
12717d489d15SJohn Stultz static struct timespec64 timekeeping_suspend_time;
12728524070bSjohn stultz 
12738524070bSjohn stultz /**
1274304529b1SJohn Stultz  * __timekeeping_inject_sleeptime - Internal function to add sleep interval
1275304529b1SJohn Stultz  * @delta: pointer to a timespec delta value
1276304529b1SJohn Stultz  *
1277304529b1SJohn Stultz  * Takes a timespec offset measuring a suspend interval and properly
1278304529b1SJohn Stultz  * adds the sleep offset to the timekeeping variables.
1279304529b1SJohn Stultz  */
1280f726a697SJohn Stultz static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
12817d489d15SJohn Stultz 					   struct timespec64 *delta)
1282304529b1SJohn Stultz {
12837d489d15SJohn Stultz 	if (!timespec64_valid_strict(delta)) {
12846d9bcb62SJohn Stultz 		printk_deferred(KERN_WARNING
12856d9bcb62SJohn Stultz 				"__timekeeping_inject_sleeptime: Invalid "
1286cb5de2f8SJohn Stultz 				"sleep delta value!\n");
1287cb5de2f8SJohn Stultz 		return;
1288cb5de2f8SJohn Stultz 	}
1289f726a697SJohn Stultz 	tk_xtime_add(tk, delta);
12907d489d15SJohn Stultz 	tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
129147da70d3SThomas Gleixner 	tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
12925c83545fSColin Cross 	tk_debug_account_sleep_time(delta);
1293304529b1SJohn Stultz }
1294304529b1SJohn Stultz 
12957f298139SXunlei Pang #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1296304529b1SJohn Stultz /**
12970fa88cb4SXunlei Pang  * We have three kinds of time sources to use for sleep time
12980fa88cb4SXunlei Pang  * injection, the preference order is:
12990fa88cb4SXunlei Pang  * 1) non-stop clocksource
13000fa88cb4SXunlei Pang  * 2) persistent clock (ie: RTC accessible when irqs are off)
13010fa88cb4SXunlei Pang  * 3) RTC
13020fa88cb4SXunlei Pang  *
13030fa88cb4SXunlei Pang  * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
13040fa88cb4SXunlei Pang  * If system has neither 1) nor 2), 3) will be used finally.
13050fa88cb4SXunlei Pang  *
13060fa88cb4SXunlei Pang  *
13070fa88cb4SXunlei Pang  * If timekeeping has injected sleeptime via either 1) or 2),
13080fa88cb4SXunlei Pang  * 3) becomes needless, so in this case we don't need to call
13090fa88cb4SXunlei Pang  * rtc_resume(), and this is what timekeeping_rtc_skipresume()
13100fa88cb4SXunlei Pang  * means.
13110fa88cb4SXunlei Pang  */
13120fa88cb4SXunlei Pang bool timekeeping_rtc_skipresume(void)
13130fa88cb4SXunlei Pang {
13140fa88cb4SXunlei Pang 	return sleeptime_injected;
13150fa88cb4SXunlei Pang }
13160fa88cb4SXunlei Pang 
13170fa88cb4SXunlei Pang /**
13180fa88cb4SXunlei Pang  * 1) can be determined whether to use or not only when doing
13190fa88cb4SXunlei Pang  * timekeeping_resume() which is invoked after rtc_suspend(),
13200fa88cb4SXunlei Pang  * so we can't skip rtc_suspend() surely if system has 1).
13210fa88cb4SXunlei Pang  *
13220fa88cb4SXunlei Pang  * But if system has 2), 2) will definitely be used, so in this
13230fa88cb4SXunlei Pang  * case we don't need to call rtc_suspend(), and this is what
13240fa88cb4SXunlei Pang  * timekeeping_rtc_skipsuspend() means.
13250fa88cb4SXunlei Pang  */
13260fa88cb4SXunlei Pang bool timekeeping_rtc_skipsuspend(void)
13270fa88cb4SXunlei Pang {
13280fa88cb4SXunlei Pang 	return persistent_clock_exists;
13290fa88cb4SXunlei Pang }
13300fa88cb4SXunlei Pang 
13310fa88cb4SXunlei Pang /**
133204d90890Spang.xunlei  * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
133304d90890Spang.xunlei  * @delta: pointer to a timespec64 delta value
1334304529b1SJohn Stultz  *
13352ee96632SXunlei Pang  * This hook is for architectures that cannot support read_persistent_clock64
1336304529b1SJohn Stultz  * because their RTC/persistent clock is only accessible when irqs are enabled.
13370fa88cb4SXunlei Pang  * and also don't have an effective nonstop clocksource.
1338304529b1SJohn Stultz  *
1339304529b1SJohn Stultz  * This function should only be called by rtc_resume(), and allows
1340304529b1SJohn Stultz  * a suspend offset to be injected into the timekeeping values.
1341304529b1SJohn Stultz  */
134204d90890Spang.xunlei void timekeeping_inject_sleeptime64(struct timespec64 *delta)
1343304529b1SJohn Stultz {
13443fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
134592c1d3edSJohn Stultz 	unsigned long flags;
1346304529b1SJohn Stultz 
13479a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
13483fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
134970471f2fSJohn Stultz 
13504e250fddSJohn Stultz 	timekeeping_forward_now(tk);
1351304529b1SJohn Stultz 
135204d90890Spang.xunlei 	__timekeeping_inject_sleeptime(tk, delta);
1353304529b1SJohn Stultz 
1354780427f0SDavid Vrabel 	timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1355304529b1SJohn Stultz 
13563fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
13579a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1358304529b1SJohn Stultz 
1359304529b1SJohn Stultz 	/* signal hrtimers about time change */
1360304529b1SJohn Stultz 	clock_was_set();
1361304529b1SJohn Stultz }
13627f298139SXunlei Pang #endif
1363304529b1SJohn Stultz 
1364304529b1SJohn Stultz /**
13658524070bSjohn stultz  * timekeeping_resume - Resumes the generic timekeeping subsystem.
13668524070bSjohn stultz  */
1367124cf911SRafael J. Wysocki void timekeeping_resume(void)
13688524070bSjohn stultz {
13693fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
1370876e7881SPeter Zijlstra 	struct clocksource *clock = tk->tkr_mono.clock;
137192c1d3edSJohn Stultz 	unsigned long flags;
13727d489d15SJohn Stultz 	struct timespec64 ts_new, ts_delta;
1373e445cf1cSFeng Tang 	cycle_t cycle_now, cycle_delta;
1374d4f587c6SMartin Schwidefsky 
13750fa88cb4SXunlei Pang 	sleeptime_injected = false;
13762ee96632SXunlei Pang 	read_persistent_clock64(&ts_new);
13778524070bSjohn stultz 
1378adc78e6bSRafael J. Wysocki 	clockevents_resume();
1379d10ff3fbSThomas Gleixner 	clocksource_resume();
1380d10ff3fbSThomas Gleixner 
13819a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
13823fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
13838524070bSjohn stultz 
1384e445cf1cSFeng Tang 	/*
1385e445cf1cSFeng Tang 	 * After system resumes, we need to calculate the suspended time and
1386e445cf1cSFeng Tang 	 * compensate it for the OS time. There are 3 sources that could be
1387e445cf1cSFeng Tang 	 * used: Nonstop clocksource during suspend, persistent clock and rtc
1388e445cf1cSFeng Tang 	 * device.
1389e445cf1cSFeng Tang 	 *
1390e445cf1cSFeng Tang 	 * One specific platform may have 1 or 2 or all of them, and the
1391e445cf1cSFeng Tang 	 * preference will be:
1392e445cf1cSFeng Tang 	 *	suspend-nonstop clocksource -> persistent clock -> rtc
1393e445cf1cSFeng Tang 	 * The less preferred source will only be tried if there is no better
1394e445cf1cSFeng Tang 	 * usable source. The rtc part is handled separately in rtc core code.
1395e445cf1cSFeng Tang 	 */
1396876e7881SPeter Zijlstra 	cycle_now = tk->tkr_mono.read(clock);
1397e445cf1cSFeng Tang 	if ((clock->flags & CLOCK_SOURCE_SUSPEND_NONSTOP) &&
1398876e7881SPeter Zijlstra 		cycle_now > tk->tkr_mono.cycle_last) {
1399e445cf1cSFeng Tang 		u64 num, max = ULLONG_MAX;
1400e445cf1cSFeng Tang 		u32 mult = clock->mult;
1401e445cf1cSFeng Tang 		u32 shift = clock->shift;
1402e445cf1cSFeng Tang 		s64 nsec = 0;
1403e445cf1cSFeng Tang 
1404876e7881SPeter Zijlstra 		cycle_delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last,
1405876e7881SPeter Zijlstra 						tk->tkr_mono.mask);
1406e445cf1cSFeng Tang 
1407e445cf1cSFeng Tang 		/*
1408e445cf1cSFeng Tang 		 * "cycle_delta * mutl" may cause 64 bits overflow, if the
1409e445cf1cSFeng Tang 		 * suspended time is too long. In that case we need do the
1410e445cf1cSFeng Tang 		 * 64 bits math carefully
1411e445cf1cSFeng Tang 		 */
1412e445cf1cSFeng Tang 		do_div(max, mult);
1413e445cf1cSFeng Tang 		if (cycle_delta > max) {
1414e445cf1cSFeng Tang 			num = div64_u64(cycle_delta, max);
1415e445cf1cSFeng Tang 			nsec = (((u64) max * mult) >> shift) * num;
1416e445cf1cSFeng Tang 			cycle_delta -= num * max;
14178524070bSjohn stultz 		}
1418e445cf1cSFeng Tang 		nsec += ((u64) cycle_delta * mult) >> shift;
1419e445cf1cSFeng Tang 
14207d489d15SJohn Stultz 		ts_delta = ns_to_timespec64(nsec);
14210fa88cb4SXunlei Pang 		sleeptime_injected = true;
14227d489d15SJohn Stultz 	} else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
14237d489d15SJohn Stultz 		ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
14240fa88cb4SXunlei Pang 		sleeptime_injected = true;
1425e445cf1cSFeng Tang 	}
1426e445cf1cSFeng Tang 
14270fa88cb4SXunlei Pang 	if (sleeptime_injected)
1428e445cf1cSFeng Tang 		__timekeeping_inject_sleeptime(tk, &ts_delta);
1429e445cf1cSFeng Tang 
1430e445cf1cSFeng Tang 	/* Re-base the last cycle value */
1431876e7881SPeter Zijlstra 	tk->tkr_mono.cycle_last = cycle_now;
14324a4ad80dSPeter Zijlstra 	tk->tkr_raw.cycle_last  = cycle_now;
14334a4ad80dSPeter Zijlstra 
14344e250fddSJohn Stultz 	tk->ntp_error = 0;
14358524070bSjohn stultz 	timekeeping_suspended = 0;
1436780427f0SDavid Vrabel 	timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
14373fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
14389a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
14398524070bSjohn stultz 
14408524070bSjohn stultz 	touch_softlockup_watchdog();
14418524070bSjohn stultz 
14424ffee521SThomas Gleixner 	tick_resume();
1443b12a03ceSThomas Gleixner 	hrtimers_resume();
14448524070bSjohn stultz }
14458524070bSjohn stultz 
1446124cf911SRafael J. Wysocki int timekeeping_suspend(void)
14478524070bSjohn stultz {
14483fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
144992c1d3edSJohn Stultz 	unsigned long flags;
14507d489d15SJohn Stultz 	struct timespec64		delta, delta_delta;
14517d489d15SJohn Stultz 	static struct timespec64	old_delta;
14528524070bSjohn stultz 
14532ee96632SXunlei Pang 	read_persistent_clock64(&timekeeping_suspend_time);
14543be90950SThomas Gleixner 
14550d6bd995SZoran Markovic 	/*
14560d6bd995SZoran Markovic 	 * On some systems the persistent_clock can not be detected at
14570d6bd995SZoran Markovic 	 * timekeeping_init by its return value, so if we see a valid
14580d6bd995SZoran Markovic 	 * value returned, update the persistent_clock_exists flag.
14590d6bd995SZoran Markovic 	 */
14600d6bd995SZoran Markovic 	if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
14610fa88cb4SXunlei Pang 		persistent_clock_exists = true;
14620d6bd995SZoran Markovic 
14639a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
14643fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
14654e250fddSJohn Stultz 	timekeeping_forward_now(tk);
14668524070bSjohn stultz 	timekeeping_suspended = 1;
1467cb33217bSJohn Stultz 
14680fa88cb4SXunlei Pang 	if (persistent_clock_exists) {
1469cb33217bSJohn Stultz 		/*
1470cb33217bSJohn Stultz 		 * To avoid drift caused by repeated suspend/resumes,
1471cb33217bSJohn Stultz 		 * which each can add ~1 second drift error,
1472cb33217bSJohn Stultz 		 * try to compensate so the difference in system time
1473cb33217bSJohn Stultz 		 * and persistent_clock time stays close to constant.
1474cb33217bSJohn Stultz 		 */
14757d489d15SJohn Stultz 		delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
14767d489d15SJohn Stultz 		delta_delta = timespec64_sub(delta, old_delta);
1477cb33217bSJohn Stultz 		if (abs(delta_delta.tv_sec) >= 2) {
1478cb33217bSJohn Stultz 			/*
1479cb33217bSJohn Stultz 			 * if delta_delta is too large, assume time correction
1480264bb3f7SXunlei Pang 			 * has occurred and set old_delta to the current delta.
1481cb33217bSJohn Stultz 			 */
1482cb33217bSJohn Stultz 			old_delta = delta;
1483cb33217bSJohn Stultz 		} else {
1484cb33217bSJohn Stultz 			/* Otherwise try to adjust old_system to compensate */
1485cb33217bSJohn Stultz 			timekeeping_suspend_time =
14867d489d15SJohn Stultz 				timespec64_add(timekeeping_suspend_time, delta_delta);
1487cb33217bSJohn Stultz 		}
1488264bb3f7SXunlei Pang 	}
1489330a1617SJohn Stultz 
1490330a1617SJohn Stultz 	timekeeping_update(tk, TK_MIRROR);
1491060407aeSRafael J. Wysocki 	halt_fast_timekeeper(tk);
14923fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
14939a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
14948524070bSjohn stultz 
14954ffee521SThomas Gleixner 	tick_suspend();
1496c54a42b1SMagnus Damm 	clocksource_suspend();
1497adc78e6bSRafael J. Wysocki 	clockevents_suspend();
14988524070bSjohn stultz 
14998524070bSjohn stultz 	return 0;
15008524070bSjohn stultz }
15018524070bSjohn stultz 
15028524070bSjohn stultz /* sysfs resume/suspend bits for timekeeping */
1503e1a85b2cSRafael J. Wysocki static struct syscore_ops timekeeping_syscore_ops = {
15048524070bSjohn stultz 	.resume		= timekeeping_resume,
15058524070bSjohn stultz 	.suspend	= timekeeping_suspend,
15068524070bSjohn stultz };
15078524070bSjohn stultz 
1508e1a85b2cSRafael J. Wysocki static int __init timekeeping_init_ops(void)
15098524070bSjohn stultz {
1510e1a85b2cSRafael J. Wysocki 	register_syscore_ops(&timekeeping_syscore_ops);
1511e1a85b2cSRafael J. Wysocki 	return 0;
15128524070bSjohn stultz }
1513e1a85b2cSRafael J. Wysocki device_initcall(timekeeping_init_ops);
15148524070bSjohn stultz 
15158524070bSjohn stultz /*
1516dc491596SJohn Stultz  * Apply a multiplier adjustment to the timekeeper
15178524070bSjohn stultz  */
1518dc491596SJohn Stultz static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1519dc491596SJohn Stultz 							 s64 offset,
1520dc491596SJohn Stultz 							 bool negative,
1521dc491596SJohn Stultz 							 int adj_scale)
15228524070bSjohn stultz {
1523dc491596SJohn Stultz 	s64 interval = tk->cycle_interval;
1524dc491596SJohn Stultz 	s32 mult_adj = 1;
15258524070bSjohn stultz 
1526dc491596SJohn Stultz 	if (negative) {
1527dc491596SJohn Stultz 		mult_adj = -mult_adj;
15288524070bSjohn stultz 		interval = -interval;
15298524070bSjohn stultz 		offset  = -offset;
15301d17d174SIngo Molnar 	}
1531dc491596SJohn Stultz 	mult_adj <<= adj_scale;
1532dc491596SJohn Stultz 	interval <<= adj_scale;
1533dc491596SJohn Stultz 	offset <<= adj_scale;
15348524070bSjohn stultz 
1535c2bc1111SJohn Stultz 	/*
1536c2bc1111SJohn Stultz 	 * So the following can be confusing.
1537c2bc1111SJohn Stultz 	 *
1538dc491596SJohn Stultz 	 * To keep things simple, lets assume mult_adj == 1 for now.
1539c2bc1111SJohn Stultz 	 *
1540dc491596SJohn Stultz 	 * When mult_adj != 1, remember that the interval and offset values
1541c2bc1111SJohn Stultz 	 * have been appropriately scaled so the math is the same.
1542c2bc1111SJohn Stultz 	 *
1543c2bc1111SJohn Stultz 	 * The basic idea here is that we're increasing the multiplier
1544c2bc1111SJohn Stultz 	 * by one, this causes the xtime_interval to be incremented by
1545c2bc1111SJohn Stultz 	 * one cycle_interval. This is because:
1546c2bc1111SJohn Stultz 	 *	xtime_interval = cycle_interval * mult
1547c2bc1111SJohn Stultz 	 * So if mult is being incremented by one:
1548c2bc1111SJohn Stultz 	 *	xtime_interval = cycle_interval * (mult + 1)
1549c2bc1111SJohn Stultz 	 * Its the same as:
1550c2bc1111SJohn Stultz 	 *	xtime_interval = (cycle_interval * mult) + cycle_interval
1551c2bc1111SJohn Stultz 	 * Which can be shortened to:
1552c2bc1111SJohn Stultz 	 *	xtime_interval += cycle_interval
1553c2bc1111SJohn Stultz 	 *
1554c2bc1111SJohn Stultz 	 * So offset stores the non-accumulated cycles. Thus the current
1555c2bc1111SJohn Stultz 	 * time (in shifted nanoseconds) is:
1556c2bc1111SJohn Stultz 	 *	now = (offset * adj) + xtime_nsec
1557c2bc1111SJohn Stultz 	 * Now, even though we're adjusting the clock frequency, we have
1558c2bc1111SJohn Stultz 	 * to keep time consistent. In other words, we can't jump back
1559c2bc1111SJohn Stultz 	 * in time, and we also want to avoid jumping forward in time.
1560c2bc1111SJohn Stultz 	 *
1561c2bc1111SJohn Stultz 	 * So given the same offset value, we need the time to be the same
1562c2bc1111SJohn Stultz 	 * both before and after the freq adjustment.
1563c2bc1111SJohn Stultz 	 *	now = (offset * adj_1) + xtime_nsec_1
1564c2bc1111SJohn Stultz 	 *	now = (offset * adj_2) + xtime_nsec_2
1565c2bc1111SJohn Stultz 	 * So:
1566c2bc1111SJohn Stultz 	 *	(offset * adj_1) + xtime_nsec_1 =
1567c2bc1111SJohn Stultz 	 *		(offset * adj_2) + xtime_nsec_2
1568c2bc1111SJohn Stultz 	 * And we know:
1569c2bc1111SJohn Stultz 	 *	adj_2 = adj_1 + 1
1570c2bc1111SJohn Stultz 	 * So:
1571c2bc1111SJohn Stultz 	 *	(offset * adj_1) + xtime_nsec_1 =
1572c2bc1111SJohn Stultz 	 *		(offset * (adj_1+1)) + xtime_nsec_2
1573c2bc1111SJohn Stultz 	 *	(offset * adj_1) + xtime_nsec_1 =
1574c2bc1111SJohn Stultz 	 *		(offset * adj_1) + offset + xtime_nsec_2
1575c2bc1111SJohn Stultz 	 * Canceling the sides:
1576c2bc1111SJohn Stultz 	 *	xtime_nsec_1 = offset + xtime_nsec_2
1577c2bc1111SJohn Stultz 	 * Which gives us:
1578c2bc1111SJohn Stultz 	 *	xtime_nsec_2 = xtime_nsec_1 - offset
1579c2bc1111SJohn Stultz 	 * Which simplfies to:
1580c2bc1111SJohn Stultz 	 *	xtime_nsec -= offset
1581c2bc1111SJohn Stultz 	 *
1582c2bc1111SJohn Stultz 	 * XXX - TODO: Doc ntp_error calculation.
1583c2bc1111SJohn Stultz 	 */
1584876e7881SPeter Zijlstra 	if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
15856067dc5aSpang.xunlei 		/* NTP adjustment caused clocksource mult overflow */
15866067dc5aSpang.xunlei 		WARN_ON_ONCE(1);
15876067dc5aSpang.xunlei 		return;
15886067dc5aSpang.xunlei 	}
15896067dc5aSpang.xunlei 
1590876e7881SPeter Zijlstra 	tk->tkr_mono.mult += mult_adj;
1591f726a697SJohn Stultz 	tk->xtime_interval += interval;
1592876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec -= offset;
1593f726a697SJohn Stultz 	tk->ntp_error -= (interval - offset) << tk->ntp_error_shift;
1594dc491596SJohn Stultz }
15952a8c0883SJohn Stultz 
1596dc491596SJohn Stultz /*
1597dc491596SJohn Stultz  * Calculate the multiplier adjustment needed to match the frequency
1598dc491596SJohn Stultz  * specified by NTP
1599dc491596SJohn Stultz  */
1600dc491596SJohn Stultz static __always_inline void timekeeping_freqadjust(struct timekeeper *tk,
1601dc491596SJohn Stultz 							s64 offset)
1602dc491596SJohn Stultz {
1603dc491596SJohn Stultz 	s64 interval = tk->cycle_interval;
1604dc491596SJohn Stultz 	s64 xinterval = tk->xtime_interval;
1605dc491596SJohn Stultz 	s64 tick_error;
1606dc491596SJohn Stultz 	bool negative;
1607dc491596SJohn Stultz 	u32 adj;
1608dc491596SJohn Stultz 
1609dc491596SJohn Stultz 	/* Remove any current error adj from freq calculation */
1610dc491596SJohn Stultz 	if (tk->ntp_err_mult)
1611dc491596SJohn Stultz 		xinterval -= tk->cycle_interval;
1612dc491596SJohn Stultz 
1613375f45b5SJohn Stultz 	tk->ntp_tick = ntp_tick_length();
1614375f45b5SJohn Stultz 
1615dc491596SJohn Stultz 	/* Calculate current error per tick */
1616dc491596SJohn Stultz 	tick_error = ntp_tick_length() >> tk->ntp_error_shift;
1617dc491596SJohn Stultz 	tick_error -= (xinterval + tk->xtime_remainder);
1618dc491596SJohn Stultz 
1619dc491596SJohn Stultz 	/* Don't worry about correcting it if its small */
1620dc491596SJohn Stultz 	if (likely((tick_error >= 0) && (tick_error <= interval)))
1621dc491596SJohn Stultz 		return;
1622dc491596SJohn Stultz 
1623dc491596SJohn Stultz 	/* preserve the direction of correction */
1624dc491596SJohn Stultz 	negative = (tick_error < 0);
1625dc491596SJohn Stultz 
1626dc491596SJohn Stultz 	/* Sort out the magnitude of the correction */
1627dc491596SJohn Stultz 	tick_error = abs(tick_error);
1628dc491596SJohn Stultz 	for (adj = 0; tick_error > interval; adj++)
1629dc491596SJohn Stultz 		tick_error >>= 1;
1630dc491596SJohn Stultz 
1631dc491596SJohn Stultz 	/* scale the corrections */
1632dc491596SJohn Stultz 	timekeeping_apply_adjustment(tk, offset, negative, adj);
1633dc491596SJohn Stultz }
1634dc491596SJohn Stultz 
1635dc491596SJohn Stultz /*
1636dc491596SJohn Stultz  * Adjust the timekeeper's multiplier to the correct frequency
1637dc491596SJohn Stultz  * and also to reduce the accumulated error value.
1638dc491596SJohn Stultz  */
1639dc491596SJohn Stultz static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
1640dc491596SJohn Stultz {
1641dc491596SJohn Stultz 	/* Correct for the current frequency error */
1642dc491596SJohn Stultz 	timekeeping_freqadjust(tk, offset);
1643dc491596SJohn Stultz 
1644dc491596SJohn Stultz 	/* Next make a small adjustment to fix any cumulative error */
1645dc491596SJohn Stultz 	if (!tk->ntp_err_mult && (tk->ntp_error > 0)) {
1646dc491596SJohn Stultz 		tk->ntp_err_mult = 1;
1647dc491596SJohn Stultz 		timekeeping_apply_adjustment(tk, offset, 0, 0);
1648dc491596SJohn Stultz 	} else if (tk->ntp_err_mult && (tk->ntp_error <= 0)) {
1649dc491596SJohn Stultz 		/* Undo any existing error adjustment */
1650dc491596SJohn Stultz 		timekeeping_apply_adjustment(tk, offset, 1, 0);
1651dc491596SJohn Stultz 		tk->ntp_err_mult = 0;
1652dc491596SJohn Stultz 	}
1653dc491596SJohn Stultz 
1654876e7881SPeter Zijlstra 	if (unlikely(tk->tkr_mono.clock->maxadj &&
1655876e7881SPeter Zijlstra 		(abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
1656876e7881SPeter Zijlstra 			> tk->tkr_mono.clock->maxadj))) {
1657dc491596SJohn Stultz 		printk_once(KERN_WARNING
1658dc491596SJohn Stultz 			"Adjusting %s more than 11%% (%ld vs %ld)\n",
1659876e7881SPeter Zijlstra 			tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
1660876e7881SPeter Zijlstra 			(long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
1661dc491596SJohn Stultz 	}
1662dc491596SJohn Stultz 
16632a8c0883SJohn Stultz 	/*
16642a8c0883SJohn Stultz 	 * It may be possible that when we entered this function, xtime_nsec
16652a8c0883SJohn Stultz 	 * was very small.  Further, if we're slightly speeding the clocksource
16662a8c0883SJohn Stultz 	 * in the code above, its possible the required corrective factor to
16672a8c0883SJohn Stultz 	 * xtime_nsec could cause it to underflow.
16682a8c0883SJohn Stultz 	 *
16692a8c0883SJohn Stultz 	 * Now, since we already accumulated the second, cannot simply roll
16702a8c0883SJohn Stultz 	 * the accumulated second back, since the NTP subsystem has been
16712a8c0883SJohn Stultz 	 * notified via second_overflow. So instead we push xtime_nsec forward
16722a8c0883SJohn Stultz 	 * by the amount we underflowed, and add that amount into the error.
16732a8c0883SJohn Stultz 	 *
16742a8c0883SJohn Stultz 	 * We'll correct this error next time through this function, when
16752a8c0883SJohn Stultz 	 * xtime_nsec is not as small.
16762a8c0883SJohn Stultz 	 */
1677876e7881SPeter Zijlstra 	if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
1678876e7881SPeter Zijlstra 		s64 neg = -(s64)tk->tkr_mono.xtime_nsec;
1679876e7881SPeter Zijlstra 		tk->tkr_mono.xtime_nsec = 0;
1680f726a697SJohn Stultz 		tk->ntp_error += neg << tk->ntp_error_shift;
16812a8c0883SJohn Stultz 	}
16828524070bSjohn stultz }
16838524070bSjohn stultz 
16848524070bSjohn stultz /**
16851f4f9487SJohn Stultz  * accumulate_nsecs_to_secs - Accumulates nsecs into secs
16861f4f9487SJohn Stultz  *
16871f4f9487SJohn Stultz  * Helper function that accumulates a the nsecs greater then a second
16881f4f9487SJohn Stultz  * from the xtime_nsec field to the xtime_secs field.
16891f4f9487SJohn Stultz  * It also calls into the NTP code to handle leapsecond processing.
16901f4f9487SJohn Stultz  *
16911f4f9487SJohn Stultz  */
1692780427f0SDavid Vrabel static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
16931f4f9487SJohn Stultz {
1694876e7881SPeter Zijlstra 	u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
16955258d3f2SJohn Stultz 	unsigned int clock_set = 0;
16961f4f9487SJohn Stultz 
1697876e7881SPeter Zijlstra 	while (tk->tkr_mono.xtime_nsec >= nsecps) {
16981f4f9487SJohn Stultz 		int leap;
16991f4f9487SJohn Stultz 
1700876e7881SPeter Zijlstra 		tk->tkr_mono.xtime_nsec -= nsecps;
17011f4f9487SJohn Stultz 		tk->xtime_sec++;
17021f4f9487SJohn Stultz 
17031f4f9487SJohn Stultz 		/* Figure out if its a leap sec and apply if needed */
17041f4f9487SJohn Stultz 		leap = second_overflow(tk->xtime_sec);
17056d0ef903SJohn Stultz 		if (unlikely(leap)) {
17067d489d15SJohn Stultz 			struct timespec64 ts;
17071f4f9487SJohn Stultz 
17086d0ef903SJohn Stultz 			tk->xtime_sec += leap;
17096d0ef903SJohn Stultz 
17106d0ef903SJohn Stultz 			ts.tv_sec = leap;
17116d0ef903SJohn Stultz 			ts.tv_nsec = 0;
17126d0ef903SJohn Stultz 			tk_set_wall_to_mono(tk,
17137d489d15SJohn Stultz 				timespec64_sub(tk->wall_to_monotonic, ts));
17146d0ef903SJohn Stultz 
1715cc244ddaSJohn Stultz 			__timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
1716cc244ddaSJohn Stultz 
17175258d3f2SJohn Stultz 			clock_set = TK_CLOCK_WAS_SET;
17186d0ef903SJohn Stultz 		}
17191f4f9487SJohn Stultz 	}
17205258d3f2SJohn Stultz 	return clock_set;
17211f4f9487SJohn Stultz }
17221f4f9487SJohn Stultz 
17231f4f9487SJohn Stultz /**
1724a092ff0fSjohn stultz  * logarithmic_accumulation - shifted accumulation of cycles
1725a092ff0fSjohn stultz  *
1726a092ff0fSjohn stultz  * This functions accumulates a shifted interval of cycles into
1727a092ff0fSjohn stultz  * into a shifted interval nanoseconds. Allows for O(log) accumulation
1728a092ff0fSjohn stultz  * loop.
1729a092ff0fSjohn stultz  *
1730a092ff0fSjohn stultz  * Returns the unconsumed cycles.
1731a092ff0fSjohn stultz  */
1732f726a697SJohn Stultz static cycle_t logarithmic_accumulation(struct timekeeper *tk, cycle_t offset,
17335258d3f2SJohn Stultz 						u32 shift,
17345258d3f2SJohn Stultz 						unsigned int *clock_set)
1735a092ff0fSjohn stultz {
173623a9537aSThomas Gleixner 	cycle_t interval = tk->cycle_interval << shift;
1737deda2e81SJason Wessel 	u64 raw_nsecs;
1738a092ff0fSjohn stultz 
1739f726a697SJohn Stultz 	/* If the offset is smaller then a shifted interval, do nothing */
174023a9537aSThomas Gleixner 	if (offset < interval)
1741a092ff0fSjohn stultz 		return offset;
1742a092ff0fSjohn stultz 
1743a092ff0fSjohn stultz 	/* Accumulate one shifted interval */
174423a9537aSThomas Gleixner 	offset -= interval;
1745876e7881SPeter Zijlstra 	tk->tkr_mono.cycle_last += interval;
17464a4ad80dSPeter Zijlstra 	tk->tkr_raw.cycle_last  += interval;
1747a092ff0fSjohn stultz 
1748876e7881SPeter Zijlstra 	tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
17495258d3f2SJohn Stultz 	*clock_set |= accumulate_nsecs_to_secs(tk);
1750a092ff0fSjohn stultz 
1751deda2e81SJason Wessel 	/* Accumulate raw time */
17525b3900cdSDan Carpenter 	raw_nsecs = (u64)tk->raw_interval << shift;
1753f726a697SJohn Stultz 	raw_nsecs += tk->raw_time.tv_nsec;
1754c7dcf87aSJohn Stultz 	if (raw_nsecs >= NSEC_PER_SEC) {
1755c7dcf87aSJohn Stultz 		u64 raw_secs = raw_nsecs;
1756c7dcf87aSJohn Stultz 		raw_nsecs = do_div(raw_secs, NSEC_PER_SEC);
1757f726a697SJohn Stultz 		tk->raw_time.tv_sec += raw_secs;
1758a092ff0fSjohn stultz 	}
1759f726a697SJohn Stultz 	tk->raw_time.tv_nsec = raw_nsecs;
1760a092ff0fSjohn stultz 
1761a092ff0fSjohn stultz 	/* Accumulate error between NTP and clock interval */
1762375f45b5SJohn Stultz 	tk->ntp_error += tk->ntp_tick << shift;
1763f726a697SJohn Stultz 	tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
1764f726a697SJohn Stultz 						(tk->ntp_error_shift + shift);
1765a092ff0fSjohn stultz 
1766a092ff0fSjohn stultz 	return offset;
1767a092ff0fSjohn stultz }
1768a092ff0fSjohn stultz 
17698524070bSjohn stultz /**
17708524070bSjohn stultz  * update_wall_time - Uses the current clocksource to increment the wall time
17718524070bSjohn stultz  *
17728524070bSjohn stultz  */
177347a1b796SJohn Stultz void update_wall_time(void)
17748524070bSjohn stultz {
17753fdb14fdSThomas Gleixner 	struct timekeeper *real_tk = &tk_core.timekeeper;
177648cdc135SThomas Gleixner 	struct timekeeper *tk = &shadow_timekeeper;
17778524070bSjohn stultz 	cycle_t offset;
1778a092ff0fSjohn stultz 	int shift = 0, maxshift;
17795258d3f2SJohn Stultz 	unsigned int clock_set = 0;
178070471f2fSJohn Stultz 	unsigned long flags;
178170471f2fSJohn Stultz 
17829a7a71b1SThomas Gleixner 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
17838524070bSjohn stultz 
17848524070bSjohn stultz 	/* Make sure we're fully resumed: */
17858524070bSjohn stultz 	if (unlikely(timekeeping_suspended))
178670471f2fSJohn Stultz 		goto out;
17878524070bSjohn stultz 
1788592913ecSJohn Stultz #ifdef CONFIG_ARCH_USES_GETTIMEOFFSET
178948cdc135SThomas Gleixner 	offset = real_tk->cycle_interval;
1790592913ecSJohn Stultz #else
1791876e7881SPeter Zijlstra 	offset = clocksource_delta(tk->tkr_mono.read(tk->tkr_mono.clock),
1792876e7881SPeter Zijlstra 				   tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
17938524070bSjohn stultz #endif
17948524070bSjohn stultz 
1795bf2ac312SJohn Stultz 	/* Check if there's really nothing to do */
179648cdc135SThomas Gleixner 	if (offset < real_tk->cycle_interval)
1797bf2ac312SJohn Stultz 		goto out;
1798bf2ac312SJohn Stultz 
17993c17ad19SJohn Stultz 	/* Do some additional sanity checking */
18003c17ad19SJohn Stultz 	timekeeping_check_update(real_tk, offset);
18013c17ad19SJohn Stultz 
1802a092ff0fSjohn stultz 	/*
1803a092ff0fSjohn stultz 	 * With NO_HZ we may have to accumulate many cycle_intervals
1804a092ff0fSjohn stultz 	 * (think "ticks") worth of time at once. To do this efficiently,
1805a092ff0fSjohn stultz 	 * we calculate the largest doubling multiple of cycle_intervals
180688b28adfSJim Cromie 	 * that is smaller than the offset.  We then accumulate that
1807a092ff0fSjohn stultz 	 * chunk in one go, and then try to consume the next smaller
1808a092ff0fSjohn stultz 	 * doubled multiple.
18098524070bSjohn stultz 	 */
18104e250fddSJohn Stultz 	shift = ilog2(offset) - ilog2(tk->cycle_interval);
1811a092ff0fSjohn stultz 	shift = max(0, shift);
181288b28adfSJim Cromie 	/* Bound shift to one less than what overflows tick_length */
1813ea7cf49aSJohn Stultz 	maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
1814a092ff0fSjohn stultz 	shift = min(shift, maxshift);
18154e250fddSJohn Stultz 	while (offset >= tk->cycle_interval) {
18165258d3f2SJohn Stultz 		offset = logarithmic_accumulation(tk, offset, shift,
18175258d3f2SJohn Stultz 							&clock_set);
18184e250fddSJohn Stultz 		if (offset < tk->cycle_interval<<shift)
1819a092ff0fSjohn stultz 			shift--;
18208524070bSjohn stultz 	}
18218524070bSjohn stultz 
18228524070bSjohn stultz 	/* correct the clock when NTP error is too big */
18234e250fddSJohn Stultz 	timekeeping_adjust(tk, offset);
18248524070bSjohn stultz 
18256a867a39SJohn Stultz 	/*
182692bb1fcfSJohn Stultz 	 * XXX This can be killed once everyone converts
182792bb1fcfSJohn Stultz 	 * to the new update_vsyscall.
18285cd1c9c5SRoman Zippel 	 */
182992bb1fcfSJohn Stultz 	old_vsyscall_fixup(tk);
18308524070bSjohn stultz 
18316a867a39SJohn Stultz 	/*
18326a867a39SJohn Stultz 	 * Finally, make sure that after the rounding
18331e75fa8bSJohn Stultz 	 * xtime_nsec isn't larger than NSEC_PER_SEC
18346a867a39SJohn Stultz 	 */
18355258d3f2SJohn Stultz 	clock_set |= accumulate_nsecs_to_secs(tk);
183683f57a11SLinus Torvalds 
18373fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
183848cdc135SThomas Gleixner 	/*
183948cdc135SThomas Gleixner 	 * Update the real timekeeper.
184048cdc135SThomas Gleixner 	 *
184148cdc135SThomas Gleixner 	 * We could avoid this memcpy by switching pointers, but that
184248cdc135SThomas Gleixner 	 * requires changes to all other timekeeper usage sites as
184348cdc135SThomas Gleixner 	 * well, i.e. move the timekeeper pointer getter into the
184448cdc135SThomas Gleixner 	 * spinlocked/seqcount protected sections. And we trade this
18453fdb14fdSThomas Gleixner 	 * memcpy under the tk_core.seq against one before we start
184648cdc135SThomas Gleixner 	 * updating.
184748cdc135SThomas Gleixner 	 */
184848cdc135SThomas Gleixner 	memcpy(real_tk, tk, sizeof(*tk));
18495258d3f2SJohn Stultz 	timekeeping_update(real_tk, clock_set);
18503fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
1851ca4523cdSThomas Gleixner out:
18529a7a71b1SThomas Gleixner 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
185347a1b796SJohn Stultz 	if (clock_set)
1854cab5e127SJohn Stultz 		/* Have to call _delayed version, since in irq context*/
1855cab5e127SJohn Stultz 		clock_was_set_delayed();
18568524070bSjohn stultz }
18577c3f1a57STomas Janousek 
18587c3f1a57STomas Janousek /**
1859d08c0cddSJohn Stultz  * getboottime64 - Return the real time of system boot.
1860d08c0cddSJohn Stultz  * @ts:		pointer to the timespec64 to be set
18617c3f1a57STomas Janousek  *
1862d08c0cddSJohn Stultz  * Returns the wall-time of boot in a timespec64.
18637c3f1a57STomas Janousek  *
18647c3f1a57STomas Janousek  * This is based on the wall_to_monotonic offset and the total suspend
18657c3f1a57STomas Janousek  * time. Calls to settimeofday will affect the value returned (which
18667c3f1a57STomas Janousek  * basically means that however wrong your real time clock is at boot time,
18677c3f1a57STomas Janousek  * you get the right time here).
18687c3f1a57STomas Janousek  */
1869d08c0cddSJohn Stultz void getboottime64(struct timespec64 *ts)
18707c3f1a57STomas Janousek {
18713fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
187202cba159SThomas Gleixner 	ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
1873d4f587c6SMartin Schwidefsky 
1874d08c0cddSJohn Stultz 	*ts = ktime_to_timespec64(t);
18757c3f1a57STomas Janousek }
1876d08c0cddSJohn Stultz EXPORT_SYMBOL_GPL(getboottime64);
18777c3f1a57STomas Janousek 
187817c38b74Sjohn stultz unsigned long get_seconds(void)
187917c38b74Sjohn stultz {
18803fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
18814e250fddSJohn Stultz 
18824e250fddSJohn Stultz 	return tk->xtime_sec;
188317c38b74Sjohn stultz }
188417c38b74Sjohn stultz EXPORT_SYMBOL(get_seconds);
188517c38b74Sjohn stultz 
1886da15cfdaSjohn stultz struct timespec __current_kernel_time(void)
1887da15cfdaSjohn stultz {
18883fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
18894e250fddSJohn Stultz 
18907d489d15SJohn Stultz 	return timespec64_to_timespec(tk_xtime(tk));
1891da15cfdaSjohn stultz }
189217c38b74Sjohn stultz 
18932c6b47deSjohn stultz struct timespec current_kernel_time(void)
18942c6b47deSjohn stultz {
18953fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
18967d489d15SJohn Stultz 	struct timespec64 now;
18972c6b47deSjohn stultz 	unsigned long seq;
18982c6b47deSjohn stultz 
18992c6b47deSjohn stultz 	do {
19003fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
190183f57a11SLinus Torvalds 
19024e250fddSJohn Stultz 		now = tk_xtime(tk);
19033fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
19042c6b47deSjohn stultz 
19057d489d15SJohn Stultz 	return timespec64_to_timespec(now);
19062c6b47deSjohn stultz }
19072c6b47deSjohn stultz EXPORT_SYMBOL(current_kernel_time);
1908da15cfdaSjohn stultz 
1909334334b5SJohn Stultz struct timespec64 get_monotonic_coarse64(void)
1910da15cfdaSjohn stultz {
19113fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
19127d489d15SJohn Stultz 	struct timespec64 now, mono;
1913da15cfdaSjohn stultz 	unsigned long seq;
1914da15cfdaSjohn stultz 
1915da15cfdaSjohn stultz 	do {
19163fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
191783f57a11SLinus Torvalds 
19184e250fddSJohn Stultz 		now = tk_xtime(tk);
19194e250fddSJohn Stultz 		mono = tk->wall_to_monotonic;
19203fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
1921da15cfdaSjohn stultz 
19227d489d15SJohn Stultz 	set_normalized_timespec64(&now, now.tv_sec + mono.tv_sec,
1923da15cfdaSjohn stultz 				now.tv_nsec + mono.tv_nsec);
19247d489d15SJohn Stultz 
1925334334b5SJohn Stultz 	return now;
1926da15cfdaSjohn stultz }
1927871cf1e5STorben Hohn 
1928871cf1e5STorben Hohn /*
1929d6ad4187SJohn Stultz  * Must hold jiffies_lock
1930871cf1e5STorben Hohn  */
1931871cf1e5STorben Hohn void do_timer(unsigned long ticks)
1932871cf1e5STorben Hohn {
1933871cf1e5STorben Hohn 	jiffies_64 += ticks;
1934871cf1e5STorben Hohn 	calc_global_load(ticks);
1935871cf1e5STorben Hohn }
193648cf76f7STorben Hohn 
193748cf76f7STorben Hohn /**
193876f41088SJohn Stultz  * ktime_get_update_offsets_now - hrtimer helper
1939868a3e91SThomas Gleixner  * @cwsseq:	pointer to check and store the clock was set sequence number
1940f6c06abfSThomas Gleixner  * @offs_real:	pointer to storage for monotonic -> realtime offset
1941f6c06abfSThomas Gleixner  * @offs_boot:	pointer to storage for monotonic -> boottime offset
1942b7bc50e4SXie XiuQi  * @offs_tai:	pointer to storage for monotonic -> clock tai offset
1943f6c06abfSThomas Gleixner  *
1944868a3e91SThomas Gleixner  * Returns current monotonic time and updates the offsets if the
1945868a3e91SThomas Gleixner  * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
1946868a3e91SThomas Gleixner  * different.
1947868a3e91SThomas Gleixner  *
1948b7bc50e4SXie XiuQi  * Called from hrtimer_interrupt() or retrigger_next_event()
1949f6c06abfSThomas Gleixner  */
1950868a3e91SThomas Gleixner ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
1951868a3e91SThomas Gleixner 				     ktime_t *offs_boot, ktime_t *offs_tai)
1952f6c06abfSThomas Gleixner {
19533fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
1954f6c06abfSThomas Gleixner 	unsigned int seq;
1955a37c0aadSThomas Gleixner 	ktime_t base;
1956a37c0aadSThomas Gleixner 	u64 nsecs;
1957f6c06abfSThomas Gleixner 
1958f6c06abfSThomas Gleixner 	do {
19593fdb14fdSThomas Gleixner 		seq = read_seqcount_begin(&tk_core.seq);
1960f6c06abfSThomas Gleixner 
1961876e7881SPeter Zijlstra 		base = tk->tkr_mono.base;
1962876e7881SPeter Zijlstra 		nsecs = timekeeping_get_ns(&tk->tkr_mono);
1963868a3e91SThomas Gleixner 		if (*cwsseq != tk->clock_was_set_seq) {
1964868a3e91SThomas Gleixner 			*cwsseq = tk->clock_was_set_seq;
19654e250fddSJohn Stultz 			*offs_real = tk->offs_real;
19664e250fddSJohn Stultz 			*offs_boot = tk->offs_boot;
196790adda98SJohn Stultz 			*offs_tai = tk->offs_tai;
1968868a3e91SThomas Gleixner 		}
19693fdb14fdSThomas Gleixner 	} while (read_seqcount_retry(&tk_core.seq, seq));
1970f6c06abfSThomas Gleixner 
1971a37c0aadSThomas Gleixner 	return ktime_add_ns(base, nsecs);
1972f6c06abfSThomas Gleixner }
1973f6c06abfSThomas Gleixner 
1974f0af911aSTorben Hohn /**
1975aa6f9c59SJohn Stultz  * do_adjtimex() - Accessor function to NTP __do_adjtimex function
1976aa6f9c59SJohn Stultz  */
1977aa6f9c59SJohn Stultz int do_adjtimex(struct timex *txc)
1978aa6f9c59SJohn Stultz {
19793fdb14fdSThomas Gleixner 	struct timekeeper *tk = &tk_core.timekeeper;
198006c017fdSJohn Stultz 	unsigned long flags;
19817d489d15SJohn Stultz 	struct timespec64 ts;
19824e8f8b34SJohn Stultz 	s32 orig_tai, tai;
1983e4085693SJohn Stultz 	int ret;
1984e4085693SJohn Stultz 
1985e4085693SJohn Stultz 	/* Validate the data before disabling interrupts */
1986e4085693SJohn Stultz 	ret = ntp_validate_timex(txc);
1987e4085693SJohn Stultz 	if (ret)
1988e4085693SJohn Stultz 		return ret;
1989e4085693SJohn Stultz 
1990cef90377SJohn Stultz 	if (txc->modes & ADJ_SETOFFSET) {
1991cef90377SJohn Stultz 		struct timespec delta;
1992cef90377SJohn Stultz 		delta.tv_sec  = txc->time.tv_sec;
1993cef90377SJohn Stultz 		delta.tv_nsec = txc->time.tv_usec;
1994cef90377SJohn Stultz 		if (!(txc->modes & ADJ_NANO))
1995cef90377SJohn Stultz 			delta.tv_nsec *= 1000;
1996cef90377SJohn Stultz 		ret = timekeeping_inject_offset(&delta);
1997cef90377SJohn Stultz 		if (ret)
1998cef90377SJohn Stultz 			return ret;
1999cef90377SJohn Stultz 	}
2000cef90377SJohn Stultz 
2001d6d29896SThomas Gleixner 	getnstimeofday64(&ts);
2002aa6f9c59SJohn Stultz 
200306c017fdSJohn Stultz 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
20043fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
200506c017fdSJohn Stultz 
20064e8f8b34SJohn Stultz 	orig_tai = tai = tk->tai_offset;
200787ace39bSJohn Stultz 	ret = __do_adjtimex(txc, &ts, &tai);
200887ace39bSJohn Stultz 
20094e8f8b34SJohn Stultz 	if (tai != orig_tai) {
20100b5154fbSJohn Stultz 		__timekeeping_set_tai_offset(tk, tai);
2011f55c0760SJohn Stultz 		timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
20124e8f8b34SJohn Stultz 	}
20133fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
201406c017fdSJohn Stultz 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
201506c017fdSJohn Stultz 
20166fdda9a9SJohn Stultz 	if (tai != orig_tai)
20176fdda9a9SJohn Stultz 		clock_was_set();
20186fdda9a9SJohn Stultz 
20197bd36014SJohn Stultz 	ntp_notify_cmos_timer();
20207bd36014SJohn Stultz 
202187ace39bSJohn Stultz 	return ret;
202287ace39bSJohn Stultz }
2023aa6f9c59SJohn Stultz 
2024aa6f9c59SJohn Stultz #ifdef CONFIG_NTP_PPS
2025aa6f9c59SJohn Stultz /**
2026aa6f9c59SJohn Stultz  * hardpps() - Accessor function to NTP __hardpps function
2027aa6f9c59SJohn Stultz  */
2028aa6f9c59SJohn Stultz void hardpps(const struct timespec *phase_ts, const struct timespec *raw_ts)
2029aa6f9c59SJohn Stultz {
203006c017fdSJohn Stultz 	unsigned long flags;
203106c017fdSJohn Stultz 
203206c017fdSJohn Stultz 	raw_spin_lock_irqsave(&timekeeper_lock, flags);
20333fdb14fdSThomas Gleixner 	write_seqcount_begin(&tk_core.seq);
203406c017fdSJohn Stultz 
2035aa6f9c59SJohn Stultz 	__hardpps(phase_ts, raw_ts);
203606c017fdSJohn Stultz 
20373fdb14fdSThomas Gleixner 	write_seqcount_end(&tk_core.seq);
203806c017fdSJohn Stultz 	raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2039aa6f9c59SJohn Stultz }
2040aa6f9c59SJohn Stultz EXPORT_SYMBOL(hardpps);
2041aa6f9c59SJohn Stultz #endif
2042aa6f9c59SJohn Stultz 
2043aa6f9c59SJohn Stultz /**
2044f0af911aSTorben Hohn  * xtime_update() - advances the timekeeping infrastructure
2045f0af911aSTorben Hohn  * @ticks:	number of ticks, that have elapsed since the last call.
2046f0af911aSTorben Hohn  *
2047f0af911aSTorben Hohn  * Must be called with interrupts disabled.
2048f0af911aSTorben Hohn  */
2049f0af911aSTorben Hohn void xtime_update(unsigned long ticks)
2050f0af911aSTorben Hohn {
2051d6ad4187SJohn Stultz 	write_seqlock(&jiffies_lock);
2052f0af911aSTorben Hohn 	do_timer(ticks);
2053d6ad4187SJohn Stultz 	write_sequnlock(&jiffies_lock);
205447a1b796SJohn Stultz 	update_wall_time();
2055f0af911aSTorben Hohn }
2056