x86/tsc: Provide 'tsc=unstable' boot parameter
[linux-2.6-block.git] / arch / x86 / kernel / tsc.c
CommitLineData
c767a54b
JP
1#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2
bfc0f594 3#include <linux/kernel.h>
0ef95533 4#include <linux/sched.h>
e6017571 5#include <linux/sched/clock.h>
0ef95533 6#include <linux/init.h>
186f4360 7#include <linux/export.h>
0ef95533 8#include <linux/timer.h>
bfc0f594 9#include <linux/acpi_pmtmr.h>
2dbe06fa 10#include <linux/cpufreq.h>
8fbbc4b4
AK
11#include <linux/delay.h>
12#include <linux/clocksource.h>
13#include <linux/percpu.h>
08604bd9 14#include <linux/timex.h>
10b033d4 15#include <linux/static_key.h>
bfc0f594
AK
16
17#include <asm/hpet.h>
8fbbc4b4
AK
18#include <asm/timer.h>
19#include <asm/vgtod.h>
20#include <asm/time.h>
21#include <asm/delay.h>
88b094fb 22#include <asm/hypervisor.h>
08047c4f 23#include <asm/nmi.h>
2d826404 24#include <asm/x86_init.h>
03da3ff1 25#include <asm/geode.h>
6731b0d6 26#include <asm/apic.h>
655e52d2 27#include <asm/intel-family.h>
0ef95533 28
f24ade3a 29unsigned int __read_mostly cpu_khz; /* TSC clocks / usec, not used here */
0ef95533 30EXPORT_SYMBOL(cpu_khz);
f24ade3a
IM
31
32unsigned int __read_mostly tsc_khz;
0ef95533
AK
33EXPORT_SYMBOL(tsc_khz);
34
35/*
36 * TSC can be unstable due to cpufreq or due to unsynced TSCs
37 */
f24ade3a 38static int __read_mostly tsc_unstable;
0ef95533
AK
39
40/* native_sched_clock() is called before tsc_init(), so
41 we must start with the TSC soft disabled to prevent
59e21e3d 42 erroneous rdtsc usage on !boot_cpu_has(X86_FEATURE_TSC) processors */
f24ade3a 43static int __read_mostly tsc_disabled = -1;
0ef95533 44
3bbfafb7 45static DEFINE_STATIC_KEY_FALSE(__use_tsc);
10b033d4 46
28a00184 47int tsc_clocksource_reliable;
57c67da2 48
f9677e0f
CH
49static u32 art_to_tsc_numerator;
50static u32 art_to_tsc_denominator;
51static u64 art_to_tsc_offset;
52struct clocksource *art_related_clocksource;
53
20d1c86a
PZ
54/*
55 * Use a ring-buffer like data structure, where a writer advances the head by
56 * writing a new data entry and a reader advances the tail when it observes a
57 * new entry.
58 *
59 * Writers are made to wait on readers until there's space to write a new
60 * entry.
61 *
62 * This means that we can always use an {offset, mul} pair to compute a ns
63 * value that is 'roughly' in the right direction, even if we're writing a new
64 * {offset, mul} pair during the clock read.
65 *
66 * The down-side is that we can no longer guarantee strict monotonicity anymore
67 * (assuming the TSC was that to begin with), because while we compute the
68 * intersection point of the two clock slopes and make sure the time is
69 * continuous at the point of switching; we can no longer guarantee a reader is
70 * strictly before or after the switch point.
71 *
72 * It does mean a reader no longer needs to disable IRQs in order to avoid
73 * CPU-Freq updates messing with his times, and similarly an NMI reader will
74 * no longer run the risk of hitting half-written state.
75 */
76
77struct cyc2ns {
78 struct cyc2ns_data data[2]; /* 0 + 2*24 = 48 */
79 struct cyc2ns_data *head; /* 48 + 8 = 56 */
80 struct cyc2ns_data *tail; /* 56 + 8 = 64 */
81}; /* exactly fits one cacheline */
82
83static DEFINE_PER_CPU_ALIGNED(struct cyc2ns, cyc2ns);
84
85struct cyc2ns_data *cyc2ns_read_begin(void)
86{
87 struct cyc2ns_data *head;
88
89 preempt_disable();
90
91 head = this_cpu_read(cyc2ns.head);
92 /*
93 * Ensure we observe the entry when we observe the pointer to it.
94 * matches the wmb from cyc2ns_write_end().
95 */
96 smp_read_barrier_depends();
97 head->__count++;
98 barrier();
99
100 return head;
101}
102
103void cyc2ns_read_end(struct cyc2ns_data *head)
104{
105 barrier();
106 /*
107 * If we're the outer most nested read; update the tail pointer
108 * when we're done. This notifies possible pending writers
109 * that we've observed the head pointer and that the other
110 * entry is now free.
111 */
112 if (!--head->__count) {
113 /*
114 * x86-TSO does not reorder writes with older reads;
115 * therefore once this write becomes visible to another
116 * cpu, we must be finished reading the cyc2ns_data.
117 *
118 * matches with cyc2ns_write_begin().
119 */
120 this_cpu_write(cyc2ns.tail, head);
121 }
122 preempt_enable();
123}
124
125/*
126 * Begin writing a new @data entry for @cpu.
127 *
128 * Assumes some sort of write side lock; currently 'provided' by the assumption
129 * that cpufreq will call its notifiers sequentially.
130 */
131static struct cyc2ns_data *cyc2ns_write_begin(int cpu)
132{
133 struct cyc2ns *c2n = &per_cpu(cyc2ns, cpu);
134 struct cyc2ns_data *data = c2n->data;
135
136 if (data == c2n->head)
137 data++;
138
139 /* XXX send an IPI to @cpu in order to guarantee a read? */
140
141 /*
142 * When we observe the tail write from cyc2ns_read_end(),
143 * the cpu must be done with that entry and its safe
144 * to start writing to it.
145 */
146 while (c2n->tail == data)
147 cpu_relax();
148
149 return data;
150}
151
152static void cyc2ns_write_end(int cpu, struct cyc2ns_data *data)
153{
154 struct cyc2ns *c2n = &per_cpu(cyc2ns, cpu);
155
156 /*
157 * Ensure the @data writes are visible before we publish the
158 * entry. Matches the data-depencency in cyc2ns_read_begin().
159 */
160 smp_wmb();
161
162 ACCESS_ONCE(c2n->head) = data;
163}
164
165/*
166 * Accelerators for sched_clock()
57c67da2
PZ
167 * convert from cycles(64bits) => nanoseconds (64bits)
168 * basic equation:
169 * ns = cycles / (freq / ns_per_sec)
170 * ns = cycles * (ns_per_sec / freq)
171 * ns = cycles * (10^9 / (cpu_khz * 10^3))
172 * ns = cycles * (10^6 / cpu_khz)
173 *
174 * Then we use scaling math (suggested by george@mvista.com) to get:
175 * ns = cycles * (10^6 * SC / cpu_khz) / SC
176 * ns = cycles * cyc2ns_scale / SC
177 *
178 * And since SC is a constant power of two, we can convert the div
b20112ed
AH
179 * into a shift. The larger SC is, the more accurate the conversion, but
180 * cyc2ns_scale needs to be a 32-bit value so that 32-bit multiplication
181 * (64-bit result) can be used.
57c67da2 182 *
b20112ed 183 * We can use khz divisor instead of mhz to keep a better precision.
57c67da2
PZ
184 * (mathieu.desnoyers@polymtl.ca)
185 *
186 * -johnstul@us.ibm.com "math is hard, lets go shopping!"
187 */
188
20d1c86a
PZ
189static void cyc2ns_data_init(struct cyc2ns_data *data)
190{
5e3c1afd 191 data->cyc2ns_mul = 0;
b20112ed 192 data->cyc2ns_shift = 0;
20d1c86a
PZ
193 data->cyc2ns_offset = 0;
194 data->__count = 0;
195}
196
197static void cyc2ns_init(int cpu)
198{
199 struct cyc2ns *c2n = &per_cpu(cyc2ns, cpu);
200
201 cyc2ns_data_init(&c2n->data[0]);
202 cyc2ns_data_init(&c2n->data[1]);
203
204 c2n->head = c2n->data;
205 c2n->tail = c2n->data;
206}
207
57c67da2
PZ
208static inline unsigned long long cycles_2_ns(unsigned long long cyc)
209{
20d1c86a
PZ
210 struct cyc2ns_data *data, *tail;
211 unsigned long long ns;
212
213 /*
214 * See cyc2ns_read_*() for details; replicated in order to avoid
215 * an extra few instructions that came with the abstraction.
216 * Notable, it allows us to only do the __count and tail update
217 * dance when its actually needed.
218 */
219
569d6557 220 preempt_disable_notrace();
20d1c86a
PZ
221 data = this_cpu_read(cyc2ns.head);
222 tail = this_cpu_read(cyc2ns.tail);
223
224 if (likely(data == tail)) {
225 ns = data->cyc2ns_offset;
b20112ed 226 ns += mul_u64_u32_shr(cyc, data->cyc2ns_mul, data->cyc2ns_shift);
20d1c86a
PZ
227 } else {
228 data->__count++;
229
230 barrier();
231
232 ns = data->cyc2ns_offset;
b20112ed 233 ns += mul_u64_u32_shr(cyc, data->cyc2ns_mul, data->cyc2ns_shift);
20d1c86a
PZ
234
235 barrier();
236
237 if (!--data->__count)
238 this_cpu_write(cyc2ns.tail, data);
239 }
569d6557 240 preempt_enable_notrace();
20d1c86a 241
57c67da2
PZ
242 return ns;
243}
244
aa297292 245static void set_cyc2ns_scale(unsigned long khz, int cpu)
57c67da2 246{
20d1c86a
PZ
247 unsigned long long tsc_now, ns_now;
248 struct cyc2ns_data *data;
249 unsigned long flags;
57c67da2
PZ
250
251 local_irq_save(flags);
252 sched_clock_idle_sleep_event();
253
aa297292 254 if (!khz)
20d1c86a
PZ
255 goto done;
256
257 data = cyc2ns_write_begin(cpu);
57c67da2 258
4ea1636b 259 tsc_now = rdtsc();
57c67da2
PZ
260 ns_now = cycles_2_ns(tsc_now);
261
20d1c86a
PZ
262 /*
263 * Compute a new multiplier as per the above comment and ensure our
264 * time function is continuous; see the comment near struct
265 * cyc2ns_data.
266 */
aa297292 267 clocks_calc_mult_shift(&data->cyc2ns_mul, &data->cyc2ns_shift, khz,
b20112ed
AH
268 NSEC_PER_MSEC, 0);
269
b9511cd7
AH
270 /*
271 * cyc2ns_shift is exported via arch_perf_update_userpage() where it is
272 * not expected to be greater than 31 due to the original published
273 * conversion algorithm shifting a 32-bit value (now specifies a 64-bit
274 * value) - refer perf_event_mmap_page documentation in perf_event.h.
275 */
276 if (data->cyc2ns_shift == 32) {
277 data->cyc2ns_shift = 31;
278 data->cyc2ns_mul >>= 1;
279 }
280
20d1c86a 281 data->cyc2ns_offset = ns_now -
b20112ed 282 mul_u64_u32_shr(tsc_now, data->cyc2ns_mul, data->cyc2ns_shift);
20d1c86a
PZ
283
284 cyc2ns_write_end(cpu, data);
57c67da2 285
20d1c86a 286done:
57c67da2
PZ
287 sched_clock_idle_wakeup_event(0);
288 local_irq_restore(flags);
289}
0ef95533
AK
290/*
291 * Scheduler clock - returns current time in nanosec units.
292 */
293u64 native_sched_clock(void)
294{
3bbfafb7
PZ
295 if (static_branch_likely(&__use_tsc)) {
296 u64 tsc_now = rdtsc();
297
298 /* return the value in ns */
299 return cycles_2_ns(tsc_now);
300 }
0ef95533
AK
301
302 /*
303 * Fall back to jiffies if there's no TSC available:
304 * ( But note that we still use it if the TSC is marked
305 * unstable. We do this because unlike Time Of Day,
306 * the scheduler clock tolerates small errors and it's
307 * very important for it to be as fast as the platform
3ad2f3fb 308 * can achieve it. )
0ef95533 309 */
0ef95533 310
3bbfafb7
PZ
311 /* No locking but a rare wrong value is not a big deal: */
312 return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
0ef95533
AK
313}
314
a94cab23
AK
315/*
316 * Generate a sched_clock if you already have a TSC value.
317 */
318u64 native_sched_clock_from_tsc(u64 tsc)
319{
320 return cycles_2_ns(tsc);
321}
322
0ef95533
AK
323/* We need to define a real function for sched_clock, to override the
324 weak default version */
325#ifdef CONFIG_PARAVIRT
326unsigned long long sched_clock(void)
327{
328 return paravirt_sched_clock();
329}
f94c8d11 330
698eff63 331bool using_native_sched_clock(void)
f94c8d11
PZ
332{
333 return pv_time_ops.sched_clock == native_sched_clock;
334}
0ef95533
AK
335#else
336unsigned long long
337sched_clock(void) __attribute__((alias("native_sched_clock")));
f94c8d11 338
698eff63 339bool using_native_sched_clock(void) { return true; }
0ef95533
AK
340#endif
341
342int check_tsc_unstable(void)
343{
344 return tsc_unstable;
345}
346EXPORT_SYMBOL_GPL(check_tsc_unstable);
347
348#ifdef CONFIG_X86_TSC
349int __init notsc_setup(char *str)
350{
c767a54b 351 pr_warn("Kernel compiled with CONFIG_X86_TSC, cannot disable TSC completely\n");
0ef95533
AK
352 tsc_disabled = 1;
353 return 1;
354}
355#else
356/*
357 * disable flag for tsc. Takes effect by clearing the TSC cpu flag
358 * in cpu/common.c
359 */
360int __init notsc_setup(char *str)
361{
362 setup_clear_cpu_cap(X86_FEATURE_TSC);
363 return 1;
364}
365#endif
366
367__setup("notsc", notsc_setup);
bfc0f594 368
e82b8e4e
VP
369static int no_sched_irq_time;
370
395628ef
AK
371static int __init tsc_setup(char *str)
372{
373 if (!strcmp(str, "reliable"))
374 tsc_clocksource_reliable = 1;
e82b8e4e
VP
375 if (!strncmp(str, "noirqtime", 9))
376 no_sched_irq_time = 1;
8309f86c
PZ
377 if (!strcmp(str, "unstable"))
378 mark_tsc_unstable("boot parameter");
395628ef
AK
379 return 1;
380}
381
382__setup("tsc=", tsc_setup);
383
bfc0f594
AK
384#define MAX_RETRIES 5
385#define SMI_TRESHOLD 50000
386
387/*
388 * Read TSC and the reference counters. Take care of SMI disturbance
389 */
827014be 390static u64 tsc_read_refs(u64 *p, int hpet)
bfc0f594
AK
391{
392 u64 t1, t2;
393 int i;
394
395 for (i = 0; i < MAX_RETRIES; i++) {
396 t1 = get_cycles();
397 if (hpet)
827014be 398 *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
bfc0f594 399 else
827014be 400 *p = acpi_pm_read_early();
bfc0f594
AK
401 t2 = get_cycles();
402 if ((t2 - t1) < SMI_TRESHOLD)
403 return t2;
404 }
405 return ULLONG_MAX;
406}
407
d683ef7a
TG
408/*
409 * Calculate the TSC frequency from HPET reference
bfc0f594 410 */
d683ef7a 411static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
bfc0f594 412{
d683ef7a 413 u64 tmp;
bfc0f594 414
d683ef7a
TG
415 if (hpet2 < hpet1)
416 hpet2 += 0x100000000ULL;
417 hpet2 -= hpet1;
418 tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
419 do_div(tmp, 1000000);
420 do_div(deltatsc, tmp);
421
422 return (unsigned long) deltatsc;
423}
424
425/*
426 * Calculate the TSC frequency from PMTimer reference
427 */
428static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
429{
430 u64 tmp;
bfc0f594 431
d683ef7a
TG
432 if (!pm1 && !pm2)
433 return ULONG_MAX;
434
435 if (pm2 < pm1)
436 pm2 += (u64)ACPI_PM_OVRRUN;
437 pm2 -= pm1;
438 tmp = pm2 * 1000000000LL;
439 do_div(tmp, PMTMR_TICKS_PER_SEC);
440 do_div(deltatsc, tmp);
441
442 return (unsigned long) deltatsc;
443}
444
a977c400 445#define CAL_MS 10
b7743970 446#define CAL_LATCH (PIT_TICK_RATE / (1000 / CAL_MS))
a977c400
TG
447#define CAL_PIT_LOOPS 1000
448
449#define CAL2_MS 50
b7743970 450#define CAL2_LATCH (PIT_TICK_RATE / (1000 / CAL2_MS))
a977c400
TG
451#define CAL2_PIT_LOOPS 5000
452
cce3e057 453
ec0c15af
LT
454/*
455 * Try to calibrate the TSC against the Programmable
456 * Interrupt Timer and return the frequency of the TSC
457 * in kHz.
458 *
459 * Return ULONG_MAX on failure to calibrate.
460 */
a977c400 461static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
ec0c15af
LT
462{
463 u64 tsc, t1, t2, delta;
464 unsigned long tscmin, tscmax;
465 int pitcnt;
466
467 /* Set the Gate high, disable speaker */
468 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
469
470 /*
471 * Setup CTC channel 2* for mode 0, (interrupt on terminal
472 * count mode), binary count. Set the latch register to 50ms
473 * (LSB then MSB) to begin countdown.
474 */
475 outb(0xb0, 0x43);
a977c400
TG
476 outb(latch & 0xff, 0x42);
477 outb(latch >> 8, 0x42);
ec0c15af
LT
478
479 tsc = t1 = t2 = get_cycles();
480
481 pitcnt = 0;
482 tscmax = 0;
483 tscmin = ULONG_MAX;
484 while ((inb(0x61) & 0x20) == 0) {
485 t2 = get_cycles();
486 delta = t2 - tsc;
487 tsc = t2;
488 if ((unsigned long) delta < tscmin)
489 tscmin = (unsigned int) delta;
490 if ((unsigned long) delta > tscmax)
491 tscmax = (unsigned int) delta;
492 pitcnt++;
493 }
494
495 /*
496 * Sanity checks:
497 *
a977c400 498 * If we were not able to read the PIT more than loopmin
ec0c15af
LT
499 * times, then we have been hit by a massive SMI
500 *
501 * If the maximum is 10 times larger than the minimum,
502 * then we got hit by an SMI as well.
503 */
a977c400 504 if (pitcnt < loopmin || tscmax > 10 * tscmin)
ec0c15af
LT
505 return ULONG_MAX;
506
507 /* Calculate the PIT value */
508 delta = t2 - t1;
a977c400 509 do_div(delta, ms);
ec0c15af
LT
510 return delta;
511}
512
6ac40ed0
LT
513/*
514 * This reads the current MSB of the PIT counter, and
515 * checks if we are running on sufficiently fast and
516 * non-virtualized hardware.
517 *
518 * Our expectations are:
519 *
520 * - the PIT is running at roughly 1.19MHz
521 *
522 * - each IO is going to take about 1us on real hardware,
523 * but we allow it to be much faster (by a factor of 10) or
524 * _slightly_ slower (ie we allow up to a 2us read+counter
525 * update - anything else implies a unacceptably slow CPU
526 * or PIT for the fast calibration to work.
527 *
528 * - with 256 PIT ticks to read the value, we have 214us to
529 * see the same MSB (and overhead like doing a single TSC
530 * read per MSB value etc).
531 *
532 * - We're doing 2 reads per loop (LSB, MSB), and we expect
533 * them each to take about a microsecond on real hardware.
534 * So we expect a count value of around 100. But we'll be
535 * generous, and accept anything over 50.
536 *
537 * - if the PIT is stuck, and we see *many* more reads, we
538 * return early (and the next caller of pit_expect_msb()
539 * then consider it a failure when they don't see the
540 * next expected value).
541 *
542 * These expectations mean that we know that we have seen the
543 * transition from one expected value to another with a fairly
544 * high accuracy, and we didn't miss any events. We can thus
545 * use the TSC value at the transitions to calculate a pretty
546 * good value for the TSC frequencty.
547 */
b6e61eef
LT
548static inline int pit_verify_msb(unsigned char val)
549{
550 /* Ignore LSB */
551 inb(0x42);
552 return inb(0x42) == val;
553}
554
9e8912e0 555static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
6ac40ed0 556{
9e8912e0 557 int count;
68f30fbe 558 u64 tsc = 0, prev_tsc = 0;
bfc0f594 559
6ac40ed0 560 for (count = 0; count < 50000; count++) {
b6e61eef 561 if (!pit_verify_msb(val))
6ac40ed0 562 break;
68f30fbe 563 prev_tsc = tsc;
9e8912e0 564 tsc = get_cycles();
6ac40ed0 565 }
68f30fbe 566 *deltap = get_cycles() - prev_tsc;
9e8912e0
LT
567 *tscp = tsc;
568
569 /*
570 * We require _some_ success, but the quality control
571 * will be based on the error terms on the TSC values.
572 */
573 return count > 5;
6ac40ed0
LT
574}
575
576/*
9e8912e0
LT
577 * How many MSB values do we want to see? We aim for
578 * a maximum error rate of 500ppm (in practice the
579 * real error is much smaller), but refuse to spend
68f30fbe 580 * more than 50ms on it.
6ac40ed0 581 */
68f30fbe 582#define MAX_QUICK_PIT_MS 50
9e8912e0 583#define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
bfc0f594 584
6ac40ed0
LT
585static unsigned long quick_pit_calibrate(void)
586{
9e8912e0
LT
587 int i;
588 u64 tsc, delta;
589 unsigned long d1, d2;
590
6ac40ed0 591 /* Set the Gate high, disable speaker */
bfc0f594
AK
592 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
593
6ac40ed0
LT
594 /*
595 * Counter 2, mode 0 (one-shot), binary count
596 *
597 * NOTE! Mode 2 decrements by two (and then the
598 * output is flipped each time, giving the same
599 * final output frequency as a decrement-by-one),
600 * so mode 0 is much better when looking at the
601 * individual counts.
602 */
bfc0f594 603 outb(0xb0, 0x43);
bfc0f594 604
6ac40ed0
LT
605 /* Start at 0xffff */
606 outb(0xff, 0x42);
607 outb(0xff, 0x42);
608
a6a80e1d
LT
609 /*
610 * The PIT starts counting at the next edge, so we
611 * need to delay for a microsecond. The easiest way
612 * to do that is to just read back the 16-bit counter
613 * once from the PIT.
614 */
b6e61eef 615 pit_verify_msb(0);
a6a80e1d 616
9e8912e0
LT
617 if (pit_expect_msb(0xff, &tsc, &d1)) {
618 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
619 if (!pit_expect_msb(0xff-i, &delta, &d2))
620 break;
621
5aac644a
AH
622 delta -= tsc;
623
624 /*
625 * Extrapolate the error and fail fast if the error will
626 * never be below 500 ppm.
627 */
628 if (i == 1 &&
629 d1 + d2 >= (delta * MAX_QUICK_PIT_ITERATIONS) >> 11)
630 return 0;
631
9e8912e0
LT
632 /*
633 * Iterate until the error is less than 500 ppm
634 */
b6e61eef
LT
635 if (d1+d2 >= delta >> 11)
636 continue;
637
638 /*
639 * Check the PIT one more time to verify that
640 * all TSC reads were stable wrt the PIT.
641 *
642 * This also guarantees serialization of the
643 * last cycle read ('d2') in pit_expect_msb.
644 */
645 if (!pit_verify_msb(0xfe - i))
646 break;
647 goto success;
6ac40ed0 648 }
6ac40ed0 649 }
52045217 650 pr_info("Fast TSC calibration failed\n");
6ac40ed0 651 return 0;
9e8912e0
LT
652
653success:
654 /*
655 * Ok, if we get here, then we've seen the
656 * MSB of the PIT decrement 'i' times, and the
657 * error has shrunk to less than 500 ppm.
658 *
659 * As a result, we can depend on there not being
660 * any odd delays anywhere, and the TSC reads are
68f30fbe 661 * reliable (within the error).
9e8912e0
LT
662 *
663 * kHz = ticks / time-in-seconds / 1000;
664 * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
665 * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
666 */
9e8912e0
LT
667 delta *= PIT_TICK_RATE;
668 do_div(delta, i*256*1000);
c767a54b 669 pr_info("Fast TSC calibration using PIT\n");
9e8912e0 670 return delta;
6ac40ed0 671}
ec0c15af 672
bfc0f594 673/**
aa297292
LB
674 * native_calibrate_tsc
675 * Determine TSC frequency via CPUID, else return 0.
bfc0f594 676 */
e93ef949 677unsigned long native_calibrate_tsc(void)
aa297292
LB
678{
679 unsigned int eax_denominator, ebx_numerator, ecx_hz, edx;
680 unsigned int crystal_khz;
681
682 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
683 return 0;
684
685 if (boot_cpu_data.cpuid_level < 0x15)
686 return 0;
687
688 eax_denominator = ebx_numerator = ecx_hz = edx = 0;
689
690 /* CPUID 15H TSC/Crystal ratio, plus optionally Crystal Hz */
691 cpuid(0x15, &eax_denominator, &ebx_numerator, &ecx_hz, &edx);
692
693 if (ebx_numerator == 0 || eax_denominator == 0)
694 return 0;
695
696 crystal_khz = ecx_hz / 1000;
697
698 if (crystal_khz == 0) {
699 switch (boot_cpu_data.x86_model) {
655e52d2
PB
700 case INTEL_FAM6_SKYLAKE_MOBILE:
701 case INTEL_FAM6_SKYLAKE_DESKTOP:
6baf3d61
PB
702 case INTEL_FAM6_KABYLAKE_MOBILE:
703 case INTEL_FAM6_KABYLAKE_DESKTOP:
ff4c8663
LB
704 crystal_khz = 24000; /* 24.0 MHz */
705 break;
6baf3d61 706 case INTEL_FAM6_SKYLAKE_X:
695085b4 707 case INTEL_FAM6_ATOM_DENVERTON:
6baf3d61
PB
708 crystal_khz = 25000; /* 25.0 MHz */
709 break;
655e52d2 710 case INTEL_FAM6_ATOM_GOLDMONT:
ff4c8663
LB
711 crystal_khz = 19200; /* 19.2 MHz */
712 break;
aa297292
LB
713 }
714 }
715
4ca4df0b
BG
716 /*
717 * TSC frequency determined by CPUID is a "hardware reported"
718 * frequency and is the most accurate one so far we have. This
719 * is considered a known frequency.
720 */
721 setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ);
722
4635fdc6
BG
723 /*
724 * For Atom SoCs TSC is the only reliable clocksource.
725 * Mark TSC reliable so no watchdog on it.
726 */
727 if (boot_cpu_data.x86_model == INTEL_FAM6_ATOM_GOLDMONT)
728 setup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE);
729
aa297292
LB
730 return crystal_khz * ebx_numerator / eax_denominator;
731}
732
733static unsigned long cpu_khz_from_cpuid(void)
734{
735 unsigned int eax_base_mhz, ebx_max_mhz, ecx_bus_mhz, edx;
736
737 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
738 return 0;
739
740 if (boot_cpu_data.cpuid_level < 0x16)
741 return 0;
742
743 eax_base_mhz = ebx_max_mhz = ecx_bus_mhz = edx = 0;
744
745 cpuid(0x16, &eax_base_mhz, &ebx_max_mhz, &ecx_bus_mhz, &edx);
746
747 return eax_base_mhz * 1000;
748}
749
750/**
751 * native_calibrate_cpu - calibrate the cpu on boot
752 */
753unsigned long native_calibrate_cpu(void)
bfc0f594 754{
827014be 755 u64 tsc1, tsc2, delta, ref1, ref2;
fbb16e24 756 unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
2d826404 757 unsigned long flags, latch, ms, fast_calibrate;
a977c400 758 int hpet = is_hpet_enabled(), i, loopmin;
bfc0f594 759
aa297292
LB
760 fast_calibrate = cpu_khz_from_cpuid();
761 if (fast_calibrate)
762 return fast_calibrate;
763
02c0cd2d 764 fast_calibrate = cpu_khz_from_msr();
5f0e0309 765 if (fast_calibrate)
7da7c156 766 return fast_calibrate;
7da7c156 767
6ac40ed0
LT
768 local_irq_save(flags);
769 fast_calibrate = quick_pit_calibrate();
bfc0f594 770 local_irq_restore(flags);
6ac40ed0
LT
771 if (fast_calibrate)
772 return fast_calibrate;
bfc0f594 773
fbb16e24
TG
774 /*
775 * Run 5 calibration loops to get the lowest frequency value
776 * (the best estimate). We use two different calibration modes
777 * here:
778 *
779 * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
780 * load a timeout of 50ms. We read the time right after we
781 * started the timer and wait until the PIT count down reaches
782 * zero. In each wait loop iteration we read the TSC and check
783 * the delta to the previous read. We keep track of the min
784 * and max values of that delta. The delta is mostly defined
785 * by the IO time of the PIT access, so we can detect when a
0d2eb44f 786 * SMI/SMM disturbance happened between the two reads. If the
fbb16e24
TG
787 * maximum time is significantly larger than the minimum time,
788 * then we discard the result and have another try.
789 *
790 * 2) Reference counter. If available we use the HPET or the
791 * PMTIMER as a reference to check the sanity of that value.
792 * We use separate TSC readouts and check inside of the
793 * reference read for a SMI/SMM disturbance. We dicard
794 * disturbed values here as well. We do that around the PIT
795 * calibration delay loop as we have to wait for a certain
796 * amount of time anyway.
797 */
a977c400
TG
798
799 /* Preset PIT loop values */
800 latch = CAL_LATCH;
801 ms = CAL_MS;
802 loopmin = CAL_PIT_LOOPS;
803
804 for (i = 0; i < 3; i++) {
ec0c15af 805 unsigned long tsc_pit_khz;
fbb16e24
TG
806
807 /*
808 * Read the start value and the reference count of
ec0c15af
LT
809 * hpet/pmtimer when available. Then do the PIT
810 * calibration, which will take at least 50ms, and
811 * read the end value.
fbb16e24 812 */
ec0c15af 813 local_irq_save(flags);
827014be 814 tsc1 = tsc_read_refs(&ref1, hpet);
a977c400 815 tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
827014be 816 tsc2 = tsc_read_refs(&ref2, hpet);
fbb16e24
TG
817 local_irq_restore(flags);
818
ec0c15af
LT
819 /* Pick the lowest PIT TSC calibration so far */
820 tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
fbb16e24
TG
821
822 /* hpet or pmtimer available ? */
62627bec 823 if (ref1 == ref2)
fbb16e24
TG
824 continue;
825
826 /* Check, whether the sampling was disturbed by an SMI */
827 if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
828 continue;
829
830 tsc2 = (tsc2 - tsc1) * 1000000LL;
d683ef7a 831 if (hpet)
827014be 832 tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
d683ef7a 833 else
827014be 834 tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
fbb16e24 835
fbb16e24 836 tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
a977c400
TG
837
838 /* Check the reference deviation */
839 delta = ((u64) tsc_pit_min) * 100;
840 do_div(delta, tsc_ref_min);
841
842 /*
843 * If both calibration results are inside a 10% window
844 * then we can be sure, that the calibration
845 * succeeded. We break out of the loop right away. We
846 * use the reference value, as it is more precise.
847 */
848 if (delta >= 90 && delta <= 110) {
c767a54b
JP
849 pr_info("PIT calibration matches %s. %d loops\n",
850 hpet ? "HPET" : "PMTIMER", i + 1);
a977c400 851 return tsc_ref_min;
fbb16e24
TG
852 }
853
a977c400
TG
854 /*
855 * Check whether PIT failed more than once. This
856 * happens in virtualized environments. We need to
857 * give the virtual PC a slightly longer timeframe for
858 * the HPET/PMTIMER to make the result precise.
859 */
860 if (i == 1 && tsc_pit_min == ULONG_MAX) {
861 latch = CAL2_LATCH;
862 ms = CAL2_MS;
863 loopmin = CAL2_PIT_LOOPS;
864 }
fbb16e24 865 }
bfc0f594
AK
866
867 /*
fbb16e24 868 * Now check the results.
bfc0f594 869 */
fbb16e24
TG
870 if (tsc_pit_min == ULONG_MAX) {
871 /* PIT gave no useful value */
c767a54b 872 pr_warn("Unable to calibrate against PIT\n");
fbb16e24
TG
873
874 /* We don't have an alternative source, disable TSC */
827014be 875 if (!hpet && !ref1 && !ref2) {
c767a54b 876 pr_notice("No reference (HPET/PMTIMER) available\n");
fbb16e24
TG
877 return 0;
878 }
879
880 /* The alternative source failed as well, disable TSC */
881 if (tsc_ref_min == ULONG_MAX) {
c767a54b 882 pr_warn("HPET/PMTIMER calibration failed\n");
fbb16e24
TG
883 return 0;
884 }
885
886 /* Use the alternative source */
c767a54b
JP
887 pr_info("using %s reference calibration\n",
888 hpet ? "HPET" : "PMTIMER");
fbb16e24
TG
889
890 return tsc_ref_min;
891 }
bfc0f594 892
fbb16e24 893 /* We don't have an alternative source, use the PIT calibration value */
827014be 894 if (!hpet && !ref1 && !ref2) {
c767a54b 895 pr_info("Using PIT calibration value\n");
fbb16e24 896 return tsc_pit_min;
bfc0f594
AK
897 }
898
fbb16e24
TG
899 /* The alternative source failed, use the PIT calibration value */
900 if (tsc_ref_min == ULONG_MAX) {
c767a54b 901 pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
fbb16e24 902 return tsc_pit_min;
bfc0f594
AK
903 }
904
fbb16e24
TG
905 /*
906 * The calibration values differ too much. In doubt, we use
907 * the PIT value as we know that there are PMTIMERs around
a977c400 908 * running at double speed. At least we let the user know:
fbb16e24 909 */
c767a54b
JP
910 pr_warn("PIT calibration deviates from %s: %lu %lu\n",
911 hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
912 pr_info("Using PIT calibration value\n");
fbb16e24 913 return tsc_pit_min;
bfc0f594
AK
914}
915
bfc0f594
AK
916int recalibrate_cpu_khz(void)
917{
918#ifndef CONFIG_SMP
919 unsigned long cpu_khz_old = cpu_khz;
920
eff4677e 921 if (!boot_cpu_has(X86_FEATURE_TSC))
bfc0f594 922 return -ENODEV;
eff4677e 923
aa297292 924 cpu_khz = x86_platform.calibrate_cpu();
eff4677e 925 tsc_khz = x86_platform.calibrate_tsc();
aa297292
LB
926 if (tsc_khz == 0)
927 tsc_khz = cpu_khz;
ff4c8663
LB
928 else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
929 cpu_khz = tsc_khz;
eff4677e
BP
930 cpu_data(0).loops_per_jiffy = cpufreq_scale(cpu_data(0).loops_per_jiffy,
931 cpu_khz_old, cpu_khz);
932
933 return 0;
bfc0f594
AK
934#else
935 return -ENODEV;
936#endif
937}
938
939EXPORT_SYMBOL(recalibrate_cpu_khz);
940
2dbe06fa 941
cd7240c0
SS
942static unsigned long long cyc2ns_suspend;
943
b74f05d6 944void tsc_save_sched_clock_state(void)
cd7240c0 945{
35af99e6 946 if (!sched_clock_stable())
cd7240c0
SS
947 return;
948
949 cyc2ns_suspend = sched_clock();
950}
951
952/*
953 * Even on processors with invariant TSC, TSC gets reset in some the
954 * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
955 * arbitrary value (still sync'd across cpu's) during resume from such sleep
956 * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
957 * that sched_clock() continues from the point where it was left off during
958 * suspend.
959 */
b74f05d6 960void tsc_restore_sched_clock_state(void)
cd7240c0
SS
961{
962 unsigned long long offset;
963 unsigned long flags;
964 int cpu;
965
35af99e6 966 if (!sched_clock_stable())
cd7240c0
SS
967 return;
968
969 local_irq_save(flags);
970
20d1c86a 971 /*
6a6256f9 972 * We're coming out of suspend, there's no concurrency yet; don't
20d1c86a
PZ
973 * bother being nice about the RCU stuff, just write to both
974 * data fields.
975 */
976
977 this_cpu_write(cyc2ns.data[0].cyc2ns_offset, 0);
978 this_cpu_write(cyc2ns.data[1].cyc2ns_offset, 0);
979
cd7240c0
SS
980 offset = cyc2ns_suspend - sched_clock();
981
20d1c86a
PZ
982 for_each_possible_cpu(cpu) {
983 per_cpu(cyc2ns.data[0].cyc2ns_offset, cpu) = offset;
984 per_cpu(cyc2ns.data[1].cyc2ns_offset, cpu) = offset;
985 }
cd7240c0
SS
986
987 local_irq_restore(flags);
988}
989
2dbe06fa
AK
990#ifdef CONFIG_CPU_FREQ
991
992/* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
993 * changes.
994 *
995 * RED-PEN: On SMP we assume all CPUs run with the same frequency. It's
996 * not that important because current Opteron setups do not support
997 * scaling on SMP anyroads.
998 *
999 * Should fix up last_tsc too. Currently gettimeofday in the
1000 * first tick after the change will be slightly wrong.
1001 */
1002
1003static unsigned int ref_freq;
1004static unsigned long loops_per_jiffy_ref;
1005static unsigned long tsc_khz_ref;
1006
1007static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
1008 void *data)
1009{
1010 struct cpufreq_freqs *freq = data;
931db6a3 1011 unsigned long *lpj;
2dbe06fa 1012
931db6a3 1013 lpj = &boot_cpu_data.loops_per_jiffy;
2dbe06fa 1014#ifdef CONFIG_SMP
931db6a3 1015 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
2dbe06fa 1016 lpj = &cpu_data(freq->cpu).loops_per_jiffy;
2dbe06fa
AK
1017#endif
1018
1019 if (!ref_freq) {
1020 ref_freq = freq->old;
1021 loops_per_jiffy_ref = *lpj;
1022 tsc_khz_ref = tsc_khz;
1023 }
1024 if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
0b443ead 1025 (val == CPUFREQ_POSTCHANGE && freq->old > freq->new)) {
878f4f53 1026 *lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
2dbe06fa
AK
1027
1028 tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
1029 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
1030 mark_tsc_unstable("cpufreq changes");
2dbe06fa 1031
3896c329
PZ
1032 set_cyc2ns_scale(tsc_khz, freq->cpu);
1033 }
2dbe06fa
AK
1034
1035 return 0;
1036}
1037
1038static struct notifier_block time_cpufreq_notifier_block = {
1039 .notifier_call = time_cpufreq_notifier
1040};
1041
a841cca7 1042static int __init cpufreq_register_tsc_scaling(void)
2dbe06fa 1043{
59e21e3d 1044 if (!boot_cpu_has(X86_FEATURE_TSC))
060700b5
LT
1045 return 0;
1046 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1047 return 0;
2dbe06fa
AK
1048 cpufreq_register_notifier(&time_cpufreq_notifier_block,
1049 CPUFREQ_TRANSITION_NOTIFIER);
1050 return 0;
1051}
1052
a841cca7 1053core_initcall(cpufreq_register_tsc_scaling);
2dbe06fa
AK
1054
1055#endif /* CONFIG_CPU_FREQ */
8fbbc4b4 1056
f9677e0f
CH
1057#define ART_CPUID_LEAF (0x15)
1058#define ART_MIN_DENOMINATOR (1)
1059
1060
1061/*
1062 * If ART is present detect the numerator:denominator to convert to TSC
1063 */
1064static void detect_art(void)
1065{
1066 unsigned int unused[2];
1067
1068 if (boot_cpu_data.cpuid_level < ART_CPUID_LEAF)
1069 return;
1070
7b3d2f6e 1071 /* Don't enable ART in a VM, non-stop TSC and TSC_ADJUST required */
f9677e0f
CH
1072 if (boot_cpu_has(X86_FEATURE_HYPERVISOR) ||
1073 !boot_cpu_has(X86_FEATURE_NONSTOP_TSC) ||
7b3d2f6e 1074 !boot_cpu_has(X86_FEATURE_TSC_ADJUST))
f9677e0f
CH
1075 return;
1076
7b3d2f6e
TG
1077 cpuid(ART_CPUID_LEAF, &art_to_tsc_denominator,
1078 &art_to_tsc_numerator, unused, unused+1);
1079
1080 if (art_to_tsc_denominator < ART_MIN_DENOMINATOR)
f9677e0f
CH
1081 return;
1082
7b3d2f6e
TG
1083 rdmsrl(MSR_IA32_TSC_ADJUST, art_to_tsc_offset);
1084
f9677e0f
CH
1085 /* Make this sticky over multiple CPU init calls */
1086 setup_force_cpu_cap(X86_FEATURE_ART);
1087}
1088
1089
8fbbc4b4
AK
1090/* clocksource code */
1091
1092static struct clocksource clocksource_tsc;
1093
6a369583
TG
1094static void tsc_resume(struct clocksource *cs)
1095{
1096 tsc_verify_tsc_adjust(true);
1097}
1098
8fbbc4b4 1099/*
09ec5442 1100 * We used to compare the TSC to the cycle_last value in the clocksource
8fbbc4b4
AK
1101 * structure to avoid a nasty time-warp. This can be observed in a
1102 * very small window right after one CPU updated cycle_last under
1103 * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
1104 * is smaller than the cycle_last reference value due to a TSC which
1105 * is slighty behind. This delta is nowhere else observable, but in
1106 * that case it results in a forward time jump in the range of hours
1107 * due to the unsigned delta calculation of the time keeping core
1108 * code, which is necessary to support wrapping clocksources like pm
1109 * timer.
09ec5442
TG
1110 *
1111 * This sanity check is now done in the core timekeeping code.
1112 * checking the result of read_tsc() - cycle_last for being negative.
1113 * That works because CLOCKSOURCE_MASK(64) does not mask out any bit.
8fbbc4b4 1114 */
a5a1d1c2 1115static u64 read_tsc(struct clocksource *cs)
8fbbc4b4 1116{
a5a1d1c2 1117 return (u64)rdtsc_ordered();
1be39679
MS
1118}
1119
12907fbb
TG
1120static void tsc_cs_mark_unstable(struct clocksource *cs)
1121{
1122 if (tsc_unstable)
1123 return;
f94c8d11 1124
12907fbb 1125 tsc_unstable = 1;
f94c8d11
PZ
1126 if (using_native_sched_clock())
1127 clear_sched_clock_stable();
12907fbb
TG
1128 disable_sched_clock_irqtime();
1129 pr_info("Marking TSC unstable due to clocksource watchdog\n");
1130}
1131
09ec5442
TG
1132/*
1133 * .mask MUST be CLOCKSOURCE_MASK(64). See comment above read_tsc()
1134 */
8fbbc4b4
AK
1135static struct clocksource clocksource_tsc = {
1136 .name = "tsc",
1137 .rating = 300,
1138 .read = read_tsc,
1139 .mask = CLOCKSOURCE_MASK(64),
8fbbc4b4
AK
1140 .flags = CLOCK_SOURCE_IS_CONTINUOUS |
1141 CLOCK_SOURCE_MUST_VERIFY,
98d0ac38 1142 .archdata = { .vclock_mode = VCLOCK_TSC },
6a369583 1143 .resume = tsc_resume,
12907fbb 1144 .mark_unstable = tsc_cs_mark_unstable,
8fbbc4b4
AK
1145};
1146
1147void mark_tsc_unstable(char *reason)
1148{
f94c8d11
PZ
1149 if (tsc_unstable)
1150 return;
1151
1152 tsc_unstable = 1;
1153 if (using_native_sched_clock())
35af99e6 1154 clear_sched_clock_stable();
f94c8d11
PZ
1155 disable_sched_clock_irqtime();
1156 pr_info("Marking TSC unstable due to %s\n", reason);
1157 /* Change only the rating, when not registered */
1158 if (clocksource_tsc.mult) {
1159 clocksource_mark_unstable(&clocksource_tsc);
1160 } else {
1161 clocksource_tsc.flags |= CLOCK_SOURCE_UNSTABLE;
1162 clocksource_tsc.rating = 0;
8fbbc4b4
AK
1163 }
1164}
1165
1166EXPORT_SYMBOL_GPL(mark_tsc_unstable);
1167
395628ef
AK
1168static void __init check_system_tsc_reliable(void)
1169{
03da3ff1
DW
1170#if defined(CONFIG_MGEODEGX1) || defined(CONFIG_MGEODE_LX) || defined(CONFIG_X86_GENERIC)
1171 if (is_geode_lx()) {
1172 /* RTSC counts during suspend */
8fbbc4b4 1173#define RTSC_SUSP 0x100
03da3ff1 1174 unsigned long res_low, res_high;
8fbbc4b4 1175
03da3ff1
DW
1176 rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
1177 /* Geode_LX - the OLPC CPU has a very reliable TSC */
1178 if (res_low & RTSC_SUSP)
1179 tsc_clocksource_reliable = 1;
1180 }
8fbbc4b4 1181#endif
395628ef
AK
1182 if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
1183 tsc_clocksource_reliable = 1;
1184}
8fbbc4b4
AK
1185
1186/*
1187 * Make an educated guess if the TSC is trustworthy and synchronized
1188 * over all CPUs.
1189 */
148f9bb8 1190int unsynchronized_tsc(void)
8fbbc4b4 1191{
59e21e3d 1192 if (!boot_cpu_has(X86_FEATURE_TSC) || tsc_unstable)
8fbbc4b4
AK
1193 return 1;
1194
3e5095d1 1195#ifdef CONFIG_SMP
8fbbc4b4
AK
1196 if (apic_is_clustered_box())
1197 return 1;
1198#endif
1199
1200 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1201 return 0;
d3b8f889 1202
1203 if (tsc_clocksource_reliable)
1204 return 0;
8fbbc4b4
AK
1205 /*
1206 * Intel systems are normally all synchronized.
1207 * Exceptions must mark TSC as unstable:
1208 */
1209 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
1210 /* assume multi socket systems are not synchronized: */
1211 if (num_possible_cpus() > 1)
d3b8f889 1212 return 1;
8fbbc4b4
AK
1213 }
1214
d3b8f889 1215 return 0;
8fbbc4b4
AK
1216}
1217
f9677e0f
CH
1218/*
1219 * Convert ART to TSC given numerator/denominator found in detect_art()
1220 */
a5a1d1c2 1221struct system_counterval_t convert_art_to_tsc(u64 art)
f9677e0f
CH
1222{
1223 u64 tmp, res, rem;
1224
1225 rem = do_div(art, art_to_tsc_denominator);
1226
1227 res = art * art_to_tsc_numerator;
1228 tmp = rem * art_to_tsc_numerator;
1229
1230 do_div(tmp, art_to_tsc_denominator);
1231 res += tmp + art_to_tsc_offset;
1232
1233 return (struct system_counterval_t) {.cs = art_related_clocksource,
1234 .cycles = res};
1235}
1236EXPORT_SYMBOL(convert_art_to_tsc);
08ec0c58
JS
1237
1238static void tsc_refine_calibration_work(struct work_struct *work);
1239static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
1240/**
1241 * tsc_refine_calibration_work - Further refine tsc freq calibration
1242 * @work - ignored.
1243 *
1244 * This functions uses delayed work over a period of a
1245 * second to further refine the TSC freq value. Since this is
1246 * timer based, instead of loop based, we don't block the boot
1247 * process while this longer calibration is done.
1248 *
0d2eb44f 1249 * If there are any calibration anomalies (too many SMIs, etc),
08ec0c58
JS
1250 * or the refined calibration is off by 1% of the fast early
1251 * calibration, we throw out the new calibration and use the
1252 * early calibration.
1253 */
1254static void tsc_refine_calibration_work(struct work_struct *work)
1255{
1256 static u64 tsc_start = -1, ref_start;
1257 static int hpet;
1258 u64 tsc_stop, ref_stop, delta;
1259 unsigned long freq;
1260
1261 /* Don't bother refining TSC on unstable systems */
1262 if (check_tsc_unstable())
1263 goto out;
1264
1265 /*
1266 * Since the work is started early in boot, we may be
1267 * delayed the first time we expire. So set the workqueue
1268 * again once we know timers are working.
1269 */
1270 if (tsc_start == -1) {
1271 /*
1272 * Only set hpet once, to avoid mixing hardware
1273 * if the hpet becomes enabled later.
1274 */
1275 hpet = is_hpet_enabled();
1276 schedule_delayed_work(&tsc_irqwork, HZ);
1277 tsc_start = tsc_read_refs(&ref_start, hpet);
1278 return;
1279 }
1280
1281 tsc_stop = tsc_read_refs(&ref_stop, hpet);
1282
1283 /* hpet or pmtimer available ? */
62627bec 1284 if (ref_start == ref_stop)
08ec0c58
JS
1285 goto out;
1286
1287 /* Check, whether the sampling was disturbed by an SMI */
1288 if (tsc_start == ULLONG_MAX || tsc_stop == ULLONG_MAX)
1289 goto out;
1290
1291 delta = tsc_stop - tsc_start;
1292 delta *= 1000000LL;
1293 if (hpet)
1294 freq = calc_hpet_ref(delta, ref_start, ref_stop);
1295 else
1296 freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
1297
1298 /* Make sure we're within 1% */
1299 if (abs(tsc_khz - freq) > tsc_khz/100)
1300 goto out;
1301
1302 tsc_khz = freq;
c767a54b
JP
1303 pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
1304 (unsigned long)tsc_khz / 1000,
1305 (unsigned long)tsc_khz % 1000);
08ec0c58 1306
6731b0d6
NS
1307 /* Inform the TSC deadline clockevent devices about the recalibration */
1308 lapic_update_tsc_freq();
1309
08ec0c58 1310out:
f9677e0f
CH
1311 if (boot_cpu_has(X86_FEATURE_ART))
1312 art_related_clocksource = &clocksource_tsc;
08ec0c58
JS
1313 clocksource_register_khz(&clocksource_tsc, tsc_khz);
1314}
1315
1316
1317static int __init init_tsc_clocksource(void)
8fbbc4b4 1318{
59e21e3d 1319 if (!boot_cpu_has(X86_FEATURE_TSC) || tsc_disabled > 0 || !tsc_khz)
a8760eca
TG
1320 return 0;
1321
395628ef
AK
1322 if (tsc_clocksource_reliable)
1323 clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
8fbbc4b4
AK
1324 /* lower the rating if we already know its unstable: */
1325 if (check_tsc_unstable()) {
1326 clocksource_tsc.rating = 0;
1327 clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
1328 }
57779dc2 1329
82f9c080
FT
1330 if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
1331 clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
1332
57779dc2 1333 /*
47c95a46
BG
1334 * When TSC frequency is known (retrieved via MSR or CPUID), we skip
1335 * the refined calibration and directly register it as a clocksource.
57779dc2 1336 */
984feceb 1337 if (boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ)) {
44fee88c
PZ
1338 if (boot_cpu_has(X86_FEATURE_ART))
1339 art_related_clocksource = &clocksource_tsc;
57779dc2
AK
1340 clocksource_register_khz(&clocksource_tsc, tsc_khz);
1341 return 0;
1342 }
1343
08ec0c58
JS
1344 schedule_delayed_work(&tsc_irqwork, 0);
1345 return 0;
8fbbc4b4 1346}
08ec0c58
JS
1347/*
1348 * We use device_initcall here, to ensure we run after the hpet
1349 * is fully initialized, which may occur at fs_initcall time.
1350 */
1351device_initcall(init_tsc_clocksource);
8fbbc4b4
AK
1352
1353void __init tsc_init(void)
1354{
1355 u64 lpj;
1356 int cpu;
1357
59e21e3d 1358 if (!boot_cpu_has(X86_FEATURE_TSC)) {
b47dcbdc 1359 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
8fbbc4b4 1360 return;
b47dcbdc 1361 }
8fbbc4b4 1362
aa297292 1363 cpu_khz = x86_platform.calibrate_cpu();
2d826404 1364 tsc_khz = x86_platform.calibrate_tsc();
ff4c8663
LB
1365
1366 /*
1367 * Trust non-zero tsc_khz as authorative,
1368 * and use it to sanity check cpu_khz,
1369 * which will be off if system timer is off.
1370 */
aa297292
LB
1371 if (tsc_khz == 0)
1372 tsc_khz = cpu_khz;
ff4c8663
LB
1373 else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
1374 cpu_khz = tsc_khz;
8fbbc4b4 1375
e93ef949 1376 if (!tsc_khz) {
8fbbc4b4 1377 mark_tsc_unstable("could not calculate TSC khz");
b47dcbdc 1378 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
8fbbc4b4
AK
1379 return;
1380 }
1381
c767a54b
JP
1382 pr_info("Detected %lu.%03lu MHz processor\n",
1383 (unsigned long)cpu_khz / 1000,
1384 (unsigned long)cpu_khz % 1000);
8fbbc4b4 1385
f2e04214
TG
1386 /* Sanitize TSC ADJUST before cyc2ns gets initialized */
1387 tsc_store_and_check_tsc_adjust(true);
1388
8fbbc4b4
AK
1389 /*
1390 * Secondary CPUs do not run through tsc_init(), so set up
1391 * all the scale factors for all CPUs, assuming the same
1392 * speed as the bootup CPU. (cpufreq notifiers will fix this
1393 * up if their speed diverges)
1394 */
20d1c86a
PZ
1395 for_each_possible_cpu(cpu) {
1396 cyc2ns_init(cpu);
aa297292 1397 set_cyc2ns_scale(tsc_khz, cpu);
20d1c86a 1398 }
8fbbc4b4
AK
1399
1400 if (tsc_disabled > 0)
1401 return;
1402
1403 /* now allow native_sched_clock() to use rdtsc */
10b033d4 1404
8fbbc4b4 1405 tsc_disabled = 0;
3bbfafb7 1406 static_branch_enable(&__use_tsc);
8fbbc4b4 1407
e82b8e4e
VP
1408 if (!no_sched_irq_time)
1409 enable_sched_clock_irqtime();
1410
70de9a97
AK
1411 lpj = ((u64)tsc_khz * 1000);
1412 do_div(lpj, HZ);
1413 lpj_fine = lpj;
1414
8fbbc4b4 1415 use_tsc_delay();
8fbbc4b4
AK
1416
1417 if (unsynchronized_tsc())
1418 mark_tsc_unstable("TSCs unsynchronized");
1419
395628ef 1420 check_system_tsc_reliable();
f9677e0f
CH
1421
1422 detect_art();
8fbbc4b4
AK
1423}
1424
b565201c
JS
1425#ifdef CONFIG_SMP
1426/*
1427 * If we have a constant TSC and are using the TSC for the delay loop,
1428 * we can skip clock calibration if another cpu in the same socket has already
1429 * been calibrated. This assumes that CONSTANT_TSC applies to all
1430 * cpus in the socket - this should be a safe assumption.
1431 */
148f9bb8 1432unsigned long calibrate_delay_is_known(void)
b565201c 1433{
c25323c0 1434 int sibling, cpu = smp_processor_id();
f508a5ba 1435 struct cpumask *mask = topology_core_cpumask(cpu);
b565201c
JS
1436
1437 if (!tsc_disabled && !cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC))
1438 return 0;
1439
f508a5ba
TG
1440 if (!mask)
1441 return 0;
1442
1443 sibling = cpumask_any_but(mask, cpu);
c25323c0
TG
1444 if (sibling < nr_cpu_ids)
1445 return cpu_data(sibling).loops_per_jiffy;
b565201c
JS
1446 return 0;
1447}
1448#endif