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