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