[PATCH] hrtimer: prevent overrun DoS in hrtimer_forward()
[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/irq.h>
36 #include <linux/module.h>
37 #include <linux/percpu.h>
38 #include <linux/hrtimer.h>
39 #include <linux/notifier.h>
40 #include <linux/syscalls.h>
41 #include <linux/kallsyms.h>
42 #include <linux/interrupt.h>
43 #include <linux/tick.h>
44 #include <linux/seq_file.h>
45 #include <linux/err.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
63 /**
64  * ktime_get_real - get the real (wall-) time in ktime_t format
65  *
66  * returns the time in ktime_t format
67  */
68 ktime_t ktime_get_real(void)
69 {
70         struct timespec now;
71
72         getnstimeofday(&now);
73
74         return timespec_to_ktime(now);
75 }
76
77 EXPORT_SYMBOL_GPL(ktime_get_real);
78
79 /*
80  * The timer bases:
81  *
82  * Note: If we want to add new timer bases, we have to skip the two
83  * clock ids captured by the cpu-timers. We do this by holding empty
84  * entries rather than doing math adjustment of the clock ids.
85  * This ensures that we capture erroneous accesses to these clock ids
86  * rather than moving them into the range of valid clock id's.
87  */
88 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
89 {
90
91         .clock_base =
92         {
93                 {
94                         .index = CLOCK_REALTIME,
95                         .get_time = &ktime_get_real,
96                         .resolution = KTIME_LOW_RES,
97                 },
98                 {
99                         .index = CLOCK_MONOTONIC,
100                         .get_time = &ktime_get,
101                         .resolution = KTIME_LOW_RES,
102                 },
103         }
104 };
105
106 /**
107  * ktime_get_ts - get the monotonic clock in timespec format
108  * @ts:         pointer to timespec variable
109  *
110  * The function calculates the monotonic clock from the realtime
111  * clock and the wall_to_monotonic offset and stores the result
112  * in normalized timespec format in the variable pointed to by @ts.
113  */
114 void ktime_get_ts(struct timespec *ts)
115 {
116         struct timespec tomono;
117         unsigned long seq;
118
119         do {
120                 seq = read_seqbegin(&xtime_lock);
121                 getnstimeofday(ts);
122                 tomono = wall_to_monotonic;
123
124         } while (read_seqretry(&xtime_lock, seq));
125
126         set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
127                                 ts->tv_nsec + tomono.tv_nsec);
128 }
129 EXPORT_SYMBOL_GPL(ktime_get_ts);
130
131 /*
132  * Get the coarse grained time at the softirq based on xtime and
133  * wall_to_monotonic.
134  */
135 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
136 {
137         ktime_t xtim, tomono;
138         struct timespec xts;
139         unsigned long seq;
140
141         do {
142                 seq = read_seqbegin(&xtime_lock);
143 #ifdef CONFIG_NO_HZ
144                 getnstimeofday(&xts);
145 #else
146                 xts = xtime;
147 #endif
148         } while (read_seqretry(&xtime_lock, seq));
149
150         xtim = timespec_to_ktime(xts);
151         tomono = timespec_to_ktime(wall_to_monotonic);
152         base->clock_base[CLOCK_REALTIME].softirq_time = xtim;
153         base->clock_base[CLOCK_MONOTONIC].softirq_time =
154                 ktime_add(xtim, tomono);
155 }
156
157 /*
158  * Helper function to check, whether the timer is running the callback
159  * function
160  */
161 static inline int hrtimer_callback_running(struct hrtimer *timer)
162 {
163         return timer->state & HRTIMER_STATE_CALLBACK;
164 }
165
166 /*
167  * Functions and macros which are different for UP/SMP systems are kept in a
168  * single place
169  */
170 #ifdef CONFIG_SMP
171
172 /*
173  * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
174  * means that all timers which are tied to this base via timer->base are
175  * locked, and the base itself is locked too.
176  *
177  * So __run_timers/migrate_timers can safely modify all timers which could
178  * be found on the lists/queues.
179  *
180  * When the timer's base is locked, and the timer removed from list, it is
181  * possible to set timer->base = NULL and drop the lock: the timer remains
182  * locked.
183  */
184 static
185 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
186                                              unsigned long *flags)
187 {
188         struct hrtimer_clock_base *base;
189
190         for (;;) {
191                 base = timer->base;
192                 if (likely(base != NULL)) {
193                         spin_lock_irqsave(&base->cpu_base->lock, *flags);
194                         if (likely(base == timer->base))
195                                 return base;
196                         /* The timer has migrated to another CPU: */
197                         spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
198                 }
199                 cpu_relax();
200         }
201 }
202
203 /*
204  * Switch the timer base to the current CPU when possible.
205  */
206 static inline struct hrtimer_clock_base *
207 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base)
208 {
209         struct hrtimer_clock_base *new_base;
210         struct hrtimer_cpu_base *new_cpu_base;
211
212         new_cpu_base = &__get_cpu_var(hrtimer_bases);
213         new_base = &new_cpu_base->clock_base[base->index];
214
215         if (base != new_base) {
216                 /*
217                  * We are trying to schedule the timer on the local CPU.
218                  * However we can't change timer's base while it is running,
219                  * so we keep it on the same CPU. No hassle vs. reprogramming
220                  * the event source in the high resolution case. The softirq
221                  * code will take care of this when the timer function has
222                  * completed. There is no conflict as we hold the lock until
223                  * the timer is enqueued.
224                  */
225                 if (unlikely(hrtimer_callback_running(timer)))
226                         return base;
227
228                 /* See the comment in lock_timer_base() */
229                 timer->base = NULL;
230                 spin_unlock(&base->cpu_base->lock);
231                 spin_lock(&new_base->cpu_base->lock);
232                 timer->base = new_base;
233         }
234         return new_base;
235 }
236
237 #else /* CONFIG_SMP */
238
239 static inline struct hrtimer_clock_base *
240 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
241 {
242         struct hrtimer_clock_base *base = timer->base;
243
244         spin_lock_irqsave(&base->cpu_base->lock, *flags);
245
246         return base;
247 }
248
249 # define switch_hrtimer_base(t, b)      (b)
250
251 #endif  /* !CONFIG_SMP */
252
253 /*
254  * Functions for the union type storage format of ktime_t which are
255  * too large for inlining:
256  */
257 #if BITS_PER_LONG < 64
258 # ifndef CONFIG_KTIME_SCALAR
259 /**
260  * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
261  * @kt:         addend
262  * @nsec:       the scalar nsec value to add
263  *
264  * Returns the sum of kt and nsec in ktime_t format
265  */
266 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
267 {
268         ktime_t tmp;
269
270         if (likely(nsec < NSEC_PER_SEC)) {
271                 tmp.tv64 = nsec;
272         } else {
273                 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
274
275                 tmp = ktime_set((long)nsec, rem);
276         }
277
278         return ktime_add(kt, tmp);
279 }
280 # endif /* !CONFIG_KTIME_SCALAR */
281
282 /*
283  * Divide a ktime value by a nanosecond value
284  */
285 unsigned long ktime_divns(const ktime_t kt, s64 div)
286 {
287         u64 dclc, inc, dns;
288         int sft = 0;
289
290         dclc = dns = ktime_to_ns(kt);
291         inc = div;
292         /* Make sure the divisor is less than 2^32: */
293         while (div >> 32) {
294                 sft++;
295                 div >>= 1;
296         }
297         dclc >>= sft;
298         do_div(dclc, (unsigned long) div);
299
300         return (unsigned long) dclc;
301 }
302 #endif /* BITS_PER_LONG >= 64 */
303
304 /* High resolution timer related functions */
305 #ifdef CONFIG_HIGH_RES_TIMERS
306
307 /*
308  * High resolution timer enabled ?
309  */
310 static int hrtimer_hres_enabled __read_mostly  = 1;
311
312 /*
313  * Enable / Disable high resolution mode
314  */
315 static int __init setup_hrtimer_hres(char *str)
316 {
317         if (!strcmp(str, "off"))
318                 hrtimer_hres_enabled = 0;
319         else if (!strcmp(str, "on"))
320                 hrtimer_hres_enabled = 1;
321         else
322                 return 0;
323         return 1;
324 }
325
326 __setup("highres=", setup_hrtimer_hres);
327
328 /*
329  * hrtimer_high_res_enabled - query, if the highres mode is enabled
330  */
331 static inline int hrtimer_is_hres_enabled(void)
332 {
333         return hrtimer_hres_enabled;
334 }
335
336 /*
337  * Is the high resolution mode active ?
338  */
339 static inline int hrtimer_hres_active(void)
340 {
341         return __get_cpu_var(hrtimer_bases).hres_active;
342 }
343
344 /*
345  * Reprogram the event source with checking both queues for the
346  * next event
347  * Called with interrupts disabled and base->lock held
348  */
349 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
350 {
351         int i;
352         struct hrtimer_clock_base *base = cpu_base->clock_base;
353         ktime_t expires;
354
355         cpu_base->expires_next.tv64 = KTIME_MAX;
356
357         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
358                 struct hrtimer *timer;
359
360                 if (!base->first)
361                         continue;
362                 timer = rb_entry(base->first, struct hrtimer, node);
363                 expires = ktime_sub(timer->expires, base->offset);
364                 if (expires.tv64 < cpu_base->expires_next.tv64)
365                         cpu_base->expires_next = expires;
366         }
367
368         if (cpu_base->expires_next.tv64 != KTIME_MAX)
369                 tick_program_event(cpu_base->expires_next, 1);
370 }
371
372 /*
373  * Shared reprogramming for clock_realtime and clock_monotonic
374  *
375  * When a timer is enqueued and expires earlier than the already enqueued
376  * timers, we have to check, whether it expires earlier than the timer for
377  * which the clock event device was armed.
378  *
379  * Called with interrupts disabled and base->cpu_base.lock held
380  */
381 static int hrtimer_reprogram(struct hrtimer *timer,
382                              struct hrtimer_clock_base *base)
383 {
384         ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
385         ktime_t expires = ktime_sub(timer->expires, base->offset);
386         int res;
387
388         /*
389          * When the callback is running, we do not reprogram the clock event
390          * device. The timer callback is either running on a different CPU or
391          * the callback is executed in the hrtimer_interupt context. The
392          * reprogramming is handled either by the softirq, which called the
393          * callback or at the end of the hrtimer_interrupt.
394          */
395         if (hrtimer_callback_running(timer))
396                 return 0;
397
398         if (expires.tv64 >= expires_next->tv64)
399                 return 0;
400
401         /*
402          * Clockevents returns -ETIME, when the event was in the past.
403          */
404         res = tick_program_event(expires, 0);
405         if (!IS_ERR_VALUE(res))
406                 *expires_next = expires;
407         return res;
408 }
409
410
411 /*
412  * Retrigger next event is called after clock was set
413  *
414  * Called with interrupts disabled via on_each_cpu()
415  */
416 static void retrigger_next_event(void *arg)
417 {
418         struct hrtimer_cpu_base *base;
419         struct timespec realtime_offset;
420         unsigned long seq;
421
422         if (!hrtimer_hres_active())
423                 return;
424
425         do {
426                 seq = read_seqbegin(&xtime_lock);
427                 set_normalized_timespec(&realtime_offset,
428                                         -wall_to_monotonic.tv_sec,
429                                         -wall_to_monotonic.tv_nsec);
430         } while (read_seqretry(&xtime_lock, seq));
431
432         base = &__get_cpu_var(hrtimer_bases);
433
434         /* Adjust CLOCK_REALTIME offset */
435         spin_lock(&base->lock);
436         base->clock_base[CLOCK_REALTIME].offset =
437                 timespec_to_ktime(realtime_offset);
438
439         hrtimer_force_reprogram(base);
440         spin_unlock(&base->lock);
441 }
442
443 /*
444  * Clock realtime was set
445  *
446  * Change the offset of the realtime clock vs. the monotonic
447  * clock.
448  *
449  * We might have to reprogram the high resolution timer interrupt. On
450  * SMP we call the architecture specific code to retrigger _all_ high
451  * resolution timer interrupts. On UP we just disable interrupts and
452  * call the high resolution interrupt code.
453  */
454 void clock_was_set(void)
455 {
456         /* Retrigger the CPU local events everywhere */
457         on_each_cpu(retrigger_next_event, NULL, 0, 1);
458 }
459
460 /*
461  * Check, whether the timer is on the callback pending list
462  */
463 static inline int hrtimer_cb_pending(const struct hrtimer *timer)
464 {
465         return timer->state & HRTIMER_STATE_PENDING;
466 }
467
468 /*
469  * Remove a timer from the callback pending list
470  */
471 static inline void hrtimer_remove_cb_pending(struct hrtimer *timer)
472 {
473         list_del_init(&timer->cb_entry);
474 }
475
476 /*
477  * Initialize the high resolution related parts of cpu_base
478  */
479 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
480 {
481         base->expires_next.tv64 = KTIME_MAX;
482         base->hres_active = 0;
483         INIT_LIST_HEAD(&base->cb_pending);
484 }
485
486 /*
487  * Initialize the high resolution related parts of a hrtimer
488  */
489 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
490 {
491         INIT_LIST_HEAD(&timer->cb_entry);
492 }
493
494 /*
495  * When High resolution timers are active, try to reprogram. Note, that in case
496  * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
497  * check happens. The timer gets enqueued into the rbtree. The reprogramming
498  * and expiry check is done in the hrtimer_interrupt or in the softirq.
499  */
500 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
501                                             struct hrtimer_clock_base *base)
502 {
503         if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
504
505                 /* Timer is expired, act upon the callback mode */
506                 switch(timer->cb_mode) {
507                 case HRTIMER_CB_IRQSAFE_NO_RESTART:
508                         /*
509                          * We can call the callback from here. No restart
510                          * happens, so no danger of recursion
511                          */
512                         BUG_ON(timer->function(timer) != HRTIMER_NORESTART);
513                         return 1;
514                 case HRTIMER_CB_IRQSAFE_NO_SOFTIRQ:
515                         /*
516                          * This is solely for the sched tick emulation with
517                          * dynamic tick support to ensure that we do not
518                          * restart the tick right on the edge and end up with
519                          * the tick timer in the softirq ! The calling site
520                          * takes care of this.
521                          */
522                         return 1;
523                 case HRTIMER_CB_IRQSAFE:
524                 case HRTIMER_CB_SOFTIRQ:
525                         /*
526                          * Move everything else into the softirq pending list !
527                          */
528                         list_add_tail(&timer->cb_entry,
529                                       &base->cpu_base->cb_pending);
530                         timer->state = HRTIMER_STATE_PENDING;
531                         raise_softirq(HRTIMER_SOFTIRQ);
532                         return 1;
533                 default:
534                         BUG();
535                 }
536         }
537         return 0;
538 }
539
540 /*
541  * Switch to high resolution mode
542  */
543 static int hrtimer_switch_to_hres(void)
544 {
545         struct hrtimer_cpu_base *base = &__get_cpu_var(hrtimer_bases);
546         unsigned long flags;
547
548         if (base->hres_active)
549                 return 1;
550
551         local_irq_save(flags);
552
553         if (tick_init_highres()) {
554                 local_irq_restore(flags);
555                 return 0;
556         }
557         base->hres_active = 1;
558         base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
559         base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
560
561         tick_setup_sched_timer();
562
563         /* "Retrigger" the interrupt to get things going */
564         retrigger_next_event(NULL);
565         local_irq_restore(flags);
566         printk(KERN_INFO "Switched to high resolution mode on CPU %d\n",
567                smp_processor_id());
568         return 1;
569 }
570
571 #else
572
573 static inline int hrtimer_hres_active(void) { return 0; }
574 static inline int hrtimer_is_hres_enabled(void) { return 0; }
575 static inline int hrtimer_switch_to_hres(void) { return 0; }
576 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
577 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
578                                             struct hrtimer_clock_base *base)
579 {
580         return 0;
581 }
582 static inline int hrtimer_cb_pending(struct hrtimer *timer) { return 0; }
583 static inline void hrtimer_remove_cb_pending(struct hrtimer *timer) { }
584 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
585 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
586
587 #endif /* CONFIG_HIGH_RES_TIMERS */
588
589 #ifdef CONFIG_TIMER_STATS
590 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
591 {
592         if (timer->start_site)
593                 return;
594
595         timer->start_site = addr;
596         memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
597         timer->start_pid = current->pid;
598 }
599 #endif
600
601 /*
602  * Counterpart to lock_timer_base above:
603  */
604 static inline
605 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
606 {
607         spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
608 }
609
610 /**
611  * hrtimer_forward - forward the timer expiry
612  * @timer:      hrtimer to forward
613  * @now:        forward past this time
614  * @interval:   the interval to forward
615  *
616  * Forward the timer expiry so it will expire in the future.
617  * Returns the number of overruns.
618  */
619 unsigned long
620 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
621 {
622         unsigned long orun = 1;
623         ktime_t delta;
624
625         delta = ktime_sub(now, timer->expires);
626
627         if (delta.tv64 < 0)
628                 return 0;
629
630         if (interval.tv64 < timer->base->resolution.tv64)
631                 interval.tv64 = timer->base->resolution.tv64;
632
633         if (unlikely(delta.tv64 >= interval.tv64)) {
634                 s64 incr = ktime_to_ns(interval);
635
636                 orun = ktime_divns(delta, incr);
637                 timer->expires = ktime_add_ns(timer->expires, incr * orun);
638                 if (timer->expires.tv64 > now.tv64)
639                         return orun;
640                 /*
641                  * This (and the ktime_add() below) is the
642                  * correction for exact:
643                  */
644                 orun++;
645         }
646         timer->expires = ktime_add(timer->expires, interval);
647         /*
648          * Make sure, that the result did not wrap with a very large
649          * interval.
650          */
651         if (timer->expires.tv64 < 0)
652                 timer->expires = ktime_set(KTIME_SEC_MAX, 0);
653
654         return orun;
655 }
656
657 /*
658  * enqueue_hrtimer - internal function to (re)start a timer
659  *
660  * The timer is inserted in expiry order. Insertion into the
661  * red black tree is O(log(n)). Must hold the base lock.
662  */
663 static void enqueue_hrtimer(struct hrtimer *timer,
664                             struct hrtimer_clock_base *base, int reprogram)
665 {
666         struct rb_node **link = &base->active.rb_node;
667         struct rb_node *parent = NULL;
668         struct hrtimer *entry;
669
670         /*
671          * Find the right place in the rbtree:
672          */
673         while (*link) {
674                 parent = *link;
675                 entry = rb_entry(parent, struct hrtimer, node);
676                 /*
677                  * We dont care about collisions. Nodes with
678                  * the same expiry time stay together.
679                  */
680                 if (timer->expires.tv64 < entry->expires.tv64)
681                         link = &(*link)->rb_left;
682                 else
683                         link = &(*link)->rb_right;
684         }
685
686         /*
687          * Insert the timer to the rbtree and check whether it
688          * replaces the first pending timer
689          */
690         if (!base->first || timer->expires.tv64 <
691             rb_entry(base->first, struct hrtimer, node)->expires.tv64) {
692                 /*
693                  * Reprogram the clock event device. When the timer is already
694                  * expired hrtimer_enqueue_reprogram has either called the
695                  * callback or added it to the pending list and raised the
696                  * softirq.
697                  *
698                  * This is a NOP for !HIGHRES
699                  */
700                 if (reprogram && hrtimer_enqueue_reprogram(timer, base))
701                         return;
702
703                 base->first = &timer->node;
704         }
705
706         rb_link_node(&timer->node, parent, link);
707         rb_insert_color(&timer->node, &base->active);
708         /*
709          * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
710          * state of a possibly running callback.
711          */
712         timer->state |= HRTIMER_STATE_ENQUEUED;
713 }
714
715 /*
716  * __remove_hrtimer - internal function to remove a timer
717  *
718  * Caller must hold the base lock.
719  *
720  * High resolution timer mode reprograms the clock event device when the
721  * timer is the one which expires next. The caller can disable this by setting
722  * reprogram to zero. This is useful, when the context does a reprogramming
723  * anyway (e.g. timer interrupt)
724  */
725 static void __remove_hrtimer(struct hrtimer *timer,
726                              struct hrtimer_clock_base *base,
727                              unsigned long newstate, int reprogram)
728 {
729         /* High res. callback list. NOP for !HIGHRES */
730         if (hrtimer_cb_pending(timer))
731                 hrtimer_remove_cb_pending(timer);
732         else {
733                 /*
734                  * Remove the timer from the rbtree and replace the
735                  * first entry pointer if necessary.
736                  */
737                 if (base->first == &timer->node) {
738                         base->first = rb_next(&timer->node);
739                         /* Reprogram the clock event device. if enabled */
740                         if (reprogram && hrtimer_hres_active())
741                                 hrtimer_force_reprogram(base->cpu_base);
742                 }
743                 rb_erase(&timer->node, &base->active);
744         }
745         timer->state = newstate;
746 }
747
748 /*
749  * remove hrtimer, called with base lock held
750  */
751 static inline int
752 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
753 {
754         if (hrtimer_is_queued(timer)) {
755                 int reprogram;
756
757                 /*
758                  * Remove the timer and force reprogramming when high
759                  * resolution mode is active and the timer is on the current
760                  * CPU. If we remove a timer on another CPU, reprogramming is
761                  * skipped. The interrupt event on this CPU is fired and
762                  * reprogramming happens in the interrupt handler. This is a
763                  * rare case and less expensive than a smp call.
764                  */
765                 timer_stats_hrtimer_clear_start_info(timer);
766                 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
767                 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
768                                  reprogram);
769                 return 1;
770         }
771         return 0;
772 }
773
774 /**
775  * hrtimer_start - (re)start an relative timer on the current CPU
776  * @timer:      the timer to be added
777  * @tim:        expiry time
778  * @mode:       expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
779  *
780  * Returns:
781  *  0 on success
782  *  1 when the timer was active
783  */
784 int
785 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
786 {
787         struct hrtimer_clock_base *base, *new_base;
788         unsigned long flags;
789         int ret;
790
791         base = lock_hrtimer_base(timer, &flags);
792
793         /* Remove an active timer from the queue: */
794         ret = remove_hrtimer(timer, base);
795
796         /* Switch the timer base, if necessary: */
797         new_base = switch_hrtimer_base(timer, base);
798
799         if (mode == HRTIMER_MODE_REL) {
800                 tim = ktime_add(tim, new_base->get_time());
801                 /*
802                  * CONFIG_TIME_LOW_RES is a temporary way for architectures
803                  * to signal that they simply return xtime in
804                  * do_gettimeoffset(). In this case we want to round up by
805                  * resolution when starting a relative timer, to avoid short
806                  * timeouts. This will go away with the GTOD framework.
807                  */
808 #ifdef CONFIG_TIME_LOW_RES
809                 tim = ktime_add(tim, base->resolution);
810 #endif
811         }
812         timer->expires = tim;
813
814         timer_stats_hrtimer_set_start_info(timer);
815
816         enqueue_hrtimer(timer, new_base, base == new_base);
817
818         unlock_hrtimer_base(timer, &flags);
819
820         return ret;
821 }
822 EXPORT_SYMBOL_GPL(hrtimer_start);
823
824 /**
825  * hrtimer_try_to_cancel - try to deactivate a timer
826  * @timer:      hrtimer to stop
827  *
828  * Returns:
829  *  0 when the timer was not active
830  *  1 when the timer was active
831  * -1 when the timer is currently excuting the callback function and
832  *    cannot be stopped
833  */
834 int hrtimer_try_to_cancel(struct hrtimer *timer)
835 {
836         struct hrtimer_clock_base *base;
837         unsigned long flags;
838         int ret = -1;
839
840         base = lock_hrtimer_base(timer, &flags);
841
842         if (!hrtimer_callback_running(timer))
843                 ret = remove_hrtimer(timer, base);
844
845         unlock_hrtimer_base(timer, &flags);
846
847         return ret;
848
849 }
850 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
851
852 /**
853  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
854  * @timer:      the timer to be cancelled
855  *
856  * Returns:
857  *  0 when the timer was not active
858  *  1 when the timer was active
859  */
860 int hrtimer_cancel(struct hrtimer *timer)
861 {
862         for (;;) {
863                 int ret = hrtimer_try_to_cancel(timer);
864
865                 if (ret >= 0)
866                         return ret;
867                 cpu_relax();
868         }
869 }
870 EXPORT_SYMBOL_GPL(hrtimer_cancel);
871
872 /**
873  * hrtimer_get_remaining - get remaining time for the timer
874  * @timer:      the timer to read
875  */
876 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
877 {
878         struct hrtimer_clock_base *base;
879         unsigned long flags;
880         ktime_t rem;
881
882         base = lock_hrtimer_base(timer, &flags);
883         rem = ktime_sub(timer->expires, base->get_time());
884         unlock_hrtimer_base(timer, &flags);
885
886         return rem;
887 }
888 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
889
890 #if defined(CONFIG_NO_IDLE_HZ) || defined(CONFIG_NO_HZ)
891 /**
892  * hrtimer_get_next_event - get the time until next expiry event
893  *
894  * Returns the delta to the next expiry event or KTIME_MAX if no timer
895  * is pending.
896  */
897 ktime_t hrtimer_get_next_event(void)
898 {
899         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
900         struct hrtimer_clock_base *base = cpu_base->clock_base;
901         ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
902         unsigned long flags;
903         int i;
904
905         spin_lock_irqsave(&cpu_base->lock, flags);
906
907         if (!hrtimer_hres_active()) {
908                 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
909                         struct hrtimer *timer;
910
911                         if (!base->first)
912                                 continue;
913
914                         timer = rb_entry(base->first, struct hrtimer, node);
915                         delta.tv64 = timer->expires.tv64;
916                         delta = ktime_sub(delta, base->get_time());
917                         if (delta.tv64 < mindelta.tv64)
918                                 mindelta.tv64 = delta.tv64;
919                 }
920         }
921
922         spin_unlock_irqrestore(&cpu_base->lock, flags);
923
924         if (mindelta.tv64 < 0)
925                 mindelta.tv64 = 0;
926         return mindelta;
927 }
928 #endif
929
930 /**
931  * hrtimer_init - initialize a timer to the given clock
932  * @timer:      the timer to be initialized
933  * @clock_id:   the clock to be used
934  * @mode:       timer mode abs/rel
935  */
936 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
937                   enum hrtimer_mode mode)
938 {
939         struct hrtimer_cpu_base *cpu_base;
940
941         memset(timer, 0, sizeof(struct hrtimer));
942
943         cpu_base = &__raw_get_cpu_var(hrtimer_bases);
944
945         if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
946                 clock_id = CLOCK_MONOTONIC;
947
948         timer->base = &cpu_base->clock_base[clock_id];
949         hrtimer_init_timer_hres(timer);
950
951 #ifdef CONFIG_TIMER_STATS
952         timer->start_site = NULL;
953         timer->start_pid = -1;
954         memset(timer->start_comm, 0, TASK_COMM_LEN);
955 #endif
956 }
957 EXPORT_SYMBOL_GPL(hrtimer_init);
958
959 /**
960  * hrtimer_get_res - get the timer resolution for a clock
961  * @which_clock: which clock to query
962  * @tp:          pointer to timespec variable to store the resolution
963  *
964  * Store the resolution of the clock selected by @which_clock in the
965  * variable pointed to by @tp.
966  */
967 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
968 {
969         struct hrtimer_cpu_base *cpu_base;
970
971         cpu_base = &__raw_get_cpu_var(hrtimer_bases);
972         *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
973
974         return 0;
975 }
976 EXPORT_SYMBOL_GPL(hrtimer_get_res);
977
978 #ifdef CONFIG_HIGH_RES_TIMERS
979
980 /*
981  * High resolution timer interrupt
982  * Called with interrupts disabled
983  */
984 void hrtimer_interrupt(struct clock_event_device *dev)
985 {
986         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
987         struct hrtimer_clock_base *base;
988         ktime_t expires_next, now;
989         int i, raise = 0;
990
991         BUG_ON(!cpu_base->hres_active);
992         cpu_base->nr_events++;
993         dev->next_event.tv64 = KTIME_MAX;
994
995  retry:
996         now = ktime_get();
997
998         expires_next.tv64 = KTIME_MAX;
999
1000         base = cpu_base->clock_base;
1001
1002         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1003                 ktime_t basenow;
1004                 struct rb_node *node;
1005
1006                 spin_lock(&cpu_base->lock);
1007
1008                 basenow = ktime_add(now, base->offset);
1009
1010                 while ((node = base->first)) {
1011                         struct hrtimer *timer;
1012
1013                         timer = rb_entry(node, struct hrtimer, node);
1014
1015                         if (basenow.tv64 < timer->expires.tv64) {
1016                                 ktime_t expires;
1017
1018                                 expires = ktime_sub(timer->expires,
1019                                                     base->offset);
1020                                 if (expires.tv64 < expires_next.tv64)
1021                                         expires_next = expires;
1022                                 break;
1023                         }
1024
1025                         /* Move softirq callbacks to the pending list */
1026                         if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1027                                 __remove_hrtimer(timer, base,
1028                                                  HRTIMER_STATE_PENDING, 0);
1029                                 list_add_tail(&timer->cb_entry,
1030                                               &base->cpu_base->cb_pending);
1031                                 raise = 1;
1032                                 continue;
1033                         }
1034
1035                         __remove_hrtimer(timer, base,
1036                                          HRTIMER_STATE_CALLBACK, 0);
1037                         timer_stats_account_hrtimer(timer);
1038
1039                         /*
1040                          * Note: We clear the CALLBACK bit after
1041                          * enqueue_hrtimer to avoid reprogramming of
1042                          * the event hardware. This happens at the end
1043                          * of this function anyway.
1044                          */
1045                         if (timer->function(timer) != HRTIMER_NORESTART) {
1046                                 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1047                                 enqueue_hrtimer(timer, base, 0);
1048                         }
1049                         timer->state &= ~HRTIMER_STATE_CALLBACK;
1050                 }
1051                 spin_unlock(&cpu_base->lock);
1052                 base++;
1053         }
1054
1055         cpu_base->expires_next = expires_next;
1056
1057         /* Reprogramming necessary ? */
1058         if (expires_next.tv64 != KTIME_MAX) {
1059                 if (tick_program_event(expires_next, 0))
1060                         goto retry;
1061         }
1062
1063         /* Raise softirq ? */
1064         if (raise)
1065                 raise_softirq(HRTIMER_SOFTIRQ);
1066 }
1067
1068 static void run_hrtimer_softirq(struct softirq_action *h)
1069 {
1070         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1071
1072         spin_lock_irq(&cpu_base->lock);
1073
1074         while (!list_empty(&cpu_base->cb_pending)) {
1075                 enum hrtimer_restart (*fn)(struct hrtimer *);
1076                 struct hrtimer *timer;
1077                 int restart;
1078
1079                 timer = list_entry(cpu_base->cb_pending.next,
1080                                    struct hrtimer, cb_entry);
1081
1082                 timer_stats_account_hrtimer(timer);
1083
1084                 fn = timer->function;
1085                 __remove_hrtimer(timer, timer->base, HRTIMER_STATE_CALLBACK, 0);
1086                 spin_unlock_irq(&cpu_base->lock);
1087
1088                 restart = fn(timer);
1089
1090                 spin_lock_irq(&cpu_base->lock);
1091
1092                 timer->state &= ~HRTIMER_STATE_CALLBACK;
1093                 if (restart == HRTIMER_RESTART) {
1094                         BUG_ON(hrtimer_active(timer));
1095                         /*
1096                          * Enqueue the timer, allow reprogramming of the event
1097                          * device
1098                          */
1099                         enqueue_hrtimer(timer, timer->base, 1);
1100                 } else if (hrtimer_active(timer)) {
1101                         /*
1102                          * If the timer was rearmed on another CPU, reprogram
1103                          * the event device.
1104                          */
1105                         if (timer->base->first == &timer->node)
1106                                 hrtimer_reprogram(timer, timer->base);
1107                 }
1108         }
1109         spin_unlock_irq(&cpu_base->lock);
1110 }
1111
1112 #endif  /* CONFIG_HIGH_RES_TIMERS */
1113
1114 /*
1115  * Expire the per base hrtimer-queue:
1116  */
1117 static inline void run_hrtimer_queue(struct hrtimer_cpu_base *cpu_base,
1118                                      int index)
1119 {
1120         struct rb_node *node;
1121         struct hrtimer_clock_base *base = &cpu_base->clock_base[index];
1122
1123         if (!base->first)
1124                 return;
1125
1126         if (base->get_softirq_time)
1127                 base->softirq_time = base->get_softirq_time();
1128
1129         spin_lock_irq(&cpu_base->lock);
1130
1131         while ((node = base->first)) {
1132                 struct hrtimer *timer;
1133                 enum hrtimer_restart (*fn)(struct hrtimer *);
1134                 int restart;
1135
1136                 timer = rb_entry(node, struct hrtimer, node);
1137                 if (base->softirq_time.tv64 <= timer->expires.tv64)
1138                         break;
1139
1140 #ifdef CONFIG_HIGH_RES_TIMERS
1141                 WARN_ON_ONCE(timer->cb_mode == HRTIMER_CB_IRQSAFE_NO_SOFTIRQ);
1142 #endif
1143                 timer_stats_account_hrtimer(timer);
1144
1145                 fn = timer->function;
1146                 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1147                 spin_unlock_irq(&cpu_base->lock);
1148
1149                 restart = fn(timer);
1150
1151                 spin_lock_irq(&cpu_base->lock);
1152
1153                 timer->state &= ~HRTIMER_STATE_CALLBACK;
1154                 if (restart != HRTIMER_NORESTART) {
1155                         BUG_ON(hrtimer_active(timer));
1156                         enqueue_hrtimer(timer, base, 0);
1157                 }
1158         }
1159         spin_unlock_irq(&cpu_base->lock);
1160 }
1161
1162 /*
1163  * Called from timer softirq every jiffy, expire hrtimers:
1164  *
1165  * For HRT its the fall back code to run the softirq in the timer
1166  * softirq context in case the hrtimer initialization failed or has
1167  * not been done yet.
1168  */
1169 void hrtimer_run_queues(void)
1170 {
1171         struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1172         int i;
1173
1174         if (hrtimer_hres_active())
1175                 return;
1176
1177         /*
1178          * This _is_ ugly: We have to check in the softirq context,
1179          * whether we can switch to highres and / or nohz mode. The
1180          * clocksource switch happens in the timer interrupt with
1181          * xtime_lock held. Notification from there only sets the
1182          * check bit in the tick_oneshot code, otherwise we might
1183          * deadlock vs. xtime_lock.
1184          */
1185         if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1186                 if (hrtimer_switch_to_hres())
1187                         return;
1188
1189         hrtimer_get_softirq_time(cpu_base);
1190
1191         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1192                 run_hrtimer_queue(cpu_base, i);
1193 }
1194
1195 /*
1196  * Sleep related functions:
1197  */
1198 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1199 {
1200         struct hrtimer_sleeper *t =
1201                 container_of(timer, struct hrtimer_sleeper, timer);
1202         struct task_struct *task = t->task;
1203
1204         t->task = NULL;
1205         if (task)
1206                 wake_up_process(task);
1207
1208         return HRTIMER_NORESTART;
1209 }
1210
1211 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1212 {
1213         sl->timer.function = hrtimer_wakeup;
1214         sl->task = task;
1215 #ifdef CONFIG_HIGH_RES_TIMERS
1216         sl->timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_RESTART;
1217 #endif
1218 }
1219
1220 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1221 {
1222         hrtimer_init_sleeper(t, current);
1223
1224         do {
1225                 set_current_state(TASK_INTERRUPTIBLE);
1226                 hrtimer_start(&t->timer, t->timer.expires, mode);
1227
1228                 if (likely(t->task))
1229                         schedule();
1230
1231                 hrtimer_cancel(&t->timer);
1232                 mode = HRTIMER_MODE_ABS;
1233
1234         } while (t->task && !signal_pending(current));
1235
1236         return t->task == NULL;
1237 }
1238
1239 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1240 {
1241         struct hrtimer_sleeper t;
1242         struct timespec __user *rmtp;
1243         struct timespec tu;
1244         ktime_t time;
1245
1246         restart->fn = do_no_restart_syscall;
1247
1248         hrtimer_init(&t.timer, restart->arg0, HRTIMER_MODE_ABS);
1249         t.timer.expires.tv64 = ((u64)restart->arg3 << 32) | (u64) restart->arg2;
1250
1251         if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1252                 return 0;
1253
1254         rmtp = (struct timespec __user *) restart->arg1;
1255         if (rmtp) {
1256                 time = ktime_sub(t.timer.expires, t.timer.base->get_time());
1257                 if (time.tv64 <= 0)
1258                         return 0;
1259                 tu = ktime_to_timespec(time);
1260                 if (copy_to_user(rmtp, &tu, sizeof(tu)))
1261                         return -EFAULT;
1262         }
1263
1264         restart->fn = hrtimer_nanosleep_restart;
1265
1266         /* The other values in restart are already filled in */
1267         return -ERESTART_RESTARTBLOCK;
1268 }
1269
1270 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1271                        const enum hrtimer_mode mode, const clockid_t clockid)
1272 {
1273         struct restart_block *restart;
1274         struct hrtimer_sleeper t;
1275         struct timespec tu;
1276         ktime_t rem;
1277
1278         hrtimer_init(&t.timer, clockid, mode);
1279         t.timer.expires = timespec_to_ktime(*rqtp);
1280         if (do_nanosleep(&t, mode))
1281                 return 0;
1282
1283         /* Absolute timers do not update the rmtp value and restart: */
1284         if (mode == HRTIMER_MODE_ABS)
1285                 return -ERESTARTNOHAND;
1286
1287         if (rmtp) {
1288                 rem = ktime_sub(t.timer.expires, t.timer.base->get_time());
1289                 if (rem.tv64 <= 0)
1290                         return 0;
1291                 tu = ktime_to_timespec(rem);
1292                 if (copy_to_user(rmtp, &tu, sizeof(tu)))
1293                         return -EFAULT;
1294         }
1295
1296         restart = &current_thread_info()->restart_block;
1297         restart->fn = hrtimer_nanosleep_restart;
1298         restart->arg0 = (unsigned long) t.timer.base->index;
1299         restart->arg1 = (unsigned long) rmtp;
1300         restart->arg2 = t.timer.expires.tv64 & 0xFFFFFFFF;
1301         restart->arg3 = t.timer.expires.tv64 >> 32;
1302
1303         return -ERESTART_RESTARTBLOCK;
1304 }
1305
1306 asmlinkage long
1307 sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1308 {
1309         struct timespec tu;
1310
1311         if (copy_from_user(&tu, rqtp, sizeof(tu)))
1312                 return -EFAULT;
1313
1314         if (!timespec_valid(&tu))
1315                 return -EINVAL;
1316
1317         return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1318 }
1319
1320 /*
1321  * Functions related to boot-time initialization:
1322  */
1323 static void __devinit init_hrtimers_cpu(int cpu)
1324 {
1325         struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1326         int i;
1327
1328         spin_lock_init(&cpu_base->lock);
1329         lockdep_set_class(&cpu_base->lock, &cpu_base->lock_key);
1330
1331         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1332                 cpu_base->clock_base[i].cpu_base = cpu_base;
1333
1334         hrtimer_init_hres(cpu_base);
1335 }
1336
1337 #ifdef CONFIG_HOTPLUG_CPU
1338
1339 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1340                                 struct hrtimer_clock_base *new_base)
1341 {
1342         struct hrtimer *timer;
1343         struct rb_node *node;
1344
1345         while ((node = rb_first(&old_base->active))) {
1346                 timer = rb_entry(node, struct hrtimer, node);
1347                 BUG_ON(hrtimer_callback_running(timer));
1348                 __remove_hrtimer(timer, old_base, HRTIMER_STATE_INACTIVE, 0);
1349                 timer->base = new_base;
1350                 /*
1351                  * Enqueue the timer. Allow reprogramming of the event device
1352                  */
1353                 enqueue_hrtimer(timer, new_base, 1);
1354         }
1355 }
1356
1357 static void migrate_hrtimers(int cpu)
1358 {
1359         struct hrtimer_cpu_base *old_base, *new_base;
1360         int i;
1361
1362         BUG_ON(cpu_online(cpu));
1363         old_base = &per_cpu(hrtimer_bases, cpu);
1364         new_base = &get_cpu_var(hrtimer_bases);
1365
1366         tick_cancel_sched_timer(cpu);
1367
1368         local_irq_disable();
1369         double_spin_lock(&new_base->lock, &old_base->lock,
1370                          smp_processor_id() < cpu);
1371
1372         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1373                 migrate_hrtimer_list(&old_base->clock_base[i],
1374                                      &new_base->clock_base[i]);
1375         }
1376
1377         double_spin_unlock(&new_base->lock, &old_base->lock,
1378                            smp_processor_id() < cpu);
1379         local_irq_enable();
1380         put_cpu_var(hrtimer_bases);
1381 }
1382 #endif /* CONFIG_HOTPLUG_CPU */
1383
1384 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1385                                         unsigned long action, void *hcpu)
1386 {
1387         long cpu = (long)hcpu;
1388
1389         switch (action) {
1390
1391         case CPU_UP_PREPARE:
1392                 init_hrtimers_cpu(cpu);
1393                 break;
1394
1395 #ifdef CONFIG_HOTPLUG_CPU
1396         case CPU_DEAD:
1397                 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &cpu);
1398                 migrate_hrtimers(cpu);
1399                 break;
1400 #endif
1401
1402         default:
1403                 break;
1404         }
1405
1406         return NOTIFY_OK;
1407 }
1408
1409 static struct notifier_block __cpuinitdata hrtimers_nb = {
1410         .notifier_call = hrtimer_cpu_notify,
1411 };
1412
1413 void __init hrtimers_init(void)
1414 {
1415         hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1416                           (void *)(long)smp_processor_id());
1417         register_cpu_notifier(&hrtimers_nb);
1418 #ifdef CONFIG_HIGH_RES_TIMERS
1419         open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq, NULL);
1420 #endif
1421 }
1422