tsc.c 31 KB

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