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