2 * linux/kernel/hrtimer.c
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
8 * High-resolution kernel timers
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.
14 * These timers are currently used for:
18 * - precise in-kernel timing
20 * Started by: Thomas Gleixner and Ingo Molnar
23 * based on kernel/timer.c
25 * Help, testing, suggestions, bugfixes, improvements were
28 * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
31 * For licencing details see kernel-base/COPYING
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>
47 #include <asm/uaccess.h>
50 * ktime_get - get the monotonic time in ktime_t format
52 * returns the time in ktime_t format
54 ktime_t ktime_get(void)
60 return timespec_to_ktime(now);
62 EXPORT_SYMBOL_GPL(ktime_get);
65 * ktime_get_real - get the real (wall-) time in ktime_t format
67 * returns the time in ktime_t format
69 ktime_t ktime_get_real(void)
75 return timespec_to_ktime(now);
78 EXPORT_SYMBOL_GPL(ktime_get_real);
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.
89 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
95 .index = CLOCK_REALTIME,
96 .get_time = &ktime_get_real,
97 .resolution = KTIME_LOW_RES,
100 .index = CLOCK_MONOTONIC,
101 .get_time = &ktime_get,
102 .resolution = KTIME_LOW_RES,
108 * ktime_get_ts - get the monotonic clock in timespec format
109 * @ts: pointer to timespec variable
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.
115 void ktime_get_ts(struct timespec *ts)
117 struct timespec tomono;
121 seq = read_seqbegin(&xtime_lock);
123 tomono = wall_to_monotonic;
125 } while (read_seqretry(&xtime_lock, seq));
127 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
128 ts->tv_nsec + tomono.tv_nsec);
130 EXPORT_SYMBOL_GPL(ktime_get_ts);
133 * Get the coarse grained time at the softirq based on xtime and
136 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
138 ktime_t xtim, tomono;
139 struct timespec xts, tom;
143 seq = read_seqbegin(&xtime_lock);
144 xts = current_kernel_time();
145 tom = wall_to_monotonic;
146 } while (read_seqretry(&xtime_lock, seq));
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);
156 * Functions and macros which are different for UP/SMP systems are kept in a
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.
166 * So __run_timers/migrate_timers can safely modify all timers which could
167 * be found on the lists/queues.
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
174 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
175 unsigned long *flags)
177 struct hrtimer_clock_base *base;
181 if (likely(base != NULL)) {
182 spin_lock_irqsave(&base->cpu_base->lock, *flags);
183 if (likely(base == timer->base))
185 /* The timer has migrated to another CPU: */
186 spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
193 * Switch the timer base to the current CPU when possible.
195 static inline struct hrtimer_clock_base *
196 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
199 struct hrtimer_clock_base *new_base;
200 struct hrtimer_cpu_base *new_cpu_base;
202 new_cpu_base = &__get_cpu_var(hrtimer_bases);
203 new_base = &new_cpu_base->clock_base[base->index];
205 if (base != new_base) {
207 * We are trying to schedule the timer on the local CPU.
208 * However we can't change timer's base while it is running,
209 * so we keep it on the same CPU. No hassle vs. reprogramming
210 * the event source in the high resolution case. The softirq
211 * code will take care of this when the timer function has
212 * completed. There is no conflict as we hold the lock until
213 * the timer is enqueued.
215 if (unlikely(hrtimer_callback_running(timer)))
218 /* See the comment in lock_timer_base() */
220 spin_unlock(&base->cpu_base->lock);
221 spin_lock(&new_base->cpu_base->lock);
222 timer->base = new_base;
227 #else /* CONFIG_SMP */
229 static inline struct hrtimer_clock_base *
230 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
232 struct hrtimer_clock_base *base = timer->base;
234 spin_lock_irqsave(&base->cpu_base->lock, *flags);
239 # define switch_hrtimer_base(t, b) (b)
241 #endif /* !CONFIG_SMP */
244 * Functions for the union type storage format of ktime_t which are
245 * too large for inlining:
247 #if BITS_PER_LONG < 64
248 # ifndef CONFIG_KTIME_SCALAR
250 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
252 * @nsec: the scalar nsec value to add
254 * Returns the sum of kt and nsec in ktime_t format
256 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
260 if (likely(nsec < NSEC_PER_SEC)) {
263 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
265 tmp = ktime_set((long)nsec, rem);
268 return ktime_add(kt, tmp);
271 EXPORT_SYMBOL_GPL(ktime_add_ns);
274 * ktime_sub_ns - Subtract a scalar nanoseconds value from a ktime_t variable
276 * @nsec: the scalar nsec value to subtract
278 * Returns the subtraction of @nsec from @kt in ktime_t format
280 ktime_t ktime_sub_ns(const ktime_t kt, u64 nsec)
284 if (likely(nsec < NSEC_PER_SEC)) {
287 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
289 tmp = ktime_set((long)nsec, rem);
292 return ktime_sub(kt, tmp);
295 EXPORT_SYMBOL_GPL(ktime_sub_ns);
296 # endif /* !CONFIG_KTIME_SCALAR */
299 * Divide a ktime value by a nanosecond value
301 u64 ktime_divns(const ktime_t kt, s64 div)
306 dclc = ktime_to_ns(kt);
307 /* Make sure the divisor is less than 2^32: */
313 do_div(dclc, (unsigned long) div);
317 #endif /* BITS_PER_LONG >= 64 */
320 * Add two ktime values and do a safety check for overflow:
322 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
324 ktime_t res = ktime_add(lhs, rhs);
327 * We use KTIME_SEC_MAX here, the maximum timeout which we can
328 * return to user space in a timespec:
330 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
331 res = ktime_set(KTIME_SEC_MAX, 0);
336 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
338 static struct debug_obj_descr hrtimer_debug_descr;
341 * fixup_init is called when:
342 * - an active object is initialized
344 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
346 struct hrtimer *timer = addr;
349 case ODEBUG_STATE_ACTIVE:
350 hrtimer_cancel(timer);
351 debug_object_init(timer, &hrtimer_debug_descr);
359 * fixup_activate is called when:
360 * - an active object is activated
361 * - an unknown object is activated (might be a statically initialized object)
363 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
367 case ODEBUG_STATE_NOTAVAILABLE:
371 case ODEBUG_STATE_ACTIVE:
380 * fixup_free is called when:
381 * - an active object is freed
383 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
385 struct hrtimer *timer = addr;
388 case ODEBUG_STATE_ACTIVE:
389 hrtimer_cancel(timer);
390 debug_object_free(timer, &hrtimer_debug_descr);
397 static struct debug_obj_descr hrtimer_debug_descr = {
399 .fixup_init = hrtimer_fixup_init,
400 .fixup_activate = hrtimer_fixup_activate,
401 .fixup_free = hrtimer_fixup_free,
404 static inline void debug_hrtimer_init(struct hrtimer *timer)
406 debug_object_init(timer, &hrtimer_debug_descr);
409 static inline void debug_hrtimer_activate(struct hrtimer *timer)
411 debug_object_activate(timer, &hrtimer_debug_descr);
414 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
416 debug_object_deactivate(timer, &hrtimer_debug_descr);
419 static inline void debug_hrtimer_free(struct hrtimer *timer)
421 debug_object_free(timer, &hrtimer_debug_descr);
424 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
425 enum hrtimer_mode mode);
427 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
428 enum hrtimer_mode mode)
430 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
431 __hrtimer_init(timer, clock_id, mode);
434 void destroy_hrtimer_on_stack(struct hrtimer *timer)
436 debug_object_free(timer, &hrtimer_debug_descr);
440 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
441 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
442 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
445 /* High resolution timer related functions */
446 #ifdef CONFIG_HIGH_RES_TIMERS
449 * High resolution timer enabled ?
451 static int hrtimer_hres_enabled __read_mostly = 1;
454 * Enable / Disable high resolution mode
456 static int __init setup_hrtimer_hres(char *str)
458 if (!strcmp(str, "off"))
459 hrtimer_hres_enabled = 0;
460 else if (!strcmp(str, "on"))
461 hrtimer_hres_enabled = 1;
467 __setup("highres=", setup_hrtimer_hres);
470 * hrtimer_high_res_enabled - query, if the highres mode is enabled
472 static inline int hrtimer_is_hres_enabled(void)
474 return hrtimer_hres_enabled;
478 * Is the high resolution mode active ?
480 static inline int hrtimer_hres_active(void)
482 return __get_cpu_var(hrtimer_bases).hres_active;
486 * Reprogram the event source with checking both queues for the
488 * Called with interrupts disabled and base->lock held
490 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
493 struct hrtimer_clock_base *base = cpu_base->clock_base;
496 cpu_base->expires_next.tv64 = KTIME_MAX;
498 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
499 struct hrtimer *timer;
503 timer = rb_entry(base->first, struct hrtimer, node);
504 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
506 * clock_was_set() has changed base->offset so the
507 * result might be negative. Fix it up to prevent a
508 * false positive in clockevents_program_event()
510 if (expires.tv64 < 0)
512 if (expires.tv64 < cpu_base->expires_next.tv64)
513 cpu_base->expires_next = expires;
516 if (cpu_base->expires_next.tv64 != KTIME_MAX)
517 tick_program_event(cpu_base->expires_next, 1);
521 * Shared reprogramming for clock_realtime and clock_monotonic
523 * When a timer is enqueued and expires earlier than the already enqueued
524 * timers, we have to check, whether it expires earlier than the timer for
525 * which the clock event device was armed.
527 * Called with interrupts disabled and base->cpu_base.lock held
529 static int hrtimer_reprogram(struct hrtimer *timer,
530 struct hrtimer_clock_base *base)
532 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
533 ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
536 WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
539 * When the callback is running, we do not reprogram the clock event
540 * device. The timer callback is either running on a different CPU or
541 * the callback is executed in the hrtimer_interrupt context. The
542 * reprogramming is handled either by the softirq, which called the
543 * callback or at the end of the hrtimer_interrupt.
545 if (hrtimer_callback_running(timer))
549 * CLOCK_REALTIME timer might be requested with an absolute
550 * expiry time which is less than base->offset. Nothing wrong
551 * about that, just avoid to call into the tick code, which
552 * has now objections against negative expiry values.
554 if (expires.tv64 < 0)
557 if (expires.tv64 >= expires_next->tv64)
561 * Clockevents returns -ETIME, when the event was in the past.
563 res = tick_program_event(expires, 0);
564 if (!IS_ERR_VALUE(res))
565 *expires_next = expires;
571 * Retrigger next event is called after clock was set
573 * Called with interrupts disabled via on_each_cpu()
575 static void retrigger_next_event(void *arg)
577 struct hrtimer_cpu_base *base;
578 struct timespec realtime_offset;
581 if (!hrtimer_hres_active())
585 seq = read_seqbegin(&xtime_lock);
586 set_normalized_timespec(&realtime_offset,
587 -wall_to_monotonic.tv_sec,
588 -wall_to_monotonic.tv_nsec);
589 } while (read_seqretry(&xtime_lock, seq));
591 base = &__get_cpu_var(hrtimer_bases);
593 /* Adjust CLOCK_REALTIME offset */
594 spin_lock(&base->lock);
595 base->clock_base[CLOCK_REALTIME].offset =
596 timespec_to_ktime(realtime_offset);
598 hrtimer_force_reprogram(base);
599 spin_unlock(&base->lock);
603 * Clock realtime was set
605 * Change the offset of the realtime clock vs. the monotonic
608 * We might have to reprogram the high resolution timer interrupt. On
609 * SMP we call the architecture specific code to retrigger _all_ high
610 * resolution timer interrupts. On UP we just disable interrupts and
611 * call the high resolution interrupt code.
613 void clock_was_set(void)
615 /* Retrigger the CPU local events everywhere */
616 on_each_cpu(retrigger_next_event, NULL, 1);
620 * During resume we might have to reprogram the high resolution timer
621 * interrupt (on the local CPU):
623 void hres_timers_resume(void)
625 WARN_ONCE(!irqs_disabled(),
626 KERN_INFO "hres_timers_resume() called with IRQs enabled!");
628 retrigger_next_event(NULL);
632 * Initialize the high resolution related parts of cpu_base
634 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
636 base->expires_next.tv64 = KTIME_MAX;
637 base->hres_active = 0;
641 * Initialize the high resolution related parts of a hrtimer
643 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
649 * When High resolution timers are active, try to reprogram. Note, that in case
650 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
651 * check happens. The timer gets enqueued into the rbtree. The reprogramming
652 * and expiry check is done in the hrtimer_interrupt or in the softirq.
654 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
655 struct hrtimer_clock_base *base,
658 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
660 spin_unlock(&base->cpu_base->lock);
661 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
662 spin_lock(&base->cpu_base->lock);
664 __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
673 * Switch to high resolution mode
675 static int hrtimer_switch_to_hres(void)
677 int cpu = smp_processor_id();
678 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
681 if (base->hres_active)
684 local_irq_save(flags);
686 if (tick_init_highres()) {
687 local_irq_restore(flags);
688 printk(KERN_WARNING "Could not switch to high resolution "
689 "mode on CPU %d\n", cpu);
692 base->hres_active = 1;
693 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
694 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
696 tick_setup_sched_timer();
698 /* "Retrigger" the interrupt to get things going */
699 retrigger_next_event(NULL);
700 local_irq_restore(flags);
701 printk(KERN_DEBUG "Switched to high resolution mode on CPU %d\n",
708 static inline int hrtimer_hres_active(void) { return 0; }
709 static inline int hrtimer_is_hres_enabled(void) { return 0; }
710 static inline int hrtimer_switch_to_hres(void) { return 0; }
711 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
712 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
713 struct hrtimer_clock_base *base,
718 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
719 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
721 #endif /* CONFIG_HIGH_RES_TIMERS */
723 #ifdef CONFIG_TIMER_STATS
724 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
726 if (timer->start_site)
729 timer->start_site = addr;
730 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
731 timer->start_pid = current->pid;
736 * Counterpart to lock_hrtimer_base above:
739 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
741 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
745 * hrtimer_forward - forward the timer expiry
746 * @timer: hrtimer to forward
747 * @now: forward past this time
748 * @interval: the interval to forward
750 * Forward the timer expiry so it will expire in the future.
751 * Returns the number of overruns.
753 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
758 delta = ktime_sub(now, hrtimer_get_expires(timer));
763 if (interval.tv64 < timer->base->resolution.tv64)
764 interval.tv64 = timer->base->resolution.tv64;
766 if (unlikely(delta.tv64 >= interval.tv64)) {
767 s64 incr = ktime_to_ns(interval);
769 orun = ktime_divns(delta, incr);
770 hrtimer_add_expires_ns(timer, incr * orun);
771 if (hrtimer_get_expires_tv64(timer) > now.tv64)
774 * This (and the ktime_add() below) is the
775 * correction for exact:
779 hrtimer_add_expires(timer, interval);
783 EXPORT_SYMBOL_GPL(hrtimer_forward);
786 * enqueue_hrtimer - internal function to (re)start a timer
788 * The timer is inserted in expiry order. Insertion into the
789 * red black tree is O(log(n)). Must hold the base lock.
791 * Returns 1 when the new timer is the leftmost timer in the tree.
793 static int enqueue_hrtimer(struct hrtimer *timer,
794 struct hrtimer_clock_base *base)
796 struct rb_node **link = &base->active.rb_node;
797 struct rb_node *parent = NULL;
798 struct hrtimer *entry;
801 debug_hrtimer_activate(timer);
804 * Find the right place in the rbtree:
808 entry = rb_entry(parent, struct hrtimer, node);
810 * We dont care about collisions. Nodes with
811 * the same expiry time stay together.
813 if (hrtimer_get_expires_tv64(timer) <
814 hrtimer_get_expires_tv64(entry)) {
815 link = &(*link)->rb_left;
817 link = &(*link)->rb_right;
823 * Insert the timer to the rbtree and check whether it
824 * replaces the first pending timer
827 base->first = &timer->node;
829 rb_link_node(&timer->node, parent, link);
830 rb_insert_color(&timer->node, &base->active);
832 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
833 * state of a possibly running callback.
835 timer->state |= HRTIMER_STATE_ENQUEUED;
841 * __remove_hrtimer - internal function to remove a timer
843 * Caller must hold the base lock.
845 * High resolution timer mode reprograms the clock event device when the
846 * timer is the one which expires next. The caller can disable this by setting
847 * reprogram to zero. This is useful, when the context does a reprogramming
848 * anyway (e.g. timer interrupt)
850 static void __remove_hrtimer(struct hrtimer *timer,
851 struct hrtimer_clock_base *base,
852 unsigned long newstate, int reprogram)
854 if (timer->state & HRTIMER_STATE_ENQUEUED) {
856 * Remove the timer from the rbtree and replace the
857 * first entry pointer if necessary.
859 if (base->first == &timer->node) {
860 base->first = rb_next(&timer->node);
861 /* Reprogram the clock event device. if enabled */
862 if (reprogram && hrtimer_hres_active())
863 hrtimer_force_reprogram(base->cpu_base);
865 rb_erase(&timer->node, &base->active);
867 timer->state = newstate;
871 * remove hrtimer, called with base lock held
874 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
876 if (hrtimer_is_queued(timer)) {
880 * Remove the timer and force reprogramming when high
881 * resolution mode is active and the timer is on the current
882 * CPU. If we remove a timer on another CPU, reprogramming is
883 * skipped. The interrupt event on this CPU is fired and
884 * reprogramming happens in the interrupt handler. This is a
885 * rare case and less expensive than a smp call.
887 debug_hrtimer_deactivate(timer);
888 timer_stats_hrtimer_clear_start_info(timer);
889 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
890 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
897 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
898 unsigned long delta_ns, const enum hrtimer_mode mode,
901 struct hrtimer_clock_base *base, *new_base;
905 base = lock_hrtimer_base(timer, &flags);
907 /* Remove an active timer from the queue: */
908 ret = remove_hrtimer(timer, base);
910 /* Switch the timer base, if necessary: */
911 new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
913 if (mode & HRTIMER_MODE_REL) {
914 tim = ktime_add_safe(tim, new_base->get_time());
916 * CONFIG_TIME_LOW_RES is a temporary way for architectures
917 * to signal that they simply return xtime in
918 * do_gettimeoffset(). In this case we want to round up by
919 * resolution when starting a relative timer, to avoid short
920 * timeouts. This will go away with the GTOD framework.
922 #ifdef CONFIG_TIME_LOW_RES
923 tim = ktime_add_safe(tim, base->resolution);
927 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
929 timer_stats_hrtimer_set_start_info(timer);
931 leftmost = enqueue_hrtimer(timer, new_base);
934 * Only allow reprogramming if the new base is on this CPU.
935 * (it might still be on another CPU if the timer was pending)
937 * XXX send_remote_softirq() ?
939 if (leftmost && new_base->cpu_base == &__get_cpu_var(hrtimer_bases))
940 hrtimer_enqueue_reprogram(timer, new_base, wakeup);
942 unlock_hrtimer_base(timer, &flags);
948 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
949 * @timer: the timer to be added
951 * @delta_ns: "slack" range for the timer
952 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
956 * 1 when the timer was active
958 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
959 unsigned long delta_ns, const enum hrtimer_mode mode)
961 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
963 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
966 * hrtimer_start - (re)start an hrtimer on the current CPU
967 * @timer: the timer to be added
969 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
973 * 1 when the timer was active
976 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
978 return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
980 EXPORT_SYMBOL_GPL(hrtimer_start);
984 * hrtimer_try_to_cancel - try to deactivate a timer
985 * @timer: hrtimer to stop
988 * 0 when the timer was not active
989 * 1 when the timer was active
990 * -1 when the timer is currently excuting the callback function and
993 int hrtimer_try_to_cancel(struct hrtimer *timer)
995 struct hrtimer_clock_base *base;
999 base = lock_hrtimer_base(timer, &flags);
1001 if (!hrtimer_callback_running(timer))
1002 ret = remove_hrtimer(timer, base);
1004 unlock_hrtimer_base(timer, &flags);
1009 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1012 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1013 * @timer: the timer to be cancelled
1016 * 0 when the timer was not active
1017 * 1 when the timer was active
1019 int hrtimer_cancel(struct hrtimer *timer)
1022 int ret = hrtimer_try_to_cancel(timer);
1029 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1032 * hrtimer_get_remaining - get remaining time for the timer
1033 * @timer: the timer to read
1035 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1037 struct hrtimer_clock_base *base;
1038 unsigned long flags;
1041 base = lock_hrtimer_base(timer, &flags);
1042 rem = hrtimer_expires_remaining(timer);
1043 unlock_hrtimer_base(timer, &flags);
1047 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1051 * hrtimer_get_next_event - get the time until next expiry event
1053 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1056 ktime_t hrtimer_get_next_event(void)
1058 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1059 struct hrtimer_clock_base *base = cpu_base->clock_base;
1060 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1061 unsigned long flags;
1064 spin_lock_irqsave(&cpu_base->lock, flags);
1066 if (!hrtimer_hres_active()) {
1067 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1068 struct hrtimer *timer;
1073 timer = rb_entry(base->first, struct hrtimer, node);
1074 delta.tv64 = hrtimer_get_expires_tv64(timer);
1075 delta = ktime_sub(delta, base->get_time());
1076 if (delta.tv64 < mindelta.tv64)
1077 mindelta.tv64 = delta.tv64;
1081 spin_unlock_irqrestore(&cpu_base->lock, flags);
1083 if (mindelta.tv64 < 0)
1089 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1090 enum hrtimer_mode mode)
1092 struct hrtimer_cpu_base *cpu_base;
1094 memset(timer, 0, sizeof(struct hrtimer));
1096 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1098 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1099 clock_id = CLOCK_MONOTONIC;
1101 timer->base = &cpu_base->clock_base[clock_id];
1102 INIT_LIST_HEAD(&timer->cb_entry);
1103 hrtimer_init_timer_hres(timer);
1105 #ifdef CONFIG_TIMER_STATS
1106 timer->start_site = NULL;
1107 timer->start_pid = -1;
1108 memset(timer->start_comm, 0, TASK_COMM_LEN);
1113 * hrtimer_init - initialize a timer to the given clock
1114 * @timer: the timer to be initialized
1115 * @clock_id: the clock to be used
1116 * @mode: timer mode abs/rel
1118 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1119 enum hrtimer_mode mode)
1121 debug_hrtimer_init(timer);
1122 __hrtimer_init(timer, clock_id, mode);
1124 EXPORT_SYMBOL_GPL(hrtimer_init);
1127 * hrtimer_get_res - get the timer resolution for a clock
1128 * @which_clock: which clock to query
1129 * @tp: pointer to timespec variable to store the resolution
1131 * Store the resolution of the clock selected by @which_clock in the
1132 * variable pointed to by @tp.
1134 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1136 struct hrtimer_cpu_base *cpu_base;
1138 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1139 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1143 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1145 static void __run_hrtimer(struct hrtimer *timer)
1147 struct hrtimer_clock_base *base = timer->base;
1148 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1149 enum hrtimer_restart (*fn)(struct hrtimer *);
1152 WARN_ON(!irqs_disabled());
1154 debug_hrtimer_deactivate(timer);
1155 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1156 timer_stats_account_hrtimer(timer);
1157 fn = timer->function;
1160 * Because we run timers from hardirq context, there is no chance
1161 * they get migrated to another cpu, therefore its safe to unlock
1164 spin_unlock(&cpu_base->lock);
1165 restart = fn(timer);
1166 spin_lock(&cpu_base->lock);
1169 * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1170 * we do not reprogramm the event hardware. Happens either in
1171 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1173 if (restart != HRTIMER_NORESTART) {
1174 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1175 enqueue_hrtimer(timer, base);
1177 timer->state &= ~HRTIMER_STATE_CALLBACK;
1180 #ifdef CONFIG_HIGH_RES_TIMERS
1182 static int force_clock_reprogram;
1185 * After 5 iteration's attempts, we consider that hrtimer_interrupt()
1186 * is hanging, which could happen with something that slows the interrupt
1187 * such as the tracing. Then we force the clock reprogramming for each future
1188 * hrtimer interrupts to avoid infinite loops and use the min_delta_ns
1189 * threshold that we will overwrite.
1190 * The next tick event will be scheduled to 3 times we currently spend on
1191 * hrtimer_interrupt(). This gives a good compromise, the cpus will spend
1192 * 1/4 of their time to process the hrtimer interrupts. This is enough to
1193 * let it running without serious starvation.
1197 hrtimer_interrupt_hanging(struct clock_event_device *dev,
1200 force_clock_reprogram = 1;
1201 dev->min_delta_ns = (unsigned long)try_time.tv64 * 3;
1202 printk(KERN_WARNING "hrtimer: interrupt too slow, "
1203 "forcing clock min delta to %lu ns\n", dev->min_delta_ns);
1206 * High resolution timer interrupt
1207 * Called with interrupts disabled
1209 void hrtimer_interrupt(struct clock_event_device *dev)
1211 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1212 struct hrtimer_clock_base *base;
1213 ktime_t expires_next, now;
1217 BUG_ON(!cpu_base->hres_active);
1218 cpu_base->nr_events++;
1219 dev->next_event.tv64 = KTIME_MAX;
1222 /* 5 retries is enough to notice a hang */
1223 if (!(++nr_retries % 5))
1224 hrtimer_interrupt_hanging(dev, ktime_sub(ktime_get(), now));
1228 expires_next.tv64 = KTIME_MAX;
1230 base = cpu_base->clock_base;
1232 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1234 struct rb_node *node;
1236 spin_lock(&cpu_base->lock);
1238 basenow = ktime_add(now, base->offset);
1240 while ((node = base->first)) {
1241 struct hrtimer *timer;
1243 timer = rb_entry(node, struct hrtimer, node);
1246 * The immediate goal for using the softexpires is
1247 * minimizing wakeups, not running timers at the
1248 * earliest interrupt after their soft expiration.
1249 * This allows us to avoid using a Priority Search
1250 * Tree, which can answer a stabbing querry for
1251 * overlapping intervals and instead use the simple
1252 * BST we already have.
1253 * We don't add extra wakeups by delaying timers that
1254 * are right-of a not yet expired timer, because that
1255 * timer will have to trigger a wakeup anyway.
1258 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1261 expires = ktime_sub(hrtimer_get_expires(timer),
1263 if (expires.tv64 < expires_next.tv64)
1264 expires_next = expires;
1268 __run_hrtimer(timer);
1270 spin_unlock(&cpu_base->lock);
1274 cpu_base->expires_next = expires_next;
1276 /* Reprogramming necessary ? */
1277 if (expires_next.tv64 != KTIME_MAX) {
1278 if (tick_program_event(expires_next, force_clock_reprogram))
1284 * local version of hrtimer_peek_ahead_timers() called with interrupts
1287 static void __hrtimer_peek_ahead_timers(void)
1289 struct tick_device *td;
1291 if (!hrtimer_hres_active())
1294 td = &__get_cpu_var(tick_cpu_device);
1295 if (td && td->evtdev)
1296 hrtimer_interrupt(td->evtdev);
1300 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1302 * hrtimer_peek_ahead_timers will peek at the timer queue of
1303 * the current cpu and check if there are any timers for which
1304 * the soft expires time has passed. If any such timers exist,
1305 * they are run immediately and then removed from the timer queue.
1308 void hrtimer_peek_ahead_timers(void)
1310 unsigned long flags;
1312 local_irq_save(flags);
1313 __hrtimer_peek_ahead_timers();
1314 local_irq_restore(flags);
1317 static void run_hrtimer_softirq(struct softirq_action *h)
1319 hrtimer_peek_ahead_timers();
1322 #else /* CONFIG_HIGH_RES_TIMERS */
1324 static inline void __hrtimer_peek_ahead_timers(void) { }
1326 #endif /* !CONFIG_HIGH_RES_TIMERS */
1329 * Called from timer softirq every jiffy, expire hrtimers:
1331 * For HRT its the fall back code to run the softirq in the timer
1332 * softirq context in case the hrtimer initialization failed or has
1333 * not been done yet.
1335 void hrtimer_run_pending(void)
1337 if (hrtimer_hres_active())
1341 * This _is_ ugly: We have to check in the softirq context,
1342 * whether we can switch to highres and / or nohz mode. The
1343 * clocksource switch happens in the timer interrupt with
1344 * xtime_lock held. Notification from there only sets the
1345 * check bit in the tick_oneshot code, otherwise we might
1346 * deadlock vs. xtime_lock.
1348 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1349 hrtimer_switch_to_hres();
1353 * Called from hardirq context every jiffy
1355 void hrtimer_run_queues(void)
1357 struct rb_node *node;
1358 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1359 struct hrtimer_clock_base *base;
1360 int index, gettime = 1;
1362 if (hrtimer_hres_active())
1365 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1366 base = &cpu_base->clock_base[index];
1372 hrtimer_get_softirq_time(cpu_base);
1376 spin_lock(&cpu_base->lock);
1378 while ((node = base->first)) {
1379 struct hrtimer *timer;
1381 timer = rb_entry(node, struct hrtimer, node);
1382 if (base->softirq_time.tv64 <=
1383 hrtimer_get_expires_tv64(timer))
1386 __run_hrtimer(timer);
1388 spin_unlock(&cpu_base->lock);
1393 * Sleep related functions:
1395 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1397 struct hrtimer_sleeper *t =
1398 container_of(timer, struct hrtimer_sleeper, timer);
1399 struct task_struct *task = t->task;
1403 wake_up_process(task);
1405 return HRTIMER_NORESTART;
1408 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1410 sl->timer.function = hrtimer_wakeup;
1414 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1416 hrtimer_init_sleeper(t, current);
1419 set_current_state(TASK_INTERRUPTIBLE);
1420 hrtimer_start_expires(&t->timer, mode);
1421 if (!hrtimer_active(&t->timer))
1424 if (likely(t->task))
1427 hrtimer_cancel(&t->timer);
1428 mode = HRTIMER_MODE_ABS;
1430 } while (t->task && !signal_pending(current));
1432 __set_current_state(TASK_RUNNING);
1434 return t->task == NULL;
1437 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1439 struct timespec rmt;
1442 rem = hrtimer_expires_remaining(timer);
1445 rmt = ktime_to_timespec(rem);
1447 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1453 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1455 struct hrtimer_sleeper t;
1456 struct timespec __user *rmtp;
1459 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1461 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1463 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1466 rmtp = restart->nanosleep.rmtp;
1468 ret = update_rmtp(&t.timer, rmtp);
1473 /* The other values in restart are already filled in */
1474 ret = -ERESTART_RESTARTBLOCK;
1476 destroy_hrtimer_on_stack(&t.timer);
1480 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1481 const enum hrtimer_mode mode, const clockid_t clockid)
1483 struct restart_block *restart;
1484 struct hrtimer_sleeper t;
1486 unsigned long slack;
1488 slack = current->timer_slack_ns;
1489 if (rt_task(current))
1492 hrtimer_init_on_stack(&t.timer, clockid, mode);
1493 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1494 if (do_nanosleep(&t, mode))
1497 /* Absolute timers do not update the rmtp value and restart: */
1498 if (mode == HRTIMER_MODE_ABS) {
1499 ret = -ERESTARTNOHAND;
1504 ret = update_rmtp(&t.timer, rmtp);
1509 restart = ¤t_thread_info()->restart_block;
1510 restart->fn = hrtimer_nanosleep_restart;
1511 restart->nanosleep.index = t.timer.base->index;
1512 restart->nanosleep.rmtp = rmtp;
1513 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1515 ret = -ERESTART_RESTARTBLOCK;
1517 destroy_hrtimer_on_stack(&t.timer);
1521 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1522 struct timespec __user *, rmtp)
1526 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1529 if (!timespec_valid(&tu))
1532 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1536 * Functions related to boot-time initialization:
1538 static void __cpuinit init_hrtimers_cpu(int cpu)
1540 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1543 spin_lock_init(&cpu_base->lock);
1545 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1546 cpu_base->clock_base[i].cpu_base = cpu_base;
1548 hrtimer_init_hres(cpu_base);
1551 #ifdef CONFIG_HOTPLUG_CPU
1553 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1554 struct hrtimer_clock_base *new_base)
1556 struct hrtimer *timer;
1557 struct rb_node *node;
1559 while ((node = rb_first(&old_base->active))) {
1560 timer = rb_entry(node, struct hrtimer, node);
1561 BUG_ON(hrtimer_callback_running(timer));
1562 debug_hrtimer_deactivate(timer);
1565 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1566 * timer could be seen as !active and just vanish away
1567 * under us on another CPU
1569 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1570 timer->base = new_base;
1572 * Enqueue the timers on the new cpu. This does not
1573 * reprogram the event device in case the timer
1574 * expires before the earliest on this CPU, but we run
1575 * hrtimer_interrupt after we migrated everything to
1576 * sort out already expired timers and reprogram the
1579 enqueue_hrtimer(timer, new_base);
1581 /* Clear the migration state bit */
1582 timer->state &= ~HRTIMER_STATE_MIGRATE;
1586 static void migrate_hrtimers(int scpu)
1588 struct hrtimer_cpu_base *old_base, *new_base;
1591 BUG_ON(cpu_online(scpu));
1592 tick_cancel_sched_timer(scpu);
1594 local_irq_disable();
1595 old_base = &per_cpu(hrtimer_bases, scpu);
1596 new_base = &__get_cpu_var(hrtimer_bases);
1598 * The caller is globally serialized and nobody else
1599 * takes two locks at once, deadlock is not possible.
1601 spin_lock(&new_base->lock);
1602 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1604 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1605 migrate_hrtimer_list(&old_base->clock_base[i],
1606 &new_base->clock_base[i]);
1609 spin_unlock(&old_base->lock);
1610 spin_unlock(&new_base->lock);
1612 /* Check, if we got expired work to do */
1613 __hrtimer_peek_ahead_timers();
1617 #endif /* CONFIG_HOTPLUG_CPU */
1619 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1620 unsigned long action, void *hcpu)
1622 int scpu = (long)hcpu;
1626 case CPU_UP_PREPARE:
1627 case CPU_UP_PREPARE_FROZEN:
1628 init_hrtimers_cpu(scpu);
1631 #ifdef CONFIG_HOTPLUG_CPU
1633 case CPU_DYING_FROZEN:
1634 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1637 case CPU_DEAD_FROZEN:
1639 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1640 migrate_hrtimers(scpu);
1652 static struct notifier_block __cpuinitdata hrtimers_nb = {
1653 .notifier_call = hrtimer_cpu_notify,
1656 void __init hrtimers_init(void)
1658 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1659 (void *)(long)smp_processor_id());
1660 register_cpu_notifier(&hrtimers_nb);
1661 #ifdef CONFIG_HIGH_RES_TIMERS
1662 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1667 * schedule_hrtimeout_range - sleep until timeout
1668 * @expires: timeout value (ktime_t)
1669 * @delta: slack in expires timeout (ktime_t)
1670 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1672 * Make the current task sleep until the given expiry time has
1673 * elapsed. The routine will return immediately unless
1674 * the current task state has been set (see set_current_state()).
1676 * The @delta argument gives the kernel the freedom to schedule the
1677 * actual wakeup to a time that is both power and performance friendly.
1678 * The kernel give the normal best effort behavior for "@expires+@delta",
1679 * but may decide to fire the timer earlier, but no earlier than @expires.
1681 * You can set the task state as follows -
1683 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1684 * pass before the routine returns.
1686 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1687 * delivered to the current task.
1689 * The current task state is guaranteed to be TASK_RUNNING when this
1692 * Returns 0 when the timer has expired otherwise -EINTR
1694 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1695 const enum hrtimer_mode mode)
1697 struct hrtimer_sleeper t;
1700 * Optimize when a zero timeout value is given. It does not
1701 * matter whether this is an absolute or a relative time.
1703 if (expires && !expires->tv64) {
1704 __set_current_state(TASK_RUNNING);
1709 * A NULL parameter means "inifinte"
1713 __set_current_state(TASK_RUNNING);
1717 hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
1718 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1720 hrtimer_init_sleeper(&t, current);
1722 hrtimer_start_expires(&t.timer, mode);
1723 if (!hrtimer_active(&t.timer))
1729 hrtimer_cancel(&t.timer);
1730 destroy_hrtimer_on_stack(&t.timer);
1732 __set_current_state(TASK_RUNNING);
1734 return !t.task ? 0 : -EINTR;
1736 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1739 * schedule_hrtimeout - sleep until timeout
1740 * @expires: timeout value (ktime_t)
1741 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1743 * Make the current task sleep until the given expiry time has
1744 * elapsed. The routine will return immediately unless
1745 * the current task state has been set (see set_current_state()).
1747 * You can set the task state as follows -
1749 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1750 * pass before the routine returns.
1752 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1753 * delivered to the current task.
1755 * The current task state is guaranteed to be TASK_RUNNING when this
1758 * Returns 0 when the timer has expired otherwise -EINTR
1760 int __sched schedule_hrtimeout(ktime_t *expires,
1761 const enum hrtimer_mode mode)
1763 return schedule_hrtimeout_range(expires, 0, mode);
1765 EXPORT_SYMBOL_GPL(schedule_hrtimeout);