clock.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * sched_clock() for unstable CPU clocks
  4. *
  5. * Copyright (C) 2008 Red Hat, Inc., Peter Zijlstra
  6. *
  7. * Updates and enhancements:
  8. * Copyright (C) 2008 Red Hat, Inc. Steven Rostedt <srostedt@redhat.com>
  9. *
  10. * Based on code by:
  11. * Ingo Molnar <mingo@redhat.com>
  12. * Guillaume Chazarain <guichaz@gmail.com>
  13. *
  14. *
  15. * What this file implements:
  16. *
  17. * cpu_clock(i) provides a fast (execution time) high resolution
  18. * clock with bounded drift between CPUs. The value of cpu_clock(i)
  19. * is monotonic for constant i. The timestamp returned is in nanoseconds.
  20. *
  21. * ######################### BIG FAT WARNING ##########################
  22. * # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
  23. * # go backwards !! #
  24. * ####################################################################
  25. *
  26. * There is no strict promise about the base, although it tends to start
  27. * at 0 on boot (but people really shouldn't rely on that).
  28. *
  29. * cpu_clock(i) -- can be used from any context, including NMI.
  30. * local_clock() -- is cpu_clock() on the current CPU.
  31. *
  32. * sched_clock_cpu(i)
  33. *
  34. * How it is implemented:
  35. *
  36. * The implementation either uses sched_clock() when
  37. * !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK, which means in that case the
  38. * sched_clock() is assumed to provide these properties (mostly it means
  39. * the architecture provides a globally synchronized highres time source).
  40. *
  41. * Otherwise it tries to create a semi stable clock from a mixture of other
  42. * clocks, including:
  43. *
  44. * - GTOD (clock monotonic)
  45. * - sched_clock()
  46. * - explicit idle events
  47. *
  48. * We use GTOD as base and use sched_clock() deltas to improve resolution. The
  49. * deltas are filtered to provide monotonicity and keeping it within an
  50. * expected window.
  51. *
  52. * Furthermore, explicit sleep and wakeup hooks allow us to account for time
  53. * that is otherwise invisible (TSC gets stopped).
  54. *
  55. */
  56. /*
  57. * Scheduler clock - returns current time in nanosec units.
  58. * This is default implementation.
  59. * Architectures and sub-architectures can override this.
  60. */
  61. notrace unsigned long long __weak sched_clock(void)
  62. {
  63. return (unsigned long long)(jiffies - INITIAL_JIFFIES)
  64. * (NSEC_PER_SEC / HZ);
  65. }
  66. EXPORT_SYMBOL_GPL(sched_clock);
  67. static DEFINE_STATIC_KEY_FALSE(sched_clock_running);
  68. #ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
  69. /*
  70. * We must start with !__sched_clock_stable because the unstable -> stable
  71. * transition is accurate, while the stable -> unstable transition is not.
  72. *
  73. * Similarly we start with __sched_clock_stable_early, thereby assuming we
  74. * will become stable, such that there's only a single 1 -> 0 transition.
  75. */
  76. static DEFINE_STATIC_KEY_FALSE(__sched_clock_stable);
  77. static int __sched_clock_stable_early = 1;
  78. /*
  79. * We want: ktime_get_ns() + __gtod_offset == sched_clock() + __sched_clock_offset
  80. */
  81. __read_mostly u64 __sched_clock_offset;
  82. static __read_mostly u64 __gtod_offset;
  83. struct sched_clock_data {
  84. u64 tick_raw;
  85. u64 tick_gtod;
  86. u64 clock;
  87. };
  88. static DEFINE_PER_CPU_SHARED_ALIGNED(struct sched_clock_data, sched_clock_data);
  89. static __always_inline struct sched_clock_data *this_scd(void)
  90. {
  91. return this_cpu_ptr(&sched_clock_data);
  92. }
  93. notrace static inline struct sched_clock_data *cpu_sdc(int cpu)
  94. {
  95. return &per_cpu(sched_clock_data, cpu);
  96. }
  97. notrace int sched_clock_stable(void)
  98. {
  99. return static_branch_likely(&__sched_clock_stable);
  100. }
  101. notrace static void __scd_stamp(struct sched_clock_data *scd)
  102. {
  103. scd->tick_gtod = ktime_get_ns();
  104. scd->tick_raw = sched_clock();
  105. }
  106. notrace static void __set_sched_clock_stable(void)
  107. {
  108. struct sched_clock_data *scd;
  109. /*
  110. * Since we're still unstable and the tick is already running, we have
  111. * to disable IRQs in order to get a consistent scd->tick* reading.
  112. */
  113. local_irq_disable();
  114. scd = this_scd();
  115. /*
  116. * Attempt to make the (initial) unstable->stable transition continuous.
  117. */
  118. __sched_clock_offset = (scd->tick_gtod + __gtod_offset) - (scd->tick_raw);
  119. local_irq_enable();
  120. printk(KERN_INFO "sched_clock: Marking stable (%lld, %lld)->(%lld, %lld)\n",
  121. scd->tick_gtod, __gtod_offset,
  122. scd->tick_raw, __sched_clock_offset);
  123. static_branch_enable(&__sched_clock_stable);
  124. tick_dep_clear(TICK_DEP_BIT_CLOCK_UNSTABLE);
  125. }
  126. /*
  127. * If we ever get here, we're screwed, because we found out -- typically after
  128. * the fact -- that TSC wasn't good. This means all our clocksources (including
  129. * ktime) could have reported wrong values.
  130. *
  131. * What we do here is an attempt to fix up and continue sort of where we left
  132. * off in a coherent manner.
  133. *
  134. * The only way to fully avoid random clock jumps is to boot with:
  135. * "tsc=unstable".
  136. */
  137. notrace static void __sched_clock_work(struct work_struct *work)
  138. {
  139. struct sched_clock_data *scd;
  140. int cpu;
  141. /* take a current timestamp and set 'now' */
  142. preempt_disable();
  143. scd = this_scd();
  144. __scd_stamp(scd);
  145. scd->clock = scd->tick_gtod + __gtod_offset;
  146. preempt_enable();
  147. /* clone to all CPUs */
  148. for_each_possible_cpu(cpu)
  149. per_cpu(sched_clock_data, cpu) = *scd;
  150. printk(KERN_WARNING "TSC found unstable after boot, most likely due to broken BIOS. Use 'tsc=unstable'.\n");
  151. printk(KERN_INFO "sched_clock: Marking unstable (%lld, %lld)<-(%lld, %lld)\n",
  152. scd->tick_gtod, __gtod_offset,
  153. scd->tick_raw, __sched_clock_offset);
  154. static_branch_disable(&__sched_clock_stable);
  155. }
  156. static DECLARE_WORK(sched_clock_work, __sched_clock_work);
  157. notrace static void __clear_sched_clock_stable(void)
  158. {
  159. if (!sched_clock_stable())
  160. return;
  161. tick_dep_set(TICK_DEP_BIT_CLOCK_UNSTABLE);
  162. schedule_work(&sched_clock_work);
  163. }
  164. notrace void clear_sched_clock_stable(void)
  165. {
  166. __sched_clock_stable_early = 0;
  167. smp_mb(); /* matches sched_clock_init_late() */
  168. if (static_key_count(&sched_clock_running.key) == 2)
  169. __clear_sched_clock_stable();
  170. }
  171. notrace static void __sched_clock_gtod_offset(void)
  172. {
  173. struct sched_clock_data *scd = this_scd();
  174. __scd_stamp(scd);
  175. __gtod_offset = (scd->tick_raw + __sched_clock_offset) - scd->tick_gtod;
  176. }
  177. void __init sched_clock_init(void)
  178. {
  179. /*
  180. * Set __gtod_offset such that once we mark sched_clock_running,
  181. * sched_clock_tick() continues where sched_clock() left off.
  182. *
  183. * Even if TSC is buggered, we're still UP at this point so it
  184. * can't really be out of sync.
  185. */
  186. local_irq_disable();
  187. __sched_clock_gtod_offset();
  188. local_irq_enable();
  189. static_branch_inc(&sched_clock_running);
  190. }
  191. /*
  192. * We run this as late_initcall() such that it runs after all built-in drivers,
  193. * notably: acpi_processor and intel_idle, which can mark the TSC as unstable.
  194. */
  195. static int __init sched_clock_init_late(void)
  196. {
  197. static_branch_inc(&sched_clock_running);
  198. /*
  199. * Ensure that it is impossible to not do a static_key update.
  200. *
  201. * Either {set,clear}_sched_clock_stable() must see sched_clock_running
  202. * and do the update, or we must see their __sched_clock_stable_early
  203. * and do the update, or both.
  204. */
  205. smp_mb(); /* matches {set,clear}_sched_clock_stable() */
  206. if (__sched_clock_stable_early)
  207. __set_sched_clock_stable();
  208. return 0;
  209. }
  210. late_initcall(sched_clock_init_late);
  211. /*
  212. * min, max except they take wrapping into account
  213. */
  214. static __always_inline u64 wrap_min(u64 x, u64 y)
  215. {
  216. return (s64)(x - y) < 0 ? x : y;
  217. }
  218. static __always_inline u64 wrap_max(u64 x, u64 y)
  219. {
  220. return (s64)(x - y) > 0 ? x : y;
  221. }
  222. /*
  223. * update the percpu scd from the raw @now value
  224. *
  225. * - filter out backward motion
  226. * - use the GTOD tick value to create a window to filter crazy TSC values
  227. */
  228. static __always_inline u64 sched_clock_local(struct sched_clock_data *scd)
  229. {
  230. u64 now, clock, old_clock, min_clock, max_clock, gtod;
  231. s64 delta;
  232. again:
  233. now = sched_clock_noinstr();
  234. delta = now - scd->tick_raw;
  235. if (unlikely(delta < 0))
  236. delta = 0;
  237. old_clock = scd->clock;
  238. /*
  239. * scd->clock = clamp(scd->tick_gtod + delta,
  240. * max(scd->tick_gtod, scd->clock),
  241. * scd->tick_gtod + TICK_NSEC);
  242. */
  243. gtod = scd->tick_gtod + __gtod_offset;
  244. clock = gtod + delta;
  245. min_clock = wrap_max(gtod, old_clock);
  246. max_clock = wrap_max(old_clock, gtod + TICK_NSEC);
  247. clock = wrap_max(clock, min_clock);
  248. clock = wrap_min(clock, max_clock);
  249. if (!raw_try_cmpxchg64(&scd->clock, &old_clock, clock))
  250. goto again;
  251. return clock;
  252. }
  253. noinstr u64 local_clock_noinstr(void)
  254. {
  255. u64 clock;
  256. if (static_branch_likely(&__sched_clock_stable))
  257. return sched_clock_noinstr() + __sched_clock_offset;
  258. if (!static_branch_likely(&sched_clock_running))
  259. return sched_clock_noinstr();
  260. clock = sched_clock_local(this_scd());
  261. return clock;
  262. }
  263. u64 local_clock(void)
  264. {
  265. u64 now;
  266. preempt_disable_notrace();
  267. now = local_clock_noinstr();
  268. preempt_enable_notrace();
  269. return now;
  270. }
  271. EXPORT_SYMBOL_GPL(local_clock);
  272. static notrace u64 sched_clock_remote(struct sched_clock_data *scd)
  273. {
  274. struct sched_clock_data *my_scd = this_scd();
  275. u64 this_clock, remote_clock;
  276. u64 *ptr, old_val, val;
  277. #if BITS_PER_LONG != 64
  278. again:
  279. /*
  280. * Careful here: The local and the remote clock values need to
  281. * be read out atomic as we need to compare the values and
  282. * then update either the local or the remote side. So the
  283. * cmpxchg64 below only protects one readout.
  284. *
  285. * We must reread via sched_clock_local() in the retry case on
  286. * 32-bit kernels as an NMI could use sched_clock_local() via the
  287. * tracer and hit between the readout of
  288. * the low 32-bit and the high 32-bit portion.
  289. */
  290. this_clock = sched_clock_local(my_scd);
  291. /*
  292. * We must enforce atomic readout on 32-bit, otherwise the
  293. * update on the remote CPU can hit in between the readout of
  294. * the low 32-bit and the high 32-bit portion.
  295. */
  296. remote_clock = cmpxchg64(&scd->clock, 0, 0);
  297. #else
  298. /*
  299. * On 64-bit kernels the read of [my]scd->clock is atomic versus the
  300. * update, so we can avoid the above 32-bit dance.
  301. */
  302. sched_clock_local(my_scd);
  303. again:
  304. this_clock = my_scd->clock;
  305. remote_clock = scd->clock;
  306. #endif
  307. /*
  308. * Use the opportunity that we have both locks
  309. * taken to couple the two clocks: we take the
  310. * larger time as the latest time for both
  311. * runqueues. (this creates monotonic movement)
  312. */
  313. if (likely((s64)(remote_clock - this_clock) < 0)) {
  314. ptr = &scd->clock;
  315. old_val = remote_clock;
  316. val = this_clock;
  317. } else {
  318. /*
  319. * Should be rare, but possible:
  320. */
  321. ptr = &my_scd->clock;
  322. old_val = this_clock;
  323. val = remote_clock;
  324. }
  325. if (!try_cmpxchg64(ptr, &old_val, val))
  326. goto again;
  327. return val;
  328. }
  329. /*
  330. * Similar to cpu_clock(), but requires local IRQs to be disabled.
  331. *
  332. * See cpu_clock().
  333. */
  334. notrace u64 sched_clock_cpu(int cpu)
  335. {
  336. struct sched_clock_data *scd;
  337. u64 clock;
  338. if (sched_clock_stable())
  339. return sched_clock() + __sched_clock_offset;
  340. if (!static_branch_likely(&sched_clock_running))
  341. return sched_clock();
  342. preempt_disable_notrace();
  343. scd = cpu_sdc(cpu);
  344. if (cpu != smp_processor_id())
  345. clock = sched_clock_remote(scd);
  346. else
  347. clock = sched_clock_local(scd);
  348. preempt_enable_notrace();
  349. return clock;
  350. }
  351. EXPORT_SYMBOL_GPL(sched_clock_cpu);
  352. notrace void sched_clock_tick(void)
  353. {
  354. struct sched_clock_data *scd;
  355. if (sched_clock_stable())
  356. return;
  357. if (!static_branch_likely(&sched_clock_running))
  358. return;
  359. lockdep_assert_irqs_disabled();
  360. scd = this_scd();
  361. __scd_stamp(scd);
  362. sched_clock_local(scd);
  363. }
  364. notrace void sched_clock_tick_stable(void)
  365. {
  366. if (!sched_clock_stable())
  367. return;
  368. /*
  369. * Called under watchdog_lock.
  370. *
  371. * The watchdog just found this TSC to (still) be stable, so now is a
  372. * good moment to update our __gtod_offset. Because once we find the
  373. * TSC to be unstable, any computation will be computing crap.
  374. */
  375. local_irq_disable();
  376. __sched_clock_gtod_offset();
  377. local_irq_enable();
  378. }
  379. /*
  380. * We are going deep-idle (IRQs are disabled):
  381. */
  382. notrace void sched_clock_idle_sleep_event(void)
  383. {
  384. sched_clock_cpu(smp_processor_id());
  385. }
  386. EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
  387. /*
  388. * We just idled; resync with ktime.
  389. */
  390. notrace void sched_clock_idle_wakeup_event(void)
  391. {
  392. unsigned long flags;
  393. if (sched_clock_stable())
  394. return;
  395. if (unlikely(timekeeping_suspended))
  396. return;
  397. local_irq_save(flags);
  398. sched_clock_tick();
  399. local_irq_restore(flags);
  400. }
  401. EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
  402. #else /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
  403. void __init sched_clock_init(void)
  404. {
  405. static_branch_inc(&sched_clock_running);
  406. local_irq_disable();
  407. generic_sched_clock_init();
  408. local_irq_enable();
  409. }
  410. notrace u64 sched_clock_cpu(int cpu)
  411. {
  412. if (!static_branch_likely(&sched_clock_running))
  413. return 0;
  414. return sched_clock();
  415. }
  416. #endif /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
  417. /*
  418. * Running clock - returns the time that has elapsed while a guest has been
  419. * running.
  420. * On a guest this value should be local_clock minus the time the guest was
  421. * suspended by the hypervisor (for any reason).
  422. * On bare metal this function should return the same as local_clock.
  423. * Architectures and sub-architectures can override this.
  424. */
  425. notrace u64 __weak running_clock(void)
  426. {
  427. return local_clock();
  428. }