tsc.c 38 KB

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