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