timer.c 54 KB

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