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