890660b44a94c505455fb71ee6eee203dd7ccb7f
[oweals/u-boot.git] / drivers / timer / tsc_timer.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2012 The Chromium OS Authors.
4  *
5  * TSC calibration codes are adapted from Linux kernel
6  * arch/x86/kernel/tsc_msr.c and arch/x86/kernel/tsc.c
7  */
8
9 #include <common.h>
10 #include <bootstage.h>
11 #include <dm.h>
12 #include <log.h>
13 #include <malloc.h>
14 #include <time.h>
15 #include <timer.h>
16 #include <asm/cpu.h>
17 #include <asm/io.h>
18 #include <asm/i8254.h>
19 #include <asm/ibmpc.h>
20 #include <asm/msr.h>
21 #include <asm/u-boot-x86.h>
22
23 #define MAX_NUM_FREQS   9
24
25 #define INTEL_FAM6_SKYLAKE_MOBILE       0x4E
26 #define INTEL_FAM6_ATOM_GOLDMONT        0x5C /* Apollo Lake */
27 #define INTEL_FAM6_SKYLAKE_DESKTOP      0x5E
28 #define INTEL_FAM6_ATOM_GOLDMONT_X      0x5F /* Denverton */
29 #define INTEL_FAM6_KABYLAKE_MOBILE      0x8E
30 #define INTEL_FAM6_KABYLAKE_DESKTOP     0x9E
31
32 DECLARE_GLOBAL_DATA_PTR;
33
34 /*
35  * native_calibrate_tsc
36  * Determine TSC frequency via CPUID, else return 0.
37  */
38 static unsigned long native_calibrate_tsc(void)
39 {
40         struct cpuid_result tsc_info;
41         unsigned int crystal_freq;
42
43         if (gd->arch.x86_vendor != X86_VENDOR_INTEL)
44                 return 0;
45
46         if (cpuid_eax(0) < 0x15)
47                 return 0;
48
49         tsc_info = cpuid(0x15);
50
51         if (tsc_info.ebx == 0 || tsc_info.eax == 0)
52                 return 0;
53
54         crystal_freq = tsc_info.ecx / 1000;
55         if (!CONFIG_IS_ENABLED(X86_TSC_TIMER_NATIVE) && !crystal_freq) {
56                 switch (gd->arch.x86_model) {
57                 case INTEL_FAM6_SKYLAKE_MOBILE:
58                 case INTEL_FAM6_SKYLAKE_DESKTOP:
59                 case INTEL_FAM6_KABYLAKE_MOBILE:
60                 case INTEL_FAM6_KABYLAKE_DESKTOP:
61                         crystal_freq = 24000;   /* 24.0 MHz */
62                         break;
63                 case INTEL_FAM6_ATOM_GOLDMONT_X:
64                         crystal_freq = 25000;   /* 25.0 MHz */
65                         break;
66                 case INTEL_FAM6_ATOM_GOLDMONT:
67                         crystal_freq = 19200;   /* 19.2 MHz */
68                         break;
69                 default:
70                         return 0;
71                 }
72         }
73
74         return (crystal_freq * tsc_info.ebx / tsc_info.eax) / 1000;
75 }
76
77 static unsigned long cpu_mhz_from_cpuid(void)
78 {
79         if (gd->arch.x86_vendor != X86_VENDOR_INTEL)
80                 return 0;
81
82         if (cpuid_eax(0) < 0x16)
83                 return 0;
84
85         return cpuid_eax(0x16);
86 }
87
88 /*
89  * According to Intel 64 and IA-32 System Programming Guide,
90  * if MSR_PERF_STAT[31] is set, the maximum resolved bus ratio can be
91  * read in MSR_PLATFORM_ID[12:8], otherwise in MSR_PERF_STAT[44:40].
92  * Unfortunately some Intel Atom SoCs aren't quite compliant to this,
93  * so we need manually differentiate SoC families. This is what the
94  * field msr_plat does.
95  */
96 struct freq_desc {
97         u8 x86_family;  /* CPU family */
98         u8 x86_model;   /* model */
99         /* 2: use 100MHz, 1: use MSR_PLATFORM_INFO, 0: MSR_IA32_PERF_STATUS */
100         u8 msr_plat;
101         u32 freqs[MAX_NUM_FREQS];
102 };
103
104 static struct freq_desc freq_desc_tables[] = {
105         /* PNW */
106         { 6, 0x27, 0, { 0, 0, 0, 0, 0, 99840, 0, 83200, 0 } },
107         /* CLV+ */
108         { 6, 0x35, 0, { 0, 133200, 0, 0, 0, 99840, 0, 83200, 0 } },
109         /* TNG - Intel Atom processor Z3400 series */
110         { 6, 0x4a, 1, { 0, 100000, 133300, 0, 0, 0, 0, 0, 0 } },
111         /* VLV2 - Intel Atom processor E3000, Z3600, Z3700 series */
112         { 6, 0x37, 1, { 83300, 100000, 133300, 116700, 80000, 0, 0, 0, 0 } },
113         /* ANN - Intel Atom processor Z3500 series */
114         { 6, 0x5a, 1, { 83300, 100000, 133300, 100000, 0, 0, 0, 0, 0 } },
115         /* AMT - Intel Atom processor X7-Z8000 and X5-Z8000 series */
116         { 6, 0x4c, 1, { 83300, 100000, 133300, 116700,
117                         80000, 93300, 90000, 88900, 87500 } },
118         /* Ivybridge */
119         { 6, 0x3a, 2, { 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
120 };
121
122 static int match_cpu(u8 family, u8 model)
123 {
124         int i;
125
126         for (i = 0; i < ARRAY_SIZE(freq_desc_tables); i++) {
127                 if ((family == freq_desc_tables[i].x86_family) &&
128                     (model == freq_desc_tables[i].x86_model))
129                         return i;
130         }
131
132         return -1;
133 }
134
135 /* Map CPU reference clock freq ID(0-7) to CPU reference clock freq(KHz) */
136 #define id_to_freq(cpu_index, freq_id) \
137         (freq_desc_tables[cpu_index].freqs[freq_id])
138
139 /*
140  * TSC on Intel Atom SoCs capable of determining TSC frequency by MSR is
141  * reliable and the frequency is known (provided by HW).
142  *
143  * On these platforms PIT/HPET is generally not available so calibration won't
144  * work at all and there is no other clocksource to act as a watchdog for the
145  * TSC, so we have no other choice than to trust it.
146  *
147  * Returns the TSC frequency in MHz or 0 if HW does not provide it.
148  */
149 static unsigned long __maybe_unused cpu_mhz_from_msr(void)
150 {
151         u32 lo, hi, ratio, freq_id, freq;
152         unsigned long res;
153         int cpu_index;
154
155         if (gd->arch.x86_vendor != X86_VENDOR_INTEL)
156                 return 0;
157
158         cpu_index = match_cpu(gd->arch.x86, gd->arch.x86_model);
159         if (cpu_index < 0)
160                 return 0;
161
162         if (freq_desc_tables[cpu_index].msr_plat) {
163                 rdmsr(MSR_PLATFORM_INFO, lo, hi);
164                 ratio = (lo >> 8) & 0xff;
165         } else {
166                 rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
167                 ratio = (hi >> 8) & 0x1f;
168         }
169         debug("Maximum core-clock to bus-clock ratio: 0x%x\n", ratio);
170
171         if (freq_desc_tables[cpu_index].msr_plat == 2) {
172                 /* TODO: Figure out how best to deal with this */
173                 freq = 100000;
174                 debug("Using frequency: %u KHz\n", freq);
175         } else {
176                 /* Get FSB FREQ ID */
177                 rdmsr(MSR_FSB_FREQ, lo, hi);
178                 freq_id = lo & 0x7;
179                 freq = id_to_freq(cpu_index, freq_id);
180                 debug("Resolved frequency ID: %u, frequency: %u KHz\n",
181                       freq_id, freq);
182         }
183
184         /* TSC frequency = maximum resolved freq * maximum resolved bus ratio */
185         res = freq * ratio / 1000;
186         debug("TSC runs at %lu MHz\n", res);
187
188         return res;
189 }
190
191 /*
192  * This reads the current MSB of the PIT counter, and
193  * checks if we are running on sufficiently fast and
194  * non-virtualized hardware.
195  *
196  * Our expectations are:
197  *
198  *  - the PIT is running at roughly 1.19MHz
199  *
200  *  - each IO is going to take about 1us on real hardware,
201  *    but we allow it to be much faster (by a factor of 10) or
202  *    _slightly_ slower (ie we allow up to a 2us read+counter
203  *    update - anything else implies a unacceptably slow CPU
204  *    or PIT for the fast calibration to work.
205  *
206  *  - with 256 PIT ticks to read the value, we have 214us to
207  *    see the same MSB (and overhead like doing a single TSC
208  *    read per MSB value etc).
209  *
210  *  - We're doing 2 reads per loop (LSB, MSB), and we expect
211  *    them each to take about a microsecond on real hardware.
212  *    So we expect a count value of around 100. But we'll be
213  *    generous, and accept anything over 50.
214  *
215  *  - if the PIT is stuck, and we see *many* more reads, we
216  *    return early (and the next caller of pit_expect_msb()
217  *    then consider it a failure when they don't see the
218  *    next expected value).
219  *
220  * These expectations mean that we know that we have seen the
221  * transition from one expected value to another with a fairly
222  * high accuracy, and we didn't miss any events. We can thus
223  * use the TSC value at the transitions to calculate a pretty
224  * good value for the TSC frequencty.
225  */
226 static inline int pit_verify_msb(unsigned char val)
227 {
228         /* Ignore LSB */
229         inb(0x42);
230         return inb(0x42) == val;
231 }
232
233 static inline int pit_expect_msb(unsigned char val, u64 *tscp,
234                                  unsigned long *deltap)
235 {
236         int count;
237         u64 tsc = 0, prev_tsc = 0;
238
239         for (count = 0; count < 50000; count++) {
240                 if (!pit_verify_msb(val))
241                         break;
242                 prev_tsc = tsc;
243                 tsc = rdtsc();
244         }
245         *deltap = rdtsc() - prev_tsc;
246         *tscp = tsc;
247
248         /*
249          * We require _some_ success, but the quality control
250          * will be based on the error terms on the TSC values.
251          */
252         return count > 5;
253 }
254
255 /*
256  * How many MSB values do we want to see? We aim for
257  * a maximum error rate of 500ppm (in practice the
258  * real error is much smaller), but refuse to spend
259  * more than 50ms on it.
260  */
261 #define MAX_QUICK_PIT_MS 50
262 #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
263
264 static unsigned long __maybe_unused quick_pit_calibrate(void)
265 {
266         int i;
267         u64 tsc, delta;
268         unsigned long d1, d2;
269
270         /* Set the Gate high, disable speaker */
271         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
272
273         /*
274          * Counter 2, mode 0 (one-shot), binary count
275          *
276          * NOTE! Mode 2 decrements by two (and then the
277          * output is flipped each time, giving the same
278          * final output frequency as a decrement-by-one),
279          * so mode 0 is much better when looking at the
280          * individual counts.
281          */
282         outb(0xb0, 0x43);
283
284         /* Start at 0xffff */
285         outb(0xff, 0x42);
286         outb(0xff, 0x42);
287
288         /*
289          * The PIT starts counting at the next edge, so we
290          * need to delay for a microsecond. The easiest way
291          * to do that is to just read back the 16-bit counter
292          * once from the PIT.
293          */
294         pit_verify_msb(0);
295
296         if (pit_expect_msb(0xff, &tsc, &d1)) {
297                 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
298                         if (!pit_expect_msb(0xff-i, &delta, &d2))
299                                 break;
300
301                         /*
302                          * Iterate until the error is less than 500 ppm
303                          */
304                         delta -= tsc;
305                         if (d1+d2 >= delta >> 11)
306                                 continue;
307
308                         /*
309                          * Check the PIT one more time to verify that
310                          * all TSC reads were stable wrt the PIT.
311                          *
312                          * This also guarantees serialization of the
313                          * last cycle read ('d2') in pit_expect_msb.
314                          */
315                         if (!pit_verify_msb(0xfe - i))
316                                 break;
317                         goto success;
318                 }
319         }
320         debug("Fast TSC calibration failed\n");
321         return 0;
322
323 success:
324         /*
325          * Ok, if we get here, then we've seen the
326          * MSB of the PIT decrement 'i' times, and the
327          * error has shrunk to less than 500 ppm.
328          *
329          * As a result, we can depend on there not being
330          * any odd delays anywhere, and the TSC reads are
331          * reliable (within the error).
332          *
333          * kHz = ticks / time-in-seconds / 1000;
334          * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
335          * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
336          */
337         delta *= PIT_TICK_RATE;
338         delta /= (i*256*1000);
339         debug("Fast TSC calibration using PIT\n");
340         return delta / 1000;
341 }
342
343 /* Get the speed of the TSC timer in MHz */
344 unsigned notrace long get_tbclk_mhz(void)
345 {
346         return get_tbclk() / 1000000;
347 }
348
349 static ulong get_ms_timer(void)
350 {
351         return (get_ticks() * 1000) / get_tbclk();
352 }
353
354 ulong get_timer(ulong base)
355 {
356         return get_ms_timer() - base;
357 }
358
359 ulong notrace timer_get_us(void)
360 {
361         return get_ticks() / get_tbclk_mhz();
362 }
363
364 ulong timer_get_boot_us(void)
365 {
366         return timer_get_us();
367 }
368
369 void __udelay(unsigned long usec)
370 {
371         u64 now = get_ticks();
372         u64 stop;
373
374         stop = now + usec * get_tbclk_mhz();
375
376         while ((int64_t)(stop - get_ticks()) > 0)
377 #if defined(CONFIG_QEMU) && defined(CONFIG_SMP)
378                 /*
379                  * Add a 'pause' instruction on qemu target,
380                  * to give other VCPUs a chance to run.
381                  */
382                 asm volatile("pause");
383 #else
384                 ;
385 #endif
386 }
387
388 static int tsc_timer_get_count(struct udevice *dev, u64 *count)
389 {
390         u64 now_tick = rdtsc();
391
392         *count = now_tick - gd->arch.tsc_base;
393
394         return 0;
395 }
396
397 static void tsc_timer_ensure_setup(bool early)
398 {
399         if (gd->arch.tsc_inited)
400                 return;
401         if (IS_ENABLED(CONFIG_X86_TSC_READ_BASE))
402                 gd->arch.tsc_base = rdtsc();
403
404         if (!gd->arch.clock_rate) {
405                 unsigned long fast_calibrate;
406
407                 fast_calibrate = native_calibrate_tsc();
408                 if (fast_calibrate)
409                         goto done;
410
411                 /* Reduce code size by dropping other methods */
412                 if (CONFIG_IS_ENABLED(X86_TSC_TIMER_NATIVE))
413                         panic("no timer");
414
415                 fast_calibrate = cpu_mhz_from_cpuid();
416                 if (fast_calibrate)
417                         goto done;
418
419                 fast_calibrate = cpu_mhz_from_msr();
420                 if (fast_calibrate)
421                         goto done;
422
423                 fast_calibrate = quick_pit_calibrate();
424                 if (fast_calibrate)
425                         goto done;
426
427                 if (early)
428                         fast_calibrate = CONFIG_X86_TSC_TIMER_EARLY_FREQ;
429                 else
430                         return;
431
432 done:
433                 gd->arch.clock_rate = fast_calibrate * 1000000;
434         }
435         gd->arch.tsc_inited = true;
436 }
437
438 static int tsc_timer_probe(struct udevice *dev)
439 {
440         struct timer_dev_priv *uc_priv = dev_get_uclass_priv(dev);
441
442         /* Try hardware calibration first */
443         tsc_timer_ensure_setup(false);
444         if (!gd->arch.clock_rate) {
445                 /*
446                  * Use the clock frequency specified in the
447                  * device tree as last resort
448                  */
449                 if (!uc_priv->clock_rate)
450                         panic("TSC frequency is ZERO");
451         } else {
452                 uc_priv->clock_rate = gd->arch.clock_rate;
453         }
454
455         return 0;
456 }
457
458 unsigned long notrace timer_early_get_rate(void)
459 {
460         /*
461          * When TSC timer is used as the early timer, be warned that the timer
462          * clock rate can only be calibrated via some hardware ways. Specifying
463          * it in the device tree won't work for the early timer.
464          */
465         tsc_timer_ensure_setup(true);
466
467         return gd->arch.clock_rate;
468 }
469
470 u64 notrace timer_early_get_count(void)
471 {
472         tsc_timer_ensure_setup(true);
473
474         return rdtsc() - gd->arch.tsc_base;
475 }
476
477 static const struct timer_ops tsc_timer_ops = {
478         .get_count = tsc_timer_get_count,
479 };
480
481 static const struct udevice_id tsc_timer_ids[] = {
482         { .compatible = "x86,tsc-timer", },
483         { }
484 };
485
486 U_BOOT_DRIVER(tsc_timer) = {
487         .name   = "tsc_timer",
488         .id     = UCLASS_TIMER,
489         .of_match = tsc_timer_ids,
490         .probe = tsc_timer_probe,
491         .ops    = &tsc_timer_ops,
492 };