xref: /openbmc/linux/kernel/time/clocksource.c (revision fd5e9fccbd504c5179ab57ff695c610bca8809d6)
135728b82SThomas Gleixner // SPDX-License-Identifier: GPL-2.0+
2734efb46Sjohn stultz /*
3734efb46Sjohn stultz  * This file contains the functions which manage clocksource drivers.
4734efb46Sjohn stultz  *
5734efb46Sjohn stultz  * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
6734efb46Sjohn stultz  */
7734efb46Sjohn stultz 
845bbfe64SJoe Perches #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
945bbfe64SJoe Perches 
10d369a5d8SKay Sievers #include <linux/device.h>
11734efb46Sjohn stultz #include <linux/clocksource.h>
12734efb46Sjohn stultz #include <linux/init.h>
13734efb46Sjohn stultz #include <linux/module.h>
14dc29a365SMathieu Desnoyers #include <linux/sched.h> /* for spin_unlock_irq() using preempt_count() m68k */
1579bf2bb3SThomas Gleixner #include <linux/tick.h>
1601548f4dSMartin Schwidefsky #include <linux/kthread.h>
17fa218f1cSPaul E. McKenney #include <linux/prandom.h>
18fa218f1cSPaul E. McKenney #include <linux/cpu.h>
19734efb46Sjohn stultz 
20c1797bafSThomas Gleixner #include "tick-internal.h"
213a978377SThomas Gleixner #include "timekeeping_internal.h"
2203e13cf5SThomas Gleixner 
cycles_to_nsec_safe(struct clocksource * cs,u64 start,u64 end)2314bd62d5SAdrian Hunter static noinline u64 cycles_to_nsec_safe(struct clocksource *cs, u64 start, u64 end)
2414bd62d5SAdrian Hunter {
2514bd62d5SAdrian Hunter 	u64 delta = clocksource_delta(end, start, cs->mask);
2614bd62d5SAdrian Hunter 
2714bd62d5SAdrian Hunter 	if (likely(delta < cs->max_cycles))
2814bd62d5SAdrian Hunter 		return clocksource_cyc2ns(delta, cs->mult, cs->shift);
2914bd62d5SAdrian Hunter 
3014bd62d5SAdrian Hunter 	return mul_u64_u32_shr(delta, cs->mult, cs->shift);
3114bd62d5SAdrian Hunter }
3214bd62d5SAdrian Hunter 
337d2f944aSThomas Gleixner /**
347d2f944aSThomas Gleixner  * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
357d2f944aSThomas Gleixner  * @mult:	pointer to mult variable
367d2f944aSThomas Gleixner  * @shift:	pointer to shift variable
377d2f944aSThomas Gleixner  * @from:	frequency to convert from
387d2f944aSThomas Gleixner  * @to:		frequency to convert to
395fdade95SNicolas Pitre  * @maxsec:	guaranteed runtime conversion range in seconds
407d2f944aSThomas Gleixner  *
417d2f944aSThomas Gleixner  * The function evaluates the shift/mult pair for the scaled math
427d2f944aSThomas Gleixner  * operations of clocksources and clockevents.
437d2f944aSThomas Gleixner  *
447d2f944aSThomas Gleixner  * @to and @from are frequency values in HZ. For clock sources @to is
457d2f944aSThomas Gleixner  * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
467d2f944aSThomas Gleixner  * event @to is the counter frequency and @from is NSEC_PER_SEC.
477d2f944aSThomas Gleixner  *
485fdade95SNicolas Pitre  * The @maxsec conversion range argument controls the time frame in
497d2f944aSThomas Gleixner  * seconds which must be covered by the runtime conversion with the
507d2f944aSThomas Gleixner  * calculated mult and shift factors. This guarantees that no 64bit
517d2f944aSThomas Gleixner  * overflow happens when the input value of the conversion is
527d2f944aSThomas Gleixner  * multiplied with the calculated mult factor. Larger ranges may
534bf07f65SIngo Molnar  * reduce the conversion accuracy by choosing smaller mult and shift
547d2f944aSThomas Gleixner  * factors.
557d2f944aSThomas Gleixner  */
567d2f944aSThomas Gleixner void
clocks_calc_mult_shift(u32 * mult,u32 * shift,u32 from,u32 to,u32 maxsec)575fdade95SNicolas Pitre clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
587d2f944aSThomas Gleixner {
597d2f944aSThomas Gleixner 	u64 tmp;
607d2f944aSThomas Gleixner 	u32 sft, sftacc= 32;
617d2f944aSThomas Gleixner 
627d2f944aSThomas Gleixner 	/*
637d2f944aSThomas Gleixner 	 * Calculate the shift factor which is limiting the conversion
647d2f944aSThomas Gleixner 	 * range:
657d2f944aSThomas Gleixner 	 */
665fdade95SNicolas Pitre 	tmp = ((u64)maxsec * from) >> 32;
677d2f944aSThomas Gleixner 	while (tmp) {
687d2f944aSThomas Gleixner 		tmp >>=1;
697d2f944aSThomas Gleixner 		sftacc--;
707d2f944aSThomas Gleixner 	}
717d2f944aSThomas Gleixner 
727d2f944aSThomas Gleixner 	/*
737d2f944aSThomas Gleixner 	 * Find the conversion shift/mult pair which has the best
747d2f944aSThomas Gleixner 	 * accuracy and fits the maxsec conversion range:
757d2f944aSThomas Gleixner 	 */
767d2f944aSThomas Gleixner 	for (sft = 32; sft > 0; sft--) {
777d2f944aSThomas Gleixner 		tmp = (u64) to << sft;
78b5776c4aSjohn stultz 		tmp += from / 2;
797d2f944aSThomas Gleixner 		do_div(tmp, from);
807d2f944aSThomas Gleixner 		if ((tmp >> sftacc) == 0)
817d2f944aSThomas Gleixner 			break;
827d2f944aSThomas Gleixner 	}
837d2f944aSThomas Gleixner 	*mult = tmp;
847d2f944aSThomas Gleixner 	*shift = sft;
857d2f944aSThomas Gleixner }
865304121aSMurali Karicheri EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
877d2f944aSThomas Gleixner 
88734efb46Sjohn stultz /*[Clocksource internal variables]---------
89734efb46Sjohn stultz  * curr_clocksource:
90f1b82746SMartin Schwidefsky  *	currently selected clocksource.
9139232ed5SBaolin Wang  * suspend_clocksource:
9239232ed5SBaolin Wang  *	used to calculate the suspend time.
93734efb46Sjohn stultz  * clocksource_list:
94734efb46Sjohn stultz  *	linked list with the registered clocksources
9575c5158fSMartin Schwidefsky  * clocksource_mutex:
9675c5158fSMartin Schwidefsky  *	protects manipulations to curr_clocksource and the clocksource_list
97734efb46Sjohn stultz  * override_name:
98734efb46Sjohn stultz  *	Name of the user-specified clocksource.
99734efb46Sjohn stultz  */
100f1b82746SMartin Schwidefsky static struct clocksource *curr_clocksource;
10139232ed5SBaolin Wang static struct clocksource *suspend_clocksource;
102734efb46Sjohn stultz static LIST_HEAD(clocksource_list);
10375c5158fSMartin Schwidefsky static DEFINE_MUTEX(clocksource_mutex);
10429b54078SThomas Gleixner static char override_name[CS_NAME_LEN];
10554a6bc0bSThomas Gleixner static int finished_booting;
10639232ed5SBaolin Wang static u64 suspend_start;
107734efb46Sjohn stultz 
1082e27e793SPaul E. McKenney /*
109c37e85c1SPaul E. McKenney  * Interval: 0.5sec.
110c37e85c1SPaul E. McKenney  */
111c37e85c1SPaul E. McKenney #define WATCHDOG_INTERVAL (HZ >> 1)
112af7ab5daSJiri Wiesner #define WATCHDOG_INTERVAL_MAX_NS ((2 * WATCHDOG_INTERVAL) * (NSEC_PER_SEC / HZ))
113c37e85c1SPaul E. McKenney 
114c37e85c1SPaul E. McKenney /*
1152e27e793SPaul E. McKenney  * Threshold: 0.0312s, when doubled: 0.0625s.
1162e27e793SPaul E. McKenney  * Also a default for cs->uncertainty_margin when registering clocks.
1172e27e793SPaul E. McKenney  */
1182e27e793SPaul E. McKenney #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 5)
1192e27e793SPaul E. McKenney 
1202e27e793SPaul E. McKenney /*
1212e27e793SPaul E. McKenney  * Maximum permissible delay between two readouts of the watchdog
1222e27e793SPaul E. McKenney  * clocksource surrounding a read of the clocksource being validated.
1232e27e793SPaul E. McKenney  * This delay could be due to SMIs, NMIs, or to VCPU preemptions.  Used as
1242e27e793SPaul E. McKenney  * a lower bound for cs->uncertainty_margin values when registering clocks.
125c37e85c1SPaul E. McKenney  *
126c37e85c1SPaul E. McKenney  * The default of 500 parts per million is based on NTP's limits.
127c37e85c1SPaul E. McKenney  * If a clocksource is good enough for NTP, it is good enough for us!
1282e27e793SPaul E. McKenney  */
129fc153c1cSWaiman Long #ifdef CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
130fc153c1cSWaiman Long #define MAX_SKEW_USEC	CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
131fc153c1cSWaiman Long #else
132c37e85c1SPaul E. McKenney #define MAX_SKEW_USEC	(125 * WATCHDOG_INTERVAL / HZ)
133fc153c1cSWaiman Long #endif
134fc153c1cSWaiman Long 
135fc153c1cSWaiman Long #define WATCHDOG_MAX_SKEW (MAX_SKEW_USEC * NSEC_PER_USEC)
1362e27e793SPaul E. McKenney 
1375d8b34fdSThomas Gleixner #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
138f79e0258SMartin Schwidefsky static void clocksource_watchdog_work(struct work_struct *work);
139332962f2SThomas Gleixner static void clocksource_select(void);
140f79e0258SMartin Schwidefsky 
1415d8b34fdSThomas Gleixner static LIST_HEAD(watchdog_list);
1425d8b34fdSThomas Gleixner static struct clocksource *watchdog;
1435d8b34fdSThomas Gleixner static struct timer_list watchdog_timer;
144f79e0258SMartin Schwidefsky static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
1455d8b34fdSThomas Gleixner static DEFINE_SPINLOCK(watchdog_lock);
146fb63a0ebSMartin Schwidefsky static int watchdog_running;
1479fb60336SThomas Gleixner static atomic_t watchdog_reset_pending;
148af7ab5daSJiri Wiesner static int64_t watchdog_max_interval;
149b52f52a0SThomas Gleixner 
clocksource_watchdog_lock(unsigned long * flags)1500f48b41fSMathieu Malaterre static inline void clocksource_watchdog_lock(unsigned long *flags)
1512aae7bcfSPeter Zijlstra {
1522aae7bcfSPeter Zijlstra 	spin_lock_irqsave(&watchdog_lock, *flags);
1532aae7bcfSPeter Zijlstra }
1542aae7bcfSPeter Zijlstra 
clocksource_watchdog_unlock(unsigned long * flags)1550f48b41fSMathieu Malaterre static inline void clocksource_watchdog_unlock(unsigned long *flags)
1562aae7bcfSPeter Zijlstra {
1572aae7bcfSPeter Zijlstra 	spin_unlock_irqrestore(&watchdog_lock, *flags);
1582aae7bcfSPeter Zijlstra }
1592aae7bcfSPeter Zijlstra 
160e2c631baSPeter Zijlstra static int clocksource_watchdog_kthread(void *data);
161e2c631baSPeter Zijlstra static void __clocksource_change_rating(struct clocksource *cs, int rating);
162e2c631baSPeter Zijlstra 
clocksource_watchdog_work(struct work_struct * work)163e2c631baSPeter Zijlstra static void clocksource_watchdog_work(struct work_struct *work)
164e2c631baSPeter Zijlstra {
165e2c631baSPeter Zijlstra 	/*
166e2c631baSPeter Zijlstra 	 * We cannot directly run clocksource_watchdog_kthread() here, because
167e2c631baSPeter Zijlstra 	 * clocksource_select() calls timekeeping_notify() which uses
168e2c631baSPeter Zijlstra 	 * stop_machine(). One cannot use stop_machine() from a workqueue() due
169e2c631baSPeter Zijlstra 	 * lock inversions wrt CPU hotplug.
170e2c631baSPeter Zijlstra 	 *
171e2c631baSPeter Zijlstra 	 * Also, we only ever run this work once or twice during the lifetime
172e2c631baSPeter Zijlstra 	 * of the kernel, so there is no point in creating a more permanent
173e2c631baSPeter Zijlstra 	 * kthread for this.
174e2c631baSPeter Zijlstra 	 *
175e2c631baSPeter Zijlstra 	 * If kthread_run fails the next watchdog scan over the
176e2c631baSPeter Zijlstra 	 * watchdog_list will find the unstable clock again.
177e2c631baSPeter Zijlstra 	 */
178e2c631baSPeter Zijlstra 	kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
179e2c631baSPeter Zijlstra }
180e2c631baSPeter Zijlstra 
__clocksource_unstable(struct clocksource * cs)1817285dd7fSThomas Gleixner static void __clocksource_unstable(struct clocksource *cs)
1827285dd7fSThomas Gleixner {
1837285dd7fSThomas Gleixner 	cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
1847285dd7fSThomas Gleixner 	cs->flags |= CLOCK_SOURCE_UNSTABLE;
18512907fbbSThomas Gleixner 
186cd2af07dSPeter Zijlstra 	/*
187e2c631baSPeter Zijlstra 	 * If the clocksource is registered clocksource_watchdog_kthread() will
188cd2af07dSPeter Zijlstra 	 * re-rate and re-select.
189cd2af07dSPeter Zijlstra 	 */
190cd2af07dSPeter Zijlstra 	if (list_empty(&cs->list)) {
191cd2af07dSPeter Zijlstra 		cs->rating = 0;
1922aae7bcfSPeter Zijlstra 		return;
193cd2af07dSPeter Zijlstra 	}
1942aae7bcfSPeter Zijlstra 
19512907fbbSThomas Gleixner 	if (cs->mark_unstable)
19612907fbbSThomas Gleixner 		cs->mark_unstable(cs);
19712907fbbSThomas Gleixner 
198e2c631baSPeter Zijlstra 	/* kick clocksource_watchdog_kthread() */
19954a6bc0bSThomas Gleixner 	if (finished_booting)
2007285dd7fSThomas Gleixner 		schedule_work(&watchdog_work);
2017285dd7fSThomas Gleixner }
2027285dd7fSThomas Gleixner 
2037285dd7fSThomas Gleixner /**
2047285dd7fSThomas Gleixner  * clocksource_mark_unstable - mark clocksource unstable via watchdog
2057285dd7fSThomas Gleixner  * @cs:		clocksource to be marked unstable
2067285dd7fSThomas Gleixner  *
2077dba33c6SPeter Zijlstra  * This function is called by the x86 TSC code to mark clocksources as unstable;
208e2c631baSPeter Zijlstra  * it defers demotion and re-selection to a kthread.
2097285dd7fSThomas Gleixner  */
clocksource_mark_unstable(struct clocksource * cs)2107285dd7fSThomas Gleixner void clocksource_mark_unstable(struct clocksource *cs)
2117285dd7fSThomas Gleixner {
2127285dd7fSThomas Gleixner 	unsigned long flags;
2137285dd7fSThomas Gleixner 
2147285dd7fSThomas Gleixner 	spin_lock_irqsave(&watchdog_lock, flags);
2157285dd7fSThomas Gleixner 	if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
2162aae7bcfSPeter Zijlstra 		if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
2177285dd7fSThomas Gleixner 			list_add(&cs->wd_list, &watchdog_list);
2187285dd7fSThomas Gleixner 		__clocksource_unstable(cs);
2197285dd7fSThomas Gleixner 	}
2207285dd7fSThomas Gleixner 	spin_unlock_irqrestore(&watchdog_lock, flags);
2215d8b34fdSThomas Gleixner }
2225d8b34fdSThomas Gleixner 
223fa218f1cSPaul E. McKenney static int verify_n_cpus = 8;
224fa218f1cSPaul E. McKenney module_param(verify_n_cpus, int, 0644);
225db3a34e1SPaul E. McKenney 
226c86ff8c5SWaiman Long enum wd_read_status {
227c86ff8c5SWaiman Long 	WD_READ_SUCCESS,
228c86ff8c5SWaiman Long 	WD_READ_UNSTABLE,
229c86ff8c5SWaiman Long 	WD_READ_SKIP
230c86ff8c5SWaiman Long };
231c86ff8c5SWaiman Long 
cs_watchdog_read(struct clocksource * cs,u64 * csnow,u64 * wdnow)232c86ff8c5SWaiman Long static enum wd_read_status cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
233db3a34e1SPaul E. McKenney {
23403c38555SFeng Tang 	unsigned int nretries, max_retries;
235c86ff8c5SWaiman Long 	int64_t wd_delay, wd_seq_delay;
23614bd62d5SAdrian Hunter 	u64 wd_end, wd_end2;
237db3a34e1SPaul E. McKenney 
23803c38555SFeng Tang 	max_retries = clocksource_get_max_watchdog_retry();
23903c38555SFeng Tang 	for (nretries = 0; nretries <= max_retries; nretries++) {
240db3a34e1SPaul E. McKenney 		local_irq_disable();
241db3a34e1SPaul E. McKenney 		*wdnow = watchdog->read(watchdog);
242db3a34e1SPaul E. McKenney 		*csnow = cs->read(cs);
243db3a34e1SPaul E. McKenney 		wd_end = watchdog->read(watchdog);
244c86ff8c5SWaiman Long 		wd_end2 = watchdog->read(watchdog);
245db3a34e1SPaul E. McKenney 		local_irq_enable();
246db3a34e1SPaul E. McKenney 
24714bd62d5SAdrian Hunter 		wd_delay = cycles_to_nsec_safe(watchdog, *wdnow, wd_end);
248db3a34e1SPaul E. McKenney 		if (wd_delay <= WATCHDOG_MAX_SKEW) {
2499d6193fdSPaul E. McKenney 			if (nretries > 1 && nretries >= max_retries) {
250db3a34e1SPaul E. McKenney 				pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
251db3a34e1SPaul E. McKenney 					smp_processor_id(), watchdog->name, nretries);
252db3a34e1SPaul E. McKenney 			}
253c86ff8c5SWaiman Long 			return WD_READ_SUCCESS;
254db3a34e1SPaul E. McKenney 		}
255c86ff8c5SWaiman Long 
256c86ff8c5SWaiman Long 		/*
257c86ff8c5SWaiman Long 		 * Now compute delay in consecutive watchdog read to see if
258c86ff8c5SWaiman Long 		 * there is too much external interferences that cause
259c86ff8c5SWaiman Long 		 * significant delay in reading both clocksource and watchdog.
260c86ff8c5SWaiman Long 		 *
261c86ff8c5SWaiman Long 		 * If consecutive WD read-back delay > WATCHDOG_MAX_SKEW/2,
262c86ff8c5SWaiman Long 		 * report system busy, reinit the watchdog and skip the current
263c86ff8c5SWaiman Long 		 * watchdog test.
264c86ff8c5SWaiman Long 		 */
26514bd62d5SAdrian Hunter 		wd_seq_delay = cycles_to_nsec_safe(watchdog, wd_end, wd_end2);
266c86ff8c5SWaiman Long 		if (wd_seq_delay > WATCHDOG_MAX_SKEW/2)
267c86ff8c5SWaiman Long 			goto skip_test;
268db3a34e1SPaul E. McKenney 	}
269db3a34e1SPaul E. McKenney 
270f092eb34SPaul E. McKenney 	pr_warn("timekeeping watchdog on CPU%d: wd-%s-wd excessive read-back delay of %lldns vs. limit of %ldns, wd-wd read-back delay only %lldns, attempt %d, marking %s unstable\n",
271f092eb34SPaul E. McKenney 		smp_processor_id(), cs->name, wd_delay, WATCHDOG_MAX_SKEW, wd_seq_delay, nretries, cs->name);
272c86ff8c5SWaiman Long 	return WD_READ_UNSTABLE;
273c86ff8c5SWaiman Long 
274c86ff8c5SWaiman Long skip_test:
275c86ff8c5SWaiman Long 	pr_info("timekeeping watchdog on CPU%d: %s wd-wd read-back delay of %lldns\n",
276c86ff8c5SWaiman Long 		smp_processor_id(), watchdog->name, wd_seq_delay);
277c86ff8c5SWaiman Long 	pr_info("wd-%s-wd read-back delay of %lldns, clock-skew test skipped!\n",
278c86ff8c5SWaiman Long 		cs->name, wd_delay);
279c86ff8c5SWaiman Long 	return WD_READ_SKIP;
280db3a34e1SPaul E. McKenney }
281db3a34e1SPaul E. McKenney 
2827560c02bSPaul E. McKenney static u64 csnow_mid;
2837560c02bSPaul E. McKenney static cpumask_t cpus_ahead;
2847560c02bSPaul E. McKenney static cpumask_t cpus_behind;
285fa218f1cSPaul E. McKenney static cpumask_t cpus_chosen;
286fa218f1cSPaul E. McKenney 
clocksource_verify_choose_cpus(void)287fa218f1cSPaul E. McKenney static void clocksource_verify_choose_cpus(void)
288fa218f1cSPaul E. McKenney {
289fa218f1cSPaul E. McKenney 	int cpu, i, n = verify_n_cpus;
290fa218f1cSPaul E. McKenney 
291fa218f1cSPaul E. McKenney 	if (n < 0) {
292fa218f1cSPaul E. McKenney 		/* Check all of the CPUs. */
293fa218f1cSPaul E. McKenney 		cpumask_copy(&cpus_chosen, cpu_online_mask);
294fa218f1cSPaul E. McKenney 		cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
295fa218f1cSPaul E. McKenney 		return;
296fa218f1cSPaul E. McKenney 	}
297fa218f1cSPaul E. McKenney 
298fa218f1cSPaul E. McKenney 	/* If no checking desired, or no other CPU to check, leave. */
299fa218f1cSPaul E. McKenney 	cpumask_clear(&cpus_chosen);
300fa218f1cSPaul E. McKenney 	if (n == 0 || num_online_cpus() <= 1)
301fa218f1cSPaul E. McKenney 		return;
302fa218f1cSPaul E. McKenney 
303fa218f1cSPaul E. McKenney 	/* Make sure to select at least one CPU other than the current CPU. */
3049b51d9d8SYury Norov 	cpu = cpumask_first(cpu_online_mask);
305fa218f1cSPaul E. McKenney 	if (cpu == smp_processor_id())
306fa218f1cSPaul E. McKenney 		cpu = cpumask_next(cpu, cpu_online_mask);
307fa218f1cSPaul E. McKenney 	if (WARN_ON_ONCE(cpu >= nr_cpu_ids))
308fa218f1cSPaul E. McKenney 		return;
309fa218f1cSPaul E. McKenney 	cpumask_set_cpu(cpu, &cpus_chosen);
310fa218f1cSPaul E. McKenney 
311fa218f1cSPaul E. McKenney 	/* Force a sane value for the boot parameter. */
312fa218f1cSPaul E. McKenney 	if (n > nr_cpu_ids)
313fa218f1cSPaul E. McKenney 		n = nr_cpu_ids;
314fa218f1cSPaul E. McKenney 
315fa218f1cSPaul E. McKenney 	/*
316fa218f1cSPaul E. McKenney 	 * Randomly select the specified number of CPUs.  If the same
317fa218f1cSPaul E. McKenney 	 * CPU is selected multiple times, that CPU is checked only once,
318fa218f1cSPaul E. McKenney 	 * and no replacement CPU is selected.  This gracefully handles
319fa218f1cSPaul E. McKenney 	 * situations where verify_n_cpus is greater than the number of
320fa218f1cSPaul E. McKenney 	 * CPUs that are currently online.
321fa218f1cSPaul E. McKenney 	 */
322fa218f1cSPaul E. McKenney 	for (i = 1; i < n; i++) {
3238032bf12SJason A. Donenfeld 		cpu = get_random_u32_below(nr_cpu_ids);
324fa218f1cSPaul E. McKenney 		cpu = cpumask_next(cpu - 1, cpu_online_mask);
325fa218f1cSPaul E. McKenney 		if (cpu >= nr_cpu_ids)
3269b51d9d8SYury Norov 			cpu = cpumask_first(cpu_online_mask);
327fa218f1cSPaul E. McKenney 		if (!WARN_ON_ONCE(cpu >= nr_cpu_ids))
328fa218f1cSPaul E. McKenney 			cpumask_set_cpu(cpu, &cpus_chosen);
329fa218f1cSPaul E. McKenney 	}
330fa218f1cSPaul E. McKenney 
331fa218f1cSPaul E. McKenney 	/* Don't verify ourselves. */
332fa218f1cSPaul E. McKenney 	cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
333fa218f1cSPaul E. McKenney }
3347560c02bSPaul E. McKenney 
clocksource_verify_one_cpu(void * csin)3357560c02bSPaul E. McKenney static void clocksource_verify_one_cpu(void *csin)
3367560c02bSPaul E. McKenney {
3377560c02bSPaul E. McKenney 	struct clocksource *cs = (struct clocksource *)csin;
3387560c02bSPaul E. McKenney 
3397560c02bSPaul E. McKenney 	csnow_mid = cs->read(cs);
3407560c02bSPaul E. McKenney }
3417560c02bSPaul E. McKenney 
clocksource_verify_percpu(struct clocksource * cs)3421253b9b8SPaul E. McKenney void clocksource_verify_percpu(struct clocksource *cs)
3437560c02bSPaul E. McKenney {
3447560c02bSPaul E. McKenney 	int64_t cs_nsec, cs_nsec_max = 0, cs_nsec_min = LLONG_MAX;
3457560c02bSPaul E. McKenney 	u64 csnow_begin, csnow_end;
3467560c02bSPaul E. McKenney 	int cpu, testcpu;
3477560c02bSPaul E. McKenney 	s64 delta;
3487560c02bSPaul E. McKenney 
349fa218f1cSPaul E. McKenney 	if (verify_n_cpus == 0)
350fa218f1cSPaul E. McKenney 		return;
3517560c02bSPaul E. McKenney 	cpumask_clear(&cpus_ahead);
3527560c02bSPaul E. McKenney 	cpumask_clear(&cpus_behind);
353698429f9SSebastian Andrzej Siewior 	cpus_read_lock();
354*8783ceeeSWaiman Long 	migrate_disable();
355fa218f1cSPaul E. McKenney 	clocksource_verify_choose_cpus();
3568afbcaf8SYury Norov 	if (cpumask_empty(&cpus_chosen)) {
357*8783ceeeSWaiman Long 		migrate_enable();
358698429f9SSebastian Andrzej Siewior 		cpus_read_unlock();
359fa218f1cSPaul E. McKenney 		pr_warn("Not enough CPUs to check clocksource '%s'.\n", cs->name);
360fa218f1cSPaul E. McKenney 		return;
361fa218f1cSPaul E. McKenney 	}
3627560c02bSPaul E. McKenney 	testcpu = smp_processor_id();
3630cc5bb93SWaiman Long 	pr_info("Checking clocksource %s synchronization from CPU %d to CPUs %*pbl.\n",
3640cc5bb93SWaiman Long 		cs->name, testcpu, cpumask_pr_args(&cpus_chosen));
365*8783ceeeSWaiman Long 	preempt_disable();
366fa218f1cSPaul E. McKenney 	for_each_cpu(cpu, &cpus_chosen) {
3677560c02bSPaul E. McKenney 		if (cpu == testcpu)
3687560c02bSPaul E. McKenney 			continue;
3697560c02bSPaul E. McKenney 		csnow_begin = cs->read(cs);
3707560c02bSPaul E. McKenney 		smp_call_function_single(cpu, clocksource_verify_one_cpu, cs, 1);
3717560c02bSPaul E. McKenney 		csnow_end = cs->read(cs);
3727560c02bSPaul E. McKenney 		delta = (s64)((csnow_mid - csnow_begin) & cs->mask);
3737560c02bSPaul E. McKenney 		if (delta < 0)
3747560c02bSPaul E. McKenney 			cpumask_set_cpu(cpu, &cpus_behind);
3757560c02bSPaul E. McKenney 		delta = (csnow_end - csnow_mid) & cs->mask;
3767560c02bSPaul E. McKenney 		if (delta < 0)
3777560c02bSPaul E. McKenney 			cpumask_set_cpu(cpu, &cpus_ahead);
37814bd62d5SAdrian Hunter 		cs_nsec = cycles_to_nsec_safe(cs, csnow_begin, csnow_end);
3797560c02bSPaul E. McKenney 		if (cs_nsec > cs_nsec_max)
3807560c02bSPaul E. McKenney 			cs_nsec_max = cs_nsec;
3817560c02bSPaul E. McKenney 		if (cs_nsec < cs_nsec_min)
3827560c02bSPaul E. McKenney 			cs_nsec_min = cs_nsec;
3837560c02bSPaul E. McKenney 	}
3847560c02bSPaul E. McKenney 	preempt_enable();
385*8783ceeeSWaiman Long 	migrate_enable();
386698429f9SSebastian Andrzej Siewior 	cpus_read_unlock();
3877560c02bSPaul E. McKenney 	if (!cpumask_empty(&cpus_ahead))
3887560c02bSPaul E. McKenney 		pr_warn("        CPUs %*pbl ahead of CPU %d for clocksource %s.\n",
3897560c02bSPaul E. McKenney 			cpumask_pr_args(&cpus_ahead), testcpu, cs->name);
3907560c02bSPaul E. McKenney 	if (!cpumask_empty(&cpus_behind))
3917560c02bSPaul E. McKenney 		pr_warn("        CPUs %*pbl behind CPU %d for clocksource %s.\n",
3927560c02bSPaul E. McKenney 			cpumask_pr_args(&cpus_behind), testcpu, cs->name);
3937560c02bSPaul E. McKenney 	if (!cpumask_empty(&cpus_ahead) || !cpumask_empty(&cpus_behind))
3947560c02bSPaul E. McKenney 		pr_warn("        CPU %d check durations %lldns - %lldns for clocksource %s.\n",
3957560c02bSPaul E. McKenney 			testcpu, cs_nsec_min, cs_nsec_max, cs->name);
3967560c02bSPaul E. McKenney }
3971253b9b8SPaul E. McKenney EXPORT_SYMBOL_GPL(clocksource_verify_percpu);
3987560c02bSPaul E. McKenney 
clocksource_reset_watchdog(void)399b7082cdfSFeng Tang static inline void clocksource_reset_watchdog(void)
400b7082cdfSFeng Tang {
401b7082cdfSFeng Tang 	struct clocksource *cs;
402b7082cdfSFeng Tang 
403b7082cdfSFeng Tang 	list_for_each_entry(cs, &watchdog_list, wd_list)
404b7082cdfSFeng Tang 		cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
405b7082cdfSFeng Tang }
406b7082cdfSFeng Tang 
407b7082cdfSFeng Tang 
clocksource_watchdog(struct timer_list * unused)408e99e88a9SKees Cook static void clocksource_watchdog(struct timer_list *unused)
4095d8b34fdSThomas Gleixner {
410af7ab5daSJiri Wiesner 	int64_t wd_nsec, cs_nsec, interval;
41114bd62d5SAdrian Hunter 	u64 csnow, wdnow, cslast, wdlast;
4129fb60336SThomas Gleixner 	int next_cpu, reset_pending;
413db3a34e1SPaul E. McKenney 	struct clocksource *cs;
414c86ff8c5SWaiman Long 	enum wd_read_status read_ret;
415b7082cdfSFeng Tang 	unsigned long extra_wait = 0;
4162e27e793SPaul E. McKenney 	u32 md;
4175d8b34fdSThomas Gleixner 
4185d8b34fdSThomas Gleixner 	spin_lock(&watchdog_lock);
419fb63a0ebSMartin Schwidefsky 	if (!watchdog_running)
420fb63a0ebSMartin Schwidefsky 		goto out;
4215d8b34fdSThomas Gleixner 
4229fb60336SThomas Gleixner 	reset_pending = atomic_read(&watchdog_reset_pending);
4239fb60336SThomas Gleixner 
424c55c87c8SMartin Schwidefsky 	list_for_each_entry(cs, &watchdog_list, wd_list) {
425c55c87c8SMartin Schwidefsky 
426c55c87c8SMartin Schwidefsky 		/* Clocksource already marked unstable? */
42701548f4dSMartin Schwidefsky 		if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
42854a6bc0bSThomas Gleixner 			if (finished_booting)
42901548f4dSMartin Schwidefsky 				schedule_work(&watchdog_work);
430c55c87c8SMartin Schwidefsky 			continue;
43101548f4dSMartin Schwidefsky 		}
432c55c87c8SMartin Schwidefsky 
433c86ff8c5SWaiman Long 		read_ret = cs_watchdog_read(cs, &csnow, &wdnow);
434c86ff8c5SWaiman Long 
435b7082cdfSFeng Tang 		if (read_ret == WD_READ_UNSTABLE) {
436db3a34e1SPaul E. McKenney 			/* Clock readout unreliable, so give it up. */
437db3a34e1SPaul E. McKenney 			__clocksource_unstable(cs);
438db3a34e1SPaul E. McKenney 			continue;
439db3a34e1SPaul E. McKenney 		}
440b52f52a0SThomas Gleixner 
441b7082cdfSFeng Tang 		/*
442b7082cdfSFeng Tang 		 * When WD_READ_SKIP is returned, it means the system is likely
443b7082cdfSFeng Tang 		 * under very heavy load, where the latency of reading
444b7082cdfSFeng Tang 		 * watchdog/clocksource is very big, and affect the accuracy of
445b7082cdfSFeng Tang 		 * watchdog check. So give system some space and suspend the
446b7082cdfSFeng Tang 		 * watchdog check for 5 minutes.
447b7082cdfSFeng Tang 		 */
448b7082cdfSFeng Tang 		if (read_ret == WD_READ_SKIP) {
449b7082cdfSFeng Tang 			/*
450b7082cdfSFeng Tang 			 * As the watchdog timer will be suspended, and
451b7082cdfSFeng Tang 			 * cs->last could keep unchanged for 5 minutes, reset
452b7082cdfSFeng Tang 			 * the counters.
453b7082cdfSFeng Tang 			 */
454b7082cdfSFeng Tang 			clocksource_reset_watchdog();
455b7082cdfSFeng Tang 			extra_wait = HZ * 300;
456b7082cdfSFeng Tang 			break;
457b7082cdfSFeng Tang 		}
458b7082cdfSFeng Tang 
4598cf4e750SMartin Schwidefsky 		/* Clocksource initialized ? */
4609fb60336SThomas Gleixner 		if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
4619fb60336SThomas Gleixner 		    atomic_read(&watchdog_reset_pending)) {
4628cf4e750SMartin Schwidefsky 			cs->flags |= CLOCK_SOURCE_WATCHDOG;
463b5199515SThomas Gleixner 			cs->wd_last = wdnow;
464b5199515SThomas Gleixner 			cs->cs_last = csnow;
465b52f52a0SThomas Gleixner 			continue;
466b52f52a0SThomas Gleixner 		}
467b52f52a0SThomas Gleixner 
46814bd62d5SAdrian Hunter 		wd_nsec = cycles_to_nsec_safe(watchdog, cs->wd_last, wdnow);
46914bd62d5SAdrian Hunter 		cs_nsec = cycles_to_nsec_safe(cs, cs->cs_last, csnow);
4700b046b21SJohn Stultz 		wdlast = cs->wd_last; /* save these in case we print them */
4710b046b21SJohn Stultz 		cslast = cs->cs_last;
472b5199515SThomas Gleixner 		cs->cs_last = csnow;
473b5199515SThomas Gleixner 		cs->wd_last = wdnow;
474b5199515SThomas Gleixner 
4759fb60336SThomas Gleixner 		if (atomic_read(&watchdog_reset_pending))
4769fb60336SThomas Gleixner 			continue;
4779fb60336SThomas Gleixner 
478af7ab5daSJiri Wiesner 		/*
479af7ab5daSJiri Wiesner 		 * The processing of timer softirqs can get delayed (usually
480af7ab5daSJiri Wiesner 		 * on account of ksoftirqd not getting to run in a timely
481af7ab5daSJiri Wiesner 		 * manner), which causes the watchdog interval to stretch.
482af7ab5daSJiri Wiesner 		 * Skew detection may fail for longer watchdog intervals
483af7ab5daSJiri Wiesner 		 * on account of fixed margins being used.
484af7ab5daSJiri Wiesner 		 * Some clocksources, e.g. acpi_pm, cannot tolerate
485af7ab5daSJiri Wiesner 		 * watchdog intervals longer than a few seconds.
486af7ab5daSJiri Wiesner 		 */
487af7ab5daSJiri Wiesner 		interval = max(cs_nsec, wd_nsec);
488af7ab5daSJiri Wiesner 		if (unlikely(interval > WATCHDOG_INTERVAL_MAX_NS)) {
489af7ab5daSJiri Wiesner 			if (system_state > SYSTEM_SCHEDULING &&
490af7ab5daSJiri Wiesner 			    interval > 2 * watchdog_max_interval) {
491af7ab5daSJiri Wiesner 				watchdog_max_interval = interval;
492af7ab5daSJiri Wiesner 				pr_warn("Long readout interval, skipping watchdog check: cs_nsec: %lld wd_nsec: %lld\n",
493af7ab5daSJiri Wiesner 					cs_nsec, wd_nsec);
494af7ab5daSJiri Wiesner 			}
495af7ab5daSJiri Wiesner 			watchdog_timer.expires = jiffies;
496af7ab5daSJiri Wiesner 			continue;
497af7ab5daSJiri Wiesner 		}
498af7ab5daSJiri Wiesner 
499b5199515SThomas Gleixner 		/* Check the deviation from the watchdog clocksource. */
5002e27e793SPaul E. McKenney 		md = cs->uncertainty_margin + watchdog->uncertainty_margin;
5012e27e793SPaul E. McKenney 		if (abs(cs_nsec - wd_nsec) > md) {
502e40806e9SPaul E. McKenney 			s64 cs_wd_msec;
503e40806e9SPaul E. McKenney 			s64 wd_msec;
504dd029269SPaul E. McKenney 			u32 wd_rem;
505dd029269SPaul E. McKenney 
506390dd67cSSeiichi Ikarashi 			pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
507390dd67cSSeiichi Ikarashi 				smp_processor_id(), cs->name);
50822a22383SFeng Tang 			pr_warn("                      '%s' wd_nsec: %lld wd_now: %llx wd_last: %llx mask: %llx\n",
50922a22383SFeng Tang 				watchdog->name, wd_nsec, wdnow, wdlast, watchdog->mask);
51022a22383SFeng Tang 			pr_warn("                      '%s' cs_nsec: %lld cs_now: %llx cs_last: %llx mask: %llx\n",
51122a22383SFeng Tang 				cs->name, cs_nsec, csnow, cslast, cs->mask);
512e40806e9SPaul E. McKenney 			cs_wd_msec = div_s64_rem(cs_nsec - wd_nsec, 1000 * 1000, &wd_rem);
513e40806e9SPaul E. McKenney 			wd_msec = div_s64_rem(wd_nsec, 1000 * 1000, &wd_rem);
514dd029269SPaul E. McKenney 			pr_warn("                      Clocksource '%s' skewed %lld ns (%lld ms) over watchdog '%s' interval of %lld ns (%lld ms)\n",
515dd029269SPaul E. McKenney 				cs->name, cs_nsec - wd_nsec, cs_wd_msec, watchdog->name, wd_nsec, wd_msec);
516fa218f1cSPaul E. McKenney 			if (curr_clocksource == cs)
517fa218f1cSPaul E. McKenney 				pr_warn("                      '%s' is current clocksource.\n", cs->name);
518fa218f1cSPaul E. McKenney 			else if (curr_clocksource)
519fa218f1cSPaul E. McKenney 				pr_warn("                      '%s' (not '%s') is current clocksource.\n", curr_clocksource->name, cs->name);
520fa218f1cSPaul E. McKenney 			else
521fa218f1cSPaul E. McKenney 				pr_warn("                      No current clocksource.\n");
5220b046b21SJohn Stultz 			__clocksource_unstable(cs);
5238cf4e750SMartin Schwidefsky 			continue;
5248cf4e750SMartin Schwidefsky 		}
5258cf4e750SMartin Schwidefsky 
526b421b22bSPeter Zijlstra 		if (cs == curr_clocksource && cs->tick_stable)
527b421b22bSPeter Zijlstra 			cs->tick_stable(cs);
528b421b22bSPeter Zijlstra 
5298cf4e750SMartin Schwidefsky 		if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
5308cf4e750SMartin Schwidefsky 		    (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
5315d8b34fdSThomas Gleixner 		    (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
532332962f2SThomas Gleixner 			/* Mark it valid for high-res. */
5335d8b34fdSThomas Gleixner 			cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
534332962f2SThomas Gleixner 
53579bf2bb3SThomas Gleixner 			/*
536332962f2SThomas Gleixner 			 * clocksource_done_booting() will sort it if
537332962f2SThomas Gleixner 			 * finished_booting is not set yet.
53879bf2bb3SThomas Gleixner 			 */
539332962f2SThomas Gleixner 			if (!finished_booting)
540332962f2SThomas Gleixner 				continue;
541332962f2SThomas Gleixner 
542332962f2SThomas Gleixner 			/*
543332962f2SThomas Gleixner 			 * If this is not the current clocksource let
544332962f2SThomas Gleixner 			 * the watchdog thread reselect it. Due to the
545332962f2SThomas Gleixner 			 * change to high res this clocksource might
546332962f2SThomas Gleixner 			 * be preferred now. If it is the current
547332962f2SThomas Gleixner 			 * clocksource let the tick code know about
548332962f2SThomas Gleixner 			 * that change.
549332962f2SThomas Gleixner 			 */
550332962f2SThomas Gleixner 			if (cs != curr_clocksource) {
551332962f2SThomas Gleixner 				cs->flags |= CLOCK_SOURCE_RESELECT;
552332962f2SThomas Gleixner 				schedule_work(&watchdog_work);
553332962f2SThomas Gleixner 			} else {
55479bf2bb3SThomas Gleixner 				tick_clock_notify();
5555d8b34fdSThomas Gleixner 			}
5565d8b34fdSThomas Gleixner 		}
557332962f2SThomas Gleixner 	}
5585d8b34fdSThomas Gleixner 
5596993fc5bSAndi Kleen 	/*
5609fb60336SThomas Gleixner 	 * We only clear the watchdog_reset_pending, when we did a
5619fb60336SThomas Gleixner 	 * full cycle through all clocksources.
5629fb60336SThomas Gleixner 	 */
5639fb60336SThomas Gleixner 	if (reset_pending)
5649fb60336SThomas Gleixner 		atomic_dec(&watchdog_reset_pending);
5659fb60336SThomas Gleixner 
5669fb60336SThomas Gleixner 	/*
567c55c87c8SMartin Schwidefsky 	 * Cycle through CPUs to check if the CPUs stay synchronized
568c55c87c8SMartin Schwidefsky 	 * to each other.
5696993fc5bSAndi Kleen 	 */
570c55c87c8SMartin Schwidefsky 	next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
571cad0e458SMike Travis 	if (next_cpu >= nr_cpu_ids)
5726b954823SRusty Russell 		next_cpu = cpumask_first(cpu_online_mask);
573febac332SKonstantin Khlebnikov 
574febac332SKonstantin Khlebnikov 	/*
575febac332SKonstantin Khlebnikov 	 * Arm timer if not already pending: could race with concurrent
576febac332SKonstantin Khlebnikov 	 * pair clocksource_stop_watchdog() clocksource_start_watchdog().
577febac332SKonstantin Khlebnikov 	 */
578febac332SKonstantin Khlebnikov 	if (!timer_pending(&watchdog_timer)) {
579b7082cdfSFeng Tang 		watchdog_timer.expires += WATCHDOG_INTERVAL + extra_wait;
5806993fc5bSAndi Kleen 		add_timer_on(&watchdog_timer, next_cpu);
581febac332SKonstantin Khlebnikov 	}
582fb63a0ebSMartin Schwidefsky out:
5835d8b34fdSThomas Gleixner 	spin_unlock(&watchdog_lock);
5845d8b34fdSThomas Gleixner }
5850f8e8ef7SMartin Schwidefsky 
clocksource_start_watchdog(void)586fb63a0ebSMartin Schwidefsky static inline void clocksource_start_watchdog(void)
587fb63a0ebSMartin Schwidefsky {
588fb63a0ebSMartin Schwidefsky 	if (watchdog_running || !watchdog || list_empty(&watchdog_list))
589fb63a0ebSMartin Schwidefsky 		return;
590e99e88a9SKees Cook 	timer_setup(&watchdog_timer, clocksource_watchdog, 0);
591fb63a0ebSMartin Schwidefsky 	watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
592fb63a0ebSMartin Schwidefsky 	add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
593fb63a0ebSMartin Schwidefsky 	watchdog_running = 1;
594fb63a0ebSMartin Schwidefsky }
595fb63a0ebSMartin Schwidefsky 
clocksource_stop_watchdog(void)596fb63a0ebSMartin Schwidefsky static inline void clocksource_stop_watchdog(void)
597fb63a0ebSMartin Schwidefsky {
598fb63a0ebSMartin Schwidefsky 	if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
599fb63a0ebSMartin Schwidefsky 		return;
600fb63a0ebSMartin Schwidefsky 	del_timer(&watchdog_timer);
601fb63a0ebSMartin Schwidefsky 	watchdog_running = 0;
602fb63a0ebSMartin Schwidefsky }
603fb63a0ebSMartin Schwidefsky 
clocksource_resume_watchdog(void)604b52f52a0SThomas Gleixner static void clocksource_resume_watchdog(void)
605b52f52a0SThomas Gleixner {
6069fb60336SThomas Gleixner 	atomic_inc(&watchdog_reset_pending);
607b52f52a0SThomas Gleixner }
608b52f52a0SThomas Gleixner 
clocksource_enqueue_watchdog(struct clocksource * cs)609fb63a0ebSMartin Schwidefsky static void clocksource_enqueue_watchdog(struct clocksource *cs)
6105d8b34fdSThomas Gleixner {
6115b9e886aSPeter Zijlstra 	INIT_LIST_HEAD(&cs->wd_list);
6125b9e886aSPeter Zijlstra 
6135d8b34fdSThomas Gleixner 	if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
614fb63a0ebSMartin Schwidefsky 		/* cs is a clocksource to be watched. */
6155d8b34fdSThomas Gleixner 		list_add(&cs->wd_list, &watchdog_list);
616fb63a0ebSMartin Schwidefsky 		cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
617948ac6d7SThomas Gleixner 	} else {
618fb63a0ebSMartin Schwidefsky 		/* cs is a watchdog. */
619948ac6d7SThomas Gleixner 		if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
6205d8b34fdSThomas Gleixner 			cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
621bbf66d89SVitaly Kuznetsov 	}
622bbf66d89SVitaly Kuznetsov }
623bbf66d89SVitaly Kuznetsov 
clocksource_select_watchdog(bool fallback)624bbf66d89SVitaly Kuznetsov static void clocksource_select_watchdog(bool fallback)
625bbf66d89SVitaly Kuznetsov {
626bbf66d89SVitaly Kuznetsov 	struct clocksource *cs, *old_wd;
627bbf66d89SVitaly Kuznetsov 	unsigned long flags;
628bbf66d89SVitaly Kuznetsov 
629bbf66d89SVitaly Kuznetsov 	spin_lock_irqsave(&watchdog_lock, flags);
630bbf66d89SVitaly Kuznetsov 	/* save current watchdog */
631bbf66d89SVitaly Kuznetsov 	old_wd = watchdog;
632bbf66d89SVitaly Kuznetsov 	if (fallback)
633bbf66d89SVitaly Kuznetsov 		watchdog = NULL;
634bbf66d89SVitaly Kuznetsov 
635bbf66d89SVitaly Kuznetsov 	list_for_each_entry(cs, &clocksource_list, list) {
636bbf66d89SVitaly Kuznetsov 		/* cs is a clocksource to be watched. */
637bbf66d89SVitaly Kuznetsov 		if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
638bbf66d89SVitaly Kuznetsov 			continue;
639bbf66d89SVitaly Kuznetsov 
640bbf66d89SVitaly Kuznetsov 		/* Skip current if we were requested for a fallback. */
641bbf66d89SVitaly Kuznetsov 		if (fallback && cs == old_wd)
642bbf66d89SVitaly Kuznetsov 			continue;
643bbf66d89SVitaly Kuznetsov 
644fb63a0ebSMartin Schwidefsky 		/* Pick the best watchdog. */
645bbf66d89SVitaly Kuznetsov 		if (!watchdog || cs->rating > watchdog->rating)
6465d8b34fdSThomas Gleixner 			watchdog = cs;
647bbf66d89SVitaly Kuznetsov 	}
648bbf66d89SVitaly Kuznetsov 	/* If we failed to find a fallback restore the old one. */
649bbf66d89SVitaly Kuznetsov 	if (!watchdog)
650bbf66d89SVitaly Kuznetsov 		watchdog = old_wd;
651bbf66d89SVitaly Kuznetsov 
652bbf66d89SVitaly Kuznetsov 	/* If we changed the watchdog we need to reset cycles. */
653bbf66d89SVitaly Kuznetsov 	if (watchdog != old_wd)
6540f8e8ef7SMartin Schwidefsky 		clocksource_reset_watchdog();
655bbf66d89SVitaly Kuznetsov 
656fb63a0ebSMartin Schwidefsky 	/* Check if the watchdog timer needs to be started. */
657fb63a0ebSMartin Schwidefsky 	clocksource_start_watchdog();
6585d8b34fdSThomas Gleixner 	spin_unlock_irqrestore(&watchdog_lock, flags);
6595d8b34fdSThomas Gleixner }
660fb63a0ebSMartin Schwidefsky 
clocksource_dequeue_watchdog(struct clocksource * cs)661fb63a0ebSMartin Schwidefsky static void clocksource_dequeue_watchdog(struct clocksource *cs)
662fb63a0ebSMartin Schwidefsky {
663a89c7edbSThomas Gleixner 	if (cs != watchdog) {
664fb63a0ebSMartin Schwidefsky 		if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
665fb63a0ebSMartin Schwidefsky 			/* cs is a watched clocksource. */
666fb63a0ebSMartin Schwidefsky 			list_del_init(&cs->wd_list);
667fb63a0ebSMartin Schwidefsky 			/* Check if the watchdog timer needs to be stopped. */
668fb63a0ebSMartin Schwidefsky 			clocksource_stop_watchdog();
669a89c7edbSThomas Gleixner 		}
670a89c7edbSThomas Gleixner 	}
671fb63a0ebSMartin Schwidefsky }
672fb63a0ebSMartin Schwidefsky 
__clocksource_watchdog_kthread(void)673e2c631baSPeter Zijlstra static int __clocksource_watchdog_kthread(void)
674c55c87c8SMartin Schwidefsky {
675c55c87c8SMartin Schwidefsky 	struct clocksource *cs, *tmp;
676c55c87c8SMartin Schwidefsky 	unsigned long flags;
677332962f2SThomas Gleixner 	int select = 0;
678c55c87c8SMartin Schwidefsky 
6797560c02bSPaul E. McKenney 	/* Do any required per-CPU skew verification. */
6807560c02bSPaul E. McKenney 	if (curr_clocksource &&
6817560c02bSPaul E. McKenney 	    curr_clocksource->flags & CLOCK_SOURCE_UNSTABLE &&
6827560c02bSPaul E. McKenney 	    curr_clocksource->flags & CLOCK_SOURCE_VERIFY_PERCPU)
6837560c02bSPaul E. McKenney 		clocksource_verify_percpu(curr_clocksource);
6847560c02bSPaul E. McKenney 
685c55c87c8SMartin Schwidefsky 	spin_lock_irqsave(&watchdog_lock, flags);
686332962f2SThomas Gleixner 	list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
687c55c87c8SMartin Schwidefsky 		if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
688c55c87c8SMartin Schwidefsky 			list_del_init(&cs->wd_list);
6892aae7bcfSPeter Zijlstra 			__clocksource_change_rating(cs, 0);
690332962f2SThomas Gleixner 			select = 1;
691332962f2SThomas Gleixner 		}
692332962f2SThomas Gleixner 		if (cs->flags & CLOCK_SOURCE_RESELECT) {
693332962f2SThomas Gleixner 			cs->flags &= ~CLOCK_SOURCE_RESELECT;
694332962f2SThomas Gleixner 			select = 1;
695332962f2SThomas Gleixner 		}
696c55c87c8SMartin Schwidefsky 	}
697c55c87c8SMartin Schwidefsky 	/* Check if the watchdog timer needs to be stopped. */
698c55c87c8SMartin Schwidefsky 	clocksource_stop_watchdog();
6996ea41d25SThomas Gleixner 	spin_unlock_irqrestore(&watchdog_lock, flags);
7006ea41d25SThomas Gleixner 
701332962f2SThomas Gleixner 	return select;
702332962f2SThomas Gleixner }
703332962f2SThomas Gleixner 
clocksource_watchdog_kthread(void * data)704e2c631baSPeter Zijlstra static int clocksource_watchdog_kthread(void *data)
705332962f2SThomas Gleixner {
706332962f2SThomas Gleixner 	mutex_lock(&clocksource_mutex);
707e2c631baSPeter Zijlstra 	if (__clocksource_watchdog_kthread())
708332962f2SThomas Gleixner 		clocksource_select();
709d0981a1bSThomas Gleixner 	mutex_unlock(&clocksource_mutex);
710e2c631baSPeter Zijlstra 	return 0;
711c55c87c8SMartin Schwidefsky }
712c55c87c8SMartin Schwidefsky 
clocksource_is_watchdog(struct clocksource * cs)7137eaeb343SThomas Gleixner static bool clocksource_is_watchdog(struct clocksource *cs)
7147eaeb343SThomas Gleixner {
7157eaeb343SThomas Gleixner 	return cs == watchdog;
7167eaeb343SThomas Gleixner }
7177eaeb343SThomas Gleixner 
718fb63a0ebSMartin Schwidefsky #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
719fb63a0ebSMartin Schwidefsky 
clocksource_enqueue_watchdog(struct clocksource * cs)720fb63a0ebSMartin Schwidefsky static void clocksource_enqueue_watchdog(struct clocksource *cs)
7215d8b34fdSThomas Gleixner {
7225d8b34fdSThomas Gleixner 	if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
7235d8b34fdSThomas Gleixner 		cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
7245d8b34fdSThomas Gleixner }
725b52f52a0SThomas Gleixner 
clocksource_select_watchdog(bool fallback)726bbf66d89SVitaly Kuznetsov static void clocksource_select_watchdog(bool fallback) { }
clocksource_dequeue_watchdog(struct clocksource * cs)727fb63a0ebSMartin Schwidefsky static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
clocksource_resume_watchdog(void)728b52f52a0SThomas Gleixner static inline void clocksource_resume_watchdog(void) { }
__clocksource_watchdog_kthread(void)729e2c631baSPeter Zijlstra static inline int __clocksource_watchdog_kthread(void) { return 0; }
clocksource_is_watchdog(struct clocksource * cs)7307eaeb343SThomas Gleixner static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
clocksource_mark_unstable(struct clocksource * cs)731397bbf6dSPrarit Bhargava void clocksource_mark_unstable(struct clocksource *cs) { }
732fb63a0ebSMartin Schwidefsky 
clocksource_watchdog_lock(unsigned long * flags)733db6f9e55SMathieu Malaterre static inline void clocksource_watchdog_lock(unsigned long *flags) { }
clocksource_watchdog_unlock(unsigned long * flags)734db6f9e55SMathieu Malaterre static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
7352aae7bcfSPeter Zijlstra 
736fb63a0ebSMartin Schwidefsky #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
7375d8b34fdSThomas Gleixner 
clocksource_is_suspend(struct clocksource * cs)73839232ed5SBaolin Wang static bool clocksource_is_suspend(struct clocksource *cs)
73939232ed5SBaolin Wang {
74039232ed5SBaolin Wang 	return cs == suspend_clocksource;
74139232ed5SBaolin Wang }
74239232ed5SBaolin Wang 
__clocksource_suspend_select(struct clocksource * cs)74339232ed5SBaolin Wang static void __clocksource_suspend_select(struct clocksource *cs)
74439232ed5SBaolin Wang {
74539232ed5SBaolin Wang 	/*
74639232ed5SBaolin Wang 	 * Skip the clocksource which will be stopped in suspend state.
74739232ed5SBaolin Wang 	 */
74839232ed5SBaolin Wang 	if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
74939232ed5SBaolin Wang 		return;
75039232ed5SBaolin Wang 
75139232ed5SBaolin Wang 	/*
75239232ed5SBaolin Wang 	 * The nonstop clocksource can be selected as the suspend clocksource to
75339232ed5SBaolin Wang 	 * calculate the suspend time, so it should not supply suspend/resume
75439232ed5SBaolin Wang 	 * interfaces to suspend the nonstop clocksource when system suspends.
75539232ed5SBaolin Wang 	 */
75639232ed5SBaolin Wang 	if (cs->suspend || cs->resume) {
75739232ed5SBaolin Wang 		pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
75839232ed5SBaolin Wang 			cs->name);
75939232ed5SBaolin Wang 	}
76039232ed5SBaolin Wang 
76139232ed5SBaolin Wang 	/* Pick the best rating. */
76239232ed5SBaolin Wang 	if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
76339232ed5SBaolin Wang 		suspend_clocksource = cs;
76439232ed5SBaolin Wang }
76539232ed5SBaolin Wang 
76639232ed5SBaolin Wang /**
76739232ed5SBaolin Wang  * clocksource_suspend_select - Select the best clocksource for suspend timing
76839232ed5SBaolin Wang  * @fallback:	if select a fallback clocksource
76939232ed5SBaolin Wang  */
clocksource_suspend_select(bool fallback)77039232ed5SBaolin Wang static void clocksource_suspend_select(bool fallback)
77139232ed5SBaolin Wang {
77239232ed5SBaolin Wang 	struct clocksource *cs, *old_suspend;
77339232ed5SBaolin Wang 
77439232ed5SBaolin Wang 	old_suspend = suspend_clocksource;
77539232ed5SBaolin Wang 	if (fallback)
77639232ed5SBaolin Wang 		suspend_clocksource = NULL;
77739232ed5SBaolin Wang 
77839232ed5SBaolin Wang 	list_for_each_entry(cs, &clocksource_list, list) {
77939232ed5SBaolin Wang 		/* Skip current if we were requested for a fallback. */
78039232ed5SBaolin Wang 		if (fallback && cs == old_suspend)
78139232ed5SBaolin Wang 			continue;
78239232ed5SBaolin Wang 
78339232ed5SBaolin Wang 		__clocksource_suspend_select(cs);
78439232ed5SBaolin Wang 	}
78539232ed5SBaolin Wang }
78639232ed5SBaolin Wang 
78739232ed5SBaolin Wang /**
78839232ed5SBaolin Wang  * clocksource_start_suspend_timing - Start measuring the suspend timing
78939232ed5SBaolin Wang  * @cs:			current clocksource from timekeeping
79039232ed5SBaolin Wang  * @start_cycles:	current cycles from timekeeping
79139232ed5SBaolin Wang  *
79239232ed5SBaolin Wang  * This function will save the start cycle values of suspend timer to calculate
79339232ed5SBaolin Wang  * the suspend time when resuming system.
79439232ed5SBaolin Wang  *
79539232ed5SBaolin Wang  * This function is called late in the suspend process from timekeeping_suspend(),
7964bf07f65SIngo Molnar  * that means processes are frozen, non-boot cpus and interrupts are disabled
79739232ed5SBaolin Wang  * now. It is therefore possible to start the suspend timer without taking the
79839232ed5SBaolin Wang  * clocksource mutex.
79939232ed5SBaolin Wang  */
clocksource_start_suspend_timing(struct clocksource * cs,u64 start_cycles)80039232ed5SBaolin Wang void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
80139232ed5SBaolin Wang {
80239232ed5SBaolin Wang 	if (!suspend_clocksource)
80339232ed5SBaolin Wang 		return;
80439232ed5SBaolin Wang 
80539232ed5SBaolin Wang 	/*
80639232ed5SBaolin Wang 	 * If current clocksource is the suspend timer, we should use the
80739232ed5SBaolin Wang 	 * tkr_mono.cycle_last value as suspend_start to avoid same reading
80839232ed5SBaolin Wang 	 * from suspend timer.
80939232ed5SBaolin Wang 	 */
81039232ed5SBaolin Wang 	if (clocksource_is_suspend(cs)) {
81139232ed5SBaolin Wang 		suspend_start = start_cycles;
81239232ed5SBaolin Wang 		return;
81339232ed5SBaolin Wang 	}
81439232ed5SBaolin Wang 
81539232ed5SBaolin Wang 	if (suspend_clocksource->enable &&
81639232ed5SBaolin Wang 	    suspend_clocksource->enable(suspend_clocksource)) {
81739232ed5SBaolin Wang 		pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
81839232ed5SBaolin Wang 		return;
81939232ed5SBaolin Wang 	}
82039232ed5SBaolin Wang 
82139232ed5SBaolin Wang 	suspend_start = suspend_clocksource->read(suspend_clocksource);
82239232ed5SBaolin Wang }
82339232ed5SBaolin Wang 
82439232ed5SBaolin Wang /**
82539232ed5SBaolin Wang  * clocksource_stop_suspend_timing - Stop measuring the suspend timing
82639232ed5SBaolin Wang  * @cs:		current clocksource from timekeeping
82739232ed5SBaolin Wang  * @cycle_now:	current cycles from timekeeping
82839232ed5SBaolin Wang  *
82939232ed5SBaolin Wang  * This function will calculate the suspend time from suspend timer.
83039232ed5SBaolin Wang  *
83139232ed5SBaolin Wang  * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
83239232ed5SBaolin Wang  *
83339232ed5SBaolin Wang  * This function is called early in the resume process from timekeeping_resume(),
83439232ed5SBaolin Wang  * that means there is only one cpu, no processes are running and the interrupts
83539232ed5SBaolin Wang  * are disabled. It is therefore possible to stop the suspend timer without
83639232ed5SBaolin Wang  * taking the clocksource mutex.
83739232ed5SBaolin Wang  */
clocksource_stop_suspend_timing(struct clocksource * cs,u64 cycle_now)83839232ed5SBaolin Wang u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
83939232ed5SBaolin Wang {
84014bd62d5SAdrian Hunter 	u64 now, nsec = 0;
84139232ed5SBaolin Wang 
84239232ed5SBaolin Wang 	if (!suspend_clocksource)
84339232ed5SBaolin Wang 		return 0;
84439232ed5SBaolin Wang 
84539232ed5SBaolin Wang 	/*
84639232ed5SBaolin Wang 	 * If current clocksource is the suspend timer, we should use the
84739232ed5SBaolin Wang 	 * tkr_mono.cycle_last value from timekeeping as current cycle to
84839232ed5SBaolin Wang 	 * avoid same reading from suspend timer.
84939232ed5SBaolin Wang 	 */
85039232ed5SBaolin Wang 	if (clocksource_is_suspend(cs))
85139232ed5SBaolin Wang 		now = cycle_now;
85239232ed5SBaolin Wang 	else
85339232ed5SBaolin Wang 		now = suspend_clocksource->read(suspend_clocksource);
85439232ed5SBaolin Wang 
85514bd62d5SAdrian Hunter 	if (now > suspend_start)
85614bd62d5SAdrian Hunter 		nsec = cycles_to_nsec_safe(suspend_clocksource, suspend_start, now);
85739232ed5SBaolin Wang 
85839232ed5SBaolin Wang 	/*
85939232ed5SBaolin Wang 	 * Disable the suspend timer to save power if current clocksource is
86039232ed5SBaolin Wang 	 * not the suspend timer.
86139232ed5SBaolin Wang 	 */
86239232ed5SBaolin Wang 	if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
86339232ed5SBaolin Wang 		suspend_clocksource->disable(suspend_clocksource);
86439232ed5SBaolin Wang 
86539232ed5SBaolin Wang 	return nsec;
86639232ed5SBaolin Wang }
86739232ed5SBaolin Wang 
868734efb46Sjohn stultz /**
869c54a42b1SMagnus Damm  * clocksource_suspend - suspend the clocksource(s)
870c54a42b1SMagnus Damm  */
clocksource_suspend(void)871c54a42b1SMagnus Damm void clocksource_suspend(void)
872c54a42b1SMagnus Damm {
873c54a42b1SMagnus Damm 	struct clocksource *cs;
874c54a42b1SMagnus Damm 
875c54a42b1SMagnus Damm 	list_for_each_entry_reverse(cs, &clocksource_list, list)
876c54a42b1SMagnus Damm 		if (cs->suspend)
877c54a42b1SMagnus Damm 			cs->suspend(cs);
878c54a42b1SMagnus Damm }
879c54a42b1SMagnus Damm 
880c54a42b1SMagnus Damm /**
881b52f52a0SThomas Gleixner  * clocksource_resume - resume the clocksource(s)
882b52f52a0SThomas Gleixner  */
clocksource_resume(void)883b52f52a0SThomas Gleixner void clocksource_resume(void)
884b52f52a0SThomas Gleixner {
8852e197586SMatthias Kaehlcke 	struct clocksource *cs;
886b52f52a0SThomas Gleixner 
88775c5158fSMartin Schwidefsky 	list_for_each_entry(cs, &clocksource_list, list)
888b52f52a0SThomas Gleixner 		if (cs->resume)
88917622339SMagnus Damm 			cs->resume(cs);
890b52f52a0SThomas Gleixner 
891b52f52a0SThomas Gleixner 	clocksource_resume_watchdog();
892b52f52a0SThomas Gleixner }
893b52f52a0SThomas Gleixner 
894b52f52a0SThomas Gleixner /**
8957c3078b6SJason Wessel  * clocksource_touch_watchdog - Update watchdog
8967c3078b6SJason Wessel  *
8977c3078b6SJason Wessel  * Update the watchdog after exception contexts such as kgdb so as not
8987b7422a5SThomas Gleixner  * to incorrectly trip the watchdog. This might fail when the kernel
8997b7422a5SThomas Gleixner  * was stopped in code which holds watchdog_lock.
9007c3078b6SJason Wessel  */
clocksource_touch_watchdog(void)9017c3078b6SJason Wessel void clocksource_touch_watchdog(void)
9027c3078b6SJason Wessel {
9037c3078b6SJason Wessel 	clocksource_resume_watchdog();
9047c3078b6SJason Wessel }
9057c3078b6SJason Wessel 
906734efb46Sjohn stultz /**
907d65670a7SJohn Stultz  * clocksource_max_adjustment- Returns max adjustment amount
908d65670a7SJohn Stultz  * @cs:         Pointer to clocksource
909d65670a7SJohn Stultz  *
910d65670a7SJohn Stultz  */
clocksource_max_adjustment(struct clocksource * cs)911d65670a7SJohn Stultz static u32 clocksource_max_adjustment(struct clocksource *cs)
912d65670a7SJohn Stultz {
913d65670a7SJohn Stultz 	u64 ret;
914d65670a7SJohn Stultz 	/*
91588b28adfSJim Cromie 	 * We won't try to correct for more than 11% adjustments (110,000 ppm),
916d65670a7SJohn Stultz 	 */
917d65670a7SJohn Stultz 	ret = (u64)cs->mult * 11;
918d65670a7SJohn Stultz 	do_div(ret,100);
919d65670a7SJohn Stultz 	return (u32)ret;
920d65670a7SJohn Stultz }
921d65670a7SJohn Stultz 
922d65670a7SJohn Stultz /**
92387d8b9ebSStephen Boyd  * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
92487d8b9ebSStephen Boyd  * @mult:	cycle to nanosecond multiplier
92587d8b9ebSStephen Boyd  * @shift:	cycle to nanosecond divisor (power of two)
92687d8b9ebSStephen Boyd  * @maxadj:	maximum adjustment value to mult (~11%)
92787d8b9ebSStephen Boyd  * @mask:	bitmask for two's complement subtraction of non 64 bit counters
928fb82fe2fSJohn Stultz  * @max_cyc:	maximum cycle value before potential overflow (does not include
929fb82fe2fSJohn Stultz  *		any safety margin)
930362fde04SJohn Stultz  *
9318e56f33fSJohn Stultz  * NOTE: This function includes a safety margin of 50%, in other words, we
9328e56f33fSJohn Stultz  * return half the number of nanoseconds the hardware counter can technically
9338e56f33fSJohn Stultz  * cover. This is done so that we can potentially detect problems caused by
9348e56f33fSJohn Stultz  * delayed timers or bad hardware, which might result in time intervals that
935571af55aSZhen Lei  * are larger than what the math used can handle without overflows.
93698962465SJon Hunter  */
clocks_calc_max_nsecs(u32 mult,u32 shift,u32 maxadj,u64 mask,u64 * max_cyc)937fb82fe2fSJohn Stultz u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
93898962465SJon Hunter {
93998962465SJon Hunter 	u64 max_nsecs, max_cycles;
94098962465SJon Hunter 
94198962465SJon Hunter 	/*
94298962465SJon Hunter 	 * Calculate the maximum number of cycles that we can pass to the
9436086e346SJohn Stultz 	 * cyc2ns() function without overflowing a 64-bit result.
94498962465SJon Hunter 	 */
9456086e346SJohn Stultz 	max_cycles = ULLONG_MAX;
9466086e346SJohn Stultz 	do_div(max_cycles, mult+maxadj);
94798962465SJon Hunter 
94898962465SJon Hunter 	/*
94998962465SJon Hunter 	 * The actual maximum number of cycles we can defer the clocksource is
95087d8b9ebSStephen Boyd 	 * determined by the minimum of max_cycles and mask.
951d65670a7SJohn Stultz 	 * Note: Here we subtract the maxadj to make sure we don't sleep for
952d65670a7SJohn Stultz 	 * too long if there's a large negative adjustment.
95398962465SJon Hunter 	 */
95487d8b9ebSStephen Boyd 	max_cycles = min(max_cycles, mask);
95587d8b9ebSStephen Boyd 	max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
95698962465SJon Hunter 
957fb82fe2fSJohn Stultz 	/* return the max_cycles value as well if requested */
958fb82fe2fSJohn Stultz 	if (max_cyc)
959fb82fe2fSJohn Stultz 		*max_cyc = max_cycles;
960fb82fe2fSJohn Stultz 
961362fde04SJohn Stultz 	/* Return 50% of the actual maximum, so we can detect bad values */
962362fde04SJohn Stultz 	max_nsecs >>= 1;
963362fde04SJohn Stultz 
96487d8b9ebSStephen Boyd 	return max_nsecs;
96587d8b9ebSStephen Boyd }
96687d8b9ebSStephen Boyd 
96787d8b9ebSStephen Boyd /**
968fb82fe2fSJohn Stultz  * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
969fb82fe2fSJohn Stultz  * @cs:         Pointer to clocksource to be updated
97087d8b9ebSStephen Boyd  *
97187d8b9ebSStephen Boyd  */
clocksource_update_max_deferment(struct clocksource * cs)972fb82fe2fSJohn Stultz static inline void clocksource_update_max_deferment(struct clocksource *cs)
97387d8b9ebSStephen Boyd {
974fb82fe2fSJohn Stultz 	cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
975fb82fe2fSJohn Stultz 						cs->maxadj, cs->mask,
976fb82fe2fSJohn Stultz 						&cs->max_cycles);
97798962465SJon Hunter }
97898962465SJon Hunter 
clocksource_find_best(bool oneshot,bool skipcur)979f5a2e343SThomas Gleixner static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
9805d33b883SThomas Gleixner {
9815d33b883SThomas Gleixner 	struct clocksource *cs;
9825d33b883SThomas Gleixner 
9835d33b883SThomas Gleixner 	if (!finished_booting || list_empty(&clocksource_list))
9845d33b883SThomas Gleixner 		return NULL;
9855d33b883SThomas Gleixner 
9865d33b883SThomas Gleixner 	/*
9875d33b883SThomas Gleixner 	 * We pick the clocksource with the highest rating. If oneshot
9885d33b883SThomas Gleixner 	 * mode is active, we pick the highres valid clocksource with
9895d33b883SThomas Gleixner 	 * the best rating.
9905d33b883SThomas Gleixner 	 */
9915d33b883SThomas Gleixner 	list_for_each_entry(cs, &clocksource_list, list) {
992f5a2e343SThomas Gleixner 		if (skipcur && cs == curr_clocksource)
993f5a2e343SThomas Gleixner 			continue;
9945d33b883SThomas Gleixner 		if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
9955d33b883SThomas Gleixner 			continue;
9965d33b883SThomas Gleixner 		return cs;
9975d33b883SThomas Gleixner 	}
9985d33b883SThomas Gleixner 	return NULL;
9995d33b883SThomas Gleixner }
10005d33b883SThomas Gleixner 
__clocksource_select(bool skipcur)1001f5a2e343SThomas Gleixner static void __clocksource_select(bool skipcur)
1002734efb46Sjohn stultz {
10035d33b883SThomas Gleixner 	bool oneshot = tick_oneshot_mode_active();
1004f1b82746SMartin Schwidefsky 	struct clocksource *best, *cs;
10055d8b34fdSThomas Gleixner 
10065d33b883SThomas Gleixner 	/* Find the best suitable clocksource */
1007f5a2e343SThomas Gleixner 	best = clocksource_find_best(oneshot, skipcur);
10085d33b883SThomas Gleixner 	if (!best)
1009f1b82746SMartin Schwidefsky 		return;
10105d33b883SThomas Gleixner 
10117f852afeSBaolin Wang 	if (!strlen(override_name))
10127f852afeSBaolin Wang 		goto found;
10137f852afeSBaolin Wang 
1014f1b82746SMartin Schwidefsky 	/* Check for the override clocksource. */
1015f1b82746SMartin Schwidefsky 	list_for_each_entry(cs, &clocksource_list, list) {
1016f5a2e343SThomas Gleixner 		if (skipcur && cs == curr_clocksource)
1017f5a2e343SThomas Gleixner 			continue;
1018f1b82746SMartin Schwidefsky 		if (strcmp(cs->name, override_name) != 0)
1019f1b82746SMartin Schwidefsky 			continue;
1020f1b82746SMartin Schwidefsky 		/*
1021f1b82746SMartin Schwidefsky 		 * Check to make sure we don't switch to a non-highres
1022f1b82746SMartin Schwidefsky 		 * capable clocksource if the tick code is in oneshot
1023f1b82746SMartin Schwidefsky 		 * mode (highres or nohz)
1024f1b82746SMartin Schwidefsky 		 */
10255d33b883SThomas Gleixner 		if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
1026f1b82746SMartin Schwidefsky 			/* Override clocksource cannot be used. */
102736374583SKyle Walker 			if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
102836374583SKyle Walker 				pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
102945bbfe64SJoe Perches 					cs->name);
1030f1b82746SMartin Schwidefsky 				override_name[0] = 0;
103136374583SKyle Walker 			} else {
103236374583SKyle Walker 				/*
103336374583SKyle Walker 				 * The override cannot be currently verified.
103436374583SKyle Walker 				 * Deferring to let the watchdog check.
103536374583SKyle Walker 				 */
103636374583SKyle Walker 				pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
103736374583SKyle Walker 					cs->name);
103836374583SKyle Walker 			}
1039f1b82746SMartin Schwidefsky 		} else
1040f1b82746SMartin Schwidefsky 			/* Override clocksource can be used. */
1041f1b82746SMartin Schwidefsky 			best = cs;
1042f1b82746SMartin Schwidefsky 		break;
1043734efb46Sjohn stultz 	}
1044ba919d1cSThomas Gleixner 
10457f852afeSBaolin Wang found:
1046ba919d1cSThomas Gleixner 	if (curr_clocksource != best && !timekeeping_notify(best)) {
1047ba919d1cSThomas Gleixner 		pr_info("Switched to clocksource %s\n", best->name);
104875c5158fSMartin Schwidefsky 		curr_clocksource = best;
1049f1b82746SMartin Schwidefsky 	}
105075c5158fSMartin Schwidefsky }
105175c5158fSMartin Schwidefsky 
1052f5a2e343SThomas Gleixner /**
1053f5a2e343SThomas Gleixner  * clocksource_select - Select the best clocksource available
1054f5a2e343SThomas Gleixner  *
1055f5a2e343SThomas Gleixner  * Private function. Must hold clocksource_mutex when called.
1056f5a2e343SThomas Gleixner  *
1057f5a2e343SThomas Gleixner  * Select the clocksource with the best rating, or the clocksource,
1058f5a2e343SThomas Gleixner  * which is selected by userspace override.
1059f5a2e343SThomas Gleixner  */
clocksource_select(void)1060f5a2e343SThomas Gleixner static void clocksource_select(void)
1061f5a2e343SThomas Gleixner {
1062cfed432dSGuillaume Gomez 	__clocksource_select(false);
1063f5a2e343SThomas Gleixner }
1064f5a2e343SThomas Gleixner 
clocksource_select_fallback(void)10657eaeb343SThomas Gleixner static void clocksource_select_fallback(void)
10667eaeb343SThomas Gleixner {
1067cfed432dSGuillaume Gomez 	__clocksource_select(true);
10687eaeb343SThomas Gleixner }
10697eaeb343SThomas Gleixner 
107075c5158fSMartin Schwidefsky /*
107175c5158fSMartin Schwidefsky  * clocksource_done_booting - Called near the end of core bootup
107275c5158fSMartin Schwidefsky  *
107375c5158fSMartin Schwidefsky  * Hack to avoid lots of clocksource churn at boot time.
107475c5158fSMartin Schwidefsky  * We use fs_initcall because we want this to start before
107575c5158fSMartin Schwidefsky  * device_initcall but after subsys_initcall.
107675c5158fSMartin Schwidefsky  */
clocksource_done_booting(void)107775c5158fSMartin Schwidefsky static int __init clocksource_done_booting(void)
107875c5158fSMartin Schwidefsky {
1079ad6759fbSjohn stultz 	mutex_lock(&clocksource_mutex);
1080ad6759fbSjohn stultz 	curr_clocksource = clocksource_default_clock();
108175c5158fSMartin Schwidefsky 	finished_booting = 1;
108254a6bc0bSThomas Gleixner 	/*
108354a6bc0bSThomas Gleixner 	 * Run the watchdog first to eliminate unstable clock sources
108454a6bc0bSThomas Gleixner 	 */
1085e2c631baSPeter Zijlstra 	__clocksource_watchdog_kthread();
108675c5158fSMartin Schwidefsky 	clocksource_select();
1087e6c73305SThomas Gleixner 	mutex_unlock(&clocksource_mutex);
108875c5158fSMartin Schwidefsky 	return 0;
108975c5158fSMartin Schwidefsky }
109075c5158fSMartin Schwidefsky fs_initcall(clocksource_done_booting);
1091f1b82746SMartin Schwidefsky 
109292c7e002SThomas Gleixner /*
109392c7e002SThomas Gleixner  * Enqueue the clocksource sorted by rating
1094734efb46Sjohn stultz  */
clocksource_enqueue(struct clocksource * cs)1095f1b82746SMartin Schwidefsky static void clocksource_enqueue(struct clocksource *cs)
1096734efb46Sjohn stultz {
1097f1b82746SMartin Schwidefsky 	struct list_head *entry = &clocksource_list;
1098f1b82746SMartin Schwidefsky 	struct clocksource *tmp;
1099734efb46Sjohn stultz 
11000fb71d34SMinfei Huang 	list_for_each_entry(tmp, &clocksource_list, list) {
110192c7e002SThomas Gleixner 		/* Keep track of the place, where to insert */
11020fb71d34SMinfei Huang 		if (tmp->rating < cs->rating)
11030fb71d34SMinfei Huang 			break;
1104f1b82746SMartin Schwidefsky 		entry = &tmp->list;
11050fb71d34SMinfei Huang 	}
1106f1b82746SMartin Schwidefsky 	list_add(&cs->list, entry);
1107734efb46Sjohn stultz }
1108734efb46Sjohn stultz 
1109d7e81c26SJohn Stultz /**
1110fba9e072SJohn Stultz  * __clocksource_update_freq_scale - Used update clocksource with new freq
1111b1b73d09SKusanagi Kouichi  * @cs:		clocksource to be registered
1112852db46dSJohn Stultz  * @scale:	Scale factor multiplied against freq to get clocksource hz
1113852db46dSJohn Stultz  * @freq:	clocksource frequency (cycles per second) divided by scale
1114852db46dSJohn Stultz  *
1115852db46dSJohn Stultz  * This should only be called from the clocksource->enable() method.
1116852db46dSJohn Stultz  *
1117852db46dSJohn Stultz  * This *SHOULD NOT* be called directly! Please use the
1118fba9e072SJohn Stultz  * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
1119fba9e072SJohn Stultz  * functions.
1120852db46dSJohn Stultz  */
__clocksource_update_freq_scale(struct clocksource * cs,u32 scale,u32 freq)1121fba9e072SJohn Stultz void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
1122852db46dSJohn Stultz {
1123c0e299b1SThomas Gleixner 	u64 sec;
1124f8935983SJohn Stultz 
1125f8935983SJohn Stultz 	/*
1126f8935983SJohn Stultz 	 * Default clocksources are *special* and self-define their mult/shift.
1127f8935983SJohn Stultz 	 * But, you're not special, so you should specify a freq value.
1128f8935983SJohn Stultz 	 */
1129f8935983SJohn Stultz 	if (freq) {
1130852db46dSJohn Stultz 		/*
1131724ed53eSThomas Gleixner 		 * Calc the maximum number of seconds which we can run before
1132f8935983SJohn Stultz 		 * wrapping around. For clocksources which have a mask > 32-bit
1133724ed53eSThomas Gleixner 		 * we need to limit the max sleep time to have a good
1134724ed53eSThomas Gleixner 		 * conversion precision. 10 minutes is still a reasonable
1135724ed53eSThomas Gleixner 		 * amount. That results in a shift value of 24 for a
1136f8935983SJohn Stultz 		 * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
1137362fde04SJohn Stultz 		 * ~ 0.06ppm granularity for NTP.
1138852db46dSJohn Stultz 		 */
1139362fde04SJohn Stultz 		sec = cs->mask;
1140724ed53eSThomas Gleixner 		do_div(sec, freq);
1141724ed53eSThomas Gleixner 		do_div(sec, scale);
1142724ed53eSThomas Gleixner 		if (!sec)
1143724ed53eSThomas Gleixner 			sec = 1;
1144724ed53eSThomas Gleixner 		else if (sec > 600 && cs->mask > UINT_MAX)
1145724ed53eSThomas Gleixner 			sec = 600;
1146724ed53eSThomas Gleixner 
1147852db46dSJohn Stultz 		clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
1148724ed53eSThomas Gleixner 				       NSEC_PER_SEC / scale, sec * scale);
1149f8935983SJohn Stultz 	}
11502e27e793SPaul E. McKenney 
11512e27e793SPaul E. McKenney 	/*
11522e27e793SPaul E. McKenney 	 * If the uncertainty margin is not specified, calculate it.
11532e27e793SPaul E. McKenney 	 * If both scale and freq are non-zero, calculate the clock
11542e27e793SPaul E. McKenney 	 * period, but bound below at 2*WATCHDOG_MAX_SKEW.  However,
11552e27e793SPaul E. McKenney 	 * if either of scale or freq is zero, be very conservative and
11562e27e793SPaul E. McKenney 	 * take the tens-of-milliseconds WATCHDOG_THRESHOLD value for the
11572e27e793SPaul E. McKenney 	 * uncertainty margin.  Allow stupidly small uncertainty margins
11582e27e793SPaul E. McKenney 	 * to be specified by the caller for testing purposes, but warn
11592e27e793SPaul E. McKenney 	 * to discourage production use of this capability.
11602e27e793SPaul E. McKenney 	 */
11612e27e793SPaul E. McKenney 	if (scale && freq && !cs->uncertainty_margin) {
11622e27e793SPaul E. McKenney 		cs->uncertainty_margin = NSEC_PER_SEC / (scale * freq);
11632e27e793SPaul E. McKenney 		if (cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW)
11642e27e793SPaul E. McKenney 			cs->uncertainty_margin = 2 * WATCHDOG_MAX_SKEW;
11652e27e793SPaul E. McKenney 	} else if (!cs->uncertainty_margin) {
11662e27e793SPaul E. McKenney 		cs->uncertainty_margin = WATCHDOG_THRESHOLD;
11672e27e793SPaul E. McKenney 	}
11682e27e793SPaul E. McKenney 	WARN_ON_ONCE(cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW);
11692e27e793SPaul E. McKenney 
1170d65670a7SJohn Stultz 	/*
1171362fde04SJohn Stultz 	 * Ensure clocksources that have large 'mult' values don't overflow
1172362fde04SJohn Stultz 	 * when adjusted.
1173d65670a7SJohn Stultz 	 */
1174d65670a7SJohn Stultz 	cs->maxadj = clocksource_max_adjustment(cs);
1175f8935983SJohn Stultz 	while (freq && ((cs->mult + cs->maxadj < cs->mult)
1176f8935983SJohn Stultz 		|| (cs->mult - cs->maxadj > cs->mult))) {
1177d65670a7SJohn Stultz 		cs->mult >>= 1;
1178d65670a7SJohn Stultz 		cs->shift--;
1179d65670a7SJohn Stultz 		cs->maxadj = clocksource_max_adjustment(cs);
1180d65670a7SJohn Stultz 	}
1181d65670a7SJohn Stultz 
1182f8935983SJohn Stultz 	/*
1183f8935983SJohn Stultz 	 * Only warn for *special* clocksources that self-define
1184f8935983SJohn Stultz 	 * their mult/shift values and don't specify a freq.
1185f8935983SJohn Stultz 	 */
1186f8935983SJohn Stultz 	WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
1187f8935983SJohn Stultz 		"timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
1188f8935983SJohn Stultz 		cs->name);
1189f8935983SJohn Stultz 
1190fb82fe2fSJohn Stultz 	clocksource_update_max_deferment(cs);
11918cc8c525SJohn Stultz 
119245bbfe64SJoe Perches 	pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
11938cc8c525SJohn Stultz 		cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
1194852db46dSJohn Stultz }
1195fba9e072SJohn Stultz EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
1196852db46dSJohn Stultz 
1197852db46dSJohn Stultz /**
1198d7e81c26SJohn Stultz  * __clocksource_register_scale - Used to install new clocksources
1199b1b73d09SKusanagi Kouichi  * @cs:		clocksource to be registered
1200d7e81c26SJohn Stultz  * @scale:	Scale factor multiplied against freq to get clocksource hz
1201d7e81c26SJohn Stultz  * @freq:	clocksource frequency (cycles per second) divided by scale
1202d7e81c26SJohn Stultz  *
1203d7e81c26SJohn Stultz  * Returns -EBUSY if registration fails, zero otherwise.
1204d7e81c26SJohn Stultz  *
1205d7e81c26SJohn Stultz  * This *SHOULD NOT* be called directly! Please use the
1206d7e81c26SJohn Stultz  * clocksource_register_hz() or clocksource_register_khz helper functions.
1207d7e81c26SJohn Stultz  */
__clocksource_register_scale(struct clocksource * cs,u32 scale,u32 freq)1208d7e81c26SJohn Stultz int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
1209d7e81c26SJohn Stultz {
12102aae7bcfSPeter Zijlstra 	unsigned long flags;
1211d7e81c26SJohn Stultz 
1212d67f34c1SThomas Gleixner 	clocksource_arch_init(cs);
1213d67f34c1SThomas Gleixner 
1214b2c67cbeSThomas Gleixner 	if (WARN_ON_ONCE((unsigned int)cs->id >= CSID_MAX))
1215b2c67cbeSThomas Gleixner 		cs->id = CSID_GENERIC;
12165d51bee7SThomas Gleixner 	if (cs->vdso_clock_mode < 0 ||
12175d51bee7SThomas Gleixner 	    cs->vdso_clock_mode >= VDSO_CLOCKMODE_MAX) {
12185d51bee7SThomas Gleixner 		pr_warn("clocksource %s registered with invalid VDSO mode %d. Disabling VDSO support.\n",
12195d51bee7SThomas Gleixner 			cs->name, cs->vdso_clock_mode);
12205d51bee7SThomas Gleixner 		cs->vdso_clock_mode = VDSO_CLOCKMODE_NONE;
12215d51bee7SThomas Gleixner 	}
12225d51bee7SThomas Gleixner 
1223b595076aSUwe Kleine-König 	/* Initialize mult/shift and max_idle_ns */
1224fba9e072SJohn Stultz 	__clocksource_update_freq_scale(cs, scale, freq);
1225d7e81c26SJohn Stultz 
1226be278e98SJames Hartley 	/* Add clocksource to the clocksource list */
1227d7e81c26SJohn Stultz 	mutex_lock(&clocksource_mutex);
12282aae7bcfSPeter Zijlstra 
12292aae7bcfSPeter Zijlstra 	clocksource_watchdog_lock(&flags);
1230d7e81c26SJohn Stultz 	clocksource_enqueue(cs);
1231d7e81c26SJohn Stultz 	clocksource_enqueue_watchdog(cs);
12322aae7bcfSPeter Zijlstra 	clocksource_watchdog_unlock(&flags);
12332aae7bcfSPeter Zijlstra 
1234e05b2efbSjohn stultz 	clocksource_select();
1235bbf66d89SVitaly Kuznetsov 	clocksource_select_watchdog(false);
123639232ed5SBaolin Wang 	__clocksource_suspend_select(cs);
1237d7e81c26SJohn Stultz 	mutex_unlock(&clocksource_mutex);
1238d7e81c26SJohn Stultz 	return 0;
1239d7e81c26SJohn Stultz }
1240d7e81c26SJohn Stultz EXPORT_SYMBOL_GPL(__clocksource_register_scale);
1241d7e81c26SJohn Stultz 
__clocksource_change_rating(struct clocksource * cs,int rating)1242d0981a1bSThomas Gleixner static void __clocksource_change_rating(struct clocksource *cs, int rating)
1243d0981a1bSThomas Gleixner {
1244d0981a1bSThomas Gleixner 	list_del(&cs->list);
1245d0981a1bSThomas Gleixner 	cs->rating = rating;
1246d0981a1bSThomas Gleixner 	clocksource_enqueue(cs);
1247d0981a1bSThomas Gleixner }
1248d0981a1bSThomas Gleixner 
1249734efb46Sjohn stultz /**
125092c7e002SThomas Gleixner  * clocksource_change_rating - Change the rating of a registered clocksource
1251b1b73d09SKusanagi Kouichi  * @cs:		clocksource to be changed
1252b1b73d09SKusanagi Kouichi  * @rating:	new rating
1253734efb46Sjohn stultz  */
clocksource_change_rating(struct clocksource * cs,int rating)125492c7e002SThomas Gleixner void clocksource_change_rating(struct clocksource *cs, int rating)
1255734efb46Sjohn stultz {
12562aae7bcfSPeter Zijlstra 	unsigned long flags;
12572aae7bcfSPeter Zijlstra 
125875c5158fSMartin Schwidefsky 	mutex_lock(&clocksource_mutex);
12592aae7bcfSPeter Zijlstra 	clocksource_watchdog_lock(&flags);
1260d0981a1bSThomas Gleixner 	__clocksource_change_rating(cs, rating);
12612aae7bcfSPeter Zijlstra 	clocksource_watchdog_unlock(&flags);
12622aae7bcfSPeter Zijlstra 
1263332962f2SThomas Gleixner 	clocksource_select();
1264bbf66d89SVitaly Kuznetsov 	clocksource_select_watchdog(false);
126539232ed5SBaolin Wang 	clocksource_suspend_select(false);
126675c5158fSMartin Schwidefsky 	mutex_unlock(&clocksource_mutex);
1267734efb46Sjohn stultz }
1268fb63a0ebSMartin Schwidefsky EXPORT_SYMBOL(clocksource_change_rating);
1269734efb46Sjohn stultz 
12707eaeb343SThomas Gleixner /*
12717eaeb343SThomas Gleixner  * Unbind clocksource @cs. Called with clocksource_mutex held
12727eaeb343SThomas Gleixner  */
clocksource_unbind(struct clocksource * cs)12737eaeb343SThomas Gleixner static int clocksource_unbind(struct clocksource *cs)
12747eaeb343SThomas Gleixner {
12752aae7bcfSPeter Zijlstra 	unsigned long flags;
12762aae7bcfSPeter Zijlstra 
1277bbf66d89SVitaly Kuznetsov 	if (clocksource_is_watchdog(cs)) {
1278bbf66d89SVitaly Kuznetsov 		/* Select and try to install a replacement watchdog. */
1279bbf66d89SVitaly Kuznetsov 		clocksource_select_watchdog(true);
12807eaeb343SThomas Gleixner 		if (clocksource_is_watchdog(cs))
12817eaeb343SThomas Gleixner 			return -EBUSY;
1282bbf66d89SVitaly Kuznetsov 	}
12837eaeb343SThomas Gleixner 
12847eaeb343SThomas Gleixner 	if (cs == curr_clocksource) {
12857eaeb343SThomas Gleixner 		/* Select and try to install a replacement clock source */
12867eaeb343SThomas Gleixner 		clocksource_select_fallback();
12877eaeb343SThomas Gleixner 		if (curr_clocksource == cs)
12887eaeb343SThomas Gleixner 			return -EBUSY;
12897eaeb343SThomas Gleixner 	}
12902aae7bcfSPeter Zijlstra 
129139232ed5SBaolin Wang 	if (clocksource_is_suspend(cs)) {
129239232ed5SBaolin Wang 		/*
129339232ed5SBaolin Wang 		 * Select and try to install a replacement suspend clocksource.
129439232ed5SBaolin Wang 		 * If no replacement suspend clocksource, we will just let the
129539232ed5SBaolin Wang 		 * clocksource go and have no suspend clocksource.
129639232ed5SBaolin Wang 		 */
129739232ed5SBaolin Wang 		clocksource_suspend_select(true);
129839232ed5SBaolin Wang 	}
129939232ed5SBaolin Wang 
13002aae7bcfSPeter Zijlstra 	clocksource_watchdog_lock(&flags);
13017eaeb343SThomas Gleixner 	clocksource_dequeue_watchdog(cs);
13027eaeb343SThomas Gleixner 	list_del_init(&cs->list);
13032aae7bcfSPeter Zijlstra 	clocksource_watchdog_unlock(&flags);
13042aae7bcfSPeter Zijlstra 
13057eaeb343SThomas Gleixner 	return 0;
13067eaeb343SThomas Gleixner }
13077eaeb343SThomas Gleixner 
13084713e22cSThomas Gleixner /**
13094713e22cSThomas Gleixner  * clocksource_unregister - remove a registered clocksource
1310b1b73d09SKusanagi Kouichi  * @cs:	clocksource to be unregistered
13114713e22cSThomas Gleixner  */
clocksource_unregister(struct clocksource * cs)1312a89c7edbSThomas Gleixner int clocksource_unregister(struct clocksource *cs)
13134713e22cSThomas Gleixner {
1314a89c7edbSThomas Gleixner 	int ret = 0;
1315a89c7edbSThomas Gleixner 
131675c5158fSMartin Schwidefsky 	mutex_lock(&clocksource_mutex);
1317a89c7edbSThomas Gleixner 	if (!list_empty(&cs->list))
1318a89c7edbSThomas Gleixner 		ret = clocksource_unbind(cs);
131975c5158fSMartin Schwidefsky 	mutex_unlock(&clocksource_mutex);
1320a89c7edbSThomas Gleixner 	return ret;
13214713e22cSThomas Gleixner }
1322fb63a0ebSMartin Schwidefsky EXPORT_SYMBOL(clocksource_unregister);
13234713e22cSThomas Gleixner 
13242b013700SDaniel Walker #ifdef CONFIG_SYSFS
1325734efb46Sjohn stultz /**
1326e87821d1SBaolin Wang  * current_clocksource_show - sysfs interface for current clocksource
1327734efb46Sjohn stultz  * @dev:	unused
1328b1b73d09SKusanagi Kouichi  * @attr:	unused
1329734efb46Sjohn stultz  * @buf:	char buffer to be filled with clocksource list
1330734efb46Sjohn stultz  *
1331734efb46Sjohn stultz  * Provides sysfs interface for listing current clocksource.
1332734efb46Sjohn stultz  */
current_clocksource_show(struct device * dev,struct device_attribute * attr,char * buf)1333e87821d1SBaolin Wang static ssize_t current_clocksource_show(struct device *dev,
1334e87821d1SBaolin Wang 					struct device_attribute *attr,
1335e87821d1SBaolin Wang 					char *buf)
1336734efb46Sjohn stultz {
13375e2cb101SMiao Xie 	ssize_t count = 0;
1338734efb46Sjohn stultz 
133975c5158fSMartin Schwidefsky 	mutex_lock(&clocksource_mutex);
13405e2cb101SMiao Xie 	count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
134175c5158fSMartin Schwidefsky 	mutex_unlock(&clocksource_mutex);
1342734efb46Sjohn stultz 
13435e2cb101SMiao Xie 	return count;
1344734efb46Sjohn stultz }
1345734efb46Sjohn stultz 
sysfs_get_uname(const char * buf,char * dst,size_t cnt)1346891292a7SPatrick Palka ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
134729b54078SThomas Gleixner {
134829b54078SThomas Gleixner 	size_t ret = cnt;
134929b54078SThomas Gleixner 
135029b54078SThomas Gleixner 	/* strings from sysfs write are not 0 terminated! */
135129b54078SThomas Gleixner 	if (!cnt || cnt >= CS_NAME_LEN)
135229b54078SThomas Gleixner 		return -EINVAL;
135329b54078SThomas Gleixner 
135429b54078SThomas Gleixner 	/* strip of \n: */
135529b54078SThomas Gleixner 	if (buf[cnt-1] == '\n')
135629b54078SThomas Gleixner 		cnt--;
135729b54078SThomas Gleixner 	if (cnt > 0)
135829b54078SThomas Gleixner 		memcpy(dst, buf, cnt);
135929b54078SThomas Gleixner 	dst[cnt] = 0;
136029b54078SThomas Gleixner 	return ret;
136129b54078SThomas Gleixner }
136229b54078SThomas Gleixner 
1363734efb46Sjohn stultz /**
1364e87821d1SBaolin Wang  * current_clocksource_store - interface for manually overriding clocksource
1365734efb46Sjohn stultz  * @dev:	unused
1366b1b73d09SKusanagi Kouichi  * @attr:	unused
1367734efb46Sjohn stultz  * @buf:	name of override clocksource
1368734efb46Sjohn stultz  * @count:	length of buffer
1369734efb46Sjohn stultz  *
1370734efb46Sjohn stultz  * Takes input from sysfs interface for manually overriding the default
1371b71a8eb0SUwe Kleine-König  * clocksource selection.
1372734efb46Sjohn stultz  */
current_clocksource_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1373e87821d1SBaolin Wang static ssize_t current_clocksource_store(struct device *dev,
1374d369a5d8SKay Sievers 					 struct device_attribute *attr,
1375734efb46Sjohn stultz 					 const char *buf, size_t count)
1376734efb46Sjohn stultz {
1377233bcb41SElad Wexler 	ssize_t ret;
1378734efb46Sjohn stultz 
137975c5158fSMartin Schwidefsky 	mutex_lock(&clocksource_mutex);
1380734efb46Sjohn stultz 
138103e13cf5SThomas Gleixner 	ret = sysfs_get_uname(buf, override_name, count);
138229b54078SThomas Gleixner 	if (ret >= 0)
1383f1b82746SMartin Schwidefsky 		clocksource_select();
1384734efb46Sjohn stultz 
138575c5158fSMartin Schwidefsky 	mutex_unlock(&clocksource_mutex);
1386734efb46Sjohn stultz 
1387734efb46Sjohn stultz 	return ret;
1388734efb46Sjohn stultz }
1389e87821d1SBaolin Wang static DEVICE_ATTR_RW(current_clocksource);
1390734efb46Sjohn stultz 
1391734efb46Sjohn stultz /**
1392e87821d1SBaolin Wang  * unbind_clocksource_store - interface for manually unbinding clocksource
13937eaeb343SThomas Gleixner  * @dev:	unused
13947eaeb343SThomas Gleixner  * @attr:	unused
13957eaeb343SThomas Gleixner  * @buf:	unused
13967eaeb343SThomas Gleixner  * @count:	length of buffer
13977eaeb343SThomas Gleixner  *
13987eaeb343SThomas Gleixner  * Takes input from sysfs interface for manually unbinding a clocksource.
13997eaeb343SThomas Gleixner  */
unbind_clocksource_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1400e87821d1SBaolin Wang static ssize_t unbind_clocksource_store(struct device *dev,
14017eaeb343SThomas Gleixner 					struct device_attribute *attr,
14027eaeb343SThomas Gleixner 					const char *buf, size_t count)
14037eaeb343SThomas Gleixner {
14047eaeb343SThomas Gleixner 	struct clocksource *cs;
14057eaeb343SThomas Gleixner 	char name[CS_NAME_LEN];
1406233bcb41SElad Wexler 	ssize_t ret;
14077eaeb343SThomas Gleixner 
140803e13cf5SThomas Gleixner 	ret = sysfs_get_uname(buf, name, count);
14097eaeb343SThomas Gleixner 	if (ret < 0)
14107eaeb343SThomas Gleixner 		return ret;
14117eaeb343SThomas Gleixner 
14127eaeb343SThomas Gleixner 	ret = -ENODEV;
14137eaeb343SThomas Gleixner 	mutex_lock(&clocksource_mutex);
14147eaeb343SThomas Gleixner 	list_for_each_entry(cs, &clocksource_list, list) {
14157eaeb343SThomas Gleixner 		if (strcmp(cs->name, name))
14167eaeb343SThomas Gleixner 			continue;
14177eaeb343SThomas Gleixner 		ret = clocksource_unbind(cs);
14187eaeb343SThomas Gleixner 		break;
14197eaeb343SThomas Gleixner 	}
14207eaeb343SThomas Gleixner 	mutex_unlock(&clocksource_mutex);
14217eaeb343SThomas Gleixner 
14227eaeb343SThomas Gleixner 	return ret ? ret : count;
14237eaeb343SThomas Gleixner }
1424e87821d1SBaolin Wang static DEVICE_ATTR_WO(unbind_clocksource);
14257eaeb343SThomas Gleixner 
14267eaeb343SThomas Gleixner /**
1427e87821d1SBaolin Wang  * available_clocksource_show - sysfs interface for listing clocksource
1428734efb46Sjohn stultz  * @dev:	unused
1429b1b73d09SKusanagi Kouichi  * @attr:	unused
1430734efb46Sjohn stultz  * @buf:	char buffer to be filled with clocksource list
1431734efb46Sjohn stultz  *
1432734efb46Sjohn stultz  * Provides sysfs interface for listing registered clocksources
1433734efb46Sjohn stultz  */
available_clocksource_show(struct device * dev,struct device_attribute * attr,char * buf)1434e87821d1SBaolin Wang static ssize_t available_clocksource_show(struct device *dev,
1435d369a5d8SKay Sievers 					  struct device_attribute *attr,
14364a0b2b4dSAndi Kleen 					  char *buf)
1437734efb46Sjohn stultz {
14382e197586SMatthias Kaehlcke 	struct clocksource *src;
14395e2cb101SMiao Xie 	ssize_t count = 0;
1440734efb46Sjohn stultz 
144175c5158fSMartin Schwidefsky 	mutex_lock(&clocksource_mutex);
14422e197586SMatthias Kaehlcke 	list_for_each_entry(src, &clocksource_list, list) {
1443cd6d95d8SThomas Gleixner 		/*
1444cd6d95d8SThomas Gleixner 		 * Don't show non-HRES clocksource if the tick code is
1445cd6d95d8SThomas Gleixner 		 * in one shot mode (highres=on or nohz=on)
1446cd6d95d8SThomas Gleixner 		 */
1447cd6d95d8SThomas Gleixner 		if (!tick_oneshot_mode_active() ||
14483f68535aSjohn stultz 		    (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
14495e2cb101SMiao Xie 			count += snprintf(buf + count,
14505e2cb101SMiao Xie 				  max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
14515e2cb101SMiao Xie 				  "%s ", src->name);
1452734efb46Sjohn stultz 	}
145375c5158fSMartin Schwidefsky 	mutex_unlock(&clocksource_mutex);
1454734efb46Sjohn stultz 
14555e2cb101SMiao Xie 	count += snprintf(buf + count,
14565e2cb101SMiao Xie 			  max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1457734efb46Sjohn stultz 
14585e2cb101SMiao Xie 	return count;
1459734efb46Sjohn stultz }
1460e87821d1SBaolin Wang static DEVICE_ATTR_RO(available_clocksource);
1461734efb46Sjohn stultz 
146227263e8dSBaolin Wang static struct attribute *clocksource_attrs[] = {
146327263e8dSBaolin Wang 	&dev_attr_current_clocksource.attr,
146427263e8dSBaolin Wang 	&dev_attr_unbind_clocksource.attr,
146527263e8dSBaolin Wang 	&dev_attr_available_clocksource.attr,
146627263e8dSBaolin Wang 	NULL
146727263e8dSBaolin Wang };
146827263e8dSBaolin Wang ATTRIBUTE_GROUPS(clocksource);
146927263e8dSBaolin Wang 
1470d369a5d8SKay Sievers static struct bus_type clocksource_subsys = {
1471af5ca3f4SKay Sievers 	.name = "clocksource",
1472d369a5d8SKay Sievers 	.dev_name = "clocksource",
1473734efb46Sjohn stultz };
1474734efb46Sjohn stultz 
1475d369a5d8SKay Sievers static struct device device_clocksource = {
1476734efb46Sjohn stultz 	.id	= 0,
1477d369a5d8SKay Sievers 	.bus	= &clocksource_subsys,
147827263e8dSBaolin Wang 	.groups	= clocksource_groups,
1479734efb46Sjohn stultz };
1480734efb46Sjohn stultz 
init_clocksource_sysfs(void)1481ad596171Sjohn stultz static int __init init_clocksource_sysfs(void)
1482734efb46Sjohn stultz {
1483d369a5d8SKay Sievers 	int error = subsys_system_register(&clocksource_subsys, NULL);
1484734efb46Sjohn stultz 
1485734efb46Sjohn stultz 	if (!error)
1486d369a5d8SKay Sievers 		error = device_register(&device_clocksource);
148727263e8dSBaolin Wang 
1488734efb46Sjohn stultz 	return error;
1489734efb46Sjohn stultz }
1490734efb46Sjohn stultz 
1491734efb46Sjohn stultz device_initcall(init_clocksource_sysfs);
14922b013700SDaniel Walker #endif /* CONFIG_SYSFS */
1493734efb46Sjohn stultz 
1494734efb46Sjohn stultz /**
1495734efb46Sjohn stultz  * boot_override_clocksource - boot clock override
1496734efb46Sjohn stultz  * @str:	override name
1497734efb46Sjohn stultz  *
1498734efb46Sjohn stultz  * Takes a clocksource= boot argument and uses it
1499734efb46Sjohn stultz  * as the clocksource override name.
1500734efb46Sjohn stultz  */
boot_override_clocksource(char * str)1501734efb46Sjohn stultz static int __init boot_override_clocksource(char* str)
1502734efb46Sjohn stultz {
150375c5158fSMartin Schwidefsky 	mutex_lock(&clocksource_mutex);
1504734efb46Sjohn stultz 	if (str)
150576edc27eSAzeem Shaikh 		strscpy(override_name, str, sizeof(override_name));
150675c5158fSMartin Schwidefsky 	mutex_unlock(&clocksource_mutex);
1507734efb46Sjohn stultz 	return 1;
1508734efb46Sjohn stultz }
1509734efb46Sjohn stultz 
1510734efb46Sjohn stultz __setup("clocksource=", boot_override_clocksource);
1511734efb46Sjohn stultz 
1512734efb46Sjohn stultz /**
1513734efb46Sjohn stultz  * boot_override_clock - Compatibility layer for deprecated boot option
1514734efb46Sjohn stultz  * @str:	override name
1515734efb46Sjohn stultz  *
1516734efb46Sjohn stultz  * DEPRECATED! Takes a clock= boot argument and uses it
1517734efb46Sjohn stultz  * as the clocksource override name
1518734efb46Sjohn stultz  */
boot_override_clock(char * str)1519734efb46Sjohn stultz static int __init boot_override_clock(char* str)
1520734efb46Sjohn stultz {
15215d0cf410Sjohn stultz 	if (!strcmp(str, "pmtmr")) {
152245bbfe64SJoe Perches 		pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
15235d0cf410Sjohn stultz 		return boot_override_clocksource("acpi_pm");
15245d0cf410Sjohn stultz 	}
152545bbfe64SJoe Perches 	pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1526734efb46Sjohn stultz 	return boot_override_clocksource(str);
1527734efb46Sjohn stultz }
1528734efb46Sjohn stultz 
1529734efb46Sjohn stultz __setup("clock=", boot_override_clock);
1530