timer.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  1. /*
  2. * linux/kernel/timer.c
  3. *
  4. * Kernel internal timers
  5. *
  6. * Copyright (C) 1991, 1992 Linus Torvalds
  7. *
  8. * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
  9. *
  10. * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
  11. * "A Kernel Model for Precision Timekeeping" by Dave Mills
  12. * 1998-12-24 Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
  13. * serialize accesses to xtime/lost_ticks).
  14. * Copyright (C) 1998 Andrea Arcangeli
  15. * 1999-03-10 Improved NTP compatibility by Ulrich Windl
  16. * 2002-05-31 Move sys_sysinfo here and make its locking sane, Robert Love
  17. * 2000-10-05 Implemented scalable SMP per-CPU timer handling.
  18. * Copyright (C) 2000, 2001, 2002 Ingo Molnar
  19. * Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
  20. */
  21. #include <linux/kernel_stat.h>
  22. #include <linux/export.h>
  23. #include <linux/interrupt.h>
  24. #include <linux/percpu.h>
  25. #include <linux/init.h>
  26. #include <linux/mm.h>
  27. #include <linux/swap.h>
  28. #include <linux/pid_namespace.h>
  29. #include <linux/notifier.h>
  30. #include <linux/thread_info.h>
  31. #include <linux/time.h>
  32. #include <linux/jiffies.h>
  33. #include <linux/posix-timers.h>
  34. #include <linux/cpu.h>
  35. #include <linux/syscalls.h>
  36. #include <linux/delay.h>
  37. #include <linux/tick.h>
  38. #include <linux/kallsyms.h>
  39. #include <linux/irq_work.h>
  40. #include <linux/sched.h>
  41. #include <linux/sched/sysctl.h>
  42. #include <linux/slab.h>
  43. #include <linux/compat.h>
  44. #include <asm/uaccess.h>
  45. #include <asm/unistd.h>
  46. #include <asm/div64.h>
  47. #include <asm/timex.h>
  48. #include <asm/io.h>
  49. #define CREATE_TRACE_POINTS
  50. #include <trace/events/timer.h>
  51. __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
  52. EXPORT_SYMBOL(jiffies_64);
  53. /*
  54. * per-CPU timer vector definitions:
  55. */
  56. #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
  57. #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
  58. #define TVN_SIZE (1 << TVN_BITS)
  59. #define TVR_SIZE (1 << TVR_BITS)
  60. #define TVN_MASK (TVN_SIZE - 1)
  61. #define TVR_MASK (TVR_SIZE - 1)
  62. #define MAX_TVAL ((unsigned long)((1ULL << (TVR_BITS + 4*TVN_BITS)) - 1))
  63. struct tvec {
  64. struct list_head vec[TVN_SIZE];
  65. };
  66. struct tvec_root {
  67. struct list_head vec[TVR_SIZE];
  68. };
  69. struct tvec_base {
  70. spinlock_t lock;
  71. struct timer_list *running_timer;
  72. unsigned long timer_jiffies;
  73. unsigned long next_timer;
  74. unsigned long active_timers;
  75. unsigned long all_timers;
  76. int cpu;
  77. struct tvec_root tv1;
  78. struct tvec tv2;
  79. struct tvec tv3;
  80. struct tvec tv4;
  81. struct tvec tv5;
  82. } ____cacheline_aligned;
  83. struct tvec_base boot_tvec_bases;
  84. EXPORT_SYMBOL(boot_tvec_bases);
  85. static DEFINE_PER_CPU(struct tvec_base *, tvec_bases) = &boot_tvec_bases;
  86. /* Functions below help us manage 'deferrable' flag */
  87. static inline unsigned int tbase_get_deferrable(struct tvec_base *base)
  88. {
  89. return ((unsigned int)(unsigned long)base & TIMER_DEFERRABLE);
  90. }
  91. static inline unsigned int tbase_get_irqsafe(struct tvec_base *base)
  92. {
  93. return ((unsigned int)(unsigned long)base & TIMER_IRQSAFE);
  94. }
  95. static inline struct tvec_base *tbase_get_base(struct tvec_base *base)
  96. {
  97. return ((struct tvec_base *)((unsigned long)base & ~TIMER_FLAG_MASK));
  98. }
  99. static inline void
  100. timer_set_base(struct timer_list *timer, struct tvec_base *new_base)
  101. {
  102. unsigned long flags = (unsigned long)timer->base & TIMER_FLAG_MASK;
  103. timer->base = (struct tvec_base *)((unsigned long)(new_base) | flags);
  104. }
  105. static unsigned long round_jiffies_common(unsigned long j, int cpu,
  106. bool force_up)
  107. {
  108. int rem;
  109. unsigned long original = j;
  110. /*
  111. * We don't want all cpus firing their timers at once hitting the
  112. * same lock or cachelines, so we skew each extra cpu with an extra
  113. * 3 jiffies. This 3 jiffies came originally from the mm/ code which
  114. * already did this.
  115. * The skew is done by adding 3*cpunr, then round, then subtract this
  116. * extra offset again.
  117. */
  118. j += cpu * 3;
  119. rem = j % HZ;
  120. /*
  121. * If the target jiffie is just after a whole second (which can happen
  122. * due to delays of the timer irq, long irq off times etc etc) then
  123. * we should round down to the whole second, not up. Use 1/4th second
  124. * as cutoff for this rounding as an extreme upper bound for this.
  125. * But never round down if @force_up is set.
  126. */
  127. if (rem < HZ/4 && !force_up) /* round down */
  128. j = j - rem;
  129. else /* round up */
  130. j = j - rem + HZ;
  131. /* now that we have rounded, subtract the extra skew again */
  132. j -= cpu * 3;
  133. /*
  134. * Make sure j is still in the future. Otherwise return the
  135. * unmodified value.
  136. */
  137. return time_is_after_jiffies(j) ? j : original;
  138. }
  139. /**
  140. * __round_jiffies - function to round jiffies to a full second
  141. * @j: the time in (absolute) jiffies that should be rounded
  142. * @cpu: the processor number on which the timeout will happen
  143. *
  144. * __round_jiffies() rounds an absolute time in the future (in jiffies)
  145. * up or down to (approximately) full seconds. This is useful for timers
  146. * for which the exact time they fire does not matter too much, as long as
  147. * they fire approximately every X seconds.
  148. *
  149. * By rounding these timers to whole seconds, all such timers will fire
  150. * at the same time, rather than at various times spread out. The goal
  151. * of this is to have the CPU wake up less, which saves power.
  152. *
  153. * The exact rounding is skewed for each processor to avoid all
  154. * processors firing at the exact same time, which could lead
  155. * to lock contention or spurious cache line bouncing.
  156. *
  157. * The return value is the rounded version of the @j parameter.
  158. */
  159. unsigned long __round_jiffies(unsigned long j, int cpu)
  160. {
  161. return round_jiffies_common(j, cpu, false);
  162. }
  163. EXPORT_SYMBOL_GPL(__round_jiffies);
  164. /**
  165. * __round_jiffies_relative - function to round jiffies to a full second
  166. * @j: the time in (relative) jiffies that should be rounded
  167. * @cpu: the processor number on which the timeout will happen
  168. *
  169. * __round_jiffies_relative() rounds a time delta in the future (in jiffies)
  170. * up or down to (approximately) full seconds. This is useful for timers
  171. * for which the exact time they fire does not matter too much, as long as
  172. * they fire approximately every X seconds.
  173. *
  174. * By rounding these timers to whole seconds, all such timers will fire
  175. * at the same time, rather than at various times spread out. The goal
  176. * of this is to have the CPU wake up less, which saves power.
  177. *
  178. * The exact rounding is skewed for each processor to avoid all
  179. * processors firing at the exact same time, which could lead
  180. * to lock contention or spurious cache line bouncing.
  181. *
  182. * The return value is the rounded version of the @j parameter.
  183. */
  184. unsigned long __round_jiffies_relative(unsigned long j, int cpu)
  185. {
  186. unsigned long j0 = jiffies;
  187. /* Use j0 because jiffies might change while we run */
  188. return round_jiffies_common(j + j0, cpu, false) - j0;
  189. }
  190. EXPORT_SYMBOL_GPL(__round_jiffies_relative);
  191. /**
  192. * round_jiffies - function to round jiffies to a full second
  193. * @j: the time in (absolute) jiffies that should be rounded
  194. *
  195. * round_jiffies() rounds an absolute time in the future (in jiffies)
  196. * up or down to (approximately) full seconds. This is useful for timers
  197. * for which the exact time they fire does not matter too much, as long as
  198. * they fire approximately every X seconds.
  199. *
  200. * By rounding these timers to whole seconds, all such timers will fire
  201. * at the same time, rather than at various times spread out. The goal
  202. * of this is to have the CPU wake up less, which saves power.
  203. *
  204. * The return value is the rounded version of the @j parameter.
  205. */
  206. unsigned long round_jiffies(unsigned long j)
  207. {
  208. return round_jiffies_common(j, raw_smp_processor_id(), false);
  209. }
  210. EXPORT_SYMBOL_GPL(round_jiffies);
  211. /**
  212. * round_jiffies_relative - function to round jiffies to a full second
  213. * @j: the time in (relative) jiffies that should be rounded
  214. *
  215. * round_jiffies_relative() rounds a time delta in the future (in jiffies)
  216. * up or down to (approximately) full seconds. This is useful for timers
  217. * for which the exact time they fire does not matter too much, as long as
  218. * they fire approximately every X seconds.
  219. *
  220. * By rounding these timers to whole seconds, all such timers will fire
  221. * at the same time, rather than at various times spread out. The goal
  222. * of this is to have the CPU wake up less, which saves power.
  223. *
  224. * The return value is the rounded version of the @j parameter.
  225. */
  226. unsigned long round_jiffies_relative(unsigned long j)
  227. {
  228. return __round_jiffies_relative(j, raw_smp_processor_id());
  229. }
  230. EXPORT_SYMBOL_GPL(round_jiffies_relative);
  231. /**
  232. * __round_jiffies_up - function to round jiffies up to a full second
  233. * @j: the time in (absolute) jiffies that should be rounded
  234. * @cpu: the processor number on which the timeout will happen
  235. *
  236. * This is the same as __round_jiffies() except that it will never
  237. * round down. This is useful for timeouts for which the exact time
  238. * of firing does not matter too much, as long as they don't fire too
  239. * early.
  240. */
  241. unsigned long __round_jiffies_up(unsigned long j, int cpu)
  242. {
  243. return round_jiffies_common(j, cpu, true);
  244. }
  245. EXPORT_SYMBOL_GPL(__round_jiffies_up);
  246. /**
  247. * __round_jiffies_up_relative - function to round jiffies up to a full second
  248. * @j: the time in (relative) jiffies that should be rounded
  249. * @cpu: the processor number on which the timeout will happen
  250. *
  251. * This is the same as __round_jiffies_relative() except that it will never
  252. * round down. This is useful for timeouts for which the exact time
  253. * of firing does not matter too much, as long as they don't fire too
  254. * early.
  255. */
  256. unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
  257. {
  258. unsigned long j0 = jiffies;
  259. /* Use j0 because jiffies might change while we run */
  260. return round_jiffies_common(j + j0, cpu, true) - j0;
  261. }
  262. EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
  263. /**
  264. * round_jiffies_up - function to round jiffies up to a full second
  265. * @j: the time in (absolute) jiffies that should be rounded
  266. *
  267. * This is the same as round_jiffies() except that it will never
  268. * round down. This is useful for timeouts for which the exact time
  269. * of firing does not matter too much, as long as they don't fire too
  270. * early.
  271. */
  272. unsigned long round_jiffies_up(unsigned long j)
  273. {
  274. return round_jiffies_common(j, raw_smp_processor_id(), true);
  275. }
  276. EXPORT_SYMBOL_GPL(round_jiffies_up);
  277. /**
  278. * round_jiffies_up_relative - function to round jiffies up to a full second
  279. * @j: the time in (relative) jiffies that should be rounded
  280. *
  281. * This is the same as round_jiffies_relative() except that it will never
  282. * round down. This is useful for timeouts for which the exact time
  283. * of firing does not matter too much, as long as they don't fire too
  284. * early.
  285. */
  286. unsigned long round_jiffies_up_relative(unsigned long j)
  287. {
  288. return __round_jiffies_up_relative(j, raw_smp_processor_id());
  289. }
  290. EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
  291. /**
  292. * set_timer_slack - set the allowed slack for a timer
  293. * @timer: the timer to be modified
  294. * @slack_hz: the amount of time (in jiffies) allowed for rounding
  295. *
  296. * Set the amount of time, in jiffies, that a certain timer has
  297. * in terms of slack. By setting this value, the timer subsystem
  298. * will schedule the actual timer somewhere between
  299. * the time mod_timer() asks for, and that time plus the slack.
  300. *
  301. * By setting the slack to -1, a percentage of the delay is used
  302. * instead.
  303. */
  304. void set_timer_slack(struct timer_list *timer, int slack_hz)
  305. {
  306. timer->slack = slack_hz;
  307. }
  308. EXPORT_SYMBOL_GPL(set_timer_slack);
  309. /*
  310. * If the list is empty, catch up ->timer_jiffies to the current time.
  311. * The caller must hold the tvec_base lock. Returns true if the list
  312. * was empty and therefore ->timer_jiffies was updated.
  313. */
  314. static bool catchup_timer_jiffies(struct tvec_base *base)
  315. {
  316. if (!base->all_timers) {
  317. base->timer_jiffies = jiffies;
  318. return true;
  319. }
  320. return false;
  321. }
  322. static void
  323. __internal_add_timer(struct tvec_base *base, struct timer_list *timer)
  324. {
  325. unsigned long expires = timer->expires;
  326. unsigned long idx = expires - base->timer_jiffies;
  327. struct list_head *vec;
  328. if (idx < TVR_SIZE) {
  329. int i = expires & TVR_MASK;
  330. vec = base->tv1.vec + i;
  331. } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
  332. int i = (expires >> TVR_BITS) & TVN_MASK;
  333. vec = base->tv2.vec + i;
  334. } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
  335. int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
  336. vec = base->tv3.vec + i;
  337. } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
  338. int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
  339. vec = base->tv4.vec + i;
  340. } else if ((signed long) idx < 0) {
  341. /*
  342. * Can happen if you add a timer with expires == jiffies,
  343. * or you set a timer to go off in the past
  344. */
  345. vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
  346. } else {
  347. int i;
  348. /* If the timeout is larger than MAX_TVAL (on 64-bit
  349. * architectures or with CONFIG_BASE_SMALL=1) then we
  350. * use the maximum timeout.
  351. */
  352. if (idx > MAX_TVAL) {
  353. idx = MAX_TVAL;
  354. expires = idx + base->timer_jiffies;
  355. }
  356. i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
  357. vec = base->tv5.vec + i;
  358. }
  359. /*
  360. * Timers are FIFO:
  361. */
  362. list_add_tail(&timer->entry, vec);
  363. }
  364. static void internal_add_timer(struct tvec_base *base, struct timer_list *timer)
  365. {
  366. (void)catchup_timer_jiffies(base);
  367. __internal_add_timer(base, timer);
  368. /*
  369. * Update base->active_timers and base->next_timer
  370. */
  371. if (!tbase_get_deferrable(timer->base)) {
  372. if (!base->active_timers++ ||
  373. time_before(timer->expires, base->next_timer))
  374. base->next_timer = timer->expires;
  375. }
  376. base->all_timers++;
  377. /*
  378. * Check whether the other CPU is in dynticks mode and needs
  379. * to be triggered to reevaluate the timer wheel.
  380. * We are protected against the other CPU fiddling
  381. * with the timer by holding the timer base lock. This also
  382. * makes sure that a CPU on the way to stop its tick can not
  383. * evaluate the timer wheel.
  384. *
  385. * Spare the IPI for deferrable timers on idle targets though.
  386. * The next busy ticks will take care of it. Except full dynticks
  387. * require special care against races with idle_cpu(), lets deal
  388. * with that later.
  389. */
  390. if (!tbase_get_deferrable(base) || tick_nohz_full_cpu(base->cpu))
  391. wake_up_nohz_cpu(base->cpu);
  392. }
  393. #ifdef CONFIG_TIMER_STATS
  394. void __timer_stats_timer_set_start_info(struct timer_list *timer, void *addr)
  395. {
  396. if (timer->start_site)
  397. return;
  398. timer->start_site = addr;
  399. memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
  400. timer->start_pid = current->pid;
  401. }
  402. static void timer_stats_account_timer(struct timer_list *timer)
  403. {
  404. unsigned int flag = 0;
  405. if (likely(!timer->start_site))
  406. return;
  407. if (unlikely(tbase_get_deferrable(timer->base)))
  408. flag |= TIMER_STATS_FLAG_DEFERRABLE;
  409. timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
  410. timer->function, timer->start_comm, flag);
  411. }
  412. #else
  413. static void timer_stats_account_timer(struct timer_list *timer) {}
  414. #endif
  415. #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
  416. static struct debug_obj_descr timer_debug_descr;
  417. static void *timer_debug_hint(void *addr)
  418. {
  419. return ((struct timer_list *) addr)->function;
  420. }
  421. /*
  422. * fixup_init is called when:
  423. * - an active object is initialized
  424. */
  425. static int timer_fixup_init(void *addr, enum debug_obj_state state)
  426. {
  427. struct timer_list *timer = addr;
  428. switch (state) {
  429. case ODEBUG_STATE_ACTIVE:
  430. del_timer_sync(timer);
  431. debug_object_init(timer, &timer_debug_descr);
  432. return 1;
  433. default:
  434. return 0;
  435. }
  436. }
  437. /* Stub timer callback for improperly used timers. */
  438. static void stub_timer(unsigned long data)
  439. {
  440. WARN_ON(1);
  441. }
  442. /*
  443. * fixup_activate is called when:
  444. * - an active object is activated
  445. * - an unknown object is activated (might be a statically initialized object)
  446. */
  447. static int timer_fixup_activate(void *addr, enum debug_obj_state state)
  448. {
  449. struct timer_list *timer = addr;
  450. switch (state) {
  451. case ODEBUG_STATE_NOTAVAILABLE:
  452. /*
  453. * This is not really a fixup. The timer was
  454. * statically initialized. We just make sure that it
  455. * is tracked in the object tracker.
  456. */
  457. if (timer->entry.next == NULL &&
  458. timer->entry.prev == TIMER_ENTRY_STATIC) {
  459. debug_object_init(timer, &timer_debug_descr);
  460. debug_object_activate(timer, &timer_debug_descr);
  461. return 0;
  462. } else {
  463. setup_timer(timer, stub_timer, 0);
  464. return 1;
  465. }
  466. return 0;
  467. case ODEBUG_STATE_ACTIVE:
  468. WARN_ON(1);
  469. default:
  470. return 0;
  471. }
  472. }
  473. /*
  474. * fixup_free is called when:
  475. * - an active object is freed
  476. */
  477. static int timer_fixup_free(void *addr, enum debug_obj_state state)
  478. {
  479. struct timer_list *timer = addr;
  480. switch (state) {
  481. case ODEBUG_STATE_ACTIVE:
  482. del_timer_sync(timer);
  483. debug_object_free(timer, &timer_debug_descr);
  484. return 1;
  485. default:
  486. return 0;
  487. }
  488. }
  489. /*
  490. * fixup_assert_init is called when:
  491. * - an untracked/uninit-ed object is found
  492. */
  493. static int timer_fixup_assert_init(void *addr, enum debug_obj_state state)
  494. {
  495. struct timer_list *timer = addr;
  496. switch (state) {
  497. case ODEBUG_STATE_NOTAVAILABLE:
  498. if (timer->entry.prev == TIMER_ENTRY_STATIC) {
  499. /*
  500. * This is not really a fixup. The timer was
  501. * statically initialized. We just make sure that it
  502. * is tracked in the object tracker.
  503. */
  504. debug_object_init(timer, &timer_debug_descr);
  505. return 0;
  506. } else {
  507. setup_timer(timer, stub_timer, 0);
  508. return 1;
  509. }
  510. default:
  511. return 0;
  512. }
  513. }
  514. static struct debug_obj_descr timer_debug_descr = {
  515. .name = "timer_list",
  516. .debug_hint = timer_debug_hint,
  517. .fixup_init = timer_fixup_init,
  518. .fixup_activate = timer_fixup_activate,
  519. .fixup_free = timer_fixup_free,
  520. .fixup_assert_init = timer_fixup_assert_init,
  521. };
  522. static inline void debug_timer_init(struct timer_list *timer)
  523. {
  524. debug_object_init(timer, &timer_debug_descr);
  525. }
  526. static inline void debug_timer_activate(struct timer_list *timer)
  527. {
  528. debug_object_activate(timer, &timer_debug_descr);
  529. }
  530. static inline void debug_timer_deactivate(struct timer_list *timer)
  531. {
  532. debug_object_deactivate(timer, &timer_debug_descr);
  533. }
  534. static inline void debug_timer_free(struct timer_list *timer)
  535. {
  536. debug_object_free(timer, &timer_debug_descr);
  537. }
  538. static inline void debug_timer_assert_init(struct timer_list *timer)
  539. {
  540. debug_object_assert_init(timer, &timer_debug_descr);
  541. }
  542. static void do_init_timer(struct timer_list *timer, unsigned int flags,
  543. const char *name, struct lock_class_key *key);
  544. void init_timer_on_stack_key(struct timer_list *timer, unsigned int flags,
  545. const char *name, struct lock_class_key *key)
  546. {
  547. debug_object_init_on_stack(timer, &timer_debug_descr);
  548. do_init_timer(timer, flags, name, key);
  549. }
  550. EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
  551. void destroy_timer_on_stack(struct timer_list *timer)
  552. {
  553. debug_object_free(timer, &timer_debug_descr);
  554. }
  555. EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
  556. #else
  557. static inline void debug_timer_init(struct timer_list *timer) { }
  558. static inline void debug_timer_activate(struct timer_list *timer) { }
  559. static inline void debug_timer_deactivate(struct timer_list *timer) { }
  560. static inline void debug_timer_assert_init(struct timer_list *timer) { }
  561. #endif
  562. static inline void debug_init(struct timer_list *timer)
  563. {
  564. debug_timer_init(timer);
  565. trace_timer_init(timer);
  566. }
  567. static inline void
  568. debug_activate(struct timer_list *timer, unsigned long expires)
  569. {
  570. debug_timer_activate(timer);
  571. trace_timer_start(timer, expires);
  572. }
  573. static inline void debug_deactivate(struct timer_list *timer)
  574. {
  575. debug_timer_deactivate(timer);
  576. trace_timer_cancel(timer);
  577. }
  578. static inline void debug_assert_init(struct timer_list *timer)
  579. {
  580. debug_timer_assert_init(timer);
  581. }
  582. static void do_init_timer(struct timer_list *timer, unsigned int flags,
  583. const char *name, struct lock_class_key *key)
  584. {
  585. struct tvec_base *base = raw_cpu_read(tvec_bases);
  586. timer->entry.next = NULL;
  587. timer->base = (void *)((unsigned long)base | flags);
  588. timer->slack = -1;
  589. #ifdef CONFIG_TIMER_STATS
  590. timer->start_site = NULL;
  591. timer->start_pid = -1;
  592. memset(timer->start_comm, 0, TASK_COMM_LEN);
  593. #endif
  594. lockdep_init_map(&timer->lockdep_map, name, key, 0);
  595. }
  596. /**
  597. * init_timer_key - initialize a timer
  598. * @timer: the timer to be initialized
  599. * @flags: timer flags
  600. * @name: name of the timer
  601. * @key: lockdep class key of the fake lock used for tracking timer
  602. * sync lock dependencies
  603. *
  604. * init_timer_key() must be done to a timer prior calling *any* of the
  605. * other timer functions.
  606. */
  607. void init_timer_key(struct timer_list *timer, unsigned int flags,
  608. const char *name, struct lock_class_key *key)
  609. {
  610. debug_init(timer);
  611. do_init_timer(timer, flags, name, key);
  612. }
  613. EXPORT_SYMBOL(init_timer_key);
  614. static inline void detach_timer(struct timer_list *timer, bool clear_pending)
  615. {
  616. struct list_head *entry = &timer->entry;
  617. debug_deactivate(timer);
  618. __list_del(entry->prev, entry->next);
  619. if (clear_pending)
  620. entry->next = NULL;
  621. entry->prev = LIST_POISON2;
  622. }
  623. static inline void
  624. detach_expired_timer(struct timer_list *timer, struct tvec_base *base)
  625. {
  626. detach_timer(timer, true);
  627. if (!tbase_get_deferrable(timer->base))
  628. base->active_timers--;
  629. base->all_timers--;
  630. (void)catchup_timer_jiffies(base);
  631. }
  632. static int detach_if_pending(struct timer_list *timer, struct tvec_base *base,
  633. bool clear_pending)
  634. {
  635. if (!timer_pending(timer))
  636. return 0;
  637. detach_timer(timer, clear_pending);
  638. if (!tbase_get_deferrable(timer->base)) {
  639. base->active_timers--;
  640. if (timer->expires == base->next_timer)
  641. base->next_timer = base->timer_jiffies;
  642. }
  643. base->all_timers--;
  644. (void)catchup_timer_jiffies(base);
  645. return 1;
  646. }
  647. /*
  648. * We are using hashed locking: holding per_cpu(tvec_bases).lock
  649. * means that all timers which are tied to this base via timer->base are
  650. * locked, and the base itself is locked too.
  651. *
  652. * So __run_timers/migrate_timers can safely modify all timers which could
  653. * be found on ->tvX lists.
  654. *
  655. * When the timer's base is locked, and the timer removed from list, it is
  656. * possible to set timer->base = NULL and drop the lock: the timer remains
  657. * locked.
  658. */
  659. static struct tvec_base *lock_timer_base(struct timer_list *timer,
  660. unsigned long *flags)
  661. __acquires(timer->base->lock)
  662. {
  663. struct tvec_base *base;
  664. for (;;) {
  665. struct tvec_base *prelock_base = timer->base;
  666. base = tbase_get_base(prelock_base);
  667. if (likely(base != NULL)) {
  668. spin_lock_irqsave(&base->lock, *flags);
  669. if (likely(prelock_base == timer->base))
  670. return base;
  671. /* The timer has migrated to another CPU */
  672. spin_unlock_irqrestore(&base->lock, *flags);
  673. }
  674. cpu_relax();
  675. }
  676. }
  677. static inline int
  678. __mod_timer(struct timer_list *timer, unsigned long expires,
  679. bool pending_only, int pinned)
  680. {
  681. struct tvec_base *base, *new_base;
  682. unsigned long flags;
  683. int ret = 0 , cpu;
  684. timer_stats_timer_set_start_info(timer);
  685. BUG_ON(!timer->function);
  686. base = lock_timer_base(timer, &flags);
  687. ret = detach_if_pending(timer, base, false);
  688. if (!ret && pending_only)
  689. goto out_unlock;
  690. debug_activate(timer, expires);
  691. cpu = get_nohz_timer_target(pinned);
  692. new_base = per_cpu(tvec_bases, cpu);
  693. if (base != new_base) {
  694. /*
  695. * We are trying to schedule the timer on the local CPU.
  696. * However we can't change timer's base while it is running,
  697. * otherwise del_timer_sync() can't detect that the timer's
  698. * handler yet has not finished. This also guarantees that
  699. * the timer is serialized wrt itself.
  700. */
  701. if (likely(base->running_timer != timer)) {
  702. /* See the comment in lock_timer_base() */
  703. timer_set_base(timer, NULL);
  704. spin_unlock(&base->lock);
  705. base = new_base;
  706. spin_lock(&base->lock);
  707. timer_set_base(timer, base);
  708. }
  709. }
  710. timer->expires = expires;
  711. internal_add_timer(base, timer);
  712. out_unlock:
  713. spin_unlock_irqrestore(&base->lock, flags);
  714. return ret;
  715. }
  716. /**
  717. * mod_timer_pending - modify a pending timer's timeout
  718. * @timer: the pending timer to be modified
  719. * @expires: new timeout in jiffies
  720. *
  721. * mod_timer_pending() is the same for pending timers as mod_timer(),
  722. * but will not re-activate and modify already deleted timers.
  723. *
  724. * It is useful for unserialized use of timers.
  725. */
  726. int mod_timer_pending(struct timer_list *timer, unsigned long expires)
  727. {
  728. return __mod_timer(timer, expires, true, TIMER_NOT_PINNED);
  729. }
  730. EXPORT_SYMBOL(mod_timer_pending);
  731. /*
  732. * Decide where to put the timer while taking the slack into account
  733. *
  734. * Algorithm:
  735. * 1) calculate the maximum (absolute) time
  736. * 2) calculate the highest bit where the expires and new max are different
  737. * 3) use this bit to make a mask
  738. * 4) use the bitmask to round down the maximum time, so that all last
  739. * bits are zeros
  740. */
  741. static inline
  742. unsigned long apply_slack(struct timer_list *timer, unsigned long expires)
  743. {
  744. unsigned long expires_limit, mask;
  745. int bit;
  746. if (timer->slack >= 0) {
  747. expires_limit = expires + timer->slack;
  748. } else {
  749. long delta = expires - jiffies;
  750. if (delta < 256)
  751. return expires;
  752. expires_limit = expires + delta / 256;
  753. }
  754. mask = expires ^ expires_limit;
  755. if (mask == 0)
  756. return expires;
  757. bit = find_last_bit(&mask, BITS_PER_LONG);
  758. mask = (1UL << bit) - 1;
  759. expires_limit = expires_limit & ~(mask);
  760. return expires_limit;
  761. }
  762. /**
  763. * mod_timer - modify a timer's timeout
  764. * @timer: the timer to be modified
  765. * @expires: new timeout in jiffies
  766. *
  767. * mod_timer() is a more efficient way to update the expire field of an
  768. * active timer (if the timer is inactive it will be activated)
  769. *
  770. * mod_timer(timer, expires) is equivalent to:
  771. *
  772. * del_timer(timer); timer->expires = expires; add_timer(timer);
  773. *
  774. * Note that if there are multiple unserialized concurrent users of the
  775. * same timer, then mod_timer() is the only safe way to modify the timeout,
  776. * since add_timer() cannot modify an already running timer.
  777. *
  778. * The function returns whether it has modified a pending timer or not.
  779. * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
  780. * active timer returns 1.)
  781. */
  782. int mod_timer(struct timer_list *timer, unsigned long expires)
  783. {
  784. expires = apply_slack(timer, expires);
  785. /*
  786. * This is a common optimization triggered by the
  787. * networking code - if the timer is re-modified
  788. * to be the same thing then just return:
  789. */
  790. if (timer_pending(timer) && timer->expires == expires)
  791. return 1;
  792. return __mod_timer(timer, expires, false, TIMER_NOT_PINNED);
  793. }
  794. EXPORT_SYMBOL(mod_timer);
  795. /**
  796. * mod_timer_pinned - modify a timer's timeout
  797. * @timer: the timer to be modified
  798. * @expires: new timeout in jiffies
  799. *
  800. * mod_timer_pinned() is a way to update the expire field of an
  801. * active timer (if the timer is inactive it will be activated)
  802. * and to ensure that the timer is scheduled on the current CPU.
  803. *
  804. * Note that this does not prevent the timer from being migrated
  805. * when the current CPU goes offline. If this is a problem for
  806. * you, use CPU-hotplug notifiers to handle it correctly, for
  807. * example, cancelling the timer when the corresponding CPU goes
  808. * offline.
  809. *
  810. * mod_timer_pinned(timer, expires) is equivalent to:
  811. *
  812. * del_timer(timer); timer->expires = expires; add_timer(timer);
  813. */
  814. int mod_timer_pinned(struct timer_list *timer, unsigned long expires)
  815. {
  816. if (timer->expires == expires && timer_pending(timer))
  817. return 1;
  818. return __mod_timer(timer, expires, false, TIMER_PINNED);
  819. }
  820. EXPORT_SYMBOL(mod_timer_pinned);
  821. /**
  822. * add_timer - start a timer
  823. * @timer: the timer to be added
  824. *
  825. * The kernel will do a ->function(->data) callback from the
  826. * timer interrupt at the ->expires point in the future. The
  827. * current time is 'jiffies'.
  828. *
  829. * The timer's ->expires, ->function (and if the handler uses it, ->data)
  830. * fields must be set prior calling this function.
  831. *
  832. * Timers with an ->expires field in the past will be executed in the next
  833. * timer tick.
  834. */
  835. void add_timer(struct timer_list *timer)
  836. {
  837. BUG_ON(timer_pending(timer));
  838. mod_timer(timer, timer->expires);
  839. }
  840. EXPORT_SYMBOL(add_timer);
  841. /**
  842. * add_timer_on - start a timer on a particular CPU
  843. * @timer: the timer to be added
  844. * @cpu: the CPU to start it on
  845. *
  846. * This is not very scalable on SMP. Double adds are not possible.
  847. */
  848. void add_timer_on(struct timer_list *timer, int cpu)
  849. {
  850. struct tvec_base *base = per_cpu(tvec_bases, cpu);
  851. unsigned long flags;
  852. timer_stats_timer_set_start_info(timer);
  853. BUG_ON(timer_pending(timer) || !timer->function);
  854. spin_lock_irqsave(&base->lock, flags);
  855. timer_set_base(timer, base);
  856. debug_activate(timer, timer->expires);
  857. internal_add_timer(base, timer);
  858. spin_unlock_irqrestore(&base->lock, flags);
  859. }
  860. EXPORT_SYMBOL_GPL(add_timer_on);
  861. /**
  862. * del_timer - deactive a timer.
  863. * @timer: the timer to be deactivated
  864. *
  865. * del_timer() deactivates a timer - this works on both active and inactive
  866. * timers.
  867. *
  868. * The function returns whether it has deactivated a pending timer or not.
  869. * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
  870. * active timer returns 1.)
  871. */
  872. int del_timer(struct timer_list *timer)
  873. {
  874. struct tvec_base *base;
  875. unsigned long flags;
  876. int ret = 0;
  877. debug_assert_init(timer);
  878. timer_stats_timer_clear_start_info(timer);
  879. if (timer_pending(timer)) {
  880. base = lock_timer_base(timer, &flags);
  881. ret = detach_if_pending(timer, base, true);
  882. spin_unlock_irqrestore(&base->lock, flags);
  883. }
  884. return ret;
  885. }
  886. EXPORT_SYMBOL(del_timer);
  887. /**
  888. * try_to_del_timer_sync - Try to deactivate a timer
  889. * @timer: timer do del
  890. *
  891. * This function tries to deactivate a timer. Upon successful (ret >= 0)
  892. * exit the timer is not queued and the handler is not running on any CPU.
  893. */
  894. int try_to_del_timer_sync(struct timer_list *timer)
  895. {
  896. struct tvec_base *base;
  897. unsigned long flags;
  898. int ret = -1;
  899. debug_assert_init(timer);
  900. base = lock_timer_base(timer, &flags);
  901. if (base->running_timer != timer) {
  902. timer_stats_timer_clear_start_info(timer);
  903. ret = detach_if_pending(timer, base, true);
  904. }
  905. spin_unlock_irqrestore(&base->lock, flags);
  906. return ret;
  907. }
  908. EXPORT_SYMBOL(try_to_del_timer_sync);
  909. #ifdef CONFIG_SMP
  910. /**
  911. * del_timer_sync - deactivate a timer and wait for the handler to finish.
  912. * @timer: the timer to be deactivated
  913. *
  914. * This function only differs from del_timer() on SMP: besides deactivating
  915. * the timer it also makes sure the handler has finished executing on other
  916. * CPUs.
  917. *
  918. * Synchronization rules: Callers must prevent restarting of the timer,
  919. * otherwise this function is meaningless. It must not be called from
  920. * interrupt contexts unless the timer is an irqsafe one. The caller must
  921. * not hold locks which would prevent completion of the timer's
  922. * handler. The timer's handler must not call add_timer_on(). Upon exit the
  923. * timer is not queued and the handler is not running on any CPU.
  924. *
  925. * Note: For !irqsafe timers, you must not hold locks that are held in
  926. * interrupt context while calling this function. Even if the lock has
  927. * nothing to do with the timer in question. Here's why:
  928. *
  929. * CPU0 CPU1
  930. * ---- ----
  931. * <SOFTIRQ>
  932. * call_timer_fn();
  933. * base->running_timer = mytimer;
  934. * spin_lock_irq(somelock);
  935. * <IRQ>
  936. * spin_lock(somelock);
  937. * del_timer_sync(mytimer);
  938. * while (base->running_timer == mytimer);
  939. *
  940. * Now del_timer_sync() will never return and never release somelock.
  941. * The interrupt on the other CPU is waiting to grab somelock but
  942. * it has interrupted the softirq that CPU0 is waiting to finish.
  943. *
  944. * The function returns whether it has deactivated a pending timer or not.
  945. */
  946. int del_timer_sync(struct timer_list *timer)
  947. {
  948. #ifdef CONFIG_LOCKDEP
  949. unsigned long flags;
  950. /*
  951. * If lockdep gives a backtrace here, please reference
  952. * the synchronization rules above.
  953. */
  954. local_irq_save(flags);
  955. lock_map_acquire(&timer->lockdep_map);
  956. lock_map_release(&timer->lockdep_map);
  957. local_irq_restore(flags);
  958. #endif
  959. /*
  960. * don't use it in hardirq context, because it
  961. * could lead to deadlock.
  962. */
  963. WARN_ON(in_irq() && !tbase_get_irqsafe(timer->base));
  964. for (;;) {
  965. int ret = try_to_del_timer_sync(timer);
  966. if (ret >= 0)
  967. return ret;
  968. cpu_relax();
  969. }
  970. }
  971. EXPORT_SYMBOL(del_timer_sync);
  972. #endif
  973. static int cascade(struct tvec_base *base, struct tvec *tv, int index)
  974. {
  975. /* cascade all the timers from tv up one level */
  976. struct timer_list *timer, *tmp;
  977. struct list_head tv_list;
  978. list_replace_init(tv->vec + index, &tv_list);
  979. /*
  980. * We are removing _all_ timers from the list, so we
  981. * don't have to detach them individually.
  982. */
  983. list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
  984. BUG_ON(tbase_get_base(timer->base) != base);
  985. /* No accounting, while moving them */
  986. __internal_add_timer(base, timer);
  987. }
  988. return index;
  989. }
  990. static void call_timer_fn(struct timer_list *timer, void (*fn)(unsigned long),
  991. unsigned long data)
  992. {
  993. int count = preempt_count();
  994. #ifdef CONFIG_LOCKDEP
  995. /*
  996. * It is permissible to free the timer from inside the
  997. * function that is called from it, this we need to take into
  998. * account for lockdep too. To avoid bogus "held lock freed"
  999. * warnings as well as problems when looking into
  1000. * timer->lockdep_map, make a copy and use that here.
  1001. */
  1002. struct lockdep_map lockdep_map;
  1003. lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
  1004. #endif
  1005. /*
  1006. * Couple the lock chain with the lock chain at
  1007. * del_timer_sync() by acquiring the lock_map around the fn()
  1008. * call here and in del_timer_sync().
  1009. */
  1010. lock_map_acquire(&lockdep_map);
  1011. trace_timer_expire_entry(timer);
  1012. fn(data);
  1013. trace_timer_expire_exit(timer);
  1014. lock_map_release(&lockdep_map);
  1015. if (count != preempt_count()) {
  1016. WARN_ONCE(1, "timer: %pF preempt leak: %08x -> %08x\n",
  1017. fn, count, preempt_count());
  1018. /*
  1019. * Restore the preempt count. That gives us a decent
  1020. * chance to survive and extract information. If the
  1021. * callback kept a lock held, bad luck, but not worse
  1022. * than the BUG() we had.
  1023. */
  1024. preempt_count_set(count);
  1025. }
  1026. }
  1027. #define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
  1028. /**
  1029. * __run_timers - run all expired timers (if any) on this CPU.
  1030. * @base: the timer vector to be processed.
  1031. *
  1032. * This function cascades all vectors and executes all expired timer
  1033. * vectors.
  1034. */
  1035. static inline void __run_timers(struct tvec_base *base)
  1036. {
  1037. struct timer_list *timer;
  1038. spin_lock_irq(&base->lock);
  1039. if (catchup_timer_jiffies(base)) {
  1040. spin_unlock_irq(&base->lock);
  1041. return;
  1042. }
  1043. while (time_after_eq(jiffies, base->timer_jiffies)) {
  1044. struct list_head work_list;
  1045. struct list_head *head = &work_list;
  1046. int index = base->timer_jiffies & TVR_MASK;
  1047. /*
  1048. * Cascade timers:
  1049. */
  1050. if (!index &&
  1051. (!cascade(base, &base->tv2, INDEX(0))) &&
  1052. (!cascade(base, &base->tv3, INDEX(1))) &&
  1053. !cascade(base, &base->tv4, INDEX(2)))
  1054. cascade(base, &base->tv5, INDEX(3));
  1055. ++base->timer_jiffies;
  1056. list_replace_init(base->tv1.vec + index, head);
  1057. while (!list_empty(head)) {
  1058. void (*fn)(unsigned long);
  1059. unsigned long data;
  1060. bool irqsafe;
  1061. timer = list_first_entry(head, struct timer_list,entry);
  1062. fn = timer->function;
  1063. data = timer->data;
  1064. irqsafe = tbase_get_irqsafe(timer->base);
  1065. timer_stats_account_timer(timer);
  1066. base->running_timer = timer;
  1067. detach_expired_timer(timer, base);
  1068. if (irqsafe) {
  1069. spin_unlock(&base->lock);
  1070. call_timer_fn(timer, fn, data);
  1071. spin_lock(&base->lock);
  1072. } else {
  1073. spin_unlock_irq(&base->lock);
  1074. call_timer_fn(timer, fn, data);
  1075. spin_lock_irq(&base->lock);
  1076. }
  1077. }
  1078. }
  1079. base->running_timer = NULL;
  1080. spin_unlock_irq(&base->lock);
  1081. }
  1082. #ifdef CONFIG_NO_HZ_COMMON
  1083. /*
  1084. * Find out when the next timer event is due to happen. This
  1085. * is used on S/390 to stop all activity when a CPU is idle.
  1086. * This function needs to be called with interrupts disabled.
  1087. */
  1088. static unsigned long __next_timer_interrupt(struct tvec_base *base)
  1089. {
  1090. unsigned long timer_jiffies = base->timer_jiffies;
  1091. unsigned long expires = timer_jiffies + NEXT_TIMER_MAX_DELTA;
  1092. int index, slot, array, found = 0;
  1093. struct timer_list *nte;
  1094. struct tvec *varray[4];
  1095. /* Look for timer events in tv1. */
  1096. index = slot = timer_jiffies & TVR_MASK;
  1097. do {
  1098. list_for_each_entry(nte, base->tv1.vec + slot, entry) {
  1099. if (tbase_get_deferrable(nte->base))
  1100. continue;
  1101. found = 1;
  1102. expires = nte->expires;
  1103. /* Look at the cascade bucket(s)? */
  1104. if (!index || slot < index)
  1105. goto cascade;
  1106. return expires;
  1107. }
  1108. slot = (slot + 1) & TVR_MASK;
  1109. } while (slot != index);
  1110. cascade:
  1111. /* Calculate the next cascade event */
  1112. if (index)
  1113. timer_jiffies += TVR_SIZE - index;
  1114. timer_jiffies >>= TVR_BITS;
  1115. /* Check tv2-tv5. */
  1116. varray[0] = &base->tv2;
  1117. varray[1] = &base->tv3;
  1118. varray[2] = &base->tv4;
  1119. varray[3] = &base->tv5;
  1120. for (array = 0; array < 4; array++) {
  1121. struct tvec *varp = varray[array];
  1122. index = slot = timer_jiffies & TVN_MASK;
  1123. do {
  1124. list_for_each_entry(nte, varp->vec + slot, entry) {
  1125. if (tbase_get_deferrable(nte->base))
  1126. continue;
  1127. found = 1;
  1128. if (time_before(nte->expires, expires))
  1129. expires = nte->expires;
  1130. }
  1131. /*
  1132. * Do we still search for the first timer or are
  1133. * we looking up the cascade buckets ?
  1134. */
  1135. if (found) {
  1136. /* Look at the cascade bucket(s)? */
  1137. if (!index || slot < index)
  1138. break;
  1139. return expires;
  1140. }
  1141. slot = (slot + 1) & TVN_MASK;
  1142. } while (slot != index);
  1143. if (index)
  1144. timer_jiffies += TVN_SIZE - index;
  1145. timer_jiffies >>= TVN_BITS;
  1146. }
  1147. return expires;
  1148. }
  1149. /*
  1150. * Check, if the next hrtimer event is before the next timer wheel
  1151. * event:
  1152. */
  1153. static unsigned long cmp_next_hrtimer_event(unsigned long now,
  1154. unsigned long expires)
  1155. {
  1156. ktime_t hr_delta = hrtimer_get_next_event();
  1157. struct timespec tsdelta;
  1158. unsigned long delta;
  1159. if (hr_delta.tv64 == KTIME_MAX)
  1160. return expires;
  1161. /*
  1162. * Expired timer available, let it expire in the next tick
  1163. */
  1164. if (hr_delta.tv64 <= 0)
  1165. return now + 1;
  1166. tsdelta = ktime_to_timespec(hr_delta);
  1167. delta = timespec_to_jiffies(&tsdelta);
  1168. /*
  1169. * Limit the delta to the max value, which is checked in
  1170. * tick_nohz_stop_sched_tick():
  1171. */
  1172. if (delta > NEXT_TIMER_MAX_DELTA)
  1173. delta = NEXT_TIMER_MAX_DELTA;
  1174. /*
  1175. * Take rounding errors in to account and make sure, that it
  1176. * expires in the next tick. Otherwise we go into an endless
  1177. * ping pong due to tick_nohz_stop_sched_tick() retriggering
  1178. * the timer softirq
  1179. */
  1180. if (delta < 1)
  1181. delta = 1;
  1182. now += delta;
  1183. if (time_before(now, expires))
  1184. return now;
  1185. return expires;
  1186. }
  1187. /**
  1188. * get_next_timer_interrupt - return the jiffy of the next pending timer
  1189. * @now: current time (in jiffies)
  1190. */
  1191. unsigned long get_next_timer_interrupt(unsigned long now)
  1192. {
  1193. struct tvec_base *base = __this_cpu_read(tvec_bases);
  1194. unsigned long expires = now + NEXT_TIMER_MAX_DELTA;
  1195. /*
  1196. * Pretend that there is no timer pending if the cpu is offline.
  1197. * Possible pending timers will be migrated later to an active cpu.
  1198. */
  1199. if (cpu_is_offline(smp_processor_id()))
  1200. return expires;
  1201. spin_lock(&base->lock);
  1202. if (base->active_timers) {
  1203. if (time_before_eq(base->next_timer, base->timer_jiffies))
  1204. base->next_timer = __next_timer_interrupt(base);
  1205. expires = base->next_timer;
  1206. }
  1207. spin_unlock(&base->lock);
  1208. if (time_before_eq(expires, now))
  1209. return now;
  1210. return cmp_next_hrtimer_event(now, expires);
  1211. }
  1212. #endif
  1213. /*
  1214. * Called from the timer interrupt handler to charge one tick to the current
  1215. * process. user_tick is 1 if the tick is user time, 0 for system.
  1216. */
  1217. void update_process_times(int user_tick)
  1218. {
  1219. struct task_struct *p = current;
  1220. int cpu = smp_processor_id();
  1221. /* Note: this timer irq context must be accounted for as well. */
  1222. account_process_tick(p, user_tick);
  1223. run_local_timers();
  1224. rcu_check_callbacks(cpu, user_tick);
  1225. #ifdef CONFIG_IRQ_WORK
  1226. if (in_irq())
  1227. irq_work_tick();
  1228. #endif
  1229. scheduler_tick();
  1230. run_posix_cpu_timers(p);
  1231. }
  1232. /*
  1233. * This function runs timers and the timer-tq in bottom half context.
  1234. */
  1235. static void run_timer_softirq(struct softirq_action *h)
  1236. {
  1237. struct tvec_base *base = __this_cpu_read(tvec_bases);
  1238. hrtimer_run_pending();
  1239. if (time_after_eq(jiffies, base->timer_jiffies))
  1240. __run_timers(base);
  1241. }
  1242. /*
  1243. * Called by the local, per-CPU timer interrupt on SMP.
  1244. */
  1245. void run_local_timers(void)
  1246. {
  1247. hrtimer_run_queues();
  1248. raise_softirq(TIMER_SOFTIRQ);
  1249. }
  1250. #ifdef __ARCH_WANT_SYS_ALARM
  1251. /*
  1252. * For backwards compatibility? This can be done in libc so Alpha
  1253. * and all newer ports shouldn't need it.
  1254. */
  1255. SYSCALL_DEFINE1(alarm, unsigned int, seconds)
  1256. {
  1257. return alarm_setitimer(seconds);
  1258. }
  1259. #endif
  1260. static void process_timeout(unsigned long __data)
  1261. {
  1262. wake_up_process((struct task_struct *)__data);
  1263. }
  1264. /**
  1265. * schedule_timeout - sleep until timeout
  1266. * @timeout: timeout value in jiffies
  1267. *
  1268. * Make the current task sleep until @timeout jiffies have
  1269. * elapsed. The routine will return immediately unless
  1270. * the current task state has been set (see set_current_state()).
  1271. *
  1272. * You can set the task state as follows -
  1273. *
  1274. * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
  1275. * pass before the routine returns. The routine will return 0
  1276. *
  1277. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1278. * delivered to the current task. In this case the remaining time
  1279. * in jiffies will be returned, or 0 if the timer expired in time
  1280. *
  1281. * The current task state is guaranteed to be TASK_RUNNING when this
  1282. * routine returns.
  1283. *
  1284. * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
  1285. * the CPU away without a bound on the timeout. In this case the return
  1286. * value will be %MAX_SCHEDULE_TIMEOUT.
  1287. *
  1288. * In all cases the return value is guaranteed to be non-negative.
  1289. */
  1290. signed long __sched schedule_timeout(signed long timeout)
  1291. {
  1292. struct timer_list timer;
  1293. unsigned long expire;
  1294. switch (timeout)
  1295. {
  1296. case MAX_SCHEDULE_TIMEOUT:
  1297. /*
  1298. * These two special cases are useful to be comfortable
  1299. * in the caller. Nothing more. We could take
  1300. * MAX_SCHEDULE_TIMEOUT from one of the negative value
  1301. * but I' d like to return a valid offset (>=0) to allow
  1302. * the caller to do everything it want with the retval.
  1303. */
  1304. schedule();
  1305. goto out;
  1306. default:
  1307. /*
  1308. * Another bit of PARANOID. Note that the retval will be
  1309. * 0 since no piece of kernel is supposed to do a check
  1310. * for a negative retval of schedule_timeout() (since it
  1311. * should never happens anyway). You just have the printk()
  1312. * that will tell you if something is gone wrong and where.
  1313. */
  1314. if (timeout < 0) {
  1315. printk(KERN_ERR "schedule_timeout: wrong timeout "
  1316. "value %lx\n", timeout);
  1317. dump_stack();
  1318. current->state = TASK_RUNNING;
  1319. goto out;
  1320. }
  1321. }
  1322. expire = timeout + jiffies;
  1323. setup_timer_on_stack(&timer, process_timeout, (unsigned long)current);
  1324. __mod_timer(&timer, expire, false, TIMER_NOT_PINNED);
  1325. schedule();
  1326. del_singleshot_timer_sync(&timer);
  1327. /* Remove the timer from the object tracker */
  1328. destroy_timer_on_stack(&timer);
  1329. timeout = expire - jiffies;
  1330. out:
  1331. return timeout < 0 ? 0 : timeout;
  1332. }
  1333. EXPORT_SYMBOL(schedule_timeout);
  1334. /*
  1335. * We can use __set_current_state() here because schedule_timeout() calls
  1336. * schedule() unconditionally.
  1337. */
  1338. signed long __sched schedule_timeout_interruptible(signed long timeout)
  1339. {
  1340. __set_current_state(TASK_INTERRUPTIBLE);
  1341. return schedule_timeout(timeout);
  1342. }
  1343. EXPORT_SYMBOL(schedule_timeout_interruptible);
  1344. signed long __sched schedule_timeout_killable(signed long timeout)
  1345. {
  1346. __set_current_state(TASK_KILLABLE);
  1347. return schedule_timeout(timeout);
  1348. }
  1349. EXPORT_SYMBOL(schedule_timeout_killable);
  1350. signed long __sched schedule_timeout_uninterruptible(signed long timeout)
  1351. {
  1352. __set_current_state(TASK_UNINTERRUPTIBLE);
  1353. return schedule_timeout(timeout);
  1354. }
  1355. EXPORT_SYMBOL(schedule_timeout_uninterruptible);
  1356. static int init_timers_cpu(int cpu)
  1357. {
  1358. int j;
  1359. struct tvec_base *base;
  1360. static char tvec_base_done[NR_CPUS];
  1361. if (!tvec_base_done[cpu]) {
  1362. static char boot_done;
  1363. if (boot_done) {
  1364. /*
  1365. * The APs use this path later in boot
  1366. */
  1367. base = kzalloc_node(sizeof(*base), GFP_KERNEL,
  1368. cpu_to_node(cpu));
  1369. if (!base)
  1370. return -ENOMEM;
  1371. /* Make sure tvec_base has TIMER_FLAG_MASK bits free */
  1372. if (WARN_ON(base != tbase_get_base(base))) {
  1373. kfree(base);
  1374. return -ENOMEM;
  1375. }
  1376. per_cpu(tvec_bases, cpu) = base;
  1377. } else {
  1378. /*
  1379. * This is for the boot CPU - we use compile-time
  1380. * static initialisation because per-cpu memory isn't
  1381. * ready yet and because the memory allocators are not
  1382. * initialised either.
  1383. */
  1384. boot_done = 1;
  1385. base = &boot_tvec_bases;
  1386. }
  1387. spin_lock_init(&base->lock);
  1388. tvec_base_done[cpu] = 1;
  1389. base->cpu = cpu;
  1390. } else {
  1391. base = per_cpu(tvec_bases, cpu);
  1392. }
  1393. for (j = 0; j < TVN_SIZE; j++) {
  1394. INIT_LIST_HEAD(base->tv5.vec + j);
  1395. INIT_LIST_HEAD(base->tv4.vec + j);
  1396. INIT_LIST_HEAD(base->tv3.vec + j);
  1397. INIT_LIST_HEAD(base->tv2.vec + j);
  1398. }
  1399. for (j = 0; j < TVR_SIZE; j++)
  1400. INIT_LIST_HEAD(base->tv1.vec + j);
  1401. base->timer_jiffies = jiffies;
  1402. base->next_timer = base->timer_jiffies;
  1403. base->active_timers = 0;
  1404. base->all_timers = 0;
  1405. return 0;
  1406. }
  1407. #ifdef CONFIG_HOTPLUG_CPU
  1408. static void migrate_timer_list(struct tvec_base *new_base, struct list_head *head)
  1409. {
  1410. struct timer_list *timer;
  1411. while (!list_empty(head)) {
  1412. timer = list_first_entry(head, struct timer_list, entry);
  1413. /* We ignore the accounting on the dying cpu */
  1414. detach_timer(timer, false);
  1415. timer_set_base(timer, new_base);
  1416. internal_add_timer(new_base, timer);
  1417. }
  1418. }
  1419. static void migrate_timers(int cpu)
  1420. {
  1421. struct tvec_base *old_base;
  1422. struct tvec_base *new_base;
  1423. int i;
  1424. BUG_ON(cpu_online(cpu));
  1425. old_base = per_cpu(tvec_bases, cpu);
  1426. new_base = get_cpu_var(tvec_bases);
  1427. /*
  1428. * The caller is globally serialized and nobody else
  1429. * takes two locks at once, deadlock is not possible.
  1430. */
  1431. spin_lock_irq(&new_base->lock);
  1432. spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
  1433. BUG_ON(old_base->running_timer);
  1434. for (i = 0; i < TVR_SIZE; i++)
  1435. migrate_timer_list(new_base, old_base->tv1.vec + i);
  1436. for (i = 0; i < TVN_SIZE; i++) {
  1437. migrate_timer_list(new_base, old_base->tv2.vec + i);
  1438. migrate_timer_list(new_base, old_base->tv3.vec + i);
  1439. migrate_timer_list(new_base, old_base->tv4.vec + i);
  1440. migrate_timer_list(new_base, old_base->tv5.vec + i);
  1441. }
  1442. spin_unlock(&old_base->lock);
  1443. spin_unlock_irq(&new_base->lock);
  1444. put_cpu_var(tvec_bases);
  1445. }
  1446. #endif /* CONFIG_HOTPLUG_CPU */
  1447. static int timer_cpu_notify(struct notifier_block *self,
  1448. unsigned long action, void *hcpu)
  1449. {
  1450. long cpu = (long)hcpu;
  1451. int err;
  1452. switch(action) {
  1453. case CPU_UP_PREPARE:
  1454. case CPU_UP_PREPARE_FROZEN:
  1455. err = init_timers_cpu(cpu);
  1456. if (err < 0)
  1457. return notifier_from_errno(err);
  1458. break;
  1459. #ifdef CONFIG_HOTPLUG_CPU
  1460. case CPU_DEAD:
  1461. case CPU_DEAD_FROZEN:
  1462. migrate_timers(cpu);
  1463. break;
  1464. #endif
  1465. default:
  1466. break;
  1467. }
  1468. return NOTIFY_OK;
  1469. }
  1470. static struct notifier_block timers_nb = {
  1471. .notifier_call = timer_cpu_notify,
  1472. };
  1473. void __init init_timers(void)
  1474. {
  1475. int err;
  1476. /* ensure there are enough low bits for flags in timer->base pointer */
  1477. BUILD_BUG_ON(__alignof__(struct tvec_base) & TIMER_FLAG_MASK);
  1478. err = timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
  1479. (void *)(long)smp_processor_id());
  1480. BUG_ON(err != NOTIFY_OK);
  1481. init_timer_stats();
  1482. register_cpu_notifier(&timers_nb);
  1483. open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
  1484. }
  1485. /**
  1486. * msleep - sleep safely even with waitqueue interruptions
  1487. * @msecs: Time in milliseconds to sleep for
  1488. */
  1489. void msleep(unsigned int msecs)
  1490. {
  1491. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1492. while (timeout)
  1493. timeout = schedule_timeout_uninterruptible(timeout);
  1494. }
  1495. EXPORT_SYMBOL(msleep);
  1496. /**
  1497. * msleep_interruptible - sleep waiting for signals
  1498. * @msecs: Time in milliseconds to sleep for
  1499. */
  1500. unsigned long msleep_interruptible(unsigned int msecs)
  1501. {
  1502. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1503. while (timeout && !signal_pending(current))
  1504. timeout = schedule_timeout_interruptible(timeout);
  1505. return jiffies_to_msecs(timeout);
  1506. }
  1507. EXPORT_SYMBOL(msleep_interruptible);
  1508. static int __sched do_usleep_range(unsigned long min, unsigned long max)
  1509. {
  1510. ktime_t kmin;
  1511. unsigned long delta;
  1512. kmin = ktime_set(0, min * NSEC_PER_USEC);
  1513. delta = (max - min) * NSEC_PER_USEC;
  1514. return schedule_hrtimeout_range(&kmin, delta, HRTIMER_MODE_REL);
  1515. }
  1516. /**
  1517. * usleep_range - Drop in replacement for udelay where wakeup is flexible
  1518. * @min: Minimum time in usecs to sleep
  1519. * @max: Maximum time in usecs to sleep
  1520. */
  1521. void usleep_range(unsigned long min, unsigned long max)
  1522. {
  1523. __set_current_state(TASK_UNINTERRUPTIBLE);
  1524. do_usleep_range(min, max);
  1525. }
  1526. EXPORT_SYMBOL(usleep_range);