Inform TSC deadline clockevent device about recalibration
[kvmfornfv.git] / kernel / arch / x86 / kernel / tsc.c
1 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2
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>
14 #include <linux/static_key.h>
15
16 #include <asm/hpet.h>
17 #include <asm/timer.h>
18 #include <asm/vgtod.h>
19 #include <asm/time.h>
20 #include <asm/delay.h>
21 #include <asm/hypervisor.h>
22 #include <asm/nmi.h>
23 #include <asm/x86_init.h>
24 #include <asm/geode.h>
25 #include <asm/apic.h>
26
27 unsigned int __read_mostly cpu_khz;     /* TSC clocks / usec, not used here */
28 EXPORT_SYMBOL(cpu_khz);
29
30 unsigned int __read_mostly tsc_khz;
31 EXPORT_SYMBOL(tsc_khz);
32
33 /*
34  * TSC can be unstable due to cpufreq or due to unsynced TSCs
35  */
36 static int __read_mostly tsc_unstable;
37
38 /* native_sched_clock() is called before tsc_init(), so
39    we must start with the TSC soft disabled to prevent
40    erroneous rdtsc usage on !cpu_has_tsc processors */
41 static int __read_mostly tsc_disabled = -1;
42
43 static DEFINE_STATIC_KEY_FALSE(__use_tsc);
44
45 int tsc_clocksource_reliable;
46
47 /*
48  * Use a ring-buffer like data structure, where a writer advances the head by
49  * writing a new data entry and a reader advances the tail when it observes a
50  * new entry.
51  *
52  * Writers are made to wait on readers until there's space to write a new
53  * entry.
54  *
55  * This means that we can always use an {offset, mul} pair to compute a ns
56  * value that is 'roughly' in the right direction, even if we're writing a new
57  * {offset, mul} pair during the clock read.
58  *
59  * The down-side is that we can no longer guarantee strict monotonicity anymore
60  * (assuming the TSC was that to begin with), because while we compute the
61  * intersection point of the two clock slopes and make sure the time is
62  * continuous at the point of switching; we can no longer guarantee a reader is
63  * strictly before or after the switch point.
64  *
65  * It does mean a reader no longer needs to disable IRQs in order to avoid
66  * CPU-Freq updates messing with his times, and similarly an NMI reader will
67  * no longer run the risk of hitting half-written state.
68  */
69
70 struct cyc2ns {
71         struct cyc2ns_data data[2];     /*  0 + 2*24 = 48 */
72         struct cyc2ns_data *head;       /* 48 + 8    = 56 */
73         struct cyc2ns_data *tail;       /* 56 + 8    = 64 */
74 }; /* exactly fits one cacheline */
75
76 static DEFINE_PER_CPU_ALIGNED(struct cyc2ns, cyc2ns);
77
78 struct cyc2ns_data *cyc2ns_read_begin(void)
79 {
80         struct cyc2ns_data *head;
81
82         preempt_disable();
83
84         head = this_cpu_read(cyc2ns.head);
85         /*
86          * Ensure we observe the entry when we observe the pointer to it.
87          * matches the wmb from cyc2ns_write_end().
88          */
89         smp_read_barrier_depends();
90         head->__count++;
91         barrier();
92
93         return head;
94 }
95
96 void cyc2ns_read_end(struct cyc2ns_data *head)
97 {
98         barrier();
99         /*
100          * If we're the outer most nested read; update the tail pointer
101          * when we're done. This notifies possible pending writers
102          * that we've observed the head pointer and that the other
103          * entry is now free.
104          */
105         if (!--head->__count) {
106                 /*
107                  * x86-TSO does not reorder writes with older reads;
108                  * therefore once this write becomes visible to another
109                  * cpu, we must be finished reading the cyc2ns_data.
110                  *
111                  * matches with cyc2ns_write_begin().
112                  */
113                 this_cpu_write(cyc2ns.tail, head);
114         }
115         preempt_enable();
116 }
117
118 /*
119  * Begin writing a new @data entry for @cpu.
120  *
121  * Assumes some sort of write side lock; currently 'provided' by the assumption
122  * that cpufreq will call its notifiers sequentially.
123  */
124 static struct cyc2ns_data *cyc2ns_write_begin(int cpu)
125 {
126         struct cyc2ns *c2n = &per_cpu(cyc2ns, cpu);
127         struct cyc2ns_data *data = c2n->data;
128
129         if (data == c2n->head)
130                 data++;
131
132         /* XXX send an IPI to @cpu in order to guarantee a read? */
133
134         /*
135          * When we observe the tail write from cyc2ns_read_end(),
136          * the cpu must be done with that entry and its safe
137          * to start writing to it.
138          */
139         while (c2n->tail == data)
140                 cpu_relax();
141
142         return data;
143 }
144
145 static void cyc2ns_write_end(int cpu, struct cyc2ns_data *data)
146 {
147         struct cyc2ns *c2n = &per_cpu(cyc2ns, cpu);
148
149         /*
150          * Ensure the @data writes are visible before we publish the
151          * entry. Matches the data-depencency in cyc2ns_read_begin().
152          */
153         smp_wmb();
154
155         ACCESS_ONCE(c2n->head) = data;
156 }
157
158 /*
159  * Accelerators for sched_clock()
160  * convert from cycles(64bits) => nanoseconds (64bits)
161  *  basic equation:
162  *              ns = cycles / (freq / ns_per_sec)
163  *              ns = cycles * (ns_per_sec / freq)
164  *              ns = cycles * (10^9 / (cpu_khz * 10^3))
165  *              ns = cycles * (10^6 / cpu_khz)
166  *
167  *      Then we use scaling math (suggested by george@mvista.com) to get:
168  *              ns = cycles * (10^6 * SC / cpu_khz) / SC
169  *              ns = cycles * cyc2ns_scale / SC
170  *
171  *      And since SC is a constant power of two, we can convert the div
172  *  into a shift. The larger SC is, the more accurate the conversion, but
173  *  cyc2ns_scale needs to be a 32-bit value so that 32-bit multiplication
174  *  (64-bit result) can be used.
175  *
176  *  We can use khz divisor instead of mhz to keep a better precision.
177  *  (mathieu.desnoyers@polymtl.ca)
178  *
179  *                      -johnstul@us.ibm.com "math is hard, lets go shopping!"
180  */
181
182 static void cyc2ns_data_init(struct cyc2ns_data *data)
183 {
184         data->cyc2ns_mul = 0;
185         data->cyc2ns_shift = 0;
186         data->cyc2ns_offset = 0;
187         data->__count = 0;
188 }
189
190 static void cyc2ns_init(int cpu)
191 {
192         struct cyc2ns *c2n = &per_cpu(cyc2ns, cpu);
193
194         cyc2ns_data_init(&c2n->data[0]);
195         cyc2ns_data_init(&c2n->data[1]);
196
197         c2n->head = c2n->data;
198         c2n->tail = c2n->data;
199 }
200
201 static inline unsigned long long cycles_2_ns(unsigned long long cyc)
202 {
203         struct cyc2ns_data *data, *tail;
204         unsigned long long ns;
205
206         /*
207          * See cyc2ns_read_*() for details; replicated in order to avoid
208          * an extra few instructions that came with the abstraction.
209          * Notable, it allows us to only do the __count and tail update
210          * dance when its actually needed.
211          */
212
213         preempt_disable_notrace();
214         data = this_cpu_read(cyc2ns.head);
215         tail = this_cpu_read(cyc2ns.tail);
216
217         if (likely(data == tail)) {
218                 ns = data->cyc2ns_offset;
219                 ns += mul_u64_u32_shr(cyc, data->cyc2ns_mul, data->cyc2ns_shift);
220         } else {
221                 data->__count++;
222
223                 barrier();
224
225                 ns = data->cyc2ns_offset;
226                 ns += mul_u64_u32_shr(cyc, data->cyc2ns_mul, data->cyc2ns_shift);
227
228                 barrier();
229
230                 if (!--data->__count)
231                         this_cpu_write(cyc2ns.tail, data);
232         }
233         preempt_enable_notrace();
234
235         return ns;
236 }
237
238 static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
239 {
240         unsigned long long tsc_now, ns_now;
241         struct cyc2ns_data *data;
242         unsigned long flags;
243
244         local_irq_save(flags);
245         sched_clock_idle_sleep_event();
246
247         if (!cpu_khz)
248                 goto done;
249
250         data = cyc2ns_write_begin(cpu);
251
252         tsc_now = rdtsc();
253         ns_now = cycles_2_ns(tsc_now);
254
255         /*
256          * Compute a new multiplier as per the above comment and ensure our
257          * time function is continuous; see the comment near struct
258          * cyc2ns_data.
259          */
260         clocks_calc_mult_shift(&data->cyc2ns_mul, &data->cyc2ns_shift, cpu_khz,
261                                NSEC_PER_MSEC, 0);
262
263         /*
264          * cyc2ns_shift is exported via arch_perf_update_userpage() where it is
265          * not expected to be greater than 31 due to the original published
266          * conversion algorithm shifting a 32-bit value (now specifies a 64-bit
267          * value) - refer perf_event_mmap_page documentation in perf_event.h.
268          */
269         if (data->cyc2ns_shift == 32) {
270                 data->cyc2ns_shift = 31;
271                 data->cyc2ns_mul >>= 1;
272         }
273
274         data->cyc2ns_offset = ns_now -
275                 mul_u64_u32_shr(tsc_now, data->cyc2ns_mul, data->cyc2ns_shift);
276
277         cyc2ns_write_end(cpu, data);
278
279 done:
280         sched_clock_idle_wakeup_event(0);
281         local_irq_restore(flags);
282 }
283 /*
284  * Scheduler clock - returns current time in nanosec units.
285  */
286 u64 native_sched_clock(void)
287 {
288         if (static_branch_likely(&__use_tsc)) {
289                 u64 tsc_now = rdtsc();
290
291                 /* return the value in ns */
292                 return cycles_2_ns(tsc_now);
293         }
294
295         /*
296          * Fall back to jiffies if there's no TSC available:
297          * ( But note that we still use it if the TSC is marked
298          *   unstable. We do this because unlike Time Of Day,
299          *   the scheduler clock tolerates small errors and it's
300          *   very important for it to be as fast as the platform
301          *   can achieve it. )
302          */
303
304         /* No locking but a rare wrong value is not a big deal: */
305         return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
306 }
307
308 /*
309  * Generate a sched_clock if you already have a TSC value.
310  */
311 u64 native_sched_clock_from_tsc(u64 tsc)
312 {
313         return cycles_2_ns(tsc);
314 }
315
316 /* We need to define a real function for sched_clock, to override the
317    weak default version */
318 #ifdef CONFIG_PARAVIRT
319 unsigned long long sched_clock(void)
320 {
321         return paravirt_sched_clock();
322 }
323 #else
324 unsigned long long
325 sched_clock(void) __attribute__((alias("native_sched_clock")));
326 #endif
327
328 int check_tsc_unstable(void)
329 {
330         return tsc_unstable;
331 }
332 EXPORT_SYMBOL_GPL(check_tsc_unstable);
333
334 int check_tsc_disabled(void)
335 {
336         return tsc_disabled;
337 }
338 EXPORT_SYMBOL_GPL(check_tsc_disabled);
339
340 #ifdef CONFIG_X86_TSC
341 int __init notsc_setup(char *str)
342 {
343         pr_warn("Kernel compiled with CONFIG_X86_TSC, cannot disable TSC completely\n");
344         tsc_disabled = 1;
345         return 1;
346 }
347 #else
348 /*
349  * disable flag for tsc. Takes effect by clearing the TSC cpu flag
350  * in cpu/common.c
351  */
352 int __init notsc_setup(char *str)
353 {
354         setup_clear_cpu_cap(X86_FEATURE_TSC);
355         return 1;
356 }
357 #endif
358
359 __setup("notsc", notsc_setup);
360
361 static int no_sched_irq_time;
362
363 static int __init tsc_setup(char *str)
364 {
365         if (!strcmp(str, "reliable"))
366                 tsc_clocksource_reliable = 1;
367         if (!strncmp(str, "noirqtime", 9))
368                 no_sched_irq_time = 1;
369         return 1;
370 }
371
372 __setup("tsc=", tsc_setup);
373
374 #define MAX_RETRIES     5
375 #define SMI_TRESHOLD    50000
376
377 /*
378  * Read TSC and the reference counters. Take care of SMI disturbance
379  */
380 static u64 tsc_read_refs(u64 *p, int hpet)
381 {
382         u64 t1, t2;
383         int i;
384
385         for (i = 0; i < MAX_RETRIES; i++) {
386                 t1 = get_cycles();
387                 if (hpet)
388                         *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
389                 else
390                         *p = acpi_pm_read_early();
391                 t2 = get_cycles();
392                 if ((t2 - t1) < SMI_TRESHOLD)
393                         return t2;
394         }
395         return ULLONG_MAX;
396 }
397
398 /*
399  * Calculate the TSC frequency from HPET reference
400  */
401 static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
402 {
403         u64 tmp;
404
405         if (hpet2 < hpet1)
406                 hpet2 += 0x100000000ULL;
407         hpet2 -= hpet1;
408         tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
409         do_div(tmp, 1000000);
410         do_div(deltatsc, tmp);
411
412         return (unsigned long) deltatsc;
413 }
414
415 /*
416  * Calculate the TSC frequency from PMTimer reference
417  */
418 static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
419 {
420         u64 tmp;
421
422         if (!pm1 && !pm2)
423                 return ULONG_MAX;
424
425         if (pm2 < pm1)
426                 pm2 += (u64)ACPI_PM_OVRRUN;
427         pm2 -= pm1;
428         tmp = pm2 * 1000000000LL;
429         do_div(tmp, PMTMR_TICKS_PER_SEC);
430         do_div(deltatsc, tmp);
431
432         return (unsigned long) deltatsc;
433 }
434
435 #define CAL_MS          10
436 #define CAL_LATCH       (PIT_TICK_RATE / (1000 / CAL_MS))
437 #define CAL_PIT_LOOPS   1000
438
439 #define CAL2_MS         50
440 #define CAL2_LATCH      (PIT_TICK_RATE / (1000 / CAL2_MS))
441 #define CAL2_PIT_LOOPS  5000
442
443
444 /*
445  * Try to calibrate the TSC against the Programmable
446  * Interrupt Timer and return the frequency of the TSC
447  * in kHz.
448  *
449  * Return ULONG_MAX on failure to calibrate.
450  */
451 static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
452 {
453         u64 tsc, t1, t2, delta;
454         unsigned long tscmin, tscmax;
455         int pitcnt;
456
457         /* Set the Gate high, disable speaker */
458         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
459
460         /*
461          * Setup CTC channel 2* for mode 0, (interrupt on terminal
462          * count mode), binary count. Set the latch register to 50ms
463          * (LSB then MSB) to begin countdown.
464          */
465         outb(0xb0, 0x43);
466         outb(latch & 0xff, 0x42);
467         outb(latch >> 8, 0x42);
468
469         tsc = t1 = t2 = get_cycles();
470
471         pitcnt = 0;
472         tscmax = 0;
473         tscmin = ULONG_MAX;
474         while ((inb(0x61) & 0x20) == 0) {
475                 t2 = get_cycles();
476                 delta = t2 - tsc;
477                 tsc = t2;
478                 if ((unsigned long) delta < tscmin)
479                         tscmin = (unsigned int) delta;
480                 if ((unsigned long) delta > tscmax)
481                         tscmax = (unsigned int) delta;
482                 pitcnt++;
483         }
484
485         /*
486          * Sanity checks:
487          *
488          * If we were not able to read the PIT more than loopmin
489          * times, then we have been hit by a massive SMI
490          *
491          * If the maximum is 10 times larger than the minimum,
492          * then we got hit by an SMI as well.
493          */
494         if (pitcnt < loopmin || tscmax > 10 * tscmin)
495                 return ULONG_MAX;
496
497         /* Calculate the PIT value */
498         delta = t2 - t1;
499         do_div(delta, ms);
500         return delta;
501 }
502
503 /*
504  * This reads the current MSB of the PIT counter, and
505  * checks if we are running on sufficiently fast and
506  * non-virtualized hardware.
507  *
508  * Our expectations are:
509  *
510  *  - the PIT is running at roughly 1.19MHz
511  *
512  *  - each IO is going to take about 1us on real hardware,
513  *    but we allow it to be much faster (by a factor of 10) or
514  *    _slightly_ slower (ie we allow up to a 2us read+counter
515  *    update - anything else implies a unacceptably slow CPU
516  *    or PIT for the fast calibration to work.
517  *
518  *  - with 256 PIT ticks to read the value, we have 214us to
519  *    see the same MSB (and overhead like doing a single TSC
520  *    read per MSB value etc).
521  *
522  *  - We're doing 2 reads per loop (LSB, MSB), and we expect
523  *    them each to take about a microsecond on real hardware.
524  *    So we expect a count value of around 100. But we'll be
525  *    generous, and accept anything over 50.
526  *
527  *  - if the PIT is stuck, and we see *many* more reads, we
528  *    return early (and the next caller of pit_expect_msb()
529  *    then consider it a failure when they don't see the
530  *    next expected value).
531  *
532  * These expectations mean that we know that we have seen the
533  * transition from one expected value to another with a fairly
534  * high accuracy, and we didn't miss any events. We can thus
535  * use the TSC value at the transitions to calculate a pretty
536  * good value for the TSC frequencty.
537  */
538 static inline int pit_verify_msb(unsigned char val)
539 {
540         /* Ignore LSB */
541         inb(0x42);
542         return inb(0x42) == val;
543 }
544
545 static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
546 {
547         int count;
548         u64 tsc = 0, prev_tsc = 0;
549
550         for (count = 0; count < 50000; count++) {
551                 if (!pit_verify_msb(val))
552                         break;
553                 prev_tsc = tsc;
554                 tsc = get_cycles();
555         }
556         *deltap = get_cycles() - prev_tsc;
557         *tscp = tsc;
558
559         /*
560          * We require _some_ success, but the quality control
561          * will be based on the error terms on the TSC values.
562          */
563         return count > 5;
564 }
565
566 /*
567  * How many MSB values do we want to see? We aim for
568  * a maximum error rate of 500ppm (in practice the
569  * real error is much smaller), but refuse to spend
570  * more than 50ms on it.
571  */
572 #define MAX_QUICK_PIT_MS 50
573 #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
574
575 static unsigned long quick_pit_calibrate(void)
576 {
577         int i;
578         u64 tsc, delta;
579         unsigned long d1, d2;
580
581         /* Set the Gate high, disable speaker */
582         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
583
584         /*
585          * Counter 2, mode 0 (one-shot), binary count
586          *
587          * NOTE! Mode 2 decrements by two (and then the
588          * output is flipped each time, giving the same
589          * final output frequency as a decrement-by-one),
590          * so mode 0 is much better when looking at the
591          * individual counts.
592          */
593         outb(0xb0, 0x43);
594
595         /* Start at 0xffff */
596         outb(0xff, 0x42);
597         outb(0xff, 0x42);
598
599         /*
600          * The PIT starts counting at the next edge, so we
601          * need to delay for a microsecond. The easiest way
602          * to do that is to just read back the 16-bit counter
603          * once from the PIT.
604          */
605         pit_verify_msb(0);
606
607         if (pit_expect_msb(0xff, &tsc, &d1)) {
608                 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
609                         if (!pit_expect_msb(0xff-i, &delta, &d2))
610                                 break;
611
612                         delta -= tsc;
613
614                         /*
615                          * Extrapolate the error and fail fast if the error will
616                          * never be below 500 ppm.
617                          */
618                         if (i == 1 &&
619                             d1 + d2 >= (delta * MAX_QUICK_PIT_ITERATIONS) >> 11)
620                                 return 0;
621
622                         /*
623                          * Iterate until the error is less than 500 ppm
624                          */
625                         if (d1+d2 >= delta >> 11)
626                                 continue;
627
628                         /*
629                          * Check the PIT one more time to verify that
630                          * all TSC reads were stable wrt the PIT.
631                          *
632                          * This also guarantees serialization of the
633                          * last cycle read ('d2') in pit_expect_msb.
634                          */
635                         if (!pit_verify_msb(0xfe - i))
636                                 break;
637                         goto success;
638                 }
639         }
640         pr_info("Fast TSC calibration failed\n");
641         return 0;
642
643 success:
644         /*
645          * Ok, if we get here, then we've seen the
646          * MSB of the PIT decrement 'i' times, and the
647          * error has shrunk to less than 500 ppm.
648          *
649          * As a result, we can depend on there not being
650          * any odd delays anywhere, and the TSC reads are
651          * reliable (within the error).
652          *
653          * kHz = ticks / time-in-seconds / 1000;
654          * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
655          * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
656          */
657         delta *= PIT_TICK_RATE;
658         do_div(delta, i*256*1000);
659         pr_info("Fast TSC calibration using PIT\n");
660         return delta;
661 }
662
663 /**
664  * native_calibrate_tsc - calibrate the tsc on boot
665  */
666 unsigned long native_calibrate_tsc(void)
667 {
668         u64 tsc1, tsc2, delta, ref1, ref2;
669         unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
670         unsigned long flags, latch, ms, fast_calibrate;
671         int hpet = is_hpet_enabled(), i, loopmin;
672
673         /* Calibrate TSC using MSR for Intel Atom SoCs */
674         local_irq_save(flags);
675         fast_calibrate = try_msr_calibrate_tsc();
676         local_irq_restore(flags);
677         if (fast_calibrate)
678                 return fast_calibrate;
679
680         local_irq_save(flags);
681         fast_calibrate = quick_pit_calibrate();
682         local_irq_restore(flags);
683         if (fast_calibrate)
684                 return fast_calibrate;
685
686         /*
687          * Run 5 calibration loops to get the lowest frequency value
688          * (the best estimate). We use two different calibration modes
689          * here:
690          *
691          * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
692          * load a timeout of 50ms. We read the time right after we
693          * started the timer and wait until the PIT count down reaches
694          * zero. In each wait loop iteration we read the TSC and check
695          * the delta to the previous read. We keep track of the min
696          * and max values of that delta. The delta is mostly defined
697          * by the IO time of the PIT access, so we can detect when a
698          * SMI/SMM disturbance happened between the two reads. If the
699          * maximum time is significantly larger than the minimum time,
700          * then we discard the result and have another try.
701          *
702          * 2) Reference counter. If available we use the HPET or the
703          * PMTIMER as a reference to check the sanity of that value.
704          * We use separate TSC readouts and check inside of the
705          * reference read for a SMI/SMM disturbance. We dicard
706          * disturbed values here as well. We do that around the PIT
707          * calibration delay loop as we have to wait for a certain
708          * amount of time anyway.
709          */
710
711         /* Preset PIT loop values */
712         latch = CAL_LATCH;
713         ms = CAL_MS;
714         loopmin = CAL_PIT_LOOPS;
715
716         for (i = 0; i < 3; i++) {
717                 unsigned long tsc_pit_khz;
718
719                 /*
720                  * Read the start value and the reference count of
721                  * hpet/pmtimer when available. Then do the PIT
722                  * calibration, which will take at least 50ms, and
723                  * read the end value.
724                  */
725                 local_irq_save(flags);
726                 tsc1 = tsc_read_refs(&ref1, hpet);
727                 tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
728                 tsc2 = tsc_read_refs(&ref2, hpet);
729                 local_irq_restore(flags);
730
731                 /* Pick the lowest PIT TSC calibration so far */
732                 tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
733
734                 /* hpet or pmtimer available ? */
735                 if (ref1 == ref2)
736                         continue;
737
738                 /* Check, whether the sampling was disturbed by an SMI */
739                 if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
740                         continue;
741
742                 tsc2 = (tsc2 - tsc1) * 1000000LL;
743                 if (hpet)
744                         tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
745                 else
746                         tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
747
748                 tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
749
750                 /* Check the reference deviation */
751                 delta = ((u64) tsc_pit_min) * 100;
752                 do_div(delta, tsc_ref_min);
753
754                 /*
755                  * If both calibration results are inside a 10% window
756                  * then we can be sure, that the calibration
757                  * succeeded. We break out of the loop right away. We
758                  * use the reference value, as it is more precise.
759                  */
760                 if (delta >= 90 && delta <= 110) {
761                         pr_info("PIT calibration matches %s. %d loops\n",
762                                 hpet ? "HPET" : "PMTIMER", i + 1);
763                         return tsc_ref_min;
764                 }
765
766                 /*
767                  * Check whether PIT failed more than once. This
768                  * happens in virtualized environments. We need to
769                  * give the virtual PC a slightly longer timeframe for
770                  * the HPET/PMTIMER to make the result precise.
771                  */
772                 if (i == 1 && tsc_pit_min == ULONG_MAX) {
773                         latch = CAL2_LATCH;
774                         ms = CAL2_MS;
775                         loopmin = CAL2_PIT_LOOPS;
776                 }
777         }
778
779         /*
780          * Now check the results.
781          */
782         if (tsc_pit_min == ULONG_MAX) {
783                 /* PIT gave no useful value */
784                 pr_warn("Unable to calibrate against PIT\n");
785
786                 /* We don't have an alternative source, disable TSC */
787                 if (!hpet && !ref1 && !ref2) {
788                         pr_notice("No reference (HPET/PMTIMER) available\n");
789                         return 0;
790                 }
791
792                 /* The alternative source failed as well, disable TSC */
793                 if (tsc_ref_min == ULONG_MAX) {
794                         pr_warn("HPET/PMTIMER calibration failed\n");
795                         return 0;
796                 }
797
798                 /* Use the alternative source */
799                 pr_info("using %s reference calibration\n",
800                         hpet ? "HPET" : "PMTIMER");
801
802                 return tsc_ref_min;
803         }
804
805         /* We don't have an alternative source, use the PIT calibration value */
806         if (!hpet && !ref1 && !ref2) {
807                 pr_info("Using PIT calibration value\n");
808                 return tsc_pit_min;
809         }
810
811         /* The alternative source failed, use the PIT calibration value */
812         if (tsc_ref_min == ULONG_MAX) {
813                 pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
814                 return tsc_pit_min;
815         }
816
817         /*
818          * The calibration values differ too much. In doubt, we use
819          * the PIT value as we know that there are PMTIMERs around
820          * running at double speed. At least we let the user know:
821          */
822         pr_warn("PIT calibration deviates from %s: %lu %lu\n",
823                 hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
824         pr_info("Using PIT calibration value\n");
825         return tsc_pit_min;
826 }
827
828 int recalibrate_cpu_khz(void)
829 {
830 #ifndef CONFIG_SMP
831         unsigned long cpu_khz_old = cpu_khz;
832
833         if (cpu_has_tsc) {
834                 tsc_khz = x86_platform.calibrate_tsc();
835                 cpu_khz = tsc_khz;
836                 cpu_data(0).loops_per_jiffy =
837                         cpufreq_scale(cpu_data(0).loops_per_jiffy,
838                                         cpu_khz_old, cpu_khz);
839                 return 0;
840         } else
841                 return -ENODEV;
842 #else
843         return -ENODEV;
844 #endif
845 }
846
847 EXPORT_SYMBOL(recalibrate_cpu_khz);
848
849
850 static unsigned long long cyc2ns_suspend;
851
852 void tsc_save_sched_clock_state(void)
853 {
854         if (!sched_clock_stable())
855                 return;
856
857         cyc2ns_suspend = sched_clock();
858 }
859
860 /*
861  * Even on processors with invariant TSC, TSC gets reset in some the
862  * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
863  * arbitrary value (still sync'd across cpu's) during resume from such sleep
864  * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
865  * that sched_clock() continues from the point where it was left off during
866  * suspend.
867  */
868 void tsc_restore_sched_clock_state(void)
869 {
870         unsigned long long offset;
871         unsigned long flags;
872         int cpu;
873
874         if (!sched_clock_stable())
875                 return;
876
877         local_irq_save(flags);
878
879         /*
880          * We're comming out of suspend, there's no concurrency yet; don't
881          * bother being nice about the RCU stuff, just write to both
882          * data fields.
883          */
884
885         this_cpu_write(cyc2ns.data[0].cyc2ns_offset, 0);
886         this_cpu_write(cyc2ns.data[1].cyc2ns_offset, 0);
887
888         offset = cyc2ns_suspend - sched_clock();
889
890         for_each_possible_cpu(cpu) {
891                 per_cpu(cyc2ns.data[0].cyc2ns_offset, cpu) = offset;
892                 per_cpu(cyc2ns.data[1].cyc2ns_offset, cpu) = offset;
893         }
894
895         local_irq_restore(flags);
896 }
897
898 #ifdef CONFIG_CPU_FREQ
899
900 /* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
901  * changes.
902  *
903  * RED-PEN: On SMP we assume all CPUs run with the same frequency.  It's
904  * not that important because current Opteron setups do not support
905  * scaling on SMP anyroads.
906  *
907  * Should fix up last_tsc too. Currently gettimeofday in the
908  * first tick after the change will be slightly wrong.
909  */
910
911 static unsigned int  ref_freq;
912 static unsigned long loops_per_jiffy_ref;
913 static unsigned long tsc_khz_ref;
914
915 static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
916                                 void *data)
917 {
918         struct cpufreq_freqs *freq = data;
919         unsigned long *lpj;
920
921         if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
922                 return 0;
923
924         lpj = &boot_cpu_data.loops_per_jiffy;
925 #ifdef CONFIG_SMP
926         if (!(freq->flags & CPUFREQ_CONST_LOOPS))
927                 lpj = &cpu_data(freq->cpu).loops_per_jiffy;
928 #endif
929
930         if (!ref_freq) {
931                 ref_freq = freq->old;
932                 loops_per_jiffy_ref = *lpj;
933                 tsc_khz_ref = tsc_khz;
934         }
935         if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
936                         (val == CPUFREQ_POSTCHANGE && freq->old > freq->new)) {
937                 *lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
938
939                 tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
940                 if (!(freq->flags & CPUFREQ_CONST_LOOPS))
941                         mark_tsc_unstable("cpufreq changes");
942
943                 set_cyc2ns_scale(tsc_khz, freq->cpu);
944         }
945
946         return 0;
947 }
948
949 static struct notifier_block time_cpufreq_notifier_block = {
950         .notifier_call  = time_cpufreq_notifier
951 };
952
953 static int __init cpufreq_tsc(void)
954 {
955         if (!cpu_has_tsc)
956                 return 0;
957         if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
958                 return 0;
959         cpufreq_register_notifier(&time_cpufreq_notifier_block,
960                                 CPUFREQ_TRANSITION_NOTIFIER);
961         return 0;
962 }
963
964 core_initcall(cpufreq_tsc);
965
966 #endif /* CONFIG_CPU_FREQ */
967
968 /* clocksource code */
969
970 static struct clocksource clocksource_tsc;
971
972 /*
973  * We used to compare the TSC to the cycle_last value in the clocksource
974  * structure to avoid a nasty time-warp. This can be observed in a
975  * very small window right after one CPU updated cycle_last under
976  * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
977  * is smaller than the cycle_last reference value due to a TSC which
978  * is slighty behind. This delta is nowhere else observable, but in
979  * that case it results in a forward time jump in the range of hours
980  * due to the unsigned delta calculation of the time keeping core
981  * code, which is necessary to support wrapping clocksources like pm
982  * timer.
983  *
984  * This sanity check is now done in the core timekeeping code.
985  * checking the result of read_tsc() - cycle_last for being negative.
986  * That works because CLOCKSOURCE_MASK(64) does not mask out any bit.
987  */
988 static cycle_t read_tsc(struct clocksource *cs)
989 {
990         return (cycle_t)rdtsc_ordered();
991 }
992
993 /*
994  * .mask MUST be CLOCKSOURCE_MASK(64). See comment above read_tsc()
995  */
996 static struct clocksource clocksource_tsc = {
997         .name                   = "tsc",
998         .rating                 = 300,
999         .read                   = read_tsc,
1000         .mask                   = CLOCKSOURCE_MASK(64),
1001         .flags                  = CLOCK_SOURCE_IS_CONTINUOUS |
1002                                   CLOCK_SOURCE_MUST_VERIFY,
1003         .archdata               = { .vclock_mode = VCLOCK_TSC },
1004 };
1005
1006 void mark_tsc_unstable(char *reason)
1007 {
1008         if (!tsc_unstable) {
1009                 tsc_unstable = 1;
1010                 clear_sched_clock_stable();
1011                 disable_sched_clock_irqtime();
1012                 pr_info("Marking TSC unstable due to %s\n", reason);
1013                 /* Change only the rating, when not registered */
1014                 if (clocksource_tsc.mult)
1015                         clocksource_mark_unstable(&clocksource_tsc);
1016                 else {
1017                         clocksource_tsc.flags |= CLOCK_SOURCE_UNSTABLE;
1018                         clocksource_tsc.rating = 0;
1019                 }
1020         }
1021 }
1022
1023 EXPORT_SYMBOL_GPL(mark_tsc_unstable);
1024
1025 static void __init check_system_tsc_reliable(void)
1026 {
1027 #if defined(CONFIG_MGEODEGX1) || defined(CONFIG_MGEODE_LX) || defined(CONFIG_X86_GENERIC)
1028         if (is_geode_lx()) {
1029                 /* RTSC counts during suspend */
1030 #define RTSC_SUSP 0x100
1031                 unsigned long res_low, res_high;
1032
1033                 rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
1034                 /* Geode_LX - the OLPC CPU has a very reliable TSC */
1035                 if (res_low & RTSC_SUSP)
1036                         tsc_clocksource_reliable = 1;
1037         }
1038 #endif
1039         if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
1040                 tsc_clocksource_reliable = 1;
1041 }
1042
1043 /*
1044  * Make an educated guess if the TSC is trustworthy and synchronized
1045  * over all CPUs.
1046  */
1047 int unsynchronized_tsc(void)
1048 {
1049         if (!cpu_has_tsc || tsc_unstable)
1050                 return 1;
1051
1052 #ifdef CONFIG_SMP
1053         if (apic_is_clustered_box())
1054                 return 1;
1055 #endif
1056
1057         if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1058                 return 0;
1059
1060         if (tsc_clocksource_reliable)
1061                 return 0;
1062         /*
1063          * Intel systems are normally all synchronized.
1064          * Exceptions must mark TSC as unstable:
1065          */
1066         if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
1067                 /* assume multi socket systems are not synchronized: */
1068                 if (num_possible_cpus() > 1)
1069                         return 1;
1070         }
1071
1072         return 0;
1073 }
1074
1075
1076 static void tsc_refine_calibration_work(struct work_struct *work);
1077 static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
1078 /**
1079  * tsc_refine_calibration_work - Further refine tsc freq calibration
1080  * @work - ignored.
1081  *
1082  * This functions uses delayed work over a period of a
1083  * second to further refine the TSC freq value. Since this is
1084  * timer based, instead of loop based, we don't block the boot
1085  * process while this longer calibration is done.
1086  *
1087  * If there are any calibration anomalies (too many SMIs, etc),
1088  * or the refined calibration is off by 1% of the fast early
1089  * calibration, we throw out the new calibration and use the
1090  * early calibration.
1091  */
1092 static void tsc_refine_calibration_work(struct work_struct *work)
1093 {
1094         static u64 tsc_start = -1, ref_start;
1095         static int hpet;
1096         u64 tsc_stop, ref_stop, delta;
1097         unsigned long freq;
1098
1099         /* Don't bother refining TSC on unstable systems */
1100         if (check_tsc_unstable())
1101                 goto out;
1102
1103         /*
1104          * Since the work is started early in boot, we may be
1105          * delayed the first time we expire. So set the workqueue
1106          * again once we know timers are working.
1107          */
1108         if (tsc_start == -1) {
1109                 /*
1110                  * Only set hpet once, to avoid mixing hardware
1111                  * if the hpet becomes enabled later.
1112                  */
1113                 hpet = is_hpet_enabled();
1114                 schedule_delayed_work(&tsc_irqwork, HZ);
1115                 tsc_start = tsc_read_refs(&ref_start, hpet);
1116                 return;
1117         }
1118
1119         tsc_stop = tsc_read_refs(&ref_stop, hpet);
1120
1121         /* hpet or pmtimer available ? */
1122         if (ref_start == ref_stop)
1123                 goto out;
1124
1125         /* Check, whether the sampling was disturbed by an SMI */
1126         if (tsc_start == ULLONG_MAX || tsc_stop == ULLONG_MAX)
1127                 goto out;
1128
1129         delta = tsc_stop - tsc_start;
1130         delta *= 1000000LL;
1131         if (hpet)
1132                 freq = calc_hpet_ref(delta, ref_start, ref_stop);
1133         else
1134                 freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
1135
1136         /* Make sure we're within 1% */
1137         if (abs(tsc_khz - freq) > tsc_khz/100)
1138                 goto out;
1139
1140         tsc_khz = freq;
1141         pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
1142                 (unsigned long)tsc_khz / 1000,
1143                 (unsigned long)tsc_khz % 1000);
1144
1145         /* Inform the TSC deadline clockevent devices about the recalibration */
1146         lapic_update_tsc_freq();
1147
1148 out:
1149         clocksource_register_khz(&clocksource_tsc, tsc_khz);
1150 }
1151
1152
1153 static int __init init_tsc_clocksource(void)
1154 {
1155         if (!cpu_has_tsc || tsc_disabled > 0 || !tsc_khz)
1156                 return 0;
1157
1158         if (tsc_clocksource_reliable)
1159                 clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
1160         /* lower the rating if we already know its unstable: */
1161         if (check_tsc_unstable()) {
1162                 clocksource_tsc.rating = 0;
1163                 clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
1164         }
1165
1166         if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
1167                 clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
1168
1169         /*
1170          * Trust the results of the earlier calibration on systems
1171          * exporting a reliable TSC.
1172          */
1173         if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE)) {
1174                 clocksource_register_khz(&clocksource_tsc, tsc_khz);
1175                 return 0;
1176         }
1177
1178         schedule_delayed_work(&tsc_irqwork, 0);
1179         return 0;
1180 }
1181 /*
1182  * We use device_initcall here, to ensure we run after the hpet
1183  * is fully initialized, which may occur at fs_initcall time.
1184  */
1185 device_initcall(init_tsc_clocksource);
1186
1187 void __init tsc_init(void)
1188 {
1189         u64 lpj;
1190         int cpu;
1191
1192         x86_init.timers.tsc_pre_init();
1193
1194         if (!cpu_has_tsc) {
1195                 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
1196                 return;
1197         }
1198
1199         tsc_khz = x86_platform.calibrate_tsc();
1200         cpu_khz = tsc_khz;
1201
1202         if (!tsc_khz) {
1203                 mark_tsc_unstable("could not calculate TSC khz");
1204                 setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
1205                 return;
1206         }
1207
1208         pr_info("Detected %lu.%03lu MHz processor\n",
1209                 (unsigned long)cpu_khz / 1000,
1210                 (unsigned long)cpu_khz % 1000);
1211
1212         /*
1213          * Secondary CPUs do not run through tsc_init(), so set up
1214          * all the scale factors for all CPUs, assuming the same
1215          * speed as the bootup CPU. (cpufreq notifiers will fix this
1216          * up if their speed diverges)
1217          */
1218         for_each_possible_cpu(cpu) {
1219                 cyc2ns_init(cpu);
1220                 set_cyc2ns_scale(cpu_khz, cpu);
1221         }
1222
1223         if (tsc_disabled > 0)
1224                 return;
1225
1226         /* now allow native_sched_clock() to use rdtsc */
1227
1228         tsc_disabled = 0;
1229         static_branch_enable(&__use_tsc);
1230
1231         if (!no_sched_irq_time)
1232                 enable_sched_clock_irqtime();
1233
1234         lpj = ((u64)tsc_khz * 1000);
1235         do_div(lpj, HZ);
1236         lpj_fine = lpj;
1237
1238         use_tsc_delay();
1239
1240         if (unsynchronized_tsc())
1241                 mark_tsc_unstable("TSCs unsynchronized");
1242
1243         check_system_tsc_reliable();
1244 }
1245
1246 #ifdef CONFIG_SMP
1247 /*
1248  * If we have a constant TSC and are using the TSC for the delay loop,
1249  * we can skip clock calibration if another cpu in the same socket has already
1250  * been calibrated. This assumes that CONSTANT_TSC applies to all
1251  * cpus in the socket - this should be a safe assumption.
1252  */
1253 unsigned long calibrate_delay_is_known(void)
1254 {
1255         int i, cpu = smp_processor_id();
1256
1257         if (!tsc_disabled && !cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC))
1258                 return 0;
1259
1260         for_each_online_cpu(i)
1261                 if (cpu_data(i).phys_proc_id == cpu_data(cpu).phys_proc_id)
1262                         return cpu_data(i).loops_per_jiffy;
1263         return 0;
1264 }
1265 #endif