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))
586 if (base->cpu_base != cpu_base)
589 if (cpu_base->in_hrtirq)
593 * CLOCK_REALTIME timer might be requested with an absolute
594 * expiry time which is less than base->offset. Nothing wrong
595 * about that, just avoid to call into the tick code, which
596 * has now objections against negative expiry values.
598 if (expires.tv64 < 0)
601 if (expires.tv64 >= cpu_base->expires_next.tv64)
605 * When the target cpu of the timer is currently executing
606 * hrtimer_interrupt(), then we do not touch the clock event
607 * device. hrtimer_interrupt() will reevaluate all clock bases
608 * before reprogramming the device.
610 if (cpu_base->in_hrtirq)
614 * If a hang was detected in the last timer interrupt then we
615 * do not schedule a timer which is earlier than the expiry
616 * which we enforced in the hang detection. We want the system
619 if (cpu_base->hang_detected)
622 cpu_base->expires_next = expires;
624 * Clockevents returns -ETIME, when the event was in the past.
626 res = tick_program_event(expires, 1);
630 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now);
631 static int hrtimer_rt_defer(struct hrtimer *timer);
634 * Initialize the high resolution related parts of cpu_base
636 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
638 base->expires_next.tv64 = KTIME_MAX;
639 base->hres_active = 0;
642 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
643 struct hrtimer_clock_base *base,
646 if (!hrtimer_reprogram(timer, base))
650 #ifdef CONFIG_PREEMPT_RT_BASE
651 if (!hrtimer_rt_defer(timer))
657 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
659 ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
660 ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
661 ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
663 return ktime_get_update_offsets_now(offs_real, offs_boot, offs_tai);
667 * Retrigger next event is called after clock was set
669 * Called with interrupts disabled via on_each_cpu()
671 static void retrigger_next_event(void *arg)
673 struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
675 if (!hrtimer_hres_active())
678 raw_spin_lock(&base->lock);
679 hrtimer_update_base(base);
680 hrtimer_force_reprogram(base, 0);
681 raw_spin_unlock(&base->lock);
685 * Switch to high resolution mode
687 static int hrtimer_switch_to_hres(void)
689 int i, cpu = smp_processor_id();
690 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
693 if (base->hres_active)
696 local_irq_save(flags);
698 if (tick_init_highres()) {
699 local_irq_restore(flags);
700 printk(KERN_WARNING "Could not switch to high resolution "
701 "mode on CPU %d\n", cpu);
704 base->hres_active = 1;
705 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
706 base->clock_base[i].resolution = KTIME_HIGH_RES;
708 tick_setup_sched_timer();
709 /* "Retrigger" the interrupt to get things going */
710 retrigger_next_event(NULL);
711 local_irq_restore(flags);
715 static void clock_was_set_work(struct work_struct *work)
720 static DECLARE_WORK(hrtimer_work, clock_was_set_work);
722 #ifdef CONFIG_PREEMPT_RT_FULL
724 * RT can not call schedule_work from real interrupt context.
725 * Need to make a thread to do the real work.
727 static struct task_struct *clock_set_delay_thread;
728 static bool do_clock_set_delay;
730 static int run_clock_set_delay(void *ignore)
732 while (!kthread_should_stop()) {
733 set_current_state(TASK_INTERRUPTIBLE);
734 if (do_clock_set_delay) {
735 do_clock_set_delay = false;
736 schedule_work(&hrtimer_work);
740 __set_current_state(TASK_RUNNING);
744 void clock_was_set_delayed(void)
746 do_clock_set_delay = true;
747 /* Make visible before waking up process */
749 wake_up_process(clock_set_delay_thread);
752 static __init int create_clock_set_delay_thread(void)
754 clock_set_delay_thread = kthread_run(run_clock_set_delay, NULL, "kclksetdelayd");
755 BUG_ON(!clock_set_delay_thread);
758 early_initcall(create_clock_set_delay_thread);
759 #else /* PREEMPT_RT_FULL */
761 * Called from timekeeping and resume code to reprogramm the hrtimer
762 * interrupt device on all cpus.
764 void clock_was_set_delayed(void)
766 schedule_work(&hrtimer_work);
772 static inline int hrtimer_hres_active(void) { return 0; }
773 static inline int hrtimer_is_hres_enabled(void) { return 0; }
774 static inline int hrtimer_switch_to_hres(void) { return 0; }
776 hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
777 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
778 struct hrtimer_clock_base *base,
784 static inline int hrtimer_reprogram(struct hrtimer *timer,
785 struct hrtimer_clock_base *base)
789 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
790 static inline void retrigger_next_event(void *arg) { }
791 #endif /* CONFIG_HIGH_RES_TIMERS */
794 * Clock realtime was set
796 * Change the offset of the realtime clock vs. the monotonic
799 * We might have to reprogram the high resolution timer interrupt. On
800 * SMP we call the architecture specific code to retrigger _all_ high
801 * resolution timer interrupts. On UP we just disable interrupts and
802 * call the high resolution interrupt code.
804 void clock_was_set(void)
806 #ifdef CONFIG_HIGH_RES_TIMERS
807 /* Retrigger the CPU local events everywhere */
808 on_each_cpu(retrigger_next_event, NULL, 1);
810 timerfd_clock_was_set();
814 * During resume we might have to reprogram the high resolution timer
815 * interrupt on all online CPUs. However, all other CPUs will be
816 * stopped with IRQs interrupts disabled so the clock_was_set() call
819 void hrtimers_resume(void)
821 WARN_ONCE(!irqs_disabled(),
822 KERN_INFO "hrtimers_resume() called with IRQs enabled!");
824 /* Retrigger on the local CPU */
825 retrigger_next_event(NULL);
826 /* And schedule a retrigger for all others */
827 clock_was_set_delayed();
830 static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
832 #ifdef CONFIG_TIMER_STATS
833 if (timer->start_site)
835 timer->start_site = __builtin_return_address(0);
836 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
837 timer->start_pid = current->pid;
841 static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
843 #ifdef CONFIG_TIMER_STATS
844 timer->start_site = NULL;
848 static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
850 #ifdef CONFIG_TIMER_STATS
851 if (likely(!timer_stats_active))
853 timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
854 timer->function, timer->start_comm, 0);
859 * Counterpart to lock_hrtimer_base above:
862 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
864 raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
868 * hrtimer_forward - forward the timer expiry
869 * @timer: hrtimer to forward
870 * @now: forward past this time
871 * @interval: the interval to forward
873 * Forward the timer expiry so it will expire in the future.
874 * Returns the number of overruns.
876 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
881 delta = ktime_sub(now, hrtimer_get_expires(timer));
886 if (interval.tv64 < timer->base->resolution.tv64)
887 interval.tv64 = timer->base->resolution.tv64;
889 if (unlikely(delta.tv64 >= interval.tv64)) {
890 s64 incr = ktime_to_ns(interval);
892 orun = ktime_divns(delta, incr);
893 hrtimer_add_expires_ns(timer, incr * orun);
894 if (hrtimer_get_expires_tv64(timer) > now.tv64)
897 * This (and the ktime_add() below) is the
898 * correction for exact:
902 hrtimer_add_expires(timer, interval);
906 EXPORT_SYMBOL_GPL(hrtimer_forward);
908 #ifdef CONFIG_PREEMPT_RT_BASE
909 # define wake_up_timer_waiters(b) wake_up(&(b)->wait)
912 * hrtimer_wait_for_timer - Wait for a running timer
914 * @timer: timer to wait for
916 * The function waits in case the timers callback function is
917 * currently executed on the waitqueue of the timer base. The
918 * waitqueue is woken up after the timer callback function has
919 * finished execution.
921 void hrtimer_wait_for_timer(const struct hrtimer *timer)
923 struct hrtimer_clock_base *base = timer->base;
925 if (base && base->cpu_base && !timer->irqsafe)
926 wait_event(base->cpu_base->wait,
927 !(timer->state & HRTIMER_STATE_CALLBACK));
931 # define wake_up_timer_waiters(b) do { } while (0)
935 * enqueue_hrtimer - internal function to (re)start a timer
937 * The timer is inserted in expiry order. Insertion into the
938 * red black tree is O(log(n)). Must hold the base lock.
940 * Returns 1 when the new timer is the leftmost timer in the tree.
942 static int enqueue_hrtimer(struct hrtimer *timer,
943 struct hrtimer_clock_base *base)
945 debug_activate(timer);
947 timerqueue_add(&base->active, &timer->node);
948 base->cpu_base->active_bases |= 1 << base->index;
951 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
952 * state of a possibly running callback.
954 timer->state |= HRTIMER_STATE_ENQUEUED;
956 return (&timer->node == base->active.next);
960 * __remove_hrtimer - internal function to remove a timer
962 * Caller must hold the base lock.
964 * High resolution timer mode reprograms the clock event device when the
965 * timer is the one which expires next. The caller can disable this by setting
966 * reprogram to zero. This is useful, when the context does a reprogramming
967 * anyway (e.g. timer interrupt)
969 static void __remove_hrtimer(struct hrtimer *timer,
970 struct hrtimer_clock_base *base,
971 unsigned long newstate, int reprogram)
973 struct timerqueue_node *next_timer;
974 if (!(timer->state & HRTIMER_STATE_ENQUEUED))
977 if (unlikely(!list_empty(&timer->cb_entry))) {
978 list_del_init(&timer->cb_entry);
982 next_timer = timerqueue_getnext(&base->active);
983 timerqueue_del(&base->active, &timer->node);
984 if (&timer->node == next_timer) {
985 #ifdef CONFIG_HIGH_RES_TIMERS
986 /* Reprogram the clock event device. if enabled */
987 if (reprogram && hrtimer_hres_active()) {
990 expires = ktime_sub(hrtimer_get_expires(timer),
992 if (base->cpu_base->expires_next.tv64 == expires.tv64)
993 hrtimer_force_reprogram(base->cpu_base, 1);
997 if (!timerqueue_getnext(&base->active))
998 base->cpu_base->active_bases &= ~(1 << base->index);
1000 timer->state = newstate;
1004 * remove hrtimer, called with base lock held
1007 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
1009 if (hrtimer_is_queued(timer)) {
1010 unsigned long state;
1014 * Remove the timer and force reprogramming when high
1015 * resolution mode is active and the timer is on the current
1016 * CPU. If we remove a timer on another CPU, reprogramming is
1017 * skipped. The interrupt event on this CPU is fired and
1018 * reprogramming happens in the interrupt handler. This is a
1019 * rare case and less expensive than a smp call.
1021 debug_deactivate(timer);
1022 timer_stats_hrtimer_clear_start_info(timer);
1023 reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1025 * We must preserve the CALLBACK state flag here,
1026 * otherwise we could move the timer base in
1027 * switch_hrtimer_base.
1029 state = timer->state & HRTIMER_STATE_CALLBACK;
1030 __remove_hrtimer(timer, base, state, reprogram);
1036 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1037 unsigned long delta_ns, const enum hrtimer_mode mode,
1040 struct hrtimer_clock_base *base, *new_base;
1041 unsigned long flags;
1044 base = lock_hrtimer_base(timer, &flags);
1046 /* Remove an active timer from the queue: */
1047 ret = remove_hrtimer(timer, base);
1049 if (mode & HRTIMER_MODE_REL) {
1050 tim = ktime_add_safe(tim, base->get_time());
1052 * CONFIG_TIME_LOW_RES is a temporary way for architectures
1053 * to signal that they simply return xtime in
1054 * do_gettimeoffset(). In this case we want to round up by
1055 * resolution when starting a relative timer, to avoid short
1056 * timeouts. This will go away with the GTOD framework.
1058 #ifdef CONFIG_TIME_LOW_RES
1059 tim = ktime_add_safe(tim, base->resolution);
1063 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1065 /* Switch the timer base, if necessary: */
1066 new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
1068 timer_stats_hrtimer_set_start_info(timer);
1069 #ifdef CONFIG_MISSED_TIMER_OFFSETS_HIST
1071 ktime_t now = new_base->get_time();
1073 if (ktime_to_ns(tim) < ktime_to_ns(now))
1074 timer->praecox = now;
1076 timer->praecox = ktime_set(0, 0);
1079 leftmost = enqueue_hrtimer(timer, new_base);
1082 unlock_hrtimer_base(timer, &flags);
1086 if (!hrtimer_is_hres_active(timer)) {
1088 * Kick to reschedule the next tick to handle the new timer
1089 * on dynticks target.
1091 wake_up_nohz_cpu(new_base->cpu_base->cpu);
1092 } else if (new_base->cpu_base == this_cpu_ptr(&hrtimer_bases)) {
1094 ret = hrtimer_enqueue_reprogram(timer, new_base, wakeup);
1097 * In case we failed to reprogram the timer (mostly
1098 * because out current timer is already elapsed),
1099 * remove it again and report a failure. This avoids
1100 * stale base->first entries.
1102 debug_deactivate(timer);
1103 __remove_hrtimer(timer, new_base,
1104 timer->state & HRTIMER_STATE_CALLBACK, 0);
1105 } else if (ret > 0) {
1107 * Only allow reprogramming if the new base is on this CPU.
1108 * (it might still be on another CPU if the timer was pending)
1110 * XXX send_remote_softirq() ?
1113 * We need to drop cpu_base->lock to avoid a
1114 * lock ordering issue vs. rq->lock.
1116 raw_spin_unlock(&new_base->cpu_base->lock);
1117 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1118 local_irq_restore(flags);
1123 unlock_hrtimer_base(timer, &flags);
1127 EXPORT_SYMBOL_GPL(__hrtimer_start_range_ns);
1130 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1131 * @timer: the timer to be added
1133 * @delta_ns: "slack" range for the timer
1134 * @mode: expiry mode: absolute (HRTIMER_MODE_ABS) or
1135 * relative (HRTIMER_MODE_REL)
1139 * 1 when the timer was active
1141 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1142 unsigned long delta_ns, const enum hrtimer_mode mode)
1144 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1146 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1149 * hrtimer_start - (re)start an hrtimer on the current CPU
1150 * @timer: the timer to be added
1152 * @mode: expiry mode: absolute (HRTIMER_MODE_ABS) or
1153 * relative (HRTIMER_MODE_REL)
1157 * 1 when the timer was active
1160 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1162 return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1164 EXPORT_SYMBOL_GPL(hrtimer_start);
1168 * hrtimer_try_to_cancel - try to deactivate a timer
1169 * @timer: hrtimer to stop
1172 * 0 when the timer was not active
1173 * 1 when the timer was active
1174 * -1 when the timer is currently excuting the callback function and
1177 int hrtimer_try_to_cancel(struct hrtimer *timer)
1179 struct hrtimer_clock_base *base;
1180 unsigned long flags;
1183 base = lock_hrtimer_base(timer, &flags);
1185 if (!hrtimer_callback_running(timer))
1186 ret = remove_hrtimer(timer, base);
1188 unlock_hrtimer_base(timer, &flags);
1193 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1196 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1197 * @timer: the timer to be cancelled
1200 * 0 when the timer was not active
1201 * 1 when the timer was active
1203 int hrtimer_cancel(struct hrtimer *timer)
1206 int ret = hrtimer_try_to_cancel(timer);
1210 hrtimer_wait_for_timer(timer);
1213 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1216 * hrtimer_get_remaining - get remaining time for the timer
1217 * @timer: the timer to read
1219 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1221 unsigned long flags;
1224 lock_hrtimer_base(timer, &flags);
1225 rem = hrtimer_expires_remaining(timer);
1226 unlock_hrtimer_base(timer, &flags);
1230 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1232 #ifdef CONFIG_NO_HZ_COMMON
1234 * hrtimer_get_next_event - get the time until next expiry event
1236 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1239 ktime_t hrtimer_get_next_event(void)
1241 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1242 ktime_t mindelta = { .tv64 = KTIME_MAX };
1243 unsigned long flags;
1245 raw_spin_lock_irqsave(&cpu_base->lock, flags);
1247 if (!hrtimer_hres_active())
1248 mindelta = ktime_sub(__hrtimer_get_next_event(cpu_base),
1251 raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1253 if (mindelta.tv64 < 0)
1259 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1260 enum hrtimer_mode mode)
1262 struct hrtimer_cpu_base *cpu_base;
1265 memset(timer, 0, sizeof(struct hrtimer));
1267 cpu_base = raw_cpu_ptr(&hrtimer_bases);
1269 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1270 clock_id = CLOCK_MONOTONIC;
1272 base = hrtimer_clockid_to_base(clock_id);
1273 timer->base = &cpu_base->clock_base[base];
1274 INIT_LIST_HEAD(&timer->cb_entry);
1275 timerqueue_init(&timer->node);
1277 #ifdef CONFIG_TIMER_STATS
1278 timer->start_site = NULL;
1279 timer->start_pid = -1;
1280 memset(timer->start_comm, 0, TASK_COMM_LEN);
1285 * hrtimer_init - initialize a timer to the given clock
1286 * @timer: the timer to be initialized
1287 * @clock_id: the clock to be used
1288 * @mode: timer mode abs/rel
1290 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1291 enum hrtimer_mode mode)
1293 debug_init(timer, clock_id, mode);
1294 __hrtimer_init(timer, clock_id, mode);
1296 EXPORT_SYMBOL_GPL(hrtimer_init);
1299 * hrtimer_get_res - get the timer resolution for a clock
1300 * @which_clock: which clock to query
1301 * @tp: pointer to timespec variable to store the resolution
1303 * Store the resolution of the clock selected by @which_clock in the
1304 * variable pointed to by @tp.
1306 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1308 struct hrtimer_cpu_base *cpu_base;
1309 int base = hrtimer_clockid_to_base(which_clock);
1311 cpu_base = raw_cpu_ptr(&hrtimer_bases);
1312 *tp = ktime_to_timespec(cpu_base->clock_base[base].resolution);
1316 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1318 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now)
1320 struct hrtimer_clock_base *base = timer->base;
1321 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1322 enum hrtimer_restart (*fn)(struct hrtimer *);
1325 WARN_ON(!irqs_disabled());
1327 debug_deactivate(timer);
1328 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1329 timer_stats_account_hrtimer(timer);
1330 fn = timer->function;
1333 * Because we run timers from hardirq context, there is no chance
1334 * they get migrated to another cpu, therefore its safe to unlock
1337 raw_spin_unlock(&cpu_base->lock);
1338 trace_hrtimer_expire_entry(timer, now);
1339 restart = fn(timer);
1340 trace_hrtimer_expire_exit(timer);
1341 raw_spin_lock(&cpu_base->lock);
1344 * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1345 * we do not reprogramm the event hardware. Happens either in
1346 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1348 if (restart != HRTIMER_NORESTART) {
1349 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1350 enqueue_hrtimer(timer, base);
1353 WARN_ON_ONCE(!(timer->state & HRTIMER_STATE_CALLBACK));
1355 timer->state &= ~HRTIMER_STATE_CALLBACK;
1358 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer);
1360 #ifdef CONFIG_PREEMPT_RT_BASE
1361 static void hrtimer_rt_reprogram(int restart, struct hrtimer *timer,
1362 struct hrtimer_clock_base *base)
1365 * Note, we clear the callback flag before we requeue the
1366 * timer otherwise we trigger the callback_running() check
1367 * in hrtimer_reprogram().
1369 timer->state &= ~HRTIMER_STATE_CALLBACK;
1371 if (restart != HRTIMER_NORESTART) {
1372 BUG_ON(hrtimer_active(timer));
1374 * Enqueue the timer, if it's the leftmost timer then
1375 * we need to reprogram it.
1377 if (!enqueue_hrtimer(timer, base))
1380 #ifndef CONFIG_HIGH_RES_TIMERS
1383 if (base->cpu_base->hres_active &&
1384 hrtimer_reprogram(timer, base))
1387 } else if (hrtimer_active(timer)) {
1389 * If the timer was rearmed on another CPU, reprogram
1392 if (&timer->node == base->active.next &&
1393 base->cpu_base->hres_active &&
1394 hrtimer_reprogram(timer, base))
1401 * Timer is expired. Thus move it from tree to pending list
1404 __remove_hrtimer(timer, base, timer->state, 0);
1405 list_add_tail(&timer->cb_entry, &base->expired);
1410 * The changes in mainline which removed the callback modes from
1411 * hrtimer are not yet working with -rt. The non wakeup_process()
1412 * based callbacks which involve sleeping locks need to be treated
1415 static void hrtimer_rt_run_pending(void)
1417 enum hrtimer_restart (*fn)(struct hrtimer *);
1418 struct hrtimer_cpu_base *cpu_base;
1419 struct hrtimer_clock_base *base;
1420 struct hrtimer *timer;
1423 local_irq_disable();
1424 cpu_base = &per_cpu(hrtimer_bases, smp_processor_id());
1426 raw_spin_lock(&cpu_base->lock);
1428 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1429 base = &cpu_base->clock_base[index];
1431 while (!list_empty(&base->expired)) {
1432 timer = list_first_entry(&base->expired,
1433 struct hrtimer, cb_entry);
1436 * Same as the above __run_hrtimer function
1437 * just we run with interrupts enabled.
1439 debug_hrtimer_deactivate(timer);
1440 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1441 timer_stats_account_hrtimer(timer);
1442 fn = timer->function;
1444 raw_spin_unlock_irq(&cpu_base->lock);
1445 restart = fn(timer);
1446 raw_spin_lock_irq(&cpu_base->lock);
1448 hrtimer_rt_reprogram(restart, timer, base);
1452 raw_spin_unlock_irq(&cpu_base->lock);
1454 wake_up_timer_waiters(cpu_base);
1457 static int hrtimer_rt_defer(struct hrtimer *timer)
1462 __remove_hrtimer(timer, timer->base, timer->state, 0);
1463 list_add_tail(&timer->cb_entry, &timer->base->expired);
1469 static inline void hrtimer_rt_run_pending(void)
1471 hrtimer_peek_ahead_timers();
1474 static inline int hrtimer_rt_defer(struct hrtimer *timer) { return 0; }
1478 #ifdef CONFIG_HIGH_RES_TIMERS
1481 * High resolution timer interrupt
1482 * Called with interrupts disabled
1484 void hrtimer_interrupt(struct clock_event_device *dev)
1486 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1487 ktime_t expires_next, now, entry_time, delta;
1488 int i, retries = 0, raise = 0;
1490 BUG_ON(!cpu_base->hres_active);
1491 cpu_base->nr_events++;
1492 dev->next_event.tv64 = KTIME_MAX;
1494 raw_spin_lock(&cpu_base->lock);
1495 entry_time = now = hrtimer_update_base(cpu_base);
1497 cpu_base->in_hrtirq = 1;
1499 * We set expires_next to KTIME_MAX here with cpu_base->lock
1500 * held to prevent that a timer is enqueued in our queue via
1501 * the migration code. This does not affect enqueueing of
1502 * timers which run their callback and need to be requeued on
1505 cpu_base->expires_next.tv64 = KTIME_MAX;
1507 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1508 struct hrtimer_clock_base *base;
1509 struct timerqueue_node *node;
1512 if (!(cpu_base->active_bases & (1 << i)))
1515 base = cpu_base->clock_base + i;
1516 basenow = ktime_add(now, base->offset);
1518 while ((node = timerqueue_getnext(&base->active))) {
1519 struct hrtimer *timer;
1521 timer = container_of(node, struct hrtimer, node);
1523 trace_hrtimer_interrupt(raw_smp_processor_id(),
1524 ktime_to_ns(ktime_sub(ktime_to_ns(timer->praecox) ?
1525 timer->praecox : hrtimer_get_expires(timer),
1528 timer->function == hrtimer_wakeup ?
1529 container_of(timer, struct hrtimer_sleeper,
1530 timer)->task : NULL);
1533 * The immediate goal for using the softexpires is
1534 * minimizing wakeups, not running timers at the
1535 * earliest interrupt after their soft expiration.
1536 * This allows us to avoid using a Priority Search
1537 * Tree, which can answer a stabbing querry for
1538 * overlapping intervals and instead use the simple
1539 * BST we already have.
1540 * We don't add extra wakeups by delaying timers that
1541 * are right-of a not yet expired timer, because that
1542 * timer will have to trigger a wakeup anyway.
1544 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer))
1547 if (!hrtimer_rt_defer(timer))
1548 __run_hrtimer(timer, &basenow);
1553 /* Reevaluate the clock bases for the next expiry */
1554 expires_next = __hrtimer_get_next_event(cpu_base);
1556 * Store the new expiry value so the migration code can verify
1559 cpu_base->expires_next = expires_next;
1560 cpu_base->in_hrtirq = 0;
1561 raw_spin_unlock(&cpu_base->lock);
1563 /* Reprogramming necessary ? */
1564 if (expires_next.tv64 == KTIME_MAX ||
1565 !tick_program_event(expires_next, 0)) {
1566 cpu_base->hang_detected = 0;
1571 * The next timer was already expired due to:
1573 * - long lasting callbacks
1574 * - being scheduled away when running in a VM
1576 * We need to prevent that we loop forever in the hrtimer
1577 * interrupt routine. We give it 3 attempts to avoid
1578 * overreacting on some spurious event.
1580 * Acquire base lock for updating the offsets and retrieving
1583 raw_spin_lock(&cpu_base->lock);
1584 now = hrtimer_update_base(cpu_base);
1585 cpu_base->nr_retries++;
1589 * Give the system a chance to do something else than looping
1590 * here. We stored the entry time, so we know exactly how long
1591 * we spent here. We schedule the next event this amount of
1594 cpu_base->nr_hangs++;
1595 cpu_base->hang_detected = 1;
1596 raw_spin_unlock(&cpu_base->lock);
1597 delta = ktime_sub(now, entry_time);
1598 if (delta.tv64 > cpu_base->max_hang_time.tv64)
1599 cpu_base->max_hang_time = delta;
1601 * Limit it to a sensible value as we enforce a longer
1602 * delay. Give the CPU at least 100ms to catch up.
1604 if (delta.tv64 > 100 * NSEC_PER_MSEC)
1605 expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1607 expires_next = ktime_add(now, delta);
1608 tick_program_event(expires_next, 1);
1609 printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1610 ktime_to_ns(delta));
1613 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1617 * local version of hrtimer_peek_ahead_timers() called with interrupts
1620 static void __hrtimer_peek_ahead_timers(void)
1622 struct tick_device *td;
1624 if (!hrtimer_hres_active())
1627 td = this_cpu_ptr(&tick_cpu_device);
1628 if (td && td->evtdev)
1629 hrtimer_interrupt(td->evtdev);
1633 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1635 * hrtimer_peek_ahead_timers will peek at the timer queue of
1636 * the current cpu and check if there are any timers for which
1637 * the soft expires time has passed. If any such timers exist,
1638 * they are run immediately and then removed from the timer queue.
1641 void hrtimer_peek_ahead_timers(void)
1643 unsigned long flags;
1645 local_irq_save(flags);
1646 __hrtimer_peek_ahead_timers();
1647 local_irq_restore(flags);
1649 #else /* CONFIG_HIGH_RES_TIMERS */
1651 static inline void __hrtimer_peek_ahead_timers(void) { }
1653 #endif /* !CONFIG_HIGH_RES_TIMERS */
1656 static void run_hrtimer_softirq(struct softirq_action *h)
1658 hrtimer_rt_run_pending();
1662 * Called from timer softirq every jiffy, expire hrtimers:
1664 * For HRT its the fall back code to run the softirq in the timer
1665 * softirq context in case the hrtimer initialization failed or has
1666 * not been done yet.
1668 void hrtimer_run_pending(void)
1670 if (hrtimer_hres_active())
1674 * This _is_ ugly: We have to check in the softirq context,
1675 * whether we can switch to highres and / or nohz mode. The
1676 * clocksource switch happens in the timer interrupt with
1677 * xtime_lock held. Notification from there only sets the
1678 * check bit in the tick_oneshot code, otherwise we might
1679 * deadlock vs. xtime_lock.
1681 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1682 hrtimer_switch_to_hres();
1686 * Called from hardirq context every jiffy
1688 void hrtimer_run_queues(void)
1690 struct timerqueue_node *node;
1691 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1692 struct hrtimer_clock_base *base;
1693 int index, gettime = 1, raise = 0;
1695 if (hrtimer_hres_active())
1698 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1699 base = &cpu_base->clock_base[index];
1700 if (!timerqueue_getnext(&base->active))
1704 hrtimer_get_softirq_time(cpu_base);
1708 raw_spin_lock(&cpu_base->lock);
1710 while ((node = timerqueue_getnext(&base->active))) {
1711 struct hrtimer *timer;
1713 timer = container_of(node, struct hrtimer, node);
1714 if (base->softirq_time.tv64 <=
1715 hrtimer_get_expires_tv64(timer))
1718 if (!hrtimer_rt_defer(timer))
1719 __run_hrtimer(timer, &base->softirq_time);
1723 raw_spin_unlock(&cpu_base->lock);
1727 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1731 * Sleep related functions:
1733 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1735 struct hrtimer_sleeper *t =
1736 container_of(timer, struct hrtimer_sleeper, timer);
1737 struct task_struct *task = t->task;
1741 wake_up_process(task);
1743 return HRTIMER_NORESTART;
1746 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1748 sl->timer.function = hrtimer_wakeup;
1749 sl->timer.irqsafe = 1;
1752 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1754 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode,
1755 unsigned long state)
1757 hrtimer_init_sleeper(t, current);
1760 set_current_state(state);
1761 hrtimer_start_expires(&t->timer, mode);
1762 if (!hrtimer_active(&t->timer))
1765 if (likely(t->task))
1766 freezable_schedule();
1768 hrtimer_cancel(&t->timer);
1769 mode = HRTIMER_MODE_ABS;
1771 } while (t->task && !signal_pending(current));
1773 __set_current_state(TASK_RUNNING);
1775 return t->task == NULL;
1778 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1780 struct timespec rmt;
1783 rem = hrtimer_expires_remaining(timer);
1786 rmt = ktime_to_timespec(rem);
1788 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1794 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1796 struct hrtimer_sleeper t;
1797 struct timespec __user *rmtp;
1800 hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
1802 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1804 /* cpu_chill() does not care about restart state. */
1805 if (do_nanosleep(&t, HRTIMER_MODE_ABS, TASK_INTERRUPTIBLE))
1808 rmtp = restart->nanosleep.rmtp;
1810 ret = update_rmtp(&t.timer, rmtp);
1815 /* The other values in restart are already filled in */
1816 ret = -ERESTART_RESTARTBLOCK;
1818 destroy_hrtimer_on_stack(&t.timer);
1823 __hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1824 const enum hrtimer_mode mode, const clockid_t clockid,
1825 unsigned long state)
1827 struct restart_block *restart;
1828 struct hrtimer_sleeper t;
1830 unsigned long slack;
1832 slack = current->timer_slack_ns;
1833 if (dl_task(current) || rt_task(current))
1836 hrtimer_init_on_stack(&t.timer, clockid, mode);
1837 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1838 if (do_nanosleep(&t, mode, state))
1841 /* Absolute timers do not update the rmtp value and restart: */
1842 if (mode == HRTIMER_MODE_ABS) {
1843 ret = -ERESTARTNOHAND;
1848 ret = update_rmtp(&t.timer, rmtp);
1853 restart = ¤t->restart_block;
1854 restart->fn = hrtimer_nanosleep_restart;
1855 restart->nanosleep.clockid = t.timer.base->clockid;
1856 restart->nanosleep.rmtp = rmtp;
1857 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1859 ret = -ERESTART_RESTARTBLOCK;
1861 destroy_hrtimer_on_stack(&t.timer);
1865 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1866 const enum hrtimer_mode mode, const clockid_t clockid)
1868 return __hrtimer_nanosleep(rqtp, rmtp, mode, clockid, TASK_INTERRUPTIBLE);
1871 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1872 struct timespec __user *, rmtp)
1876 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1879 if (!timespec_valid(&tu))
1882 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1885 #ifdef CONFIG_PREEMPT_RT_FULL
1887 * Sleep for 1 ms in hope whoever holds what we want will let it go.
1889 void cpu_chill(void)
1891 struct timespec tu = {
1892 .tv_nsec = NSEC_PER_MSEC,
1894 unsigned int freeze_flag = current->flags & PF_NOFREEZE;
1896 current->flags |= PF_NOFREEZE;
1897 __hrtimer_nanosleep(&tu, NULL, HRTIMER_MODE_REL, CLOCK_MONOTONIC,
1898 TASK_UNINTERRUPTIBLE);
1900 current->flags &= ~PF_NOFREEZE;
1902 EXPORT_SYMBOL(cpu_chill);
1906 * Functions related to boot-time initialization:
1908 static void init_hrtimers_cpu(int cpu)
1910 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1913 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1914 cpu_base->clock_base[i].cpu_base = cpu_base;
1915 timerqueue_init_head(&cpu_base->clock_base[i].active);
1916 INIT_LIST_HEAD(&cpu_base->clock_base[i].expired);
1919 cpu_base->cpu = cpu;
1920 hrtimer_init_hres(cpu_base);
1921 #ifdef CONFIG_PREEMPT_RT_BASE
1922 init_waitqueue_head(&cpu_base->wait);
1926 #ifdef CONFIG_HOTPLUG_CPU
1928 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1929 struct hrtimer_clock_base *new_base)
1931 struct hrtimer *timer;
1932 struct timerqueue_node *node;
1934 while ((node = timerqueue_getnext(&old_base->active))) {
1935 timer = container_of(node, struct hrtimer, node);
1936 BUG_ON(hrtimer_callback_running(timer));
1937 debug_deactivate(timer);
1940 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1941 * timer could be seen as !active and just vanish away
1942 * under us on another CPU
1944 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1945 timer->base = new_base;
1947 * Enqueue the timers on the new cpu. This does not
1948 * reprogram the event device in case the timer
1949 * expires before the earliest on this CPU, but we run
1950 * hrtimer_interrupt after we migrated everything to
1951 * sort out already expired timers and reprogram the
1954 enqueue_hrtimer(timer, new_base);
1956 /* Clear the migration state bit */
1957 timer->state &= ~HRTIMER_STATE_MIGRATE;
1961 static void migrate_hrtimers(int scpu)
1963 struct hrtimer_cpu_base *old_base, *new_base;
1966 BUG_ON(cpu_online(scpu));
1967 tick_cancel_sched_timer(scpu);
1969 local_irq_disable();
1970 old_base = &per_cpu(hrtimer_bases, scpu);
1971 new_base = this_cpu_ptr(&hrtimer_bases);
1973 * The caller is globally serialized and nobody else
1974 * takes two locks at once, deadlock is not possible.
1976 raw_spin_lock(&new_base->lock);
1977 raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1979 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1980 migrate_hrtimer_list(&old_base->clock_base[i],
1981 &new_base->clock_base[i]);
1984 raw_spin_unlock(&old_base->lock);
1985 raw_spin_unlock(&new_base->lock);
1987 /* Check, if we got expired work to do */
1988 __hrtimer_peek_ahead_timers();
1992 #endif /* CONFIG_HOTPLUG_CPU */
1994 static int hrtimer_cpu_notify(struct notifier_block *self,
1995 unsigned long action, void *hcpu)
1997 int scpu = (long)hcpu;
2001 case CPU_UP_PREPARE:
2002 case CPU_UP_PREPARE_FROZEN:
2003 init_hrtimers_cpu(scpu);
2006 #ifdef CONFIG_HOTPLUG_CPU
2008 case CPU_DEAD_FROZEN:
2009 migrate_hrtimers(scpu);
2020 static struct notifier_block hrtimers_nb = {
2021 .notifier_call = hrtimer_cpu_notify,
2024 void __init hrtimers_init(void)
2026 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
2027 (void *)(long)smp_processor_id());
2028 register_cpu_notifier(&hrtimers_nb);
2029 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
2033 * schedule_hrtimeout_range_clock - sleep until timeout
2034 * @expires: timeout value (ktime_t)
2035 * @delta: slack in expires timeout (ktime_t)
2036 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2037 * @clock: timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
2040 schedule_hrtimeout_range_clock(ktime_t *expires, unsigned long delta,
2041 const enum hrtimer_mode mode, int clock)
2043 struct hrtimer_sleeper t;
2046 * Optimize when a zero timeout value is given. It does not
2047 * matter whether this is an absolute or a relative time.
2049 if (expires && !expires->tv64) {
2050 __set_current_state(TASK_RUNNING);
2055 * A NULL parameter means "infinite"
2062 hrtimer_init_on_stack(&t.timer, clock, mode);
2063 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
2065 hrtimer_init_sleeper(&t, current);
2067 hrtimer_start_expires(&t.timer, mode);
2068 if (!hrtimer_active(&t.timer))
2074 hrtimer_cancel(&t.timer);
2075 destroy_hrtimer_on_stack(&t.timer);
2077 __set_current_state(TASK_RUNNING);
2079 return !t.task ? 0 : -EINTR;
2083 * schedule_hrtimeout_range - sleep until timeout
2084 * @expires: timeout value (ktime_t)
2085 * @delta: slack in expires timeout (ktime_t)
2086 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2088 * Make the current task sleep until the given expiry time has
2089 * elapsed. The routine will return immediately unless
2090 * the current task state has been set (see set_current_state()).
2092 * The @delta argument gives the kernel the freedom to schedule the
2093 * actual wakeup to a time that is both power and performance friendly.
2094 * The kernel give the normal best effort behavior for "@expires+@delta",
2095 * but may decide to fire the timer earlier, but no earlier than @expires.
2097 * You can set the task state as follows -
2099 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2100 * pass before the routine returns.
2102 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2103 * delivered to the current task.
2105 * The current task state is guaranteed to be TASK_RUNNING when this
2108 * Returns 0 when the timer has expired otherwise -EINTR
2110 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
2111 const enum hrtimer_mode mode)
2113 return schedule_hrtimeout_range_clock(expires, delta, mode,
2116 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
2119 * schedule_hrtimeout - sleep until timeout
2120 * @expires: timeout value (ktime_t)
2121 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2123 * Make the current task sleep until the given expiry time has
2124 * elapsed. The routine will return immediately unless
2125 * the current task state has been set (see set_current_state()).
2127 * You can set the task state as follows -
2129 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2130 * pass before the routine returns.
2132 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2133 * delivered to the current task.
2135 * The current task state is guaranteed to be TASK_RUNNING when this
2138 * Returns 0 when the timer has expired otherwise -EINTR
2140 int __sched schedule_hrtimeout(ktime_t *expires,
2141 const enum hrtimer_mode mode)
2143 return schedule_hrtimeout_range(expires, 0, mode);
2145 EXPORT_SYMBOL_GPL(schedule_hrtimeout);