GNU Linux-libre 4.19.207-gnu1
[releases.git] / kernel / time / clocksource.c
1 /*
2  * linux/kernel/time/clocksource.c
3  *
4  * This file contains the functions which manage clocksource drivers.
5  *
6  * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
7  *
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.
12  *
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.
17  *
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.
21  *
22  * TODO WishList:
23  *   o Allow clocksource drivers to be unregistered
24  */
25
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27
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>
35
36 #include "tick-internal.h"
37 #include "timekeeping_internal.h"
38
39 /**
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
46  *
47  * The function evaluates the shift/mult pair for the scaled math
48  * operations of clocksources and clockevents.
49  *
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.
53  *
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
60  * factors.
61  */
62 void
63 clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
64 {
65         u64 tmp;
66         u32 sft, sftacc= 32;
67
68         /*
69          * Calculate the shift factor which is limiting the conversion
70          * range:
71          */
72         tmp = ((u64)maxsec * from) >> 32;
73         while (tmp) {
74                 tmp >>=1;
75                 sftacc--;
76         }
77
78         /*
79          * Find the conversion shift/mult pair which has the best
80          * accuracy and fits the maxsec conversion range:
81          */
82         for (sft = 32; sft > 0; sft--) {
83                 tmp = (u64) to << sft;
84                 tmp += from / 2;
85                 do_div(tmp, from);
86                 if ((tmp >> sftacc) == 0)
87                         break;
88         }
89         *mult = tmp;
90         *shift = sft;
91 }
92 EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
93
94 /*[Clocksource internal variables]---------
95  * curr_clocksource:
96  *      currently selected clocksource.
97  * suspend_clocksource:
98  *      used to calculate the suspend time.
99  * clocksource_list:
100  *      linked list with the registered clocksources
101  * clocksource_mutex:
102  *      protects manipulations to curr_clocksource and the clocksource_list
103  * override_name:
104  *      Name of the user-specified clocksource.
105  */
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;
113
114 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
115 static void clocksource_watchdog_work(struct work_struct *work);
116 static void clocksource_select(void);
117
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;
125
126 static void inline clocksource_watchdog_lock(unsigned long *flags)
127 {
128         spin_lock_irqsave(&watchdog_lock, *flags);
129 }
130
131 static void inline clocksource_watchdog_unlock(unsigned long *flags)
132 {
133         spin_unlock_irqrestore(&watchdog_lock, *flags);
134 }
135
136 static int clocksource_watchdog_kthread(void *data);
137 static void __clocksource_change_rating(struct clocksource *cs, int rating);
138
139 /*
140  * Interval: 0.5sec Threshold: 0.0625s
141  */
142 #define WATCHDOG_INTERVAL (HZ >> 1)
143 #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 4)
144
145 /*
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.
149  */
150 #define WATCHDOG_MAX_SKEW (100 * NSEC_PER_USEC)
151
152 static void clocksource_watchdog_work(struct work_struct *work)
153 {
154         /*
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.
159          *
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
162          * kthread for this.
163          *
164          * If kthread_run fails the next watchdog scan over the
165          * watchdog_list will find the unstable clock again.
166          */
167         kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
168 }
169
170 static void __clocksource_unstable(struct clocksource *cs)
171 {
172         cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
173         cs->flags |= CLOCK_SOURCE_UNSTABLE;
174
175         /*
176          * If the clocksource is registered clocksource_watchdog_kthread() will
177          * re-rate and re-select.
178          */
179         if (list_empty(&cs->list)) {
180                 cs->rating = 0;
181                 return;
182         }
183
184         if (cs->mark_unstable)
185                 cs->mark_unstable(cs);
186
187         /* kick clocksource_watchdog_kthread() */
188         if (finished_booting)
189                 schedule_work(&watchdog_work);
190 }
191
192 /**
193  * clocksource_mark_unstable - mark clocksource unstable via watchdog
194  * @cs:         clocksource to be marked unstable
195  *
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.
198  */
199 void clocksource_mark_unstable(struct clocksource *cs)
200 {
201         unsigned long flags;
202
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);
208         }
209         spin_unlock_irqrestore(&watchdog_lock, flags);
210 }
211
212 static ulong max_cswd_read_retries = 3;
213 module_param(max_cswd_read_retries, ulong, 0644);
214
215 static bool cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
216 {
217         unsigned int nretries;
218         u64 wd_end, wd_delta;
219         int64_t wd_delay;
220
221         for (nretries = 0; nretries <= max_cswd_read_retries; nretries++) {
222                 local_irq_disable();
223                 *wdnow = watchdog->read(watchdog);
224                 *csnow = cs->read(cs);
225                 wd_end = watchdog->read(watchdog);
226                 local_irq_enable();
227
228                 wd_delta = clocksource_delta(wd_end, *wdnow, watchdog->mask);
229                 wd_delay = clocksource_cyc2ns(wd_delta, watchdog->mult,
230                                               watchdog->shift);
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);
235                         }
236                         return true;
237                 }
238         }
239
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);
242         return false;
243 }
244
245 static void clocksource_watchdog(struct timer_list *unused)
246 {
247         u64 csnow, wdnow, cslast, wdlast, delta;
248         int next_cpu, reset_pending;
249         int64_t wd_nsec, cs_nsec;
250         struct clocksource *cs;
251
252         spin_lock(&watchdog_lock);
253         if (!watchdog_running)
254                 goto out;
255
256         reset_pending = atomic_read(&watchdog_reset_pending);
257
258         list_for_each_entry(cs, &watchdog_list, wd_list) {
259
260                 /* Clocksource already marked unstable? */
261                 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
262                         if (finished_booting)
263                                 schedule_work(&watchdog_work);
264                         continue;
265                 }
266
267                 if (!cs_watchdog_read(cs, &csnow, &wdnow)) {
268                         /* Clock readout unreliable, so give it up. */
269                         __clocksource_unstable(cs);
270                         continue;
271                 }
272
273                 /* Clocksource initialized ? */
274                 if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
275                     atomic_read(&watchdog_reset_pending)) {
276                         cs->flags |= CLOCK_SOURCE_WATCHDOG;
277                         cs->wd_last = wdnow;
278                         cs->cs_last = csnow;
279                         continue;
280                 }
281
282                 delta = clocksource_delta(wdnow, cs->wd_last, watchdog->mask);
283                 wd_nsec = clocksource_cyc2ns(delta, watchdog->mult,
284                                              watchdog->shift);
285
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;
290                 cs->cs_last = csnow;
291                 cs->wd_last = wdnow;
292
293                 if (atomic_read(&watchdog_reset_pending))
294                         continue;
295
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);
305                         continue;
306                 }
307
308                 if (cs == curr_clocksource && cs->tick_stable)
309                         cs->tick_stable(cs);
310
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;
316
317                         /*
318                          * clocksource_done_booting() will sort it if
319                          * finished_booting is not set yet.
320                          */
321                         if (!finished_booting)
322                                 continue;
323
324                         /*
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
330                          * that change.
331                          */
332                         if (cs != curr_clocksource) {
333                                 cs->flags |= CLOCK_SOURCE_RESELECT;
334                                 schedule_work(&watchdog_work);
335                         } else {
336                                 tick_clock_notify();
337                         }
338                 }
339         }
340
341         /*
342          * We only clear the watchdog_reset_pending, when we did a
343          * full cycle through all clocksources.
344          */
345         if (reset_pending)
346                 atomic_dec(&watchdog_reset_pending);
347
348         /*
349          * Cycle through CPUs to check if the CPUs stay synchronized
350          * to each other.
351          */
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);
355
356         /*
357          * Arm timer if not already pending: could race with concurrent
358          * pair clocksource_stop_watchdog() clocksource_start_watchdog().
359          */
360         if (!timer_pending(&watchdog_timer)) {
361                 watchdog_timer.expires += WATCHDOG_INTERVAL;
362                 add_timer_on(&watchdog_timer, next_cpu);
363         }
364 out:
365         spin_unlock(&watchdog_lock);
366 }
367
368 static inline void clocksource_start_watchdog(void)
369 {
370         if (watchdog_running || !watchdog || list_empty(&watchdog_list))
371                 return;
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;
376 }
377
378 static inline void clocksource_stop_watchdog(void)
379 {
380         if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
381                 return;
382         del_timer(&watchdog_timer);
383         watchdog_running = 0;
384 }
385
386 static inline void clocksource_reset_watchdog(void)
387 {
388         struct clocksource *cs;
389
390         list_for_each_entry(cs, &watchdog_list, wd_list)
391                 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
392 }
393
394 static void clocksource_resume_watchdog(void)
395 {
396         atomic_inc(&watchdog_reset_pending);
397 }
398
399 static void clocksource_enqueue_watchdog(struct clocksource *cs)
400 {
401         INIT_LIST_HEAD(&cs->wd_list);
402
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;
407         } else {
408                 /* cs is a watchdog. */
409                 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
410                         cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
411         }
412 }
413
414 static void clocksource_select_watchdog(bool fallback)
415 {
416         struct clocksource *cs, *old_wd;
417         unsigned long flags;
418
419         spin_lock_irqsave(&watchdog_lock, flags);
420         /* save current watchdog */
421         old_wd = watchdog;
422         if (fallback)
423                 watchdog = NULL;
424
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)
428                         continue;
429
430                 /* Skip current if we were requested for a fallback. */
431                 if (fallback && cs == old_wd)
432                         continue;
433
434                 /* Pick the best watchdog. */
435                 if (!watchdog || cs->rating > watchdog->rating)
436                         watchdog = cs;
437         }
438         /* If we failed to find a fallback restore the old one. */
439         if (!watchdog)
440                 watchdog = old_wd;
441
442         /* If we changed the watchdog we need to reset cycles. */
443         if (watchdog != old_wd)
444                 clocksource_reset_watchdog();
445
446         /* Check if the watchdog timer needs to be started. */
447         clocksource_start_watchdog();
448         spin_unlock_irqrestore(&watchdog_lock, flags);
449 }
450
451 static void clocksource_dequeue_watchdog(struct clocksource *cs)
452 {
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();
459                 }
460         }
461 }
462
463 static int __clocksource_watchdog_kthread(void)
464 {
465         struct clocksource *cs, *tmp;
466         unsigned long flags;
467         int select = 0;
468
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);
474                         select = 1;
475                 }
476                 if (cs->flags & CLOCK_SOURCE_RESELECT) {
477                         cs->flags &= ~CLOCK_SOURCE_RESELECT;
478                         select = 1;
479                 }
480         }
481         /* Check if the watchdog timer needs to be stopped. */
482         clocksource_stop_watchdog();
483         spin_unlock_irqrestore(&watchdog_lock, flags);
484
485         return select;
486 }
487
488 static int clocksource_watchdog_kthread(void *data)
489 {
490         mutex_lock(&clocksource_mutex);
491         if (__clocksource_watchdog_kthread())
492                 clocksource_select();
493         mutex_unlock(&clocksource_mutex);
494         return 0;
495 }
496
497 static bool clocksource_is_watchdog(struct clocksource *cs)
498 {
499         return cs == watchdog;
500 }
501
502 #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
503
504 static void clocksource_enqueue_watchdog(struct clocksource *cs)
505 {
506         if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
507                 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
508 }
509
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) { }
516
517 static inline void clocksource_watchdog_lock(unsigned long *flags) { }
518 static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
519
520 #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
521
522 static bool clocksource_is_suspend(struct clocksource *cs)
523 {
524         return cs == suspend_clocksource;
525 }
526
527 static void __clocksource_suspend_select(struct clocksource *cs)
528 {
529         /*
530          * Skip the clocksource which will be stopped in suspend state.
531          */
532         if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
533                 return;
534
535         /*
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.
539          */
540         if (cs->suspend || cs->resume) {
541                 pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
542                         cs->name);
543         }
544
545         /* Pick the best rating. */
546         if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
547                 suspend_clocksource = cs;
548 }
549
550 /**
551  * clocksource_suspend_select - Select the best clocksource for suspend timing
552  * @fallback:   if select a fallback clocksource
553  */
554 static void clocksource_suspend_select(bool fallback)
555 {
556         struct clocksource *cs, *old_suspend;
557
558         old_suspend = suspend_clocksource;
559         if (fallback)
560                 suspend_clocksource = NULL;
561
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)
565                         continue;
566
567                 __clocksource_suspend_select(cs);
568         }
569 }
570
571 /**
572  * clocksource_start_suspend_timing - Start measuring the suspend timing
573  * @cs:                 current clocksource from timekeeping
574  * @start_cycles:       current cycles from timekeeping
575  *
576  * This function will save the start cycle values of suspend timer to calculate
577  * the suspend time when resuming system.
578  *
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
582  * clocksource mutex.
583  */
584 void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
585 {
586         if (!suspend_clocksource)
587                 return;
588
589         /*
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.
593          */
594         if (clocksource_is_suspend(cs)) {
595                 suspend_start = start_cycles;
596                 return;
597         }
598
599         if (suspend_clocksource->enable &&
600             suspend_clocksource->enable(suspend_clocksource)) {
601                 pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
602                 return;
603         }
604
605         suspend_start = suspend_clocksource->read(suspend_clocksource);
606 }
607
608 /**
609  * clocksource_stop_suspend_timing - Stop measuring the suspend timing
610  * @cs:         current clocksource from timekeeping
611  * @cycle_now:  current cycles from timekeeping
612  *
613  * This function will calculate the suspend time from suspend timer.
614  *
615  * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
616  *
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.
621  */
622 u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
623 {
624         u64 now, delta, nsec = 0;
625
626         if (!suspend_clocksource)
627                 return 0;
628
629         /*
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.
633          */
634         if (clocksource_is_suspend(cs))
635                 now = cycle_now;
636         else
637                 now = suspend_clocksource->read(suspend_clocksource);
638
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);
644         }
645
646         /*
647          * Disable the suspend timer to save power if current clocksource is
648          * not the suspend timer.
649          */
650         if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
651                 suspend_clocksource->disable(suspend_clocksource);
652
653         return nsec;
654 }
655
656 /**
657  * clocksource_suspend - suspend the clocksource(s)
658  */
659 void clocksource_suspend(void)
660 {
661         struct clocksource *cs;
662
663         list_for_each_entry_reverse(cs, &clocksource_list, list)
664                 if (cs->suspend)
665                         cs->suspend(cs);
666 }
667
668 /**
669  * clocksource_resume - resume the clocksource(s)
670  */
671 void clocksource_resume(void)
672 {
673         struct clocksource *cs;
674
675         list_for_each_entry(cs, &clocksource_list, list)
676                 if (cs->resume)
677                         cs->resume(cs);
678
679         clocksource_resume_watchdog();
680 }
681
682 /**
683  * clocksource_touch_watchdog - Update watchdog
684  *
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.
688  */
689 void clocksource_touch_watchdog(void)
690 {
691         clocksource_resume_watchdog();
692 }
693
694 /**
695  * clocksource_max_adjustment- Returns max adjustment amount
696  * @cs:         Pointer to clocksource
697  *
698  */
699 static u32 clocksource_max_adjustment(struct clocksource *cs)
700 {
701         u64 ret;
702         /*
703          * We won't try to correct for more than 11% adjustments (110,000 ppm),
704          */
705         ret = (u64)cs->mult * 11;
706         do_div(ret,100);
707         return (u32)ret;
708 }
709
710 /**
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
717  *              any safety margin)
718  *
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.
724  */
725 u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
726 {
727         u64 max_nsecs, max_cycles;
728
729         /*
730          * Calculate the maximum number of cycles that we can pass to the
731          * cyc2ns() function without overflowing a 64-bit result.
732          */
733         max_cycles = ULLONG_MAX;
734         do_div(max_cycles, mult+maxadj);
735
736         /*
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.
741          */
742         max_cycles = min(max_cycles, mask);
743         max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
744
745         /* return the max_cycles value as well if requested */
746         if (max_cyc)
747                 *max_cyc = max_cycles;
748
749         /* Return 50% of the actual maximum, so we can detect bad values */
750         max_nsecs >>= 1;
751
752         return max_nsecs;
753 }
754
755 /**
756  * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
757  * @cs:         Pointer to clocksource to be updated
758  *
759  */
760 static inline void clocksource_update_max_deferment(struct clocksource *cs)
761 {
762         cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
763                                                 cs->maxadj, cs->mask,
764                                                 &cs->max_cycles);
765 }
766
767 #ifndef CONFIG_ARCH_USES_GETTIMEOFFSET
768
769 static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
770 {
771         struct clocksource *cs;
772
773         if (!finished_booting || list_empty(&clocksource_list))
774                 return NULL;
775
776         /*
777          * We pick the clocksource with the highest rating. If oneshot
778          * mode is active, we pick the highres valid clocksource with
779          * the best rating.
780          */
781         list_for_each_entry(cs, &clocksource_list, list) {
782                 if (skipcur && cs == curr_clocksource)
783                         continue;
784                 if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
785                         continue;
786                 return cs;
787         }
788         return NULL;
789 }
790
791 static void __clocksource_select(bool skipcur)
792 {
793         bool oneshot = tick_oneshot_mode_active();
794         struct clocksource *best, *cs;
795
796         /* Find the best suitable clocksource */
797         best = clocksource_find_best(oneshot, skipcur);
798         if (!best)
799                 return;
800
801         if (!strlen(override_name))
802                 goto found;
803
804         /* Check for the override clocksource. */
805         list_for_each_entry(cs, &clocksource_list, list) {
806                 if (skipcur && cs == curr_clocksource)
807                         continue;
808                 if (strcmp(cs->name, override_name) != 0)
809                         continue;
810                 /*
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)
814                  */
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",
819                                         cs->name);
820                                 override_name[0] = 0;
821                         } else {
822                                 /*
823                                  * The override cannot be currently verified.
824                                  * Deferring to let the watchdog check.
825                                  */
826                                 pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
827                                         cs->name);
828                         }
829                 } else
830                         /* Override clocksource can be used. */
831                         best = cs;
832                 break;
833         }
834
835 found:
836         if (curr_clocksource != best && !timekeeping_notify(best)) {
837                 pr_info("Switched to clocksource %s\n", best->name);
838                 curr_clocksource = best;
839         }
840 }
841
842 /**
843  * clocksource_select - Select the best clocksource available
844  *
845  * Private function. Must hold clocksource_mutex when called.
846  *
847  * Select the clocksource with the best rating, or the clocksource,
848  * which is selected by userspace override.
849  */
850 static void clocksource_select(void)
851 {
852         __clocksource_select(false);
853 }
854
855 static void clocksource_select_fallback(void)
856 {
857         __clocksource_select(true);
858 }
859
860 #else /* !CONFIG_ARCH_USES_GETTIMEOFFSET */
861 static inline void clocksource_select(void) { }
862 static inline void clocksource_select_fallback(void) { }
863
864 #endif
865
866 /*
867  * clocksource_done_booting - Called near the end of core bootup
868  *
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.
872  */
873 static int __init clocksource_done_booting(void)
874 {
875         mutex_lock(&clocksource_mutex);
876         curr_clocksource = clocksource_default_clock();
877         finished_booting = 1;
878         /*
879          * Run the watchdog first to eliminate unstable clock sources
880          */
881         __clocksource_watchdog_kthread();
882         clocksource_select();
883         mutex_unlock(&clocksource_mutex);
884         return 0;
885 }
886 fs_initcall(clocksource_done_booting);
887
888 /*
889  * Enqueue the clocksource sorted by rating
890  */
891 static void clocksource_enqueue(struct clocksource *cs)
892 {
893         struct list_head *entry = &clocksource_list;
894         struct clocksource *tmp;
895
896         list_for_each_entry(tmp, &clocksource_list, list) {
897                 /* Keep track of the place, where to insert */
898                 if (tmp->rating < cs->rating)
899                         break;
900                 entry = &tmp->list;
901         }
902         list_add(&cs->list, entry);
903 }
904
905 /**
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
910  *
911  * This should only be called from the clocksource->enable() method.
912  *
913  * This *SHOULD NOT* be called directly! Please use the
914  * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
915  * functions.
916  */
917 void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
918 {
919         u64 sec;
920
921         /*
922          * Default clocksources are *special* and self-define their mult/shift.
923          * But, you're not special, so you should specify a freq value.
924          */
925         if (freq) {
926                 /*
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.
934                  */
935                 sec = cs->mask;
936                 do_div(sec, freq);
937                 do_div(sec, scale);
938                 if (!sec)
939                         sec = 1;
940                 else if (sec > 600 && cs->mask > UINT_MAX)
941                         sec = 600;
942
943                 clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
944                                        NSEC_PER_SEC / scale, sec * scale);
945         }
946         /*
947          * Ensure clocksources that have large 'mult' values don't overflow
948          * when adjusted.
949          */
950         cs->maxadj = clocksource_max_adjustment(cs);
951         while (freq && ((cs->mult + cs->maxadj < cs->mult)
952                 || (cs->mult - cs->maxadj > cs->mult))) {
953                 cs->mult >>= 1;
954                 cs->shift--;
955                 cs->maxadj = clocksource_max_adjustment(cs);
956         }
957
958         /*
959          * Only warn for *special* clocksources that self-define
960          * their mult/shift values and don't specify a freq.
961          */
962         WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
963                 "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
964                 cs->name);
965
966         clocksource_update_max_deferment(cs);
967
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);
970 }
971 EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
972
973 /**
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
978  *
979  * Returns -EBUSY if registration fails, zero otherwise.
980  *
981  * This *SHOULD NOT* be called directly! Please use the
982  * clocksource_register_hz() or clocksource_register_khz helper functions.
983  */
984 int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
985 {
986         unsigned long flags;
987
988         /* Initialize mult/shift and max_idle_ns */
989         __clocksource_update_freq_scale(cs, scale, freq);
990
991         /* Add clocksource to the clocksource list */
992         mutex_lock(&clocksource_mutex);
993
994         clocksource_watchdog_lock(&flags);
995         clocksource_enqueue(cs);
996         clocksource_enqueue_watchdog(cs);
997         clocksource_watchdog_unlock(&flags);
998
999         clocksource_select();
1000         clocksource_select_watchdog(false);
1001         __clocksource_suspend_select(cs);
1002         mutex_unlock(&clocksource_mutex);
1003         return 0;
1004 }
1005 EXPORT_SYMBOL_GPL(__clocksource_register_scale);
1006
1007 static void __clocksource_change_rating(struct clocksource *cs, int rating)
1008 {
1009         list_del(&cs->list);
1010         cs->rating = rating;
1011         clocksource_enqueue(cs);
1012 }
1013
1014 /**
1015  * clocksource_change_rating - Change the rating of a registered clocksource
1016  * @cs:         clocksource to be changed
1017  * @rating:     new rating
1018  */
1019 void clocksource_change_rating(struct clocksource *cs, int rating)
1020 {
1021         unsigned long flags;
1022
1023         mutex_lock(&clocksource_mutex);
1024         clocksource_watchdog_lock(&flags);
1025         __clocksource_change_rating(cs, rating);
1026         clocksource_watchdog_unlock(&flags);
1027
1028         clocksource_select();
1029         clocksource_select_watchdog(false);
1030         clocksource_suspend_select(false);
1031         mutex_unlock(&clocksource_mutex);
1032 }
1033 EXPORT_SYMBOL(clocksource_change_rating);
1034
1035 /*
1036  * Unbind clocksource @cs. Called with clocksource_mutex held
1037  */
1038 static int clocksource_unbind(struct clocksource *cs)
1039 {
1040         unsigned long flags;
1041
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))
1046                         return -EBUSY;
1047         }
1048
1049         if (cs == curr_clocksource) {
1050                 /* Select and try to install a replacement clock source */
1051                 clocksource_select_fallback();
1052                 if (curr_clocksource == cs)
1053                         return -EBUSY;
1054         }
1055
1056         if (clocksource_is_suspend(cs)) {
1057                 /*
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.
1061                  */
1062                 clocksource_suspend_select(true);
1063         }
1064
1065         clocksource_watchdog_lock(&flags);
1066         clocksource_dequeue_watchdog(cs);
1067         list_del_init(&cs->list);
1068         clocksource_watchdog_unlock(&flags);
1069
1070         return 0;
1071 }
1072
1073 /**
1074  * clocksource_unregister - remove a registered clocksource
1075  * @cs: clocksource to be unregistered
1076  */
1077 int clocksource_unregister(struct clocksource *cs)
1078 {
1079         int ret = 0;
1080
1081         mutex_lock(&clocksource_mutex);
1082         if (!list_empty(&cs->list))
1083                 ret = clocksource_unbind(cs);
1084         mutex_unlock(&clocksource_mutex);
1085         return ret;
1086 }
1087 EXPORT_SYMBOL(clocksource_unregister);
1088
1089 #ifdef CONFIG_SYSFS
1090 /**
1091  * current_clocksource_show - sysfs interface for current clocksource
1092  * @dev:        unused
1093  * @attr:       unused
1094  * @buf:        char buffer to be filled with clocksource list
1095  *
1096  * Provides sysfs interface for listing current clocksource.
1097  */
1098 static ssize_t current_clocksource_show(struct device *dev,
1099                                         struct device_attribute *attr,
1100                                         char *buf)
1101 {
1102         ssize_t count = 0;
1103
1104         mutex_lock(&clocksource_mutex);
1105         count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
1106         mutex_unlock(&clocksource_mutex);
1107
1108         return count;
1109 }
1110
1111 ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
1112 {
1113         size_t ret = cnt;
1114
1115         /* strings from sysfs write are not 0 terminated! */
1116         if (!cnt || cnt >= CS_NAME_LEN)
1117                 return -EINVAL;
1118
1119         /* strip of \n: */
1120         if (buf[cnt-1] == '\n')
1121                 cnt--;
1122         if (cnt > 0)
1123                 memcpy(dst, buf, cnt);
1124         dst[cnt] = 0;
1125         return ret;
1126 }
1127
1128 /**
1129  * current_clocksource_store - interface for manually overriding clocksource
1130  * @dev:        unused
1131  * @attr:       unused
1132  * @buf:        name of override clocksource
1133  * @count:      length of buffer
1134  *
1135  * Takes input from sysfs interface for manually overriding the default
1136  * clocksource selection.
1137  */
1138 static ssize_t current_clocksource_store(struct device *dev,
1139                                          struct device_attribute *attr,
1140                                          const char *buf, size_t count)
1141 {
1142         ssize_t ret;
1143
1144         mutex_lock(&clocksource_mutex);
1145
1146         ret = sysfs_get_uname(buf, override_name, count);
1147         if (ret >= 0)
1148                 clocksource_select();
1149
1150         mutex_unlock(&clocksource_mutex);
1151
1152         return ret;
1153 }
1154 static DEVICE_ATTR_RW(current_clocksource);
1155
1156 /**
1157  * unbind_clocksource_store - interface for manually unbinding clocksource
1158  * @dev:        unused
1159  * @attr:       unused
1160  * @buf:        unused
1161  * @count:      length of buffer
1162  *
1163  * Takes input from sysfs interface for manually unbinding a clocksource.
1164  */
1165 static ssize_t unbind_clocksource_store(struct device *dev,
1166                                         struct device_attribute *attr,
1167                                         const char *buf, size_t count)
1168 {
1169         struct clocksource *cs;
1170         char name[CS_NAME_LEN];
1171         ssize_t ret;
1172
1173         ret = sysfs_get_uname(buf, name, count);
1174         if (ret < 0)
1175                 return ret;
1176
1177         ret = -ENODEV;
1178         mutex_lock(&clocksource_mutex);
1179         list_for_each_entry(cs, &clocksource_list, list) {
1180                 if (strcmp(cs->name, name))
1181                         continue;
1182                 ret = clocksource_unbind(cs);
1183                 break;
1184         }
1185         mutex_unlock(&clocksource_mutex);
1186
1187         return ret ? ret : count;
1188 }
1189 static DEVICE_ATTR_WO(unbind_clocksource);
1190
1191 /**
1192  * available_clocksource_show - sysfs interface for listing clocksource
1193  * @dev:        unused
1194  * @attr:       unused
1195  * @buf:        char buffer to be filled with clocksource list
1196  *
1197  * Provides sysfs interface for listing registered clocksources
1198  */
1199 static ssize_t available_clocksource_show(struct device *dev,
1200                                           struct device_attribute *attr,
1201                                           char *buf)
1202 {
1203         struct clocksource *src;
1204         ssize_t count = 0;
1205
1206         mutex_lock(&clocksource_mutex);
1207         list_for_each_entry(src, &clocksource_list, list) {
1208                 /*
1209                  * Don't show non-HRES clocksource if the tick code is
1210                  * in one shot mode (highres=on or nohz=on)
1211                  */
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),
1216                                   "%s ", src->name);
1217         }
1218         mutex_unlock(&clocksource_mutex);
1219
1220         count += snprintf(buf + count,
1221                           max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1222
1223         return count;
1224 }
1225 static DEVICE_ATTR_RO(available_clocksource);
1226
1227 static struct attribute *clocksource_attrs[] = {
1228         &dev_attr_current_clocksource.attr,
1229         &dev_attr_unbind_clocksource.attr,
1230         &dev_attr_available_clocksource.attr,
1231         NULL
1232 };
1233 ATTRIBUTE_GROUPS(clocksource);
1234
1235 static struct bus_type clocksource_subsys = {
1236         .name = "clocksource",
1237         .dev_name = "clocksource",
1238 };
1239
1240 static struct device device_clocksource = {
1241         .id     = 0,
1242         .bus    = &clocksource_subsys,
1243         .groups = clocksource_groups,
1244 };
1245
1246 static int __init init_clocksource_sysfs(void)
1247 {
1248         int error = subsys_system_register(&clocksource_subsys, NULL);
1249
1250         if (!error)
1251                 error = device_register(&device_clocksource);
1252
1253         return error;
1254 }
1255
1256 device_initcall(init_clocksource_sysfs);
1257 #endif /* CONFIG_SYSFS */
1258
1259 /**
1260  * boot_override_clocksource - boot clock override
1261  * @str:        override name
1262  *
1263  * Takes a clocksource= boot argument and uses it
1264  * as the clocksource override name.
1265  */
1266 static int __init boot_override_clocksource(char* str)
1267 {
1268         mutex_lock(&clocksource_mutex);
1269         if (str)
1270                 strlcpy(override_name, str, sizeof(override_name));
1271         mutex_unlock(&clocksource_mutex);
1272         return 1;
1273 }
1274
1275 __setup("clocksource=", boot_override_clocksource);
1276
1277 /**
1278  * boot_override_clock - Compatibility layer for deprecated boot option
1279  * @str:        override name
1280  *
1281  * DEPRECATED! Takes a clock= boot argument and uses it
1282  * as the clocksource override name
1283  */
1284 static int __init boot_override_clock(char* str)
1285 {
1286         if (!strcmp(str, "pmtmr")) {
1287                 pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
1288                 return boot_override_clocksource("acpi_pm");
1289         }
1290         pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1291         return boot_override_clocksource(str);
1292 }
1293
1294 __setup("clock=", boot_override_clock);