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