tsc.c 37 KB

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