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 #include <linux/prandom.h>
18 #include <linux/cpu.h>
19
20 #include "tick-internal.h"
21 #include "timekeeping_internal.h"
22
23 /**
24 * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
25 * @mult: pointer to mult variable
26 * @shift: pointer to shift variable
27 * @from: frequency to convert from
28 * @to: frequency to convert to
29 * @maxsec: guaranteed runtime conversion range in seconds
30 *
31 * The function evaluates the shift/mult pair for the scaled math
32 * operations of clocksources and clockevents.
33 *
34 * @to and @from are frequency values in HZ. For clock sources @to is
35 * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
36 * event @to is the counter frequency and @from is NSEC_PER_SEC.
37 *
38 * The @maxsec conversion range argument controls the time frame in
39 * seconds which must be covered by the runtime conversion with the
40 * calculated mult and shift factors. This guarantees that no 64bit
41 * overflow happens when the input value of the conversion is
42 * multiplied with the calculated mult factor. Larger ranges may
43 * reduce the conversion accuracy by choosing smaller mult and shift
44 * factors.
45 */
46 void
clocks_calc_mult_shift(u32 * mult,u32 * shift,u32 from,u32 to,u32 maxsec)47 clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
48 {
49 u64 tmp;
50 u32 sft, sftacc= 32;
51
52 /*
53 * Calculate the shift factor which is limiting the conversion
54 * range:
55 */
56 tmp = ((u64)maxsec * from) >> 32;
57 while (tmp) {
58 tmp >>=1;
59 sftacc--;
60 }
61
62 /*
63 * Find the conversion shift/mult pair which has the best
64 * accuracy and fits the maxsec conversion range:
65 */
66 for (sft = 32; sft > 0; sft--) {
67 tmp = (u64) to << sft;
68 tmp += from / 2;
69 do_div(tmp, from);
70 if ((tmp >> sftacc) == 0)
71 break;
72 }
73 *mult = tmp;
74 *shift = sft;
75 }
76 EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
77
78 /*[Clocksource internal variables]---------
79 * curr_clocksource:
80 * currently selected clocksource.
81 * suspend_clocksource:
82 * used to calculate the suspend time.
83 * clocksource_list:
84 * linked list with the registered clocksources
85 * clocksource_mutex:
86 * protects manipulations to curr_clocksource and the clocksource_list
87 * override_name:
88 * Name of the user-specified clocksource.
89 */
90 static struct clocksource *curr_clocksource;
91 static struct clocksource *suspend_clocksource;
92 static LIST_HEAD(clocksource_list);
93 static DEFINE_MUTEX(clocksource_mutex);
94 static char override_name[CS_NAME_LEN];
95 static int finished_booting;
96 static u64 suspend_start;
97
98 /*
99 * Threshold: 0.0312s, when doubled: 0.0625s.
100 * Also a default for cs->uncertainty_margin when registering clocks.
101 */
102 #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 5)
103
104 /*
105 * Maximum permissible delay between two readouts of the watchdog
106 * clocksource surrounding a read of the clocksource being validated.
107 * This delay could be due to SMIs, NMIs, or to VCPU preemptions. Used as
108 * a lower bound for cs->uncertainty_margin values when registering clocks.
109 */
110 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
111 #define MAX_SKEW_USEC CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
112 #else
113 #define MAX_SKEW_USEC 100
114 #endif
115
116 #define WATCHDOG_MAX_SKEW (MAX_SKEW_USEC * NSEC_PER_USEC)
117
118 #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
119 static void clocksource_watchdog_work(struct work_struct *work);
120 static void clocksource_select(void);
121
122 static LIST_HEAD(watchdog_list);
123 static struct clocksource *watchdog;
124 static struct timer_list watchdog_timer;
125 static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
126 static DEFINE_SPINLOCK(watchdog_lock);
127 static int watchdog_running;
128 static atomic_t watchdog_reset_pending;
129 static int64_t watchdog_max_interval;
130
clocksource_watchdog_lock(unsigned long * flags)131 static inline void clocksource_watchdog_lock(unsigned long *flags)
132 {
133 spin_lock_irqsave(&watchdog_lock, *flags);
134 }
135
clocksource_watchdog_unlock(unsigned long * flags)136 static inline void clocksource_watchdog_unlock(unsigned long *flags)
137 {
138 spin_unlock_irqrestore(&watchdog_lock, *flags);
139 }
140
141 static int clocksource_watchdog_kthread(void *data);
142 static void __clocksource_change_rating(struct clocksource *cs, int rating);
143
144 /*
145 * Interval: 0.5sec.
146 */
147 #define WATCHDOG_INTERVAL (HZ >> 1)
148 #define WATCHDOG_INTERVAL_MAX_NS ((2 * WATCHDOG_INTERVAL) * (NSEC_PER_SEC / HZ))
149
clocksource_watchdog_work(struct work_struct * work)150 static void clocksource_watchdog_work(struct work_struct *work)
151 {
152 /*
153 * We cannot directly run clocksource_watchdog_kthread() here, because
154 * clocksource_select() calls timekeeping_notify() which uses
155 * stop_machine(). One cannot use stop_machine() from a workqueue() due
156 * lock inversions wrt CPU hotplug.
157 *
158 * Also, we only ever run this work once or twice during the lifetime
159 * of the kernel, so there is no point in creating a more permanent
160 * kthread for this.
161 *
162 * If kthread_run fails the next watchdog scan over the
163 * watchdog_list will find the unstable clock again.
164 */
165 kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
166 }
167
__clocksource_unstable(struct clocksource * cs)168 static void __clocksource_unstable(struct clocksource *cs)
169 {
170 cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
171 cs->flags |= CLOCK_SOURCE_UNSTABLE;
172
173 /*
174 * If the clocksource is registered clocksource_watchdog_kthread() will
175 * re-rate and re-select.
176 */
177 if (list_empty(&cs->list)) {
178 cs->rating = 0;
179 return;
180 }
181
182 if (cs->mark_unstable)
183 cs->mark_unstable(cs);
184
185 /* kick clocksource_watchdog_kthread() */
186 if (finished_booting)
187 schedule_work(&watchdog_work);
188 }
189
190 /**
191 * clocksource_mark_unstable - mark clocksource unstable via watchdog
192 * @cs: clocksource to be marked unstable
193 *
194 * This function is called by the x86 TSC code to mark clocksources as unstable;
195 * it defers demotion and re-selection to a kthread.
196 */
clocksource_mark_unstable(struct clocksource * cs)197 void clocksource_mark_unstable(struct clocksource *cs)
198 {
199 unsigned long flags;
200
201 spin_lock_irqsave(&watchdog_lock, flags);
202 if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
203 if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
204 list_add(&cs->wd_list, &watchdog_list);
205 __clocksource_unstable(cs);
206 }
207 spin_unlock_irqrestore(&watchdog_lock, flags);
208 }
209
210 ulong max_cswd_read_retries = 2;
211 module_param(max_cswd_read_retries, ulong, 0644);
212 EXPORT_SYMBOL_GPL(max_cswd_read_retries);
213 static int verify_n_cpus = 8;
214 module_param(verify_n_cpus, int, 0644);
215
216 enum wd_read_status {
217 WD_READ_SUCCESS,
218 WD_READ_UNSTABLE,
219 WD_READ_SKIP
220 };
221
cs_watchdog_read(struct clocksource * cs,u64 * csnow,u64 * wdnow)222 static enum wd_read_status cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
223 {
224 unsigned int nretries;
225 u64 wd_end, wd_end2, wd_delta;
226 int64_t wd_delay, wd_seq_delay;
227
228 for (nretries = 0; nretries <= max_cswd_read_retries; nretries++) {
229 local_irq_disable();
230 *wdnow = watchdog->read(watchdog);
231 *csnow = cs->read(cs);
232 wd_end = watchdog->read(watchdog);
233 wd_end2 = watchdog->read(watchdog);
234 local_irq_enable();
235
236 wd_delta = clocksource_delta(wd_end, *wdnow, watchdog->mask);
237 wd_delay = clocksource_cyc2ns(wd_delta, watchdog->mult,
238 watchdog->shift);
239 if (wd_delay <= WATCHDOG_MAX_SKEW) {
240 if (nretries > 1 || nretries >= max_cswd_read_retries) {
241 pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
242 smp_processor_id(), watchdog->name, nretries);
243 }
244 return WD_READ_SUCCESS;
245 }
246
247 /*
248 * Now compute delay in consecutive watchdog read to see if
249 * there is too much external interferences that cause
250 * significant delay in reading both clocksource and watchdog.
251 *
252 * If consecutive WD read-back delay > WATCHDOG_MAX_SKEW/2,
253 * report system busy, reinit the watchdog and skip the current
254 * watchdog test.
255 */
256 wd_delta = clocksource_delta(wd_end2, wd_end, watchdog->mask);
257 wd_seq_delay = clocksource_cyc2ns(wd_delta, watchdog->mult, watchdog->shift);
258 if (wd_seq_delay > WATCHDOG_MAX_SKEW/2)
259 goto skip_test;
260 }
261
262 pr_warn("timekeeping watchdog on CPU%d: %s read-back delay of %lldns, attempt %d, marking unstable\n",
263 smp_processor_id(), watchdog->name, wd_delay, nretries);
264 return WD_READ_UNSTABLE;
265
266 skip_test:
267 pr_info("timekeeping watchdog on CPU%d: %s wd-wd read-back delay of %lldns\n",
268 smp_processor_id(), watchdog->name, wd_seq_delay);
269 pr_info("wd-%s-wd read-back delay of %lldns, clock-skew test skipped!\n",
270 cs->name, wd_delay);
271 return WD_READ_SKIP;
272 }
273
274 static u64 csnow_mid;
275 static cpumask_t cpus_ahead;
276 static cpumask_t cpus_behind;
277 static cpumask_t cpus_chosen;
278
clocksource_verify_choose_cpus(void)279 static void clocksource_verify_choose_cpus(void)
280 {
281 int cpu, i, n = verify_n_cpus;
282
283 if (n < 0) {
284 /* Check all of the CPUs. */
285 cpumask_copy(&cpus_chosen, cpu_online_mask);
286 cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
287 return;
288 }
289
290 /* If no checking desired, or no other CPU to check, leave. */
291 cpumask_clear(&cpus_chosen);
292 if (n == 0 || num_online_cpus() <= 1)
293 return;
294
295 /* Make sure to select at least one CPU other than the current CPU. */
296 cpu = cpumask_first(cpu_online_mask);
297 if (cpu == smp_processor_id())
298 cpu = cpumask_next(cpu, cpu_online_mask);
299 if (WARN_ON_ONCE(cpu >= nr_cpu_ids))
300 return;
301 cpumask_set_cpu(cpu, &cpus_chosen);
302
303 /* Force a sane value for the boot parameter. */
304 if (n > nr_cpu_ids)
305 n = nr_cpu_ids;
306
307 /*
308 * Randomly select the specified number of CPUs. If the same
309 * CPU is selected multiple times, that CPU is checked only once,
310 * and no replacement CPU is selected. This gracefully handles
311 * situations where verify_n_cpus is greater than the number of
312 * CPUs that are currently online.
313 */
314 for (i = 1; i < n; i++) {
315 cpu = prandom_u32_max(nr_cpu_ids);
316 cpu = cpumask_next(cpu - 1, cpu_online_mask);
317 if (cpu >= nr_cpu_ids)
318 cpu = cpumask_first(cpu_online_mask);
319 if (!WARN_ON_ONCE(cpu >= nr_cpu_ids))
320 cpumask_set_cpu(cpu, &cpus_chosen);
321 }
322
323 /* Don't verify ourselves. */
324 cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
325 }
326
clocksource_verify_one_cpu(void * csin)327 static void clocksource_verify_one_cpu(void *csin)
328 {
329 struct clocksource *cs = (struct clocksource *)csin;
330
331 csnow_mid = cs->read(cs);
332 }
333
clocksource_verify_percpu(struct clocksource * cs)334 void clocksource_verify_percpu(struct clocksource *cs)
335 {
336 int64_t cs_nsec, cs_nsec_max = 0, cs_nsec_min = LLONG_MAX;
337 u64 csnow_begin, csnow_end;
338 int cpu, testcpu;
339 s64 delta;
340
341 if (verify_n_cpus == 0)
342 return;
343 cpumask_clear(&cpus_ahead);
344 cpumask_clear(&cpus_behind);
345 cpus_read_lock();
346 preempt_disable();
347 clocksource_verify_choose_cpus();
348 if (cpumask_empty(&cpus_chosen)) {
349 preempt_enable();
350 cpus_read_unlock();
351 pr_warn("Not enough CPUs to check clocksource '%s'.\n", cs->name);
352 return;
353 }
354 testcpu = smp_processor_id();
355 pr_warn("Checking clocksource %s synchronization from CPU %d to CPUs %*pbl.\n", cs->name, testcpu, cpumask_pr_args(&cpus_chosen));
356 for_each_cpu(cpu, &cpus_chosen) {
357 if (cpu == testcpu)
358 continue;
359 csnow_begin = cs->read(cs);
360 smp_call_function_single(cpu, clocksource_verify_one_cpu, cs, 1);
361 csnow_end = cs->read(cs);
362 delta = (s64)((csnow_mid - csnow_begin) & cs->mask);
363 if (delta < 0)
364 cpumask_set_cpu(cpu, &cpus_behind);
365 delta = (csnow_end - csnow_mid) & cs->mask;
366 if (delta < 0)
367 cpumask_set_cpu(cpu, &cpus_ahead);
368 delta = clocksource_delta(csnow_end, csnow_begin, cs->mask);
369 cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
370 if (cs_nsec > cs_nsec_max)
371 cs_nsec_max = cs_nsec;
372 if (cs_nsec < cs_nsec_min)
373 cs_nsec_min = cs_nsec;
374 }
375 preempt_enable();
376 cpus_read_unlock();
377 if (!cpumask_empty(&cpus_ahead))
378 pr_warn(" CPUs %*pbl ahead of CPU %d for clocksource %s.\n",
379 cpumask_pr_args(&cpus_ahead), testcpu, cs->name);
380 if (!cpumask_empty(&cpus_behind))
381 pr_warn(" CPUs %*pbl behind CPU %d for clocksource %s.\n",
382 cpumask_pr_args(&cpus_behind), testcpu, cs->name);
383 if (!cpumask_empty(&cpus_ahead) || !cpumask_empty(&cpus_behind))
384 pr_warn(" CPU %d check durations %lldns - %lldns for clocksource %s.\n",
385 testcpu, cs_nsec_min, cs_nsec_max, cs->name);
386 }
387 EXPORT_SYMBOL_GPL(clocksource_verify_percpu);
388
clocksource_reset_watchdog(void)389 static inline void clocksource_reset_watchdog(void)
390 {
391 struct clocksource *cs;
392
393 list_for_each_entry(cs, &watchdog_list, wd_list)
394 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
395 }
396
397
clocksource_watchdog(struct timer_list * unused)398 static void clocksource_watchdog(struct timer_list *unused)
399 {
400 u64 csnow, wdnow, cslast, wdlast, delta;
401 int64_t wd_nsec, cs_nsec, interval;
402 int next_cpu, reset_pending;
403 struct clocksource *cs;
404 enum wd_read_status read_ret;
405 unsigned long extra_wait = 0;
406 u32 md;
407
408 spin_lock(&watchdog_lock);
409 if (!watchdog_running)
410 goto out;
411
412 reset_pending = atomic_read(&watchdog_reset_pending);
413
414 list_for_each_entry(cs, &watchdog_list, wd_list) {
415
416 /* Clocksource already marked unstable? */
417 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
418 if (finished_booting)
419 schedule_work(&watchdog_work);
420 continue;
421 }
422
423 read_ret = cs_watchdog_read(cs, &csnow, &wdnow);
424
425 if (read_ret == WD_READ_UNSTABLE) {
426 /* Clock readout unreliable, so give it up. */
427 __clocksource_unstable(cs);
428 continue;
429 }
430
431 /*
432 * When WD_READ_SKIP is returned, it means the system is likely
433 * under very heavy load, where the latency of reading
434 * watchdog/clocksource is very big, and affect the accuracy of
435 * watchdog check. So give system some space and suspend the
436 * watchdog check for 5 minutes.
437 */
438 if (read_ret == WD_READ_SKIP) {
439 /*
440 * As the watchdog timer will be suspended, and
441 * cs->last could keep unchanged for 5 minutes, reset
442 * the counters.
443 */
444 clocksource_reset_watchdog();
445 extra_wait = HZ * 300;
446 break;
447 }
448
449 /* Clocksource initialized ? */
450 if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
451 atomic_read(&watchdog_reset_pending)) {
452 cs->flags |= CLOCK_SOURCE_WATCHDOG;
453 cs->wd_last = wdnow;
454 cs->cs_last = csnow;
455 continue;
456 }
457
458 delta = clocksource_delta(wdnow, cs->wd_last, watchdog->mask);
459 wd_nsec = clocksource_cyc2ns(delta, watchdog->mult,
460 watchdog->shift);
461
462 delta = clocksource_delta(csnow, cs->cs_last, cs->mask);
463 cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
464 wdlast = cs->wd_last; /* save these in case we print them */
465 cslast = cs->cs_last;
466 cs->cs_last = csnow;
467 cs->wd_last = wdnow;
468
469 if (atomic_read(&watchdog_reset_pending))
470 continue;
471
472 /*
473 * The processing of timer softirqs can get delayed (usually
474 * on account of ksoftirqd not getting to run in a timely
475 * manner), which causes the watchdog interval to stretch.
476 * Skew detection may fail for longer watchdog intervals
477 * on account of fixed margins being used.
478 * Some clocksources, e.g. acpi_pm, cannot tolerate
479 * watchdog intervals longer than a few seconds.
480 */
481 interval = max(cs_nsec, wd_nsec);
482 if (unlikely(interval > WATCHDOG_INTERVAL_MAX_NS)) {
483 if (system_state > SYSTEM_SCHEDULING &&
484 interval > 2 * watchdog_max_interval) {
485 watchdog_max_interval = interval;
486 pr_warn("Long readout interval, skipping watchdog check: cs_nsec: %lld wd_nsec: %lld\n",
487 cs_nsec, wd_nsec);
488 }
489 watchdog_timer.expires = jiffies;
490 continue;
491 }
492
493 /* Check the deviation from the watchdog clocksource. */
494 md = cs->uncertainty_margin + watchdog->uncertainty_margin;
495 if (abs(cs_nsec - wd_nsec) > md) {
496 pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
497 smp_processor_id(), cs->name);
498 pr_warn(" '%s' wd_nsec: %lld wd_now: %llx wd_last: %llx mask: %llx\n",
499 watchdog->name, wd_nsec, wdnow, wdlast, watchdog->mask);
500 pr_warn(" '%s' cs_nsec: %lld cs_now: %llx cs_last: %llx mask: %llx\n",
501 cs->name, cs_nsec, csnow, cslast, cs->mask);
502 if (curr_clocksource == cs)
503 pr_warn(" '%s' is current clocksource.\n", cs->name);
504 else if (curr_clocksource)
505 pr_warn(" '%s' (not '%s') is current clocksource.\n", curr_clocksource->name, cs->name);
506 else
507 pr_warn(" No current clocksource.\n");
508 __clocksource_unstable(cs);
509 continue;
510 }
511
512 if (cs == curr_clocksource && cs->tick_stable)
513 cs->tick_stable(cs);
514
515 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
516 (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
517 (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
518 /* Mark it valid for high-res. */
519 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
520
521 /*
522 * clocksource_done_booting() will sort it if
523 * finished_booting is not set yet.
524 */
525 if (!finished_booting)
526 continue;
527
528 /*
529 * If this is not the current clocksource let
530 * the watchdog thread reselect it. Due to the
531 * change to high res this clocksource might
532 * be preferred now. If it is the current
533 * clocksource let the tick code know about
534 * that change.
535 */
536 if (cs != curr_clocksource) {
537 cs->flags |= CLOCK_SOURCE_RESELECT;
538 schedule_work(&watchdog_work);
539 } else {
540 tick_clock_notify();
541 }
542 }
543 }
544
545 /*
546 * We only clear the watchdog_reset_pending, when we did a
547 * full cycle through all clocksources.
548 */
549 if (reset_pending)
550 atomic_dec(&watchdog_reset_pending);
551
552 /*
553 * Cycle through CPUs to check if the CPUs stay synchronized
554 * to each other.
555 */
556 next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
557 if (next_cpu >= nr_cpu_ids)
558 next_cpu = cpumask_first(cpu_online_mask);
559
560 /*
561 * Arm timer if not already pending: could race with concurrent
562 * pair clocksource_stop_watchdog() clocksource_start_watchdog().
563 */
564 if (!timer_pending(&watchdog_timer)) {
565 watchdog_timer.expires += WATCHDOG_INTERVAL + extra_wait;
566 add_timer_on(&watchdog_timer, next_cpu);
567 }
568 out:
569 spin_unlock(&watchdog_lock);
570 }
571
clocksource_start_watchdog(void)572 static inline void clocksource_start_watchdog(void)
573 {
574 if (watchdog_running || !watchdog || list_empty(&watchdog_list))
575 return;
576 timer_setup(&watchdog_timer, clocksource_watchdog, 0);
577 watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
578 add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
579 watchdog_running = 1;
580 }
581
clocksource_stop_watchdog(void)582 static inline void clocksource_stop_watchdog(void)
583 {
584 if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
585 return;
586 del_timer(&watchdog_timer);
587 watchdog_running = 0;
588 }
589
clocksource_resume_watchdog(void)590 static void clocksource_resume_watchdog(void)
591 {
592 atomic_inc(&watchdog_reset_pending);
593 }
594
clocksource_enqueue_watchdog(struct clocksource * cs)595 static void clocksource_enqueue_watchdog(struct clocksource *cs)
596 {
597 INIT_LIST_HEAD(&cs->wd_list);
598
599 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
600 /* cs is a clocksource to be watched. */
601 list_add(&cs->wd_list, &watchdog_list);
602 cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
603 } else {
604 /* cs is a watchdog. */
605 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
606 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
607 }
608 }
609
clocksource_select_watchdog(bool fallback)610 static void clocksource_select_watchdog(bool fallback)
611 {
612 struct clocksource *cs, *old_wd;
613 unsigned long flags;
614
615 spin_lock_irqsave(&watchdog_lock, flags);
616 /* save current watchdog */
617 old_wd = watchdog;
618 if (fallback)
619 watchdog = NULL;
620
621 list_for_each_entry(cs, &clocksource_list, list) {
622 /* cs is a clocksource to be watched. */
623 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
624 continue;
625
626 /* Skip current if we were requested for a fallback. */
627 if (fallback && cs == old_wd)
628 continue;
629
630 /* Pick the best watchdog. */
631 if (!watchdog || cs->rating > watchdog->rating)
632 watchdog = cs;
633 }
634 /* If we failed to find a fallback restore the old one. */
635 if (!watchdog)
636 watchdog = old_wd;
637
638 /* If we changed the watchdog we need to reset cycles. */
639 if (watchdog != old_wd)
640 clocksource_reset_watchdog();
641
642 /* Check if the watchdog timer needs to be started. */
643 clocksource_start_watchdog();
644 spin_unlock_irqrestore(&watchdog_lock, flags);
645 }
646
clocksource_dequeue_watchdog(struct clocksource * cs)647 static void clocksource_dequeue_watchdog(struct clocksource *cs)
648 {
649 if (cs != watchdog) {
650 if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
651 /* cs is a watched clocksource. */
652 list_del_init(&cs->wd_list);
653 /* Check if the watchdog timer needs to be stopped. */
654 clocksource_stop_watchdog();
655 }
656 }
657 }
658
__clocksource_watchdog_kthread(void)659 static int __clocksource_watchdog_kthread(void)
660 {
661 struct clocksource *cs, *tmp;
662 unsigned long flags;
663 int select = 0;
664
665 /* Do any required per-CPU skew verification. */
666 if (curr_clocksource &&
667 curr_clocksource->flags & CLOCK_SOURCE_UNSTABLE &&
668 curr_clocksource->flags & CLOCK_SOURCE_VERIFY_PERCPU)
669 clocksource_verify_percpu(curr_clocksource);
670
671 spin_lock_irqsave(&watchdog_lock, flags);
672 list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
673 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
674 list_del_init(&cs->wd_list);
675 __clocksource_change_rating(cs, 0);
676 select = 1;
677 }
678 if (cs->flags & CLOCK_SOURCE_RESELECT) {
679 cs->flags &= ~CLOCK_SOURCE_RESELECT;
680 select = 1;
681 }
682 }
683 /* Check if the watchdog timer needs to be stopped. */
684 clocksource_stop_watchdog();
685 spin_unlock_irqrestore(&watchdog_lock, flags);
686
687 return select;
688 }
689
clocksource_watchdog_kthread(void * data)690 static int clocksource_watchdog_kthread(void *data)
691 {
692 mutex_lock(&clocksource_mutex);
693 if (__clocksource_watchdog_kthread())
694 clocksource_select();
695 mutex_unlock(&clocksource_mutex);
696 return 0;
697 }
698
clocksource_is_watchdog(struct clocksource * cs)699 static bool clocksource_is_watchdog(struct clocksource *cs)
700 {
701 return cs == watchdog;
702 }
703
704 #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
705
clocksource_enqueue_watchdog(struct clocksource * cs)706 static void clocksource_enqueue_watchdog(struct clocksource *cs)
707 {
708 if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
709 cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
710 }
711
clocksource_select_watchdog(bool fallback)712 static void clocksource_select_watchdog(bool fallback) { }
clocksource_dequeue_watchdog(struct clocksource * cs)713 static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
clocksource_resume_watchdog(void)714 static inline void clocksource_resume_watchdog(void) { }
__clocksource_watchdog_kthread(void)715 static inline int __clocksource_watchdog_kthread(void) { return 0; }
clocksource_is_watchdog(struct clocksource * cs)716 static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
clocksource_mark_unstable(struct clocksource * cs)717 void clocksource_mark_unstable(struct clocksource *cs) { }
718
clocksource_watchdog_lock(unsigned long * flags)719 static inline void clocksource_watchdog_lock(unsigned long *flags) { }
clocksource_watchdog_unlock(unsigned long * flags)720 static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
721
722 #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
723
clocksource_is_suspend(struct clocksource * cs)724 static bool clocksource_is_suspend(struct clocksource *cs)
725 {
726 return cs == suspend_clocksource;
727 }
728
__clocksource_suspend_select(struct clocksource * cs)729 static void __clocksource_suspend_select(struct clocksource *cs)
730 {
731 /*
732 * Skip the clocksource which will be stopped in suspend state.
733 */
734 if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
735 return;
736
737 /*
738 * The nonstop clocksource can be selected as the suspend clocksource to
739 * calculate the suspend time, so it should not supply suspend/resume
740 * interfaces to suspend the nonstop clocksource when system suspends.
741 */
742 if (cs->suspend || cs->resume) {
743 pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
744 cs->name);
745 }
746
747 /* Pick the best rating. */
748 if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
749 suspend_clocksource = cs;
750 }
751
752 /**
753 * clocksource_suspend_select - Select the best clocksource for suspend timing
754 * @fallback: if select a fallback clocksource
755 */
clocksource_suspend_select(bool fallback)756 static void clocksource_suspend_select(bool fallback)
757 {
758 struct clocksource *cs, *old_suspend;
759
760 old_suspend = suspend_clocksource;
761 if (fallback)
762 suspend_clocksource = NULL;
763
764 list_for_each_entry(cs, &clocksource_list, list) {
765 /* Skip current if we were requested for a fallback. */
766 if (fallback && cs == old_suspend)
767 continue;
768
769 __clocksource_suspend_select(cs);
770 }
771 }
772
773 /**
774 * clocksource_start_suspend_timing - Start measuring the suspend timing
775 * @cs: current clocksource from timekeeping
776 * @start_cycles: current cycles from timekeeping
777 *
778 * This function will save the start cycle values of suspend timer to calculate
779 * the suspend time when resuming system.
780 *
781 * This function is called late in the suspend process from timekeeping_suspend(),
782 * that means processes are frozen, non-boot cpus and interrupts are disabled
783 * now. It is therefore possible to start the suspend timer without taking the
784 * clocksource mutex.
785 */
clocksource_start_suspend_timing(struct clocksource * cs,u64 start_cycles)786 void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
787 {
788 if (!suspend_clocksource)
789 return;
790
791 /*
792 * If current clocksource is the suspend timer, we should use the
793 * tkr_mono.cycle_last value as suspend_start to avoid same reading
794 * from suspend timer.
795 */
796 if (clocksource_is_suspend(cs)) {
797 suspend_start = start_cycles;
798 return;
799 }
800
801 if (suspend_clocksource->enable &&
802 suspend_clocksource->enable(suspend_clocksource)) {
803 pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
804 return;
805 }
806
807 suspend_start = suspend_clocksource->read(suspend_clocksource);
808 }
809
810 /**
811 * clocksource_stop_suspend_timing - Stop measuring the suspend timing
812 * @cs: current clocksource from timekeeping
813 * @cycle_now: current cycles from timekeeping
814 *
815 * This function will calculate the suspend time from suspend timer.
816 *
817 * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
818 *
819 * This function is called early in the resume process from timekeeping_resume(),
820 * that means there is only one cpu, no processes are running and the interrupts
821 * are disabled. It is therefore possible to stop the suspend timer without
822 * taking the clocksource mutex.
823 */
clocksource_stop_suspend_timing(struct clocksource * cs,u64 cycle_now)824 u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
825 {
826 u64 now, delta, nsec = 0;
827
828 if (!suspend_clocksource)
829 return 0;
830
831 /*
832 * If current clocksource is the suspend timer, we should use the
833 * tkr_mono.cycle_last value from timekeeping as current cycle to
834 * avoid same reading from suspend timer.
835 */
836 if (clocksource_is_suspend(cs))
837 now = cycle_now;
838 else
839 now = suspend_clocksource->read(suspend_clocksource);
840
841 if (now > suspend_start) {
842 delta = clocksource_delta(now, suspend_start,
843 suspend_clocksource->mask);
844 nsec = mul_u64_u32_shr(delta, suspend_clocksource->mult,
845 suspend_clocksource->shift);
846 }
847
848 /*
849 * Disable the suspend timer to save power if current clocksource is
850 * not the suspend timer.
851 */
852 if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
853 suspend_clocksource->disable(suspend_clocksource);
854
855 return nsec;
856 }
857
858 /**
859 * clocksource_suspend - suspend the clocksource(s)
860 */
clocksource_suspend(void)861 void clocksource_suspend(void)
862 {
863 struct clocksource *cs;
864
865 list_for_each_entry_reverse(cs, &clocksource_list, list)
866 if (cs->suspend)
867 cs->suspend(cs);
868 }
869
870 /**
871 * clocksource_resume - resume the clocksource(s)
872 */
clocksource_resume(void)873 void clocksource_resume(void)
874 {
875 struct clocksource *cs;
876
877 list_for_each_entry(cs, &clocksource_list, list)
878 if (cs->resume)
879 cs->resume(cs);
880
881 clocksource_resume_watchdog();
882 }
883
884 /**
885 * clocksource_touch_watchdog - Update watchdog
886 *
887 * Update the watchdog after exception contexts such as kgdb so as not
888 * to incorrectly trip the watchdog. This might fail when the kernel
889 * was stopped in code which holds watchdog_lock.
890 */
clocksource_touch_watchdog(void)891 void clocksource_touch_watchdog(void)
892 {
893 clocksource_resume_watchdog();
894 }
895
896 /**
897 * clocksource_max_adjustment- Returns max adjustment amount
898 * @cs: Pointer to clocksource
899 *
900 */
clocksource_max_adjustment(struct clocksource * cs)901 static u32 clocksource_max_adjustment(struct clocksource *cs)
902 {
903 u64 ret;
904 /*
905 * We won't try to correct for more than 11% adjustments (110,000 ppm),
906 */
907 ret = (u64)cs->mult * 11;
908 do_div(ret,100);
909 return (u32)ret;
910 }
911
912 /**
913 * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
914 * @mult: cycle to nanosecond multiplier
915 * @shift: cycle to nanosecond divisor (power of two)
916 * @maxadj: maximum adjustment value to mult (~11%)
917 * @mask: bitmask for two's complement subtraction of non 64 bit counters
918 * @max_cyc: maximum cycle value before potential overflow (does not include
919 * any safety margin)
920 *
921 * NOTE: This function includes a safety margin of 50%, in other words, we
922 * return half the number of nanoseconds the hardware counter can technically
923 * cover. This is done so that we can potentially detect problems caused by
924 * delayed timers or bad hardware, which might result in time intervals that
925 * are larger than what the math used can handle without overflows.
926 */
clocks_calc_max_nsecs(u32 mult,u32 shift,u32 maxadj,u64 mask,u64 * max_cyc)927 u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
928 {
929 u64 max_nsecs, max_cycles;
930
931 /*
932 * Calculate the maximum number of cycles that we can pass to the
933 * cyc2ns() function without overflowing a 64-bit result.
934 */
935 max_cycles = ULLONG_MAX;
936 do_div(max_cycles, mult+maxadj);
937
938 /*
939 * The actual maximum number of cycles we can defer the clocksource is
940 * determined by the minimum of max_cycles and mask.
941 * Note: Here we subtract the maxadj to make sure we don't sleep for
942 * too long if there's a large negative adjustment.
943 */
944 max_cycles = min(max_cycles, mask);
945 max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
946
947 /* return the max_cycles value as well if requested */
948 if (max_cyc)
949 *max_cyc = max_cycles;
950
951 /* Return 50% of the actual maximum, so we can detect bad values */
952 max_nsecs >>= 1;
953
954 return max_nsecs;
955 }
956
957 /**
958 * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
959 * @cs: Pointer to clocksource to be updated
960 *
961 */
clocksource_update_max_deferment(struct clocksource * cs)962 static inline void clocksource_update_max_deferment(struct clocksource *cs)
963 {
964 cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
965 cs->maxadj, cs->mask,
966 &cs->max_cycles);
967 }
968
clocksource_find_best(bool oneshot,bool skipcur)969 static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
970 {
971 struct clocksource *cs;
972
973 if (!finished_booting || list_empty(&clocksource_list))
974 return NULL;
975
976 /*
977 * We pick the clocksource with the highest rating. If oneshot
978 * mode is active, we pick the highres valid clocksource with
979 * the best rating.
980 */
981 list_for_each_entry(cs, &clocksource_list, list) {
982 if (skipcur && cs == curr_clocksource)
983 continue;
984 if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
985 continue;
986 return cs;
987 }
988 return NULL;
989 }
990
__clocksource_select(bool skipcur)991 static void __clocksource_select(bool skipcur)
992 {
993 bool oneshot = tick_oneshot_mode_active();
994 struct clocksource *best, *cs;
995
996 /* Find the best suitable clocksource */
997 best = clocksource_find_best(oneshot, skipcur);
998 if (!best)
999 return;
1000
1001 if (!strlen(override_name))
1002 goto found;
1003
1004 /* Check for the override clocksource. */
1005 list_for_each_entry(cs, &clocksource_list, list) {
1006 if (skipcur && cs == curr_clocksource)
1007 continue;
1008 if (strcmp(cs->name, override_name) != 0)
1009 continue;
1010 /*
1011 * Check to make sure we don't switch to a non-highres
1012 * capable clocksource if the tick code is in oneshot
1013 * mode (highres or nohz)
1014 */
1015 if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
1016 /* Override clocksource cannot be used. */
1017 if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
1018 pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
1019 cs->name);
1020 override_name[0] = 0;
1021 } else {
1022 /*
1023 * The override cannot be currently verified.
1024 * Deferring to let the watchdog check.
1025 */
1026 pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
1027 cs->name);
1028 }
1029 } else
1030 /* Override clocksource can be used. */
1031 best = cs;
1032 break;
1033 }
1034
1035 found:
1036 if (curr_clocksource != best && !timekeeping_notify(best)) {
1037 pr_info("Switched to clocksource %s\n", best->name);
1038 curr_clocksource = best;
1039 }
1040 }
1041
1042 /**
1043 * clocksource_select - Select the best clocksource available
1044 *
1045 * Private function. Must hold clocksource_mutex when called.
1046 *
1047 * Select the clocksource with the best rating, or the clocksource,
1048 * which is selected by userspace override.
1049 */
clocksource_select(void)1050 static void clocksource_select(void)
1051 {
1052 __clocksource_select(false);
1053 }
1054
clocksource_select_fallback(void)1055 static void clocksource_select_fallback(void)
1056 {
1057 __clocksource_select(true);
1058 }
1059
1060 /*
1061 * clocksource_done_booting - Called near the end of core bootup
1062 *
1063 * Hack to avoid lots of clocksource churn at boot time.
1064 * We use fs_initcall because we want this to start before
1065 * device_initcall but after subsys_initcall.
1066 */
clocksource_done_booting(void)1067 static int __init clocksource_done_booting(void)
1068 {
1069 mutex_lock(&clocksource_mutex);
1070 curr_clocksource = clocksource_default_clock();
1071 finished_booting = 1;
1072 /*
1073 * Run the watchdog first to eliminate unstable clock sources
1074 */
1075 __clocksource_watchdog_kthread();
1076 clocksource_select();
1077 mutex_unlock(&clocksource_mutex);
1078 return 0;
1079 }
1080 fs_initcall(clocksource_done_booting);
1081
1082 /*
1083 * Enqueue the clocksource sorted by rating
1084 */
clocksource_enqueue(struct clocksource * cs)1085 static void clocksource_enqueue(struct clocksource *cs)
1086 {
1087 struct list_head *entry = &clocksource_list;
1088 struct clocksource *tmp;
1089
1090 list_for_each_entry(tmp, &clocksource_list, list) {
1091 /* Keep track of the place, where to insert */
1092 if (tmp->rating < cs->rating)
1093 break;
1094 entry = &tmp->list;
1095 }
1096 list_add(&cs->list, entry);
1097 }
1098
1099 /**
1100 * __clocksource_update_freq_scale - Used update clocksource with new freq
1101 * @cs: clocksource to be registered
1102 * @scale: Scale factor multiplied against freq to get clocksource hz
1103 * @freq: clocksource frequency (cycles per second) divided by scale
1104 *
1105 * This should only be called from the clocksource->enable() method.
1106 *
1107 * This *SHOULD NOT* be called directly! Please use the
1108 * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
1109 * functions.
1110 */
__clocksource_update_freq_scale(struct clocksource * cs,u32 scale,u32 freq)1111 void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
1112 {
1113 u64 sec;
1114
1115 /*
1116 * Default clocksources are *special* and self-define their mult/shift.
1117 * But, you're not special, so you should specify a freq value.
1118 */
1119 if (freq) {
1120 /*
1121 * Calc the maximum number of seconds which we can run before
1122 * wrapping around. For clocksources which have a mask > 32-bit
1123 * we need to limit the max sleep time to have a good
1124 * conversion precision. 10 minutes is still a reasonable
1125 * amount. That results in a shift value of 24 for a
1126 * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
1127 * ~ 0.06ppm granularity for NTP.
1128 */
1129 sec = cs->mask;
1130 do_div(sec, freq);
1131 do_div(sec, scale);
1132 if (!sec)
1133 sec = 1;
1134 else if (sec > 600 && cs->mask > UINT_MAX)
1135 sec = 600;
1136
1137 clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
1138 NSEC_PER_SEC / scale, sec * scale);
1139 }
1140
1141 /*
1142 * If the uncertainty margin is not specified, calculate it.
1143 * If both scale and freq are non-zero, calculate the clock
1144 * period, but bound below at 2*WATCHDOG_MAX_SKEW. However,
1145 * if either of scale or freq is zero, be very conservative and
1146 * take the tens-of-milliseconds WATCHDOG_THRESHOLD value for the
1147 * uncertainty margin. Allow stupidly small uncertainty margins
1148 * to be specified by the caller for testing purposes, but warn
1149 * to discourage production use of this capability.
1150 */
1151 if (scale && freq && !cs->uncertainty_margin) {
1152 cs->uncertainty_margin = NSEC_PER_SEC / (scale * freq);
1153 if (cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW)
1154 cs->uncertainty_margin = 2 * WATCHDOG_MAX_SKEW;
1155 } else if (!cs->uncertainty_margin) {
1156 cs->uncertainty_margin = WATCHDOG_THRESHOLD;
1157 }
1158 WARN_ON_ONCE(cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW);
1159
1160 /*
1161 * Ensure clocksources that have large 'mult' values don't overflow
1162 * when adjusted.
1163 */
1164 cs->maxadj = clocksource_max_adjustment(cs);
1165 while (freq && ((cs->mult + cs->maxadj < cs->mult)
1166 || (cs->mult - cs->maxadj > cs->mult))) {
1167 cs->mult >>= 1;
1168 cs->shift--;
1169 cs->maxadj = clocksource_max_adjustment(cs);
1170 }
1171
1172 /*
1173 * Only warn for *special* clocksources that self-define
1174 * their mult/shift values and don't specify a freq.
1175 */
1176 WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
1177 "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
1178 cs->name);
1179
1180 clocksource_update_max_deferment(cs);
1181
1182 pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
1183 cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
1184 }
1185 EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
1186
1187 /**
1188 * __clocksource_register_scale - Used to install new clocksources
1189 * @cs: clocksource to be registered
1190 * @scale: Scale factor multiplied against freq to get clocksource hz
1191 * @freq: clocksource frequency (cycles per second) divided by scale
1192 *
1193 * Returns -EBUSY if registration fails, zero otherwise.
1194 *
1195 * This *SHOULD NOT* be called directly! Please use the
1196 * clocksource_register_hz() or clocksource_register_khz helper functions.
1197 */
__clocksource_register_scale(struct clocksource * cs,u32 scale,u32 freq)1198 int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
1199 {
1200 unsigned long flags;
1201
1202 clocksource_arch_init(cs);
1203
1204 if (WARN_ON_ONCE((unsigned int)cs->id >= CSID_MAX))
1205 cs->id = CSID_GENERIC;
1206 if (cs->vdso_clock_mode < 0 ||
1207 cs->vdso_clock_mode >= VDSO_CLOCKMODE_MAX) {
1208 pr_warn("clocksource %s registered with invalid VDSO mode %d. Disabling VDSO support.\n",
1209 cs->name, cs->vdso_clock_mode);
1210 cs->vdso_clock_mode = VDSO_CLOCKMODE_NONE;
1211 }
1212
1213 /* Initialize mult/shift and max_idle_ns */
1214 __clocksource_update_freq_scale(cs, scale, freq);
1215
1216 /* Add clocksource to the clocksource list */
1217 mutex_lock(&clocksource_mutex);
1218
1219 clocksource_watchdog_lock(&flags);
1220 clocksource_enqueue(cs);
1221 clocksource_enqueue_watchdog(cs);
1222 clocksource_watchdog_unlock(&flags);
1223
1224 clocksource_select();
1225 clocksource_select_watchdog(false);
1226 __clocksource_suspend_select(cs);
1227 mutex_unlock(&clocksource_mutex);
1228 return 0;
1229 }
1230 EXPORT_SYMBOL_GPL(__clocksource_register_scale);
1231
__clocksource_change_rating(struct clocksource * cs,int rating)1232 static void __clocksource_change_rating(struct clocksource *cs, int rating)
1233 {
1234 list_del(&cs->list);
1235 cs->rating = rating;
1236 clocksource_enqueue(cs);
1237 }
1238
1239 /**
1240 * clocksource_change_rating - Change the rating of a registered clocksource
1241 * @cs: clocksource to be changed
1242 * @rating: new rating
1243 */
clocksource_change_rating(struct clocksource * cs,int rating)1244 void clocksource_change_rating(struct clocksource *cs, int rating)
1245 {
1246 unsigned long flags;
1247
1248 mutex_lock(&clocksource_mutex);
1249 clocksource_watchdog_lock(&flags);
1250 __clocksource_change_rating(cs, rating);
1251 clocksource_watchdog_unlock(&flags);
1252
1253 clocksource_select();
1254 clocksource_select_watchdog(false);
1255 clocksource_suspend_select(false);
1256 mutex_unlock(&clocksource_mutex);
1257 }
1258 EXPORT_SYMBOL(clocksource_change_rating);
1259
1260 /*
1261 * Unbind clocksource @cs. Called with clocksource_mutex held
1262 */
clocksource_unbind(struct clocksource * cs)1263 static int clocksource_unbind(struct clocksource *cs)
1264 {
1265 unsigned long flags;
1266
1267 if (clocksource_is_watchdog(cs)) {
1268 /* Select and try to install a replacement watchdog. */
1269 clocksource_select_watchdog(true);
1270 if (clocksource_is_watchdog(cs))
1271 return -EBUSY;
1272 }
1273
1274 if (cs == curr_clocksource) {
1275 /* Select and try to install a replacement clock source */
1276 clocksource_select_fallback();
1277 if (curr_clocksource == cs)
1278 return -EBUSY;
1279 }
1280
1281 if (clocksource_is_suspend(cs)) {
1282 /*
1283 * Select and try to install a replacement suspend clocksource.
1284 * If no replacement suspend clocksource, we will just let the
1285 * clocksource go and have no suspend clocksource.
1286 */
1287 clocksource_suspend_select(true);
1288 }
1289
1290 clocksource_watchdog_lock(&flags);
1291 clocksource_dequeue_watchdog(cs);
1292 list_del_init(&cs->list);
1293 clocksource_watchdog_unlock(&flags);
1294
1295 return 0;
1296 }
1297
1298 /**
1299 * clocksource_unregister - remove a registered clocksource
1300 * @cs: clocksource to be unregistered
1301 */
clocksource_unregister(struct clocksource * cs)1302 int clocksource_unregister(struct clocksource *cs)
1303 {
1304 int ret = 0;
1305
1306 mutex_lock(&clocksource_mutex);
1307 if (!list_empty(&cs->list))
1308 ret = clocksource_unbind(cs);
1309 mutex_unlock(&clocksource_mutex);
1310 return ret;
1311 }
1312 EXPORT_SYMBOL(clocksource_unregister);
1313
1314 #ifdef CONFIG_SYSFS
1315 /**
1316 * current_clocksource_show - sysfs interface for current clocksource
1317 * @dev: unused
1318 * @attr: unused
1319 * @buf: char buffer to be filled with clocksource list
1320 *
1321 * Provides sysfs interface for listing current clocksource.
1322 */
current_clocksource_show(struct device * dev,struct device_attribute * attr,char * buf)1323 static ssize_t current_clocksource_show(struct device *dev,
1324 struct device_attribute *attr,
1325 char *buf)
1326 {
1327 ssize_t count = 0;
1328
1329 mutex_lock(&clocksource_mutex);
1330 count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
1331 mutex_unlock(&clocksource_mutex);
1332
1333 return count;
1334 }
1335
sysfs_get_uname(const char * buf,char * dst,size_t cnt)1336 ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
1337 {
1338 size_t ret = cnt;
1339
1340 /* strings from sysfs write are not 0 terminated! */
1341 if (!cnt || cnt >= CS_NAME_LEN)
1342 return -EINVAL;
1343
1344 /* strip of \n: */
1345 if (buf[cnt-1] == '\n')
1346 cnt--;
1347 if (cnt > 0)
1348 memcpy(dst, buf, cnt);
1349 dst[cnt] = 0;
1350 return ret;
1351 }
1352
1353 /**
1354 * current_clocksource_store - interface for manually overriding clocksource
1355 * @dev: unused
1356 * @attr: unused
1357 * @buf: name of override clocksource
1358 * @count: length of buffer
1359 *
1360 * Takes input from sysfs interface for manually overriding the default
1361 * clocksource selection.
1362 */
current_clocksource_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1363 static ssize_t current_clocksource_store(struct device *dev,
1364 struct device_attribute *attr,
1365 const char *buf, size_t count)
1366 {
1367 ssize_t ret;
1368
1369 mutex_lock(&clocksource_mutex);
1370
1371 ret = sysfs_get_uname(buf, override_name, count);
1372 if (ret >= 0)
1373 clocksource_select();
1374
1375 mutex_unlock(&clocksource_mutex);
1376
1377 return ret;
1378 }
1379 static DEVICE_ATTR_RW(current_clocksource);
1380
1381 /**
1382 * unbind_clocksource_store - interface for manually unbinding clocksource
1383 * @dev: unused
1384 * @attr: unused
1385 * @buf: unused
1386 * @count: length of buffer
1387 *
1388 * Takes input from sysfs interface for manually unbinding a clocksource.
1389 */
unbind_clocksource_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1390 static ssize_t unbind_clocksource_store(struct device *dev,
1391 struct device_attribute *attr,
1392 const char *buf, size_t count)
1393 {
1394 struct clocksource *cs;
1395 char name[CS_NAME_LEN];
1396 ssize_t ret;
1397
1398 ret = sysfs_get_uname(buf, name, count);
1399 if (ret < 0)
1400 return ret;
1401
1402 ret = -ENODEV;
1403 mutex_lock(&clocksource_mutex);
1404 list_for_each_entry(cs, &clocksource_list, list) {
1405 if (strcmp(cs->name, name))
1406 continue;
1407 ret = clocksource_unbind(cs);
1408 break;
1409 }
1410 mutex_unlock(&clocksource_mutex);
1411
1412 return ret ? ret : count;
1413 }
1414 static DEVICE_ATTR_WO(unbind_clocksource);
1415
1416 /**
1417 * available_clocksource_show - sysfs interface for listing clocksource
1418 * @dev: unused
1419 * @attr: unused
1420 * @buf: char buffer to be filled with clocksource list
1421 *
1422 * Provides sysfs interface for listing registered clocksources
1423 */
available_clocksource_show(struct device * dev,struct device_attribute * attr,char * buf)1424 static ssize_t available_clocksource_show(struct device *dev,
1425 struct device_attribute *attr,
1426 char *buf)
1427 {
1428 struct clocksource *src;
1429 ssize_t count = 0;
1430
1431 mutex_lock(&clocksource_mutex);
1432 list_for_each_entry(src, &clocksource_list, list) {
1433 /*
1434 * Don't show non-HRES clocksource if the tick code is
1435 * in one shot mode (highres=on or nohz=on)
1436 */
1437 if (!tick_oneshot_mode_active() ||
1438 (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
1439 count += snprintf(buf + count,
1440 max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
1441 "%s ", src->name);
1442 }
1443 mutex_unlock(&clocksource_mutex);
1444
1445 count += snprintf(buf + count,
1446 max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
1447
1448 return count;
1449 }
1450 static DEVICE_ATTR_RO(available_clocksource);
1451
1452 static struct attribute *clocksource_attrs[] = {
1453 &dev_attr_current_clocksource.attr,
1454 &dev_attr_unbind_clocksource.attr,
1455 &dev_attr_available_clocksource.attr,
1456 NULL
1457 };
1458 ATTRIBUTE_GROUPS(clocksource);
1459
1460 static struct bus_type clocksource_subsys = {
1461 .name = "clocksource",
1462 .dev_name = "clocksource",
1463 };
1464
1465 static struct device device_clocksource = {
1466 .id = 0,
1467 .bus = &clocksource_subsys,
1468 .groups = clocksource_groups,
1469 };
1470
init_clocksource_sysfs(void)1471 static int __init init_clocksource_sysfs(void)
1472 {
1473 int error = subsys_system_register(&clocksource_subsys, NULL);
1474
1475 if (!error)
1476 error = device_register(&device_clocksource);
1477
1478 return error;
1479 }
1480
1481 device_initcall(init_clocksource_sysfs);
1482 #endif /* CONFIG_SYSFS */
1483
1484 /**
1485 * boot_override_clocksource - boot clock override
1486 * @str: override name
1487 *
1488 * Takes a clocksource= boot argument and uses it
1489 * as the clocksource override name.
1490 */
boot_override_clocksource(char * str)1491 static int __init boot_override_clocksource(char* str)
1492 {
1493 mutex_lock(&clocksource_mutex);
1494 if (str)
1495 strlcpy(override_name, str, sizeof(override_name));
1496 mutex_unlock(&clocksource_mutex);
1497 return 1;
1498 }
1499
1500 __setup("clocksource=", boot_override_clocksource);
1501
1502 /**
1503 * boot_override_clock - Compatibility layer for deprecated boot option
1504 * @str: override name
1505 *
1506 * DEPRECATED! Takes a clock= boot argument and uses it
1507 * as the clocksource override name
1508 */
boot_override_clock(char * str)1509 static int __init boot_override_clock(char* str)
1510 {
1511 if (!strcmp(str, "pmtmr")) {
1512 pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
1513 return boot_override_clocksource("acpi_pm");
1514 }
1515 pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
1516 return boot_override_clocksource(str);
1517 }
1518
1519 __setup("clock=", boot_override_clock);
1520