• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * This file contains the functions which manage clocksource drivers.
4  *
5  * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
6  */
7 
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #include <linux/device.h>
11 #include <linux/clocksource.h>
12 #include <linux/init.h>
13 #include <linux/module.h>
14 #include <linux/sched.h> /* for spin_unlock_irq() using preempt_count() m68k */
15 #include <linux/tick.h>
16 #include <linux/kthread.h>
17 
18 #include "tick-internal.h"
19 #include "timekeeping_internal.h"
20 
21 /**
22  * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
23  * @mult:	pointer to mult variable
24  * @shift:	pointer to shift variable
25  * @from:	frequency to convert from
26  * @to:		frequency to convert to
27  * @maxsec:	guaranteed runtime conversion range in seconds
28  *
29  * The function evaluates the shift/mult pair for the scaled math
30  * operations of clocksources and clockevents.
31  *
32  * @to and @from are frequency values in HZ. For clock sources @to is
33  * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
34  * event @to is the counter frequency and @from is NSEC_PER_SEC.
35  *
36  * The @maxsec conversion range argument controls the time frame in
37  * seconds which must be covered by the runtime conversion with the
38  * calculated mult and shift factors. This guarantees that no 64bit
39  * overflow happens when the input value of the conversion is
40  * multiplied with the calculated mult factor. Larger ranges may
41  * reduce the conversion accuracy by chosing smaller mult and shift
42  * factors.
43  */
44 void
clocks_calc_mult_shift(u32 * mult,u32 * shift,u32 from,u32 to,u32 maxsec)45 clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
46 {
47 	u64 tmp;
48 	u32 sft, sftacc= 32;
49 
50 	/*
51 	 * Calculate the shift factor which is limiting the conversion
52 	 * range:
53 	 */
54 	tmp = ((u64)maxsec * from) >> 32;
55 	while (tmp) {
56 		tmp >>=1;
57 		sftacc--;
58 	}
59 
60 	/*
61 	 * Find the conversion shift/mult pair which has the best
62 	 * accuracy and fits the maxsec conversion range:
63 	 */
64 	for (sft = 32; sft > 0; sft--) {
65 		tmp = (u64) to << sft;
66 		tmp += from / 2;
67 		do_div(tmp, from);
68 		if ((tmp >> sftacc) == 0)
69 			break;
70 	}
71 	*mult = tmp;
72 	*shift = sft;
73 }
74 EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
75 
76 /*[Clocksource internal variables]---------
77  * curr_clocksource:
78  *	currently selected clocksource.
79  * suspend_clocksource:
80  *	used to calculate the suspend time.
81  * clocksource_list:
82  *	linked list with the registered clocksources
83  * clocksource_mutex:
84  *	protects manipulations to curr_clocksource and the clocksource_list
85  * override_name:
86  *	Name of the user-specified clocksource.
87  */
88 static struct clocksource *curr_clocksource;
89 static struct clocksource *suspend_clocksource;
90 static LIST_HEAD(clocksource_list);
91 static DEFINE_MUTEX(clocksource_mutex);
92 static char override_name[CS_NAME_LEN];
93 static int finished_booting;
94 static u64 suspend_start;
95 
96 /*
97  * Threshold: 0.0312s, when doubled: 0.0625s.
98  * Also a default for cs->uncertainty_margin when registering clocks.
99  */
100 #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 5)
101 
102 /*
103  * Maximum permissible delay between two readouts of the watchdog
104  * clocksource surrounding a read of the clocksource being validated.
105  * This delay could be due to SMIs, NMIs, or to VCPU preemptions.  Used as
106  * a lower bound for cs->uncertainty_margin values when registering clocks.
107  */
108 #define WATCHDOG_MAX_SKEW (100 * NSEC_PER_USEC)
109 
110 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
111 static void clocksource_watchdog_work(struct work_struct *work);
112 static void clocksource_select(void);
113 
114 static LIST_HEAD(watchdog_list);
115 static struct clocksource *watchdog;
116 static struct timer_list watchdog_timer;
117 static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
118 static DEFINE_SPINLOCK(watchdog_lock);
119 static int watchdog_running;
120 static atomic_t watchdog_reset_pending;
121 
clocksource_watchdog_lock(unsigned long * flags)122 static inline void clocksource_watchdog_lock(unsigned long *flags)
123 {
124 	spin_lock_irqsave(&watchdog_lock, *flags);
125 }
126 
clocksource_watchdog_unlock(unsigned long * flags)127 static inline void clocksource_watchdog_unlock(unsigned long *flags)
128 {
129 	spin_unlock_irqrestore(&watchdog_lock, *flags);
130 }
131 
132 static int clocksource_watchdog_kthread(void *data);
133 static void __clocksource_change_rating(struct clocksource *cs, int rating);
134 
135 /*
136  * Interval: 0.5sec.
137  */
138 #define WATCHDOG_INTERVAL (HZ >> 1)
139 
clocksource_watchdog_work(struct work_struct * work)140 static void clocksource_watchdog_work(struct work_struct *work)
141 {
142 	/*
143 	 * We cannot directly run clocksource_watchdog_kthread() here, because
144 	 * clocksource_select() calls timekeeping_notify() which uses
145 	 * stop_machine(). One cannot use stop_machine() from a workqueue() due
146 	 * lock inversions wrt CPU hotplug.
147 	 *
148 	 * Also, we only ever run this work once or twice during the lifetime
149 	 * of the kernel, so there is no point in creating a more permanent
150 	 * kthread for this.
151 	 *
152 	 * If kthread_run fails the next watchdog scan over the
153 	 * watchdog_list will find the unstable clock again.
154 	 */
155 	kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
156 }
157 
__clocksource_unstable(struct clocksource * cs)158 static void __clocksource_unstable(struct clocksource *cs)
159 {
160 	cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
161 	cs->flags |= CLOCK_SOURCE_UNSTABLE;
162 
163 	/*
164 	 * If the clocksource is registered clocksource_watchdog_kthread() will
165 	 * re-rate and re-select.
166 	 */
167 	if (list_empty(&cs->list)) {
168 		cs->rating = 0;
169 		return;
170 	}
171 
172 	if (cs->mark_unstable)
173 		cs->mark_unstable(cs);
174 
175 	/* kick clocksource_watchdog_kthread() */
176 	if (finished_booting)
177 		schedule_work(&watchdog_work);
178 }
179 
180 /**
181  * clocksource_mark_unstable - mark clocksource unstable via watchdog
182  * @cs:		clocksource to be marked unstable
183  *
184  * This function is called by the x86 TSC code to mark clocksources as unstable;
185  * it defers demotion and re-selection to a kthread.
186  */
clocksource_mark_unstable(struct clocksource * cs)187 void clocksource_mark_unstable(struct clocksource *cs)
188 {
189 	unsigned long flags;
190 
191 	spin_lock_irqsave(&watchdog_lock, flags);
192 	if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
193 		if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
194 			list_add(&cs->wd_list, &watchdog_list);
195 		__clocksource_unstable(cs);
196 	}
197 	spin_unlock_irqrestore(&watchdog_lock, flags);
198 }
199 
200 static ulong max_cswd_read_retries = 3;
201 module_param(max_cswd_read_retries, ulong, 0644);
202 
203 enum wd_read_status {
204 	WD_READ_SUCCESS,
205 	WD_READ_UNSTABLE,
206 	WD_READ_SKIP
207 };
208 
cs_watchdog_read(struct clocksource * cs,u64 * csnow,u64 * wdnow)209 static enum wd_read_status cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
210 {
211 	unsigned int nretries;
212 	u64 wd_end, wd_end2, wd_delta;
213 	int64_t wd_delay, wd_seq_delay;
214 
215 	for (nretries = 0; nretries <= max_cswd_read_retries; nretries++) {
216 		local_irq_disable();
217 		*wdnow = watchdog->read(watchdog);
218 		*csnow = cs->read(cs);
219 		wd_end = watchdog->read(watchdog);
220 		wd_end2 = watchdog->read(watchdog);
221 		local_irq_enable();
222 
223 		wd_delta = clocksource_delta(wd_end, *wdnow, watchdog->mask);
224 		wd_delay = clocksource_cyc2ns(wd_delta, watchdog->mult,
225 					      watchdog->shift);
226 		if (wd_delay <= WATCHDOG_MAX_SKEW) {
227 			if (nretries > 1 || nretries >= max_cswd_read_retries) {
228 				pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
229 					smp_processor_id(), watchdog->name, nretries);
230 			}
231 			return WD_READ_SUCCESS;
232 		}
233 
234 		/*
235 		 * Now compute delay in consecutive watchdog read to see if
236 		 * there is too much external interferences that cause
237 		 * significant delay in reading both clocksource and watchdog.
238 		 *
239 		 * If consecutive WD read-back delay > WATCHDOG_MAX_SKEW/2,
240 		 * report system busy, reinit the watchdog and skip the current
241 		 * watchdog test.
242 		 */
243 		wd_delta = clocksource_delta(wd_end2, wd_end, watchdog->mask);
244 		wd_seq_delay = clocksource_cyc2ns(wd_delta, watchdog->mult, watchdog->shift);
245 		if (wd_seq_delay > WATCHDOG_MAX_SKEW/2)
246 			goto skip_test;
247 	}
248 
249 	pr_warn("timekeeping watchdog on CPU%d: %s read-back delay of %lldns, attempt %d, marking unstable\n",
250 		smp_processor_id(), watchdog->name, wd_delay, nretries);
251 	return WD_READ_UNSTABLE;
252 
253 skip_test:
254 	pr_info("timekeeping watchdog on CPU%d: %s wd-wd read-back delay of %lldns\n",
255 		smp_processor_id(), watchdog->name, wd_seq_delay);
256 	pr_info("wd-%s-wd read-back delay of %lldns, clock-skew test skipped!\n",
257 		cs->name, wd_delay);
258 	return WD_READ_SKIP;
259 }
260 
261 static u64 csnow_mid;
262 static cpumask_t cpus_ahead;
263 static cpumask_t cpus_behind;
264 
clocksource_verify_one_cpu(void * csin)265 static void clocksource_verify_one_cpu(void *csin)
266 {
267 	struct clocksource *cs = (struct clocksource *)csin;
268 
269 	csnow_mid = cs->read(cs);
270 }
271 
clocksource_verify_percpu(struct clocksource * cs)272 static void clocksource_verify_percpu(struct clocksource *cs)
273 {
274 	int64_t cs_nsec, cs_nsec_max = 0, cs_nsec_min = LLONG_MAX;
275 	u64 csnow_begin, csnow_end;
276 	int cpu, testcpu;
277 	s64 delta;
278 
279 	cpumask_clear(&cpus_ahead);
280 	cpumask_clear(&cpus_behind);
281 	preempt_disable();
282 	testcpu = smp_processor_id();
283 	pr_warn("Checking clocksource %s synchronization from CPU %d.\n", cs->name, testcpu);
284 	for_each_online_cpu(cpu) {
285 		if (cpu == testcpu)
286 			continue;
287 		csnow_begin = cs->read(cs);
288 		smp_call_function_single(cpu, clocksource_verify_one_cpu, cs, 1);
289 		csnow_end = cs->read(cs);
290 		delta = (s64)((csnow_mid - csnow_begin) & cs->mask);
291 		if (delta < 0)
292 			cpumask_set_cpu(cpu, &cpus_behind);
293 		delta = (csnow_end - csnow_mid) & cs->mask;
294 		if (delta < 0)
295 			cpumask_set_cpu(cpu, &cpus_ahead);
296 		delta = clocksource_delta(csnow_end, csnow_begin, cs->mask);
297 		cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
298 		if (cs_nsec > cs_nsec_max)
299 			cs_nsec_max = cs_nsec;
300 		if (cs_nsec < cs_nsec_min)
301 			cs_nsec_min = cs_nsec;
302 	}
303 	preempt_enable();
304 	if (!cpumask_empty(&cpus_ahead))
305 		pr_warn("        CPUs %*pbl ahead of CPU %d for clocksource %s.\n",
306 			cpumask_pr_args(&cpus_ahead), testcpu, cs->name);
307 	if (!cpumask_empty(&cpus_behind))
308 		pr_warn("        CPUs %*pbl behind CPU %d for clocksource %s.\n",
309 			cpumask_pr_args(&cpus_behind), testcpu, cs->name);
310 	if (!cpumask_empty(&cpus_ahead) || !cpumask_empty(&cpus_behind))
311 		pr_warn("        CPU %d check durations %lldns - %lldns for clocksource %s.\n",
312 			testcpu, cs_nsec_min, cs_nsec_max, cs->name);
313 }
314 
clocksource_reset_watchdog(void)315 static inline void clocksource_reset_watchdog(void)
316 {
317 	struct clocksource *cs;
318 
319 	list_for_each_entry(cs, &watchdog_list, wd_list)
320 		cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
321 }
322 
323 
clocksource_watchdog(struct timer_list * unused)324 static void clocksource_watchdog(struct timer_list *unused)
325 {
326 	u64 csnow, wdnow, cslast, wdlast, delta;
327 	int next_cpu, reset_pending;
328 	int64_t wd_nsec, cs_nsec;
329 	struct clocksource *cs;
330 	enum wd_read_status read_ret;
331 	unsigned long extra_wait = 0;
332 	u32 md;
333 
334 	spin_lock(&watchdog_lock);
335 	if (!watchdog_running)
336 		goto out;
337 
338 	reset_pending = atomic_read(&watchdog_reset_pending);
339 
340 	list_for_each_entry(cs, &watchdog_list, wd_list) {
341 
342 		/* Clocksource already marked unstable? */
343 		if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
344 			if (finished_booting)
345 				schedule_work(&watchdog_work);
346 			continue;
347 		}
348 
349 		read_ret = cs_watchdog_read(cs, &csnow, &wdnow);
350 
351 		if (read_ret == WD_READ_UNSTABLE) {
352 			/* Clock readout unreliable, so give it up. */
353 			__clocksource_unstable(cs);
354 			continue;
355 		}
356 
357 		/*
358 		 * When WD_READ_SKIP is returned, it means the system is likely
359 		 * under very heavy load, where the latency of reading
360 		 * watchdog/clocksource is very big, and affect the accuracy of
361 		 * watchdog check. So give system some space and suspend the
362 		 * watchdog check for 5 minutes.
363 		 */
364 		if (read_ret == WD_READ_SKIP) {
365 			/*
366 			 * As the watchdog timer will be suspended, and
367 			 * cs->last could keep unchanged for 5 minutes, reset
368 			 * the counters.
369 			 */
370 			clocksource_reset_watchdog();
371 			extra_wait = HZ * 300;
372 			break;
373 		}
374 
375 		/* Clocksource initialized ? */
376 		if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
377 		    atomic_read(&watchdog_reset_pending)) {
378 			cs->flags |= CLOCK_SOURCE_WATCHDOG;
379 			cs->wd_last = wdnow;
380 			cs->cs_last = csnow;
381 			continue;
382 		}
383 
384 		delta = clocksource_delta(wdnow, cs->wd_last, watchdog->mask);
385 		wd_nsec = clocksource_cyc2ns(delta, watchdog->mult,
386 					     watchdog->shift);
387 
388 		delta = clocksource_delta(csnow, cs->cs_last, cs->mask);
389 		cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
390 		wdlast = cs->wd_last; /* save these in case we print them */
391 		cslast = cs->cs_last;
392 		cs->cs_last = csnow;
393 		cs->wd_last = wdnow;
394 
395 		if (atomic_read(&watchdog_reset_pending))
396 			continue;
397 
398 		/* Check the deviation from the watchdog clocksource. */
399 		md = cs->uncertainty_margin + watchdog->uncertainty_margin;
400 		if (abs(cs_nsec - wd_nsec) > md) {
401 			pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
402 				smp_processor_id(), cs->name);
403 			pr_warn("                      '%s' wd_now: %llx wd_last: %llx mask: %llx\n",
404 				watchdog->name, wdnow, wdlast, watchdog->mask);
405 			pr_warn("                      '%s' cs_now: %llx cs_last: %llx mask: %llx\n",
406 				cs->name, csnow, cslast, cs->mask);
407 			__clocksource_unstable(cs);
408 			continue;
409 		}
410 
411 		if (cs == curr_clocksource && cs->tick_stable)
412 			cs->tick_stable(cs);
413 
414 		if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
415 		    (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
416 		    (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
417 			/* Mark it valid for high-res. */
418 			cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
419 
420 			/*
421 			 * clocksource_done_booting() will sort it if
422 			 * finished_booting is not set yet.
423 			 */
424 			if (!finished_booting)
425 				continue;
426 
427 			/*
428 			 * If this is not the current clocksource let
429 			 * the watchdog thread reselect it. Due to the
430 			 * change to high res this clocksource might
431 			 * be preferred now. If it is the current
432 			 * clocksource let the tick code know about
433 			 * that change.
434 			 */
435 			if (cs != curr_clocksource) {
436 				cs->flags |= CLOCK_SOURCE_RESELECT;
437 				schedule_work(&watchdog_work);
438 			} else {
439 				tick_clock_notify();
440 			}
441 		}
442 	}
443 
444 	/*
445 	 * We only clear the watchdog_reset_pending, when we did a
446 	 * full cycle through all clocksources.
447 	 */
448 	if (reset_pending)
449 		atomic_dec(&watchdog_reset_pending);
450 
451 	/*
452 	 * Cycle through CPUs to check if the CPUs stay synchronized
453 	 * to each other.
454 	 */
455 	next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
456 	if (next_cpu >= nr_cpu_ids)
457 		next_cpu = cpumask_first(cpu_online_mask);
458 
459 	/*
460 	 * Arm timer if not already pending: could race with concurrent
461 	 * pair clocksource_stop_watchdog() clocksource_start_watchdog().
462 	 */
463 	if (!timer_pending(&watchdog_timer)) {
464 		watchdog_timer.expires += WATCHDOG_INTERVAL + extra_wait;
465 		add_timer_on(&watchdog_timer, next_cpu);
466 	}
467 out:
468 	spin_unlock(&watchdog_lock);
469 }
470 
clocksource_start_watchdog(void)471 static inline void clocksource_start_watchdog(void)
472 {
473 	if (watchdog_running || !watchdog || list_empty(&watchdog_list))
474 		return;
475 	timer_setup(&watchdog_timer, clocksource_watchdog, 0);
476 	watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
477 	add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
478 	watchdog_running = 1;
479 }
480 
clocksource_stop_watchdog(void)481 static inline void clocksource_stop_watchdog(void)
482 {
483 	if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
484 		return;
485 	del_timer(&watchdog_timer);
486 	watchdog_running = 0;
487 }
488 
clocksource_resume_watchdog(void)489 static void clocksource_resume_watchdog(void)
490 {
491 	atomic_inc(&watchdog_reset_pending);
492 }
493 
clocksource_enqueue_watchdog(struct clocksource * cs)494 static void clocksource_enqueue_watchdog(struct clocksource *cs)
495 {
496 	INIT_LIST_HEAD(&cs->wd_list);
497 
498 	if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
499 		/* cs is a clocksource to be watched. */
500 		list_add(&cs->wd_list, &watchdog_list);
501 		cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
502 	} else {
503 		/* cs is a watchdog. */
504 		if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
505 			cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
506 	}
507 }
508 
clocksource_select_watchdog(bool fallback)509 static void clocksource_select_watchdog(bool fallback)
510 {
511 	struct clocksource *cs, *old_wd;
512 	unsigned long flags;
513 
514 	spin_lock_irqsave(&watchdog_lock, flags);
515 	/* save current watchdog */
516 	old_wd = watchdog;
517 	if (fallback)
518 		watchdog = NULL;
519 
520 	list_for_each_entry(cs, &clocksource_list, list) {
521 		/* cs is a clocksource to be watched. */
522 		if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
523 			continue;
524 
525 		/* Skip current if we were requested for a fallback. */
526 		if (fallback && cs == old_wd)
527 			continue;
528 
529 		/* Pick the best watchdog. */
530 		if (!watchdog || cs->rating > watchdog->rating)
531 			watchdog = cs;
532 	}
533 	/* If we failed to find a fallback restore the old one. */
534 	if (!watchdog)
535 		watchdog = old_wd;
536 
537 	/* If we changed the watchdog we need to reset cycles. */
538 	if (watchdog != old_wd)
539 		clocksource_reset_watchdog();
540 
541 	/* Check if the watchdog timer needs to be started. */
542 	clocksource_start_watchdog();
543 	spin_unlock_irqrestore(&watchdog_lock, flags);
544 }
545 
clocksource_dequeue_watchdog(struct clocksource * cs)546 static void clocksource_dequeue_watchdog(struct clocksource *cs)
547 {
548 	if (cs != watchdog) {
549 		if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
550 			/* cs is a watched clocksource. */
551 			list_del_init(&cs->wd_list);
552 			/* Check if the watchdog timer needs to be stopped. */
553 			clocksource_stop_watchdog();
554 		}
555 	}
556 }
557 
__clocksource_watchdog_kthread(void)558 static int __clocksource_watchdog_kthread(void)
559 {
560 	struct clocksource *cs, *tmp;
561 	unsigned long flags;
562 	int select = 0;
563 
564 	/* Do any required per-CPU skew verification. */
565 	if (curr_clocksource &&
566 	    curr_clocksource->flags & CLOCK_SOURCE_UNSTABLE &&
567 	    curr_clocksource->flags & CLOCK_SOURCE_VERIFY_PERCPU)
568 		clocksource_verify_percpu(curr_clocksource);
569 
570 	spin_lock_irqsave(&watchdog_lock, flags);
571 	list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
572 		if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
573 			list_del_init(&cs->wd_list);
574 			__clocksource_change_rating(cs, 0);
575 			select = 1;
576 		}
577 		if (cs->flags & CLOCK_SOURCE_RESELECT) {
578 			cs->flags &= ~CLOCK_SOURCE_RESELECT;
579 			select = 1;
580 		}
581 	}
582 	/* Check if the watchdog timer needs to be stopped. */
583 	clocksource_stop_watchdog();
584 	spin_unlock_irqrestore(&watchdog_lock, flags);
585 
586 	return select;
587 }
588 
clocksource_watchdog_kthread(void * data)589 static int clocksource_watchdog_kthread(void *data)
590 {
591 	mutex_lock(&clocksource_mutex);
592 	if (__clocksource_watchdog_kthread())
593 		clocksource_select();
594 	mutex_unlock(&clocksource_mutex);
595 	return 0;
596 }
597 
clocksource_is_watchdog(struct clocksource * cs)598 static bool clocksource_is_watchdog(struct clocksource *cs)
599 {
600 	return cs == watchdog;
601 }
602 
603 #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
604 
clocksource_enqueue_watchdog(struct clocksource * cs)605 static void clocksource_enqueue_watchdog(struct clocksource *cs)
606 {
607 	if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
608 		cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
609 }
610 
clocksource_select_watchdog(bool fallback)611 static void clocksource_select_watchdog(bool fallback) { }
clocksource_dequeue_watchdog(struct clocksource * cs)612 static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
clocksource_resume_watchdog(void)613 static inline void clocksource_resume_watchdog(void) { }
__clocksource_watchdog_kthread(void)614 static inline int __clocksource_watchdog_kthread(void) { return 0; }
clocksource_is_watchdog(struct clocksource * cs)615 static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
clocksource_mark_unstable(struct clocksource * cs)616 void clocksource_mark_unstable(struct clocksource *cs) { }
617 
clocksource_watchdog_lock(unsigned long * flags)618 static inline void clocksource_watchdog_lock(unsigned long *flags) { }
clocksource_watchdog_unlock(unsigned long * flags)619 static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
620 
621 #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
622 
clocksource_is_suspend(struct clocksource * cs)623 static bool clocksource_is_suspend(struct clocksource *cs)
624 {
625 	return cs == suspend_clocksource;
626 }
627 
__clocksource_suspend_select(struct clocksource * cs)628 static void __clocksource_suspend_select(struct clocksource *cs)
629 {
630 	/*
631 	 * Skip the clocksource which will be stopped in suspend state.
632 	 */
633 	if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
634 		return;
635 
636 	/*
637 	 * The nonstop clocksource can be selected as the suspend clocksource to
638 	 * calculate the suspend time, so it should not supply suspend/resume
639 	 * interfaces to suspend the nonstop clocksource when system suspends.
640 	 */
641 	if (cs->suspend || cs->resume) {
642 		pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
643 			cs->name);
644 	}
645 
646 	/* Pick the best rating. */
647 	if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
648 		suspend_clocksource = cs;
649 }
650 
651 /**
652  * clocksource_suspend_select - Select the best clocksource for suspend timing
653  * @fallback:	if select a fallback clocksource
654  */
clocksource_suspend_select(bool fallback)655 static void clocksource_suspend_select(bool fallback)
656 {
657 	struct clocksource *cs, *old_suspend;
658 
659 	old_suspend = suspend_clocksource;
660 	if (fallback)
661 		suspend_clocksource = NULL;
662 
663 	list_for_each_entry(cs, &clocksource_list, list) {
664 		/* Skip current if we were requested for a fallback. */
665 		if (fallback && cs == old_suspend)
666 			continue;
667 
668 		__clocksource_suspend_select(cs);
669 	}
670 }
671 
672 /**
673  * clocksource_start_suspend_timing - Start measuring the suspend timing
674  * @cs:			current clocksource from timekeeping
675  * @start_cycles:	current cycles from timekeeping
676  *
677  * This function will save the start cycle values of suspend timer to calculate
678  * the suspend time when resuming system.
679  *
680  * This function is called late in the suspend process from timekeeping_suspend(),
681  * that means processes are freezed, non-boot cpus and interrupts are disabled
682  * now. It is therefore possible to start the suspend timer without taking the
683  * clocksource mutex.
684  */
clocksource_start_suspend_timing(struct clocksource * cs,u64 start_cycles)685 void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
686 {
687 	if (!suspend_clocksource)
688 		return;
689 
690 	/*
691 	 * If current clocksource is the suspend timer, we should use the
692 	 * tkr_mono.cycle_last value as suspend_start to avoid same reading
693 	 * from suspend timer.
694 	 */
695 	if (clocksource_is_suspend(cs)) {
696 		suspend_start = start_cycles;
697 		return;
698 	}
699 
700 	if (suspend_clocksource->enable &&
701 	    suspend_clocksource->enable(suspend_clocksource)) {
702 		pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
703 		return;
704 	}
705 
706 	suspend_start = suspend_clocksource->read(suspend_clocksource);
707 }
708 
709 /**
710  * clocksource_stop_suspend_timing - Stop measuring the suspend timing
711  * @cs:		current clocksource from timekeeping
712  * @cycle_now:	current cycles from timekeeping
713  *
714  * This function will calculate the suspend time from suspend timer.
715  *
716  * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
717  *
718  * This function is called early in the resume process from timekeeping_resume(),
719  * that means there is only one cpu, no processes are running and the interrupts
720  * are disabled. It is therefore possible to stop the suspend timer without
721  * taking the clocksource mutex.
722  */
clocksource_stop_suspend_timing(struct clocksource * cs,u64 cycle_now)723 u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
724 {
725 	u64 now, delta, nsec = 0;
726 
727 	if (!suspend_clocksource)
728 		return 0;
729 
730 	/*
731 	 * If current clocksource is the suspend timer, we should use the
732 	 * tkr_mono.cycle_last value from timekeeping as current cycle to
733 	 * avoid same reading from suspend timer.
734 	 */
735 	if (clocksource_is_suspend(cs))
736 		now = cycle_now;
737 	else
738 		now = suspend_clocksource->read(suspend_clocksource);
739 
740 	if (now > suspend_start) {
741 		delta = clocksource_delta(now, suspend_start,
742 					  suspend_clocksource->mask);
743 		nsec = mul_u64_u32_shr(delta, suspend_clocksource->mult,
744 				       suspend_clocksource->shift);
745 	}
746 
747 	/*
748 	 * Disable the suspend timer to save power if current clocksource is
749 	 * not the suspend timer.
750 	 */
751 	if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
752 		suspend_clocksource->disable(suspend_clocksource);
753 
754 	return nsec;
755 }
756 
757 /**
758  * clocksource_suspend - suspend the clocksource(s)
759  */
clocksource_suspend(void)760 void clocksource_suspend(void)
761 {
762 	struct clocksource *cs;
763 
764 	list_for_each_entry_reverse(cs, &clocksource_list, list)
765 		if (cs->suspend)
766 			cs->suspend(cs);
767 }
768 
769 /**
770  * clocksource_resume - resume the clocksource(s)
771  */
clocksource_resume(void)772 void clocksource_resume(void)
773 {
774 	struct clocksource *cs;
775 
776 	list_for_each_entry(cs, &clocksource_list, list)
777 		if (cs->resume)
778 			cs->resume(cs);
779 
780 	clocksource_resume_watchdog();
781 }
782 
783 /**
784  * clocksource_touch_watchdog - Update watchdog
785  *
786  * Update the watchdog after exception contexts such as kgdb so as not
787  * to incorrectly trip the watchdog. This might fail when the kernel
788  * was stopped in code which holds watchdog_lock.
789  */
clocksource_touch_watchdog(void)790 void clocksource_touch_watchdog(void)
791 {
792 	clocksource_resume_watchdog();
793 }
794 
795 /**
796  * clocksource_max_adjustment- Returns max adjustment amount
797  * @cs:         Pointer to clocksource
798  *
799  */
clocksource_max_adjustment(struct clocksource * cs)800 static u32 clocksource_max_adjustment(struct clocksource *cs)
801 {
802 	u64 ret;
803 	/*
804 	 * We won't try to correct for more than 11% adjustments (110,000 ppm),
805 	 */
806 	ret = (u64)cs->mult * 11;
807 	do_div(ret,100);
808 	return (u32)ret;
809 }
810 
811 /**
812  * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
813  * @mult:	cycle to nanosecond multiplier
814  * @shift:	cycle to nanosecond divisor (power of two)
815  * @maxadj:	maximum adjustment value to mult (~11%)
816  * @mask:	bitmask for two's complement subtraction of non 64 bit counters
817  * @max_cyc:	maximum cycle value before potential overflow (does not include
818  *		any safety margin)
819  *
820  * NOTE: This function includes a safety margin of 50%, in other words, we
821  * return half the number of nanoseconds the hardware counter can technically
822  * cover. This is done so that we can potentially detect problems caused by
823  * delayed timers or bad hardware, which might result in time intervals that
824  * are larger than what the math used can handle without overflows.
825  */
clocks_calc_max_nsecs(u32 mult,u32 shift,u32 maxadj,u64 mask,u64 * max_cyc)826 u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
827 {
828 	u64 max_nsecs, max_cycles;
829 
830 	/*
831 	 * Calculate the maximum number of cycles that we can pass to the
832 	 * cyc2ns() function without overflowing a 64-bit result.
833 	 */
834 	max_cycles = ULLONG_MAX;
835 	do_div(max_cycles, mult+maxadj);
836 
837 	/*
838 	 * The actual maximum number of cycles we can defer the clocksource is
839 	 * determined by the minimum of max_cycles and mask.
840 	 * Note: Here we subtract the maxadj to make sure we don't sleep for
841 	 * too long if there's a large negative adjustment.
842 	 */
843 	max_cycles = min(max_cycles, mask);
844 	max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
845 
846 	/* return the max_cycles value as well if requested */
847 	if (max_cyc)
848 		*max_cyc = max_cycles;
849 
850 	/* Return 50% of the actual maximum, so we can detect bad values */
851 	max_nsecs >>= 1;
852 
853 	return max_nsecs;
854 }
855 
856 /**
857  * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
858  * @cs:         Pointer to clocksource to be updated
859  *
860  */
clocksource_update_max_deferment(struct clocksource * cs)861 static inline void clocksource_update_max_deferment(struct clocksource *cs)
862 {
863 	cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
864 						cs->maxadj, cs->mask,
865 						&cs->max_cycles);
866 }
867 
868 #ifndef CONFIG_ARCH_USES_GETTIMEOFFSET
869 
clocksource_find_best(bool oneshot,bool skipcur)870 static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
871 {
872 	struct clocksource *cs;
873 
874 	if (!finished_booting || list_empty(&clocksource_list))
875 		return NULL;
876 
877 	/*
878 	 * We pick the clocksource with the highest rating. If oneshot
879 	 * mode is active, we pick the highres valid clocksource with
880 	 * the best rating.
881 	 */
882 	list_for_each_entry(cs, &clocksource_list, list) {
883 		if (skipcur && cs == curr_clocksource)
884 			continue;
885 		if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
886 			continue;
887 		return cs;
888 	}
889 	return NULL;
890 }
891 
__clocksource_select(bool skipcur)892 static void __clocksource_select(bool skipcur)
893 {
894 	bool oneshot = tick_oneshot_mode_active();
895 	struct clocksource *best, *cs;
896 
897 	/* Find the best suitable clocksource */
898 	best = clocksource_find_best(oneshot, skipcur);
899 	if (!best)
900 		return;
901 
902 	if (!strlen(override_name))
903 		goto found;
904 
905 	/* Check for the override clocksource. */
906 	list_for_each_entry(cs, &clocksource_list, list) {
907 		if (skipcur && cs == curr_clocksource)
908 			continue;
909 		if (strcmp(cs->name, override_name) != 0)
910 			continue;
911 		/*
912 		 * Check to make sure we don't switch to a non-highres
913 		 * capable clocksource if the tick code is in oneshot
914 		 * mode (highres or nohz)
915 		 */
916 		if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
917 			/* Override clocksource cannot be used. */
918 			if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
919 				pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
920 					cs->name);
921 				override_name[0] = 0;
922 			} else {
923 				/*
924 				 * The override cannot be currently verified.
925 				 * Deferring to let the watchdog check.
926 				 */
927 				pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
928 					cs->name);
929 			}
930 		} else
931 			/* Override clocksource can be used. */
932 			best = cs;
933 		break;
934 	}
935 
936 found:
937 	if (curr_clocksource != best && !timekeeping_notify(best)) {
938 		pr_info("Switched to clocksource %s\n", best->name);
939 		curr_clocksource = best;
940 	}
941 }
942 
943 /**
944  * clocksource_select - Select the best clocksource available
945  *
946  * Private function. Must hold clocksource_mutex when called.
947  *
948  * Select the clocksource with the best rating, or the clocksource,
949  * which is selected by userspace override.
950  */
clocksource_select(void)951 static void clocksource_select(void)
952 {
953 	__clocksource_select(false);
954 }
955 
clocksource_select_fallback(void)956 static void clocksource_select_fallback(void)
957 {
958 	__clocksource_select(true);
959 }
960 
961 #else /* !CONFIG_ARCH_USES_GETTIMEOFFSET */
clocksource_select(void)962 static inline void clocksource_select(void) { }
clocksource_select_fallback(void)963 static inline void clocksource_select_fallback(void) { }
964 
965 #endif
966 
967 /*
968  * clocksource_done_booting - Called near the end of core bootup
969  *
970  * Hack to avoid lots of clocksource churn at boot time.
971  * We use fs_initcall because we want this to start before
972  * device_initcall but after subsys_initcall.
973  */
clocksource_done_booting(void)974 static int __init clocksource_done_booting(void)
975 {
976 	mutex_lock(&clocksource_mutex);
977 	curr_clocksource = clocksource_default_clock();
978 	finished_booting = 1;
979 	/*
980 	 * Run the watchdog first to eliminate unstable clock sources
981 	 */
982 	__clocksource_watchdog_kthread();
983 	clocksource_select();
984 	mutex_unlock(&clocksource_mutex);
985 	return 0;
986 }
987 fs_initcall(clocksource_done_booting);
988 
989 /*
990  * Enqueue the clocksource sorted by rating
991  */
clocksource_enqueue(struct clocksource * cs)992 static void clocksource_enqueue(struct clocksource *cs)
993 {
994 	struct list_head *entry = &clocksource_list;
995 	struct clocksource *tmp;
996 
997 	list_for_each_entry(tmp, &clocksource_list, list) {
998 		/* Keep track of the place, where to insert */
999 		if (tmp->rating < cs->rating)
1000 			break;
1001 		entry = &tmp->list;
1002 	}
1003 	list_add(&cs->list, entry);
1004 }
1005 
1006 /**
1007  * __clocksource_update_freq_scale - Used update clocksource with new freq
1008  * @cs:		clocksource to be registered
1009  * @scale:	Scale factor multiplied against freq to get clocksource hz
1010  * @freq:	clocksource frequency (cycles per second) divided by scale
1011  *
1012  * This should only be called from the clocksource->enable() method.
1013  *
1014  * This *SHOULD NOT* be called directly! Please use the
1015  * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
1016  * functions.
1017  */
__clocksource_update_freq_scale(struct clocksource * cs,u32 scale,u32 freq)1018 void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
1019 {
1020 	u64 sec;
1021 
1022 	/*
1023 	 * Default clocksources are *special* and self-define their mult/shift.
1024 	 * But, you're not special, so you should specify a freq value.
1025 	 */
1026 	if (freq) {
1027 		/*
1028 		 * Calc the maximum number of seconds which we can run before
1029 		 * wrapping around. For clocksources which have a mask > 32-bit
1030 		 * we need to limit the max sleep time to have a good
1031 		 * conversion precision. 10 minutes is still a reasonable
1032 		 * amount. That results in a shift value of 24 for a
1033 		 * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
1034 		 * ~ 0.06ppm granularity for NTP.
1035 		 */
1036 		sec = cs->mask;
1037 		do_div(sec, freq);
1038 		do_div(sec, scale);
1039 		if (!sec)
1040 			sec = 1;
1041 		else if (sec > 600 && cs->mask > UINT_MAX)
1042 			sec = 600;
1043 
1044 		clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
1045 				       NSEC_PER_SEC / scale, sec * scale);
1046 	}
1047 
1048 	/*
1049 	 * If the uncertainty margin is not specified, calculate it.
1050 	 * If both scale and freq are non-zero, calculate the clock
1051 	 * period, but bound below at 2*WATCHDOG_MAX_SKEW.  However,
1052 	 * if either of scale or freq is zero, be very conservative and
1053 	 * take the tens-of-milliseconds WATCHDOG_THRESHOLD value for the
1054 	 * uncertainty margin.  Allow stupidly small uncertainty margins
1055 	 * to be specified by the caller for testing purposes, but warn
1056 	 * to discourage production use of this capability.
1057 	 */
1058 	if (scale && freq && !cs->uncertainty_margin) {
1059 		cs->uncertainty_margin = NSEC_PER_SEC / (scale * freq);
1060 		if (cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW)
1061 			cs->uncertainty_margin = 2 * WATCHDOG_MAX_SKEW;
1062 	} else if (!cs->uncertainty_margin) {
1063 		cs->uncertainty_margin = WATCHDOG_THRESHOLD;
1064 	}
1065 	WARN_ON_ONCE(cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW);
1066 
1067 	/*
1068 	 * Ensure clocksources that have large 'mult' values don't overflow
1069 	 * when adjusted.
1070 	 */
1071 	cs->maxadj = clocksource_max_adjustment(cs);
1072 	while (freq && ((cs->mult + cs->maxadj < cs->mult)
1073 		|| (cs->mult - cs->maxadj > cs->mult))) {
1074 		cs->mult >>= 1;
1075 		cs->shift--;
1076 		cs->maxadj = clocksource_max_adjustment(cs);
1077 	}
1078 
1079 	/*
1080 	 * Only warn for *special* clocksources that self-define
1081 	 * their mult/shift values and don't specify a freq.
1082 	 */
1083 	WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
1084 		"timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
1085 		cs->name);
1086 
1087 	clocksource_update_max_deferment(cs);
1088 
1089 	pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
1090 		cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
1091 }
1092 EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
1093 
1094 /**
1095  * __clocksource_register_scale - Used to install new clocksources
1096  * @cs:		clocksource to be registered
1097  * @scale:	Scale factor multiplied against freq to get clocksource hz
1098  * @freq:	clocksource frequency (cycles per second) divided by scale
1099  *
1100  * Returns -EBUSY if registration fails, zero otherwise.
1101  *
1102  * This *SHOULD NOT* be called directly! Please use the
1103  * clocksource_register_hz() or clocksource_register_khz helper functions.
1104  */
__clocksource_register_scale(struct clocksource * cs,u32 scale,u32 freq)1105 int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
1106 {
1107 	unsigned long flags;
1108 
1109 	clocksource_arch_init(cs);
1110 
1111 	if (cs->vdso_clock_mode < 0 ||
1112 	    cs->vdso_clock_mode >= VDSO_CLOCKMODE_MAX) {
1113 		pr_warn("clocksource %s registered with invalid VDSO mode %d. Disabling VDSO support.\n",
1114 			cs->name, cs->vdso_clock_mode);
1115 		cs->vdso_clock_mode = VDSO_CLOCKMODE_NONE;
1116 	}
1117 
1118 	/* Initialize mult/shift and max_idle_ns */
1119 	__clocksource_update_freq_scale(cs, scale, freq);
1120 
1121 	/* Add clocksource to the clocksource list */
1122 	mutex_lock(&clocksource_mutex);
1123 
1124 	clocksource_watchdog_lock(&flags);
1125 	clocksource_enqueue(cs);
1126 	clocksource_enqueue_watchdog(cs);
1127 	clocksource_watchdog_unlock(&flags);
1128 
1129 	clocksource_select();
1130 	clocksource_select_watchdog(false);
1131 	__clocksource_suspend_select(cs);
1132 	mutex_unlock(&clocksource_mutex);
1133 	return 0;
1134 }
1135 EXPORT_SYMBOL_GPL(__clocksource_register_scale);
1136 
__clocksource_change_rating(struct clocksource * cs,int rating)1137 static void __clocksource_change_rating(struct clocksource *cs, int rating)
1138 {
1139 	list_del(&cs->list);
1140 	cs->rating = rating;
1141 	clocksource_enqueue(cs);
1142 }
1143 
1144 /**
1145  * clocksource_change_rating - Change the rating of a registered clocksource
1146  * @cs:		clocksource to be changed
1147  * @rating:	new rating
1148  */
clocksource_change_rating(struct clocksource * cs,int rating)1149 void clocksource_change_rating(struct clocksource *cs, int rating)
1150 {
1151 	unsigned long flags;
1152 
1153 	mutex_lock(&clocksource_mutex);
1154 	clocksource_watchdog_lock(&flags);
1155 	__clocksource_change_rating(cs, rating);
1156 	clocksource_watchdog_unlock(&flags);
1157 
1158 	clocksource_select();
1159 	clocksource_select_watchdog(false);
1160 	clocksource_suspend_select(false);
1161 	mutex_unlock(&clocksource_mutex);
1162 }
1163 EXPORT_SYMBOL(clocksource_change_rating);
1164 
1165 /*
1166  * Unbind clocksource @cs. Called with clocksource_mutex held
1167  */
clocksource_unbind(struct clocksource * cs)1168 static int clocksource_unbind(struct clocksource *cs)
1169 {
1170 	unsigned long flags;
1171 
1172 	if (clocksource_is_watchdog(cs)) {
1173 		/* Select and try to install a replacement watchdog. */
1174 		clocksource_select_watchdog(true);
1175 		if (clocksource_is_watchdog(cs))
1176 			return -EBUSY;
1177 	}
1178 
1179 	if (cs == curr_clocksource) {
1180 		/* Select and try to install a replacement clock source */
1181 		clocksource_select_fallback();
1182 		if (curr_clocksource == cs)
1183 			return -EBUSY;
1184 	}
1185 
1186 	if (clocksource_is_suspend(cs)) {
1187 		/*
1188 		 * Select and try to install a replacement suspend clocksource.
1189 		 * If no replacement suspend clocksource, we will just let the
1190 		 * clocksource go and have no suspend clocksource.
1191 		 */
1192 		clocksource_suspend_select(true);
1193 	}
1194 
1195 	clocksource_watchdog_lock(&flags);
1196 	clocksource_dequeue_watchdog(cs);
1197 	list_del_init(&cs->list);
1198 	clocksource_watchdog_unlock(&flags);
1199 
1200 	return 0;
1201 }
1202 
1203 /**
1204  * clocksource_unregister - remove a registered clocksource
1205  * @cs:	clocksource to be unregistered
1206  */
clocksource_unregister(struct clocksource * cs)1207 int clocksource_unregister(struct clocksource *cs)
1208 {
1209 	int ret = 0;
1210 
1211 	mutex_lock(&clocksource_mutex);
1212 	if (!list_empty(&cs->list))
1213 		ret = clocksource_unbind(cs);
1214 	mutex_unlock(&clocksource_mutex);
1215 	return ret;
1216 }
1217 EXPORT_SYMBOL(clocksource_unregister);
1218 
1219 #ifdef CONFIG_SYSFS
1220 /**
1221  * current_clocksource_show - sysfs interface for current clocksource
1222  * @dev:	unused
1223  * @attr:	unused
1224  * @buf:	char buffer to be filled with clocksource list
1225  *
1226  * Provides sysfs interface for listing current clocksource.
1227  */
current_clocksource_show(struct device * dev,struct device_attribute * attr,char * buf)1228 static ssize_t current_clocksource_show(struct device *dev,
1229 					struct device_attribute *attr,
1230 					char *buf)
1231 {
1232 	ssize_t count = 0;
1233 
1234 	mutex_lock(&clocksource_mutex);
1235 	count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
1236 	mutex_unlock(&clocksource_mutex);
1237 
1238 	return count;
1239 }
1240 
sysfs_get_uname(const char * buf,char * dst,size_t cnt)1241 ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
1242 {
1243 	size_t ret = cnt;
1244 
1245 	/* strings from sysfs write are not 0 terminated! */
1246 	if (!cnt || cnt >= CS_NAME_LEN)
1247 		return -EINVAL;
1248 
1249 	/* strip of \n: */
1250 	if (buf[cnt-1] == '\n')
1251 		cnt--;
1252 	if (cnt > 0)
1253 		memcpy(dst, buf, cnt);
1254 	dst[cnt] = 0;
1255 	return ret;
1256 }
1257 
1258 /**
1259  * current_clocksource_store - interface for manually overriding clocksource
1260  * @dev:	unused
1261  * @attr:	unused
1262  * @buf:	name of override clocksource
1263  * @count:	length of buffer
1264  *
1265  * Takes input from sysfs interface for manually overriding the default
1266  * clocksource selection.
1267  */
current_clocksource_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1268 static ssize_t current_clocksource_store(struct device *dev,
1269 					 struct device_attribute *attr,
1270 					 const char *buf, size_t count)
1271 {
1272 	ssize_t ret;
1273 
1274 	mutex_lock(&clocksource_mutex);
1275 
1276 	ret = sysfs_get_uname(buf, override_name, count);
1277 	if (ret >= 0)
1278 		clocksource_select();
1279 
1280 	mutex_unlock(&clocksource_mutex);
1281 
1282 	return ret;
1283 }
1284 static DEVICE_ATTR_RW(current_clocksource);
1285 
1286 /**
1287  * unbind_clocksource_store - interface for manually unbinding clocksource
1288  * @dev:	unused
1289  * @attr:	unused
1290  * @buf:	unused
1291  * @count:	length of buffer
1292  *
1293  * Takes input from sysfs interface for manually unbinding a clocksource.
1294  */
unbind_clocksource_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1295 static ssize_t unbind_clocksource_store(struct device *dev,
1296 					struct device_attribute *attr,
1297 					const char *buf, size_t count)
1298 {
1299 	struct clocksource *cs;
1300 	char name[CS_NAME_LEN];
1301 	ssize_t ret;
1302 
1303 	ret = sysfs_get_uname(buf, name, count);
1304 	if (ret < 0)
1305 		return ret;
1306 
1307 	ret = -ENODEV;
1308 	mutex_lock(&clocksource_mutex);
1309 	list_for_each_entry(cs, &clocksource_list, list) {
1310 		if (strcmp(cs->name, name))
1311 			continue;
1312 		ret = clocksource_unbind(cs);
1313 		break;
1314 	}
1315 	mutex_unlock(&clocksource_mutex);
1316 
1317 	return ret ? ret : count;
1318 }
1319 static DEVICE_ATTR_WO(unbind_clocksource);
1320 
1321 /**
1322  * available_clocksource_show - sysfs interface for listing clocksource
1323  * @dev:	unused
1324  * @attr:	unused
1325  * @buf:	char buffer to be filled with clocksource list
1326  *
1327  * Provides sysfs interface for listing registered clocksources
1328  */
available_clocksource_show(struct device * dev,struct device_attribute * attr,char * buf)1329 static ssize_t available_clocksource_show(struct device *dev,
1330 					  struct device_attribute *attr,
1331 					  char *buf)
1332 {
1333 	struct clocksource *src;
1334 	ssize_t count = 0;
1335 
1336 	mutex_lock(&clocksource_mutex);
1337 	list_for_each_entry(src, &clocksource_list, list) {
1338 		/*
1339 		 * Don't show non-HRES clocksource if the tick code is
1340 		 * in one shot mode (highres=on or nohz=on)
1341 		 */
1342 		if (!tick_oneshot_mode_active() ||
1343 		    (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
1344 			count += snprintf(buf + count,
1345 				  max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
1346 				  "%s ", src->name);
1347 	}
1348 	mutex_unlock(&clocksource_mutex);
1349 
1350 	count += snprintf(buf + count,
1351 			  max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1352 
1353 	return count;
1354 }
1355 static DEVICE_ATTR_RO(available_clocksource);
1356 
1357 static struct attribute *clocksource_attrs[] = {
1358 	&dev_attr_current_clocksource.attr,
1359 	&dev_attr_unbind_clocksource.attr,
1360 	&dev_attr_available_clocksource.attr,
1361 	NULL
1362 };
1363 ATTRIBUTE_GROUPS(clocksource);
1364 
1365 static struct bus_type clocksource_subsys = {
1366 	.name = "clocksource",
1367 	.dev_name = "clocksource",
1368 };
1369 
1370 static struct device device_clocksource = {
1371 	.id	= 0,
1372 	.bus	= &clocksource_subsys,
1373 	.groups	= clocksource_groups,
1374 };
1375 
init_clocksource_sysfs(void)1376 static int __init init_clocksource_sysfs(void)
1377 {
1378 	int error = subsys_system_register(&clocksource_subsys, NULL);
1379 
1380 	if (!error)
1381 		error = device_register(&device_clocksource);
1382 
1383 	return error;
1384 }
1385 
1386 device_initcall(init_clocksource_sysfs);
1387 #endif /* CONFIG_SYSFS */
1388 
1389 /**
1390  * boot_override_clocksource - boot clock override
1391  * @str:	override name
1392  *
1393  * Takes a clocksource= boot argument and uses it
1394  * as the clocksource override name.
1395  */
boot_override_clocksource(char * str)1396 static int __init boot_override_clocksource(char* str)
1397 {
1398 	mutex_lock(&clocksource_mutex);
1399 	if (str)
1400 		strlcpy(override_name, str, sizeof(override_name));
1401 	mutex_unlock(&clocksource_mutex);
1402 	return 1;
1403 }
1404 
1405 __setup("clocksource=", boot_override_clocksource);
1406 
1407 /**
1408  * boot_override_clock - Compatibility layer for deprecated boot option
1409  * @str:	override name
1410  *
1411  * DEPRECATED! Takes a clock= boot argument and uses it
1412  * as the clocksource override name
1413  */
boot_override_clock(char * str)1414 static int __init boot_override_clock(char* str)
1415 {
1416 	if (!strcmp(str, "pmtmr")) {
1417 		pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
1418 		return boot_override_clocksource("acpi_pm");
1419 	}
1420 	pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1421 	return boot_override_clocksource(str);
1422 }
1423 
1424 __setup("clock=", boot_override_clock);
1425