timer.c 57 KB

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