1 // SPDX-License-Identifier: GPL-2.0+
3 * This file contains the functions which manage clocksource drivers.
5 * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
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>
18 #include "tick-internal.h"
19 #include "timekeeping_internal.h"
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
29 * The function evaluates the shift/mult pair for the scaled math
30 * operations of clocksources and clockevents.
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.
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
45 clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
51 * Calculate the shift factor which is limiting the conversion
54 tmp = ((u64)maxsec * from) >> 32;
61 * Find the conversion shift/mult pair which has the best
62 * accuracy and fits the maxsec conversion range:
64 for (sft = 32; sft > 0; sft--) {
65 tmp = (u64) to << sft;
68 if ((tmp >> sftacc) == 0)
74 EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
76 /*[Clocksource internal variables]---------
78 * currently selected clocksource.
79 * suspend_clocksource:
80 * used to calculate the suspend time.
82 * linked list with the registered clocksources
84 * protects manipulations to curr_clocksource and the clocksource_list
86 * Name of the user-specified clocksource.
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;
96 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
97 static void clocksource_watchdog_work(struct work_struct *work);
98 static void clocksource_select(void);
100 static LIST_HEAD(watchdog_list);
101 static struct clocksource *watchdog;
102 static struct timer_list watchdog_timer;
103 static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
104 static DEFINE_SPINLOCK(watchdog_lock);
105 static int watchdog_running;
106 static atomic_t watchdog_reset_pending;
108 static inline void clocksource_watchdog_lock(unsigned long *flags)
110 spin_lock_irqsave(&watchdog_lock, *flags);
113 static inline void clocksource_watchdog_unlock(unsigned long *flags)
115 spin_unlock_irqrestore(&watchdog_lock, *flags);
118 static int clocksource_watchdog_kthread(void *data);
119 static void __clocksource_change_rating(struct clocksource *cs, int rating);
122 * Interval: 0.5sec Threshold: 0.0625s
124 #define WATCHDOG_INTERVAL (HZ >> 1)
125 #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 4)
128 * Maximum permissible delay between two readouts of the watchdog
129 * clocksource surrounding a read of the clocksource being validated.
130 * This delay could be due to SMIs, NMIs, or to VCPU preemptions.
132 #define WATCHDOG_MAX_SKEW (100 * NSEC_PER_USEC)
134 static void clocksource_watchdog_work(struct work_struct *work)
137 * We cannot directly run clocksource_watchdog_kthread() here, because
138 * clocksource_select() calls timekeeping_notify() which uses
139 * stop_machine(). One cannot use stop_machine() from a workqueue() due
140 * lock inversions wrt CPU hotplug.
142 * Also, we only ever run this work once or twice during the lifetime
143 * of the kernel, so there is no point in creating a more permanent
146 * If kthread_run fails the next watchdog scan over the
147 * watchdog_list will find the unstable clock again.
149 kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
152 static void __clocksource_unstable(struct clocksource *cs)
154 cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
155 cs->flags |= CLOCK_SOURCE_UNSTABLE;
158 * If the clocksource is registered clocksource_watchdog_kthread() will
159 * re-rate and re-select.
161 if (list_empty(&cs->list)) {
166 if (cs->mark_unstable)
167 cs->mark_unstable(cs);
169 /* kick clocksource_watchdog_kthread() */
170 if (finished_booting)
171 schedule_work(&watchdog_work);
175 * clocksource_mark_unstable - mark clocksource unstable via watchdog
176 * @cs: clocksource to be marked unstable
178 * This function is called by the x86 TSC code to mark clocksources as unstable;
179 * it defers demotion and re-selection to a kthread.
181 void clocksource_mark_unstable(struct clocksource *cs)
185 spin_lock_irqsave(&watchdog_lock, flags);
186 if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
187 if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
188 list_add(&cs->wd_list, &watchdog_list);
189 __clocksource_unstable(cs);
191 spin_unlock_irqrestore(&watchdog_lock, flags);
194 static ulong max_cswd_read_retries = 3;
195 module_param(max_cswd_read_retries, ulong, 0644);
197 static bool cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
199 unsigned int nretries;
200 u64 wd_end, wd_delta;
203 for (nretries = 0; nretries <= max_cswd_read_retries; nretries++) {
205 *wdnow = watchdog->read(watchdog);
206 *csnow = cs->read(cs);
207 wd_end = watchdog->read(watchdog);
210 wd_delta = clocksource_delta(wd_end, *wdnow, watchdog->mask);
211 wd_delay = clocksource_cyc2ns(wd_delta, watchdog->mult,
213 if (wd_delay <= WATCHDOG_MAX_SKEW) {
214 if (nretries > 1 || nretries >= max_cswd_read_retries) {
215 pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
216 smp_processor_id(), watchdog->name, nretries);
222 pr_warn("timekeeping watchdog on CPU%d: %s read-back delay of %lldns, attempt %d, marking unstable\n",
223 smp_processor_id(), watchdog->name, wd_delay, nretries);
227 static void clocksource_watchdog(struct timer_list *unused)
229 u64 csnow, wdnow, cslast, wdlast, delta;
230 int next_cpu, reset_pending;
231 int64_t wd_nsec, cs_nsec;
232 struct clocksource *cs;
234 spin_lock(&watchdog_lock);
235 if (!watchdog_running)
238 reset_pending = atomic_read(&watchdog_reset_pending);
240 list_for_each_entry(cs, &watchdog_list, wd_list) {
242 /* Clocksource already marked unstable? */
243 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
244 if (finished_booting)
245 schedule_work(&watchdog_work);
249 if (!cs_watchdog_read(cs, &csnow, &wdnow)) {
250 /* Clock readout unreliable, so give it up. */
251 __clocksource_unstable(cs);
255 /* Clocksource initialized ? */
256 if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
257 atomic_read(&watchdog_reset_pending)) {
258 cs->flags |= CLOCK_SOURCE_WATCHDOG;
264 delta = clocksource_delta(wdnow, cs->wd_last, watchdog->mask);
265 wd_nsec = clocksource_cyc2ns(delta, watchdog->mult,
268 delta = clocksource_delta(csnow, cs->cs_last, cs->mask);
269 cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
270 wdlast = cs->wd_last; /* save these in case we print them */
271 cslast = cs->cs_last;
275 if (atomic_read(&watchdog_reset_pending))
278 /* Check the deviation from the watchdog clocksource. */
279 if (abs(cs_nsec - wd_nsec) > WATCHDOG_THRESHOLD) {
280 pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
281 smp_processor_id(), cs->name);
282 pr_warn(" '%s' wd_now: %llx wd_last: %llx mask: %llx\n",
283 watchdog->name, wdnow, wdlast, watchdog->mask);
284 pr_warn(" '%s' cs_now: %llx cs_last: %llx mask: %llx\n",
285 cs->name, csnow, cslast, cs->mask);
286 __clocksource_unstable(cs);
290 if (cs == curr_clocksource && cs->tick_stable)
293 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
294 (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
295 (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
296 /* Mark it valid for high-res. */
297 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
300 * clocksource_done_booting() will sort it if
301 * finished_booting is not set yet.
303 if (!finished_booting)
307 * If this is not the current clocksource let
308 * the watchdog thread reselect it. Due to the
309 * change to high res this clocksource might
310 * be preferred now. If it is the current
311 * clocksource let the tick code know about
314 if (cs != curr_clocksource) {
315 cs->flags |= CLOCK_SOURCE_RESELECT;
316 schedule_work(&watchdog_work);
324 * We only clear the watchdog_reset_pending, when we did a
325 * full cycle through all clocksources.
328 atomic_dec(&watchdog_reset_pending);
331 * Cycle through CPUs to check if the CPUs stay synchronized
334 next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
335 if (next_cpu >= nr_cpu_ids)
336 next_cpu = cpumask_first(cpu_online_mask);
339 * Arm timer if not already pending: could race with concurrent
340 * pair clocksource_stop_watchdog() clocksource_start_watchdog().
342 if (!timer_pending(&watchdog_timer)) {
343 watchdog_timer.expires += WATCHDOG_INTERVAL;
344 add_timer_on(&watchdog_timer, next_cpu);
347 spin_unlock(&watchdog_lock);
350 static inline void clocksource_start_watchdog(void)
352 if (watchdog_running || !watchdog || list_empty(&watchdog_list))
354 timer_setup(&watchdog_timer, clocksource_watchdog, 0);
355 watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
356 add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
357 watchdog_running = 1;
360 static inline void clocksource_stop_watchdog(void)
362 if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
364 del_timer(&watchdog_timer);
365 watchdog_running = 0;
368 static inline void clocksource_reset_watchdog(void)
370 struct clocksource *cs;
372 list_for_each_entry(cs, &watchdog_list, wd_list)
373 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
376 static void clocksource_resume_watchdog(void)
378 atomic_inc(&watchdog_reset_pending);
381 static void clocksource_enqueue_watchdog(struct clocksource *cs)
383 INIT_LIST_HEAD(&cs->wd_list);
385 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
386 /* cs is a clocksource to be watched. */
387 list_add(&cs->wd_list, &watchdog_list);
388 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
390 /* cs is a watchdog. */
391 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
392 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
396 static void clocksource_select_watchdog(bool fallback)
398 struct clocksource *cs, *old_wd;
401 spin_lock_irqsave(&watchdog_lock, flags);
402 /* save current watchdog */
407 list_for_each_entry(cs, &clocksource_list, list) {
408 /* cs is a clocksource to be watched. */
409 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
412 /* Skip current if we were requested for a fallback. */
413 if (fallback && cs == old_wd)
416 /* Pick the best watchdog. */
417 if (!watchdog || cs->rating > watchdog->rating)
420 /* If we failed to find a fallback restore the old one. */
424 /* If we changed the watchdog we need to reset cycles. */
425 if (watchdog != old_wd)
426 clocksource_reset_watchdog();
428 /* Check if the watchdog timer needs to be started. */
429 clocksource_start_watchdog();
430 spin_unlock_irqrestore(&watchdog_lock, flags);
433 static void clocksource_dequeue_watchdog(struct clocksource *cs)
435 if (cs != watchdog) {
436 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
437 /* cs is a watched clocksource. */
438 list_del_init(&cs->wd_list);
439 /* Check if the watchdog timer needs to be stopped. */
440 clocksource_stop_watchdog();
445 static int __clocksource_watchdog_kthread(void)
447 struct clocksource *cs, *tmp;
451 spin_lock_irqsave(&watchdog_lock, flags);
452 list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
453 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
454 list_del_init(&cs->wd_list);
455 __clocksource_change_rating(cs, 0);
458 if (cs->flags & CLOCK_SOURCE_RESELECT) {
459 cs->flags &= ~CLOCK_SOURCE_RESELECT;
463 /* Check if the watchdog timer needs to be stopped. */
464 clocksource_stop_watchdog();
465 spin_unlock_irqrestore(&watchdog_lock, flags);
470 static int clocksource_watchdog_kthread(void *data)
472 mutex_lock(&clocksource_mutex);
473 if (__clocksource_watchdog_kthread())
474 clocksource_select();
475 mutex_unlock(&clocksource_mutex);
479 static bool clocksource_is_watchdog(struct clocksource *cs)
481 return cs == watchdog;
484 #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
486 static void clocksource_enqueue_watchdog(struct clocksource *cs)
488 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
489 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
492 static void clocksource_select_watchdog(bool fallback) { }
493 static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
494 static inline void clocksource_resume_watchdog(void) { }
495 static inline int __clocksource_watchdog_kthread(void) { return 0; }
496 static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
497 void clocksource_mark_unstable(struct clocksource *cs) { }
499 static inline void clocksource_watchdog_lock(unsigned long *flags) { }
500 static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
502 #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
504 static bool clocksource_is_suspend(struct clocksource *cs)
506 return cs == suspend_clocksource;
509 static void __clocksource_suspend_select(struct clocksource *cs)
512 * Skip the clocksource which will be stopped in suspend state.
514 if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
518 * The nonstop clocksource can be selected as the suspend clocksource to
519 * calculate the suspend time, so it should not supply suspend/resume
520 * interfaces to suspend the nonstop clocksource when system suspends.
522 if (cs->suspend || cs->resume) {
523 pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
527 /* Pick the best rating. */
528 if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
529 suspend_clocksource = cs;
533 * clocksource_suspend_select - Select the best clocksource for suspend timing
534 * @fallback: if select a fallback clocksource
536 static void clocksource_suspend_select(bool fallback)
538 struct clocksource *cs, *old_suspend;
540 old_suspend = suspend_clocksource;
542 suspend_clocksource = NULL;
544 list_for_each_entry(cs, &clocksource_list, list) {
545 /* Skip current if we were requested for a fallback. */
546 if (fallback && cs == old_suspend)
549 __clocksource_suspend_select(cs);
554 * clocksource_start_suspend_timing - Start measuring the suspend timing
555 * @cs: current clocksource from timekeeping
556 * @start_cycles: current cycles from timekeeping
558 * This function will save the start cycle values of suspend timer to calculate
559 * the suspend time when resuming system.
561 * This function is called late in the suspend process from timekeeping_suspend(),
562 * that means processes are freezed, non-boot cpus and interrupts are disabled
563 * now. It is therefore possible to start the suspend timer without taking the
566 void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
568 if (!suspend_clocksource)
572 * If current clocksource is the suspend timer, we should use the
573 * tkr_mono.cycle_last value as suspend_start to avoid same reading
574 * from suspend timer.
576 if (clocksource_is_suspend(cs)) {
577 suspend_start = start_cycles;
581 if (suspend_clocksource->enable &&
582 suspend_clocksource->enable(suspend_clocksource)) {
583 pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
587 suspend_start = suspend_clocksource->read(suspend_clocksource);
591 * clocksource_stop_suspend_timing - Stop measuring the suspend timing
592 * @cs: current clocksource from timekeeping
593 * @cycle_now: current cycles from timekeeping
595 * This function will calculate the suspend time from suspend timer.
597 * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
599 * This function is called early in the resume process from timekeeping_resume(),
600 * that means there is only one cpu, no processes are running and the interrupts
601 * are disabled. It is therefore possible to stop the suspend timer without
602 * taking the clocksource mutex.
604 u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
606 u64 now, delta, nsec = 0;
608 if (!suspend_clocksource)
612 * If current clocksource is the suspend timer, we should use the
613 * tkr_mono.cycle_last value from timekeeping as current cycle to
614 * avoid same reading from suspend timer.
616 if (clocksource_is_suspend(cs))
619 now = suspend_clocksource->read(suspend_clocksource);
621 if (now > suspend_start) {
622 delta = clocksource_delta(now, suspend_start,
623 suspend_clocksource->mask);
624 nsec = mul_u64_u32_shr(delta, suspend_clocksource->mult,
625 suspend_clocksource->shift);
629 * Disable the suspend timer to save power if current clocksource is
630 * not the suspend timer.
632 if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
633 suspend_clocksource->disable(suspend_clocksource);
639 * clocksource_suspend - suspend the clocksource(s)
641 void clocksource_suspend(void)
643 struct clocksource *cs;
645 list_for_each_entry_reverse(cs, &clocksource_list, list)
651 * clocksource_resume - resume the clocksource(s)
653 void clocksource_resume(void)
655 struct clocksource *cs;
657 list_for_each_entry(cs, &clocksource_list, list)
661 clocksource_resume_watchdog();
665 * clocksource_touch_watchdog - Update watchdog
667 * Update the watchdog after exception contexts such as kgdb so as not
668 * to incorrectly trip the watchdog. This might fail when the kernel
669 * was stopped in code which holds watchdog_lock.
671 void clocksource_touch_watchdog(void)
673 clocksource_resume_watchdog();
677 * clocksource_max_adjustment- Returns max adjustment amount
678 * @cs: Pointer to clocksource
681 static u32 clocksource_max_adjustment(struct clocksource *cs)
685 * We won't try to correct for more than 11% adjustments (110,000 ppm),
687 ret = (u64)cs->mult * 11;
693 * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
694 * @mult: cycle to nanosecond multiplier
695 * @shift: cycle to nanosecond divisor (power of two)
696 * @maxadj: maximum adjustment value to mult (~11%)
697 * @mask: bitmask for two's complement subtraction of non 64 bit counters
698 * @max_cyc: maximum cycle value before potential overflow (does not include
701 * NOTE: This function includes a safety margin of 50%, in other words, we
702 * return half the number of nanoseconds the hardware counter can technically
703 * cover. This is done so that we can potentially detect problems caused by
704 * delayed timers or bad hardware, which might result in time intervals that
705 * are larger than what the math used can handle without overflows.
707 u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
709 u64 max_nsecs, max_cycles;
712 * Calculate the maximum number of cycles that we can pass to the
713 * cyc2ns() function without overflowing a 64-bit result.
715 max_cycles = ULLONG_MAX;
716 do_div(max_cycles, mult+maxadj);
719 * The actual maximum number of cycles we can defer the clocksource is
720 * determined by the minimum of max_cycles and mask.
721 * Note: Here we subtract the maxadj to make sure we don't sleep for
722 * too long if there's a large negative adjustment.
724 max_cycles = min(max_cycles, mask);
725 max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
727 /* return the max_cycles value as well if requested */
729 *max_cyc = max_cycles;
731 /* Return 50% of the actual maximum, so we can detect bad values */
738 * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
739 * @cs: Pointer to clocksource to be updated
742 static inline void clocksource_update_max_deferment(struct clocksource *cs)
744 cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
745 cs->maxadj, cs->mask,
749 #ifndef CONFIG_ARCH_USES_GETTIMEOFFSET
751 static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
753 struct clocksource *cs;
755 if (!finished_booting || list_empty(&clocksource_list))
759 * We pick the clocksource with the highest rating. If oneshot
760 * mode is active, we pick the highres valid clocksource with
763 list_for_each_entry(cs, &clocksource_list, list) {
764 if (skipcur && cs == curr_clocksource)
766 if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
773 static void __clocksource_select(bool skipcur)
775 bool oneshot = tick_oneshot_mode_active();
776 struct clocksource *best, *cs;
778 /* Find the best suitable clocksource */
779 best = clocksource_find_best(oneshot, skipcur);
783 if (!strlen(override_name))
786 /* Check for the override clocksource. */
787 list_for_each_entry(cs, &clocksource_list, list) {
788 if (skipcur && cs == curr_clocksource)
790 if (strcmp(cs->name, override_name) != 0)
793 * Check to make sure we don't switch to a non-highres
794 * capable clocksource if the tick code is in oneshot
795 * mode (highres or nohz)
797 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
798 /* Override clocksource cannot be used. */
799 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
800 pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
802 override_name[0] = 0;
805 * The override cannot be currently verified.
806 * Deferring to let the watchdog check.
808 pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
812 /* Override clocksource can be used. */
818 if (curr_clocksource != best && !timekeeping_notify(best)) {
819 pr_info("Switched to clocksource %s\n", best->name);
820 curr_clocksource = best;
825 * clocksource_select - Select the best clocksource available
827 * Private function. Must hold clocksource_mutex when called.
829 * Select the clocksource with the best rating, or the clocksource,
830 * which is selected by userspace override.
832 static void clocksource_select(void)
834 __clocksource_select(false);
837 static void clocksource_select_fallback(void)
839 __clocksource_select(true);
842 #else /* !CONFIG_ARCH_USES_GETTIMEOFFSET */
843 static inline void clocksource_select(void) { }
844 static inline void clocksource_select_fallback(void) { }
849 * clocksource_done_booting - Called near the end of core bootup
851 * Hack to avoid lots of clocksource churn at boot time.
852 * We use fs_initcall because we want this to start before
853 * device_initcall but after subsys_initcall.
855 static int __init clocksource_done_booting(void)
857 mutex_lock(&clocksource_mutex);
858 curr_clocksource = clocksource_default_clock();
859 finished_booting = 1;
861 * Run the watchdog first to eliminate unstable clock sources
863 __clocksource_watchdog_kthread();
864 clocksource_select();
865 mutex_unlock(&clocksource_mutex);
868 fs_initcall(clocksource_done_booting);
871 * Enqueue the clocksource sorted by rating
873 static void clocksource_enqueue(struct clocksource *cs)
875 struct list_head *entry = &clocksource_list;
876 struct clocksource *tmp;
878 list_for_each_entry(tmp, &clocksource_list, list) {
879 /* Keep track of the place, where to insert */
880 if (tmp->rating < cs->rating)
884 list_add(&cs->list, entry);
888 * __clocksource_update_freq_scale - Used update clocksource with new freq
889 * @cs: clocksource to be registered
890 * @scale: Scale factor multiplied against freq to get clocksource hz
891 * @freq: clocksource frequency (cycles per second) divided by scale
893 * This should only be called from the clocksource->enable() method.
895 * This *SHOULD NOT* be called directly! Please use the
896 * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
899 void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
904 * Default clocksources are *special* and self-define their mult/shift.
905 * But, you're not special, so you should specify a freq value.
909 * Calc the maximum number of seconds which we can run before
910 * wrapping around. For clocksources which have a mask > 32-bit
911 * we need to limit the max sleep time to have a good
912 * conversion precision. 10 minutes is still a reasonable
913 * amount. That results in a shift value of 24 for a
914 * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
915 * ~ 0.06ppm granularity for NTP.
922 else if (sec > 600 && cs->mask > UINT_MAX)
925 clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
926 NSEC_PER_SEC / scale, sec * scale);
929 * Ensure clocksources that have large 'mult' values don't overflow
932 cs->maxadj = clocksource_max_adjustment(cs);
933 while (freq && ((cs->mult + cs->maxadj < cs->mult)
934 || (cs->mult - cs->maxadj > cs->mult))) {
937 cs->maxadj = clocksource_max_adjustment(cs);
941 * Only warn for *special* clocksources that self-define
942 * their mult/shift values and don't specify a freq.
944 WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
945 "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
948 clocksource_update_max_deferment(cs);
950 pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
951 cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
953 EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
956 * __clocksource_register_scale - Used to install new clocksources
957 * @cs: clocksource to be registered
958 * @scale: Scale factor multiplied against freq to get clocksource hz
959 * @freq: clocksource frequency (cycles per second) divided by scale
961 * Returns -EBUSY if registration fails, zero otherwise.
963 * This *SHOULD NOT* be called directly! Please use the
964 * clocksource_register_hz() or clocksource_register_khz helper functions.
966 int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
970 clocksource_arch_init(cs);
972 /* Initialize mult/shift and max_idle_ns */
973 __clocksource_update_freq_scale(cs, scale, freq);
975 /* Add clocksource to the clocksource list */
976 mutex_lock(&clocksource_mutex);
978 clocksource_watchdog_lock(&flags);
979 clocksource_enqueue(cs);
980 clocksource_enqueue_watchdog(cs);
981 clocksource_watchdog_unlock(&flags);
983 clocksource_select();
984 clocksource_select_watchdog(false);
985 __clocksource_suspend_select(cs);
986 mutex_unlock(&clocksource_mutex);
989 EXPORT_SYMBOL_GPL(__clocksource_register_scale);
991 static void __clocksource_change_rating(struct clocksource *cs, int rating)
995 clocksource_enqueue(cs);
999 * clocksource_change_rating - Change the rating of a registered clocksource
1000 * @cs: clocksource to be changed
1001 * @rating: new rating
1003 void clocksource_change_rating(struct clocksource *cs, int rating)
1005 unsigned long flags;
1007 mutex_lock(&clocksource_mutex);
1008 clocksource_watchdog_lock(&flags);
1009 __clocksource_change_rating(cs, rating);
1010 clocksource_watchdog_unlock(&flags);
1012 clocksource_select();
1013 clocksource_select_watchdog(false);
1014 clocksource_suspend_select(false);
1015 mutex_unlock(&clocksource_mutex);
1017 EXPORT_SYMBOL(clocksource_change_rating);
1020 * Unbind clocksource @cs. Called with clocksource_mutex held
1022 static int clocksource_unbind(struct clocksource *cs)
1024 unsigned long flags;
1026 if (clocksource_is_watchdog(cs)) {
1027 /* Select and try to install a replacement watchdog. */
1028 clocksource_select_watchdog(true);
1029 if (clocksource_is_watchdog(cs))
1033 if (cs == curr_clocksource) {
1034 /* Select and try to install a replacement clock source */
1035 clocksource_select_fallback();
1036 if (curr_clocksource == cs)
1040 if (clocksource_is_suspend(cs)) {
1042 * Select and try to install a replacement suspend clocksource.
1043 * If no replacement suspend clocksource, we will just let the
1044 * clocksource go and have no suspend clocksource.
1046 clocksource_suspend_select(true);
1049 clocksource_watchdog_lock(&flags);
1050 clocksource_dequeue_watchdog(cs);
1051 list_del_init(&cs->list);
1052 clocksource_watchdog_unlock(&flags);
1058 * clocksource_unregister - remove a registered clocksource
1059 * @cs: clocksource to be unregistered
1061 int clocksource_unregister(struct clocksource *cs)
1065 mutex_lock(&clocksource_mutex);
1066 if (!list_empty(&cs->list))
1067 ret = clocksource_unbind(cs);
1068 mutex_unlock(&clocksource_mutex);
1071 EXPORT_SYMBOL(clocksource_unregister);
1075 * current_clocksource_show - sysfs interface for current clocksource
1078 * @buf: char buffer to be filled with clocksource list
1080 * Provides sysfs interface for listing current clocksource.
1082 static ssize_t current_clocksource_show(struct device *dev,
1083 struct device_attribute *attr,
1088 mutex_lock(&clocksource_mutex);
1089 count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
1090 mutex_unlock(&clocksource_mutex);
1095 ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
1099 /* strings from sysfs write are not 0 terminated! */
1100 if (!cnt || cnt >= CS_NAME_LEN)
1104 if (buf[cnt-1] == '\n')
1107 memcpy(dst, buf, cnt);
1113 * current_clocksource_store - interface for manually overriding clocksource
1116 * @buf: name of override clocksource
1117 * @count: length of buffer
1119 * Takes input from sysfs interface for manually overriding the default
1120 * clocksource selection.
1122 static ssize_t current_clocksource_store(struct device *dev,
1123 struct device_attribute *attr,
1124 const char *buf, size_t count)
1128 mutex_lock(&clocksource_mutex);
1130 ret = sysfs_get_uname(buf, override_name, count);
1132 clocksource_select();
1134 mutex_unlock(&clocksource_mutex);
1138 static DEVICE_ATTR_RW(current_clocksource);
1141 * unbind_clocksource_store - interface for manually unbinding clocksource
1145 * @count: length of buffer
1147 * Takes input from sysfs interface for manually unbinding a clocksource.
1149 static ssize_t unbind_clocksource_store(struct device *dev,
1150 struct device_attribute *attr,
1151 const char *buf, size_t count)
1153 struct clocksource *cs;
1154 char name[CS_NAME_LEN];
1157 ret = sysfs_get_uname(buf, name, count);
1162 mutex_lock(&clocksource_mutex);
1163 list_for_each_entry(cs, &clocksource_list, list) {
1164 if (strcmp(cs->name, name))
1166 ret = clocksource_unbind(cs);
1169 mutex_unlock(&clocksource_mutex);
1171 return ret ? ret : count;
1173 static DEVICE_ATTR_WO(unbind_clocksource);
1176 * available_clocksource_show - sysfs interface for listing clocksource
1179 * @buf: char buffer to be filled with clocksource list
1181 * Provides sysfs interface for listing registered clocksources
1183 static ssize_t available_clocksource_show(struct device *dev,
1184 struct device_attribute *attr,
1187 struct clocksource *src;
1190 mutex_lock(&clocksource_mutex);
1191 list_for_each_entry(src, &clocksource_list, list) {
1193 * Don't show non-HRES clocksource if the tick code is
1194 * in one shot mode (highres=on or nohz=on)
1196 if (!tick_oneshot_mode_active() ||
1197 (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
1198 count += snprintf(buf + count,
1199 max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
1202 mutex_unlock(&clocksource_mutex);
1204 count += snprintf(buf + count,
1205 max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1209 static DEVICE_ATTR_RO(available_clocksource);
1211 static struct attribute *clocksource_attrs[] = {
1212 &dev_attr_current_clocksource.attr,
1213 &dev_attr_unbind_clocksource.attr,
1214 &dev_attr_available_clocksource.attr,
1217 ATTRIBUTE_GROUPS(clocksource);
1219 static struct bus_type clocksource_subsys = {
1220 .name = "clocksource",
1221 .dev_name = "clocksource",
1224 static struct device device_clocksource = {
1226 .bus = &clocksource_subsys,
1227 .groups = clocksource_groups,
1230 static int __init init_clocksource_sysfs(void)
1232 int error = subsys_system_register(&clocksource_subsys, NULL);
1235 error = device_register(&device_clocksource);
1240 device_initcall(init_clocksource_sysfs);
1241 #endif /* CONFIG_SYSFS */
1244 * boot_override_clocksource - boot clock override
1245 * @str: override name
1247 * Takes a clocksource= boot argument and uses it
1248 * as the clocksource override name.
1250 static int __init boot_override_clocksource(char* str)
1252 mutex_lock(&clocksource_mutex);
1254 strlcpy(override_name, str, sizeof(override_name));
1255 mutex_unlock(&clocksource_mutex);
1259 __setup("clocksource=", boot_override_clocksource);
1262 * boot_override_clock - Compatibility layer for deprecated boot option
1263 * @str: override name
1265 * DEPRECATED! Takes a clock= boot argument and uses it
1266 * as the clocksource override name
1268 static int __init boot_override_clock(char* str)
1270 if (!strcmp(str, "pmtmr")) {
1271 pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
1272 return boot_override_clocksource("acpi_pm");
1274 pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1275 return boot_override_clocksource(str);
1278 __setup("clock=", boot_override_clock);