xref: /openbmc/linux/arch/x86/kernel/tsc.c (revision 5ee5e97e)
1bfc0f594SAlok Kataria #include <linux/kernel.h>
20ef95533SAlok Kataria #include <linux/sched.h>
30ef95533SAlok Kataria #include <linux/init.h>
40ef95533SAlok Kataria #include <linux/module.h>
50ef95533SAlok Kataria #include <linux/timer.h>
6bfc0f594SAlok Kataria #include <linux/acpi_pmtmr.h>
72dbe06faSAlok Kataria #include <linux/cpufreq.h>
88fbbc4b4SAlok Kataria #include <linux/dmi.h>
98fbbc4b4SAlok Kataria #include <linux/delay.h>
108fbbc4b4SAlok Kataria #include <linux/clocksource.h>
118fbbc4b4SAlok Kataria #include <linux/percpu.h>
1208604bd9SArnd Bergmann #include <linux/timex.h>
13bfc0f594SAlok Kataria 
14bfc0f594SAlok Kataria #include <asm/hpet.h>
158fbbc4b4SAlok Kataria #include <asm/timer.h>
168fbbc4b4SAlok Kataria #include <asm/vgtod.h>
178fbbc4b4SAlok Kataria #include <asm/time.h>
188fbbc4b4SAlok Kataria #include <asm/delay.h>
1988b094fbSAlok Kataria #include <asm/hypervisor.h>
2008047c4fSThomas Gleixner #include <asm/nmi.h>
212d826404SThomas Gleixner #include <asm/x86_init.h>
220ef95533SAlok Kataria 
23f24ade3aSIngo Molnar unsigned int __read_mostly cpu_khz;	/* TSC clocks / usec, not used here */
240ef95533SAlok Kataria EXPORT_SYMBOL(cpu_khz);
25f24ade3aSIngo Molnar 
26f24ade3aSIngo Molnar unsigned int __read_mostly tsc_khz;
270ef95533SAlok Kataria EXPORT_SYMBOL(tsc_khz);
280ef95533SAlok Kataria 
290ef95533SAlok Kataria /*
300ef95533SAlok Kataria  * TSC can be unstable due to cpufreq or due to unsynced TSCs
310ef95533SAlok Kataria  */
32f24ade3aSIngo Molnar static int __read_mostly tsc_unstable;
330ef95533SAlok Kataria 
340ef95533SAlok Kataria /* native_sched_clock() is called before tsc_init(), so
350ef95533SAlok Kataria    we must start with the TSC soft disabled to prevent
360ef95533SAlok Kataria    erroneous rdtsc usage on !cpu_has_tsc processors */
37f24ade3aSIngo Molnar static int __read_mostly tsc_disabled = -1;
380ef95533SAlok Kataria 
39395628efSAlok Kataria static int tsc_clocksource_reliable;
400ef95533SAlok Kataria /*
410ef95533SAlok Kataria  * Scheduler clock - returns current time in nanosec units.
420ef95533SAlok Kataria  */
430ef95533SAlok Kataria u64 native_sched_clock(void)
440ef95533SAlok Kataria {
450ef95533SAlok Kataria 	u64 this_offset;
460ef95533SAlok Kataria 
470ef95533SAlok Kataria 	/*
480ef95533SAlok Kataria 	 * Fall back to jiffies if there's no TSC available:
490ef95533SAlok Kataria 	 * ( But note that we still use it if the TSC is marked
500ef95533SAlok Kataria 	 *   unstable. We do this because unlike Time Of Day,
510ef95533SAlok Kataria 	 *   the scheduler clock tolerates small errors and it's
520ef95533SAlok Kataria 	 *   very important for it to be as fast as the platform
533ad2f3fbSDaniel Mack 	 *   can achieve it. )
540ef95533SAlok Kataria 	 */
550ef95533SAlok Kataria 	if (unlikely(tsc_disabled)) {
560ef95533SAlok Kataria 		/* No locking but a rare wrong value is not a big deal: */
570ef95533SAlok Kataria 		return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
580ef95533SAlok Kataria 	}
590ef95533SAlok Kataria 
600ef95533SAlok Kataria 	/* read the Time Stamp Counter: */
610ef95533SAlok Kataria 	rdtscll(this_offset);
620ef95533SAlok Kataria 
630ef95533SAlok Kataria 	/* return the value in ns */
647cbaef9cSIngo Molnar 	return __cycles_2_ns(this_offset);
650ef95533SAlok Kataria }
660ef95533SAlok Kataria 
670ef95533SAlok Kataria /* We need to define a real function for sched_clock, to override the
680ef95533SAlok Kataria    weak default version */
690ef95533SAlok Kataria #ifdef CONFIG_PARAVIRT
700ef95533SAlok Kataria unsigned long long sched_clock(void)
710ef95533SAlok Kataria {
720ef95533SAlok Kataria 	return paravirt_sched_clock();
730ef95533SAlok Kataria }
740ef95533SAlok Kataria #else
750ef95533SAlok Kataria unsigned long long
760ef95533SAlok Kataria sched_clock(void) __attribute__((alias("native_sched_clock")));
770ef95533SAlok Kataria #endif
780ef95533SAlok Kataria 
790ef95533SAlok Kataria int check_tsc_unstable(void)
800ef95533SAlok Kataria {
810ef95533SAlok Kataria 	return tsc_unstable;
820ef95533SAlok Kataria }
830ef95533SAlok Kataria EXPORT_SYMBOL_GPL(check_tsc_unstable);
840ef95533SAlok Kataria 
850ef95533SAlok Kataria #ifdef CONFIG_X86_TSC
860ef95533SAlok Kataria int __init notsc_setup(char *str)
870ef95533SAlok Kataria {
880ef95533SAlok Kataria 	printk(KERN_WARNING "notsc: Kernel compiled with CONFIG_X86_TSC, "
890ef95533SAlok Kataria 			"cannot disable TSC completely.\n");
900ef95533SAlok Kataria 	tsc_disabled = 1;
910ef95533SAlok Kataria 	return 1;
920ef95533SAlok Kataria }
930ef95533SAlok Kataria #else
940ef95533SAlok Kataria /*
950ef95533SAlok Kataria  * disable flag for tsc. Takes effect by clearing the TSC cpu flag
960ef95533SAlok Kataria  * in cpu/common.c
970ef95533SAlok Kataria  */
980ef95533SAlok Kataria int __init notsc_setup(char *str)
990ef95533SAlok Kataria {
1000ef95533SAlok Kataria 	setup_clear_cpu_cap(X86_FEATURE_TSC);
1010ef95533SAlok Kataria 	return 1;
1020ef95533SAlok Kataria }
1030ef95533SAlok Kataria #endif
1040ef95533SAlok Kataria 
1050ef95533SAlok Kataria __setup("notsc", notsc_setup);
106bfc0f594SAlok Kataria 
107395628efSAlok Kataria static int __init tsc_setup(char *str)
108395628efSAlok Kataria {
109395628efSAlok Kataria 	if (!strcmp(str, "reliable"))
110395628efSAlok Kataria 		tsc_clocksource_reliable = 1;
111395628efSAlok Kataria 	return 1;
112395628efSAlok Kataria }
113395628efSAlok Kataria 
114395628efSAlok Kataria __setup("tsc=", tsc_setup);
115395628efSAlok Kataria 
116bfc0f594SAlok Kataria #define MAX_RETRIES     5
117bfc0f594SAlok Kataria #define SMI_TRESHOLD    50000
118bfc0f594SAlok Kataria 
119bfc0f594SAlok Kataria /*
120bfc0f594SAlok Kataria  * Read TSC and the reference counters. Take care of SMI disturbance
121bfc0f594SAlok Kataria  */
122827014beSThomas Gleixner static u64 tsc_read_refs(u64 *p, int hpet)
123bfc0f594SAlok Kataria {
124bfc0f594SAlok Kataria 	u64 t1, t2;
125bfc0f594SAlok Kataria 	int i;
126bfc0f594SAlok Kataria 
127bfc0f594SAlok Kataria 	for (i = 0; i < MAX_RETRIES; i++) {
128bfc0f594SAlok Kataria 		t1 = get_cycles();
129bfc0f594SAlok Kataria 		if (hpet)
130827014beSThomas Gleixner 			*p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
131bfc0f594SAlok Kataria 		else
132827014beSThomas Gleixner 			*p = acpi_pm_read_early();
133bfc0f594SAlok Kataria 		t2 = get_cycles();
134bfc0f594SAlok Kataria 		if ((t2 - t1) < SMI_TRESHOLD)
135bfc0f594SAlok Kataria 			return t2;
136bfc0f594SAlok Kataria 	}
137bfc0f594SAlok Kataria 	return ULLONG_MAX;
138bfc0f594SAlok Kataria }
139bfc0f594SAlok Kataria 
140ec0c15afSLinus Torvalds /*
141d683ef7aSThomas Gleixner  * Calculate the TSC frequency from HPET reference
142d683ef7aSThomas Gleixner  */
143d683ef7aSThomas Gleixner static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
144d683ef7aSThomas Gleixner {
145d683ef7aSThomas Gleixner 	u64 tmp;
146d683ef7aSThomas Gleixner 
147d683ef7aSThomas Gleixner 	if (hpet2 < hpet1)
148d683ef7aSThomas Gleixner 		hpet2 += 0x100000000ULL;
149d683ef7aSThomas Gleixner 	hpet2 -= hpet1;
150d683ef7aSThomas Gleixner 	tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
151d683ef7aSThomas Gleixner 	do_div(tmp, 1000000);
152d683ef7aSThomas Gleixner 	do_div(deltatsc, tmp);
153d683ef7aSThomas Gleixner 
154d683ef7aSThomas Gleixner 	return (unsigned long) deltatsc;
155d683ef7aSThomas Gleixner }
156d683ef7aSThomas Gleixner 
157d683ef7aSThomas Gleixner /*
158d683ef7aSThomas Gleixner  * Calculate the TSC frequency from PMTimer reference
159d683ef7aSThomas Gleixner  */
160d683ef7aSThomas Gleixner static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
161d683ef7aSThomas Gleixner {
162d683ef7aSThomas Gleixner 	u64 tmp;
163d683ef7aSThomas Gleixner 
164d683ef7aSThomas Gleixner 	if (!pm1 && !pm2)
165d683ef7aSThomas Gleixner 		return ULONG_MAX;
166d683ef7aSThomas Gleixner 
167d683ef7aSThomas Gleixner 	if (pm2 < pm1)
168d683ef7aSThomas Gleixner 		pm2 += (u64)ACPI_PM_OVRRUN;
169d683ef7aSThomas Gleixner 	pm2 -= pm1;
170d683ef7aSThomas Gleixner 	tmp = pm2 * 1000000000LL;
171d683ef7aSThomas Gleixner 	do_div(tmp, PMTMR_TICKS_PER_SEC);
172d683ef7aSThomas Gleixner 	do_div(deltatsc, tmp);
173d683ef7aSThomas Gleixner 
174d683ef7aSThomas Gleixner 	return (unsigned long) deltatsc;
175d683ef7aSThomas Gleixner }
176d683ef7aSThomas Gleixner 
177a977c400SThomas Gleixner #define CAL_MS		10
178cce3e057SThomas Gleixner #define CAL_LATCH	(CLOCK_TICK_RATE / (1000 / CAL_MS))
179a977c400SThomas Gleixner #define CAL_PIT_LOOPS	1000
180a977c400SThomas Gleixner 
181a977c400SThomas Gleixner #define CAL2_MS		50
182a977c400SThomas Gleixner #define CAL2_LATCH	(CLOCK_TICK_RATE / (1000 / CAL2_MS))
183a977c400SThomas Gleixner #define CAL2_PIT_LOOPS	5000
184a977c400SThomas Gleixner 
185cce3e057SThomas Gleixner 
186ec0c15afSLinus Torvalds /*
187ec0c15afSLinus Torvalds  * Try to calibrate the TSC against the Programmable
188ec0c15afSLinus Torvalds  * Interrupt Timer and return the frequency of the TSC
189ec0c15afSLinus Torvalds  * in kHz.
190ec0c15afSLinus Torvalds  *
191ec0c15afSLinus Torvalds  * Return ULONG_MAX on failure to calibrate.
192ec0c15afSLinus Torvalds  */
193a977c400SThomas Gleixner static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
194ec0c15afSLinus Torvalds {
195ec0c15afSLinus Torvalds 	u64 tsc, t1, t2, delta;
196ec0c15afSLinus Torvalds 	unsigned long tscmin, tscmax;
197ec0c15afSLinus Torvalds 	int pitcnt;
198ec0c15afSLinus Torvalds 
199ec0c15afSLinus Torvalds 	/* Set the Gate high, disable speaker */
200ec0c15afSLinus Torvalds 	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
201ec0c15afSLinus Torvalds 
202ec0c15afSLinus Torvalds 	/*
203ec0c15afSLinus Torvalds 	 * Setup CTC channel 2* for mode 0, (interrupt on terminal
204ec0c15afSLinus Torvalds 	 * count mode), binary count. Set the latch register to 50ms
205ec0c15afSLinus Torvalds 	 * (LSB then MSB) to begin countdown.
206ec0c15afSLinus Torvalds 	 */
207ec0c15afSLinus Torvalds 	outb(0xb0, 0x43);
208a977c400SThomas Gleixner 	outb(latch & 0xff, 0x42);
209a977c400SThomas Gleixner 	outb(latch >> 8, 0x42);
210ec0c15afSLinus Torvalds 
211ec0c15afSLinus Torvalds 	tsc = t1 = t2 = get_cycles();
212ec0c15afSLinus Torvalds 
213ec0c15afSLinus Torvalds 	pitcnt = 0;
214ec0c15afSLinus Torvalds 	tscmax = 0;
215ec0c15afSLinus Torvalds 	tscmin = ULONG_MAX;
216ec0c15afSLinus Torvalds 	while ((inb(0x61) & 0x20) == 0) {
217ec0c15afSLinus Torvalds 		t2 = get_cycles();
218ec0c15afSLinus Torvalds 		delta = t2 - tsc;
219ec0c15afSLinus Torvalds 		tsc = t2;
220ec0c15afSLinus Torvalds 		if ((unsigned long) delta < tscmin)
221ec0c15afSLinus Torvalds 			tscmin = (unsigned int) delta;
222ec0c15afSLinus Torvalds 		if ((unsigned long) delta > tscmax)
223ec0c15afSLinus Torvalds 			tscmax = (unsigned int) delta;
224ec0c15afSLinus Torvalds 		pitcnt++;
225ec0c15afSLinus Torvalds 	}
226ec0c15afSLinus Torvalds 
227ec0c15afSLinus Torvalds 	/*
228ec0c15afSLinus Torvalds 	 * Sanity checks:
229ec0c15afSLinus Torvalds 	 *
230a977c400SThomas Gleixner 	 * If we were not able to read the PIT more than loopmin
231ec0c15afSLinus Torvalds 	 * times, then we have been hit by a massive SMI
232ec0c15afSLinus Torvalds 	 *
233ec0c15afSLinus Torvalds 	 * If the maximum is 10 times larger than the minimum,
234ec0c15afSLinus Torvalds 	 * then we got hit by an SMI as well.
235ec0c15afSLinus Torvalds 	 */
236a977c400SThomas Gleixner 	if (pitcnt < loopmin || tscmax > 10 * tscmin)
237ec0c15afSLinus Torvalds 		return ULONG_MAX;
238ec0c15afSLinus Torvalds 
239ec0c15afSLinus Torvalds 	/* Calculate the PIT value */
240ec0c15afSLinus Torvalds 	delta = t2 - t1;
241a977c400SThomas Gleixner 	do_div(delta, ms);
242ec0c15afSLinus Torvalds 	return delta;
243ec0c15afSLinus Torvalds }
244ec0c15afSLinus Torvalds 
2456ac40ed0SLinus Torvalds /*
2466ac40ed0SLinus Torvalds  * This reads the current MSB of the PIT counter, and
2476ac40ed0SLinus Torvalds  * checks if we are running on sufficiently fast and
2486ac40ed0SLinus Torvalds  * non-virtualized hardware.
2496ac40ed0SLinus Torvalds  *
2506ac40ed0SLinus Torvalds  * Our expectations are:
2516ac40ed0SLinus Torvalds  *
2526ac40ed0SLinus Torvalds  *  - the PIT is running at roughly 1.19MHz
2536ac40ed0SLinus Torvalds  *
2546ac40ed0SLinus Torvalds  *  - each IO is going to take about 1us on real hardware,
2556ac40ed0SLinus Torvalds  *    but we allow it to be much faster (by a factor of 10) or
2566ac40ed0SLinus Torvalds  *    _slightly_ slower (ie we allow up to a 2us read+counter
2576ac40ed0SLinus Torvalds  *    update - anything else implies a unacceptably slow CPU
2586ac40ed0SLinus Torvalds  *    or PIT for the fast calibration to work.
2596ac40ed0SLinus Torvalds  *
2606ac40ed0SLinus Torvalds  *  - with 256 PIT ticks to read the value, we have 214us to
2616ac40ed0SLinus Torvalds  *    see the same MSB (and overhead like doing a single TSC
2626ac40ed0SLinus Torvalds  *    read per MSB value etc).
2636ac40ed0SLinus Torvalds  *
2646ac40ed0SLinus Torvalds  *  - We're doing 2 reads per loop (LSB, MSB), and we expect
2656ac40ed0SLinus Torvalds  *    them each to take about a microsecond on real hardware.
2666ac40ed0SLinus Torvalds  *    So we expect a count value of around 100. But we'll be
2676ac40ed0SLinus Torvalds  *    generous, and accept anything over 50.
2686ac40ed0SLinus Torvalds  *
2696ac40ed0SLinus Torvalds  *  - if the PIT is stuck, and we see *many* more reads, we
2706ac40ed0SLinus Torvalds  *    return early (and the next caller of pit_expect_msb()
2716ac40ed0SLinus Torvalds  *    then consider it a failure when they don't see the
2726ac40ed0SLinus Torvalds  *    next expected value).
2736ac40ed0SLinus Torvalds  *
2746ac40ed0SLinus Torvalds  * These expectations mean that we know that we have seen the
2756ac40ed0SLinus Torvalds  * transition from one expected value to another with a fairly
2766ac40ed0SLinus Torvalds  * high accuracy, and we didn't miss any events. We can thus
2776ac40ed0SLinus Torvalds  * use the TSC value at the transitions to calculate a pretty
2786ac40ed0SLinus Torvalds  * good value for the TSC frequencty.
2796ac40ed0SLinus Torvalds  */
280b6e61eefSLinus Torvalds static inline int pit_verify_msb(unsigned char val)
281b6e61eefSLinus Torvalds {
282b6e61eefSLinus Torvalds 	/* Ignore LSB */
283b6e61eefSLinus Torvalds 	inb(0x42);
284b6e61eefSLinus Torvalds 	return inb(0x42) == val;
285b6e61eefSLinus Torvalds }
286b6e61eefSLinus Torvalds 
2879e8912e0SLinus Torvalds static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
2886ac40ed0SLinus Torvalds {
2899e8912e0SLinus Torvalds 	int count;
2909e8912e0SLinus Torvalds 	u64 tsc = 0;
2916ac40ed0SLinus Torvalds 
2926ac40ed0SLinus Torvalds 	for (count = 0; count < 50000; count++) {
293b6e61eefSLinus Torvalds 		if (!pit_verify_msb(val))
2946ac40ed0SLinus Torvalds 			break;
2959e8912e0SLinus Torvalds 		tsc = get_cycles();
2966ac40ed0SLinus Torvalds 	}
2979e8912e0SLinus Torvalds 	*deltap = get_cycles() - tsc;
2989e8912e0SLinus Torvalds 	*tscp = tsc;
2999e8912e0SLinus Torvalds 
3009e8912e0SLinus Torvalds 	/*
3019e8912e0SLinus Torvalds 	 * We require _some_ success, but the quality control
3029e8912e0SLinus Torvalds 	 * will be based on the error terms on the TSC values.
3039e8912e0SLinus Torvalds 	 */
3049e8912e0SLinus Torvalds 	return count > 5;
3056ac40ed0SLinus Torvalds }
3066ac40ed0SLinus Torvalds 
3076ac40ed0SLinus Torvalds /*
3089e8912e0SLinus Torvalds  * How many MSB values do we want to see? We aim for
3099e8912e0SLinus Torvalds  * a maximum error rate of 500ppm (in practice the
3109e8912e0SLinus Torvalds  * real error is much smaller), but refuse to spend
3119e8912e0SLinus Torvalds  * more than 25ms on it.
3126ac40ed0SLinus Torvalds  */
3139e8912e0SLinus Torvalds #define MAX_QUICK_PIT_MS 25
3149e8912e0SLinus Torvalds #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
3156ac40ed0SLinus Torvalds 
3166ac40ed0SLinus Torvalds static unsigned long quick_pit_calibrate(void)
3176ac40ed0SLinus Torvalds {
3189e8912e0SLinus Torvalds 	int i;
3199e8912e0SLinus Torvalds 	u64 tsc, delta;
3209e8912e0SLinus Torvalds 	unsigned long d1, d2;
3219e8912e0SLinus Torvalds 
3226ac40ed0SLinus Torvalds 	/* Set the Gate high, disable speaker */
3236ac40ed0SLinus Torvalds 	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
3246ac40ed0SLinus Torvalds 
3256ac40ed0SLinus Torvalds 	/*
3266ac40ed0SLinus Torvalds 	 * Counter 2, mode 0 (one-shot), binary count
3276ac40ed0SLinus Torvalds 	 *
3286ac40ed0SLinus Torvalds 	 * NOTE! Mode 2 decrements by two (and then the
3296ac40ed0SLinus Torvalds 	 * output is flipped each time, giving the same
3306ac40ed0SLinus Torvalds 	 * final output frequency as a decrement-by-one),
3316ac40ed0SLinus Torvalds 	 * so mode 0 is much better when looking at the
3326ac40ed0SLinus Torvalds 	 * individual counts.
3336ac40ed0SLinus Torvalds 	 */
3346ac40ed0SLinus Torvalds 	outb(0xb0, 0x43);
3356ac40ed0SLinus Torvalds 
3366ac40ed0SLinus Torvalds 	/* Start at 0xffff */
3376ac40ed0SLinus Torvalds 	outb(0xff, 0x42);
3386ac40ed0SLinus Torvalds 	outb(0xff, 0x42);
3396ac40ed0SLinus Torvalds 
340a6a80e1dSLinus Torvalds 	/*
341a6a80e1dSLinus Torvalds 	 * The PIT starts counting at the next edge, so we
342a6a80e1dSLinus Torvalds 	 * need to delay for a microsecond. The easiest way
343a6a80e1dSLinus Torvalds 	 * to do that is to just read back the 16-bit counter
344a6a80e1dSLinus Torvalds 	 * once from the PIT.
345a6a80e1dSLinus Torvalds 	 */
346b6e61eefSLinus Torvalds 	pit_verify_msb(0);
347a6a80e1dSLinus Torvalds 
3489e8912e0SLinus Torvalds 	if (pit_expect_msb(0xff, &tsc, &d1)) {
3499e8912e0SLinus Torvalds 		for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
3509e8912e0SLinus Torvalds 			if (!pit_expect_msb(0xff-i, &delta, &d2))
3519e8912e0SLinus Torvalds 				break;
3526ac40ed0SLinus Torvalds 
3536ac40ed0SLinus Torvalds 			/*
3549e8912e0SLinus Torvalds 			 * Iterate until the error is less than 500 ppm
3554156e9a8SIngo Molnar 			 */
3569e8912e0SLinus Torvalds 			delta -= tsc;
357b6e61eefSLinus Torvalds 			if (d1+d2 >= delta >> 11)
358b6e61eefSLinus Torvalds 				continue;
359b6e61eefSLinus Torvalds 
360b6e61eefSLinus Torvalds 			/*
361b6e61eefSLinus Torvalds 			 * Check the PIT one more time to verify that
362b6e61eefSLinus Torvalds 			 * all TSC reads were stable wrt the PIT.
363b6e61eefSLinus Torvalds 			 *
364b6e61eefSLinus Torvalds 			 * This also guarantees serialization of the
365b6e61eefSLinus Torvalds 			 * last cycle read ('d2') in pit_expect_msb.
366b6e61eefSLinus Torvalds 			 */
367b6e61eefSLinus Torvalds 			if (!pit_verify_msb(0xfe - i))
368b6e61eefSLinus Torvalds 				break;
3699e8912e0SLinus Torvalds 			goto success;
3709e8912e0SLinus Torvalds 		}
3719e8912e0SLinus Torvalds 	}
3729e8912e0SLinus Torvalds 	printk("Fast TSC calibration failed\n");
3739e8912e0SLinus Torvalds 	return 0;
3744156e9a8SIngo Molnar 
3759e8912e0SLinus Torvalds success:
3764156e9a8SIngo Molnar 	/*
3776ac40ed0SLinus Torvalds 	 * Ok, if we get here, then we've seen the
3789e8912e0SLinus Torvalds 	 * MSB of the PIT decrement 'i' times, and the
3799e8912e0SLinus Torvalds 	 * error has shrunk to less than 500 ppm.
3806ac40ed0SLinus Torvalds 	 *
3816ac40ed0SLinus Torvalds 	 * As a result, we can depend on there not being
3826ac40ed0SLinus Torvalds 	 * any odd delays anywhere, and the TSC reads are
3839e8912e0SLinus Torvalds 	 * reliable (within the error). We also adjust the
3849e8912e0SLinus Torvalds 	 * delta to the middle of the error bars, just
3859e8912e0SLinus Torvalds 	 * because it looks nicer.
3866ac40ed0SLinus Torvalds 	 *
3876ac40ed0SLinus Torvalds 	 * kHz = ticks / time-in-seconds / 1000;
3889e8912e0SLinus Torvalds 	 * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
3899e8912e0SLinus Torvalds 	 * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
3906ac40ed0SLinus Torvalds 	 */
3919e8912e0SLinus Torvalds 	delta += (long)(d2 - d1)/2;
3929e8912e0SLinus Torvalds 	delta *= PIT_TICK_RATE;
3939e8912e0SLinus Torvalds 	do_div(delta, i*256*1000);
3946ac40ed0SLinus Torvalds 	printk("Fast TSC calibration using PIT\n");
3956ac40ed0SLinus Torvalds 	return delta;
3966ac40ed0SLinus Torvalds }
397ec0c15afSLinus Torvalds 
398bfc0f594SAlok Kataria /**
399e93ef949SAlok Kataria  * native_calibrate_tsc - calibrate the tsc on boot
400bfc0f594SAlok Kataria  */
401e93ef949SAlok Kataria unsigned long native_calibrate_tsc(void)
402bfc0f594SAlok Kataria {
403827014beSThomas Gleixner 	u64 tsc1, tsc2, delta, ref1, ref2;
404fbb16e24SThomas Gleixner 	unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
4052d826404SThomas Gleixner 	unsigned long flags, latch, ms, fast_calibrate;
406a977c400SThomas Gleixner 	int hpet = is_hpet_enabled(), i, loopmin;
407bfc0f594SAlok Kataria 
408bfc0f594SAlok Kataria 	local_irq_save(flags);
4096ac40ed0SLinus Torvalds 	fast_calibrate = quick_pit_calibrate();
410bfc0f594SAlok Kataria 	local_irq_restore(flags);
4116ac40ed0SLinus Torvalds 	if (fast_calibrate)
4126ac40ed0SLinus Torvalds 		return fast_calibrate;
413fbb16e24SThomas Gleixner 
414fbb16e24SThomas Gleixner 	/*
415fbb16e24SThomas Gleixner 	 * Run 5 calibration loops to get the lowest frequency value
416fbb16e24SThomas Gleixner 	 * (the best estimate). We use two different calibration modes
417fbb16e24SThomas Gleixner 	 * here:
418fbb16e24SThomas Gleixner 	 *
419fbb16e24SThomas Gleixner 	 * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
420fbb16e24SThomas Gleixner 	 * load a timeout of 50ms. We read the time right after we
421fbb16e24SThomas Gleixner 	 * started the timer and wait until the PIT count down reaches
422fbb16e24SThomas Gleixner 	 * zero. In each wait loop iteration we read the TSC and check
423fbb16e24SThomas Gleixner 	 * the delta to the previous read. We keep track of the min
424fbb16e24SThomas Gleixner 	 * and max values of that delta. The delta is mostly defined
425fbb16e24SThomas Gleixner 	 * by the IO time of the PIT access, so we can detect when a
426fbb16e24SThomas Gleixner 	 * SMI/SMM disturbance happend between the two reads. If the
427fbb16e24SThomas Gleixner 	 * maximum time is significantly larger than the minimum time,
428fbb16e24SThomas Gleixner 	 * then we discard the result and have another try.
429fbb16e24SThomas Gleixner 	 *
430fbb16e24SThomas Gleixner 	 * 2) Reference counter. If available we use the HPET or the
431fbb16e24SThomas Gleixner 	 * PMTIMER as a reference to check the sanity of that value.
432fbb16e24SThomas Gleixner 	 * We use separate TSC readouts and check inside of the
433fbb16e24SThomas Gleixner 	 * reference read for a SMI/SMM disturbance. We dicard
434fbb16e24SThomas Gleixner 	 * disturbed values here as well. We do that around the PIT
435fbb16e24SThomas Gleixner 	 * calibration delay loop as we have to wait for a certain
436fbb16e24SThomas Gleixner 	 * amount of time anyway.
437fbb16e24SThomas Gleixner 	 */
438a977c400SThomas Gleixner 
439a977c400SThomas Gleixner 	/* Preset PIT loop values */
440a977c400SThomas Gleixner 	latch = CAL_LATCH;
441a977c400SThomas Gleixner 	ms = CAL_MS;
442a977c400SThomas Gleixner 	loopmin = CAL_PIT_LOOPS;
443a977c400SThomas Gleixner 
444a977c400SThomas Gleixner 	for (i = 0; i < 3; i++) {
445ec0c15afSLinus Torvalds 		unsigned long tsc_pit_khz;
446bfc0f594SAlok Kataria 
447fbb16e24SThomas Gleixner 		/*
448fbb16e24SThomas Gleixner 		 * Read the start value and the reference count of
449ec0c15afSLinus Torvalds 		 * hpet/pmtimer when available. Then do the PIT
450ec0c15afSLinus Torvalds 		 * calibration, which will take at least 50ms, and
451ec0c15afSLinus Torvalds 		 * read the end value.
452fbb16e24SThomas Gleixner 		 */
453ec0c15afSLinus Torvalds 		local_irq_save(flags);
454827014beSThomas Gleixner 		tsc1 = tsc_read_refs(&ref1, hpet);
455a977c400SThomas Gleixner 		tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
456827014beSThomas Gleixner 		tsc2 = tsc_read_refs(&ref2, hpet);
457bfc0f594SAlok Kataria 		local_irq_restore(flags);
458bfc0f594SAlok Kataria 
459ec0c15afSLinus Torvalds 		/* Pick the lowest PIT TSC calibration so far */
460ec0c15afSLinus Torvalds 		tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
461bfc0f594SAlok Kataria 
462bfc0f594SAlok Kataria 		/* hpet or pmtimer available ? */
463827014beSThomas Gleixner 		if (!hpet && !ref1 && !ref2)
464fbb16e24SThomas Gleixner 			continue;
465bfc0f594SAlok Kataria 
466bfc0f594SAlok Kataria 		/* Check, whether the sampling was disturbed by an SMI */
467fbb16e24SThomas Gleixner 		if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
468fbb16e24SThomas Gleixner 			continue;
469bfc0f594SAlok Kataria 
470bfc0f594SAlok Kataria 		tsc2 = (tsc2 - tsc1) * 1000000LL;
471d683ef7aSThomas Gleixner 		if (hpet)
472827014beSThomas Gleixner 			tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
473d683ef7aSThomas Gleixner 		else
474827014beSThomas Gleixner 			tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
475bfc0f594SAlok Kataria 
476fbb16e24SThomas Gleixner 		tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
477a977c400SThomas Gleixner 
478a977c400SThomas Gleixner 		/* Check the reference deviation */
479a977c400SThomas Gleixner 		delta = ((u64) tsc_pit_min) * 100;
480a977c400SThomas Gleixner 		do_div(delta, tsc_ref_min);
481a977c400SThomas Gleixner 
482a977c400SThomas Gleixner 		/*
483a977c400SThomas Gleixner 		 * If both calibration results are inside a 10% window
484a977c400SThomas Gleixner 		 * then we can be sure, that the calibration
485a977c400SThomas Gleixner 		 * succeeded. We break out of the loop right away. We
486a977c400SThomas Gleixner 		 * use the reference value, as it is more precise.
487a977c400SThomas Gleixner 		 */
488a977c400SThomas Gleixner 		if (delta >= 90 && delta <= 110) {
489a977c400SThomas Gleixner 			printk(KERN_INFO
490a977c400SThomas Gleixner 			       "TSC: PIT calibration matches %s. %d loops\n",
491a977c400SThomas Gleixner 			       hpet ? "HPET" : "PMTIMER", i + 1);
492a977c400SThomas Gleixner 			return tsc_ref_min;
493bfc0f594SAlok Kataria 		}
494bfc0f594SAlok Kataria 
495a977c400SThomas Gleixner 		/*
496a977c400SThomas Gleixner 		 * Check whether PIT failed more than once. This
497a977c400SThomas Gleixner 		 * happens in virtualized environments. We need to
498a977c400SThomas Gleixner 		 * give the virtual PC a slightly longer timeframe for
499a977c400SThomas Gleixner 		 * the HPET/PMTIMER to make the result precise.
500a977c400SThomas Gleixner 		 */
501a977c400SThomas Gleixner 		if (i == 1 && tsc_pit_min == ULONG_MAX) {
502a977c400SThomas Gleixner 			latch = CAL2_LATCH;
503a977c400SThomas Gleixner 			ms = CAL2_MS;
504a977c400SThomas Gleixner 			loopmin = CAL2_PIT_LOOPS;
505a977c400SThomas Gleixner 		}
506bfc0f594SAlok Kataria 	}
507bfc0f594SAlok Kataria 
508fbb16e24SThomas Gleixner 	/*
509fbb16e24SThomas Gleixner 	 * Now check the results.
510fbb16e24SThomas Gleixner 	 */
511fbb16e24SThomas Gleixner 	if (tsc_pit_min == ULONG_MAX) {
512fbb16e24SThomas Gleixner 		/* PIT gave no useful value */
513de014d61SAlok N Kataria 		printk(KERN_WARNING "TSC: Unable to calibrate against PIT\n");
514fbb16e24SThomas Gleixner 
515fbb16e24SThomas Gleixner 		/* We don't have an alternative source, disable TSC */
516827014beSThomas Gleixner 		if (!hpet && !ref1 && !ref2) {
517fbb16e24SThomas Gleixner 			printk("TSC: No reference (HPET/PMTIMER) available\n");
518fbb16e24SThomas Gleixner 			return 0;
519fbb16e24SThomas Gleixner 		}
520fbb16e24SThomas Gleixner 
521fbb16e24SThomas Gleixner 		/* The alternative source failed as well, disable TSC */
522fbb16e24SThomas Gleixner 		if (tsc_ref_min == ULONG_MAX) {
523fbb16e24SThomas Gleixner 			printk(KERN_WARNING "TSC: HPET/PMTIMER calibration "
524a977c400SThomas Gleixner 			       "failed.\n");
525fbb16e24SThomas Gleixner 			return 0;
526fbb16e24SThomas Gleixner 		}
527fbb16e24SThomas Gleixner 
528fbb16e24SThomas Gleixner 		/* Use the alternative source */
529fbb16e24SThomas Gleixner 		printk(KERN_INFO "TSC: using %s reference calibration\n",
530fbb16e24SThomas Gleixner 		       hpet ? "HPET" : "PMTIMER");
531fbb16e24SThomas Gleixner 
532fbb16e24SThomas Gleixner 		return tsc_ref_min;
533fbb16e24SThomas Gleixner 	}
534fbb16e24SThomas Gleixner 
535fbb16e24SThomas Gleixner 	/* We don't have an alternative source, use the PIT calibration value */
536827014beSThomas Gleixner 	if (!hpet && !ref1 && !ref2) {
537fbb16e24SThomas Gleixner 		printk(KERN_INFO "TSC: Using PIT calibration value\n");
538fbb16e24SThomas Gleixner 		return tsc_pit_min;
539fbb16e24SThomas Gleixner 	}
540fbb16e24SThomas Gleixner 
541fbb16e24SThomas Gleixner 	/* The alternative source failed, use the PIT calibration value */
542fbb16e24SThomas Gleixner 	if (tsc_ref_min == ULONG_MAX) {
543a977c400SThomas Gleixner 		printk(KERN_WARNING "TSC: HPET/PMTIMER calibration failed. "
544a977c400SThomas Gleixner 		       "Using PIT calibration\n");
545fbb16e24SThomas Gleixner 		return tsc_pit_min;
546fbb16e24SThomas Gleixner 	}
547fbb16e24SThomas Gleixner 
548fbb16e24SThomas Gleixner 	/*
549fbb16e24SThomas Gleixner 	 * The calibration values differ too much. In doubt, we use
550fbb16e24SThomas Gleixner 	 * the PIT value as we know that there are PMTIMERs around
551a977c400SThomas Gleixner 	 * running at double speed. At least we let the user know:
552fbb16e24SThomas Gleixner 	 */
553a977c400SThomas Gleixner 	printk(KERN_WARNING "TSC: PIT calibration deviates from %s: %lu %lu.\n",
554a977c400SThomas Gleixner 	       hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
555fbb16e24SThomas Gleixner 	printk(KERN_INFO "TSC: Using PIT calibration value\n");
556fbb16e24SThomas Gleixner 	return tsc_pit_min;
557fbb16e24SThomas Gleixner }
558bfc0f594SAlok Kataria 
559bfc0f594SAlok Kataria int recalibrate_cpu_khz(void)
560bfc0f594SAlok Kataria {
561bfc0f594SAlok Kataria #ifndef CONFIG_SMP
562bfc0f594SAlok Kataria 	unsigned long cpu_khz_old = cpu_khz;
563bfc0f594SAlok Kataria 
564bfc0f594SAlok Kataria 	if (cpu_has_tsc) {
5652d826404SThomas Gleixner 		tsc_khz = x86_platform.calibrate_tsc();
566e93ef949SAlok Kataria 		cpu_khz = tsc_khz;
567bfc0f594SAlok Kataria 		cpu_data(0).loops_per_jiffy =
568bfc0f594SAlok Kataria 			cpufreq_scale(cpu_data(0).loops_per_jiffy,
569bfc0f594SAlok Kataria 					cpu_khz_old, cpu_khz);
570bfc0f594SAlok Kataria 		return 0;
571bfc0f594SAlok Kataria 	} else
572bfc0f594SAlok Kataria 		return -ENODEV;
573bfc0f594SAlok Kataria #else
574bfc0f594SAlok Kataria 	return -ENODEV;
575bfc0f594SAlok Kataria #endif
576bfc0f594SAlok Kataria }
577bfc0f594SAlok Kataria 
578bfc0f594SAlok Kataria EXPORT_SYMBOL(recalibrate_cpu_khz);
579bfc0f594SAlok Kataria 
5802dbe06faSAlok Kataria 
5812dbe06faSAlok Kataria /* Accelerators for sched_clock()
5822dbe06faSAlok Kataria  * convert from cycles(64bits) => nanoseconds (64bits)
5832dbe06faSAlok Kataria  *  basic equation:
5842dbe06faSAlok Kataria  *              ns = cycles / (freq / ns_per_sec)
5852dbe06faSAlok Kataria  *              ns = cycles * (ns_per_sec / freq)
5862dbe06faSAlok Kataria  *              ns = cycles * (10^9 / (cpu_khz * 10^3))
5872dbe06faSAlok Kataria  *              ns = cycles * (10^6 / cpu_khz)
5882dbe06faSAlok Kataria  *
5892dbe06faSAlok Kataria  *      Then we use scaling math (suggested by george@mvista.com) to get:
5902dbe06faSAlok Kataria  *              ns = cycles * (10^6 * SC / cpu_khz) / SC
5912dbe06faSAlok Kataria  *              ns = cycles * cyc2ns_scale / SC
5922dbe06faSAlok Kataria  *
5932dbe06faSAlok Kataria  *      And since SC is a constant power of two, we can convert the div
5942dbe06faSAlok Kataria  *  into a shift.
5952dbe06faSAlok Kataria  *
5962dbe06faSAlok Kataria  *  We can use khz divisor instead of mhz to keep a better precision, since
5972dbe06faSAlok Kataria  *  cyc2ns_scale is limited to 10^6 * 2^10, which fits in 32 bits.
5982dbe06faSAlok Kataria  *  (mathieu.desnoyers@polymtl.ca)
5992dbe06faSAlok Kataria  *
6002dbe06faSAlok Kataria  *                      -johnstul@us.ibm.com "math is hard, lets go shopping!"
6012dbe06faSAlok Kataria  */
6022dbe06faSAlok Kataria 
6032dbe06faSAlok Kataria DEFINE_PER_CPU(unsigned long, cyc2ns);
60484599f8aSPeter Zijlstra DEFINE_PER_CPU(unsigned long long, cyc2ns_offset);
6052dbe06faSAlok Kataria 
6068fbbc4b4SAlok Kataria static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
6072dbe06faSAlok Kataria {
60884599f8aSPeter Zijlstra 	unsigned long long tsc_now, ns_now, *offset;
6092dbe06faSAlok Kataria 	unsigned long flags, *scale;
6102dbe06faSAlok Kataria 
6112dbe06faSAlok Kataria 	local_irq_save(flags);
6122dbe06faSAlok Kataria 	sched_clock_idle_sleep_event();
6132dbe06faSAlok Kataria 
6142dbe06faSAlok Kataria 	scale = &per_cpu(cyc2ns, cpu);
61584599f8aSPeter Zijlstra 	offset = &per_cpu(cyc2ns_offset, cpu);
6162dbe06faSAlok Kataria 
6172dbe06faSAlok Kataria 	rdtscll(tsc_now);
6182dbe06faSAlok Kataria 	ns_now = __cycles_2_ns(tsc_now);
6192dbe06faSAlok Kataria 
62084599f8aSPeter Zijlstra 	if (cpu_khz) {
6212dbe06faSAlok Kataria 		*scale = (NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR)/cpu_khz;
62284599f8aSPeter Zijlstra 		*offset = ns_now - (tsc_now * *scale >> CYC2NS_SCALE_FACTOR);
62384599f8aSPeter Zijlstra 	}
6242dbe06faSAlok Kataria 
6252dbe06faSAlok Kataria 	sched_clock_idle_wakeup_event(0);
6262dbe06faSAlok Kataria 	local_irq_restore(flags);
6272dbe06faSAlok Kataria }
6282dbe06faSAlok Kataria 
629cd7240c0SSuresh Siddha static unsigned long long cyc2ns_suspend;
630cd7240c0SSuresh Siddha 
631cd7240c0SSuresh Siddha void save_sched_clock_state(void)
632cd7240c0SSuresh Siddha {
633cd7240c0SSuresh Siddha 	if (!sched_clock_stable)
634cd7240c0SSuresh Siddha 		return;
635cd7240c0SSuresh Siddha 
636cd7240c0SSuresh Siddha 	cyc2ns_suspend = sched_clock();
637cd7240c0SSuresh Siddha }
638cd7240c0SSuresh Siddha 
639cd7240c0SSuresh Siddha /*
640cd7240c0SSuresh Siddha  * Even on processors with invariant TSC, TSC gets reset in some the
641cd7240c0SSuresh Siddha  * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
642cd7240c0SSuresh Siddha  * arbitrary value (still sync'd across cpu's) during resume from such sleep
643cd7240c0SSuresh Siddha  * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
644cd7240c0SSuresh Siddha  * that sched_clock() continues from the point where it was left off during
645cd7240c0SSuresh Siddha  * suspend.
646cd7240c0SSuresh Siddha  */
647cd7240c0SSuresh Siddha void restore_sched_clock_state(void)
648cd7240c0SSuresh Siddha {
649cd7240c0SSuresh Siddha 	unsigned long long offset;
650cd7240c0SSuresh Siddha 	unsigned long flags;
651cd7240c0SSuresh Siddha 	int cpu;
652cd7240c0SSuresh Siddha 
653cd7240c0SSuresh Siddha 	if (!sched_clock_stable)
654cd7240c0SSuresh Siddha 		return;
655cd7240c0SSuresh Siddha 
656cd7240c0SSuresh Siddha 	local_irq_save(flags);
657cd7240c0SSuresh Siddha 
6585ee5e97eSPeter Zijlstra 	__get_cpu_var(cyc2ns_offset) = 0;
659cd7240c0SSuresh Siddha 	offset = cyc2ns_suspend - sched_clock();
660cd7240c0SSuresh Siddha 
661cd7240c0SSuresh Siddha 	for_each_possible_cpu(cpu)
662cd7240c0SSuresh Siddha 		per_cpu(cyc2ns_offset, cpu) = offset;
663cd7240c0SSuresh Siddha 
664cd7240c0SSuresh Siddha 	local_irq_restore(flags);
665cd7240c0SSuresh Siddha }
666cd7240c0SSuresh Siddha 
6672dbe06faSAlok Kataria #ifdef CONFIG_CPU_FREQ
6682dbe06faSAlok Kataria 
6692dbe06faSAlok Kataria /* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
6702dbe06faSAlok Kataria  * changes.
6712dbe06faSAlok Kataria  *
6722dbe06faSAlok Kataria  * RED-PEN: On SMP we assume all CPUs run with the same frequency.  It's
6732dbe06faSAlok Kataria  * not that important because current Opteron setups do not support
6742dbe06faSAlok Kataria  * scaling on SMP anyroads.
6752dbe06faSAlok Kataria  *
6762dbe06faSAlok Kataria  * Should fix up last_tsc too. Currently gettimeofday in the
6772dbe06faSAlok Kataria  * first tick after the change will be slightly wrong.
6782dbe06faSAlok Kataria  */
6792dbe06faSAlok Kataria 
6802dbe06faSAlok Kataria static unsigned int  ref_freq;
6812dbe06faSAlok Kataria static unsigned long loops_per_jiffy_ref;
6822dbe06faSAlok Kataria static unsigned long tsc_khz_ref;
6832dbe06faSAlok Kataria 
6842dbe06faSAlok Kataria static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
6852dbe06faSAlok Kataria 				void *data)
6862dbe06faSAlok Kataria {
6872dbe06faSAlok Kataria 	struct cpufreq_freqs *freq = data;
688931db6a3SDave Jones 	unsigned long *lpj;
6892dbe06faSAlok Kataria 
6902dbe06faSAlok Kataria 	if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
6912dbe06faSAlok Kataria 		return 0;
6922dbe06faSAlok Kataria 
6932dbe06faSAlok Kataria 	lpj = &boot_cpu_data.loops_per_jiffy;
694931db6a3SDave Jones #ifdef CONFIG_SMP
695931db6a3SDave Jones 	if (!(freq->flags & CPUFREQ_CONST_LOOPS))
696931db6a3SDave Jones 		lpj = &cpu_data(freq->cpu).loops_per_jiffy;
6972dbe06faSAlok Kataria #endif
6982dbe06faSAlok Kataria 
6992dbe06faSAlok Kataria 	if (!ref_freq) {
7002dbe06faSAlok Kataria 		ref_freq = freq->old;
7012dbe06faSAlok Kataria 		loops_per_jiffy_ref = *lpj;
7022dbe06faSAlok Kataria 		tsc_khz_ref = tsc_khz;
7032dbe06faSAlok Kataria 	}
7042dbe06faSAlok Kataria 	if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
7052dbe06faSAlok Kataria 			(val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
7062dbe06faSAlok Kataria 			(val == CPUFREQ_RESUMECHANGE)) {
7072dbe06faSAlok Kataria 		*lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
7082dbe06faSAlok Kataria 
7092dbe06faSAlok Kataria 		tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
7102dbe06faSAlok Kataria 		if (!(freq->flags & CPUFREQ_CONST_LOOPS))
7112dbe06faSAlok Kataria 			mark_tsc_unstable("cpufreq changes");
7122dbe06faSAlok Kataria 	}
7132dbe06faSAlok Kataria 
71452a8968cSPeter Zijlstra 	set_cyc2ns_scale(tsc_khz, freq->cpu);
7152dbe06faSAlok Kataria 
7162dbe06faSAlok Kataria 	return 0;
7172dbe06faSAlok Kataria }
7182dbe06faSAlok Kataria 
7192dbe06faSAlok Kataria static struct notifier_block time_cpufreq_notifier_block = {
7202dbe06faSAlok Kataria 	.notifier_call  = time_cpufreq_notifier
7212dbe06faSAlok Kataria };
7222dbe06faSAlok Kataria 
7232dbe06faSAlok Kataria static int __init cpufreq_tsc(void)
7242dbe06faSAlok Kataria {
725060700b5SLinus Torvalds 	if (!cpu_has_tsc)
726060700b5SLinus Torvalds 		return 0;
727060700b5SLinus Torvalds 	if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
728060700b5SLinus Torvalds 		return 0;
7292dbe06faSAlok Kataria 	cpufreq_register_notifier(&time_cpufreq_notifier_block,
7302dbe06faSAlok Kataria 				CPUFREQ_TRANSITION_NOTIFIER);
7312dbe06faSAlok Kataria 	return 0;
7322dbe06faSAlok Kataria }
7332dbe06faSAlok Kataria 
7342dbe06faSAlok Kataria core_initcall(cpufreq_tsc);
7352dbe06faSAlok Kataria 
7362dbe06faSAlok Kataria #endif /* CONFIG_CPU_FREQ */
7378fbbc4b4SAlok Kataria 
7388fbbc4b4SAlok Kataria /* clocksource code */
7398fbbc4b4SAlok Kataria 
7408fbbc4b4SAlok Kataria static struct clocksource clocksource_tsc;
7418fbbc4b4SAlok Kataria 
7428fbbc4b4SAlok Kataria /*
7438fbbc4b4SAlok Kataria  * We compare the TSC to the cycle_last value in the clocksource
7448fbbc4b4SAlok Kataria  * structure to avoid a nasty time-warp. This can be observed in a
7458fbbc4b4SAlok Kataria  * very small window right after one CPU updated cycle_last under
7468fbbc4b4SAlok Kataria  * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
7478fbbc4b4SAlok Kataria  * is smaller than the cycle_last reference value due to a TSC which
7488fbbc4b4SAlok Kataria  * is slighty behind. This delta is nowhere else observable, but in
7498fbbc4b4SAlok Kataria  * that case it results in a forward time jump in the range of hours
7508fbbc4b4SAlok Kataria  * due to the unsigned delta calculation of the time keeping core
7518fbbc4b4SAlok Kataria  * code, which is necessary to support wrapping clocksources like pm
7528fbbc4b4SAlok Kataria  * timer.
7538fbbc4b4SAlok Kataria  */
7548e19608eSMagnus Damm static cycle_t read_tsc(struct clocksource *cs)
7558fbbc4b4SAlok Kataria {
7568fbbc4b4SAlok Kataria 	cycle_t ret = (cycle_t)get_cycles();
7578fbbc4b4SAlok Kataria 
7588fbbc4b4SAlok Kataria 	return ret >= clocksource_tsc.cycle_last ?
7598fbbc4b4SAlok Kataria 		ret : clocksource_tsc.cycle_last;
7608fbbc4b4SAlok Kataria }
7618fbbc4b4SAlok Kataria 
762431ceb83SThomas Gleixner #ifdef CONFIG_X86_64
7638fbbc4b4SAlok Kataria static cycle_t __vsyscall_fn vread_tsc(void)
7648fbbc4b4SAlok Kataria {
7657d96fd41SPetr Tesarik 	cycle_t ret;
7667d96fd41SPetr Tesarik 
7677d96fd41SPetr Tesarik 	/*
7687d96fd41SPetr Tesarik 	 * Surround the RDTSC by barriers, to make sure it's not
7697d96fd41SPetr Tesarik 	 * speculated to outside the seqlock critical section and
7707d96fd41SPetr Tesarik 	 * does not cause time warps:
7717d96fd41SPetr Tesarik 	 */
7727d96fd41SPetr Tesarik 	rdtsc_barrier();
7737d96fd41SPetr Tesarik 	ret = (cycle_t)vget_cycles();
7747d96fd41SPetr Tesarik 	rdtsc_barrier();
7758fbbc4b4SAlok Kataria 
7768fbbc4b4SAlok Kataria 	return ret >= __vsyscall_gtod_data.clock.cycle_last ?
7778fbbc4b4SAlok Kataria 		ret : __vsyscall_gtod_data.clock.cycle_last;
7788fbbc4b4SAlok Kataria }
779431ceb83SThomas Gleixner #endif
7808fbbc4b4SAlok Kataria 
78117622339SMagnus Damm static void resume_tsc(struct clocksource *cs)
7821be39679SMartin Schwidefsky {
7831be39679SMartin Schwidefsky 	clocksource_tsc.cycle_last = 0;
7841be39679SMartin Schwidefsky }
7851be39679SMartin Schwidefsky 
7868fbbc4b4SAlok Kataria static struct clocksource clocksource_tsc = {
7878fbbc4b4SAlok Kataria 	.name                   = "tsc",
7888fbbc4b4SAlok Kataria 	.rating                 = 300,
7898fbbc4b4SAlok Kataria 	.read                   = read_tsc,
7901be39679SMartin Schwidefsky 	.resume			= resume_tsc,
7918fbbc4b4SAlok Kataria 	.mask                   = CLOCKSOURCE_MASK(64),
7928fbbc4b4SAlok Kataria 	.flags                  = CLOCK_SOURCE_IS_CONTINUOUS |
7938fbbc4b4SAlok Kataria 				  CLOCK_SOURCE_MUST_VERIFY,
7948fbbc4b4SAlok Kataria #ifdef CONFIG_X86_64
7958fbbc4b4SAlok Kataria 	.vread                  = vread_tsc,
7968fbbc4b4SAlok Kataria #endif
7978fbbc4b4SAlok Kataria };
7988fbbc4b4SAlok Kataria 
7998fbbc4b4SAlok Kataria void mark_tsc_unstable(char *reason)
8008fbbc4b4SAlok Kataria {
8018fbbc4b4SAlok Kataria 	if (!tsc_unstable) {
8028fbbc4b4SAlok Kataria 		tsc_unstable = 1;
8036c56ccecSPallipadi, Venkatesh 		sched_clock_stable = 0;
8047285dd7fSThomas Gleixner 		printk(KERN_INFO "Marking TSC unstable due to %s\n", reason);
8058fbbc4b4SAlok Kataria 		/* Change only the rating, when not registered */
8068fbbc4b4SAlok Kataria 		if (clocksource_tsc.mult)
8077285dd7fSThomas Gleixner 			clocksource_mark_unstable(&clocksource_tsc);
8087285dd7fSThomas Gleixner 		else {
8097285dd7fSThomas Gleixner 			clocksource_tsc.flags |= CLOCK_SOURCE_UNSTABLE;
8108fbbc4b4SAlok Kataria 			clocksource_tsc.rating = 0;
8118fbbc4b4SAlok Kataria 		}
8128fbbc4b4SAlok Kataria 	}
8137285dd7fSThomas Gleixner }
8148fbbc4b4SAlok Kataria 
8158fbbc4b4SAlok Kataria EXPORT_SYMBOL_GPL(mark_tsc_unstable);
8168fbbc4b4SAlok Kataria 
8178fbbc4b4SAlok Kataria static int __init dmi_mark_tsc_unstable(const struct dmi_system_id *d)
8188fbbc4b4SAlok Kataria {
8198fbbc4b4SAlok Kataria 	printk(KERN_NOTICE "%s detected: marking TSC unstable.\n",
8208fbbc4b4SAlok Kataria 			d->ident);
8218fbbc4b4SAlok Kataria 	tsc_unstable = 1;
8228fbbc4b4SAlok Kataria 	return 0;
8238fbbc4b4SAlok Kataria }
8248fbbc4b4SAlok Kataria 
8258fbbc4b4SAlok Kataria /* List of systems that have known TSC problems */
8268fbbc4b4SAlok Kataria static struct dmi_system_id __initdata bad_tsc_dmi_table[] = {
8278fbbc4b4SAlok Kataria 	{
8288fbbc4b4SAlok Kataria 		.callback = dmi_mark_tsc_unstable,
8298fbbc4b4SAlok Kataria 		.ident = "IBM Thinkpad 380XD",
8308fbbc4b4SAlok Kataria 		.matches = {
8318fbbc4b4SAlok Kataria 			DMI_MATCH(DMI_BOARD_VENDOR, "IBM"),
8328fbbc4b4SAlok Kataria 			DMI_MATCH(DMI_BOARD_NAME, "2635FA0"),
8338fbbc4b4SAlok Kataria 		},
8348fbbc4b4SAlok Kataria 	},
8358fbbc4b4SAlok Kataria 	{}
8368fbbc4b4SAlok Kataria };
8378fbbc4b4SAlok Kataria 
838395628efSAlok Kataria static void __init check_system_tsc_reliable(void)
839395628efSAlok Kataria {
8408fbbc4b4SAlok Kataria #ifdef CONFIG_MGEODE_LX
8418fbbc4b4SAlok Kataria 	/* RTSC counts during suspend */
8428fbbc4b4SAlok Kataria #define RTSC_SUSP 0x100
8438fbbc4b4SAlok Kataria 	unsigned long res_low, res_high;
8448fbbc4b4SAlok Kataria 
8458fbbc4b4SAlok Kataria 	rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
84600097c4fSThadeu Lima de Souza Cascardo 	/* Geode_LX - the OLPC CPU has a very reliable TSC */
8478fbbc4b4SAlok Kataria 	if (res_low & RTSC_SUSP)
848395628efSAlok Kataria 		tsc_clocksource_reliable = 1;
8498fbbc4b4SAlok Kataria #endif
850395628efSAlok Kataria 	if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
851395628efSAlok Kataria 		tsc_clocksource_reliable = 1;
852395628efSAlok Kataria }
8538fbbc4b4SAlok Kataria 
8548fbbc4b4SAlok Kataria /*
8558fbbc4b4SAlok Kataria  * Make an educated guess if the TSC is trustworthy and synchronized
8568fbbc4b4SAlok Kataria  * over all CPUs.
8578fbbc4b4SAlok Kataria  */
8588fbbc4b4SAlok Kataria __cpuinit int unsynchronized_tsc(void)
8598fbbc4b4SAlok Kataria {
8608fbbc4b4SAlok Kataria 	if (!cpu_has_tsc || tsc_unstable)
8618fbbc4b4SAlok Kataria 		return 1;
8628fbbc4b4SAlok Kataria 
8633e5095d1SIngo Molnar #ifdef CONFIG_SMP
8648fbbc4b4SAlok Kataria 	if (apic_is_clustered_box())
8658fbbc4b4SAlok Kataria 		return 1;
8668fbbc4b4SAlok Kataria #endif
8678fbbc4b4SAlok Kataria 
8688fbbc4b4SAlok Kataria 	if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
8698fbbc4b4SAlok Kataria 		return 0;
8708fbbc4b4SAlok Kataria 	/*
8718fbbc4b4SAlok Kataria 	 * Intel systems are normally all synchronized.
8728fbbc4b4SAlok Kataria 	 * Exceptions must mark TSC as unstable:
8738fbbc4b4SAlok Kataria 	 */
8748fbbc4b4SAlok Kataria 	if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
8758fbbc4b4SAlok Kataria 		/* assume multi socket systems are not synchronized: */
8768fbbc4b4SAlok Kataria 		if (num_possible_cpus() > 1)
8778fbbc4b4SAlok Kataria 			tsc_unstable = 1;
8788fbbc4b4SAlok Kataria 	}
8798fbbc4b4SAlok Kataria 
8808fbbc4b4SAlok Kataria 	return tsc_unstable;
8818fbbc4b4SAlok Kataria }
8828fbbc4b4SAlok Kataria 
8838fbbc4b4SAlok Kataria static void __init init_tsc_clocksource(void)
8848fbbc4b4SAlok Kataria {
885395628efSAlok Kataria 	if (tsc_clocksource_reliable)
886395628efSAlok Kataria 		clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
8878fbbc4b4SAlok Kataria 	/* lower the rating if we already know its unstable: */
8888fbbc4b4SAlok Kataria 	if (check_tsc_unstable()) {
8898fbbc4b4SAlok Kataria 		clocksource_tsc.rating = 0;
8908fbbc4b4SAlok Kataria 		clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
8918fbbc4b4SAlok Kataria 	}
892f12a15beSJohn Stultz 	clocksource_register_khz(&clocksource_tsc, tsc_khz);
8938fbbc4b4SAlok Kataria }
8948fbbc4b4SAlok Kataria 
89508047c4fSThomas Gleixner #ifdef CONFIG_X86_64
89608047c4fSThomas Gleixner /*
89708047c4fSThomas Gleixner  * calibrate_cpu is used on systems with fixed rate TSCs to determine
89808047c4fSThomas Gleixner  * processor frequency
89908047c4fSThomas Gleixner  */
90008047c4fSThomas Gleixner #define TICK_COUNT 100000000
90108047c4fSThomas Gleixner static unsigned long __init calibrate_cpu(void)
90208047c4fSThomas Gleixner {
90308047c4fSThomas Gleixner 	int tsc_start, tsc_now;
90408047c4fSThomas Gleixner 	int i, no_ctr_free;
90508047c4fSThomas Gleixner 	unsigned long evntsel3 = 0, pmc3 = 0, pmc_now = 0;
90608047c4fSThomas Gleixner 	unsigned long flags;
90708047c4fSThomas Gleixner 
90808047c4fSThomas Gleixner 	for (i = 0; i < 4; i++)
90908047c4fSThomas Gleixner 		if (avail_to_resrv_perfctr_nmi_bit(i))
91008047c4fSThomas Gleixner 			break;
91108047c4fSThomas Gleixner 	no_ctr_free = (i == 4);
91208047c4fSThomas Gleixner 	if (no_ctr_free) {
91308047c4fSThomas Gleixner 		WARN(1, KERN_WARNING "Warning: AMD perfctrs busy ... "
91408047c4fSThomas Gleixner 		     "cpu_khz value may be incorrect.\n");
91508047c4fSThomas Gleixner 		i = 3;
91608047c4fSThomas Gleixner 		rdmsrl(MSR_K7_EVNTSEL3, evntsel3);
91708047c4fSThomas Gleixner 		wrmsrl(MSR_K7_EVNTSEL3, 0);
91808047c4fSThomas Gleixner 		rdmsrl(MSR_K7_PERFCTR3, pmc3);
91908047c4fSThomas Gleixner 	} else {
92008047c4fSThomas Gleixner 		reserve_perfctr_nmi(MSR_K7_PERFCTR0 + i);
92108047c4fSThomas Gleixner 		reserve_evntsel_nmi(MSR_K7_EVNTSEL0 + i);
92208047c4fSThomas Gleixner 	}
92308047c4fSThomas Gleixner 	local_irq_save(flags);
92408047c4fSThomas Gleixner 	/* start measuring cycles, incrementing from 0 */
92508047c4fSThomas Gleixner 	wrmsrl(MSR_K7_PERFCTR0 + i, 0);
92608047c4fSThomas Gleixner 	wrmsrl(MSR_K7_EVNTSEL0 + i, 1 << 22 | 3 << 16 | 0x76);
92708047c4fSThomas Gleixner 	rdtscl(tsc_start);
92808047c4fSThomas Gleixner 	do {
92908047c4fSThomas Gleixner 		rdmsrl(MSR_K7_PERFCTR0 + i, pmc_now);
93008047c4fSThomas Gleixner 		tsc_now = get_cycles();
93108047c4fSThomas Gleixner 	} while ((tsc_now - tsc_start) < TICK_COUNT);
93208047c4fSThomas Gleixner 
93308047c4fSThomas Gleixner 	local_irq_restore(flags);
93408047c4fSThomas Gleixner 	if (no_ctr_free) {
93508047c4fSThomas Gleixner 		wrmsrl(MSR_K7_EVNTSEL3, 0);
93608047c4fSThomas Gleixner 		wrmsrl(MSR_K7_PERFCTR3, pmc3);
93708047c4fSThomas Gleixner 		wrmsrl(MSR_K7_EVNTSEL3, evntsel3);
93808047c4fSThomas Gleixner 	} else {
93908047c4fSThomas Gleixner 		release_perfctr_nmi(MSR_K7_PERFCTR0 + i);
94008047c4fSThomas Gleixner 		release_evntsel_nmi(MSR_K7_EVNTSEL0 + i);
94108047c4fSThomas Gleixner 	}
94208047c4fSThomas Gleixner 
94308047c4fSThomas Gleixner 	return pmc_now * tsc_khz / (tsc_now - tsc_start);
94408047c4fSThomas Gleixner }
94508047c4fSThomas Gleixner #else
94608047c4fSThomas Gleixner static inline unsigned long calibrate_cpu(void) { return cpu_khz; }
94708047c4fSThomas Gleixner #endif
94808047c4fSThomas Gleixner 
9498fbbc4b4SAlok Kataria void __init tsc_init(void)
9508fbbc4b4SAlok Kataria {
9518fbbc4b4SAlok Kataria 	u64 lpj;
9528fbbc4b4SAlok Kataria 	int cpu;
9538fbbc4b4SAlok Kataria 
954845b3944SThomas Gleixner 	x86_init.timers.tsc_pre_init();
955845b3944SThomas Gleixner 
9568fbbc4b4SAlok Kataria 	if (!cpu_has_tsc)
9578fbbc4b4SAlok Kataria 		return;
9588fbbc4b4SAlok Kataria 
9592d826404SThomas Gleixner 	tsc_khz = x86_platform.calibrate_tsc();
960e93ef949SAlok Kataria 	cpu_khz = tsc_khz;
9618fbbc4b4SAlok Kataria 
962e93ef949SAlok Kataria 	if (!tsc_khz) {
9638fbbc4b4SAlok Kataria 		mark_tsc_unstable("could not calculate TSC khz");
9648fbbc4b4SAlok Kataria 		return;
9658fbbc4b4SAlok Kataria 	}
9668fbbc4b4SAlok Kataria 
9678fbbc4b4SAlok Kataria 	if (cpu_has(&boot_cpu_data, X86_FEATURE_CONSTANT_TSC) &&
9688fbbc4b4SAlok Kataria 			(boot_cpu_data.x86_vendor == X86_VENDOR_AMD))
9698fbbc4b4SAlok Kataria 		cpu_khz = calibrate_cpu();
9708fbbc4b4SAlok Kataria 
9718fbbc4b4SAlok Kataria 	printk("Detected %lu.%03lu MHz processor.\n",
9728fbbc4b4SAlok Kataria 			(unsigned long)cpu_khz / 1000,
9738fbbc4b4SAlok Kataria 			(unsigned long)cpu_khz % 1000);
9748fbbc4b4SAlok Kataria 
9758fbbc4b4SAlok Kataria 	/*
9768fbbc4b4SAlok Kataria 	 * Secondary CPUs do not run through tsc_init(), so set up
9778fbbc4b4SAlok Kataria 	 * all the scale factors for all CPUs, assuming the same
9788fbbc4b4SAlok Kataria 	 * speed as the bootup CPU. (cpufreq notifiers will fix this
9798fbbc4b4SAlok Kataria 	 * up if their speed diverges)
9808fbbc4b4SAlok Kataria 	 */
9818fbbc4b4SAlok Kataria 	for_each_possible_cpu(cpu)
9828fbbc4b4SAlok Kataria 		set_cyc2ns_scale(cpu_khz, cpu);
9838fbbc4b4SAlok Kataria 
9848fbbc4b4SAlok Kataria 	if (tsc_disabled > 0)
9858fbbc4b4SAlok Kataria 		return;
9868fbbc4b4SAlok Kataria 
9878fbbc4b4SAlok Kataria 	/* now allow native_sched_clock() to use rdtsc */
9888fbbc4b4SAlok Kataria 	tsc_disabled = 0;
9898fbbc4b4SAlok Kataria 
99070de9a97SAlok Kataria 	lpj = ((u64)tsc_khz * 1000);
99170de9a97SAlok Kataria 	do_div(lpj, HZ);
99270de9a97SAlok Kataria 	lpj_fine = lpj;
99370de9a97SAlok Kataria 
9948fbbc4b4SAlok Kataria 	use_tsc_delay();
9958fbbc4b4SAlok Kataria 	/* Check and install the TSC clocksource */
9968fbbc4b4SAlok Kataria 	dmi_check_system(bad_tsc_dmi_table);
9978fbbc4b4SAlok Kataria 
9988fbbc4b4SAlok Kataria 	if (unsynchronized_tsc())
9998fbbc4b4SAlok Kataria 		mark_tsc_unstable("TSCs unsynchronized");
10008fbbc4b4SAlok Kataria 
1001395628efSAlok Kataria 	check_system_tsc_reliable();
10028fbbc4b4SAlok Kataria 	init_tsc_clocksource();
10038fbbc4b4SAlok Kataria }
10048fbbc4b4SAlok Kataria 
1005