1 // SPDX-License-Identifier: GPL-2.0+
3 * This file contains the functions which manage clocksource drivers.
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
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 #include <linux/prandom.h>
18 #include <linux/cpu.h>
20 #include "tick-internal.h"
21 #include "timekeeping_internal.h"
23 static noinline u64 cycles_to_nsec_safe(struct clocksource *cs, u64 start, u64 end)
25 u64 delta = clocksource_delta(end, start, cs->mask);
27 if (likely(delta < cs->max_cycles))
28 return clocksource_cyc2ns(delta, cs->mult, cs->shift);
30 return mul_u64_u32_shr(delta, cs->mult, cs->shift);
34 * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
35 * @mult: pointer to mult variable
36 * @shift: pointer to shift variable
37 * @from: frequency to convert from
38 * @to: frequency to convert to
39 * @maxsec: guaranteed runtime conversion range in seconds
41 * The function evaluates the shift/mult pair for the scaled math
42 * operations of clocksources and clockevents.
44 * @to and @from are frequency values in HZ. For clock sources @to is
45 * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
46 * event @to is the counter frequency and @from is NSEC_PER_SEC.
48 * The @maxsec conversion range argument controls the time frame in
49 * seconds which must be covered by the runtime conversion with the
50 * calculated mult and shift factors. This guarantees that no 64bit
51 * overflow happens when the input value of the conversion is
52 * multiplied with the calculated mult factor. Larger ranges may
53 * reduce the conversion accuracy by choosing smaller mult and shift
57 clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
63 * Calculate the shift factor which is limiting the conversion
66 tmp = ((u64)maxsec * from) >> 32;
73 * Find the conversion shift/mult pair which has the best
74 * accuracy and fits the maxsec conversion range:
76 for (sft = 32; sft > 0; sft--) {
77 tmp = (u64) to << sft;
80 if ((tmp >> sftacc) == 0)
86 EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
88 /*[Clocksource internal variables]---------
90 * currently selected clocksource.
91 * suspend_clocksource:
92 * used to calculate the suspend time.
94 * linked list with the registered clocksources
96 * protects manipulations to curr_clocksource and the clocksource_list
98 * Name of the user-specified clocksource.
100 static struct clocksource *curr_clocksource;
101 static struct clocksource *suspend_clocksource;
102 static LIST_HEAD(clocksource_list);
103 static DEFINE_MUTEX(clocksource_mutex);
104 static char override_name[CS_NAME_LEN];
105 static int finished_booting;
106 static u64 suspend_start;
111 #define WATCHDOG_INTERVAL (HZ >> 1)
112 #define WATCHDOG_INTERVAL_MAX_NS ((2 * WATCHDOG_INTERVAL) * (NSEC_PER_SEC / HZ))
115 * Threshold: 0.0312s, when doubled: 0.0625s.
117 #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 5)
120 * Maximum permissible delay between two readouts of the watchdog
121 * clocksource surrounding a read of the clocksource being validated.
122 * This delay could be due to SMIs, NMIs, or to VCPU preemptions. Used as
123 * a lower bound for cs->uncertainty_margin values when registering clocks.
125 * The default of 500 parts per million is based on NTP's limits.
126 * If a clocksource is good enough for NTP, it is good enough for us!
128 * In other words, by default, even if a clocksource is extremely
129 * precise (for example, with a sub-nanosecond period), the maximum
130 * permissible skew between the clocksource watchdog and the clocksource
131 * under test is not permitted to go below the 500ppm minimum defined
132 * by MAX_SKEW_USEC. This 500ppm minimum may be overridden using the
133 * CLOCKSOURCE_WATCHDOG_MAX_SKEW_US Kconfig option.
135 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
136 #define MAX_SKEW_USEC CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
138 #define MAX_SKEW_USEC (125 * WATCHDOG_INTERVAL / HZ)
142 * Default for maximum permissible skew when cs->uncertainty_margin is
143 * not specified, and the lower bound even when cs->uncertainty_margin
144 * is specified. This is also the default that is used when registering
145 * clocks with unspecifed cs->uncertainty_margin, so this macro is used
146 * even in CONFIG_CLOCKSOURCE_WATCHDOG=n kernels.
148 #define WATCHDOG_MAX_SKEW (MAX_SKEW_USEC * NSEC_PER_USEC)
150 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
151 static void clocksource_watchdog_work(struct work_struct *work);
152 static void clocksource_select(void);
154 static LIST_HEAD(watchdog_list);
155 static struct clocksource *watchdog;
156 static struct timer_list watchdog_timer;
157 static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
158 static DEFINE_SPINLOCK(watchdog_lock);
159 static int watchdog_running;
160 static atomic_t watchdog_reset_pending;
161 static int64_t watchdog_max_interval;
163 static inline void clocksource_watchdog_lock(unsigned long *flags)
165 spin_lock_irqsave(&watchdog_lock, *flags);
168 static inline void clocksource_watchdog_unlock(unsigned long *flags)
170 spin_unlock_irqrestore(&watchdog_lock, *flags);
173 static int clocksource_watchdog_kthread(void *data);
174 static void __clocksource_change_rating(struct clocksource *cs, int rating);
176 static void clocksource_watchdog_work(struct work_struct *work)
179 * We cannot directly run clocksource_watchdog_kthread() here, because
180 * clocksource_select() calls timekeeping_notify() which uses
181 * stop_machine(). One cannot use stop_machine() from a workqueue() due
182 * lock inversions wrt CPU hotplug.
184 * Also, we only ever run this work once or twice during the lifetime
185 * of the kernel, so there is no point in creating a more permanent
188 * If kthread_run fails the next watchdog scan over the
189 * watchdog_list will find the unstable clock again.
191 kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
194 static void __clocksource_unstable(struct clocksource *cs)
196 cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
197 cs->flags |= CLOCK_SOURCE_UNSTABLE;
200 * If the clocksource is registered clocksource_watchdog_kthread() will
201 * re-rate and re-select.
203 if (list_empty(&cs->list)) {
208 if (cs->mark_unstable)
209 cs->mark_unstable(cs);
211 /* kick clocksource_watchdog_kthread() */
212 if (finished_booting)
213 schedule_work(&watchdog_work);
217 * clocksource_mark_unstable - mark clocksource unstable via watchdog
218 * @cs: clocksource to be marked unstable
220 * This function is called by the x86 TSC code to mark clocksources as unstable;
221 * it defers demotion and re-selection to a kthread.
223 void clocksource_mark_unstable(struct clocksource *cs)
227 spin_lock_irqsave(&watchdog_lock, flags);
228 if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
229 if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
230 list_add(&cs->wd_list, &watchdog_list);
231 __clocksource_unstable(cs);
233 spin_unlock_irqrestore(&watchdog_lock, flags);
236 static int verify_n_cpus = 8;
237 module_param(verify_n_cpus, int, 0644);
239 enum wd_read_status {
245 static enum wd_read_status cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
247 int64_t md = 2 * watchdog->uncertainty_margin;
248 unsigned int nretries, max_retries;
249 int64_t wd_delay, wd_seq_delay;
252 max_retries = clocksource_get_max_watchdog_retry();
253 for (nretries = 0; nretries <= max_retries; nretries++) {
255 *wdnow = watchdog->read(watchdog);
256 *csnow = cs->read(cs);
257 wd_end = watchdog->read(watchdog);
258 wd_end2 = watchdog->read(watchdog);
261 wd_delay = cycles_to_nsec_safe(watchdog, *wdnow, wd_end);
262 if (wd_delay <= md + cs->uncertainty_margin) {
263 if (nretries > 1 && nretries >= max_retries) {
264 pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
265 smp_processor_id(), watchdog->name, nretries);
267 return WD_READ_SUCCESS;
271 * Now compute delay in consecutive watchdog read to see if
272 * there is too much external interferences that cause
273 * significant delay in reading both clocksource and watchdog.
275 * If consecutive WD read-back delay > md, report
276 * system busy, reinit the watchdog and skip the current
279 wd_seq_delay = cycles_to_nsec_safe(watchdog, wd_end, wd_end2);
280 if (wd_seq_delay > md)
284 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",
285 smp_processor_id(), cs->name, wd_delay, WATCHDOG_MAX_SKEW, wd_seq_delay, nretries, cs->name);
286 return WD_READ_UNSTABLE;
289 pr_info("timekeeping watchdog on CPU%d: %s wd-wd read-back delay of %lldns\n",
290 smp_processor_id(), watchdog->name, wd_seq_delay);
291 pr_info("wd-%s-wd read-back delay of %lldns, clock-skew test skipped!\n",
296 static u64 csnow_mid;
297 static cpumask_t cpus_ahead;
298 static cpumask_t cpus_behind;
299 static cpumask_t cpus_chosen;
301 static void clocksource_verify_choose_cpus(void)
303 int cpu, i, n = verify_n_cpus;
306 /* Check all of the CPUs. */
307 cpumask_copy(&cpus_chosen, cpu_online_mask);
308 cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
312 /* If no checking desired, or no other CPU to check, leave. */
313 cpumask_clear(&cpus_chosen);
314 if (n == 0 || num_online_cpus() <= 1)
317 /* Make sure to select at least one CPU other than the current CPU. */
318 cpu = cpumask_first(cpu_online_mask);
319 if (cpu == smp_processor_id())
320 cpu = cpumask_next(cpu, cpu_online_mask);
321 if (WARN_ON_ONCE(cpu >= nr_cpu_ids))
323 cpumask_set_cpu(cpu, &cpus_chosen);
325 /* Force a sane value for the boot parameter. */
330 * Randomly select the specified number of CPUs. If the same
331 * CPU is selected multiple times, that CPU is checked only once,
332 * and no replacement CPU is selected. This gracefully handles
333 * situations where verify_n_cpus is greater than the number of
334 * CPUs that are currently online.
336 for (i = 1; i < n; i++) {
337 cpu = get_random_u32_below(nr_cpu_ids);
338 cpu = cpumask_next(cpu - 1, cpu_online_mask);
339 if (cpu >= nr_cpu_ids)
340 cpu = cpumask_first(cpu_online_mask);
341 if (!WARN_ON_ONCE(cpu >= nr_cpu_ids))
342 cpumask_set_cpu(cpu, &cpus_chosen);
345 /* Don't verify ourselves. */
346 cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
349 static void clocksource_verify_one_cpu(void *csin)
351 struct clocksource *cs = (struct clocksource *)csin;
353 csnow_mid = cs->read(cs);
356 void clocksource_verify_percpu(struct clocksource *cs)
358 int64_t cs_nsec, cs_nsec_max = 0, cs_nsec_min = LLONG_MAX;
359 u64 csnow_begin, csnow_end;
363 if (verify_n_cpus == 0)
365 cpumask_clear(&cpus_ahead);
366 cpumask_clear(&cpus_behind);
369 clocksource_verify_choose_cpus();
370 if (cpumask_empty(&cpus_chosen)) {
373 pr_warn("Not enough CPUs to check clocksource '%s'.\n", cs->name);
376 testcpu = smp_processor_id();
377 pr_warn("Checking clocksource %s synchronization from CPU %d to CPUs %*pbl.\n", cs->name, testcpu, cpumask_pr_args(&cpus_chosen));
378 for_each_cpu(cpu, &cpus_chosen) {
381 csnow_begin = cs->read(cs);
382 smp_call_function_single(cpu, clocksource_verify_one_cpu, cs, 1);
383 csnow_end = cs->read(cs);
384 delta = (s64)((csnow_mid - csnow_begin) & cs->mask);
386 cpumask_set_cpu(cpu, &cpus_behind);
387 delta = (csnow_end - csnow_mid) & cs->mask;
389 cpumask_set_cpu(cpu, &cpus_ahead);
390 cs_nsec = cycles_to_nsec_safe(cs, csnow_begin, csnow_end);
391 if (cs_nsec > cs_nsec_max)
392 cs_nsec_max = cs_nsec;
393 if (cs_nsec < cs_nsec_min)
394 cs_nsec_min = cs_nsec;
398 if (!cpumask_empty(&cpus_ahead))
399 pr_warn(" CPUs %*pbl ahead of CPU %d for clocksource %s.\n",
400 cpumask_pr_args(&cpus_ahead), testcpu, cs->name);
401 if (!cpumask_empty(&cpus_behind))
402 pr_warn(" CPUs %*pbl behind CPU %d for clocksource %s.\n",
403 cpumask_pr_args(&cpus_behind), testcpu, cs->name);
404 if (!cpumask_empty(&cpus_ahead) || !cpumask_empty(&cpus_behind))
405 pr_warn(" CPU %d check durations %lldns - %lldns for clocksource %s.\n",
406 testcpu, cs_nsec_min, cs_nsec_max, cs->name);
408 EXPORT_SYMBOL_GPL(clocksource_verify_percpu);
410 static inline void clocksource_reset_watchdog(void)
412 struct clocksource *cs;
414 list_for_each_entry(cs, &watchdog_list, wd_list)
415 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
419 static void clocksource_watchdog(struct timer_list *unused)
421 int64_t wd_nsec, cs_nsec, interval;
422 u64 csnow, wdnow, cslast, wdlast;
423 int next_cpu, reset_pending;
424 struct clocksource *cs;
425 enum wd_read_status read_ret;
426 unsigned long extra_wait = 0;
429 spin_lock(&watchdog_lock);
430 if (!watchdog_running)
433 reset_pending = atomic_read(&watchdog_reset_pending);
435 list_for_each_entry(cs, &watchdog_list, wd_list) {
437 /* Clocksource already marked unstable? */
438 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
439 if (finished_booting)
440 schedule_work(&watchdog_work);
444 read_ret = cs_watchdog_read(cs, &csnow, &wdnow);
446 if (read_ret == WD_READ_UNSTABLE) {
447 /* Clock readout unreliable, so give it up. */
448 __clocksource_unstable(cs);
453 * When WD_READ_SKIP is returned, it means the system is likely
454 * under very heavy load, where the latency of reading
455 * watchdog/clocksource is very big, and affect the accuracy of
456 * watchdog check. So give system some space and suspend the
457 * watchdog check for 5 minutes.
459 if (read_ret == WD_READ_SKIP) {
461 * As the watchdog timer will be suspended, and
462 * cs->last could keep unchanged for 5 minutes, reset
465 clocksource_reset_watchdog();
466 extra_wait = HZ * 300;
470 /* Clocksource initialized ? */
471 if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
472 atomic_read(&watchdog_reset_pending)) {
473 cs->flags |= CLOCK_SOURCE_WATCHDOG;
479 wd_nsec = cycles_to_nsec_safe(watchdog, cs->wd_last, wdnow);
480 cs_nsec = cycles_to_nsec_safe(cs, cs->cs_last, csnow);
481 wdlast = cs->wd_last; /* save these in case we print them */
482 cslast = cs->cs_last;
486 if (atomic_read(&watchdog_reset_pending))
490 * The processing of timer softirqs can get delayed (usually
491 * on account of ksoftirqd not getting to run in a timely
492 * manner), which causes the watchdog interval to stretch.
493 * Skew detection may fail for longer watchdog intervals
494 * on account of fixed margins being used.
495 * Some clocksources, e.g. acpi_pm, cannot tolerate
496 * watchdog intervals longer than a few seconds.
498 interval = max(cs_nsec, wd_nsec);
499 if (unlikely(interval > WATCHDOG_INTERVAL_MAX_NS)) {
500 if (system_state > SYSTEM_SCHEDULING &&
501 interval > 2 * watchdog_max_interval) {
502 watchdog_max_interval = interval;
503 pr_warn("Long readout interval, skipping watchdog check: cs_nsec: %lld wd_nsec: %lld\n",
506 watchdog_timer.expires = jiffies;
510 /* Check the deviation from the watchdog clocksource. */
511 md = cs->uncertainty_margin + watchdog->uncertainty_margin;
512 if (abs(cs_nsec - wd_nsec) > md) {
517 pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
518 smp_processor_id(), cs->name);
519 pr_warn(" '%s' wd_nsec: %lld wd_now: %llx wd_last: %llx mask: %llx\n",
520 watchdog->name, wd_nsec, wdnow, wdlast, watchdog->mask);
521 pr_warn(" '%s' cs_nsec: %lld cs_now: %llx cs_last: %llx mask: %llx\n",
522 cs->name, cs_nsec, csnow, cslast, cs->mask);
523 cs_wd_msec = div_s64_rem(cs_nsec - wd_nsec, 1000 * 1000, &wd_rem);
524 wd_msec = div_s64_rem(wd_nsec, 1000 * 1000, &wd_rem);
525 pr_warn(" Clocksource '%s' skewed %lld ns (%lld ms) over watchdog '%s' interval of %lld ns (%lld ms)\n",
526 cs->name, cs_nsec - wd_nsec, cs_wd_msec, watchdog->name, wd_nsec, wd_msec);
527 if (curr_clocksource == cs)
528 pr_warn(" '%s' is current clocksource.\n", cs->name);
529 else if (curr_clocksource)
530 pr_warn(" '%s' (not '%s') is current clocksource.\n", curr_clocksource->name, cs->name);
532 pr_warn(" No current clocksource.\n");
533 __clocksource_unstable(cs);
537 if (cs == curr_clocksource && cs->tick_stable)
540 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
541 (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
542 (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
543 /* Mark it valid for high-res. */
544 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
547 * clocksource_done_booting() will sort it if
548 * finished_booting is not set yet.
550 if (!finished_booting)
554 * If this is not the current clocksource let
555 * the watchdog thread reselect it. Due to the
556 * change to high res this clocksource might
557 * be preferred now. If it is the current
558 * clocksource let the tick code know about
561 if (cs != curr_clocksource) {
562 cs->flags |= CLOCK_SOURCE_RESELECT;
563 schedule_work(&watchdog_work);
571 * We only clear the watchdog_reset_pending, when we did a
572 * full cycle through all clocksources.
575 atomic_dec(&watchdog_reset_pending);
578 * Cycle through CPUs to check if the CPUs stay synchronized
581 next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
582 if (next_cpu >= nr_cpu_ids)
583 next_cpu = cpumask_first(cpu_online_mask);
586 * Arm timer if not already pending: could race with concurrent
587 * pair clocksource_stop_watchdog() clocksource_start_watchdog().
589 if (!timer_pending(&watchdog_timer)) {
590 watchdog_timer.expires += WATCHDOG_INTERVAL + extra_wait;
591 add_timer_on(&watchdog_timer, next_cpu);
594 spin_unlock(&watchdog_lock);
597 static inline void clocksource_start_watchdog(void)
599 if (watchdog_running || !watchdog || list_empty(&watchdog_list))
601 timer_setup(&watchdog_timer, clocksource_watchdog, 0);
602 watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
603 add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
604 watchdog_running = 1;
607 static inline void clocksource_stop_watchdog(void)
609 if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
611 del_timer(&watchdog_timer);
612 watchdog_running = 0;
615 static void clocksource_resume_watchdog(void)
617 atomic_inc(&watchdog_reset_pending);
620 static void clocksource_enqueue_watchdog(struct clocksource *cs)
622 INIT_LIST_HEAD(&cs->wd_list);
624 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
625 /* cs is a clocksource to be watched. */
626 list_add(&cs->wd_list, &watchdog_list);
627 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
629 /* cs is a watchdog. */
630 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
631 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
635 static void clocksource_select_watchdog(bool fallback)
637 struct clocksource *cs, *old_wd;
640 spin_lock_irqsave(&watchdog_lock, flags);
641 /* save current watchdog */
646 list_for_each_entry(cs, &clocksource_list, list) {
647 /* cs is a clocksource to be watched. */
648 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
651 /* Skip current if we were requested for a fallback. */
652 if (fallback && cs == old_wd)
655 /* Pick the best watchdog. */
656 if (!watchdog || cs->rating > watchdog->rating)
659 /* If we failed to find a fallback restore the old one. */
663 /* If we changed the watchdog we need to reset cycles. */
664 if (watchdog != old_wd)
665 clocksource_reset_watchdog();
667 /* Check if the watchdog timer needs to be started. */
668 clocksource_start_watchdog();
669 spin_unlock_irqrestore(&watchdog_lock, flags);
672 static void clocksource_dequeue_watchdog(struct clocksource *cs)
674 if (cs != watchdog) {
675 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
676 /* cs is a watched clocksource. */
677 list_del_init(&cs->wd_list);
678 /* Check if the watchdog timer needs to be stopped. */
679 clocksource_stop_watchdog();
684 static int __clocksource_watchdog_kthread(void)
686 struct clocksource *cs, *tmp;
690 /* Do any required per-CPU skew verification. */
691 if (curr_clocksource &&
692 curr_clocksource->flags & CLOCK_SOURCE_UNSTABLE &&
693 curr_clocksource->flags & CLOCK_SOURCE_VERIFY_PERCPU)
694 clocksource_verify_percpu(curr_clocksource);
696 spin_lock_irqsave(&watchdog_lock, flags);
697 list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
698 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
699 list_del_init(&cs->wd_list);
700 __clocksource_change_rating(cs, 0);
703 if (cs->flags & CLOCK_SOURCE_RESELECT) {
704 cs->flags &= ~CLOCK_SOURCE_RESELECT;
708 /* Check if the watchdog timer needs to be stopped. */
709 clocksource_stop_watchdog();
710 spin_unlock_irqrestore(&watchdog_lock, flags);
715 static int clocksource_watchdog_kthread(void *data)
717 mutex_lock(&clocksource_mutex);
718 if (__clocksource_watchdog_kthread())
719 clocksource_select();
720 mutex_unlock(&clocksource_mutex);
724 static bool clocksource_is_watchdog(struct clocksource *cs)
726 return cs == watchdog;
729 #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
731 static void clocksource_enqueue_watchdog(struct clocksource *cs)
733 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
734 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
737 static void clocksource_select_watchdog(bool fallback) { }
738 static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
739 static inline void clocksource_resume_watchdog(void) { }
740 static inline int __clocksource_watchdog_kthread(void) { return 0; }
741 static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
742 void clocksource_mark_unstable(struct clocksource *cs) { }
744 static inline void clocksource_watchdog_lock(unsigned long *flags) { }
745 static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
747 #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
749 static bool clocksource_is_suspend(struct clocksource *cs)
751 return cs == suspend_clocksource;
754 static void __clocksource_suspend_select(struct clocksource *cs)
757 * Skip the clocksource which will be stopped in suspend state.
759 if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
763 * The nonstop clocksource can be selected as the suspend clocksource to
764 * calculate the suspend time, so it should not supply suspend/resume
765 * interfaces to suspend the nonstop clocksource when system suspends.
767 if (cs->suspend || cs->resume) {
768 pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
772 /* Pick the best rating. */
773 if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
774 suspend_clocksource = cs;
778 * clocksource_suspend_select - Select the best clocksource for suspend timing
779 * @fallback: if select a fallback clocksource
781 static void clocksource_suspend_select(bool fallback)
783 struct clocksource *cs, *old_suspend;
785 old_suspend = suspend_clocksource;
787 suspend_clocksource = NULL;
789 list_for_each_entry(cs, &clocksource_list, list) {
790 /* Skip current if we were requested for a fallback. */
791 if (fallback && cs == old_suspend)
794 __clocksource_suspend_select(cs);
799 * clocksource_start_suspend_timing - Start measuring the suspend timing
800 * @cs: current clocksource from timekeeping
801 * @start_cycles: current cycles from timekeeping
803 * This function will save the start cycle values of suspend timer to calculate
804 * the suspend time when resuming system.
806 * This function is called late in the suspend process from timekeeping_suspend(),
807 * that means processes are frozen, non-boot cpus and interrupts are disabled
808 * now. It is therefore possible to start the suspend timer without taking the
811 void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
813 if (!suspend_clocksource)
817 * If current clocksource is the suspend timer, we should use the
818 * tkr_mono.cycle_last value as suspend_start to avoid same reading
819 * from suspend timer.
821 if (clocksource_is_suspend(cs)) {
822 suspend_start = start_cycles;
826 if (suspend_clocksource->enable &&
827 suspend_clocksource->enable(suspend_clocksource)) {
828 pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
832 suspend_start = suspend_clocksource->read(suspend_clocksource);
836 * clocksource_stop_suspend_timing - Stop measuring the suspend timing
837 * @cs: current clocksource from timekeeping
838 * @cycle_now: current cycles from timekeeping
840 * This function will calculate the suspend time from suspend timer.
842 * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
844 * This function is called early in the resume process from timekeeping_resume(),
845 * that means there is only one cpu, no processes are running and the interrupts
846 * are disabled. It is therefore possible to stop the suspend timer without
847 * taking the clocksource mutex.
849 u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
853 if (!suspend_clocksource)
857 * If current clocksource is the suspend timer, we should use the
858 * tkr_mono.cycle_last value from timekeeping as current cycle to
859 * avoid same reading from suspend timer.
861 if (clocksource_is_suspend(cs))
864 now = suspend_clocksource->read(suspend_clocksource);
866 if (now > suspend_start)
867 nsec = cycles_to_nsec_safe(suspend_clocksource, suspend_start, now);
870 * Disable the suspend timer to save power if current clocksource is
871 * not the suspend timer.
873 if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
874 suspend_clocksource->disable(suspend_clocksource);
880 * clocksource_suspend - suspend the clocksource(s)
882 void clocksource_suspend(void)
884 struct clocksource *cs;
886 list_for_each_entry_reverse(cs, &clocksource_list, list)
892 * clocksource_resume - resume the clocksource(s)
894 void clocksource_resume(void)
896 struct clocksource *cs;
898 list_for_each_entry(cs, &clocksource_list, list)
902 clocksource_resume_watchdog();
906 * clocksource_touch_watchdog - Update watchdog
908 * Update the watchdog after exception contexts such as kgdb so as not
909 * to incorrectly trip the watchdog. This might fail when the kernel
910 * was stopped in code which holds watchdog_lock.
912 void clocksource_touch_watchdog(void)
914 clocksource_resume_watchdog();
918 * clocksource_max_adjustment- Returns max adjustment amount
919 * @cs: Pointer to clocksource
922 static u32 clocksource_max_adjustment(struct clocksource *cs)
926 * We won't try to correct for more than 11% adjustments (110,000 ppm),
928 ret = (u64)cs->mult * 11;
934 * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
935 * @mult: cycle to nanosecond multiplier
936 * @shift: cycle to nanosecond divisor (power of two)
937 * @maxadj: maximum adjustment value to mult (~11%)
938 * @mask: bitmask for two's complement subtraction of non 64 bit counters
939 * @max_cyc: maximum cycle value before potential overflow (does not include
942 * NOTE: This function includes a safety margin of 50%, in other words, we
943 * return half the number of nanoseconds the hardware counter can technically
944 * cover. This is done so that we can potentially detect problems caused by
945 * delayed timers or bad hardware, which might result in time intervals that
946 * are larger than what the math used can handle without overflows.
948 u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
950 u64 max_nsecs, max_cycles;
953 * Calculate the maximum number of cycles that we can pass to the
954 * cyc2ns() function without overflowing a 64-bit result.
956 max_cycles = ULLONG_MAX;
957 do_div(max_cycles, mult+maxadj);
960 * The actual maximum number of cycles we can defer the clocksource is
961 * determined by the minimum of max_cycles and mask.
962 * Note: Here we subtract the maxadj to make sure we don't sleep for
963 * too long if there's a large negative adjustment.
965 max_cycles = min(max_cycles, mask);
966 max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
968 /* return the max_cycles value as well if requested */
970 *max_cyc = max_cycles;
972 /* Return 50% of the actual maximum, so we can detect bad values */
979 * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
980 * @cs: Pointer to clocksource to be updated
983 static inline void clocksource_update_max_deferment(struct clocksource *cs)
985 cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
986 cs->maxadj, cs->mask,
990 static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
992 struct clocksource *cs;
994 if (!finished_booting || list_empty(&clocksource_list))
998 * We pick the clocksource with the highest rating. If oneshot
999 * mode is active, we pick the highres valid clocksource with
1002 list_for_each_entry(cs, &clocksource_list, list) {
1003 if (skipcur && cs == curr_clocksource)
1005 if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
1012 static void __clocksource_select(bool skipcur)
1014 bool oneshot = tick_oneshot_mode_active();
1015 struct clocksource *best, *cs;
1017 /* Find the best suitable clocksource */
1018 best = clocksource_find_best(oneshot, skipcur);
1022 if (!strlen(override_name))
1025 /* Check for the override clocksource. */
1026 list_for_each_entry(cs, &clocksource_list, list) {
1027 if (skipcur && cs == curr_clocksource)
1029 if (strcmp(cs->name, override_name) != 0)
1032 * Check to make sure we don't switch to a non-highres
1033 * capable clocksource if the tick code is in oneshot
1034 * mode (highres or nohz)
1036 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
1037 /* Override clocksource cannot be used. */
1038 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
1039 pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
1041 override_name[0] = 0;
1044 * The override cannot be currently verified.
1045 * Deferring to let the watchdog check.
1047 pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
1051 /* Override clocksource can be used. */
1057 if (curr_clocksource != best && !timekeeping_notify(best)) {
1058 pr_info("Switched to clocksource %s\n", best->name);
1059 curr_clocksource = best;
1064 * clocksource_select - Select the best clocksource available
1066 * Private function. Must hold clocksource_mutex when called.
1068 * Select the clocksource with the best rating, or the clocksource,
1069 * which is selected by userspace override.
1071 static void clocksource_select(void)
1073 __clocksource_select(false);
1076 static void clocksource_select_fallback(void)
1078 __clocksource_select(true);
1082 * clocksource_done_booting - Called near the end of core bootup
1084 * Hack to avoid lots of clocksource churn at boot time.
1085 * We use fs_initcall because we want this to start before
1086 * device_initcall but after subsys_initcall.
1088 static int __init clocksource_done_booting(void)
1090 mutex_lock(&clocksource_mutex);
1091 curr_clocksource = clocksource_default_clock();
1092 finished_booting = 1;
1094 * Run the watchdog first to eliminate unstable clock sources
1096 __clocksource_watchdog_kthread();
1097 clocksource_select();
1098 mutex_unlock(&clocksource_mutex);
1101 fs_initcall(clocksource_done_booting);
1104 * Enqueue the clocksource sorted by rating
1106 static void clocksource_enqueue(struct clocksource *cs)
1108 struct list_head *entry = &clocksource_list;
1109 struct clocksource *tmp;
1111 list_for_each_entry(tmp, &clocksource_list, list) {
1112 /* Keep track of the place, where to insert */
1113 if (tmp->rating < cs->rating)
1117 list_add(&cs->list, entry);
1121 * __clocksource_update_freq_scale - Used update clocksource with new freq
1122 * @cs: clocksource to be registered
1123 * @scale: Scale factor multiplied against freq to get clocksource hz
1124 * @freq: clocksource frequency (cycles per second) divided by scale
1126 * This should only be called from the clocksource->enable() method.
1128 * This *SHOULD NOT* be called directly! Please use the
1129 * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
1132 void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
1137 * Default clocksources are *special* and self-define their mult/shift.
1138 * But, you're not special, so you should specify a freq value.
1142 * Calc the maximum number of seconds which we can run before
1143 * wrapping around. For clocksources which have a mask > 32-bit
1144 * we need to limit the max sleep time to have a good
1145 * conversion precision. 10 minutes is still a reasonable
1146 * amount. That results in a shift value of 24 for a
1147 * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
1148 * ~ 0.06ppm granularity for NTP.
1155 else if (sec > 600 && cs->mask > UINT_MAX)
1158 clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
1159 NSEC_PER_SEC / scale, sec * scale);
1163 * If the uncertainty margin is not specified, calculate it. If
1164 * both scale and freq are non-zero, calculate the clock period, but
1165 * bound below at 2*WATCHDOG_MAX_SKEW, that is, 500ppm by default.
1166 * However, if either of scale or freq is zero, be very conservative
1167 * and take the tens-of-milliseconds WATCHDOG_THRESHOLD value
1168 * for the uncertainty margin. Allow stupidly small uncertainty
1169 * margins to be specified by the caller for testing purposes,
1170 * but warn to discourage production use of this capability.
1172 * Bottom line: The sum of the uncertainty margins of the
1173 * watchdog clocksource and the clocksource under test will be at
1174 * least 500ppm by default. For more information, please see the
1175 * comment preceding CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US above.
1177 if (scale && freq && !cs->uncertainty_margin) {
1178 cs->uncertainty_margin = NSEC_PER_SEC / (scale * freq);
1179 if (cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW)
1180 cs->uncertainty_margin = 2 * WATCHDOG_MAX_SKEW;
1181 } else if (!cs->uncertainty_margin) {
1182 cs->uncertainty_margin = WATCHDOG_THRESHOLD;
1184 WARN_ON_ONCE(cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW);
1187 * Ensure clocksources that have large 'mult' values don't overflow
1190 cs->maxadj = clocksource_max_adjustment(cs);
1191 while (freq && ((cs->mult + cs->maxadj < cs->mult)
1192 || (cs->mult - cs->maxadj > cs->mult))) {
1195 cs->maxadj = clocksource_max_adjustment(cs);
1199 * Only warn for *special* clocksources that self-define
1200 * their mult/shift values and don't specify a freq.
1202 WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
1203 "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
1206 clocksource_update_max_deferment(cs);
1208 pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
1209 cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
1211 EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
1214 * __clocksource_register_scale - Used to install new clocksources
1215 * @cs: clocksource to be registered
1216 * @scale: Scale factor multiplied against freq to get clocksource hz
1217 * @freq: clocksource frequency (cycles per second) divided by scale
1219 * Returns -EBUSY if registration fails, zero otherwise.
1221 * This *SHOULD NOT* be called directly! Please use the
1222 * clocksource_register_hz() or clocksource_register_khz helper functions.
1224 int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
1226 unsigned long flags;
1228 clocksource_arch_init(cs);
1230 if (WARN_ON_ONCE((unsigned int)cs->id >= CSID_MAX))
1231 cs->id = CSID_GENERIC;
1232 if (cs->vdso_clock_mode < 0 ||
1233 cs->vdso_clock_mode >= VDSO_CLOCKMODE_MAX) {
1234 pr_warn("clocksource %s registered with invalid VDSO mode %d. Disabling VDSO support.\n",
1235 cs->name, cs->vdso_clock_mode);
1236 cs->vdso_clock_mode = VDSO_CLOCKMODE_NONE;
1239 /* Initialize mult/shift and max_idle_ns */
1240 __clocksource_update_freq_scale(cs, scale, freq);
1242 /* Add clocksource to the clocksource list */
1243 mutex_lock(&clocksource_mutex);
1245 clocksource_watchdog_lock(&flags);
1246 clocksource_enqueue(cs);
1247 clocksource_enqueue_watchdog(cs);
1248 clocksource_watchdog_unlock(&flags);
1250 clocksource_select();
1251 clocksource_select_watchdog(false);
1252 __clocksource_suspend_select(cs);
1253 mutex_unlock(&clocksource_mutex);
1256 EXPORT_SYMBOL_GPL(__clocksource_register_scale);
1258 static void __clocksource_change_rating(struct clocksource *cs, int rating)
1260 list_del(&cs->list);
1261 cs->rating = rating;
1262 clocksource_enqueue(cs);
1266 * clocksource_change_rating - Change the rating of a registered clocksource
1267 * @cs: clocksource to be changed
1268 * @rating: new rating
1270 void clocksource_change_rating(struct clocksource *cs, int rating)
1272 unsigned long flags;
1274 mutex_lock(&clocksource_mutex);
1275 clocksource_watchdog_lock(&flags);
1276 __clocksource_change_rating(cs, rating);
1277 clocksource_watchdog_unlock(&flags);
1279 clocksource_select();
1280 clocksource_select_watchdog(false);
1281 clocksource_suspend_select(false);
1282 mutex_unlock(&clocksource_mutex);
1284 EXPORT_SYMBOL(clocksource_change_rating);
1287 * Unbind clocksource @cs. Called with clocksource_mutex held
1289 static int clocksource_unbind(struct clocksource *cs)
1291 unsigned long flags;
1293 if (clocksource_is_watchdog(cs)) {
1294 /* Select and try to install a replacement watchdog. */
1295 clocksource_select_watchdog(true);
1296 if (clocksource_is_watchdog(cs))
1300 if (cs == curr_clocksource) {
1301 /* Select and try to install a replacement clock source */
1302 clocksource_select_fallback();
1303 if (curr_clocksource == cs)
1307 if (clocksource_is_suspend(cs)) {
1309 * Select and try to install a replacement suspend clocksource.
1310 * If no replacement suspend clocksource, we will just let the
1311 * clocksource go and have no suspend clocksource.
1313 clocksource_suspend_select(true);
1316 clocksource_watchdog_lock(&flags);
1317 clocksource_dequeue_watchdog(cs);
1318 list_del_init(&cs->list);
1319 clocksource_watchdog_unlock(&flags);
1325 * clocksource_unregister - remove a registered clocksource
1326 * @cs: clocksource to be unregistered
1328 int clocksource_unregister(struct clocksource *cs)
1332 mutex_lock(&clocksource_mutex);
1333 if (!list_empty(&cs->list))
1334 ret = clocksource_unbind(cs);
1335 mutex_unlock(&clocksource_mutex);
1338 EXPORT_SYMBOL(clocksource_unregister);
1342 * current_clocksource_show - sysfs interface for current clocksource
1345 * @buf: char buffer to be filled with clocksource list
1347 * Provides sysfs interface for listing current clocksource.
1349 static ssize_t current_clocksource_show(struct device *dev,
1350 struct device_attribute *attr,
1355 mutex_lock(&clocksource_mutex);
1356 count = sysfs_emit(buf, "%s\n", curr_clocksource->name);
1357 mutex_unlock(&clocksource_mutex);
1362 ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
1366 /* strings from sysfs write are not 0 terminated! */
1367 if (!cnt || cnt >= CS_NAME_LEN)
1371 if (buf[cnt-1] == '\n')
1374 memcpy(dst, buf, cnt);
1380 * current_clocksource_store - interface for manually overriding clocksource
1383 * @buf: name of override clocksource
1384 * @count: length of buffer
1386 * Takes input from sysfs interface for manually overriding the default
1387 * clocksource selection.
1389 static ssize_t current_clocksource_store(struct device *dev,
1390 struct device_attribute *attr,
1391 const char *buf, size_t count)
1395 mutex_lock(&clocksource_mutex);
1397 ret = sysfs_get_uname(buf, override_name, count);
1399 clocksource_select();
1401 mutex_unlock(&clocksource_mutex);
1405 static DEVICE_ATTR_RW(current_clocksource);
1408 * unbind_clocksource_store - interface for manually unbinding clocksource
1412 * @count: length of buffer
1414 * Takes input from sysfs interface for manually unbinding a clocksource.
1416 static ssize_t unbind_clocksource_store(struct device *dev,
1417 struct device_attribute *attr,
1418 const char *buf, size_t count)
1420 struct clocksource *cs;
1421 char name[CS_NAME_LEN];
1424 ret = sysfs_get_uname(buf, name, count);
1429 mutex_lock(&clocksource_mutex);
1430 list_for_each_entry(cs, &clocksource_list, list) {
1431 if (strcmp(cs->name, name))
1433 ret = clocksource_unbind(cs);
1436 mutex_unlock(&clocksource_mutex);
1438 return ret ? ret : count;
1440 static DEVICE_ATTR_WO(unbind_clocksource);
1443 * available_clocksource_show - sysfs interface for listing clocksource
1446 * @buf: char buffer to be filled with clocksource list
1448 * Provides sysfs interface for listing registered clocksources
1450 static ssize_t available_clocksource_show(struct device *dev,
1451 struct device_attribute *attr,
1454 struct clocksource *src;
1457 mutex_lock(&clocksource_mutex);
1458 list_for_each_entry(src, &clocksource_list, list) {
1460 * Don't show non-HRES clocksource if the tick code is
1461 * in one shot mode (highres=on or nohz=on)
1463 if (!tick_oneshot_mode_active() ||
1464 (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
1465 count += snprintf(buf + count,
1466 max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
1469 mutex_unlock(&clocksource_mutex);
1471 count += snprintf(buf + count,
1472 max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1476 static DEVICE_ATTR_RO(available_clocksource);
1478 static struct attribute *clocksource_attrs[] = {
1479 &dev_attr_current_clocksource.attr,
1480 &dev_attr_unbind_clocksource.attr,
1481 &dev_attr_available_clocksource.attr,
1484 ATTRIBUTE_GROUPS(clocksource);
1486 static const struct bus_type clocksource_subsys = {
1487 .name = "clocksource",
1488 .dev_name = "clocksource",
1491 static struct device device_clocksource = {
1493 .bus = &clocksource_subsys,
1494 .groups = clocksource_groups,
1497 static int __init init_clocksource_sysfs(void)
1499 int error = subsys_system_register(&clocksource_subsys, NULL);
1502 error = device_register(&device_clocksource);
1507 device_initcall(init_clocksource_sysfs);
1508 #endif /* CONFIG_SYSFS */
1511 * boot_override_clocksource - boot clock override
1512 * @str: override name
1514 * Takes a clocksource= boot argument and uses it
1515 * as the clocksource override name.
1517 static int __init boot_override_clocksource(char* str)
1519 mutex_lock(&clocksource_mutex);
1521 strscpy(override_name, str, sizeof(override_name));
1522 mutex_unlock(&clocksource_mutex);
1526 __setup("clocksource=", boot_override_clocksource);
1529 * boot_override_clock - Compatibility layer for deprecated boot option
1530 * @str: override name
1532 * DEPRECATED! Takes a clock= boot argument and uses it
1533 * as the clocksource override name
1535 static int __init boot_override_clock(char* str)
1537 if (!strcmp(str, "pmtmr")) {
1538 pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
1539 return boot_override_clocksource("acpi_pm");
1541 pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1542 return boot_override_clocksource(str);
1545 __setup("clock=", boot_override_clock);