tsc.c 34 KB

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