timekeeping: Move ktime_get() functions to timekeeping.c
[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         INIT_LIST_HEAD(&timer->cb_entry);
1096         hrtimer_init_timer_hres(timer);
1097
1098 #ifdef CONFIG_TIMER_STATS
1099         timer->start_site = NULL;
1100         timer->start_pid = -1;
1101         memset(timer->start_comm, 0, TASK_COMM_LEN);
1102 #endif
1103 }
1104
1105 /**
1106  * hrtimer_init - initialize a timer to the given clock
1107  * @timer:      the timer to be initialized
1108  * @clock_id:   the clock to be used
1109  * @mode:       timer mode abs/rel
1110  */
1111 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1112                   enum hrtimer_mode mode)
1113 {
1114         debug_hrtimer_init(timer);
1115         __hrtimer_init(timer, clock_id, mode);
1116 }
1117 EXPORT_SYMBOL_GPL(hrtimer_init);
1118
1119 /**
1120  * hrtimer_get_res - get the timer resolution for a clock
1121  * @which_clock: which clock to query
1122  * @tp:          pointer to timespec variable to store the resolution
1123  *
1124  * Store the resolution of the clock selected by @which_clock in the
1125  * variable pointed to by @tp.
1126  */
1127 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1128 {
1129         struct hrtimer_cpu_base *cpu_base;
1130
1131         cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1132         *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1133
1134         return 0;
1135 }
1136 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1137
1138 static void __run_hrtimer(struct hrtimer *timer)
1139 {
1140         struct hrtimer_clock_base *base = timer->base;
1141         struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1142         enum hrtimer_restart (*fn)(struct hrtimer *);
1143         int restart;
1144
1145         WARN_ON(!irqs_disabled());
1146
1147         debug_hrtimer_deactivate(timer);
1148         __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1149         timer_stats_account_hrtimer(timer);
1150         fn = timer->function;
1151
1152         /*
1153          * Because we run timers from hardirq context, there is no chance
1154          * they get migrated to another cpu, therefore its safe to unlock
1155          * the timer base.
1156          */
1157         spin_unlock(&cpu_base->lock);
1158         restart = fn(timer);
1159         spin_lock(&cpu_base->lock);
1160
1161         /*
1162          * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1163          * we do not reprogramm the event hardware. Happens either in
1164          * hrtimer_start_range_ns() or in hrtimer_interrupt()
1165          */
1166         if (restart != HRTIMER_NORESTART) {
1167                 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1168                 enqueue_hrtimer(timer, base);
1169         }
1170         timer->state &= ~HRTIMER_STATE_CALLBACK;
1171 }
1172
1173 #ifdef CONFIG_HIGH_RES_TIMERS
1174
1175 static int force_clock_reprogram;
1176
1177 /*
1178  * After 5 iteration's attempts, we consider that hrtimer_interrupt()
1179  * is hanging, which could happen with something that slows the interrupt
1180  * such as the tracing. Then we force the clock reprogramming for each future
1181  * hrtimer interrupts to avoid infinite loops and use the min_delta_ns
1182  * threshold that we will overwrite.
1183  * The next tick event will be scheduled to 3 times we currently spend on
1184  * hrtimer_interrupt(). This gives a good compromise, the cpus will spend
1185  * 1/4 of their time to process the hrtimer interrupts. This is enough to
1186  * let it running without serious starvation.
1187  */
1188
1189 static inline void
1190 hrtimer_interrupt_hanging(struct clock_event_device *dev,
1191                         ktime_t try_time)
1192 {
1193         force_clock_reprogram = 1;
1194         dev->min_delta_ns = (unsigned long)try_time.tv64 * 3;
1195         printk(KERN_WARNING "hrtimer: interrupt too slow, "
1196                 "forcing clock min delta to %lu ns\n", dev->min_delta_ns);
1197 }
1198 /*
1199  * High resolution timer interrupt
1200  * Called with interrupts disabled
1201  */
1202 void hrtimer_interrupt(struct clock_event_device *dev)
1203 {
1204         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1205         struct hrtimer_clock_base *base;
1206         ktime_t expires_next, now;
1207         int nr_retries = 0;
1208         int i;
1209
1210         BUG_ON(!cpu_base->hres_active);
1211         cpu_base->nr_events++;
1212         dev->next_event.tv64 = KTIME_MAX;
1213
1214  retry:
1215         /* 5 retries is enough to notice a hang */
1216         if (!(++nr_retries % 5))
1217                 hrtimer_interrupt_hanging(dev, ktime_sub(ktime_get(), now));
1218
1219         now = ktime_get();
1220
1221         expires_next.tv64 = KTIME_MAX;
1222
1223         base = cpu_base->clock_base;
1224
1225         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1226                 ktime_t basenow;
1227                 struct rb_node *node;
1228
1229                 spin_lock(&cpu_base->lock);
1230
1231                 basenow = ktime_add(now, base->offset);
1232
1233                 while ((node = base->first)) {
1234                         struct hrtimer *timer;
1235
1236                         timer = rb_entry(node, struct hrtimer, node);
1237
1238                         /*
1239                          * The immediate goal for using the softexpires is
1240                          * minimizing wakeups, not running timers at the
1241                          * earliest interrupt after their soft expiration.
1242                          * This allows us to avoid using a Priority Search
1243                          * Tree, which can answer a stabbing querry for
1244                          * overlapping intervals and instead use the simple
1245                          * BST we already have.
1246                          * We don't add extra wakeups by delaying timers that
1247                          * are right-of a not yet expired timer, because that
1248                          * timer will have to trigger a wakeup anyway.
1249                          */
1250
1251                         if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1252                                 ktime_t expires;
1253
1254                                 expires = ktime_sub(hrtimer_get_expires(timer),
1255                                                     base->offset);
1256                                 if (expires.tv64 < expires_next.tv64)
1257                                         expires_next = expires;
1258                                 break;
1259                         }
1260
1261                         __run_hrtimer(timer);
1262                 }
1263                 spin_unlock(&cpu_base->lock);
1264                 base++;
1265         }
1266
1267         cpu_base->expires_next = expires_next;
1268
1269         /* Reprogramming necessary ? */
1270         if (expires_next.tv64 != KTIME_MAX) {
1271                 if (tick_program_event(expires_next, force_clock_reprogram))
1272                         goto retry;
1273         }
1274 }
1275
1276 /*
1277  * local version of hrtimer_peek_ahead_timers() called with interrupts
1278  * disabled.
1279  */
1280 static void __hrtimer_peek_ahead_timers(void)
1281 {
1282         struct tick_device *td;
1283
1284         if (!hrtimer_hres_active())
1285                 return;
1286
1287         td = &__get_cpu_var(tick_cpu_device);
1288         if (td && td->evtdev)
1289                 hrtimer_interrupt(td->evtdev);
1290 }
1291
1292 /**
1293  * hrtimer_peek_ahead_timers -- run soft-expired timers now
1294  *
1295  * hrtimer_peek_ahead_timers will peek at the timer queue of
1296  * the current cpu and check if there are any timers for which
1297  * the soft expires time has passed. If any such timers exist,
1298  * they are run immediately and then removed from the timer queue.
1299  *
1300  */
1301 void hrtimer_peek_ahead_timers(void)
1302 {
1303         unsigned long flags;
1304
1305         local_irq_save(flags);
1306         __hrtimer_peek_ahead_timers();
1307         local_irq_restore(flags);
1308 }
1309
1310 static void run_hrtimer_softirq(struct softirq_action *h)
1311 {
1312         hrtimer_peek_ahead_timers();
1313 }
1314
1315 #else /* CONFIG_HIGH_RES_TIMERS */
1316
1317 static inline void __hrtimer_peek_ahead_timers(void) { }
1318
1319 #endif  /* !CONFIG_HIGH_RES_TIMERS */
1320
1321 /*
1322  * Called from timer softirq every jiffy, expire hrtimers:
1323  *
1324  * For HRT its the fall back code to run the softirq in the timer
1325  * softirq context in case the hrtimer initialization failed or has
1326  * not been done yet.
1327  */
1328 void hrtimer_run_pending(void)
1329 {
1330         if (hrtimer_hres_active())
1331                 return;
1332
1333         /*
1334          * This _is_ ugly: We have to check in the softirq context,
1335          * whether we can switch to highres and / or nohz mode. The
1336          * clocksource switch happens in the timer interrupt with
1337          * xtime_lock held. Notification from there only sets the
1338          * check bit in the tick_oneshot code, otherwise we might
1339          * deadlock vs. xtime_lock.
1340          */
1341         if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1342                 hrtimer_switch_to_hres();
1343 }
1344
1345 /*
1346  * Called from hardirq context every jiffy
1347  */
1348 void hrtimer_run_queues(void)
1349 {
1350         struct rb_node *node;
1351         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1352         struct hrtimer_clock_base *base;
1353         int index, gettime = 1;
1354
1355         if (hrtimer_hres_active())
1356                 return;
1357
1358         for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1359                 base = &cpu_base->clock_base[index];
1360
1361                 if (!base->first)
1362                         continue;
1363
1364                 if (gettime) {
1365                         hrtimer_get_softirq_time(cpu_base);
1366                         gettime = 0;
1367                 }
1368
1369                 spin_lock(&cpu_base->lock);
1370
1371                 while ((node = base->first)) {
1372                         struct hrtimer *timer;
1373
1374                         timer = rb_entry(node, struct hrtimer, node);
1375                         if (base->softirq_time.tv64 <=
1376                                         hrtimer_get_expires_tv64(timer))
1377                                 break;
1378
1379                         __run_hrtimer(timer);
1380                 }
1381                 spin_unlock(&cpu_base->lock);
1382         }
1383 }
1384
1385 /*
1386  * Sleep related functions:
1387  */
1388 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1389 {
1390         struct hrtimer_sleeper *t =
1391                 container_of(timer, struct hrtimer_sleeper, timer);
1392         struct task_struct *task = t->task;
1393
1394         t->task = NULL;
1395         if (task)
1396                 wake_up_process(task);
1397
1398         return HRTIMER_NORESTART;
1399 }
1400
1401 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1402 {
1403         sl->timer.function = hrtimer_wakeup;
1404         sl->task = task;
1405 }
1406
1407 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1408 {
1409         hrtimer_init_sleeper(t, current);
1410
1411         do {
1412                 set_current_state(TASK_INTERRUPTIBLE);
1413                 hrtimer_start_expires(&t->timer, mode);
1414                 if (!hrtimer_active(&t->timer))
1415                         t->task = NULL;
1416
1417                 if (likely(t->task))
1418                         schedule();
1419
1420                 hrtimer_cancel(&t->timer);
1421                 mode = HRTIMER_MODE_ABS;
1422
1423         } while (t->task && !signal_pending(current));
1424
1425         __set_current_state(TASK_RUNNING);
1426
1427         return t->task == NULL;
1428 }
1429
1430 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1431 {
1432         struct timespec rmt;
1433         ktime_t rem;
1434
1435         rem = hrtimer_expires_remaining(timer);
1436         if (rem.tv64 <= 0)
1437                 return 0;
1438         rmt = ktime_to_timespec(rem);
1439
1440         if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1441                 return -EFAULT;
1442
1443         return 1;
1444 }
1445
1446 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1447 {
1448         struct hrtimer_sleeper t;
1449         struct timespec __user  *rmtp;
1450         int ret = 0;
1451
1452         hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1453                                 HRTIMER_MODE_ABS);
1454         hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1455
1456         if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1457                 goto out;
1458
1459         rmtp = restart->nanosleep.rmtp;
1460         if (rmtp) {
1461                 ret = update_rmtp(&t.timer, rmtp);
1462                 if (ret <= 0)
1463                         goto out;
1464         }
1465
1466         /* The other values in restart are already filled in */
1467         ret = -ERESTART_RESTARTBLOCK;
1468 out:
1469         destroy_hrtimer_on_stack(&t.timer);
1470         return ret;
1471 }
1472
1473 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1474                        const enum hrtimer_mode mode, const clockid_t clockid)
1475 {
1476         struct restart_block *restart;
1477         struct hrtimer_sleeper t;
1478         int ret = 0;
1479         unsigned long slack;
1480
1481         slack = current->timer_slack_ns;
1482         if (rt_task(current))
1483                 slack = 0;
1484
1485         hrtimer_init_on_stack(&t.timer, clockid, mode);
1486         hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1487         if (do_nanosleep(&t, mode))
1488                 goto out;
1489
1490         /* Absolute timers do not update the rmtp value and restart: */
1491         if (mode == HRTIMER_MODE_ABS) {
1492                 ret = -ERESTARTNOHAND;
1493                 goto out;
1494         }
1495
1496         if (rmtp) {
1497                 ret = update_rmtp(&t.timer, rmtp);
1498                 if (ret <= 0)
1499                         goto out;
1500         }
1501
1502         restart = &current_thread_info()->restart_block;
1503         restart->fn = hrtimer_nanosleep_restart;
1504         restart->nanosleep.index = t.timer.base->index;
1505         restart->nanosleep.rmtp = rmtp;
1506         restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1507
1508         ret = -ERESTART_RESTARTBLOCK;
1509 out:
1510         destroy_hrtimer_on_stack(&t.timer);
1511         return ret;
1512 }
1513
1514 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1515                 struct timespec __user *, rmtp)
1516 {
1517         struct timespec tu;
1518
1519         if (copy_from_user(&tu, rqtp, sizeof(tu)))
1520                 return -EFAULT;
1521
1522         if (!timespec_valid(&tu))
1523                 return -EINVAL;
1524
1525         return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1526 }
1527
1528 /*
1529  * Functions related to boot-time initialization:
1530  */
1531 static void __cpuinit init_hrtimers_cpu(int cpu)
1532 {
1533         struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1534         int i;
1535
1536         spin_lock_init(&cpu_base->lock);
1537
1538         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1539                 cpu_base->clock_base[i].cpu_base = cpu_base;
1540
1541         hrtimer_init_hres(cpu_base);
1542 }
1543
1544 #ifdef CONFIG_HOTPLUG_CPU
1545
1546 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1547                                 struct hrtimer_clock_base *new_base)
1548 {
1549         struct hrtimer *timer;
1550         struct rb_node *node;
1551
1552         while ((node = rb_first(&old_base->active))) {
1553                 timer = rb_entry(node, struct hrtimer, node);
1554                 BUG_ON(hrtimer_callback_running(timer));
1555                 debug_hrtimer_deactivate(timer);
1556
1557                 /*
1558                  * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1559                  * timer could be seen as !active and just vanish away
1560                  * under us on another CPU
1561                  */
1562                 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1563                 timer->base = new_base;
1564                 /*
1565                  * Enqueue the timers on the new cpu. This does not
1566                  * reprogram the event device in case the timer
1567                  * expires before the earliest on this CPU, but we run
1568                  * hrtimer_interrupt after we migrated everything to
1569                  * sort out already expired timers and reprogram the
1570                  * event device.
1571                  */
1572                 enqueue_hrtimer(timer, new_base);
1573
1574                 /* Clear the migration state bit */
1575                 timer->state &= ~HRTIMER_STATE_MIGRATE;
1576         }
1577 }
1578
1579 static void migrate_hrtimers(int scpu)
1580 {
1581         struct hrtimer_cpu_base *old_base, *new_base;
1582         int i;
1583
1584         BUG_ON(cpu_online(scpu));
1585         tick_cancel_sched_timer(scpu);
1586
1587         local_irq_disable();
1588         old_base = &per_cpu(hrtimer_bases, scpu);
1589         new_base = &__get_cpu_var(hrtimer_bases);
1590         /*
1591          * The caller is globally serialized and nobody else
1592          * takes two locks at once, deadlock is not possible.
1593          */
1594         spin_lock(&new_base->lock);
1595         spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1596
1597         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1598                 migrate_hrtimer_list(&old_base->clock_base[i],
1599                                      &new_base->clock_base[i]);
1600         }
1601
1602         spin_unlock(&old_base->lock);
1603         spin_unlock(&new_base->lock);
1604
1605         /* Check, if we got expired work to do */
1606         __hrtimer_peek_ahead_timers();
1607         local_irq_enable();
1608 }
1609
1610 #endif /* CONFIG_HOTPLUG_CPU */
1611
1612 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1613                                         unsigned long action, void *hcpu)
1614 {
1615         int scpu = (long)hcpu;
1616
1617         switch (action) {
1618
1619         case CPU_UP_PREPARE:
1620         case CPU_UP_PREPARE_FROZEN:
1621                 init_hrtimers_cpu(scpu);
1622                 break;
1623
1624 #ifdef CONFIG_HOTPLUG_CPU
1625         case CPU_DYING:
1626         case CPU_DYING_FROZEN:
1627                 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1628                 break;
1629         case CPU_DEAD:
1630         case CPU_DEAD_FROZEN:
1631         {
1632                 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1633                 migrate_hrtimers(scpu);
1634                 break;
1635         }
1636 #endif
1637
1638         default:
1639                 break;
1640         }
1641
1642         return NOTIFY_OK;
1643 }
1644
1645 static struct notifier_block __cpuinitdata hrtimers_nb = {
1646         .notifier_call = hrtimer_cpu_notify,
1647 };
1648
1649 void __init hrtimers_init(void)
1650 {
1651         hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1652                           (void *)(long)smp_processor_id());
1653         register_cpu_notifier(&hrtimers_nb);
1654 #ifdef CONFIG_HIGH_RES_TIMERS
1655         open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1656 #endif
1657 }
1658
1659 /**
1660  * schedule_hrtimeout_range - sleep until timeout
1661  * @expires:    timeout value (ktime_t)
1662  * @delta:      slack in expires timeout (ktime_t)
1663  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1664  *
1665  * Make the current task sleep until the given expiry time has
1666  * elapsed. The routine will return immediately unless
1667  * the current task state has been set (see set_current_state()).
1668  *
1669  * The @delta argument gives the kernel the freedom to schedule the
1670  * actual wakeup to a time that is both power and performance friendly.
1671  * The kernel give the normal best effort behavior for "@expires+@delta",
1672  * but may decide to fire the timer earlier, but no earlier than @expires.
1673  *
1674  * You can set the task state as follows -
1675  *
1676  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1677  * pass before the routine returns.
1678  *
1679  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1680  * delivered to the current task.
1681  *
1682  * The current task state is guaranteed to be TASK_RUNNING when this
1683  * routine returns.
1684  *
1685  * Returns 0 when the timer has expired otherwise -EINTR
1686  */
1687 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1688                                const enum hrtimer_mode mode)
1689 {
1690         struct hrtimer_sleeper t;
1691
1692         /*
1693          * Optimize when a zero timeout value is given. It does not
1694          * matter whether this is an absolute or a relative time.
1695          */
1696         if (expires && !expires->tv64) {
1697                 __set_current_state(TASK_RUNNING);
1698                 return 0;
1699         }
1700
1701         /*
1702          * A NULL parameter means "inifinte"
1703          */
1704         if (!expires) {
1705                 schedule();
1706                 __set_current_state(TASK_RUNNING);
1707                 return -EINTR;
1708         }
1709
1710         hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
1711         hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1712
1713         hrtimer_init_sleeper(&t, current);
1714
1715         hrtimer_start_expires(&t.timer, mode);
1716         if (!hrtimer_active(&t.timer))
1717                 t.task = NULL;
1718
1719         if (likely(t.task))
1720                 schedule();
1721
1722         hrtimer_cancel(&t.timer);
1723         destroy_hrtimer_on_stack(&t.timer);
1724
1725         __set_current_state(TASK_RUNNING);
1726
1727         return !t.task ? 0 : -EINTR;
1728 }
1729 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1730
1731 /**
1732  * schedule_hrtimeout - sleep until timeout
1733  * @expires:    timeout value (ktime_t)
1734  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1735  *
1736  * Make the current task sleep until the given expiry time has
1737  * elapsed. The routine will return immediately unless
1738  * the current task state has been set (see set_current_state()).
1739  *
1740  * You can set the task state as follows -
1741  *
1742  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1743  * pass before the routine returns.
1744  *
1745  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1746  * delivered to the current task.
1747  *
1748  * The current task state is guaranteed to be TASK_RUNNING when this
1749  * routine returns.
1750  *
1751  * Returns 0 when the timer has expired otherwise -EINTR
1752  */
1753 int __sched schedule_hrtimeout(ktime_t *expires,
1754                                const enum hrtimer_mode mode)
1755 {
1756         return schedule_hrtimeout_range(expires, 0, mode);
1757 }
1758 EXPORT_SYMBOL_GPL(schedule_hrtimeout);