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