hrtimer.c 46 KB

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