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/irq.h>
36 #include <linux/module.h>
37 #include <linux/percpu.h>
38 #include <linux/hrtimer.h>
39 #include <linux/notifier.h>
40 #include <linux/syscalls.h>
41 #include <linux/kallsyms.h>
42 #include <linux/interrupt.h>
43 #include <linux/tick.h>
44 #include <linux/seq_file.h>
45 #include <linux/err.h>
46 #include <linux/debugobjects.h>
48 #include <asm/uaccess.h>
51 * ktime_get - get the monotonic time in ktime_t format
53 * returns the time in ktime_t format
55 ktime_t ktime_get(void)
61 return timespec_to_ktime(now);
63 EXPORT_SYMBOL_GPL(ktime_get);
66 * ktime_get_real - get the real (wall-) time in ktime_t format
68 * returns the time in ktime_t format
70 ktime_t ktime_get_real(void)
76 return timespec_to_ktime(now);
79 EXPORT_SYMBOL_GPL(ktime_get_real);
84 * Note: If we want to add new timer bases, we have to skip the two
85 * clock ids captured by the cpu-timers. We do this by holding empty
86 * entries rather than doing math adjustment of the clock ids.
87 * This ensures that we capture erroneous accesses to these clock ids
88 * rather than moving them into the range of valid clock id's.
90 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
96 .index = CLOCK_REALTIME,
97 .get_time = &ktime_get_real,
98 .resolution = KTIME_LOW_RES,
101 .index = CLOCK_MONOTONIC,
102 .get_time = &ktime_get,
103 .resolution = KTIME_LOW_RES,
109 * ktime_get_ts - get the monotonic clock in timespec format
110 * @ts: pointer to timespec variable
112 * The function calculates the monotonic clock from the realtime
113 * clock and the wall_to_monotonic offset and stores the result
114 * in normalized timespec format in the variable pointed to by @ts.
116 void ktime_get_ts(struct timespec *ts)
118 struct timespec tomono;
122 seq = read_seqbegin(&xtime_lock);
124 tomono = wall_to_monotonic;
126 } while (read_seqretry(&xtime_lock, seq));
128 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
129 ts->tv_nsec + tomono.tv_nsec);
131 EXPORT_SYMBOL_GPL(ktime_get_ts);
134 * Get the coarse grained time at the softirq based on xtime and
137 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
139 ktime_t xtim, tomono;
140 struct timespec xts, tom;
144 seq = read_seqbegin(&xtime_lock);
145 xts = current_kernel_time();
146 tom = wall_to_monotonic;
147 } while (read_seqretry(&xtime_lock, seq));
149 xtim = timespec_to_ktime(xts);
150 tomono = timespec_to_ktime(tom);
151 base->clock_base[CLOCK_REALTIME].softirq_time = xtim;
152 base->clock_base[CLOCK_MONOTONIC].softirq_time =
153 ktime_add(xtim, tomono);
157 * Functions and macros which are different for UP/SMP systems are kept in a
163 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
164 * means that all timers which are tied to this base via timer->base are
165 * locked, and the base itself is locked too.
167 * So __run_timers/migrate_timers can safely modify all timers which could
168 * be found on the lists/queues.
170 * When the timer's base is locked, and the timer removed from list, it is
171 * possible to set timer->base = NULL and drop the lock: the timer remains
175 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
176 unsigned long *flags)
178 struct hrtimer_clock_base *base;
182 if (likely(base != NULL)) {
183 spin_lock_irqsave(&base->cpu_base->lock, *flags);
184 if (likely(base == timer->base))
186 /* The timer has migrated to another CPU: */
187 spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
194 * Switch the timer base to the current CPU when possible.
196 static inline struct hrtimer_clock_base *
197 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 = dns = ktime_to_ns(kt);
308 /* Make sure the divisor is less than 2^32: */
314 do_div(dclc, (unsigned long) div);
318 #endif /* BITS_PER_LONG >= 64 */
321 * Add two ktime values and do a safety check for overflow:
323 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
325 ktime_t res = ktime_add(lhs, rhs);
328 * We use KTIME_SEC_MAX here, the maximum timeout which we can
329 * return to user space in a timespec:
331 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
332 res = ktime_set(KTIME_SEC_MAX, 0);
337 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
339 static struct debug_obj_descr hrtimer_debug_descr;
342 * fixup_init is called when:
343 * - an active object is initialized
345 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
347 struct hrtimer *timer = addr;
350 case ODEBUG_STATE_ACTIVE:
351 hrtimer_cancel(timer);
352 debug_object_init(timer, &hrtimer_debug_descr);
360 * fixup_activate is called when:
361 * - an active object is activated
362 * - an unknown object is activated (might be a statically initialized object)
364 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
368 case ODEBUG_STATE_NOTAVAILABLE:
372 case ODEBUG_STATE_ACTIVE:
381 * fixup_free is called when:
382 * - an active object is freed
384 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
386 struct hrtimer *timer = addr;
389 case ODEBUG_STATE_ACTIVE:
390 hrtimer_cancel(timer);
391 debug_object_free(timer, &hrtimer_debug_descr);
398 static struct debug_obj_descr hrtimer_debug_descr = {
400 .fixup_init = hrtimer_fixup_init,
401 .fixup_activate = hrtimer_fixup_activate,
402 .fixup_free = hrtimer_fixup_free,
405 static inline void debug_hrtimer_init(struct hrtimer *timer)
407 debug_object_init(timer, &hrtimer_debug_descr);
410 static inline void debug_hrtimer_activate(struct hrtimer *timer)
412 debug_object_activate(timer, &hrtimer_debug_descr);
415 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
417 debug_object_deactivate(timer, &hrtimer_debug_descr);
420 static inline void debug_hrtimer_free(struct hrtimer *timer)
422 debug_object_free(timer, &hrtimer_debug_descr);
425 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
426 enum hrtimer_mode mode);
428 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
429 enum hrtimer_mode mode)
431 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
432 __hrtimer_init(timer, clock_id, mode);
435 void destroy_hrtimer_on_stack(struct hrtimer *timer)
437 debug_object_free(timer, &hrtimer_debug_descr);
441 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
442 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
443 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
447 * Check, whether the timer is on the callback pending list
449 static inline int hrtimer_cb_pending(const struct hrtimer *timer)
451 return timer->state & HRTIMER_STATE_PENDING;
455 * Remove a timer from the callback pending list
457 static inline void hrtimer_remove_cb_pending(struct hrtimer *timer)
459 list_del_init(&timer->cb_entry);
462 /* High resolution timer related functions */
463 #ifdef CONFIG_HIGH_RES_TIMERS
466 * High resolution timer enabled ?
468 static int hrtimer_hres_enabled __read_mostly = 1;
471 * Enable / Disable high resolution mode
473 static int __init setup_hrtimer_hres(char *str)
475 if (!strcmp(str, "off"))
476 hrtimer_hres_enabled = 0;
477 else if (!strcmp(str, "on"))
478 hrtimer_hres_enabled = 1;
484 __setup("highres=", setup_hrtimer_hres);
487 * hrtimer_high_res_enabled - query, if the highres mode is enabled
489 static inline int hrtimer_is_hres_enabled(void)
491 return hrtimer_hres_enabled;
495 * Is the high resolution mode active ?
497 static inline int hrtimer_hres_active(void)
499 return __get_cpu_var(hrtimer_bases).hres_active;
503 * Reprogram the event source with checking both queues for the
505 * Called with interrupts disabled and base->lock held
507 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
510 struct hrtimer_clock_base *base = cpu_base->clock_base;
513 cpu_base->expires_next.tv64 = KTIME_MAX;
515 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
516 struct hrtimer *timer;
520 timer = rb_entry(base->first, struct hrtimer, node);
521 expires = ktime_sub(timer->expires, base->offset);
522 if (expires.tv64 < cpu_base->expires_next.tv64)
523 cpu_base->expires_next = expires;
526 if (cpu_base->expires_next.tv64 != KTIME_MAX)
527 tick_program_event(cpu_base->expires_next, 1);
531 * Shared reprogramming for clock_realtime and clock_monotonic
533 * When a timer is enqueued and expires earlier than the already enqueued
534 * timers, we have to check, whether it expires earlier than the timer for
535 * which the clock event device was armed.
537 * Called with interrupts disabled and base->cpu_base.lock held
539 static int hrtimer_reprogram(struct hrtimer *timer,
540 struct hrtimer_clock_base *base)
542 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
543 ktime_t expires = ktime_sub(timer->expires, base->offset);
546 WARN_ON_ONCE(timer->expires.tv64 < 0);
549 * When the callback is running, we do not reprogram the clock event
550 * device. The timer callback is either running on a different CPU or
551 * the callback is executed in the hrtimer_interrupt context. The
552 * reprogramming is handled either by the softirq, which called the
553 * callback or at the end of the hrtimer_interrupt.
555 if (hrtimer_callback_running(timer))
559 * CLOCK_REALTIME timer might be requested with an absolute
560 * expiry time which is less than base->offset. Nothing wrong
561 * about that, just avoid to call into the tick code, which
562 * has now objections against negative expiry values.
564 if (expires.tv64 < 0)
567 if (expires.tv64 >= expires_next->tv64)
571 * Clockevents returns -ETIME, when the event was in the past.
573 res = tick_program_event(expires, 0);
574 if (!IS_ERR_VALUE(res))
575 *expires_next = expires;
581 * Retrigger next event is called after clock was set
583 * Called with interrupts disabled via on_each_cpu()
585 static void retrigger_next_event(void *arg)
587 struct hrtimer_cpu_base *base;
588 struct timespec realtime_offset;
591 if (!hrtimer_hres_active())
595 seq = read_seqbegin(&xtime_lock);
596 set_normalized_timespec(&realtime_offset,
597 -wall_to_monotonic.tv_sec,
598 -wall_to_monotonic.tv_nsec);
599 } while (read_seqretry(&xtime_lock, seq));
601 base = &__get_cpu_var(hrtimer_bases);
603 /* Adjust CLOCK_REALTIME offset */
604 spin_lock(&base->lock);
605 base->clock_base[CLOCK_REALTIME].offset =
606 timespec_to_ktime(realtime_offset);
608 hrtimer_force_reprogram(base);
609 spin_unlock(&base->lock);
613 * Clock realtime was set
615 * Change the offset of the realtime clock vs. the monotonic
618 * We might have to reprogram the high resolution timer interrupt. On
619 * SMP we call the architecture specific code to retrigger _all_ high
620 * resolution timer interrupts. On UP we just disable interrupts and
621 * call the high resolution interrupt code.
623 void clock_was_set(void)
625 /* Retrigger the CPU local events everywhere */
626 on_each_cpu(retrigger_next_event, NULL, 0, 1);
630 * During resume we might have to reprogram the high resolution timer
631 * interrupt (on the local CPU):
633 void hres_timers_resume(void)
635 WARN_ON_ONCE(num_online_cpus() > 1);
637 /* Retrigger the CPU local events: */
638 retrigger_next_event(NULL);
642 * Initialize the high resolution related parts of cpu_base
644 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
646 base->expires_next.tv64 = KTIME_MAX;
647 base->hres_active = 0;
651 * Initialize the high resolution related parts of a hrtimer
653 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
658 * When High resolution timers are active, try to reprogram. Note, that in case
659 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
660 * check happens. The timer gets enqueued into the rbtree. The reprogramming
661 * and expiry check is done in the hrtimer_interrupt or in the softirq.
663 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
664 struct hrtimer_clock_base *base)
666 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
668 /* Timer is expired, act upon the callback mode */
669 switch(timer->cb_mode) {
670 case HRTIMER_CB_IRQSAFE_NO_RESTART:
671 debug_hrtimer_deactivate(timer);
673 * We can call the callback from here. No restart
674 * happens, so no danger of recursion
676 BUG_ON(timer->function(timer) != HRTIMER_NORESTART);
678 case HRTIMER_CB_IRQSAFE_NO_SOFTIRQ:
680 * This is solely for the sched tick emulation with
681 * dynamic tick support to ensure that we do not
682 * restart the tick right on the edge and end up with
683 * the tick timer in the softirq ! The calling site
684 * takes care of this.
686 debug_hrtimer_deactivate(timer);
688 case HRTIMER_CB_IRQSAFE:
689 case HRTIMER_CB_SOFTIRQ:
691 * Move everything else into the softirq pending list !
693 list_add_tail(&timer->cb_entry,
694 &base->cpu_base->cb_pending);
695 timer->state = HRTIMER_STATE_PENDING;
705 * Switch to high resolution mode
707 static int hrtimer_switch_to_hres(void)
709 int cpu = smp_processor_id();
710 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
713 if (base->hres_active)
716 local_irq_save(flags);
718 if (tick_init_highres()) {
719 local_irq_restore(flags);
720 printk(KERN_WARNING "Could not switch to high resolution "
721 "mode on CPU %d\n", cpu);
724 base->hres_active = 1;
725 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
726 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
728 tick_setup_sched_timer();
730 /* "Retrigger" the interrupt to get things going */
731 retrigger_next_event(NULL);
732 local_irq_restore(flags);
733 printk(KERN_DEBUG "Switched to high resolution mode on CPU %d\n",
738 static inline void hrtimer_raise_softirq(void)
740 raise_softirq(HRTIMER_SOFTIRQ);
745 static inline int hrtimer_hres_active(void) { return 0; }
746 static inline int hrtimer_is_hres_enabled(void) { return 0; }
747 static inline int hrtimer_switch_to_hres(void) { return 0; }
748 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
749 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
750 struct hrtimer_clock_base *base)
754 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
755 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
756 static inline int hrtimer_reprogram(struct hrtimer *timer,
757 struct hrtimer_clock_base *base)
761 static inline void hrtimer_raise_softirq(void) { }
763 #endif /* CONFIG_HIGH_RES_TIMERS */
765 #ifdef CONFIG_TIMER_STATS
766 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
768 if (timer->start_site)
771 timer->start_site = addr;
772 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
773 timer->start_pid = current->pid;
778 * Counterpart to lock_hrtimer_base above:
781 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
783 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
787 * hrtimer_forward - forward the timer expiry
788 * @timer: hrtimer to forward
789 * @now: forward past this time
790 * @interval: the interval to forward
792 * Forward the timer expiry so it will expire in the future.
793 * Returns the number of overruns.
795 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
800 delta = ktime_sub(now, timer->expires);
805 if (interval.tv64 < timer->base->resolution.tv64)
806 interval.tv64 = timer->base->resolution.tv64;
808 if (unlikely(delta.tv64 >= interval.tv64)) {
809 s64 incr = ktime_to_ns(interval);
811 orun = ktime_divns(delta, incr);
812 timer->expires = ktime_add_ns(timer->expires, incr * orun);
813 if (timer->expires.tv64 > now.tv64)
816 * This (and the ktime_add() below) is the
817 * correction for exact:
821 timer->expires = ktime_add_safe(timer->expires, interval);
825 EXPORT_SYMBOL_GPL(hrtimer_forward);
828 * enqueue_hrtimer - internal function to (re)start a timer
830 * The timer is inserted in expiry order. Insertion into the
831 * red black tree is O(log(n)). Must hold the base lock.
833 static void enqueue_hrtimer(struct hrtimer *timer,
834 struct hrtimer_clock_base *base, int reprogram)
836 struct rb_node **link = &base->active.rb_node;
837 struct rb_node *parent = NULL;
838 struct hrtimer *entry;
841 debug_hrtimer_activate(timer);
844 * Find the right place in the rbtree:
848 entry = rb_entry(parent, struct hrtimer, node);
850 * We dont care about collisions. Nodes with
851 * the same expiry time stay together.
853 if (timer->expires.tv64 < entry->expires.tv64) {
854 link = &(*link)->rb_left;
856 link = &(*link)->rb_right;
862 * Insert the timer to the rbtree and check whether it
863 * replaces the first pending timer
867 * Reprogram the clock event device. When the timer is already
868 * expired hrtimer_enqueue_reprogram has either called the
869 * callback or added it to the pending list and raised the
872 * This is a NOP for !HIGHRES
874 if (reprogram && hrtimer_enqueue_reprogram(timer, base))
877 base->first = &timer->node;
880 rb_link_node(&timer->node, parent, link);
881 rb_insert_color(&timer->node, &base->active);
883 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
884 * state of a possibly running callback.
886 timer->state |= HRTIMER_STATE_ENQUEUED;
890 * __remove_hrtimer - internal function to remove a timer
892 * Caller must hold the base lock.
894 * High resolution timer mode reprograms the clock event device when the
895 * timer is the one which expires next. The caller can disable this by setting
896 * reprogram to zero. This is useful, when the context does a reprogramming
897 * anyway (e.g. timer interrupt)
899 static void __remove_hrtimer(struct hrtimer *timer,
900 struct hrtimer_clock_base *base,
901 unsigned long newstate, int reprogram)
903 /* High res. callback list. NOP for !HIGHRES */
904 if (hrtimer_cb_pending(timer))
905 hrtimer_remove_cb_pending(timer);
908 * Remove the timer from the rbtree and replace the
909 * first entry pointer if necessary.
911 if (base->first == &timer->node) {
912 base->first = rb_next(&timer->node);
913 /* Reprogram the clock event device. if enabled */
914 if (reprogram && hrtimer_hres_active())
915 hrtimer_force_reprogram(base->cpu_base);
917 rb_erase(&timer->node, &base->active);
919 timer->state = newstate;
923 * remove hrtimer, called with base lock held
926 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
928 if (hrtimer_is_queued(timer)) {
932 * Remove the timer and force reprogramming when high
933 * resolution mode is active and the timer is on the current
934 * CPU. If we remove a timer on another CPU, reprogramming is
935 * skipped. The interrupt event on this CPU is fired and
936 * reprogramming happens in the interrupt handler. This is a
937 * rare case and less expensive than a smp call.
939 debug_hrtimer_deactivate(timer);
940 timer_stats_hrtimer_clear_start_info(timer);
941 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
942 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
950 * hrtimer_start - (re)start an relative timer on the current CPU
951 * @timer: the timer to be added
953 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
957 * 1 when the timer was active
960 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
962 struct hrtimer_clock_base *base, *new_base;
966 base = lock_hrtimer_base(timer, &flags);
968 /* Remove an active timer from the queue: */
969 ret = remove_hrtimer(timer, base);
971 /* Switch the timer base, if necessary: */
972 new_base = switch_hrtimer_base(timer, base);
974 if (mode == HRTIMER_MODE_REL) {
975 tim = ktime_add_safe(tim, new_base->get_time());
977 * CONFIG_TIME_LOW_RES is a temporary way for architectures
978 * to signal that they simply return xtime in
979 * do_gettimeoffset(). In this case we want to round up by
980 * resolution when starting a relative timer, to avoid short
981 * timeouts. This will go away with the GTOD framework.
983 #ifdef CONFIG_TIME_LOW_RES
984 tim = ktime_add_safe(tim, base->resolution);
988 timer->expires = tim;
990 timer_stats_hrtimer_set_start_info(timer);
993 * Only allow reprogramming if the new base is on this CPU.
994 * (it might still be on another CPU if the timer was pending)
996 enqueue_hrtimer(timer, new_base,
997 new_base->cpu_base == &__get_cpu_var(hrtimer_bases));
1000 * The timer may be expired and moved to the cb_pending
1001 * list. We can not raise the softirq with base lock held due
1002 * to a possible deadlock with runqueue lock.
1004 raise = timer->state == HRTIMER_STATE_PENDING;
1007 * We use preempt_disable to prevent this task from migrating after
1008 * setting up the softirq and raising it. Otherwise, if me migrate
1009 * we will raise the softirq on the wrong CPU.
1013 unlock_hrtimer_base(timer, &flags);
1016 hrtimer_raise_softirq();
1021 EXPORT_SYMBOL_GPL(hrtimer_start);
1024 * hrtimer_try_to_cancel - try to deactivate a timer
1025 * @timer: hrtimer to stop
1028 * 0 when the timer was not active
1029 * 1 when the timer was active
1030 * -1 when the timer is currently excuting the callback function and
1033 int hrtimer_try_to_cancel(struct hrtimer *timer)
1035 struct hrtimer_clock_base *base;
1036 unsigned long flags;
1039 base = lock_hrtimer_base(timer, &flags);
1041 if (!hrtimer_callback_running(timer))
1042 ret = remove_hrtimer(timer, base);
1044 unlock_hrtimer_base(timer, &flags);
1049 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1052 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1053 * @timer: the timer to be cancelled
1056 * 0 when the timer was not active
1057 * 1 when the timer was active
1059 int hrtimer_cancel(struct hrtimer *timer)
1062 int ret = hrtimer_try_to_cancel(timer);
1069 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1072 * hrtimer_get_remaining - get remaining time for the timer
1073 * @timer: the timer to read
1075 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1077 struct hrtimer_clock_base *base;
1078 unsigned long flags;
1081 base = lock_hrtimer_base(timer, &flags);
1082 rem = ktime_sub(timer->expires, base->get_time());
1083 unlock_hrtimer_base(timer, &flags);
1087 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1089 #if defined(CONFIG_NO_IDLE_HZ) || defined(CONFIG_NO_HZ)
1091 * hrtimer_get_next_event - get the time until next expiry event
1093 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1096 ktime_t hrtimer_get_next_event(void)
1098 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1099 struct hrtimer_clock_base *base = cpu_base->clock_base;
1100 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1101 unsigned long flags;
1104 spin_lock_irqsave(&cpu_base->lock, flags);
1106 if (!hrtimer_hres_active()) {
1107 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1108 struct hrtimer *timer;
1113 timer = rb_entry(base->first, struct hrtimer, node);
1114 delta.tv64 = timer->expires.tv64;
1115 delta = ktime_sub(delta, base->get_time());
1116 if (delta.tv64 < mindelta.tv64)
1117 mindelta.tv64 = delta.tv64;
1121 spin_unlock_irqrestore(&cpu_base->lock, flags);
1123 if (mindelta.tv64 < 0)
1129 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1130 enum hrtimer_mode mode)
1132 struct hrtimer_cpu_base *cpu_base;
1134 memset(timer, 0, sizeof(struct hrtimer));
1136 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1138 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1139 clock_id = CLOCK_MONOTONIC;
1141 timer->base = &cpu_base->clock_base[clock_id];
1142 INIT_LIST_HEAD(&timer->cb_entry);
1143 hrtimer_init_timer_hres(timer);
1145 #ifdef CONFIG_TIMER_STATS
1146 timer->start_site = NULL;
1147 timer->start_pid = -1;
1148 memset(timer->start_comm, 0, TASK_COMM_LEN);
1153 * hrtimer_init - initialize a timer to the given clock
1154 * @timer: the timer to be initialized
1155 * @clock_id: the clock to be used
1156 * @mode: timer mode abs/rel
1158 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1159 enum hrtimer_mode mode)
1161 debug_hrtimer_init(timer);
1162 __hrtimer_init(timer, clock_id, mode);
1164 EXPORT_SYMBOL_GPL(hrtimer_init);
1167 * hrtimer_get_res - get the timer resolution for a clock
1168 * @which_clock: which clock to query
1169 * @tp: pointer to timespec variable to store the resolution
1171 * Store the resolution of the clock selected by @which_clock in the
1172 * variable pointed to by @tp.
1174 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1176 struct hrtimer_cpu_base *cpu_base;
1178 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1179 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1183 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1185 static void run_hrtimer_pending(struct hrtimer_cpu_base *cpu_base)
1187 spin_lock_irq(&cpu_base->lock);
1189 while (!list_empty(&cpu_base->cb_pending)) {
1190 enum hrtimer_restart (*fn)(struct hrtimer *);
1191 struct hrtimer *timer;
1194 timer = list_entry(cpu_base->cb_pending.next,
1195 struct hrtimer, cb_entry);
1197 debug_hrtimer_deactivate(timer);
1198 timer_stats_account_hrtimer(timer);
1200 fn = timer->function;
1201 __remove_hrtimer(timer, timer->base, HRTIMER_STATE_CALLBACK, 0);
1202 spin_unlock_irq(&cpu_base->lock);
1204 restart = fn(timer);
1206 spin_lock_irq(&cpu_base->lock);
1208 timer->state &= ~HRTIMER_STATE_CALLBACK;
1209 if (restart == HRTIMER_RESTART) {
1210 BUG_ON(hrtimer_active(timer));
1212 * Enqueue the timer, allow reprogramming of the event
1215 enqueue_hrtimer(timer, timer->base, 1);
1216 } else if (hrtimer_active(timer)) {
1218 * If the timer was rearmed on another CPU, reprogram
1221 struct hrtimer_clock_base *base = timer->base;
1223 if (base->first == &timer->node &&
1224 hrtimer_reprogram(timer, base)) {
1226 * Timer is expired. Thus move it from tree to
1227 * pending list again.
1229 __remove_hrtimer(timer, base,
1230 HRTIMER_STATE_PENDING, 0);
1231 list_add_tail(&timer->cb_entry,
1232 &base->cpu_base->cb_pending);
1236 spin_unlock_irq(&cpu_base->lock);
1239 static void __run_hrtimer(struct hrtimer *timer)
1241 struct hrtimer_clock_base *base = timer->base;
1242 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1243 enum hrtimer_restart (*fn)(struct hrtimer *);
1246 debug_hrtimer_deactivate(timer);
1247 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1248 timer_stats_account_hrtimer(timer);
1250 fn = timer->function;
1251 if (timer->cb_mode == HRTIMER_CB_IRQSAFE_NO_SOFTIRQ) {
1253 * Used for scheduler timers, avoid lock inversion with
1254 * rq->lock and tasklist_lock.
1256 * These timers are required to deal with enqueue expiry
1257 * themselves and are not allowed to migrate.
1259 spin_unlock(&cpu_base->lock);
1260 restart = fn(timer);
1261 spin_lock(&cpu_base->lock);
1263 restart = fn(timer);
1266 * Note: We clear the CALLBACK bit after enqueue_hrtimer to avoid
1267 * reprogramming of the event hardware. This happens at the end of this
1270 if (restart != HRTIMER_NORESTART) {
1271 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1272 enqueue_hrtimer(timer, base, 0);
1274 timer->state &= ~HRTIMER_STATE_CALLBACK;
1277 #ifdef CONFIG_HIGH_RES_TIMERS
1280 * High resolution timer interrupt
1281 * Called with interrupts disabled
1283 void hrtimer_interrupt(struct clock_event_device *dev)
1285 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1286 struct hrtimer_clock_base *base;
1287 ktime_t expires_next, now;
1290 BUG_ON(!cpu_base->hres_active);
1291 cpu_base->nr_events++;
1292 dev->next_event.tv64 = KTIME_MAX;
1297 expires_next.tv64 = KTIME_MAX;
1299 base = cpu_base->clock_base;
1301 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1303 struct rb_node *node;
1305 spin_lock(&cpu_base->lock);
1307 basenow = ktime_add(now, base->offset);
1309 while ((node = base->first)) {
1310 struct hrtimer *timer;
1312 timer = rb_entry(node, struct hrtimer, node);
1314 if (basenow.tv64 < timer->expires.tv64) {
1317 expires = ktime_sub(timer->expires,
1319 if (expires.tv64 < expires_next.tv64)
1320 expires_next = expires;
1324 /* Move softirq callbacks to the pending list */
1325 if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1326 __remove_hrtimer(timer, base,
1327 HRTIMER_STATE_PENDING, 0);
1328 list_add_tail(&timer->cb_entry,
1329 &base->cpu_base->cb_pending);
1334 __run_hrtimer(timer);
1336 spin_unlock(&cpu_base->lock);
1340 cpu_base->expires_next = expires_next;
1342 /* Reprogramming necessary ? */
1343 if (expires_next.tv64 != KTIME_MAX) {
1344 if (tick_program_event(expires_next, 0))
1348 /* Raise softirq ? */
1350 raise_softirq(HRTIMER_SOFTIRQ);
1353 static void run_hrtimer_softirq(struct softirq_action *h)
1355 run_hrtimer_pending(&__get_cpu_var(hrtimer_bases));
1358 #endif /* CONFIG_HIGH_RES_TIMERS */
1361 * Called from timer softirq every jiffy, expire hrtimers:
1363 * For HRT its the fall back code to run the softirq in the timer
1364 * softirq context in case the hrtimer initialization failed or has
1365 * not been done yet.
1367 void hrtimer_run_pending(void)
1369 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1371 if (hrtimer_hres_active())
1375 * This _is_ ugly: We have to check in the softirq context,
1376 * whether we can switch to highres and / or nohz mode. The
1377 * clocksource switch happens in the timer interrupt with
1378 * xtime_lock held. Notification from there only sets the
1379 * check bit in the tick_oneshot code, otherwise we might
1380 * deadlock vs. xtime_lock.
1382 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1383 hrtimer_switch_to_hres();
1385 run_hrtimer_pending(cpu_base);
1389 * Called from hardirq context every jiffy
1391 void hrtimer_run_queues(void)
1393 struct rb_node *node;
1394 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1395 struct hrtimer_clock_base *base;
1396 int index, gettime = 1;
1398 if (hrtimer_hres_active())
1401 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1402 base = &cpu_base->clock_base[index];
1407 if (base->get_softirq_time)
1408 base->softirq_time = base->get_softirq_time();
1410 hrtimer_get_softirq_time(cpu_base);
1414 spin_lock(&cpu_base->lock);
1416 while ((node = base->first)) {
1417 struct hrtimer *timer;
1419 timer = rb_entry(node, struct hrtimer, node);
1420 if (base->softirq_time.tv64 <= timer->expires.tv64)
1423 if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1424 __remove_hrtimer(timer, base,
1425 HRTIMER_STATE_PENDING, 0);
1426 list_add_tail(&timer->cb_entry,
1427 &base->cpu_base->cb_pending);
1431 __run_hrtimer(timer);
1433 spin_unlock(&cpu_base->lock);
1438 * Sleep related functions:
1440 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1442 struct hrtimer_sleeper *t =
1443 container_of(timer, struct hrtimer_sleeper, timer);
1444 struct task_struct *task = t->task;
1448 wake_up_process(task);
1450 return HRTIMER_NORESTART;
1453 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1455 sl->timer.function = hrtimer_wakeup;
1457 #ifdef CONFIG_HIGH_RES_TIMERS
1458 sl->timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1462 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1464 hrtimer_init_sleeper(t, current);
1467 set_current_state(TASK_INTERRUPTIBLE);
1468 hrtimer_start(&t->timer, t->timer.expires, mode);
1469 if (!hrtimer_active(&t->timer))
1472 if (likely(t->task))
1475 hrtimer_cancel(&t->timer);
1476 mode = HRTIMER_MODE_ABS;
1478 } while (t->task && !signal_pending(current));
1480 __set_current_state(TASK_RUNNING);
1482 return t->task == NULL;
1485 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1487 struct timespec rmt;
1490 rem = ktime_sub(timer->expires, timer->base->get_time());
1493 rmt = ktime_to_timespec(rem);
1495 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1501 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1503 struct hrtimer_sleeper t;
1504 struct timespec __user *rmtp;
1507 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1509 t.timer.expires.tv64 = restart->nanosleep.expires;
1511 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1514 rmtp = restart->nanosleep.rmtp;
1516 ret = update_rmtp(&t.timer, rmtp);
1521 /* The other values in restart are already filled in */
1522 ret = -ERESTART_RESTARTBLOCK;
1524 destroy_hrtimer_on_stack(&t.timer);
1528 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1529 const enum hrtimer_mode mode, const clockid_t clockid)
1531 struct restart_block *restart;
1532 struct hrtimer_sleeper t;
1535 hrtimer_init_on_stack(&t.timer, clockid, mode);
1536 t.timer.expires = timespec_to_ktime(*rqtp);
1537 if (do_nanosleep(&t, mode))
1540 /* Absolute timers do not update the rmtp value and restart: */
1541 if (mode == HRTIMER_MODE_ABS) {
1542 ret = -ERESTARTNOHAND;
1547 ret = update_rmtp(&t.timer, rmtp);
1552 restart = ¤t_thread_info()->restart_block;
1553 restart->fn = hrtimer_nanosleep_restart;
1554 restart->nanosleep.index = t.timer.base->index;
1555 restart->nanosleep.rmtp = rmtp;
1556 restart->nanosleep.expires = t.timer.expires.tv64;
1558 ret = -ERESTART_RESTARTBLOCK;
1560 destroy_hrtimer_on_stack(&t.timer);
1565 sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1569 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1572 if (!timespec_valid(&tu))
1575 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1579 * Functions related to boot-time initialization:
1581 static void __cpuinit init_hrtimers_cpu(int cpu)
1583 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1586 spin_lock_init(&cpu_base->lock);
1588 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1589 cpu_base->clock_base[i].cpu_base = cpu_base;
1591 INIT_LIST_HEAD(&cpu_base->cb_pending);
1592 hrtimer_init_hres(cpu_base);
1595 #ifdef CONFIG_HOTPLUG_CPU
1597 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1598 struct hrtimer_clock_base *new_base)
1600 struct hrtimer *timer;
1601 struct rb_node *node;
1603 while ((node = rb_first(&old_base->active))) {
1604 timer = rb_entry(node, struct hrtimer, node);
1605 BUG_ON(hrtimer_callback_running(timer));
1606 debug_hrtimer_deactivate(timer);
1607 __remove_hrtimer(timer, old_base, HRTIMER_STATE_INACTIVE, 0);
1608 timer->base = new_base;
1610 * Enqueue the timer. Allow reprogramming of the event device
1612 enqueue_hrtimer(timer, new_base, 1);
1616 static void migrate_hrtimers(int cpu)
1618 struct hrtimer_cpu_base *old_base, *new_base;
1621 BUG_ON(cpu_online(cpu));
1622 old_base = &per_cpu(hrtimer_bases, cpu);
1623 new_base = &get_cpu_var(hrtimer_bases);
1625 tick_cancel_sched_timer(cpu);
1627 local_irq_disable();
1628 spin_lock(&new_base->lock);
1629 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1631 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1632 migrate_hrtimer_list(&old_base->clock_base[i],
1633 &new_base->clock_base[i]);
1636 spin_unlock(&old_base->lock);
1637 spin_unlock(&new_base->lock);
1639 put_cpu_var(hrtimer_bases);
1641 #endif /* CONFIG_HOTPLUG_CPU */
1643 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1644 unsigned long action, void *hcpu)
1646 unsigned int cpu = (long)hcpu;
1650 case CPU_UP_PREPARE:
1651 case CPU_UP_PREPARE_FROZEN:
1652 init_hrtimers_cpu(cpu);
1655 #ifdef CONFIG_HOTPLUG_CPU
1657 case CPU_DEAD_FROZEN:
1658 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &cpu);
1659 migrate_hrtimers(cpu);
1670 static struct notifier_block __cpuinitdata hrtimers_nb = {
1671 .notifier_call = hrtimer_cpu_notify,
1674 void __init hrtimers_init(void)
1676 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1677 (void *)(long)smp_processor_id());
1678 register_cpu_notifier(&hrtimers_nb);
1679 #ifdef CONFIG_HIGH_RES_TIMERS
1680 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq, NULL);