timer.c 47 KB

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