clocksource.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. /*
  2. * linux/kernel/time/clocksource.c
  3. *
  4. * This file contains the functions which manage clocksource drivers.
  5. *
  6. * Copyright (C) 2004, 2005 IBM, John Stultz (johnstul@us.ibm.com)
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  21. *
  22. * TODO WishList:
  23. * o Allow clocksource drivers to be unregistered
  24. */
  25. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  26. #include <linux/device.h>
  27. #include <linux/clocksource.h>
  28. #include <linux/init.h>
  29. #include <linux/module.h>
  30. #include <linux/sched.h> /* for spin_unlock_irq() using preempt_count() m68k */
  31. #include <linux/tick.h>
  32. #include <linux/kthread.h>
  33. #include "tick-internal.h"
  34. #include "timekeeping_internal.h"
  35. /**
  36. * clocks_calc_mult_shift - calculate mult/shift factors for scaled math of clocks
  37. * @mult: pointer to mult variable
  38. * @shift: pointer to shift variable
  39. * @from: frequency to convert from
  40. * @to: frequency to convert to
  41. * @maxsec: guaranteed runtime conversion range in seconds
  42. *
  43. * The function evaluates the shift/mult pair for the scaled math
  44. * operations of clocksources and clockevents.
  45. *
  46. * @to and @from are frequency values in HZ. For clock sources @to is
  47. * NSEC_PER_SEC == 1GHz and @from is the counter frequency. For clock
  48. * event @to is the counter frequency and @from is NSEC_PER_SEC.
  49. *
  50. * The @maxsec conversion range argument controls the time frame in
  51. * seconds which must be covered by the runtime conversion with the
  52. * calculated mult and shift factors. This guarantees that no 64bit
  53. * overflow happens when the input value of the conversion is
  54. * multiplied with the calculated mult factor. Larger ranges may
  55. * reduce the conversion accuracy by chosing smaller mult and shift
  56. * factors.
  57. */
  58. void
  59. clocks_calc_mult_shift(u32 *mult, u32 *shift, u32 from, u32 to, u32 maxsec)
  60. {
  61. u64 tmp;
  62. u32 sft, sftacc= 32;
  63. /*
  64. * Calculate the shift factor which is limiting the conversion
  65. * range:
  66. */
  67. tmp = ((u64)maxsec * from) >> 32;
  68. while (tmp) {
  69. tmp >>=1;
  70. sftacc--;
  71. }
  72. /*
  73. * Find the conversion shift/mult pair which has the best
  74. * accuracy and fits the maxsec conversion range:
  75. */
  76. for (sft = 32; sft > 0; sft--) {
  77. tmp = (u64) to << sft;
  78. tmp += from / 2;
  79. do_div(tmp, from);
  80. if ((tmp >> sftacc) == 0)
  81. break;
  82. }
  83. *mult = tmp;
  84. *shift = sft;
  85. }
  86. EXPORT_SYMBOL_GPL(clocks_calc_mult_shift);
  87. /*[Clocksource internal variables]---------
  88. * curr_clocksource:
  89. * currently selected clocksource.
  90. * suspend_clocksource:
  91. * used to calculate the suspend time.
  92. * clocksource_list:
  93. * linked list with the registered clocksources
  94. * clocksource_mutex:
  95. * protects manipulations to curr_clocksource and the clocksource_list
  96. * override_name:
  97. * Name of the user-specified clocksource.
  98. */
  99. static struct clocksource *curr_clocksource;
  100. static struct clocksource *suspend_clocksource;
  101. static LIST_HEAD(clocksource_list);
  102. static DEFINE_MUTEX(clocksource_mutex);
  103. static char override_name[CS_NAME_LEN];
  104. static int finished_booting;
  105. static u64 suspend_start;
  106. #ifdef CONFIG_CLOCKSOURCE_WATCHDOG
  107. static void clocksource_watchdog_work(struct work_struct *work);
  108. static void clocksource_select(void);
  109. static LIST_HEAD(watchdog_list);
  110. static struct clocksource *watchdog;
  111. static struct timer_list watchdog_timer;
  112. static DECLARE_WORK(watchdog_work, clocksource_watchdog_work);
  113. static DEFINE_SPINLOCK(watchdog_lock);
  114. static int watchdog_running;
  115. static atomic_t watchdog_reset_pending;
  116. static void inline clocksource_watchdog_lock(unsigned long *flags)
  117. {
  118. spin_lock_irqsave(&watchdog_lock, *flags);
  119. }
  120. static void inline clocksource_watchdog_unlock(unsigned long *flags)
  121. {
  122. spin_unlock_irqrestore(&watchdog_lock, *flags);
  123. }
  124. static int clocksource_watchdog_kthread(void *data);
  125. static void __clocksource_change_rating(struct clocksource *cs, int rating);
  126. /*
  127. * Interval: 0.5sec Threshold: 0.0625s
  128. */
  129. #define WATCHDOG_INTERVAL (HZ >> 1)
  130. #define WATCHDOG_THRESHOLD (NSEC_PER_SEC >> 4)
  131. static void clocksource_watchdog_work(struct work_struct *work)
  132. {
  133. /*
  134. * We cannot directly run clocksource_watchdog_kthread() here, because
  135. * clocksource_select() calls timekeeping_notify() which uses
  136. * stop_machine(). One cannot use stop_machine() from a workqueue() due
  137. * lock inversions wrt CPU hotplug.
  138. *
  139. * Also, we only ever run this work once or twice during the lifetime
  140. * of the kernel, so there is no point in creating a more permanent
  141. * kthread for this.
  142. *
  143. * If kthread_run fails the next watchdog scan over the
  144. * watchdog_list will find the unstable clock again.
  145. */
  146. kthread_run(clocksource_watchdog_kthread, NULL, "kwatchdog");
  147. }
  148. static void __clocksource_unstable(struct clocksource *cs)
  149. {
  150. cs->flags &= ~(CLOCK_SOURCE_VALID_FOR_HRES | CLOCK_SOURCE_WATCHDOG);
  151. cs->flags |= CLOCK_SOURCE_UNSTABLE;
  152. /*
  153. * If the clocksource is registered clocksource_watchdog_kthread() will
  154. * re-rate and re-select.
  155. */
  156. if (list_empty(&cs->list)) {
  157. cs->rating = 0;
  158. return;
  159. }
  160. if (cs->mark_unstable)
  161. cs->mark_unstable(cs);
  162. /* kick clocksource_watchdog_kthread() */
  163. if (finished_booting)
  164. schedule_work(&watchdog_work);
  165. }
  166. /**
  167. * clocksource_mark_unstable - mark clocksource unstable via watchdog
  168. * @cs: clocksource to be marked unstable
  169. *
  170. * This function is called by the x86 TSC code to mark clocksources as unstable;
  171. * it defers demotion and re-selection to a kthread.
  172. */
  173. void clocksource_mark_unstable(struct clocksource *cs)
  174. {
  175. unsigned long flags;
  176. spin_lock_irqsave(&watchdog_lock, flags);
  177. if (!(cs->flags & CLOCK_SOURCE_UNSTABLE)) {
  178. if (!list_empty(&cs->list) && list_empty(&cs->wd_list))
  179. list_add(&cs->wd_list, &watchdog_list);
  180. __clocksource_unstable(cs);
  181. }
  182. spin_unlock_irqrestore(&watchdog_lock, flags);
  183. }
  184. static void clocksource_watchdog(struct timer_list *unused)
  185. {
  186. struct clocksource *cs;
  187. u64 csnow, wdnow, cslast, wdlast, delta;
  188. int64_t wd_nsec, cs_nsec;
  189. int next_cpu, reset_pending;
  190. spin_lock(&watchdog_lock);
  191. if (!watchdog_running)
  192. goto out;
  193. reset_pending = atomic_read(&watchdog_reset_pending);
  194. list_for_each_entry(cs, &watchdog_list, wd_list) {
  195. /* Clocksource already marked unstable? */
  196. if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
  197. if (finished_booting)
  198. schedule_work(&watchdog_work);
  199. continue;
  200. }
  201. local_irq_disable();
  202. csnow = cs->read(cs);
  203. wdnow = watchdog->read(watchdog);
  204. local_irq_enable();
  205. /* Clocksource initialized ? */
  206. if (!(cs->flags & CLOCK_SOURCE_WATCHDOG) ||
  207. atomic_read(&watchdog_reset_pending)) {
  208. cs->flags |= CLOCK_SOURCE_WATCHDOG;
  209. cs->wd_last = wdnow;
  210. cs->cs_last = csnow;
  211. continue;
  212. }
  213. delta = clocksource_delta(wdnow, cs->wd_last, watchdog->mask);
  214. wd_nsec = clocksource_cyc2ns(delta, watchdog->mult,
  215. watchdog->shift);
  216. delta = clocksource_delta(csnow, cs->cs_last, cs->mask);
  217. cs_nsec = clocksource_cyc2ns(delta, cs->mult, cs->shift);
  218. wdlast = cs->wd_last; /* save these in case we print them */
  219. cslast = cs->cs_last;
  220. cs->cs_last = csnow;
  221. cs->wd_last = wdnow;
  222. if (atomic_read(&watchdog_reset_pending))
  223. continue;
  224. /* Check the deviation from the watchdog clocksource. */
  225. if (abs(cs_nsec - wd_nsec) > WATCHDOG_THRESHOLD) {
  226. pr_warn("timekeeping watchdog on CPU%d: Marking clocksource '%s' as unstable because the skew is too large:\n",
  227. smp_processor_id(), cs->name);
  228. pr_warn(" '%s' wd_now: %llx wd_last: %llx mask: %llx\n",
  229. watchdog->name, wdnow, wdlast, watchdog->mask);
  230. pr_warn(" '%s' cs_now: %llx cs_last: %llx mask: %llx\n",
  231. cs->name, csnow, cslast, cs->mask);
  232. __clocksource_unstable(cs);
  233. continue;
  234. }
  235. if (cs == curr_clocksource && cs->tick_stable)
  236. cs->tick_stable(cs);
  237. if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) &&
  238. (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS) &&
  239. (watchdog->flags & CLOCK_SOURCE_IS_CONTINUOUS)) {
  240. /* Mark it valid for high-res. */
  241. cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
  242. /*
  243. * clocksource_done_booting() will sort it if
  244. * finished_booting is not set yet.
  245. */
  246. if (!finished_booting)
  247. continue;
  248. /*
  249. * If this is not the current clocksource let
  250. * the watchdog thread reselect it. Due to the
  251. * change to high res this clocksource might
  252. * be preferred now. If it is the current
  253. * clocksource let the tick code know about
  254. * that change.
  255. */
  256. if (cs != curr_clocksource) {
  257. cs->flags |= CLOCK_SOURCE_RESELECT;
  258. schedule_work(&watchdog_work);
  259. } else {
  260. tick_clock_notify();
  261. }
  262. }
  263. }
  264. /*
  265. * We only clear the watchdog_reset_pending, when we did a
  266. * full cycle through all clocksources.
  267. */
  268. if (reset_pending)
  269. atomic_dec(&watchdog_reset_pending);
  270. /*
  271. * Cycle through CPUs to check if the CPUs stay synchronized
  272. * to each other.
  273. */
  274. next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
  275. if (next_cpu >= nr_cpu_ids)
  276. next_cpu = cpumask_first(cpu_online_mask);
  277. /*
  278. * Arm timer if not already pending: could race with concurrent
  279. * pair clocksource_stop_watchdog() clocksource_start_watchdog().
  280. */
  281. if (!timer_pending(&watchdog_timer)) {
  282. watchdog_timer.expires += WATCHDOG_INTERVAL;
  283. add_timer_on(&watchdog_timer, next_cpu);
  284. }
  285. out:
  286. spin_unlock(&watchdog_lock);
  287. }
  288. static inline void clocksource_start_watchdog(void)
  289. {
  290. if (watchdog_running || !watchdog || list_empty(&watchdog_list))
  291. return;
  292. timer_setup(&watchdog_timer, clocksource_watchdog, 0);
  293. watchdog_timer.expires = jiffies + WATCHDOG_INTERVAL;
  294. add_timer_on(&watchdog_timer, cpumask_first(cpu_online_mask));
  295. watchdog_running = 1;
  296. }
  297. static inline void clocksource_stop_watchdog(void)
  298. {
  299. if (!watchdog_running || (watchdog && !list_empty(&watchdog_list)))
  300. return;
  301. del_timer(&watchdog_timer);
  302. watchdog_running = 0;
  303. }
  304. static inline void clocksource_reset_watchdog(void)
  305. {
  306. struct clocksource *cs;
  307. list_for_each_entry(cs, &watchdog_list, wd_list)
  308. cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
  309. }
  310. static void clocksource_resume_watchdog(void)
  311. {
  312. atomic_inc(&watchdog_reset_pending);
  313. }
  314. static void clocksource_enqueue_watchdog(struct clocksource *cs)
  315. {
  316. INIT_LIST_HEAD(&cs->wd_list);
  317. if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
  318. /* cs is a clocksource to be watched. */
  319. list_add(&cs->wd_list, &watchdog_list);
  320. cs->flags &= ~CLOCK_SOURCE_WATCHDOG;
  321. } else {
  322. /* cs is a watchdog. */
  323. if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
  324. cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
  325. }
  326. }
  327. static void clocksource_select_watchdog(bool fallback)
  328. {
  329. struct clocksource *cs, *old_wd;
  330. unsigned long flags;
  331. spin_lock_irqsave(&watchdog_lock, flags);
  332. /* save current watchdog */
  333. old_wd = watchdog;
  334. if (fallback)
  335. watchdog = NULL;
  336. list_for_each_entry(cs, &clocksource_list, list) {
  337. /* cs is a clocksource to be watched. */
  338. if (cs->flags & CLOCK_SOURCE_MUST_VERIFY)
  339. continue;
  340. /* Skip current if we were requested for a fallback. */
  341. if (fallback && cs == old_wd)
  342. continue;
  343. /* Pick the best watchdog. */
  344. if (!watchdog || cs->rating > watchdog->rating)
  345. watchdog = cs;
  346. }
  347. /* If we failed to find a fallback restore the old one. */
  348. if (!watchdog)
  349. watchdog = old_wd;
  350. /* If we changed the watchdog we need to reset cycles. */
  351. if (watchdog != old_wd)
  352. clocksource_reset_watchdog();
  353. /* Check if the watchdog timer needs to be started. */
  354. clocksource_start_watchdog();
  355. spin_unlock_irqrestore(&watchdog_lock, flags);
  356. }
  357. static void clocksource_dequeue_watchdog(struct clocksource *cs)
  358. {
  359. if (cs != watchdog) {
  360. if (cs->flags & CLOCK_SOURCE_MUST_VERIFY) {
  361. /* cs is a watched clocksource. */
  362. list_del_init(&cs->wd_list);
  363. /* Check if the watchdog timer needs to be stopped. */
  364. clocksource_stop_watchdog();
  365. }
  366. }
  367. }
  368. static int __clocksource_watchdog_kthread(void)
  369. {
  370. struct clocksource *cs, *tmp;
  371. unsigned long flags;
  372. int select = 0;
  373. spin_lock_irqsave(&watchdog_lock, flags);
  374. list_for_each_entry_safe(cs, tmp, &watchdog_list, wd_list) {
  375. if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
  376. list_del_init(&cs->wd_list);
  377. __clocksource_change_rating(cs, 0);
  378. select = 1;
  379. }
  380. if (cs->flags & CLOCK_SOURCE_RESELECT) {
  381. cs->flags &= ~CLOCK_SOURCE_RESELECT;
  382. select = 1;
  383. }
  384. }
  385. /* Check if the watchdog timer needs to be stopped. */
  386. clocksource_stop_watchdog();
  387. spin_unlock_irqrestore(&watchdog_lock, flags);
  388. return select;
  389. }
  390. static int clocksource_watchdog_kthread(void *data)
  391. {
  392. mutex_lock(&clocksource_mutex);
  393. if (__clocksource_watchdog_kthread())
  394. clocksource_select();
  395. mutex_unlock(&clocksource_mutex);
  396. return 0;
  397. }
  398. static bool clocksource_is_watchdog(struct clocksource *cs)
  399. {
  400. return cs == watchdog;
  401. }
  402. #else /* CONFIG_CLOCKSOURCE_WATCHDOG */
  403. static void clocksource_enqueue_watchdog(struct clocksource *cs)
  404. {
  405. if (cs->flags & CLOCK_SOURCE_IS_CONTINUOUS)
  406. cs->flags |= CLOCK_SOURCE_VALID_FOR_HRES;
  407. }
  408. static void clocksource_select_watchdog(bool fallback) { }
  409. static inline void clocksource_dequeue_watchdog(struct clocksource *cs) { }
  410. static inline void clocksource_resume_watchdog(void) { }
  411. static inline int __clocksource_watchdog_kthread(void) { return 0; }
  412. static bool clocksource_is_watchdog(struct clocksource *cs) { return false; }
  413. void clocksource_mark_unstable(struct clocksource *cs) { }
  414. static inline void clocksource_watchdog_lock(unsigned long *flags) { }
  415. static inline void clocksource_watchdog_unlock(unsigned long *flags) { }
  416. #endif /* CONFIG_CLOCKSOURCE_WATCHDOG */
  417. static bool clocksource_is_suspend(struct clocksource *cs)
  418. {
  419. return cs == suspend_clocksource;
  420. }
  421. static void __clocksource_suspend_select(struct clocksource *cs)
  422. {
  423. /*
  424. * Skip the clocksource which will be stopped in suspend state.
  425. */
  426. if (!(cs->flags & CLOCK_SOURCE_SUSPEND_NONSTOP))
  427. return;
  428. /*
  429. * The nonstop clocksource can be selected as the suspend clocksource to
  430. * calculate the suspend time, so it should not supply suspend/resume
  431. * interfaces to suspend the nonstop clocksource when system suspends.
  432. */
  433. if (cs->suspend || cs->resume) {
  434. pr_warn("Nonstop clocksource %s should not supply suspend/resume interfaces\n",
  435. cs->name);
  436. }
  437. /* Pick the best rating. */
  438. if (!suspend_clocksource || cs->rating > suspend_clocksource->rating)
  439. suspend_clocksource = cs;
  440. }
  441. /**
  442. * clocksource_suspend_select - Select the best clocksource for suspend timing
  443. * @fallback: if select a fallback clocksource
  444. */
  445. static void clocksource_suspend_select(bool fallback)
  446. {
  447. struct clocksource *cs, *old_suspend;
  448. old_suspend = suspend_clocksource;
  449. if (fallback)
  450. suspend_clocksource = NULL;
  451. list_for_each_entry(cs, &clocksource_list, list) {
  452. /* Skip current if we were requested for a fallback. */
  453. if (fallback && cs == old_suspend)
  454. continue;
  455. __clocksource_suspend_select(cs);
  456. }
  457. }
  458. /**
  459. * clocksource_start_suspend_timing - Start measuring the suspend timing
  460. * @cs: current clocksource from timekeeping
  461. * @start_cycles: current cycles from timekeeping
  462. *
  463. * This function will save the start cycle values of suspend timer to calculate
  464. * the suspend time when resuming system.
  465. *
  466. * This function is called late in the suspend process from timekeeping_suspend(),
  467. * that means processes are freezed, non-boot cpus and interrupts are disabled
  468. * now. It is therefore possible to start the suspend timer without taking the
  469. * clocksource mutex.
  470. */
  471. void clocksource_start_suspend_timing(struct clocksource *cs, u64 start_cycles)
  472. {
  473. if (!suspend_clocksource)
  474. return;
  475. /*
  476. * If current clocksource is the suspend timer, we should use the
  477. * tkr_mono.cycle_last value as suspend_start to avoid same reading
  478. * from suspend timer.
  479. */
  480. if (clocksource_is_suspend(cs)) {
  481. suspend_start = start_cycles;
  482. return;
  483. }
  484. if (suspend_clocksource->enable &&
  485. suspend_clocksource->enable(suspend_clocksource)) {
  486. pr_warn_once("Failed to enable the non-suspend-able clocksource.\n");
  487. return;
  488. }
  489. suspend_start = suspend_clocksource->read(suspend_clocksource);
  490. }
  491. /**
  492. * clocksource_stop_suspend_timing - Stop measuring the suspend timing
  493. * @cs: current clocksource from timekeeping
  494. * @cycle_now: current cycles from timekeeping
  495. *
  496. * This function will calculate the suspend time from suspend timer.
  497. *
  498. * Returns nanoseconds since suspend started, 0 if no usable suspend clocksource.
  499. *
  500. * This function is called early in the resume process from timekeeping_resume(),
  501. * that means there is only one cpu, no processes are running and the interrupts
  502. * are disabled. It is therefore possible to stop the suspend timer without
  503. * taking the clocksource mutex.
  504. */
  505. u64 clocksource_stop_suspend_timing(struct clocksource *cs, u64 cycle_now)
  506. {
  507. u64 now, delta, nsec = 0;
  508. if (!suspend_clocksource)
  509. return 0;
  510. /*
  511. * If current clocksource is the suspend timer, we should use the
  512. * tkr_mono.cycle_last value from timekeeping as current cycle to
  513. * avoid same reading from suspend timer.
  514. */
  515. if (clocksource_is_suspend(cs))
  516. now = cycle_now;
  517. else
  518. now = suspend_clocksource->read(suspend_clocksource);
  519. if (now > suspend_start) {
  520. delta = clocksource_delta(now, suspend_start,
  521. suspend_clocksource->mask);
  522. nsec = mul_u64_u32_shr(delta, suspend_clocksource->mult,
  523. suspend_clocksource->shift);
  524. }
  525. /*
  526. * Disable the suspend timer to save power if current clocksource is
  527. * not the suspend timer.
  528. */
  529. if (!clocksource_is_suspend(cs) && suspend_clocksource->disable)
  530. suspend_clocksource->disable(suspend_clocksource);
  531. return nsec;
  532. }
  533. /**
  534. * clocksource_suspend - suspend the clocksource(s)
  535. */
  536. void clocksource_suspend(void)
  537. {
  538. struct clocksource *cs;
  539. list_for_each_entry_reverse(cs, &clocksource_list, list)
  540. if (cs->suspend)
  541. cs->suspend(cs);
  542. }
  543. /**
  544. * clocksource_resume - resume the clocksource(s)
  545. */
  546. void clocksource_resume(void)
  547. {
  548. struct clocksource *cs;
  549. list_for_each_entry(cs, &clocksource_list, list)
  550. if (cs->resume)
  551. cs->resume(cs);
  552. clocksource_resume_watchdog();
  553. }
  554. /**
  555. * clocksource_touch_watchdog - Update watchdog
  556. *
  557. * Update the watchdog after exception contexts such as kgdb so as not
  558. * to incorrectly trip the watchdog. This might fail when the kernel
  559. * was stopped in code which holds watchdog_lock.
  560. */
  561. void clocksource_touch_watchdog(void)
  562. {
  563. clocksource_resume_watchdog();
  564. }
  565. /**
  566. * clocksource_max_adjustment- Returns max adjustment amount
  567. * @cs: Pointer to clocksource
  568. *
  569. */
  570. static u32 clocksource_max_adjustment(struct clocksource *cs)
  571. {
  572. u64 ret;
  573. /*
  574. * We won't try to correct for more than 11% adjustments (110,000 ppm),
  575. */
  576. ret = (u64)cs->mult * 11;
  577. do_div(ret,100);
  578. return (u32)ret;
  579. }
  580. /**
  581. * clocks_calc_max_nsecs - Returns maximum nanoseconds that can be converted
  582. * @mult: cycle to nanosecond multiplier
  583. * @shift: cycle to nanosecond divisor (power of two)
  584. * @maxadj: maximum adjustment value to mult (~11%)
  585. * @mask: bitmask for two's complement subtraction of non 64 bit counters
  586. * @max_cyc: maximum cycle value before potential overflow (does not include
  587. * any safety margin)
  588. *
  589. * NOTE: This function includes a safety margin of 50%, in other words, we
  590. * return half the number of nanoseconds the hardware counter can technically
  591. * cover. This is done so that we can potentially detect problems caused by
  592. * delayed timers or bad hardware, which might result in time intervals that
  593. * are larger than what the math used can handle without overflows.
  594. */
  595. u64 clocks_calc_max_nsecs(u32 mult, u32 shift, u32 maxadj, u64 mask, u64 *max_cyc)
  596. {
  597. u64 max_nsecs, max_cycles;
  598. /*
  599. * Calculate the maximum number of cycles that we can pass to the
  600. * cyc2ns() function without overflowing a 64-bit result.
  601. */
  602. max_cycles = ULLONG_MAX;
  603. do_div(max_cycles, mult+maxadj);
  604. /*
  605. * The actual maximum number of cycles we can defer the clocksource is
  606. * determined by the minimum of max_cycles and mask.
  607. * Note: Here we subtract the maxadj to make sure we don't sleep for
  608. * too long if there's a large negative adjustment.
  609. */
  610. max_cycles = min(max_cycles, mask);
  611. max_nsecs = clocksource_cyc2ns(max_cycles, mult - maxadj, shift);
  612. /* return the max_cycles value as well if requested */
  613. if (max_cyc)
  614. *max_cyc = max_cycles;
  615. /* Return 50% of the actual maximum, so we can detect bad values */
  616. max_nsecs >>= 1;
  617. return max_nsecs;
  618. }
  619. /**
  620. * clocksource_update_max_deferment - Updates the clocksource max_idle_ns & max_cycles
  621. * @cs: Pointer to clocksource to be updated
  622. *
  623. */
  624. static inline void clocksource_update_max_deferment(struct clocksource *cs)
  625. {
  626. cs->max_idle_ns = clocks_calc_max_nsecs(cs->mult, cs->shift,
  627. cs->maxadj, cs->mask,
  628. &cs->max_cycles);
  629. }
  630. #ifndef CONFIG_ARCH_USES_GETTIMEOFFSET
  631. static struct clocksource *clocksource_find_best(bool oneshot, bool skipcur)
  632. {
  633. struct clocksource *cs;
  634. if (!finished_booting || list_empty(&clocksource_list))
  635. return NULL;
  636. /*
  637. * We pick the clocksource with the highest rating. If oneshot
  638. * mode is active, we pick the highres valid clocksource with
  639. * the best rating.
  640. */
  641. list_for_each_entry(cs, &clocksource_list, list) {
  642. if (skipcur && cs == curr_clocksource)
  643. continue;
  644. if (oneshot && !(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES))
  645. continue;
  646. return cs;
  647. }
  648. return NULL;
  649. }
  650. static void __clocksource_select(bool skipcur)
  651. {
  652. bool oneshot = tick_oneshot_mode_active();
  653. struct clocksource *best, *cs;
  654. /* Find the best suitable clocksource */
  655. best = clocksource_find_best(oneshot, skipcur);
  656. if (!best)
  657. return;
  658. if (!strlen(override_name))
  659. goto found;
  660. /* Check for the override clocksource. */
  661. list_for_each_entry(cs, &clocksource_list, list) {
  662. if (skipcur && cs == curr_clocksource)
  663. continue;
  664. if (strcmp(cs->name, override_name) != 0)
  665. continue;
  666. /*
  667. * Check to make sure we don't switch to a non-highres
  668. * capable clocksource if the tick code is in oneshot
  669. * mode (highres or nohz)
  670. */
  671. if (!(cs->flags & CLOCK_SOURCE_VALID_FOR_HRES) && oneshot) {
  672. /* Override clocksource cannot be used. */
  673. if (cs->flags & CLOCK_SOURCE_UNSTABLE) {
  674. pr_warn("Override clocksource %s is unstable and not HRT compatible - cannot switch while in HRT/NOHZ mode\n",
  675. cs->name);
  676. override_name[0] = 0;
  677. } else {
  678. /*
  679. * The override cannot be currently verified.
  680. * Deferring to let the watchdog check.
  681. */
  682. pr_info("Override clocksource %s is not currently HRT compatible - deferring\n",
  683. cs->name);
  684. }
  685. } else
  686. /* Override clocksource can be used. */
  687. best = cs;
  688. break;
  689. }
  690. found:
  691. if (curr_clocksource != best && !timekeeping_notify(best)) {
  692. pr_info("Switched to clocksource %s\n", best->name);
  693. curr_clocksource = best;
  694. }
  695. }
  696. /**
  697. * clocksource_select - Select the best clocksource available
  698. *
  699. * Private function. Must hold clocksource_mutex when called.
  700. *
  701. * Select the clocksource with the best rating, or the clocksource,
  702. * which is selected by userspace override.
  703. */
  704. static void clocksource_select(void)
  705. {
  706. __clocksource_select(false);
  707. }
  708. static void clocksource_select_fallback(void)
  709. {
  710. __clocksource_select(true);
  711. }
  712. #else /* !CONFIG_ARCH_USES_GETTIMEOFFSET */
  713. static inline void clocksource_select(void) { }
  714. static inline void clocksource_select_fallback(void) { }
  715. #endif
  716. /*
  717. * clocksource_done_booting - Called near the end of core bootup
  718. *
  719. * Hack to avoid lots of clocksource churn at boot time.
  720. * We use fs_initcall because we want this to start before
  721. * device_initcall but after subsys_initcall.
  722. */
  723. static int __init clocksource_done_booting(void)
  724. {
  725. mutex_lock(&clocksource_mutex);
  726. curr_clocksource = clocksource_default_clock();
  727. finished_booting = 1;
  728. /*
  729. * Run the watchdog first to eliminate unstable clock sources
  730. */
  731. __clocksource_watchdog_kthread();
  732. clocksource_select();
  733. mutex_unlock(&clocksource_mutex);
  734. return 0;
  735. }
  736. fs_initcall(clocksource_done_booting);
  737. /*
  738. * Enqueue the clocksource sorted by rating
  739. */
  740. static void clocksource_enqueue(struct clocksource *cs)
  741. {
  742. struct list_head *entry = &clocksource_list;
  743. struct clocksource *tmp;
  744. list_for_each_entry(tmp, &clocksource_list, list) {
  745. /* Keep track of the place, where to insert */
  746. if (tmp->rating < cs->rating)
  747. break;
  748. entry = &tmp->list;
  749. }
  750. list_add(&cs->list, entry);
  751. }
  752. /**
  753. * __clocksource_update_freq_scale - Used update clocksource with new freq
  754. * @cs: clocksource to be registered
  755. * @scale: Scale factor multiplied against freq to get clocksource hz
  756. * @freq: clocksource frequency (cycles per second) divided by scale
  757. *
  758. * This should only be called from the clocksource->enable() method.
  759. *
  760. * This *SHOULD NOT* be called directly! Please use the
  761. * __clocksource_update_freq_hz() or __clocksource_update_freq_khz() helper
  762. * functions.
  763. */
  764. void __clocksource_update_freq_scale(struct clocksource *cs, u32 scale, u32 freq)
  765. {
  766. u64 sec;
  767. /*
  768. * Default clocksources are *special* and self-define their mult/shift.
  769. * But, you're not special, so you should specify a freq value.
  770. */
  771. if (freq) {
  772. /*
  773. * Calc the maximum number of seconds which we can run before
  774. * wrapping around. For clocksources which have a mask > 32-bit
  775. * we need to limit the max sleep time to have a good
  776. * conversion precision. 10 minutes is still a reasonable
  777. * amount. That results in a shift value of 24 for a
  778. * clocksource with mask >= 40-bit and f >= 4GHz. That maps to
  779. * ~ 0.06ppm granularity for NTP.
  780. */
  781. sec = cs->mask;
  782. do_div(sec, freq);
  783. do_div(sec, scale);
  784. if (!sec)
  785. sec = 1;
  786. else if (sec > 600 && cs->mask > UINT_MAX)
  787. sec = 600;
  788. clocks_calc_mult_shift(&cs->mult, &cs->shift, freq,
  789. NSEC_PER_SEC / scale, sec * scale);
  790. }
  791. /*
  792. * Ensure clocksources that have large 'mult' values don't overflow
  793. * when adjusted.
  794. */
  795. cs->maxadj = clocksource_max_adjustment(cs);
  796. while (freq && ((cs->mult + cs->maxadj < cs->mult)
  797. || (cs->mult - cs->maxadj > cs->mult))) {
  798. cs->mult >>= 1;
  799. cs->shift--;
  800. cs->maxadj = clocksource_max_adjustment(cs);
  801. }
  802. /*
  803. * Only warn for *special* clocksources that self-define
  804. * their mult/shift values and don't specify a freq.
  805. */
  806. WARN_ONCE(cs->mult + cs->maxadj < cs->mult,
  807. "timekeeping: Clocksource %s might overflow on 11%% adjustment\n",
  808. cs->name);
  809. clocksource_update_max_deferment(cs);
  810. pr_info("%s: mask: 0x%llx max_cycles: 0x%llx, max_idle_ns: %lld ns\n",
  811. cs->name, cs->mask, cs->max_cycles, cs->max_idle_ns);
  812. }
  813. EXPORT_SYMBOL_GPL(__clocksource_update_freq_scale);
  814. /**
  815. * __clocksource_register_scale - Used to install new clocksources
  816. * @cs: clocksource to be registered
  817. * @scale: Scale factor multiplied against freq to get clocksource hz
  818. * @freq: clocksource frequency (cycles per second) divided by scale
  819. *
  820. * Returns -EBUSY if registration fails, zero otherwise.
  821. *
  822. * This *SHOULD NOT* be called directly! Please use the
  823. * clocksource_register_hz() or clocksource_register_khz helper functions.
  824. */
  825. int __clocksource_register_scale(struct clocksource *cs, u32 scale, u32 freq)
  826. {
  827. unsigned long flags;
  828. /* Initialize mult/shift and max_idle_ns */
  829. __clocksource_update_freq_scale(cs, scale, freq);
  830. /* Add clocksource to the clocksource list */
  831. mutex_lock(&clocksource_mutex);
  832. clocksource_watchdog_lock(&flags);
  833. clocksource_enqueue(cs);
  834. clocksource_enqueue_watchdog(cs);
  835. clocksource_watchdog_unlock(&flags);
  836. clocksource_select();
  837. clocksource_select_watchdog(false);
  838. __clocksource_suspend_select(cs);
  839. mutex_unlock(&clocksource_mutex);
  840. return 0;
  841. }
  842. EXPORT_SYMBOL_GPL(__clocksource_register_scale);
  843. static void __clocksource_change_rating(struct clocksource *cs, int rating)
  844. {
  845. list_del(&cs->list);
  846. cs->rating = rating;
  847. clocksource_enqueue(cs);
  848. }
  849. /**
  850. * clocksource_change_rating - Change the rating of a registered clocksource
  851. * @cs: clocksource to be changed
  852. * @rating: new rating
  853. */
  854. void clocksource_change_rating(struct clocksource *cs, int rating)
  855. {
  856. unsigned long flags;
  857. mutex_lock(&clocksource_mutex);
  858. clocksource_watchdog_lock(&flags);
  859. __clocksource_change_rating(cs, rating);
  860. clocksource_watchdog_unlock(&flags);
  861. clocksource_select();
  862. clocksource_select_watchdog(false);
  863. clocksource_suspend_select(false);
  864. mutex_unlock(&clocksource_mutex);
  865. }
  866. EXPORT_SYMBOL(clocksource_change_rating);
  867. /*
  868. * Unbind clocksource @cs. Called with clocksource_mutex held
  869. */
  870. static int clocksource_unbind(struct clocksource *cs)
  871. {
  872. unsigned long flags;
  873. if (clocksource_is_watchdog(cs)) {
  874. /* Select and try to install a replacement watchdog. */
  875. clocksource_select_watchdog(true);
  876. if (clocksource_is_watchdog(cs))
  877. return -EBUSY;
  878. }
  879. if (cs == curr_clocksource) {
  880. /* Select and try to install a replacement clock source */
  881. clocksource_select_fallback();
  882. if (curr_clocksource == cs)
  883. return -EBUSY;
  884. }
  885. if (clocksource_is_suspend(cs)) {
  886. /*
  887. * Select and try to install a replacement suspend clocksource.
  888. * If no replacement suspend clocksource, we will just let the
  889. * clocksource go and have no suspend clocksource.
  890. */
  891. clocksource_suspend_select(true);
  892. }
  893. clocksource_watchdog_lock(&flags);
  894. clocksource_dequeue_watchdog(cs);
  895. list_del_init(&cs->list);
  896. clocksource_watchdog_unlock(&flags);
  897. return 0;
  898. }
  899. /**
  900. * clocksource_unregister - remove a registered clocksource
  901. * @cs: clocksource to be unregistered
  902. */
  903. int clocksource_unregister(struct clocksource *cs)
  904. {
  905. int ret = 0;
  906. mutex_lock(&clocksource_mutex);
  907. if (!list_empty(&cs->list))
  908. ret = clocksource_unbind(cs);
  909. mutex_unlock(&clocksource_mutex);
  910. return ret;
  911. }
  912. EXPORT_SYMBOL(clocksource_unregister);
  913. #ifdef CONFIG_SYSFS
  914. /**
  915. * current_clocksource_show - sysfs interface for current clocksource
  916. * @dev: unused
  917. * @attr: unused
  918. * @buf: char buffer to be filled with clocksource list
  919. *
  920. * Provides sysfs interface for listing current clocksource.
  921. */
  922. static ssize_t current_clocksource_show(struct device *dev,
  923. struct device_attribute *attr,
  924. char *buf)
  925. {
  926. ssize_t count = 0;
  927. mutex_lock(&clocksource_mutex);
  928. count = snprintf(buf, PAGE_SIZE, "%s\n", curr_clocksource->name);
  929. mutex_unlock(&clocksource_mutex);
  930. return count;
  931. }
  932. ssize_t sysfs_get_uname(const char *buf, char *dst, size_t cnt)
  933. {
  934. size_t ret = cnt;
  935. /* strings from sysfs write are not 0 terminated! */
  936. if (!cnt || cnt >= CS_NAME_LEN)
  937. return -EINVAL;
  938. /* strip of \n: */
  939. if (buf[cnt-1] == '\n')
  940. cnt--;
  941. if (cnt > 0)
  942. memcpy(dst, buf, cnt);
  943. dst[cnt] = 0;
  944. return ret;
  945. }
  946. /**
  947. * current_clocksource_store - interface for manually overriding clocksource
  948. * @dev: unused
  949. * @attr: unused
  950. * @buf: name of override clocksource
  951. * @count: length of buffer
  952. *
  953. * Takes input from sysfs interface for manually overriding the default
  954. * clocksource selection.
  955. */
  956. static ssize_t current_clocksource_store(struct device *dev,
  957. struct device_attribute *attr,
  958. const char *buf, size_t count)
  959. {
  960. ssize_t ret;
  961. mutex_lock(&clocksource_mutex);
  962. ret = sysfs_get_uname(buf, override_name, count);
  963. if (ret >= 0)
  964. clocksource_select();
  965. mutex_unlock(&clocksource_mutex);
  966. return ret;
  967. }
  968. static DEVICE_ATTR_RW(current_clocksource);
  969. /**
  970. * unbind_clocksource_store - interface for manually unbinding clocksource
  971. * @dev: unused
  972. * @attr: unused
  973. * @buf: unused
  974. * @count: length of buffer
  975. *
  976. * Takes input from sysfs interface for manually unbinding a clocksource.
  977. */
  978. static ssize_t unbind_clocksource_store(struct device *dev,
  979. struct device_attribute *attr,
  980. const char *buf, size_t count)
  981. {
  982. struct clocksource *cs;
  983. char name[CS_NAME_LEN];
  984. ssize_t ret;
  985. ret = sysfs_get_uname(buf, name, count);
  986. if (ret < 0)
  987. return ret;
  988. ret = -ENODEV;
  989. mutex_lock(&clocksource_mutex);
  990. list_for_each_entry(cs, &clocksource_list, list) {
  991. if (strcmp(cs->name, name))
  992. continue;
  993. ret = clocksource_unbind(cs);
  994. break;
  995. }
  996. mutex_unlock(&clocksource_mutex);
  997. return ret ? ret : count;
  998. }
  999. static DEVICE_ATTR_WO(unbind_clocksource);
  1000. /**
  1001. * available_clocksource_show - sysfs interface for listing clocksource
  1002. * @dev: unused
  1003. * @attr: unused
  1004. * @buf: char buffer to be filled with clocksource list
  1005. *
  1006. * Provides sysfs interface for listing registered clocksources
  1007. */
  1008. static ssize_t available_clocksource_show(struct device *dev,
  1009. struct device_attribute *attr,
  1010. char *buf)
  1011. {
  1012. struct clocksource *src;
  1013. ssize_t count = 0;
  1014. mutex_lock(&clocksource_mutex);
  1015. list_for_each_entry(src, &clocksource_list, list) {
  1016. /*
  1017. * Don't show non-HRES clocksource if the tick code is
  1018. * in one shot mode (highres=on or nohz=on)
  1019. */
  1020. if (!tick_oneshot_mode_active() ||
  1021. (src->flags & CLOCK_SOURCE_VALID_FOR_HRES))
  1022. count += snprintf(buf + count,
  1023. max((ssize_t)PAGE_SIZE - count, (ssize_t)0),
  1024. "%s ", src->name);
  1025. }
  1026. mutex_unlock(&clocksource_mutex);
  1027. count += snprintf(buf + count,
  1028. max((ssize_t)PAGE_SIZE - count, (ssize_t)0), "\n");
  1029. return count;
  1030. }
  1031. static DEVICE_ATTR_RO(available_clocksource);
  1032. static struct attribute *clocksource_attrs[] = {
  1033. &dev_attr_current_clocksource.attr,
  1034. &dev_attr_unbind_clocksource.attr,
  1035. &dev_attr_available_clocksource.attr,
  1036. NULL
  1037. };
  1038. ATTRIBUTE_GROUPS(clocksource);
  1039. static struct bus_type clocksource_subsys = {
  1040. .name = "clocksource",
  1041. .dev_name = "clocksource",
  1042. };
  1043. static struct device device_clocksource = {
  1044. .id = 0,
  1045. .bus = &clocksource_subsys,
  1046. .groups = clocksource_groups,
  1047. };
  1048. static int __init init_clocksource_sysfs(void)
  1049. {
  1050. int error = subsys_system_register(&clocksource_subsys, NULL);
  1051. if (!error)
  1052. error = device_register(&device_clocksource);
  1053. return error;
  1054. }
  1055. device_initcall(init_clocksource_sysfs);
  1056. #endif /* CONFIG_SYSFS */
  1057. /**
  1058. * boot_override_clocksource - boot clock override
  1059. * @str: override name
  1060. *
  1061. * Takes a clocksource= boot argument and uses it
  1062. * as the clocksource override name.
  1063. */
  1064. static int __init boot_override_clocksource(char* str)
  1065. {
  1066. mutex_lock(&clocksource_mutex);
  1067. if (str)
  1068. strlcpy(override_name, str, sizeof(override_name));
  1069. mutex_unlock(&clocksource_mutex);
  1070. return 1;
  1071. }
  1072. __setup("clocksource=", boot_override_clocksource);
  1073. /**
  1074. * boot_override_clock - Compatibility layer for deprecated boot option
  1075. * @str: override name
  1076. *
  1077. * DEPRECATED! Takes a clock= boot argument and uses it
  1078. * as the clocksource override name
  1079. */
  1080. static int __init boot_override_clock(char* str)
  1081. {
  1082. if (!strcmp(str, "pmtmr")) {
  1083. pr_warn("clock=pmtmr is deprecated - use clocksource=acpi_pm\n");
  1084. return boot_override_clocksource("acpi_pm");
  1085. }
  1086. pr_warn("clock= boot option is deprecated - use clocksource=xyz\n");
  1087. return boot_override_clocksource(str);
  1088. }
  1089. __setup("clock=", boot_override_clock);