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>
46 #include <linux/sched.h>
47 #include <linux/timer.h>
49 #include <asm/uaccess.h>
54 * Note: If we want to add new timer bases, we have to skip the two
55 * clock ids captured by the cpu-timers. We do this by holding empty
56 * entries rather than doing math adjustment of the clock ids.
57 * This ensures that we capture erroneous accesses to these clock ids
58 * rather than moving them into the range of valid clock id's.
60 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
66 .index = CLOCK_REALTIME,
67 .get_time = &ktime_get_real,
68 .resolution = KTIME_LOW_RES,
71 .index = CLOCK_MONOTONIC,
72 .get_time = &ktime_get,
73 .resolution = KTIME_LOW_RES,
79 * Get the coarse grained time at the softirq based on xtime and
82 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
85 struct timespec xts, tom;
89 seq = read_seqbegin(&xtime_lock);
90 xts = current_kernel_time();
91 tom = wall_to_monotonic;
92 } while (read_seqretry(&xtime_lock, seq));
94 xtim = timespec_to_ktime(xts);
95 tomono = timespec_to_ktime(tom);
96 base->clock_base[CLOCK_REALTIME].softirq_time = xtim;
97 base->clock_base[CLOCK_MONOTONIC].softirq_time =
98 ktime_add(xtim, tomono);
102 * Functions and macros which are different for UP/SMP systems are kept in a
108 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
109 * means that all timers which are tied to this base via timer->base are
110 * locked, and the base itself is locked too.
112 * So __run_timers/migrate_timers can safely modify all timers which could
113 * be found on the lists/queues.
115 * When the timer's base is locked, and the timer removed from list, it is
116 * possible to set timer->base = NULL and drop the lock: the timer remains
120 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
121 unsigned long *flags)
123 struct hrtimer_clock_base *base;
127 if (likely(base != NULL)) {
128 spin_lock_irqsave(&base->cpu_base->lock, *flags);
129 if (likely(base == timer->base))
131 /* The timer has migrated to another CPU: */
132 spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
139 * Switch the timer base to the current CPU when possible.
141 static inline struct hrtimer_clock_base *
142 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
145 struct hrtimer_clock_base *new_base;
146 struct hrtimer_cpu_base *new_cpu_base;
147 int cpu, preferred_cpu = -1;
149 cpu = smp_processor_id();
150 #if defined(CONFIG_NO_HZ) && defined(CONFIG_SMP)
151 if (!pinned && get_sysctl_timer_migration() && idle_cpu(cpu)) {
152 preferred_cpu = get_nohz_load_balancer();
153 if (preferred_cpu >= 0)
159 new_cpu_base = &per_cpu(hrtimer_bases, cpu);
160 new_base = &new_cpu_base->clock_base[base->index];
162 if (base != new_base) {
164 * We are trying to schedule the timer on the local CPU.
165 * However we can't change timer's base while it is running,
166 * so we keep it on the same CPU. No hassle vs. reprogramming
167 * the event source in the high resolution case. The softirq
168 * code will take care of this when the timer function has
169 * completed. There is no conflict as we hold the lock until
170 * the timer is enqueued.
172 if (unlikely(hrtimer_callback_running(timer)))
175 /* See the comment in lock_timer_base() */
177 spin_unlock(&base->cpu_base->lock);
178 spin_lock(&new_base->cpu_base->lock);
180 /* Optimized away for NOHZ=n SMP=n */
181 if (cpu == preferred_cpu) {
182 /* Calculate clock monotonic expiry time */
183 #ifdef CONFIG_HIGH_RES_TIMERS
184 ktime_t expires = ktime_sub(hrtimer_get_expires(timer),
187 ktime_t expires = hrtimer_get_expires(timer);
191 * Get the next event on target cpu from the
192 * clock events layer.
193 * This covers the highres=off nohz=on case as well.
195 ktime_t next = clockevents_get_next_event(cpu);
197 ktime_t delta = ktime_sub(expires, next);
200 * We do not migrate the timer when it is expiring
201 * before the next event on the target cpu because
202 * we cannot reprogram the target cpu hardware and
203 * we would cause it to fire late.
205 if (delta.tv64 < 0) {
206 cpu = smp_processor_id();
207 spin_unlock(&new_base->cpu_base->lock);
208 spin_lock(&base->cpu_base->lock);
213 timer->base = new_base;
218 #else /* CONFIG_SMP */
220 static inline struct hrtimer_clock_base *
221 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
223 struct hrtimer_clock_base *base = timer->base;
225 spin_lock_irqsave(&base->cpu_base->lock, *flags);
230 # define switch_hrtimer_base(t, b, p) (b)
232 #endif /* !CONFIG_SMP */
235 * Functions for the union type storage format of ktime_t which are
236 * too large for inlining:
238 #if BITS_PER_LONG < 64
239 # ifndef CONFIG_KTIME_SCALAR
241 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
243 * @nsec: the scalar nsec value to add
245 * Returns the sum of kt and nsec in ktime_t format
247 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
251 if (likely(nsec < NSEC_PER_SEC)) {
254 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
256 tmp = ktime_set((long)nsec, rem);
259 return ktime_add(kt, tmp);
262 EXPORT_SYMBOL_GPL(ktime_add_ns);
265 * ktime_sub_ns - Subtract a scalar nanoseconds value from a ktime_t variable
267 * @nsec: the scalar nsec value to subtract
269 * Returns the subtraction of @nsec from @kt in ktime_t format
271 ktime_t ktime_sub_ns(const ktime_t kt, u64 nsec)
275 if (likely(nsec < NSEC_PER_SEC)) {
278 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
280 tmp = ktime_set((long)nsec, rem);
283 return ktime_sub(kt, tmp);
286 EXPORT_SYMBOL_GPL(ktime_sub_ns);
287 # endif /* !CONFIG_KTIME_SCALAR */
290 * Divide a ktime value by a nanosecond value
292 u64 ktime_divns(const ktime_t kt, s64 div)
297 dclc = ktime_to_ns(kt);
298 /* Make sure the divisor is less than 2^32: */
304 do_div(dclc, (unsigned long) div);
308 #endif /* BITS_PER_LONG >= 64 */
311 * Add two ktime values and do a safety check for overflow:
313 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
315 ktime_t res = ktime_add(lhs, rhs);
318 * We use KTIME_SEC_MAX here, the maximum timeout which we can
319 * return to user space in a timespec:
321 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
322 res = ktime_set(KTIME_SEC_MAX, 0);
327 EXPORT_SYMBOL_GPL(ktime_add_safe);
329 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
331 static struct debug_obj_descr hrtimer_debug_descr;
334 * fixup_init is called when:
335 * - an active object is initialized
337 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
339 struct hrtimer *timer = addr;
342 case ODEBUG_STATE_ACTIVE:
343 hrtimer_cancel(timer);
344 debug_object_init(timer, &hrtimer_debug_descr);
352 * fixup_activate is called when:
353 * - an active object is activated
354 * - an unknown object is activated (might be a statically initialized object)
356 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
360 case ODEBUG_STATE_NOTAVAILABLE:
364 case ODEBUG_STATE_ACTIVE:
373 * fixup_free is called when:
374 * - an active object is freed
376 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
378 struct hrtimer *timer = addr;
381 case ODEBUG_STATE_ACTIVE:
382 hrtimer_cancel(timer);
383 debug_object_free(timer, &hrtimer_debug_descr);
390 static struct debug_obj_descr hrtimer_debug_descr = {
392 .fixup_init = hrtimer_fixup_init,
393 .fixup_activate = hrtimer_fixup_activate,
394 .fixup_free = hrtimer_fixup_free,
397 static inline void debug_hrtimer_init(struct hrtimer *timer)
399 debug_object_init(timer, &hrtimer_debug_descr);
402 static inline void debug_hrtimer_activate(struct hrtimer *timer)
404 debug_object_activate(timer, &hrtimer_debug_descr);
407 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
409 debug_object_deactivate(timer, &hrtimer_debug_descr);
412 static inline void debug_hrtimer_free(struct hrtimer *timer)
414 debug_object_free(timer, &hrtimer_debug_descr);
417 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
418 enum hrtimer_mode mode);
420 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
421 enum hrtimer_mode mode)
423 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
424 __hrtimer_init(timer, clock_id, mode);
427 void destroy_hrtimer_on_stack(struct hrtimer *timer)
429 debug_object_free(timer, &hrtimer_debug_descr);
433 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
434 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
435 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
438 /* High resolution timer related functions */
439 #ifdef CONFIG_HIGH_RES_TIMERS
442 * High resolution timer enabled ?
444 static int hrtimer_hres_enabled __read_mostly = 1;
447 * Enable / Disable high resolution mode
449 static int __init setup_hrtimer_hres(char *str)
451 if (!strcmp(str, "off"))
452 hrtimer_hres_enabled = 0;
453 else if (!strcmp(str, "on"))
454 hrtimer_hres_enabled = 1;
460 __setup("highres=", setup_hrtimer_hres);
463 * hrtimer_high_res_enabled - query, if the highres mode is enabled
465 static inline int hrtimer_is_hres_enabled(void)
467 return hrtimer_hres_enabled;
471 * Is the high resolution mode active ?
473 static inline int hrtimer_hres_active(void)
475 return __get_cpu_var(hrtimer_bases).hres_active;
479 * Reprogram the event source with checking both queues for the
481 * Called with interrupts disabled and base->lock held
483 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
486 struct hrtimer_clock_base *base = cpu_base->clock_base;
489 cpu_base->expires_next.tv64 = KTIME_MAX;
491 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
492 struct hrtimer *timer;
496 timer = rb_entry(base->first, struct hrtimer, node);
497 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
499 * clock_was_set() has changed base->offset so the
500 * result might be negative. Fix it up to prevent a
501 * false positive in clockevents_program_event()
503 if (expires.tv64 < 0)
505 if (expires.tv64 < cpu_base->expires_next.tv64)
506 cpu_base->expires_next = expires;
509 if (cpu_base->expires_next.tv64 != KTIME_MAX)
510 tick_program_event(cpu_base->expires_next, 1);
514 * Shared reprogramming for clock_realtime and clock_monotonic
516 * When a timer is enqueued and expires earlier than the already enqueued
517 * timers, we have to check, whether it expires earlier than the timer for
518 * which the clock event device was armed.
520 * Called with interrupts disabled and base->cpu_base.lock held
522 static int hrtimer_reprogram(struct hrtimer *timer,
523 struct hrtimer_clock_base *base)
525 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
526 ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
529 WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
532 * When the callback is running, we do not reprogram the clock event
533 * device. The timer callback is either running on a different CPU or
534 * the callback is executed in the hrtimer_interrupt context. The
535 * reprogramming is handled either by the softirq, which called the
536 * callback or at the end of the hrtimer_interrupt.
538 if (hrtimer_callback_running(timer))
542 * CLOCK_REALTIME timer might be requested with an absolute
543 * expiry time which is less than base->offset. Nothing wrong
544 * about that, just avoid to call into the tick code, which
545 * has now objections against negative expiry values.
547 if (expires.tv64 < 0)
550 if (expires.tv64 >= expires_next->tv64)
554 * Clockevents returns -ETIME, when the event was in the past.
556 res = tick_program_event(expires, 0);
557 if (!IS_ERR_VALUE(res))
558 *expires_next = expires;
564 * Retrigger next event is called after clock was set
566 * Called with interrupts disabled via on_each_cpu()
568 static void retrigger_next_event(void *arg)
570 struct hrtimer_cpu_base *base;
571 struct timespec realtime_offset;
574 if (!hrtimer_hres_active())
578 seq = read_seqbegin(&xtime_lock);
579 set_normalized_timespec(&realtime_offset,
580 -wall_to_monotonic.tv_sec,
581 -wall_to_monotonic.tv_nsec);
582 } while (read_seqretry(&xtime_lock, seq));
584 base = &__get_cpu_var(hrtimer_bases);
586 /* Adjust CLOCK_REALTIME offset */
587 spin_lock(&base->lock);
588 base->clock_base[CLOCK_REALTIME].offset =
589 timespec_to_ktime(realtime_offset);
591 hrtimer_force_reprogram(base);
592 spin_unlock(&base->lock);
596 * Clock realtime was set
598 * Change the offset of the realtime clock vs. the monotonic
601 * We might have to reprogram the high resolution timer interrupt. On
602 * SMP we call the architecture specific code to retrigger _all_ high
603 * resolution timer interrupts. On UP we just disable interrupts and
604 * call the high resolution interrupt code.
606 void clock_was_set(void)
608 /* Retrigger the CPU local events everywhere */
609 on_each_cpu(retrigger_next_event, NULL, 1);
613 * During resume we might have to reprogram the high resolution timer
614 * interrupt (on the local CPU):
616 void hres_timers_resume(void)
618 WARN_ONCE(!irqs_disabled(),
619 KERN_INFO "hres_timers_resume() called with IRQs enabled!");
621 retrigger_next_event(NULL);
625 * Initialize the high resolution related parts of cpu_base
627 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
629 base->expires_next.tv64 = KTIME_MAX;
630 base->hres_active = 0;
634 * Initialize the high resolution related parts of a hrtimer
636 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
642 * When High resolution timers are active, try to reprogram. Note, that in case
643 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
644 * check happens. The timer gets enqueued into the rbtree. The reprogramming
645 * and expiry check is done in the hrtimer_interrupt or in the softirq.
647 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
648 struct hrtimer_clock_base *base,
651 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
653 spin_unlock(&base->cpu_base->lock);
654 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
655 spin_lock(&base->cpu_base->lock);
657 __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
666 * Switch to high resolution mode
668 static int hrtimer_switch_to_hres(void)
670 int cpu = smp_processor_id();
671 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
674 if (base->hres_active)
677 local_irq_save(flags);
679 if (tick_init_highres()) {
680 local_irq_restore(flags);
681 printk(KERN_WARNING "Could not switch to high resolution "
682 "mode on CPU %d\n", cpu);
685 base->hres_active = 1;
686 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
687 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
689 tick_setup_sched_timer();
691 /* "Retrigger" the interrupt to get things going */
692 retrigger_next_event(NULL);
693 local_irq_restore(flags);
694 printk(KERN_DEBUG "Switched to high resolution mode on CPU %d\n",
701 static inline int hrtimer_hres_active(void) { return 0; }
702 static inline int hrtimer_is_hres_enabled(void) { return 0; }
703 static inline int hrtimer_switch_to_hres(void) { return 0; }
704 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
705 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
706 struct hrtimer_clock_base *base,
711 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
712 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
714 #endif /* CONFIG_HIGH_RES_TIMERS */
716 #ifdef CONFIG_TIMER_STATS
717 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
719 if (timer->start_site)
722 timer->start_site = addr;
723 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
724 timer->start_pid = current->pid;
729 * Counterpart to lock_hrtimer_base above:
732 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
734 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
738 * hrtimer_forward - forward the timer expiry
739 * @timer: hrtimer to forward
740 * @now: forward past this time
741 * @interval: the interval to forward
743 * Forward the timer expiry so it will expire in the future.
744 * Returns the number of overruns.
746 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
751 delta = ktime_sub(now, hrtimer_get_expires(timer));
756 if (interval.tv64 < timer->base->resolution.tv64)
757 interval.tv64 = timer->base->resolution.tv64;
759 if (unlikely(delta.tv64 >= interval.tv64)) {
760 s64 incr = ktime_to_ns(interval);
762 orun = ktime_divns(delta, incr);
763 hrtimer_add_expires_ns(timer, incr * orun);
764 if (hrtimer_get_expires_tv64(timer) > now.tv64)
767 * This (and the ktime_add() below) is the
768 * correction for exact:
772 hrtimer_add_expires(timer, interval);
776 EXPORT_SYMBOL_GPL(hrtimer_forward);
779 * enqueue_hrtimer - internal function to (re)start a timer
781 * The timer is inserted in expiry order. Insertion into the
782 * red black tree is O(log(n)). Must hold the base lock.
784 * Returns 1 when the new timer is the leftmost timer in the tree.
786 static int enqueue_hrtimer(struct hrtimer *timer,
787 struct hrtimer_clock_base *base)
789 struct rb_node **link = &base->active.rb_node;
790 struct rb_node *parent = NULL;
791 struct hrtimer *entry;
794 debug_hrtimer_activate(timer);
797 * Find the right place in the rbtree:
801 entry = rb_entry(parent, struct hrtimer, node);
803 * We dont care about collisions. Nodes with
804 * the same expiry time stay together.
806 if (hrtimer_get_expires_tv64(timer) <
807 hrtimer_get_expires_tv64(entry)) {
808 link = &(*link)->rb_left;
810 link = &(*link)->rb_right;
816 * Insert the timer to the rbtree and check whether it
817 * replaces the first pending timer
820 base->first = &timer->node;
822 rb_link_node(&timer->node, parent, link);
823 rb_insert_color(&timer->node, &base->active);
825 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
826 * state of a possibly running callback.
828 timer->state |= HRTIMER_STATE_ENQUEUED;
834 * __remove_hrtimer - internal function to remove a timer
836 * Caller must hold the base lock.
838 * High resolution timer mode reprograms the clock event device when the
839 * timer is the one which expires next. The caller can disable this by setting
840 * reprogram to zero. This is useful, when the context does a reprogramming
841 * anyway (e.g. timer interrupt)
843 static void __remove_hrtimer(struct hrtimer *timer,
844 struct hrtimer_clock_base *base,
845 unsigned long newstate, int reprogram)
847 if (timer->state & HRTIMER_STATE_ENQUEUED) {
849 * Remove the timer from the rbtree and replace the
850 * first entry pointer if necessary.
852 if (base->first == &timer->node) {
853 base->first = rb_next(&timer->node);
854 /* Reprogram the clock event device. if enabled */
855 if (reprogram && hrtimer_hres_active())
856 hrtimer_force_reprogram(base->cpu_base);
858 rb_erase(&timer->node, &base->active);
860 timer->state = newstate;
864 * remove hrtimer, called with base lock held
867 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
869 if (hrtimer_is_queued(timer)) {
873 * Remove the timer and force reprogramming when high
874 * resolution mode is active and the timer is on the current
875 * CPU. If we remove a timer on another CPU, reprogramming is
876 * skipped. The interrupt event on this CPU is fired and
877 * reprogramming happens in the interrupt handler. This is a
878 * rare case and less expensive than a smp call.
880 debug_hrtimer_deactivate(timer);
881 timer_stats_hrtimer_clear_start_info(timer);
882 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
883 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
890 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
891 unsigned long delta_ns, const enum hrtimer_mode mode,
894 struct hrtimer_clock_base *base, *new_base;
898 base = lock_hrtimer_base(timer, &flags);
900 /* Remove an active timer from the queue: */
901 ret = remove_hrtimer(timer, base);
903 /* Switch the timer base, if necessary: */
904 new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
906 if (mode & HRTIMER_MODE_REL) {
907 tim = ktime_add_safe(tim, new_base->get_time());
909 * CONFIG_TIME_LOW_RES is a temporary way for architectures
910 * to signal that they simply return xtime in
911 * do_gettimeoffset(). In this case we want to round up by
912 * resolution when starting a relative timer, to avoid short
913 * timeouts. This will go away with the GTOD framework.
915 #ifdef CONFIG_TIME_LOW_RES
916 tim = ktime_add_safe(tim, base->resolution);
920 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
922 timer_stats_hrtimer_set_start_info(timer);
924 leftmost = enqueue_hrtimer(timer, new_base);
927 * Only allow reprogramming if the new base is on this CPU.
928 * (it might still be on another CPU if the timer was pending)
930 * XXX send_remote_softirq() ?
932 if (leftmost && new_base->cpu_base == &__get_cpu_var(hrtimer_bases))
933 hrtimer_enqueue_reprogram(timer, new_base, wakeup);
935 unlock_hrtimer_base(timer, &flags);
941 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
942 * @timer: the timer to be added
944 * @delta_ns: "slack" range for the timer
945 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
949 * 1 when the timer was active
951 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
952 unsigned long delta_ns, const enum hrtimer_mode mode)
954 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
956 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
959 * hrtimer_start - (re)start an hrtimer on the current CPU
960 * @timer: the timer to be added
962 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
966 * 1 when the timer was active
969 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
971 return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
973 EXPORT_SYMBOL_GPL(hrtimer_start);
977 * hrtimer_try_to_cancel - try to deactivate a timer
978 * @timer: hrtimer to stop
981 * 0 when the timer was not active
982 * 1 when the timer was active
983 * -1 when the timer is currently excuting the callback function and
986 int hrtimer_try_to_cancel(struct hrtimer *timer)
988 struct hrtimer_clock_base *base;
992 base = lock_hrtimer_base(timer, &flags);
994 if (!hrtimer_callback_running(timer))
995 ret = remove_hrtimer(timer, base);
997 unlock_hrtimer_base(timer, &flags);
1002 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1005 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1006 * @timer: the timer to be cancelled
1009 * 0 when the timer was not active
1010 * 1 when the timer was active
1012 int hrtimer_cancel(struct hrtimer *timer)
1015 int ret = hrtimer_try_to_cancel(timer);
1022 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1025 * hrtimer_get_remaining - get remaining time for the timer
1026 * @timer: the timer to read
1028 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1030 struct hrtimer_clock_base *base;
1031 unsigned long flags;
1034 base = lock_hrtimer_base(timer, &flags);
1035 rem = hrtimer_expires_remaining(timer);
1036 unlock_hrtimer_base(timer, &flags);
1040 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1044 * hrtimer_get_next_event - get the time until next expiry event
1046 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1049 ktime_t hrtimer_get_next_event(void)
1051 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1052 struct hrtimer_clock_base *base = cpu_base->clock_base;
1053 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1054 unsigned long flags;
1057 spin_lock_irqsave(&cpu_base->lock, flags);
1059 if (!hrtimer_hres_active()) {
1060 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1061 struct hrtimer *timer;
1066 timer = rb_entry(base->first, struct hrtimer, node);
1067 delta.tv64 = hrtimer_get_expires_tv64(timer);
1068 delta = ktime_sub(delta, base->get_time());
1069 if (delta.tv64 < mindelta.tv64)
1070 mindelta.tv64 = delta.tv64;
1074 spin_unlock_irqrestore(&cpu_base->lock, flags);
1076 if (mindelta.tv64 < 0)
1082 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1083 enum hrtimer_mode mode)
1085 struct hrtimer_cpu_base *cpu_base;
1087 memset(timer, 0, sizeof(struct hrtimer));
1089 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1091 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1092 clock_id = CLOCK_MONOTONIC;
1094 timer->base = &cpu_base->clock_base[clock_id];
1095 INIT_LIST_HEAD(&timer->cb_entry);
1096 hrtimer_init_timer_hres(timer);
1098 #ifdef CONFIG_TIMER_STATS
1099 timer->start_site = NULL;
1100 timer->start_pid = -1;
1101 memset(timer->start_comm, 0, TASK_COMM_LEN);
1106 * hrtimer_init - initialize a timer to the given clock
1107 * @timer: the timer to be initialized
1108 * @clock_id: the clock to be used
1109 * @mode: timer mode abs/rel
1111 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1112 enum hrtimer_mode mode)
1114 debug_hrtimer_init(timer);
1115 __hrtimer_init(timer, clock_id, mode);
1117 EXPORT_SYMBOL_GPL(hrtimer_init);
1120 * hrtimer_get_res - get the timer resolution for a clock
1121 * @which_clock: which clock to query
1122 * @tp: pointer to timespec variable to store the resolution
1124 * Store the resolution of the clock selected by @which_clock in the
1125 * variable pointed to by @tp.
1127 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1129 struct hrtimer_cpu_base *cpu_base;
1131 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1132 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1136 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1138 static void __run_hrtimer(struct hrtimer *timer)
1140 struct hrtimer_clock_base *base = timer->base;
1141 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1142 enum hrtimer_restart (*fn)(struct hrtimer *);
1145 WARN_ON(!irqs_disabled());
1147 debug_hrtimer_deactivate(timer);
1148 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1149 timer_stats_account_hrtimer(timer);
1150 fn = timer->function;
1153 * Because we run timers from hardirq context, there is no chance
1154 * they get migrated to another cpu, therefore its safe to unlock
1157 spin_unlock(&cpu_base->lock);
1158 restart = fn(timer);
1159 spin_lock(&cpu_base->lock);
1162 * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1163 * we do not reprogramm the event hardware. Happens either in
1164 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1166 if (restart != HRTIMER_NORESTART) {
1167 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1168 enqueue_hrtimer(timer, base);
1170 timer->state &= ~HRTIMER_STATE_CALLBACK;
1173 #ifdef CONFIG_HIGH_RES_TIMERS
1175 static int force_clock_reprogram;
1178 * After 5 iteration's attempts, we consider that hrtimer_interrupt()
1179 * is hanging, which could happen with something that slows the interrupt
1180 * such as the tracing. Then we force the clock reprogramming for each future
1181 * hrtimer interrupts to avoid infinite loops and use the min_delta_ns
1182 * threshold that we will overwrite.
1183 * The next tick event will be scheduled to 3 times we currently spend on
1184 * hrtimer_interrupt(). This gives a good compromise, the cpus will spend
1185 * 1/4 of their time to process the hrtimer interrupts. This is enough to
1186 * let it running without serious starvation.
1190 hrtimer_interrupt_hanging(struct clock_event_device *dev,
1193 force_clock_reprogram = 1;
1194 dev->min_delta_ns = (unsigned long)try_time.tv64 * 3;
1195 printk(KERN_WARNING "hrtimer: interrupt too slow, "
1196 "forcing clock min delta to %lu ns\n", dev->min_delta_ns);
1199 * High resolution timer interrupt
1200 * Called with interrupts disabled
1202 void hrtimer_interrupt(struct clock_event_device *dev)
1204 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1205 struct hrtimer_clock_base *base;
1206 ktime_t expires_next, now;
1210 BUG_ON(!cpu_base->hres_active);
1211 cpu_base->nr_events++;
1212 dev->next_event.tv64 = KTIME_MAX;
1215 /* 5 retries is enough to notice a hang */
1216 if (!(++nr_retries % 5))
1217 hrtimer_interrupt_hanging(dev, ktime_sub(ktime_get(), now));
1221 expires_next.tv64 = KTIME_MAX;
1223 base = cpu_base->clock_base;
1225 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1227 struct rb_node *node;
1229 spin_lock(&cpu_base->lock);
1231 basenow = ktime_add(now, base->offset);
1233 while ((node = base->first)) {
1234 struct hrtimer *timer;
1236 timer = rb_entry(node, struct hrtimer, node);
1239 * The immediate goal for using the softexpires is
1240 * minimizing wakeups, not running timers at the
1241 * earliest interrupt after their soft expiration.
1242 * This allows us to avoid using a Priority Search
1243 * Tree, which can answer a stabbing querry for
1244 * overlapping intervals and instead use the simple
1245 * BST we already have.
1246 * We don't add extra wakeups by delaying timers that
1247 * are right-of a not yet expired timer, because that
1248 * timer will have to trigger a wakeup anyway.
1251 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1254 expires = ktime_sub(hrtimer_get_expires(timer),
1256 if (expires.tv64 < expires_next.tv64)
1257 expires_next = expires;
1261 __run_hrtimer(timer);
1263 spin_unlock(&cpu_base->lock);
1267 cpu_base->expires_next = expires_next;
1269 /* Reprogramming necessary ? */
1270 if (expires_next.tv64 != KTIME_MAX) {
1271 if (tick_program_event(expires_next, force_clock_reprogram))
1277 * local version of hrtimer_peek_ahead_timers() called with interrupts
1280 static void __hrtimer_peek_ahead_timers(void)
1282 struct tick_device *td;
1284 if (!hrtimer_hres_active())
1287 td = &__get_cpu_var(tick_cpu_device);
1288 if (td && td->evtdev)
1289 hrtimer_interrupt(td->evtdev);
1293 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1295 * hrtimer_peek_ahead_timers will peek at the timer queue of
1296 * the current cpu and check if there are any timers for which
1297 * the soft expires time has passed. If any such timers exist,
1298 * they are run immediately and then removed from the timer queue.
1301 void hrtimer_peek_ahead_timers(void)
1303 unsigned long flags;
1305 local_irq_save(flags);
1306 __hrtimer_peek_ahead_timers();
1307 local_irq_restore(flags);
1310 static void run_hrtimer_softirq(struct softirq_action *h)
1312 hrtimer_peek_ahead_timers();
1315 #else /* CONFIG_HIGH_RES_TIMERS */
1317 static inline void __hrtimer_peek_ahead_timers(void) { }
1319 #endif /* !CONFIG_HIGH_RES_TIMERS */
1322 * Called from timer softirq every jiffy, expire hrtimers:
1324 * For HRT its the fall back code to run the softirq in the timer
1325 * softirq context in case the hrtimer initialization failed or has
1326 * not been done yet.
1328 void hrtimer_run_pending(void)
1330 if (hrtimer_hres_active())
1334 * This _is_ ugly: We have to check in the softirq context,
1335 * whether we can switch to highres and / or nohz mode. The
1336 * clocksource switch happens in the timer interrupt with
1337 * xtime_lock held. Notification from there only sets the
1338 * check bit in the tick_oneshot code, otherwise we might
1339 * deadlock vs. xtime_lock.
1341 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1342 hrtimer_switch_to_hres();
1346 * Called from hardirq context every jiffy
1348 void hrtimer_run_queues(void)
1350 struct rb_node *node;
1351 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1352 struct hrtimer_clock_base *base;
1353 int index, gettime = 1;
1355 if (hrtimer_hres_active())
1358 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1359 base = &cpu_base->clock_base[index];
1365 hrtimer_get_softirq_time(cpu_base);
1369 spin_lock(&cpu_base->lock);
1371 while ((node = base->first)) {
1372 struct hrtimer *timer;
1374 timer = rb_entry(node, struct hrtimer, node);
1375 if (base->softirq_time.tv64 <=
1376 hrtimer_get_expires_tv64(timer))
1379 __run_hrtimer(timer);
1381 spin_unlock(&cpu_base->lock);
1386 * Sleep related functions:
1388 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1390 struct hrtimer_sleeper *t =
1391 container_of(timer, struct hrtimer_sleeper, timer);
1392 struct task_struct *task = t->task;
1396 wake_up_process(task);
1398 return HRTIMER_NORESTART;
1401 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1403 sl->timer.function = hrtimer_wakeup;
1407 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1409 hrtimer_init_sleeper(t, current);
1412 set_current_state(TASK_INTERRUPTIBLE);
1413 hrtimer_start_expires(&t->timer, mode);
1414 if (!hrtimer_active(&t->timer))
1417 if (likely(t->task))
1420 hrtimer_cancel(&t->timer);
1421 mode = HRTIMER_MODE_ABS;
1423 } while (t->task && !signal_pending(current));
1425 __set_current_state(TASK_RUNNING);
1427 return t->task == NULL;
1430 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1432 struct timespec rmt;
1435 rem = hrtimer_expires_remaining(timer);
1438 rmt = ktime_to_timespec(rem);
1440 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1446 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1448 struct hrtimer_sleeper t;
1449 struct timespec __user *rmtp;
1452 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1454 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1456 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1459 rmtp = restart->nanosleep.rmtp;
1461 ret = update_rmtp(&t.timer, rmtp);
1466 /* The other values in restart are already filled in */
1467 ret = -ERESTART_RESTARTBLOCK;
1469 destroy_hrtimer_on_stack(&t.timer);
1473 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1474 const enum hrtimer_mode mode, const clockid_t clockid)
1476 struct restart_block *restart;
1477 struct hrtimer_sleeper t;
1479 unsigned long slack;
1481 slack = current->timer_slack_ns;
1482 if (rt_task(current))
1485 hrtimer_init_on_stack(&t.timer, clockid, mode);
1486 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1487 if (do_nanosleep(&t, mode))
1490 /* Absolute timers do not update the rmtp value and restart: */
1491 if (mode == HRTIMER_MODE_ABS) {
1492 ret = -ERESTARTNOHAND;
1497 ret = update_rmtp(&t.timer, rmtp);
1502 restart = ¤t_thread_info()->restart_block;
1503 restart->fn = hrtimer_nanosleep_restart;
1504 restart->nanosleep.index = t.timer.base->index;
1505 restart->nanosleep.rmtp = rmtp;
1506 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1508 ret = -ERESTART_RESTARTBLOCK;
1510 destroy_hrtimer_on_stack(&t.timer);
1514 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1515 struct timespec __user *, rmtp)
1519 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1522 if (!timespec_valid(&tu))
1525 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1529 * Functions related to boot-time initialization:
1531 static void __cpuinit init_hrtimers_cpu(int cpu)
1533 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1536 spin_lock_init(&cpu_base->lock);
1538 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1539 cpu_base->clock_base[i].cpu_base = cpu_base;
1541 hrtimer_init_hres(cpu_base);
1544 #ifdef CONFIG_HOTPLUG_CPU
1546 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1547 struct hrtimer_clock_base *new_base)
1549 struct hrtimer *timer;
1550 struct rb_node *node;
1552 while ((node = rb_first(&old_base->active))) {
1553 timer = rb_entry(node, struct hrtimer, node);
1554 BUG_ON(hrtimer_callback_running(timer));
1555 debug_hrtimer_deactivate(timer);
1558 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1559 * timer could be seen as !active and just vanish away
1560 * under us on another CPU
1562 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1563 timer->base = new_base;
1565 * Enqueue the timers on the new cpu. This does not
1566 * reprogram the event device in case the timer
1567 * expires before the earliest on this CPU, but we run
1568 * hrtimer_interrupt after we migrated everything to
1569 * sort out already expired timers and reprogram the
1572 enqueue_hrtimer(timer, new_base);
1574 /* Clear the migration state bit */
1575 timer->state &= ~HRTIMER_STATE_MIGRATE;
1579 static void migrate_hrtimers(int scpu)
1581 struct hrtimer_cpu_base *old_base, *new_base;
1584 BUG_ON(cpu_online(scpu));
1585 tick_cancel_sched_timer(scpu);
1587 local_irq_disable();
1588 old_base = &per_cpu(hrtimer_bases, scpu);
1589 new_base = &__get_cpu_var(hrtimer_bases);
1591 * The caller is globally serialized and nobody else
1592 * takes two locks at once, deadlock is not possible.
1594 spin_lock(&new_base->lock);
1595 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1597 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1598 migrate_hrtimer_list(&old_base->clock_base[i],
1599 &new_base->clock_base[i]);
1602 spin_unlock(&old_base->lock);
1603 spin_unlock(&new_base->lock);
1605 /* Check, if we got expired work to do */
1606 __hrtimer_peek_ahead_timers();
1610 #endif /* CONFIG_HOTPLUG_CPU */
1612 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1613 unsigned long action, void *hcpu)
1615 int scpu = (long)hcpu;
1619 case CPU_UP_PREPARE:
1620 case CPU_UP_PREPARE_FROZEN:
1621 init_hrtimers_cpu(scpu);
1624 #ifdef CONFIG_HOTPLUG_CPU
1626 case CPU_DYING_FROZEN:
1627 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1630 case CPU_DEAD_FROZEN:
1632 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1633 migrate_hrtimers(scpu);
1645 static struct notifier_block __cpuinitdata hrtimers_nb = {
1646 .notifier_call = hrtimer_cpu_notify,
1649 void __init hrtimers_init(void)
1651 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1652 (void *)(long)smp_processor_id());
1653 register_cpu_notifier(&hrtimers_nb);
1654 #ifdef CONFIG_HIGH_RES_TIMERS
1655 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1660 * schedule_hrtimeout_range - sleep until timeout
1661 * @expires: timeout value (ktime_t)
1662 * @delta: slack in expires timeout (ktime_t)
1663 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1665 * Make the current task sleep until the given expiry time has
1666 * elapsed. The routine will return immediately unless
1667 * the current task state has been set (see set_current_state()).
1669 * The @delta argument gives the kernel the freedom to schedule the
1670 * actual wakeup to a time that is both power and performance friendly.
1671 * The kernel give the normal best effort behavior for "@expires+@delta",
1672 * but may decide to fire the timer earlier, but no earlier than @expires.
1674 * You can set the task state as follows -
1676 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1677 * pass before the routine returns.
1679 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1680 * delivered to the current task.
1682 * The current task state is guaranteed to be TASK_RUNNING when this
1685 * Returns 0 when the timer has expired otherwise -EINTR
1687 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1688 const enum hrtimer_mode mode)
1690 struct hrtimer_sleeper t;
1693 * Optimize when a zero timeout value is given. It does not
1694 * matter whether this is an absolute or a relative time.
1696 if (expires && !expires->tv64) {
1697 __set_current_state(TASK_RUNNING);
1702 * A NULL parameter means "inifinte"
1706 __set_current_state(TASK_RUNNING);
1710 hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
1711 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1713 hrtimer_init_sleeper(&t, current);
1715 hrtimer_start_expires(&t.timer, mode);
1716 if (!hrtimer_active(&t.timer))
1722 hrtimer_cancel(&t.timer);
1723 destroy_hrtimer_on_stack(&t.timer);
1725 __set_current_state(TASK_RUNNING);
1727 return !t.task ? 0 : -EINTR;
1729 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1732 * schedule_hrtimeout - sleep until timeout
1733 * @expires: timeout value (ktime_t)
1734 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1736 * Make the current task sleep until the given expiry time has
1737 * elapsed. The routine will return immediately unless
1738 * the current task state has been set (see set_current_state()).
1740 * You can set the task state as follows -
1742 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1743 * pass before the routine returns.
1745 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1746 * delivered to the current task.
1748 * The current task state is guaranteed to be TASK_RUNNING when this
1751 * Returns 0 when the timer has expired otherwise -EINTR
1753 int __sched schedule_hrtimeout(ktime_t *expires,
1754 const enum hrtimer_mode mode)
1756 return schedule_hrtimeout_range(expires, 0, mode);
1758 EXPORT_SYMBOL_GPL(schedule_hrtimeout);