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