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