gcc-4.1.0 is bust
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / hrtimer.c
bloba29ceb04c257ee9b2e47a038ea553b85f5ef47d2
1 /*
2 * linux/kernel/hrtimer.c
4 * Copyright(C) 2005, Thomas Gleixner <tglx@linutronix.de>
5 * Copyright(C) 2005, Red Hat, Inc., Ingo Molnar
7 * High-resolution kernel timers
9 * In contrast to the low-resolution timeout API implemented in
10 * kernel/timer.c, hrtimers provide finer resolution and accuracy
11 * depending on system configuration and capabilities.
13 * These timers are currently used for:
14 * - itimers
15 * - POSIX timers
16 * - nanosleep
17 * - precise in-kernel timing
19 * Started by: Thomas Gleixner and Ingo Molnar
21 * Credits:
22 * based on kernel/timer.c
24 * Help, testing, suggestions, bugfixes, improvements were
25 * provided by:
27 * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
28 * et. al.
30 * For licencing details see kernel-base/COPYING
33 #include <linux/cpu.h>
34 #include <linux/module.h>
35 #include <linux/percpu.h>
36 #include <linux/hrtimer.h>
37 #include <linux/notifier.h>
38 #include <linux/syscalls.h>
39 #include <linux/interrupt.h>
41 #include <asm/uaccess.h>
43 /**
44 * ktime_get - get the monotonic time in ktime_t format
46 * returns the time in ktime_t format
48 static ktime_t ktime_get(void)
50 struct timespec now;
52 ktime_get_ts(&now);
54 return timespec_to_ktime(now);
57 /**
58 * ktime_get_real - get the real (wall-) time in ktime_t format
60 * returns the time in ktime_t format
62 static ktime_t ktime_get_real(void)
64 struct timespec now;
66 getnstimeofday(&now);
68 return timespec_to_ktime(now);
71 EXPORT_SYMBOL_GPL(ktime_get_real);
74 * The timer bases:
76 * Note: If we want to add new timer bases, we have to skip the two
77 * clock ids captured by the cpu-timers. We do this by holding empty
78 * entries rather than doing math adjustment of the clock ids.
79 * This ensures that we capture erroneous accesses to these clock ids
80 * rather than moving them into the range of valid clock id's.
83 #define MAX_HRTIMER_BASES 2
85 static DEFINE_PER_CPU(struct hrtimer_base, hrtimer_bases[MAX_HRTIMER_BASES]) =
88 .index = CLOCK_REALTIME,
89 .get_time = &ktime_get_real,
90 .resolution = KTIME_REALTIME_RES,
93 .index = CLOCK_MONOTONIC,
94 .get_time = &ktime_get,
95 .resolution = KTIME_MONOTONIC_RES,
99 /**
100 * ktime_get_ts - get the monotonic clock in timespec format
102 * @ts: pointer to timespec variable
104 * The function calculates the monotonic clock from the realtime
105 * clock and the wall_to_monotonic offset and stores the result
106 * in normalized timespec format in the variable pointed to by ts.
108 void ktime_get_ts(struct timespec *ts)
110 struct timespec tomono;
111 unsigned long seq;
113 do {
114 seq = read_seqbegin(&xtime_lock);
115 getnstimeofday(ts);
116 tomono = wall_to_monotonic;
118 } while (read_seqretry(&xtime_lock, seq));
120 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
121 ts->tv_nsec + tomono.tv_nsec);
123 EXPORT_SYMBOL_GPL(ktime_get_ts);
126 * Functions and macros which are different for UP/SMP systems are kept in a
127 * single place
129 #ifdef CONFIG_SMP
131 #define set_curr_timer(b, t) do { (b)->curr_timer = (t); } while (0)
134 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
135 * means that all timers which are tied to this base via timer->base are
136 * locked, and the base itself is locked too.
138 * So __run_timers/migrate_timers can safely modify all timers which could
139 * be found on the lists/queues.
141 * When the timer's base is locked, and the timer removed from list, it is
142 * possible to set timer->base = NULL and drop the lock: the timer remains
143 * locked.
145 static struct hrtimer_base *lock_hrtimer_base(const struct hrtimer *timer,
146 unsigned long *flags)
148 struct hrtimer_base *base;
150 for (;;) {
151 base = timer->base;
152 if (likely(base != NULL)) {
153 spin_lock_irqsave(&base->lock, *flags);
154 if (likely(base == timer->base))
155 return base;
156 /* The timer has migrated to another CPU: */
157 spin_unlock_irqrestore(&base->lock, *flags);
159 cpu_relax();
164 * Switch the timer base to the current CPU when possible.
166 static inline struct hrtimer_base *
167 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_base *base)
169 struct hrtimer_base *new_base;
171 new_base = &__get_cpu_var(hrtimer_bases[base->index]);
173 if (base != new_base) {
175 * We are trying to schedule the timer on the local CPU.
176 * However we can't change timer's base while it is running,
177 * so we keep it on the same CPU. No hassle vs. reprogramming
178 * the event source in the high resolution case. The softirq
179 * code will take care of this when the timer function has
180 * completed. There is no conflict as we hold the lock until
181 * the timer is enqueued.
183 if (unlikely(base->curr_timer == timer))
184 return base;
186 /* See the comment in lock_timer_base() */
187 timer->base = NULL;
188 spin_unlock(&base->lock);
189 spin_lock(&new_base->lock);
190 timer->base = new_base;
192 return new_base;
195 #else /* CONFIG_SMP */
197 #define set_curr_timer(b, t) do { } while (0)
199 static inline struct hrtimer_base *
200 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
202 struct hrtimer_base *base = timer->base;
204 spin_lock_irqsave(&base->lock, *flags);
206 return base;
209 #define switch_hrtimer_base(t, b) (b)
211 #endif /* !CONFIG_SMP */
214 * Functions for the union type storage format of ktime_t which are
215 * too large for inlining:
217 #if BITS_PER_LONG < 64
218 # ifndef CONFIG_KTIME_SCALAR
220 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
222 * @kt: addend
223 * @nsec: the scalar nsec value to add
225 * Returns the sum of kt and nsec in ktime_t format
227 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
229 ktime_t tmp;
231 if (likely(nsec < NSEC_PER_SEC)) {
232 tmp.tv64 = nsec;
233 } else {
234 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
236 tmp = ktime_set((long)nsec, rem);
239 return ktime_add(kt, tmp);
242 #else /* CONFIG_KTIME_SCALAR */
244 # endif /* !CONFIG_KTIME_SCALAR */
247 * Divide a ktime value by a nanosecond value
249 static unsigned long ktime_divns(const ktime_t kt, nsec_t div)
251 u64 dclc, inc, dns;
252 int sft = 0;
254 dclc = dns = ktime_to_ns(kt);
255 inc = div;
256 /* Make sure the divisor is less than 2^32: */
257 while (div >> 32) {
258 sft++;
259 div >>= 1;
261 dclc >>= sft;
262 do_div(dclc, (unsigned long) div);
264 return (unsigned long) dclc;
267 #else /* BITS_PER_LONG < 64 */
268 # define ktime_divns(kt, div) (unsigned long)((kt).tv64 / (div))
269 #endif /* BITS_PER_LONG >= 64 */
272 * Counterpart to lock_timer_base above:
274 static inline
275 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
277 spin_unlock_irqrestore(&timer->base->lock, *flags);
281 * hrtimer_forward - forward the timer expiry
283 * @timer: hrtimer to forward
284 * @interval: the interval to forward
286 * Forward the timer expiry so it will expire in the future.
287 * Returns the number of overruns.
289 unsigned long
290 hrtimer_forward(struct hrtimer *timer, ktime_t interval)
292 unsigned long orun = 1;
293 ktime_t delta, now;
295 now = timer->base->get_time();
297 delta = ktime_sub(now, timer->expires);
299 if (delta.tv64 < 0)
300 return 0;
302 if (interval.tv64 < timer->base->resolution.tv64)
303 interval.tv64 = timer->base->resolution.tv64;
305 if (unlikely(delta.tv64 >= interval.tv64)) {
306 nsec_t incr = ktime_to_ns(interval);
308 orun = ktime_divns(delta, incr);
309 timer->expires = ktime_add_ns(timer->expires, incr * orun);
310 if (timer->expires.tv64 > now.tv64)
311 return orun;
313 * This (and the ktime_add() below) is the
314 * correction for exact:
316 orun++;
318 timer->expires = ktime_add(timer->expires, interval);
320 * Make sure, that the result did not wrap with a very large
321 * interval.
323 if (timer->expires.tv64 < 0)
324 timer->expires = ktime_set(KTIME_SEC_MAX, 0);
326 return orun;
330 * enqueue_hrtimer - internal function to (re)start a timer
332 * The timer is inserted in expiry order. Insertion into the
333 * red black tree is O(log(n)). Must hold the base lock.
335 static void enqueue_hrtimer(struct hrtimer *timer, struct hrtimer_base *base)
337 struct rb_node **link = &base->active.rb_node;
338 struct rb_node *parent = NULL;
339 struct hrtimer *entry;
342 * Find the right place in the rbtree:
344 while (*link) {
345 parent = *link;
346 entry = rb_entry(parent, struct hrtimer, node);
348 * We dont care about collisions. Nodes with
349 * the same expiry time stay together.
351 if (timer->expires.tv64 < entry->expires.tv64)
352 link = &(*link)->rb_left;
353 else
354 link = &(*link)->rb_right;
358 * Insert the timer to the rbtree and check whether it
359 * replaces the first pending timer
361 rb_link_node(&timer->node, parent, link);
362 rb_insert_color(&timer->node, &base->active);
364 timer->state = HRTIMER_PENDING;
366 if (!base->first || timer->expires.tv64 <
367 rb_entry(base->first, struct hrtimer, node)->expires.tv64)
368 base->first = &timer->node;
372 * __remove_hrtimer - internal function to remove a timer
374 * Caller must hold the base lock.
376 static void __remove_hrtimer(struct hrtimer *timer, struct hrtimer_base *base)
379 * Remove the timer from the rbtree and replace the
380 * first entry pointer if necessary.
382 if (base->first == &timer->node)
383 base->first = rb_next(&timer->node);
384 rb_erase(&timer->node, &base->active);
388 * remove hrtimer, called with base lock held
390 static inline int
391 remove_hrtimer(struct hrtimer *timer, struct hrtimer_base *base)
393 if (hrtimer_active(timer)) {
394 __remove_hrtimer(timer, base);
395 timer->state = HRTIMER_INACTIVE;
396 return 1;
398 return 0;
402 * hrtimer_start - (re)start an relative timer on the current CPU
404 * @timer: the timer to be added
405 * @tim: expiry time
406 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
408 * Returns:
409 * 0 on success
410 * 1 when the timer was active
413 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
415 struct hrtimer_base *base, *new_base;
416 unsigned long flags;
417 int ret;
419 base = lock_hrtimer_base(timer, &flags);
421 /* Remove an active timer from the queue: */
422 ret = remove_hrtimer(timer, base);
424 /* Switch the timer base, if necessary: */
425 new_base = switch_hrtimer_base(timer, base);
427 if (mode == HRTIMER_REL) {
428 tim = ktime_add(tim, new_base->get_time());
430 * CONFIG_TIME_LOW_RES is a temporary way for architectures
431 * to signal that they simply return xtime in
432 * do_gettimeoffset(). In this case we want to round up by
433 * resolution when starting a relative timer, to avoid short
434 * timeouts. This will go away with the GTOD framework.
436 #ifdef CONFIG_TIME_LOW_RES
437 tim = ktime_add(tim, base->resolution);
438 #endif
440 timer->expires = tim;
442 enqueue_hrtimer(timer, new_base);
444 unlock_hrtimer_base(timer, &flags);
446 return ret;
450 * hrtimer_try_to_cancel - try to deactivate a timer
452 * @timer: hrtimer to stop
454 * Returns:
455 * 0 when the timer was not active
456 * 1 when the timer was active
457 * -1 when the timer is currently excuting the callback function and
458 * can not be stopped
460 int hrtimer_try_to_cancel(struct hrtimer *timer)
462 struct hrtimer_base *base;
463 unsigned long flags;
464 int ret = -1;
466 base = lock_hrtimer_base(timer, &flags);
468 if (base->curr_timer != timer)
469 ret = remove_hrtimer(timer, base);
471 unlock_hrtimer_base(timer, &flags);
473 return ret;
478 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
480 * @timer: the timer to be cancelled
482 * Returns:
483 * 0 when the timer was not active
484 * 1 when the timer was active
486 int hrtimer_cancel(struct hrtimer *timer)
488 for (;;) {
489 int ret = hrtimer_try_to_cancel(timer);
491 if (ret >= 0)
492 return ret;
497 * hrtimer_get_remaining - get remaining time for the timer
499 * @timer: the timer to read
501 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
503 struct hrtimer_base *base;
504 unsigned long flags;
505 ktime_t rem;
507 base = lock_hrtimer_base(timer, &flags);
508 rem = ktime_sub(timer->expires, timer->base->get_time());
509 unlock_hrtimer_base(timer, &flags);
511 return rem;
514 #ifdef CONFIG_NO_IDLE_HZ
516 * hrtimer_get_next_event - get the time until next expiry event
518 * Returns the delta to the next expiry event or KTIME_MAX if no timer
519 * is pending.
521 ktime_t hrtimer_get_next_event(void)
523 struct hrtimer_base *base = __get_cpu_var(hrtimer_bases);
524 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
525 unsigned long flags;
526 int i;
528 for (i = 0; i < MAX_HRTIMER_BASES; i++, base++) {
529 struct hrtimer *timer;
531 spin_lock_irqsave(&base->lock, flags);
532 if (!base->first) {
533 spin_unlock_irqrestore(&base->lock, flags);
534 continue;
536 timer = rb_entry(base->first, struct hrtimer, node);
537 delta.tv64 = timer->expires.tv64;
538 spin_unlock_irqrestore(&base->lock, flags);
539 delta = ktime_sub(delta, base->get_time());
540 if (delta.tv64 < mindelta.tv64)
541 mindelta.tv64 = delta.tv64;
543 if (mindelta.tv64 < 0)
544 mindelta.tv64 = 0;
545 return mindelta;
547 #endif
550 * hrtimer_init - initialize a timer to the given clock
552 * @timer: the timer to be initialized
553 * @clock_id: the clock to be used
554 * @mode: timer mode abs/rel
556 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
557 enum hrtimer_mode mode)
559 struct hrtimer_base *bases;
561 memset(timer, 0, sizeof(struct hrtimer));
563 bases = per_cpu(hrtimer_bases, raw_smp_processor_id());
565 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_ABS)
566 clock_id = CLOCK_MONOTONIC;
568 timer->base = &bases[clock_id];
572 * hrtimer_get_res - get the timer resolution for a clock
574 * @which_clock: which clock to query
575 * @tp: pointer to timespec variable to store the resolution
577 * Store the resolution of the clock selected by which_clock in the
578 * variable pointed to by tp.
580 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
582 struct hrtimer_base *bases;
584 bases = per_cpu(hrtimer_bases, raw_smp_processor_id());
585 *tp = ktime_to_timespec(bases[which_clock].resolution);
587 return 0;
591 * Expire the per base hrtimer-queue:
593 static inline void run_hrtimer_queue(struct hrtimer_base *base)
595 ktime_t now = base->get_time();
596 struct rb_node *node;
598 spin_lock_irq(&base->lock);
600 while ((node = base->first)) {
601 struct hrtimer *timer;
602 int (*fn)(void *);
603 int restart;
604 void *data;
606 timer = rb_entry(node, struct hrtimer, node);
607 if (now.tv64 <= timer->expires.tv64)
608 break;
610 fn = timer->function;
611 data = timer->data;
612 set_curr_timer(base, timer);
613 timer->state = HRTIMER_RUNNING;
614 __remove_hrtimer(timer, base);
615 spin_unlock_irq(&base->lock);
618 * fn == NULL is special case for the simplest timer
619 * variant - wake up process and do not restart:
621 if (!fn) {
622 wake_up_process(data);
623 restart = HRTIMER_NORESTART;
624 } else
625 restart = fn(data);
627 spin_lock_irq(&base->lock);
629 /* Another CPU has added back the timer */
630 if (timer->state != HRTIMER_RUNNING)
631 continue;
633 if (restart == HRTIMER_RESTART)
634 enqueue_hrtimer(timer, base);
635 else
636 timer->state = HRTIMER_EXPIRED;
638 set_curr_timer(base, NULL);
639 spin_unlock_irq(&base->lock);
643 * Called from timer softirq every jiffy, expire hrtimers:
645 void hrtimer_run_queues(void)
647 struct hrtimer_base *base = __get_cpu_var(hrtimer_bases);
648 int i;
650 for (i = 0; i < MAX_HRTIMER_BASES; i++)
651 run_hrtimer_queue(&base[i]);
655 * Sleep related functions:
659 * schedule_hrtimer - sleep until timeout
661 * @timer: hrtimer variable initialized with the correct clock base
662 * @mode: timeout value is abs/rel
664 * Make the current task sleep until @timeout is
665 * elapsed.
667 * You can set the task state as follows -
669 * %TASK_UNINTERRUPTIBLE - at least @timeout is guaranteed to
670 * pass before the routine returns. The routine will return 0
672 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
673 * delivered to the current task. In this case the remaining time
674 * will be returned
676 * The current task state is guaranteed to be TASK_RUNNING when this
677 * routine returns.
679 static ktime_t __sched
680 schedule_hrtimer(struct hrtimer *timer, const enum hrtimer_mode mode)
682 /* fn stays NULL, meaning single-shot wakeup: */
683 timer->data = current;
685 hrtimer_start(timer, timer->expires, mode);
687 schedule();
688 hrtimer_cancel(timer);
690 /* Return the remaining time: */
691 if (timer->state != HRTIMER_EXPIRED)
692 return ktime_sub(timer->expires, timer->base->get_time());
693 else
694 return (ktime_t) {.tv64 = 0 };
697 static inline ktime_t __sched
698 schedule_hrtimer_interruptible(struct hrtimer *timer,
699 const enum hrtimer_mode mode)
701 set_current_state(TASK_INTERRUPTIBLE);
703 return schedule_hrtimer(timer, mode);
706 static long __sched nanosleep_restart(struct restart_block *restart)
708 struct timespec __user *rmtp;
709 struct timespec tu;
710 void *rfn_save = restart->fn;
711 struct hrtimer timer;
712 ktime_t rem;
714 restart->fn = do_no_restart_syscall;
716 hrtimer_init(&timer, (clockid_t) restart->arg3, HRTIMER_ABS);
718 timer.expires.tv64 = ((u64)restart->arg1 << 32) | (u64) restart->arg0;
720 rem = schedule_hrtimer_interruptible(&timer, HRTIMER_ABS);
722 if (rem.tv64 <= 0)
723 return 0;
725 rmtp = (struct timespec __user *) restart->arg2;
726 tu = ktime_to_timespec(rem);
727 if (rmtp && copy_to_user(rmtp, &tu, sizeof(tu)))
728 return -EFAULT;
730 restart->fn = rfn_save;
732 /* The other values in restart are already filled in */
733 return -ERESTART_RESTARTBLOCK;
736 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
737 const enum hrtimer_mode mode, const clockid_t clockid)
739 struct restart_block *restart;
740 struct hrtimer timer;
741 struct timespec tu;
742 ktime_t rem;
744 hrtimer_init(&timer, clockid, mode);
746 timer.expires = timespec_to_ktime(*rqtp);
748 rem = schedule_hrtimer_interruptible(&timer, mode);
749 if (rem.tv64 <= 0)
750 return 0;
752 /* Absolute timers do not update the rmtp value and restart: */
753 if (mode == HRTIMER_ABS)
754 return -ERESTARTNOHAND;
756 tu = ktime_to_timespec(rem);
758 if (rmtp && copy_to_user(rmtp, &tu, sizeof(tu)))
759 return -EFAULT;
761 restart = &current_thread_info()->restart_block;
762 restart->fn = nanosleep_restart;
763 restart->arg0 = timer.expires.tv64 & 0xFFFFFFFF;
764 restart->arg1 = timer.expires.tv64 >> 32;
765 restart->arg2 = (unsigned long) rmtp;
766 restart->arg3 = (unsigned long) timer.base->index;
768 return -ERESTART_RESTARTBLOCK;
771 asmlinkage long
772 sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
774 struct timespec tu;
776 if (copy_from_user(&tu, rqtp, sizeof(tu)))
777 return -EFAULT;
779 if (!timespec_valid(&tu))
780 return -EINVAL;
782 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_REL, CLOCK_MONOTONIC);
786 * Functions related to boot-time initialization:
788 static void __devinit init_hrtimers_cpu(int cpu)
790 struct hrtimer_base *base = per_cpu(hrtimer_bases, cpu);
791 int i;
793 for (i = 0; i < MAX_HRTIMER_BASES; i++, base++)
794 spin_lock_init(&base->lock);
797 #ifdef CONFIG_HOTPLUG_CPU
799 static void migrate_hrtimer_list(struct hrtimer_base *old_base,
800 struct hrtimer_base *new_base)
802 struct hrtimer *timer;
803 struct rb_node *node;
805 while ((node = rb_first(&old_base->active))) {
806 timer = rb_entry(node, struct hrtimer, node);
807 __remove_hrtimer(timer, old_base);
808 timer->base = new_base;
809 enqueue_hrtimer(timer, new_base);
813 static void migrate_hrtimers(int cpu)
815 struct hrtimer_base *old_base, *new_base;
816 int i;
818 BUG_ON(cpu_online(cpu));
819 old_base = per_cpu(hrtimer_bases, cpu);
820 new_base = get_cpu_var(hrtimer_bases);
822 local_irq_disable();
824 for (i = 0; i < MAX_HRTIMER_BASES; i++) {
826 spin_lock(&new_base->lock);
827 spin_lock(&old_base->lock);
829 BUG_ON(old_base->curr_timer);
831 migrate_hrtimer_list(old_base, new_base);
833 spin_unlock(&old_base->lock);
834 spin_unlock(&new_base->lock);
835 old_base++;
836 new_base++;
839 local_irq_enable();
840 put_cpu_var(hrtimer_bases);
842 #endif /* CONFIG_HOTPLUG_CPU */
844 static int __devinit hrtimer_cpu_notify(struct notifier_block *self,
845 unsigned long action, void *hcpu)
847 long cpu = (long)hcpu;
849 switch (action) {
851 case CPU_UP_PREPARE:
852 init_hrtimers_cpu(cpu);
853 break;
855 #ifdef CONFIG_HOTPLUG_CPU
856 case CPU_DEAD:
857 migrate_hrtimers(cpu);
858 break;
859 #endif
861 default:
862 break;
865 return NOTIFY_OK;
868 static struct notifier_block __devinitdata hrtimers_nb = {
869 .notifier_call = hrtimer_cpu_notify,
872 void __init hrtimers_init(void)
874 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
875 (void *)(long)smp_processor_id());
876 register_cpu_notifier(&hrtimers_nb);