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 = ktime_to_ns(kt);
307 /* Make sure the divisor is less than 2^32: */
313 do_div(dclc, (unsigned long) div);
317 #endif /* BITS_PER_LONG >= 64 */
320 * Add two ktime values and do a safety check for overflow:
322 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
324 ktime_t res = ktime_add(lhs, rhs);
327 * We use KTIME_SEC_MAX here, the maximum timeout which we can
328 * return to user space in a timespec:
330 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
331 res = ktime_set(KTIME_SEC_MAX, 0);
336 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
338 static struct debug_obj_descr hrtimer_debug_descr;
341 * fixup_init is called when:
342 * - an active object is initialized
344 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
346 struct hrtimer *timer = addr;
349 case ODEBUG_STATE_ACTIVE:
350 hrtimer_cancel(timer);
351 debug_object_init(timer, &hrtimer_debug_descr);
359 * fixup_activate is called when:
360 * - an active object is activated
361 * - an unknown object is activated (might be a statically initialized object)
363 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
367 case ODEBUG_STATE_NOTAVAILABLE:
371 case ODEBUG_STATE_ACTIVE:
380 * fixup_free is called when:
381 * - an active object is freed
383 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
385 struct hrtimer *timer = addr;
388 case ODEBUG_STATE_ACTIVE:
389 hrtimer_cancel(timer);
390 debug_object_free(timer, &hrtimer_debug_descr);
397 static struct debug_obj_descr hrtimer_debug_descr = {
399 .fixup_init = hrtimer_fixup_init,
400 .fixup_activate = hrtimer_fixup_activate,
401 .fixup_free = hrtimer_fixup_free,
404 static inline void debug_hrtimer_init(struct hrtimer *timer)
406 debug_object_init(timer, &hrtimer_debug_descr);
409 static inline void debug_hrtimer_activate(struct hrtimer *timer)
411 debug_object_activate(timer, &hrtimer_debug_descr);
414 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
416 debug_object_deactivate(timer, &hrtimer_debug_descr);
419 static inline void debug_hrtimer_free(struct hrtimer *timer)
421 debug_object_free(timer, &hrtimer_debug_descr);
424 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
425 enum hrtimer_mode mode);
427 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
428 enum hrtimer_mode mode)
430 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
431 __hrtimer_init(timer, clock_id, mode);
434 void destroy_hrtimer_on_stack(struct hrtimer *timer)
436 debug_object_free(timer, &hrtimer_debug_descr);
440 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
441 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
442 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
446 * Check, whether the timer is on the callback pending list
448 static inline int hrtimer_cb_pending(const struct hrtimer *timer)
450 return timer->state & HRTIMER_STATE_PENDING;
454 * Remove a timer from the callback pending list
456 static inline void hrtimer_remove_cb_pending(struct hrtimer *timer)
458 list_del_init(&timer->cb_entry);
461 /* High resolution timer related functions */
462 #ifdef CONFIG_HIGH_RES_TIMERS
465 * High resolution timer enabled ?
467 static int hrtimer_hres_enabled __read_mostly = 1;
470 * Enable / Disable high resolution mode
472 static int __init setup_hrtimer_hres(char *str)
474 if (!strcmp(str, "off"))
475 hrtimer_hres_enabled = 0;
476 else if (!strcmp(str, "on"))
477 hrtimer_hres_enabled = 1;
483 __setup("highres=", setup_hrtimer_hres);
486 * hrtimer_high_res_enabled - query, if the highres mode is enabled
488 static inline int hrtimer_is_hres_enabled(void)
490 return hrtimer_hres_enabled;
494 * Is the high resolution mode active ?
496 static inline int hrtimer_hres_active(void)
498 return __get_cpu_var(hrtimer_bases).hres_active;
502 * Reprogram the event source with checking both queues for the
504 * Called with interrupts disabled and base->lock held
506 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
509 struct hrtimer_clock_base *base = cpu_base->clock_base;
512 cpu_base->expires_next.tv64 = KTIME_MAX;
514 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
515 struct hrtimer *timer;
519 timer = rb_entry(base->first, struct hrtimer, node);
520 expires = ktime_sub(timer->expires, base->offset);
521 if (expires.tv64 < cpu_base->expires_next.tv64)
522 cpu_base->expires_next = expires;
525 if (cpu_base->expires_next.tv64 != KTIME_MAX)
526 tick_program_event(cpu_base->expires_next, 1);
530 * Shared reprogramming for clock_realtime and clock_monotonic
532 * When a timer is enqueued and expires earlier than the already enqueued
533 * timers, we have to check, whether it expires earlier than the timer for
534 * which the clock event device was armed.
536 * Called with interrupts disabled and base->cpu_base.lock held
538 static int hrtimer_reprogram(struct hrtimer *timer,
539 struct hrtimer_clock_base *base)
541 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
542 ktime_t expires = ktime_sub(timer->expires, base->offset);
545 WARN_ON_ONCE(timer->expires.tv64 < 0);
548 * When the callback is running, we do not reprogram the clock event
549 * device. The timer callback is either running on a different CPU or
550 * the callback is executed in the hrtimer_interrupt context. The
551 * reprogramming is handled either by the softirq, which called the
552 * callback or at the end of the hrtimer_interrupt.
554 if (hrtimer_callback_running(timer))
558 * CLOCK_REALTIME timer might be requested with an absolute
559 * expiry time which is less than base->offset. Nothing wrong
560 * about that, just avoid to call into the tick code, which
561 * has now objections against negative expiry values.
563 if (expires.tv64 < 0)
566 if (expires.tv64 >= expires_next->tv64)
570 * Clockevents returns -ETIME, when the event was in the past.
572 res = tick_program_event(expires, 0);
573 if (!IS_ERR_VALUE(res))
574 *expires_next = expires;
580 * Retrigger next event is called after clock was set
582 * Called with interrupts disabled via on_each_cpu()
584 static void retrigger_next_event(void *arg)
586 struct hrtimer_cpu_base *base;
587 struct timespec realtime_offset;
590 if (!hrtimer_hres_active())
594 seq = read_seqbegin(&xtime_lock);
595 set_normalized_timespec(&realtime_offset,
596 -wall_to_monotonic.tv_sec,
597 -wall_to_monotonic.tv_nsec);
598 } while (read_seqretry(&xtime_lock, seq));
600 base = &__get_cpu_var(hrtimer_bases);
602 /* Adjust CLOCK_REALTIME offset */
603 spin_lock(&base->lock);
604 base->clock_base[CLOCK_REALTIME].offset =
605 timespec_to_ktime(realtime_offset);
607 hrtimer_force_reprogram(base);
608 spin_unlock(&base->lock);
612 * Clock realtime was set
614 * Change the offset of the realtime clock vs. the monotonic
617 * We might have to reprogram the high resolution timer interrupt. On
618 * SMP we call the architecture specific code to retrigger _all_ high
619 * resolution timer interrupts. On UP we just disable interrupts and
620 * call the high resolution interrupt code.
622 void clock_was_set(void)
624 /* Retrigger the CPU local events everywhere */
625 on_each_cpu(retrigger_next_event, NULL, 0, 1);
629 * During resume we might have to reprogram the high resolution timer
630 * interrupt (on the local CPU):
632 void hres_timers_resume(void)
634 /* Retrigger the CPU local events: */
635 retrigger_next_event(NULL);
639 * Initialize the high resolution related parts of cpu_base
641 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
643 base->expires_next.tv64 = KTIME_MAX;
644 base->hres_active = 0;
648 * Initialize the high resolution related parts of a hrtimer
650 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
655 * When High resolution timers are active, try to reprogram. Note, that in case
656 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
657 * check happens. The timer gets enqueued into the rbtree. The reprogramming
658 * and expiry check is done in the hrtimer_interrupt or in the softirq.
660 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
661 struct hrtimer_clock_base *base)
663 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
665 /* Timer is expired, act upon the callback mode */
666 switch(timer->cb_mode) {
667 case HRTIMER_CB_IRQSAFE_NO_RESTART:
668 debug_hrtimer_deactivate(timer);
670 * We can call the callback from here. No restart
671 * happens, so no danger of recursion
673 BUG_ON(timer->function(timer) != HRTIMER_NORESTART);
675 case HRTIMER_CB_IRQSAFE_NO_SOFTIRQ:
677 * This is solely for the sched tick emulation with
678 * dynamic tick support to ensure that we do not
679 * restart the tick right on the edge and end up with
680 * the tick timer in the softirq ! The calling site
681 * takes care of this.
683 debug_hrtimer_deactivate(timer);
685 case HRTIMER_CB_IRQSAFE:
686 case HRTIMER_CB_SOFTIRQ:
688 * Move everything else into the softirq pending list !
690 list_add_tail(&timer->cb_entry,
691 &base->cpu_base->cb_pending);
692 timer->state = HRTIMER_STATE_PENDING;
702 * Switch to high resolution mode
704 static int hrtimer_switch_to_hres(void)
706 int cpu = smp_processor_id();
707 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
710 if (base->hres_active)
713 local_irq_save(flags);
715 if (tick_init_highres()) {
716 local_irq_restore(flags);
717 printk(KERN_WARNING "Could not switch to high resolution "
718 "mode on CPU %d\n", cpu);
721 base->hres_active = 1;
722 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
723 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
725 tick_setup_sched_timer();
727 /* "Retrigger" the interrupt to get things going */
728 retrigger_next_event(NULL);
729 local_irq_restore(flags);
730 printk(KERN_DEBUG "Switched to high resolution mode on CPU %d\n",
735 static inline void hrtimer_raise_softirq(void)
737 raise_softirq(HRTIMER_SOFTIRQ);
742 static inline int hrtimer_hres_active(void) { return 0; }
743 static inline int hrtimer_is_hres_enabled(void) { return 0; }
744 static inline int hrtimer_switch_to_hres(void) { return 0; }
745 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
746 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
747 struct hrtimer_clock_base *base)
751 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
752 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
753 static inline int hrtimer_reprogram(struct hrtimer *timer,
754 struct hrtimer_clock_base *base)
758 static inline void hrtimer_raise_softirq(void) { }
760 #endif /* CONFIG_HIGH_RES_TIMERS */
762 #ifdef CONFIG_TIMER_STATS
763 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
765 if (timer->start_site)
768 timer->start_site = addr;
769 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
770 timer->start_pid = current->pid;
775 * Counterpart to lock_hrtimer_base above:
778 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
780 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
784 * hrtimer_forward - forward the timer expiry
785 * @timer: hrtimer to forward
786 * @now: forward past this time
787 * @interval: the interval to forward
789 * Forward the timer expiry so it will expire in the future.
790 * Returns the number of overruns.
792 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
797 delta = ktime_sub(now, timer->expires);
802 if (interval.tv64 < timer->base->resolution.tv64)
803 interval.tv64 = timer->base->resolution.tv64;
805 if (unlikely(delta.tv64 >= interval.tv64)) {
806 s64 incr = ktime_to_ns(interval);
808 orun = ktime_divns(delta, incr);
809 timer->expires = ktime_add_ns(timer->expires, incr * orun);
810 if (timer->expires.tv64 > now.tv64)
813 * This (and the ktime_add() below) is the
814 * correction for exact:
818 timer->expires = ktime_add_safe(timer->expires, interval);
822 EXPORT_SYMBOL_GPL(hrtimer_forward);
825 * enqueue_hrtimer - internal function to (re)start a timer
827 * The timer is inserted in expiry order. Insertion into the
828 * red black tree is O(log(n)). Must hold the base lock.
830 static void enqueue_hrtimer(struct hrtimer *timer,
831 struct hrtimer_clock_base *base, int reprogram)
833 struct rb_node **link = &base->active.rb_node;
834 struct rb_node *parent = NULL;
835 struct hrtimer *entry;
838 debug_hrtimer_activate(timer);
841 * Find the right place in the rbtree:
845 entry = rb_entry(parent, struct hrtimer, node);
847 * We dont care about collisions. Nodes with
848 * the same expiry time stay together.
850 if (timer->expires.tv64 < entry->expires.tv64) {
851 link = &(*link)->rb_left;
853 link = &(*link)->rb_right;
859 * Insert the timer to the rbtree and check whether it
860 * replaces the first pending timer
864 * Reprogram the clock event device. When the timer is already
865 * expired hrtimer_enqueue_reprogram has either called the
866 * callback or added it to the pending list and raised the
869 * This is a NOP for !HIGHRES
871 if (reprogram && hrtimer_enqueue_reprogram(timer, base))
874 base->first = &timer->node;
877 rb_link_node(&timer->node, parent, link);
878 rb_insert_color(&timer->node, &base->active);
880 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
881 * state of a possibly running callback.
883 timer->state |= HRTIMER_STATE_ENQUEUED;
887 * __remove_hrtimer - internal function to remove a timer
889 * Caller must hold the base lock.
891 * High resolution timer mode reprograms the clock event device when the
892 * timer is the one which expires next. The caller can disable this by setting
893 * reprogram to zero. This is useful, when the context does a reprogramming
894 * anyway (e.g. timer interrupt)
896 static void __remove_hrtimer(struct hrtimer *timer,
897 struct hrtimer_clock_base *base,
898 unsigned long newstate, int reprogram)
900 /* High res. callback list. NOP for !HIGHRES */
901 if (hrtimer_cb_pending(timer))
902 hrtimer_remove_cb_pending(timer);
905 * Remove the timer from the rbtree and replace the
906 * first entry pointer if necessary.
908 if (base->first == &timer->node) {
909 base->first = rb_next(&timer->node);
910 /* Reprogram the clock event device. if enabled */
911 if (reprogram && hrtimer_hres_active())
912 hrtimer_force_reprogram(base->cpu_base);
914 rb_erase(&timer->node, &base->active);
916 timer->state = newstate;
920 * remove hrtimer, called with base lock held
923 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
925 if (hrtimer_is_queued(timer)) {
929 * Remove the timer and force reprogramming when high
930 * resolution mode is active and the timer is on the current
931 * CPU. If we remove a timer on another CPU, reprogramming is
932 * skipped. The interrupt event on this CPU is fired and
933 * reprogramming happens in the interrupt handler. This is a
934 * rare case and less expensive than a smp call.
936 debug_hrtimer_deactivate(timer);
937 timer_stats_hrtimer_clear_start_info(timer);
938 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
939 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
947 * hrtimer_start - (re)start an relative timer on the current CPU
948 * @timer: the timer to be added
950 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
954 * 1 when the timer was active
957 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
959 struct hrtimer_clock_base *base, *new_base;
963 base = lock_hrtimer_base(timer, &flags);
965 /* Remove an active timer from the queue: */
966 ret = remove_hrtimer(timer, base);
968 /* Switch the timer base, if necessary: */
969 new_base = switch_hrtimer_base(timer, base);
971 if (mode == HRTIMER_MODE_REL) {
972 tim = ktime_add_safe(tim, new_base->get_time());
974 * CONFIG_TIME_LOW_RES is a temporary way for architectures
975 * to signal that they simply return xtime in
976 * do_gettimeoffset(). In this case we want to round up by
977 * resolution when starting a relative timer, to avoid short
978 * timeouts. This will go away with the GTOD framework.
980 #ifdef CONFIG_TIME_LOW_RES
981 tim = ktime_add_safe(tim, base->resolution);
985 timer->expires = tim;
987 timer_stats_hrtimer_set_start_info(timer);
990 * Only allow reprogramming if the new base is on this CPU.
991 * (it might still be on another CPU if the timer was pending)
993 enqueue_hrtimer(timer, new_base,
994 new_base->cpu_base == &__get_cpu_var(hrtimer_bases));
997 * The timer may be expired and moved to the cb_pending
998 * list. We can not raise the softirq with base lock held due
999 * to a possible deadlock with runqueue lock.
1001 raise = timer->state == HRTIMER_STATE_PENDING;
1003 unlock_hrtimer_base(timer, &flags);
1006 hrtimer_raise_softirq();
1010 EXPORT_SYMBOL_GPL(hrtimer_start);
1013 * hrtimer_try_to_cancel - try to deactivate a timer
1014 * @timer: hrtimer to stop
1017 * 0 when the timer was not active
1018 * 1 when the timer was active
1019 * -1 when the timer is currently excuting the callback function and
1022 int hrtimer_try_to_cancel(struct hrtimer *timer)
1024 struct hrtimer_clock_base *base;
1025 unsigned long flags;
1028 base = lock_hrtimer_base(timer, &flags);
1030 if (!hrtimer_callback_running(timer))
1031 ret = remove_hrtimer(timer, base);
1033 unlock_hrtimer_base(timer, &flags);
1038 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1041 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1042 * @timer: the timer to be cancelled
1045 * 0 when the timer was not active
1046 * 1 when the timer was active
1048 int hrtimer_cancel(struct hrtimer *timer)
1051 int ret = hrtimer_try_to_cancel(timer);
1058 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1061 * hrtimer_get_remaining - get remaining time for the timer
1062 * @timer: the timer to read
1064 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1066 struct hrtimer_clock_base *base;
1067 unsigned long flags;
1070 base = lock_hrtimer_base(timer, &flags);
1071 rem = ktime_sub(timer->expires, base->get_time());
1072 unlock_hrtimer_base(timer, &flags);
1076 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1078 #if defined(CONFIG_NO_IDLE_HZ) || defined(CONFIG_NO_HZ)
1080 * hrtimer_get_next_event - get the time until next expiry event
1082 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1085 ktime_t hrtimer_get_next_event(void)
1087 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1088 struct hrtimer_clock_base *base = cpu_base->clock_base;
1089 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1090 unsigned long flags;
1093 spin_lock_irqsave(&cpu_base->lock, flags);
1095 if (!hrtimer_hres_active()) {
1096 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1097 struct hrtimer *timer;
1102 timer = rb_entry(base->first, struct hrtimer, node);
1103 delta.tv64 = timer->expires.tv64;
1104 delta = ktime_sub(delta, base->get_time());
1105 if (delta.tv64 < mindelta.tv64)
1106 mindelta.tv64 = delta.tv64;
1110 spin_unlock_irqrestore(&cpu_base->lock, flags);
1112 if (mindelta.tv64 < 0)
1118 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1119 enum hrtimer_mode mode)
1121 struct hrtimer_cpu_base *cpu_base;
1123 memset(timer, 0, sizeof(struct hrtimer));
1125 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1127 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1128 clock_id = CLOCK_MONOTONIC;
1130 timer->base = &cpu_base->clock_base[clock_id];
1131 INIT_LIST_HEAD(&timer->cb_entry);
1132 hrtimer_init_timer_hres(timer);
1134 #ifdef CONFIG_TIMER_STATS
1135 timer->start_site = NULL;
1136 timer->start_pid = -1;
1137 memset(timer->start_comm, 0, TASK_COMM_LEN);
1142 * hrtimer_init - initialize a timer to the given clock
1143 * @timer: the timer to be initialized
1144 * @clock_id: the clock to be used
1145 * @mode: timer mode abs/rel
1147 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1148 enum hrtimer_mode mode)
1150 debug_hrtimer_init(timer);
1151 __hrtimer_init(timer, clock_id, mode);
1153 EXPORT_SYMBOL_GPL(hrtimer_init);
1156 * hrtimer_get_res - get the timer resolution for a clock
1157 * @which_clock: which clock to query
1158 * @tp: pointer to timespec variable to store the resolution
1160 * Store the resolution of the clock selected by @which_clock in the
1161 * variable pointed to by @tp.
1163 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1165 struct hrtimer_cpu_base *cpu_base;
1167 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1168 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1172 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1174 static void run_hrtimer_pending(struct hrtimer_cpu_base *cpu_base)
1176 spin_lock_irq(&cpu_base->lock);
1178 while (!list_empty(&cpu_base->cb_pending)) {
1179 enum hrtimer_restart (*fn)(struct hrtimer *);
1180 struct hrtimer *timer;
1183 timer = list_entry(cpu_base->cb_pending.next,
1184 struct hrtimer, cb_entry);
1186 debug_hrtimer_deactivate(timer);
1187 timer_stats_account_hrtimer(timer);
1189 fn = timer->function;
1190 __remove_hrtimer(timer, timer->base, HRTIMER_STATE_CALLBACK, 0);
1191 spin_unlock_irq(&cpu_base->lock);
1193 restart = fn(timer);
1195 spin_lock_irq(&cpu_base->lock);
1197 timer->state &= ~HRTIMER_STATE_CALLBACK;
1198 if (restart == HRTIMER_RESTART) {
1199 BUG_ON(hrtimer_active(timer));
1201 * Enqueue the timer, allow reprogramming of the event
1204 enqueue_hrtimer(timer, timer->base, 1);
1205 } else if (hrtimer_active(timer)) {
1207 * If the timer was rearmed on another CPU, reprogram
1210 struct hrtimer_clock_base *base = timer->base;
1212 if (base->first == &timer->node &&
1213 hrtimer_reprogram(timer, base)) {
1215 * Timer is expired. Thus move it from tree to
1216 * pending list again.
1218 __remove_hrtimer(timer, base,
1219 HRTIMER_STATE_PENDING, 0);
1220 list_add_tail(&timer->cb_entry,
1221 &base->cpu_base->cb_pending);
1225 spin_unlock_irq(&cpu_base->lock);
1228 static void __run_hrtimer(struct hrtimer *timer)
1230 struct hrtimer_clock_base *base = timer->base;
1231 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1232 enum hrtimer_restart (*fn)(struct hrtimer *);
1235 debug_hrtimer_deactivate(timer);
1236 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1237 timer_stats_account_hrtimer(timer);
1239 fn = timer->function;
1240 if (timer->cb_mode == HRTIMER_CB_IRQSAFE_NO_SOFTIRQ) {
1242 * Used for scheduler timers, avoid lock inversion with
1243 * rq->lock and tasklist_lock.
1245 * These timers are required to deal with enqueue expiry
1246 * themselves and are not allowed to migrate.
1248 spin_unlock(&cpu_base->lock);
1249 restart = fn(timer);
1250 spin_lock(&cpu_base->lock);
1252 restart = fn(timer);
1255 * Note: We clear the CALLBACK bit after enqueue_hrtimer to avoid
1256 * reprogramming of the event hardware. This happens at the end of this
1259 if (restart != HRTIMER_NORESTART) {
1260 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1261 enqueue_hrtimer(timer, base, 0);
1263 timer->state &= ~HRTIMER_STATE_CALLBACK;
1266 #ifdef CONFIG_HIGH_RES_TIMERS
1269 * High resolution timer interrupt
1270 * Called with interrupts disabled
1272 void hrtimer_interrupt(struct clock_event_device *dev)
1274 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1275 struct hrtimer_clock_base *base;
1276 ktime_t expires_next, now;
1279 BUG_ON(!cpu_base->hres_active);
1280 cpu_base->nr_events++;
1281 dev->next_event.tv64 = KTIME_MAX;
1286 expires_next.tv64 = KTIME_MAX;
1288 base = cpu_base->clock_base;
1290 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1292 struct rb_node *node;
1294 spin_lock(&cpu_base->lock);
1296 basenow = ktime_add(now, base->offset);
1298 while ((node = base->first)) {
1299 struct hrtimer *timer;
1301 timer = rb_entry(node, struct hrtimer, node);
1303 if (basenow.tv64 < timer->expires.tv64) {
1306 expires = ktime_sub(timer->expires,
1308 if (expires.tv64 < expires_next.tv64)
1309 expires_next = expires;
1313 /* Move softirq callbacks to the pending list */
1314 if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1315 __remove_hrtimer(timer, base,
1316 HRTIMER_STATE_PENDING, 0);
1317 list_add_tail(&timer->cb_entry,
1318 &base->cpu_base->cb_pending);
1323 __run_hrtimer(timer);
1325 spin_unlock(&cpu_base->lock);
1329 cpu_base->expires_next = expires_next;
1331 /* Reprogramming necessary ? */
1332 if (expires_next.tv64 != KTIME_MAX) {
1333 if (tick_program_event(expires_next, 0))
1337 /* Raise softirq ? */
1339 raise_softirq(HRTIMER_SOFTIRQ);
1342 static void run_hrtimer_softirq(struct softirq_action *h)
1344 run_hrtimer_pending(&__get_cpu_var(hrtimer_bases));
1347 #endif /* CONFIG_HIGH_RES_TIMERS */
1350 * Called from timer softirq every jiffy, expire hrtimers:
1352 * For HRT its the fall back code to run the softirq in the timer
1353 * softirq context in case the hrtimer initialization failed or has
1354 * not been done yet.
1356 void hrtimer_run_pending(void)
1358 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1360 if (hrtimer_hres_active())
1364 * This _is_ ugly: We have to check in the softirq context,
1365 * whether we can switch to highres and / or nohz mode. The
1366 * clocksource switch happens in the timer interrupt with
1367 * xtime_lock held. Notification from there only sets the
1368 * check bit in the tick_oneshot code, otherwise we might
1369 * deadlock vs. xtime_lock.
1371 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1372 hrtimer_switch_to_hres();
1374 run_hrtimer_pending(cpu_base);
1378 * Called from hardirq context every jiffy
1380 void hrtimer_run_queues(void)
1382 struct rb_node *node;
1383 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1384 struct hrtimer_clock_base *base;
1385 int index, gettime = 1;
1387 if (hrtimer_hres_active())
1390 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1391 base = &cpu_base->clock_base[index];
1396 if (base->get_softirq_time)
1397 base->softirq_time = base->get_softirq_time();
1399 hrtimer_get_softirq_time(cpu_base);
1403 spin_lock(&cpu_base->lock);
1405 while ((node = base->first)) {
1406 struct hrtimer *timer;
1408 timer = rb_entry(node, struct hrtimer, node);
1409 if (base->softirq_time.tv64 <= timer->expires.tv64)
1412 if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1413 __remove_hrtimer(timer, base,
1414 HRTIMER_STATE_PENDING, 0);
1415 list_add_tail(&timer->cb_entry,
1416 &base->cpu_base->cb_pending);
1420 __run_hrtimer(timer);
1422 spin_unlock(&cpu_base->lock);
1427 * Sleep related functions:
1429 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1431 struct hrtimer_sleeper *t =
1432 container_of(timer, struct hrtimer_sleeper, timer);
1433 struct task_struct *task = t->task;
1437 wake_up_process(task);
1439 return HRTIMER_NORESTART;
1442 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1444 sl->timer.function = hrtimer_wakeup;
1446 #ifdef CONFIG_HIGH_RES_TIMERS
1447 sl->timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1451 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1453 hrtimer_init_sleeper(t, current);
1456 set_current_state(TASK_INTERRUPTIBLE);
1457 hrtimer_start(&t->timer, t->timer.expires, mode);
1458 if (!hrtimer_active(&t->timer))
1461 if (likely(t->task))
1464 hrtimer_cancel(&t->timer);
1465 mode = HRTIMER_MODE_ABS;
1467 } while (t->task && !signal_pending(current));
1469 __set_current_state(TASK_RUNNING);
1471 return t->task == NULL;
1474 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1476 struct timespec rmt;
1479 rem = ktime_sub(timer->expires, timer->base->get_time());
1482 rmt = ktime_to_timespec(rem);
1484 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1490 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1492 struct hrtimer_sleeper t;
1493 struct timespec __user *rmtp;
1496 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1498 t.timer.expires.tv64 = restart->nanosleep.expires;
1500 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1503 rmtp = restart->nanosleep.rmtp;
1505 ret = update_rmtp(&t.timer, rmtp);
1510 /* The other values in restart are already filled in */
1511 ret = -ERESTART_RESTARTBLOCK;
1513 destroy_hrtimer_on_stack(&t.timer);
1517 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1518 const enum hrtimer_mode mode, const clockid_t clockid)
1520 struct restart_block *restart;
1521 struct hrtimer_sleeper t;
1524 hrtimer_init_on_stack(&t.timer, clockid, mode);
1525 t.timer.expires = timespec_to_ktime(*rqtp);
1526 if (do_nanosleep(&t, mode))
1529 /* Absolute timers do not update the rmtp value and restart: */
1530 if (mode == HRTIMER_MODE_ABS) {
1531 ret = -ERESTARTNOHAND;
1536 ret = update_rmtp(&t.timer, rmtp);
1541 restart = ¤t_thread_info()->restart_block;
1542 restart->fn = hrtimer_nanosleep_restart;
1543 restart->nanosleep.index = t.timer.base->index;
1544 restart->nanosleep.rmtp = rmtp;
1545 restart->nanosleep.expires = t.timer.expires.tv64;
1547 ret = -ERESTART_RESTARTBLOCK;
1549 destroy_hrtimer_on_stack(&t.timer);
1554 sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1558 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1561 if (!timespec_valid(&tu))
1564 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1568 * Functions related to boot-time initialization:
1570 static void __cpuinit init_hrtimers_cpu(int cpu)
1572 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1575 spin_lock_init(&cpu_base->lock);
1577 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1578 cpu_base->clock_base[i].cpu_base = cpu_base;
1580 INIT_LIST_HEAD(&cpu_base->cb_pending);
1581 hrtimer_init_hres(cpu_base);
1584 #ifdef CONFIG_HOTPLUG_CPU
1586 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1587 struct hrtimer_clock_base *new_base)
1589 struct hrtimer *timer;
1590 struct rb_node *node;
1592 while ((node = rb_first(&old_base->active))) {
1593 timer = rb_entry(node, struct hrtimer, node);
1594 BUG_ON(hrtimer_callback_running(timer));
1595 debug_hrtimer_deactivate(timer);
1596 __remove_hrtimer(timer, old_base, HRTIMER_STATE_INACTIVE, 0);
1597 timer->base = new_base;
1599 * Enqueue the timer. Allow reprogramming of the event device
1601 enqueue_hrtimer(timer, new_base, 1);
1605 static void migrate_hrtimers(int cpu)
1607 struct hrtimer_cpu_base *old_base, *new_base;
1610 BUG_ON(cpu_online(cpu));
1611 old_base = &per_cpu(hrtimer_bases, cpu);
1612 new_base = &get_cpu_var(hrtimer_bases);
1614 tick_cancel_sched_timer(cpu);
1616 local_irq_disable();
1617 spin_lock(&new_base->lock);
1618 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1620 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1621 migrate_hrtimer_list(&old_base->clock_base[i],
1622 &new_base->clock_base[i]);
1625 spin_unlock(&old_base->lock);
1626 spin_unlock(&new_base->lock);
1628 put_cpu_var(hrtimer_bases);
1630 #endif /* CONFIG_HOTPLUG_CPU */
1632 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1633 unsigned long action, void *hcpu)
1635 unsigned int cpu = (long)hcpu;
1639 case CPU_UP_PREPARE:
1640 case CPU_UP_PREPARE_FROZEN:
1641 init_hrtimers_cpu(cpu);
1644 #ifdef CONFIG_HOTPLUG_CPU
1646 case CPU_DEAD_FROZEN:
1647 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &cpu);
1648 migrate_hrtimers(cpu);
1659 static struct notifier_block __cpuinitdata hrtimers_nb = {
1660 .notifier_call = hrtimer_cpu_notify,
1663 void __init hrtimers_init(void)
1665 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1666 (void *)(long)smp_processor_id());
1667 register_cpu_notifier(&hrtimers_nb);
1668 #ifdef CONFIG_HIGH_RES_TIMERS
1669 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq, NULL);