timer.c 57 KB

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