hrtimer.c 47 KB

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