x86: Replace the now identical time_32/64.c by time.c
[linux-2.6-block.git] / arch / x86 / kernel / tsc.c
CommitLineData
bfc0f594 1#include <linux/kernel.h>
0ef95533
AK
2#include <linux/sched.h>
3#include <linux/init.h>
4#include <linux/module.h>
5#include <linux/timer.h>
bfc0f594 6#include <linux/acpi_pmtmr.h>
2dbe06fa 7#include <linux/cpufreq.h>
8fbbc4b4
AK
8#include <linux/dmi.h>
9#include <linux/delay.h>
10#include <linux/clocksource.h>
11#include <linux/percpu.h>
08604bd9 12#include <linux/timex.h>
bfc0f594
AK
13
14#include <asm/hpet.h>
8fbbc4b4
AK
15#include <asm/timer.h>
16#include <asm/vgtod.h>
17#include <asm/time.h>
18#include <asm/delay.h>
88b094fb 19#include <asm/hypervisor.h>
08047c4f 20#include <asm/nmi.h>
0ef95533 21
f24ade3a 22unsigned int __read_mostly cpu_khz; /* TSC clocks / usec, not used here */
0ef95533 23EXPORT_SYMBOL(cpu_khz);
f24ade3a
IM
24
25unsigned int __read_mostly tsc_khz;
0ef95533
AK
26EXPORT_SYMBOL(tsc_khz);
27
28/*
29 * TSC can be unstable due to cpufreq or due to unsynced TSCs
30 */
f24ade3a 31static int __read_mostly tsc_unstable;
0ef95533
AK
32
33/* native_sched_clock() is called before tsc_init(), so
34 we must start with the TSC soft disabled to prevent
35 erroneous rdtsc usage on !cpu_has_tsc processors */
f24ade3a 36static int __read_mostly tsc_disabled = -1;
0ef95533 37
395628ef 38static int tsc_clocksource_reliable;
0ef95533
AK
39/*
40 * Scheduler clock - returns current time in nanosec units.
41 */
42u64 native_sched_clock(void)
43{
44 u64 this_offset;
45
46 /*
47 * Fall back to jiffies if there's no TSC available:
48 * ( But note that we still use it if the TSC is marked
49 * unstable. We do this because unlike Time Of Day,
50 * the scheduler clock tolerates small errors and it's
51 * very important for it to be as fast as the platform
52 * can achive it. )
53 */
54 if (unlikely(tsc_disabled)) {
55 /* No locking but a rare wrong value is not a big deal: */
56 return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
57 }
58
59 /* read the Time Stamp Counter: */
60 rdtscll(this_offset);
61
62 /* return the value in ns */
7cbaef9c 63 return __cycles_2_ns(this_offset);
0ef95533
AK
64}
65
66/* We need to define a real function for sched_clock, to override the
67 weak default version */
68#ifdef CONFIG_PARAVIRT
69unsigned long long sched_clock(void)
70{
71 return paravirt_sched_clock();
72}
73#else
74unsigned long long
75sched_clock(void) __attribute__((alias("native_sched_clock")));
76#endif
77
78int check_tsc_unstable(void)
79{
80 return tsc_unstable;
81}
82EXPORT_SYMBOL_GPL(check_tsc_unstable);
83
84#ifdef CONFIG_X86_TSC
85int __init notsc_setup(char *str)
86{
87 printk(KERN_WARNING "notsc: Kernel compiled with CONFIG_X86_TSC, "
88 "cannot disable TSC completely.\n");
89 tsc_disabled = 1;
90 return 1;
91}
92#else
93/*
94 * disable flag for tsc. Takes effect by clearing the TSC cpu flag
95 * in cpu/common.c
96 */
97int __init notsc_setup(char *str)
98{
99 setup_clear_cpu_cap(X86_FEATURE_TSC);
100 return 1;
101}
102#endif
103
104__setup("notsc", notsc_setup);
bfc0f594 105
395628ef
AK
106static int __init tsc_setup(char *str)
107{
108 if (!strcmp(str, "reliable"))
109 tsc_clocksource_reliable = 1;
110 return 1;
111}
112
113__setup("tsc=", tsc_setup);
114
bfc0f594
AK
115#define MAX_RETRIES 5
116#define SMI_TRESHOLD 50000
117
118/*
119 * Read TSC and the reference counters. Take care of SMI disturbance
120 */
827014be 121static u64 tsc_read_refs(u64 *p, int hpet)
bfc0f594
AK
122{
123 u64 t1, t2;
124 int i;
125
126 for (i = 0; i < MAX_RETRIES; i++) {
127 t1 = get_cycles();
128 if (hpet)
827014be 129 *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
bfc0f594 130 else
827014be 131 *p = acpi_pm_read_early();
bfc0f594
AK
132 t2 = get_cycles();
133 if ((t2 - t1) < SMI_TRESHOLD)
134 return t2;
135 }
136 return ULLONG_MAX;
137}
138
d683ef7a
TG
139/*
140 * Calculate the TSC frequency from HPET reference
bfc0f594 141 */
d683ef7a 142static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
bfc0f594 143{
d683ef7a 144 u64 tmp;
bfc0f594 145
d683ef7a
TG
146 if (hpet2 < hpet1)
147 hpet2 += 0x100000000ULL;
148 hpet2 -= hpet1;
149 tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
150 do_div(tmp, 1000000);
151 do_div(deltatsc, tmp);
152
153 return (unsigned long) deltatsc;
154}
155
156/*
157 * Calculate the TSC frequency from PMTimer reference
158 */
159static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
160{
161 u64 tmp;
bfc0f594 162
d683ef7a
TG
163 if (!pm1 && !pm2)
164 return ULONG_MAX;
165
166 if (pm2 < pm1)
167 pm2 += (u64)ACPI_PM_OVRRUN;
168 pm2 -= pm1;
169 tmp = pm2 * 1000000000LL;
170 do_div(tmp, PMTMR_TICKS_PER_SEC);
171 do_div(deltatsc, tmp);
172
173 return (unsigned long) deltatsc;
174}
175
a977c400 176#define CAL_MS 10
cce3e057 177#define CAL_LATCH (CLOCK_TICK_RATE / (1000 / CAL_MS))
a977c400
TG
178#define CAL_PIT_LOOPS 1000
179
180#define CAL2_MS 50
181#define CAL2_LATCH (CLOCK_TICK_RATE / (1000 / CAL2_MS))
182#define CAL2_PIT_LOOPS 5000
183
cce3e057 184
ec0c15af
LT
185/*
186 * Try to calibrate the TSC against the Programmable
187 * Interrupt Timer and return the frequency of the TSC
188 * in kHz.
189 *
190 * Return ULONG_MAX on failure to calibrate.
191 */
a977c400 192static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
ec0c15af
LT
193{
194 u64 tsc, t1, t2, delta;
195 unsigned long tscmin, tscmax;
196 int pitcnt;
197
198 /* Set the Gate high, disable speaker */
199 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
200
201 /*
202 * Setup CTC channel 2* for mode 0, (interrupt on terminal
203 * count mode), binary count. Set the latch register to 50ms
204 * (LSB then MSB) to begin countdown.
205 */
206 outb(0xb0, 0x43);
a977c400
TG
207 outb(latch & 0xff, 0x42);
208 outb(latch >> 8, 0x42);
ec0c15af
LT
209
210 tsc = t1 = t2 = get_cycles();
211
212 pitcnt = 0;
213 tscmax = 0;
214 tscmin = ULONG_MAX;
215 while ((inb(0x61) & 0x20) == 0) {
216 t2 = get_cycles();
217 delta = t2 - tsc;
218 tsc = t2;
219 if ((unsigned long) delta < tscmin)
220 tscmin = (unsigned int) delta;
221 if ((unsigned long) delta > tscmax)
222 tscmax = (unsigned int) delta;
223 pitcnt++;
224 }
225
226 /*
227 * Sanity checks:
228 *
a977c400 229 * If we were not able to read the PIT more than loopmin
ec0c15af
LT
230 * times, then we have been hit by a massive SMI
231 *
232 * If the maximum is 10 times larger than the minimum,
233 * then we got hit by an SMI as well.
234 */
a977c400 235 if (pitcnt < loopmin || tscmax > 10 * tscmin)
ec0c15af
LT
236 return ULONG_MAX;
237
238 /* Calculate the PIT value */
239 delta = t2 - t1;
a977c400 240 do_div(delta, ms);
ec0c15af
LT
241 return delta;
242}
243
6ac40ed0
LT
244/*
245 * This reads the current MSB of the PIT counter, and
246 * checks if we are running on sufficiently fast and
247 * non-virtualized hardware.
248 *
249 * Our expectations are:
250 *
251 * - the PIT is running at roughly 1.19MHz
252 *
253 * - each IO is going to take about 1us on real hardware,
254 * but we allow it to be much faster (by a factor of 10) or
255 * _slightly_ slower (ie we allow up to a 2us read+counter
256 * update - anything else implies a unacceptably slow CPU
257 * or PIT for the fast calibration to work.
258 *
259 * - with 256 PIT ticks to read the value, we have 214us to
260 * see the same MSB (and overhead like doing a single TSC
261 * read per MSB value etc).
262 *
263 * - We're doing 2 reads per loop (LSB, MSB), and we expect
264 * them each to take about a microsecond on real hardware.
265 * So we expect a count value of around 100. But we'll be
266 * generous, and accept anything over 50.
267 *
268 * - if the PIT is stuck, and we see *many* more reads, we
269 * return early (and the next caller of pit_expect_msb()
270 * then consider it a failure when they don't see the
271 * next expected value).
272 *
273 * These expectations mean that we know that we have seen the
274 * transition from one expected value to another with a fairly
275 * high accuracy, and we didn't miss any events. We can thus
276 * use the TSC value at the transitions to calculate a pretty
277 * good value for the TSC frequencty.
278 */
b6e61eef
LT
279static inline int pit_verify_msb(unsigned char val)
280{
281 /* Ignore LSB */
282 inb(0x42);
283 return inb(0x42) == val;
284}
285
9e8912e0 286static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
6ac40ed0 287{
9e8912e0
LT
288 int count;
289 u64 tsc = 0;
bfc0f594 290
6ac40ed0 291 for (count = 0; count < 50000; count++) {
b6e61eef 292 if (!pit_verify_msb(val))
6ac40ed0 293 break;
9e8912e0 294 tsc = get_cycles();
6ac40ed0 295 }
9e8912e0
LT
296 *deltap = get_cycles() - tsc;
297 *tscp = tsc;
298
299 /*
300 * We require _some_ success, but the quality control
301 * will be based on the error terms on the TSC values.
302 */
303 return count > 5;
6ac40ed0
LT
304}
305
306/*
9e8912e0
LT
307 * How many MSB values do we want to see? We aim for
308 * a maximum error rate of 500ppm (in practice the
309 * real error is much smaller), but refuse to spend
310 * more than 25ms on it.
6ac40ed0 311 */
9e8912e0
LT
312#define MAX_QUICK_PIT_MS 25
313#define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
bfc0f594 314
6ac40ed0
LT
315static unsigned long quick_pit_calibrate(void)
316{
9e8912e0
LT
317 int i;
318 u64 tsc, delta;
319 unsigned long d1, d2;
320
6ac40ed0 321 /* Set the Gate high, disable speaker */
bfc0f594
AK
322 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
323
6ac40ed0
LT
324 /*
325 * Counter 2, mode 0 (one-shot), binary count
326 *
327 * NOTE! Mode 2 decrements by two (and then the
328 * output is flipped each time, giving the same
329 * final output frequency as a decrement-by-one),
330 * so mode 0 is much better when looking at the
331 * individual counts.
332 */
bfc0f594 333 outb(0xb0, 0x43);
bfc0f594 334
6ac40ed0
LT
335 /* Start at 0xffff */
336 outb(0xff, 0x42);
337 outb(0xff, 0x42);
338
a6a80e1d
LT
339 /*
340 * The PIT starts counting at the next edge, so we
341 * need to delay for a microsecond. The easiest way
342 * to do that is to just read back the 16-bit counter
343 * once from the PIT.
344 */
b6e61eef 345 pit_verify_msb(0);
a6a80e1d 346
9e8912e0
LT
347 if (pit_expect_msb(0xff, &tsc, &d1)) {
348 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
349 if (!pit_expect_msb(0xff-i, &delta, &d2))
350 break;
351
352 /*
353 * Iterate until the error is less than 500 ppm
354 */
355 delta -= tsc;
b6e61eef
LT
356 if (d1+d2 >= delta >> 11)
357 continue;
358
359 /*
360 * Check the PIT one more time to verify that
361 * all TSC reads were stable wrt the PIT.
362 *
363 * This also guarantees serialization of the
364 * last cycle read ('d2') in pit_expect_msb.
365 */
366 if (!pit_verify_msb(0xfe - i))
367 break;
368 goto success;
6ac40ed0 369 }
6ac40ed0 370 }
9e8912e0 371 printk("Fast TSC calibration failed\n");
6ac40ed0 372 return 0;
9e8912e0
LT
373
374success:
375 /*
376 * Ok, if we get here, then we've seen the
377 * MSB of the PIT decrement 'i' times, and the
378 * error has shrunk to less than 500 ppm.
379 *
380 * As a result, we can depend on there not being
381 * any odd delays anywhere, and the TSC reads are
382 * reliable (within the error). We also adjust the
383 * delta to the middle of the error bars, just
384 * because it looks nicer.
385 *
386 * kHz = ticks / time-in-seconds / 1000;
387 * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
388 * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
389 */
390 delta += (long)(d2 - d1)/2;
391 delta *= PIT_TICK_RATE;
392 do_div(delta, i*256*1000);
393 printk("Fast TSC calibration using PIT\n");
394 return delta;
6ac40ed0 395}
ec0c15af 396
bfc0f594 397/**
e93ef949 398 * native_calibrate_tsc - calibrate the tsc on boot
bfc0f594 399 */
e93ef949 400unsigned long native_calibrate_tsc(void)
bfc0f594 401{
827014be 402 u64 tsc1, tsc2, delta, ref1, ref2;
fbb16e24 403 unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
2c1b284e 404 unsigned long flags, latch, ms, fast_calibrate, hv_tsc_khz;
a977c400 405 int hpet = is_hpet_enabled(), i, loopmin;
bfc0f594 406
2c1b284e
JSR
407 hv_tsc_khz = get_hypervisor_tsc_freq();
408 if (hv_tsc_khz) {
88b094fb 409 printk(KERN_INFO "TSC: Frequency read from the hypervisor\n");
2c1b284e 410 return hv_tsc_khz;
88b094fb
AK
411 }
412
6ac40ed0
LT
413 local_irq_save(flags);
414 fast_calibrate = quick_pit_calibrate();
bfc0f594 415 local_irq_restore(flags);
6ac40ed0
LT
416 if (fast_calibrate)
417 return fast_calibrate;
bfc0f594 418
fbb16e24
TG
419 /*
420 * Run 5 calibration loops to get the lowest frequency value
421 * (the best estimate). We use two different calibration modes
422 * here:
423 *
424 * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
425 * load a timeout of 50ms. We read the time right after we
426 * started the timer and wait until the PIT count down reaches
427 * zero. In each wait loop iteration we read the TSC and check
428 * the delta to the previous read. We keep track of the min
429 * and max values of that delta. The delta is mostly defined
430 * by the IO time of the PIT access, so we can detect when a
431 * SMI/SMM disturbance happend between the two reads. If the
432 * maximum time is significantly larger than the minimum time,
433 * then we discard the result and have another try.
434 *
435 * 2) Reference counter. If available we use the HPET or the
436 * PMTIMER as a reference to check the sanity of that value.
437 * We use separate TSC readouts and check inside of the
438 * reference read for a SMI/SMM disturbance. We dicard
439 * disturbed values here as well. We do that around the PIT
440 * calibration delay loop as we have to wait for a certain
441 * amount of time anyway.
442 */
a977c400
TG
443
444 /* Preset PIT loop values */
445 latch = CAL_LATCH;
446 ms = CAL_MS;
447 loopmin = CAL_PIT_LOOPS;
448
449 for (i = 0; i < 3; i++) {
ec0c15af 450 unsigned long tsc_pit_khz;
fbb16e24
TG
451
452 /*
453 * Read the start value and the reference count of
ec0c15af
LT
454 * hpet/pmtimer when available. Then do the PIT
455 * calibration, which will take at least 50ms, and
456 * read the end value.
fbb16e24 457 */
ec0c15af 458 local_irq_save(flags);
827014be 459 tsc1 = tsc_read_refs(&ref1, hpet);
a977c400 460 tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
827014be 461 tsc2 = tsc_read_refs(&ref2, hpet);
fbb16e24
TG
462 local_irq_restore(flags);
463
ec0c15af
LT
464 /* Pick the lowest PIT TSC calibration so far */
465 tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
fbb16e24
TG
466
467 /* hpet or pmtimer available ? */
827014be 468 if (!hpet && !ref1 && !ref2)
fbb16e24
TG
469 continue;
470
471 /* Check, whether the sampling was disturbed by an SMI */
472 if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
473 continue;
474
475 tsc2 = (tsc2 - tsc1) * 1000000LL;
d683ef7a 476 if (hpet)
827014be 477 tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
d683ef7a 478 else
827014be 479 tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
fbb16e24 480
fbb16e24 481 tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
a977c400
TG
482
483 /* Check the reference deviation */
484 delta = ((u64) tsc_pit_min) * 100;
485 do_div(delta, tsc_ref_min);
486
487 /*
488 * If both calibration results are inside a 10% window
489 * then we can be sure, that the calibration
490 * succeeded. We break out of the loop right away. We
491 * use the reference value, as it is more precise.
492 */
493 if (delta >= 90 && delta <= 110) {
494 printk(KERN_INFO
495 "TSC: PIT calibration matches %s. %d loops\n",
496 hpet ? "HPET" : "PMTIMER", i + 1);
497 return tsc_ref_min;
fbb16e24
TG
498 }
499
a977c400
TG
500 /*
501 * Check whether PIT failed more than once. This
502 * happens in virtualized environments. We need to
503 * give the virtual PC a slightly longer timeframe for
504 * the HPET/PMTIMER to make the result precise.
505 */
506 if (i == 1 && tsc_pit_min == ULONG_MAX) {
507 latch = CAL2_LATCH;
508 ms = CAL2_MS;
509 loopmin = CAL2_PIT_LOOPS;
510 }
fbb16e24 511 }
bfc0f594
AK
512
513 /*
fbb16e24 514 * Now check the results.
bfc0f594 515 */
fbb16e24
TG
516 if (tsc_pit_min == ULONG_MAX) {
517 /* PIT gave no useful value */
de014d61 518 printk(KERN_WARNING "TSC: Unable to calibrate against PIT\n");
fbb16e24
TG
519
520 /* We don't have an alternative source, disable TSC */
827014be 521 if (!hpet && !ref1 && !ref2) {
fbb16e24
TG
522 printk("TSC: No reference (HPET/PMTIMER) available\n");
523 return 0;
524 }
525
526 /* The alternative source failed as well, disable TSC */
527 if (tsc_ref_min == ULONG_MAX) {
528 printk(KERN_WARNING "TSC: HPET/PMTIMER calibration "
a977c400 529 "failed.\n");
fbb16e24
TG
530 return 0;
531 }
532
533 /* Use the alternative source */
534 printk(KERN_INFO "TSC: using %s reference calibration\n",
535 hpet ? "HPET" : "PMTIMER");
536
537 return tsc_ref_min;
538 }
bfc0f594 539
fbb16e24 540 /* We don't have an alternative source, use the PIT calibration value */
827014be 541 if (!hpet && !ref1 && !ref2) {
fbb16e24
TG
542 printk(KERN_INFO "TSC: Using PIT calibration value\n");
543 return tsc_pit_min;
bfc0f594
AK
544 }
545
fbb16e24
TG
546 /* The alternative source failed, use the PIT calibration value */
547 if (tsc_ref_min == ULONG_MAX) {
a977c400
TG
548 printk(KERN_WARNING "TSC: HPET/PMTIMER calibration failed. "
549 "Using PIT calibration\n");
fbb16e24 550 return tsc_pit_min;
bfc0f594
AK
551 }
552
fbb16e24
TG
553 /*
554 * The calibration values differ too much. In doubt, we use
555 * the PIT value as we know that there are PMTIMERs around
a977c400 556 * running at double speed. At least we let the user know:
fbb16e24 557 */
a977c400
TG
558 printk(KERN_WARNING "TSC: PIT calibration deviates from %s: %lu %lu.\n",
559 hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
fbb16e24
TG
560 printk(KERN_INFO "TSC: Using PIT calibration value\n");
561 return tsc_pit_min;
bfc0f594
AK
562}
563
bfc0f594
AK
564int recalibrate_cpu_khz(void)
565{
566#ifndef CONFIG_SMP
567 unsigned long cpu_khz_old = cpu_khz;
568
569 if (cpu_has_tsc) {
e93ef949
AK
570 tsc_khz = calibrate_tsc();
571 cpu_khz = tsc_khz;
bfc0f594
AK
572 cpu_data(0).loops_per_jiffy =
573 cpufreq_scale(cpu_data(0).loops_per_jiffy,
574 cpu_khz_old, cpu_khz);
575 return 0;
576 } else
577 return -ENODEV;
578#else
579 return -ENODEV;
580#endif
581}
582
583EXPORT_SYMBOL(recalibrate_cpu_khz);
584
2dbe06fa
AK
585
586/* Accelerators for sched_clock()
587 * convert from cycles(64bits) => nanoseconds (64bits)
588 * basic equation:
589 * ns = cycles / (freq / ns_per_sec)
590 * ns = cycles * (ns_per_sec / freq)
591 * ns = cycles * (10^9 / (cpu_khz * 10^3))
592 * ns = cycles * (10^6 / cpu_khz)
593 *
594 * Then we use scaling math (suggested by george@mvista.com) to get:
595 * ns = cycles * (10^6 * SC / cpu_khz) / SC
596 * ns = cycles * cyc2ns_scale / SC
597 *
598 * And since SC is a constant power of two, we can convert the div
599 * into a shift.
600 *
601 * We can use khz divisor instead of mhz to keep a better precision, since
602 * cyc2ns_scale is limited to 10^6 * 2^10, which fits in 32 bits.
603 * (mathieu.desnoyers@polymtl.ca)
604 *
605 * -johnstul@us.ibm.com "math is hard, lets go shopping!"
606 */
607
608DEFINE_PER_CPU(unsigned long, cyc2ns);
84599f8a 609DEFINE_PER_CPU(unsigned long long, cyc2ns_offset);
2dbe06fa 610
8fbbc4b4 611static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
2dbe06fa 612{
84599f8a 613 unsigned long long tsc_now, ns_now, *offset;
2dbe06fa
AK
614 unsigned long flags, *scale;
615
616 local_irq_save(flags);
617 sched_clock_idle_sleep_event();
618
619 scale = &per_cpu(cyc2ns, cpu);
84599f8a 620 offset = &per_cpu(cyc2ns_offset, cpu);
2dbe06fa
AK
621
622 rdtscll(tsc_now);
623 ns_now = __cycles_2_ns(tsc_now);
624
84599f8a 625 if (cpu_khz) {
2dbe06fa 626 *scale = (NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR)/cpu_khz;
84599f8a
PZ
627 *offset = ns_now - (tsc_now * *scale >> CYC2NS_SCALE_FACTOR);
628 }
2dbe06fa
AK
629
630 sched_clock_idle_wakeup_event(0);
631 local_irq_restore(flags);
632}
633
634#ifdef CONFIG_CPU_FREQ
635
636/* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
637 * changes.
638 *
639 * RED-PEN: On SMP we assume all CPUs run with the same frequency. It's
640 * not that important because current Opteron setups do not support
641 * scaling on SMP anyroads.
642 *
643 * Should fix up last_tsc too. Currently gettimeofday in the
644 * first tick after the change will be slightly wrong.
645 */
646
647static unsigned int ref_freq;
648static unsigned long loops_per_jiffy_ref;
649static unsigned long tsc_khz_ref;
650
651static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
652 void *data)
653{
654 struct cpufreq_freqs *freq = data;
931db6a3 655 unsigned long *lpj;
2dbe06fa
AK
656
657 if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
658 return 0;
659
931db6a3 660 lpj = &boot_cpu_data.loops_per_jiffy;
2dbe06fa 661#ifdef CONFIG_SMP
931db6a3 662 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
2dbe06fa 663 lpj = &cpu_data(freq->cpu).loops_per_jiffy;
2dbe06fa
AK
664#endif
665
666 if (!ref_freq) {
667 ref_freq = freq->old;
668 loops_per_jiffy_ref = *lpj;
669 tsc_khz_ref = tsc_khz;
670 }
671 if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
672 (val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
673 (val == CPUFREQ_RESUMECHANGE)) {
674 *lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
675
676 tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
677 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
678 mark_tsc_unstable("cpufreq changes");
679 }
680
52a8968c 681 set_cyc2ns_scale(tsc_khz, freq->cpu);
2dbe06fa
AK
682
683 return 0;
684}
685
686static struct notifier_block time_cpufreq_notifier_block = {
687 .notifier_call = time_cpufreq_notifier
688};
689
690static int __init cpufreq_tsc(void)
691{
060700b5
LT
692 if (!cpu_has_tsc)
693 return 0;
694 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
695 return 0;
2dbe06fa
AK
696 cpufreq_register_notifier(&time_cpufreq_notifier_block,
697 CPUFREQ_TRANSITION_NOTIFIER);
698 return 0;
699}
700
701core_initcall(cpufreq_tsc);
702
703#endif /* CONFIG_CPU_FREQ */
8fbbc4b4
AK
704
705/* clocksource code */
706
707static struct clocksource clocksource_tsc;
708
709/*
710 * We compare the TSC to the cycle_last value in the clocksource
711 * structure to avoid a nasty time-warp. This can be observed in a
712 * very small window right after one CPU updated cycle_last under
713 * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
714 * is smaller than the cycle_last reference value due to a TSC which
715 * is slighty behind. This delta is nowhere else observable, but in
716 * that case it results in a forward time jump in the range of hours
717 * due to the unsigned delta calculation of the time keeping core
718 * code, which is necessary to support wrapping clocksources like pm
719 * timer.
720 */
8e19608e 721static cycle_t read_tsc(struct clocksource *cs)
8fbbc4b4
AK
722{
723 cycle_t ret = (cycle_t)get_cycles();
724
725 return ret >= clocksource_tsc.cycle_last ?
726 ret : clocksource_tsc.cycle_last;
727}
728
431ceb83 729#ifdef CONFIG_X86_64
8fbbc4b4
AK
730static cycle_t __vsyscall_fn vread_tsc(void)
731{
7d96fd41
PT
732 cycle_t ret;
733
734 /*
735 * Surround the RDTSC by barriers, to make sure it's not
736 * speculated to outside the seqlock critical section and
737 * does not cause time warps:
738 */
739 rdtsc_barrier();
740 ret = (cycle_t)vget_cycles();
741 rdtsc_barrier();
8fbbc4b4
AK
742
743 return ret >= __vsyscall_gtod_data.clock.cycle_last ?
744 ret : __vsyscall_gtod_data.clock.cycle_last;
745}
431ceb83 746#endif
8fbbc4b4
AK
747
748static struct clocksource clocksource_tsc = {
749 .name = "tsc",
750 .rating = 300,
751 .read = read_tsc,
752 .mask = CLOCKSOURCE_MASK(64),
753 .shift = 22,
754 .flags = CLOCK_SOURCE_IS_CONTINUOUS |
755 CLOCK_SOURCE_MUST_VERIFY,
756#ifdef CONFIG_X86_64
757 .vread = vread_tsc,
758#endif
759};
760
761void mark_tsc_unstable(char *reason)
762{
763 if (!tsc_unstable) {
764 tsc_unstable = 1;
765 printk("Marking TSC unstable due to %s\n", reason);
766 /* Change only the rating, when not registered */
767 if (clocksource_tsc.mult)
768 clocksource_change_rating(&clocksource_tsc, 0);
769 else
770 clocksource_tsc.rating = 0;
771 }
772}
773
774EXPORT_SYMBOL_GPL(mark_tsc_unstable);
775
776static int __init dmi_mark_tsc_unstable(const struct dmi_system_id *d)
777{
778 printk(KERN_NOTICE "%s detected: marking TSC unstable.\n",
779 d->ident);
780 tsc_unstable = 1;
781 return 0;
782}
783
784/* List of systems that have known TSC problems */
785static struct dmi_system_id __initdata bad_tsc_dmi_table[] = {
786 {
787 .callback = dmi_mark_tsc_unstable,
788 .ident = "IBM Thinkpad 380XD",
789 .matches = {
790 DMI_MATCH(DMI_BOARD_VENDOR, "IBM"),
791 DMI_MATCH(DMI_BOARD_NAME, "2635FA0"),
792 },
793 },
794 {}
795};
796
395628ef
AK
797static void __init check_system_tsc_reliable(void)
798{
8fbbc4b4 799#ifdef CONFIG_MGEODE_LX
395628ef 800 /* RTSC counts during suspend */
8fbbc4b4 801#define RTSC_SUSP 0x100
8fbbc4b4
AK
802 unsigned long res_low, res_high;
803
804 rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
395628ef 805 /* Geode_LX - the OLPC CPU has a possibly a very reliable TSC */
8fbbc4b4 806 if (res_low & RTSC_SUSP)
395628ef 807 tsc_clocksource_reliable = 1;
8fbbc4b4 808#endif
395628ef
AK
809 if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
810 tsc_clocksource_reliable = 1;
811}
8fbbc4b4
AK
812
813/*
814 * Make an educated guess if the TSC is trustworthy and synchronized
815 * over all CPUs.
816 */
817__cpuinit int unsynchronized_tsc(void)
818{
819 if (!cpu_has_tsc || tsc_unstable)
820 return 1;
821
3e5095d1 822#ifdef CONFIG_SMP
8fbbc4b4
AK
823 if (apic_is_clustered_box())
824 return 1;
825#endif
826
827 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
828 return 0;
829 /*
830 * Intel systems are normally all synchronized.
831 * Exceptions must mark TSC as unstable:
832 */
833 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
834 /* assume multi socket systems are not synchronized: */
835 if (num_possible_cpus() > 1)
836 tsc_unstable = 1;
837 }
838
839 return tsc_unstable;
840}
841
842static void __init init_tsc_clocksource(void)
843{
844 clocksource_tsc.mult = clocksource_khz2mult(tsc_khz,
845 clocksource_tsc.shift);
395628ef
AK
846 if (tsc_clocksource_reliable)
847 clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
8fbbc4b4
AK
848 /* lower the rating if we already know its unstable: */
849 if (check_tsc_unstable()) {
850 clocksource_tsc.rating = 0;
851 clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
852 }
853 clocksource_register(&clocksource_tsc);
854}
855
08047c4f
TG
856#ifdef CONFIG_X86_64
857/*
858 * calibrate_cpu is used on systems with fixed rate TSCs to determine
859 * processor frequency
860 */
861#define TICK_COUNT 100000000
862static unsigned long __init calibrate_cpu(void)
863{
864 int tsc_start, tsc_now;
865 int i, no_ctr_free;
866 unsigned long evntsel3 = 0, pmc3 = 0, pmc_now = 0;
867 unsigned long flags;
868
869 for (i = 0; i < 4; i++)
870 if (avail_to_resrv_perfctr_nmi_bit(i))
871 break;
872 no_ctr_free = (i == 4);
873 if (no_ctr_free) {
874 WARN(1, KERN_WARNING "Warning: AMD perfctrs busy ... "
875 "cpu_khz value may be incorrect.\n");
876 i = 3;
877 rdmsrl(MSR_K7_EVNTSEL3, evntsel3);
878 wrmsrl(MSR_K7_EVNTSEL3, 0);
879 rdmsrl(MSR_K7_PERFCTR3, pmc3);
880 } else {
881 reserve_perfctr_nmi(MSR_K7_PERFCTR0 + i);
882 reserve_evntsel_nmi(MSR_K7_EVNTSEL0 + i);
883 }
884 local_irq_save(flags);
885 /* start measuring cycles, incrementing from 0 */
886 wrmsrl(MSR_K7_PERFCTR0 + i, 0);
887 wrmsrl(MSR_K7_EVNTSEL0 + i, 1 << 22 | 3 << 16 | 0x76);
888 rdtscl(tsc_start);
889 do {
890 rdmsrl(MSR_K7_PERFCTR0 + i, pmc_now);
891 tsc_now = get_cycles();
892 } while ((tsc_now - tsc_start) < TICK_COUNT);
893
894 local_irq_restore(flags);
895 if (no_ctr_free) {
896 wrmsrl(MSR_K7_EVNTSEL3, 0);
897 wrmsrl(MSR_K7_PERFCTR3, pmc3);
898 wrmsrl(MSR_K7_EVNTSEL3, evntsel3);
899 } else {
900 release_perfctr_nmi(MSR_K7_PERFCTR0 + i);
901 release_evntsel_nmi(MSR_K7_EVNTSEL0 + i);
902 }
903
904 return pmc_now * tsc_khz / (tsc_now - tsc_start);
905}
906#else
907static inline unsigned long calibrate_cpu(void) { return cpu_khz; }
908#endif
909
8fbbc4b4
AK
910void __init tsc_init(void)
911{
912 u64 lpj;
913 int cpu;
914
845b3944
TG
915 x86_init.timers.tsc_pre_init();
916
8fbbc4b4
AK
917 if (!cpu_has_tsc)
918 return;
919
e93ef949
AK
920 tsc_khz = calibrate_tsc();
921 cpu_khz = tsc_khz;
8fbbc4b4 922
e93ef949 923 if (!tsc_khz) {
8fbbc4b4
AK
924 mark_tsc_unstable("could not calculate TSC khz");
925 return;
926 }
927
8fbbc4b4
AK
928 if (cpu_has(&boot_cpu_data, X86_FEATURE_CONSTANT_TSC) &&
929 (boot_cpu_data.x86_vendor == X86_VENDOR_AMD))
930 cpu_khz = calibrate_cpu();
8fbbc4b4 931
8fbbc4b4
AK
932 printk("Detected %lu.%03lu MHz processor.\n",
933 (unsigned long)cpu_khz / 1000,
934 (unsigned long)cpu_khz % 1000);
935
936 /*
937 * Secondary CPUs do not run through tsc_init(), so set up
938 * all the scale factors for all CPUs, assuming the same
939 * speed as the bootup CPU. (cpufreq notifiers will fix this
940 * up if their speed diverges)
941 */
942 for_each_possible_cpu(cpu)
943 set_cyc2ns_scale(cpu_khz, cpu);
944
945 if (tsc_disabled > 0)
946 return;
947
948 /* now allow native_sched_clock() to use rdtsc */
949 tsc_disabled = 0;
950
70de9a97
AK
951 lpj = ((u64)tsc_khz * 1000);
952 do_div(lpj, HZ);
953 lpj_fine = lpj;
954
8fbbc4b4
AK
955 use_tsc_delay();
956 /* Check and install the TSC clocksource */
957 dmi_check_system(bad_tsc_dmi_table);
958
959 if (unsynchronized_tsc())
960 mark_tsc_unstable("TSCs unsynchronized");
961
395628ef 962 check_system_tsc_reliable();
8fbbc4b4
AK
963 init_tsc_clocksource();
964}
965