Linux Audio

Check our new training course

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