timer.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. /*
  2. * linux/kernel/timer.c
  3. *
  4. * Kernel internal timers, basic process system calls
  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/module.h>
  23. #include <linux/interrupt.h>
  24. #include <linux/percpu.h>
  25. #include <linux/init.h>
  26. #include <linux/mm.h>
  27. #include <linux/swap.h>
  28. #include <linux/pid_namespace.h>
  29. #include <linux/notifier.h>
  30. #include <linux/thread_info.h>
  31. #include <linux/time.h>
  32. #include <linux/jiffies.h>
  33. #include <linux/posix-timers.h>
  34. #include <linux/cpu.h>
  35. #include <linux/syscalls.h>
  36. #include <linux/delay.h>
  37. #include <linux/tick.h>
  38. #include <linux/kallsyms.h>
  39. #include <linux/irq_work.h>
  40. #include <linux/sched.h>
  41. #include <linux/slab.h>
  42. #include <asm/uaccess.h>
  43. #include <asm/unistd.h>
  44. #include <asm/div64.h>
  45. #include <asm/timex.h>
  46. #include <asm/io.h>
  47. #define CREATE_TRACE_POINTS
  48. #include <trace/events/timer.h>
  49. u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
  50. EXPORT_SYMBOL(jiffies_64);
  51. /*
  52. * per-CPU timer vector definitions:
  53. */
  54. #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
  55. #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
  56. #define TVN_SIZE (1 << TVN_BITS)
  57. #define TVR_SIZE (1 << TVR_BITS)
  58. #define TVN_MASK (TVN_SIZE - 1)
  59. #define TVR_MASK (TVR_SIZE - 1)
  60. struct tvec {
  61. struct list_head vec[TVN_SIZE];
  62. };
  63. struct tvec_root {
  64. struct list_head vec[TVR_SIZE];
  65. };
  66. struct tvec_base {
  67. spinlock_t lock;
  68. struct timer_list *running_timer;
  69. unsigned long timer_jiffies;
  70. unsigned long next_timer;
  71. struct tvec_root tv1;
  72. struct tvec tv2;
  73. struct tvec tv3;
  74. struct tvec tv4;
  75. struct tvec tv5;
  76. } ____cacheline_aligned;
  77. struct tvec_base boot_tvec_bases;
  78. EXPORT_SYMBOL(boot_tvec_bases);
  79. static DEFINE_PER_CPU(struct tvec_base *, tvec_bases) = &boot_tvec_bases;
  80. /* Functions below help us manage 'deferrable' flag */
  81. static inline unsigned int tbase_get_deferrable(struct tvec_base *base)
  82. {
  83. return ((unsigned int)(unsigned long)base & TBASE_DEFERRABLE_FLAG);
  84. }
  85. static inline struct tvec_base *tbase_get_base(struct tvec_base *base)
  86. {
  87. return ((struct tvec_base *)((unsigned long)base & ~TBASE_DEFERRABLE_FLAG));
  88. }
  89. static inline void timer_set_deferrable(struct timer_list *timer)
  90. {
  91. timer->base = TBASE_MAKE_DEFERRED(timer->base);
  92. }
  93. static inline void
  94. timer_set_base(struct timer_list *timer, struct tvec_base *new_base)
  95. {
  96. timer->base = (struct tvec_base *)((unsigned long)(new_base) |
  97. tbase_get_deferrable(timer->base));
  98. }
  99. static unsigned long round_jiffies_common(unsigned long j, int cpu,
  100. bool force_up)
  101. {
  102. int rem;
  103. unsigned long original = j;
  104. /*
  105. * We don't want all cpus firing their timers at once hitting the
  106. * same lock or cachelines, so we skew each extra cpu with an extra
  107. * 3 jiffies. This 3 jiffies came originally from the mm/ code which
  108. * already did this.
  109. * The skew is done by adding 3*cpunr, then round, then subtract this
  110. * extra offset again.
  111. */
  112. j += cpu * 3;
  113. rem = j % HZ;
  114. /*
  115. * If the target jiffie is just after a whole second (which can happen
  116. * due to delays of the timer irq, long irq off times etc etc) then
  117. * we should round down to the whole second, not up. Use 1/4th second
  118. * as cutoff for this rounding as an extreme upper bound for this.
  119. * But never round down if @force_up is set.
  120. */
  121. if (rem < HZ/4 && !force_up) /* round down */
  122. j = j - rem;
  123. else /* round up */
  124. j = j - rem + HZ;
  125. /* now that we have rounded, subtract the extra skew again */
  126. j -= cpu * 3;
  127. if (j <= jiffies) /* rounding ate our timeout entirely; */
  128. return original;
  129. return j;
  130. }
  131. /**
  132. * __round_jiffies - function to round jiffies to a full second
  133. * @j: the time in (absolute) jiffies that should be rounded
  134. * @cpu: the processor number on which the timeout will happen
  135. *
  136. * __round_jiffies() rounds an absolute time in the future (in jiffies)
  137. * up or down to (approximately) full seconds. This is useful for timers
  138. * for which the exact time they fire does not matter too much, as long as
  139. * they fire approximately every X seconds.
  140. *
  141. * By rounding these timers to whole seconds, all such timers will fire
  142. * at the same time, rather than at various times spread out. The goal
  143. * of this is to have the CPU wake up less, which saves power.
  144. *
  145. * The exact rounding is skewed for each processor to avoid all
  146. * processors firing at the exact same time, which could lead
  147. * to lock contention or spurious cache line bouncing.
  148. *
  149. * The return value is the rounded version of the @j parameter.
  150. */
  151. unsigned long __round_jiffies(unsigned long j, int cpu)
  152. {
  153. return round_jiffies_common(j, cpu, false);
  154. }
  155. EXPORT_SYMBOL_GPL(__round_jiffies);
  156. /**
  157. * __round_jiffies_relative - function to round jiffies to a full second
  158. * @j: the time in (relative) jiffies that should be rounded
  159. * @cpu: the processor number on which the timeout will happen
  160. *
  161. * __round_jiffies_relative() rounds a time delta in the future (in jiffies)
  162. * up or down to (approximately) full seconds. This is useful for timers
  163. * for which the exact time they fire does not matter too much, as long as
  164. * they fire approximately every X seconds.
  165. *
  166. * By rounding these timers to whole seconds, all such timers will fire
  167. * at the same time, rather than at various times spread out. The goal
  168. * of this is to have the CPU wake up less, which saves power.
  169. *
  170. * The exact rounding is skewed for each processor to avoid all
  171. * processors firing at the exact same time, which could lead
  172. * to lock contention or spurious cache line bouncing.
  173. *
  174. * The return value is the rounded version of the @j parameter.
  175. */
  176. unsigned long __round_jiffies_relative(unsigned long j, int cpu)
  177. {
  178. unsigned long j0 = jiffies;
  179. /* Use j0 because jiffies might change while we run */
  180. return round_jiffies_common(j + j0, cpu, false) - j0;
  181. }
  182. EXPORT_SYMBOL_GPL(__round_jiffies_relative);
  183. /**
  184. * round_jiffies - function to round jiffies to a full second
  185. * @j: the time in (absolute) jiffies that should be rounded
  186. *
  187. * round_jiffies() rounds an absolute time in the future (in jiffies)
  188. * up or down to (approximately) full seconds. This is useful for timers
  189. * for which the exact time they fire does not matter too much, as long as
  190. * they fire approximately every X seconds.
  191. *
  192. * By rounding these timers to whole seconds, all such timers will fire
  193. * at the same time, rather than at various times spread out. The goal
  194. * of this is to have the CPU wake up less, which saves power.
  195. *
  196. * The return value is the rounded version of the @j parameter.
  197. */
  198. unsigned long round_jiffies(unsigned long j)
  199. {
  200. return round_jiffies_common(j, raw_smp_processor_id(), false);
  201. }
  202. EXPORT_SYMBOL_GPL(round_jiffies);
  203. /**
  204. * round_jiffies_relative - function to round jiffies to a full second
  205. * @j: the time in (relative) jiffies that should be rounded
  206. *
  207. * round_jiffies_relative() rounds a time delta in the future (in jiffies)
  208. * up or down to (approximately) full seconds. This is useful for timers
  209. * for which the exact time they fire does not matter too much, as long as
  210. * they fire approximately every X seconds.
  211. *
  212. * By rounding these timers to whole seconds, all such timers will fire
  213. * at the same time, rather than at various times spread out. The goal
  214. * of this is to have the CPU wake up less, which saves power.
  215. *
  216. * The return value is the rounded version of the @j parameter.
  217. */
  218. unsigned long round_jiffies_relative(unsigned long j)
  219. {
  220. return __round_jiffies_relative(j, raw_smp_processor_id());
  221. }
  222. EXPORT_SYMBOL_GPL(round_jiffies_relative);
  223. /**
  224. * __round_jiffies_up - function to round jiffies up to a full second
  225. * @j: the time in (absolute) jiffies that should be rounded
  226. * @cpu: the processor number on which the timeout will happen
  227. *
  228. * This is the same as __round_jiffies() except that it will never
  229. * round down. This is useful for timeouts for which the exact time
  230. * of firing does not matter too much, as long as they don't fire too
  231. * early.
  232. */
  233. unsigned long __round_jiffies_up(unsigned long j, int cpu)
  234. {
  235. return round_jiffies_common(j, cpu, true);
  236. }
  237. EXPORT_SYMBOL_GPL(__round_jiffies_up);
  238. /**
  239. * __round_jiffies_up_relative - function to round jiffies up to a full second
  240. * @j: the time in (relative) jiffies that should be rounded
  241. * @cpu: the processor number on which the timeout will happen
  242. *
  243. * This is the same as __round_jiffies_relative() except that it will never
  244. * round down. This is useful for timeouts for which the exact time
  245. * of firing does not matter too much, as long as they don't fire too
  246. * early.
  247. */
  248. unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
  249. {
  250. unsigned long j0 = jiffies;
  251. /* Use j0 because jiffies might change while we run */
  252. return round_jiffies_common(j + j0, cpu, true) - j0;
  253. }
  254. EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
  255. /**
  256. * round_jiffies_up - function to round jiffies up to a full second
  257. * @j: the time in (absolute) jiffies that should be rounded
  258. *
  259. * This is the same as round_jiffies() except that it will never
  260. * round down. This is useful for timeouts for which the exact time
  261. * of firing does not matter too much, as long as they don't fire too
  262. * early.
  263. */
  264. unsigned long round_jiffies_up(unsigned long j)
  265. {
  266. return round_jiffies_common(j, raw_smp_processor_id(), true);
  267. }
  268. EXPORT_SYMBOL_GPL(round_jiffies_up);
  269. /**
  270. * round_jiffies_up_relative - function to round jiffies up to a full second
  271. * @j: the time in (relative) jiffies that should be rounded
  272. *
  273. * This is the same as round_jiffies_relative() except that it will never
  274. * round down. This is useful for timeouts for which the exact time
  275. * of firing does not matter too much, as long as they don't fire too
  276. * early.
  277. */
  278. unsigned long round_jiffies_up_relative(unsigned long j)
  279. {
  280. return __round_jiffies_up_relative(j, raw_smp_processor_id());
  281. }
  282. EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
  283. /**
  284. * set_timer_slack - set the allowed slack for a timer
  285. * @timer: the timer to be modified
  286. * @slack_hz: the amount of time (in jiffies) allowed for rounding
  287. *
  288. * Set the amount of time, in jiffies, that a certain timer has
  289. * in terms of slack. By setting this value, the timer subsystem
  290. * will schedule the actual timer somewhere between
  291. * the time mod_timer() asks for, and that time plus the slack.
  292. *
  293. * By setting the slack to -1, a percentage of the delay is used
  294. * instead.
  295. */
  296. void set_timer_slack(struct timer_list *timer, int slack_hz)
  297. {
  298. timer->slack = slack_hz;
  299. }
  300. EXPORT_SYMBOL_GPL(set_timer_slack);
  301. static void internal_add_timer(struct tvec_base *base, struct timer_list *timer)
  302. {
  303. unsigned long expires = timer->expires;
  304. unsigned long idx = expires - base->timer_jiffies;
  305. struct list_head *vec;
  306. if (idx < TVR_SIZE) {
  307. int i = expires & TVR_MASK;
  308. vec = base->tv1.vec + i;
  309. } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
  310. int i = (expires >> TVR_BITS) & TVN_MASK;
  311. vec = base->tv2.vec + i;
  312. } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
  313. int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
  314. vec = base->tv3.vec + i;
  315. } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
  316. int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
  317. vec = base->tv4.vec + i;
  318. } else if ((signed long) idx < 0) {
  319. /*
  320. * Can happen if you add a timer with expires == jiffies,
  321. * or you set a timer to go off in the past
  322. */
  323. vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
  324. } else {
  325. int i;
  326. /* If the timeout is larger than 0xffffffff on 64-bit
  327. * architectures then we use the maximum timeout:
  328. */
  329. if (idx > 0xffffffffUL) {
  330. idx = 0xffffffffUL;
  331. expires = idx + base->timer_jiffies;
  332. }
  333. i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
  334. vec = base->tv5.vec + i;
  335. }
  336. /*
  337. * Timers are FIFO:
  338. */
  339. list_add_tail(&timer->entry, vec);
  340. }
  341. #ifdef CONFIG_TIMER_STATS
  342. void __timer_stats_timer_set_start_info(struct timer_list *timer, void *addr)
  343. {
  344. if (timer->start_site)
  345. return;
  346. timer->start_site = addr;
  347. memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
  348. timer->start_pid = current->pid;
  349. }
  350. static void timer_stats_account_timer(struct timer_list *timer)
  351. {
  352. unsigned int flag = 0;
  353. if (likely(!timer->start_site))
  354. return;
  355. if (unlikely(tbase_get_deferrable(timer->base)))
  356. flag |= TIMER_STATS_FLAG_DEFERRABLE;
  357. timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
  358. timer->function, timer->start_comm, flag);
  359. }
  360. #else
  361. static void timer_stats_account_timer(struct timer_list *timer) {}
  362. #endif
  363. #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
  364. static struct debug_obj_descr timer_debug_descr;
  365. /*
  366. * fixup_init is called when:
  367. * - an active object is initialized
  368. */
  369. static int timer_fixup_init(void *addr, enum debug_obj_state state)
  370. {
  371. struct timer_list *timer = addr;
  372. switch (state) {
  373. case ODEBUG_STATE_ACTIVE:
  374. del_timer_sync(timer);
  375. debug_object_init(timer, &timer_debug_descr);
  376. return 1;
  377. default:
  378. return 0;
  379. }
  380. }
  381. /*
  382. * fixup_activate is called when:
  383. * - an active object is activated
  384. * - an unknown object is activated (might be a statically initialized object)
  385. */
  386. static int timer_fixup_activate(void *addr, enum debug_obj_state state)
  387. {
  388. struct timer_list *timer = addr;
  389. switch (state) {
  390. case ODEBUG_STATE_NOTAVAILABLE:
  391. /*
  392. * This is not really a fixup. The timer was
  393. * statically initialized. We just make sure that it
  394. * is tracked in the object tracker.
  395. */
  396. if (timer->entry.next == NULL &&
  397. timer->entry.prev == TIMER_ENTRY_STATIC) {
  398. debug_object_init(timer, &timer_debug_descr);
  399. debug_object_activate(timer, &timer_debug_descr);
  400. return 0;
  401. } else {
  402. WARN_ON_ONCE(1);
  403. }
  404. return 0;
  405. case ODEBUG_STATE_ACTIVE:
  406. WARN_ON(1);
  407. default:
  408. return 0;
  409. }
  410. }
  411. /*
  412. * fixup_free is called when:
  413. * - an active object is freed
  414. */
  415. static int timer_fixup_free(void *addr, enum debug_obj_state state)
  416. {
  417. struct timer_list *timer = addr;
  418. switch (state) {
  419. case ODEBUG_STATE_ACTIVE:
  420. del_timer_sync(timer);
  421. debug_object_free(timer, &timer_debug_descr);
  422. return 1;
  423. default:
  424. return 0;
  425. }
  426. }
  427. static struct debug_obj_descr timer_debug_descr = {
  428. .name = "timer_list",
  429. .fixup_init = timer_fixup_init,
  430. .fixup_activate = timer_fixup_activate,
  431. .fixup_free = timer_fixup_free,
  432. };
  433. static inline void debug_timer_init(struct timer_list *timer)
  434. {
  435. debug_object_init(timer, &timer_debug_descr);
  436. }
  437. static inline void debug_timer_activate(struct timer_list *timer)
  438. {
  439. debug_object_activate(timer, &timer_debug_descr);
  440. }
  441. static inline void debug_timer_deactivate(struct timer_list *timer)
  442. {
  443. debug_object_deactivate(timer, &timer_debug_descr);
  444. }
  445. static inline void debug_timer_free(struct timer_list *timer)
  446. {
  447. debug_object_free(timer, &timer_debug_descr);
  448. }
  449. static void __init_timer(struct timer_list *timer,
  450. const char *name,
  451. struct lock_class_key *key);
  452. void init_timer_on_stack_key(struct timer_list *timer,
  453. const char *name,
  454. struct lock_class_key *key)
  455. {
  456. debug_object_init_on_stack(timer, &timer_debug_descr);
  457. __init_timer(timer, name, key);
  458. }
  459. EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
  460. void destroy_timer_on_stack(struct timer_list *timer)
  461. {
  462. debug_object_free(timer, &timer_debug_descr);
  463. }
  464. EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
  465. #else
  466. static inline void debug_timer_init(struct timer_list *timer) { }
  467. static inline void debug_timer_activate(struct timer_list *timer) { }
  468. static inline void debug_timer_deactivate(struct timer_list *timer) { }
  469. #endif
  470. static inline void debug_init(struct timer_list *timer)
  471. {
  472. debug_timer_init(timer);
  473. trace_timer_init(timer);
  474. }
  475. static inline void
  476. debug_activate(struct timer_list *timer, unsigned long expires)
  477. {
  478. debug_timer_activate(timer);
  479. trace_timer_start(timer, expires);
  480. }
  481. static inline void debug_deactivate(struct timer_list *timer)
  482. {
  483. debug_timer_deactivate(timer);
  484. trace_timer_cancel(timer);
  485. }
  486. static void __init_timer(struct timer_list *timer,
  487. const char *name,
  488. struct lock_class_key *key)
  489. {
  490. timer->entry.next = NULL;
  491. timer->base = __raw_get_cpu_var(tvec_bases);
  492. timer->slack = -1;
  493. #ifdef CONFIG_TIMER_STATS
  494. timer->start_site = NULL;
  495. timer->start_pid = -1;
  496. memset(timer->start_comm, 0, TASK_COMM_LEN);
  497. #endif
  498. lockdep_init_map(&timer->lockdep_map, name, key, 0);
  499. }
  500. void setup_deferrable_timer_on_stack_key(struct timer_list *timer,
  501. const char *name,
  502. struct lock_class_key *key,
  503. void (*function)(unsigned long),
  504. unsigned long data)
  505. {
  506. timer->function = function;
  507. timer->data = data;
  508. init_timer_on_stack_key(timer, name, key);
  509. timer_set_deferrable(timer);
  510. }
  511. EXPORT_SYMBOL_GPL(setup_deferrable_timer_on_stack_key);
  512. /**
  513. * init_timer_key - initialize a timer
  514. * @timer: the timer to be initialized
  515. * @name: name of the timer
  516. * @key: lockdep class key of the fake lock used for tracking timer
  517. * sync lock dependencies
  518. *
  519. * init_timer_key() must be done to a timer prior calling *any* of the
  520. * other timer functions.
  521. */
  522. void init_timer_key(struct timer_list *timer,
  523. const char *name,
  524. struct lock_class_key *key)
  525. {
  526. debug_init(timer);
  527. __init_timer(timer, name, key);
  528. }
  529. EXPORT_SYMBOL(init_timer_key);
  530. void init_timer_deferrable_key(struct timer_list *timer,
  531. const char *name,
  532. struct lock_class_key *key)
  533. {
  534. init_timer_key(timer, name, key);
  535. timer_set_deferrable(timer);
  536. }
  537. EXPORT_SYMBOL(init_timer_deferrable_key);
  538. static inline void detach_timer(struct timer_list *timer,
  539. int clear_pending)
  540. {
  541. struct list_head *entry = &timer->entry;
  542. debug_deactivate(timer);
  543. __list_del(entry->prev, entry->next);
  544. if (clear_pending)
  545. entry->next = NULL;
  546. entry->prev = LIST_POISON2;
  547. }
  548. /*
  549. * We are using hashed locking: holding per_cpu(tvec_bases).lock
  550. * means that all timers which are tied to this base via timer->base are
  551. * locked, and the base itself is locked too.
  552. *
  553. * So __run_timers/migrate_timers can safely modify all timers which could
  554. * be found on ->tvX lists.
  555. *
  556. * When the timer's base is locked, and the timer removed from list, it is
  557. * possible to set timer->base = NULL and drop the lock: the timer remains
  558. * locked.
  559. */
  560. static struct tvec_base *lock_timer_base(struct timer_list *timer,
  561. unsigned long *flags)
  562. __acquires(timer->base->lock)
  563. {
  564. struct tvec_base *base;
  565. for (;;) {
  566. struct tvec_base *prelock_base = timer->base;
  567. base = tbase_get_base(prelock_base);
  568. if (likely(base != NULL)) {
  569. spin_lock_irqsave(&base->lock, *flags);
  570. if (likely(prelock_base == timer->base))
  571. return base;
  572. /* The timer has migrated to another CPU */
  573. spin_unlock_irqrestore(&base->lock, *flags);
  574. }
  575. cpu_relax();
  576. }
  577. }
  578. static inline int
  579. __mod_timer(struct timer_list *timer, unsigned long expires,
  580. bool pending_only, int pinned)
  581. {
  582. struct tvec_base *base, *new_base;
  583. unsigned long flags;
  584. int ret = 0 , cpu;
  585. timer_stats_timer_set_start_info(timer);
  586. BUG_ON(!timer->function);
  587. base = lock_timer_base(timer, &flags);
  588. if (timer_pending(timer)) {
  589. detach_timer(timer, 0);
  590. if (timer->expires == base->next_timer &&
  591. !tbase_get_deferrable(timer->base))
  592. base->next_timer = base->timer_jiffies;
  593. ret = 1;
  594. } else {
  595. if (pending_only)
  596. goto out_unlock;
  597. }
  598. debug_activate(timer, expires);
  599. cpu = smp_processor_id();
  600. #if defined(CONFIG_NO_HZ) && defined(CONFIG_SMP)
  601. if (!pinned && get_sysctl_timer_migration() && idle_cpu(cpu))
  602. cpu = get_nohz_timer_target();
  603. #endif
  604. new_base = per_cpu(tvec_bases, cpu);
  605. if (base != new_base) {
  606. /*
  607. * We are trying to schedule the timer on the local CPU.
  608. * However we can't change timer's base while it is running,
  609. * otherwise del_timer_sync() can't detect that the timer's
  610. * handler yet has not finished. This also guarantees that
  611. * the timer is serialized wrt itself.
  612. */
  613. if (likely(base->running_timer != timer)) {
  614. /* See the comment in lock_timer_base() */
  615. timer_set_base(timer, NULL);
  616. spin_unlock(&base->lock);
  617. base = new_base;
  618. spin_lock(&base->lock);
  619. timer_set_base(timer, base);
  620. }
  621. }
  622. timer->expires = expires;
  623. if (time_before(timer->expires, base->next_timer) &&
  624. !tbase_get_deferrable(timer->base))
  625. base->next_timer = timer->expires;
  626. internal_add_timer(base, timer);
  627. out_unlock:
  628. spin_unlock_irqrestore(&base->lock, flags);
  629. return ret;
  630. }
  631. /**
  632. * mod_timer_pending - modify a pending timer's timeout
  633. * @timer: the pending timer to be modified
  634. * @expires: new timeout in jiffies
  635. *
  636. * mod_timer_pending() is the same for pending timers as mod_timer(),
  637. * but will not re-activate and modify already deleted timers.
  638. *
  639. * It is useful for unserialized use of timers.
  640. */
  641. int mod_timer_pending(struct timer_list *timer, unsigned long expires)
  642. {
  643. return __mod_timer(timer, expires, true, TIMER_NOT_PINNED);
  644. }
  645. EXPORT_SYMBOL(mod_timer_pending);
  646. /*
  647. * Decide where to put the timer while taking the slack into account
  648. *
  649. * Algorithm:
  650. * 1) calculate the maximum (absolute) time
  651. * 2) calculate the highest bit where the expires and new max are different
  652. * 3) use this bit to make a mask
  653. * 4) use the bitmask to round down the maximum time, so that all last
  654. * bits are zeros
  655. */
  656. static inline
  657. unsigned long apply_slack(struct timer_list *timer, unsigned long expires)
  658. {
  659. unsigned long expires_limit, mask;
  660. int bit;
  661. expires_limit = expires;
  662. if (timer->slack >= 0) {
  663. expires_limit = expires + timer->slack;
  664. } else {
  665. unsigned long now = jiffies;
  666. /* No slack, if already expired else auto slack 0.4% */
  667. if (time_after(expires, now))
  668. expires_limit = expires + (expires - now)/256;
  669. }
  670. mask = expires ^ expires_limit;
  671. if (mask == 0)
  672. return expires;
  673. bit = find_last_bit(&mask, BITS_PER_LONG);
  674. mask = (1 << bit) - 1;
  675. expires_limit = expires_limit & ~(mask);
  676. return expires_limit;
  677. }
  678. /**
  679. * mod_timer - modify a timer's timeout
  680. * @timer: the timer to be modified
  681. * @expires: new timeout in jiffies
  682. *
  683. * mod_timer() is a more efficient way to update the expire field of an
  684. * active timer (if the timer is inactive it will be activated)
  685. *
  686. * mod_timer(timer, expires) is equivalent to:
  687. *
  688. * del_timer(timer); timer->expires = expires; add_timer(timer);
  689. *
  690. * Note that if there are multiple unserialized concurrent users of the
  691. * same timer, then mod_timer() is the only safe way to modify the timeout,
  692. * since add_timer() cannot modify an already running timer.
  693. *
  694. * The function returns whether it has modified a pending timer or not.
  695. * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
  696. * active timer returns 1.)
  697. */
  698. int mod_timer(struct timer_list *timer, unsigned long expires)
  699. {
  700. /*
  701. * This is a common optimization triggered by the
  702. * networking code - if the timer is re-modified
  703. * to be the same thing then just return:
  704. */
  705. if (timer_pending(timer) && timer->expires == expires)
  706. return 1;
  707. expires = apply_slack(timer, expires);
  708. return __mod_timer(timer, expires, false, TIMER_NOT_PINNED);
  709. }
  710. EXPORT_SYMBOL(mod_timer);
  711. /**
  712. * mod_timer_pinned - modify a timer's timeout
  713. * @timer: the timer to be modified
  714. * @expires: new timeout in jiffies
  715. *
  716. * mod_timer_pinned() is a way to update the expire field of an
  717. * active timer (if the timer is inactive it will be activated)
  718. * and not allow the timer to be migrated to a different CPU.
  719. *
  720. * mod_timer_pinned(timer, expires) is equivalent to:
  721. *
  722. * del_timer(timer); timer->expires = expires; add_timer(timer);
  723. */
  724. int mod_timer_pinned(struct timer_list *timer, unsigned long expires)
  725. {
  726. if (timer->expires == expires && timer_pending(timer))
  727. return 1;
  728. return __mod_timer(timer, expires, false, TIMER_PINNED);
  729. }
  730. EXPORT_SYMBOL(mod_timer_pinned);
  731. /**
  732. * add_timer - start a timer
  733. * @timer: the timer to be added
  734. *
  735. * The kernel will do a ->function(->data) callback from the
  736. * timer interrupt at the ->expires point in the future. The
  737. * current time is 'jiffies'.
  738. *
  739. * The timer's ->expires, ->function (and if the handler uses it, ->data)
  740. * fields must be set prior calling this function.
  741. *
  742. * Timers with an ->expires field in the past will be executed in the next
  743. * timer tick.
  744. */
  745. void add_timer(struct timer_list *timer)
  746. {
  747. BUG_ON(timer_pending(timer));
  748. mod_timer(timer, timer->expires);
  749. }
  750. EXPORT_SYMBOL(add_timer);
  751. /**
  752. * add_timer_on - start a timer on a particular CPU
  753. * @timer: the timer to be added
  754. * @cpu: the CPU to start it on
  755. *
  756. * This is not very scalable on SMP. Double adds are not possible.
  757. */
  758. void add_timer_on(struct timer_list *timer, int cpu)
  759. {
  760. struct tvec_base *base = per_cpu(tvec_bases, cpu);
  761. unsigned long flags;
  762. timer_stats_timer_set_start_info(timer);
  763. BUG_ON(timer_pending(timer) || !timer->function);
  764. spin_lock_irqsave(&base->lock, flags);
  765. timer_set_base(timer, base);
  766. debug_activate(timer, timer->expires);
  767. if (time_before(timer->expires, base->next_timer) &&
  768. !tbase_get_deferrable(timer->base))
  769. base->next_timer = timer->expires;
  770. internal_add_timer(base, timer);
  771. /*
  772. * Check whether the other CPU is idle and needs to be
  773. * triggered to reevaluate the timer wheel when nohz is
  774. * active. We are protected against the other CPU fiddling
  775. * with the timer by holding the timer base lock. This also
  776. * makes sure that a CPU on the way to idle can not evaluate
  777. * the timer wheel.
  778. */
  779. wake_up_idle_cpu(cpu);
  780. spin_unlock_irqrestore(&base->lock, flags);
  781. }
  782. EXPORT_SYMBOL_GPL(add_timer_on);
  783. /**
  784. * del_timer - deactive a timer.
  785. * @timer: the timer to be deactivated
  786. *
  787. * del_timer() deactivates a timer - this works on both active and inactive
  788. * timers.
  789. *
  790. * The function returns whether it has deactivated a pending timer or not.
  791. * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
  792. * active timer returns 1.)
  793. */
  794. int del_timer(struct timer_list *timer)
  795. {
  796. struct tvec_base *base;
  797. unsigned long flags;
  798. int ret = 0;
  799. timer_stats_timer_clear_start_info(timer);
  800. if (timer_pending(timer)) {
  801. base = lock_timer_base(timer, &flags);
  802. if (timer_pending(timer)) {
  803. detach_timer(timer, 1);
  804. if (timer->expires == base->next_timer &&
  805. !tbase_get_deferrable(timer->base))
  806. base->next_timer = base->timer_jiffies;
  807. ret = 1;
  808. }
  809. spin_unlock_irqrestore(&base->lock, flags);
  810. }
  811. return ret;
  812. }
  813. EXPORT_SYMBOL(del_timer);
  814. /**
  815. * try_to_del_timer_sync - Try to deactivate a timer
  816. * @timer: timer do del
  817. *
  818. * This function tries to deactivate a timer. Upon successful (ret >= 0)
  819. * exit the timer is not queued and the handler is not running on any CPU.
  820. */
  821. int try_to_del_timer_sync(struct timer_list *timer)
  822. {
  823. struct tvec_base *base;
  824. unsigned long flags;
  825. int ret = -1;
  826. base = lock_timer_base(timer, &flags);
  827. if (base->running_timer == timer)
  828. goto out;
  829. timer_stats_timer_clear_start_info(timer);
  830. ret = 0;
  831. if (timer_pending(timer)) {
  832. detach_timer(timer, 1);
  833. if (timer->expires == base->next_timer &&
  834. !tbase_get_deferrable(timer->base))
  835. base->next_timer = base->timer_jiffies;
  836. ret = 1;
  837. }
  838. out:
  839. spin_unlock_irqrestore(&base->lock, flags);
  840. return ret;
  841. }
  842. EXPORT_SYMBOL(try_to_del_timer_sync);
  843. #ifdef CONFIG_SMP
  844. /**
  845. * del_timer_sync - deactivate a timer and wait for the handler to finish.
  846. * @timer: the timer to be deactivated
  847. *
  848. * This function only differs from del_timer() on SMP: besides deactivating
  849. * the timer it also makes sure the handler has finished executing on other
  850. * CPUs.
  851. *
  852. * Synchronization rules: Callers must prevent restarting of the timer,
  853. * otherwise this function is meaningless. It must not be called from
  854. * interrupt contexts. The caller must not hold locks which would prevent
  855. * completion of the timer's handler. The timer's handler must not call
  856. * add_timer_on(). Upon exit the timer is not queued and the handler is
  857. * not running on any CPU.
  858. *
  859. * The function returns whether it has deactivated a pending timer or not.
  860. */
  861. int del_timer_sync(struct timer_list *timer)
  862. {
  863. #ifdef CONFIG_LOCKDEP
  864. unsigned long flags;
  865. local_irq_save(flags);
  866. lock_map_acquire(&timer->lockdep_map);
  867. lock_map_release(&timer->lockdep_map);
  868. local_irq_restore(flags);
  869. #endif
  870. /*
  871. * don't use it in hardirq context, because it
  872. * could lead to deadlock.
  873. */
  874. WARN_ON(in_irq());
  875. for (;;) {
  876. int ret = try_to_del_timer_sync(timer);
  877. if (ret >= 0)
  878. return ret;
  879. cpu_relax();
  880. }
  881. }
  882. EXPORT_SYMBOL(del_timer_sync);
  883. #endif
  884. static int cascade(struct tvec_base *base, struct tvec *tv, int index)
  885. {
  886. /* cascade all the timers from tv up one level */
  887. struct timer_list *timer, *tmp;
  888. struct list_head tv_list;
  889. list_replace_init(tv->vec + index, &tv_list);
  890. /*
  891. * We are removing _all_ timers from the list, so we
  892. * don't have to detach them individually.
  893. */
  894. list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
  895. BUG_ON(tbase_get_base(timer->base) != base);
  896. internal_add_timer(base, timer);
  897. }
  898. return index;
  899. }
  900. static void call_timer_fn(struct timer_list *timer, void (*fn)(unsigned long),
  901. unsigned long data)
  902. {
  903. int preempt_count = preempt_count();
  904. #ifdef CONFIG_LOCKDEP
  905. /*
  906. * It is permissible to free the timer from inside the
  907. * function that is called from it, this we need to take into
  908. * account for lockdep too. To avoid bogus "held lock freed"
  909. * warnings as well as problems when looking into
  910. * timer->lockdep_map, make a copy and use that here.
  911. */
  912. struct lockdep_map lockdep_map = timer->lockdep_map;
  913. #endif
  914. /*
  915. * Couple the lock chain with the lock chain at
  916. * del_timer_sync() by acquiring the lock_map around the fn()
  917. * call here and in del_timer_sync().
  918. */
  919. lock_map_acquire(&lockdep_map);
  920. trace_timer_expire_entry(timer);
  921. fn(data);
  922. trace_timer_expire_exit(timer);
  923. lock_map_release(&lockdep_map);
  924. if (preempt_count != preempt_count()) {
  925. WARN_ONCE(1, "timer: %pF preempt leak: %08x -> %08x\n",
  926. fn, preempt_count, preempt_count());
  927. /*
  928. * Restore the preempt count. That gives us a decent
  929. * chance to survive and extract information. If the
  930. * callback kept a lock held, bad luck, but not worse
  931. * than the BUG() we had.
  932. */
  933. preempt_count() = preempt_count;
  934. }
  935. }
  936. #define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
  937. /**
  938. * __run_timers - run all expired timers (if any) on this CPU.
  939. * @base: the timer vector to be processed.
  940. *
  941. * This function cascades all vectors and executes all expired timer
  942. * vectors.
  943. */
  944. static inline void __run_timers(struct tvec_base *base)
  945. {
  946. struct timer_list *timer;
  947. spin_lock_irq(&base->lock);
  948. while (time_after_eq(jiffies, base->timer_jiffies)) {
  949. struct list_head work_list;
  950. struct list_head *head = &work_list;
  951. int index = base->timer_jiffies & TVR_MASK;
  952. /*
  953. * Cascade timers:
  954. */
  955. if (!index &&
  956. (!cascade(base, &base->tv2, INDEX(0))) &&
  957. (!cascade(base, &base->tv3, INDEX(1))) &&
  958. !cascade(base, &base->tv4, INDEX(2)))
  959. cascade(base, &base->tv5, INDEX(3));
  960. ++base->timer_jiffies;
  961. list_replace_init(base->tv1.vec + index, &work_list);
  962. while (!list_empty(head)) {
  963. void (*fn)(unsigned long);
  964. unsigned long data;
  965. timer = list_first_entry(head, struct timer_list,entry);
  966. fn = timer->function;
  967. data = timer->data;
  968. timer_stats_account_timer(timer);
  969. base->running_timer = timer;
  970. detach_timer(timer, 1);
  971. spin_unlock_irq(&base->lock);
  972. call_timer_fn(timer, fn, data);
  973. spin_lock_irq(&base->lock);
  974. }
  975. }
  976. base->running_timer = NULL;
  977. spin_unlock_irq(&base->lock);
  978. }
  979. #ifdef CONFIG_NO_HZ
  980. /*
  981. * Find out when the next timer event is due to happen. This
  982. * is used on S/390 to stop all activity when a CPU is idle.
  983. * This function needs to be called with interrupts disabled.
  984. */
  985. static unsigned long __next_timer_interrupt(struct tvec_base *base)
  986. {
  987. unsigned long timer_jiffies = base->timer_jiffies;
  988. unsigned long expires = timer_jiffies + NEXT_TIMER_MAX_DELTA;
  989. int index, slot, array, found = 0;
  990. struct timer_list *nte;
  991. struct tvec *varray[4];
  992. /* Look for timer events in tv1. */
  993. index = slot = timer_jiffies & TVR_MASK;
  994. do {
  995. list_for_each_entry(nte, base->tv1.vec + slot, entry) {
  996. if (tbase_get_deferrable(nte->base))
  997. continue;
  998. found = 1;
  999. expires = nte->expires;
  1000. /* Look at the cascade bucket(s)? */
  1001. if (!index || slot < index)
  1002. goto cascade;
  1003. return expires;
  1004. }
  1005. slot = (slot + 1) & TVR_MASK;
  1006. } while (slot != index);
  1007. cascade:
  1008. /* Calculate the next cascade event */
  1009. if (index)
  1010. timer_jiffies += TVR_SIZE - index;
  1011. timer_jiffies >>= TVR_BITS;
  1012. /* Check tv2-tv5. */
  1013. varray[0] = &base->tv2;
  1014. varray[1] = &base->tv3;
  1015. varray[2] = &base->tv4;
  1016. varray[3] = &base->tv5;
  1017. for (array = 0; array < 4; array++) {
  1018. struct tvec *varp = varray[array];
  1019. index = slot = timer_jiffies & TVN_MASK;
  1020. do {
  1021. list_for_each_entry(nte, varp->vec + slot, entry) {
  1022. if (tbase_get_deferrable(nte->base))
  1023. continue;
  1024. found = 1;
  1025. if (time_before(nte->expires, expires))
  1026. expires = nte->expires;
  1027. }
  1028. /*
  1029. * Do we still search for the first timer or are
  1030. * we looking up the cascade buckets ?
  1031. */
  1032. if (found) {
  1033. /* Look at the cascade bucket(s)? */
  1034. if (!index || slot < index)
  1035. break;
  1036. return expires;
  1037. }
  1038. slot = (slot + 1) & TVN_MASK;
  1039. } while (slot != index);
  1040. if (index)
  1041. timer_jiffies += TVN_SIZE - index;
  1042. timer_jiffies >>= TVN_BITS;
  1043. }
  1044. return expires;
  1045. }
  1046. /*
  1047. * Check, if the next hrtimer event is before the next timer wheel
  1048. * event:
  1049. */
  1050. static unsigned long cmp_next_hrtimer_event(unsigned long now,
  1051. unsigned long expires)
  1052. {
  1053. ktime_t hr_delta = hrtimer_get_next_event();
  1054. struct timespec tsdelta;
  1055. unsigned long delta;
  1056. if (hr_delta.tv64 == KTIME_MAX)
  1057. return expires;
  1058. /*
  1059. * Expired timer available, let it expire in the next tick
  1060. */
  1061. if (hr_delta.tv64 <= 0)
  1062. return now + 1;
  1063. tsdelta = ktime_to_timespec(hr_delta);
  1064. delta = timespec_to_jiffies(&tsdelta);
  1065. /*
  1066. * Limit the delta to the max value, which is checked in
  1067. * tick_nohz_stop_sched_tick():
  1068. */
  1069. if (delta > NEXT_TIMER_MAX_DELTA)
  1070. delta = NEXT_TIMER_MAX_DELTA;
  1071. /*
  1072. * Take rounding errors in to account and make sure, that it
  1073. * expires in the next tick. Otherwise we go into an endless
  1074. * ping pong due to tick_nohz_stop_sched_tick() retriggering
  1075. * the timer softirq
  1076. */
  1077. if (delta < 1)
  1078. delta = 1;
  1079. now += delta;
  1080. if (time_before(now, expires))
  1081. return now;
  1082. return expires;
  1083. }
  1084. /**
  1085. * get_next_timer_interrupt - return the jiffy of the next pending timer
  1086. * @now: current time (in jiffies)
  1087. */
  1088. unsigned long get_next_timer_interrupt(unsigned long now)
  1089. {
  1090. struct tvec_base *base = __this_cpu_read(tvec_bases);
  1091. unsigned long expires;
  1092. /*
  1093. * Pretend that there is no timer pending if the cpu is offline.
  1094. * Possible pending timers will be migrated later to an active cpu.
  1095. */
  1096. if (cpu_is_offline(smp_processor_id()))
  1097. return now + NEXT_TIMER_MAX_DELTA;
  1098. spin_lock(&base->lock);
  1099. if (time_before_eq(base->next_timer, base->timer_jiffies))
  1100. base->next_timer = __next_timer_interrupt(base);
  1101. expires = base->next_timer;
  1102. spin_unlock(&base->lock);
  1103. if (time_before_eq(expires, now))
  1104. return now;
  1105. return cmp_next_hrtimer_event(now, expires);
  1106. }
  1107. #endif
  1108. /*
  1109. * Called from the timer interrupt handler to charge one tick to the current
  1110. * process. user_tick is 1 if the tick is user time, 0 for system.
  1111. */
  1112. void update_process_times(int user_tick)
  1113. {
  1114. struct task_struct *p = current;
  1115. int cpu = smp_processor_id();
  1116. /* Note: this timer irq context must be accounted for as well. */
  1117. account_process_tick(p, user_tick);
  1118. run_local_timers();
  1119. rcu_check_callbacks(cpu, user_tick);
  1120. printk_tick();
  1121. #ifdef CONFIG_IRQ_WORK
  1122. if (in_irq())
  1123. irq_work_run();
  1124. #endif
  1125. scheduler_tick();
  1126. run_posix_cpu_timers(p);
  1127. }
  1128. /*
  1129. * This function runs timers and the timer-tq in bottom half context.
  1130. */
  1131. static void run_timer_softirq(struct softirq_action *h)
  1132. {
  1133. struct tvec_base *base = __this_cpu_read(tvec_bases);
  1134. hrtimer_run_pending();
  1135. if (time_after_eq(jiffies, base->timer_jiffies))
  1136. __run_timers(base);
  1137. }
  1138. /*
  1139. * Called by the local, per-CPU timer interrupt on SMP.
  1140. */
  1141. void run_local_timers(void)
  1142. {
  1143. hrtimer_run_queues();
  1144. raise_softirq(TIMER_SOFTIRQ);
  1145. }
  1146. /*
  1147. * The 64-bit jiffies value is not atomic - you MUST NOT read it
  1148. * without sampling the sequence number in xtime_lock.
  1149. * jiffies is defined in the linker script...
  1150. */
  1151. void do_timer(unsigned long ticks)
  1152. {
  1153. jiffies_64 += ticks;
  1154. update_wall_time();
  1155. calc_global_load(ticks);
  1156. }
  1157. #ifdef __ARCH_WANT_SYS_ALARM
  1158. /*
  1159. * For backwards compatibility? This can be done in libc so Alpha
  1160. * and all newer ports shouldn't need it.
  1161. */
  1162. SYSCALL_DEFINE1(alarm, unsigned int, seconds)
  1163. {
  1164. return alarm_setitimer(seconds);
  1165. }
  1166. #endif
  1167. #ifndef __alpha__
  1168. /*
  1169. * The Alpha uses getxpid, getxuid, and getxgid instead. Maybe this
  1170. * should be moved into arch/i386 instead?
  1171. */
  1172. /**
  1173. * sys_getpid - return the thread group id of the current process
  1174. *
  1175. * Note, despite the name, this returns the tgid not the pid. The tgid and
  1176. * the pid are identical unless CLONE_THREAD was specified on clone() in
  1177. * which case the tgid is the same in all threads of the same group.
  1178. *
  1179. * This is SMP safe as current->tgid does not change.
  1180. */
  1181. SYSCALL_DEFINE0(getpid)
  1182. {
  1183. return task_tgid_vnr(current);
  1184. }
  1185. /*
  1186. * Accessing ->real_parent is not SMP-safe, it could
  1187. * change from under us. However, we can use a stale
  1188. * value of ->real_parent under rcu_read_lock(), see
  1189. * release_task()->call_rcu(delayed_put_task_struct).
  1190. */
  1191. SYSCALL_DEFINE0(getppid)
  1192. {
  1193. int pid;
  1194. rcu_read_lock();
  1195. pid = task_tgid_vnr(current->real_parent);
  1196. rcu_read_unlock();
  1197. return pid;
  1198. }
  1199. SYSCALL_DEFINE0(getuid)
  1200. {
  1201. /* Only we change this so SMP safe */
  1202. return current_uid();
  1203. }
  1204. SYSCALL_DEFINE0(geteuid)
  1205. {
  1206. /* Only we change this so SMP safe */
  1207. return current_euid();
  1208. }
  1209. SYSCALL_DEFINE0(getgid)
  1210. {
  1211. /* Only we change this so SMP safe */
  1212. return current_gid();
  1213. }
  1214. SYSCALL_DEFINE0(getegid)
  1215. {
  1216. /* Only we change this so SMP safe */
  1217. return current_egid();
  1218. }
  1219. #endif
  1220. static void process_timeout(unsigned long __data)
  1221. {
  1222. wake_up_process((struct task_struct *)__data);
  1223. }
  1224. /**
  1225. * schedule_timeout - sleep until timeout
  1226. * @timeout: timeout value in jiffies
  1227. *
  1228. * Make the current task sleep until @timeout jiffies have
  1229. * elapsed. The routine will return immediately unless
  1230. * the current task state has been set (see set_current_state()).
  1231. *
  1232. * You can set the task state as follows -
  1233. *
  1234. * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
  1235. * pass before the routine returns. The routine will return 0
  1236. *
  1237. * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
  1238. * delivered to the current task. In this case the remaining time
  1239. * in jiffies will be returned, or 0 if the timer expired in time
  1240. *
  1241. * The current task state is guaranteed to be TASK_RUNNING when this
  1242. * routine returns.
  1243. *
  1244. * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
  1245. * the CPU away without a bound on the timeout. In this case the return
  1246. * value will be %MAX_SCHEDULE_TIMEOUT.
  1247. *
  1248. * In all cases the return value is guaranteed to be non-negative.
  1249. */
  1250. signed long __sched schedule_timeout(signed long timeout)
  1251. {
  1252. struct timer_list timer;
  1253. unsigned long expire;
  1254. switch (timeout)
  1255. {
  1256. case MAX_SCHEDULE_TIMEOUT:
  1257. /*
  1258. * These two special cases are useful to be comfortable
  1259. * in the caller. Nothing more. We could take
  1260. * MAX_SCHEDULE_TIMEOUT from one of the negative value
  1261. * but I' d like to return a valid offset (>=0) to allow
  1262. * the caller to do everything it want with the retval.
  1263. */
  1264. schedule();
  1265. goto out;
  1266. default:
  1267. /*
  1268. * Another bit of PARANOID. Note that the retval will be
  1269. * 0 since no piece of kernel is supposed to do a check
  1270. * for a negative retval of schedule_timeout() (since it
  1271. * should never happens anyway). You just have the printk()
  1272. * that will tell you if something is gone wrong and where.
  1273. */
  1274. if (timeout < 0) {
  1275. printk(KERN_ERR "schedule_timeout: wrong timeout "
  1276. "value %lx\n", timeout);
  1277. dump_stack();
  1278. current->state = TASK_RUNNING;
  1279. goto out;
  1280. }
  1281. }
  1282. expire = timeout + jiffies;
  1283. setup_timer_on_stack(&timer, process_timeout, (unsigned long)current);
  1284. __mod_timer(&timer, expire, false, TIMER_NOT_PINNED);
  1285. schedule();
  1286. del_singleshot_timer_sync(&timer);
  1287. /* Remove the timer from the object tracker */
  1288. destroy_timer_on_stack(&timer);
  1289. timeout = expire - jiffies;
  1290. out:
  1291. return timeout < 0 ? 0 : timeout;
  1292. }
  1293. EXPORT_SYMBOL(schedule_timeout);
  1294. /*
  1295. * We can use __set_current_state() here because schedule_timeout() calls
  1296. * schedule() unconditionally.
  1297. */
  1298. signed long __sched schedule_timeout_interruptible(signed long timeout)
  1299. {
  1300. __set_current_state(TASK_INTERRUPTIBLE);
  1301. return schedule_timeout(timeout);
  1302. }
  1303. EXPORT_SYMBOL(schedule_timeout_interruptible);
  1304. signed long __sched schedule_timeout_killable(signed long timeout)
  1305. {
  1306. __set_current_state(TASK_KILLABLE);
  1307. return schedule_timeout(timeout);
  1308. }
  1309. EXPORT_SYMBOL(schedule_timeout_killable);
  1310. signed long __sched schedule_timeout_uninterruptible(signed long timeout)
  1311. {
  1312. __set_current_state(TASK_UNINTERRUPTIBLE);
  1313. return schedule_timeout(timeout);
  1314. }
  1315. EXPORT_SYMBOL(schedule_timeout_uninterruptible);
  1316. /* Thread ID - the internal kernel "pid" */
  1317. SYSCALL_DEFINE0(gettid)
  1318. {
  1319. return task_pid_vnr(current);
  1320. }
  1321. /**
  1322. * do_sysinfo - fill in sysinfo struct
  1323. * @info: pointer to buffer to fill
  1324. */
  1325. int do_sysinfo(struct sysinfo *info)
  1326. {
  1327. unsigned long mem_total, sav_total;
  1328. unsigned int mem_unit, bitcount;
  1329. struct timespec tp;
  1330. memset(info, 0, sizeof(struct sysinfo));
  1331. ktime_get_ts(&tp);
  1332. monotonic_to_bootbased(&tp);
  1333. info->uptime = tp.tv_sec + (tp.tv_nsec ? 1 : 0);
  1334. get_avenrun(info->loads, 0, SI_LOAD_SHIFT - FSHIFT);
  1335. info->procs = nr_threads;
  1336. si_meminfo(info);
  1337. si_swapinfo(info);
  1338. /*
  1339. * If the sum of all the available memory (i.e. ram + swap)
  1340. * is less than can be stored in a 32 bit unsigned long then
  1341. * we can be binary compatible with 2.2.x kernels. If not,
  1342. * well, in that case 2.2.x was broken anyways...
  1343. *
  1344. * -Erik Andersen <andersee@debian.org>
  1345. */
  1346. mem_total = info->totalram + info->totalswap;
  1347. if (mem_total < info->totalram || mem_total < info->totalswap)
  1348. goto out;
  1349. bitcount = 0;
  1350. mem_unit = info->mem_unit;
  1351. while (mem_unit > 1) {
  1352. bitcount++;
  1353. mem_unit >>= 1;
  1354. sav_total = mem_total;
  1355. mem_total <<= 1;
  1356. if (mem_total < sav_total)
  1357. goto out;
  1358. }
  1359. /*
  1360. * If mem_total did not overflow, multiply all memory values by
  1361. * info->mem_unit and set it to 1. This leaves things compatible
  1362. * with 2.2.x, and also retains compatibility with earlier 2.4.x
  1363. * kernels...
  1364. */
  1365. info->mem_unit = 1;
  1366. info->totalram <<= bitcount;
  1367. info->freeram <<= bitcount;
  1368. info->sharedram <<= bitcount;
  1369. info->bufferram <<= bitcount;
  1370. info->totalswap <<= bitcount;
  1371. info->freeswap <<= bitcount;
  1372. info->totalhigh <<= bitcount;
  1373. info->freehigh <<= bitcount;
  1374. out:
  1375. return 0;
  1376. }
  1377. SYSCALL_DEFINE1(sysinfo, struct sysinfo __user *, info)
  1378. {
  1379. struct sysinfo val;
  1380. do_sysinfo(&val);
  1381. if (copy_to_user(info, &val, sizeof(struct sysinfo)))
  1382. return -EFAULT;
  1383. return 0;
  1384. }
  1385. static int __cpuinit init_timers_cpu(int cpu)
  1386. {
  1387. int j;
  1388. struct tvec_base *base;
  1389. static char __cpuinitdata tvec_base_done[NR_CPUS];
  1390. if (!tvec_base_done[cpu]) {
  1391. static char boot_done;
  1392. if (boot_done) {
  1393. /*
  1394. * The APs use this path later in boot
  1395. */
  1396. base = kmalloc_node(sizeof(*base),
  1397. GFP_KERNEL | __GFP_ZERO,
  1398. cpu_to_node(cpu));
  1399. if (!base)
  1400. return -ENOMEM;
  1401. /* Make sure that tvec_base is 2 byte aligned */
  1402. if (tbase_get_deferrable(base)) {
  1403. WARN_ON(1);
  1404. kfree(base);
  1405. return -ENOMEM;
  1406. }
  1407. per_cpu(tvec_bases, cpu) = base;
  1408. } else {
  1409. /*
  1410. * This is for the boot CPU - we use compile-time
  1411. * static initialisation because per-cpu memory isn't
  1412. * ready yet and because the memory allocators are not
  1413. * initialised either.
  1414. */
  1415. boot_done = 1;
  1416. base = &boot_tvec_bases;
  1417. }
  1418. tvec_base_done[cpu] = 1;
  1419. } else {
  1420. base = per_cpu(tvec_bases, cpu);
  1421. }
  1422. spin_lock_init(&base->lock);
  1423. for (j = 0; j < TVN_SIZE; j++) {
  1424. INIT_LIST_HEAD(base->tv5.vec + j);
  1425. INIT_LIST_HEAD(base->tv4.vec + j);
  1426. INIT_LIST_HEAD(base->tv3.vec + j);
  1427. INIT_LIST_HEAD(base->tv2.vec + j);
  1428. }
  1429. for (j = 0; j < TVR_SIZE; j++)
  1430. INIT_LIST_HEAD(base->tv1.vec + j);
  1431. base->timer_jiffies = jiffies;
  1432. base->next_timer = base->timer_jiffies;
  1433. return 0;
  1434. }
  1435. #ifdef CONFIG_HOTPLUG_CPU
  1436. static void migrate_timer_list(struct tvec_base *new_base, struct list_head *head)
  1437. {
  1438. struct timer_list *timer;
  1439. while (!list_empty(head)) {
  1440. timer = list_first_entry(head, struct timer_list, entry);
  1441. detach_timer(timer, 0);
  1442. timer_set_base(timer, new_base);
  1443. if (time_before(timer->expires, new_base->next_timer) &&
  1444. !tbase_get_deferrable(timer->base))
  1445. new_base->next_timer = timer->expires;
  1446. internal_add_timer(new_base, timer);
  1447. }
  1448. }
  1449. static void __cpuinit migrate_timers(int cpu)
  1450. {
  1451. struct tvec_base *old_base;
  1452. struct tvec_base *new_base;
  1453. int i;
  1454. BUG_ON(cpu_online(cpu));
  1455. old_base = per_cpu(tvec_bases, cpu);
  1456. new_base = get_cpu_var(tvec_bases);
  1457. /*
  1458. * The caller is globally serialized and nobody else
  1459. * takes two locks at once, deadlock is not possible.
  1460. */
  1461. spin_lock_irq(&new_base->lock);
  1462. spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
  1463. BUG_ON(old_base->running_timer);
  1464. for (i = 0; i < TVR_SIZE; i++)
  1465. migrate_timer_list(new_base, old_base->tv1.vec + i);
  1466. for (i = 0; i < TVN_SIZE; i++) {
  1467. migrate_timer_list(new_base, old_base->tv2.vec + i);
  1468. migrate_timer_list(new_base, old_base->tv3.vec + i);
  1469. migrate_timer_list(new_base, old_base->tv4.vec + i);
  1470. migrate_timer_list(new_base, old_base->tv5.vec + i);
  1471. }
  1472. spin_unlock(&old_base->lock);
  1473. spin_unlock_irq(&new_base->lock);
  1474. put_cpu_var(tvec_bases);
  1475. }
  1476. #endif /* CONFIG_HOTPLUG_CPU */
  1477. static int __cpuinit timer_cpu_notify(struct notifier_block *self,
  1478. unsigned long action, void *hcpu)
  1479. {
  1480. long cpu = (long)hcpu;
  1481. int err;
  1482. switch(action) {
  1483. case CPU_UP_PREPARE:
  1484. case CPU_UP_PREPARE_FROZEN:
  1485. err = init_timers_cpu(cpu);
  1486. if (err < 0)
  1487. return notifier_from_errno(err);
  1488. break;
  1489. #ifdef CONFIG_HOTPLUG_CPU
  1490. case CPU_DEAD:
  1491. case CPU_DEAD_FROZEN:
  1492. migrate_timers(cpu);
  1493. break;
  1494. #endif
  1495. default:
  1496. break;
  1497. }
  1498. return NOTIFY_OK;
  1499. }
  1500. static struct notifier_block __cpuinitdata timers_nb = {
  1501. .notifier_call = timer_cpu_notify,
  1502. };
  1503. void __init init_timers(void)
  1504. {
  1505. int err = timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
  1506. (void *)(long)smp_processor_id());
  1507. init_timer_stats();
  1508. BUG_ON(err != NOTIFY_OK);
  1509. register_cpu_notifier(&timers_nb);
  1510. open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
  1511. }
  1512. /**
  1513. * msleep - sleep safely even with waitqueue interruptions
  1514. * @msecs: Time in milliseconds to sleep for
  1515. */
  1516. void msleep(unsigned int msecs)
  1517. {
  1518. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1519. while (timeout)
  1520. timeout = schedule_timeout_uninterruptible(timeout);
  1521. }
  1522. EXPORT_SYMBOL(msleep);
  1523. /**
  1524. * msleep_interruptible - sleep waiting for signals
  1525. * @msecs: Time in milliseconds to sleep for
  1526. */
  1527. unsigned long msleep_interruptible(unsigned int msecs)
  1528. {
  1529. unsigned long timeout = msecs_to_jiffies(msecs) + 1;
  1530. while (timeout && !signal_pending(current))
  1531. timeout = schedule_timeout_interruptible(timeout);
  1532. return jiffies_to_msecs(timeout);
  1533. }
  1534. EXPORT_SYMBOL(msleep_interruptible);
  1535. static int __sched do_usleep_range(unsigned long min, unsigned long max)
  1536. {
  1537. ktime_t kmin;
  1538. unsigned long delta;
  1539. kmin = ktime_set(0, min * NSEC_PER_USEC);
  1540. delta = (max - min) * NSEC_PER_USEC;
  1541. return schedule_hrtimeout_range(&kmin, delta, HRTIMER_MODE_REL);
  1542. }
  1543. /**
  1544. * usleep_range - Drop in replacement for udelay where wakeup is flexible
  1545. * @min: Minimum time in usecs to sleep
  1546. * @max: Maximum time in usecs to sleep
  1547. */
  1548. void usleep_range(unsigned long min, unsigned long max)
  1549. {
  1550. __set_current_state(TASK_UNINTERRUPTIBLE);
  1551. do_usleep_range(min, max);
  1552. }
  1553. EXPORT_SYMBOL(usleep_range);