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