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