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