Luca's patch ported
[cbs-scheduler.git] / kernel / hrtimer.c
blob0585702b506366f6071801231c66e4393fb8839a
1 /*
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:
15 * - itimers
16 * - POSIX timers
17 * - nanosleep
18 * - precise in-kernel timing
20 * Started by: Thomas Gleixner and Ingo Molnar
22 * Credits:
23 * based on kernel/timer.c
25 * Help, testing, suggestions, bugfixes, improvements were
26 * provided by:
28 * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
29 * et. al.
31 * For licencing details see kernel-base/COPYING
34 #include <linux/cpu.h>
35 #include <linux/module.h>
36 #include <linux/percpu.h>
37 #include <linux/hrtimer.h>
38 #include <linux/notifier.h>
39 #include <linux/syscalls.h>
40 #include <linux/kallsyms.h>
41 #include <linux/interrupt.h>
42 #include <linux/tick.h>
43 #include <linux/seq_file.h>
44 #include <linux/err.h>
45 #include <linux/debugobjects.h>
47 #include <asm/uaccess.h>
49 /**
50 * ktime_get - get the monotonic time in ktime_t format
52 * returns the time in ktime_t format
54 ktime_t ktime_get(void)
56 struct timespec now;
58 ktime_get_ts(&now);
60 return timespec_to_ktime(now);
62 EXPORT_SYMBOL_GPL(ktime_get);
64 /**
65 * ktime_get_real - get the real (wall-) time in ktime_t format
67 * returns the time in ktime_t format
69 ktime_t ktime_get_real(void)
71 struct timespec now;
73 getnstimeofday(&now);
75 return timespec_to_ktime(now);
78 EXPORT_SYMBOL_GPL(ktime_get_real);
81 * The timer bases:
83 * Note: If we want to add new timer bases, we have to skip the two
84 * clock ids captured by the cpu-timers. We do this by holding empty
85 * entries rather than doing math adjustment of the clock ids.
86 * This ensures that we capture erroneous accesses to these clock ids
87 * rather than moving them into the range of valid clock id's.
89 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
92 .clock_base =
95 .index = CLOCK_REALTIME,
96 .get_time = &ktime_get_real,
97 .resolution = KTIME_LOW_RES,
100 .index = CLOCK_MONOTONIC,
101 .get_time = &ktime_get,
102 .resolution = KTIME_LOW_RES,
108 * ktime_get_ts - get the monotonic clock in timespec format
109 * @ts: pointer to timespec variable
111 * The function calculates the monotonic clock from the realtime
112 * clock and the wall_to_monotonic offset and stores the result
113 * in normalized timespec format in the variable pointed to by @ts.
115 void ktime_get_ts(struct timespec *ts)
117 struct timespec tomono;
118 unsigned long seq;
120 do {
121 seq = read_seqbegin(&xtime_lock);
122 getnstimeofday(ts);
123 tomono = wall_to_monotonic;
125 } while (read_seqretry(&xtime_lock, seq));
127 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
128 ts->tv_nsec + tomono.tv_nsec);
130 EXPORT_SYMBOL_GPL(ktime_get_ts);
133 * Get the coarse grained time at the softirq based on xtime and
134 * wall_to_monotonic.
136 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
138 ktime_t xtim, tomono;
139 struct timespec xts, tom;
140 unsigned long seq;
142 do {
143 seq = read_seqbegin(&xtime_lock);
144 xts = current_kernel_time();
145 tom = wall_to_monotonic;
146 } while (read_seqretry(&xtime_lock, seq));
148 xtim = timespec_to_ktime(xts);
149 tomono = timespec_to_ktime(tom);
150 base->clock_base[CLOCK_REALTIME].softirq_time = xtim;
151 base->clock_base[CLOCK_MONOTONIC].softirq_time =
152 ktime_add(xtim, tomono);
156 * Functions and macros which are different for UP/SMP systems are kept in a
157 * single place
159 #ifdef CONFIG_SMP
162 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
163 * means that all timers which are tied to this base via timer->base are
164 * locked, and the base itself is locked too.
166 * So __run_timers/migrate_timers can safely modify all timers which could
167 * be found on the lists/queues.
169 * When the timer's base is locked, and the timer removed from list, it is
170 * possible to set timer->base = NULL and drop the lock: the timer remains
171 * locked.
173 static
174 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
175 unsigned long *flags)
177 struct hrtimer_clock_base *base;
179 for (;;) {
180 base = timer->base;
181 if (likely(base != NULL)) {
182 spin_lock_irqsave(&base->cpu_base->lock, *flags);
183 if (likely(base == timer->base))
184 return base;
185 /* The timer has migrated to another CPU: */
186 spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
188 cpu_relax();
193 * Switch the timer base to the current CPU when possible.
195 static inline struct hrtimer_clock_base *
196 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base)
198 struct hrtimer_clock_base *new_base;
199 struct hrtimer_cpu_base *new_cpu_base;
201 new_cpu_base = &__get_cpu_var(hrtimer_bases);
202 new_base = &new_cpu_base->clock_base[base->index];
204 if (base != new_base) {
206 * We are trying to schedule the timer on the local CPU.
207 * However we can't change timer's base while it is running,
208 * so we keep it on the same CPU. No hassle vs. reprogramming
209 * the event source in the high resolution case. The softirq
210 * code will take care of this when the timer function has
211 * completed. There is no conflict as we hold the lock until
212 * the timer is enqueued.
214 if (unlikely(hrtimer_callback_running(timer)))
215 return base;
217 /* See the comment in lock_timer_base() */
218 timer->base = NULL;
219 spin_unlock(&base->cpu_base->lock);
220 spin_lock(&new_base->cpu_base->lock);
221 timer->base = new_base;
223 return new_base;
226 #else /* CONFIG_SMP */
228 static inline struct hrtimer_clock_base *
229 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
231 struct hrtimer_clock_base *base = timer->base;
233 spin_lock_irqsave(&base->cpu_base->lock, *flags);
235 return base;
238 # define switch_hrtimer_base(t, b) (b)
240 #endif /* !CONFIG_SMP */
243 * Functions for the union type storage format of ktime_t which are
244 * too large for inlining:
246 #if BITS_PER_LONG < 64
247 # ifndef CONFIG_KTIME_SCALAR
249 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
250 * @kt: addend
251 * @nsec: the scalar nsec value to add
253 * Returns the sum of kt and nsec in ktime_t format
255 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
257 ktime_t tmp;
259 if (likely(nsec < NSEC_PER_SEC)) {
260 tmp.tv64 = nsec;
261 } else {
262 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
264 tmp = ktime_set((long)nsec, rem);
267 return ktime_add(kt, tmp);
270 EXPORT_SYMBOL_GPL(ktime_add_ns);
273 * ktime_sub_ns - Subtract a scalar nanoseconds value from a ktime_t variable
274 * @kt: minuend
275 * @nsec: the scalar nsec value to subtract
277 * Returns the subtraction of @nsec from @kt in ktime_t format
279 ktime_t ktime_sub_ns(const ktime_t kt, u64 nsec)
281 ktime_t tmp;
283 if (likely(nsec < NSEC_PER_SEC)) {
284 tmp.tv64 = nsec;
285 } else {
286 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
288 tmp = ktime_set((long)nsec, rem);
291 return ktime_sub(kt, tmp);
294 EXPORT_SYMBOL_GPL(ktime_sub_ns);
295 # endif /* !CONFIG_KTIME_SCALAR */
298 * Divide a ktime value by a nanosecond value
300 u64 ktime_divns(const ktime_t kt, s64 div)
302 u64 dclc;
303 int sft = 0;
305 dclc = ktime_to_ns(kt);
306 /* Make sure the divisor is less than 2^32: */
307 while (div >> 32) {
308 sft++;
309 div >>= 1;
311 dclc >>= sft;
312 do_div(dclc, (unsigned long) div);
314 return dclc;
316 #endif /* BITS_PER_LONG >= 64 */
319 * Add two ktime values and do a safety check for overflow:
321 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
323 ktime_t res = ktime_add(lhs, rhs);
326 * We use KTIME_SEC_MAX here, the maximum timeout which we can
327 * return to user space in a timespec:
329 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
330 res = ktime_set(KTIME_SEC_MAX, 0);
332 return res;
335 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
337 static struct debug_obj_descr hrtimer_debug_descr;
340 * fixup_init is called when:
341 * - an active object is initialized
343 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
345 struct hrtimer *timer = addr;
347 switch (state) {
348 case ODEBUG_STATE_ACTIVE:
349 hrtimer_cancel(timer);
350 debug_object_init(timer, &hrtimer_debug_descr);
351 return 1;
352 default:
353 return 0;
358 * fixup_activate is called when:
359 * - an active object is activated
360 * - an unknown object is activated (might be a statically initialized object)
362 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
364 switch (state) {
366 case ODEBUG_STATE_NOTAVAILABLE:
367 WARN_ON_ONCE(1);
368 return 0;
370 case ODEBUG_STATE_ACTIVE:
371 WARN_ON(1);
373 default:
374 return 0;
379 * fixup_free is called when:
380 * - an active object is freed
382 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
384 struct hrtimer *timer = addr;
386 switch (state) {
387 case ODEBUG_STATE_ACTIVE:
388 hrtimer_cancel(timer);
389 debug_object_free(timer, &hrtimer_debug_descr);
390 return 1;
391 default:
392 return 0;
396 static struct debug_obj_descr hrtimer_debug_descr = {
397 .name = "hrtimer",
398 .fixup_init = hrtimer_fixup_init,
399 .fixup_activate = hrtimer_fixup_activate,
400 .fixup_free = hrtimer_fixup_free,
403 static inline void debug_hrtimer_init(struct hrtimer *timer)
405 debug_object_init(timer, &hrtimer_debug_descr);
408 static inline void debug_hrtimer_activate(struct hrtimer *timer)
410 debug_object_activate(timer, &hrtimer_debug_descr);
413 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
415 debug_object_deactivate(timer, &hrtimer_debug_descr);
418 static inline void debug_hrtimer_free(struct hrtimer *timer)
420 debug_object_free(timer, &hrtimer_debug_descr);
423 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
424 enum hrtimer_mode mode);
426 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
427 enum hrtimer_mode mode)
429 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
430 __hrtimer_init(timer, clock_id, mode);
433 void destroy_hrtimer_on_stack(struct hrtimer *timer)
435 debug_object_free(timer, &hrtimer_debug_descr);
438 #else
439 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
440 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
441 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
442 #endif
444 /* High resolution timer related functions */
445 #ifdef CONFIG_HIGH_RES_TIMERS
448 * High resolution timer enabled ?
450 static int hrtimer_hres_enabled __read_mostly = 1;
453 * Enable / Disable high resolution mode
455 static int __init setup_hrtimer_hres(char *str)
457 if (!strcmp(str, "off"))
458 hrtimer_hres_enabled = 0;
459 else if (!strcmp(str, "on"))
460 hrtimer_hres_enabled = 1;
461 else
462 return 0;
463 return 1;
466 __setup("highres=", setup_hrtimer_hres);
469 * hrtimer_high_res_enabled - query, if the highres mode is enabled
471 static inline int hrtimer_is_hres_enabled(void)
473 return hrtimer_hres_enabled;
477 * Is the high resolution mode active ?
479 static inline int hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base)
481 return cpu_base->hres_active;
485 * Reprogram the event source with checking both queues for the
486 * next event
487 * Called with interrupts disabled and base->lock held
489 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
491 int i;
492 struct hrtimer_clock_base *base = cpu_base->clock_base;
493 ktime_t expires;
495 cpu_base->expires_next.tv64 = KTIME_MAX;
497 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
498 struct hrtimer *timer;
500 if (!base->first)
501 continue;
502 timer = rb_entry(base->first, struct hrtimer, node);
503 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
505 * clock_was_set() has changed base->offset so the
506 * result might be negative. Fix it up to prevent a
507 * false positive in clockevents_program_event()
509 if (expires.tv64 < 0)
510 expires.tv64 = 0;
511 if (expires.tv64 < cpu_base->expires_next.tv64)
512 cpu_base->expires_next = expires;
515 if (cpu_base->expires_next.tv64 != KTIME_MAX)
516 tick_program_event(cpu_base->expires_next, 1);
520 * Shared reprogramming for clock_realtime and clock_monotonic
522 * When a timer is enqueued and expires earlier than the already enqueued
523 * timers, we have to check, whether it expires earlier than the timer for
524 * which the clock event device was armed.
526 * Called with interrupts disabled and base->cpu_base.lock held
528 static int hrtimer_reprogram(struct hrtimer *timer,
529 struct hrtimer_clock_base *base)
531 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
532 ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
533 int res;
535 WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
538 * When the callback is running, we do not reprogram the clock event
539 * device. The timer callback is either running on a different CPU or
540 * the callback is executed in the hrtimer_interrupt context. The
541 * reprogramming is handled at the end of the hrtimer_interrupt.
543 if (hrtimer_callback_running(timer))
544 return 0;
547 * CLOCK_REALTIME timer might be requested with an absolute
548 * expiry time which is less than base->offset. Nothing wrong
549 * about that, just avoid to call into the tick code, which
550 * has now objections against negative expiry values.
552 if (expires.tv64 < 0)
553 return -ETIME;
555 if (expires.tv64 >= expires_next->tv64)
556 return 0;
559 * Clockevents returns -ETIME, when the event was in the past.
561 res = tick_program_event(expires, 0);
562 if (!IS_ERR_VALUE(res))
563 *expires_next = expires;
564 return res;
569 * Retrigger next event is called after clock was set
571 * Called with interrupts disabled via on_each_cpu()
573 static void retrigger_next_event(void *arg)
575 struct hrtimer_cpu_base *base = &__get_cpu_var(hrtimer_bases);
577 struct timespec realtime_offset;
578 unsigned long seq;
580 if (!hrtimer_hres_active(base))
581 return;
583 do {
584 seq = read_seqbegin(&xtime_lock);
585 set_normalized_timespec(&realtime_offset,
586 -wall_to_monotonic.tv_sec,
587 -wall_to_monotonic.tv_nsec);
588 } while (read_seqretry(&xtime_lock, seq));
590 /* Adjust CLOCK_REALTIME offset */
591 spin_lock(&base->lock);
592 base->clock_base[CLOCK_REALTIME].offset =
593 timespec_to_ktime(realtime_offset);
595 hrtimer_force_reprogram(base);
596 spin_unlock(&base->lock);
600 * Clock realtime was set
602 * Change the offset of the realtime clock vs. the monotonic
603 * clock.
605 * We might have to reprogram the high resolution timer interrupt. On
606 * SMP we call the architecture specific code to retrigger _all_ high
607 * resolution timer interrupts. On UP we just disable interrupts and
608 * call the high resolution interrupt code.
610 void clock_was_set(void)
612 /* Retrigger the CPU local events everywhere */
613 on_each_cpu(retrigger_next_event, NULL, 1);
617 * During resume we might have to reprogram the high resolution timer
618 * interrupt (on the local CPU):
620 void hres_timers_resume(void)
622 WARN_ONCE(!irqs_disabled(),
623 KERN_INFO "hres_timers_resume() called with IRQs enabled!");
625 retrigger_next_event(NULL);
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;
638 * Initialize the high resolution related parts of a hrtimer
640 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
644 static void __run_hrtimer(struct hrtimer *timer);
645 static int hrtimer_rt_defer(struct hrtimer *timer);
648 * When High resolution timers are active, try to reprogram. Note, that in case
649 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
650 * check happens. The timer gets enqueued into the rbtree. The reprogramming
651 * and expiry check is done in the hrtimer_interrupt or in the softirq.
653 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
654 struct hrtimer_clock_base *base,
655 int wakeup)
657 #ifdef CONFIG_PREEMPT_RT
658 again:
659 #endif
660 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
661 #ifdef CONFIG_PREEMPT_RT
663 * Move softirq based timers away from the rbtree in
664 * case it expired already. Otherwise we would have a
665 * stale base->first entry until the softirq runs.
667 if (!hrtimer_rt_defer(timer)) {
668 __run_hrtimer(timer);
670 * __run_hrtimer might have requeued timer and
671 * it could be base->first again.
673 if (base->first == &timer->node)
674 goto again;
675 return 1;
677 #endif
678 if (wakeup) {
679 spin_unlock(&base->cpu_base->lock);
680 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
681 spin_lock(&base->cpu_base->lock);
682 } else
683 __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
685 return 1;
688 return 0;
692 * Switch to high resolution mode
694 static int hrtimer_switch_to_hres(struct hrtimer_cpu_base *base)
696 unsigned long flags;
698 if (base->hres_active)
699 return 1;
701 local_irq_save(flags);
703 if (tick_init_highres()) {
704 local_irq_restore(flags);
705 printk(KERN_WARNING "Could not switch to high resolution "
706 "mode on CPU %d\n", raw_smp_processor_id());
707 return 0;
709 base->hres_active = 1;
710 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
711 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
713 tick_setup_sched_timer();
715 /* "Retrigger" the interrupt to get things going */
716 retrigger_next_event(NULL);
717 local_irq_restore(flags);
718 return 1;
721 #else
723 static inline int hrtimer_hres_active(struct hrtimer_cpu_base *base)
725 return 0;
727 static inline int hrtimer_is_hres_enabled(void) { return 0; }
728 static inline int hrtimer_switch_to_hres(struct hrtimer_cpu_base *base)
730 return 0;
732 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
733 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
734 struct hrtimer_clock_base *base,
735 int wakeup)
737 return 0;
740 static inline int hrtimer_reprogram(struct hrtimer *timer,
741 struct hrtimer_clock_base *base)
743 return 0;
746 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
747 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
749 #endif /* CONFIG_HIGH_RES_TIMERS */
751 #ifdef CONFIG_TIMER_STATS
752 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
754 if (timer->start_site)
755 return;
757 timer->start_site = addr;
758 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
759 timer->start_pid = current->pid;
761 #endif
764 * Counterpart to lock_hrtimer_base above:
766 static inline
767 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
769 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
773 * hrtimer_forward - forward the timer expiry
774 * @timer: hrtimer to forward
775 * @now: forward past this time
776 * @interval: the interval to forward
778 * Forward the timer expiry so it will expire in the future.
779 * Returns the number of overruns.
781 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
783 u64 orun = 1;
784 ktime_t delta;
786 delta = ktime_sub(now, hrtimer_get_expires(timer));
788 if (delta.tv64 < 0)
789 return 0;
791 if (interval.tv64 < timer->base->resolution.tv64)
792 interval.tv64 = timer->base->resolution.tv64;
794 if (unlikely(delta.tv64 >= interval.tv64)) {
795 s64 incr = ktime_to_ns(interval);
797 orun = ktime_divns(delta, incr);
798 hrtimer_add_expires_ns(timer, incr * orun);
799 if (hrtimer_get_expires_tv64(timer) > now.tv64)
800 return orun;
802 * This (and the ktime_add() below) is the
803 * correction for exact:
805 orun++;
807 hrtimer_add_expires(timer, interval);
809 return orun;
811 EXPORT_SYMBOL_GPL(hrtimer_forward);
814 * enqueue_hrtimer - internal function to (re)start a timer
816 * The timer is inserted in expiry order. Insertion into the
817 * red black tree is O(log(n)). Must hold the base lock.
819 * Returns 1 when the new timer is the leftmost timer in the tree.
821 static int enqueue_hrtimer(struct hrtimer *timer,
822 struct hrtimer_clock_base *base)
824 struct rb_node **link = &base->active.rb_node;
825 struct rb_node *parent = NULL;
826 struct hrtimer *entry;
827 int leftmost = 1;
829 debug_hrtimer_activate(timer);
832 * Find the right place in the rbtree:
834 while (*link) {
835 parent = *link;
836 entry = rb_entry(parent, struct hrtimer, node);
838 * We dont care about collisions. Nodes with
839 * the same expiry time stay together.
841 if (hrtimer_get_expires_tv64(timer) <
842 hrtimer_get_expires_tv64(entry)) {
843 link = &(*link)->rb_left;
844 } else {
845 link = &(*link)->rb_right;
846 leftmost = 0;
851 * Insert the timer to the rbtree and check whether it
852 * replaces the first pending timer
854 if (leftmost)
855 base->first = &timer->node;
857 rb_link_node(&timer->node, parent, link);
858 rb_insert_color(&timer->node, &base->active);
860 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
861 * state of a possibly running callback.
863 timer->state |= HRTIMER_STATE_ENQUEUED;
865 return leftmost;
868 #ifdef CONFIG_PREEMPT_SOFTIRQS
869 # define wake_up_timer_waiters(b) wake_up(&(b)->wait)
872 * hrtimer_wait_for_timer - Wait for a running timer
874 * @timer: timer to wait for
876 * The function waits in case the timers callback function is
877 * currently executed on the waitqueue of the timer base. The
878 * waitqueue is woken up after the timer callback function has
879 * finished execution.
881 void hrtimer_wait_for_timer(const struct hrtimer *timer)
883 struct hrtimer_clock_base *base = timer->base;
885 if (base && base->cpu_base && !timer->irqsafe)
886 wait_event(base->cpu_base->wait,
887 !(timer->state & HRTIMER_STATE_CALLBACK));
890 #else
891 # define wake_up_timer_waiters(b) do { } while (0)
892 #endif
895 * __remove_hrtimer - internal function to remove a timer
897 * Caller must hold the base lock.
899 * High resolution timer mode reprograms the clock event device when the
900 * timer is the one which expires next. The caller can disable this by setting
901 * reprogram to zero. This is useful, when the context does a reprogramming
902 * anyway (e.g. timer interrupt)
904 static void __remove_hrtimer(struct hrtimer *timer,
905 struct hrtimer_clock_base *base,
906 unsigned long newstate, int reprogram)
908 if (timer->state & HRTIMER_STATE_ENQUEUED) {
910 if (unlikely(!list_empty(&timer->cb_entry))) {
911 list_del_init(&timer->cb_entry);
912 goto out;
915 * Remove the timer from the rbtree and replace the
916 * first entry pointer if necessary.
918 if (base->first == &timer->node) {
919 base->first = rb_next(&timer->node);
920 /* Reprogram the clock event device. if enabled */
921 if (reprogram && hrtimer_hres_active(base->cpu_base))
922 hrtimer_force_reprogram(base->cpu_base);
924 rb_erase(&timer->node, &base->active);
926 out:
927 timer->state = newstate;
931 * remove hrtimer, called with base lock held
933 static inline int
934 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
936 if (hrtimer_is_queued(timer)) {
937 int reprogram;
940 * Remove the timer and force reprogramming when high
941 * resolution mode is active and the timer is on the current
942 * CPU. If we remove a timer on another CPU, reprogramming is
943 * skipped. The interrupt event on this CPU is fired and
944 * reprogramming happens in the interrupt handler. This is a
945 * rare case and less expensive than a smp call.
947 debug_hrtimer_deactivate(timer);
948 timer_stats_hrtimer_clear_start_info(timer);
949 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
950 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
951 reprogram);
952 return 1;
954 return 0;
957 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
958 unsigned long delta_ns, const enum hrtimer_mode mode,
959 int wakeup)
961 struct hrtimer_clock_base *base, *new_base;
962 unsigned long flags;
963 int ret, leftmost;
965 base = lock_hrtimer_base(timer, &flags);
967 /* Remove an active timer from the queue: */
968 ret = remove_hrtimer(timer, base);
970 /* Switch the timer base, if necessary: */
971 new_base = switch_hrtimer_base(timer, base);
973 if (mode == HRTIMER_MODE_REL) {
974 tim = ktime_add_safe(tim, new_base->get_time());
976 * CONFIG_TIME_LOW_RES is a temporary way for architectures
977 * to signal that they simply return xtime in
978 * do_gettimeoffset(). In this case we want to round up by
979 * resolution when starting a relative timer, to avoid short
980 * timeouts. This will go away with the GTOD framework.
982 #ifdef CONFIG_TIME_LOW_RES
983 tim = ktime_add_safe(tim, base->resolution);
984 #endif
987 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
989 timer_stats_hrtimer_set_start_info(timer);
991 leftmost = enqueue_hrtimer(timer, new_base);
994 * Only allow reprogramming if the new base is on this CPU.
995 * (it might still be on another CPU if the timer was pending)
997 * XXX send_remote_softirq() ?
999 if (leftmost && new_base->cpu_base == &__get_cpu_var(hrtimer_bases))
1000 hrtimer_enqueue_reprogram(timer, new_base, wakeup);
1002 unlock_hrtimer_base(timer, &flags);
1004 return ret;
1008 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1009 * @timer: the timer to be added
1010 * @tim: expiry time
1011 * @delta_ns: "slack" range for the timer
1012 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1014 * Returns:
1015 * 0 on success
1016 * 1 when the timer was active
1018 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1019 unsigned long delta_ns, const enum hrtimer_mode mode)
1021 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1023 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1026 * hrtimer_start - (re)start an hrtimer on the current CPU
1027 * @timer: the timer to be added
1028 * @tim: expiry time
1029 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1031 * Returns:
1032 * 0 on success
1033 * 1 when the timer was active
1036 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1038 return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1040 EXPORT_SYMBOL_GPL(hrtimer_start);
1044 * hrtimer_try_to_cancel - try to deactivate a timer
1045 * @timer: hrtimer to stop
1047 * Returns:
1048 * 0 when the timer was not active
1049 * 1 when the timer was active
1050 * -1 when the timer is currently excuting the callback function and
1051 * cannot be stopped
1053 int hrtimer_try_to_cancel(struct hrtimer *timer)
1055 struct hrtimer_clock_base *base;
1056 unsigned long flags;
1057 int ret = -1;
1059 base = lock_hrtimer_base(timer, &flags);
1061 if (!hrtimer_callback_running(timer))
1062 ret = remove_hrtimer(timer, base);
1064 unlock_hrtimer_base(timer, &flags);
1066 return ret;
1069 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1072 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1073 * @timer: the timer to be cancelled
1075 * Returns:
1076 * 0 when the timer was not active
1077 * 1 when the timer was active
1079 int hrtimer_cancel(struct hrtimer *timer)
1081 for (;;) {
1082 int ret = hrtimer_try_to_cancel(timer);
1084 if (ret >= 0)
1085 return ret;
1086 hrtimer_wait_for_timer(timer);
1089 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1092 * hrtimer_get_remaining - get remaining time for the timer
1093 * @timer: the timer to read
1095 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1097 struct hrtimer_clock_base *base;
1098 unsigned long flags;
1099 ktime_t rem;
1101 base = lock_hrtimer_base(timer, &flags);
1102 rem = hrtimer_expires_remaining(timer);
1103 unlock_hrtimer_base(timer, &flags);
1105 return rem;
1107 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1109 #ifdef CONFIG_NO_HZ
1111 * hrtimer_get_next_event - get the time until next expiry event
1113 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1114 * is pending.
1116 ktime_t hrtimer_get_next_event(void)
1118 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1119 struct hrtimer_clock_base *base = cpu_base->clock_base;
1120 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1121 unsigned long flags;
1122 int i;
1124 spin_lock_irqsave(&cpu_base->lock, flags);
1126 if (!hrtimer_hres_active(cpu_base)) {
1127 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1128 struct hrtimer *timer;
1130 if (!base->first)
1131 continue;
1133 timer = rb_entry(base->first, struct hrtimer, node);
1134 delta.tv64 = hrtimer_get_expires_tv64(timer);
1135 delta = ktime_sub(delta, base->get_time());
1136 if (delta.tv64 < mindelta.tv64)
1137 mindelta.tv64 = delta.tv64;
1141 spin_unlock_irqrestore(&cpu_base->lock, flags);
1143 if (mindelta.tv64 < 0)
1144 mindelta.tv64 = 0;
1145 return mindelta;
1147 #endif
1149 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1150 enum hrtimer_mode mode)
1152 struct hrtimer_cpu_base *cpu_base;
1154 memset(timer, 0, sizeof(struct hrtimer));
1156 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1158 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1159 clock_id = CLOCK_MONOTONIC;
1161 timer->base = &cpu_base->clock_base[clock_id];
1162 INIT_LIST_HEAD(&timer->cb_entry);
1163 hrtimer_init_timer_hres(timer);
1165 #ifdef CONFIG_TIMER_STATS
1166 timer->start_site = NULL;
1167 timer->start_pid = -1;
1168 memset(timer->start_comm, 0, TASK_COMM_LEN);
1169 #endif
1173 * hrtimer_init - initialize a timer to the given clock
1174 * @timer: the timer to be initialized
1175 * @clock_id: the clock to be used
1176 * @mode: timer mode abs/rel
1178 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1179 enum hrtimer_mode mode)
1181 debug_hrtimer_init(timer);
1182 __hrtimer_init(timer, clock_id, mode);
1184 EXPORT_SYMBOL_GPL(hrtimer_init);
1187 * hrtimer_get_res - get the timer resolution for a clock
1188 * @which_clock: which clock to query
1189 * @tp: pointer to timespec variable to store the resolution
1191 * Store the resolution of the clock selected by @which_clock in the
1192 * variable pointed to by @tp.
1194 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1196 struct hrtimer_cpu_base *cpu_base;
1198 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1199 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1201 return 0;
1203 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1205 static void __run_hrtimer(struct hrtimer *timer)
1207 struct hrtimer_clock_base *base = timer->base;
1208 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1209 enum hrtimer_restart (*fn)(struct hrtimer *);
1210 int restart;
1212 WARN_ON(!irqs_disabled());
1214 debug_hrtimer_deactivate(timer);
1215 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1216 timer_stats_account_hrtimer(timer);
1217 fn = timer->function;
1220 * Because we run timers from hardirq context, there is no chance
1221 * they get migrated to another cpu, therefore its safe to unlock
1222 * the timer base.
1224 spin_unlock(&cpu_base->lock);
1225 restart = fn(timer);
1226 spin_lock(&cpu_base->lock);
1229 * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1230 * we do not reprogramm the event hardware. Happens either in
1231 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1233 if (restart != HRTIMER_NORESTART) {
1234 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1235 enqueue_hrtimer(timer, base);
1237 timer->state &= ~HRTIMER_STATE_CALLBACK;
1240 #ifdef CONFIG_PREEMPT_RT
1242 static void hrtimer_rt_reprogram(int restart, struct hrtimer *timer,
1243 struct hrtimer_clock_base *base)
1246 * Note, we clear the callback flag before we requeue the
1247 * timer otherwise we trigger the callback_running() check
1248 * in hrtimer_reprogram().
1250 timer->state &= ~HRTIMER_STATE_CALLBACK;
1252 if (restart != HRTIMER_NORESTART) {
1253 BUG_ON(hrtimer_active(timer));
1255 * Enqueue the timer, if it's the leftmost timer then
1256 * we need to reprogram it.
1258 if (!enqueue_hrtimer(timer, base))
1259 return;
1261 if (hrtimer_reprogram(timer, base))
1262 goto requeue;
1264 } else if (hrtimer_active(timer)) {
1266 * If the timer was rearmed on another CPU, reprogram
1267 * the event device.
1269 if (base->first == &timer->node &&
1270 hrtimer_reprogram(timer, base))
1271 goto requeue;
1273 return;
1275 requeue:
1277 * Timer is expired. Thus move it from tree to pending list
1278 * again.
1280 __remove_hrtimer(timer, base, timer->state, 0);
1281 list_add_tail(&timer->cb_entry, &base->expired);
1285 * The changes in mainline which removed the callback modes from
1286 * hrtimer are not yet working with -rt. The non wakeup_process()
1287 * based callbacks which involve sleeping locks need to be treated
1288 * seperately.
1290 static void hrtimer_rt_run_pending(void)
1292 enum hrtimer_restart (*fn)(struct hrtimer *);
1293 struct hrtimer_cpu_base *cpu_base;
1294 struct hrtimer_clock_base *base;
1295 struct hrtimer *timer;
1296 int index, restart;
1298 local_irq_disable();
1299 cpu_base = &per_cpu(hrtimer_bases, smp_processor_id());
1301 spin_lock(&cpu_base->lock);
1303 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1304 base = &cpu_base->clock_base[index];
1306 while (!list_empty(&base->expired)) {
1307 timer = list_first_entry(&base->expired,
1308 struct hrtimer, cb_entry);
1311 * Same as the above __run_hrtimer function
1312 * just we run with interrupts enabled.
1314 debug_hrtimer_deactivate(timer);
1315 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1316 timer_stats_account_hrtimer(timer);
1317 fn = timer->function;
1319 spin_unlock_irq(&cpu_base->lock);
1320 restart = fn(timer);
1321 spin_lock_irq(&cpu_base->lock);
1323 hrtimer_rt_reprogram(restart, timer, base);
1326 spin_unlock_irq(&cpu_base->lock);
1328 wake_up_timer_waiters(cpu_base);
1331 static int hrtimer_rt_defer(struct hrtimer *timer)
1333 if (timer->irqsafe)
1334 return 0;
1336 __remove_hrtimer(timer, timer->base, timer->state, 0);
1337 list_add_tail(&timer->cb_entry, &timer->base->expired);
1338 return 1;
1341 #else
1343 static inline void hrtimer_rt_run_pending(void) { }
1344 static inline int hrtimer_rt_defer(struct hrtimer *timer) { return 0; }
1346 #endif
1348 #ifdef CONFIG_HIGH_RES_TIMERS
1350 static int force_clock_reprogram;
1353 * After 5 iteration's attempts, we consider that hrtimer_interrupt()
1354 * is hanging, which could happen with something that slows the interrupt
1355 * such as the tracing. Then we force the clock reprogramming for each future
1356 * hrtimer interrupts to avoid infinite loops and use the min_delta_ns
1357 * threshold that we will overwrite.
1358 * The next tick event will be scheduled to 3 times we currently spend on
1359 * hrtimer_interrupt(). This gives a good compromise, the cpus will spend
1360 * 1/4 of their time to process the hrtimer interrupts. This is enough to
1361 * let it running without serious starvation.
1364 static inline void
1365 hrtimer_interrupt_hanging(struct clock_event_device *dev,
1366 ktime_t try_time)
1368 force_clock_reprogram = 1;
1369 dev->min_delta_ns = (unsigned long)try_time.tv64 * 3;
1370 printk(KERN_WARNING "hrtimer: interrupt too slow, "
1371 "forcing clock min delta to %lu ns\n", dev->min_delta_ns);
1374 * High resolution timer interrupt
1375 * Called with interrupts disabled
1377 void hrtimer_interrupt(struct clock_event_device *dev)
1379 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1380 struct hrtimer_clock_base *base;
1381 ktime_t expires_next, now;
1382 int nr_retries = 0;
1383 int i, raise = 0;
1385 BUG_ON(!cpu_base->hres_active);
1386 cpu_base->nr_events++;
1387 dev->next_event.tv64 = KTIME_MAX;
1389 retry:
1390 /* 5 retries is enough to notice a hang */
1391 if (!(++nr_retries % 5))
1392 hrtimer_interrupt_hanging(dev, ktime_sub(ktime_get(), now));
1394 now = ktime_get();
1396 expires_next.tv64 = KTIME_MAX;
1398 base = cpu_base->clock_base;
1400 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1401 ktime_t basenow;
1402 struct rb_node *node;
1404 spin_lock(&cpu_base->lock);
1406 basenow = ktime_add(now, base->offset);
1408 while ((node = base->first)) {
1409 struct hrtimer *timer;
1411 timer = rb_entry(node, struct hrtimer, node);
1414 * The immediate goal for using the softexpires is
1415 * minimizing wakeups, not running timers at the
1416 * earliest interrupt after their soft expiration.
1417 * This allows us to avoid using a Priority Search
1418 * Tree, which can answer a stabbing querry for
1419 * overlapping intervals and instead use the simple
1420 * BST we already have.
1421 * We don't add extra wakeups by delaying timers that
1422 * are right-of a not yet expired timer, because that
1423 * timer will have to trigger a wakeup anyway.
1426 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1427 ktime_t expires;
1429 expires = ktime_sub(hrtimer_get_expires(timer),
1430 base->offset);
1431 if (expires.tv64 < expires_next.tv64)
1432 expires_next = expires;
1433 break;
1436 if (!hrtimer_rt_defer(timer))
1437 __run_hrtimer(timer);
1438 else
1439 raise = 1;
1441 spin_unlock(&cpu_base->lock);
1442 base++;
1445 cpu_base->expires_next = expires_next;
1447 /* Reprogramming necessary ? */
1448 if (expires_next.tv64 != KTIME_MAX) {
1449 if (tick_program_event(expires_next, force_clock_reprogram))
1450 goto retry;
1453 if (raise)
1454 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1458 * local version of hrtimer_peek_ahead_timers() called with interrupts
1459 * disabled.
1461 static void __hrtimer_peek_ahead_timers(void)
1463 struct hrtimer_cpu_base *cpu_base;
1464 struct tick_device *td;
1466 cpu_base = &__get_cpu_var(hrtimer_bases);
1467 if (!hrtimer_hres_active(cpu_base))
1468 return;
1470 td = &__get_cpu_var(tick_cpu_device);
1471 if (td && td->evtdev)
1472 hrtimer_interrupt(td->evtdev);
1476 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1478 * hrtimer_peek_ahead_timers will peek at the timer queue of
1479 * the current cpu and check if there are any timers for which
1480 * the soft expires time has passed. If any such timers exist,
1481 * they are run immediately and then removed from the timer queue.
1484 void hrtimer_peek_ahead_timers(void)
1486 unsigned long flags;
1488 local_irq_save(flags);
1489 __hrtimer_peek_ahead_timers();
1490 local_irq_restore(flags);
1493 #else /* CONFIG_HIGH_RES_TIMERS */
1495 static inline void __hrtimer_peek_ahead_timers(void) { }
1497 #endif /* !CONFIG_HIGH_RES_TIMERS */
1499 static void run_hrtimer_softirq(struct softirq_action *h)
1501 hrtimer_rt_run_pending();
1505 * Called from timer softirq every jiffy, expire hrtimers:
1507 * For HRT its the fall back code to run the softirq in the timer
1508 * softirq context in case the hrtimer initialization failed or has
1509 * not been done yet.
1511 void hrtimer_run_pending(void)
1513 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1515 if (hrtimer_hres_active(cpu_base))
1516 return;
1519 * This _is_ ugly: We have to check in the softirq context,
1520 * whether we can switch to highres and / or nohz mode. The
1521 * clocksource switch happens in the timer interrupt with
1522 * xtime_lock held. Notification from there only sets the
1523 * check bit in the tick_oneshot code, otherwise we might
1524 * deadlock vs. xtime_lock.
1526 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1527 hrtimer_switch_to_hres(cpu_base);
1531 * Called from hardirq context every jiffy
1533 void hrtimer_run_queues(void)
1535 struct rb_node *node;
1536 struct hrtimer_cpu_base *cpu_base;
1537 struct hrtimer_clock_base *base;
1538 int index, gettime = 1, raise = 0;
1540 cpu_base = &per_cpu(hrtimer_bases, raw_smp_processor_id());
1541 if (hrtimer_hres_active(cpu_base))
1542 return;
1544 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1545 base = &cpu_base->clock_base[index];
1547 if (!base->first)
1548 continue;
1550 if (gettime) {
1551 hrtimer_get_softirq_time(cpu_base);
1552 gettime = 0;
1555 spin_lock(&cpu_base->lock);
1557 while ((node = base->first)) {
1558 struct hrtimer *timer;
1560 timer = rb_entry(node, struct hrtimer, node);
1561 if (base->softirq_time.tv64 <=
1562 hrtimer_get_expires_tv64(timer))
1563 break;
1565 if (!hrtimer_rt_defer(timer))
1566 __run_hrtimer(timer);
1567 else
1568 raise = 1;
1570 spin_unlock(&cpu_base->lock);
1573 if (raise)
1574 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1578 * Sleep related functions:
1580 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1582 struct hrtimer_sleeper *t =
1583 container_of(timer, struct hrtimer_sleeper, timer);
1584 struct task_struct *task = t->task;
1586 t->task = NULL;
1587 if (task)
1588 wake_up_process(task);
1590 return HRTIMER_NORESTART;
1593 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1595 sl->timer.function = hrtimer_wakeup;
1596 sl->timer.irqsafe = 1;
1597 sl->task = task;
1600 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1602 hrtimer_init_sleeper(t, current);
1604 do {
1605 set_current_state(TASK_INTERRUPTIBLE);
1606 hrtimer_start_expires(&t->timer, mode);
1607 if (!hrtimer_active(&t->timer))
1608 t->task = NULL;
1610 if (likely(t->task))
1611 schedule();
1613 hrtimer_cancel(&t->timer);
1614 mode = HRTIMER_MODE_ABS;
1616 } while (t->task && !signal_pending(current));
1618 __set_current_state(TASK_RUNNING);
1620 return t->task == NULL;
1623 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1625 struct timespec rmt;
1626 ktime_t rem;
1628 rem = hrtimer_expires_remaining(timer);
1629 if (rem.tv64 <= 0)
1630 return 0;
1631 rmt = ktime_to_timespec(rem);
1633 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1634 return -EFAULT;
1636 return 1;
1639 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1641 struct hrtimer_sleeper t;
1642 struct timespec __user *rmtp;
1643 int ret = 0;
1645 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1646 HRTIMER_MODE_ABS);
1647 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1649 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1650 goto out;
1652 rmtp = restart->nanosleep.rmtp;
1653 if (rmtp) {
1654 ret = update_rmtp(&t.timer, rmtp);
1655 if (ret <= 0)
1656 goto out;
1659 /* The other values in restart are already filled in */
1660 ret = -ERESTART_RESTARTBLOCK;
1661 out:
1662 destroy_hrtimer_on_stack(&t.timer);
1663 return ret;
1666 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1667 const enum hrtimer_mode mode, const clockid_t clockid)
1669 struct restart_block *restart;
1670 struct hrtimer_sleeper t;
1671 int ret = 0;
1672 unsigned long slack;
1674 slack = current->timer_slack_ns;
1675 if (rt_task(current))
1676 slack = 0;
1678 hrtimer_init_on_stack(&t.timer, clockid, mode);
1679 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1680 if (do_nanosleep(&t, mode))
1681 goto out;
1683 /* Absolute timers do not update the rmtp value and restart: */
1684 if (mode == HRTIMER_MODE_ABS) {
1685 ret = -ERESTARTNOHAND;
1686 goto out;
1689 if (rmtp) {
1690 ret = update_rmtp(&t.timer, rmtp);
1691 if (ret <= 0)
1692 goto out;
1695 restart = &current_thread_info()->restart_block;
1696 restart->fn = hrtimer_nanosleep_restart;
1697 restart->nanosleep.index = t.timer.base->index;
1698 restart->nanosleep.rmtp = rmtp;
1699 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1701 ret = -ERESTART_RESTARTBLOCK;
1702 out:
1703 destroy_hrtimer_on_stack(&t.timer);
1704 return ret;
1707 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1708 struct timespec __user *, rmtp)
1710 struct timespec tu;
1712 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1713 return -EFAULT;
1715 if (!timespec_valid(&tu))
1716 return -EINVAL;
1718 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1722 * Functions related to boot-time initialization:
1724 static void __cpuinit init_hrtimers_cpu(int cpu)
1726 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1727 int i;
1729 spin_lock_init(&cpu_base->lock);
1731 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1732 cpu_base->clock_base[i].cpu_base = cpu_base;
1733 INIT_LIST_HEAD(&cpu_base->clock_base[i].expired);
1736 hrtimer_init_hres(cpu_base);
1737 #ifdef CONFIG_PREEMPT_RT
1738 init_waitqueue_head(&cpu_base->wait);
1739 #endif
1742 #ifdef CONFIG_HOTPLUG_CPU
1744 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1745 struct hrtimer_clock_base *new_base)
1747 struct hrtimer *timer;
1748 struct rb_node *node;
1750 while ((node = rb_first(&old_base->active))) {
1751 timer = rb_entry(node, struct hrtimer, node);
1752 BUG_ON(hrtimer_callback_running(timer));
1753 debug_hrtimer_deactivate(timer);
1756 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1757 * timer could be seen as !active and just vanish away
1758 * under us on another CPU
1760 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1761 timer->base = new_base;
1763 * Enqueue the timers on the new cpu. This does not
1764 * reprogram the event device in case the timer
1765 * expires before the earliest on this CPU, but we run
1766 * hrtimer_interrupt after we migrated everything to
1767 * sort out already expired timers and reprogram the
1768 * event device.
1770 enqueue_hrtimer(timer, new_base);
1772 /* Clear the migration state bit */
1773 timer->state &= ~HRTIMER_STATE_MIGRATE;
1777 static void migrate_hrtimers(int scpu)
1779 struct hrtimer_cpu_base *old_base, *new_base;
1780 int i;
1782 BUG_ON(cpu_online(scpu));
1783 tick_cancel_sched_timer(scpu);
1785 local_irq_disable();
1786 old_base = &per_cpu(hrtimer_bases, scpu);
1787 new_base = &__get_cpu_var(hrtimer_bases);
1789 * The caller is globally serialized and nobody else
1790 * takes two locks at once, deadlock is not possible.
1792 spin_lock(&new_base->lock);
1793 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1795 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1796 migrate_hrtimer_list(&old_base->clock_base[i],
1797 &new_base->clock_base[i]);
1800 spin_unlock(&old_base->lock);
1801 spin_unlock(&new_base->lock);
1803 /* Check, if we got expired work to do */
1804 __hrtimer_peek_ahead_timers();
1805 local_irq_enable();
1808 #endif /* CONFIG_HOTPLUG_CPU */
1810 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1811 unsigned long action, void *hcpu)
1813 int scpu = (long)hcpu;
1815 switch (action) {
1817 case CPU_UP_PREPARE:
1818 case CPU_UP_PREPARE_FROZEN:
1819 init_hrtimers_cpu(scpu);
1820 break;
1822 #ifdef CONFIG_HOTPLUG_CPU
1823 case CPU_DYING:
1824 case CPU_DYING_FROZEN:
1825 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1826 break;
1827 case CPU_DEAD:
1828 case CPU_DEAD_FROZEN:
1830 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1831 migrate_hrtimers(scpu);
1832 break;
1834 #endif
1836 default:
1837 break;
1840 return NOTIFY_OK;
1843 static struct notifier_block __cpuinitdata hrtimers_nb = {
1844 .notifier_call = hrtimer_cpu_notify,
1847 void __init hrtimers_init(void)
1849 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1850 (void *)(long)smp_processor_id());
1851 register_cpu_notifier(&hrtimers_nb);
1852 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1856 * schedule_hrtimeout_range - sleep until timeout
1857 * @expires: timeout value (ktime_t)
1858 * @delta: slack in expires timeout (ktime_t)
1859 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1861 * Make the current task sleep until the given expiry time has
1862 * elapsed. The routine will return immediately unless
1863 * the current task state has been set (see set_current_state()).
1865 * The @delta argument gives the kernel the freedom to schedule the
1866 * actual wakeup to a time that is both power and performance friendly.
1867 * The kernel give the normal best effort behavior for "@expires+@delta",
1868 * but may decide to fire the timer earlier, but no earlier than @expires.
1870 * You can set the task state as follows -
1872 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1873 * pass before the routine returns.
1875 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1876 * delivered to the current task.
1878 * The current task state is guaranteed to be TASK_RUNNING when this
1879 * routine returns.
1881 * Returns 0 when the timer has expired otherwise -EINTR
1883 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1884 const enum hrtimer_mode mode)
1886 struct hrtimer_sleeper t;
1889 * Optimize when a zero timeout value is given. It does not
1890 * matter whether this is an absolute or a relative time.
1892 if (expires && !expires->tv64) {
1893 __set_current_state(TASK_RUNNING);
1894 return 0;
1898 * A NULL parameter means "inifinte"
1900 if (!expires) {
1901 schedule();
1902 __set_current_state(TASK_RUNNING);
1903 return -EINTR;
1906 hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
1907 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1909 hrtimer_init_sleeper(&t, current);
1911 hrtimer_start_expires(&t.timer, mode);
1912 if (!hrtimer_active(&t.timer))
1913 t.task = NULL;
1915 if (likely(t.task))
1916 schedule();
1918 hrtimer_cancel(&t.timer);
1919 destroy_hrtimer_on_stack(&t.timer);
1921 __set_current_state(TASK_RUNNING);
1923 return !t.task ? 0 : -EINTR;
1925 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1928 * schedule_hrtimeout - sleep until timeout
1929 * @expires: timeout value (ktime_t)
1930 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1932 * Make the current task sleep until the given expiry time has
1933 * elapsed. The routine will return immediately unless
1934 * the current task state has been set (see set_current_state()).
1936 * You can set the task state as follows -
1938 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1939 * pass before the routine returns.
1941 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1942 * delivered to the current task.
1944 * The current task state is guaranteed to be TASK_RUNNING when this
1945 * routine returns.
1947 * Returns 0 when the timer has expired otherwise -EINTR
1949 int __sched schedule_hrtimeout(ktime_t *expires,
1950 const enum hrtimer_mode mode)
1952 return schedule_hrtimeout_range(expires, 0, mode);
1954 EXPORT_SYMBOL_GPL(schedule_hrtimeout);