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