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