rds: prevent dereference of a NULL device in rds_iw_laddr_check
[pandora-kernel.git] / kernel / hrtimer.c
1 /*
2  *  linux/kernel/hrtimer.c
3  *
4  *  Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
6  *  Copyright(C) 2006-2007  Timesys Corp., Thomas Gleixner
7  *
8  *  High-resolution kernel timers
9  *
10  *  In contrast to the low-resolution timeout API implemented in
11  *  kernel/timer.c, hrtimers provide finer resolution and accuracy
12  *  depending on system configuration and capabilities.
13  *
14  *  These timers are currently used for:
15  *   - itimers
16  *   - POSIX timers
17  *   - nanosleep
18  *   - precise in-kernel timing
19  *
20  *  Started by: Thomas Gleixner and Ingo Molnar
21  *
22  *  Credits:
23  *      based on kernel/timer.c
24  *
25  *      Help, testing, suggestions, bugfixes, improvements were
26  *      provided by:
27  *
28  *      George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
29  *      et. al.
30  *
31  *  For licencing details see kernel-base/COPYING
32  */
33
34 #include <linux/cpu.h>
35 #include <linux/export.h>
36 #include <linux/percpu.h>
37 #include <linux/hrtimer.h>
38 #include <linux/notifier.h>
39 #include <linux/syscalls.h>
40 #include <linux/kallsyms.h>
41 #include <linux/interrupt.h>
42 #include <linux/tick.h>
43 #include <linux/seq_file.h>
44 #include <linux/err.h>
45 #include <linux/debugobjects.h>
46 #include <linux/sched.h>
47 #include <linux/timer.h>
48
49 #include <asm/uaccess.h>
50
51 #include <trace/events/timer.h>
52
53 /*
54  * The timer bases:
55  *
56  * There are more clockids then hrtimer bases. Thus, we index
57  * into the timer bases by the hrtimer_base_type enum. When trying
58  * to reach a base using a clockid, hrtimer_clockid_to_base()
59  * is used to convert from clockid to the proper hrtimer_base_type.
60  */
61 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
62 {
63
64         .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
65         .clock_base =
66         {
67                 {
68                         .index = HRTIMER_BASE_MONOTONIC,
69                         .clockid = CLOCK_MONOTONIC,
70                         .get_time = &ktime_get,
71                         .resolution = KTIME_LOW_RES,
72                 },
73                 {
74                         .index = HRTIMER_BASE_REALTIME,
75                         .clockid = CLOCK_REALTIME,
76                         .get_time = &ktime_get_real,
77                         .resolution = KTIME_LOW_RES,
78                 },
79                 {
80                         .index = HRTIMER_BASE_BOOTTIME,
81                         .clockid = CLOCK_BOOTTIME,
82                         .get_time = &ktime_get_boottime,
83                         .resolution = KTIME_LOW_RES,
84                 },
85         }
86 };
87
88 static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
89         [CLOCK_REALTIME]        = HRTIMER_BASE_REALTIME,
90         [CLOCK_MONOTONIC]       = HRTIMER_BASE_MONOTONIC,
91         [CLOCK_BOOTTIME]        = HRTIMER_BASE_BOOTTIME,
92 };
93
94 static inline int hrtimer_clockid_to_base(clockid_t clock_id)
95 {
96         return hrtimer_clock_to_base_table[clock_id];
97 }
98
99
100 /*
101  * Get the coarse grained time at the softirq based on xtime and
102  * wall_to_monotonic.
103  */
104 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
105 {
106         ktime_t xtim, mono, boot;
107         struct timespec xts, tom, slp;
108
109         get_xtime_and_monotonic_and_sleep_offset(&xts, &tom, &slp);
110
111         xtim = timespec_to_ktime(xts);
112         mono = ktime_add(xtim, timespec_to_ktime(tom));
113         boot = ktime_add(mono, timespec_to_ktime(slp));
114         base->clock_base[HRTIMER_BASE_REALTIME].softirq_time = xtim;
115         base->clock_base[HRTIMER_BASE_MONOTONIC].softirq_time = mono;
116         base->clock_base[HRTIMER_BASE_BOOTTIME].softirq_time = boot;
117 }
118
119 /*
120  * Functions and macros which are different for UP/SMP systems are kept in a
121  * single place
122  */
123 #ifdef CONFIG_SMP
124
125 /*
126  * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
127  * means that all timers which are tied to this base via timer->base are
128  * locked, and the base itself is locked too.
129  *
130  * So __run_timers/migrate_timers can safely modify all timers which could
131  * be found on the lists/queues.
132  *
133  * When the timer's base is locked, and the timer removed from list, it is
134  * possible to set timer->base = NULL and drop the lock: the timer remains
135  * locked.
136  */
137 static
138 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
139                                              unsigned long *flags)
140 {
141         struct hrtimer_clock_base *base;
142
143         for (;;) {
144                 base = timer->base;
145                 if (likely(base != NULL)) {
146                         raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
147                         if (likely(base == timer->base))
148                                 return base;
149                         /* The timer has migrated to another CPU: */
150                         raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
151                 }
152                 cpu_relax();
153         }
154 }
155
156
157 /*
158  * Get the preferred target CPU for NOHZ
159  */
160 static int hrtimer_get_target(int this_cpu, int pinned)
161 {
162 #ifdef CONFIG_NO_HZ
163         if (!pinned && get_sysctl_timer_migration() && idle_cpu(this_cpu))
164                 return get_nohz_timer_target();
165 #endif
166         return this_cpu;
167 }
168
169 /*
170  * With HIGHRES=y we do not migrate the timer when it is expiring
171  * before the next event on the target cpu because we cannot reprogram
172  * the target cpu hardware and we would cause it to fire late.
173  *
174  * Called with cpu_base->lock of target cpu held.
175  */
176 static int
177 hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
178 {
179 #ifdef CONFIG_HIGH_RES_TIMERS
180         ktime_t expires;
181
182         if (!new_base->cpu_base->hres_active)
183                 return 0;
184
185         expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
186         return expires.tv64 <= new_base->cpu_base->expires_next.tv64;
187 #else
188         return 0;
189 #endif
190 }
191
192 /*
193  * Switch the timer base to the current CPU when possible.
194  */
195 static inline struct hrtimer_clock_base *
196 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
197                     int pinned)
198 {
199         struct hrtimer_clock_base *new_base;
200         struct hrtimer_cpu_base *new_cpu_base;
201         int this_cpu = smp_processor_id();
202         int cpu = hrtimer_get_target(this_cpu, pinned);
203         int basenum = base->index;
204
205 again:
206         new_cpu_base = &per_cpu(hrtimer_bases, cpu);
207         new_base = &new_cpu_base->clock_base[basenum];
208
209         if (base != new_base) {
210                 /*
211                  * We are trying to move timer to new_base.
212                  * However we can't change timer's base while it is running,
213                  * so we keep it on the same CPU. No hassle vs. reprogramming
214                  * the event source in the high resolution case. The softirq
215                  * code will take care of this when the timer function has
216                  * completed. There is no conflict as we hold the lock until
217                  * the timer is enqueued.
218                  */
219                 if (unlikely(hrtimer_callback_running(timer)))
220                         return base;
221
222                 /* See the comment in lock_timer_base() */
223                 timer->base = NULL;
224                 raw_spin_unlock(&base->cpu_base->lock);
225                 raw_spin_lock(&new_base->cpu_base->lock);
226
227                 if (cpu != this_cpu && hrtimer_check_target(timer, new_base)) {
228                         cpu = this_cpu;
229                         raw_spin_unlock(&new_base->cpu_base->lock);
230                         raw_spin_lock(&base->cpu_base->lock);
231                         timer->base = base;
232                         goto again;
233                 }
234                 timer->base = new_base;
235         }
236         return new_base;
237 }
238
239 #else /* CONFIG_SMP */
240
241 static inline struct hrtimer_clock_base *
242 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
243 {
244         struct hrtimer_clock_base *base = timer->base;
245
246         raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
247
248         return base;
249 }
250
251 # define switch_hrtimer_base(t, b, p)   (b)
252
253 #endif  /* !CONFIG_SMP */
254
255 /*
256  * Functions for the union type storage format of ktime_t which are
257  * too large for inlining:
258  */
259 #if BITS_PER_LONG < 64
260 # ifndef CONFIG_KTIME_SCALAR
261 /**
262  * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
263  * @kt:         addend
264  * @nsec:       the scalar nsec value to add
265  *
266  * Returns the sum of kt and nsec in ktime_t format
267  */
268 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
269 {
270         ktime_t tmp;
271
272         if (likely(nsec < NSEC_PER_SEC)) {
273                 tmp.tv64 = nsec;
274         } else {
275                 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
276
277                 tmp = ktime_set((long)nsec, rem);
278         }
279
280         return ktime_add(kt, tmp);
281 }
282
283 EXPORT_SYMBOL_GPL(ktime_add_ns);
284
285 /**
286  * ktime_sub_ns - Subtract a scalar nanoseconds value from a ktime_t variable
287  * @kt:         minuend
288  * @nsec:       the scalar nsec value to subtract
289  *
290  * Returns the subtraction of @nsec from @kt in ktime_t format
291  */
292 ktime_t ktime_sub_ns(const ktime_t kt, u64 nsec)
293 {
294         ktime_t tmp;
295
296         if (likely(nsec < NSEC_PER_SEC)) {
297                 tmp.tv64 = nsec;
298         } else {
299                 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
300
301                 /* Make sure nsec fits into long */
302                 if (unlikely(nsec > KTIME_SEC_MAX))
303                         return (ktime_t){ .tv64 = KTIME_MAX };
304
305                 tmp = ktime_set((long)nsec, rem);
306         }
307
308         return ktime_sub(kt, tmp);
309 }
310
311 EXPORT_SYMBOL_GPL(ktime_sub_ns);
312 # endif /* !CONFIG_KTIME_SCALAR */
313
314 /*
315  * Divide a ktime value by a nanosecond value
316  */
317 u64 ktime_divns(const ktime_t kt, s64 div)
318 {
319         u64 dclc;
320         int sft = 0;
321
322         dclc = ktime_to_ns(kt);
323         /* Make sure the divisor is less than 2^32: */
324         while (div >> 32) {
325                 sft++;
326                 div >>= 1;
327         }
328         dclc >>= sft;
329         do_div(dclc, (unsigned long) div);
330
331         return dclc;
332 }
333 #endif /* BITS_PER_LONG >= 64 */
334
335 /*
336  * Add two ktime values and do a safety check for overflow:
337  */
338 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
339 {
340         ktime_t res = ktime_add(lhs, rhs);
341
342         /*
343          * We use KTIME_SEC_MAX here, the maximum timeout which we can
344          * return to user space in a timespec:
345          */
346         if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
347                 res = ktime_set(KTIME_SEC_MAX, 0);
348
349         return res;
350 }
351
352 EXPORT_SYMBOL_GPL(ktime_add_safe);
353
354 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
355
356 static struct debug_obj_descr hrtimer_debug_descr;
357
358 static void *hrtimer_debug_hint(void *addr)
359 {
360         return ((struct hrtimer *) addr)->function;
361 }
362
363 /*
364  * fixup_init is called when:
365  * - an active object is initialized
366  */
367 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
368 {
369         struct hrtimer *timer = addr;
370
371         switch (state) {
372         case ODEBUG_STATE_ACTIVE:
373                 hrtimer_cancel(timer);
374                 debug_object_init(timer, &hrtimer_debug_descr);
375                 return 1;
376         default:
377                 return 0;
378         }
379 }
380
381 /*
382  * fixup_activate is called when:
383  * - an active object is activated
384  * - an unknown object is activated (might be a statically initialized object)
385  */
386 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
387 {
388         switch (state) {
389
390         case ODEBUG_STATE_NOTAVAILABLE:
391                 WARN_ON_ONCE(1);
392                 return 0;
393
394         case ODEBUG_STATE_ACTIVE:
395                 WARN_ON(1);
396
397         default:
398                 return 0;
399         }
400 }
401
402 /*
403  * fixup_free is called when:
404  * - an active object is freed
405  */
406 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
407 {
408         struct hrtimer *timer = addr;
409
410         switch (state) {
411         case ODEBUG_STATE_ACTIVE:
412                 hrtimer_cancel(timer);
413                 debug_object_free(timer, &hrtimer_debug_descr);
414                 return 1;
415         default:
416                 return 0;
417         }
418 }
419
420 static struct debug_obj_descr hrtimer_debug_descr = {
421         .name           = "hrtimer",
422         .debug_hint     = hrtimer_debug_hint,
423         .fixup_init     = hrtimer_fixup_init,
424         .fixup_activate = hrtimer_fixup_activate,
425         .fixup_free     = hrtimer_fixup_free,
426 };
427
428 static inline void debug_hrtimer_init(struct hrtimer *timer)
429 {
430         debug_object_init(timer, &hrtimer_debug_descr);
431 }
432
433 static inline void debug_hrtimer_activate(struct hrtimer *timer)
434 {
435         debug_object_activate(timer, &hrtimer_debug_descr);
436 }
437
438 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
439 {
440         debug_object_deactivate(timer, &hrtimer_debug_descr);
441 }
442
443 static inline void debug_hrtimer_free(struct hrtimer *timer)
444 {
445         debug_object_free(timer, &hrtimer_debug_descr);
446 }
447
448 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
449                            enum hrtimer_mode mode);
450
451 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
452                            enum hrtimer_mode mode)
453 {
454         debug_object_init_on_stack(timer, &hrtimer_debug_descr);
455         __hrtimer_init(timer, clock_id, mode);
456 }
457 EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
458
459 void destroy_hrtimer_on_stack(struct hrtimer *timer)
460 {
461         debug_object_free(timer, &hrtimer_debug_descr);
462 }
463
464 #else
465 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
466 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
467 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
468 #endif
469
470 static inline void
471 debug_init(struct hrtimer *timer, clockid_t clockid,
472            enum hrtimer_mode mode)
473 {
474         debug_hrtimer_init(timer);
475         trace_hrtimer_init(timer, clockid, mode);
476 }
477
478 static inline void debug_activate(struct hrtimer *timer)
479 {
480         debug_hrtimer_activate(timer);
481         trace_hrtimer_start(timer);
482 }
483
484 static inline void debug_deactivate(struct hrtimer *timer)
485 {
486         debug_hrtimer_deactivate(timer);
487         trace_hrtimer_cancel(timer);
488 }
489
490 /* High resolution timer related functions */
491 #ifdef CONFIG_HIGH_RES_TIMERS
492
493 /*
494  * High resolution timer enabled ?
495  */
496 static int hrtimer_hres_enabled __read_mostly  = 1;
497
498 /*
499  * Enable / Disable high resolution mode
500  */
501 static int __init setup_hrtimer_hres(char *str)
502 {
503         if (!strcmp(str, "off"))
504                 hrtimer_hres_enabled = 0;
505         else if (!strcmp(str, "on"))
506                 hrtimer_hres_enabled = 1;
507         else
508                 return 0;
509         return 1;
510 }
511
512 __setup("highres=", setup_hrtimer_hres);
513
514 /*
515  * hrtimer_high_res_enabled - query, if the highres mode is enabled
516  */
517 static inline int hrtimer_is_hres_enabled(void)
518 {
519         return hrtimer_hres_enabled;
520 }
521
522 /*
523  * Is the high resolution mode active ?
524  */
525 static inline int hrtimer_hres_active(void)
526 {
527         return __this_cpu_read(hrtimer_bases.hres_active);
528 }
529
530 /*
531  * Reprogram the event source with checking both queues for the
532  * next event
533  * Called with interrupts disabled and base->lock held
534  */
535 static void
536 hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
537 {
538         int i;
539         struct hrtimer_clock_base *base = cpu_base->clock_base;
540         ktime_t expires, expires_next;
541
542         expires_next.tv64 = KTIME_MAX;
543
544         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
545                 struct hrtimer *timer;
546                 struct timerqueue_node *next;
547
548                 next = timerqueue_getnext(&base->active);
549                 if (!next)
550                         continue;
551                 timer = container_of(next, struct hrtimer, node);
552
553                 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
554                 /*
555                  * clock_was_set() has changed base->offset so the
556                  * result might be negative. Fix it up to prevent a
557                  * false positive in clockevents_program_event()
558                  */
559                 if (expires.tv64 < 0)
560                         expires.tv64 = 0;
561                 if (expires.tv64 < expires_next.tv64)
562                         expires_next = expires;
563         }
564
565         if (skip_equal && expires_next.tv64 == cpu_base->expires_next.tv64)
566                 return;
567
568         cpu_base->expires_next.tv64 = expires_next.tv64;
569
570         if (cpu_base->expires_next.tv64 != KTIME_MAX)
571                 tick_program_event(cpu_base->expires_next, 1);
572 }
573
574 /*
575  * Shared reprogramming for clock_realtime and clock_monotonic
576  *
577  * When a timer is enqueued and expires earlier than the already enqueued
578  * timers, we have to check, whether it expires earlier than the timer for
579  * which the clock event device was armed.
580  *
581  * Called with interrupts disabled and base->cpu_base.lock held
582  */
583 static int hrtimer_reprogram(struct hrtimer *timer,
584                              struct hrtimer_clock_base *base)
585 {
586         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
587         ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
588         int res;
589
590         WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
591
592         /*
593          * When the callback is running, we do not reprogram the clock event
594          * device. The timer callback is either running on a different CPU or
595          * the callback is executed in the hrtimer_interrupt context. The
596          * reprogramming is handled either by the softirq, which called the
597          * callback or at the end of the hrtimer_interrupt.
598          */
599         if (hrtimer_callback_running(timer))
600                 return 0;
601
602         /*
603          * CLOCK_REALTIME timer might be requested with an absolute
604          * expiry time which is less than base->offset. Nothing wrong
605          * about that, just avoid to call into the tick code, which
606          * has now objections against negative expiry values.
607          */
608         if (expires.tv64 < 0)
609                 return -ETIME;
610
611         if (expires.tv64 >= cpu_base->expires_next.tv64)
612                 return 0;
613
614         /*
615          * If a hang was detected in the last timer interrupt then we
616          * do not schedule a timer which is earlier than the expiry
617          * which we enforced in the hang detection. We want the system
618          * to make progress.
619          */
620         if (cpu_base->hang_detected)
621                 return 0;
622
623         /*
624          * Clockevents returns -ETIME, when the event was in the past.
625          */
626         res = tick_program_event(expires, 0);
627         if (!IS_ERR_VALUE(res))
628                 cpu_base->expires_next = expires;
629         return res;
630 }
631
632 /*
633  * Initialize the high resolution related parts of cpu_base
634  */
635 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
636 {
637         base->expires_next.tv64 = KTIME_MAX;
638         base->hres_active = 0;
639 }
640
641 /*
642  * When High resolution timers are active, try to reprogram. Note, that in case
643  * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
644  * check happens. The timer gets enqueued into the rbtree. The reprogramming
645  * and expiry check is done in the hrtimer_interrupt or in the softirq.
646  */
647 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
648                                             struct hrtimer_clock_base *base)
649 {
650         return base->cpu_base->hres_active && hrtimer_reprogram(timer, base);
651 }
652
653 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
654 {
655         ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
656         ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
657
658         return ktime_get_update_offsets(offs_real, offs_boot);
659 }
660
661 /*
662  * Retrigger next event is called after clock was set
663  *
664  * Called with interrupts disabled via on_each_cpu()
665  */
666 static void retrigger_next_event(void *arg)
667 {
668         struct hrtimer_cpu_base *base = &__get_cpu_var(hrtimer_bases);
669
670         if (!hrtimer_hres_active())
671                 return;
672
673         raw_spin_lock(&base->lock);
674         hrtimer_update_base(base);
675         hrtimer_force_reprogram(base, 0);
676         raw_spin_unlock(&base->lock);
677 }
678
679 /*
680  * Switch to high resolution mode
681  */
682 static int hrtimer_switch_to_hres(void)
683 {
684         int i, cpu = smp_processor_id();
685         struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
686         unsigned long flags;
687
688         if (base->hres_active)
689                 return 1;
690
691         local_irq_save(flags);
692
693         if (tick_init_highres()) {
694                 local_irq_restore(flags);
695                 printk(KERN_WARNING "Could not switch to high resolution "
696                                     "mode on CPU %d\n", cpu);
697                 return 0;
698         }
699         base->hres_active = 1;
700         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
701                 base->clock_base[i].resolution = KTIME_HIGH_RES;
702
703         tick_setup_sched_timer();
704         /* "Retrigger" the interrupt to get things going */
705         retrigger_next_event(NULL);
706         local_irq_restore(flags);
707         return 1;
708 }
709
710 /*
711  * Called from timekeeping code to reprogramm the hrtimer interrupt
712  * device. If called from the timer interrupt context we defer it to
713  * softirq context.
714  */
715 void clock_was_set_delayed(void)
716 {
717         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
718
719         cpu_base->clock_was_set = 1;
720         __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
721 }
722
723 #else
724
725 static inline int hrtimer_hres_active(void) { return 0; }
726 static inline int hrtimer_is_hres_enabled(void) { return 0; }
727 static inline int hrtimer_switch_to_hres(void) { return 0; }
728 static inline void
729 hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
730 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
731                                             struct hrtimer_clock_base *base)
732 {
733         return 0;
734 }
735 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
736 static inline void retrigger_next_event(void *arg) { }
737
738 #endif /* CONFIG_HIGH_RES_TIMERS */
739
740 /*
741  * Clock realtime was set
742  *
743  * Change the offset of the realtime clock vs. the monotonic
744  * clock.
745  *
746  * We might have to reprogram the high resolution timer interrupt. On
747  * SMP we call the architecture specific code to retrigger _all_ high
748  * resolution timer interrupts. On UP we just disable interrupts and
749  * call the high resolution interrupt code.
750  */
751 void clock_was_set(void)
752 {
753 #ifdef CONFIG_HIGH_RES_TIMERS
754         /* Retrigger the CPU local events everywhere */
755         on_each_cpu(retrigger_next_event, NULL, 1);
756 #endif
757         timerfd_clock_was_set();
758 }
759
760 /*
761  * During resume we might have to reprogram the high resolution timer
762  * interrupt (on the local CPU):
763  */
764 void hrtimers_resume(void)
765 {
766         WARN_ONCE(!irqs_disabled(),
767                   KERN_INFO "hrtimers_resume() called with IRQs enabled!");
768
769         retrigger_next_event(NULL);
770         timerfd_clock_was_set();
771 }
772
773 static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
774 {
775 #ifdef CONFIG_TIMER_STATS
776         if (timer->start_site)
777                 return;
778         timer->start_site = __builtin_return_address(0);
779         memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
780         timer->start_pid = current->pid;
781 #endif
782 }
783
784 static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
785 {
786 #ifdef CONFIG_TIMER_STATS
787         timer->start_site = NULL;
788 #endif
789 }
790
791 static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
792 {
793 #ifdef CONFIG_TIMER_STATS
794         if (likely(!timer_stats_active))
795                 return;
796         timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
797                                  timer->function, timer->start_comm, 0);
798 #endif
799 }
800
801 /*
802  * Counterpart to lock_hrtimer_base above:
803  */
804 static inline
805 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
806 {
807         raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
808 }
809
810 /**
811  * hrtimer_forward - forward the timer expiry
812  * @timer:      hrtimer to forward
813  * @now:        forward past this time
814  * @interval:   the interval to forward
815  *
816  * Forward the timer expiry so it will expire in the future.
817  * Returns the number of overruns.
818  */
819 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
820 {
821         u64 orun = 1;
822         ktime_t delta;
823
824         delta = ktime_sub(now, hrtimer_get_expires(timer));
825
826         if (delta.tv64 < 0)
827                 return 0;
828
829         if (interval.tv64 < timer->base->resolution.tv64)
830                 interval.tv64 = timer->base->resolution.tv64;
831
832         if (unlikely(delta.tv64 >= interval.tv64)) {
833                 s64 incr = ktime_to_ns(interval);
834
835                 orun = ktime_divns(delta, incr);
836                 hrtimer_add_expires_ns(timer, incr * orun);
837                 if (hrtimer_get_expires_tv64(timer) > now.tv64)
838                         return orun;
839                 /*
840                  * This (and the ktime_add() below) is the
841                  * correction for exact:
842                  */
843                 orun++;
844         }
845         hrtimer_add_expires(timer, interval);
846
847         return orun;
848 }
849 EXPORT_SYMBOL_GPL(hrtimer_forward);
850
851 /*
852  * enqueue_hrtimer - internal function to (re)start a timer
853  *
854  * The timer is inserted in expiry order. Insertion into the
855  * red black tree is O(log(n)). Must hold the base lock.
856  *
857  * Returns 1 when the new timer is the leftmost timer in the tree.
858  */
859 static int enqueue_hrtimer(struct hrtimer *timer,
860                            struct hrtimer_clock_base *base)
861 {
862         debug_activate(timer);
863
864         timerqueue_add(&base->active, &timer->node);
865         base->cpu_base->active_bases |= 1 << base->index;
866
867         /*
868          * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
869          * state of a possibly running callback.
870          */
871         timer->state |= HRTIMER_STATE_ENQUEUED;
872
873         return (&timer->node == base->active.next);
874 }
875
876 /*
877  * __remove_hrtimer - internal function to remove a timer
878  *
879  * Caller must hold the base lock.
880  *
881  * High resolution timer mode reprograms the clock event device when the
882  * timer is the one which expires next. The caller can disable this by setting
883  * reprogram to zero. This is useful, when the context does a reprogramming
884  * anyway (e.g. timer interrupt)
885  */
886 static void __remove_hrtimer(struct hrtimer *timer,
887                              struct hrtimer_clock_base *base,
888                              unsigned long newstate, int reprogram)
889 {
890         struct timerqueue_node *next_timer;
891         if (!(timer->state & HRTIMER_STATE_ENQUEUED))
892                 goto out;
893
894         next_timer = timerqueue_getnext(&base->active);
895         timerqueue_del(&base->active, &timer->node);
896         if (&timer->node == next_timer) {
897 #ifdef CONFIG_HIGH_RES_TIMERS
898                 /* Reprogram the clock event device. if enabled */
899                 if (reprogram && hrtimer_hres_active()) {
900                         ktime_t expires;
901
902                         expires = ktime_sub(hrtimer_get_expires(timer),
903                                             base->offset);
904                         if (base->cpu_base->expires_next.tv64 == expires.tv64)
905                                 hrtimer_force_reprogram(base->cpu_base, 1);
906                 }
907 #endif
908         }
909         if (!timerqueue_getnext(&base->active))
910                 base->cpu_base->active_bases &= ~(1 << base->index);
911 out:
912         timer->state = newstate;
913 }
914
915 /*
916  * remove hrtimer, called with base lock held
917  */
918 static inline int
919 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
920 {
921         if (hrtimer_is_queued(timer)) {
922                 unsigned long state;
923                 int reprogram;
924
925                 /*
926                  * Remove the timer and force reprogramming when high
927                  * resolution mode is active and the timer is on the current
928                  * CPU. If we remove a timer on another CPU, reprogramming is
929                  * skipped. The interrupt event on this CPU is fired and
930                  * reprogramming happens in the interrupt handler. This is a
931                  * rare case and less expensive than a smp call.
932                  */
933                 debug_deactivate(timer);
934                 timer_stats_hrtimer_clear_start_info(timer);
935                 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
936                 /*
937                  * We must preserve the CALLBACK state flag here,
938                  * otherwise we could move the timer base in
939                  * switch_hrtimer_base.
940                  */
941                 state = timer->state & HRTIMER_STATE_CALLBACK;
942                 __remove_hrtimer(timer, base, state, reprogram);
943                 return 1;
944         }
945         return 0;
946 }
947
948 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
949                 unsigned long delta_ns, const enum hrtimer_mode mode,
950                 int wakeup)
951 {
952         struct hrtimer_clock_base *base, *new_base;
953         unsigned long flags;
954         int ret, leftmost;
955
956         base = lock_hrtimer_base(timer, &flags);
957
958         /* Remove an active timer from the queue: */
959         ret = remove_hrtimer(timer, base);
960
961         /* Switch the timer base, if necessary: */
962         new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
963
964         if (mode & HRTIMER_MODE_REL) {
965                 tim = ktime_add_safe(tim, new_base->get_time());
966                 /*
967                  * CONFIG_TIME_LOW_RES is a temporary way for architectures
968                  * to signal that they simply return xtime in
969                  * do_gettimeoffset(). In this case we want to round up by
970                  * resolution when starting a relative timer, to avoid short
971                  * timeouts. This will go away with the GTOD framework.
972                  */
973 #ifdef CONFIG_TIME_LOW_RES
974                 tim = ktime_add_safe(tim, base->resolution);
975 #endif
976         }
977
978         hrtimer_set_expires_range_ns(timer, tim, delta_ns);
979
980         timer_stats_hrtimer_set_start_info(timer);
981
982         leftmost = enqueue_hrtimer(timer, new_base);
983
984         /*
985          * Only allow reprogramming if the new base is on this CPU.
986          * (it might still be on another CPU if the timer was pending)
987          *
988          * XXX send_remote_softirq() ?
989          */
990         if (leftmost && new_base->cpu_base == &__get_cpu_var(hrtimer_bases)
991                 && hrtimer_enqueue_reprogram(timer, new_base)) {
992                 if (wakeup) {
993                         /*
994                          * We need to drop cpu_base->lock to avoid a
995                          * lock ordering issue vs. rq->lock.
996                          */
997                         raw_spin_unlock(&new_base->cpu_base->lock);
998                         raise_softirq_irqoff(HRTIMER_SOFTIRQ);
999                         local_irq_restore(flags);
1000                         return ret;
1001                 } else {
1002                         __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1003                 }
1004         }
1005
1006         unlock_hrtimer_base(timer, &flags);
1007
1008         return ret;
1009 }
1010
1011 /**
1012  * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1013  * @timer:      the timer to be added
1014  * @tim:        expiry time
1015  * @delta_ns:   "slack" range for the timer
1016  * @mode:       expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1017  *
1018  * Returns:
1019  *  0 on success
1020  *  1 when the timer was active
1021  */
1022 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1023                 unsigned long delta_ns, const enum hrtimer_mode mode)
1024 {
1025         return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1026 }
1027 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1028
1029 /**
1030  * hrtimer_start - (re)start an hrtimer on the current CPU
1031  * @timer:      the timer to be added
1032  * @tim:        expiry time
1033  * @mode:       expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1034  *
1035  * Returns:
1036  *  0 on success
1037  *  1 when the timer was active
1038  */
1039 int
1040 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1041 {
1042         return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1043 }
1044 EXPORT_SYMBOL_GPL(hrtimer_start);
1045
1046
1047 /**
1048  * hrtimer_try_to_cancel - try to deactivate a timer
1049  * @timer:      hrtimer to stop
1050  *
1051  * Returns:
1052  *  0 when the timer was not active
1053  *  1 when the timer was active
1054  * -1 when the timer is currently excuting the callback function and
1055  *    cannot be stopped
1056  */
1057 int hrtimer_try_to_cancel(struct hrtimer *timer)
1058 {
1059         struct hrtimer_clock_base *base;
1060         unsigned long flags;
1061         int ret = -1;
1062
1063         base = lock_hrtimer_base(timer, &flags);
1064
1065         if (!hrtimer_callback_running(timer))
1066                 ret = remove_hrtimer(timer, base);
1067
1068         unlock_hrtimer_base(timer, &flags);
1069
1070         return ret;
1071
1072 }
1073 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1074
1075 /**
1076  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1077  * @timer:      the timer to be cancelled
1078  *
1079  * Returns:
1080  *  0 when the timer was not active
1081  *  1 when the timer was active
1082  */
1083 int hrtimer_cancel(struct hrtimer *timer)
1084 {
1085         for (;;) {
1086                 int ret = hrtimer_try_to_cancel(timer);
1087
1088                 if (ret >= 0)
1089                         return ret;
1090                 cpu_relax();
1091         }
1092 }
1093 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1094
1095 /**
1096  * hrtimer_get_remaining - get remaining time for the timer
1097  * @timer:      the timer to read
1098  */
1099 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1100 {
1101         unsigned long flags;
1102         ktime_t rem;
1103
1104         lock_hrtimer_base(timer, &flags);
1105         rem = hrtimer_expires_remaining(timer);
1106         unlock_hrtimer_base(timer, &flags);
1107
1108         return rem;
1109 }
1110 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1111
1112 #ifdef CONFIG_NO_HZ
1113 /**
1114  * hrtimer_get_next_event - get the time until next expiry event
1115  *
1116  * Returns the delta to the next expiry event or KTIME_MAX if no timer
1117  * is pending.
1118  */
1119 ktime_t hrtimer_get_next_event(void)
1120 {
1121         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1122         struct hrtimer_clock_base *base = cpu_base->clock_base;
1123         ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1124         unsigned long flags;
1125         int i;
1126
1127         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1128
1129         if (!hrtimer_hres_active()) {
1130                 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1131                         struct hrtimer *timer;
1132                         struct timerqueue_node *next;
1133
1134                         next = timerqueue_getnext(&base->active);
1135                         if (!next)
1136                                 continue;
1137
1138                         timer = container_of(next, struct hrtimer, node);
1139                         delta.tv64 = hrtimer_get_expires_tv64(timer);
1140                         delta = ktime_sub(delta, base->get_time());
1141                         if (delta.tv64 < mindelta.tv64)
1142                                 mindelta.tv64 = delta.tv64;
1143                 }
1144         }
1145
1146         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1147
1148         if (mindelta.tv64 < 0)
1149                 mindelta.tv64 = 0;
1150         return mindelta;
1151 }
1152 #endif
1153
1154 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1155                            enum hrtimer_mode mode)
1156 {
1157         struct hrtimer_cpu_base *cpu_base;
1158         int base;
1159
1160         memset(timer, 0, sizeof(struct hrtimer));
1161
1162         cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1163
1164         if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1165                 clock_id = CLOCK_MONOTONIC;
1166
1167         base = hrtimer_clockid_to_base(clock_id);
1168         timer->base = &cpu_base->clock_base[base];
1169         timerqueue_init(&timer->node);
1170
1171 #ifdef CONFIG_TIMER_STATS
1172         timer->start_site = NULL;
1173         timer->start_pid = -1;
1174         memset(timer->start_comm, 0, TASK_COMM_LEN);
1175 #endif
1176 }
1177
1178 /**
1179  * hrtimer_init - initialize a timer to the given clock
1180  * @timer:      the timer to be initialized
1181  * @clock_id:   the clock to be used
1182  * @mode:       timer mode abs/rel
1183  */
1184 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1185                   enum hrtimer_mode mode)
1186 {
1187         debug_init(timer, clock_id, mode);
1188         __hrtimer_init(timer, clock_id, mode);
1189 }
1190 EXPORT_SYMBOL_GPL(hrtimer_init);
1191
1192 /**
1193  * hrtimer_get_res - get the timer resolution for a clock
1194  * @which_clock: which clock to query
1195  * @tp:          pointer to timespec variable to store the resolution
1196  *
1197  * Store the resolution of the clock selected by @which_clock in the
1198  * variable pointed to by @tp.
1199  */
1200 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1201 {
1202         struct hrtimer_cpu_base *cpu_base;
1203         int base = hrtimer_clockid_to_base(which_clock);
1204
1205         cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1206         *tp = ktime_to_timespec(cpu_base->clock_base[base].resolution);
1207
1208         return 0;
1209 }
1210 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1211
1212 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now)
1213 {
1214         struct hrtimer_clock_base *base = timer->base;
1215         struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1216         enum hrtimer_restart (*fn)(struct hrtimer *);
1217         int restart;
1218
1219         WARN_ON(!irqs_disabled());
1220
1221         debug_deactivate(timer);
1222         __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1223         timer_stats_account_hrtimer(timer);
1224         fn = timer->function;
1225
1226         /*
1227          * Because we run timers from hardirq context, there is no chance
1228          * they get migrated to another cpu, therefore its safe to unlock
1229          * the timer base.
1230          */
1231         raw_spin_unlock(&cpu_base->lock);
1232         trace_hrtimer_expire_entry(timer, now);
1233         restart = fn(timer);
1234         trace_hrtimer_expire_exit(timer);
1235         raw_spin_lock(&cpu_base->lock);
1236
1237         /*
1238          * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1239          * we do not reprogramm the event hardware. Happens either in
1240          * hrtimer_start_range_ns() or in hrtimer_interrupt()
1241          */
1242         if (restart != HRTIMER_NORESTART) {
1243                 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1244                 enqueue_hrtimer(timer, base);
1245         }
1246
1247         WARN_ON_ONCE(!(timer->state & HRTIMER_STATE_CALLBACK));
1248
1249         timer->state &= ~HRTIMER_STATE_CALLBACK;
1250 }
1251
1252 #ifdef CONFIG_HIGH_RES_TIMERS
1253
1254 /*
1255  * High resolution timer interrupt
1256  * Called with interrupts disabled
1257  */
1258 void hrtimer_interrupt(struct clock_event_device *dev)
1259 {
1260         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1261         ktime_t expires_next, now, entry_time, delta;
1262         int i, retries = 0;
1263
1264         BUG_ON(!cpu_base->hres_active);
1265         cpu_base->nr_events++;
1266         dev->next_event.tv64 = KTIME_MAX;
1267
1268         raw_spin_lock(&cpu_base->lock);
1269         entry_time = now = hrtimer_update_base(cpu_base);
1270 retry:
1271         expires_next.tv64 = KTIME_MAX;
1272         /*
1273          * We set expires_next to KTIME_MAX here with cpu_base->lock
1274          * held to prevent that a timer is enqueued in our queue via
1275          * the migration code. This does not affect enqueueing of
1276          * timers which run their callback and need to be requeued on
1277          * this CPU.
1278          */
1279         cpu_base->expires_next.tv64 = KTIME_MAX;
1280
1281         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1282                 struct hrtimer_clock_base *base;
1283                 struct timerqueue_node *node;
1284                 ktime_t basenow;
1285
1286                 if (!(cpu_base->active_bases & (1 << i)))
1287                         continue;
1288
1289                 base = cpu_base->clock_base + i;
1290                 basenow = ktime_add(now, base->offset);
1291
1292                 while ((node = timerqueue_getnext(&base->active))) {
1293                         struct hrtimer *timer;
1294
1295                         timer = container_of(node, struct hrtimer, node);
1296
1297                         /*
1298                          * The immediate goal for using the softexpires is
1299                          * minimizing wakeups, not running timers at the
1300                          * earliest interrupt after their soft expiration.
1301                          * This allows us to avoid using a Priority Search
1302                          * Tree, which can answer a stabbing querry for
1303                          * overlapping intervals and instead use the simple
1304                          * BST we already have.
1305                          * We don't add extra wakeups by delaying timers that
1306                          * are right-of a not yet expired timer, because that
1307                          * timer will have to trigger a wakeup anyway.
1308                          */
1309
1310                         if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1311                                 ktime_t expires;
1312
1313                                 expires = ktime_sub(hrtimer_get_expires(timer),
1314                                                     base->offset);
1315                                 if (expires.tv64 < 0)
1316                                         expires.tv64 = KTIME_MAX;
1317                                 if (expires.tv64 < expires_next.tv64)
1318                                         expires_next = expires;
1319                                 break;
1320                         }
1321
1322                         __run_hrtimer(timer, &basenow);
1323                 }
1324         }
1325
1326         /*
1327          * Store the new expiry value so the migration code can verify
1328          * against it.
1329          */
1330         cpu_base->expires_next = expires_next;
1331         raw_spin_unlock(&cpu_base->lock);
1332
1333         /* Reprogramming necessary ? */
1334         if (expires_next.tv64 == KTIME_MAX ||
1335             !tick_program_event(expires_next, 0)) {
1336                 cpu_base->hang_detected = 0;
1337                 return;
1338         }
1339
1340         /*
1341          * The next timer was already expired due to:
1342          * - tracing
1343          * - long lasting callbacks
1344          * - being scheduled away when running in a VM
1345          *
1346          * We need to prevent that we loop forever in the hrtimer
1347          * interrupt routine. We give it 3 attempts to avoid
1348          * overreacting on some spurious event.
1349          *
1350          * Acquire base lock for updating the offsets and retrieving
1351          * the current time.
1352          */
1353         raw_spin_lock(&cpu_base->lock);
1354         now = hrtimer_update_base(cpu_base);
1355         cpu_base->nr_retries++;
1356         if (++retries < 3)
1357                 goto retry;
1358         /*
1359          * Give the system a chance to do something else than looping
1360          * here. We stored the entry time, so we know exactly how long
1361          * we spent here. We schedule the next event this amount of
1362          * time away.
1363          */
1364         cpu_base->nr_hangs++;
1365         cpu_base->hang_detected = 1;
1366         raw_spin_unlock(&cpu_base->lock);
1367         delta = ktime_sub(now, entry_time);
1368         if (delta.tv64 > cpu_base->max_hang_time.tv64)
1369                 cpu_base->max_hang_time = delta;
1370         /*
1371          * Limit it to a sensible value as we enforce a longer
1372          * delay. Give the CPU at least 100ms to catch up.
1373          */
1374         if (delta.tv64 > 100 * NSEC_PER_MSEC)
1375                 expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1376         else
1377                 expires_next = ktime_add(now, delta);
1378         tick_program_event(expires_next, 1);
1379         printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1380                     ktime_to_ns(delta));
1381 }
1382
1383 /*
1384  * local version of hrtimer_peek_ahead_timers() called with interrupts
1385  * disabled.
1386  */
1387 static void __hrtimer_peek_ahead_timers(void)
1388 {
1389         struct tick_device *td;
1390
1391         if (!hrtimer_hres_active())
1392                 return;
1393
1394         td = &__get_cpu_var(tick_cpu_device);
1395         if (td && td->evtdev)
1396                 hrtimer_interrupt(td->evtdev);
1397 }
1398
1399 /**
1400  * hrtimer_peek_ahead_timers -- run soft-expired timers now
1401  *
1402  * hrtimer_peek_ahead_timers will peek at the timer queue of
1403  * the current cpu and check if there are any timers for which
1404  * the soft expires time has passed. If any such timers exist,
1405  * they are run immediately and then removed from the timer queue.
1406  *
1407  */
1408 void hrtimer_peek_ahead_timers(void)
1409 {
1410         unsigned long flags;
1411
1412         local_irq_save(flags);
1413         __hrtimer_peek_ahead_timers();
1414         local_irq_restore(flags);
1415 }
1416
1417 static void run_hrtimer_softirq(struct softirq_action *h)
1418 {
1419         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1420
1421         if (cpu_base->clock_was_set) {
1422                 cpu_base->clock_was_set = 0;
1423                 clock_was_set();
1424         }
1425
1426         hrtimer_peek_ahead_timers();
1427 }
1428
1429 #else /* CONFIG_HIGH_RES_TIMERS */
1430
1431 static inline void __hrtimer_peek_ahead_timers(void) { }
1432
1433 #endif  /* !CONFIG_HIGH_RES_TIMERS */
1434
1435 /*
1436  * Called from timer softirq every jiffy, expire hrtimers:
1437  *
1438  * For HRT its the fall back code to run the softirq in the timer
1439  * softirq context in case the hrtimer initialization failed or has
1440  * not been done yet.
1441  */
1442 void hrtimer_run_pending(void)
1443 {
1444         if (hrtimer_hres_active())
1445                 return;
1446
1447         /*
1448          * This _is_ ugly: We have to check in the softirq context,
1449          * whether we can switch to highres and / or nohz mode. The
1450          * clocksource switch happens in the timer interrupt with
1451          * xtime_lock held. Notification from there only sets the
1452          * check bit in the tick_oneshot code, otherwise we might
1453          * deadlock vs. xtime_lock.
1454          */
1455         if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1456                 hrtimer_switch_to_hres();
1457 }
1458
1459 /*
1460  * Called from hardirq context every jiffy
1461  */
1462 void hrtimer_run_queues(void)
1463 {
1464         struct timerqueue_node *node;
1465         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1466         struct hrtimer_clock_base *base;
1467         int index, gettime = 1;
1468
1469         if (hrtimer_hres_active())
1470                 return;
1471
1472         for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1473                 base = &cpu_base->clock_base[index];
1474                 if (!timerqueue_getnext(&base->active))
1475                         continue;
1476
1477                 if (gettime) {
1478                         hrtimer_get_softirq_time(cpu_base);
1479                         gettime = 0;
1480                 }
1481
1482                 raw_spin_lock(&cpu_base->lock);
1483
1484                 while ((node = timerqueue_getnext(&base->active))) {
1485                         struct hrtimer *timer;
1486
1487                         timer = container_of(node, struct hrtimer, node);
1488                         if (base->softirq_time.tv64 <=
1489                                         hrtimer_get_expires_tv64(timer))
1490                                 break;
1491
1492                         __run_hrtimer(timer, &base->softirq_time);
1493                 }
1494                 raw_spin_unlock(&cpu_base->lock);
1495         }
1496 }
1497
1498 /*
1499  * Sleep related functions:
1500  */
1501 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1502 {
1503         struct hrtimer_sleeper *t =
1504                 container_of(timer, struct hrtimer_sleeper, timer);
1505         struct task_struct *task = t->task;
1506
1507         t->task = NULL;
1508         if (task)
1509                 wake_up_process(task);
1510
1511         return HRTIMER_NORESTART;
1512 }
1513
1514 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1515 {
1516         sl->timer.function = hrtimer_wakeup;
1517         sl->task = task;
1518 }
1519 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1520
1521 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1522 {
1523         hrtimer_init_sleeper(t, current);
1524
1525         do {
1526                 set_current_state(TASK_INTERRUPTIBLE);
1527                 hrtimer_start_expires(&t->timer, mode);
1528                 if (!hrtimer_active(&t->timer))
1529                         t->task = NULL;
1530
1531                 if (likely(t->task))
1532                         schedule();
1533
1534                 hrtimer_cancel(&t->timer);
1535                 mode = HRTIMER_MODE_ABS;
1536
1537         } while (t->task && !signal_pending(current));
1538
1539         __set_current_state(TASK_RUNNING);
1540
1541         return t->task == NULL;
1542 }
1543
1544 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1545 {
1546         struct timespec rmt;
1547         ktime_t rem;
1548
1549         rem = hrtimer_expires_remaining(timer);
1550         if (rem.tv64 <= 0)
1551                 return 0;
1552         rmt = ktime_to_timespec(rem);
1553
1554         if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1555                 return -EFAULT;
1556
1557         return 1;
1558 }
1559
1560 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1561 {
1562         struct hrtimer_sleeper t;
1563         struct timespec __user  *rmtp;
1564         int ret = 0;
1565
1566         hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
1567                                 HRTIMER_MODE_ABS);
1568         hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1569
1570         if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1571                 goto out;
1572
1573         rmtp = restart->nanosleep.rmtp;
1574         if (rmtp) {
1575                 ret = update_rmtp(&t.timer, rmtp);
1576                 if (ret <= 0)
1577                         goto out;
1578         }
1579
1580         /* The other values in restart are already filled in */
1581         ret = -ERESTART_RESTARTBLOCK;
1582 out:
1583         destroy_hrtimer_on_stack(&t.timer);
1584         return ret;
1585 }
1586
1587 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1588                        const enum hrtimer_mode mode, const clockid_t clockid)
1589 {
1590         struct restart_block *restart;
1591         struct hrtimer_sleeper t;
1592         int ret = 0;
1593         unsigned long slack;
1594
1595         slack = current->timer_slack_ns;
1596         if (rt_task(current))
1597                 slack = 0;
1598
1599         hrtimer_init_on_stack(&t.timer, clockid, mode);
1600         hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1601         if (do_nanosleep(&t, mode))
1602                 goto out;
1603
1604         /* Absolute timers do not update the rmtp value and restart: */
1605         if (mode == HRTIMER_MODE_ABS) {
1606                 ret = -ERESTARTNOHAND;
1607                 goto out;
1608         }
1609
1610         if (rmtp) {
1611                 ret = update_rmtp(&t.timer, rmtp);
1612                 if (ret <= 0)
1613                         goto out;
1614         }
1615
1616         restart = &current_thread_info()->restart_block;
1617         restart->fn = hrtimer_nanosleep_restart;
1618         restart->nanosleep.clockid = t.timer.base->clockid;
1619         restart->nanosleep.rmtp = rmtp;
1620         restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1621
1622         ret = -ERESTART_RESTARTBLOCK;
1623 out:
1624         destroy_hrtimer_on_stack(&t.timer);
1625         return ret;
1626 }
1627
1628 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1629                 struct timespec __user *, rmtp)
1630 {
1631         struct timespec tu;
1632
1633         if (copy_from_user(&tu, rqtp, sizeof(tu)))
1634                 return -EFAULT;
1635
1636         if (!timespec_valid(&tu))
1637                 return -EINVAL;
1638
1639         return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1640 }
1641
1642 /*
1643  * Functions related to boot-time initialization:
1644  */
1645 static void __cpuinit init_hrtimers_cpu(int cpu)
1646 {
1647         struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1648         int i;
1649
1650         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1651                 cpu_base->clock_base[i].cpu_base = cpu_base;
1652                 timerqueue_init_head(&cpu_base->clock_base[i].active);
1653         }
1654
1655         hrtimer_init_hres(cpu_base);
1656 }
1657
1658 #ifdef CONFIG_HOTPLUG_CPU
1659
1660 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1661                                 struct hrtimer_clock_base *new_base)
1662 {
1663         struct hrtimer *timer;
1664         struct timerqueue_node *node;
1665
1666         while ((node = timerqueue_getnext(&old_base->active))) {
1667                 timer = container_of(node, struct hrtimer, node);
1668                 BUG_ON(hrtimer_callback_running(timer));
1669                 debug_deactivate(timer);
1670
1671                 /*
1672                  * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1673                  * timer could be seen as !active and just vanish away
1674                  * under us on another CPU
1675                  */
1676                 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1677                 timer->base = new_base;
1678                 /*
1679                  * Enqueue the timers on the new cpu. This does not
1680                  * reprogram the event device in case the timer
1681                  * expires before the earliest on this CPU, but we run
1682                  * hrtimer_interrupt after we migrated everything to
1683                  * sort out already expired timers and reprogram the
1684                  * event device.
1685                  */
1686                 enqueue_hrtimer(timer, new_base);
1687
1688                 /* Clear the migration state bit */
1689                 timer->state &= ~HRTIMER_STATE_MIGRATE;
1690         }
1691 }
1692
1693 static void migrate_hrtimers(int scpu)
1694 {
1695         struct hrtimer_cpu_base *old_base, *new_base;
1696         int i;
1697
1698         BUG_ON(cpu_online(scpu));
1699         tick_cancel_sched_timer(scpu);
1700
1701         local_irq_disable();
1702         old_base = &per_cpu(hrtimer_bases, scpu);
1703         new_base = &__get_cpu_var(hrtimer_bases);
1704         /*
1705          * The caller is globally serialized and nobody else
1706          * takes two locks at once, deadlock is not possible.
1707          */
1708         raw_spin_lock(&new_base->lock);
1709         raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1710
1711         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1712                 migrate_hrtimer_list(&old_base->clock_base[i],
1713                                      &new_base->clock_base[i]);
1714         }
1715
1716         raw_spin_unlock(&old_base->lock);
1717         raw_spin_unlock(&new_base->lock);
1718
1719         /* Check, if we got expired work to do */
1720         __hrtimer_peek_ahead_timers();
1721         local_irq_enable();
1722 }
1723
1724 #endif /* CONFIG_HOTPLUG_CPU */
1725
1726 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1727                                         unsigned long action, void *hcpu)
1728 {
1729         int scpu = (long)hcpu;
1730
1731         switch (action) {
1732
1733         case CPU_UP_PREPARE:
1734         case CPU_UP_PREPARE_FROZEN:
1735                 init_hrtimers_cpu(scpu);
1736                 break;
1737
1738 #ifdef CONFIG_HOTPLUG_CPU
1739         case CPU_DYING:
1740         case CPU_DYING_FROZEN:
1741                 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1742                 break;
1743         case CPU_DEAD:
1744         case CPU_DEAD_FROZEN:
1745         {
1746                 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1747                 migrate_hrtimers(scpu);
1748                 break;
1749         }
1750 #endif
1751
1752         default:
1753                 break;
1754         }
1755
1756         return NOTIFY_OK;
1757 }
1758
1759 static struct notifier_block __cpuinitdata hrtimers_nb = {
1760         .notifier_call = hrtimer_cpu_notify,
1761 };
1762
1763 void __init hrtimers_init(void)
1764 {
1765         hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1766                           (void *)(long)smp_processor_id());
1767         register_cpu_notifier(&hrtimers_nb);
1768 #ifdef CONFIG_HIGH_RES_TIMERS
1769         open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1770 #endif
1771 }
1772
1773 /**
1774  * schedule_hrtimeout_range_clock - sleep until timeout
1775  * @expires:    timeout value (ktime_t)
1776  * @delta:      slack in expires timeout (ktime_t)
1777  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1778  * @clock:      timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
1779  */
1780 int __sched
1781 schedule_hrtimeout_range_clock(ktime_t *expires, unsigned long delta,
1782                                const enum hrtimer_mode mode, int clock)
1783 {
1784         struct hrtimer_sleeper t;
1785
1786         /*
1787          * Optimize when a zero timeout value is given. It does not
1788          * matter whether this is an absolute or a relative time.
1789          */
1790         if (expires && !expires->tv64) {
1791                 __set_current_state(TASK_RUNNING);
1792                 return 0;
1793         }
1794
1795         /*
1796          * A NULL parameter means "infinite"
1797          */
1798         if (!expires) {
1799                 schedule();
1800                 __set_current_state(TASK_RUNNING);
1801                 return -EINTR;
1802         }
1803
1804         hrtimer_init_on_stack(&t.timer, clock, mode);
1805         hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1806
1807         hrtimer_init_sleeper(&t, current);
1808
1809         hrtimer_start_expires(&t.timer, mode);
1810         if (!hrtimer_active(&t.timer))
1811                 t.task = NULL;
1812
1813         if (likely(t.task))
1814                 schedule();
1815
1816         hrtimer_cancel(&t.timer);
1817         destroy_hrtimer_on_stack(&t.timer);
1818
1819         __set_current_state(TASK_RUNNING);
1820
1821         return !t.task ? 0 : -EINTR;
1822 }
1823
1824 /**
1825  * schedule_hrtimeout_range - sleep until timeout
1826  * @expires:    timeout value (ktime_t)
1827  * @delta:      slack in expires timeout (ktime_t)
1828  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1829  *
1830  * Make the current task sleep until the given expiry time has
1831  * elapsed. The routine will return immediately unless
1832  * the current task state has been set (see set_current_state()).
1833  *
1834  * The @delta argument gives the kernel the freedom to schedule the
1835  * actual wakeup to a time that is both power and performance friendly.
1836  * The kernel give the normal best effort behavior for "@expires+@delta",
1837  * but may decide to fire the timer earlier, but no earlier than @expires.
1838  *
1839  * You can set the task state as follows -
1840  *
1841  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1842  * pass before the routine returns.
1843  *
1844  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1845  * delivered to the current task.
1846  *
1847  * The current task state is guaranteed to be TASK_RUNNING when this
1848  * routine returns.
1849  *
1850  * Returns 0 when the timer has expired otherwise -EINTR
1851  */
1852 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1853                                      const enum hrtimer_mode mode)
1854 {
1855         return schedule_hrtimeout_range_clock(expires, delta, mode,
1856                                               CLOCK_MONOTONIC);
1857 }
1858 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1859
1860 /**
1861  * schedule_hrtimeout - sleep until timeout
1862  * @expires:    timeout value (ktime_t)
1863  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1864  *
1865  * Make the current task sleep until the given expiry time has
1866  * elapsed. The routine will return immediately unless
1867  * the current task state has been set (see set_current_state()).
1868  *
1869  * You can set the task state as follows -
1870  *
1871  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1872  * pass before the routine returns.
1873  *
1874  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1875  * delivered to the current task.
1876  *
1877  * The current task state is guaranteed to be TASK_RUNNING when this
1878  * routine returns.
1879  *
1880  * Returns 0 when the timer has expired otherwise -EINTR
1881  */
1882 int __sched schedule_hrtimeout(ktime_t *expires,
1883                                const enum hrtimer_mode mode)
1884 {
1885         return schedule_hrtimeout_range(expires, 0, mode);
1886 }
1887 EXPORT_SYMBOL_GPL(schedule_hrtimeout);