clocksource.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * This file contains the functions which manage clocksource drivers.
  4. *
  5. * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
  6. */
  7. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  8. #include <linux/device.h>
  9. #include <linux/clocksource.h>
  10. #include <linux/init.h>
  11. #include <linux/module.h>
  12. #include <linux/sched.h> /* for spin_unlock_irq() using preempt_count() m68k */
  13. #include <linux/tick.h>
  14. #include <linux/kthread.h>
  15. #include <linux/prandom.h>
  16. #include <linux/cpu.h>
  17. #include "tick-internal.h"
  18. #include "timekeeping_internal.h"
  19. static noinline u64 cycles_to_nsec_safe(struct clocksource *cs, u64 start, u64 end)
  20. {
  21. u64 delta = clocksource_delta(end, start, cs->mask, cs->max_raw_delta);
  22. if (likely(delta < cs->max_cycles))
  23. return clocksource_cyc2ns(delta, cs->mult, cs->shift);
  24. return mul_u64_u32_shr(delta, cs->mult, cs->shift);
  25. }
  26. /**
  27. * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
  28. * @mult: pointer to mult variable
  29. * @shift: pointer to shift variable
  30. * @from: frequency to convert from
  31. * @to: frequency to convert to
  32. * @maxsec: guaranteed runtime conversion range in seconds
  33. *
  34. * The function evaluates the shift/mult pair for the scaled math
  35. * operations of clocksources and clockevents.
  36. *
  37. * @to and @from are frequency values in HZ. For clock sources @to is
  38. * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
  39. * event @to is the counter frequency and @from is NSEC_PER_SEC.
  40. *
  41. * The @maxsec conversion range argument controls the time frame in
  42. * seconds which must be covered by the runtime conversion with the
  43. * calculated mult and shift factors. This guarantees that no 64bit
  44. * overflow happens when the input value of the conversion is
  45. * multiplied with the calculated mult factor. Larger ranges may
  46. * reduce the conversion accuracy by choosing smaller mult and shift
  47. * factors.
  48. */
  49. void
  50. clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
  51. {
  52. u64 tmp;
  53. u32 sft, sftacc= 32;
  54. /*
  55. * Calculate the shift factor which is limiting the conversion
  56. * range:
  57. */
  58. tmp = ((u64)maxsec * from) >> 32;
  59. while (tmp) {
  60. tmp >>=1;
  61. sftacc--;
  62. }
  63. /*
  64. * Find the conversion shift/mult pair which has the best
  65. * accuracy and fits the maxsec conversion range:
  66. */
  67. for (sft = 32; sft > 0; sft--) {
  68. tmp = (u64) to << sft;
  69. tmp += from / 2;
  70. do_div(tmp, from);
  71. if ((tmp >> sftacc) == 0)
  72. break;
  73. }
  74. *mult = tmp;
  75. *shift = sft;
  76. }
  77. EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
  78. /*[Clocksource internal variables]---------
  79. * curr_clocksource:
  80. * currently selected clocksource.
  81. * suspend_clocksource:
  82. * used to calculate the suspend time.
  83. * clocksource_list:
  84. * linked list with the registered clocksources
  85. * clocksource_mutex:
  86. * protects manipulations to curr_clocksource and the clocksource_list
  87. * override_name:
  88. * Name of the user-specified clocksource.
  89. */
  90. static struct clocksource *curr_clocksource;
  91. static struct clocksource *suspend_clocksource;
  92. static LIST_HEAD(clocksource_list);
  93. static DEFINE_MUTEX(clocksource_mutex);
  94. static char override_name[CS_NAME_LEN];
  95. static int finished_booting;
  96. static u64 suspend_start;
  97. /*
  98. * Interval: 0.5sec.
  99. */
  100. #define WATCHDOG_INTERVAL (HZ >> 1)
  101. #define WATCHDOG_INTERVAL_MAX_NS ((2 * WATCHDOG_INTERVAL) * (NSEC_PER_SEC / HZ))
  102. /*
  103. * Threshold: 0.0312s, when doubled: 0.0625s.
  104. */
  105. #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 5)
  106. /*
  107. * Maximum permissible delay between two readouts of the watchdog
  108. * clocksource surrounding a read of the clocksource being validated.
  109. * This delay could be due to SMIs, NMIs, or to VCPU preemptions. Used as
  110. * a lower bound for cs->uncertainty_margin values when registering clocks.
  111. *
  112. * The default of 500 parts per million is based on NTP's limits.
  113. * If a clocksource is good enough for NTP, it is good enough for us!
  114. *
  115. * In other words, by default, even if a clocksource is extremely
  116. * precise (for example, with a sub-nanosecond period), the maximum
  117. * permissible skew between the clocksource watchdog and the clocksource
  118. * under test is not permitted to go below the 500ppm minimum defined
  119. * by MAX_SKEW_USEC. This 500ppm minimum may be overridden using the
  120. * CLOCKSOURCE_WATCHDOG_MAX_SKEW_US Kconfig option.
  121. */
  122. #ifdef CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
  123. #define MAX_SKEW_USEC CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US
  124. #else
  125. #define MAX_SKEW_USEC (125 * WATCHDOG_INTERVAL / HZ)
  126. #endif
  127. /*
  128. * Default for maximum permissible skew when cs->uncertainty_margin is
  129. * not specified, and the lower bound even when cs->uncertainty_margin
  130. * is specified. This is also the default that is used when registering
  131. * clocks with unspecifed cs->uncertainty_margin, so this macro is used
  132. * even in CONFIG_CLOCKSOURCE_WATCHDOG=n kernels.
  133. */
  134. #define WATCHDOG_MAX_SKEW (MAX_SKEW_USEC * NSEC_PER_USEC)
  135. #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
  136. static void clocksource_watchdog_work(struct work_struct *work);
  137. static void clocksource_select(void);
  138. static LIST_HEAD(watchdog_list);
  139. static struct clocksource *watchdog;
  140. static struct timer_list watchdog_timer;
  141. static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
  142. static DEFINE_SPINLOCK(watchdog_lock);
  143. static int watchdog_running;
  144. static atomic_t watchdog_reset_pending;
  145. static int64_t watchdog_max_interval;
  146. static inline void clocksource_watchdog_lock(unsigned long *flags)
  147. {
  148. spin_lock_irqsave(&watchdog_lock, *flags);
  149. }
  150. static inline void clocksource_watchdog_unlock(unsigned long *flags)
  151. {
  152. spin_unlock_irqrestore(&watchdog_lock, *flags);
  153. }
  154. static int clocksource_watchdog_kthread(void *data);
  155. static void __clocksource_change_rating(struct clocksource *cs, int rating);
  156. static void clocksource_watchdog_work(struct work_struct *work)
  157. {
  158. /*
  159. * We cannot directly run clocksource_watchdog_kthread() here, because
  160. * clocksource_select() calls timekeeping_notify() which uses
  161. * stop_machine(). One cannot use stop_machine() from a workqueue() due
  162. * lock inversions wrt CPU hotplug.
  163. *
  164. * Also, we only ever run this work once or twice during the lifetime
  165. * of the kernel, so there is no point in creating a more permanent
  166. * kthread for this.
  167. *
  168. * If kthread_run fails the next watchdog scan over the
  169. * watchdog_list will find the unstable clock again.
  170. */
  171. kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
  172. }
  173. static void __clocksource_unstable(struct clocksource *cs)
  174. {
  175. cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
  176. cs->flags |= CLOCK_SOURCE_UNSTABLE;
  177. /*
  178. * If the clocksource is registered clocksource_watchdog_kthread() will
  179. * re-rate and re-select.
  180. */
  181. if (list_empty(&cs->list)) {
  182. cs->rating = 0;
  183. return;
  184. }
  185. if (cs->mark_unstable)
  186. cs->mark_unstable(cs);
  187. /* kick clocksource_watchdog_kthread() */
  188. if (finished_booting)
  189. schedule_work(&watchdog_work);
  190. }
  191. /**
  192. * clocksource_mark_unstable - mark clocksource unstable via watchdog
  193. * @cs: clocksource to be marked unstable
  194. *
  195. * This function is called by the x86 TSC code to mark clocksources as unstable;
  196. * it defers demotion and re-selection to a kthread.
  197. */
  198. void clocksource_mark_unstable(struct clocksource *cs)
  199. {
  200. unsigned long flags;
  201. spin_lock_irqsave(&watchdog_lock, flags);
  202. if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
  203. if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
  204. list_add(&cs->wd_list, &watchdog_list);
  205. __clocksource_unstable(cs);
  206. }
  207. spin_unlock_irqrestore(&watchdog_lock, flags);
  208. }
  209. static int verify_n_cpus = 8;
  210. module_param(verify_n_cpus, int, 0644);
  211. enum wd_read_status {
  212. WD_READ_SUCCESS,
  213. WD_READ_UNSTABLE,
  214. WD_READ_SKIP
  215. };
  216. static enum wd_read_status cs_watchdog_read(struct clocksource *cs, u64 *csnow, u64 *wdnow)
  217. {
  218. int64_t md = 2 * watchdog->uncertainty_margin;
  219. unsigned int nretries, max_retries;
  220. int64_t wd_delay, wd_seq_delay;
  221. u64 wd_end, wd_end2;
  222. max_retries = clocksource_get_max_watchdog_retry();
  223. for (nretries = 0; nretries <= max_retries; nretries++) {
  224. local_irq_disable();
  225. *wdnow = watchdog->read(watchdog);
  226. *csnow = cs->read(cs);
  227. wd_end = watchdog->read(watchdog);
  228. wd_end2 = watchdog->read(watchdog);
  229. local_irq_enable();
  230. wd_delay = cycles_to_nsec_safe(watchdog, *wdnow, wd_end);
  231. if (wd_delay <= md + cs->uncertainty_margin) {
  232. if (nretries > 1 && nretries >= max_retries) {
  233. pr_warn("timekeeping watchdog on CPU%d: %s retried %d times before success\n",
  234. smp_processor_id(), watchdog->name, nretries);
  235. }
  236. return WD_READ_SUCCESS;
  237. }
  238. /*
  239. * Now compute delay in consecutive watchdog read to see if
  240. * there is too much external interferences that cause
  241. * significant delay in reading both clocksource and watchdog.
  242. *
  243. * If consecutive WD read-back delay > md, report
  244. * system busy, reinit the watchdog and skip the current
  245. * watchdog test.
  246. */
  247. wd_seq_delay = cycles_to_nsec_safe(watchdog, wd_end, wd_end2);
  248. if (wd_seq_delay > md)
  249. goto skip_test;
  250. }
  251. pr_warn("timekeeping watchdog on CPU%d: wd-%s-wd excessive read-back delay of %lldns vs. limit of %ldns, wd-wd read-back delay only %lldns, attempt %d, marking %s unstable\n",
  252. smp_processor_id(), cs->name, wd_delay, WATCHDOG_MAX_SKEW, wd_seq_delay, nretries, cs->name);
  253. return WD_READ_UNSTABLE;
  254. skip_test:
  255. pr_info("timekeeping watchdog on CPU%d: %s wd-wd read-back delay of %lldns\n",
  256. smp_processor_id(), watchdog->name, wd_seq_delay);
  257. pr_info("wd-%s-wd read-back delay of %lldns, clock-skew test skipped!\n",
  258. cs->name, wd_delay);
  259. return WD_READ_SKIP;
  260. }
  261. static u64 csnow_mid;
  262. static cpumask_t cpus_ahead;
  263. static cpumask_t cpus_behind;
  264. static cpumask_t cpus_chosen;
  265. static void clocksource_verify_choose_cpus(void)
  266. {
  267. int cpu, i, n = verify_n_cpus;
  268. if (n < 0) {
  269. /* Check all of the CPUs. */
  270. cpumask_copy(&cpus_chosen, cpu_online_mask);
  271. cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
  272. return;
  273. }
  274. /* If no checking desired, or no other CPU to check, leave. */
  275. cpumask_clear(&cpus_chosen);
  276. if (n == 0 || num_online_cpus() <= 1)
  277. return;
  278. /* Make sure to select at least one CPU other than the current CPU. */
  279. cpu = cpumask_first(cpu_online_mask);
  280. if (cpu == smp_processor_id())
  281. cpu = cpumask_next(cpu, cpu_online_mask);
  282. if (WARN_ON_ONCE(cpu >= nr_cpu_ids))
  283. return;
  284. cpumask_set_cpu(cpu, &cpus_chosen);
  285. /* Force a sane value for the boot parameter. */
  286. if (n > nr_cpu_ids)
  287. n = nr_cpu_ids;
  288. /*
  289. * Randomly select the specified number of CPUs. If the same
  290. * CPU is selected multiple times, that CPU is checked only once,
  291. * and no replacement CPU is selected. This gracefully handles
  292. * situations where verify_n_cpus is greater than the number of
  293. * CPUs that are currently online.
  294. */
  295. for (i = 1; i < n; i++) {
  296. cpu = get_random_u32_below(nr_cpu_ids);
  297. cpu = cpumask_next(cpu - 1, cpu_online_mask);
  298. if (cpu >= nr_cpu_ids)
  299. cpu = cpumask_first(cpu_online_mask);
  300. if (!WARN_ON_ONCE(cpu >= nr_cpu_ids))
  301. cpumask_set_cpu(cpu, &cpus_chosen);
  302. }
  303. /* Don't verify ourselves. */
  304. cpumask_clear_cpu(smp_processor_id(), &cpus_chosen);
  305. }
  306. static void clocksource_verify_one_cpu(void *csin)
  307. {
  308. struct clocksource *cs = (struct clocksource *)csin;
  309. csnow_mid = cs->read(cs);
  310. }
  311. void clocksource_verify_percpu(struct clocksource *cs)
  312. {
  313. int64_t cs_nsec, cs_nsec_max = 0, cs_nsec_min = LLONG_MAX;
  314. u64 csnow_begin, csnow_end;
  315. int cpu, testcpu;
  316. s64 delta;
  317. if (verify_n_cpus == 0)
  318. return;
  319. cpumask_clear(&cpus_ahead);
  320. cpumask_clear(&cpus_behind);
  321. cpus_read_lock();
  322. migrate_disable();
  323. clocksource_verify_choose_cpus();
  324. if (cpumask_empty(&cpus_chosen)) {
  325. migrate_enable();
  326. cpus_read_unlock();
  327. pr_warn("Not enough CPUs to check clocksource '%s'.\n", cs->name);
  328. return;
  329. }
  330. testcpu = smp_processor_id();
  331. pr_info("Checking clocksource %s synchronization from CPU %d to CPUs %*pbl.\n",
  332. cs->name, testcpu, cpumask_pr_args(&cpus_chosen));
  333. preempt_disable();
  334. for_each_cpu(cpu, &cpus_chosen) {
  335. if (cpu == testcpu)
  336. continue;
  337. csnow_begin = cs->read(cs);
  338. smp_call_function_single(cpu, clocksource_verify_one_cpu, cs, 1);
  339. csnow_end = cs->read(cs);
  340. delta = (s64)((csnow_mid - csnow_begin) & cs->mask);
  341. if (delta < 0)
  342. cpumask_set_cpu(cpu, &cpus_behind);
  343. delta = (csnow_end - csnow_mid) & cs->mask;
  344. if (delta < 0)
  345. cpumask_set_cpu(cpu, &cpus_ahead);
  346. cs_nsec = cycles_to_nsec_safe(cs, csnow_begin, csnow_end);
  347. if (cs_nsec > cs_nsec_max)
  348. cs_nsec_max = cs_nsec;
  349. if (cs_nsec < cs_nsec_min)
  350. cs_nsec_min = cs_nsec;
  351. }
  352. preempt_enable();
  353. migrate_enable();
  354. cpus_read_unlock();
  355. if (!cpumask_empty(&cpus_ahead))
  356. pr_warn(" CPUs %*pbl ahead of CPU %d for clocksource %s.\n",
  357. cpumask_pr_args(&cpus_ahead), testcpu, cs->name);
  358. if (!cpumask_empty(&cpus_behind))
  359. pr_warn(" CPUs %*pbl behind CPU %d for clocksource %s.\n",
  360. cpumask_pr_args(&cpus_behind), testcpu, cs->name);
  361. if (!cpumask_empty(&cpus_ahead) || !cpumask_empty(&cpus_behind))
  362. pr_warn(" CPU %d check durations %lldns - %lldns for clocksource %s.\n",
  363. testcpu, cs_nsec_min, cs_nsec_max, cs->name);
  364. }
  365. EXPORT_SYMBOL_GPL(clocksource_verify_percpu);
  366. static inline void clocksource_reset_watchdog(void)
  367. {
  368. struct clocksource *cs;
  369. list_for_each_entry(cs, &watchdog_list, wd_list)
  370. cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
  371. }
  372. static void clocksource_watchdog(struct timer_list *unused)
  373. {
  374. int64_t wd_nsec, cs_nsec, interval;
  375. u64 csnow, wdnow, cslast, wdlast;
  376. int next_cpu, reset_pending;
  377. struct clocksource *cs;
  378. enum wd_read_status read_ret;
  379. unsigned long extra_wait = 0;
  380. u32 md;
  381. spin_lock(&watchdog_lock);
  382. if (!watchdog_running)
  383. goto out;
  384. reset_pending = atomic_read(&watchdog_reset_pending);
  385. list_for_each_entry(cs, &watchdog_list, wd_list) {
  386. /* Clocksource already marked unstable? */
  387. if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
  388. if (finished_booting)
  389. schedule_work(&watchdog_work);
  390. continue;
  391. }
  392. read_ret = cs_watchdog_read(cs, &csnow, &wdnow);
  393. if (read_ret == WD_READ_UNSTABLE) {
  394. /* Clock readout unreliable, so give it up. */
  395. __clocksource_unstable(cs);
  396. continue;
  397. }
  398. /*
  399. * When WD_READ_SKIP is returned, it means the system is likely
  400. * under very heavy load, where the latency of reading
  401. * watchdog/clocksource is very big, and affect the accuracy of
  402. * watchdog check. So give system some space and suspend the
  403. * watchdog check for 5 minutes.
  404. */
  405. if (read_ret == WD_READ_SKIP) {
  406. /*
  407. * As the watchdog timer will be suspended, and
  408. * cs->last could keep unchanged for 5 minutes, reset
  409. * the counters.
  410. */
  411. clocksource_reset_watchdog();
  412. extra_wait = HZ * 300;
  413. break;
  414. }
  415. /* Clocksource initialized ? */
  416. if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
  417. atomic_read(&watchdog_reset_pending)) {
  418. cs->flags |= CLOCK_SOURCE_WATCHDOG;
  419. cs->wd_last = wdnow;
  420. cs->cs_last = csnow;
  421. continue;
  422. }
  423. wd_nsec = cycles_to_nsec_safe(watchdog, cs->wd_last, wdnow);
  424. cs_nsec = cycles_to_nsec_safe(cs, cs->cs_last, csnow);
  425. wdlast = cs->wd_last; /* save these in case we print them */
  426. cslast = cs->cs_last;
  427. cs->cs_last = csnow;
  428. cs->wd_last = wdnow;
  429. if (atomic_read(&watchdog_reset_pending))
  430. continue;
  431. /*
  432. * The processing of timer softirqs can get delayed (usually
  433. * on account of ksoftirqd not getting to run in a timely
  434. * manner), which causes the watchdog interval to stretch.
  435. * Skew detection may fail for longer watchdog intervals
  436. * on account of fixed margins being used.
  437. * Some clocksources, e.g. acpi_pm, cannot tolerate
  438. * watchdog intervals longer than a few seconds.
  439. */
  440. interval = max(cs_nsec, wd_nsec);
  441. if (unlikely(interval > WATCHDOG_INTERVAL_MAX_NS)) {
  442. if (system_state > SYSTEM_SCHEDULING &&
  443. interval > 2 * watchdog_max_interval) {
  444. watchdog_max_interval = interval;
  445. pr_warn("Long readout interval, skipping watchdog check: cs_nsec: %lld wd_nsec: %lld\n",
  446. cs_nsec, wd_nsec);
  447. }
  448. watchdog_timer.expires = jiffies;
  449. continue;
  450. }
  451. /* Check the deviation from the watchdog clocksource. */
  452. md = cs->uncertainty_margin + watchdog->uncertainty_margin;
  453. if (abs(cs_nsec - wd_nsec) > md) {
  454. s64 cs_wd_msec;
  455. s64 wd_msec;
  456. u32 wd_rem;
  457. pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
  458. smp_processor_id(), cs->name);
  459. pr_warn(" '%s' wd_nsec: %lld wd_now: %llx wd_last: %llx mask: %llx\n",
  460. watchdog->name, wd_nsec, wdnow, wdlast, watchdog->mask);
  461. pr_warn(" '%s' cs_nsec: %lld cs_now: %llx cs_last: %llx mask: %llx\n",
  462. cs->name, cs_nsec, csnow, cslast, cs->mask);
  463. cs_wd_msec = div_s64_rem(cs_nsec - wd_nsec, 1000 * 1000, &wd_rem);
  464. wd_msec = div_s64_rem(wd_nsec, 1000 * 1000, &wd_rem);
  465. pr_warn(" Clocksource '%s' skewed %lld ns (%lld ms) over watchdog '%s' interval of %lld ns (%lld ms)\n",
  466. cs->name, cs_nsec - wd_nsec, cs_wd_msec, watchdog->name, wd_nsec, wd_msec);
  467. if (curr_clocksource == cs)
  468. pr_warn(" '%s' is current clocksource.\n", cs->name);
  469. else if (curr_clocksource)
  470. pr_warn(" '%s' (not '%s') is current clocksource.\n", curr_clocksource->name, cs->name);
  471. else
  472. pr_warn(" No current clocksource.\n");
  473. __clocksource_unstable(cs);
  474. continue;
  475. }
  476. if (cs == curr_clocksource && cs->tick_stable)
  477. cs->tick_stable(cs);
  478. if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
  479. (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
  480. (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
  481. /* Mark it valid for high-res. */
  482. cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
  483. /*
  484. * clocksource_done_booting() will sort it if
  485. * finished_booting is not set yet.
  486. */
  487. if (!finished_booting)
  488. continue;
  489. /*
  490. * If this is not the current clocksource let
  491. * the watchdog thread reselect it. Due to the
  492. * change to high res this clocksource might
  493. * be preferred now. If it is the current
  494. * clocksource let the tick code know about
  495. * that change.
  496. */
  497. if (cs != curr_clocksource) {
  498. cs->flags |= CLOCK_SOURCE_RESELECT;
  499. schedule_work(&watchdog_work);
  500. } else {
  501. tick_clock_notify();
  502. }
  503. }
  504. }
  505. /*
  506. * We only clear the watchdog_reset_pending, when we did a
  507. * full cycle through all clocksources.
  508. */
  509. if (reset_pending)
  510. atomic_dec(&watchdog_reset_pending);
  511. /*
  512. * Cycle through CPUs to check if the CPUs stay synchronized
  513. * to each other.
  514. */
  515. next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
  516. if (next_cpu >= nr_cpu_ids)
  517. next_cpu = cpumask_first(cpu_online_mask);
  518. /*
  519. * Arm timer if not already pending: could race with concurrent
  520. * pair clocksource_stop_watchdog() clocksource_start_watchdog().
  521. */
  522. if (!timer_pending(&watchdog_timer)) {
  523. watchdog_timer.expires += WATCHDOG_INTERVAL + extra_wait;
  524. add_timer_on(&watchdog_timer, next_cpu);
  525. }
  526. out:
  527. spin_unlock(&watchdog_lock);
  528. }
  529. static inline void clocksource_start_watchdog(void)
  530. {
  531. if (watchdog_running || !watchdog || list_empty(&watchdog_list))
  532. return;
  533. timer_setup(&watchdog_timer, clocksource_watchdog, 0);
  534. watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
  535. add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
  536. watchdog_running = 1;
  537. }
  538. static inline void clocksource_stop_watchdog(void)
  539. {
  540. if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
  541. return;
  542. del_timer(&watchdog_timer);
  543. watchdog_running = 0;
  544. }
  545. static void clocksource_resume_watchdog(void)
  546. {
  547. atomic_inc(&watchdog_reset_pending);
  548. }
  549. static void clocksource_enqueue_watchdog(struct clocksource *cs)
  550. {
  551. INIT_LIST_HEAD(&cs->wd_list);
  552. if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
  553. /* cs is a clocksource to be watched. */
  554. list_add(&cs->wd_list, &watchdog_list);
  555. cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
  556. } else {
  557. /* cs is a watchdog. */
  558. if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
  559. cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
  560. }
  561. }
  562. static void clocksource_select_watchdog(bool fallback)
  563. {
  564. struct clocksource *cs, *old_wd;
  565. unsigned long flags;
  566. spin_lock_irqsave(&watchdog_lock, flags);
  567. /* save current watchdog */
  568. old_wd = watchdog;
  569. if (fallback)
  570. watchdog = NULL;
  571. list_for_each_entry(cs, &clocksource_list, list) {
  572. /* cs is a clocksource to be watched. */
  573. if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
  574. continue;
  575. /* Skip current if we were requested for a fallback. */
  576. if (fallback && cs == old_wd)
  577. continue;
  578. /* Pick the best watchdog. */
  579. if (!watchdog || cs->rating > watchdog->rating)
  580. watchdog = cs;
  581. }
  582. /* If we failed to find a fallback restore the old one. */
  583. if (!watchdog)
  584. watchdog = old_wd;
  585. /* If we changed the watchdog we need to reset cycles. */
  586. if (watchdog != old_wd)
  587. clocksource_reset_watchdog();
  588. /* Check if the watchdog timer needs to be started. */
  589. clocksource_start_watchdog();
  590. spin_unlock_irqrestore(&watchdog_lock, flags);
  591. }
  592. static void clocksource_dequeue_watchdog(struct clocksource *cs)
  593. {
  594. if (cs != watchdog) {
  595. if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
  596. /* cs is a watched clocksource. */
  597. list_del_init(&cs->wd_list);
  598. /* Check if the watchdog timer needs to be stopped. */
  599. clocksource_stop_watchdog();
  600. }
  601. }
  602. }
  603. static int __clocksource_watchdog_kthread(void)
  604. {
  605. struct clocksource *cs, *tmp;
  606. unsigned long flags;
  607. int select = 0;
  608. /* Do any required per-CPU skew verification. */
  609. if (curr_clocksource &&
  610. curr_clocksource->flags & CLOCK_SOURCE_UNSTABLE &&
  611. curr_clocksource->flags & CLOCK_SOURCE_VERIFY_PERCPU)
  612. clocksource_verify_percpu(curr_clocksource);
  613. spin_lock_irqsave(&watchdog_lock, flags);
  614. list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
  615. if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
  616. list_del_init(&cs->wd_list);
  617. __clocksource_change_rating(cs, 0);
  618. select = 1;
  619. }
  620. if (cs->flags & CLOCK_SOURCE_RESELECT) {
  621. cs->flags &= ~CLOCK_SOURCE_RESELECT;
  622. select = 1;
  623. }
  624. }
  625. /* Check if the watchdog timer needs to be stopped. */
  626. clocksource_stop_watchdog();
  627. spin_unlock_irqrestore(&watchdog_lock, flags);
  628. return select;
  629. }
  630. static int clocksource_watchdog_kthread(void *data)
  631. {
  632. mutex_lock(&clocksource_mutex);
  633. if (__clocksource_watchdog_kthread())
  634. clocksource_select();
  635. mutex_unlock(&clocksource_mutex);
  636. return 0;
  637. }
  638. static bool clocksource_is_watchdog(struct clocksource *cs)
  639. {
  640. return cs == watchdog;
  641. }
  642. #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
  643. static void clocksource_enqueue_watchdog(struct clocksource *cs)
  644. {
  645. if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
  646. cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
  647. }
  648. static void clocksource_select_watchdog(bool fallback) { }
  649. static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
  650. static inline void clocksource_resume_watchdog(void) { }
  651. static inline int __clocksource_watchdog_kthread(void) { return 0; }
  652. static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
  653. void clocksource_mark_unstable(struct clocksource *cs) { }
  654. static inline void clocksource_watchdog_lock(unsigned long *flags) { }
  655. static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
  656. #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
  657. static bool clocksource_is_suspend(struct clocksource *cs)
  658. {
  659. return cs == suspend_clocksource;
  660. }
  661. static void __clocksource_suspend_select(struct clocksource *cs)
  662. {
  663. /*
  664. * Skip the clocksource which will be stopped in suspend state.
  665. */
  666. if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
  667. return;
  668. /*
  669. * The nonstop clocksource can be selected as the suspend clocksource to
  670. * calculate the suspend time, so it should not supply suspend/resume
  671. * interfaces to suspend the nonstop clocksource when system suspends.
  672. */
  673. if (cs->suspend || cs->resume) {
  674. pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
  675. cs->name);
  676. }
  677. /* Pick the best rating. */
  678. if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
  679. suspend_clocksource = cs;
  680. }
  681. /**
  682. * clocksource_suspend_select - Select the best clocksource for suspend timing
  683. * @fallback: if select a fallback clocksource
  684. */
  685. static void clocksource_suspend_select(bool fallback)
  686. {
  687. struct clocksource *cs, *old_suspend;
  688. old_suspend = suspend_clocksource;
  689. if (fallback)
  690. suspend_clocksource = NULL;
  691. list_for_each_entry(cs, &clocksource_list, list) {
  692. /* Skip current if we were requested for a fallback. */
  693. if (fallback && cs == old_suspend)
  694. continue;
  695. __clocksource_suspend_select(cs);
  696. }
  697. }
  698. /**
  699. * clocksource_start_suspend_timing - Start measuring the suspend timing
  700. * @cs: current clocksource from timekeeping
  701. * @start_cycles: current cycles from timekeeping
  702. *
  703. * This function will save the start cycle values of suspend timer to calculate
  704. * the suspend time when resuming system.
  705. *
  706. * This function is called late in the suspend process from timekeeping_suspend(),
  707. * that means processes are frozen, non-boot cpus and interrupts are disabled
  708. * now. It is therefore possible to start the suspend timer without taking the
  709. * clocksource mutex.
  710. */
  711. void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
  712. {
  713. if (!suspend_clocksource)
  714. return;
  715. /*
  716. * If current clocksource is the suspend timer, we should use the
  717. * tkr_mono.cycle_last value as suspend_start to avoid same reading
  718. * from suspend timer.
  719. */
  720. if (clocksource_is_suspend(cs)) {
  721. suspend_start = start_cycles;
  722. return;
  723. }
  724. if (suspend_clocksource->enable &&
  725. suspend_clocksource->enable(suspend_clocksource)) {
  726. pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
  727. return;
  728. }
  729. suspend_start = suspend_clocksource->read(suspend_clocksource);
  730. }
  731. /**
  732. * clocksource_stop_suspend_timing - Stop measuring the suspend timing
  733. * @cs: current clocksource from timekeeping
  734. * @cycle_now: current cycles from timekeeping
  735. *
  736. * This function will calculate the suspend time from suspend timer.
  737. *
  738. * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
  739. *
  740. * This function is called early in the resume process from timekeeping_resume(),
  741. * that means there is only one cpu, no processes are running and the interrupts
  742. * are disabled. It is therefore possible to stop the suspend timer without
  743. * taking the clocksource mutex.
  744. */
  745. u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
  746. {
  747. u64 now, nsec = 0;
  748. if (!suspend_clocksource)
  749. return 0;
  750. /*
  751. * If current clocksource is the suspend timer, we should use the
  752. * tkr_mono.cycle_last value from timekeeping as current cycle to
  753. * avoid same reading from suspend timer.
  754. */
  755. if (clocksource_is_suspend(cs))
  756. now = cycle_now;
  757. else
  758. now = suspend_clocksource->read(suspend_clocksource);
  759. if (now > suspend_start)
  760. nsec = cycles_to_nsec_safe(suspend_clocksource, suspend_start, now);
  761. /*
  762. * Disable the suspend timer to save power if current clocksource is
  763. * not the suspend timer.
  764. */
  765. if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
  766. suspend_clocksource->disable(suspend_clocksource);
  767. return nsec;
  768. }
  769. /**
  770. * clocksource_suspend - suspend the clocksource(s)
  771. */
  772. void clocksource_suspend(void)
  773. {
  774. struct clocksource *cs;
  775. list_for_each_entry_reverse(cs, &clocksource_list, list)
  776. if (cs->suspend)
  777. cs->suspend(cs);
  778. }
  779. /**
  780. * clocksource_resume - resume the clocksource(s)
  781. */
  782. void clocksource_resume(void)
  783. {
  784. struct clocksource *cs;
  785. list_for_each_entry(cs, &clocksource_list, list)
  786. if (cs->resume)
  787. cs->resume(cs);
  788. clocksource_resume_watchdog();
  789. }
  790. /**
  791. * clocksource_touch_watchdog - Update watchdog
  792. *
  793. * Update the watchdog after exception contexts such as kgdb so as not
  794. * to incorrectly trip the watchdog. This might fail when the kernel
  795. * was stopped in code which holds watchdog_lock.
  796. */
  797. void clocksource_touch_watchdog(void)
  798. {
  799. clocksource_resume_watchdog();
  800. }
  801. /**
  802. * clocksource_max_adjustment- Returns max adjustment amount
  803. * @cs: Pointer to clocksource
  804. *
  805. */
  806. static u32 clocksource_max_adjustment(struct clocksource *cs)
  807. {
  808. u64 ret;
  809. /*
  810. * We won't try to correct for more than 11% adjustments (110,000 ppm),
  811. */
  812. ret = (u64)cs->mult * 11;
  813. do_div(ret,100);
  814. return (u32)ret;
  815. }
  816. /**
  817. * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
  818. * @mult: cycle to nanosecond multiplier
  819. * @shift: cycle to nanosecond divisor (power of two)
  820. * @maxadj: maximum adjustment value to mult (~11%)
  821. * @mask: bitmask for two's complement subtraction of non 64 bit counters
  822. * @max_cyc: maximum cycle value before potential overflow (does not include
  823. * any safety margin)
  824. *
  825. * NOTE: This function includes a safety margin of 50%, in other words, we
  826. * return half the number of nanoseconds the hardware counter can technically
  827. * cover. This is done so that we can potentially detect problems caused by
  828. * delayed timers or bad hardware, which might result in time intervals that
  829. * are larger than what the math used can handle without overflows.
  830. */
  831. u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
  832. {
  833. u64 max_nsecs, max_cycles;
  834. /*
  835. * Calculate the maximum number of cycles that we can pass to the
  836. * cyc2ns() function without overflowing a 64-bit result.
  837. */
  838. max_cycles = ULLONG_MAX;
  839. do_div(max_cycles, mult+maxadj);
  840. /*
  841. * The actual maximum number of cycles we can defer the clocksource is
  842. * determined by the minimum of max_cycles and mask.
  843. * Note: Here we subtract the maxadj to make sure we don't sleep for
  844. * too long if there's a large negative adjustment.
  845. */
  846. max_cycles = min(max_cycles, mask);
  847. max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
  848. /* return the max_cycles value as well if requested */
  849. if (max_cyc)
  850. *max_cyc = max_cycles;
  851. /* Return 50% of the actual maximum, so we can detect bad values */
  852. max_nsecs >>= 1;
  853. return max_nsecs;
  854. }
  855. /**
  856. * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
  857. * @cs: Pointer to clocksource to be updated
  858. *
  859. */
  860. static inline void clocksource_update_max_deferment(struct clocksource *cs)
  861. {
  862. cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
  863. cs->maxadj, cs->mask,
  864. &cs->max_cycles);
  865. /*
  866. * Threshold for detecting negative motion in clocksource_delta().
  867. *
  868. * Allow for 0.875 of the counter width so that overly long idle
  869. * sleeps, which go slightly over mask/2, do not trigger the
  870. * negative motion detection.
  871. */
  872. cs->max_raw_delta = (cs->mask >> 1) + (cs->mask >> 2) + (cs->mask >> 3);
  873. }
  874. static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
  875. {
  876. struct clocksource *cs;
  877. if (!finished_booting || list_empty(&clocksource_list))
  878. return NULL;
  879. /*
  880. * We pick the clocksource with the highest rating. If oneshot
  881. * mode is active, we pick the highres valid clocksource with
  882. * the best rating.
  883. */
  884. list_for_each_entry(cs, &clocksource_list, list) {
  885. if (skipcur && cs == curr_clocksource)
  886. continue;
  887. if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
  888. continue;
  889. return cs;
  890. }
  891. return NULL;
  892. }
  893. static void __clocksource_select(bool skipcur)
  894. {
  895. bool oneshot = tick_oneshot_mode_active();
  896. struct clocksource *best, *cs;
  897. /* Find the best suitable clocksource */
  898. best = clocksource_find_best(oneshot, skipcur);
  899. if (!best)
  900. return;
  901. if (!strlen(override_name))
  902. goto found;
  903. /* Check for the override clocksource. */
  904. list_for_each_entry(cs, &clocksource_list, list) {
  905. if (skipcur && cs == curr_clocksource)
  906. continue;
  907. if (strcmp(cs->name, override_name) != 0)
  908. continue;
  909. /*
  910. * Check to make sure we don't switch to a non-highres
  911. * capable clocksource if the tick code is in oneshot
  912. * mode (highres or nohz)
  913. */
  914. if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
  915. /* Override clocksource cannot be used. */
  916. if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
  917. pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
  918. cs->name);
  919. override_name[0] = 0;
  920. } else {
  921. /*
  922. * The override cannot be currently verified.
  923. * Deferring to let the watchdog check.
  924. */
  925. pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
  926. cs->name);
  927. }
  928. } else
  929. /* Override clocksource can be used. */
  930. best = cs;
  931. break;
  932. }
  933. found:
  934. if (curr_clocksource != best && !timekeeping_notify(best)) {
  935. pr_info("Switched to clocksource %s\n", best->name);
  936. curr_clocksource = best;
  937. }
  938. }
  939. /**
  940. * clocksource_select - Select the best clocksource available
  941. *
  942. * Private function. Must hold clocksource_mutex when called.
  943. *
  944. * Select the clocksource with the best rating, or the clocksource,
  945. * which is selected by userspace override.
  946. */
  947. static void clocksource_select(void)
  948. {
  949. __clocksource_select(false);
  950. }
  951. static void clocksource_select_fallback(void)
  952. {
  953. __clocksource_select(true);
  954. }
  955. /*
  956. * clocksource_done_booting - Called near the end of core bootup
  957. *
  958. * Hack to avoid lots of clocksource churn at boot time.
  959. * We use fs_initcall because we want this to start before
  960. * device_initcall but after subsys_initcall.
  961. */
  962. static int __init clocksource_done_booting(void)
  963. {
  964. mutex_lock(&clocksource_mutex);
  965. curr_clocksource = clocksource_default_clock();
  966. finished_booting = 1;
  967. /*
  968. * Run the watchdog first to eliminate unstable clock sources
  969. */
  970. __clocksource_watchdog_kthread();
  971. clocksource_select();
  972. mutex_unlock(&clocksource_mutex);
  973. return 0;
  974. }
  975. fs_initcall(clocksource_done_booting);
  976. /*
  977. * Enqueue the clocksource sorted by rating
  978. */
  979. static void clocksource_enqueue(struct clocksource *cs)
  980. {
  981. struct list_head *entry = &clocksource_list;
  982. struct clocksource *tmp;
  983. list_for_each_entry(tmp, &clocksource_list, list) {
  984. /* Keep track of the place, where to insert */
  985. if (tmp->rating < cs->rating)
  986. break;
  987. entry = &tmp->list;
  988. }
  989. list_add(&cs->list, entry);
  990. }
  991. /**
  992. * __clocksource_update_freq_scale - Used update clocksource with new freq
  993. * @cs: clocksource to be registered
  994. * @scale: Scale factor multiplied against freq to get clocksource hz
  995. * @freq: clocksource frequency (cycles per second) divided by scale
  996. *
  997. * This should only be called from the clocksource->enable() method.
  998. *
  999. * This *SHOULD NOT* be called directly! Please use the
  1000. * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
  1001. * functions.
  1002. */
  1003. void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
  1004. {
  1005. u64 sec;
  1006. /*
  1007. * Default clocksources are *special* and self-define their mult/shift.
  1008. * But, you're not special, so you should specify a freq value.
  1009. */
  1010. if (freq) {
  1011. /*
  1012. * Calc the maximum number of seconds which we can run before
  1013. * wrapping around. For clocksources which have a mask > 32-bit
  1014. * we need to limit the max sleep time to have a good
  1015. * conversion precision. 10 minutes is still a reasonable
  1016. * amount. That results in a shift value of 24 for a
  1017. * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
  1018. * ~ 0.06ppm granularity for NTP.
  1019. */
  1020. sec = cs->mask;
  1021. do_div(sec, freq);
  1022. do_div(sec, scale);
  1023. if (!sec)
  1024. sec = 1;
  1025. else if (sec > 600 && cs->mask > UINT_MAX)
  1026. sec = 600;
  1027. clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
  1028. NSEC_PER_SEC / scale, sec * scale);
  1029. }
  1030. /*
  1031. * If the uncertainty margin is not specified, calculate it. If
  1032. * both scale and freq are non-zero, calculate the clock period, but
  1033. * bound below at 2*WATCHDOG_MAX_SKEW, that is, 500ppm by default.
  1034. * However, if either of scale or freq is zero, be very conservative
  1035. * and take the tens-of-milliseconds WATCHDOG_THRESHOLD value
  1036. * for the uncertainty margin. Allow stupidly small uncertainty
  1037. * margins to be specified by the caller for testing purposes,
  1038. * but warn to discourage production use of this capability.
  1039. *
  1040. * Bottom line: The sum of the uncertainty margins of the
  1041. * watchdog clocksource and the clocksource under test will be at
  1042. * least 500ppm by default. For more information, please see the
  1043. * comment preceding CONFIG_CLOCKSOURCE_WATCHDOG_MAX_SKEW_US above.
  1044. */
  1045. if (scale && freq && !cs->uncertainty_margin) {
  1046. cs->uncertainty_margin = NSEC_PER_SEC / (scale * freq);
  1047. if (cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW)
  1048. cs->uncertainty_margin = 2 * WATCHDOG_MAX_SKEW;
  1049. } else if (!cs->uncertainty_margin) {
  1050. cs->uncertainty_margin = WATCHDOG_THRESHOLD;
  1051. }
  1052. WARN_ON_ONCE(cs->uncertainty_margin < 2 * WATCHDOG_MAX_SKEW);
  1053. /*
  1054. * Ensure clocksources that have large 'mult' values don't overflow
  1055. * when adjusted.
  1056. */
  1057. cs->maxadj = clocksource_max_adjustment(cs);
  1058. while (freq && ((cs->mult + cs->maxadj < cs->mult)
  1059. || (cs->mult - cs->maxadj > cs->mult))) {
  1060. cs->mult >>= 1;
  1061. cs->shift--;
  1062. cs->maxadj = clocksource_max_adjustment(cs);
  1063. }
  1064. /*
  1065. * Only warn for *special* clocksources that self-define
  1066. * their mult/shift values and don't specify a freq.
  1067. */
  1068. WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
  1069. "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
  1070. cs->name);
  1071. clocksource_update_max_deferment(cs);
  1072. pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
  1073. cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
  1074. }
  1075. EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
  1076. /**
  1077. * __clocksource_register_scale - Used to install new clocksources
  1078. * @cs: clocksource to be registered
  1079. * @scale: Scale factor multiplied against freq to get clocksource hz
  1080. * @freq: clocksource frequency (cycles per second) divided by scale
  1081. *
  1082. * Returns -EBUSY if registration fails, zero otherwise.
  1083. *
  1084. * This *SHOULD NOT* be called directly! Please use the
  1085. * clocksource_register_hz() or clocksource_register_khz helper functions.
  1086. */
  1087. int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
  1088. {
  1089. unsigned long flags;
  1090. clocksource_arch_init(cs);
  1091. if (WARN_ON_ONCE((unsigned int)cs->id >= CSID_MAX))
  1092. cs->id = CSID_GENERIC;
  1093. if (cs->vdso_clock_mode < 0 ||
  1094. cs->vdso_clock_mode >= VDSO_CLOCKMODE_MAX) {
  1095. pr_warn("clocksource %s registered with invalid VDSO mode %d. Disabling VDSO support.\n",
  1096. cs->name, cs->vdso_clock_mode);
  1097. cs->vdso_clock_mode = VDSO_CLOCKMODE_NONE;
  1098. }
  1099. /* Initialize mult/shift and max_idle_ns */
  1100. __clocksource_update_freq_scale(cs, scale, freq);
  1101. /* Add clocksource to the clocksource list */
  1102. mutex_lock(&clocksource_mutex);
  1103. clocksource_watchdog_lock(&flags);
  1104. clocksource_enqueue(cs);
  1105. clocksource_enqueue_watchdog(cs);
  1106. clocksource_watchdog_unlock(&flags);
  1107. clocksource_select();
  1108. clocksource_select_watchdog(false);
  1109. __clocksource_suspend_select(cs);
  1110. mutex_unlock(&clocksource_mutex);
  1111. return 0;
  1112. }
  1113. EXPORT_SYMBOL_GPL(__clocksource_register_scale);
  1114. static void __clocksource_change_rating(struct clocksource *cs, int rating)
  1115. {
  1116. list_del(&cs->list);
  1117. cs->rating = rating;
  1118. clocksource_enqueue(cs);
  1119. }
  1120. /**
  1121. * clocksource_change_rating - Change the rating of a registered clocksource
  1122. * @cs: clocksource to be changed
  1123. * @rating: new rating
  1124. */
  1125. void clocksource_change_rating(struct clocksource *cs, int rating)
  1126. {
  1127. unsigned long flags;
  1128. mutex_lock(&clocksource_mutex);
  1129. clocksource_watchdog_lock(&flags);
  1130. __clocksource_change_rating(cs, rating);
  1131. clocksource_watchdog_unlock(&flags);
  1132. clocksource_select();
  1133. clocksource_select_watchdog(false);
  1134. clocksource_suspend_select(false);
  1135. mutex_unlock(&clocksource_mutex);
  1136. }
  1137. EXPORT_SYMBOL(clocksource_change_rating);
  1138. /*
  1139. * Unbind clocksource @cs. Called with clocksource_mutex held
  1140. */
  1141. static int clocksource_unbind(struct clocksource *cs)
  1142. {
  1143. unsigned long flags;
  1144. if (clocksource_is_watchdog(cs)) {
  1145. /* Select and try to install a replacement watchdog. */
  1146. clocksource_select_watchdog(true);
  1147. if (clocksource_is_watchdog(cs))
  1148. return -EBUSY;
  1149. }
  1150. if (cs == curr_clocksource) {
  1151. /* Select and try to install a replacement clock source */
  1152. clocksource_select_fallback();
  1153. if (curr_clocksource == cs)
  1154. return -EBUSY;
  1155. }
  1156. if (clocksource_is_suspend(cs)) {
  1157. /*
  1158. * Select and try to install a replacement suspend clocksource.
  1159. * If no replacement suspend clocksource, we will just let the
  1160. * clocksource go and have no suspend clocksource.
  1161. */
  1162. clocksource_suspend_select(true);
  1163. }
  1164. clocksource_watchdog_lock(&flags);
  1165. clocksource_dequeue_watchdog(cs);
  1166. list_del_init(&cs->list);
  1167. clocksource_watchdog_unlock(&flags);
  1168. return 0;
  1169. }
  1170. /**
  1171. * clocksource_unregister - remove a registered clocksource
  1172. * @cs: clocksource to be unregistered
  1173. */
  1174. int clocksource_unregister(struct clocksource *cs)
  1175. {
  1176. int ret = 0;
  1177. mutex_lock(&clocksource_mutex);
  1178. if (!list_empty(&cs->list))
  1179. ret = clocksource_unbind(cs);
  1180. mutex_unlock(&clocksource_mutex);
  1181. return ret;
  1182. }
  1183. EXPORT_SYMBOL(clocksource_unregister);
  1184. #ifdef CONFIG_SYSFS
  1185. /**
  1186. * current_clocksource_show - sysfs interface for current clocksource
  1187. * @dev: unused
  1188. * @attr: unused
  1189. * @buf: char buffer to be filled with clocksource list
  1190. *
  1191. * Provides sysfs interface for listing current clocksource.
  1192. */
  1193. static ssize_t current_clocksource_show(struct device *dev,
  1194. struct device_attribute *attr,
  1195. char *buf)
  1196. {
  1197. ssize_t count = 0;
  1198. mutex_lock(&clocksource_mutex);
  1199. count = sysfs_emit(buf, "%s\n", curr_clocksource->name);
  1200. mutex_unlock(&clocksource_mutex);
  1201. return count;
  1202. }
  1203. ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
  1204. {
  1205. size_t ret = cnt;
  1206. /* strings from sysfs write are not 0 terminated! */
  1207. if (!cnt || cnt >= CS_NAME_LEN)
  1208. return -EINVAL;
  1209. /* strip of \n: */
  1210. if (buf[cnt-1] == '\n')
  1211. cnt--;
  1212. if (cnt > 0)
  1213. memcpy(dst, buf, cnt);
  1214. dst[cnt] = 0;
  1215. return ret;
  1216. }
  1217. /**
  1218. * current_clocksource_store - interface for manually overriding clocksource
  1219. * @dev: unused
  1220. * @attr: unused
  1221. * @buf: name of override clocksource
  1222. * @count: length of buffer
  1223. *
  1224. * Takes input from sysfs interface for manually overriding the default
  1225. * clocksource selection.
  1226. */
  1227. static ssize_t current_clocksource_store(struct device *dev,
  1228. struct device_attribute *attr,
  1229. const char *buf, size_t count)
  1230. {
  1231. ssize_t ret;
  1232. mutex_lock(&clocksource_mutex);
  1233. ret = sysfs_get_uname(buf, override_name, count);
  1234. if (ret >= 0)
  1235. clocksource_select();
  1236. mutex_unlock(&clocksource_mutex);
  1237. return ret;
  1238. }
  1239. static DEVICE_ATTR_RW(current_clocksource);
  1240. /**
  1241. * unbind_clocksource_store - interface for manually unbinding clocksource
  1242. * @dev: unused
  1243. * @attr: unused
  1244. * @buf: unused
  1245. * @count: length of buffer
  1246. *
  1247. * Takes input from sysfs interface for manually unbinding a clocksource.
  1248. */
  1249. static ssize_t unbind_clocksource_store(struct device *dev,
  1250. struct device_attribute *attr,
  1251. const char *buf, size_t count)
  1252. {
  1253. struct clocksource *cs;
  1254. char name[CS_NAME_LEN];
  1255. ssize_t ret;
  1256. ret = sysfs_get_uname(buf, name, count);
  1257. if (ret < 0)
  1258. return ret;
  1259. ret = -ENODEV;
  1260. mutex_lock(&clocksource_mutex);
  1261. list_for_each_entry(cs, &clocksource_list, list) {
  1262. if (strcmp(cs->name, name))
  1263. continue;
  1264. ret = clocksource_unbind(cs);
  1265. break;
  1266. }
  1267. mutex_unlock(&clocksource_mutex);
  1268. return ret ? ret : count;
  1269. }
  1270. static DEVICE_ATTR_WO(unbind_clocksource);
  1271. /**
  1272. * available_clocksource_show - sysfs interface for listing clocksource
  1273. * @dev: unused
  1274. * @attr: unused
  1275. * @buf: char buffer to be filled with clocksource list
  1276. *
  1277. * Provides sysfs interface for listing registered clocksources
  1278. */
  1279. static ssize_t available_clocksource_show(struct device *dev,
  1280. struct device_attribute *attr,
  1281. char *buf)
  1282. {
  1283. struct clocksource *src;
  1284. ssize_t count = 0;
  1285. mutex_lock(&clocksource_mutex);
  1286. list_for_each_entry(src, &clocksource_list, list) {
  1287. /*
  1288. * Don't show non-HRES clocksource if the tick code is
  1289. * in one shot mode (highres=on or nohz=on)
  1290. */
  1291. if (!tick_oneshot_mode_active() ||
  1292. (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
  1293. count += snprintf(buf + count,
  1294. max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
  1295. "%s ", src->name);
  1296. }
  1297. mutex_unlock(&clocksource_mutex);
  1298. count += snprintf(buf + count,
  1299. max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
  1300. return count;
  1301. }
  1302. static DEVICE_ATTR_RO(available_clocksource);
  1303. static struct attribute *clocksource_attrs[] = {
  1304. &dev_attr_current_clocksource.attr,
  1305. &dev_attr_unbind_clocksource.attr,
  1306. &dev_attr_available_clocksource.attr,
  1307. NULL
  1308. };
  1309. ATTRIBUTE_GROUPS(clocksource);
  1310. static const struct bus_type clocksource_subsys = {
  1311. .name = "clocksource",
  1312. .dev_name = "clocksource",
  1313. };
  1314. static struct device device_clocksource = {
  1315. .id = 0,
  1316. .bus = &clocksource_subsys,
  1317. .groups = clocksource_groups,
  1318. };
  1319. static int __init init_clocksource_sysfs(void)
  1320. {
  1321. int error = subsys_system_register(&clocksource_subsys, NULL);
  1322. if (!error)
  1323. error = device_register(&device_clocksource);
  1324. return error;
  1325. }
  1326. device_initcall(init_clocksource_sysfs);
  1327. #endif /* CONFIG_SYSFS */
  1328. /**
  1329. * boot_override_clocksource - boot clock override
  1330. * @str: override name
  1331. *
  1332. * Takes a clocksource= boot argument and uses it
  1333. * as the clocksource override name.
  1334. */
  1335. static int __init boot_override_clocksource(char* str)
  1336. {
  1337. mutex_lock(&clocksource_mutex);
  1338. if (str)
  1339. strscpy(override_name, str, sizeof(override_name));
  1340. mutex_unlock(&clocksource_mutex);
  1341. return 1;
  1342. }
  1343. __setup("clocksource=", boot_override_clocksource);
  1344. /**
  1345. * boot_override_clock - Compatibility layer for deprecated boot option
  1346. * @str: override name
  1347. *
  1348. * DEPRECATED! Takes a clock= boot argument and uses it
  1349. * as the clocksource override name
  1350. */
  1351. static int __init boot_override_clock(char* str)
  1352. {
  1353. if (!strcmp(str, "pmtmr")) {
  1354. pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
  1355. return boot_override_clocksource("acpi_pm");
  1356. }
  1357. pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
  1358. return boot_override_clocksource(str);
  1359. }
  1360. __setup("clock=", boot_override_clock);