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