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