hrtimer.c 46 KB

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