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