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