xref: /openbmc/linux/arch/x86/kernel/tsc_sync.c (revision b24413180f5600bcb3bb70fbed5cf186b60864bd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * check TSC synchronization.
4  *
5  * Copyright (C) 2006, Red Hat, Inc., Ingo Molnar
6  *
7  * We check whether all boot CPUs have their TSC's synchronized,
8  * print a warning if not and turn off the TSC clock-source.
9  *
10  * The warp-check is point-to-point between two CPUs, the CPU
11  * initiating the bootup is the 'source CPU', the freshly booting
12  * CPU is the 'target CPU'.
13  *
14  * Only two CPUs may participate - they can enter in any order.
15  * ( The serial nature of the boot logic and the CPU hotplug lock
16  *   protects against more than 2 CPUs entering this code. )
17  */
18 #include <linux/topology.h>
19 #include <linux/spinlock.h>
20 #include <linux/kernel.h>
21 #include <linux/smp.h>
22 #include <linux/nmi.h>
23 #include <asm/tsc.h>
24 
25 struct tsc_adjust {
26 	s64		bootval;
27 	s64		adjusted;
28 	unsigned long	nextcheck;
29 	bool		warned;
30 };
31 
32 static DEFINE_PER_CPU(struct tsc_adjust, tsc_adjust);
33 
34 void tsc_verify_tsc_adjust(bool resume)
35 {
36 	struct tsc_adjust *adj = this_cpu_ptr(&tsc_adjust);
37 	s64 curval;
38 
39 	if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST))
40 		return;
41 
42 	/* Rate limit the MSR check */
43 	if (!resume && time_before(jiffies, adj->nextcheck))
44 		return;
45 
46 	adj->nextcheck = jiffies + HZ;
47 
48 	rdmsrl(MSR_IA32_TSC_ADJUST, curval);
49 	if (adj->adjusted == curval)
50 		return;
51 
52 	/* Restore the original value */
53 	wrmsrl(MSR_IA32_TSC_ADJUST, adj->adjusted);
54 
55 	if (!adj->warned || resume) {
56 		pr_warn(FW_BUG "TSC ADJUST differs: CPU%u %lld --> %lld. Restoring\n",
57 			smp_processor_id(), adj->adjusted, curval);
58 		adj->warned = true;
59 	}
60 }
61 
62 static void tsc_sanitize_first_cpu(struct tsc_adjust *cur, s64 bootval,
63 				   unsigned int cpu, bool bootcpu)
64 {
65 	/*
66 	 * First online CPU in a package stores the boot value in the
67 	 * adjustment value. This value might change later via the sync
68 	 * mechanism. If that fails we still can yell about boot values not
69 	 * being consistent.
70 	 *
71 	 * On the boot cpu we just force set the ADJUST value to 0 if it's
72 	 * non zero. We don't do that on non boot cpus because physical
73 	 * hotplug should have set the ADJUST register to a value > 0 so
74 	 * the TSC is in sync with the already running cpus.
75 	 */
76 	if (bootcpu && bootval != 0) {
77 		pr_warn(FW_BUG "TSC ADJUST: CPU%u: %lld force to 0\n", cpu,
78 			bootval);
79 		wrmsrl(MSR_IA32_TSC_ADJUST, 0);
80 		bootval = 0;
81 	}
82 	cur->adjusted = bootval;
83 }
84 
85 #ifndef CONFIG_SMP
86 bool __init tsc_store_and_check_tsc_adjust(bool bootcpu)
87 {
88 	struct tsc_adjust *cur = this_cpu_ptr(&tsc_adjust);
89 	s64 bootval;
90 
91 	if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST))
92 		return false;
93 
94 	rdmsrl(MSR_IA32_TSC_ADJUST, bootval);
95 	cur->bootval = bootval;
96 	cur->nextcheck = jiffies + HZ;
97 	tsc_sanitize_first_cpu(cur, bootval, smp_processor_id(), bootcpu);
98 	return false;
99 }
100 
101 #else /* !CONFIG_SMP */
102 
103 /*
104  * Store and check the TSC ADJUST MSR if available
105  */
106 bool tsc_store_and_check_tsc_adjust(bool bootcpu)
107 {
108 	struct tsc_adjust *ref, *cur = this_cpu_ptr(&tsc_adjust);
109 	unsigned int refcpu, cpu = smp_processor_id();
110 	struct cpumask *mask;
111 	s64 bootval;
112 
113 	if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST))
114 		return false;
115 
116 	rdmsrl(MSR_IA32_TSC_ADJUST, bootval);
117 	cur->bootval = bootval;
118 	cur->nextcheck = jiffies + HZ;
119 	cur->warned = false;
120 
121 	/*
122 	 * Check whether this CPU is the first in a package to come up. In
123 	 * this case do not check the boot value against another package
124 	 * because the new package might have been physically hotplugged,
125 	 * where TSC_ADJUST is expected to be different. When called on the
126 	 * boot CPU topology_core_cpumask() might not be available yet.
127 	 */
128 	mask = topology_core_cpumask(cpu);
129 	refcpu = mask ? cpumask_any_but(mask, cpu) : nr_cpu_ids;
130 
131 	if (refcpu >= nr_cpu_ids) {
132 		tsc_sanitize_first_cpu(cur, bootval, smp_processor_id(),
133 				       bootcpu);
134 		return false;
135 	}
136 
137 	ref = per_cpu_ptr(&tsc_adjust, refcpu);
138 	/*
139 	 * Compare the boot value and complain if it differs in the
140 	 * package.
141 	 */
142 	if (bootval != ref->bootval) {
143 		pr_warn(FW_BUG "TSC ADJUST differs: Reference CPU%u: %lld CPU%u: %lld\n",
144 			refcpu, ref->bootval, cpu, bootval);
145 	}
146 	/*
147 	 * The TSC_ADJUST values in a package must be the same. If the boot
148 	 * value on this newly upcoming CPU differs from the adjustment
149 	 * value of the already online CPU in this package, set it to that
150 	 * adjusted value.
151 	 */
152 	if (bootval != ref->adjusted) {
153 		pr_warn("TSC ADJUST synchronize: Reference CPU%u: %lld CPU%u: %lld\n",
154 			refcpu, ref->adjusted, cpu, bootval);
155 		cur->adjusted = ref->adjusted;
156 		wrmsrl(MSR_IA32_TSC_ADJUST, ref->adjusted);
157 	}
158 	/*
159 	 * We have the TSCs forced to be in sync on this package. Skip sync
160 	 * test:
161 	 */
162 	return true;
163 }
164 
165 /*
166  * Entry/exit counters that make sure that both CPUs
167  * run the measurement code at once:
168  */
169 static atomic_t start_count;
170 static atomic_t stop_count;
171 static atomic_t skip_test;
172 static atomic_t test_runs;
173 
174 /*
175  * We use a raw spinlock in this exceptional case, because
176  * we want to have the fastest, inlined, non-debug version
177  * of a critical section, to be able to prove TSC time-warps:
178  */
179 static arch_spinlock_t sync_lock = __ARCH_SPIN_LOCK_UNLOCKED;
180 
181 static cycles_t last_tsc;
182 static cycles_t max_warp;
183 static int nr_warps;
184 static int random_warps;
185 
186 /*
187  * TSC-warp measurement loop running on both CPUs.  This is not called
188  * if there is no TSC.
189  */
190 static cycles_t check_tsc_warp(unsigned int timeout)
191 {
192 	cycles_t start, now, prev, end, cur_max_warp = 0;
193 	int i, cur_warps = 0;
194 
195 	start = rdtsc_ordered();
196 	/*
197 	 * The measurement runs for 'timeout' msecs:
198 	 */
199 	end = start + (cycles_t) tsc_khz * timeout;
200 	now = start;
201 
202 	for (i = 0; ; i++) {
203 		/*
204 		 * We take the global lock, measure TSC, save the
205 		 * previous TSC that was measured (possibly on
206 		 * another CPU) and update the previous TSC timestamp.
207 		 */
208 		arch_spin_lock(&sync_lock);
209 		prev = last_tsc;
210 		now = rdtsc_ordered();
211 		last_tsc = now;
212 		arch_spin_unlock(&sync_lock);
213 
214 		/*
215 		 * Be nice every now and then (and also check whether
216 		 * measurement is done [we also insert a 10 million
217 		 * loops safety exit, so we dont lock up in case the
218 		 * TSC readout is totally broken]):
219 		 */
220 		if (unlikely(!(i & 7))) {
221 			if (now > end || i > 10000000)
222 				break;
223 			cpu_relax();
224 			touch_nmi_watchdog();
225 		}
226 		/*
227 		 * Outside the critical section we can now see whether
228 		 * we saw a time-warp of the TSC going backwards:
229 		 */
230 		if (unlikely(prev > now)) {
231 			arch_spin_lock(&sync_lock);
232 			max_warp = max(max_warp, prev - now);
233 			cur_max_warp = max_warp;
234 			/*
235 			 * Check whether this bounces back and forth. Only
236 			 * one CPU should observe time going backwards.
237 			 */
238 			if (cur_warps != nr_warps)
239 				random_warps++;
240 			nr_warps++;
241 			cur_warps = nr_warps;
242 			arch_spin_unlock(&sync_lock);
243 		}
244 	}
245 	WARN(!(now-start),
246 		"Warning: zero tsc calibration delta: %Ld [max: %Ld]\n",
247 			now-start, end-start);
248 	return cur_max_warp;
249 }
250 
251 /*
252  * If the target CPU coming online doesn't have any of its core-siblings
253  * online, a timeout of 20msec will be used for the TSC-warp measurement
254  * loop. Otherwise a smaller timeout of 2msec will be used, as we have some
255  * information about this socket already (and this information grows as we
256  * have more and more logical-siblings in that socket).
257  *
258  * Ideally we should be able to skip the TSC sync check on the other
259  * core-siblings, if the first logical CPU in a socket passed the sync test.
260  * But as the TSC is per-logical CPU and can potentially be modified wrongly
261  * by the bios, TSC sync test for smaller duration should be able
262  * to catch such errors. Also this will catch the condition where all the
263  * cores in the socket doesn't get reset at the same time.
264  */
265 static inline unsigned int loop_timeout(int cpu)
266 {
267 	return (cpumask_weight(topology_core_cpumask(cpu)) > 1) ? 2 : 20;
268 }
269 
270 /*
271  * Source CPU calls into this - it waits for the freshly booted
272  * target CPU to arrive and then starts the measurement:
273  */
274 void check_tsc_sync_source(int cpu)
275 {
276 	int cpus = 2;
277 
278 	/*
279 	 * No need to check if we already know that the TSC is not
280 	 * synchronized or if we have no TSC.
281 	 */
282 	if (unsynchronized_tsc())
283 		return;
284 
285 	/*
286 	 * Set the maximum number of test runs to
287 	 *  1 if the CPU does not provide the TSC_ADJUST MSR
288 	 *  3 if the MSR is available, so the target can try to adjust
289 	 */
290 	if (!boot_cpu_has(X86_FEATURE_TSC_ADJUST))
291 		atomic_set(&test_runs, 1);
292 	else
293 		atomic_set(&test_runs, 3);
294 retry:
295 	/*
296 	 * Wait for the target to start or to skip the test:
297 	 */
298 	while (atomic_read(&start_count) != cpus - 1) {
299 		if (atomic_read(&skip_test) > 0) {
300 			atomic_set(&skip_test, 0);
301 			return;
302 		}
303 		cpu_relax();
304 	}
305 
306 	/*
307 	 * Trigger the target to continue into the measurement too:
308 	 */
309 	atomic_inc(&start_count);
310 
311 	check_tsc_warp(loop_timeout(cpu));
312 
313 	while (atomic_read(&stop_count) != cpus-1)
314 		cpu_relax();
315 
316 	/*
317 	 * If the test was successful set the number of runs to zero and
318 	 * stop. If not, decrement the number of runs an check if we can
319 	 * retry. In case of random warps no retry is attempted.
320 	 */
321 	if (!nr_warps) {
322 		atomic_set(&test_runs, 0);
323 
324 		pr_debug("TSC synchronization [CPU#%d -> CPU#%d]: passed\n",
325 			smp_processor_id(), cpu);
326 
327 	} else if (atomic_dec_and_test(&test_runs) || random_warps) {
328 		/* Force it to 0 if random warps brought us here */
329 		atomic_set(&test_runs, 0);
330 
331 		pr_warning("TSC synchronization [CPU#%d -> CPU#%d]:\n",
332 			smp_processor_id(), cpu);
333 		pr_warning("Measured %Ld cycles TSC warp between CPUs, "
334 			   "turning off TSC clock.\n", max_warp);
335 		if (random_warps)
336 			pr_warning("TSC warped randomly between CPUs\n");
337 		mark_tsc_unstable("check_tsc_sync_source failed");
338 	}
339 
340 	/*
341 	 * Reset it - just in case we boot another CPU later:
342 	 */
343 	atomic_set(&start_count, 0);
344 	random_warps = 0;
345 	nr_warps = 0;
346 	max_warp = 0;
347 	last_tsc = 0;
348 
349 	/*
350 	 * Let the target continue with the bootup:
351 	 */
352 	atomic_inc(&stop_count);
353 
354 	/*
355 	 * Retry, if there is a chance to do so.
356 	 */
357 	if (atomic_read(&test_runs) > 0)
358 		goto retry;
359 }
360 
361 /*
362  * Freshly booted CPUs call into this:
363  */
364 void check_tsc_sync_target(void)
365 {
366 	struct tsc_adjust *cur = this_cpu_ptr(&tsc_adjust);
367 	unsigned int cpu = smp_processor_id();
368 	cycles_t cur_max_warp, gbl_max_warp;
369 	int cpus = 2;
370 
371 	/* Also aborts if there is no TSC. */
372 	if (unsynchronized_tsc())
373 		return;
374 
375 	/*
376 	 * Store, verify and sanitize the TSC adjust register. If
377 	 * successful skip the test.
378 	 *
379 	 * The test is also skipped when the TSC is marked reliable. This
380 	 * is true for SoCs which have no fallback clocksource. On these
381 	 * SoCs the TSC is frequency synchronized, but still the TSC ADJUST
382 	 * register might have been wreckaged by the BIOS..
383 	 */
384 	if (tsc_store_and_check_tsc_adjust(false) || tsc_clocksource_reliable) {
385 		atomic_inc(&skip_test);
386 		return;
387 	}
388 
389 retry:
390 	/*
391 	 * Register this CPU's participation and wait for the
392 	 * source CPU to start the measurement:
393 	 */
394 	atomic_inc(&start_count);
395 	while (atomic_read(&start_count) != cpus)
396 		cpu_relax();
397 
398 	cur_max_warp = check_tsc_warp(loop_timeout(cpu));
399 
400 	/*
401 	 * Store the maximum observed warp value for a potential retry:
402 	 */
403 	gbl_max_warp = max_warp;
404 
405 	/*
406 	 * Ok, we are done:
407 	 */
408 	atomic_inc(&stop_count);
409 
410 	/*
411 	 * Wait for the source CPU to print stuff:
412 	 */
413 	while (atomic_read(&stop_count) != cpus)
414 		cpu_relax();
415 
416 	/*
417 	 * Reset it for the next sync test:
418 	 */
419 	atomic_set(&stop_count, 0);
420 
421 	/*
422 	 * Check the number of remaining test runs. If not zero, the test
423 	 * failed and a retry with adjusted TSC is possible. If zero the
424 	 * test was either successful or failed terminally.
425 	 */
426 	if (!atomic_read(&test_runs))
427 		return;
428 
429 	/*
430 	 * If the warp value of this CPU is 0, then the other CPU
431 	 * observed time going backwards so this TSC was ahead and
432 	 * needs to move backwards.
433 	 */
434 	if (!cur_max_warp)
435 		cur_max_warp = -gbl_max_warp;
436 
437 	/*
438 	 * Add the result to the previous adjustment value.
439 	 *
440 	 * The adjustement value is slightly off by the overhead of the
441 	 * sync mechanism (observed values are ~200 TSC cycles), but this
442 	 * really depends on CPU, node distance and frequency. So
443 	 * compensating for this is hard to get right. Experiments show
444 	 * that the warp is not longer detectable when the observed warp
445 	 * value is used. In the worst case the adjustment needs to go
446 	 * through a 3rd run for fine tuning.
447 	 */
448 	cur->adjusted += cur_max_warp;
449 
450 	pr_warn("TSC ADJUST compensate: CPU%u observed %lld warp. Adjust: %lld\n",
451 		cpu, cur_max_warp, cur->adjusted);
452 
453 	wrmsrl(MSR_IA32_TSC_ADJUST, cur->adjusted);
454 	goto retry;
455 
456 }
457 
458 #endif /* CONFIG_SMP */
459