tsc.c 32 KB

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