x86: Add quick TSC calibration via PIT
[oweals/u-boot.git] / arch / x86 / lib / tsc_timer.c
1 /*
2  * Copyright (c) 2012 The Chromium OS Authors.
3  *
4  * TSC calibration codes are adapted from Linux kernel
5  * arch/x86/kernel/tsc_msr.c and arch/x86/kernel/tsc.c
6  *
7  * SPDX-License-Identifier:     GPL-2.0+
8  */
9
10 #include <common.h>
11 #include <malloc.h>
12 #include <asm/io.h>
13 #include <asm/i8254.h>
14 #include <asm/ibmpc.h>
15 #include <asm/msr.h>
16 #include <asm/u-boot-x86.h>
17
18 /* CPU reference clock frequency: in KHz */
19 #define FREQ_83         83200
20 #define FREQ_100        99840
21 #define FREQ_133        133200
22 #define FREQ_166        166400
23
24 #define MAX_NUM_FREQS   8
25
26 DECLARE_GLOBAL_DATA_PTR;
27
28 /*
29  * According to Intel 64 and IA-32 System Programming Guide,
30  * if MSR_PERF_STAT[31] is set, the maximum resolved bus ratio can be
31  * read in MSR_PLATFORM_ID[12:8], otherwise in MSR_PERF_STAT[44:40].
32  * Unfortunately some Intel Atom SoCs aren't quite compliant to this,
33  * so we need manually differentiate SoC families. This is what the
34  * field msr_plat does.
35  */
36 struct freq_desc {
37         u8 x86_family;  /* CPU family */
38         u8 x86_model;   /* model */
39         u8 msr_plat;    /* 1: use MSR_PLATFORM_INFO, 0: MSR_IA32_PERF_STATUS */
40         u32 freqs[MAX_NUM_FREQS];
41 };
42
43 static struct freq_desc freq_desc_tables[] = {
44         /* PNW */
45         { 6, 0x27, 0, { 0, 0, 0, 0, 0, FREQ_100, 0, FREQ_83 } },
46         /* CLV+ */
47         { 6, 0x35, 0, { 0, FREQ_133, 0, 0, 0, FREQ_100, 0, FREQ_83 } },
48         /* TNG */
49         { 6, 0x4a, 1, { 0, FREQ_100, FREQ_133, 0, 0, 0, 0, 0 } },
50         /* VLV2 */
51         { 6, 0x37, 1, { FREQ_83, FREQ_100, FREQ_133, FREQ_166, 0, 0, 0, 0 } },
52         /* ANN */
53         { 6, 0x5a, 1, { FREQ_83, FREQ_100, FREQ_133, FREQ_100, 0, 0, 0, 0 } },
54 };
55
56 static int match_cpu(u8 family, u8 model)
57 {
58         int i;
59
60         for (i = 0; i < ARRAY_SIZE(freq_desc_tables); i++) {
61                 if ((family == freq_desc_tables[i].x86_family) &&
62                     (model == freq_desc_tables[i].x86_model))
63                         return i;
64         }
65
66         return -1;
67 }
68
69 /* Map CPU reference clock freq ID(0-7) to CPU reference clock freq(KHz) */
70 #define id_to_freq(cpu_index, freq_id) \
71         (freq_desc_tables[cpu_index].freqs[freq_id])
72
73 /*
74  * Do MSR calibration only for known/supported CPUs.
75  *
76  * Returns the calibration value or 0 if MSR calibration failed.
77  */
78 static unsigned long try_msr_calibrate_tsc(void)
79 {
80         u32 lo, hi, ratio, freq_id, freq;
81         unsigned long res;
82         int cpu_index;
83
84         cpu_index = match_cpu(gd->arch.x86, gd->arch.x86_model);
85         if (cpu_index < 0)
86                 return 0;
87
88         if (freq_desc_tables[cpu_index].msr_plat) {
89                 rdmsr(MSR_PLATFORM_INFO, lo, hi);
90                 ratio = (lo >> 8) & 0x1f;
91         } else {
92                 rdmsr(MSR_IA32_PERF_STATUS, lo, hi);
93                 ratio = (hi >> 8) & 0x1f;
94         }
95         debug("Maximum core-clock to bus-clock ratio: 0x%x\n", ratio);
96
97         if (!ratio)
98                 goto fail;
99
100         /* Get FSB FREQ ID */
101         rdmsr(MSR_FSB_FREQ, lo, hi);
102         freq_id = lo & 0x7;
103         freq = id_to_freq(cpu_index, freq_id);
104         debug("Resolved frequency ID: %u, frequency: %u KHz\n", freq_id, freq);
105         if (!freq)
106                 goto fail;
107
108         /* TSC frequency = maximum resolved freq * maximum resolved bus ratio */
109         res = freq * ratio / 1000;
110         debug("TSC runs at %lu MHz\n", res);
111
112         return res;
113
114 fail:
115         debug("Fast TSC calibration using MSR failed\n");
116         return 0;
117 }
118
119 /*
120  * This reads the current MSB of the PIT counter, and
121  * checks if we are running on sufficiently fast and
122  * non-virtualized hardware.
123  *
124  * Our expectations are:
125  *
126  *  - the PIT is running at roughly 1.19MHz
127  *
128  *  - each IO is going to take about 1us on real hardware,
129  *    but we allow it to be much faster (by a factor of 10) or
130  *    _slightly_ slower (ie we allow up to a 2us read+counter
131  *    update - anything else implies a unacceptably slow CPU
132  *    or PIT for the fast calibration to work.
133  *
134  *  - with 256 PIT ticks to read the value, we have 214us to
135  *    see the same MSB (and overhead like doing a single TSC
136  *    read per MSB value etc).
137  *
138  *  - We're doing 2 reads per loop (LSB, MSB), and we expect
139  *    them each to take about a microsecond on real hardware.
140  *    So we expect a count value of around 100. But we'll be
141  *    generous, and accept anything over 50.
142  *
143  *  - if the PIT is stuck, and we see *many* more reads, we
144  *    return early (and the next caller of pit_expect_msb()
145  *    then consider it a failure when they don't see the
146  *    next expected value).
147  *
148  * These expectations mean that we know that we have seen the
149  * transition from one expected value to another with a fairly
150  * high accuracy, and we didn't miss any events. We can thus
151  * use the TSC value at the transitions to calculate a pretty
152  * good value for the TSC frequencty.
153  */
154 static inline int pit_verify_msb(unsigned char val)
155 {
156         /* Ignore LSB */
157         inb(0x42);
158         return inb(0x42) == val;
159 }
160
161 static inline int pit_expect_msb(unsigned char val, u64 *tscp,
162                                  unsigned long *deltap)
163 {
164         int count;
165         u64 tsc = 0, prev_tsc = 0;
166
167         for (count = 0; count < 50000; count++) {
168                 if (!pit_verify_msb(val))
169                         break;
170                 prev_tsc = tsc;
171                 tsc = rdtsc();
172         }
173         *deltap = rdtsc() - prev_tsc;
174         *tscp = tsc;
175
176         /*
177          * We require _some_ success, but the quality control
178          * will be based on the error terms on the TSC values.
179          */
180         return count > 5;
181 }
182
183 /*
184  * How many MSB values do we want to see? We aim for
185  * a maximum error rate of 500ppm (in practice the
186  * real error is much smaller), but refuse to spend
187  * more than 50ms on it.
188  */
189 #define MAX_QUICK_PIT_MS 50
190 #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
191
192 static unsigned long quick_pit_calibrate(void)
193 {
194         int i;
195         u64 tsc, delta;
196         unsigned long d1, d2;
197
198         /* Set the Gate high, disable speaker */
199         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
200
201         /*
202          * Counter 2, mode 0 (one-shot), binary count
203          *
204          * NOTE! Mode 2 decrements by two (and then the
205          * output is flipped each time, giving the same
206          * final output frequency as a decrement-by-one),
207          * so mode 0 is much better when looking at the
208          * individual counts.
209          */
210         outb(0xb0, 0x43);
211
212         /* Start at 0xffff */
213         outb(0xff, 0x42);
214         outb(0xff, 0x42);
215
216         /*
217          * The PIT starts counting at the next edge, so we
218          * need to delay for a microsecond. The easiest way
219          * to do that is to just read back the 16-bit counter
220          * once from the PIT.
221          */
222         pit_verify_msb(0);
223
224         if (pit_expect_msb(0xff, &tsc, &d1)) {
225                 for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
226                         if (!pit_expect_msb(0xff-i, &delta, &d2))
227                                 break;
228
229                         /*
230                          * Iterate until the error is less than 500 ppm
231                          */
232                         delta -= tsc;
233                         if (d1+d2 >= delta >> 11)
234                                 continue;
235
236                         /*
237                          * Check the PIT one more time to verify that
238                          * all TSC reads were stable wrt the PIT.
239                          *
240                          * This also guarantees serialization of the
241                          * last cycle read ('d2') in pit_expect_msb.
242                          */
243                         if (!pit_verify_msb(0xfe - i))
244                                 break;
245                         goto success;
246                 }
247         }
248         debug("Fast TSC calibration failed\n");
249         return 0;
250
251 success:
252         /*
253          * Ok, if we get here, then we've seen the
254          * MSB of the PIT decrement 'i' times, and the
255          * error has shrunk to less than 500 ppm.
256          *
257          * As a result, we can depend on there not being
258          * any odd delays anywhere, and the TSC reads are
259          * reliable (within the error).
260          *
261          * kHz = ticks / time-in-seconds / 1000;
262          * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
263          * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
264          */
265         delta *= PIT_TICK_RATE;
266         delta /= (i*256*1000);
267         debug("Fast TSC calibration using PIT\n");
268         return delta / 1000;
269 }
270
271 void timer_set_base(u64 base)
272 {
273         gd->arch.tsc_base = base;
274 }
275
276 /*
277  * Get the number of CPU time counter ticks since it was read first time after
278  * restart. This yields a free running counter guaranteed to take almost 6
279  * years to wrap around even at 100GHz clock rate.
280  */
281 u64 __attribute__((no_instrument_function)) get_ticks(void)
282 {
283         u64 now_tick = rdtsc();
284
285         /* We assume that 0 means the base hasn't been set yet */
286         if (!gd->arch.tsc_base)
287                 panic("No tick base available");
288         return now_tick - gd->arch.tsc_base;
289 }
290
291 /* Get the speed of the TSC timer in MHz */
292 unsigned __attribute__((no_instrument_function)) long get_tbclk_mhz(void)
293 {
294         unsigned long fast_calibrate;
295
296         fast_calibrate = try_msr_calibrate_tsc();
297         if (fast_calibrate)
298                 return fast_calibrate;
299
300         fast_calibrate = quick_pit_calibrate();
301         if (!fast_calibrate)
302                 panic("TSC frequency is ZERO");
303
304         return fast_calibrate;
305 }
306
307 unsigned long get_tbclk(void)
308 {
309         return get_tbclk_mhz() * 1000 * 1000;
310 }
311
312 static ulong get_ms_timer(void)
313 {
314         return (get_ticks() * 1000) / get_tbclk();
315 }
316
317 ulong get_timer(ulong base)
318 {
319         return get_ms_timer() - base;
320 }
321
322 ulong __attribute__((no_instrument_function)) timer_get_us(void)
323 {
324         return get_ticks() / get_tbclk_mhz();
325 }
326
327 ulong timer_get_boot_us(void)
328 {
329         return timer_get_us();
330 }
331
332 void __udelay(unsigned long usec)
333 {
334         u64 now = get_ticks();
335         u64 stop;
336
337         stop = now + usec * get_tbclk_mhz();
338
339         while ((int64_t)(stop - get_ticks()) > 0)
340                 ;
341 }
342
343 int timer_init(void)
344 {
345 #ifdef CONFIG_SYS_PCAT_TIMER
346         /* Set up the PCAT timer if required */
347         pcat_timer_init();
348 #endif
349
350         return 0;
351 }