xref: /openbmc/linux/arch/x86/kernel/tsc.c (revision c73deb6a)
1c767a54bSJoe Perches #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2c767a54bSJoe Perches 
3bfc0f594SAlok Kataria #include <linux/kernel.h>
40ef95533SAlok Kataria #include <linux/sched.h>
50ef95533SAlok Kataria #include <linux/init.h>
60ef95533SAlok Kataria #include <linux/module.h>
70ef95533SAlok Kataria #include <linux/timer.h>
8bfc0f594SAlok Kataria #include <linux/acpi_pmtmr.h>
92dbe06faSAlok Kataria #include <linux/cpufreq.h>
108fbbc4b4SAlok Kataria #include <linux/delay.h>
118fbbc4b4SAlok Kataria #include <linux/clocksource.h>
128fbbc4b4SAlok Kataria #include <linux/percpu.h>
1308604bd9SArnd Bergmann #include <linux/timex.h>
14bfc0f594SAlok Kataria 
15bfc0f594SAlok Kataria #include <asm/hpet.h>
168fbbc4b4SAlok Kataria #include <asm/timer.h>
178fbbc4b4SAlok Kataria #include <asm/vgtod.h>
188fbbc4b4SAlok Kataria #include <asm/time.h>
198fbbc4b4SAlok Kataria #include <asm/delay.h>
2088b094fbSAlok Kataria #include <asm/hypervisor.h>
2108047c4fSThomas Gleixner #include <asm/nmi.h>
222d826404SThomas Gleixner #include <asm/x86_init.h>
230ef95533SAlok Kataria 
24f24ade3aSIngo Molnar unsigned int __read_mostly cpu_khz;	/* TSC clocks / usec, not used here */
250ef95533SAlok Kataria EXPORT_SYMBOL(cpu_khz);
26f24ade3aSIngo Molnar 
27f24ade3aSIngo Molnar unsigned int __read_mostly tsc_khz;
280ef95533SAlok Kataria EXPORT_SYMBOL(tsc_khz);
290ef95533SAlok Kataria 
300ef95533SAlok Kataria /*
310ef95533SAlok Kataria  * TSC can be unstable due to cpufreq or due to unsynced TSCs
320ef95533SAlok Kataria  */
33f24ade3aSIngo Molnar static int __read_mostly tsc_unstable;
340ef95533SAlok Kataria 
350ef95533SAlok Kataria /* native_sched_clock() is called before tsc_init(), so
360ef95533SAlok Kataria    we must start with the TSC soft disabled to prevent
370ef95533SAlok Kataria    erroneous rdtsc usage on !cpu_has_tsc processors */
38f24ade3aSIngo Molnar static int __read_mostly tsc_disabled = -1;
390ef95533SAlok Kataria 
4028a00184SSuresh Siddha int tsc_clocksource_reliable;
410ef95533SAlok Kataria /*
420ef95533SAlok Kataria  * Scheduler clock - returns current time in nanosec units.
430ef95533SAlok Kataria  */
440ef95533SAlok Kataria u64 native_sched_clock(void)
450ef95533SAlok Kataria {
460ef95533SAlok Kataria 	u64 this_offset;
470ef95533SAlok Kataria 
480ef95533SAlok Kataria 	/*
490ef95533SAlok Kataria 	 * Fall back to jiffies if there's no TSC available:
500ef95533SAlok Kataria 	 * ( But note that we still use it if the TSC is marked
510ef95533SAlok Kataria 	 *   unstable. We do this because unlike Time Of Day,
520ef95533SAlok Kataria 	 *   the scheduler clock tolerates small errors and it's
530ef95533SAlok Kataria 	 *   very important for it to be as fast as the platform
543ad2f3fbSDaniel Mack 	 *   can achieve it. )
550ef95533SAlok Kataria 	 */
560ef95533SAlok Kataria 	if (unlikely(tsc_disabled)) {
570ef95533SAlok Kataria 		/* No locking but a rare wrong value is not a big deal: */
580ef95533SAlok Kataria 		return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
590ef95533SAlok Kataria 	}
600ef95533SAlok Kataria 
610ef95533SAlok Kataria 	/* read the Time Stamp Counter: */
620ef95533SAlok Kataria 	rdtscll(this_offset);
630ef95533SAlok Kataria 
640ef95533SAlok Kataria 	/* return the value in ns */
657cbaef9cSIngo Molnar 	return __cycles_2_ns(this_offset);
660ef95533SAlok Kataria }
670ef95533SAlok Kataria 
680ef95533SAlok Kataria /* We need to define a real function for sched_clock, to override the
690ef95533SAlok Kataria    weak default version */
700ef95533SAlok Kataria #ifdef CONFIG_PARAVIRT
710ef95533SAlok Kataria unsigned long long sched_clock(void)
720ef95533SAlok Kataria {
730ef95533SAlok Kataria 	return paravirt_sched_clock();
740ef95533SAlok Kataria }
750ef95533SAlok Kataria #else
760ef95533SAlok Kataria unsigned long long
770ef95533SAlok Kataria sched_clock(void) __attribute__((alias("native_sched_clock")));
780ef95533SAlok Kataria #endif
790ef95533SAlok Kataria 
80ce37f400SDavid Vrabel unsigned long long native_read_tsc(void)
81ce37f400SDavid Vrabel {
82ce37f400SDavid Vrabel 	return __native_read_tsc();
83ce37f400SDavid Vrabel }
84ce37f400SDavid Vrabel EXPORT_SYMBOL(native_read_tsc);
85ce37f400SDavid Vrabel 
860ef95533SAlok Kataria int check_tsc_unstable(void)
870ef95533SAlok Kataria {
880ef95533SAlok Kataria 	return tsc_unstable;
890ef95533SAlok Kataria }
900ef95533SAlok Kataria EXPORT_SYMBOL_GPL(check_tsc_unstable);
910ef95533SAlok Kataria 
92c73deb6aSAdrian Hunter int check_tsc_disabled(void)
93c73deb6aSAdrian Hunter {
94c73deb6aSAdrian Hunter 	return tsc_disabled;
95c73deb6aSAdrian Hunter }
96c73deb6aSAdrian Hunter EXPORT_SYMBOL_GPL(check_tsc_disabled);
97c73deb6aSAdrian Hunter 
980ef95533SAlok Kataria #ifdef CONFIG_X86_TSC
990ef95533SAlok Kataria int __init notsc_setup(char *str)
1000ef95533SAlok Kataria {
101c767a54bSJoe Perches 	pr_warn("Kernel compiled with CONFIG_X86_TSC, cannot disable TSC completely\n");
1020ef95533SAlok Kataria 	tsc_disabled = 1;
1030ef95533SAlok Kataria 	return 1;
1040ef95533SAlok Kataria }
1050ef95533SAlok Kataria #else
1060ef95533SAlok Kataria /*
1070ef95533SAlok Kataria  * disable flag for tsc. Takes effect by clearing the TSC cpu flag
1080ef95533SAlok Kataria  * in cpu/common.c
1090ef95533SAlok Kataria  */
1100ef95533SAlok Kataria int __init notsc_setup(char *str)
1110ef95533SAlok Kataria {
1120ef95533SAlok Kataria 	setup_clear_cpu_cap(X86_FEATURE_TSC);
1130ef95533SAlok Kataria 	return 1;
1140ef95533SAlok Kataria }
1150ef95533SAlok Kataria #endif
1160ef95533SAlok Kataria 
1170ef95533SAlok Kataria __setup("notsc", notsc_setup);
118bfc0f594SAlok Kataria 
119e82b8e4eSVenkatesh Pallipadi static int no_sched_irq_time;
120e82b8e4eSVenkatesh Pallipadi 
121395628efSAlok Kataria static int __init tsc_setup(char *str)
122395628efSAlok Kataria {
123395628efSAlok Kataria 	if (!strcmp(str, "reliable"))
124395628efSAlok Kataria 		tsc_clocksource_reliable = 1;
125e82b8e4eSVenkatesh Pallipadi 	if (!strncmp(str, "noirqtime", 9))
126e82b8e4eSVenkatesh Pallipadi 		no_sched_irq_time = 1;
127395628efSAlok Kataria 	return 1;
128395628efSAlok Kataria }
129395628efSAlok Kataria 
130395628efSAlok Kataria __setup("tsc=", tsc_setup);
131395628efSAlok Kataria 
132bfc0f594SAlok Kataria #define MAX_RETRIES     5
133bfc0f594SAlok Kataria #define SMI_TRESHOLD    50000
134bfc0f594SAlok Kataria 
135bfc0f594SAlok Kataria /*
136bfc0f594SAlok Kataria  * Read TSC and the reference counters. Take care of SMI disturbance
137bfc0f594SAlok Kataria  */
138827014beSThomas Gleixner static u64 tsc_read_refs(u64 *p, int hpet)
139bfc0f594SAlok Kataria {
140bfc0f594SAlok Kataria 	u64 t1, t2;
141bfc0f594SAlok Kataria 	int i;
142bfc0f594SAlok Kataria 
143bfc0f594SAlok Kataria 	for (i = 0; i < MAX_RETRIES; i++) {
144bfc0f594SAlok Kataria 		t1 = get_cycles();
145bfc0f594SAlok Kataria 		if (hpet)
146827014beSThomas Gleixner 			*p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
147bfc0f594SAlok Kataria 		else
148827014beSThomas Gleixner 			*p = acpi_pm_read_early();
149bfc0f594SAlok Kataria 		t2 = get_cycles();
150bfc0f594SAlok Kataria 		if ((t2 - t1) < SMI_TRESHOLD)
151bfc0f594SAlok Kataria 			return t2;
152bfc0f594SAlok Kataria 	}
153bfc0f594SAlok Kataria 	return ULLONG_MAX;
154bfc0f594SAlok Kataria }
155bfc0f594SAlok Kataria 
156ec0c15afSLinus Torvalds /*
157d683ef7aSThomas Gleixner  * Calculate the TSC frequency from HPET reference
158d683ef7aSThomas Gleixner  */
159d683ef7aSThomas Gleixner static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
160d683ef7aSThomas Gleixner {
161d683ef7aSThomas Gleixner 	u64 tmp;
162d683ef7aSThomas Gleixner 
163d683ef7aSThomas Gleixner 	if (hpet2 < hpet1)
164d683ef7aSThomas Gleixner 		hpet2 += 0x100000000ULL;
165d683ef7aSThomas Gleixner 	hpet2 -= hpet1;
166d683ef7aSThomas Gleixner 	tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
167d683ef7aSThomas Gleixner 	do_div(tmp, 1000000);
168d683ef7aSThomas Gleixner 	do_div(deltatsc, tmp);
169d683ef7aSThomas Gleixner 
170d683ef7aSThomas Gleixner 	return (unsigned long) deltatsc;
171d683ef7aSThomas Gleixner }
172d683ef7aSThomas Gleixner 
173d683ef7aSThomas Gleixner /*
174d683ef7aSThomas Gleixner  * Calculate the TSC frequency from PMTimer reference
175d683ef7aSThomas Gleixner  */
176d683ef7aSThomas Gleixner static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
177d683ef7aSThomas Gleixner {
178d683ef7aSThomas Gleixner 	u64 tmp;
179d683ef7aSThomas Gleixner 
180d683ef7aSThomas Gleixner 	if (!pm1 && !pm2)
181d683ef7aSThomas Gleixner 		return ULONG_MAX;
182d683ef7aSThomas Gleixner 
183d683ef7aSThomas Gleixner 	if (pm2 < pm1)
184d683ef7aSThomas Gleixner 		pm2 += (u64)ACPI_PM_OVRRUN;
185d683ef7aSThomas Gleixner 	pm2 -= pm1;
186d683ef7aSThomas Gleixner 	tmp = pm2 * 1000000000LL;
187d683ef7aSThomas Gleixner 	do_div(tmp, PMTMR_TICKS_PER_SEC);
188d683ef7aSThomas Gleixner 	do_div(deltatsc, tmp);
189d683ef7aSThomas Gleixner 
190d683ef7aSThomas Gleixner 	return (unsigned long) deltatsc;
191d683ef7aSThomas Gleixner }
192d683ef7aSThomas Gleixner 
193a977c400SThomas Gleixner #define CAL_MS		10
194b7743970SDeepak Saxena #define CAL_LATCH	(PIT_TICK_RATE / (1000 / CAL_MS))
195a977c400SThomas Gleixner #define CAL_PIT_LOOPS	1000
196a977c400SThomas Gleixner 
197a977c400SThomas Gleixner #define CAL2_MS		50
198b7743970SDeepak Saxena #define CAL2_LATCH	(PIT_TICK_RATE / (1000 / CAL2_MS))
199a977c400SThomas Gleixner #define CAL2_PIT_LOOPS	5000
200a977c400SThomas Gleixner 
201cce3e057SThomas Gleixner 
202ec0c15afSLinus Torvalds /*
203ec0c15afSLinus Torvalds  * Try to calibrate the TSC against the Programmable
204ec0c15afSLinus Torvalds  * Interrupt Timer and return the frequency of the TSC
205ec0c15afSLinus Torvalds  * in kHz.
206ec0c15afSLinus Torvalds  *
207ec0c15afSLinus Torvalds  * Return ULONG_MAX on failure to calibrate.
208ec0c15afSLinus Torvalds  */
209a977c400SThomas Gleixner static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
210ec0c15afSLinus Torvalds {
211ec0c15afSLinus Torvalds 	u64 tsc, t1, t2, delta;
212ec0c15afSLinus Torvalds 	unsigned long tscmin, tscmax;
213ec0c15afSLinus Torvalds 	int pitcnt;
214ec0c15afSLinus Torvalds 
215ec0c15afSLinus Torvalds 	/* Set the Gate high, disable speaker */
216ec0c15afSLinus Torvalds 	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
217ec0c15afSLinus Torvalds 
218ec0c15afSLinus Torvalds 	/*
219ec0c15afSLinus Torvalds 	 * Setup CTC channel 2* for mode 0, (interrupt on terminal
220ec0c15afSLinus Torvalds 	 * count mode), binary count. Set the latch register to 50ms
221ec0c15afSLinus Torvalds 	 * (LSB then MSB) to begin countdown.
222ec0c15afSLinus Torvalds 	 */
223ec0c15afSLinus Torvalds 	outb(0xb0, 0x43);
224a977c400SThomas Gleixner 	outb(latch & 0xff, 0x42);
225a977c400SThomas Gleixner 	outb(latch >> 8, 0x42);
226ec0c15afSLinus Torvalds 
227ec0c15afSLinus Torvalds 	tsc = t1 = t2 = get_cycles();
228ec0c15afSLinus Torvalds 
229ec0c15afSLinus Torvalds 	pitcnt = 0;
230ec0c15afSLinus Torvalds 	tscmax = 0;
231ec0c15afSLinus Torvalds 	tscmin = ULONG_MAX;
232ec0c15afSLinus Torvalds 	while ((inb(0x61) & 0x20) == 0) {
233ec0c15afSLinus Torvalds 		t2 = get_cycles();
234ec0c15afSLinus Torvalds 		delta = t2 - tsc;
235ec0c15afSLinus Torvalds 		tsc = t2;
236ec0c15afSLinus Torvalds 		if ((unsigned long) delta < tscmin)
237ec0c15afSLinus Torvalds 			tscmin = (unsigned int) delta;
238ec0c15afSLinus Torvalds 		if ((unsigned long) delta > tscmax)
239ec0c15afSLinus Torvalds 			tscmax = (unsigned int) delta;
240ec0c15afSLinus Torvalds 		pitcnt++;
241ec0c15afSLinus Torvalds 	}
242ec0c15afSLinus Torvalds 
243ec0c15afSLinus Torvalds 	/*
244ec0c15afSLinus Torvalds 	 * Sanity checks:
245ec0c15afSLinus Torvalds 	 *
246a977c400SThomas Gleixner 	 * If we were not able to read the PIT more than loopmin
247ec0c15afSLinus Torvalds 	 * times, then we have been hit by a massive SMI
248ec0c15afSLinus Torvalds 	 *
249ec0c15afSLinus Torvalds 	 * If the maximum is 10 times larger than the minimum,
250ec0c15afSLinus Torvalds 	 * then we got hit by an SMI as well.
251ec0c15afSLinus Torvalds 	 */
252a977c400SThomas Gleixner 	if (pitcnt < loopmin || tscmax > 10 * tscmin)
253ec0c15afSLinus Torvalds 		return ULONG_MAX;
254ec0c15afSLinus Torvalds 
255ec0c15afSLinus Torvalds 	/* Calculate the PIT value */
256ec0c15afSLinus Torvalds 	delta = t2 - t1;
257a977c400SThomas Gleixner 	do_div(delta, ms);
258ec0c15afSLinus Torvalds 	return delta;
259ec0c15afSLinus Torvalds }
260ec0c15afSLinus Torvalds 
2616ac40ed0SLinus Torvalds /*
2626ac40ed0SLinus Torvalds  * This reads the current MSB of the PIT counter, and
2636ac40ed0SLinus Torvalds  * checks if we are running on sufficiently fast and
2646ac40ed0SLinus Torvalds  * non-virtualized hardware.
2656ac40ed0SLinus Torvalds  *
2666ac40ed0SLinus Torvalds  * Our expectations are:
2676ac40ed0SLinus Torvalds  *
2686ac40ed0SLinus Torvalds  *  - the PIT is running at roughly 1.19MHz
2696ac40ed0SLinus Torvalds  *
2706ac40ed0SLinus Torvalds  *  - each IO is going to take about 1us on real hardware,
2716ac40ed0SLinus Torvalds  *    but we allow it to be much faster (by a factor of 10) or
2726ac40ed0SLinus Torvalds  *    _slightly_ slower (ie we allow up to a 2us read+counter
2736ac40ed0SLinus Torvalds  *    update - anything else implies a unacceptably slow CPU
2746ac40ed0SLinus Torvalds  *    or PIT for the fast calibration to work.
2756ac40ed0SLinus Torvalds  *
2766ac40ed0SLinus Torvalds  *  - with 256 PIT ticks to read the value, we have 214us to
2776ac40ed0SLinus Torvalds  *    see the same MSB (and overhead like doing a single TSC
2786ac40ed0SLinus Torvalds  *    read per MSB value etc).
2796ac40ed0SLinus Torvalds  *
2806ac40ed0SLinus Torvalds  *  - We're doing 2 reads per loop (LSB, MSB), and we expect
2816ac40ed0SLinus Torvalds  *    them each to take about a microsecond on real hardware.
2826ac40ed0SLinus Torvalds  *    So we expect a count value of around 100. But we'll be
2836ac40ed0SLinus Torvalds  *    generous, and accept anything over 50.
2846ac40ed0SLinus Torvalds  *
2856ac40ed0SLinus Torvalds  *  - if the PIT is stuck, and we see *many* more reads, we
2866ac40ed0SLinus Torvalds  *    return early (and the next caller of pit_expect_msb()
2876ac40ed0SLinus Torvalds  *    then consider it a failure when they don't see the
2886ac40ed0SLinus Torvalds  *    next expected value).
2896ac40ed0SLinus Torvalds  *
2906ac40ed0SLinus Torvalds  * These expectations mean that we know that we have seen the
2916ac40ed0SLinus Torvalds  * transition from one expected value to another with a fairly
2926ac40ed0SLinus Torvalds  * high accuracy, and we didn't miss any events. We can thus
2936ac40ed0SLinus Torvalds  * use the TSC value at the transitions to calculate a pretty
2946ac40ed0SLinus Torvalds  * good value for the TSC frequencty.
2956ac40ed0SLinus Torvalds  */
296b6e61eefSLinus Torvalds static inline int pit_verify_msb(unsigned char val)
297b6e61eefSLinus Torvalds {
298b6e61eefSLinus Torvalds 	/* Ignore LSB */
299b6e61eefSLinus Torvalds 	inb(0x42);
300b6e61eefSLinus Torvalds 	return inb(0x42) == val;
301b6e61eefSLinus Torvalds }
302b6e61eefSLinus Torvalds 
3039e8912e0SLinus Torvalds static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
3046ac40ed0SLinus Torvalds {
3059e8912e0SLinus Torvalds 	int count;
30668f30fbeSLinus Torvalds 	u64 tsc = 0, prev_tsc = 0;
3076ac40ed0SLinus Torvalds 
3086ac40ed0SLinus Torvalds 	for (count = 0; count < 50000; count++) {
309b6e61eefSLinus Torvalds 		if (!pit_verify_msb(val))
3106ac40ed0SLinus Torvalds 			break;
31168f30fbeSLinus Torvalds 		prev_tsc = tsc;
3129e8912e0SLinus Torvalds 		tsc = get_cycles();
3136ac40ed0SLinus Torvalds 	}
31468f30fbeSLinus Torvalds 	*deltap = get_cycles() - prev_tsc;
3159e8912e0SLinus Torvalds 	*tscp = tsc;
3169e8912e0SLinus Torvalds 
3179e8912e0SLinus Torvalds 	/*
3189e8912e0SLinus Torvalds 	 * We require _some_ success, but the quality control
3199e8912e0SLinus Torvalds 	 * will be based on the error terms on the TSC values.
3209e8912e0SLinus Torvalds 	 */
3219e8912e0SLinus Torvalds 	return count > 5;
3226ac40ed0SLinus Torvalds }
3236ac40ed0SLinus Torvalds 
3246ac40ed0SLinus Torvalds /*
3259e8912e0SLinus Torvalds  * How many MSB values do we want to see? We aim for
3269e8912e0SLinus Torvalds  * a maximum error rate of 500ppm (in practice the
3279e8912e0SLinus Torvalds  * real error is much smaller), but refuse to spend
32868f30fbeSLinus Torvalds  * more than 50ms on it.
3296ac40ed0SLinus Torvalds  */
33068f30fbeSLinus Torvalds #define MAX_QUICK_PIT_MS 50
3319e8912e0SLinus Torvalds #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
3326ac40ed0SLinus Torvalds 
3336ac40ed0SLinus Torvalds static unsigned long quick_pit_calibrate(void)
3346ac40ed0SLinus Torvalds {
3359e8912e0SLinus Torvalds 	int i;
3369e8912e0SLinus Torvalds 	u64 tsc, delta;
3379e8912e0SLinus Torvalds 	unsigned long d1, d2;
3389e8912e0SLinus Torvalds 
3396ac40ed0SLinus Torvalds 	/* Set the Gate high, disable speaker */
3406ac40ed0SLinus Torvalds 	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
3416ac40ed0SLinus Torvalds 
3426ac40ed0SLinus Torvalds 	/*
3436ac40ed0SLinus Torvalds 	 * Counter 2, mode 0 (one-shot), binary count
3446ac40ed0SLinus Torvalds 	 *
3456ac40ed0SLinus Torvalds 	 * NOTE! Mode 2 decrements by two (and then the
3466ac40ed0SLinus Torvalds 	 * output is flipped each time, giving the same
3476ac40ed0SLinus Torvalds 	 * final output frequency as a decrement-by-one),
3486ac40ed0SLinus Torvalds 	 * so mode 0 is much better when looking at the
3496ac40ed0SLinus Torvalds 	 * individual counts.
3506ac40ed0SLinus Torvalds 	 */
3516ac40ed0SLinus Torvalds 	outb(0xb0, 0x43);
3526ac40ed0SLinus Torvalds 
3536ac40ed0SLinus Torvalds 	/* Start at 0xffff */
3546ac40ed0SLinus Torvalds 	outb(0xff, 0x42);
3556ac40ed0SLinus Torvalds 	outb(0xff, 0x42);
3566ac40ed0SLinus Torvalds 
357a6a80e1dSLinus Torvalds 	/*
358a6a80e1dSLinus Torvalds 	 * The PIT starts counting at the next edge, so we
359a6a80e1dSLinus Torvalds 	 * need to delay for a microsecond. The easiest way
360a6a80e1dSLinus Torvalds 	 * to do that is to just read back the 16-bit counter
361a6a80e1dSLinus Torvalds 	 * once from the PIT.
362a6a80e1dSLinus Torvalds 	 */
363b6e61eefSLinus Torvalds 	pit_verify_msb(0);
364a6a80e1dSLinus Torvalds 
3659e8912e0SLinus Torvalds 	if (pit_expect_msb(0xff, &tsc, &d1)) {
3669e8912e0SLinus Torvalds 		for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
3679e8912e0SLinus Torvalds 			if (!pit_expect_msb(0xff-i, &delta, &d2))
3689e8912e0SLinus Torvalds 				break;
3696ac40ed0SLinus Torvalds 
3706ac40ed0SLinus Torvalds 			/*
3719e8912e0SLinus Torvalds 			 * Iterate until the error is less than 500 ppm
3724156e9a8SIngo Molnar 			 */
3739e8912e0SLinus Torvalds 			delta -= tsc;
374b6e61eefSLinus Torvalds 			if (d1+d2 >= delta >> 11)
375b6e61eefSLinus Torvalds 				continue;
376b6e61eefSLinus Torvalds 
377b6e61eefSLinus Torvalds 			/*
378b6e61eefSLinus Torvalds 			 * Check the PIT one more time to verify that
379b6e61eefSLinus Torvalds 			 * all TSC reads were stable wrt the PIT.
380b6e61eefSLinus Torvalds 			 *
381b6e61eefSLinus Torvalds 			 * This also guarantees serialization of the
382b6e61eefSLinus Torvalds 			 * last cycle read ('d2') in pit_expect_msb.
383b6e61eefSLinus Torvalds 			 */
384b6e61eefSLinus Torvalds 			if (!pit_verify_msb(0xfe - i))
385b6e61eefSLinus Torvalds 				break;
3869e8912e0SLinus Torvalds 			goto success;
3879e8912e0SLinus Torvalds 		}
3889e8912e0SLinus Torvalds 	}
389c767a54bSJoe Perches 	pr_err("Fast TSC calibration failed\n");
3909e8912e0SLinus Torvalds 	return 0;
3914156e9a8SIngo Molnar 
3929e8912e0SLinus Torvalds success:
3934156e9a8SIngo Molnar 	/*
3946ac40ed0SLinus Torvalds 	 * Ok, if we get here, then we've seen the
3959e8912e0SLinus Torvalds 	 * MSB of the PIT decrement 'i' times, and the
3969e8912e0SLinus Torvalds 	 * error has shrunk to less than 500 ppm.
3976ac40ed0SLinus Torvalds 	 *
3986ac40ed0SLinus Torvalds 	 * As a result, we can depend on there not being
3996ac40ed0SLinus Torvalds 	 * any odd delays anywhere, and the TSC reads are
40068f30fbeSLinus Torvalds 	 * reliable (within the error).
4016ac40ed0SLinus Torvalds 	 *
4026ac40ed0SLinus Torvalds 	 * kHz = ticks / time-in-seconds / 1000;
4039e8912e0SLinus Torvalds 	 * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
4049e8912e0SLinus Torvalds 	 * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
4056ac40ed0SLinus Torvalds 	 */
4069e8912e0SLinus Torvalds 	delta *= PIT_TICK_RATE;
4079e8912e0SLinus Torvalds 	do_div(delta, i*256*1000);
408c767a54bSJoe Perches 	pr_info("Fast TSC calibration using PIT\n");
4096ac40ed0SLinus Torvalds 	return delta;
4106ac40ed0SLinus Torvalds }
411ec0c15afSLinus Torvalds 
412bfc0f594SAlok Kataria /**
413e93ef949SAlok Kataria  * native_calibrate_tsc - calibrate the tsc on boot
414bfc0f594SAlok Kataria  */
415e93ef949SAlok Kataria unsigned long native_calibrate_tsc(void)
416bfc0f594SAlok Kataria {
417827014beSThomas Gleixner 	u64 tsc1, tsc2, delta, ref1, ref2;
418fbb16e24SThomas Gleixner 	unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
4192d826404SThomas Gleixner 	unsigned long flags, latch, ms, fast_calibrate;
420a977c400SThomas Gleixner 	int hpet = is_hpet_enabled(), i, loopmin;
421bfc0f594SAlok Kataria 
422bfc0f594SAlok Kataria 	local_irq_save(flags);
4236ac40ed0SLinus Torvalds 	fast_calibrate = quick_pit_calibrate();
424bfc0f594SAlok Kataria 	local_irq_restore(flags);
4256ac40ed0SLinus Torvalds 	if (fast_calibrate)
4266ac40ed0SLinus Torvalds 		return fast_calibrate;
427fbb16e24SThomas Gleixner 
428fbb16e24SThomas Gleixner 	/*
429fbb16e24SThomas Gleixner 	 * Run 5 calibration loops to get the lowest frequency value
430fbb16e24SThomas Gleixner 	 * (the best estimate). We use two different calibration modes
431fbb16e24SThomas Gleixner 	 * here:
432fbb16e24SThomas Gleixner 	 *
433fbb16e24SThomas Gleixner 	 * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
434fbb16e24SThomas Gleixner 	 * load a timeout of 50ms. We read the time right after we
435fbb16e24SThomas Gleixner 	 * started the timer and wait until the PIT count down reaches
436fbb16e24SThomas Gleixner 	 * zero. In each wait loop iteration we read the TSC and check
437fbb16e24SThomas Gleixner 	 * the delta to the previous read. We keep track of the min
438fbb16e24SThomas Gleixner 	 * and max values of that delta. The delta is mostly defined
439fbb16e24SThomas Gleixner 	 * by the IO time of the PIT access, so we can detect when a
4400d2eb44fSLucas De Marchi 	 * SMI/SMM disturbance happened between the two reads. If the
441fbb16e24SThomas Gleixner 	 * maximum time is significantly larger than the minimum time,
442fbb16e24SThomas Gleixner 	 * then we discard the result and have another try.
443fbb16e24SThomas Gleixner 	 *
444fbb16e24SThomas Gleixner 	 * 2) Reference counter. If available we use the HPET or the
445fbb16e24SThomas Gleixner 	 * PMTIMER as a reference to check the sanity of that value.
446fbb16e24SThomas Gleixner 	 * We use separate TSC readouts and check inside of the
447fbb16e24SThomas Gleixner 	 * reference read for a SMI/SMM disturbance. We dicard
448fbb16e24SThomas Gleixner 	 * disturbed values here as well. We do that around the PIT
449fbb16e24SThomas Gleixner 	 * calibration delay loop as we have to wait for a certain
450fbb16e24SThomas Gleixner 	 * amount of time anyway.
451fbb16e24SThomas Gleixner 	 */
452a977c400SThomas Gleixner 
453a977c400SThomas Gleixner 	/* Preset PIT loop values */
454a977c400SThomas Gleixner 	latch = CAL_LATCH;
455a977c400SThomas Gleixner 	ms = CAL_MS;
456a977c400SThomas Gleixner 	loopmin = CAL_PIT_LOOPS;
457a977c400SThomas Gleixner 
458a977c400SThomas Gleixner 	for (i = 0; i < 3; i++) {
459ec0c15afSLinus Torvalds 		unsigned long tsc_pit_khz;
460bfc0f594SAlok Kataria 
461fbb16e24SThomas Gleixner 		/*
462fbb16e24SThomas Gleixner 		 * Read the start value and the reference count of
463ec0c15afSLinus Torvalds 		 * hpet/pmtimer when available. Then do the PIT
464ec0c15afSLinus Torvalds 		 * calibration, which will take at least 50ms, and
465ec0c15afSLinus Torvalds 		 * read the end value.
466fbb16e24SThomas Gleixner 		 */
467ec0c15afSLinus Torvalds 		local_irq_save(flags);
468827014beSThomas Gleixner 		tsc1 = tsc_read_refs(&ref1, hpet);
469a977c400SThomas Gleixner 		tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
470827014beSThomas Gleixner 		tsc2 = tsc_read_refs(&ref2, hpet);
471bfc0f594SAlok Kataria 		local_irq_restore(flags);
472bfc0f594SAlok Kataria 
473ec0c15afSLinus Torvalds 		/* Pick the lowest PIT TSC calibration so far */
474ec0c15afSLinus Torvalds 		tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
475bfc0f594SAlok Kataria 
476bfc0f594SAlok Kataria 		/* hpet or pmtimer available ? */
47762627becSJohn Stultz 		if (ref1 == ref2)
478fbb16e24SThomas Gleixner 			continue;
479bfc0f594SAlok Kataria 
480bfc0f594SAlok Kataria 		/* Check, whether the sampling was disturbed by an SMI */
481fbb16e24SThomas Gleixner 		if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
482fbb16e24SThomas Gleixner 			continue;
483bfc0f594SAlok Kataria 
484bfc0f594SAlok Kataria 		tsc2 = (tsc2 - tsc1) * 1000000LL;
485d683ef7aSThomas Gleixner 		if (hpet)
486827014beSThomas Gleixner 			tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
487d683ef7aSThomas Gleixner 		else
488827014beSThomas Gleixner 			tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
489bfc0f594SAlok Kataria 
490fbb16e24SThomas Gleixner 		tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
491a977c400SThomas Gleixner 
492a977c400SThomas Gleixner 		/* Check the reference deviation */
493a977c400SThomas Gleixner 		delta = ((u64) tsc_pit_min) * 100;
494a977c400SThomas Gleixner 		do_div(delta, tsc_ref_min);
495a977c400SThomas Gleixner 
496a977c400SThomas Gleixner 		/*
497a977c400SThomas Gleixner 		 * If both calibration results are inside a 10% window
498a977c400SThomas Gleixner 		 * then we can be sure, that the calibration
499a977c400SThomas Gleixner 		 * succeeded. We break out of the loop right away. We
500a977c400SThomas Gleixner 		 * use the reference value, as it is more precise.
501a977c400SThomas Gleixner 		 */
502a977c400SThomas Gleixner 		if (delta >= 90 && delta <= 110) {
503c767a54bSJoe Perches 			pr_info("PIT calibration matches %s. %d loops\n",
504a977c400SThomas Gleixner 				hpet ? "HPET" : "PMTIMER", i + 1);
505a977c400SThomas Gleixner 			return tsc_ref_min;
506bfc0f594SAlok Kataria 		}
507bfc0f594SAlok Kataria 
508a977c400SThomas Gleixner 		/*
509a977c400SThomas Gleixner 		 * Check whether PIT failed more than once. This
510a977c400SThomas Gleixner 		 * happens in virtualized environments. We need to
511a977c400SThomas Gleixner 		 * give the virtual PC a slightly longer timeframe for
512a977c400SThomas Gleixner 		 * the HPET/PMTIMER to make the result precise.
513a977c400SThomas Gleixner 		 */
514a977c400SThomas Gleixner 		if (i == 1 && tsc_pit_min == ULONG_MAX) {
515a977c400SThomas Gleixner 			latch = CAL2_LATCH;
516a977c400SThomas Gleixner 			ms = CAL2_MS;
517a977c400SThomas Gleixner 			loopmin = CAL2_PIT_LOOPS;
518a977c400SThomas Gleixner 		}
519bfc0f594SAlok Kataria 	}
520bfc0f594SAlok Kataria 
521fbb16e24SThomas Gleixner 	/*
522fbb16e24SThomas Gleixner 	 * Now check the results.
523fbb16e24SThomas Gleixner 	 */
524fbb16e24SThomas Gleixner 	if (tsc_pit_min == ULONG_MAX) {
525fbb16e24SThomas Gleixner 		/* PIT gave no useful value */
526c767a54bSJoe Perches 		pr_warn("Unable to calibrate against PIT\n");
527fbb16e24SThomas Gleixner 
528fbb16e24SThomas Gleixner 		/* We don't have an alternative source, disable TSC */
529827014beSThomas Gleixner 		if (!hpet && !ref1 && !ref2) {
530c767a54bSJoe Perches 			pr_notice("No reference (HPET/PMTIMER) available\n");
531fbb16e24SThomas Gleixner 			return 0;
532fbb16e24SThomas Gleixner 		}
533fbb16e24SThomas Gleixner 
534fbb16e24SThomas Gleixner 		/* The alternative source failed as well, disable TSC */
535fbb16e24SThomas Gleixner 		if (tsc_ref_min == ULONG_MAX) {
536c767a54bSJoe Perches 			pr_warn("HPET/PMTIMER calibration failed\n");
537fbb16e24SThomas Gleixner 			return 0;
538fbb16e24SThomas Gleixner 		}
539fbb16e24SThomas Gleixner 
540fbb16e24SThomas Gleixner 		/* Use the alternative source */
541c767a54bSJoe Perches 		pr_info("using %s reference calibration\n",
542fbb16e24SThomas Gleixner 			hpet ? "HPET" : "PMTIMER");
543fbb16e24SThomas Gleixner 
544fbb16e24SThomas Gleixner 		return tsc_ref_min;
545fbb16e24SThomas Gleixner 	}
546fbb16e24SThomas Gleixner 
547fbb16e24SThomas Gleixner 	/* We don't have an alternative source, use the PIT calibration value */
548827014beSThomas Gleixner 	if (!hpet && !ref1 && !ref2) {
549c767a54bSJoe Perches 		pr_info("Using PIT calibration value\n");
550fbb16e24SThomas Gleixner 		return tsc_pit_min;
551fbb16e24SThomas Gleixner 	}
552fbb16e24SThomas Gleixner 
553fbb16e24SThomas Gleixner 	/* The alternative source failed, use the PIT calibration value */
554fbb16e24SThomas Gleixner 	if (tsc_ref_min == ULONG_MAX) {
555c767a54bSJoe Perches 		pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
556fbb16e24SThomas Gleixner 		return tsc_pit_min;
557fbb16e24SThomas Gleixner 	}
558fbb16e24SThomas Gleixner 
559fbb16e24SThomas Gleixner 	/*
560fbb16e24SThomas Gleixner 	 * The calibration values differ too much. In doubt, we use
561fbb16e24SThomas Gleixner 	 * the PIT value as we know that there are PMTIMERs around
562a977c400SThomas Gleixner 	 * running at double speed. At least we let the user know:
563fbb16e24SThomas Gleixner 	 */
564c767a54bSJoe Perches 	pr_warn("PIT calibration deviates from %s: %lu %lu\n",
565a977c400SThomas Gleixner 		hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
566c767a54bSJoe Perches 	pr_info("Using PIT calibration value\n");
567fbb16e24SThomas Gleixner 	return tsc_pit_min;
568fbb16e24SThomas Gleixner }
569bfc0f594SAlok Kataria 
570bfc0f594SAlok Kataria int recalibrate_cpu_khz(void)
571bfc0f594SAlok Kataria {
572bfc0f594SAlok Kataria #ifndef CONFIG_SMP
573bfc0f594SAlok Kataria 	unsigned long cpu_khz_old = cpu_khz;
574bfc0f594SAlok Kataria 
575bfc0f594SAlok Kataria 	if (cpu_has_tsc) {
5762d826404SThomas Gleixner 		tsc_khz = x86_platform.calibrate_tsc();
577e93ef949SAlok Kataria 		cpu_khz = tsc_khz;
578bfc0f594SAlok Kataria 		cpu_data(0).loops_per_jiffy =
579bfc0f594SAlok Kataria 			cpufreq_scale(cpu_data(0).loops_per_jiffy,
580bfc0f594SAlok Kataria 					cpu_khz_old, cpu_khz);
581bfc0f594SAlok Kataria 		return 0;
582bfc0f594SAlok Kataria 	} else
583bfc0f594SAlok Kataria 		return -ENODEV;
584bfc0f594SAlok Kataria #else
585bfc0f594SAlok Kataria 	return -ENODEV;
586bfc0f594SAlok Kataria #endif
587bfc0f594SAlok Kataria }
588bfc0f594SAlok Kataria 
589bfc0f594SAlok Kataria EXPORT_SYMBOL(recalibrate_cpu_khz);
590bfc0f594SAlok Kataria 
5912dbe06faSAlok Kataria 
5922dbe06faSAlok Kataria /* Accelerators for sched_clock()
5932dbe06faSAlok Kataria  * convert from cycles(64bits) => nanoseconds (64bits)
5942dbe06faSAlok Kataria  *  basic equation:
5952dbe06faSAlok Kataria  *              ns = cycles / (freq / ns_per_sec)
5962dbe06faSAlok Kataria  *              ns = cycles * (ns_per_sec / freq)
5972dbe06faSAlok Kataria  *              ns = cycles * (10^9 / (cpu_khz * 10^3))
5982dbe06faSAlok Kataria  *              ns = cycles * (10^6 / cpu_khz)
5992dbe06faSAlok Kataria  *
6002dbe06faSAlok Kataria  *      Then we use scaling math (suggested by george@mvista.com) to get:
6012dbe06faSAlok Kataria  *              ns = cycles * (10^6 * SC / cpu_khz) / SC
6022dbe06faSAlok Kataria  *              ns = cycles * cyc2ns_scale / SC
6032dbe06faSAlok Kataria  *
6042dbe06faSAlok Kataria  *      And since SC is a constant power of two, we can convert the div
6052dbe06faSAlok Kataria  *  into a shift.
6062dbe06faSAlok Kataria  *
6072dbe06faSAlok Kataria  *  We can use khz divisor instead of mhz to keep a better precision, since
6082dbe06faSAlok Kataria  *  cyc2ns_scale is limited to 10^6 * 2^10, which fits in 32 bits.
6092dbe06faSAlok Kataria  *  (mathieu.desnoyers@polymtl.ca)
6102dbe06faSAlok Kataria  *
6112dbe06faSAlok Kataria  *                      -johnstul@us.ibm.com "math is hard, lets go shopping!"
6122dbe06faSAlok Kataria  */
6132dbe06faSAlok Kataria 
6142dbe06faSAlok Kataria DEFINE_PER_CPU(unsigned long, cyc2ns);
61584599f8aSPeter Zijlstra DEFINE_PER_CPU(unsigned long long, cyc2ns_offset);
6162dbe06faSAlok Kataria 
6178fbbc4b4SAlok Kataria static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
6182dbe06faSAlok Kataria {
61984599f8aSPeter Zijlstra 	unsigned long long tsc_now, ns_now, *offset;
6202dbe06faSAlok Kataria 	unsigned long flags, *scale;
6212dbe06faSAlok Kataria 
6222dbe06faSAlok Kataria 	local_irq_save(flags);
6232dbe06faSAlok Kataria 	sched_clock_idle_sleep_event();
6242dbe06faSAlok Kataria 
6252dbe06faSAlok Kataria 	scale = &per_cpu(cyc2ns, cpu);
62684599f8aSPeter Zijlstra 	offset = &per_cpu(cyc2ns_offset, cpu);
6272dbe06faSAlok Kataria 
6282dbe06faSAlok Kataria 	rdtscll(tsc_now);
6292dbe06faSAlok Kataria 	ns_now = __cycles_2_ns(tsc_now);
6302dbe06faSAlok Kataria 
63184599f8aSPeter Zijlstra 	if (cpu_khz) {
6322353b47bSBernd Faust 		*scale = ((NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR) +
6332353b47bSBernd Faust 				cpu_khz / 2) / cpu_khz;
6349993bc63SSalman Qazi 		*offset = ns_now - mult_frac(tsc_now, *scale,
6359993bc63SSalman Qazi 					     (1UL << CYC2NS_SCALE_FACTOR));
63684599f8aSPeter Zijlstra 	}
6372dbe06faSAlok Kataria 
6382dbe06faSAlok Kataria 	sched_clock_idle_wakeup_event(0);
6392dbe06faSAlok Kataria 	local_irq_restore(flags);
6402dbe06faSAlok Kataria }
6412dbe06faSAlok Kataria 
642cd7240c0SSuresh Siddha static unsigned long long cyc2ns_suspend;
643cd7240c0SSuresh Siddha 
644b74f05d6SMarcelo Tosatti void tsc_save_sched_clock_state(void)
645cd7240c0SSuresh Siddha {
646cd7240c0SSuresh Siddha 	if (!sched_clock_stable)
647cd7240c0SSuresh Siddha 		return;
648cd7240c0SSuresh Siddha 
649cd7240c0SSuresh Siddha 	cyc2ns_suspend = sched_clock();
650cd7240c0SSuresh Siddha }
651cd7240c0SSuresh Siddha 
652cd7240c0SSuresh Siddha /*
653cd7240c0SSuresh Siddha  * Even on processors with invariant TSC, TSC gets reset in some the
654cd7240c0SSuresh Siddha  * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
655cd7240c0SSuresh Siddha  * arbitrary value (still sync'd across cpu's) during resume from such sleep
656cd7240c0SSuresh Siddha  * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
657cd7240c0SSuresh Siddha  * that sched_clock() continues from the point where it was left off during
658cd7240c0SSuresh Siddha  * suspend.
659cd7240c0SSuresh Siddha  */
660b74f05d6SMarcelo Tosatti void tsc_restore_sched_clock_state(void)
661cd7240c0SSuresh Siddha {
662cd7240c0SSuresh Siddha 	unsigned long long offset;
663cd7240c0SSuresh Siddha 	unsigned long flags;
664cd7240c0SSuresh Siddha 	int cpu;
665cd7240c0SSuresh Siddha 
666cd7240c0SSuresh Siddha 	if (!sched_clock_stable)
667cd7240c0SSuresh Siddha 		return;
668cd7240c0SSuresh Siddha 
669cd7240c0SSuresh Siddha 	local_irq_save(flags);
670cd7240c0SSuresh Siddha 
6710a3aee0dSTejun Heo 	__this_cpu_write(cyc2ns_offset, 0);
672cd7240c0SSuresh Siddha 	offset = cyc2ns_suspend - sched_clock();
673cd7240c0SSuresh Siddha 
674cd7240c0SSuresh Siddha 	for_each_possible_cpu(cpu)
675cd7240c0SSuresh Siddha 		per_cpu(cyc2ns_offset, cpu) = offset;
676cd7240c0SSuresh Siddha 
677cd7240c0SSuresh Siddha 	local_irq_restore(flags);
678cd7240c0SSuresh Siddha }
679cd7240c0SSuresh Siddha 
6802dbe06faSAlok Kataria #ifdef CONFIG_CPU_FREQ
6812dbe06faSAlok Kataria 
6822dbe06faSAlok Kataria /* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
6832dbe06faSAlok Kataria  * changes.
6842dbe06faSAlok Kataria  *
6852dbe06faSAlok Kataria  * RED-PEN: On SMP we assume all CPUs run with the same frequency.  It's
6862dbe06faSAlok Kataria  * not that important because current Opteron setups do not support
6872dbe06faSAlok Kataria  * scaling on SMP anyroads.
6882dbe06faSAlok Kataria  *
6892dbe06faSAlok Kataria  * Should fix up last_tsc too. Currently gettimeofday in the
6902dbe06faSAlok Kataria  * first tick after the change will be slightly wrong.
6912dbe06faSAlok Kataria  */
6922dbe06faSAlok Kataria 
6932dbe06faSAlok Kataria static unsigned int  ref_freq;
6942dbe06faSAlok Kataria static unsigned long loops_per_jiffy_ref;
6952dbe06faSAlok Kataria static unsigned long tsc_khz_ref;
6962dbe06faSAlok Kataria 
6972dbe06faSAlok Kataria static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
6982dbe06faSAlok Kataria 				void *data)
6992dbe06faSAlok Kataria {
7002dbe06faSAlok Kataria 	struct cpufreq_freqs *freq = data;
701931db6a3SDave Jones 	unsigned long *lpj;
7022dbe06faSAlok Kataria 
7032dbe06faSAlok Kataria 	if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
7042dbe06faSAlok Kataria 		return 0;
7052dbe06faSAlok Kataria 
7062dbe06faSAlok Kataria 	lpj = &boot_cpu_data.loops_per_jiffy;
707931db6a3SDave Jones #ifdef CONFIG_SMP
708931db6a3SDave Jones 	if (!(freq->flags & CPUFREQ_CONST_LOOPS))
709931db6a3SDave Jones 		lpj = &cpu_data(freq->cpu).loops_per_jiffy;
7102dbe06faSAlok Kataria #endif
7112dbe06faSAlok Kataria 
7122dbe06faSAlok Kataria 	if (!ref_freq) {
7132dbe06faSAlok Kataria 		ref_freq = freq->old;
7142dbe06faSAlok Kataria 		loops_per_jiffy_ref = *lpj;
7152dbe06faSAlok Kataria 		tsc_khz_ref = tsc_khz;
7162dbe06faSAlok Kataria 	}
7172dbe06faSAlok Kataria 	if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
7182dbe06faSAlok Kataria 			(val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
7192dbe06faSAlok Kataria 			(val == CPUFREQ_RESUMECHANGE)) {
7202dbe06faSAlok Kataria 		*lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
7212dbe06faSAlok Kataria 
7222dbe06faSAlok Kataria 		tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
7232dbe06faSAlok Kataria 		if (!(freq->flags & CPUFREQ_CONST_LOOPS))
7242dbe06faSAlok Kataria 			mark_tsc_unstable("cpufreq changes");
7252dbe06faSAlok Kataria 	}
7262dbe06faSAlok Kataria 
72752a8968cSPeter Zijlstra 	set_cyc2ns_scale(tsc_khz, freq->cpu);
7282dbe06faSAlok Kataria 
7292dbe06faSAlok Kataria 	return 0;
7302dbe06faSAlok Kataria }
7312dbe06faSAlok Kataria 
7322dbe06faSAlok Kataria static struct notifier_block time_cpufreq_notifier_block = {
7332dbe06faSAlok Kataria 	.notifier_call  = time_cpufreq_notifier
7342dbe06faSAlok Kataria };
7352dbe06faSAlok Kataria 
7362dbe06faSAlok Kataria static int __init cpufreq_tsc(void)
7372dbe06faSAlok Kataria {
738060700b5SLinus Torvalds 	if (!cpu_has_tsc)
739060700b5SLinus Torvalds 		return 0;
740060700b5SLinus Torvalds 	if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
741060700b5SLinus Torvalds 		return 0;
7422dbe06faSAlok Kataria 	cpufreq_register_notifier(&time_cpufreq_notifier_block,
7432dbe06faSAlok Kataria 				CPUFREQ_TRANSITION_NOTIFIER);
7442dbe06faSAlok Kataria 	return 0;
7452dbe06faSAlok Kataria }
7462dbe06faSAlok Kataria 
7472dbe06faSAlok Kataria core_initcall(cpufreq_tsc);
7482dbe06faSAlok Kataria 
7492dbe06faSAlok Kataria #endif /* CONFIG_CPU_FREQ */
7508fbbc4b4SAlok Kataria 
7518fbbc4b4SAlok Kataria /* clocksource code */
7528fbbc4b4SAlok Kataria 
7538fbbc4b4SAlok Kataria static struct clocksource clocksource_tsc;
7548fbbc4b4SAlok Kataria 
7558fbbc4b4SAlok Kataria /*
7568fbbc4b4SAlok Kataria  * We compare the TSC to the cycle_last value in the clocksource
7578fbbc4b4SAlok Kataria  * structure to avoid a nasty time-warp. This can be observed in a
7588fbbc4b4SAlok Kataria  * very small window right after one CPU updated cycle_last under
7598fbbc4b4SAlok Kataria  * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
7608fbbc4b4SAlok Kataria  * is smaller than the cycle_last reference value due to a TSC which
7618fbbc4b4SAlok Kataria  * is slighty behind. This delta is nowhere else observable, but in
7628fbbc4b4SAlok Kataria  * that case it results in a forward time jump in the range of hours
7638fbbc4b4SAlok Kataria  * due to the unsigned delta calculation of the time keeping core
7648fbbc4b4SAlok Kataria  * code, which is necessary to support wrapping clocksources like pm
7658fbbc4b4SAlok Kataria  * timer.
7668fbbc4b4SAlok Kataria  */
7678e19608eSMagnus Damm static cycle_t read_tsc(struct clocksource *cs)
7688fbbc4b4SAlok Kataria {
7698fbbc4b4SAlok Kataria 	cycle_t ret = (cycle_t)get_cycles();
7708fbbc4b4SAlok Kataria 
7718fbbc4b4SAlok Kataria 	return ret >= clocksource_tsc.cycle_last ?
7728fbbc4b4SAlok Kataria 		ret : clocksource_tsc.cycle_last;
7738fbbc4b4SAlok Kataria }
7748fbbc4b4SAlok Kataria 
77517622339SMagnus Damm static void resume_tsc(struct clocksource *cs)
7761be39679SMartin Schwidefsky {
77782f9c080SFeng Tang 	if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
7781be39679SMartin Schwidefsky 		clocksource_tsc.cycle_last = 0;
7791be39679SMartin Schwidefsky }
7801be39679SMartin Schwidefsky 
7818fbbc4b4SAlok Kataria static struct clocksource clocksource_tsc = {
7828fbbc4b4SAlok Kataria 	.name                   = "tsc",
7838fbbc4b4SAlok Kataria 	.rating                 = 300,
7848fbbc4b4SAlok Kataria 	.read                   = read_tsc,
7851be39679SMartin Schwidefsky 	.resume			= resume_tsc,
7868fbbc4b4SAlok Kataria 	.mask                   = CLOCKSOURCE_MASK(64),
7878fbbc4b4SAlok Kataria 	.flags                  = CLOCK_SOURCE_IS_CONTINUOUS |
7888fbbc4b4SAlok Kataria 				  CLOCK_SOURCE_MUST_VERIFY,
7898fbbc4b4SAlok Kataria #ifdef CONFIG_X86_64
79098d0ac38SAndy Lutomirski 	.archdata               = { .vclock_mode = VCLOCK_TSC },
7918fbbc4b4SAlok Kataria #endif
7928fbbc4b4SAlok Kataria };
7938fbbc4b4SAlok Kataria 
7948fbbc4b4SAlok Kataria void mark_tsc_unstable(char *reason)
7958fbbc4b4SAlok Kataria {
7968fbbc4b4SAlok Kataria 	if (!tsc_unstable) {
7978fbbc4b4SAlok Kataria 		tsc_unstable = 1;
7986c56ccecSPallipadi, Venkatesh 		sched_clock_stable = 0;
799e82b8e4eSVenkatesh Pallipadi 		disable_sched_clock_irqtime();
800c767a54bSJoe Perches 		pr_info("Marking TSC unstable due to %s\n", reason);
8018fbbc4b4SAlok Kataria 		/* Change only the rating, when not registered */
8028fbbc4b4SAlok Kataria 		if (clocksource_tsc.mult)
8037285dd7fSThomas Gleixner 			clocksource_mark_unstable(&clocksource_tsc);
8047285dd7fSThomas Gleixner 		else {
8057285dd7fSThomas Gleixner 			clocksource_tsc.flags |= CLOCK_SOURCE_UNSTABLE;
8068fbbc4b4SAlok Kataria 			clocksource_tsc.rating = 0;
8078fbbc4b4SAlok Kataria 		}
8088fbbc4b4SAlok Kataria 	}
8097285dd7fSThomas Gleixner }
8108fbbc4b4SAlok Kataria 
8118fbbc4b4SAlok Kataria EXPORT_SYMBOL_GPL(mark_tsc_unstable);
8128fbbc4b4SAlok Kataria 
813395628efSAlok Kataria static void __init check_system_tsc_reliable(void)
814395628efSAlok Kataria {
8158fbbc4b4SAlok Kataria #ifdef CONFIG_MGEODE_LX
8168fbbc4b4SAlok Kataria 	/* RTSC counts during suspend */
8178fbbc4b4SAlok Kataria #define RTSC_SUSP 0x100
8188fbbc4b4SAlok Kataria 	unsigned long res_low, res_high;
8198fbbc4b4SAlok Kataria 
8208fbbc4b4SAlok Kataria 	rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
82100097c4fSThadeu Lima de Souza Cascardo 	/* Geode_LX - the OLPC CPU has a very reliable TSC */
8228fbbc4b4SAlok Kataria 	if (res_low & RTSC_SUSP)
823395628efSAlok Kataria 		tsc_clocksource_reliable = 1;
8248fbbc4b4SAlok Kataria #endif
825395628efSAlok Kataria 	if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
826395628efSAlok Kataria 		tsc_clocksource_reliable = 1;
827395628efSAlok Kataria }
8288fbbc4b4SAlok Kataria 
8298fbbc4b4SAlok Kataria /*
8308fbbc4b4SAlok Kataria  * Make an educated guess if the TSC is trustworthy and synchronized
8318fbbc4b4SAlok Kataria  * over all CPUs.
8328fbbc4b4SAlok Kataria  */
833148f9bb8SPaul Gortmaker int unsynchronized_tsc(void)
8348fbbc4b4SAlok Kataria {
8358fbbc4b4SAlok Kataria 	if (!cpu_has_tsc || tsc_unstable)
8368fbbc4b4SAlok Kataria 		return 1;
8378fbbc4b4SAlok Kataria 
8383e5095d1SIngo Molnar #ifdef CONFIG_SMP
8398fbbc4b4SAlok Kataria 	if (apic_is_clustered_box())
8408fbbc4b4SAlok Kataria 		return 1;
8418fbbc4b4SAlok Kataria #endif
8428fbbc4b4SAlok Kataria 
8438fbbc4b4SAlok Kataria 	if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8448fbbc4b4SAlok Kataria 		return 0;
845d3b8f889Sjohn stultz 
846d3b8f889Sjohn stultz 	if (tsc_clocksource_reliable)
847d3b8f889Sjohn stultz 		return 0;
8488fbbc4b4SAlok Kataria 	/*
8498fbbc4b4SAlok Kataria 	 * Intel systems are normally all synchronized.
8508fbbc4b4SAlok Kataria 	 * Exceptions must mark TSC as unstable:
8518fbbc4b4SAlok Kataria 	 */
8528fbbc4b4SAlok Kataria 	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
8538fbbc4b4SAlok Kataria 		/* assume multi socket systems are not synchronized: */
8548fbbc4b4SAlok Kataria 		if (num_possible_cpus() > 1)
855d3b8f889Sjohn stultz 			return 1;
8568fbbc4b4SAlok Kataria 	}
8578fbbc4b4SAlok Kataria 
858d3b8f889Sjohn stultz 	return 0;
8598fbbc4b4SAlok Kataria }
8608fbbc4b4SAlok Kataria 
86108ec0c58SJohn Stultz 
86208ec0c58SJohn Stultz static void tsc_refine_calibration_work(struct work_struct *work);
86308ec0c58SJohn Stultz static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
86408ec0c58SJohn Stultz /**
86508ec0c58SJohn Stultz  * tsc_refine_calibration_work - Further refine tsc freq calibration
86608ec0c58SJohn Stultz  * @work - ignored.
86708ec0c58SJohn Stultz  *
86808ec0c58SJohn Stultz  * This functions uses delayed work over a period of a
86908ec0c58SJohn Stultz  * second to further refine the TSC freq value. Since this is
87008ec0c58SJohn Stultz  * timer based, instead of loop based, we don't block the boot
87108ec0c58SJohn Stultz  * process while this longer calibration is done.
87208ec0c58SJohn Stultz  *
8730d2eb44fSLucas De Marchi  * If there are any calibration anomalies (too many SMIs, etc),
87408ec0c58SJohn Stultz  * or the refined calibration is off by 1% of the fast early
87508ec0c58SJohn Stultz  * calibration, we throw out the new calibration and use the
87608ec0c58SJohn Stultz  * early calibration.
87708ec0c58SJohn Stultz  */
87808ec0c58SJohn Stultz static void tsc_refine_calibration_work(struct work_struct *work)
87908ec0c58SJohn Stultz {
88008ec0c58SJohn Stultz 	static u64 tsc_start = -1, ref_start;
88108ec0c58SJohn Stultz 	static int hpet;
88208ec0c58SJohn Stultz 	u64 tsc_stop, ref_stop, delta;
88308ec0c58SJohn Stultz 	unsigned long freq;
88408ec0c58SJohn Stultz 
88508ec0c58SJohn Stultz 	/* Don't bother refining TSC on unstable systems */
88608ec0c58SJohn Stultz 	if (check_tsc_unstable())
88708ec0c58SJohn Stultz 		goto out;
88808ec0c58SJohn Stultz 
88908ec0c58SJohn Stultz 	/*
89008ec0c58SJohn Stultz 	 * Since the work is started early in boot, we may be
89108ec0c58SJohn Stultz 	 * delayed the first time we expire. So set the workqueue
89208ec0c58SJohn Stultz 	 * again once we know timers are working.
89308ec0c58SJohn Stultz 	 */
89408ec0c58SJohn Stultz 	if (tsc_start == -1) {
89508ec0c58SJohn Stultz 		/*
89608ec0c58SJohn Stultz 		 * Only set hpet once, to avoid mixing hardware
89708ec0c58SJohn Stultz 		 * if the hpet becomes enabled later.
89808ec0c58SJohn Stultz 		 */
89908ec0c58SJohn Stultz 		hpet = is_hpet_enabled();
90008ec0c58SJohn Stultz 		schedule_delayed_work(&tsc_irqwork, HZ);
90108ec0c58SJohn Stultz 		tsc_start = tsc_read_refs(&ref_start, hpet);
90208ec0c58SJohn Stultz 		return;
90308ec0c58SJohn Stultz 	}
90408ec0c58SJohn Stultz 
90508ec0c58SJohn Stultz 	tsc_stop = tsc_read_refs(&ref_stop, hpet);
90608ec0c58SJohn Stultz 
90708ec0c58SJohn Stultz 	/* hpet or pmtimer available ? */
90862627becSJohn Stultz 	if (ref_start == ref_stop)
90908ec0c58SJohn Stultz 		goto out;
91008ec0c58SJohn Stultz 
91108ec0c58SJohn Stultz 	/* Check, whether the sampling was disturbed by an SMI */
91208ec0c58SJohn Stultz 	if (tsc_start == ULLONG_MAX || tsc_stop == ULLONG_MAX)
91308ec0c58SJohn Stultz 		goto out;
91408ec0c58SJohn Stultz 
91508ec0c58SJohn Stultz 	delta = tsc_stop - tsc_start;
91608ec0c58SJohn Stultz 	delta *= 1000000LL;
91708ec0c58SJohn Stultz 	if (hpet)
91808ec0c58SJohn Stultz 		freq = calc_hpet_ref(delta, ref_start, ref_stop);
91908ec0c58SJohn Stultz 	else
92008ec0c58SJohn Stultz 		freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
92108ec0c58SJohn Stultz 
92208ec0c58SJohn Stultz 	/* Make sure we're within 1% */
92308ec0c58SJohn Stultz 	if (abs(tsc_khz - freq) > tsc_khz/100)
92408ec0c58SJohn Stultz 		goto out;
92508ec0c58SJohn Stultz 
92608ec0c58SJohn Stultz 	tsc_khz = freq;
927c767a54bSJoe Perches 	pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
928c767a54bSJoe Perches 		(unsigned long)tsc_khz / 1000,
92908ec0c58SJohn Stultz 		(unsigned long)tsc_khz % 1000);
93008ec0c58SJohn Stultz 
93108ec0c58SJohn Stultz out:
93208ec0c58SJohn Stultz 	clocksource_register_khz(&clocksource_tsc, tsc_khz);
93308ec0c58SJohn Stultz }
93408ec0c58SJohn Stultz 
93508ec0c58SJohn Stultz 
93608ec0c58SJohn Stultz static int __init init_tsc_clocksource(void)
9378fbbc4b4SAlok Kataria {
93829fe359cSThomas Gleixner 	if (!cpu_has_tsc || tsc_disabled > 0 || !tsc_khz)
939a8760ecaSThomas Gleixner 		return 0;
940a8760ecaSThomas Gleixner 
941395628efSAlok Kataria 	if (tsc_clocksource_reliable)
942395628efSAlok Kataria 		clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
9438fbbc4b4SAlok Kataria 	/* lower the rating if we already know its unstable: */
9448fbbc4b4SAlok Kataria 	if (check_tsc_unstable()) {
9458fbbc4b4SAlok Kataria 		clocksource_tsc.rating = 0;
9468fbbc4b4SAlok Kataria 		clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
9478fbbc4b4SAlok Kataria 	}
94857779dc2SAlok Kataria 
94982f9c080SFeng Tang 	if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
95082f9c080SFeng Tang 		clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
95182f9c080SFeng Tang 
95257779dc2SAlok Kataria 	/*
95357779dc2SAlok Kataria 	 * Trust the results of the earlier calibration on systems
95457779dc2SAlok Kataria 	 * exporting a reliable TSC.
95557779dc2SAlok Kataria 	 */
95657779dc2SAlok Kataria 	if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE)) {
95757779dc2SAlok Kataria 		clocksource_register_khz(&clocksource_tsc, tsc_khz);
95857779dc2SAlok Kataria 		return 0;
95957779dc2SAlok Kataria 	}
96057779dc2SAlok Kataria 
96108ec0c58SJohn Stultz 	schedule_delayed_work(&tsc_irqwork, 0);
96208ec0c58SJohn Stultz 	return 0;
9638fbbc4b4SAlok Kataria }
96408ec0c58SJohn Stultz /*
96508ec0c58SJohn Stultz  * We use device_initcall here, to ensure we run after the hpet
96608ec0c58SJohn Stultz  * is fully initialized, which may occur at fs_initcall time.
96708ec0c58SJohn Stultz  */
96808ec0c58SJohn Stultz device_initcall(init_tsc_clocksource);
9698fbbc4b4SAlok Kataria 
9708fbbc4b4SAlok Kataria void __init tsc_init(void)
9718fbbc4b4SAlok Kataria {
9728fbbc4b4SAlok Kataria 	u64 lpj;
9738fbbc4b4SAlok Kataria 	int cpu;
9748fbbc4b4SAlok Kataria 
975845b3944SThomas Gleixner 	x86_init.timers.tsc_pre_init();
976845b3944SThomas Gleixner 
9778fbbc4b4SAlok Kataria 	if (!cpu_has_tsc)
9788fbbc4b4SAlok Kataria 		return;
9798fbbc4b4SAlok Kataria 
9802d826404SThomas Gleixner 	tsc_khz = x86_platform.calibrate_tsc();
981e93ef949SAlok Kataria 	cpu_khz = tsc_khz;
9828fbbc4b4SAlok Kataria 
983e93ef949SAlok Kataria 	if (!tsc_khz) {
9848fbbc4b4SAlok Kataria 		mark_tsc_unstable("could not calculate TSC khz");
9858fbbc4b4SAlok Kataria 		return;
9868fbbc4b4SAlok Kataria 	}
9878fbbc4b4SAlok Kataria 
988c767a54bSJoe Perches 	pr_info("Detected %lu.%03lu MHz processor\n",
9898fbbc4b4SAlok Kataria 		(unsigned long)cpu_khz / 1000,
9908fbbc4b4SAlok Kataria 		(unsigned long)cpu_khz % 1000);
9918fbbc4b4SAlok Kataria 
9928fbbc4b4SAlok Kataria 	/*
9938fbbc4b4SAlok Kataria 	 * Secondary CPUs do not run through tsc_init(), so set up
9948fbbc4b4SAlok Kataria 	 * all the scale factors for all CPUs, assuming the same
9958fbbc4b4SAlok Kataria 	 * speed as the bootup CPU. (cpufreq notifiers will fix this
9968fbbc4b4SAlok Kataria 	 * up if their speed diverges)
9978fbbc4b4SAlok Kataria 	 */
9988fbbc4b4SAlok Kataria 	for_each_possible_cpu(cpu)
9998fbbc4b4SAlok Kataria 		set_cyc2ns_scale(cpu_khz, cpu);
10008fbbc4b4SAlok Kataria 
10018fbbc4b4SAlok Kataria 	if (tsc_disabled > 0)
10028fbbc4b4SAlok Kataria 		return;
10038fbbc4b4SAlok Kataria 
10048fbbc4b4SAlok Kataria 	/* now allow native_sched_clock() to use rdtsc */
10058fbbc4b4SAlok Kataria 	tsc_disabled = 0;
10068fbbc4b4SAlok Kataria 
1007e82b8e4eSVenkatesh Pallipadi 	if (!no_sched_irq_time)
1008e82b8e4eSVenkatesh Pallipadi 		enable_sched_clock_irqtime();
1009e82b8e4eSVenkatesh Pallipadi 
101070de9a97SAlok Kataria 	lpj = ((u64)tsc_khz * 1000);
101170de9a97SAlok Kataria 	do_div(lpj, HZ);
101270de9a97SAlok Kataria 	lpj_fine = lpj;
101370de9a97SAlok Kataria 
10148fbbc4b4SAlok Kataria 	use_tsc_delay();
10158fbbc4b4SAlok Kataria 
10168fbbc4b4SAlok Kataria 	if (unsynchronized_tsc())
10178fbbc4b4SAlok Kataria 		mark_tsc_unstable("TSCs unsynchronized");
10188fbbc4b4SAlok Kataria 
1019395628efSAlok Kataria 	check_system_tsc_reliable();
10208fbbc4b4SAlok Kataria }
10218fbbc4b4SAlok Kataria 
1022b565201cSJack Steiner #ifdef CONFIG_SMP
1023b565201cSJack Steiner /*
1024b565201cSJack Steiner  * If we have a constant TSC and are using the TSC for the delay loop,
1025b565201cSJack Steiner  * we can skip clock calibration if another cpu in the same socket has already
1026b565201cSJack Steiner  * been calibrated. This assumes that CONSTANT_TSC applies to all
1027b565201cSJack Steiner  * cpus in the socket - this should be a safe assumption.
1028b565201cSJack Steiner  */
1029148f9bb8SPaul Gortmaker unsigned long calibrate_delay_is_known(void)
1030b565201cSJack Steiner {
1031b565201cSJack Steiner 	int i, cpu = smp_processor_id();
1032b565201cSJack Steiner 
1033b565201cSJack Steiner 	if (!tsc_disabled && !cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC))
1034b565201cSJack Steiner 		return 0;
1035b565201cSJack Steiner 
1036b565201cSJack Steiner 	for_each_online_cpu(i)
1037b565201cSJack Steiner 		if (cpu_data(i).phys_proc_id == cpu_data(cpu).phys_proc_id)
1038b565201cSJack Steiner 			return cpu_data(i).loops_per_jiffy;
1039b565201cSJack Steiner 	return 0;
1040b565201cSJack Steiner }
1041b565201cSJack Steiner #endif
1042