timer.c 57 KB

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