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