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