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