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