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/export.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/sched/sysctl.h>
48 #include <linux/sched/rt.h>
49 #include <linux/sched/deadline.h>
50 #include <linux/timer.h>
51 #include <linux/kthread.h>
52 #include <linux/freezer.h>
54 #include <asm/uaccess.h>
56 #include <trace/events/timer.h>
57 #include <trace/events/hist.h>
59 #include "tick-internal.h"
64 * There are more clockids then hrtimer bases. Thus, we index
65 * into the timer bases by the hrtimer_base_type enum. When trying
66 * to reach a base using a clockid, hrtimer_clockid_to_base()
67 * is used to convert from clockid to the proper hrtimer_base_type.
69 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
72 .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
76 .index = HRTIMER_BASE_MONOTONIC,
77 .clockid = CLOCK_MONOTONIC,
78 .get_time = &ktime_get,
79 .resolution = KTIME_LOW_RES,
82 .index = HRTIMER_BASE_REALTIME,
83 .clockid = CLOCK_REALTIME,
84 .get_time = &ktime_get_real,
85 .resolution = KTIME_LOW_RES,
88 .index = HRTIMER_BASE_BOOTTIME,
89 .clockid = CLOCK_BOOTTIME,
90 .get_time = &ktime_get_boottime,
91 .resolution = KTIME_LOW_RES,
94 .index = HRTIMER_BASE_TAI,
96 .get_time = &ktime_get_clocktai,
97 .resolution = KTIME_LOW_RES,
102 static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
103 [CLOCK_REALTIME] = HRTIMER_BASE_REALTIME,
104 [CLOCK_MONOTONIC] = HRTIMER_BASE_MONOTONIC,
105 [CLOCK_BOOTTIME] = HRTIMER_BASE_BOOTTIME,
106 [CLOCK_TAI] = HRTIMER_BASE_TAI,
109 static inline int hrtimer_clockid_to_base(clockid_t clock_id)
111 return hrtimer_clock_to_base_table[clock_id];
116 * Get the coarse grained time at the softirq based on xtime and
119 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
121 ktime_t xtim, mono, boot, tai;
122 ktime_t off_real, off_boot, off_tai;
124 mono = ktime_get_update_offsets_tick(&off_real, &off_boot, &off_tai);
125 boot = ktime_add(mono, off_boot);
126 xtim = ktime_add(mono, off_real);
127 tai = ktime_add(mono, off_tai);
129 base->clock_base[HRTIMER_BASE_REALTIME].softirq_time = xtim;
130 base->clock_base[HRTIMER_BASE_MONOTONIC].softirq_time = mono;
131 base->clock_base[HRTIMER_BASE_BOOTTIME].softirq_time = boot;
132 base->clock_base[HRTIMER_BASE_TAI].softirq_time = tai;
136 * Functions and macros which are different for UP/SMP systems are kept in a
142 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
143 * means that all timers which are tied to this base via timer->base are
144 * locked, and the base itself is locked too.
146 * So __run_timers/migrate_timers can safely modify all timers which could
147 * be found on the lists/queues.
149 * When the timer's base is locked, and the timer removed from list, it is
150 * possible to set timer->base = NULL and drop the lock: the timer remains
154 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
155 unsigned long *flags)
157 struct hrtimer_clock_base *base;
161 if (likely(base != NULL)) {
162 raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
163 if (likely(base == timer->base))
165 /* The timer has migrated to another CPU: */
166 raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
173 * With HIGHRES=y we do not migrate the timer when it is expiring
174 * before the next event on the target cpu because we cannot reprogram
175 * the target cpu hardware and we would cause it to fire late.
177 * Called with cpu_base->lock of target cpu held.
180 hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
182 #ifdef CONFIG_HIGH_RES_TIMERS
185 if (!new_base->cpu_base->hres_active)
188 expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
189 return expires.tv64 <= new_base->cpu_base->expires_next.tv64;
196 * Switch the timer base to the current CPU when possible.
198 static inline struct hrtimer_clock_base *
199 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
202 struct hrtimer_clock_base *new_base;
203 struct hrtimer_cpu_base *new_cpu_base;
204 int this_cpu = smp_processor_id();
205 int cpu = get_nohz_timer_target(pinned);
206 int basenum = base->index;
209 new_cpu_base = &per_cpu(hrtimer_bases, cpu);
210 new_base = &new_cpu_base->clock_base[basenum];
212 if (base != new_base) {
214 * We are trying to move timer to new_base.
215 * However we can't change timer's base while it is running,
216 * so we keep it on the same CPU. No hassle vs. reprogramming
217 * the event source in the high resolution case. The softirq
218 * code will take care of this when the timer function has
219 * completed. There is no conflict as we hold the lock until
220 * the timer is enqueued.
222 if (unlikely(hrtimer_callback_running(timer)))
225 /* See the comment in lock_timer_base() */
227 raw_spin_unlock(&base->cpu_base->lock);
228 raw_spin_lock(&new_base->cpu_base->lock);
230 if (cpu != this_cpu && hrtimer_check_target(timer, new_base)) {
232 raw_spin_unlock(&new_base->cpu_base->lock);
233 raw_spin_lock(&base->cpu_base->lock);
237 timer->base = new_base;
239 if (cpu != this_cpu && hrtimer_check_target(timer, new_base)) {
247 #else /* CONFIG_SMP */
249 static inline struct hrtimer_clock_base *
250 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
252 struct hrtimer_clock_base *base = timer->base;
254 raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
259 # define switch_hrtimer_base(t, b, p) (b)
261 #endif /* !CONFIG_SMP */
264 * Functions for the union type storage format of ktime_t which are
265 * too large for inlining:
267 #if BITS_PER_LONG < 64
269 * Divide a ktime value by a nanosecond value
271 s64 __ktime_divns(const ktime_t kt, s64 div)
277 dclc = ktime_to_ns(kt);
278 tmp = dclc < 0 ? -dclc : dclc;
280 /* Make sure the divisor is less than 2^32: */
286 do_div(tmp, (unsigned long) div);
287 return dclc < 0 ? -tmp : tmp;
289 EXPORT_SYMBOL_GPL(__ktime_divns);
290 #endif /* BITS_PER_LONG >= 64 */
293 * Add two ktime values and do a safety check for overflow:
295 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
297 ktime_t res = ktime_add(lhs, rhs);
300 * We use KTIME_SEC_MAX here, the maximum timeout which we can
301 * return to user space in a timespec:
303 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
304 res = ktime_set(KTIME_SEC_MAX, 0);
309 EXPORT_SYMBOL_GPL(ktime_add_safe);
311 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
313 static struct debug_obj_descr hrtimer_debug_descr;
315 static void *hrtimer_debug_hint(void *addr)
317 return ((struct hrtimer *) addr)->function;
321 * fixup_init is called when:
322 * - an active object is initialized
324 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
326 struct hrtimer *timer = addr;
329 case ODEBUG_STATE_ACTIVE:
330 hrtimer_cancel(timer);
331 debug_object_init(timer, &hrtimer_debug_descr);
339 * fixup_activate is called when:
340 * - an active object is activated
341 * - an unknown object is activated (might be a statically initialized object)
343 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
347 case ODEBUG_STATE_NOTAVAILABLE:
351 case ODEBUG_STATE_ACTIVE:
360 * fixup_free is called when:
361 * - an active object is freed
363 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
365 struct hrtimer *timer = addr;
368 case ODEBUG_STATE_ACTIVE:
369 hrtimer_cancel(timer);
370 debug_object_free(timer, &hrtimer_debug_descr);
377 static struct debug_obj_descr hrtimer_debug_descr = {
379 .debug_hint = hrtimer_debug_hint,
380 .fixup_init = hrtimer_fixup_init,
381 .fixup_activate = hrtimer_fixup_activate,
382 .fixup_free = hrtimer_fixup_free,
385 static inline void debug_hrtimer_init(struct hrtimer *timer)
387 debug_object_init(timer, &hrtimer_debug_descr);
390 static inline void debug_hrtimer_activate(struct hrtimer *timer)
392 debug_object_activate(timer, &hrtimer_debug_descr);
395 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
397 debug_object_deactivate(timer, &hrtimer_debug_descr);
400 static inline void debug_hrtimer_free(struct hrtimer *timer)
402 debug_object_free(timer, &hrtimer_debug_descr);
405 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
406 enum hrtimer_mode mode);
408 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
409 enum hrtimer_mode mode)
411 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
412 __hrtimer_init(timer, clock_id, mode);
414 EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
416 void destroy_hrtimer_on_stack(struct hrtimer *timer)
418 debug_object_free(timer, &hrtimer_debug_descr);
422 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
423 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
424 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
428 debug_init(struct hrtimer *timer, clockid_t clockid,
429 enum hrtimer_mode mode)
431 debug_hrtimer_init(timer);
432 trace_hrtimer_init(timer, clockid, mode);
435 static inline void debug_activate(struct hrtimer *timer)
437 debug_hrtimer_activate(timer);
438 trace_hrtimer_start(timer);
441 static inline void debug_deactivate(struct hrtimer *timer)
443 debug_hrtimer_deactivate(timer);
444 trace_hrtimer_cancel(timer);
447 #if defined(CONFIG_NO_HZ_COMMON) || defined(CONFIG_HIGH_RES_TIMERS)
448 static ktime_t __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base)
450 struct hrtimer_clock_base *base = cpu_base->clock_base;
451 ktime_t expires, expires_next = { .tv64 = KTIME_MAX };
454 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
455 struct timerqueue_node *next;
456 struct hrtimer *timer;
458 next = timerqueue_getnext(&base->active);
462 timer = container_of(next, struct hrtimer, node);
463 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
464 if (expires.tv64 < expires_next.tv64)
465 expires_next = expires;
468 * clock_was_set() might have changed base->offset of any of
469 * the clock bases so the result might be negative. Fix it up
470 * to prevent a false positive in clockevents_program_event().
472 if (expires_next.tv64 < 0)
473 expires_next.tv64 = 0;
478 /* High resolution timer related functions */
479 #ifdef CONFIG_HIGH_RES_TIMERS
482 * High resolution timer enabled ?
484 static int hrtimer_hres_enabled __read_mostly = 1;
487 * Enable / Disable high resolution mode
489 static int __init setup_hrtimer_hres(char *str)
491 if (!strcmp(str, "off"))
492 hrtimer_hres_enabled = 0;
493 else if (!strcmp(str, "on"))
494 hrtimer_hres_enabled = 1;
500 __setup("highres=", setup_hrtimer_hres);
503 * hrtimer_high_res_enabled - query, if the highres mode is enabled
505 static inline int hrtimer_is_hres_enabled(void)
507 return hrtimer_hres_enabled;
511 * Is the high resolution mode active ?
513 static inline int hrtimer_hres_active(void)
515 return __this_cpu_read(hrtimer_bases.hres_active);
519 * Reprogram the event source with checking both queues for the
521 * Called with interrupts disabled and base->lock held
524 hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
526 ktime_t expires_next = __hrtimer_get_next_event(cpu_base);
528 if (skip_equal && expires_next.tv64 == cpu_base->expires_next.tv64)
531 cpu_base->expires_next.tv64 = expires_next.tv64;
534 * If a hang was detected in the last timer interrupt then we
535 * leave the hang delay active in the hardware. We want the
536 * system to make progress. That also prevents the following
538 * T1 expires 50ms from now
539 * T2 expires 5s from now
541 * T1 is removed, so this code is called and would reprogram
542 * the hardware to 5s from now. Any hrtimer_start after that
543 * will not reprogram the hardware due to hang_detected being
544 * set. So we'd effectivly block all timers until the T2 event
547 if (cpu_base->hang_detected)
550 if (cpu_base->expires_next.tv64 != KTIME_MAX)
551 tick_program_event(cpu_base->expires_next, 1);
555 * Shared reprogramming for clock_realtime and clock_monotonic
557 * When a timer is enqueued and expires earlier than the already enqueued
558 * timers, we have to check, whether it expires earlier than the timer for
559 * which the clock event device was armed.
561 * Note, that in case the state has HRTIMER_STATE_CALLBACK set, no reprogramming
562 * and no expiry check happens. The timer gets enqueued into the rbtree. The
563 * reprogramming and expiry check is done in the hrtimer_interrupt or in the
566 * Called with interrupts disabled and base->cpu_base.lock held
568 static int hrtimer_reprogram(struct hrtimer *timer,
569 struct hrtimer_clock_base *base)
571 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
572 ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
575 WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
578 * When the callback is running, we do not reprogram the clock event
579 * device. The timer callback is either running on a different CPU or
580 * the callback is executed in the hrtimer_interrupt context. The
581 * reprogramming is handled at the end of the hrtimer_interrupt.
583 if (hrtimer_callback_running(timer))
587 * CLOCK_REALTIME timer might be requested with an absolute
588 * expiry time which is less than base->offset. Nothing wrong
589 * about that, just avoid to call into the tick code, which
590 * has now objections against negative expiry values.
592 if (expires.tv64 < 0)
595 if (expires.tv64 >= cpu_base->expires_next.tv64)
599 * When the target cpu of the timer is currently executing
600 * hrtimer_interrupt(), then we do not touch the clock event
601 * device. hrtimer_interrupt() will reevaluate all clock bases
602 * before reprogramming the device.
604 if (cpu_base->in_hrtirq)
608 * If a hang was detected in the last timer interrupt then we
609 * do not schedule a timer which is earlier than the expiry
610 * which we enforced in the hang detection. We want the system
613 if (cpu_base->hang_detected)
617 * Clockevents returns -ETIME, when the event was in the past.
619 res = tick_program_event(expires, 0);
620 if (!IS_ERR_VALUE(res))
621 cpu_base->expires_next = expires;
625 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now);
626 static int hrtimer_rt_defer(struct hrtimer *timer);
629 * Initialize the high resolution related parts of cpu_base
631 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
633 base->expires_next.tv64 = KTIME_MAX;
634 base->hres_active = 0;
637 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
638 struct hrtimer_clock_base *base,
641 if (!hrtimer_reprogram(timer, base))
645 #ifdef CONFIG_PREEMPT_RT_BASE
646 if (!hrtimer_rt_defer(timer))
652 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
654 ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
655 ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
656 ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
658 return ktime_get_update_offsets_now(offs_real, offs_boot, offs_tai);
662 * Retrigger next event is called after clock was set
664 * Called with interrupts disabled via on_each_cpu()
666 static void retrigger_next_event(void *arg)
668 struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
670 if (!hrtimer_hres_active())
673 raw_spin_lock(&base->lock);
674 hrtimer_update_base(base);
675 hrtimer_force_reprogram(base, 0);
676 raw_spin_unlock(&base->lock);
680 * Switch to high resolution mode
682 static int hrtimer_switch_to_hres(void)
684 int i, cpu = smp_processor_id();
685 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
688 if (base->hres_active)
691 local_irq_save(flags);
693 if (tick_init_highres()) {
694 local_irq_restore(flags);
695 printk(KERN_WARNING "Could not switch to high resolution "
696 "mode on CPU %d\n", cpu);
699 base->hres_active = 1;
700 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
701 base->clock_base[i].resolution = KTIME_HIGH_RES;
703 tick_setup_sched_timer();
704 /* "Retrigger" the interrupt to get things going */
705 retrigger_next_event(NULL);
706 local_irq_restore(flags);
710 static void clock_was_set_work(struct work_struct *work)
715 static DECLARE_WORK(hrtimer_work, clock_was_set_work);
717 #ifdef CONFIG_PREEMPT_RT_FULL
719 * RT can not call schedule_work from real interrupt context.
720 * Need to make a thread to do the real work.
722 static struct task_struct *clock_set_delay_thread;
723 static bool do_clock_set_delay;
725 static int run_clock_set_delay(void *ignore)
727 while (!kthread_should_stop()) {
728 set_current_state(TASK_INTERRUPTIBLE);
729 if (do_clock_set_delay) {
730 do_clock_set_delay = false;
731 schedule_work(&hrtimer_work);
735 __set_current_state(TASK_RUNNING);
739 void clock_was_set_delayed(void)
741 do_clock_set_delay = true;
742 /* Make visible before waking up process */
744 wake_up_process(clock_set_delay_thread);
747 static __init int create_clock_set_delay_thread(void)
749 clock_set_delay_thread = kthread_run(run_clock_set_delay, NULL, "kclksetdelayd");
750 BUG_ON(!clock_set_delay_thread);
753 early_initcall(create_clock_set_delay_thread);
754 #else /* PREEMPT_RT_FULL */
756 * Called from timekeeping and resume code to reprogramm the hrtimer
757 * interrupt device on all cpus.
759 void clock_was_set_delayed(void)
761 schedule_work(&hrtimer_work);
767 static inline int hrtimer_hres_active(void) { return 0; }
768 static inline int hrtimer_is_hres_enabled(void) { return 0; }
769 static inline int hrtimer_switch_to_hres(void) { return 0; }
771 hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
772 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
773 struct hrtimer_clock_base *base,
779 static inline int hrtimer_reprogram(struct hrtimer *timer,
780 struct hrtimer_clock_base *base)
784 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
785 static inline void retrigger_next_event(void *arg) { }
786 #endif /* CONFIG_HIGH_RES_TIMERS */
789 * Clock realtime was set
791 * Change the offset of the realtime clock vs. the monotonic
794 * We might have to reprogram the high resolution timer interrupt. On
795 * SMP we call the architecture specific code to retrigger _all_ high
796 * resolution timer interrupts. On UP we just disable interrupts and
797 * call the high resolution interrupt code.
799 void clock_was_set(void)
801 #ifdef CONFIG_HIGH_RES_TIMERS
802 /* Retrigger the CPU local events everywhere */
803 on_each_cpu(retrigger_next_event, NULL, 1);
805 timerfd_clock_was_set();
809 * During resume we might have to reprogram the high resolution timer
810 * interrupt on all online CPUs. However, all other CPUs will be
811 * stopped with IRQs interrupts disabled so the clock_was_set() call
814 void hrtimers_resume(void)
816 WARN_ONCE(!irqs_disabled(),
817 KERN_INFO "hrtimers_resume() called with IRQs enabled!");
819 /* Retrigger on the local CPU */
820 retrigger_next_event(NULL);
821 /* And schedule a retrigger for all others */
822 clock_was_set_delayed();
825 static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
827 #ifdef CONFIG_TIMER_STATS
828 if (timer->start_site)
830 timer->start_site = __builtin_return_address(0);
831 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
832 timer->start_pid = current->pid;
836 static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
838 #ifdef CONFIG_TIMER_STATS
839 timer->start_site = NULL;
843 static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
845 #ifdef CONFIG_TIMER_STATS
846 if (likely(!timer_stats_active))
848 timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
849 timer->function, timer->start_comm, 0);
854 * Counterpart to lock_hrtimer_base above:
857 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
859 raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
863 * hrtimer_forward - forward the timer expiry
864 * @timer: hrtimer to forward
865 * @now: forward past this time
866 * @interval: the interval to forward
868 * Forward the timer expiry so it will expire in the future.
869 * Returns the number of overruns.
871 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
876 delta = ktime_sub(now, hrtimer_get_expires(timer));
881 if (interval.tv64 < timer->base->resolution.tv64)
882 interval.tv64 = timer->base->resolution.tv64;
884 if (unlikely(delta.tv64 >= interval.tv64)) {
885 s64 incr = ktime_to_ns(interval);
887 orun = ktime_divns(delta, incr);
888 hrtimer_add_expires_ns(timer, incr * orun);
889 if (hrtimer_get_expires_tv64(timer) > now.tv64)
892 * This (and the ktime_add() below) is the
893 * correction for exact:
897 hrtimer_add_expires(timer, interval);
901 EXPORT_SYMBOL_GPL(hrtimer_forward);
903 #ifdef CONFIG_PREEMPT_RT_BASE
904 # define wake_up_timer_waiters(b) wake_up(&(b)->wait)
907 * hrtimer_wait_for_timer - Wait for a running timer
909 * @timer: timer to wait for
911 * The function waits in case the timers callback function is
912 * currently executed on the waitqueue of the timer base. The
913 * waitqueue is woken up after the timer callback function has
914 * finished execution.
916 void hrtimer_wait_for_timer(const struct hrtimer *timer)
918 struct hrtimer_clock_base *base = timer->base;
920 if (base && base->cpu_base && !timer->irqsafe)
921 wait_event(base->cpu_base->wait,
922 !(timer->state & HRTIMER_STATE_CALLBACK));
926 # define wake_up_timer_waiters(b) do { } while (0)
930 * enqueue_hrtimer - internal function to (re)start a timer
932 * The timer is inserted in expiry order. Insertion into the
933 * red black tree is O(log(n)). Must hold the base lock.
935 * Returns 1 when the new timer is the leftmost timer in the tree.
937 static int enqueue_hrtimer(struct hrtimer *timer,
938 struct hrtimer_clock_base *base)
940 debug_activate(timer);
942 timerqueue_add(&base->active, &timer->node);
943 base->cpu_base->active_bases |= 1 << base->index;
946 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
947 * state of a possibly running callback.
949 timer->state |= HRTIMER_STATE_ENQUEUED;
951 return (&timer->node == base->active.next);
955 * __remove_hrtimer - internal function to remove a timer
957 * Caller must hold the base lock.
959 * High resolution timer mode reprograms the clock event device when the
960 * timer is the one which expires next. The caller can disable this by setting
961 * reprogram to zero. This is useful, when the context does a reprogramming
962 * anyway (e.g. timer interrupt)
964 static void __remove_hrtimer(struct hrtimer *timer,
965 struct hrtimer_clock_base *base,
966 unsigned long newstate, int reprogram)
968 struct timerqueue_node *next_timer;
969 if (!(timer->state & HRTIMER_STATE_ENQUEUED))
972 if (unlikely(!list_empty(&timer->cb_entry))) {
973 list_del_init(&timer->cb_entry);
977 next_timer = timerqueue_getnext(&base->active);
978 timerqueue_del(&base->active, &timer->node);
979 if (&timer->node == next_timer) {
980 #ifdef CONFIG_HIGH_RES_TIMERS
981 /* Reprogram the clock event device. if enabled */
982 if (reprogram && hrtimer_hres_active()) {
985 expires = ktime_sub(hrtimer_get_expires(timer),
987 if (base->cpu_base->expires_next.tv64 == expires.tv64)
988 hrtimer_force_reprogram(base->cpu_base, 1);
992 if (!timerqueue_getnext(&base->active))
993 base->cpu_base->active_bases &= ~(1 << base->index);
995 timer->state = newstate;
999 * remove hrtimer, called with base lock held
1002 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
1004 if (hrtimer_is_queued(timer)) {
1005 unsigned long state;
1009 * Remove the timer and force reprogramming when high
1010 * resolution mode is active and the timer is on the current
1011 * CPU. If we remove a timer on another CPU, reprogramming is
1012 * skipped. The interrupt event on this CPU is fired and
1013 * reprogramming happens in the interrupt handler. This is a
1014 * rare case and less expensive than a smp call.
1016 debug_deactivate(timer);
1017 timer_stats_hrtimer_clear_start_info(timer);
1018 reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1020 * We must preserve the CALLBACK state flag here,
1021 * otherwise we could move the timer base in
1022 * switch_hrtimer_base.
1024 state = timer->state & HRTIMER_STATE_CALLBACK;
1025 __remove_hrtimer(timer, base, state, reprogram);
1031 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1032 unsigned long delta_ns, const enum hrtimer_mode mode,
1035 struct hrtimer_clock_base *base, *new_base;
1036 unsigned long flags;
1039 base = lock_hrtimer_base(timer, &flags);
1041 /* Remove an active timer from the queue: */
1042 ret = remove_hrtimer(timer, base);
1044 if (mode & HRTIMER_MODE_REL) {
1045 tim = ktime_add_safe(tim, base->get_time());
1047 * CONFIG_TIME_LOW_RES is a temporary way for architectures
1048 * to signal that they simply return xtime in
1049 * do_gettimeoffset(). In this case we want to round up by
1050 * resolution when starting a relative timer, to avoid short
1051 * timeouts. This will go away with the GTOD framework.
1053 #ifdef CONFIG_TIME_LOW_RES
1054 tim = ktime_add_safe(tim, base->resolution);
1058 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1060 /* Switch the timer base, if necessary: */
1061 new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
1063 timer_stats_hrtimer_set_start_info(timer);
1064 #ifdef CONFIG_MISSED_TIMER_OFFSETS_HIST
1066 ktime_t now = new_base->get_time();
1068 if (ktime_to_ns(tim) < ktime_to_ns(now))
1069 timer->praecox = now;
1071 timer->praecox = ktime_set(0, 0);
1074 leftmost = enqueue_hrtimer(timer, new_base);
1077 unlock_hrtimer_base(timer, &flags);
1081 if (!hrtimer_is_hres_active(timer)) {
1083 * Kick to reschedule the next tick to handle the new timer
1084 * on dynticks target.
1086 wake_up_nohz_cpu(new_base->cpu_base->cpu);
1087 } else if (new_base->cpu_base == this_cpu_ptr(&hrtimer_bases)) {
1089 ret = hrtimer_enqueue_reprogram(timer, new_base, wakeup);
1092 * In case we failed to reprogram the timer (mostly
1093 * because out current timer is already elapsed),
1094 * remove it again and report a failure. This avoids
1095 * stale base->first entries.
1097 debug_deactivate(timer);
1098 __remove_hrtimer(timer, new_base,
1099 timer->state & HRTIMER_STATE_CALLBACK, 0);
1100 } else if (ret > 0) {
1102 * Only allow reprogramming if the new base is on this CPU.
1103 * (it might still be on another CPU if the timer was pending)
1105 * XXX send_remote_softirq() ?
1108 * We need to drop cpu_base->lock to avoid a
1109 * lock ordering issue vs. rq->lock.
1111 raw_spin_unlock(&new_base->cpu_base->lock);
1112 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1113 local_irq_restore(flags);
1118 unlock_hrtimer_base(timer, &flags);
1122 EXPORT_SYMBOL_GPL(__hrtimer_start_range_ns);
1125 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1126 * @timer: the timer to be added
1128 * @delta_ns: "slack" range for the timer
1129 * @mode: expiry mode: absolute (HRTIMER_MODE_ABS) or
1130 * relative (HRTIMER_MODE_REL)
1134 * 1 when the timer was active
1136 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1137 unsigned long delta_ns, const enum hrtimer_mode mode)
1139 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1141 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1144 * hrtimer_start - (re)start an hrtimer on the current CPU
1145 * @timer: the timer to be added
1147 * @mode: expiry mode: absolute (HRTIMER_MODE_ABS) or
1148 * relative (HRTIMER_MODE_REL)
1152 * 1 when the timer was active
1155 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1157 return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1159 EXPORT_SYMBOL_GPL(hrtimer_start);
1163 * hrtimer_try_to_cancel - try to deactivate a timer
1164 * @timer: hrtimer to stop
1167 * 0 when the timer was not active
1168 * 1 when the timer was active
1169 * -1 when the timer is currently excuting the callback function and
1172 int hrtimer_try_to_cancel(struct hrtimer *timer)
1174 struct hrtimer_clock_base *base;
1175 unsigned long flags;
1178 base = lock_hrtimer_base(timer, &flags);
1180 if (!hrtimer_callback_running(timer))
1181 ret = remove_hrtimer(timer, base);
1183 unlock_hrtimer_base(timer, &flags);
1188 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1191 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1192 * @timer: the timer to be cancelled
1195 * 0 when the timer was not active
1196 * 1 when the timer was active
1198 int hrtimer_cancel(struct hrtimer *timer)
1201 int ret = hrtimer_try_to_cancel(timer);
1205 hrtimer_wait_for_timer(timer);
1208 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1211 * hrtimer_get_remaining - get remaining time for the timer
1212 * @timer: the timer to read
1214 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1216 unsigned long flags;
1219 lock_hrtimer_base(timer, &flags);
1220 rem = hrtimer_expires_remaining(timer);
1221 unlock_hrtimer_base(timer, &flags);
1225 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1227 #ifdef CONFIG_NO_HZ_COMMON
1229 * hrtimer_get_next_event - get the time until next expiry event
1231 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1234 ktime_t hrtimer_get_next_event(void)
1236 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1237 ktime_t mindelta = { .tv64 = KTIME_MAX };
1238 unsigned long flags;
1240 raw_spin_lock_irqsave(&cpu_base->lock, flags);
1242 if (!hrtimer_hres_active())
1243 mindelta = ktime_sub(__hrtimer_get_next_event(cpu_base),
1246 raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1248 if (mindelta.tv64 < 0)
1254 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1255 enum hrtimer_mode mode)
1257 struct hrtimer_cpu_base *cpu_base;
1260 memset(timer, 0, sizeof(struct hrtimer));
1262 cpu_base = raw_cpu_ptr(&hrtimer_bases);
1264 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1265 clock_id = CLOCK_MONOTONIC;
1267 base = hrtimer_clockid_to_base(clock_id);
1268 timer->base = &cpu_base->clock_base[base];
1269 INIT_LIST_HEAD(&timer->cb_entry);
1270 timerqueue_init(&timer->node);
1272 #ifdef CONFIG_TIMER_STATS
1273 timer->start_site = NULL;
1274 timer->start_pid = -1;
1275 memset(timer->start_comm, 0, TASK_COMM_LEN);
1280 * hrtimer_init - initialize a timer to the given clock
1281 * @timer: the timer to be initialized
1282 * @clock_id: the clock to be used
1283 * @mode: timer mode abs/rel
1285 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1286 enum hrtimer_mode mode)
1288 debug_init(timer, clock_id, mode);
1289 __hrtimer_init(timer, clock_id, mode);
1291 EXPORT_SYMBOL_GPL(hrtimer_init);
1294 * hrtimer_get_res - get the timer resolution for a clock
1295 * @which_clock: which clock to query
1296 * @tp: pointer to timespec variable to store the resolution
1298 * Store the resolution of the clock selected by @which_clock in the
1299 * variable pointed to by @tp.
1301 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1303 struct hrtimer_cpu_base *cpu_base;
1304 int base = hrtimer_clockid_to_base(which_clock);
1306 cpu_base = raw_cpu_ptr(&hrtimer_bases);
1307 *tp = ktime_to_timespec(cpu_base->clock_base[base].resolution);
1311 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1313 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now)
1315 struct hrtimer_clock_base *base = timer->base;
1316 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1317 enum hrtimer_restart (*fn)(struct hrtimer *);
1320 WARN_ON(!irqs_disabled());
1322 debug_deactivate(timer);
1323 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1324 timer_stats_account_hrtimer(timer);
1325 fn = timer->function;
1328 * Because we run timers from hardirq context, there is no chance
1329 * they get migrated to another cpu, therefore its safe to unlock
1332 raw_spin_unlock(&cpu_base->lock);
1333 trace_hrtimer_expire_entry(timer, now);
1334 restart = fn(timer);
1335 trace_hrtimer_expire_exit(timer);
1336 raw_spin_lock(&cpu_base->lock);
1339 * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1340 * we do not reprogramm the event hardware. Happens either in
1341 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1343 if (restart != HRTIMER_NORESTART) {
1344 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1345 enqueue_hrtimer(timer, base);
1348 WARN_ON_ONCE(!(timer->state & HRTIMER_STATE_CALLBACK));
1350 timer->state &= ~HRTIMER_STATE_CALLBACK;
1353 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer);
1355 #ifdef CONFIG_PREEMPT_RT_BASE
1356 static void hrtimer_rt_reprogram(int restart, struct hrtimer *timer,
1357 struct hrtimer_clock_base *base)
1360 * Note, we clear the callback flag before we requeue the
1361 * timer otherwise we trigger the callback_running() check
1362 * in hrtimer_reprogram().
1364 timer->state &= ~HRTIMER_STATE_CALLBACK;
1366 if (restart != HRTIMER_NORESTART) {
1367 BUG_ON(hrtimer_active(timer));
1369 * Enqueue the timer, if it's the leftmost timer then
1370 * we need to reprogram it.
1372 if (!enqueue_hrtimer(timer, base))
1375 #ifndef CONFIG_HIGH_RES_TIMERS
1378 if (base->cpu_base->hres_active &&
1379 hrtimer_reprogram(timer, base))
1382 } else if (hrtimer_active(timer)) {
1384 * If the timer was rearmed on another CPU, reprogram
1387 if (&timer->node == base->active.next &&
1388 base->cpu_base->hres_active &&
1389 hrtimer_reprogram(timer, base))
1396 * Timer is expired. Thus move it from tree to pending list
1399 __remove_hrtimer(timer, base, timer->state, 0);
1400 list_add_tail(&timer->cb_entry, &base->expired);
1405 * The changes in mainline which removed the callback modes from
1406 * hrtimer are not yet working with -rt. The non wakeup_process()
1407 * based callbacks which involve sleeping locks need to be treated
1410 static void hrtimer_rt_run_pending(void)
1412 enum hrtimer_restart (*fn)(struct hrtimer *);
1413 struct hrtimer_cpu_base *cpu_base;
1414 struct hrtimer_clock_base *base;
1415 struct hrtimer *timer;
1418 local_irq_disable();
1419 cpu_base = &per_cpu(hrtimer_bases, smp_processor_id());
1421 raw_spin_lock(&cpu_base->lock);
1423 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1424 base = &cpu_base->clock_base[index];
1426 while (!list_empty(&base->expired)) {
1427 timer = list_first_entry(&base->expired,
1428 struct hrtimer, cb_entry);
1431 * Same as the above __run_hrtimer function
1432 * just we run with interrupts enabled.
1434 debug_hrtimer_deactivate(timer);
1435 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1436 timer_stats_account_hrtimer(timer);
1437 fn = timer->function;
1439 raw_spin_unlock_irq(&cpu_base->lock);
1440 restart = fn(timer);
1441 raw_spin_lock_irq(&cpu_base->lock);
1443 hrtimer_rt_reprogram(restart, timer, base);
1447 raw_spin_unlock_irq(&cpu_base->lock);
1449 wake_up_timer_waiters(cpu_base);
1452 static int hrtimer_rt_defer(struct hrtimer *timer)
1457 __remove_hrtimer(timer, timer->base, timer->state, 0);
1458 list_add_tail(&timer->cb_entry, &timer->base->expired);
1464 static inline void hrtimer_rt_run_pending(void)
1466 hrtimer_peek_ahead_timers();
1469 static inline int hrtimer_rt_defer(struct hrtimer *timer) { return 0; }
1473 #ifdef CONFIG_HIGH_RES_TIMERS
1476 * High resolution timer interrupt
1477 * Called with interrupts disabled
1479 void hrtimer_interrupt(struct clock_event_device *dev)
1481 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1482 ktime_t expires_next, now, entry_time, delta;
1483 int i, retries = 0, raise = 0;
1485 BUG_ON(!cpu_base->hres_active);
1486 cpu_base->nr_events++;
1487 dev->next_event.tv64 = KTIME_MAX;
1489 raw_spin_lock(&cpu_base->lock);
1490 entry_time = now = hrtimer_update_base(cpu_base);
1492 cpu_base->in_hrtirq = 1;
1494 * We set expires_next to KTIME_MAX here with cpu_base->lock
1495 * held to prevent that a timer is enqueued in our queue via
1496 * the migration code. This does not affect enqueueing of
1497 * timers which run their callback and need to be requeued on
1500 cpu_base->expires_next.tv64 = KTIME_MAX;
1502 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1503 struct hrtimer_clock_base *base;
1504 struct timerqueue_node *node;
1507 if (!(cpu_base->active_bases & (1 << i)))
1510 base = cpu_base->clock_base + i;
1511 basenow = ktime_add(now, base->offset);
1513 while ((node = timerqueue_getnext(&base->active))) {
1514 struct hrtimer *timer;
1516 timer = container_of(node, struct hrtimer, node);
1518 trace_hrtimer_interrupt(raw_smp_processor_id(),
1519 ktime_to_ns(ktime_sub(ktime_to_ns(timer->praecox) ?
1520 timer->praecox : hrtimer_get_expires(timer),
1523 timer->function == hrtimer_wakeup ?
1524 container_of(timer, struct hrtimer_sleeper,
1525 timer)->task : NULL);
1528 * The immediate goal for using the softexpires is
1529 * minimizing wakeups, not running timers at the
1530 * earliest interrupt after their soft expiration.
1531 * This allows us to avoid using a Priority Search
1532 * Tree, which can answer a stabbing querry for
1533 * overlapping intervals and instead use the simple
1534 * BST we already have.
1535 * We don't add extra wakeups by delaying timers that
1536 * are right-of a not yet expired timer, because that
1537 * timer will have to trigger a wakeup anyway.
1539 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer))
1542 if (!hrtimer_rt_defer(timer))
1543 __run_hrtimer(timer, &basenow);
1548 /* Reevaluate the clock bases for the next expiry */
1549 expires_next = __hrtimer_get_next_event(cpu_base);
1551 * Store the new expiry value so the migration code can verify
1554 cpu_base->expires_next = expires_next;
1555 cpu_base->in_hrtirq = 0;
1556 raw_spin_unlock(&cpu_base->lock);
1558 /* Reprogramming necessary ? */
1559 if (expires_next.tv64 == KTIME_MAX ||
1560 !tick_program_event(expires_next, 0)) {
1561 cpu_base->hang_detected = 0;
1566 * The next timer was already expired due to:
1568 * - long lasting callbacks
1569 * - being scheduled away when running in a VM
1571 * We need to prevent that we loop forever in the hrtimer
1572 * interrupt routine. We give it 3 attempts to avoid
1573 * overreacting on some spurious event.
1575 * Acquire base lock for updating the offsets and retrieving
1578 raw_spin_lock(&cpu_base->lock);
1579 now = hrtimer_update_base(cpu_base);
1580 cpu_base->nr_retries++;
1584 * Give the system a chance to do something else than looping
1585 * here. We stored the entry time, so we know exactly how long
1586 * we spent here. We schedule the next event this amount of
1589 cpu_base->nr_hangs++;
1590 cpu_base->hang_detected = 1;
1591 raw_spin_unlock(&cpu_base->lock);
1592 delta = ktime_sub(now, entry_time);
1593 if (delta.tv64 > cpu_base->max_hang_time.tv64)
1594 cpu_base->max_hang_time = delta;
1596 * Limit it to a sensible value as we enforce a longer
1597 * delay. Give the CPU at least 100ms to catch up.
1599 if (delta.tv64 > 100 * NSEC_PER_MSEC)
1600 expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1602 expires_next = ktime_add(now, delta);
1603 tick_program_event(expires_next, 1);
1604 printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1605 ktime_to_ns(delta));
1608 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1612 * local version of hrtimer_peek_ahead_timers() called with interrupts
1615 static void __hrtimer_peek_ahead_timers(void)
1617 struct tick_device *td;
1619 if (!hrtimer_hres_active())
1622 td = this_cpu_ptr(&tick_cpu_device);
1623 if (td && td->evtdev)
1624 hrtimer_interrupt(td->evtdev);
1628 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1630 * hrtimer_peek_ahead_timers will peek at the timer queue of
1631 * the current cpu and check if there are any timers for which
1632 * the soft expires time has passed. If any such timers exist,
1633 * they are run immediately and then removed from the timer queue.
1636 void hrtimer_peek_ahead_timers(void)
1638 unsigned long flags;
1640 local_irq_save(flags);
1641 __hrtimer_peek_ahead_timers();
1642 local_irq_restore(flags);
1644 #else /* CONFIG_HIGH_RES_TIMERS */
1646 static inline void __hrtimer_peek_ahead_timers(void) { }
1648 #endif /* !CONFIG_HIGH_RES_TIMERS */
1651 static void run_hrtimer_softirq(struct softirq_action *h)
1653 hrtimer_rt_run_pending();
1657 * Called from timer softirq every jiffy, expire hrtimers:
1659 * For HRT its the fall back code to run the softirq in the timer
1660 * softirq context in case the hrtimer initialization failed or has
1661 * not been done yet.
1663 void hrtimer_run_pending(void)
1665 if (hrtimer_hres_active())
1669 * This _is_ ugly: We have to check in the softirq context,
1670 * whether we can switch to highres and / or nohz mode. The
1671 * clocksource switch happens in the timer interrupt with
1672 * xtime_lock held. Notification from there only sets the
1673 * check bit in the tick_oneshot code, otherwise we might
1674 * deadlock vs. xtime_lock.
1676 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1677 hrtimer_switch_to_hres();
1681 * Called from hardirq context every jiffy
1683 void hrtimer_run_queues(void)
1685 struct timerqueue_node *node;
1686 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1687 struct hrtimer_clock_base *base;
1688 int index, gettime = 1, raise = 0;
1690 if (hrtimer_hres_active())
1693 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1694 base = &cpu_base->clock_base[index];
1695 if (!timerqueue_getnext(&base->active))
1699 hrtimer_get_softirq_time(cpu_base);
1703 raw_spin_lock(&cpu_base->lock);
1705 while ((node = timerqueue_getnext(&base->active))) {
1706 struct hrtimer *timer;
1708 timer = container_of(node, struct hrtimer, node);
1709 if (base->softirq_time.tv64 <=
1710 hrtimer_get_expires_tv64(timer))
1713 if (!hrtimer_rt_defer(timer))
1714 __run_hrtimer(timer, &base->softirq_time);
1718 raw_spin_unlock(&cpu_base->lock);
1722 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1726 * Sleep related functions:
1728 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1730 struct hrtimer_sleeper *t =
1731 container_of(timer, struct hrtimer_sleeper, timer);
1732 struct task_struct *task = t->task;
1736 wake_up_process(task);
1738 return HRTIMER_NORESTART;
1741 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1743 sl->timer.function = hrtimer_wakeup;
1744 sl->timer.irqsafe = 1;
1747 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1749 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode,
1750 unsigned long state)
1752 hrtimer_init_sleeper(t, current);
1755 set_current_state(state);
1756 hrtimer_start_expires(&t->timer, mode);
1757 if (!hrtimer_active(&t->timer))
1760 if (likely(t->task))
1761 freezable_schedule();
1763 hrtimer_cancel(&t->timer);
1764 mode = HRTIMER_MODE_ABS;
1766 } while (t->task && !signal_pending(current));
1768 __set_current_state(TASK_RUNNING);
1770 return t->task == NULL;
1773 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1775 struct timespec rmt;
1778 rem = hrtimer_expires_remaining(timer);
1781 rmt = ktime_to_timespec(rem);
1783 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1789 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1791 struct hrtimer_sleeper t;
1792 struct timespec __user *rmtp;
1795 hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
1797 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1799 /* cpu_chill() does not care about restart state. */
1800 if (do_nanosleep(&t, HRTIMER_MODE_ABS, TASK_INTERRUPTIBLE))
1803 rmtp = restart->nanosleep.rmtp;
1805 ret = update_rmtp(&t.timer, rmtp);
1810 /* The other values in restart are already filled in */
1811 ret = -ERESTART_RESTARTBLOCK;
1813 destroy_hrtimer_on_stack(&t.timer);
1818 __hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1819 const enum hrtimer_mode mode, const clockid_t clockid,
1820 unsigned long state)
1822 struct restart_block *restart;
1823 struct hrtimer_sleeper t;
1825 unsigned long slack;
1827 slack = current->timer_slack_ns;
1828 if (dl_task(current) || rt_task(current))
1831 hrtimer_init_on_stack(&t.timer, clockid, mode);
1832 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1833 if (do_nanosleep(&t, mode, state))
1836 /* Absolute timers do not update the rmtp value and restart: */
1837 if (mode == HRTIMER_MODE_ABS) {
1838 ret = -ERESTARTNOHAND;
1843 ret = update_rmtp(&t.timer, rmtp);
1848 restart = ¤t->restart_block;
1849 restart->fn = hrtimer_nanosleep_restart;
1850 restart->nanosleep.clockid = t.timer.base->clockid;
1851 restart->nanosleep.rmtp = rmtp;
1852 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1854 ret = -ERESTART_RESTARTBLOCK;
1856 destroy_hrtimer_on_stack(&t.timer);
1860 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1861 const enum hrtimer_mode mode, const clockid_t clockid)
1863 return __hrtimer_nanosleep(rqtp, rmtp, mode, clockid, TASK_INTERRUPTIBLE);
1866 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1867 struct timespec __user *, rmtp)
1871 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1874 if (!timespec_valid(&tu))
1877 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1880 #ifdef CONFIG_PREEMPT_RT_FULL
1882 * Sleep for 1 ms in hope whoever holds what we want will let it go.
1884 void cpu_chill(void)
1886 struct timespec tu = {
1887 .tv_nsec = NSEC_PER_MSEC,
1889 unsigned int freeze_flag = current->flags & PF_NOFREEZE;
1891 current->flags |= PF_NOFREEZE;
1892 __hrtimer_nanosleep(&tu, NULL, HRTIMER_MODE_REL, CLOCK_MONOTONIC,
1893 TASK_UNINTERRUPTIBLE);
1895 current->flags &= ~PF_NOFREEZE;
1897 EXPORT_SYMBOL(cpu_chill);
1901 * Functions related to boot-time initialization:
1903 static void init_hrtimers_cpu(int cpu)
1905 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1908 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1909 cpu_base->clock_base[i].cpu_base = cpu_base;
1910 timerqueue_init_head(&cpu_base->clock_base[i].active);
1911 INIT_LIST_HEAD(&cpu_base->clock_base[i].expired);
1914 cpu_base->cpu = cpu;
1915 hrtimer_init_hres(cpu_base);
1916 #ifdef CONFIG_PREEMPT_RT_BASE
1917 init_waitqueue_head(&cpu_base->wait);
1921 #ifdef CONFIG_HOTPLUG_CPU
1923 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1924 struct hrtimer_clock_base *new_base)
1926 struct hrtimer *timer;
1927 struct timerqueue_node *node;
1929 while ((node = timerqueue_getnext(&old_base->active))) {
1930 timer = container_of(node, struct hrtimer, node);
1931 BUG_ON(hrtimer_callback_running(timer));
1932 debug_deactivate(timer);
1935 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1936 * timer could be seen as !active and just vanish away
1937 * under us on another CPU
1939 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1940 timer->base = new_base;
1942 * Enqueue the timers on the new cpu. This does not
1943 * reprogram the event device in case the timer
1944 * expires before the earliest on this CPU, but we run
1945 * hrtimer_interrupt after we migrated everything to
1946 * sort out already expired timers and reprogram the
1949 enqueue_hrtimer(timer, new_base);
1951 /* Clear the migration state bit */
1952 timer->state &= ~HRTIMER_STATE_MIGRATE;
1956 static void migrate_hrtimers(int scpu)
1958 struct hrtimer_cpu_base *old_base, *new_base;
1961 BUG_ON(cpu_online(scpu));
1962 tick_cancel_sched_timer(scpu);
1964 local_irq_disable();
1965 old_base = &per_cpu(hrtimer_bases, scpu);
1966 new_base = this_cpu_ptr(&hrtimer_bases);
1968 * The caller is globally serialized and nobody else
1969 * takes two locks at once, deadlock is not possible.
1971 raw_spin_lock(&new_base->lock);
1972 raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1974 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1975 migrate_hrtimer_list(&old_base->clock_base[i],
1976 &new_base->clock_base[i]);
1979 raw_spin_unlock(&old_base->lock);
1980 raw_spin_unlock(&new_base->lock);
1982 /* Check, if we got expired work to do */
1983 __hrtimer_peek_ahead_timers();
1987 #endif /* CONFIG_HOTPLUG_CPU */
1989 static int hrtimer_cpu_notify(struct notifier_block *self,
1990 unsigned long action, void *hcpu)
1992 int scpu = (long)hcpu;
1996 case CPU_UP_PREPARE:
1997 case CPU_UP_PREPARE_FROZEN:
1998 init_hrtimers_cpu(scpu);
2001 #ifdef CONFIG_HOTPLUG_CPU
2003 case CPU_DEAD_FROZEN:
2004 migrate_hrtimers(scpu);
2015 static struct notifier_block hrtimers_nb = {
2016 .notifier_call = hrtimer_cpu_notify,
2019 void __init hrtimers_init(void)
2021 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
2022 (void *)(long)smp_processor_id());
2023 register_cpu_notifier(&hrtimers_nb);
2024 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
2028 * schedule_hrtimeout_range_clock - sleep until timeout
2029 * @expires: timeout value (ktime_t)
2030 * @delta: slack in expires timeout (ktime_t)
2031 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2032 * @clock: timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
2035 schedule_hrtimeout_range_clock(ktime_t *expires, unsigned long delta,
2036 const enum hrtimer_mode mode, int clock)
2038 struct hrtimer_sleeper t;
2041 * Optimize when a zero timeout value is given. It does not
2042 * matter whether this is an absolute or a relative time.
2044 if (expires && !expires->tv64) {
2045 __set_current_state(TASK_RUNNING);
2050 * A NULL parameter means "infinite"
2057 hrtimer_init_on_stack(&t.timer, clock, mode);
2058 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
2060 hrtimer_init_sleeper(&t, current);
2062 hrtimer_start_expires(&t.timer, mode);
2063 if (!hrtimer_active(&t.timer))
2069 hrtimer_cancel(&t.timer);
2070 destroy_hrtimer_on_stack(&t.timer);
2072 __set_current_state(TASK_RUNNING);
2074 return !t.task ? 0 : -EINTR;
2078 * schedule_hrtimeout_range - sleep until timeout
2079 * @expires: timeout value (ktime_t)
2080 * @delta: slack in expires timeout (ktime_t)
2081 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2083 * Make the current task sleep until the given expiry time has
2084 * elapsed. The routine will return immediately unless
2085 * the current task state has been set (see set_current_state()).
2087 * The @delta argument gives the kernel the freedom to schedule the
2088 * actual wakeup to a time that is both power and performance friendly.
2089 * The kernel give the normal best effort behavior for "@expires+@delta",
2090 * but may decide to fire the timer earlier, but no earlier than @expires.
2092 * You can set the task state as follows -
2094 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2095 * pass before the routine returns.
2097 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2098 * delivered to the current task.
2100 * The current task state is guaranteed to be TASK_RUNNING when this
2103 * Returns 0 when the timer has expired otherwise -EINTR
2105 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
2106 const enum hrtimer_mode mode)
2108 return schedule_hrtimeout_range_clock(expires, delta, mode,
2111 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
2114 * schedule_hrtimeout - sleep until timeout
2115 * @expires: timeout value (ktime_t)
2116 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2118 * Make the current task sleep until the given expiry time has
2119 * elapsed. The routine will return immediately unless
2120 * the current task state has been set (see set_current_state()).
2122 * You can set the task state as follows -
2124 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2125 * pass before the routine returns.
2127 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2128 * delivered to the current task.
2130 * The current task state is guaranteed to be TASK_RUNNING when this
2133 * Returns 0 when the timer has expired otherwise -EINTR
2135 int __sched schedule_hrtimeout(ktime_t *expires,
2136 const enum hrtimer_mode mode)
2138 return schedule_hrtimeout_range(expires, 0, mode);
2140 EXPORT_SYMBOL_GPL(schedule_hrtimeout);