hrtimer.c 47 KB

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