timer.c 56 KB

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