mfd: wm8350-i2c: Make sure the i2c regmap functions are compiled
[linux/fpc-iii.git] / arch / x86 / kernel / tsc.c
blobb40765803d05d3e796d866bbbbaa6359064019fb
1 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3 #include <linux/kernel.h>
4 #include <linux/sched.h>
5 #include <linux/init.h>
6 #include <linux/module.h>
7 #include <linux/timer.h>
8 #include <linux/acpi_pmtmr.h>
9 #include <linux/cpufreq.h>
10 #include <linux/delay.h>
11 #include <linux/clocksource.h>
12 #include <linux/percpu.h>
13 #include <linux/timex.h>
15 #include <asm/hpet.h>
16 #include <asm/timer.h>
17 #include <asm/vgtod.h>
18 #include <asm/time.h>
19 #include <asm/delay.h>
20 #include <asm/hypervisor.h>
21 #include <asm/nmi.h>
22 #include <asm/x86_init.h>
23 #include <asm/geode.h>
25 unsigned int __read_mostly cpu_khz; /* TSC clocks / usec, not used here */
26 EXPORT_SYMBOL(cpu_khz);
28 unsigned int __read_mostly tsc_khz;
29 EXPORT_SYMBOL(tsc_khz);
32 * TSC can be unstable due to cpufreq or due to unsynced TSCs
34 static int __read_mostly tsc_unstable;
36 /* native_sched_clock() is called before tsc_init(), so
37 we must start with the TSC soft disabled to prevent
38 erroneous rdtsc usage on !cpu_has_tsc processors */
39 static int __read_mostly tsc_disabled = -1;
41 int tsc_clocksource_reliable;
43 * Scheduler clock - returns current time in nanosec units.
45 u64 native_sched_clock(void)
47 u64 this_offset;
50 * Fall back to jiffies if there's no TSC available:
51 * ( But note that we still use it if the TSC is marked
52 * unstable. We do this because unlike Time Of Day,
53 * the scheduler clock tolerates small errors and it's
54 * very important for it to be as fast as the platform
55 * can achieve it. )
57 if (unlikely(tsc_disabled)) {
58 /* No locking but a rare wrong value is not a big deal: */
59 return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
62 /* read the Time Stamp Counter: */
63 rdtscll(this_offset);
65 /* return the value in ns */
66 return __cycles_2_ns(this_offset);
69 /* We need to define a real function for sched_clock, to override the
70 weak default version */
71 #ifdef CONFIG_PARAVIRT
72 unsigned long long sched_clock(void)
74 return paravirt_sched_clock();
76 #else
77 unsigned long long
78 sched_clock(void) __attribute__((alias("native_sched_clock")));
79 #endif
81 unsigned long long native_read_tsc(void)
83 return __native_read_tsc();
85 EXPORT_SYMBOL(native_read_tsc);
87 int check_tsc_unstable(void)
89 return tsc_unstable;
91 EXPORT_SYMBOL_GPL(check_tsc_unstable);
93 int check_tsc_disabled(void)
95 return tsc_disabled;
97 EXPORT_SYMBOL_GPL(check_tsc_disabled);
99 #ifdef CONFIG_X86_TSC
100 int __init notsc_setup(char *str)
102 pr_warn("Kernel compiled with CONFIG_X86_TSC, cannot disable TSC completely\n");
103 tsc_disabled = 1;
104 return 1;
106 #else
108 * disable flag for tsc. Takes effect by clearing the TSC cpu flag
109 * in cpu/common.c
111 int __init notsc_setup(char *str)
113 setup_clear_cpu_cap(X86_FEATURE_TSC);
114 return 1;
116 #endif
118 __setup("notsc", notsc_setup);
120 static int no_sched_irq_time;
122 static int __init tsc_setup(char *str)
124 if (!strcmp(str, "reliable"))
125 tsc_clocksource_reliable = 1;
126 if (!strncmp(str, "noirqtime", 9))
127 no_sched_irq_time = 1;
128 return 1;
131 __setup("tsc=", tsc_setup);
133 #define MAX_RETRIES 5
134 #define SMI_TRESHOLD 50000
137 * Read TSC and the reference counters. Take care of SMI disturbance
139 static u64 tsc_read_refs(u64 *p, int hpet)
141 u64 t1, t2;
142 int i;
144 for (i = 0; i < MAX_RETRIES; i++) {
145 t1 = get_cycles();
146 if (hpet)
147 *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
148 else
149 *p = acpi_pm_read_early();
150 t2 = get_cycles();
151 if ((t2 - t1) < SMI_TRESHOLD)
152 return t2;
154 return ULLONG_MAX;
158 * Calculate the TSC frequency from HPET reference
160 static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
162 u64 tmp;
164 if (hpet2 < hpet1)
165 hpet2 += 0x100000000ULL;
166 hpet2 -= hpet1;
167 tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
168 do_div(tmp, 1000000);
169 do_div(deltatsc, tmp);
171 return (unsigned long) deltatsc;
175 * Calculate the TSC frequency from PMTimer reference
177 static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
179 u64 tmp;
181 if (!pm1 && !pm2)
182 return ULONG_MAX;
184 if (pm2 < pm1)
185 pm2 += (u64)ACPI_PM_OVRRUN;
186 pm2 -= pm1;
187 tmp = pm2 * 1000000000LL;
188 do_div(tmp, PMTMR_TICKS_PER_SEC);
189 do_div(deltatsc, tmp);
191 return (unsigned long) deltatsc;
194 #define CAL_MS 10
195 #define CAL_LATCH (PIT_TICK_RATE / (1000 / CAL_MS))
196 #define CAL_PIT_LOOPS 1000
198 #define CAL2_MS 50
199 #define CAL2_LATCH (PIT_TICK_RATE / (1000 / CAL2_MS))
200 #define CAL2_PIT_LOOPS 5000
204 * Try to calibrate the TSC against the Programmable
205 * Interrupt Timer and return the frequency of the TSC
206 * in kHz.
208 * Return ULONG_MAX on failure to calibrate.
210 static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
212 u64 tsc, t1, t2, delta;
213 unsigned long tscmin, tscmax;
214 int pitcnt;
216 /* Set the Gate high, disable speaker */
217 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
220 * Setup CTC channel 2* for mode 0, (interrupt on terminal
221 * count mode), binary count. Set the latch register to 50ms
222 * (LSB then MSB) to begin countdown.
224 outb(0xb0, 0x43);
225 outb(latch & 0xff, 0x42);
226 outb(latch >> 8, 0x42);
228 tsc = t1 = t2 = get_cycles();
230 pitcnt = 0;
231 tscmax = 0;
232 tscmin = ULONG_MAX;
233 while ((inb(0x61) & 0x20) == 0) {
234 t2 = get_cycles();
235 delta = t2 - tsc;
236 tsc = t2;
237 if ((unsigned long) delta < tscmin)
238 tscmin = (unsigned int) delta;
239 if ((unsigned long) delta > tscmax)
240 tscmax = (unsigned int) delta;
241 pitcnt++;
245 * Sanity checks:
247 * If we were not able to read the PIT more than loopmin
248 * times, then we have been hit by a massive SMI
250 * If the maximum is 10 times larger than the minimum,
251 * then we got hit by an SMI as well.
253 if (pitcnt < loopmin || tscmax > 10 * tscmin)
254 return ULONG_MAX;
256 /* Calculate the PIT value */
257 delta = t2 - t1;
258 do_div(delta, ms);
259 return delta;
263 * This reads the current MSB of the PIT counter, and
264 * checks if we are running on sufficiently fast and
265 * non-virtualized hardware.
267 * Our expectations are:
269 * - the PIT is running at roughly 1.19MHz
271 * - each IO is going to take about 1us on real hardware,
272 * but we allow it to be much faster (by a factor of 10) or
273 * _slightly_ slower (ie we allow up to a 2us read+counter
274 * update - anything else implies a unacceptably slow CPU
275 * or PIT for the fast calibration to work.
277 * - with 256 PIT ticks to read the value, we have 214us to
278 * see the same MSB (and overhead like doing a single TSC
279 * read per MSB value etc).
281 * - We're doing 2 reads per loop (LSB, MSB), and we expect
282 * them each to take about a microsecond on real hardware.
283 * So we expect a count value of around 100. But we'll be
284 * generous, and accept anything over 50.
286 * - if the PIT is stuck, and we see *many* more reads, we
287 * return early (and the next caller of pit_expect_msb()
288 * then consider it a failure when they don't see the
289 * next expected value).
291 * These expectations mean that we know that we have seen the
292 * transition from one expected value to another with a fairly
293 * high accuracy, and we didn't miss any events. We can thus
294 * use the TSC value at the transitions to calculate a pretty
295 * good value for the TSC frequencty.
297 static inline int pit_verify_msb(unsigned char val)
299 /* Ignore LSB */
300 inb(0x42);
301 return inb(0x42) == val;
304 static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
306 int count;
307 u64 tsc = 0, prev_tsc = 0;
309 for (count = 0; count < 50000; count++) {
310 if (!pit_verify_msb(val))
311 break;
312 prev_tsc = tsc;
313 tsc = get_cycles();
315 *deltap = get_cycles() - prev_tsc;
316 *tscp = tsc;
319 * We require _some_ success, but the quality control
320 * will be based on the error terms on the TSC values.
322 return count > 5;
326 * How many MSB values do we want to see? We aim for
327 * a maximum error rate of 500ppm (in practice the
328 * real error is much smaller), but refuse to spend
329 * more than 50ms on it.
331 #define MAX_QUICK_PIT_MS 50
332 #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
334 static unsigned long quick_pit_calibrate(void)
336 int i;
337 u64 tsc, delta;
338 unsigned long d1, d2;
340 /* Set the Gate high, disable speaker */
341 outb((inb(0x61) & ~0x02) | 0x01, 0x61);
344 * Counter 2, mode 0 (one-shot), binary count
346 * NOTE! Mode 2 decrements by two (and then the
347 * output is flipped each time, giving the same
348 * final output frequency as a decrement-by-one),
349 * so mode 0 is much better when looking at the
350 * individual counts.
352 outb(0xb0, 0x43);
354 /* Start at 0xffff */
355 outb(0xff, 0x42);
356 outb(0xff, 0x42);
359 * The PIT starts counting at the next edge, so we
360 * need to delay for a microsecond. The easiest way
361 * to do that is to just read back the 16-bit counter
362 * once from the PIT.
364 pit_verify_msb(0);
366 if (pit_expect_msb(0xff, &tsc, &d1)) {
367 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
368 if (!pit_expect_msb(0xff-i, &delta, &d2))
369 break;
372 * Iterate until the error is less than 500 ppm
374 delta -= tsc;
375 if (d1+d2 >= delta >> 11)
376 continue;
379 * Check the PIT one more time to verify that
380 * all TSC reads were stable wrt the PIT.
382 * This also guarantees serialization of the
383 * last cycle read ('d2') in pit_expect_msb.
385 if (!pit_verify_msb(0xfe - i))
386 break;
387 goto success;
390 pr_info("Fast TSC calibration failed\n");
391 return 0;
393 success:
395 * Ok, if we get here, then we've seen the
396 * MSB of the PIT decrement 'i' times, and the
397 * error has shrunk to less than 500 ppm.
399 * As a result, we can depend on there not being
400 * any odd delays anywhere, and the TSC reads are
401 * reliable (within the error).
403 * kHz = ticks / time-in-seconds / 1000;
404 * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
405 * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
407 delta *= PIT_TICK_RATE;
408 do_div(delta, i*256*1000);
409 pr_info("Fast TSC calibration using PIT\n");
410 return delta;
414 * native_calibrate_tsc - calibrate the tsc on boot
416 unsigned long native_calibrate_tsc(void)
418 u64 tsc1, tsc2, delta, ref1, ref2;
419 unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
420 unsigned long flags, latch, ms, fast_calibrate;
421 int hpet = is_hpet_enabled(), i, loopmin;
423 local_irq_save(flags);
424 fast_calibrate = quick_pit_calibrate();
425 local_irq_restore(flags);
426 if (fast_calibrate)
427 return fast_calibrate;
430 * Run 5 calibration loops to get the lowest frequency value
431 * (the best estimate). We use two different calibration modes
432 * here:
434 * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
435 * load a timeout of 50ms. We read the time right after we
436 * started the timer and wait until the PIT count down reaches
437 * zero. In each wait loop iteration we read the TSC and check
438 * the delta to the previous read. We keep track of the min
439 * and max values of that delta. The delta is mostly defined
440 * by the IO time of the PIT access, so we can detect when a
441 * SMI/SMM disturbance happened between the two reads. If the
442 * maximum time is significantly larger than the minimum time,
443 * then we discard the result and have another try.
445 * 2) Reference counter. If available we use the HPET or the
446 * PMTIMER as a reference to check the sanity of that value.
447 * We use separate TSC readouts and check inside of the
448 * reference read for a SMI/SMM disturbance. We dicard
449 * disturbed values here as well. We do that around the PIT
450 * calibration delay loop as we have to wait for a certain
451 * amount of time anyway.
454 /* Preset PIT loop values */
455 latch = CAL_LATCH;
456 ms = CAL_MS;
457 loopmin = CAL_PIT_LOOPS;
459 for (i = 0; i < 3; i++) {
460 unsigned long tsc_pit_khz;
463 * Read the start value and the reference count of
464 * hpet/pmtimer when available. Then do the PIT
465 * calibration, which will take at least 50ms, and
466 * read the end value.
468 local_irq_save(flags);
469 tsc1 = tsc_read_refs(&ref1, hpet);
470 tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
471 tsc2 = tsc_read_refs(&ref2, hpet);
472 local_irq_restore(flags);
474 /* Pick the lowest PIT TSC calibration so far */
475 tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
477 /* hpet or pmtimer available ? */
478 if (ref1 == ref2)
479 continue;
481 /* Check, whether the sampling was disturbed by an SMI */
482 if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
483 continue;
485 tsc2 = (tsc2 - tsc1) * 1000000LL;
486 if (hpet)
487 tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
488 else
489 tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
491 tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
493 /* Check the reference deviation */
494 delta = ((u64) tsc_pit_min) * 100;
495 do_div(delta, tsc_ref_min);
498 * If both calibration results are inside a 10% window
499 * then we can be sure, that the calibration
500 * succeeded. We break out of the loop right away. We
501 * use the reference value, as it is more precise.
503 if (delta >= 90 && delta <= 110) {
504 pr_info("PIT calibration matches %s. %d loops\n",
505 hpet ? "HPET" : "PMTIMER", i + 1);
506 return tsc_ref_min;
510 * Check whether PIT failed more than once. This
511 * happens in virtualized environments. We need to
512 * give the virtual PC a slightly longer timeframe for
513 * the HPET/PMTIMER to make the result precise.
515 if (i == 1 && tsc_pit_min == ULONG_MAX) {
516 latch = CAL2_LATCH;
517 ms = CAL2_MS;
518 loopmin = CAL2_PIT_LOOPS;
523 * Now check the results.
525 if (tsc_pit_min == ULONG_MAX) {
526 /* PIT gave no useful value */
527 pr_warn("Unable to calibrate against PIT\n");
529 /* We don't have an alternative source, disable TSC */
530 if (!hpet && !ref1 && !ref2) {
531 pr_notice("No reference (HPET/PMTIMER) available\n");
532 return 0;
535 /* The alternative source failed as well, disable TSC */
536 if (tsc_ref_min == ULONG_MAX) {
537 pr_warn("HPET/PMTIMER calibration failed\n");
538 return 0;
541 /* Use the alternative source */
542 pr_info("using %s reference calibration\n",
543 hpet ? "HPET" : "PMTIMER");
545 return tsc_ref_min;
548 /* We don't have an alternative source, use the PIT calibration value */
549 if (!hpet && !ref1 && !ref2) {
550 pr_info("Using PIT calibration value\n");
551 return tsc_pit_min;
554 /* The alternative source failed, use the PIT calibration value */
555 if (tsc_ref_min == ULONG_MAX) {
556 pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
557 return tsc_pit_min;
561 * The calibration values differ too much. In doubt, we use
562 * the PIT value as we know that there are PMTIMERs around
563 * running at double speed. At least we let the user know:
565 pr_warn("PIT calibration deviates from %s: %lu %lu\n",
566 hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
567 pr_info("Using PIT calibration value\n");
568 return tsc_pit_min;
571 int recalibrate_cpu_khz(void)
573 #ifndef CONFIG_SMP
574 unsigned long cpu_khz_old = cpu_khz;
576 if (cpu_has_tsc) {
577 tsc_khz = x86_platform.calibrate_tsc();
578 cpu_khz = tsc_khz;
579 cpu_data(0).loops_per_jiffy =
580 cpufreq_scale(cpu_data(0).loops_per_jiffy,
581 cpu_khz_old, cpu_khz);
582 return 0;
583 } else
584 return -ENODEV;
585 #else
586 return -ENODEV;
587 #endif
590 EXPORT_SYMBOL(recalibrate_cpu_khz);
593 /* Accelerators for sched_clock()
594 * convert from cycles(64bits) => nanoseconds (64bits)
595 * basic equation:
596 * ns = cycles / (freq / ns_per_sec)
597 * ns = cycles * (ns_per_sec / freq)
598 * ns = cycles * (10^9 / (cpu_khz * 10^3))
599 * ns = cycles * (10^6 / cpu_khz)
601 * Then we use scaling math (suggested by george@mvista.com) to get:
602 * ns = cycles * (10^6 * SC / cpu_khz) / SC
603 * ns = cycles * cyc2ns_scale / SC
605 * And since SC is a constant power of two, we can convert the div
606 * into a shift.
608 * We can use khz divisor instead of mhz to keep a better precision, since
609 * cyc2ns_scale is limited to 10^6 * 2^10, which fits in 32 bits.
610 * (mathieu.desnoyers@polymtl.ca)
612 * -johnstul@us.ibm.com "math is hard, lets go shopping!"
615 DEFINE_PER_CPU(unsigned long, cyc2ns);
616 DEFINE_PER_CPU(unsigned long long, cyc2ns_offset);
618 static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
620 unsigned long long tsc_now, ns_now, *offset;
621 unsigned long flags, *scale;
623 local_irq_save(flags);
624 sched_clock_idle_sleep_event();
626 scale = &per_cpu(cyc2ns, cpu);
627 offset = &per_cpu(cyc2ns_offset, cpu);
629 rdtscll(tsc_now);
630 ns_now = __cycles_2_ns(tsc_now);
632 if (cpu_khz) {
633 *scale = ((NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR) +
634 cpu_khz / 2) / cpu_khz;
635 *offset = ns_now - mult_frac(tsc_now, *scale,
636 (1UL << CYC2NS_SCALE_FACTOR));
639 sched_clock_idle_wakeup_event(0);
640 local_irq_restore(flags);
643 static unsigned long long cyc2ns_suspend;
645 void tsc_save_sched_clock_state(void)
647 if (!sched_clock_stable)
648 return;
650 cyc2ns_suspend = sched_clock();
654 * Even on processors with invariant TSC, TSC gets reset in some the
655 * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
656 * arbitrary value (still sync'd across cpu's) during resume from such sleep
657 * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
658 * that sched_clock() continues from the point where it was left off during
659 * suspend.
661 void tsc_restore_sched_clock_state(void)
663 unsigned long long offset;
664 unsigned long flags;
665 int cpu;
667 if (!sched_clock_stable)
668 return;
670 local_irq_save(flags);
672 __this_cpu_write(cyc2ns_offset, 0);
673 offset = cyc2ns_suspend - sched_clock();
675 for_each_possible_cpu(cpu)
676 per_cpu(cyc2ns_offset, cpu) = offset;
678 local_irq_restore(flags);
681 #ifdef CONFIG_CPU_FREQ
683 /* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
684 * changes.
686 * RED-PEN: On SMP we assume all CPUs run with the same frequency. It's
687 * not that important because current Opteron setups do not support
688 * scaling on SMP anyroads.
690 * Should fix up last_tsc too. Currently gettimeofday in the
691 * first tick after the change will be slightly wrong.
694 static unsigned int ref_freq;
695 static unsigned long loops_per_jiffy_ref;
696 static unsigned long tsc_khz_ref;
698 static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
699 void *data)
701 struct cpufreq_freqs *freq = data;
702 unsigned long *lpj;
704 if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
705 return 0;
707 lpj = &boot_cpu_data.loops_per_jiffy;
708 #ifdef CONFIG_SMP
709 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
710 lpj = &cpu_data(freq->cpu).loops_per_jiffy;
711 #endif
713 if (!ref_freq) {
714 ref_freq = freq->old;
715 loops_per_jiffy_ref = *lpj;
716 tsc_khz_ref = tsc_khz;
718 if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
719 (val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
720 (val == CPUFREQ_RESUMECHANGE)) {
721 *lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
723 tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
724 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
725 mark_tsc_unstable("cpufreq changes");
728 set_cyc2ns_scale(tsc_khz, freq->cpu);
730 return 0;
733 static struct notifier_block time_cpufreq_notifier_block = {
734 .notifier_call = time_cpufreq_notifier
737 static int __init cpufreq_tsc(void)
739 if (!cpu_has_tsc)
740 return 0;
741 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
742 return 0;
743 cpufreq_register_notifier(&time_cpufreq_notifier_block,
744 CPUFREQ_TRANSITION_NOTIFIER);
745 return 0;
748 core_initcall(cpufreq_tsc);
750 #endif /* CONFIG_CPU_FREQ */
752 /* clocksource code */
754 static struct clocksource clocksource_tsc;
757 * We compare the TSC to the cycle_last value in the clocksource
758 * structure to avoid a nasty time-warp. This can be observed in a
759 * very small window right after one CPU updated cycle_last under
760 * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
761 * is smaller than the cycle_last reference value due to a TSC which
762 * is slighty behind. This delta is nowhere else observable, but in
763 * that case it results in a forward time jump in the range of hours
764 * due to the unsigned delta calculation of the time keeping core
765 * code, which is necessary to support wrapping clocksources like pm
766 * timer.
768 static cycle_t read_tsc(struct clocksource *cs)
770 cycle_t ret = (cycle_t)get_cycles();
772 return ret >= clocksource_tsc.cycle_last ?
773 ret : clocksource_tsc.cycle_last;
776 static void resume_tsc(struct clocksource *cs)
778 if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
779 clocksource_tsc.cycle_last = 0;
782 static struct clocksource clocksource_tsc = {
783 .name = "tsc",
784 .rating = 300,
785 .read = read_tsc,
786 .resume = resume_tsc,
787 .mask = CLOCKSOURCE_MASK(64),
788 .flags = CLOCK_SOURCE_IS_CONTINUOUS |
789 CLOCK_SOURCE_MUST_VERIFY,
790 #ifdef CONFIG_X86_64
791 .archdata = { .vclock_mode = VCLOCK_TSC },
792 #endif
795 void mark_tsc_unstable(char *reason)
797 if (!tsc_unstable) {
798 tsc_unstable = 1;
799 sched_clock_stable = 0;
800 disable_sched_clock_irqtime();
801 pr_info("Marking TSC unstable due to %s\n", reason);
802 /* Change only the rating, when not registered */
803 if (clocksource_tsc.mult)
804 clocksource_mark_unstable(&clocksource_tsc);
805 else {
806 clocksource_tsc.flags |= CLOCK_SOURCE_UNSTABLE;
807 clocksource_tsc.rating = 0;
812 EXPORT_SYMBOL_GPL(mark_tsc_unstable);
814 static void __init check_system_tsc_reliable(void)
816 #if defined(CONFIG_MGEODEGX1) || defined(CONFIG_MGEODE_LX) || defined(CONFIG_X86_GENERIC)
817 if (is_geode_lx()) {
818 /* RTSC counts during suspend */
819 #define RTSC_SUSP 0x100
820 unsigned long res_low, res_high;
822 rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
823 /* Geode_LX - the OLPC CPU has a very reliable TSC */
824 if (res_low & RTSC_SUSP)
825 tsc_clocksource_reliable = 1;
827 #endif
828 if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
829 tsc_clocksource_reliable = 1;
833 * Make an educated guess if the TSC is trustworthy and synchronized
834 * over all CPUs.
836 int unsynchronized_tsc(void)
838 if (!cpu_has_tsc || tsc_unstable)
839 return 1;
841 #ifdef CONFIG_SMP
842 if (apic_is_clustered_box())
843 return 1;
844 #endif
846 if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
847 return 0;
849 if (tsc_clocksource_reliable)
850 return 0;
852 * Intel systems are normally all synchronized.
853 * Exceptions must mark TSC as unstable:
855 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
856 /* assume multi socket systems are not synchronized: */
857 if (num_possible_cpus() > 1)
858 return 1;
861 return 0;
865 static void tsc_refine_calibration_work(struct work_struct *work);
866 static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
868 * tsc_refine_calibration_work - Further refine tsc freq calibration
869 * @work - ignored.
871 * This functions uses delayed work over a period of a
872 * second to further refine the TSC freq value. Since this is
873 * timer based, instead of loop based, we don't block the boot
874 * process while this longer calibration is done.
876 * If there are any calibration anomalies (too many SMIs, etc),
877 * or the refined calibration is off by 1% of the fast early
878 * calibration, we throw out the new calibration and use the
879 * early calibration.
881 static void tsc_refine_calibration_work(struct work_struct *work)
883 static u64 tsc_start = -1, ref_start;
884 static int hpet;
885 u64 tsc_stop, ref_stop, delta;
886 unsigned long freq;
888 /* Don't bother refining TSC on unstable systems */
889 if (check_tsc_unstable())
890 goto out;
893 * Since the work is started early in boot, we may be
894 * delayed the first time we expire. So set the workqueue
895 * again once we know timers are working.
897 if (tsc_start == -1) {
899 * Only set hpet once, to avoid mixing hardware
900 * if the hpet becomes enabled later.
902 hpet = is_hpet_enabled();
903 schedule_delayed_work(&tsc_irqwork, HZ);
904 tsc_start = tsc_read_refs(&ref_start, hpet);
905 return;
908 tsc_stop = tsc_read_refs(&ref_stop, hpet);
910 /* hpet or pmtimer available ? */
911 if (ref_start == ref_stop)
912 goto out;
914 /* Check, whether the sampling was disturbed by an SMI */
915 if (tsc_start == ULLONG_MAX || tsc_stop == ULLONG_MAX)
916 goto out;
918 delta = tsc_stop - tsc_start;
919 delta *= 1000000LL;
920 if (hpet)
921 freq = calc_hpet_ref(delta, ref_start, ref_stop);
922 else
923 freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
925 /* Make sure we're within 1% */
926 if (abs(tsc_khz - freq) > tsc_khz/100)
927 goto out;
929 tsc_khz = freq;
930 pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
931 (unsigned long)tsc_khz / 1000,
932 (unsigned long)tsc_khz % 1000);
934 out:
935 clocksource_register_khz(&clocksource_tsc, tsc_khz);
939 static int __init init_tsc_clocksource(void)
941 if (!cpu_has_tsc || tsc_disabled > 0 || !tsc_khz)
942 return 0;
944 if (tsc_clocksource_reliable)
945 clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
946 /* lower the rating if we already know its unstable: */
947 if (check_tsc_unstable()) {
948 clocksource_tsc.rating = 0;
949 clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
952 if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
953 clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
956 * Trust the results of the earlier calibration on systems
957 * exporting a reliable TSC.
959 if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE)) {
960 clocksource_register_khz(&clocksource_tsc, tsc_khz);
961 return 0;
964 schedule_delayed_work(&tsc_irqwork, 0);
965 return 0;
968 * We use device_initcall here, to ensure we run after the hpet
969 * is fully initialized, which may occur at fs_initcall time.
971 device_initcall(init_tsc_clocksource);
973 void __init tsc_init(void)
975 u64 lpj;
976 int cpu;
978 x86_init.timers.tsc_pre_init();
980 if (!cpu_has_tsc) {
981 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
982 return;
985 tsc_khz = x86_platform.calibrate_tsc();
986 cpu_khz = tsc_khz;
988 if (!tsc_khz) {
989 mark_tsc_unstable("could not calculate TSC khz");
990 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
991 return;
994 pr_info("Detected %lu.%03lu MHz processor\n",
995 (unsigned long)cpu_khz / 1000,
996 (unsigned long)cpu_khz % 1000);
999 * Secondary CPUs do not run through tsc_init(), so set up
1000 * all the scale factors for all CPUs, assuming the same
1001 * speed as the bootup CPU. (cpufreq notifiers will fix this
1002 * up if their speed diverges)
1004 for_each_possible_cpu(cpu)
1005 set_cyc2ns_scale(cpu_khz, cpu);
1007 if (tsc_disabled > 0)
1008 return;
1010 /* now allow native_sched_clock() to use rdtsc */
1011 tsc_disabled = 0;
1013 if (!no_sched_irq_time)
1014 enable_sched_clock_irqtime();
1016 lpj = ((u64)tsc_khz * 1000);
1017 do_div(lpj, HZ);
1018 lpj_fine = lpj;
1020 use_tsc_delay();
1022 if (unsynchronized_tsc())
1023 mark_tsc_unstable("TSCs unsynchronized");
1025 check_system_tsc_reliable();
1028 #ifdef CONFIG_SMP
1030 * If we have a constant TSC and are using the TSC for the delay loop,
1031 * we can skip clock calibration if another cpu in the same socket has already
1032 * been calibrated. This assumes that CONSTANT_TSC applies to all
1033 * cpus in the socket - this should be a safe assumption.
1035 unsigned long calibrate_delay_is_known(void)
1037 int i, cpu = smp_processor_id();
1039 if (!tsc_disabled && !cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC))
1040 return 0;
1042 for_each_online_cpu(i)
1043 if (cpu_data(i).phys_proc_id == cpu_data(cpu).phys_proc_id)
1044 return cpu_data(i).loops_per_jiffy;
1045 return 0;
1047 #endif