hrtimer.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. /*
  2. * linux/kernel/hrtimer.c
  3. *
  4. * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
  5. * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
  6. * Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner
  7. *
  8. * High-resolution kernel timers
  9. *
  10. * In contrast to the low-resolution timeout API implemented in
  11. * kernel/timer.c, hrtimers provide finer resolution and accuracy
  12. * depending on system configuration and capabilities.
  13. *
  14. * These timers are currently used for:
  15. * - itimers
  16. * - POSIX timers
  17. * - nanosleep
  18. * - precise in-kernel timing
  19. *
  20. * Started by: Thomas Gleixner and Ingo Molnar
  21. *
  22. * Credits:
  23. * based on kernel/timer.c
  24. *
  25. * Help, testing, suggestions, bugfixes, improvements were
  26. * provided by:
  27. *
  28. * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
  29. * et. al.
  30. *
  31. * For licencing details see kernel-base/COPYING
  32. */
  33. #include <linux/cpu.h>
  34. #include <linux/export.h>
  35. #include <linux/percpu.h>
  36. #include <linux/hrtimer.h>
  37. #include <linux/notifier.h>
  38. #include <linux/syscalls.h>
  39. #include <linux/kallsyms.h>
  40. #include <linux/interrupt.h>
  41. #include <linux/tick.h>
  42. #include <linux/seq_file.h>
  43. #include <linux/err.h>
  44. #include <linux/debugobjects.h>
  45. #include <linux/sched.h>
  46. #include <linux/sched/sysctl.h>
  47. #include <linux/sched/rt.h>
  48. #include <linux/sched/deadline.h>
  49. #include <linux/timer.h>
  50. #include <linux/freezer.h>
  51. #include <asm/uaccess.h>
  52. #include <trace/events/timer.h>
  53. #include "tick-internal.h"
  54. /*
  55. * The timer bases:
  56. *
  57. * There are more clockids than hrtimer bases. Thus, we index
  58. * into the timer bases by the hrtimer_base_type enum. When trying
  59. * to reach a base using a clockid, hrtimer_clockid_to_base()
  60. * is used to convert from clockid to the proper hrtimer_base_type.
  61. */
  62. DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
  63. {
  64. .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
  65. .seq = SEQCNT_ZERO(hrtimer_bases.seq),
  66. .clock_base =
  67. {
  68. {
  69. .index = HRTIMER_BASE_MONOTONIC,
  70. .clockid = CLOCK_MONOTONIC,
  71. .get_time = &ktime_get,
  72. },
  73. {
  74. .index = HRTIMER_BASE_REALTIME,
  75. .clockid = CLOCK_REALTIME,
  76. .get_time = &ktime_get_real,
  77. },
  78. {
  79. .index = HRTIMER_BASE_BOOTTIME,
  80. .clockid = CLOCK_BOOTTIME,
  81. .get_time = &ktime_get_boottime,
  82. },
  83. {
  84. .index = HRTIMER_BASE_TAI,
  85. .clockid = CLOCK_TAI,
  86. .get_time = &ktime_get_clocktai,
  87. },
  88. }
  89. };
  90. static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
  91. /* Make sure we catch unsupported clockids */
  92. [0 ... MAX_CLOCKS - 1] = HRTIMER_MAX_CLOCK_BASES,
  93. [CLOCK_REALTIME] = HRTIMER_BASE_REALTIME,
  94. [CLOCK_MONOTONIC] = HRTIMER_BASE_MONOTONIC,
  95. [CLOCK_BOOTTIME] = HRTIMER_BASE_BOOTTIME,
  96. [CLOCK_TAI] = HRTIMER_BASE_TAI,
  97. };
  98. /*
  99. * Functions and macros which are different for UP/SMP systems are kept in a
  100. * single place
  101. */
  102. #ifdef CONFIG_SMP
  103. /*
  104. * We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base()
  105. * such that hrtimer_callback_running() can unconditionally dereference
  106. * timer->base->cpu_base
  107. */
  108. static struct hrtimer_cpu_base migration_cpu_base = {
  109. .seq = SEQCNT_ZERO(migration_cpu_base),
  110. .clock_base = { { .cpu_base = &migration_cpu_base, }, },
  111. };
  112. #define migration_base migration_cpu_base.clock_base[0]
  113. /*
  114. * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
  115. * means that all timers which are tied to this base via timer->base are
  116. * locked, and the base itself is locked too.
  117. *
  118. * So __run_timers/migrate_timers can safely modify all timers which could
  119. * be found on the lists/queues.
  120. *
  121. * When the timer's base is locked, and the timer removed from list, it is
  122. * possible to set timer->base = &migration_base and drop the lock: the timer
  123. * remains locked.
  124. */
  125. static
  126. struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
  127. unsigned long *flags)
  128. {
  129. struct hrtimer_clock_base *base;
  130. for (;;) {
  131. base = timer->base;
  132. if (likely(base != &migration_base)) {
  133. raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
  134. if (likely(base == timer->base))
  135. return base;
  136. /* The timer has migrated to another CPU: */
  137. raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
  138. }
  139. cpu_relax();
  140. }
  141. }
  142. /*
  143. * With HIGHRES=y we do not migrate the timer when it is expiring
  144. * before the next event on the target cpu because we cannot reprogram
  145. * the target cpu hardware and we would cause it to fire late.
  146. *
  147. * Called with cpu_base->lock of target cpu held.
  148. */
  149. static int
  150. hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
  151. {
  152. #ifdef CONFIG_HIGH_RES_TIMERS
  153. ktime_t expires;
  154. if (!new_base->cpu_base->hres_active)
  155. return 0;
  156. expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
  157. return expires.tv64 <= new_base->cpu_base->expires_next.tv64;
  158. #else
  159. return 0;
  160. #endif
  161. }
  162. #ifdef CONFIG_NO_HZ_COMMON
  163. static inline
  164. struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base,
  165. int pinned)
  166. {
  167. if (pinned || !base->migration_enabled)
  168. return base;
  169. return &per_cpu(hrtimer_bases, get_nohz_timer_target());
  170. }
  171. #else
  172. static inline
  173. struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base,
  174. int pinned)
  175. {
  176. return base;
  177. }
  178. #endif
  179. /*
  180. * We switch the timer base to a power-optimized selected CPU target,
  181. * if:
  182. * - NO_HZ_COMMON is enabled
  183. * - timer migration is enabled
  184. * - the timer callback is not running
  185. * - the timer is not the first expiring timer on the new target
  186. *
  187. * If one of the above requirements is not fulfilled we move the timer
  188. * to the current CPU or leave it on the previously assigned CPU if
  189. * the timer callback is currently running.
  190. */
  191. static inline struct hrtimer_clock_base *
  192. switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
  193. int pinned)
  194. {
  195. struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base;
  196. struct hrtimer_clock_base *new_base;
  197. int basenum = base->index;
  198. this_cpu_base = this_cpu_ptr(&hrtimer_bases);
  199. new_cpu_base = get_target_base(this_cpu_base, pinned);
  200. again:
  201. new_base = &new_cpu_base->clock_base[basenum];
  202. if (base != new_base) {
  203. /*
  204. * We are trying to move timer to new_base.
  205. * However we can't change timer's base while it is running,
  206. * so we keep it on the same CPU. No hassle vs. reprogramming
  207. * the event source in the high resolution case. The softirq
  208. * code will take care of this when the timer function has
  209. * completed. There is no conflict as we hold the lock until
  210. * the timer is enqueued.
  211. */
  212. if (unlikely(hrtimer_callback_running(timer)))
  213. return base;
  214. /* See the comment in lock_hrtimer_base() */
  215. timer->base = &migration_base;
  216. raw_spin_unlock(&base->cpu_base->lock);
  217. raw_spin_lock(&new_base->cpu_base->lock);
  218. if (new_cpu_base != this_cpu_base &&
  219. hrtimer_check_target(timer, new_base)) {
  220. raw_spin_unlock(&new_base->cpu_base->lock);
  221. raw_spin_lock(&base->cpu_base->lock);
  222. new_cpu_base = this_cpu_base;
  223. timer->base = base;
  224. goto again;
  225. }
  226. timer->base = new_base;
  227. } else {
  228. if (new_cpu_base != this_cpu_base &&
  229. hrtimer_check_target(timer, new_base)) {
  230. new_cpu_base = this_cpu_base;
  231. goto again;
  232. }
  233. }
  234. return new_base;
  235. }
  236. #else /* CONFIG_SMP */
  237. static inline struct hrtimer_clock_base *
  238. lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
  239. {
  240. struct hrtimer_clock_base *base = timer->base;
  241. raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
  242. return base;
  243. }
  244. # define switch_hrtimer_base(t, b, p) (b)
  245. #endif /* !CONFIG_SMP */
  246. /*
  247. * Functions for the union type storage format of ktime_t which are
  248. * too large for inlining:
  249. */
  250. #if BITS_PER_LONG < 64
  251. /*
  252. * Divide a ktime value by a nanosecond value
  253. */
  254. s64 __ktime_divns(const ktime_t kt, s64 div)
  255. {
  256. int sft = 0;
  257. s64 dclc;
  258. u64 tmp;
  259. dclc = ktime_to_ns(kt);
  260. tmp = dclc < 0 ? -dclc : dclc;
  261. /* Make sure the divisor is less than 2^32: */
  262. while (div >> 32) {
  263. sft++;
  264. div >>= 1;
  265. }
  266. tmp >>= sft;
  267. do_div(tmp, (unsigned long) div);
  268. return dclc < 0 ? -tmp : tmp;
  269. }
  270. EXPORT_SYMBOL_GPL(__ktime_divns);
  271. #endif /* BITS_PER_LONG >= 64 */
  272. /*
  273. * Add two ktime values and do a safety check for overflow:
  274. */
  275. ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
  276. {
  277. ktime_t res = ktime_add_unsafe(lhs, rhs);
  278. /*
  279. * We use KTIME_SEC_MAX here, the maximum timeout which we can
  280. * return to user space in a timespec:
  281. */
  282. if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
  283. res = ktime_set(KTIME_SEC_MAX, 0);
  284. return res;
  285. }
  286. EXPORT_SYMBOL_GPL(ktime_add_safe);
  287. #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
  288. static struct debug_obj_descr hrtimer_debug_descr;
  289. static void *hrtimer_debug_hint(void *addr)
  290. {
  291. return ((struct hrtimer *) addr)->function;
  292. }
  293. /*
  294. * fixup_init is called when:
  295. * - an active object is initialized
  296. */
  297. static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state)
  298. {
  299. struct hrtimer *timer = addr;
  300. switch (state) {
  301. case ODEBUG_STATE_ACTIVE:
  302. hrtimer_cancel(timer);
  303. debug_object_init(timer, &hrtimer_debug_descr);
  304. return true;
  305. default:
  306. return false;
  307. }
  308. }
  309. /*
  310. * fixup_activate is called when:
  311. * - an active object is activated
  312. * - an unknown non-static object is activated
  313. */
  314. static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
  315. {
  316. switch (state) {
  317. case ODEBUG_STATE_ACTIVE:
  318. WARN_ON(1);
  319. default:
  320. return false;
  321. }
  322. }
  323. /*
  324. * fixup_free is called when:
  325. * - an active object is freed
  326. */
  327. static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state)
  328. {
  329. struct hrtimer *timer = addr;
  330. switch (state) {
  331. case ODEBUG_STATE_ACTIVE:
  332. hrtimer_cancel(timer);
  333. debug_object_free(timer, &hrtimer_debug_descr);
  334. return true;
  335. default:
  336. return false;
  337. }
  338. }
  339. static struct debug_obj_descr hrtimer_debug_descr = {
  340. .name = "hrtimer",
  341. .debug_hint = hrtimer_debug_hint,
  342. .fixup_init = hrtimer_fixup_init,
  343. .fixup_activate = hrtimer_fixup_activate,
  344. .fixup_free = hrtimer_fixup_free,
  345. };
  346. static inline void debug_hrtimer_init(struct hrtimer *timer)
  347. {
  348. debug_object_init(timer, &hrtimer_debug_descr);
  349. }
  350. static inline void debug_hrtimer_activate(struct hrtimer *timer)
  351. {
  352. debug_object_activate(timer, &hrtimer_debug_descr);
  353. }
  354. static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
  355. {
  356. debug_object_deactivate(timer, &hrtimer_debug_descr);
  357. }
  358. static inline void debug_hrtimer_free(struct hrtimer *timer)
  359. {
  360. debug_object_free(timer, &hrtimer_debug_descr);
  361. }
  362. static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
  363. enum hrtimer_mode mode);
  364. void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
  365. enum hrtimer_mode mode)
  366. {
  367. debug_object_init_on_stack(timer, &hrtimer_debug_descr);
  368. __hrtimer_init(timer, clock_id, mode);
  369. }
  370. EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
  371. void destroy_hrtimer_on_stack(struct hrtimer *timer)
  372. {
  373. debug_object_free(timer, &hrtimer_debug_descr);
  374. }
  375. EXPORT_SYMBOL_GPL(destroy_hrtimer_on_stack);
  376. #else
  377. static inline void debug_hrtimer_init(struct hrtimer *timer) { }
  378. static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
  379. static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
  380. #endif
  381. static inline void
  382. debug_init(struct hrtimer *timer, clockid_t clockid,
  383. enum hrtimer_mode mode)
  384. {
  385. debug_hrtimer_init(timer);
  386. trace_hrtimer_init(timer, clockid, mode);
  387. }
  388. static inline void debug_activate(struct hrtimer *timer)
  389. {
  390. debug_hrtimer_activate(timer);
  391. trace_hrtimer_start(timer);
  392. }
  393. static inline void debug_deactivate(struct hrtimer *timer)
  394. {
  395. debug_hrtimer_deactivate(timer);
  396. trace_hrtimer_cancel(timer);
  397. }
  398. #if defined(CONFIG_NO_HZ_COMMON) || defined(CONFIG_HIGH_RES_TIMERS)
  399. static inline void hrtimer_update_next_timer(struct hrtimer_cpu_base *cpu_base,
  400. struct hrtimer *timer)
  401. {
  402. #ifdef CONFIG_HIGH_RES_TIMERS
  403. cpu_base->next_timer = timer;
  404. #endif
  405. }
  406. static ktime_t __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base)
  407. {
  408. struct hrtimer_clock_base *base = cpu_base->clock_base;
  409. ktime_t expires, expires_next = { .tv64 = KTIME_MAX };
  410. unsigned int active = cpu_base->active_bases;
  411. hrtimer_update_next_timer(cpu_base, NULL);
  412. for (; active; base++, active >>= 1) {
  413. struct timerqueue_node *next;
  414. struct hrtimer *timer;
  415. if (!(active & 0x01))
  416. continue;
  417. next = timerqueue_getnext(&base->active);
  418. timer = container_of(next, struct hrtimer, node);
  419. expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
  420. if (expires.tv64 < expires_next.tv64) {
  421. expires_next = expires;
  422. hrtimer_update_next_timer(cpu_base, timer);
  423. }
  424. }
  425. /*
  426. * clock_was_set() might have changed base->offset of any of
  427. * the clock bases so the result might be negative. Fix it up
  428. * to prevent a false positive in clockevents_program_event().
  429. */
  430. if (expires_next.tv64 < 0)
  431. expires_next.tv64 = 0;
  432. return expires_next;
  433. }
  434. #endif
  435. static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
  436. {
  437. ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
  438. ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
  439. ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
  440. return ktime_get_update_offsets_now(&base->clock_was_set_seq,
  441. offs_real, offs_boot, offs_tai);
  442. }
  443. /* High resolution timer related functions */
  444. #ifdef CONFIG_HIGH_RES_TIMERS
  445. /*
  446. * High resolution timer enabled ?
  447. */
  448. static bool hrtimer_hres_enabled __read_mostly = true;
  449. unsigned int hrtimer_resolution __read_mostly = LOW_RES_NSEC;
  450. EXPORT_SYMBOL_GPL(hrtimer_resolution);
  451. /*
  452. * Enable / Disable high resolution mode
  453. */
  454. static int __init setup_hrtimer_hres(char *str)
  455. {
  456. return (kstrtobool(str, &hrtimer_hres_enabled) == 0);
  457. }
  458. __setup("highres=", setup_hrtimer_hres);
  459. /*
  460. * hrtimer_high_res_enabled - query, if the highres mode is enabled
  461. */
  462. static inline int hrtimer_is_hres_enabled(void)
  463. {
  464. return hrtimer_hres_enabled;
  465. }
  466. /*
  467. * Is the high resolution mode active ?
  468. */
  469. static inline int __hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base)
  470. {
  471. return cpu_base->hres_active;
  472. }
  473. static inline int hrtimer_hres_active(void)
  474. {
  475. return __hrtimer_hres_active(this_cpu_ptr(&hrtimer_bases));
  476. }
  477. /*
  478. * Reprogram the event source with checking both queues for the
  479. * next event
  480. * Called with interrupts disabled and base->lock held
  481. */
  482. static void
  483. hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
  484. {
  485. ktime_t expires_next;
  486. if (!cpu_base->hres_active)
  487. return;
  488. expires_next = __hrtimer_get_next_event(cpu_base);
  489. if (skip_equal && expires_next.tv64 == cpu_base->expires_next.tv64)
  490. return;
  491. cpu_base->expires_next.tv64 = expires_next.tv64;
  492. /*
  493. * If a hang was detected in the last timer interrupt then we
  494. * leave the hang delay active in the hardware. We want the
  495. * system to make progress. That also prevents the following
  496. * scenario:
  497. * T1 expires 50ms from now
  498. * T2 expires 5s from now
  499. *
  500. * T1 is removed, so this code is called and would reprogram
  501. * the hardware to 5s from now. Any hrtimer_start after that
  502. * will not reprogram the hardware due to hang_detected being
  503. * set. So we'd effectivly block all timers until the T2 event
  504. * fires.
  505. */
  506. if (cpu_base->hang_detected)
  507. return;
  508. tick_program_event(cpu_base->expires_next, 1);
  509. }
  510. /*
  511. * When a timer is enqueued and expires earlier than the already enqueued
  512. * timers, we have to check, whether it expires earlier than the timer for
  513. * which the clock event device was armed.
  514. *
  515. * Called with interrupts disabled and base->cpu_base.lock held
  516. */
  517. static void hrtimer_reprogram(struct hrtimer *timer,
  518. struct hrtimer_clock_base *base)
  519. {
  520. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  521. ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
  522. WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
  523. /*
  524. * If the timer is not on the current cpu, we cannot reprogram
  525. * the other cpus clock event device.
  526. */
  527. if (base->cpu_base != cpu_base)
  528. return;
  529. /*
  530. * If the hrtimer interrupt is running, then it will
  531. * reevaluate the clock bases and reprogram the clock event
  532. * device. The callbacks are always executed in hard interrupt
  533. * context so we don't need an extra check for a running
  534. * callback.
  535. */
  536. if (cpu_base->in_hrtirq)
  537. return;
  538. /*
  539. * CLOCK_REALTIME timer might be requested with an absolute
  540. * expiry time which is less than base->offset. Set it to 0.
  541. */
  542. if (expires.tv64 < 0)
  543. expires.tv64 = 0;
  544. if (expires.tv64 >= cpu_base->expires_next.tv64)
  545. return;
  546. /* Update the pointer to the next expiring timer */
  547. cpu_base->next_timer = timer;
  548. /*
  549. * If a hang was detected in the last timer interrupt then we
  550. * do not schedule a timer which is earlier than the expiry
  551. * which we enforced in the hang detection. We want the system
  552. * to make progress.
  553. */
  554. if (cpu_base->hang_detected)
  555. return;
  556. /*
  557. * Program the timer hardware. We enforce the expiry for
  558. * events which are already in the past.
  559. */
  560. cpu_base->expires_next = expires;
  561. tick_program_event(expires, 1);
  562. }
  563. /*
  564. * Initialize the high resolution related parts of cpu_base
  565. */
  566. static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
  567. {
  568. base->expires_next.tv64 = KTIME_MAX;
  569. base->hang_detected = 0;
  570. base->hres_active = 0;
  571. base->next_timer = NULL;
  572. }
  573. /*
  574. * Retrigger next event is called after clock was set
  575. *
  576. * Called with interrupts disabled via on_each_cpu()
  577. */
  578. static void retrigger_next_event(void *arg)
  579. {
  580. struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
  581. if (!base->hres_active)
  582. return;
  583. raw_spin_lock(&base->lock);
  584. hrtimer_update_base(base);
  585. hrtimer_force_reprogram(base, 0);
  586. raw_spin_unlock(&base->lock);
  587. }
  588. /*
  589. * Switch to high resolution mode
  590. */
  591. static void hrtimer_switch_to_hres(void)
  592. {
  593. struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
  594. if (tick_init_highres()) {
  595. printk(KERN_WARNING "Could not switch to high resolution "
  596. "mode on CPU %d\n", base->cpu);
  597. return;
  598. }
  599. base->hres_active = 1;
  600. hrtimer_resolution = HIGH_RES_NSEC;
  601. tick_setup_sched_timer();
  602. /* "Retrigger" the interrupt to get things going */
  603. retrigger_next_event(NULL);
  604. }
  605. static void clock_was_set_work(struct work_struct *work)
  606. {
  607. clock_was_set();
  608. }
  609. static DECLARE_WORK(hrtimer_work, clock_was_set_work);
  610. /*
  611. * Called from timekeeping and resume code to reprogram the hrtimer
  612. * interrupt device on all cpus.
  613. */
  614. void clock_was_set_delayed(void)
  615. {
  616. schedule_work(&hrtimer_work);
  617. }
  618. #else
  619. static inline int __hrtimer_hres_active(struct hrtimer_cpu_base *b) { return 0; }
  620. static inline int hrtimer_hres_active(void) { return 0; }
  621. static inline int hrtimer_is_hres_enabled(void) { return 0; }
  622. static inline void hrtimer_switch_to_hres(void) { }
  623. static inline void
  624. hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
  625. static inline int hrtimer_reprogram(struct hrtimer *timer,
  626. struct hrtimer_clock_base *base)
  627. {
  628. return 0;
  629. }
  630. static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
  631. static inline void retrigger_next_event(void *arg) { }
  632. #endif /* CONFIG_HIGH_RES_TIMERS */
  633. /*
  634. * Clock realtime was set
  635. *
  636. * Change the offset of the realtime clock vs. the monotonic
  637. * clock.
  638. *
  639. * We might have to reprogram the high resolution timer interrupt. On
  640. * SMP we call the architecture specific code to retrigger _all_ high
  641. * resolution timer interrupts. On UP we just disable interrupts and
  642. * call the high resolution interrupt code.
  643. */
  644. void clock_was_set(void)
  645. {
  646. #ifdef CONFIG_HIGH_RES_TIMERS
  647. /* Retrigger the CPU local events everywhere */
  648. on_each_cpu(retrigger_next_event, NULL, 1);
  649. #endif
  650. timerfd_clock_was_set();
  651. }
  652. /*
  653. * During resume we might have to reprogram the high resolution timer
  654. * interrupt on all online CPUs. However, all other CPUs will be
  655. * stopped with IRQs interrupts disabled so the clock_was_set() call
  656. * must be deferred.
  657. */
  658. void hrtimers_resume(void)
  659. {
  660. WARN_ONCE(!irqs_disabled(),
  661. KERN_INFO "hrtimers_resume() called with IRQs enabled!");
  662. /* Retrigger on the local CPU */
  663. retrigger_next_event(NULL);
  664. /* And schedule a retrigger for all others */
  665. clock_was_set_delayed();
  666. }
  667. static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
  668. {
  669. #ifdef CONFIG_TIMER_STATS
  670. if (timer->start_site)
  671. return;
  672. timer->start_site = __builtin_return_address(0);
  673. memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
  674. timer->start_pid = current->pid;
  675. #endif
  676. }
  677. static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
  678. {
  679. #ifdef CONFIG_TIMER_STATS
  680. timer->start_site = NULL;
  681. #endif
  682. }
  683. static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
  684. {
  685. #ifdef CONFIG_TIMER_STATS
  686. if (likely(!timer_stats_active))
  687. return;
  688. timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
  689. timer->function, timer->start_comm, 0);
  690. #endif
  691. }
  692. /*
  693. * Counterpart to lock_hrtimer_base above:
  694. */
  695. static inline
  696. void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
  697. {
  698. raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
  699. }
  700. /**
  701. * hrtimer_forward - forward the timer expiry
  702. * @timer: hrtimer to forward
  703. * @now: forward past this time
  704. * @interval: the interval to forward
  705. *
  706. * Forward the timer expiry so it will expire in the future.
  707. * Returns the number of overruns.
  708. *
  709. * Can be safely called from the callback function of @timer. If
  710. * called from other contexts @timer must neither be enqueued nor
  711. * running the callback and the caller needs to take care of
  712. * serialization.
  713. *
  714. * Note: This only updates the timer expiry value and does not requeue
  715. * the timer.
  716. */
  717. u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
  718. {
  719. u64 orun = 1;
  720. ktime_t delta;
  721. delta = ktime_sub(now, hrtimer_get_expires(timer));
  722. if (delta.tv64 < 0)
  723. return 0;
  724. if (WARN_ON(timer->state & HRTIMER_STATE_ENQUEUED))
  725. return 0;
  726. if (interval.tv64 < hrtimer_resolution)
  727. interval.tv64 = hrtimer_resolution;
  728. if (unlikely(delta.tv64 >= interval.tv64)) {
  729. s64 incr = ktime_to_ns(interval);
  730. orun = ktime_divns(delta, incr);
  731. hrtimer_add_expires_ns(timer, incr * orun);
  732. if (hrtimer_get_expires_tv64(timer) > now.tv64)
  733. return orun;
  734. /*
  735. * This (and the ktime_add() below) is the
  736. * correction for exact:
  737. */
  738. orun++;
  739. }
  740. hrtimer_add_expires(timer, interval);
  741. return orun;
  742. }
  743. EXPORT_SYMBOL_GPL(hrtimer_forward);
  744. /*
  745. * enqueue_hrtimer - internal function to (re)start a timer
  746. *
  747. * The timer is inserted in expiry order. Insertion into the
  748. * red black tree is O(log(n)). Must hold the base lock.
  749. *
  750. * Returns 1 when the new timer is the leftmost timer in the tree.
  751. */
  752. static int enqueue_hrtimer(struct hrtimer *timer,
  753. struct hrtimer_clock_base *base)
  754. {
  755. debug_activate(timer);
  756. base->cpu_base->active_bases |= 1 << base->index;
  757. timer->state = HRTIMER_STATE_ENQUEUED;
  758. return timerqueue_add(&base->active, &timer->node);
  759. }
  760. /*
  761. * __remove_hrtimer - internal function to remove a timer
  762. *
  763. * Caller must hold the base lock.
  764. *
  765. * High resolution timer mode reprograms the clock event device when the
  766. * timer is the one which expires next. The caller can disable this by setting
  767. * reprogram to zero. This is useful, when the context does a reprogramming
  768. * anyway (e.g. timer interrupt)
  769. */
  770. static void __remove_hrtimer(struct hrtimer *timer,
  771. struct hrtimer_clock_base *base,
  772. u8 newstate, int reprogram)
  773. {
  774. struct hrtimer_cpu_base *cpu_base = base->cpu_base;
  775. u8 state = timer->state;
  776. timer->state = newstate;
  777. if (!(state & HRTIMER_STATE_ENQUEUED))
  778. return;
  779. if (!timerqueue_del(&base->active, &timer->node))
  780. cpu_base->active_bases &= ~(1 << base->index);
  781. #ifdef CONFIG_HIGH_RES_TIMERS
  782. /*
  783. * Note: If reprogram is false we do not update
  784. * cpu_base->next_timer. This happens when we remove the first
  785. * timer on a remote cpu. No harm as we never dereference
  786. * cpu_base->next_timer. So the worst thing what can happen is
  787. * an superflous call to hrtimer_force_reprogram() on the
  788. * remote cpu later on if the same timer gets enqueued again.
  789. */
  790. if (reprogram && timer == cpu_base->next_timer)
  791. hrtimer_force_reprogram(cpu_base, 1);
  792. #endif
  793. }
  794. /*
  795. * remove hrtimer, called with base lock held
  796. */
  797. static inline int
  798. remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base, bool restart)
  799. {
  800. if (hrtimer_is_queued(timer)) {
  801. u8 state = timer->state;
  802. int reprogram;
  803. /*
  804. * Remove the timer and force reprogramming when high
  805. * resolution mode is active and the timer is on the current
  806. * CPU. If we remove a timer on another CPU, reprogramming is
  807. * skipped. The interrupt event on this CPU is fired and
  808. * reprogramming happens in the interrupt handler. This is a
  809. * rare case and less expensive than a smp call.
  810. */
  811. debug_deactivate(timer);
  812. timer_stats_hrtimer_clear_start_info(timer);
  813. reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
  814. if (!restart)
  815. state = HRTIMER_STATE_INACTIVE;
  816. __remove_hrtimer(timer, base, state, reprogram);
  817. return 1;
  818. }
  819. return 0;
  820. }
  821. static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim,
  822. const enum hrtimer_mode mode)
  823. {
  824. #ifdef CONFIG_TIME_LOW_RES
  825. /*
  826. * CONFIG_TIME_LOW_RES indicates that the system has no way to return
  827. * granular time values. For relative timers we add hrtimer_resolution
  828. * (i.e. one jiffie) to prevent short timeouts.
  829. */
  830. timer->is_rel = mode & HRTIMER_MODE_REL;
  831. if (timer->is_rel)
  832. tim = ktime_add_safe(tim, ktime_set(0, hrtimer_resolution));
  833. #endif
  834. return tim;
  835. }
  836. /**
  837. * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
  838. * @timer: the timer to be added
  839. * @tim: expiry time
  840. * @delta_ns: "slack" range for the timer
  841. * @mode: expiry mode: absolute (HRTIMER_MODE_ABS) or
  842. * relative (HRTIMER_MODE_REL)
  843. */
  844. void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
  845. u64 delta_ns, const enum hrtimer_mode mode)
  846. {
  847. struct hrtimer_clock_base *base, *new_base;
  848. unsigned long flags;
  849. int leftmost;
  850. base = lock_hrtimer_base(timer, &flags);
  851. /* Remove an active timer from the queue: */
  852. remove_hrtimer(timer, base, true);
  853. if (mode & HRTIMER_MODE_REL)
  854. tim = ktime_add_safe(tim, base->get_time());
  855. tim = hrtimer_update_lowres(timer, tim, mode);
  856. hrtimer_set_expires_range_ns(timer, tim, delta_ns);
  857. /* Switch the timer base, if necessary: */
  858. new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
  859. timer_stats_hrtimer_set_start_info(timer);
  860. leftmost = enqueue_hrtimer(timer, new_base);
  861. if (!leftmost)
  862. goto unlock;
  863. if (!hrtimer_is_hres_active(timer)) {
  864. /*
  865. * Kick to reschedule the next tick to handle the new timer
  866. * on dynticks target.
  867. */
  868. if (new_base->cpu_base->nohz_active)
  869. wake_up_nohz_cpu(new_base->cpu_base->cpu);
  870. } else {
  871. hrtimer_reprogram(timer, new_base);
  872. }
  873. unlock:
  874. unlock_hrtimer_base(timer, &flags);
  875. }
  876. EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
  877. /**
  878. * hrtimer_try_to_cancel - try to deactivate a timer
  879. * @timer: hrtimer to stop
  880. *
  881. * Returns:
  882. * 0 when the timer was not active
  883. * 1 when the timer was active
  884. * -1 when the timer is currently excuting the callback function and
  885. * cannot be stopped
  886. */
  887. int hrtimer_try_to_cancel(struct hrtimer *timer)
  888. {
  889. struct hrtimer_clock_base *base;
  890. unsigned long flags;
  891. int ret = -1;
  892. /*
  893. * Check lockless first. If the timer is not active (neither
  894. * enqueued nor running the callback, nothing to do here. The
  895. * base lock does not serialize against a concurrent enqueue,
  896. * so we can avoid taking it.
  897. */
  898. if (!hrtimer_active(timer))
  899. return 0;
  900. base = lock_hrtimer_base(timer, &flags);
  901. if (!hrtimer_callback_running(timer))
  902. ret = remove_hrtimer(timer, base, false);
  903. unlock_hrtimer_base(timer, &flags);
  904. return ret;
  905. }
  906. EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
  907. /**
  908. * hrtimer_cancel - cancel a timer and wait for the handler to finish.
  909. * @timer: the timer to be cancelled
  910. *
  911. * Returns:
  912. * 0 when the timer was not active
  913. * 1 when the timer was active
  914. */
  915. int hrtimer_cancel(struct hrtimer *timer)
  916. {
  917. for (;;) {
  918. int ret = hrtimer_try_to_cancel(timer);
  919. if (ret >= 0)
  920. return ret;
  921. cpu_relax();
  922. }
  923. }
  924. EXPORT_SYMBOL_GPL(hrtimer_cancel);
  925. /**
  926. * hrtimer_get_remaining - get remaining time for the timer
  927. * @timer: the timer to read
  928. * @adjust: adjust relative timers when CONFIG_TIME_LOW_RES=y
  929. */
  930. ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
  931. {
  932. unsigned long flags;
  933. ktime_t rem;
  934. lock_hrtimer_base(timer, &flags);
  935. if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
  936. rem = hrtimer_expires_remaining_adjusted(timer);
  937. else
  938. rem = hrtimer_expires_remaining(timer);
  939. unlock_hrtimer_base(timer, &flags);
  940. return rem;
  941. }
  942. EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
  943. #ifdef CONFIG_NO_HZ_COMMON
  944. /**
  945. * hrtimer_get_next_event - get the time until next expiry event
  946. *
  947. * Returns the next expiry time or KTIME_MAX if no timer is pending.
  948. */
  949. u64 hrtimer_get_next_event(void)
  950. {
  951. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  952. u64 expires = KTIME_MAX;
  953. unsigned long flags;
  954. raw_spin_lock_irqsave(&cpu_base->lock, flags);
  955. if (!__hrtimer_hres_active(cpu_base))
  956. expires = __hrtimer_get_next_event(cpu_base).tv64;
  957. raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
  958. return expires;
  959. }
  960. #endif
  961. static inline int hrtimer_clockid_to_base(clockid_t clock_id)
  962. {
  963. if (likely(clock_id < MAX_CLOCKS)) {
  964. int base = hrtimer_clock_to_base_table[clock_id];
  965. if (likely(base != HRTIMER_MAX_CLOCK_BASES))
  966. return base;
  967. }
  968. WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
  969. return HRTIMER_BASE_MONOTONIC;
  970. }
  971. static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
  972. enum hrtimer_mode mode)
  973. {
  974. struct hrtimer_cpu_base *cpu_base;
  975. int base;
  976. memset(timer, 0, sizeof(struct hrtimer));
  977. cpu_base = raw_cpu_ptr(&hrtimer_bases);
  978. /*
  979. * POSIX magic: Relative CLOCK_REALTIME timers are not affected by
  980. * clock modifications, so they needs to become CLOCK_MONOTONIC to
  981. * ensure POSIX compliance.
  982. */
  983. if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL)
  984. clock_id = CLOCK_MONOTONIC;
  985. base = hrtimer_clockid_to_base(clock_id);
  986. timer->base = &cpu_base->clock_base[base];
  987. timerqueue_init(&timer->node);
  988. #ifdef CONFIG_TIMER_STATS
  989. timer->start_site = NULL;
  990. timer->start_pid = -1;
  991. memset(timer->start_comm, 0, TASK_COMM_LEN);
  992. #endif
  993. }
  994. /**
  995. * hrtimer_init - initialize a timer to the given clock
  996. * @timer: the timer to be initialized
  997. * @clock_id: the clock to be used
  998. * @mode: timer mode abs/rel
  999. */
  1000. void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
  1001. enum hrtimer_mode mode)
  1002. {
  1003. debug_init(timer, clock_id, mode);
  1004. __hrtimer_init(timer, clock_id, mode);
  1005. }
  1006. EXPORT_SYMBOL_GPL(hrtimer_init);
  1007. /*
  1008. * A timer is active, when it is enqueued into the rbtree or the
  1009. * callback function is running or it's in the state of being migrated
  1010. * to another cpu.
  1011. *
  1012. * It is important for this function to not return a false negative.
  1013. */
  1014. bool hrtimer_active(const struct hrtimer *timer)
  1015. {
  1016. struct hrtimer_cpu_base *cpu_base;
  1017. unsigned int seq;
  1018. do {
  1019. cpu_base = READ_ONCE(timer->base->cpu_base);
  1020. seq = raw_read_seqcount_begin(&cpu_base->seq);
  1021. if (timer->state != HRTIMER_STATE_INACTIVE ||
  1022. cpu_base->running == timer)
  1023. return true;
  1024. } while (read_seqcount_retry(&cpu_base->seq, seq) ||
  1025. cpu_base != READ_ONCE(timer->base->cpu_base));
  1026. return false;
  1027. }
  1028. EXPORT_SYMBOL_GPL(hrtimer_active);
  1029. /*
  1030. * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
  1031. * distinct sections:
  1032. *
  1033. * - queued: the timer is queued
  1034. * - callback: the timer is being ran
  1035. * - post: the timer is inactive or (re)queued
  1036. *
  1037. * On the read side we ensure we observe timer->state and cpu_base->running
  1038. * from the same section, if anything changed while we looked at it, we retry.
  1039. * This includes timer->base changing because sequence numbers alone are
  1040. * insufficient for that.
  1041. *
  1042. * The sequence numbers are required because otherwise we could still observe
  1043. * a false negative if the read side got smeared over multiple consequtive
  1044. * __run_hrtimer() invocations.
  1045. */
  1046. static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base,
  1047. struct hrtimer_clock_base *base,
  1048. struct hrtimer *timer, ktime_t *now)
  1049. {
  1050. enum hrtimer_restart (*fn)(struct hrtimer *);
  1051. int restart;
  1052. lockdep_assert_held(&cpu_base->lock);
  1053. debug_deactivate(timer);
  1054. cpu_base->running = timer;
  1055. /*
  1056. * Separate the ->running assignment from the ->state assignment.
  1057. *
  1058. * As with a regular write barrier, this ensures the read side in
  1059. * hrtimer_active() cannot observe cpu_base->running == NULL &&
  1060. * timer->state == INACTIVE.
  1061. */
  1062. raw_write_seqcount_barrier(&cpu_base->seq);
  1063. __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, 0);
  1064. timer_stats_account_hrtimer(timer);
  1065. fn = timer->function;
  1066. /*
  1067. * Clear the 'is relative' flag for the TIME_LOW_RES case. If the
  1068. * timer is restarted with a period then it becomes an absolute
  1069. * timer. If its not restarted it does not matter.
  1070. */
  1071. if (IS_ENABLED(CONFIG_TIME_LOW_RES))
  1072. timer->is_rel = false;
  1073. /*
  1074. * Because we run timers from hardirq context, there is no chance
  1075. * they get migrated to another cpu, therefore its safe to unlock
  1076. * the timer base.
  1077. */
  1078. raw_spin_unlock(&cpu_base->lock);
  1079. trace_hrtimer_expire_entry(timer, now);
  1080. restart = fn(timer);
  1081. trace_hrtimer_expire_exit(timer);
  1082. raw_spin_lock(&cpu_base->lock);
  1083. /*
  1084. * Note: We clear the running state after enqueue_hrtimer and
  1085. * we do not reprogram the event hardware. Happens either in
  1086. * hrtimer_start_range_ns() or in hrtimer_interrupt()
  1087. *
  1088. * Note: Because we dropped the cpu_base->lock above,
  1089. * hrtimer_start_range_ns() can have popped in and enqueued the timer
  1090. * for us already.
  1091. */
  1092. if (restart != HRTIMER_NORESTART &&
  1093. !(timer->state & HRTIMER_STATE_ENQUEUED))
  1094. enqueue_hrtimer(timer, base);
  1095. /*
  1096. * Separate the ->running assignment from the ->state assignment.
  1097. *
  1098. * As with a regular write barrier, this ensures the read side in
  1099. * hrtimer_active() cannot observe cpu_base->running == NULL &&
  1100. * timer->state == INACTIVE.
  1101. */
  1102. raw_write_seqcount_barrier(&cpu_base->seq);
  1103. WARN_ON_ONCE(cpu_base->running != timer);
  1104. cpu_base->running = NULL;
  1105. }
  1106. static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now)
  1107. {
  1108. struct hrtimer_clock_base *base = cpu_base->clock_base;
  1109. unsigned int active = cpu_base->active_bases;
  1110. for (; active; base++, active >>= 1) {
  1111. struct timerqueue_node *node;
  1112. ktime_t basenow;
  1113. if (!(active & 0x01))
  1114. continue;
  1115. basenow = ktime_add(now, base->offset);
  1116. while ((node = timerqueue_getnext(&base->active))) {
  1117. struct hrtimer *timer;
  1118. timer = container_of(node, struct hrtimer, node);
  1119. /*
  1120. * The immediate goal for using the softexpires is
  1121. * minimizing wakeups, not running timers at the
  1122. * earliest interrupt after their soft expiration.
  1123. * This allows us to avoid using a Priority Search
  1124. * Tree, which can answer a stabbing querry for
  1125. * overlapping intervals and instead use the simple
  1126. * BST we already have.
  1127. * We don't add extra wakeups by delaying timers that
  1128. * are right-of a not yet expired timer, because that
  1129. * timer will have to trigger a wakeup anyway.
  1130. */
  1131. if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer))
  1132. break;
  1133. __run_hrtimer(cpu_base, base, timer, &basenow);
  1134. }
  1135. }
  1136. }
  1137. #ifdef CONFIG_HIGH_RES_TIMERS
  1138. /*
  1139. * High resolution timer interrupt
  1140. * Called with interrupts disabled
  1141. */
  1142. void hrtimer_interrupt(struct clock_event_device *dev)
  1143. {
  1144. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  1145. ktime_t expires_next, now, entry_time, delta;
  1146. int retries = 0;
  1147. BUG_ON(!cpu_base->hres_active);
  1148. cpu_base->nr_events++;
  1149. dev->next_event.tv64 = KTIME_MAX;
  1150. raw_spin_lock(&cpu_base->lock);
  1151. entry_time = now = hrtimer_update_base(cpu_base);
  1152. retry:
  1153. cpu_base->in_hrtirq = 1;
  1154. /*
  1155. * We set expires_next to KTIME_MAX here with cpu_base->lock
  1156. * held to prevent that a timer is enqueued in our queue via
  1157. * the migration code. This does not affect enqueueing of
  1158. * timers which run their callback and need to be requeued on
  1159. * this CPU.
  1160. */
  1161. cpu_base->expires_next.tv64 = KTIME_MAX;
  1162. __hrtimer_run_queues(cpu_base, now);
  1163. /* Reevaluate the clock bases for the next expiry */
  1164. expires_next = __hrtimer_get_next_event(cpu_base);
  1165. /*
  1166. * Store the new expiry value so the migration code can verify
  1167. * against it.
  1168. */
  1169. cpu_base->expires_next = expires_next;
  1170. cpu_base->in_hrtirq = 0;
  1171. raw_spin_unlock(&cpu_base->lock);
  1172. /* Reprogramming necessary ? */
  1173. if (!tick_program_event(expires_next, 0)) {
  1174. cpu_base->hang_detected = 0;
  1175. return;
  1176. }
  1177. /*
  1178. * The next timer was already expired due to:
  1179. * - tracing
  1180. * - long lasting callbacks
  1181. * - being scheduled away when running in a VM
  1182. *
  1183. * We need to prevent that we loop forever in the hrtimer
  1184. * interrupt routine. We give it 3 attempts to avoid
  1185. * overreacting on some spurious event.
  1186. *
  1187. * Acquire base lock for updating the offsets and retrieving
  1188. * the current time.
  1189. */
  1190. raw_spin_lock(&cpu_base->lock);
  1191. now = hrtimer_update_base(cpu_base);
  1192. cpu_base->nr_retries++;
  1193. if (++retries < 3)
  1194. goto retry;
  1195. /*
  1196. * Give the system a chance to do something else than looping
  1197. * here. We stored the entry time, so we know exactly how long
  1198. * we spent here. We schedule the next event this amount of
  1199. * time away.
  1200. */
  1201. cpu_base->nr_hangs++;
  1202. cpu_base->hang_detected = 1;
  1203. raw_spin_unlock(&cpu_base->lock);
  1204. delta = ktime_sub(now, entry_time);
  1205. if ((unsigned int)delta.tv64 > cpu_base->max_hang_time)
  1206. cpu_base->max_hang_time = (unsigned int) delta.tv64;
  1207. /*
  1208. * Limit it to a sensible value as we enforce a longer
  1209. * delay. Give the CPU at least 100ms to catch up.
  1210. */
  1211. if (delta.tv64 > 100 * NSEC_PER_MSEC)
  1212. expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
  1213. else
  1214. expires_next = ktime_add(now, delta);
  1215. tick_program_event(expires_next, 1);
  1216. printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
  1217. ktime_to_ns(delta));
  1218. }
  1219. /*
  1220. * local version of hrtimer_peek_ahead_timers() called with interrupts
  1221. * disabled.
  1222. */
  1223. static inline void __hrtimer_peek_ahead_timers(void)
  1224. {
  1225. struct tick_device *td;
  1226. if (!hrtimer_hres_active())
  1227. return;
  1228. td = this_cpu_ptr(&tick_cpu_device);
  1229. if (td && td->evtdev)
  1230. hrtimer_interrupt(td->evtdev);
  1231. }
  1232. #else /* CONFIG_HIGH_RES_TIMERS */
  1233. static inline void __hrtimer_peek_ahead_timers(void) { }
  1234. #endif /* !CONFIG_HIGH_RES_TIMERS */
  1235. /*
  1236. * Called from run_local_timers in hardirq context every jiffy
  1237. */
  1238. void hrtimer_run_queues(void)
  1239. {
  1240. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  1241. ktime_t now;
  1242. if (__hrtimer_hres_active(cpu_base))
  1243. return;
  1244. /*
  1245. * This _is_ ugly: We have to check periodically, whether we
  1246. * can switch to highres and / or nohz mode. The clocksource
  1247. * switch happens with xtime_lock held. Notification from
  1248. * there only sets the check bit in the tick_oneshot code,
  1249. * otherwise we might deadlock vs. xtime_lock.
  1250. */
  1251. if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
  1252. hrtimer_switch_to_hres();
  1253. return;
  1254. }
  1255. raw_spin_lock(&cpu_base->lock);
  1256. now = hrtimer_update_base(cpu_base);
  1257. __hrtimer_run_queues(cpu_base, now);
  1258. raw_spin_unlock(&cpu_base->lock);
  1259. }
  1260. /*
  1261. * Sleep related functions:
  1262. */
  1263. static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
  1264. {
  1265. struct hrtimer_sleeper *t =
  1266. container_of(timer, struct hrtimer_sleeper, timer);
  1267. struct task_struct *task = t->task;
  1268. t->task = NULL;
  1269. if (task)
  1270. wake_up_process(task);
  1271. return HRTIMER_NORESTART;
  1272. }
  1273. void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
  1274. {
  1275. sl->timer.function = hrtimer_wakeup;
  1276. sl->task = task;
  1277. }
  1278. EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
  1279. static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
  1280. {
  1281. hrtimer_init_sleeper(t, current);
  1282. do {
  1283. set_current_state(TASK_INTERRUPTIBLE);
  1284. hrtimer_start_expires(&t->timer, mode);
  1285. if (likely(t->task))
  1286. freezable_schedule();
  1287. hrtimer_cancel(&t->timer);
  1288. mode = HRTIMER_MODE_ABS;
  1289. } while (t->task && !signal_pending(current));
  1290. __set_current_state(TASK_RUNNING);
  1291. return t->task == NULL;
  1292. }
  1293. static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
  1294. {
  1295. struct timespec rmt;
  1296. ktime_t rem;
  1297. rem = hrtimer_expires_remaining(timer);
  1298. if (rem.tv64 <= 0)
  1299. return 0;
  1300. rmt = ktime_to_timespec(rem);
  1301. if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
  1302. return -EFAULT;
  1303. return 1;
  1304. }
  1305. long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
  1306. {
  1307. struct hrtimer_sleeper t;
  1308. struct timespec __user *rmtp;
  1309. int ret = 0;
  1310. hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
  1311. HRTIMER_MODE_ABS);
  1312. hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
  1313. if (do_nanosleep(&t, HRTIMER_MODE_ABS))
  1314. goto out;
  1315. rmtp = restart->nanosleep.rmtp;
  1316. if (rmtp) {
  1317. ret = update_rmtp(&t.timer, rmtp);
  1318. if (ret <= 0)
  1319. goto out;
  1320. }
  1321. /* The other values in restart are already filled in */
  1322. ret = -ERESTART_RESTARTBLOCK;
  1323. out:
  1324. destroy_hrtimer_on_stack(&t.timer);
  1325. return ret;
  1326. }
  1327. long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
  1328. const enum hrtimer_mode mode, const clockid_t clockid)
  1329. {
  1330. struct restart_block *restart;
  1331. struct hrtimer_sleeper t;
  1332. int ret = 0;
  1333. u64 slack;
  1334. slack = current->timer_slack_ns;
  1335. if (dl_task(current) || rt_task(current))
  1336. slack = 0;
  1337. hrtimer_init_on_stack(&t.timer, clockid, mode);
  1338. hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
  1339. if (do_nanosleep(&t, mode))
  1340. goto out;
  1341. /* Absolute timers do not update the rmtp value and restart: */
  1342. if (mode == HRTIMER_MODE_ABS) {
  1343. ret = -ERESTARTNOHAND;
  1344. goto out;
  1345. }
  1346. if (rmtp) {
  1347. ret = update_rmtp(&t.timer, rmtp);
  1348. if (ret <= 0)
  1349. goto out;
  1350. }
  1351. restart = &current->restart_block;
  1352. restart->fn = hrtimer_nanosleep_restart;
  1353. restart->nanosleep.clockid = t.timer.base->clockid;
  1354. restart->nanosleep.rmtp = rmtp;
  1355. restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
  1356. ret = -ERESTART_RESTARTBLOCK;
  1357. out:
  1358. destroy_hrtimer_on_stack(&t.timer);
  1359. return ret;
  1360. }
  1361. SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
  1362. struct timespec __user *, rmtp)
  1363. {
  1364. struct timespec tu;
  1365. if (copy_from_user(&tu, rqtp, sizeof(tu)))
  1366. return -EFAULT;
  1367. if (!timespec_valid(&tu))
  1368. return -EINVAL;
  1369. return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
  1370. }
  1371. /*
  1372. * Functions related to boot-time initialization:
  1373. */
  1374. int hrtimers_prepare_cpu(unsigned int cpu)
  1375. {
  1376. struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
  1377. int i;
  1378. for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
  1379. cpu_base->clock_base[i].cpu_base = cpu_base;
  1380. timerqueue_init_head(&cpu_base->clock_base[i].active);
  1381. }
  1382. cpu_base->active_bases = 0;
  1383. cpu_base->cpu = cpu;
  1384. hrtimer_init_hres(cpu_base);
  1385. return 0;
  1386. }
  1387. #ifdef CONFIG_HOTPLUG_CPU
  1388. static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
  1389. struct hrtimer_clock_base *new_base)
  1390. {
  1391. struct hrtimer *timer;
  1392. struct timerqueue_node *node;
  1393. while ((node = timerqueue_getnext(&old_base->active))) {
  1394. timer = container_of(node, struct hrtimer, node);
  1395. BUG_ON(hrtimer_callback_running(timer));
  1396. debug_deactivate(timer);
  1397. /*
  1398. * Mark it as ENQUEUED not INACTIVE otherwise the
  1399. * timer could be seen as !active and just vanish away
  1400. * under us on another CPU
  1401. */
  1402. __remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, 0);
  1403. timer->base = new_base;
  1404. /*
  1405. * Enqueue the timers on the new cpu. This does not
  1406. * reprogram the event device in case the timer
  1407. * expires before the earliest on this CPU, but we run
  1408. * hrtimer_interrupt after we migrated everything to
  1409. * sort out already expired timers and reprogram the
  1410. * event device.
  1411. */
  1412. enqueue_hrtimer(timer, new_base);
  1413. }
  1414. }
  1415. int hrtimers_dead_cpu(unsigned int scpu)
  1416. {
  1417. struct hrtimer_cpu_base *old_base, *new_base;
  1418. int i;
  1419. BUG_ON(cpu_online(scpu));
  1420. tick_cancel_sched_timer(scpu);
  1421. local_irq_disable();
  1422. old_base = &per_cpu(hrtimer_bases, scpu);
  1423. new_base = this_cpu_ptr(&hrtimer_bases);
  1424. /*
  1425. * The caller is globally serialized and nobody else
  1426. * takes two locks at once, deadlock is not possible.
  1427. */
  1428. raw_spin_lock(&new_base->lock);
  1429. raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
  1430. for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
  1431. migrate_hrtimer_list(&old_base->clock_base[i],
  1432. &new_base->clock_base[i]);
  1433. }
  1434. raw_spin_unlock(&old_base->lock);
  1435. raw_spin_unlock(&new_base->lock);
  1436. /* Check, if we got expired work to do */
  1437. __hrtimer_peek_ahead_timers();
  1438. local_irq_enable();
  1439. return 0;
  1440. }
  1441. #endif /* CONFIG_HOTPLUG_CPU */
  1442. void __init hrtimers_init(void)
  1443. {
  1444. hrtimers_prepare_cpu(smp_processor_id());
  1445. }
  1446. /**
  1447. * schedule_hrtimeout_range_clock - sleep until timeout
  1448. * @expires: timeout value (ktime_t)
  1449. * @delta: slack in expires timeout (ktime_t)
  1450. * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
  1451. * @clock: timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
  1452. */
  1453. int __sched
  1454. schedule_hrtimeout_range_clock(ktime_t *expires, u64 delta,
  1455. const enum hrtimer_mode mode, int clock)
  1456. {
  1457. struct hrtimer_sleeper t;
  1458. /*
  1459. * Optimize when a zero timeout value is given. It does not
  1460. * matter whether this is an absolute or a relative time.
  1461. */
  1462. if (expires && !expires->tv64) {
  1463. __set_current_state(TASK_RUNNING);
  1464. return 0;
  1465. }
  1466. /*
  1467. * A NULL parameter means "infinite"
  1468. */
  1469. if (!expires) {
  1470. schedule();
  1471. return -EINTR;
  1472. }
  1473. hrtimer_init_on_stack(&t.timer, clock, mode);
  1474. hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
  1475. hrtimer_init_sleeper(&t, current);
  1476. hrtimer_start_expires(&t.timer, mode);
  1477. if (likely(t.task))
  1478. schedule();
  1479. hrtimer_cancel(&t.timer);
  1480. destroy_hrtimer_on_stack(&t.timer);
  1481. __set_current_state(TASK_RUNNING);
  1482. return !t.task ? 0 : -EINTR;
  1483. }
  1484. /**
  1485. * schedule_hrtimeout_range - sleep until timeout
  1486. * @expires: timeout value (ktime_t)
  1487. * @delta: slack in expires timeout (ktime_t)
  1488. * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
  1489. *
  1490. * Make the current task sleep until the given expiry time has
  1491. * elapsed. The routine will return immediately unless
  1492. * the current task state has been set (see set_current_state()).
  1493. *
  1494. * The @delta argument gives the kernel the freedom to schedule the
  1495. * actual wakeup to a time that is both power and performance friendly.
  1496. * The kernel give the normal best effort behavior for "@expires+@delta",
  1497. * but may decide to fire the timer earlier, but no earlier than @expires.
  1498. *
  1499. * You can set the task state as follows -
  1500. *
  1501. * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
  1502. * pass before the routine returns.
  1503. *
  1504. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1505. * delivered to the current task.
  1506. *
  1507. * The current task state is guaranteed to be TASK_RUNNING when this
  1508. * routine returns.
  1509. *
  1510. * Returns 0 when the timer has expired otherwise -EINTR
  1511. */
  1512. int __sched schedule_hrtimeout_range(ktime_t *expires, u64 delta,
  1513. const enum hrtimer_mode mode)
  1514. {
  1515. return schedule_hrtimeout_range_clock(expires, delta, mode,
  1516. CLOCK_MONOTONIC);
  1517. }
  1518. EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
  1519. /**
  1520. * schedule_hrtimeout - sleep until timeout
  1521. * @expires: timeout value (ktime_t)
  1522. * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
  1523. *
  1524. * Make the current task sleep until the given expiry time has
  1525. * elapsed. The routine will return immediately unless
  1526. * the current task state has been set (see set_current_state()).
  1527. *
  1528. * You can set the task state as follows -
  1529. *
  1530. * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
  1531. * pass before the routine returns.
  1532. *
  1533. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1534. * delivered to the current task.
  1535. *
  1536. * The current task state is guaranteed to be TASK_RUNNING when this
  1537. * routine returns.
  1538. *
  1539. * Returns 0 when the timer has expired otherwise -EINTR
  1540. */
  1541. int __sched schedule_hrtimeout(ktime_t *expires,
  1542. const enum hrtimer_mode mode)
  1543. {
  1544. return schedule_hrtimeout_range(expires, 0, mode);
  1545. }
  1546. EXPORT_SYMBOL_GPL(schedule_hrtimeout);