87e749106dda669e8788904d984ac60fa5aa026c
[linux-2.6-block.git] / arch / x86 / kernel / tsc.c
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/percpu.h>
15 #include <linux/timex.h>
16 #include <linux/static_key.h>
17 #include <linux/static_call.h>
18
19 #include <asm/cpuid/api.h>
20 #include <asm/hpet.h>
21 #include <asm/timer.h>
22 #include <asm/vgtod.h>
23 #include <asm/time.h>
24 #include <asm/delay.h>
25 #include <asm/hypervisor.h>
26 #include <asm/nmi.h>
27 #include <asm/x86_init.h>
28 #include <asm/geode.h>
29 #include <asm/apic.h>
30 #include <asm/cpu_device_id.h>
31 #include <asm/i8259.h>
32 #include <asm/msr.h>
33 #include <asm/topology.h>
34 #include <asm/uv/uv.h>
35 #include <asm/sev.h>
36
37 unsigned int __read_mostly cpu_khz;     /* TSC clocks / usec, not used here */
38 EXPORT_SYMBOL(cpu_khz);
39
40 unsigned int __read_mostly tsc_khz;
41 EXPORT_SYMBOL(tsc_khz);
42
43 #define KHZ     1000
44
45 /*
46  * TSC can be unstable due to cpufreq or due to unsynced TSCs
47  */
48 static int __read_mostly tsc_unstable;
49 static unsigned int __initdata tsc_early_khz;
50
51 static DEFINE_STATIC_KEY_FALSE_RO(__use_tsc);
52
53 int tsc_clocksource_reliable;
54
55 static int __read_mostly tsc_force_recalibrate;
56
57 static struct clocksource_base art_base_clk = {
58         .id    = CSID_X86_ART,
59 };
60 static bool have_art;
61
62 struct cyc2ns {
63         struct cyc2ns_data data[2];     /*  0 + 2*16 = 32 */
64         seqcount_latch_t   seq;         /* 32 + 4    = 36 */
65
66 }; /* fits one cacheline */
67
68 static DEFINE_PER_CPU_ALIGNED(struct cyc2ns, cyc2ns);
69
70 static int __init tsc_early_khz_setup(char *buf)
71 {
72         return kstrtouint(buf, 0, &tsc_early_khz);
73 }
74 early_param("tsc_early_khz", tsc_early_khz_setup);
75
76 __always_inline void __cyc2ns_read(struct cyc2ns_data *data)
77 {
78         int seq, idx;
79
80         do {
81                 seq = this_cpu_read(cyc2ns.seq.seqcount.sequence);
82                 idx = seq & 1;
83
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);
87
88         } while (unlikely(seq != this_cpu_read(cyc2ns.seq.seqcount.sequence)));
89 }
90
91 __always_inline void cyc2ns_read_begin(struct cyc2ns_data *data)
92 {
93         preempt_disable_notrace();
94         __cyc2ns_read(data);
95 }
96
97 __always_inline void cyc2ns_read_end(void)
98 {
99         preempt_enable_notrace();
100 }
101
102 /*
103  * Accelerators for sched_clock()
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
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.
119  *
120  *  We can use khz divisor instead of mhz to keep a better precision.
121  *  (mathieu.desnoyers@polymtl.ca)
122  *
123  *                      -johnstul@us.ibm.com "math is hard, lets go shopping!"
124  */
125
126 static __always_inline unsigned long long __cycles_2_ns(unsigned long long cyc)
127 {
128         struct cyc2ns_data data;
129         unsigned long long ns;
130
131         __cyc2ns_read(&data);
132
133         ns = data.cyc2ns_offset;
134         ns += mul_u64_u32_shr(cyc, data.cyc2ns_mul, data.cyc2ns_shift);
135
136         return ns;
137 }
138
139 static __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();
145         return ns;
146 }
147
148 static void __set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long tsc_now)
149 {
150         unsigned long long ns_now;
151         struct cyc2ns_data data;
152         struct cyc2ns *c2n;
153
154         ns_now = cycles_2_ns(tsc_now);
155
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          */
161         clocks_calc_mult_shift(&data.cyc2ns_mul, &data.cyc2ns_shift, khz,
162                                NSEC_PER_MSEC, 0);
163
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          */
170         if (data.cyc2ns_shift == 32) {
171                 data.cyc2ns_shift = 31;
172                 data.cyc2ns_mul >>= 1;
173         }
174
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);
179
180         write_seqcount_latch_begin(&c2n->seq);
181         c2n->data[0] = data;
182         write_seqcount_latch(&c2n->seq);
183         c2n->data[1] = data;
184         write_seqcount_latch_end(&c2n->seq);
185 }
186
187 static 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);
196
197         sched_clock_idle_wakeup_event();
198         local_irq_restore(flags);
199 }
200
201 /*
202  * Initialize cyc2ns for boot cpu
203  */
204 static void __init cyc2ns_init_boot_cpu(void)
205 {
206         struct cyc2ns *c2n = this_cpu_ptr(&cyc2ns);
207
208         seqcount_latch_init(&c2n->seq);
209         __set_cyc2ns_scale(tsc_khz, smp_processor_id(), rdtsc());
210 }
211
212 /*
213  * Secondary CPUs do not run through tsc_init(), so set up
214  * all the scale factors for all CPUs, assuming the same
215  * speed as the bootup CPU.
216  */
217 static 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) {
225                         seqcount_latch_init(&c2n->seq);
226                         c2n = per_cpu_ptr(&cyc2ns, cpu);
227                         c2n->data[0] = data[0];
228                         c2n->data[1] = data[1];
229                 }
230         }
231 }
232
233 /*
234  * Scheduler clock - returns current time in nanosec units.
235  */
236 noinstr u64 native_sched_clock(void)
237 {
238         if (static_branch_likely(&__use_tsc)) {
239                 u64 tsc_now = rdtsc();
240
241                 /* return the value in ns */
242                 return __cycles_2_ns(tsc_now);
243         }
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
251          *   can achieve it. )
252          */
253
254         /* No locking but a rare wrong value is not a big deal: */
255         return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
256 }
257
258 /*
259  * Generate a sched_clock if you already have a TSC value.
260  */
261 u64 native_sched_clock_from_tsc(u64 tsc)
262 {
263         return cycles_2_ns(tsc);
264 }
265
266 /* We need to define a real function for sched_clock, to override the
267    weak default version */
268 #ifdef CONFIG_PARAVIRT
269 noinstr u64 sched_clock_noinstr(void)
270 {
271         return paravirt_sched_clock();
272 }
273
274 bool using_native_sched_clock(void)
275 {
276         return static_call_query(pv_sched_clock) == native_sched_clock;
277 }
278 #else
279 u64 sched_clock_noinstr(void) __attribute__((alias("native_sched_clock")));
280
281 bool using_native_sched_clock(void) { return true; }
282 #endif
283
284 notrace 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
293 int check_tsc_unstable(void)
294 {
295         return tsc_unstable;
296 }
297 EXPORT_SYMBOL_GPL(check_tsc_unstable);
298
299 #ifdef CONFIG_X86_TSC
300 int __init notsc_setup(char *str)
301 {
302         mark_tsc_unstable("boot parameter notsc");
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  */
310 int __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);
318
319 static int no_sched_irq_time;
320 static int no_tsc_watchdog;
321 static int tsc_as_watchdog;
322
323 static 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                 no_tsc_watchdog = 1;
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         }
338         if (!strcmp(str, "recalibrate"))
339                 tsc_force_recalibrate = 1;
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         }
347         return 1;
348 }
349
350 __setup("tsc=", tsc_setup);
351
352 #define MAX_RETRIES             5
353 #define TSC_DEFAULT_THRESHOLD   0x20000
354
355 /*
356  * Read TSC and the reference counters. Take care of any disturbances
357  */
358 static u64 tsc_read_refs(u64 *p, int hpet)
359 {
360         u64 t1, t2;
361         u64 thresh = tsc_khz ? tsc_khz >> 5 : TSC_DEFAULT_THRESHOLD;
362         int i;
363
364         for (i = 0; i < MAX_RETRIES; i++) {
365                 t1 = get_cycles();
366                 if (hpet)
367                         *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
368                 else
369                         *p = acpi_pm_read_early();
370                 t2 = get_cycles();
371                 if ((t2 - t1) < thresh)
372                         return t2;
373         }
374         return ULLONG_MAX;
375 }
376
377 /*
378  * Calculate the TSC frequency from HPET reference
379  */
380 static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
381 {
382         u64 tmp;
383
384         if (hpet2 < hpet1)
385                 hpet2 += 0x100000000ULL;
386         hpet2 -= hpet1;
387         tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
388         do_div(tmp, 1000000);
389         deltatsc = div64_u64(deltatsc, tmp);
390
391         return (unsigned long) deltatsc;
392 }
393
394 /*
395  * Calculate the TSC frequency from PMTimer reference
396  */
397 static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
398 {
399         u64 tmp;
400
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
414 #define CAL_MS          10
415 #define CAL_LATCH       (PIT_TICK_RATE / (1000 / CAL_MS))
416 #define CAL_PIT_LOOPS   1000
417
418 #define CAL2_MS         50
419 #define CAL2_LATCH      (PIT_TICK_RATE / (1000 / CAL2_MS))
420 #define CAL2_PIT_LOOPS  5000
421
422
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  */
430 static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
431 {
432         u64 tsc, t1, t2, delta;
433         unsigned long tscmin, tscmax;
434         int pitcnt;
435
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
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);
459         outb(latch & 0xff, 0x42);
460         outb(latch >> 8, 0x42);
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          *
481          * If we were not able to read the PIT more than loopmin
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          */
487         if (pitcnt < loopmin || tscmax > 10 * tscmin)
488                 return ULONG_MAX;
489
490         /* Calculate the PIT value */
491         delta = t2 - t1;
492         do_div(delta, ms);
493         return delta;
494 }
495
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
529  * good value for the TSC frequency.
530  */
531 static inline int pit_verify_msb(unsigned char val)
532 {
533         /* Ignore LSB */
534         inb(0x42);
535         return inb(0x42) == val;
536 }
537
538 static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
539 {
540         int count;
541         u64 tsc = 0, prev_tsc = 0;
542
543         for (count = 0; count < 50000; count++) {
544                 if (!pit_verify_msb(val))
545                         break;
546                 prev_tsc = tsc;
547                 tsc = get_cycles();
548         }
549         *deltap = get_cycles() - prev_tsc;
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;
557 }
558
559 /*
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
563  * more than 50ms on it.
564  */
565 #define MAX_QUICK_PIT_MS 50
566 #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
567
568 static unsigned long quick_pit_calibrate(void)
569 {
570         int i;
571         u64 tsc, delta;
572         unsigned long d1, d2;
573
574         if (!has_legacy_pic())
575                 return 0;
576
577         /* Set the Gate high, disable speaker */
578         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
579
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          */
589         outb(0xb0, 0x43);
590
591         /* Start at 0xffff */
592         outb(0xff, 0x42);
593         outb(0xff, 0x42);
594
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          */
601         pit_verify_msb(0);
602
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
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
618                         /*
619                          * Iterate until the error is less than 500 ppm
620                          */
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;
634                 }
635         }
636         pr_info("Fast TSC calibration failed\n");
637         return 0;
638
639 success:
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
647          * reliable (within the error).
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          */
653         delta *= PIT_TICK_RATE;
654         do_div(delta, i*256*1000);
655         pr_info("Fast TSC calibration using PIT\n");
656         return delta;
657 }
658
659 /**
660  * native_calibrate_tsc - determine TSC frequency
661  * Determine TSC frequency via CPUID, else return 0.
662  */
663 unsigned long native_calibrate_tsc(void)
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
671         if (boot_cpu_data.cpuid_level < CPUID_LEAF_TSC)
672                 return 0;
673
674         eax_denominator = ebx_numerator = ecx_hz = edx = 0;
675
676         /* CPUID 15H TSC/Crystal ratio, plus optionally Crystal Hz */
677         cpuid(CPUID_LEAF_TSC, &eax_denominator, &ebx_numerator, &ecx_hz, &edx);
678
679         if (ebx_numerator == 0 || eax_denominator == 0)
680                 return 0;
681
682         crystal_khz = ecx_hz / 1000;
683
684         /*
685          * Denverton SoCs don't report crystal clock, and also don't support
686          * CPUID_LEAF_FREQ for the calculation below, so hardcode the 25MHz
687          * crystal clock.
688          */
689         if (crystal_khz == 0 &&
690                         boot_cpu_data.x86_vfm == INTEL_ATOM_GOLDMONT_D)
691                 crystal_khz = 25000;
692
693         /*
694          * TSC frequency reported directly by CPUID is a "hardware reported"
695          * frequency and is the most accurate one so far we have. This
696          * is considered a known frequency.
697          */
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          */
706         if (crystal_khz == 0 && boot_cpu_data.cpuid_level >= CPUID_LEAF_FREQ) {
707                 unsigned int eax_base_mhz, ebx, ecx, edx;
708
709                 cpuid(CPUID_LEAF_FREQ, &eax_base_mhz, &ebx, &ecx, &edx);
710                 crystal_khz = eax_base_mhz * 1000 *
711                         eax_denominator / ebx_numerator;
712         }
713
714         if (crystal_khz == 0)
715                 return 0;
716
717         /*
718          * For Atom SoCs TSC is the only reliable clocksource.
719          * Mark TSC reliable so no watchdog on it.
720          */
721         if (boot_cpu_data.x86_vfm == INTEL_ATOM_GOLDMONT)
722                 setup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE);
723
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
734         return crystal_khz * ebx_numerator / eax_denominator;
735 }
736
737 static 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
744         if (boot_cpu_data.cpuid_level < CPUID_LEAF_FREQ)
745                 return 0;
746
747         eax_base_mhz = ebx_max_mhz = ecx_bus_mhz = edx = 0;
748
749         cpuid(CPUID_LEAF_FREQ, &eax_base_mhz, &ebx_max_mhz, &ecx_bus_mhz, &edx);
750
751         return eax_base_mhz * 1000;
752 }
753
754 /*
755  * calibrate cpu using pit, hpet, and ptimer methods. They are available
756  * later in boot after acpi is initialized.
757  */
758 static unsigned long pit_hpet_ptimer_calibrate_cpu(void)
759 {
760         u64 tsc1, tsc2, delta, ref1, ref2;
761         unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
762         unsigned long flags, latch, ms;
763         int hpet = is_hpet_enabled(), i, loopmin;
764
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
776          * by the IO time of the PIT access, so we can detect when
777          * any disturbance happened between the two reads. If the
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
784          * reference read for any possible disturbance. We discard
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          */
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++) {
796                 unsigned long tsc_pit_khz;
797
798                 /*
799                  * Read the start value and the reference count of
800                  * hpet/pmtimer when available. Then do the PIT
801                  * calibration, which will take at least 50ms, and
802                  * read the end value.
803                  */
804                 local_irq_save(flags);
805                 tsc1 = tsc_read_refs(&ref1, hpet);
806                 tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
807                 tsc2 = tsc_read_refs(&ref2, hpet);
808                 local_irq_restore(flags);
809
810                 /* Pick the lowest PIT TSC calibration so far */
811                 tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
812
813                 /* hpet or pmtimer available ? */
814                 if (ref1 == ref2)
815                         continue;
816
817                 /* Check, whether the sampling was disturbed */
818                 if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
819                         continue;
820
821                 tsc2 = (tsc2 - tsc1) * 1000000LL;
822                 if (hpet)
823                         tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
824                 else
825                         tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
826
827                 tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
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) {
840                         pr_info("PIT calibration matches %s. %d loops\n",
841                                 hpet ? "HPET" : "PMTIMER", i + 1);
842                         return tsc_ref_min;
843                 }
844
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                 }
856         }
857
858         /*
859          * Now check the results.
860          */
861         if (tsc_pit_min == ULONG_MAX) {
862                 /* PIT gave no useful value */
863                 pr_warn("Unable to calibrate against PIT\n");
864
865                 /* We don't have an alternative source, disable TSC */
866                 if (!hpet && !ref1 && !ref2) {
867                         pr_notice("No reference (HPET/PMTIMER) available\n");
868                         return 0;
869                 }
870
871                 /* The alternative source failed as well, disable TSC */
872                 if (tsc_ref_min == ULONG_MAX) {
873                         pr_warn("HPET/PMTIMER calibration failed\n");
874                         return 0;
875                 }
876
877                 /* Use the alternative source */
878                 pr_info("using %s reference calibration\n",
879                         hpet ? "HPET" : "PMTIMER");
880
881                 return tsc_ref_min;
882         }
883
884         /* We don't have an alternative source, use the PIT calibration value */
885         if (!hpet && !ref1 && !ref2) {
886                 pr_info("Using PIT calibration value\n");
887                 return tsc_pit_min;
888         }
889
890         /* The alternative source failed, use the PIT calibration value */
891         if (tsc_ref_min == ULONG_MAX) {
892                 pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
893                 return tsc_pit_min;
894         }
895
896         /*
897          * The calibration values differ too much. In doubt, we use
898          * the PIT value as we know that there are PMTIMERs around
899          * running at double speed. At least we let the user know:
900          */
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");
904         return tsc_pit_min;
905 }
906
907 /**
908  * native_calibrate_cpu_early - can calibrate the cpu early in boot
909  */
910 unsigned 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  */
928 static unsigned long native_calibrate_cpu(void)
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
938 void recalibrate_cpu_khz(void)
939 {
940 #ifndef CONFIG_SMP
941         unsigned long cpu_khz_old = cpu_khz;
942
943         if (!boot_cpu_has(X86_FEATURE_TSC))
944                 return;
945
946         cpu_khz = x86_platform.calibrate_cpu();
947         tsc_khz = x86_platform.calibrate_tsc();
948         if (tsc_khz == 0)
949                 tsc_khz = cpu_khz;
950         else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
951                 cpu_khz = tsc_khz;
952         cpu_data(0).loops_per_jiffy = cpufreq_scale(cpu_data(0).loops_per_jiffy,
953                                                     cpu_khz_old, cpu_khz);
954 #endif
955 }
956 EXPORT_SYMBOL_GPL(recalibrate_cpu_khz);
957
958
959 static unsigned long long cyc2ns_suspend;
960
961 void tsc_save_sched_clock_state(void)
962 {
963         if (!static_branch_likely(&__use_tsc) && !sched_clock_stable())
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  */
977 void tsc_restore_sched_clock_state(void)
978 {
979         unsigned long long offset;
980         unsigned long flags;
981         int cpu;
982
983         if (!static_branch_likely(&__use_tsc) && !sched_clock_stable())
984                 return;
985
986         local_irq_save(flags);
987
988         /*
989          * We're coming out of suspend, there's no concurrency yet; don't
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
997         offset = cyc2ns_suspend - sched_clock();
998
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         }
1003
1004         local_irq_restore(flags);
1005 }
1006
1007 #ifdef CONFIG_CPU_FREQ
1008 /*
1009  * Frequency scaling support. Adjust the TSC based timer when the CPU frequency
1010  * changes.
1011  *
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.
1014  *
1015  * Should fix up last_tsc too. Currently gettimeofday in the
1016  * first tick after the change will be slightly wrong.
1017  */
1018
1019 static unsigned int  ref_freq;
1020 static unsigned long loops_per_jiffy_ref;
1021 static unsigned long tsc_khz_ref;
1022
1023 static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
1024                                 void *data)
1025 {
1026         struct cpufreq_freqs *freq = data;
1027
1028         if (num_online_cpus() > 1) {
1029                 mark_tsc_unstable("cpufreq changes on SMP");
1030                 return 0;
1031         }
1032
1033         if (!ref_freq) {
1034                 ref_freq = freq->old;
1035                 loops_per_jiffy_ref = boot_cpu_data.loops_per_jiffy;
1036                 tsc_khz_ref = tsc_khz;
1037         }
1038
1039         if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
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);
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");
1047
1048                 set_cyc2ns_scale(tsc_khz, freq->policy->cpu, rdtsc());
1049         }
1050
1051         return 0;
1052 }
1053
1054 static struct notifier_block time_cpufreq_notifier_block = {
1055         .notifier_call  = time_cpufreq_notifier
1056 };
1057
1058 static int __init cpufreq_register_tsc_scaling(void)
1059 {
1060         if (!boot_cpu_has(X86_FEATURE_TSC))
1061                 return 0;
1062         if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1063                 return 0;
1064         cpufreq_register_notifier(&time_cpufreq_notifier_block,
1065                                 CPUFREQ_TRANSITION_NOTIFIER);
1066         return 0;
1067 }
1068
1069 core_initcall(cpufreq_register_tsc_scaling);
1070
1071 #endif /* CONFIG_CPU_FREQ */
1072
1073 #define ART_MIN_DENOMINATOR (1)
1074
1075 /*
1076  * If ART is present detect the numerator:denominator to convert to TSC
1077  */
1078 static void __init detect_art(void)
1079 {
1080         unsigned int unused;
1081
1082         if (boot_cpu_data.cpuid_level < CPUID_LEAF_TSC)
1083                 return;
1084
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          */
1089         if (boot_cpu_has(X86_FEATURE_HYPERVISOR) ||
1090             !boot_cpu_has(X86_FEATURE_NONSTOP_TSC) ||
1091             !boot_cpu_has(X86_FEATURE_TSC_ADJUST) ||
1092             tsc_async_resets)
1093                 return;
1094
1095         cpuid(CPUID_LEAF_TSC, &art_base_clk.denominator,
1096               &art_base_clk.numerator, &art_base_clk.freq_khz, &unused);
1097
1098         art_base_clk.freq_khz /= KHZ;
1099         if (art_base_clk.denominator < ART_MIN_DENOMINATOR)
1100                 return;
1101
1102         rdmsrq(MSR_IA32_TSC_ADJUST, art_base_clk.offset);
1103
1104         /* Make this sticky over multiple CPU init calls */
1105         setup_force_cpu_cap(X86_FEATURE_ART);
1106 }
1107
1108
1109 /* clocksource code */
1110
1111 static void tsc_resume(struct clocksource *cs)
1112 {
1113         tsc_verify_tsc_adjust(true);
1114 }
1115
1116 /*
1117  * We used to compare the TSC to the cycle_last value in the clocksource
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
1122  * is slightly behind. This delta is nowhere else observable, but in
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.
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.
1131  */
1132 static u64 read_tsc(struct clocksource *cs)
1133 {
1134         return (u64)rdtsc_ordered();
1135 }
1136
1137 static void tsc_cs_mark_unstable(struct clocksource *cs)
1138 {
1139         if (tsc_unstable)
1140                 return;
1141
1142         tsc_unstable = 1;
1143         if (using_native_sched_clock())
1144                 clear_sched_clock_stable();
1145         disable_sched_clock_irqtime();
1146         pr_info("Marking TSC unstable due to clocksource watchdog\n");
1147 }
1148
1149 static 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
1158 static int tsc_cs_enable(struct clocksource *cs)
1159 {
1160         vclocks_set_used(VDSO_CLOCKMODE_TSC);
1161         return 0;
1162 }
1163
1164 /*
1165  * .mask MUST be CLOCKSOURCE_MASK(64). See comment above read_tsc()
1166  */
1167 static struct clocksource clocksource_tsc_early = {
1168         .name                   = "tsc-early",
1169         .rating                 = 299,
1170         .uncertainty_margin     = 32 * NSEC_PER_MSEC,
1171         .read                   = read_tsc,
1172         .mask                   = CLOCKSOURCE_MASK(64),
1173         .flags                  = CLOCK_SOURCE_IS_CONTINUOUS |
1174                                   CLOCK_SOURCE_MUST_VERIFY,
1175         .id                     = CSID_X86_TSC_EARLY,
1176         .vdso_clock_mode        = VDSO_CLOCKMODE_TSC,
1177         .enable                 = tsc_cs_enable,
1178         .resume                 = tsc_resume,
1179         .mark_unstable          = tsc_cs_mark_unstable,
1180         .tick_stable            = tsc_cs_tick_stable,
1181         .list                   = LIST_HEAD_INIT(clocksource_tsc_early.list),
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  */
1189 static struct clocksource clocksource_tsc = {
1190         .name                   = "tsc",
1191         .rating                 = 300,
1192         .read                   = read_tsc,
1193         .mask                   = CLOCKSOURCE_MASK(64),
1194         .flags                  = CLOCK_SOURCE_IS_CONTINUOUS |
1195                                   CLOCK_SOURCE_VALID_FOR_HRES |
1196                                   CLOCK_SOURCE_MUST_VERIFY |
1197                                   CLOCK_SOURCE_VERIFY_PERCPU,
1198         .id                     = CSID_X86_TSC,
1199         .vdso_clock_mode        = VDSO_CLOCKMODE_TSC,
1200         .enable                 = tsc_cs_enable,
1201         .resume                 = tsc_resume,
1202         .mark_unstable          = tsc_cs_mark_unstable,
1203         .tick_stable            = tsc_cs_tick_stable,
1204         .list                   = LIST_HEAD_INIT(clocksource_tsc.list),
1205 };
1206
1207 void mark_tsc_unstable(char *reason)
1208 {
1209         if (tsc_unstable)
1210                 return;
1211
1212         tsc_unstable = 1;
1213         if (using_native_sched_clock())
1214                 clear_sched_clock_stable();
1215         disable_sched_clock_irqtime();
1216         pr_info("Marking TSC unstable due to %s\n", reason);
1217
1218         clocksource_mark_unstable(&clocksource_tsc_early);
1219         clocksource_mark_unstable(&clocksource_tsc);
1220 }
1221
1222 EXPORT_SYMBOL_GPL(mark_tsc_unstable);
1223
1224 static 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
1230 bool tsc_clocksource_watchdog_disabled(void)
1231 {
1232         return !(clocksource_tsc.flags & CLOCK_SOURCE_MUST_VERIFY) &&
1233                tsc_as_watchdog && !no_tsc_watchdog;
1234 }
1235
1236 static void __init check_system_tsc_reliable(void)
1237 {
1238 #if defined(CONFIG_MGEODEGX1) || defined(CONFIG_MGEODE_LX) || defined(CONFIG_X86_GENERIC)
1239         if (is_geode_lx()) {
1240                 /* RTSC counts during suspend */
1241 #define RTSC_SUSP 0x100
1242                 unsigned long res_low, res_high;
1243
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         }
1249 #endif
1250         if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
1251                 tsc_clocksource_reliable = 1;
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
1259          *  - not more than four packages
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) &&
1264             topology_max_packages() <= 4)
1265                 tsc_disable_clocksource_watchdog();
1266 }
1267
1268 /*
1269  * Make an educated guess if the TSC is trustworthy and synchronized
1270  * over all CPUs.
1271  */
1272 int unsynchronized_tsc(void)
1273 {
1274         if (!boot_cpu_has(X86_FEATURE_TSC) || tsc_unstable)
1275                 return 1;
1276
1277 #ifdef CONFIG_SMP
1278         if (apic_is_clustered_box())
1279                 return 1;
1280 #endif
1281
1282         if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1283                 return 0;
1284
1285         if (tsc_clocksource_reliable)
1286                 return 0;
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: */
1293                 if (topology_max_packages() > 1)
1294                         return 1;
1295         }
1296
1297         return 0;
1298 }
1299
1300 static void tsc_refine_calibration_work(struct work_struct *work);
1301 static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
1302 /**
1303  * tsc_refine_calibration_work - Further refine tsc freq calibration
1304  * @work: ignored.
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  *
1311  * If there are any calibration anomalies (too many SMIs, etc),
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  */
1316 static void tsc_refine_calibration_work(struct work_struct *work)
1317 {
1318         static u64 tsc_start = ULLONG_MAX, ref_start;
1319         static int hpet;
1320         u64 tsc_stop, ref_stop, delta;
1321         unsigned long freq;
1322         int cpu;
1323
1324         /* Don't bother refining TSC on unstable systems */
1325         if (tsc_unstable)
1326                 goto unreg;
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          */
1333         if (tsc_start == ULLONG_MAX) {
1334 restart:
1335                 /*
1336                  * Only set hpet once, to avoid mixing hardware
1337                  * if the hpet becomes enabled later.
1338                  */
1339                 hpet = is_hpet_enabled();
1340                 tsc_start = tsc_read_refs(&ref_start, hpet);
1341                 schedule_delayed_work(&tsc_irqwork, HZ);
1342                 return;
1343         }
1344
1345         tsc_stop = tsc_read_refs(&ref_stop, hpet);
1346
1347         /* hpet or pmtimer available ? */
1348         if (ref_start == ref_stop)
1349                 goto out;
1350
1351         /* Check, whether the sampling was disturbed */
1352         if (tsc_stop == ULLONG_MAX)
1353                 goto restart;
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
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
1381         /* Make sure we're within 1% */
1382         if (abs(tsc_khz - freq) > tsc_khz/100)
1383                 goto out;
1384
1385         tsc_khz = freq;
1386         pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
1387                 (unsigned long)tsc_khz / 1000,
1388                 (unsigned long)tsc_khz % 1000);
1389
1390         /* Inform the TSC deadline clockevent devices about the recalibration */
1391         lapic_update_tsc_freq();
1392
1393         /* Update the sched_clock() rate to match the clocksource one */
1394         for_each_possible_cpu(cpu)
1395                 set_cyc2ns_scale(tsc_khz, cpu, tsc_stop);
1396
1397 out:
1398         if (tsc_unstable)
1399                 goto unreg;
1400
1401         if (boot_cpu_has(X86_FEATURE_ART)) {
1402                 have_art = true;
1403                 clocksource_tsc.base = &art_base_clk;
1404         }
1405         clocksource_register_khz(&clocksource_tsc, tsc_khz);
1406 unreg:
1407         clocksource_unregister(&clocksource_tsc_early);
1408 }
1409
1410
1411 static int __init init_tsc_clocksource(void)
1412 {
1413         if (!boot_cpu_has(X86_FEATURE_TSC) || !tsc_khz)
1414                 return 0;
1415
1416         if (tsc_unstable) {
1417                 clocksource_unregister(&clocksource_tsc_early);
1418                 return 0;
1419         }
1420
1421         if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
1422                 clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
1423
1424         /*
1425          * When TSC frequency is known (retrieved via MSR or CPUID), we skip
1426          * the refined calibration and directly register it as a clocksource.
1427          */
1428         if (boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ)) {
1429                 if (boot_cpu_has(X86_FEATURE_ART)) {
1430                         have_art = true;
1431                         clocksource_tsc.base = &art_base_clk;
1432                 }
1433                 clocksource_register_khz(&clocksource_tsc, tsc_khz);
1434                 clocksource_unregister(&clocksource_tsc_early);
1435
1436                 if (!tsc_force_recalibrate)
1437                         return 0;
1438         }
1439
1440         schedule_delayed_work(&tsc_irqwork, 0);
1441         return 0;
1442 }
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  */
1447 device_initcall(init_tsc_clocksource);
1448
1449 static bool __init determine_cpu_tsc_frequencies(bool early)
1450 {
1451         /* Make sure that cpu and tsc are not already calibrated */
1452         WARN_ON(cpu_khz || tsc_khz);
1453
1454         if (early) {
1455                 cpu_khz = x86_platform.calibrate_cpu();
1456                 if (tsc_early_khz) {
1457                         tsc_khz = tsc_early_khz;
1458                 } else {
1459                         tsc_khz = x86_platform.calibrate_tsc();
1460                         clocksource_tsc.freq_khz = tsc_khz;
1461                 }
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         }
1467
1468         /*
1469          * Trust non-zero tsc_khz as authoritative,
1470          * and use it to sanity check cpu_khz,
1471          * which will be off if system timer is off.
1472          */
1473         if (tsc_khz == 0)
1474                 tsc_khz = cpu_khz;
1475         else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
1476                 cpu_khz = tsc_khz;
1477
1478         if (tsc_khz == 0)
1479                 return false;
1480
1481         pr_info("Detected %lu.%03lu MHz processor\n",
1482                 (unsigned long)cpu_khz / KHZ,
1483                 (unsigned long)cpu_khz % KHZ);
1484
1485         if (cpu_khz != tsc_khz) {
1486                 pr_info("Detected %lu.%03lu MHz TSC",
1487                         (unsigned long)tsc_khz / KHZ,
1488                         (unsigned long)tsc_khz % KHZ);
1489         }
1490         return true;
1491 }
1492
1493 static unsigned long __init get_loops_per_jiffy(void)
1494 {
1495         u64 lpj = (u64)tsc_khz * KHZ;
1496
1497         do_div(lpj, HZ);
1498         return lpj;
1499 }
1500
1501 static void __init tsc_enable_sched_clock(void)
1502 {
1503         loops_per_jiffy = get_loops_per_jiffy();
1504         use_tsc_delay();
1505
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
1512 void __init tsc_early_init(void)
1513 {
1514         if (!boot_cpu_has(X86_FEATURE_TSC))
1515                 return;
1516         /* Don't change UV TSC multi-chassis synchronization */
1517         if (is_early_uv_system())
1518                 return;
1519
1520         snp_secure_tsc_init();
1521
1522         if (!determine_cpu_tsc_frequencies(true))
1523                 return;
1524         tsc_enable_sched_clock();
1525 }
1526
1527 void __init tsc_init(void)
1528 {
1529         if (!cpu_feature_enabled(X86_FEATURE_TSC)) {
1530                 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
1531                 return;
1532         }
1533
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
1541         if (!tsc_khz) {
1542                 /* We failed to determine frequencies earlier, try again */
1543                 if (!determine_cpu_tsc_frequencies(false)) {
1544                         mark_tsc_unstable("could not calculate TSC khz");
1545                         setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
1546                         return;
1547                 }
1548                 tsc_enable_sched_clock();
1549         }
1550
1551         cyc2ns_init_secondary_cpus();
1552
1553         if (!no_sched_irq_time)
1554                 enable_sched_clock_irqtime();
1555
1556         lpj_fine = get_loops_per_jiffy();
1557
1558         check_system_tsc_reliable();
1559
1560         if (unsynchronized_tsc()) {
1561                 mark_tsc_unstable("TSCs unsynchronized");
1562                 return;
1563         }
1564
1565         if (tsc_clocksource_reliable || no_tsc_watchdog)
1566                 tsc_disable_clocksource_watchdog();
1567
1568         clocksource_register_khz(&clocksource_tsc_early, tsc_khz);
1569         detect_art();
1570 }
1571
1572 #ifdef CONFIG_SMP
1573 /*
1574  * Check whether existing calibration data can be reused.
1575  */
1576 unsigned long calibrate_delay_is_known(void)
1577 {
1578         int sibling, cpu = smp_processor_id();
1579         int constant_tsc = cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC);
1580         const struct cpumask *mask = topology_core_cpumask(cpu);
1581
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          */
1597         if (!constant_tsc || !mask)
1598                 return 0;
1599
1600         sibling = cpumask_any_but(mask, cpu);
1601         if (sibling < nr_cpu_ids)
1602                 return cpu_data(sibling).loops_per_jiffy;
1603         return 0;
1604 }
1605 #endif