tsc.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  3. #include <linux/kernel.h>
  4. #include <linux/sched.h>
  5. #include <linux/sched/clock.h>
  6. #include <linux/init.h>
  7. #include <linux/export.h>
  8. #include <linux/timer.h>
  9. #include <linux/acpi_pmtmr.h>
  10. #include <linux/cpufreq.h>
  11. #include <linux/delay.h>
  12. #include <linux/clocksource.h>
  13. #include <linux/percpu.h>
  14. #include <linux/timex.h>
  15. #include <linux/static_key.h>
  16. #include <linux/static_call.h>
  17. #include <asm/hpet.h>
  18. #include <asm/timer.h>
  19. #include <asm/vgtod.h>
  20. #include <asm/time.h>
  21. #include <asm/delay.h>
  22. #include <asm/hypervisor.h>
  23. #include <asm/nmi.h>
  24. #include <asm/x86_init.h>
  25. #include <asm/geode.h>
  26. #include <asm/apic.h>
  27. #include <asm/cpu_device_id.h>
  28. #include <asm/i8259.h>
  29. #include <asm/topology.h>
  30. #include <asm/uv/uv.h>
  31. unsigned int __read_mostly cpu_khz; /* TSC clocks / usec, not used here */
  32. EXPORT_SYMBOL(cpu_khz);
  33. unsigned int __read_mostly tsc_khz;
  34. EXPORT_SYMBOL(tsc_khz);
  35. #define KHZ 1000
  36. /*
  37. * TSC can be unstable due to cpufreq or due to unsynced TSCs
  38. */
  39. static int __read_mostly tsc_unstable;
  40. static unsigned int __initdata tsc_early_khz;
  41. static DEFINE_STATIC_KEY_FALSE_RO(__use_tsc);
  42. int tsc_clocksource_reliable;
  43. static int __read_mostly tsc_force_recalibrate;
  44. static struct clocksource_base art_base_clk = {
  45. .id = CSID_X86_ART,
  46. };
  47. static bool have_art;
  48. struct cyc2ns {
  49. struct cyc2ns_data data[2]; /* 0 + 2*16 = 32 */
  50. seqcount_latch_t seq; /* 32 + 4 = 36 */
  51. }; /* fits one cacheline */
  52. static DEFINE_PER_CPU_ALIGNED(struct cyc2ns, cyc2ns);
  53. static int __init tsc_early_khz_setup(char *buf)
  54. {
  55. return kstrtouint(buf, 0, &tsc_early_khz);
  56. }
  57. early_param("tsc_early_khz", tsc_early_khz_setup);
  58. __always_inline void __cyc2ns_read(struct cyc2ns_data *data)
  59. {
  60. int seq, idx;
  61. do {
  62. seq = this_cpu_read(cyc2ns.seq.seqcount.sequence);
  63. idx = seq & 1;
  64. data->cyc2ns_offset = this_cpu_read(cyc2ns.data[idx].cyc2ns_offset);
  65. data->cyc2ns_mul = this_cpu_read(cyc2ns.data[idx].cyc2ns_mul);
  66. data->cyc2ns_shift = this_cpu_read(cyc2ns.data[idx].cyc2ns_shift);
  67. } while (unlikely(seq != this_cpu_read(cyc2ns.seq.seqcount.sequence)));
  68. }
  69. __always_inline void cyc2ns_read_begin(struct cyc2ns_data *data)
  70. {
  71. preempt_disable_notrace();
  72. __cyc2ns_read(data);
  73. }
  74. __always_inline void cyc2ns_read_end(void)
  75. {
  76. preempt_enable_notrace();
  77. }
  78. /*
  79. * Accelerators for sched_clock()
  80. * convert from cycles(64bits) => nanoseconds (64bits)
  81. * basic equation:
  82. * ns = cycles / (freq / ns_per_sec)
  83. * ns = cycles * (ns_per_sec / freq)
  84. * ns = cycles * (10^9 / (cpu_khz * 10^3))
  85. * ns = cycles * (10^6 / cpu_khz)
  86. *
  87. * Then we use scaling math (suggested by george@mvista.com) to get:
  88. * ns = cycles * (10^6 * SC / cpu_khz) / SC
  89. * ns = cycles * cyc2ns_scale / SC
  90. *
  91. * And since SC is a constant power of two, we can convert the div
  92. * into a shift. The larger SC is, the more accurate the conversion, but
  93. * cyc2ns_scale needs to be a 32-bit value so that 32-bit multiplication
  94. * (64-bit result) can be used.
  95. *
  96. * We can use khz divisor instead of mhz to keep a better precision.
  97. * (mathieu.desnoyers@polymtl.ca)
  98. *
  99. * -johnstul@us.ibm.com "math is hard, lets go shopping!"
  100. */
  101. static __always_inline unsigned long long __cycles_2_ns(unsigned long long cyc)
  102. {
  103. struct cyc2ns_data data;
  104. unsigned long long ns;
  105. __cyc2ns_read(&data);
  106. ns = data.cyc2ns_offset;
  107. ns += mul_u64_u32_shr(cyc, data.cyc2ns_mul, data.cyc2ns_shift);
  108. return ns;
  109. }
  110. static __always_inline unsigned long long cycles_2_ns(unsigned long long cyc)
  111. {
  112. unsigned long long ns;
  113. preempt_disable_notrace();
  114. ns = __cycles_2_ns(cyc);
  115. preempt_enable_notrace();
  116. return ns;
  117. }
  118. static void __set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long tsc_now)
  119. {
  120. unsigned long long ns_now;
  121. struct cyc2ns_data data;
  122. struct cyc2ns *c2n;
  123. ns_now = cycles_2_ns(tsc_now);
  124. /*
  125. * Compute a new multiplier as per the above comment and ensure our
  126. * time function is continuous; see the comment near struct
  127. * cyc2ns_data.
  128. */
  129. clocks_calc_mult_shift(&data.cyc2ns_mul, &data.cyc2ns_shift, khz,
  130. NSEC_PER_MSEC, 0);
  131. /*
  132. * cyc2ns_shift is exported via arch_perf_update_userpage() where it is
  133. * not expected to be greater than 31 due to the original published
  134. * conversion algorithm shifting a 32-bit value (now specifies a 64-bit
  135. * value) - refer perf_event_mmap_page documentation in perf_event.h.
  136. */
  137. if (data.cyc2ns_shift == 32) {
  138. data.cyc2ns_shift = 31;
  139. data.cyc2ns_mul >>= 1;
  140. }
  141. data.cyc2ns_offset = ns_now -
  142. mul_u64_u32_shr(tsc_now, data.cyc2ns_mul, data.cyc2ns_shift);
  143. c2n = per_cpu_ptr(&cyc2ns, cpu);
  144. raw_write_seqcount_latch(&c2n->seq);
  145. c2n->data[0] = data;
  146. raw_write_seqcount_latch(&c2n->seq);
  147. c2n->data[1] = data;
  148. }
  149. static void set_cyc2ns_scale(unsigned long khz, int cpu, unsigned long long tsc_now)
  150. {
  151. unsigned long flags;
  152. local_irq_save(flags);
  153. sched_clock_idle_sleep_event();
  154. if (khz)
  155. __set_cyc2ns_scale(khz, cpu, tsc_now);
  156. sched_clock_idle_wakeup_event();
  157. local_irq_restore(flags);
  158. }
  159. /*
  160. * Initialize cyc2ns for boot cpu
  161. */
  162. static void __init cyc2ns_init_boot_cpu(void)
  163. {
  164. struct cyc2ns *c2n = this_cpu_ptr(&cyc2ns);
  165. seqcount_latch_init(&c2n->seq);
  166. __set_cyc2ns_scale(tsc_khz, smp_processor_id(), rdtsc());
  167. }
  168. /*
  169. * Secondary CPUs do not run through tsc_init(), so set up
  170. * all the scale factors for all CPUs, assuming the same
  171. * speed as the bootup CPU.
  172. */
  173. static void __init cyc2ns_init_secondary_cpus(void)
  174. {
  175. unsigned int cpu, this_cpu = smp_processor_id();
  176. struct cyc2ns *c2n = this_cpu_ptr(&cyc2ns);
  177. struct cyc2ns_data *data = c2n->data;
  178. for_each_possible_cpu(cpu) {
  179. if (cpu != this_cpu) {
  180. seqcount_latch_init(&c2n->seq);
  181. c2n = per_cpu_ptr(&cyc2ns, cpu);
  182. c2n->data[0] = data[0];
  183. c2n->data[1] = data[1];
  184. }
  185. }
  186. }
  187. /*
  188. * Scheduler clock - returns current time in nanosec units.
  189. */
  190. noinstr u64 native_sched_clock(void)
  191. {
  192. if (static_branch_likely(&__use_tsc)) {
  193. u64 tsc_now = rdtsc();
  194. /* return the value in ns */
  195. return __cycles_2_ns(tsc_now);
  196. }
  197. /*
  198. * Fall back to jiffies if there's no TSC available:
  199. * ( But note that we still use it if the TSC is marked
  200. * unstable. We do this because unlike Time Of Day,
  201. * the scheduler clock tolerates small errors and it's
  202. * very important for it to be as fast as the platform
  203. * can achieve it. )
  204. */
  205. /* No locking but a rare wrong value is not a big deal: */
  206. return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
  207. }
  208. /*
  209. * Generate a sched_clock if you already have a TSC value.
  210. */
  211. u64 native_sched_clock_from_tsc(u64 tsc)
  212. {
  213. return cycles_2_ns(tsc);
  214. }
  215. /* We need to define a real function for sched_clock, to override the
  216. weak default version */
  217. #ifdef CONFIG_PARAVIRT
  218. noinstr u64 sched_clock_noinstr(void)
  219. {
  220. return paravirt_sched_clock();
  221. }
  222. bool using_native_sched_clock(void)
  223. {
  224. return static_call_query(pv_sched_clock) == native_sched_clock;
  225. }
  226. #else
  227. u64 sched_clock_noinstr(void) __attribute__((alias("native_sched_clock")));
  228. bool using_native_sched_clock(void) { return true; }
  229. #endif
  230. notrace u64 sched_clock(void)
  231. {
  232. u64 now;
  233. preempt_disable_notrace();
  234. now = sched_clock_noinstr();
  235. preempt_enable_notrace();
  236. return now;
  237. }
  238. int check_tsc_unstable(void)
  239. {
  240. return tsc_unstable;
  241. }
  242. EXPORT_SYMBOL_GPL(check_tsc_unstable);
  243. #ifdef CONFIG_X86_TSC
  244. int __init notsc_setup(char *str)
  245. {
  246. mark_tsc_unstable("boot parameter notsc");
  247. return 1;
  248. }
  249. #else
  250. /*
  251. * disable flag for tsc. Takes effect by clearing the TSC cpu flag
  252. * in cpu/common.c
  253. */
  254. int __init notsc_setup(char *str)
  255. {
  256. setup_clear_cpu_cap(X86_FEATURE_TSC);
  257. return 1;
  258. }
  259. #endif
  260. __setup("notsc", notsc_setup);
  261. static int no_sched_irq_time;
  262. static int no_tsc_watchdog;
  263. static int tsc_as_watchdog;
  264. static int __init tsc_setup(char *str)
  265. {
  266. if (!strcmp(str, "reliable"))
  267. tsc_clocksource_reliable = 1;
  268. if (!strncmp(str, "noirqtime", 9))
  269. no_sched_irq_time = 1;
  270. if (!strcmp(str, "unstable"))
  271. mark_tsc_unstable("boot parameter");
  272. if (!strcmp(str, "nowatchdog")) {
  273. no_tsc_watchdog = 1;
  274. if (tsc_as_watchdog)
  275. pr_alert("%s: Overriding earlier tsc=watchdog with tsc=nowatchdog\n",
  276. __func__);
  277. tsc_as_watchdog = 0;
  278. }
  279. if (!strcmp(str, "recalibrate"))
  280. tsc_force_recalibrate = 1;
  281. if (!strcmp(str, "watchdog")) {
  282. if (no_tsc_watchdog)
  283. pr_alert("%s: tsc=watchdog overridden by earlier tsc=nowatchdog\n",
  284. __func__);
  285. else
  286. tsc_as_watchdog = 1;
  287. }
  288. return 1;
  289. }
  290. __setup("tsc=", tsc_setup);
  291. #define MAX_RETRIES 5
  292. #define TSC_DEFAULT_THRESHOLD 0x20000
  293. /*
  294. * Read TSC and the reference counters. Take care of any disturbances
  295. */
  296. static u64 tsc_read_refs(u64 *p, int hpet)
  297. {
  298. u64 t1, t2;
  299. u64 thresh = tsc_khz ? tsc_khz >> 5 : TSC_DEFAULT_THRESHOLD;
  300. int i;
  301. for (i = 0; i < MAX_RETRIES; i++) {
  302. t1 = get_cycles();
  303. if (hpet)
  304. *p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
  305. else
  306. *p = acpi_pm_read_early();
  307. t2 = get_cycles();
  308. if ((t2 - t1) < thresh)
  309. return t2;
  310. }
  311. return ULLONG_MAX;
  312. }
  313. /*
  314. * Calculate the TSC frequency from HPET reference
  315. */
  316. static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
  317. {
  318. u64 tmp;
  319. if (hpet2 < hpet1)
  320. hpet2 += 0x100000000ULL;
  321. hpet2 -= hpet1;
  322. tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
  323. do_div(tmp, 1000000);
  324. deltatsc = div64_u64(deltatsc, tmp);
  325. return (unsigned long) deltatsc;
  326. }
  327. /*
  328. * Calculate the TSC frequency from PMTimer reference
  329. */
  330. static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
  331. {
  332. u64 tmp;
  333. if (!pm1 && !pm2)
  334. return ULONG_MAX;
  335. if (pm2 < pm1)
  336. pm2 += (u64)ACPI_PM_OVRRUN;
  337. pm2 -= pm1;
  338. tmp = pm2 * 1000000000LL;
  339. do_div(tmp, PMTMR_TICKS_PER_SEC);
  340. do_div(deltatsc, tmp);
  341. return (unsigned long) deltatsc;
  342. }
  343. #define CAL_MS 10
  344. #define CAL_LATCH (PIT_TICK_RATE / (1000 / CAL_MS))
  345. #define CAL_PIT_LOOPS 1000
  346. #define CAL2_MS 50
  347. #define CAL2_LATCH (PIT_TICK_RATE / (1000 / CAL2_MS))
  348. #define CAL2_PIT_LOOPS 5000
  349. /*
  350. * Try to calibrate the TSC against the Programmable
  351. * Interrupt Timer and return the frequency of the TSC
  352. * in kHz.
  353. *
  354. * Return ULONG_MAX on failure to calibrate.
  355. */
  356. static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
  357. {
  358. u64 tsc, t1, t2, delta;
  359. unsigned long tscmin, tscmax;
  360. int pitcnt;
  361. if (!has_legacy_pic()) {
  362. /*
  363. * Relies on tsc_early_delay_calibrate() to have given us semi
  364. * usable udelay(), wait for the same 50ms we would have with
  365. * the PIT loop below.
  366. */
  367. udelay(10 * USEC_PER_MSEC);
  368. udelay(10 * USEC_PER_MSEC);
  369. udelay(10 * USEC_PER_MSEC);
  370. udelay(10 * USEC_PER_MSEC);
  371. udelay(10 * USEC_PER_MSEC);
  372. return ULONG_MAX;
  373. }
  374. /* Set the Gate high, disable speaker */
  375. outb((inb(0x61) & ~0x02) | 0x01, 0x61);
  376. /*
  377. * Setup CTC channel 2* for mode 0, (interrupt on terminal
  378. * count mode), binary count. Set the latch register to 50ms
  379. * (LSB then MSB) to begin countdown.
  380. */
  381. outb(0xb0, 0x43);
  382. outb(latch & 0xff, 0x42);
  383. outb(latch >> 8, 0x42);
  384. tsc = t1 = t2 = get_cycles();
  385. pitcnt = 0;
  386. tscmax = 0;
  387. tscmin = ULONG_MAX;
  388. while ((inb(0x61) & 0x20) == 0) {
  389. t2 = get_cycles();
  390. delta = t2 - tsc;
  391. tsc = t2;
  392. if ((unsigned long) delta < tscmin)
  393. tscmin = (unsigned int) delta;
  394. if ((unsigned long) delta > tscmax)
  395. tscmax = (unsigned int) delta;
  396. pitcnt++;
  397. }
  398. /*
  399. * Sanity checks:
  400. *
  401. * If we were not able to read the PIT more than loopmin
  402. * times, then we have been hit by a massive SMI
  403. *
  404. * If the maximum is 10 times larger than the minimum,
  405. * then we got hit by an SMI as well.
  406. */
  407. if (pitcnt < loopmin || tscmax > 10 * tscmin)
  408. return ULONG_MAX;
  409. /* Calculate the PIT value */
  410. delta = t2 - t1;
  411. do_div(delta, ms);
  412. return delta;
  413. }
  414. /*
  415. * This reads the current MSB of the PIT counter, and
  416. * checks if we are running on sufficiently fast and
  417. * non-virtualized hardware.
  418. *
  419. * Our expectations are:
  420. *
  421. * - the PIT is running at roughly 1.19MHz
  422. *
  423. * - each IO is going to take about 1us on real hardware,
  424. * but we allow it to be much faster (by a factor of 10) or
  425. * _slightly_ slower (ie we allow up to a 2us read+counter
  426. * update - anything else implies a unacceptably slow CPU
  427. * or PIT for the fast calibration to work.
  428. *
  429. * - with 256 PIT ticks to read the value, we have 214us to
  430. * see the same MSB (and overhead like doing a single TSC
  431. * read per MSB value etc).
  432. *
  433. * - We're doing 2 reads per loop (LSB, MSB), and we expect
  434. * them each to take about a microsecond on real hardware.
  435. * So we expect a count value of around 100. But we'll be
  436. * generous, and accept anything over 50.
  437. *
  438. * - if the PIT is stuck, and we see *many* more reads, we
  439. * return early (and the next caller of pit_expect_msb()
  440. * then consider it a failure when they don't see the
  441. * next expected value).
  442. *
  443. * These expectations mean that we know that we have seen the
  444. * transition from one expected value to another with a fairly
  445. * high accuracy, and we didn't miss any events. We can thus
  446. * use the TSC value at the transitions to calculate a pretty
  447. * good value for the TSC frequency.
  448. */
  449. static inline int pit_verify_msb(unsigned char val)
  450. {
  451. /* Ignore LSB */
  452. inb(0x42);
  453. return inb(0x42) == val;
  454. }
  455. static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
  456. {
  457. int count;
  458. u64 tsc = 0, prev_tsc = 0;
  459. for (count = 0; count < 50000; count++) {
  460. if (!pit_verify_msb(val))
  461. break;
  462. prev_tsc = tsc;
  463. tsc = get_cycles();
  464. }
  465. *deltap = get_cycles() - prev_tsc;
  466. *tscp = tsc;
  467. /*
  468. * We require _some_ success, but the quality control
  469. * will be based on the error terms on the TSC values.
  470. */
  471. return count > 5;
  472. }
  473. /*
  474. * How many MSB values do we want to see? We aim for
  475. * a maximum error rate of 500ppm (in practice the
  476. * real error is much smaller), but refuse to spend
  477. * more than 50ms on it.
  478. */
  479. #define MAX_QUICK_PIT_MS 50
  480. #define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
  481. static unsigned long quick_pit_calibrate(void)
  482. {
  483. int i;
  484. u64 tsc, delta;
  485. unsigned long d1, d2;
  486. if (!has_legacy_pic())
  487. return 0;
  488. /* Set the Gate high, disable speaker */
  489. outb((inb(0x61) & ~0x02) | 0x01, 0x61);
  490. /*
  491. * Counter 2, mode 0 (one-shot), binary count
  492. *
  493. * NOTE! Mode 2 decrements by two (and then the
  494. * output is flipped each time, giving the same
  495. * final output frequency as a decrement-by-one),
  496. * so mode 0 is much better when looking at the
  497. * individual counts.
  498. */
  499. outb(0xb0, 0x43);
  500. /* Start at 0xffff */
  501. outb(0xff, 0x42);
  502. outb(0xff, 0x42);
  503. /*
  504. * The PIT starts counting at the next edge, so we
  505. * need to delay for a microsecond. The easiest way
  506. * to do that is to just read back the 16-bit counter
  507. * once from the PIT.
  508. */
  509. pit_verify_msb(0);
  510. if (pit_expect_msb(0xff, &tsc, &d1)) {
  511. for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
  512. if (!pit_expect_msb(0xff-i, &delta, &d2))
  513. break;
  514. delta -= tsc;
  515. /*
  516. * Extrapolate the error and fail fast if the error will
  517. * never be below 500 ppm.
  518. */
  519. if (i == 1 &&
  520. d1 + d2 >= (delta * MAX_QUICK_PIT_ITERATIONS) >> 11)
  521. return 0;
  522. /*
  523. * Iterate until the error is less than 500 ppm
  524. */
  525. if (d1+d2 >= delta >> 11)
  526. continue;
  527. /*
  528. * Check the PIT one more time to verify that
  529. * all TSC reads were stable wrt the PIT.
  530. *
  531. * This also guarantees serialization of the
  532. * last cycle read ('d2') in pit_expect_msb.
  533. */
  534. if (!pit_verify_msb(0xfe - i))
  535. break;
  536. goto success;
  537. }
  538. }
  539. pr_info("Fast TSC calibration failed\n");
  540. return 0;
  541. success:
  542. /*
  543. * Ok, if we get here, then we've seen the
  544. * MSB of the PIT decrement 'i' times, and the
  545. * error has shrunk to less than 500 ppm.
  546. *
  547. * As a result, we can depend on there not being
  548. * any odd delays anywhere, and the TSC reads are
  549. * reliable (within the error).
  550. *
  551. * kHz = ticks / time-in-seconds / 1000;
  552. * kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
  553. * kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
  554. */
  555. delta *= PIT_TICK_RATE;
  556. do_div(delta, i*256*1000);
  557. pr_info("Fast TSC calibration using PIT\n");
  558. return delta;
  559. }
  560. /**
  561. * native_calibrate_tsc - determine TSC frequency
  562. * Determine TSC frequency via CPUID, else return 0.
  563. */
  564. unsigned long native_calibrate_tsc(void)
  565. {
  566. unsigned int eax_denominator, ebx_numerator, ecx_hz, edx;
  567. unsigned int crystal_khz;
  568. if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
  569. return 0;
  570. if (boot_cpu_data.cpuid_level < 0x15)
  571. return 0;
  572. eax_denominator = ebx_numerator = ecx_hz = edx = 0;
  573. /* CPUID 15H TSC/Crystal ratio, plus optionally Crystal Hz */
  574. cpuid(0x15, &eax_denominator, &ebx_numerator, &ecx_hz, &edx);
  575. if (ebx_numerator == 0 || eax_denominator == 0)
  576. return 0;
  577. crystal_khz = ecx_hz / 1000;
  578. /*
  579. * Denverton SoCs don't report crystal clock, and also don't support
  580. * CPUID.0x16 for the calculation below, so hardcode the 25MHz crystal
  581. * clock.
  582. */
  583. if (crystal_khz == 0 &&
  584. boot_cpu_data.x86_vfm == INTEL_ATOM_GOLDMONT_D)
  585. crystal_khz = 25000;
  586. /*
  587. * TSC frequency reported directly by CPUID is a "hardware reported"
  588. * frequency and is the most accurate one so far we have. This
  589. * is considered a known frequency.
  590. */
  591. if (crystal_khz != 0)
  592. setup_force_cpu_cap(X86_FEATURE_TSC_KNOWN_FREQ);
  593. /*
  594. * Some Intel SoCs like Skylake and Kabylake don't report the crystal
  595. * clock, but we can easily calculate it to a high degree of accuracy
  596. * by considering the crystal ratio and the CPU speed.
  597. */
  598. if (crystal_khz == 0 && boot_cpu_data.cpuid_level >= 0x16) {
  599. unsigned int eax_base_mhz, ebx, ecx, edx;
  600. cpuid(0x16, &eax_base_mhz, &ebx, &ecx, &edx);
  601. crystal_khz = eax_base_mhz * 1000 *
  602. eax_denominator / ebx_numerator;
  603. }
  604. if (crystal_khz == 0)
  605. return 0;
  606. /*
  607. * For Atom SoCs TSC is the only reliable clocksource.
  608. * Mark TSC reliable so no watchdog on it.
  609. */
  610. if (boot_cpu_data.x86_vfm == INTEL_ATOM_GOLDMONT)
  611. setup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE);
  612. #ifdef CONFIG_X86_LOCAL_APIC
  613. /*
  614. * The local APIC appears to be fed by the core crystal clock
  615. * (which sounds entirely sensible). We can set the global
  616. * lapic_timer_period here to avoid having to calibrate the APIC
  617. * timer later.
  618. */
  619. lapic_timer_period = crystal_khz * 1000 / HZ;
  620. #endif
  621. return crystal_khz * ebx_numerator / eax_denominator;
  622. }
  623. static unsigned long cpu_khz_from_cpuid(void)
  624. {
  625. unsigned int eax_base_mhz, ebx_max_mhz, ecx_bus_mhz, edx;
  626. if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
  627. return 0;
  628. if (boot_cpu_data.cpuid_level < 0x16)
  629. return 0;
  630. eax_base_mhz = ebx_max_mhz = ecx_bus_mhz = edx = 0;
  631. cpuid(0x16, &eax_base_mhz, &ebx_max_mhz, &ecx_bus_mhz, &edx);
  632. return eax_base_mhz * 1000;
  633. }
  634. /*
  635. * calibrate cpu using pit, hpet, and ptimer methods. They are available
  636. * later in boot after acpi is initialized.
  637. */
  638. static unsigned long pit_hpet_ptimer_calibrate_cpu(void)
  639. {
  640. u64 tsc1, tsc2, delta, ref1, ref2;
  641. unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
  642. unsigned long flags, latch, ms;
  643. int hpet = is_hpet_enabled(), i, loopmin;
  644. /*
  645. * Run 5 calibration loops to get the lowest frequency value
  646. * (the best estimate). We use two different calibration modes
  647. * here:
  648. *
  649. * 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
  650. * load a timeout of 50ms. We read the time right after we
  651. * started the timer and wait until the PIT count down reaches
  652. * zero. In each wait loop iteration we read the TSC and check
  653. * the delta to the previous read. We keep track of the min
  654. * and max values of that delta. The delta is mostly defined
  655. * by the IO time of the PIT access, so we can detect when
  656. * any disturbance happened between the two reads. If the
  657. * maximum time is significantly larger than the minimum time,
  658. * then we discard the result and have another try.
  659. *
  660. * 2) Reference counter. If available we use the HPET or the
  661. * PMTIMER as a reference to check the sanity of that value.
  662. * We use separate TSC readouts and check inside of the
  663. * reference read for any possible disturbance. We discard
  664. * disturbed values here as well. We do that around the PIT
  665. * calibration delay loop as we have to wait for a certain
  666. * amount of time anyway.
  667. */
  668. /* Preset PIT loop values */
  669. latch = CAL_LATCH;
  670. ms = CAL_MS;
  671. loopmin = CAL_PIT_LOOPS;
  672. for (i = 0; i < 3; i++) {
  673. unsigned long tsc_pit_khz;
  674. /*
  675. * Read the start value and the reference count of
  676. * hpet/pmtimer when available. Then do the PIT
  677. * calibration, which will take at least 50ms, and
  678. * read the end value.
  679. */
  680. local_irq_save(flags);
  681. tsc1 = tsc_read_refs(&ref1, hpet);
  682. tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
  683. tsc2 = tsc_read_refs(&ref2, hpet);
  684. local_irq_restore(flags);
  685. /* Pick the lowest PIT TSC calibration so far */
  686. tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
  687. /* hpet or pmtimer available ? */
  688. if (ref1 == ref2)
  689. continue;
  690. /* Check, whether the sampling was disturbed */
  691. if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
  692. continue;
  693. tsc2 = (tsc2 - tsc1) * 1000000LL;
  694. if (hpet)
  695. tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
  696. else
  697. tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
  698. tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
  699. /* Check the reference deviation */
  700. delta = ((u64) tsc_pit_min) * 100;
  701. do_div(delta, tsc_ref_min);
  702. /*
  703. * If both calibration results are inside a 10% window
  704. * then we can be sure, that the calibration
  705. * succeeded. We break out of the loop right away. We
  706. * use the reference value, as it is more precise.
  707. */
  708. if (delta >= 90 && delta <= 110) {
  709. pr_info("PIT calibration matches %s. %d loops\n",
  710. hpet ? "HPET" : "PMTIMER", i + 1);
  711. return tsc_ref_min;
  712. }
  713. /*
  714. * Check whether PIT failed more than once. This
  715. * happens in virtualized environments. We need to
  716. * give the virtual PC a slightly longer timeframe for
  717. * the HPET/PMTIMER to make the result precise.
  718. */
  719. if (i == 1 && tsc_pit_min == ULONG_MAX) {
  720. latch = CAL2_LATCH;
  721. ms = CAL2_MS;
  722. loopmin = CAL2_PIT_LOOPS;
  723. }
  724. }
  725. /*
  726. * Now check the results.
  727. */
  728. if (tsc_pit_min == ULONG_MAX) {
  729. /* PIT gave no useful value */
  730. pr_warn("Unable to calibrate against PIT\n");
  731. /* We don't have an alternative source, disable TSC */
  732. if (!hpet && !ref1 && !ref2) {
  733. pr_notice("No reference (HPET/PMTIMER) available\n");
  734. return 0;
  735. }
  736. /* The alternative source failed as well, disable TSC */
  737. if (tsc_ref_min == ULONG_MAX) {
  738. pr_warn("HPET/PMTIMER calibration failed\n");
  739. return 0;
  740. }
  741. /* Use the alternative source */
  742. pr_info("using %s reference calibration\n",
  743. hpet ? "HPET" : "PMTIMER");
  744. return tsc_ref_min;
  745. }
  746. /* We don't have an alternative source, use the PIT calibration value */
  747. if (!hpet && !ref1 && !ref2) {
  748. pr_info("Using PIT calibration value\n");
  749. return tsc_pit_min;
  750. }
  751. /* The alternative source failed, use the PIT calibration value */
  752. if (tsc_ref_min == ULONG_MAX) {
  753. pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
  754. return tsc_pit_min;
  755. }
  756. /*
  757. * The calibration values differ too much. In doubt, we use
  758. * the PIT value as we know that there are PMTIMERs around
  759. * running at double speed. At least we let the user know:
  760. */
  761. pr_warn("PIT calibration deviates from %s: %lu %lu\n",
  762. hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
  763. pr_info("Using PIT calibration value\n");
  764. return tsc_pit_min;
  765. }
  766. /**
  767. * native_calibrate_cpu_early - can calibrate the cpu early in boot
  768. */
  769. unsigned long native_calibrate_cpu_early(void)
  770. {
  771. unsigned long flags, fast_calibrate = cpu_khz_from_cpuid();
  772. if (!fast_calibrate)
  773. fast_calibrate = cpu_khz_from_msr();
  774. if (!fast_calibrate) {
  775. local_irq_save(flags);
  776. fast_calibrate = quick_pit_calibrate();
  777. local_irq_restore(flags);
  778. }
  779. return fast_calibrate;
  780. }
  781. /**
  782. * native_calibrate_cpu - calibrate the cpu
  783. */
  784. static unsigned long native_calibrate_cpu(void)
  785. {
  786. unsigned long tsc_freq = native_calibrate_cpu_early();
  787. if (!tsc_freq)
  788. tsc_freq = pit_hpet_ptimer_calibrate_cpu();
  789. return tsc_freq;
  790. }
  791. void recalibrate_cpu_khz(void)
  792. {
  793. #ifndef CONFIG_SMP
  794. unsigned long cpu_khz_old = cpu_khz;
  795. if (!boot_cpu_has(X86_FEATURE_TSC))
  796. return;
  797. cpu_khz = x86_platform.calibrate_cpu();
  798. tsc_khz = x86_platform.calibrate_tsc();
  799. if (tsc_khz == 0)
  800. tsc_khz = cpu_khz;
  801. else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
  802. cpu_khz = tsc_khz;
  803. cpu_data(0).loops_per_jiffy = cpufreq_scale(cpu_data(0).loops_per_jiffy,
  804. cpu_khz_old, cpu_khz);
  805. #endif
  806. }
  807. EXPORT_SYMBOL_GPL(recalibrate_cpu_khz);
  808. static unsigned long long cyc2ns_suspend;
  809. void tsc_save_sched_clock_state(void)
  810. {
  811. if (!sched_clock_stable())
  812. return;
  813. cyc2ns_suspend = sched_clock();
  814. }
  815. /*
  816. * Even on processors with invariant TSC, TSC gets reset in some the
  817. * ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
  818. * arbitrary value (still sync'd across cpu's) during resume from such sleep
  819. * states. To cope up with this, recompute the cyc2ns_offset for each cpu so
  820. * that sched_clock() continues from the point where it was left off during
  821. * suspend.
  822. */
  823. void tsc_restore_sched_clock_state(void)
  824. {
  825. unsigned long long offset;
  826. unsigned long flags;
  827. int cpu;
  828. if (!sched_clock_stable())
  829. return;
  830. local_irq_save(flags);
  831. /*
  832. * We're coming out of suspend, there's no concurrency yet; don't
  833. * bother being nice about the RCU stuff, just write to both
  834. * data fields.
  835. */
  836. this_cpu_write(cyc2ns.data[0].cyc2ns_offset, 0);
  837. this_cpu_write(cyc2ns.data[1].cyc2ns_offset, 0);
  838. offset = cyc2ns_suspend - sched_clock();
  839. for_each_possible_cpu(cpu) {
  840. per_cpu(cyc2ns.data[0].cyc2ns_offset, cpu) = offset;
  841. per_cpu(cyc2ns.data[1].cyc2ns_offset, cpu) = offset;
  842. }
  843. local_irq_restore(flags);
  844. }
  845. #ifdef CONFIG_CPU_FREQ
  846. /*
  847. * Frequency scaling support. Adjust the TSC based timer when the CPU frequency
  848. * changes.
  849. *
  850. * NOTE: On SMP the situation is not fixable in general, so simply mark the TSC
  851. * as unstable and give up in those cases.
  852. *
  853. * Should fix up last_tsc too. Currently gettimeofday in the
  854. * first tick after the change will be slightly wrong.
  855. */
  856. static unsigned int ref_freq;
  857. static unsigned long loops_per_jiffy_ref;
  858. static unsigned long tsc_khz_ref;
  859. static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
  860. void *data)
  861. {
  862. struct cpufreq_freqs *freq = data;
  863. if (num_online_cpus() > 1) {
  864. mark_tsc_unstable("cpufreq changes on SMP");
  865. return 0;
  866. }
  867. if (!ref_freq) {
  868. ref_freq = freq->old;
  869. loops_per_jiffy_ref = boot_cpu_data.loops_per_jiffy;
  870. tsc_khz_ref = tsc_khz;
  871. }
  872. if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
  873. (val == CPUFREQ_POSTCHANGE && freq->old > freq->new)) {
  874. boot_cpu_data.loops_per_jiffy =
  875. cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
  876. tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
  877. if (!(freq->flags & CPUFREQ_CONST_LOOPS))
  878. mark_tsc_unstable("cpufreq changes");
  879. set_cyc2ns_scale(tsc_khz, freq->policy->cpu, rdtsc());
  880. }
  881. return 0;
  882. }
  883. static struct notifier_block time_cpufreq_notifier_block = {
  884. .notifier_call = time_cpufreq_notifier
  885. };
  886. static int __init cpufreq_register_tsc_scaling(void)
  887. {
  888. if (!boot_cpu_has(X86_FEATURE_TSC))
  889. return 0;
  890. if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  891. return 0;
  892. cpufreq_register_notifier(&time_cpufreq_notifier_block,
  893. CPUFREQ_TRANSITION_NOTIFIER);
  894. return 0;
  895. }
  896. core_initcall(cpufreq_register_tsc_scaling);
  897. #endif /* CONFIG_CPU_FREQ */
  898. #define ART_CPUID_LEAF (0x15)
  899. #define ART_MIN_DENOMINATOR (1)
  900. /*
  901. * If ART is present detect the numerator:denominator to convert to TSC
  902. */
  903. static void __init detect_art(void)
  904. {
  905. unsigned int unused;
  906. if (boot_cpu_data.cpuid_level < ART_CPUID_LEAF)
  907. return;
  908. /*
  909. * Don't enable ART in a VM, non-stop TSC and TSC_ADJUST required,
  910. * and the TSC counter resets must not occur asynchronously.
  911. */
  912. if (boot_cpu_has(X86_FEATURE_HYPERVISOR) ||
  913. !boot_cpu_has(X86_FEATURE_NONSTOP_TSC) ||
  914. !boot_cpu_has(X86_FEATURE_TSC_ADJUST) ||
  915. tsc_async_resets)
  916. return;
  917. cpuid(ART_CPUID_LEAF, &art_base_clk.denominator,
  918. &art_base_clk.numerator, &art_base_clk.freq_khz, &unused);
  919. art_base_clk.freq_khz /= KHZ;
  920. if (art_base_clk.denominator < ART_MIN_DENOMINATOR)
  921. return;
  922. rdmsrl(MSR_IA32_TSC_ADJUST, art_base_clk.offset);
  923. /* Make this sticky over multiple CPU init calls */
  924. setup_force_cpu_cap(X86_FEATURE_ART);
  925. }
  926. /* clocksource code */
  927. static void tsc_resume(struct clocksource *cs)
  928. {
  929. tsc_verify_tsc_adjust(true);
  930. }
  931. /*
  932. * We used to compare the TSC to the cycle_last value in the clocksource
  933. * structure to avoid a nasty time-warp. This can be observed in a
  934. * very small window right after one CPU updated cycle_last under
  935. * xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
  936. * is smaller than the cycle_last reference value due to a TSC which
  937. * is slightly behind. This delta is nowhere else observable, but in
  938. * that case it results in a forward time jump in the range of hours
  939. * due to the unsigned delta calculation of the time keeping core
  940. * code, which is necessary to support wrapping clocksources like pm
  941. * timer.
  942. *
  943. * This sanity check is now done in the core timekeeping code.
  944. * checking the result of read_tsc() - cycle_last for being negative.
  945. * That works because CLOCKSOURCE_MASK(64) does not mask out any bit.
  946. */
  947. static u64 read_tsc(struct clocksource *cs)
  948. {
  949. return (u64)rdtsc_ordered();
  950. }
  951. static void tsc_cs_mark_unstable(struct clocksource *cs)
  952. {
  953. if (tsc_unstable)
  954. return;
  955. tsc_unstable = 1;
  956. if (using_native_sched_clock())
  957. clear_sched_clock_stable();
  958. disable_sched_clock_irqtime();
  959. pr_info("Marking TSC unstable due to clocksource watchdog\n");
  960. }
  961. static void tsc_cs_tick_stable(struct clocksource *cs)
  962. {
  963. if (tsc_unstable)
  964. return;
  965. if (using_native_sched_clock())
  966. sched_clock_tick_stable();
  967. }
  968. static int tsc_cs_enable(struct clocksource *cs)
  969. {
  970. vclocks_set_used(VDSO_CLOCKMODE_TSC);
  971. return 0;
  972. }
  973. /*
  974. * .mask MUST be CLOCKSOURCE_MASK(64). See comment above read_tsc()
  975. */
  976. static struct clocksource clocksource_tsc_early = {
  977. .name = "tsc-early",
  978. .rating = 299,
  979. .uncertainty_margin = 32 * NSEC_PER_MSEC,
  980. .read = read_tsc,
  981. .mask = CLOCKSOURCE_MASK(64),
  982. .flags = CLOCK_SOURCE_IS_CONTINUOUS |
  983. CLOCK_SOURCE_MUST_VERIFY,
  984. .id = CSID_X86_TSC_EARLY,
  985. .vdso_clock_mode = VDSO_CLOCKMODE_TSC,
  986. .enable = tsc_cs_enable,
  987. .resume = tsc_resume,
  988. .mark_unstable = tsc_cs_mark_unstable,
  989. .tick_stable = tsc_cs_tick_stable,
  990. .list = LIST_HEAD_INIT(clocksource_tsc_early.list),
  991. };
  992. /*
  993. * Must mark VALID_FOR_HRES early such that when we unregister tsc_early
  994. * this one will immediately take over. We will only register if TSC has
  995. * been found good.
  996. */
  997. static struct clocksource clocksource_tsc = {
  998. .name = "tsc",
  999. .rating = 300,
  1000. .read = read_tsc,
  1001. .mask = CLOCKSOURCE_MASK(64),
  1002. .flags = CLOCK_SOURCE_IS_CONTINUOUS |
  1003. CLOCK_SOURCE_VALID_FOR_HRES |
  1004. CLOCK_SOURCE_MUST_VERIFY |
  1005. CLOCK_SOURCE_VERIFY_PERCPU,
  1006. .id = CSID_X86_TSC,
  1007. .vdso_clock_mode = VDSO_CLOCKMODE_TSC,
  1008. .enable = tsc_cs_enable,
  1009. .resume = tsc_resume,
  1010. .mark_unstable = tsc_cs_mark_unstable,
  1011. .tick_stable = tsc_cs_tick_stable,
  1012. .list = LIST_HEAD_INIT(clocksource_tsc.list),
  1013. };
  1014. void mark_tsc_unstable(char *reason)
  1015. {
  1016. if (tsc_unstable)
  1017. return;
  1018. tsc_unstable = 1;
  1019. if (using_native_sched_clock())
  1020. clear_sched_clock_stable();
  1021. disable_sched_clock_irqtime();
  1022. pr_info("Marking TSC unstable due to %s\n", reason);
  1023. clocksource_mark_unstable(&clocksource_tsc_early);
  1024. clocksource_mark_unstable(&clocksource_tsc);
  1025. }
  1026. EXPORT_SYMBOL_GPL(mark_tsc_unstable);
  1027. static void __init tsc_disable_clocksource_watchdog(void)
  1028. {
  1029. clocksource_tsc_early.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
  1030. clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
  1031. }
  1032. bool tsc_clocksource_watchdog_disabled(void)
  1033. {
  1034. return !(clocksource_tsc.flags & CLOCK_SOURCE_MUST_VERIFY) &&
  1035. tsc_as_watchdog && !no_tsc_watchdog;
  1036. }
  1037. static void __init check_system_tsc_reliable(void)
  1038. {
  1039. #if defined(CONFIG_MGEODEGX1) || defined(CONFIG_MGEODE_LX) || defined(CONFIG_X86_GENERIC)
  1040. if (is_geode_lx()) {
  1041. /* RTSC counts during suspend */
  1042. #define RTSC_SUSP 0x100
  1043. unsigned long res_low, res_high;
  1044. rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
  1045. /* Geode_LX - the OLPC CPU has a very reliable TSC */
  1046. if (res_low & RTSC_SUSP)
  1047. tsc_clocksource_reliable = 1;
  1048. }
  1049. #endif
  1050. if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
  1051. tsc_clocksource_reliable = 1;
  1052. /*
  1053. * Disable the clocksource watchdog when the system has:
  1054. * - TSC running at constant frequency
  1055. * - TSC which does not stop in C-States
  1056. * - the TSC_ADJUST register which allows to detect even minimal
  1057. * modifications
  1058. * - not more than four packages
  1059. */
  1060. if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC) &&
  1061. boot_cpu_has(X86_FEATURE_NONSTOP_TSC) &&
  1062. boot_cpu_has(X86_FEATURE_TSC_ADJUST) &&
  1063. topology_max_packages() <= 4)
  1064. tsc_disable_clocksource_watchdog();
  1065. }
  1066. /*
  1067. * Make an educated guess if the TSC is trustworthy and synchronized
  1068. * over all CPUs.
  1069. */
  1070. int unsynchronized_tsc(void)
  1071. {
  1072. if (!boot_cpu_has(X86_FEATURE_TSC) || tsc_unstable)
  1073. return 1;
  1074. #ifdef CONFIG_SMP
  1075. if (apic_is_clustered_box())
  1076. return 1;
  1077. #endif
  1078. if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
  1079. return 0;
  1080. if (tsc_clocksource_reliable)
  1081. return 0;
  1082. /*
  1083. * Intel systems are normally all synchronized.
  1084. * Exceptions must mark TSC as unstable:
  1085. */
  1086. if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
  1087. /* assume multi socket systems are not synchronized: */
  1088. if (topology_max_packages() > 1)
  1089. return 1;
  1090. }
  1091. return 0;
  1092. }
  1093. static void tsc_refine_calibration_work(struct work_struct *work);
  1094. static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
  1095. /**
  1096. * tsc_refine_calibration_work - Further refine tsc freq calibration
  1097. * @work: ignored.
  1098. *
  1099. * This functions uses delayed work over a period of a
  1100. * second to further refine the TSC freq value. Since this is
  1101. * timer based, instead of loop based, we don't block the boot
  1102. * process while this longer calibration is done.
  1103. *
  1104. * If there are any calibration anomalies (too many SMIs, etc),
  1105. * or the refined calibration is off by 1% of the fast early
  1106. * calibration, we throw out the new calibration and use the
  1107. * early calibration.
  1108. */
  1109. static void tsc_refine_calibration_work(struct work_struct *work)
  1110. {
  1111. static u64 tsc_start = ULLONG_MAX, ref_start;
  1112. static int hpet;
  1113. u64 tsc_stop, ref_stop, delta;
  1114. unsigned long freq;
  1115. int cpu;
  1116. /* Don't bother refining TSC on unstable systems */
  1117. if (tsc_unstable)
  1118. goto unreg;
  1119. /*
  1120. * Since the work is started early in boot, we may be
  1121. * delayed the first time we expire. So set the workqueue
  1122. * again once we know timers are working.
  1123. */
  1124. if (tsc_start == ULLONG_MAX) {
  1125. restart:
  1126. /*
  1127. * Only set hpet once, to avoid mixing hardware
  1128. * if the hpet becomes enabled later.
  1129. */
  1130. hpet = is_hpet_enabled();
  1131. tsc_start = tsc_read_refs(&ref_start, hpet);
  1132. schedule_delayed_work(&tsc_irqwork, HZ);
  1133. return;
  1134. }
  1135. tsc_stop = tsc_read_refs(&ref_stop, hpet);
  1136. /* hpet or pmtimer available ? */
  1137. if (ref_start == ref_stop)
  1138. goto out;
  1139. /* Check, whether the sampling was disturbed */
  1140. if (tsc_stop == ULLONG_MAX)
  1141. goto restart;
  1142. delta = tsc_stop - tsc_start;
  1143. delta *= 1000000LL;
  1144. if (hpet)
  1145. freq = calc_hpet_ref(delta, ref_start, ref_stop);
  1146. else
  1147. freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
  1148. /* Will hit this only if tsc_force_recalibrate has been set */
  1149. if (boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ)) {
  1150. /* Warn if the deviation exceeds 500 ppm */
  1151. if (abs(tsc_khz - freq) > (tsc_khz >> 11)) {
  1152. pr_warn("Warning: TSC freq calibrated by CPUID/MSR differs from what is calibrated by HW timer, please check with vendor!!\n");
  1153. pr_info("Previous calibrated TSC freq:\t %lu.%03lu MHz\n",
  1154. (unsigned long)tsc_khz / 1000,
  1155. (unsigned long)tsc_khz % 1000);
  1156. }
  1157. pr_info("TSC freq recalibrated by [%s]:\t %lu.%03lu MHz\n",
  1158. hpet ? "HPET" : "PM_TIMER",
  1159. (unsigned long)freq / 1000,
  1160. (unsigned long)freq % 1000);
  1161. return;
  1162. }
  1163. /* Make sure we're within 1% */
  1164. if (abs(tsc_khz - freq) > tsc_khz/100)
  1165. goto out;
  1166. tsc_khz = freq;
  1167. pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
  1168. (unsigned long)tsc_khz / 1000,
  1169. (unsigned long)tsc_khz % 1000);
  1170. /* Inform the TSC deadline clockevent devices about the recalibration */
  1171. lapic_update_tsc_freq();
  1172. /* Update the sched_clock() rate to match the clocksource one */
  1173. for_each_possible_cpu(cpu)
  1174. set_cyc2ns_scale(tsc_khz, cpu, tsc_stop);
  1175. out:
  1176. if (tsc_unstable)
  1177. goto unreg;
  1178. if (boot_cpu_has(X86_FEATURE_ART)) {
  1179. have_art = true;
  1180. clocksource_tsc.base = &art_base_clk;
  1181. }
  1182. clocksource_register_khz(&clocksource_tsc, tsc_khz);
  1183. unreg:
  1184. clocksource_unregister(&clocksource_tsc_early);
  1185. }
  1186. static int __init init_tsc_clocksource(void)
  1187. {
  1188. if (!boot_cpu_has(X86_FEATURE_TSC) || !tsc_khz)
  1189. return 0;
  1190. if (tsc_unstable) {
  1191. clocksource_unregister(&clocksource_tsc_early);
  1192. return 0;
  1193. }
  1194. if (boot_cpu_has(X86_FEATURE_NONSTOP_TSC_S3))
  1195. clocksource_tsc.flags |= CLOCK_SOURCE_SUSPEND_NONSTOP;
  1196. /*
  1197. * When TSC frequency is known (retrieved via MSR or CPUID), we skip
  1198. * the refined calibration and directly register it as a clocksource.
  1199. */
  1200. if (boot_cpu_has(X86_FEATURE_TSC_KNOWN_FREQ)) {
  1201. if (boot_cpu_has(X86_FEATURE_ART)) {
  1202. have_art = true;
  1203. clocksource_tsc.base = &art_base_clk;
  1204. }
  1205. clocksource_register_khz(&clocksource_tsc, tsc_khz);
  1206. clocksource_unregister(&clocksource_tsc_early);
  1207. if (!tsc_force_recalibrate)
  1208. return 0;
  1209. }
  1210. schedule_delayed_work(&tsc_irqwork, 0);
  1211. return 0;
  1212. }
  1213. /*
  1214. * We use device_initcall here, to ensure we run after the hpet
  1215. * is fully initialized, which may occur at fs_initcall time.
  1216. */
  1217. device_initcall(init_tsc_clocksource);
  1218. static bool __init determine_cpu_tsc_frequencies(bool early)
  1219. {
  1220. /* Make sure that cpu and tsc are not already calibrated */
  1221. WARN_ON(cpu_khz || tsc_khz);
  1222. if (early) {
  1223. cpu_khz = x86_platform.calibrate_cpu();
  1224. if (tsc_early_khz) {
  1225. tsc_khz = tsc_early_khz;
  1226. } else {
  1227. tsc_khz = x86_platform.calibrate_tsc();
  1228. clocksource_tsc.freq_khz = tsc_khz;
  1229. }
  1230. } else {
  1231. /* We should not be here with non-native cpu calibration */
  1232. WARN_ON(x86_platform.calibrate_cpu != native_calibrate_cpu);
  1233. cpu_khz = pit_hpet_ptimer_calibrate_cpu();
  1234. }
  1235. /*
  1236. * Trust non-zero tsc_khz as authoritative,
  1237. * and use it to sanity check cpu_khz,
  1238. * which will be off if system timer is off.
  1239. */
  1240. if (tsc_khz == 0)
  1241. tsc_khz = cpu_khz;
  1242. else if (abs(cpu_khz - tsc_khz) * 10 > tsc_khz)
  1243. cpu_khz = tsc_khz;
  1244. if (tsc_khz == 0)
  1245. return false;
  1246. pr_info("Detected %lu.%03lu MHz processor\n",
  1247. (unsigned long)cpu_khz / KHZ,
  1248. (unsigned long)cpu_khz % KHZ);
  1249. if (cpu_khz != tsc_khz) {
  1250. pr_info("Detected %lu.%03lu MHz TSC",
  1251. (unsigned long)tsc_khz / KHZ,
  1252. (unsigned long)tsc_khz % KHZ);
  1253. }
  1254. return true;
  1255. }
  1256. static unsigned long __init get_loops_per_jiffy(void)
  1257. {
  1258. u64 lpj = (u64)tsc_khz * KHZ;
  1259. do_div(lpj, HZ);
  1260. return lpj;
  1261. }
  1262. static void __init tsc_enable_sched_clock(void)
  1263. {
  1264. loops_per_jiffy = get_loops_per_jiffy();
  1265. use_tsc_delay();
  1266. /* Sanitize TSC ADJUST before cyc2ns gets initialized */
  1267. tsc_store_and_check_tsc_adjust(true);
  1268. cyc2ns_init_boot_cpu();
  1269. static_branch_enable(&__use_tsc);
  1270. }
  1271. void __init tsc_early_init(void)
  1272. {
  1273. if (!boot_cpu_has(X86_FEATURE_TSC))
  1274. return;
  1275. /* Don't change UV TSC multi-chassis synchronization */
  1276. if (is_early_uv_system())
  1277. return;
  1278. if (!determine_cpu_tsc_frequencies(true))
  1279. return;
  1280. tsc_enable_sched_clock();
  1281. }
  1282. void __init tsc_init(void)
  1283. {
  1284. if (!cpu_feature_enabled(X86_FEATURE_TSC)) {
  1285. setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
  1286. return;
  1287. }
  1288. /*
  1289. * native_calibrate_cpu_early can only calibrate using methods that are
  1290. * available early in boot.
  1291. */
  1292. if (x86_platform.calibrate_cpu == native_calibrate_cpu_early)
  1293. x86_platform.calibrate_cpu = native_calibrate_cpu;
  1294. if (!tsc_khz) {
  1295. /* We failed to determine frequencies earlier, try again */
  1296. if (!determine_cpu_tsc_frequencies(false)) {
  1297. mark_tsc_unstable("could not calculate TSC khz");
  1298. setup_clear_cpu_cap(X86_FEATURE_TSC_DEADLINE_TIMER);
  1299. return;
  1300. }
  1301. tsc_enable_sched_clock();
  1302. }
  1303. cyc2ns_init_secondary_cpus();
  1304. if (!no_sched_irq_time)
  1305. enable_sched_clock_irqtime();
  1306. lpj_fine = get_loops_per_jiffy();
  1307. check_system_tsc_reliable();
  1308. if (unsynchronized_tsc()) {
  1309. mark_tsc_unstable("TSCs unsynchronized");
  1310. return;
  1311. }
  1312. if (tsc_clocksource_reliable || no_tsc_watchdog)
  1313. tsc_disable_clocksource_watchdog();
  1314. clocksource_register_khz(&clocksource_tsc_early, tsc_khz);
  1315. detect_art();
  1316. }
  1317. #ifdef CONFIG_SMP
  1318. /*
  1319. * Check whether existing calibration data can be reused.
  1320. */
  1321. unsigned long calibrate_delay_is_known(void)
  1322. {
  1323. int sibling, cpu = smp_processor_id();
  1324. int constant_tsc = cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC);
  1325. const struct cpumask *mask = topology_core_cpumask(cpu);
  1326. /*
  1327. * If TSC has constant frequency and TSC is synchronized across
  1328. * sockets then reuse CPU0 calibration.
  1329. */
  1330. if (constant_tsc && !tsc_unstable)
  1331. return cpu_data(0).loops_per_jiffy;
  1332. /*
  1333. * If TSC has constant frequency and TSC is not synchronized across
  1334. * sockets and this is not the first CPU in the socket, then reuse
  1335. * the calibration value of an already online CPU on that socket.
  1336. *
  1337. * This assumes that CONSTANT_TSC is consistent for all CPUs in a
  1338. * socket.
  1339. */
  1340. if (!constant_tsc || !mask)
  1341. return 0;
  1342. sibling = cpumask_any_but(mask, cpu);
  1343. if (sibling < nr_cpu_ids)
  1344. return cpu_data(sibling).loops_per_jiffy;
  1345. return 0;
  1346. }
  1347. #endif