timer.c 57 KB

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