tsc_sync.c 13 KB

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