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