timer.c 55 KB

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