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