tsc.c 35 KB

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