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