2 * linux/kernel/time/clocksource.c
4 * This file contains the functions which manage clocksource drivers.
6 * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 * o Allow clocksource drivers to be unregistered
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
28 #include <linux/device.h>
29 #include <linux/clocksource.h>
30 #include <linux/init.h>
31 #include <linux/module.h>
32 #include <linux/sched.h> /* for spin_unlock_irq() using preempt_count() m68k */
33 #include <linux/tick.h>
34 #include <linux/kthread.h>
36 #include "tick-internal.h"
37 #include "timekeeping_internal.h"
40 * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
41 * @mult: pointer to mult variable
42 * @shift: pointer to shift variable
43 * @from: frequency to convert from
44 * @to: frequency to convert to
45 * @maxsec: guaranteed runtime conversion range in seconds
47 * The function evaluates the shift/mult pair for the scaled math
48 * operations of clocksources and clockevents.
50 * @to and @from are frequency values in HZ. For clock sources @to is
51 * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
52 * event @to is the counter frequency and @from is NSEC_PER_SEC.
54 * The @maxsec conversion range argument controls the time frame in
55 * seconds which must be covered by the runtime conversion with the
56 * calculated mult and shift factors. This guarantees that no 64bit
57 * overflow happens when the input value of the conversion is
58 * multiplied with the calculated mult factor. Larger ranges may
59 * reduce the conversion accuracy by chosing smaller mult and shift
63 clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
69 * Calculate the shift factor which is limiting the conversion
72 tmp = ((u64)maxsec * from) >> 32;
79 * Find the conversion shift/mult pair which has the best
80 * accuracy and fits the maxsec conversion range:
82 for (sft = 32; sft > 0; sft--) {
83 tmp = (u64) to << sft;
86 if ((tmp >> sftacc) == 0)
92 EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
94 /*[Clocksource internal variables]---------
96 * currently selected clocksource.
97 * suspend_clocksource:
98 * used to calculate the suspend time.
100 * linked list with the registered clocksources
102 * protects manipulations to curr_clocksource and the clocksource_list
104 * Name of the user-specified clocksource.
106 static struct clocksource *curr_clocksource;
107 static struct clocksource *suspend_clocksource;
108 static LIST_HEAD(clocksource_list);
109 static DEFINE_MUTEX(clocksource_mutex);
110 static char override_name[CS_NAME_LEN];
111 static int finished_booting;
112 static u64 suspend_start;
114 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
115 static void clocksource_watchdog_work(struct work_struct *work);
116 static void clocksource_select(void);
118 static LIST_HEAD(watchdog_list);
119 static struct clocksource *watchdog;
120 static struct timer_list watchdog_timer;
121 static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
122 static DEFINE_SPINLOCK(watchdog_lock);
123 static int watchdog_running;
124 static atomic_t watchdog_reset_pending;
126 static void inline clocksource_watchdog_lock(unsigned long *flags)
128 spin_lock_irqsave(&watchdog_lock, *flags);
131 static void inline clocksource_watchdog_unlock(unsigned long *flags)
133 spin_unlock_irqrestore(&watchdog_lock, *flags);
136 static int clocksource_watchdog_kthread(void *data);
137 static void __clocksource_change_rating(struct clocksource *cs, int rating);
140 * Interval: 0.5sec Threshold: 0.0625s
142 #define WATCHDOG_INTERVAL (HZ >> 1)
143 #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 4)
146 * Maximum permissible delay between two readouts of the watchdog
147 * clocksource surrounding a read of the clocksource being validated.
148 * This delay could be due to SMIs, NMIs, or to VCPU preemptions.
150 #define WATCHDOG_MAX_SKEW (100 * NSEC_PER_USEC)
152 static void clocksource_watchdog_work(struct work_struct *work)
155 * We cannot directly run clocksource_watchdog_kthread() here, because
156 * clocksource_select() calls timekeeping_notify() which uses
157 * stop_machine(). One cannot use stop_machine() from a workqueue() due
158 * lock inversions wrt CPU hotplug.
160 * Also, we only ever run this work once or twice during the lifetime
161 * of the kernel, so there is no point in creating a more permanent
164 * If kthread_run fails the next watchdog scan over the
165 * watchdog_list will find the unstable clock again.
167 kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
170 static void __clocksource_unstable(struct clocksource *cs)
172 cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
173 cs->flags |= CLOCK_SOURCE_UNSTABLE;
176 * If the clocksource is registered clocksource_watchdog_kthread() will
177 * re-rate and re-select.
179 if (list_empty(&cs->list)) {
184 if (cs->mark_unstable)
185 cs->mark_unstable(cs);
187 /* kick clocksource_watchdog_kthread() */
188 if (finished_booting)
189 schedule_work(&watchdog_work);
193 * clocksource_mark_unstable - mark clocksource unstable via watchdog
194 * @cs: clocksource to be marked unstable
196 * This function is called by the x86 TSC code to mark clocksources as unstable;
197 * it defers demotion and re-selection to a kthread.
199 void clocksource_mark_unstable(struct clocksource *cs)
203 spin_lock_irqsave(&watchdog_lock, flags);
204 if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
205 if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
206 list_add(&cs->wd_list, &watchdog_list);
207 __clocksource_unstable(cs);
209 spin_unlock_irqrestore(&watchdog_lock, flags);
212 static ulong max_cswd_read_retries = 3;
213 module_param(max_cswd_read_retries, ulong, 0644);
215 static bool cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
217 unsigned int nretries;
218 u64 wd_end, wd_delta;
221 for (nretries = 0; nretries <= max_cswd_read_retries; nretries++) {
223 *wdnow = watchdog->read(watchdog);
224 *csnow = cs->read(cs);
225 wd_end = watchdog->read(watchdog);
228 wd_delta = clocksource_delta(wd_end, *wdnow, watchdog->mask);
229 wd_delay = clocksource_cyc2ns(wd_delta, watchdog->mult,
231 if (wd_delay <= WATCHDOG_MAX_SKEW) {
232 if (nretries > 1 || nretries >= max_cswd_read_retries) {
233 pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
234 smp_processor_id(), watchdog->name, nretries);
240 pr_warn("timekeeping watchdog on CPU%d: %s read-back delay of %lldns, attempt %d, marking unstable\n",
241 smp_processor_id(), watchdog->name, wd_delay, nretries);
245 static void clocksource_watchdog(struct timer_list *unused)
247 u64 csnow, wdnow, cslast, wdlast, delta;
248 int next_cpu, reset_pending;
249 int64_t wd_nsec, cs_nsec;
250 struct clocksource *cs;
252 spin_lock(&watchdog_lock);
253 if (!watchdog_running)
256 reset_pending = atomic_read(&watchdog_reset_pending);
258 list_for_each_entry(cs, &watchdog_list, wd_list) {
260 /* Clocksource already marked unstable? */
261 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
262 if (finished_booting)
263 schedule_work(&watchdog_work);
267 if (!cs_watchdog_read(cs, &csnow, &wdnow)) {
268 /* Clock readout unreliable, so give it up. */
269 __clocksource_unstable(cs);
273 /* Clocksource initialized ? */
274 if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
275 atomic_read(&watchdog_reset_pending)) {
276 cs->flags |= CLOCK_SOURCE_WATCHDOG;
282 delta = clocksource_delta(wdnow, cs->wd_last, watchdog->mask);
283 wd_nsec = clocksource_cyc2ns(delta, watchdog->mult,
286 delta = clocksource_delta(csnow, cs->cs_last, cs->mask);
287 cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
288 wdlast = cs->wd_last; /* save these in case we print them */
289 cslast = cs->cs_last;
293 if (atomic_read(&watchdog_reset_pending))
296 /* Check the deviation from the watchdog clocksource. */
297 if (abs(cs_nsec - wd_nsec) > WATCHDOG_THRESHOLD) {
298 pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
299 smp_processor_id(), cs->name);
300 pr_warn(" '%s' wd_now: %llx wd_last: %llx mask: %llx\n",
301 watchdog->name, wdnow, wdlast, watchdog->mask);
302 pr_warn(" '%s' cs_now: %llx cs_last: %llx mask: %llx\n",
303 cs->name, csnow, cslast, cs->mask);
304 __clocksource_unstable(cs);
308 if (cs == curr_clocksource && cs->tick_stable)
311 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
312 (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
313 (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
314 /* Mark it valid for high-res. */
315 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
318 * clocksource_done_booting() will sort it if
319 * finished_booting is not set yet.
321 if (!finished_booting)
325 * If this is not the current clocksource let
326 * the watchdog thread reselect it. Due to the
327 * change to high res this clocksource might
328 * be preferred now. If it is the current
329 * clocksource let the tick code know about
332 if (cs != curr_clocksource) {
333 cs->flags |= CLOCK_SOURCE_RESELECT;
334 schedule_work(&watchdog_work);
342 * We only clear the watchdog_reset_pending, when we did a
343 * full cycle through all clocksources.
346 atomic_dec(&watchdog_reset_pending);
349 * Cycle through CPUs to check if the CPUs stay synchronized
352 next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
353 if (next_cpu >= nr_cpu_ids)
354 next_cpu = cpumask_first(cpu_online_mask);
357 * Arm timer if not already pending: could race with concurrent
358 * pair clocksource_stop_watchdog() clocksource_start_watchdog().
360 if (!timer_pending(&watchdog_timer)) {
361 watchdog_timer.expires += WATCHDOG_INTERVAL;
362 add_timer_on(&watchdog_timer, next_cpu);
365 spin_unlock(&watchdog_lock);
368 static inline void clocksource_start_watchdog(void)
370 if (watchdog_running || !watchdog || list_empty(&watchdog_list))
372 timer_setup(&watchdog_timer, clocksource_watchdog, 0);
373 watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
374 add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
375 watchdog_running = 1;
378 static inline void clocksource_stop_watchdog(void)
380 if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
382 del_timer(&watchdog_timer);
383 watchdog_running = 0;
386 static inline void clocksource_reset_watchdog(void)
388 struct clocksource *cs;
390 list_for_each_entry(cs, &watchdog_list, wd_list)
391 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
394 static void clocksource_resume_watchdog(void)
396 atomic_inc(&watchdog_reset_pending);
399 static void clocksource_enqueue_watchdog(struct clocksource *cs)
401 INIT_LIST_HEAD(&cs->wd_list);
403 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
404 /* cs is a clocksource to be watched. */
405 list_add(&cs->wd_list, &watchdog_list);
406 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
408 /* cs is a watchdog. */
409 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
410 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
414 static void clocksource_select_watchdog(bool fallback)
416 struct clocksource *cs, *old_wd;
419 spin_lock_irqsave(&watchdog_lock, flags);
420 /* save current watchdog */
425 list_for_each_entry(cs, &clocksource_list, list) {
426 /* cs is a clocksource to be watched. */
427 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
430 /* Skip current if we were requested for a fallback. */
431 if (fallback && cs == old_wd)
434 /* Pick the best watchdog. */
435 if (!watchdog || cs->rating > watchdog->rating)
438 /* If we failed to find a fallback restore the old one. */
442 /* If we changed the watchdog we need to reset cycles. */
443 if (watchdog != old_wd)
444 clocksource_reset_watchdog();
446 /* Check if the watchdog timer needs to be started. */
447 clocksource_start_watchdog();
448 spin_unlock_irqrestore(&watchdog_lock, flags);
451 static void clocksource_dequeue_watchdog(struct clocksource *cs)
453 if (cs != watchdog) {
454 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
455 /* cs is a watched clocksource. */
456 list_del_init(&cs->wd_list);
457 /* Check if the watchdog timer needs to be stopped. */
458 clocksource_stop_watchdog();
463 static int __clocksource_watchdog_kthread(void)
465 struct clocksource *cs, *tmp;
469 spin_lock_irqsave(&watchdog_lock, flags);
470 list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
471 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
472 list_del_init(&cs->wd_list);
473 __clocksource_change_rating(cs, 0);
476 if (cs->flags & CLOCK_SOURCE_RESELECT) {
477 cs->flags &= ~CLOCK_SOURCE_RESELECT;
481 /* Check if the watchdog timer needs to be stopped. */
482 clocksource_stop_watchdog();
483 spin_unlock_irqrestore(&watchdog_lock, flags);
488 static int clocksource_watchdog_kthread(void *data)
490 mutex_lock(&clocksource_mutex);
491 if (__clocksource_watchdog_kthread())
492 clocksource_select();
493 mutex_unlock(&clocksource_mutex);
497 static bool clocksource_is_watchdog(struct clocksource *cs)
499 return cs == watchdog;
502 #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
504 static void clocksource_enqueue_watchdog(struct clocksource *cs)
506 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
507 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
510 static void clocksource_select_watchdog(bool fallback) { }
511 static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
512 static inline void clocksource_resume_watchdog(void) { }
513 static inline int __clocksource_watchdog_kthread(void) { return 0; }
514 static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
515 void clocksource_mark_unstable(struct clocksource *cs) { }
517 static inline void clocksource_watchdog_lock(unsigned long *flags) { }
518 static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
520 #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
522 static bool clocksource_is_suspend(struct clocksource *cs)
524 return cs == suspend_clocksource;
527 static void __clocksource_suspend_select(struct clocksource *cs)
530 * Skip the clocksource which will be stopped in suspend state.
532 if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
536 * The nonstop clocksource can be selected as the suspend clocksource to
537 * calculate the suspend time, so it should not supply suspend/resume
538 * interfaces to suspend the nonstop clocksource when system suspends.
540 if (cs->suspend || cs->resume) {
541 pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
545 /* Pick the best rating. */
546 if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
547 suspend_clocksource = cs;
551 * clocksource_suspend_select - Select the best clocksource for suspend timing
552 * @fallback: if select a fallback clocksource
554 static void clocksource_suspend_select(bool fallback)
556 struct clocksource *cs, *old_suspend;
558 old_suspend = suspend_clocksource;
560 suspend_clocksource = NULL;
562 list_for_each_entry(cs, &clocksource_list, list) {
563 /* Skip current if we were requested for a fallback. */
564 if (fallback && cs == old_suspend)
567 __clocksource_suspend_select(cs);
572 * clocksource_start_suspend_timing - Start measuring the suspend timing
573 * @cs: current clocksource from timekeeping
574 * @start_cycles: current cycles from timekeeping
576 * This function will save the start cycle values of suspend timer to calculate
577 * the suspend time when resuming system.
579 * This function is called late in the suspend process from timekeeping_suspend(),
580 * that means processes are freezed, non-boot cpus and interrupts are disabled
581 * now. It is therefore possible to start the suspend timer without taking the
584 void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
586 if (!suspend_clocksource)
590 * If current clocksource is the suspend timer, we should use the
591 * tkr_mono.cycle_last value as suspend_start to avoid same reading
592 * from suspend timer.
594 if (clocksource_is_suspend(cs)) {
595 suspend_start = start_cycles;
599 if (suspend_clocksource->enable &&
600 suspend_clocksource->enable(suspend_clocksource)) {
601 pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
605 suspend_start = suspend_clocksource->read(suspend_clocksource);
609 * clocksource_stop_suspend_timing - Stop measuring the suspend timing
610 * @cs: current clocksource from timekeeping
611 * @cycle_now: current cycles from timekeeping
613 * This function will calculate the suspend time from suspend timer.
615 * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
617 * This function is called early in the resume process from timekeeping_resume(),
618 * that means there is only one cpu, no processes are running and the interrupts
619 * are disabled. It is therefore possible to stop the suspend timer without
620 * taking the clocksource mutex.
622 u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
624 u64 now, delta, nsec = 0;
626 if (!suspend_clocksource)
630 * If current clocksource is the suspend timer, we should use the
631 * tkr_mono.cycle_last value from timekeeping as current cycle to
632 * avoid same reading from suspend timer.
634 if (clocksource_is_suspend(cs))
637 now = suspend_clocksource->read(suspend_clocksource);
639 if (now > suspend_start) {
640 delta = clocksource_delta(now, suspend_start,
641 suspend_clocksource->mask);
642 nsec = mul_u64_u32_shr(delta, suspend_clocksource->mult,
643 suspend_clocksource->shift);
647 * Disable the suspend timer to save power if current clocksource is
648 * not the suspend timer.
650 if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
651 suspend_clocksource->disable(suspend_clocksource);
657 * clocksource_suspend - suspend the clocksource(s)
659 void clocksource_suspend(void)
661 struct clocksource *cs;
663 list_for_each_entry_reverse(cs, &clocksource_list, list)
669 * clocksource_resume - resume the clocksource(s)
671 void clocksource_resume(void)
673 struct clocksource *cs;
675 list_for_each_entry(cs, &clocksource_list, list)
679 clocksource_resume_watchdog();
683 * clocksource_touch_watchdog - Update watchdog
685 * Update the watchdog after exception contexts such as kgdb so as not
686 * to incorrectly trip the watchdog. This might fail when the kernel
687 * was stopped in code which holds watchdog_lock.
689 void clocksource_touch_watchdog(void)
691 clocksource_resume_watchdog();
695 * clocksource_max_adjustment- Returns max adjustment amount
696 * @cs: Pointer to clocksource
699 static u32 clocksource_max_adjustment(struct clocksource *cs)
703 * We won't try to correct for more than 11% adjustments (110,000 ppm),
705 ret = (u64)cs->mult * 11;
711 * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
712 * @mult: cycle to nanosecond multiplier
713 * @shift: cycle to nanosecond divisor (power of two)
714 * @maxadj: maximum adjustment value to mult (~11%)
715 * @mask: bitmask for two's complement subtraction of non 64 bit counters
716 * @max_cyc: maximum cycle value before potential overflow (does not include
719 * NOTE: This function includes a safety margin of 50%, in other words, we
720 * return half the number of nanoseconds the hardware counter can technically
721 * cover. This is done so that we can potentially detect problems caused by
722 * delayed timers or bad hardware, which might result in time intervals that
723 * are larger than what the math used can handle without overflows.
725 u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
727 u64 max_nsecs, max_cycles;
730 * Calculate the maximum number of cycles that we can pass to the
731 * cyc2ns() function without overflowing a 64-bit result.
733 max_cycles = ULLONG_MAX;
734 do_div(max_cycles, mult+maxadj);
737 * The actual maximum number of cycles we can defer the clocksource is
738 * determined by the minimum of max_cycles and mask.
739 * Note: Here we subtract the maxadj to make sure we don't sleep for
740 * too long if there's a large negative adjustment.
742 max_cycles = min(max_cycles, mask);
743 max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
745 /* return the max_cycles value as well if requested */
747 *max_cyc = max_cycles;
749 /* Return 50% of the actual maximum, so we can detect bad values */
756 * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
757 * @cs: Pointer to clocksource to be updated
760 static inline void clocksource_update_max_deferment(struct clocksource *cs)
762 cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
763 cs->maxadj, cs->mask,
767 #ifndef CONFIG_ARCH_USES_GETTIMEOFFSET
769 static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
771 struct clocksource *cs;
773 if (!finished_booting || list_empty(&clocksource_list))
777 * We pick the clocksource with the highest rating. If oneshot
778 * mode is active, we pick the highres valid clocksource with
781 list_for_each_entry(cs, &clocksource_list, list) {
782 if (skipcur && cs == curr_clocksource)
784 if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
791 static void __clocksource_select(bool skipcur)
793 bool oneshot = tick_oneshot_mode_active();
794 struct clocksource *best, *cs;
796 /* Find the best suitable clocksource */
797 best = clocksource_find_best(oneshot, skipcur);
801 if (!strlen(override_name))
804 /* Check for the override clocksource. */
805 list_for_each_entry(cs, &clocksource_list, list) {
806 if (skipcur && cs == curr_clocksource)
808 if (strcmp(cs->name, override_name) != 0)
811 * Check to make sure we don't switch to a non-highres
812 * capable clocksource if the tick code is in oneshot
813 * mode (highres or nohz)
815 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
816 /* Override clocksource cannot be used. */
817 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
818 pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
820 override_name[0] = 0;
823 * The override cannot be currently verified.
824 * Deferring to let the watchdog check.
826 pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
830 /* Override clocksource can be used. */
836 if (curr_clocksource != best && !timekeeping_notify(best)) {
837 pr_info("Switched to clocksource %s\n", best->name);
838 curr_clocksource = best;
843 * clocksource_select - Select the best clocksource available
845 * Private function. Must hold clocksource_mutex when called.
847 * Select the clocksource with the best rating, or the clocksource,
848 * which is selected by userspace override.
850 static void clocksource_select(void)
852 __clocksource_select(false);
855 static void clocksource_select_fallback(void)
857 __clocksource_select(true);
860 #else /* !CONFIG_ARCH_USES_GETTIMEOFFSET */
861 static inline void clocksource_select(void) { }
862 static inline void clocksource_select_fallback(void) { }
867 * clocksource_done_booting - Called near the end of core bootup
869 * Hack to avoid lots of clocksource churn at boot time.
870 * We use fs_initcall because we want this to start before
871 * device_initcall but after subsys_initcall.
873 static int __init clocksource_done_booting(void)
875 mutex_lock(&clocksource_mutex);
876 curr_clocksource = clocksource_default_clock();
877 finished_booting = 1;
879 * Run the watchdog first to eliminate unstable clock sources
881 __clocksource_watchdog_kthread();
882 clocksource_select();
883 mutex_unlock(&clocksource_mutex);
886 fs_initcall(clocksource_done_booting);
889 * Enqueue the clocksource sorted by rating
891 static void clocksource_enqueue(struct clocksource *cs)
893 struct list_head *entry = &clocksource_list;
894 struct clocksource *tmp;
896 list_for_each_entry(tmp, &clocksource_list, list) {
897 /* Keep track of the place, where to insert */
898 if (tmp->rating < cs->rating)
902 list_add(&cs->list, entry);
906 * __clocksource_update_freq_scale - Used update clocksource with new freq
907 * @cs: clocksource to be registered
908 * @scale: Scale factor multiplied against freq to get clocksource hz
909 * @freq: clocksource frequency (cycles per second) divided by scale
911 * This should only be called from the clocksource->enable() method.
913 * This *SHOULD NOT* be called directly! Please use the
914 * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
917 void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
922 * Default clocksources are *special* and self-define their mult/shift.
923 * But, you're not special, so you should specify a freq value.
927 * Calc the maximum number of seconds which we can run before
928 * wrapping around. For clocksources which have a mask > 32-bit
929 * we need to limit the max sleep time to have a good
930 * conversion precision. 10 minutes is still a reasonable
931 * amount. That results in a shift value of 24 for a
932 * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
933 * ~ 0.06ppm granularity for NTP.
940 else if (sec > 600 && cs->mask > UINT_MAX)
943 clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
944 NSEC_PER_SEC / scale, sec * scale);
947 * Ensure clocksources that have large 'mult' values don't overflow
950 cs->maxadj = clocksource_max_adjustment(cs);
951 while (freq && ((cs->mult + cs->maxadj < cs->mult)
952 || (cs->mult - cs->maxadj > cs->mult))) {
955 cs->maxadj = clocksource_max_adjustment(cs);
959 * Only warn for *special* clocksources that self-define
960 * their mult/shift values and don't specify a freq.
962 WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
963 "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
966 clocksource_update_max_deferment(cs);
968 pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
969 cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
971 EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
974 * __clocksource_register_scale - Used to install new clocksources
975 * @cs: clocksource to be registered
976 * @scale: Scale factor multiplied against freq to get clocksource hz
977 * @freq: clocksource frequency (cycles per second) divided by scale
979 * Returns -EBUSY if registration fails, zero otherwise.
981 * This *SHOULD NOT* be called directly! Please use the
982 * clocksource_register_hz() or clocksource_register_khz helper functions.
984 int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
988 /* Initialize mult/shift and max_idle_ns */
989 __clocksource_update_freq_scale(cs, scale, freq);
991 /* Add clocksource to the clocksource list */
992 mutex_lock(&clocksource_mutex);
994 clocksource_watchdog_lock(&flags);
995 clocksource_enqueue(cs);
996 clocksource_enqueue_watchdog(cs);
997 clocksource_watchdog_unlock(&flags);
999 clocksource_select();
1000 clocksource_select_watchdog(false);
1001 __clocksource_suspend_select(cs);
1002 mutex_unlock(&clocksource_mutex);
1005 EXPORT_SYMBOL_GPL(__clocksource_register_scale);
1007 static void __clocksource_change_rating(struct clocksource *cs, int rating)
1009 list_del(&cs->list);
1010 cs->rating = rating;
1011 clocksource_enqueue(cs);
1015 * clocksource_change_rating - Change the rating of a registered clocksource
1016 * @cs: clocksource to be changed
1017 * @rating: new rating
1019 void clocksource_change_rating(struct clocksource *cs, int rating)
1021 unsigned long flags;
1023 mutex_lock(&clocksource_mutex);
1024 clocksource_watchdog_lock(&flags);
1025 __clocksource_change_rating(cs, rating);
1026 clocksource_watchdog_unlock(&flags);
1028 clocksource_select();
1029 clocksource_select_watchdog(false);
1030 clocksource_suspend_select(false);
1031 mutex_unlock(&clocksource_mutex);
1033 EXPORT_SYMBOL(clocksource_change_rating);
1036 * Unbind clocksource @cs. Called with clocksource_mutex held
1038 static int clocksource_unbind(struct clocksource *cs)
1040 unsigned long flags;
1042 if (clocksource_is_watchdog(cs)) {
1043 /* Select and try to install a replacement watchdog. */
1044 clocksource_select_watchdog(true);
1045 if (clocksource_is_watchdog(cs))
1049 if (cs == curr_clocksource) {
1050 /* Select and try to install a replacement clock source */
1051 clocksource_select_fallback();
1052 if (curr_clocksource == cs)
1056 if (clocksource_is_suspend(cs)) {
1058 * Select and try to install a replacement suspend clocksource.
1059 * If no replacement suspend clocksource, we will just let the
1060 * clocksource go and have no suspend clocksource.
1062 clocksource_suspend_select(true);
1065 clocksource_watchdog_lock(&flags);
1066 clocksource_dequeue_watchdog(cs);
1067 list_del_init(&cs->list);
1068 clocksource_watchdog_unlock(&flags);
1074 * clocksource_unregister - remove a registered clocksource
1075 * @cs: clocksource to be unregistered
1077 int clocksource_unregister(struct clocksource *cs)
1081 mutex_lock(&clocksource_mutex);
1082 if (!list_empty(&cs->list))
1083 ret = clocksource_unbind(cs);
1084 mutex_unlock(&clocksource_mutex);
1087 EXPORT_SYMBOL(clocksource_unregister);
1091 * current_clocksource_show - sysfs interface for current clocksource
1094 * @buf: char buffer to be filled with clocksource list
1096 * Provides sysfs interface for listing current clocksource.
1098 static ssize_t current_clocksource_show(struct device *dev,
1099 struct device_attribute *attr,
1104 mutex_lock(&clocksource_mutex);
1105 count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
1106 mutex_unlock(&clocksource_mutex);
1111 ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
1115 /* strings from sysfs write are not 0 terminated! */
1116 if (!cnt || cnt >= CS_NAME_LEN)
1120 if (buf[cnt-1] == '\n')
1123 memcpy(dst, buf, cnt);
1129 * current_clocksource_store - interface for manually overriding clocksource
1132 * @buf: name of override clocksource
1133 * @count: length of buffer
1135 * Takes input from sysfs interface for manually overriding the default
1136 * clocksource selection.
1138 static ssize_t current_clocksource_store(struct device *dev,
1139 struct device_attribute *attr,
1140 const char *buf, size_t count)
1144 mutex_lock(&clocksource_mutex);
1146 ret = sysfs_get_uname(buf, override_name, count);
1148 clocksource_select();
1150 mutex_unlock(&clocksource_mutex);
1154 static DEVICE_ATTR_RW(current_clocksource);
1157 * unbind_clocksource_store - interface for manually unbinding clocksource
1161 * @count: length of buffer
1163 * Takes input from sysfs interface for manually unbinding a clocksource.
1165 static ssize_t unbind_clocksource_store(struct device *dev,
1166 struct device_attribute *attr,
1167 const char *buf, size_t count)
1169 struct clocksource *cs;
1170 char name[CS_NAME_LEN];
1173 ret = sysfs_get_uname(buf, name, count);
1178 mutex_lock(&clocksource_mutex);
1179 list_for_each_entry(cs, &clocksource_list, list) {
1180 if (strcmp(cs->name, name))
1182 ret = clocksource_unbind(cs);
1185 mutex_unlock(&clocksource_mutex);
1187 return ret ? ret : count;
1189 static DEVICE_ATTR_WO(unbind_clocksource);
1192 * available_clocksource_show - sysfs interface for listing clocksource
1195 * @buf: char buffer to be filled with clocksource list
1197 * Provides sysfs interface for listing registered clocksources
1199 static ssize_t available_clocksource_show(struct device *dev,
1200 struct device_attribute *attr,
1203 struct clocksource *src;
1206 mutex_lock(&clocksource_mutex);
1207 list_for_each_entry(src, &clocksource_list, list) {
1209 * Don't show non-HRES clocksource if the tick code is
1210 * in one shot mode (highres=on or nohz=on)
1212 if (!tick_oneshot_mode_active() ||
1213 (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
1214 count += snprintf(buf + count,
1215 max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
1218 mutex_unlock(&clocksource_mutex);
1220 count += snprintf(buf + count,
1221 max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1225 static DEVICE_ATTR_RO(available_clocksource);
1227 static struct attribute *clocksource_attrs[] = {
1228 &dev_attr_current_clocksource.attr,
1229 &dev_attr_unbind_clocksource.attr,
1230 &dev_attr_available_clocksource.attr,
1233 ATTRIBUTE_GROUPS(clocksource);
1235 static struct bus_type clocksource_subsys = {
1236 .name = "clocksource",
1237 .dev_name = "clocksource",
1240 static struct device device_clocksource = {
1242 .bus = &clocksource_subsys,
1243 .groups = clocksource_groups,
1246 static int __init init_clocksource_sysfs(void)
1248 int error = subsys_system_register(&clocksource_subsys, NULL);
1251 error = device_register(&device_clocksource);
1256 device_initcall(init_clocksource_sysfs);
1257 #endif /* CONFIG_SYSFS */
1260 * boot_override_clocksource - boot clock override
1261 * @str: override name
1263 * Takes a clocksource= boot argument and uses it
1264 * as the clocksource override name.
1266 static int __init boot_override_clocksource(char* str)
1268 mutex_lock(&clocksource_mutex);
1270 strlcpy(override_name, str, sizeof(override_name));
1271 mutex_unlock(&clocksource_mutex);
1275 __setup("clocksource=", boot_override_clocksource);
1278 * boot_override_clock - Compatibility layer for deprecated boot option
1279 * @str: override name
1281 * DEPRECATED! Takes a clock= boot argument and uses it
1282 * as the clocksource override name
1284 static int __init boot_override_clock(char* str)
1286 if (!strcmp(str, "pmtmr")) {
1287 pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
1288 return boot_override_clocksource("acpi_pm");
1290 pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1291 return boot_override_clocksource(str);
1294 __setup("clock=", boot_override_clock);