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