projects/linux·blob master · refs

1596 lines · 40.7 KiB

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