hrtimer.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  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->hres_active = 0;
  570. }
  571. /*
  572. * Retrigger next event is called after clock was set
  573. *
  574. * Called with interrupts disabled via on_each_cpu()
  575. */
  576. static void retrigger_next_event(void *arg)
  577. {
  578. struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
  579. if (!base->hres_active)
  580. return;
  581. raw_spin_lock(&base->lock);
  582. hrtimer_update_base(base);
  583. hrtimer_force_reprogram(base, 0);
  584. raw_spin_unlock(&base->lock);
  585. }
  586. /*
  587. * Switch to high resolution mode
  588. */
  589. static void hrtimer_switch_to_hres(void)
  590. {
  591. struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
  592. if (tick_init_highres()) {
  593. printk(KERN_WARNING "Could not switch to high resolution "
  594. "mode on CPU %d\n", base->cpu);
  595. return;
  596. }
  597. base->hres_active = 1;
  598. hrtimer_resolution = HIGH_RES_NSEC;
  599. tick_setup_sched_timer();
  600. /* "Retrigger" the interrupt to get things going */
  601. retrigger_next_event(NULL);
  602. }
  603. static void clock_was_set_work(struct work_struct *work)
  604. {
  605. clock_was_set();
  606. }
  607. static DECLARE_WORK(hrtimer_work, clock_was_set_work);
  608. /*
  609. * Called from timekeeping and resume code to reprogram the hrtimer
  610. * interrupt device on all cpus.
  611. */
  612. void clock_was_set_delayed(void)
  613. {
  614. schedule_work(&hrtimer_work);
  615. }
  616. #else
  617. static inline int __hrtimer_hres_active(struct hrtimer_cpu_base *b) { return 0; }
  618. static inline int hrtimer_hres_active(void) { return 0; }
  619. static inline int hrtimer_is_hres_enabled(void) { return 0; }
  620. static inline void hrtimer_switch_to_hres(void) { }
  621. static inline void
  622. hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
  623. static inline int hrtimer_reprogram(struct hrtimer *timer,
  624. struct hrtimer_clock_base *base)
  625. {
  626. return 0;
  627. }
  628. static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
  629. static inline void retrigger_next_event(void *arg) { }
  630. #endif /* CONFIG_HIGH_RES_TIMERS */
  631. /*
  632. * Clock realtime was set
  633. *
  634. * Change the offset of the realtime clock vs. the monotonic
  635. * clock.
  636. *
  637. * We might have to reprogram the high resolution timer interrupt. On
  638. * SMP we call the architecture specific code to retrigger _all_ high
  639. * resolution timer interrupts. On UP we just disable interrupts and
  640. * call the high resolution interrupt code.
  641. */
  642. void clock_was_set(void)
  643. {
  644. #ifdef CONFIG_HIGH_RES_TIMERS
  645. /* Retrigger the CPU local events everywhere */
  646. on_each_cpu(retrigger_next_event, NULL, 1);
  647. #endif
  648. timerfd_clock_was_set();
  649. }
  650. /*
  651. * During resume we might have to reprogram the high resolution timer
  652. * interrupt on all online CPUs. However, all other CPUs will be
  653. * stopped with IRQs interrupts disabled so the clock_was_set() call
  654. * must be deferred.
  655. */
  656. void hrtimers_resume(void)
  657. {
  658. WARN_ONCE(!irqs_disabled(),
  659. KERN_INFO "hrtimers_resume() called with IRQs enabled!");
  660. /* Retrigger on the local CPU */
  661. retrigger_next_event(NULL);
  662. /* And schedule a retrigger for all others */
  663. clock_was_set_delayed();
  664. }
  665. static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
  666. {
  667. #ifdef CONFIG_TIMER_STATS
  668. if (timer->start_site)
  669. return;
  670. timer->start_site = __builtin_return_address(0);
  671. memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
  672. timer->start_pid = current->pid;
  673. #endif
  674. }
  675. static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
  676. {
  677. #ifdef CONFIG_TIMER_STATS
  678. timer->start_site = NULL;
  679. #endif
  680. }
  681. static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
  682. {
  683. #ifdef CONFIG_TIMER_STATS
  684. if (likely(!timer_stats_active))
  685. return;
  686. timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
  687. timer->function, timer->start_comm, 0);
  688. #endif
  689. }
  690. /*
  691. * Counterpart to lock_hrtimer_base above:
  692. */
  693. static inline
  694. void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
  695. {
  696. raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
  697. }
  698. /**
  699. * hrtimer_forward - forward the timer expiry
  700. * @timer: hrtimer to forward
  701. * @now: forward past this time
  702. * @interval: the interval to forward
  703. *
  704. * Forward the timer expiry so it will expire in the future.
  705. * Returns the number of overruns.
  706. *
  707. * Can be safely called from the callback function of @timer. If
  708. * called from other contexts @timer must neither be enqueued nor
  709. * running the callback and the caller needs to take care of
  710. * serialization.
  711. *
  712. * Note: This only updates the timer expiry value and does not requeue
  713. * the timer.
  714. */
  715. u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
  716. {
  717. u64 orun = 1;
  718. ktime_t delta;
  719. delta = ktime_sub(now, hrtimer_get_expires(timer));
  720. if (delta.tv64 < 0)
  721. return 0;
  722. if (WARN_ON(timer->state & HRTIMER_STATE_ENQUEUED))
  723. return 0;
  724. if (interval.tv64 < hrtimer_resolution)
  725. interval.tv64 = hrtimer_resolution;
  726. if (unlikely(delta.tv64 >= interval.tv64)) {
  727. s64 incr = ktime_to_ns(interval);
  728. orun = ktime_divns(delta, incr);
  729. hrtimer_add_expires_ns(timer, incr * orun);
  730. if (hrtimer_get_expires_tv64(timer) > now.tv64)
  731. return orun;
  732. /*
  733. * This (and the ktime_add() below) is the
  734. * correction for exact:
  735. */
  736. orun++;
  737. }
  738. hrtimer_add_expires(timer, interval);
  739. return orun;
  740. }
  741. EXPORT_SYMBOL_GPL(hrtimer_forward);
  742. /*
  743. * enqueue_hrtimer - internal function to (re)start a timer
  744. *
  745. * The timer is inserted in expiry order. Insertion into the
  746. * red black tree is O(log(n)). Must hold the base lock.
  747. *
  748. * Returns 1 when the new timer is the leftmost timer in the tree.
  749. */
  750. static int enqueue_hrtimer(struct hrtimer *timer,
  751. struct hrtimer_clock_base *base)
  752. {
  753. debug_activate(timer);
  754. base->cpu_base->active_bases |= 1 << base->index;
  755. timer->state = HRTIMER_STATE_ENQUEUED;
  756. return timerqueue_add(&base->active, &timer->node);
  757. }
  758. /*
  759. * __remove_hrtimer - internal function to remove a timer
  760. *
  761. * Caller must hold the base lock.
  762. *
  763. * High resolution timer mode reprograms the clock event device when the
  764. * timer is the one which expires next. The caller can disable this by setting
  765. * reprogram to zero. This is useful, when the context does a reprogramming
  766. * anyway (e.g. timer interrupt)
  767. */
  768. static void __remove_hrtimer(struct hrtimer *timer,
  769. struct hrtimer_clock_base *base,
  770. u8 newstate, int reprogram)
  771. {
  772. struct hrtimer_cpu_base *cpu_base = base->cpu_base;
  773. u8 state = timer->state;
  774. timer->state = newstate;
  775. if (!(state & HRTIMER_STATE_ENQUEUED))
  776. return;
  777. if (!timerqueue_del(&base->active, &timer->node))
  778. cpu_base->active_bases &= ~(1 << base->index);
  779. #ifdef CONFIG_HIGH_RES_TIMERS
  780. /*
  781. * Note: If reprogram is false we do not update
  782. * cpu_base->next_timer. This happens when we remove the first
  783. * timer on a remote cpu. No harm as we never dereference
  784. * cpu_base->next_timer. So the worst thing what can happen is
  785. * an superflous call to hrtimer_force_reprogram() on the
  786. * remote cpu later on if the same timer gets enqueued again.
  787. */
  788. if (reprogram && timer == cpu_base->next_timer)
  789. hrtimer_force_reprogram(cpu_base, 1);
  790. #endif
  791. }
  792. /*
  793. * remove hrtimer, called with base lock held
  794. */
  795. static inline int
  796. remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base, bool restart)
  797. {
  798. if (hrtimer_is_queued(timer)) {
  799. u8 state = timer->state;
  800. int reprogram;
  801. /*
  802. * Remove the timer and force reprogramming when high
  803. * resolution mode is active and the timer is on the current
  804. * CPU. If we remove a timer on another CPU, reprogramming is
  805. * skipped. The interrupt event on this CPU is fired and
  806. * reprogramming happens in the interrupt handler. This is a
  807. * rare case and less expensive than a smp call.
  808. */
  809. debug_deactivate(timer);
  810. timer_stats_hrtimer_clear_start_info(timer);
  811. reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
  812. if (!restart)
  813. state = HRTIMER_STATE_INACTIVE;
  814. __remove_hrtimer(timer, base, state, reprogram);
  815. return 1;
  816. }
  817. return 0;
  818. }
  819. static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim,
  820. const enum hrtimer_mode mode)
  821. {
  822. #ifdef CONFIG_TIME_LOW_RES
  823. /*
  824. * CONFIG_TIME_LOW_RES indicates that the system has no way to return
  825. * granular time values. For relative timers we add hrtimer_resolution
  826. * (i.e. one jiffie) to prevent short timeouts.
  827. */
  828. timer->is_rel = mode & HRTIMER_MODE_REL;
  829. if (timer->is_rel)
  830. tim = ktime_add_safe(tim, ktime_set(0, hrtimer_resolution));
  831. #endif
  832. return tim;
  833. }
  834. /**
  835. * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
  836. * @timer: the timer to be added
  837. * @tim: expiry time
  838. * @delta_ns: "slack" range for the timer
  839. * @mode: expiry mode: absolute (HRTIMER_MODE_ABS) or
  840. * relative (HRTIMER_MODE_REL)
  841. */
  842. void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
  843. u64 delta_ns, const enum hrtimer_mode mode)
  844. {
  845. struct hrtimer_clock_base *base, *new_base;
  846. unsigned long flags;
  847. int leftmost;
  848. base = lock_hrtimer_base(timer, &flags);
  849. /* Remove an active timer from the queue: */
  850. remove_hrtimer(timer, base, true);
  851. if (mode & HRTIMER_MODE_REL)
  852. tim = ktime_add_safe(tim, base->get_time());
  853. tim = hrtimer_update_lowres(timer, tim, mode);
  854. hrtimer_set_expires_range_ns(timer, tim, delta_ns);
  855. /* Switch the timer base, if necessary: */
  856. new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
  857. timer_stats_hrtimer_set_start_info(timer);
  858. leftmost = enqueue_hrtimer(timer, new_base);
  859. if (!leftmost)
  860. goto unlock;
  861. if (!hrtimer_is_hres_active(timer)) {
  862. /*
  863. * Kick to reschedule the next tick to handle the new timer
  864. * on dynticks target.
  865. */
  866. if (new_base->cpu_base->nohz_active)
  867. wake_up_nohz_cpu(new_base->cpu_base->cpu);
  868. } else {
  869. hrtimer_reprogram(timer, new_base);
  870. }
  871. unlock:
  872. unlock_hrtimer_base(timer, &flags);
  873. }
  874. EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
  875. /**
  876. * hrtimer_try_to_cancel - try to deactivate a timer
  877. * @timer: hrtimer to stop
  878. *
  879. * Returns:
  880. * 0 when the timer was not active
  881. * 1 when the timer was active
  882. * -1 when the timer is currently excuting the callback function and
  883. * cannot be stopped
  884. */
  885. int hrtimer_try_to_cancel(struct hrtimer *timer)
  886. {
  887. struct hrtimer_clock_base *base;
  888. unsigned long flags;
  889. int ret = -1;
  890. /*
  891. * Check lockless first. If the timer is not active (neither
  892. * enqueued nor running the callback, nothing to do here. The
  893. * base lock does not serialize against a concurrent enqueue,
  894. * so we can avoid taking it.
  895. */
  896. if (!hrtimer_active(timer))
  897. return 0;
  898. base = lock_hrtimer_base(timer, &flags);
  899. if (!hrtimer_callback_running(timer))
  900. ret = remove_hrtimer(timer, base, false);
  901. unlock_hrtimer_base(timer, &flags);
  902. return ret;
  903. }
  904. EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
  905. /**
  906. * hrtimer_cancel - cancel a timer and wait for the handler to finish.
  907. * @timer: the timer to be cancelled
  908. *
  909. * Returns:
  910. * 0 when the timer was not active
  911. * 1 when the timer was active
  912. */
  913. int hrtimer_cancel(struct hrtimer *timer)
  914. {
  915. for (;;) {
  916. int ret = hrtimer_try_to_cancel(timer);
  917. if (ret >= 0)
  918. return ret;
  919. cpu_relax();
  920. }
  921. }
  922. EXPORT_SYMBOL_GPL(hrtimer_cancel);
  923. /**
  924. * hrtimer_get_remaining - get remaining time for the timer
  925. * @timer: the timer to read
  926. * @adjust: adjust relative timers when CONFIG_TIME_LOW_RES=y
  927. */
  928. ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
  929. {
  930. unsigned long flags;
  931. ktime_t rem;
  932. lock_hrtimer_base(timer, &flags);
  933. if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
  934. rem = hrtimer_expires_remaining_adjusted(timer);
  935. else
  936. rem = hrtimer_expires_remaining(timer);
  937. unlock_hrtimer_base(timer, &flags);
  938. return rem;
  939. }
  940. EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
  941. #ifdef CONFIG_NO_HZ_COMMON
  942. /**
  943. * hrtimer_get_next_event - get the time until next expiry event
  944. *
  945. * Returns the next expiry time or KTIME_MAX if no timer is pending.
  946. */
  947. u64 hrtimer_get_next_event(void)
  948. {
  949. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  950. u64 expires = KTIME_MAX;
  951. unsigned long flags;
  952. raw_spin_lock_irqsave(&cpu_base->lock, flags);
  953. if (!__hrtimer_hres_active(cpu_base))
  954. expires = __hrtimer_get_next_event(cpu_base).tv64;
  955. raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
  956. return expires;
  957. }
  958. #endif
  959. static inline int hrtimer_clockid_to_base(clockid_t clock_id)
  960. {
  961. if (likely(clock_id < MAX_CLOCKS)) {
  962. int base = hrtimer_clock_to_base_table[clock_id];
  963. if (likely(base != HRTIMER_MAX_CLOCK_BASES))
  964. return base;
  965. }
  966. WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
  967. return HRTIMER_BASE_MONOTONIC;
  968. }
  969. static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
  970. enum hrtimer_mode mode)
  971. {
  972. struct hrtimer_cpu_base *cpu_base;
  973. int base;
  974. memset(timer, 0, sizeof(struct hrtimer));
  975. cpu_base = raw_cpu_ptr(&hrtimer_bases);
  976. if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
  977. clock_id = CLOCK_MONOTONIC;
  978. base = hrtimer_clockid_to_base(clock_id);
  979. timer->base = &cpu_base->clock_base[base];
  980. timerqueue_init(&timer->node);
  981. #ifdef CONFIG_TIMER_STATS
  982. timer->start_site = NULL;
  983. timer->start_pid = -1;
  984. memset(timer->start_comm, 0, TASK_COMM_LEN);
  985. #endif
  986. }
  987. /**
  988. * hrtimer_init - initialize a timer to the given clock
  989. * @timer: the timer to be initialized
  990. * @clock_id: the clock to be used
  991. * @mode: timer mode abs/rel
  992. */
  993. void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
  994. enum hrtimer_mode mode)
  995. {
  996. debug_init(timer, clock_id, mode);
  997. __hrtimer_init(timer, clock_id, mode);
  998. }
  999. EXPORT_SYMBOL_GPL(hrtimer_init);
  1000. /*
  1001. * A timer is active, when it is enqueued into the rbtree or the
  1002. * callback function is running or it's in the state of being migrated
  1003. * to another cpu.
  1004. *
  1005. * It is important for this function to not return a false negative.
  1006. */
  1007. bool hrtimer_active(const struct hrtimer *timer)
  1008. {
  1009. struct hrtimer_cpu_base *cpu_base;
  1010. unsigned int seq;
  1011. do {
  1012. cpu_base = READ_ONCE(timer->base->cpu_base);
  1013. seq = raw_read_seqcount_begin(&cpu_base->seq);
  1014. if (timer->state != HRTIMER_STATE_INACTIVE ||
  1015. cpu_base->running == timer)
  1016. return true;
  1017. } while (read_seqcount_retry(&cpu_base->seq, seq) ||
  1018. cpu_base != READ_ONCE(timer->base->cpu_base));
  1019. return false;
  1020. }
  1021. EXPORT_SYMBOL_GPL(hrtimer_active);
  1022. /*
  1023. * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
  1024. * distinct sections:
  1025. *
  1026. * - queued: the timer is queued
  1027. * - callback: the timer is being ran
  1028. * - post: the timer is inactive or (re)queued
  1029. *
  1030. * On the read side we ensure we observe timer->state and cpu_base->running
  1031. * from the same section, if anything changed while we looked at it, we retry.
  1032. * This includes timer->base changing because sequence numbers alone are
  1033. * insufficient for that.
  1034. *
  1035. * The sequence numbers are required because otherwise we could still observe
  1036. * a false negative if the read side got smeared over multiple consequtive
  1037. * __run_hrtimer() invocations.
  1038. */
  1039. static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base,
  1040. struct hrtimer_clock_base *base,
  1041. struct hrtimer *timer, ktime_t *now)
  1042. {
  1043. enum hrtimer_restart (*fn)(struct hrtimer *);
  1044. int restart;
  1045. lockdep_assert_held(&cpu_base->lock);
  1046. debug_deactivate(timer);
  1047. cpu_base->running = timer;
  1048. /*
  1049. * Separate the ->running assignment from the ->state assignment.
  1050. *
  1051. * As with a regular write barrier, this ensures the read side in
  1052. * hrtimer_active() cannot observe cpu_base->running == NULL &&
  1053. * timer->state == INACTIVE.
  1054. */
  1055. raw_write_seqcount_barrier(&cpu_base->seq);
  1056. __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, 0);
  1057. timer_stats_account_hrtimer(timer);
  1058. fn = timer->function;
  1059. /*
  1060. * Clear the 'is relative' flag for the TIME_LOW_RES case. If the
  1061. * timer is restarted with a period then it becomes an absolute
  1062. * timer. If its not restarted it does not matter.
  1063. */
  1064. if (IS_ENABLED(CONFIG_TIME_LOW_RES))
  1065. timer->is_rel = false;
  1066. /*
  1067. * Because we run timers from hardirq context, there is no chance
  1068. * they get migrated to another cpu, therefore its safe to unlock
  1069. * the timer base.
  1070. */
  1071. raw_spin_unlock(&cpu_base->lock);
  1072. trace_hrtimer_expire_entry(timer, now);
  1073. restart = fn(timer);
  1074. trace_hrtimer_expire_exit(timer);
  1075. raw_spin_lock(&cpu_base->lock);
  1076. /*
  1077. * Note: We clear the running state after enqueue_hrtimer and
  1078. * we do not reprogram the event hardware. Happens either in
  1079. * hrtimer_start_range_ns() or in hrtimer_interrupt()
  1080. *
  1081. * Note: Because we dropped the cpu_base->lock above,
  1082. * hrtimer_start_range_ns() can have popped in and enqueued the timer
  1083. * for us already.
  1084. */
  1085. if (restart != HRTIMER_NORESTART &&
  1086. !(timer->state & HRTIMER_STATE_ENQUEUED))
  1087. enqueue_hrtimer(timer, base);
  1088. /*
  1089. * Separate the ->running assignment from the ->state assignment.
  1090. *
  1091. * As with a regular write barrier, this ensures the read side in
  1092. * hrtimer_active() cannot observe cpu_base->running == NULL &&
  1093. * timer->state == INACTIVE.
  1094. */
  1095. raw_write_seqcount_barrier(&cpu_base->seq);
  1096. WARN_ON_ONCE(cpu_base->running != timer);
  1097. cpu_base->running = NULL;
  1098. }
  1099. static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now)
  1100. {
  1101. struct hrtimer_clock_base *base = cpu_base->clock_base;
  1102. unsigned int active = cpu_base->active_bases;
  1103. for (; active; base++, active >>= 1) {
  1104. struct timerqueue_node *node;
  1105. ktime_t basenow;
  1106. if (!(active & 0x01))
  1107. continue;
  1108. basenow = ktime_add(now, base->offset);
  1109. while ((node = timerqueue_getnext(&base->active))) {
  1110. struct hrtimer *timer;
  1111. timer = container_of(node, struct hrtimer, node);
  1112. /*
  1113. * The immediate goal for using the softexpires is
  1114. * minimizing wakeups, not running timers at the
  1115. * earliest interrupt after their soft expiration.
  1116. * This allows us to avoid using a Priority Search
  1117. * Tree, which can answer a stabbing querry for
  1118. * overlapping intervals and instead use the simple
  1119. * BST we already have.
  1120. * We don't add extra wakeups by delaying timers that
  1121. * are right-of a not yet expired timer, because that
  1122. * timer will have to trigger a wakeup anyway.
  1123. */
  1124. if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer))
  1125. break;
  1126. __run_hrtimer(cpu_base, base, timer, &basenow);
  1127. }
  1128. }
  1129. }
  1130. #ifdef CONFIG_HIGH_RES_TIMERS
  1131. /*
  1132. * High resolution timer interrupt
  1133. * Called with interrupts disabled
  1134. */
  1135. void hrtimer_interrupt(struct clock_event_device *dev)
  1136. {
  1137. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  1138. ktime_t expires_next, now, entry_time, delta;
  1139. int retries = 0;
  1140. BUG_ON(!cpu_base->hres_active);
  1141. cpu_base->nr_events++;
  1142. dev->next_event.tv64 = KTIME_MAX;
  1143. raw_spin_lock(&cpu_base->lock);
  1144. entry_time = now = hrtimer_update_base(cpu_base);
  1145. retry:
  1146. cpu_base->in_hrtirq = 1;
  1147. /*
  1148. * We set expires_next to KTIME_MAX here with cpu_base->lock
  1149. * held to prevent that a timer is enqueued in our queue via
  1150. * the migration code. This does not affect enqueueing of
  1151. * timers which run their callback and need to be requeued on
  1152. * this CPU.
  1153. */
  1154. cpu_base->expires_next.tv64 = KTIME_MAX;
  1155. __hrtimer_run_queues(cpu_base, now);
  1156. /* Reevaluate the clock bases for the next expiry */
  1157. expires_next = __hrtimer_get_next_event(cpu_base);
  1158. /*
  1159. * Store the new expiry value so the migration code can verify
  1160. * against it.
  1161. */
  1162. cpu_base->expires_next = expires_next;
  1163. cpu_base->in_hrtirq = 0;
  1164. raw_spin_unlock(&cpu_base->lock);
  1165. /* Reprogramming necessary ? */
  1166. if (!tick_program_event(expires_next, 0)) {
  1167. cpu_base->hang_detected = 0;
  1168. return;
  1169. }
  1170. /*
  1171. * The next timer was already expired due to:
  1172. * - tracing
  1173. * - long lasting callbacks
  1174. * - being scheduled away when running in a VM
  1175. *
  1176. * We need to prevent that we loop forever in the hrtimer
  1177. * interrupt routine. We give it 3 attempts to avoid
  1178. * overreacting on some spurious event.
  1179. *
  1180. * Acquire base lock for updating the offsets and retrieving
  1181. * the current time.
  1182. */
  1183. raw_spin_lock(&cpu_base->lock);
  1184. now = hrtimer_update_base(cpu_base);
  1185. cpu_base->nr_retries++;
  1186. if (++retries < 3)
  1187. goto retry;
  1188. /*
  1189. * Give the system a chance to do something else than looping
  1190. * here. We stored the entry time, so we know exactly how long
  1191. * we spent here. We schedule the next event this amount of
  1192. * time away.
  1193. */
  1194. cpu_base->nr_hangs++;
  1195. cpu_base->hang_detected = 1;
  1196. raw_spin_unlock(&cpu_base->lock);
  1197. delta = ktime_sub(now, entry_time);
  1198. if ((unsigned int)delta.tv64 > cpu_base->max_hang_time)
  1199. cpu_base->max_hang_time = (unsigned int) delta.tv64;
  1200. /*
  1201. * Limit it to a sensible value as we enforce a longer
  1202. * delay. Give the CPU at least 100ms to catch up.
  1203. */
  1204. if (delta.tv64 > 100 * NSEC_PER_MSEC)
  1205. expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
  1206. else
  1207. expires_next = ktime_add(now, delta);
  1208. tick_program_event(expires_next, 1);
  1209. printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
  1210. ktime_to_ns(delta));
  1211. }
  1212. /*
  1213. * local version of hrtimer_peek_ahead_timers() called with interrupts
  1214. * disabled.
  1215. */
  1216. static inline void __hrtimer_peek_ahead_timers(void)
  1217. {
  1218. struct tick_device *td;
  1219. if (!hrtimer_hres_active())
  1220. return;
  1221. td = this_cpu_ptr(&tick_cpu_device);
  1222. if (td && td->evtdev)
  1223. hrtimer_interrupt(td->evtdev);
  1224. }
  1225. #else /* CONFIG_HIGH_RES_TIMERS */
  1226. static inline void __hrtimer_peek_ahead_timers(void) { }
  1227. #endif /* !CONFIG_HIGH_RES_TIMERS */
  1228. /*
  1229. * Called from run_local_timers in hardirq context every jiffy
  1230. */
  1231. void hrtimer_run_queues(void)
  1232. {
  1233. struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
  1234. ktime_t now;
  1235. if (__hrtimer_hres_active(cpu_base))
  1236. return;
  1237. /*
  1238. * This _is_ ugly: We have to check periodically, whether we
  1239. * can switch to highres and / or nohz mode. The clocksource
  1240. * switch happens with xtime_lock held. Notification from
  1241. * there only sets the check bit in the tick_oneshot code,
  1242. * otherwise we might deadlock vs. xtime_lock.
  1243. */
  1244. if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
  1245. hrtimer_switch_to_hres();
  1246. return;
  1247. }
  1248. raw_spin_lock(&cpu_base->lock);
  1249. now = hrtimer_update_base(cpu_base);
  1250. __hrtimer_run_queues(cpu_base, now);
  1251. raw_spin_unlock(&cpu_base->lock);
  1252. }
  1253. /*
  1254. * Sleep related functions:
  1255. */
  1256. static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
  1257. {
  1258. struct hrtimer_sleeper *t =
  1259. container_of(timer, struct hrtimer_sleeper, timer);
  1260. struct task_struct *task = t->task;
  1261. t->task = NULL;
  1262. if (task)
  1263. wake_up_process(task);
  1264. return HRTIMER_NORESTART;
  1265. }
  1266. void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
  1267. {
  1268. sl->timer.function = hrtimer_wakeup;
  1269. sl->task = task;
  1270. }
  1271. EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
  1272. static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
  1273. {
  1274. hrtimer_init_sleeper(t, current);
  1275. do {
  1276. set_current_state(TASK_INTERRUPTIBLE);
  1277. hrtimer_start_expires(&t->timer, mode);
  1278. if (likely(t->task))
  1279. freezable_schedule();
  1280. hrtimer_cancel(&t->timer);
  1281. mode = HRTIMER_MODE_ABS;
  1282. } while (t->task && !signal_pending(current));
  1283. __set_current_state(TASK_RUNNING);
  1284. return t->task == NULL;
  1285. }
  1286. static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
  1287. {
  1288. struct timespec rmt;
  1289. ktime_t rem;
  1290. rem = hrtimer_expires_remaining(timer);
  1291. if (rem.tv64 <= 0)
  1292. return 0;
  1293. rmt = ktime_to_timespec(rem);
  1294. if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
  1295. return -EFAULT;
  1296. return 1;
  1297. }
  1298. long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
  1299. {
  1300. struct hrtimer_sleeper t;
  1301. struct timespec __user *rmtp;
  1302. int ret = 0;
  1303. hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
  1304. HRTIMER_MODE_ABS);
  1305. hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
  1306. if (do_nanosleep(&t, HRTIMER_MODE_ABS))
  1307. goto out;
  1308. rmtp = restart->nanosleep.rmtp;
  1309. if (rmtp) {
  1310. ret = update_rmtp(&t.timer, rmtp);
  1311. if (ret <= 0)
  1312. goto out;
  1313. }
  1314. /* The other values in restart are already filled in */
  1315. ret = -ERESTART_RESTARTBLOCK;
  1316. out:
  1317. destroy_hrtimer_on_stack(&t.timer);
  1318. return ret;
  1319. }
  1320. long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
  1321. const enum hrtimer_mode mode, const clockid_t clockid)
  1322. {
  1323. struct restart_block *restart;
  1324. struct hrtimer_sleeper t;
  1325. int ret = 0;
  1326. u64 slack;
  1327. slack = current->timer_slack_ns;
  1328. if (dl_task(current) || rt_task(current))
  1329. slack = 0;
  1330. hrtimer_init_on_stack(&t.timer, clockid, mode);
  1331. hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
  1332. if (do_nanosleep(&t, mode))
  1333. goto out;
  1334. /* Absolute timers do not update the rmtp value and restart: */
  1335. if (mode == HRTIMER_MODE_ABS) {
  1336. ret = -ERESTARTNOHAND;
  1337. goto out;
  1338. }
  1339. if (rmtp) {
  1340. ret = update_rmtp(&t.timer, rmtp);
  1341. if (ret <= 0)
  1342. goto out;
  1343. }
  1344. restart = &current->restart_block;
  1345. restart->fn = hrtimer_nanosleep_restart;
  1346. restart->nanosleep.clockid = t.timer.base->clockid;
  1347. restart->nanosleep.rmtp = rmtp;
  1348. restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
  1349. ret = -ERESTART_RESTARTBLOCK;
  1350. out:
  1351. destroy_hrtimer_on_stack(&t.timer);
  1352. return ret;
  1353. }
  1354. SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
  1355. struct timespec __user *, rmtp)
  1356. {
  1357. struct timespec tu;
  1358. if (copy_from_user(&tu, rqtp, sizeof(tu)))
  1359. return -EFAULT;
  1360. if (!timespec_valid(&tu))
  1361. return -EINVAL;
  1362. return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
  1363. }
  1364. /*
  1365. * Functions related to boot-time initialization:
  1366. */
  1367. int hrtimers_prepare_cpu(unsigned int cpu)
  1368. {
  1369. struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
  1370. int i;
  1371. for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
  1372. cpu_base->clock_base[i].cpu_base = cpu_base;
  1373. timerqueue_init_head(&cpu_base->clock_base[i].active);
  1374. }
  1375. cpu_base->cpu = cpu;
  1376. hrtimer_init_hres(cpu_base);
  1377. return 0;
  1378. }
  1379. #ifdef CONFIG_HOTPLUG_CPU
  1380. static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
  1381. struct hrtimer_clock_base *new_base)
  1382. {
  1383. struct hrtimer *timer;
  1384. struct timerqueue_node *node;
  1385. while ((node = timerqueue_getnext(&old_base->active))) {
  1386. timer = container_of(node, struct hrtimer, node);
  1387. BUG_ON(hrtimer_callback_running(timer));
  1388. debug_deactivate(timer);
  1389. /*
  1390. * Mark it as ENQUEUED not INACTIVE otherwise the
  1391. * timer could be seen as !active and just vanish away
  1392. * under us on another CPU
  1393. */
  1394. __remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, 0);
  1395. timer->base = new_base;
  1396. /*
  1397. * Enqueue the timers on the new cpu. This does not
  1398. * reprogram the event device in case the timer
  1399. * expires before the earliest on this CPU, but we run
  1400. * hrtimer_interrupt after we migrated everything to
  1401. * sort out already expired timers and reprogram the
  1402. * event device.
  1403. */
  1404. enqueue_hrtimer(timer, new_base);
  1405. }
  1406. }
  1407. int hrtimers_dead_cpu(unsigned int scpu)
  1408. {
  1409. struct hrtimer_cpu_base *old_base, *new_base;
  1410. int i;
  1411. BUG_ON(cpu_online(scpu));
  1412. tick_cancel_sched_timer(scpu);
  1413. local_irq_disable();
  1414. old_base = &per_cpu(hrtimer_bases, scpu);
  1415. new_base = this_cpu_ptr(&hrtimer_bases);
  1416. /*
  1417. * The caller is globally serialized and nobody else
  1418. * takes two locks at once, deadlock is not possible.
  1419. */
  1420. raw_spin_lock(&new_base->lock);
  1421. raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
  1422. for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
  1423. migrate_hrtimer_list(&old_base->clock_base[i],
  1424. &new_base->clock_base[i]);
  1425. }
  1426. raw_spin_unlock(&old_base->lock);
  1427. raw_spin_unlock(&new_base->lock);
  1428. /* Check, if we got expired work to do */
  1429. __hrtimer_peek_ahead_timers();
  1430. local_irq_enable();
  1431. return 0;
  1432. }
  1433. #endif /* CONFIG_HOTPLUG_CPU */
  1434. void __init hrtimers_init(void)
  1435. {
  1436. hrtimers_prepare_cpu(smp_processor_id());
  1437. }
  1438. /**
  1439. * schedule_hrtimeout_range_clock - sleep until timeout
  1440. * @expires: timeout value (ktime_t)
  1441. * @delta: slack in expires timeout (ktime_t)
  1442. * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
  1443. * @clock: timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
  1444. */
  1445. int __sched
  1446. schedule_hrtimeout_range_clock(ktime_t *expires, u64 delta,
  1447. const enum hrtimer_mode mode, int clock)
  1448. {
  1449. struct hrtimer_sleeper t;
  1450. /*
  1451. * Optimize when a zero timeout value is given. It does not
  1452. * matter whether this is an absolute or a relative time.
  1453. */
  1454. if (expires && !expires->tv64) {
  1455. __set_current_state(TASK_RUNNING);
  1456. return 0;
  1457. }
  1458. /*
  1459. * A NULL parameter means "infinite"
  1460. */
  1461. if (!expires) {
  1462. schedule();
  1463. return -EINTR;
  1464. }
  1465. hrtimer_init_on_stack(&t.timer, clock, mode);
  1466. hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
  1467. hrtimer_init_sleeper(&t, current);
  1468. hrtimer_start_expires(&t.timer, mode);
  1469. if (likely(t.task))
  1470. schedule();
  1471. hrtimer_cancel(&t.timer);
  1472. destroy_hrtimer_on_stack(&t.timer);
  1473. __set_current_state(TASK_RUNNING);
  1474. return !t.task ? 0 : -EINTR;
  1475. }
  1476. /**
  1477. * schedule_hrtimeout_range - sleep until timeout
  1478. * @expires: timeout value (ktime_t)
  1479. * @delta: slack in expires timeout (ktime_t)
  1480. * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
  1481. *
  1482. * Make the current task sleep until the given expiry time has
  1483. * elapsed. The routine will return immediately unless
  1484. * the current task state has been set (see set_current_state()).
  1485. *
  1486. * The @delta argument gives the kernel the freedom to schedule the
  1487. * actual wakeup to a time that is both power and performance friendly.
  1488. * The kernel give the normal best effort behavior for "@expires+@delta",
  1489. * but may decide to fire the timer earlier, but no earlier than @expires.
  1490. *
  1491. * You can set the task state as follows -
  1492. *
  1493. * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
  1494. * pass before the routine returns.
  1495. *
  1496. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1497. * delivered to the current task.
  1498. *
  1499. * The current task state is guaranteed to be TASK_RUNNING when this
  1500. * routine returns.
  1501. *
  1502. * Returns 0 when the timer has expired otherwise -EINTR
  1503. */
  1504. int __sched schedule_hrtimeout_range(ktime_t *expires, u64 delta,
  1505. const enum hrtimer_mode mode)
  1506. {
  1507. return schedule_hrtimeout_range_clock(expires, delta, mode,
  1508. CLOCK_MONOTONIC);
  1509. }
  1510. EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
  1511. /**
  1512. * schedule_hrtimeout - sleep until timeout
  1513. * @expires: timeout value (ktime_t)
  1514. * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
  1515. *
  1516. * Make the current task sleep until the given expiry time has
  1517. * elapsed. The routine will return immediately unless
  1518. * the current task state has been set (see set_current_state()).
  1519. *
  1520. * You can set the task state as follows -
  1521. *
  1522. * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
  1523. * pass before the routine returns.
  1524. *
  1525. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1526. * delivered to the current task.
  1527. *
  1528. * The current task state is guaranteed to be TASK_RUNNING when this
  1529. * routine returns.
  1530. *
  1531. * Returns 0 when the timer has expired otherwise -EINTR
  1532. */
  1533. int __sched schedule_hrtimeout(ktime_t *expires,
  1534. const enum hrtimer_mode mode)
  1535. {
  1536. return schedule_hrtimeout_range(expires, 0, mode);
  1537. }
  1538. EXPORT_SYMBOL_GPL(schedule_hrtimeout);