OSDN Git Service

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