timer.c 51 KB

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