tsc.c 40 KB

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