hrtimer.c 46 KB

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