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 hrtimer_init_timer_hres(timer);
1097 #ifdef CONFIG_TIMER_STATS
1098 timer->start_site = NULL;
1099 timer->start_pid = -1;
1100 memset(timer->start_comm, 0, TASK_COMM_LEN);
1105 * hrtimer_init - initialize a timer to the given clock
1106 * @timer: the timer to be initialized
1107 * @clock_id: the clock to be used
1108 * @mode: timer mode abs/rel
1110 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1111 enum hrtimer_mode mode)
1113 debug_hrtimer_init(timer);
1114 __hrtimer_init(timer, clock_id, mode);
1116 EXPORT_SYMBOL_GPL(hrtimer_init);
1119 * hrtimer_get_res - get the timer resolution for a clock
1120 * @which_clock: which clock to query
1121 * @tp: pointer to timespec variable to store the resolution
1123 * Store the resolution of the clock selected by @which_clock in the
1124 * variable pointed to by @tp.
1126 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1128 struct hrtimer_cpu_base *cpu_base;
1130 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1131 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1135 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1137 static void __run_hrtimer(struct hrtimer *timer)
1139 struct hrtimer_clock_base *base = timer->base;
1140 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1141 enum hrtimer_restart (*fn)(struct hrtimer *);
1144 WARN_ON(!irqs_disabled());
1146 debug_hrtimer_deactivate(timer);
1147 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1148 timer_stats_account_hrtimer(timer);
1149 fn = timer->function;
1152 * Because we run timers from hardirq context, there is no chance
1153 * they get migrated to another cpu, therefore its safe to unlock
1156 spin_unlock(&cpu_base->lock);
1157 restart = fn(timer);
1158 spin_lock(&cpu_base->lock);
1161 * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1162 * we do not reprogramm the event hardware. Happens either in
1163 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1165 if (restart != HRTIMER_NORESTART) {
1166 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1167 enqueue_hrtimer(timer, base);
1169 timer->state &= ~HRTIMER_STATE_CALLBACK;
1172 #ifdef CONFIG_HIGH_RES_TIMERS
1174 static int force_clock_reprogram;
1177 * After 5 iteration's attempts, we consider that hrtimer_interrupt()
1178 * is hanging, which could happen with something that slows the interrupt
1179 * such as the tracing. Then we force the clock reprogramming for each future
1180 * hrtimer interrupts to avoid infinite loops and use the min_delta_ns
1181 * threshold that we will overwrite.
1182 * The next tick event will be scheduled to 3 times we currently spend on
1183 * hrtimer_interrupt(). This gives a good compromise, the cpus will spend
1184 * 1/4 of their time to process the hrtimer interrupts. This is enough to
1185 * let it running without serious starvation.
1189 hrtimer_interrupt_hanging(struct clock_event_device *dev,
1192 force_clock_reprogram = 1;
1193 dev->min_delta_ns = (unsigned long)try_time.tv64 * 3;
1194 printk(KERN_WARNING "hrtimer: interrupt too slow, "
1195 "forcing clock min delta to %lu ns\n", dev->min_delta_ns);
1198 * High resolution timer interrupt
1199 * Called with interrupts disabled
1201 void hrtimer_interrupt(struct clock_event_device *dev)
1203 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1204 struct hrtimer_clock_base *base;
1205 ktime_t expires_next, now;
1209 BUG_ON(!cpu_base->hres_active);
1210 cpu_base->nr_events++;
1211 dev->next_event.tv64 = KTIME_MAX;
1214 /* 5 retries is enough to notice a hang */
1215 if (!(++nr_retries % 5))
1216 hrtimer_interrupt_hanging(dev, ktime_sub(ktime_get(), now));
1220 expires_next.tv64 = KTIME_MAX;
1222 base = cpu_base->clock_base;
1224 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1226 struct rb_node *node;
1228 spin_lock(&cpu_base->lock);
1230 basenow = ktime_add(now, base->offset);
1232 while ((node = base->first)) {
1233 struct hrtimer *timer;
1235 timer = rb_entry(node, struct hrtimer, node);
1238 * The immediate goal for using the softexpires is
1239 * minimizing wakeups, not running timers at the
1240 * earliest interrupt after their soft expiration.
1241 * This allows us to avoid using a Priority Search
1242 * Tree, which can answer a stabbing querry for
1243 * overlapping intervals and instead use the simple
1244 * BST we already have.
1245 * We don't add extra wakeups by delaying timers that
1246 * are right-of a not yet expired timer, because that
1247 * timer will have to trigger a wakeup anyway.
1250 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1253 expires = ktime_sub(hrtimer_get_expires(timer),
1255 if (expires.tv64 < expires_next.tv64)
1256 expires_next = expires;
1260 __run_hrtimer(timer);
1262 spin_unlock(&cpu_base->lock);
1266 cpu_base->expires_next = expires_next;
1268 /* Reprogramming necessary ? */
1269 if (expires_next.tv64 != KTIME_MAX) {
1270 if (tick_program_event(expires_next, force_clock_reprogram))
1276 * local version of hrtimer_peek_ahead_timers() called with interrupts
1279 static void __hrtimer_peek_ahead_timers(void)
1281 struct tick_device *td;
1283 if (!hrtimer_hres_active())
1286 td = &__get_cpu_var(tick_cpu_device);
1287 if (td && td->evtdev)
1288 hrtimer_interrupt(td->evtdev);
1292 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1294 * hrtimer_peek_ahead_timers will peek at the timer queue of
1295 * the current cpu and check if there are any timers for which
1296 * the soft expires time has passed. If any such timers exist,
1297 * they are run immediately and then removed from the timer queue.
1300 void hrtimer_peek_ahead_timers(void)
1302 unsigned long flags;
1304 local_irq_save(flags);
1305 __hrtimer_peek_ahead_timers();
1306 local_irq_restore(flags);
1309 static void run_hrtimer_softirq(struct softirq_action *h)
1311 hrtimer_peek_ahead_timers();
1314 #else /* CONFIG_HIGH_RES_TIMERS */
1316 static inline void __hrtimer_peek_ahead_timers(void) { }
1318 #endif /* !CONFIG_HIGH_RES_TIMERS */
1321 * Called from timer softirq every jiffy, expire hrtimers:
1323 * For HRT its the fall back code to run the softirq in the timer
1324 * softirq context in case the hrtimer initialization failed or has
1325 * not been done yet.
1327 void hrtimer_run_pending(void)
1329 if (hrtimer_hres_active())
1333 * This _is_ ugly: We have to check in the softirq context,
1334 * whether we can switch to highres and / or nohz mode. The
1335 * clocksource switch happens in the timer interrupt with
1336 * xtime_lock held. Notification from there only sets the
1337 * check bit in the tick_oneshot code, otherwise we might
1338 * deadlock vs. xtime_lock.
1340 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1341 hrtimer_switch_to_hres();
1345 * Called from hardirq context every jiffy
1347 void hrtimer_run_queues(void)
1349 struct rb_node *node;
1350 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1351 struct hrtimer_clock_base *base;
1352 int index, gettime = 1;
1354 if (hrtimer_hres_active())
1357 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1358 base = &cpu_base->clock_base[index];
1364 hrtimer_get_softirq_time(cpu_base);
1368 spin_lock(&cpu_base->lock);
1370 while ((node = base->first)) {
1371 struct hrtimer *timer;
1373 timer = rb_entry(node, struct hrtimer, node);
1374 if (base->softirq_time.tv64 <=
1375 hrtimer_get_expires_tv64(timer))
1378 __run_hrtimer(timer);
1380 spin_unlock(&cpu_base->lock);
1385 * Sleep related functions:
1387 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1389 struct hrtimer_sleeper *t =
1390 container_of(timer, struct hrtimer_sleeper, timer);
1391 struct task_struct *task = t->task;
1395 wake_up_process(task);
1397 return HRTIMER_NORESTART;
1400 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1402 sl->timer.function = hrtimer_wakeup;
1406 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1408 hrtimer_init_sleeper(t, current);
1411 set_current_state(TASK_INTERRUPTIBLE);
1412 hrtimer_start_expires(&t->timer, mode);
1413 if (!hrtimer_active(&t->timer))
1416 if (likely(t->task))
1419 hrtimer_cancel(&t->timer);
1420 mode = HRTIMER_MODE_ABS;
1422 } while (t->task && !signal_pending(current));
1424 __set_current_state(TASK_RUNNING);
1426 return t->task == NULL;
1429 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1431 struct timespec rmt;
1434 rem = hrtimer_expires_remaining(timer);
1437 rmt = ktime_to_timespec(rem);
1439 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1445 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1447 struct hrtimer_sleeper t;
1448 struct timespec __user *rmtp;
1451 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1453 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1455 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1458 rmtp = restart->nanosleep.rmtp;
1460 ret = update_rmtp(&t.timer, rmtp);
1465 /* The other values in restart are already filled in */
1466 ret = -ERESTART_RESTARTBLOCK;
1468 destroy_hrtimer_on_stack(&t.timer);
1472 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1473 const enum hrtimer_mode mode, const clockid_t clockid)
1475 struct restart_block *restart;
1476 struct hrtimer_sleeper t;
1478 unsigned long slack;
1480 slack = current->timer_slack_ns;
1481 if (rt_task(current))
1484 hrtimer_init_on_stack(&t.timer, clockid, mode);
1485 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1486 if (do_nanosleep(&t, mode))
1489 /* Absolute timers do not update the rmtp value and restart: */
1490 if (mode == HRTIMER_MODE_ABS) {
1491 ret = -ERESTARTNOHAND;
1496 ret = update_rmtp(&t.timer, rmtp);
1501 restart = ¤t_thread_info()->restart_block;
1502 restart->fn = hrtimer_nanosleep_restart;
1503 restart->nanosleep.index = t.timer.base->index;
1504 restart->nanosleep.rmtp = rmtp;
1505 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1507 ret = -ERESTART_RESTARTBLOCK;
1509 destroy_hrtimer_on_stack(&t.timer);
1513 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1514 struct timespec __user *, rmtp)
1518 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1521 if (!timespec_valid(&tu))
1524 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1528 * Functions related to boot-time initialization:
1530 static void __cpuinit init_hrtimers_cpu(int cpu)
1532 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1535 spin_lock_init(&cpu_base->lock);
1537 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1538 cpu_base->clock_base[i].cpu_base = cpu_base;
1540 hrtimer_init_hres(cpu_base);
1543 #ifdef CONFIG_HOTPLUG_CPU
1545 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1546 struct hrtimer_clock_base *new_base)
1548 struct hrtimer *timer;
1549 struct rb_node *node;
1551 while ((node = rb_first(&old_base->active))) {
1552 timer = rb_entry(node, struct hrtimer, node);
1553 BUG_ON(hrtimer_callback_running(timer));
1554 debug_hrtimer_deactivate(timer);
1557 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1558 * timer could be seen as !active and just vanish away
1559 * under us on another CPU
1561 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1562 timer->base = new_base;
1564 * Enqueue the timers on the new cpu. This does not
1565 * reprogram the event device in case the timer
1566 * expires before the earliest on this CPU, but we run
1567 * hrtimer_interrupt after we migrated everything to
1568 * sort out already expired timers and reprogram the
1571 enqueue_hrtimer(timer, new_base);
1573 /* Clear the migration state bit */
1574 timer->state &= ~HRTIMER_STATE_MIGRATE;
1578 static void migrate_hrtimers(int scpu)
1580 struct hrtimer_cpu_base *old_base, *new_base;
1583 BUG_ON(cpu_online(scpu));
1584 tick_cancel_sched_timer(scpu);
1586 local_irq_disable();
1587 old_base = &per_cpu(hrtimer_bases, scpu);
1588 new_base = &__get_cpu_var(hrtimer_bases);
1590 * The caller is globally serialized and nobody else
1591 * takes two locks at once, deadlock is not possible.
1593 spin_lock(&new_base->lock);
1594 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1596 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1597 migrate_hrtimer_list(&old_base->clock_base[i],
1598 &new_base->clock_base[i]);
1601 spin_unlock(&old_base->lock);
1602 spin_unlock(&new_base->lock);
1604 /* Check, if we got expired work to do */
1605 __hrtimer_peek_ahead_timers();
1609 #endif /* CONFIG_HOTPLUG_CPU */
1611 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1612 unsigned long action, void *hcpu)
1614 int scpu = (long)hcpu;
1618 case CPU_UP_PREPARE:
1619 case CPU_UP_PREPARE_FROZEN:
1620 init_hrtimers_cpu(scpu);
1623 #ifdef CONFIG_HOTPLUG_CPU
1625 case CPU_DYING_FROZEN:
1626 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1629 case CPU_DEAD_FROZEN:
1631 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1632 migrate_hrtimers(scpu);
1644 static struct notifier_block __cpuinitdata hrtimers_nb = {
1645 .notifier_call = hrtimer_cpu_notify,
1648 void __init hrtimers_init(void)
1650 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1651 (void *)(long)smp_processor_id());
1652 register_cpu_notifier(&hrtimers_nb);
1653 #ifdef CONFIG_HIGH_RES_TIMERS
1654 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1659 * schedule_hrtimeout_range - sleep until timeout
1660 * @expires: timeout value (ktime_t)
1661 * @delta: slack in expires timeout (ktime_t)
1662 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1664 * Make the current task sleep until the given expiry time has
1665 * elapsed. The routine will return immediately unless
1666 * the current task state has been set (see set_current_state()).
1668 * The @delta argument gives the kernel the freedom to schedule the
1669 * actual wakeup to a time that is both power and performance friendly.
1670 * The kernel give the normal best effort behavior for "@expires+@delta",
1671 * but may decide to fire the timer earlier, but no earlier than @expires.
1673 * You can set the task state as follows -
1675 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1676 * pass before the routine returns.
1678 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1679 * delivered to the current task.
1681 * The current task state is guaranteed to be TASK_RUNNING when this
1684 * Returns 0 when the timer has expired otherwise -EINTR
1686 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1687 const enum hrtimer_mode mode)
1689 struct hrtimer_sleeper t;
1692 * Optimize when a zero timeout value is given. It does not
1693 * matter whether this is an absolute or a relative time.
1695 if (expires && !expires->tv64) {
1696 __set_current_state(TASK_RUNNING);
1701 * A NULL parameter means "inifinte"
1705 __set_current_state(TASK_RUNNING);
1709 hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
1710 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1712 hrtimer_init_sleeper(&t, current);
1714 hrtimer_start_expires(&t.timer, mode);
1715 if (!hrtimer_active(&t.timer))
1721 hrtimer_cancel(&t.timer);
1722 destroy_hrtimer_on_stack(&t.timer);
1724 __set_current_state(TASK_RUNNING);
1726 return !t.task ? 0 : -EINTR;
1728 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1731 * schedule_hrtimeout - sleep until timeout
1732 * @expires: timeout value (ktime_t)
1733 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1735 * Make the current task sleep until the given expiry time has
1736 * elapsed. The routine will return immediately unless
1737 * the current task state has been set (see set_current_state()).
1739 * You can set the task state as follows -
1741 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1742 * pass before the routine returns.
1744 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1745 * delivered to the current task.
1747 * The current task state is guaranteed to be TASK_RUNNING when this
1750 * Returns 0 when the timer has expired otherwise -EINTR
1752 int __sched schedule_hrtimeout(ktime_t *expires,
1753 const enum hrtimer_mode mode)
1755 return schedule_hrtimeout_range(expires, 0, mode);
1757 EXPORT_SYMBOL_GPL(schedule_hrtimeout);