timer.c 56 KB

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