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