Linux 2.6.16.62-rc1
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / hrtimer.c
blob3372edd69edbe41dd6ca05e4558608625548fe9a
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);
72 * The timer bases:
74 * Note: If we want to add new timer bases, we have to skip the two
75 * clock ids captured by the cpu-timers. We do this by holding empty
76 * entries rather than doing math adjustment of the clock ids.
77 * This ensures that we capture erroneous accesses to these clock ids
78 * rather than moving them into the range of valid clock id's.
81 #define MAX_HRTIMER_BASES 2
83 static DEFINE_PER_CPU(struct hrtimer_base, hrtimer_bases[MAX_HRTIMER_BASES]) =
86 .index = CLOCK_REALTIME,
87 .get_time = &ktime_get_real,
88 .resolution = KTIME_REALTIME_RES,
91 .index = CLOCK_MONOTONIC,
92 .get_time = &ktime_get,
93 .resolution = KTIME_MONOTONIC_RES,
97 /**
98 * ktime_get_ts - get the monotonic clock in timespec format
100 * @ts: pointer to timespec variable
102 * The function calculates the monotonic clock from the realtime
103 * clock and the wall_to_monotonic offset and stores the result
104 * in normalized timespec format in the variable pointed to by ts.
106 void ktime_get_ts(struct timespec *ts)
108 struct timespec tomono;
109 unsigned long seq;
111 do {
112 seq = read_seqbegin(&xtime_lock);
113 getnstimeofday(ts);
114 tomono = wall_to_monotonic;
116 } while (read_seqretry(&xtime_lock, seq));
118 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
119 ts->tv_nsec + tomono.tv_nsec);
121 EXPORT_SYMBOL_GPL(ktime_get_ts);
124 * Functions and macros which are different for UP/SMP systems are kept in a
125 * single place
127 #ifdef CONFIG_SMP
129 #define set_curr_timer(b, t) do { (b)->curr_timer = (t); } while (0)
132 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
133 * means that all timers which are tied to this base via timer->base are
134 * locked, and the base itself is locked too.
136 * So __run_timers/migrate_timers can safely modify all timers which could
137 * be found on the lists/queues.
139 * When the timer's base is locked, and the timer removed from list, it is
140 * possible to set timer->base = NULL and drop the lock: the timer remains
141 * locked.
143 static struct hrtimer_base *lock_hrtimer_base(const struct hrtimer *timer,
144 unsigned long *flags)
146 struct hrtimer_base *base;
148 for (;;) {
149 base = timer->base;
150 if (likely(base != NULL)) {
151 spin_lock_irqsave(&base->lock, *flags);
152 if (likely(base == timer->base))
153 return base;
154 /* The timer has migrated to another CPU: */
155 spin_unlock_irqrestore(&base->lock, *flags);
157 cpu_relax();
162 * Switch the timer base to the current CPU when possible.
164 static inline struct hrtimer_base *
165 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_base *base)
167 struct hrtimer_base *new_base;
169 new_base = &__get_cpu_var(hrtimer_bases[base->index]);
171 if (base != new_base) {
173 * We are trying to schedule the timer on the local CPU.
174 * However we can't change timer's base while it is running,
175 * so we keep it on the same CPU. No hassle vs. reprogramming
176 * the event source in the high resolution case. The softirq
177 * code will take care of this when the timer function has
178 * completed. There is no conflict as we hold the lock until
179 * the timer is enqueued.
181 if (unlikely(base->curr_timer == timer))
182 return base;
184 /* See the comment in lock_timer_base() */
185 timer->base = NULL;
186 spin_unlock(&base->lock);
187 spin_lock(&new_base->lock);
188 timer->base = new_base;
190 return new_base;
193 #else /* CONFIG_SMP */
195 #define set_curr_timer(b, t) do { } while (0)
197 static inline struct hrtimer_base *
198 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
200 struct hrtimer_base *base = timer->base;
202 spin_lock_irqsave(&base->lock, *flags);
204 return base;
207 #define switch_hrtimer_base(t, b) (b)
209 #endif /* !CONFIG_SMP */
212 * Functions for the union type storage format of ktime_t which are
213 * too large for inlining:
215 #if BITS_PER_LONG < 64
216 # ifndef CONFIG_KTIME_SCALAR
218 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
220 * @kt: addend
221 * @nsec: the scalar nsec value to add
223 * Returns the sum of kt and nsec in ktime_t format
225 ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
227 ktime_t tmp;
229 if (likely(nsec < NSEC_PER_SEC)) {
230 tmp.tv64 = nsec;
231 } else {
232 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
234 tmp = ktime_set((long)nsec, rem);
237 return ktime_add(kt, tmp);
240 #else /* CONFIG_KTIME_SCALAR */
242 # endif /* !CONFIG_KTIME_SCALAR */
245 * Divide a ktime value by a nanosecond value
247 static unsigned long ktime_divns(const ktime_t kt, nsec_t div)
249 u64 dclc, inc, dns;
250 int sft = 0;
252 dclc = dns = ktime_to_ns(kt);
253 inc = div;
254 /* Make sure the divisor is less than 2^32: */
255 while (div >> 32) {
256 sft++;
257 div >>= 1;
259 dclc >>= sft;
260 do_div(dclc, (unsigned long) div);
262 return (unsigned long) dclc;
265 #else /* BITS_PER_LONG < 64 */
266 # define ktime_divns(kt, div) (unsigned long)((kt).tv64 / (div))
267 #endif /* BITS_PER_LONG >= 64 */
270 * Counterpart to lock_timer_base above:
272 static inline
273 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
275 spin_unlock_irqrestore(&timer->base->lock, *flags);
279 * hrtimer_forward - forward the timer expiry
281 * @timer: hrtimer to forward
282 * @interval: the interval to forward
284 * Forward the timer expiry so it will expire in the future.
285 * Returns the number of overruns.
287 unsigned long
288 hrtimer_forward(struct hrtimer *timer, ktime_t interval)
290 unsigned long orun = 1;
291 ktime_t delta, now;
293 now = timer->base->get_time();
295 delta = ktime_sub(now, timer->expires);
297 if (delta.tv64 < 0)
298 return 0;
300 if (interval.tv64 < timer->base->resolution.tv64)
301 interval.tv64 = timer->base->resolution.tv64;
303 if (unlikely(delta.tv64 >= interval.tv64)) {
304 nsec_t incr = ktime_to_ns(interval);
306 orun = ktime_divns(delta, incr);
307 timer->expires = ktime_add_ns(timer->expires, incr * orun);
308 if (timer->expires.tv64 > now.tv64)
309 return orun;
311 * This (and the ktime_add() below) is the
312 * correction for exact:
314 orun++;
316 timer->expires = ktime_add(timer->expires, interval);
318 * Make sure, that the result did not wrap with a very large
319 * interval.
321 if (timer->expires.tv64 < 0)
322 timer->expires = ktime_set(KTIME_SEC_MAX, 0);
324 return orun;
328 * enqueue_hrtimer - internal function to (re)start a timer
330 * The timer is inserted in expiry order. Insertion into the
331 * red black tree is O(log(n)). Must hold the base lock.
333 static void enqueue_hrtimer(struct hrtimer *timer, struct hrtimer_base *base)
335 struct rb_node **link = &base->active.rb_node;
336 struct rb_node *parent = NULL;
337 struct hrtimer *entry;
340 * Find the right place in the rbtree:
342 while (*link) {
343 parent = *link;
344 entry = rb_entry(parent, struct hrtimer, node);
346 * We dont care about collisions. Nodes with
347 * the same expiry time stay together.
349 if (timer->expires.tv64 < entry->expires.tv64)
350 link = &(*link)->rb_left;
351 else
352 link = &(*link)->rb_right;
356 * Insert the timer to the rbtree and check whether it
357 * replaces the first pending timer
359 rb_link_node(&timer->node, parent, link);
360 rb_insert_color(&timer->node, &base->active);
362 timer->state = HRTIMER_PENDING;
364 if (!base->first || timer->expires.tv64 <
365 rb_entry(base->first, struct hrtimer, node)->expires.tv64)
366 base->first = &timer->node;
370 * __remove_hrtimer - internal function to remove a timer
372 * Caller must hold the base lock.
374 static void __remove_hrtimer(struct hrtimer *timer, struct hrtimer_base *base)
377 * Remove the timer from the rbtree and replace the
378 * first entry pointer if necessary.
380 if (base->first == &timer->node)
381 base->first = rb_next(&timer->node);
382 rb_erase(&timer->node, &base->active);
386 * remove hrtimer, called with base lock held
388 static inline int
389 remove_hrtimer(struct hrtimer *timer, struct hrtimer_base *base)
391 if (hrtimer_active(timer)) {
392 __remove_hrtimer(timer, base);
393 timer->state = HRTIMER_INACTIVE;
394 return 1;
396 return 0;
400 * hrtimer_start - (re)start an relative timer on the current CPU
402 * @timer: the timer to be added
403 * @tim: expiry time
404 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
406 * Returns:
407 * 0 on success
408 * 1 when the timer was active
411 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
413 struct hrtimer_base *base, *new_base;
414 unsigned long flags;
415 int ret;
417 base = lock_hrtimer_base(timer, &flags);
419 /* Remove an active timer from the queue: */
420 ret = remove_hrtimer(timer, base);
422 /* Switch the timer base, if necessary: */
423 new_base = switch_hrtimer_base(timer, base);
425 if (mode == HRTIMER_REL) {
426 tim = ktime_add(tim, new_base->get_time());
428 * CONFIG_TIME_LOW_RES is a temporary way for architectures
429 * to signal that they simply return xtime in
430 * do_gettimeoffset(). In this case we want to round up by
431 * resolution when starting a relative timer, to avoid short
432 * timeouts. This will go away with the GTOD framework.
434 #ifdef CONFIG_TIME_LOW_RES
435 tim = ktime_add(tim, base->resolution);
436 #endif
438 timer->expires = tim;
440 enqueue_hrtimer(timer, new_base);
442 unlock_hrtimer_base(timer, &flags);
444 return ret;
448 * hrtimer_try_to_cancel - try to deactivate a timer
450 * @timer: hrtimer to stop
452 * Returns:
453 * 0 when the timer was not active
454 * 1 when the timer was active
455 * -1 when the timer is currently excuting the callback function and
456 * can not be stopped
458 int hrtimer_try_to_cancel(struct hrtimer *timer)
460 struct hrtimer_base *base;
461 unsigned long flags;
462 int ret = -1;
464 base = lock_hrtimer_base(timer, &flags);
466 if (base->curr_timer != timer)
467 ret = remove_hrtimer(timer, base);
469 unlock_hrtimer_base(timer, &flags);
471 return ret;
476 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
478 * @timer: the timer to be cancelled
480 * Returns:
481 * 0 when the timer was not active
482 * 1 when the timer was active
484 int hrtimer_cancel(struct hrtimer *timer)
486 for (;;) {
487 int ret = hrtimer_try_to_cancel(timer);
489 if (ret >= 0)
490 return ret;
495 * hrtimer_get_remaining - get remaining time for the timer
497 * @timer: the timer to read
499 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
501 struct hrtimer_base *base;
502 unsigned long flags;
503 ktime_t rem;
505 base = lock_hrtimer_base(timer, &flags);
506 rem = ktime_sub(timer->expires, timer->base->get_time());
507 unlock_hrtimer_base(timer, &flags);
509 return rem;
512 #ifdef CONFIG_NO_IDLE_HZ
514 * hrtimer_get_next_event - get the time until next expiry event
516 * Returns the delta to the next expiry event or KTIME_MAX if no timer
517 * is pending.
519 ktime_t hrtimer_get_next_event(void)
521 struct hrtimer_base *base = __get_cpu_var(hrtimer_bases);
522 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
523 unsigned long flags;
524 int i;
526 for (i = 0; i < MAX_HRTIMER_BASES; i++, base++) {
527 struct hrtimer *timer;
529 spin_lock_irqsave(&base->lock, flags);
530 if (!base->first) {
531 spin_unlock_irqrestore(&base->lock, flags);
532 continue;
534 timer = rb_entry(base->first, struct hrtimer, node);
535 delta.tv64 = timer->expires.tv64;
536 spin_unlock_irqrestore(&base->lock, flags);
537 delta = ktime_sub(delta, base->get_time());
538 if (delta.tv64 < mindelta.tv64)
539 mindelta.tv64 = delta.tv64;
541 if (mindelta.tv64 < 0)
542 mindelta.tv64 = 0;
543 return mindelta;
545 #endif
548 * hrtimer_init - initialize a timer to the given clock
550 * @timer: the timer to be initialized
551 * @clock_id: the clock to be used
552 * @mode: timer mode abs/rel
554 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
555 enum hrtimer_mode mode)
557 struct hrtimer_base *bases;
559 memset(timer, 0, sizeof(struct hrtimer));
561 bases = per_cpu(hrtimer_bases, raw_smp_processor_id());
563 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_ABS)
564 clock_id = CLOCK_MONOTONIC;
566 timer->base = &bases[clock_id];
570 * hrtimer_get_res - get the timer resolution for a clock
572 * @which_clock: which clock to query
573 * @tp: pointer to timespec variable to store the resolution
575 * Store the resolution of the clock selected by which_clock in the
576 * variable pointed to by tp.
578 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
580 struct hrtimer_base *bases;
582 bases = per_cpu(hrtimer_bases, raw_smp_processor_id());
583 *tp = ktime_to_timespec(bases[which_clock].resolution);
585 return 0;
589 * Expire the per base hrtimer-queue:
591 static inline void run_hrtimer_queue(struct hrtimer_base *base)
593 ktime_t now = base->get_time();
594 struct rb_node *node;
596 spin_lock_irq(&base->lock);
598 while ((node = base->first)) {
599 struct hrtimer *timer;
600 int (*fn)(void *);
601 int restart;
602 void *data;
604 timer = rb_entry(node, struct hrtimer, node);
605 if (now.tv64 <= timer->expires.tv64)
606 break;
608 fn = timer->function;
609 data = timer->data;
610 set_curr_timer(base, timer);
611 timer->state = HRTIMER_RUNNING;
612 __remove_hrtimer(timer, base);
613 spin_unlock_irq(&base->lock);
616 * fn == NULL is special case for the simplest timer
617 * variant - wake up process and do not restart:
619 if (!fn) {
620 wake_up_process(data);
621 restart = HRTIMER_NORESTART;
622 } else
623 restart = fn(data);
625 spin_lock_irq(&base->lock);
627 /* Another CPU has added back the timer */
628 if (timer->state != HRTIMER_RUNNING)
629 continue;
631 if (restart == HRTIMER_RESTART)
632 enqueue_hrtimer(timer, base);
633 else
634 timer->state = HRTIMER_EXPIRED;
636 set_curr_timer(base, NULL);
637 spin_unlock_irq(&base->lock);
641 * Called from timer softirq every jiffy, expire hrtimers:
643 void hrtimer_run_queues(void)
645 struct hrtimer_base *base = __get_cpu_var(hrtimer_bases);
646 int i;
648 for (i = 0; i < MAX_HRTIMER_BASES; i++)
649 run_hrtimer_queue(&base[i]);
653 * Sleep related functions:
657 * schedule_hrtimer - sleep until timeout
659 * @timer: hrtimer variable initialized with the correct clock base
660 * @mode: timeout value is abs/rel
662 * Make the current task sleep until @timeout is
663 * elapsed.
665 * You can set the task state as follows -
667 * %TASK_UNINTERRUPTIBLE - at least @timeout is guaranteed to
668 * pass before the routine returns. The routine will return 0
670 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
671 * delivered to the current task. In this case the remaining time
672 * will be returned
674 * The current task state is guaranteed to be TASK_RUNNING when this
675 * routine returns.
677 static ktime_t __sched
678 schedule_hrtimer(struct hrtimer *timer, const enum hrtimer_mode mode)
680 /* fn stays NULL, meaning single-shot wakeup: */
681 timer->data = current;
683 hrtimer_start(timer, timer->expires, mode);
685 schedule();
686 hrtimer_cancel(timer);
688 /* Return the remaining time: */
689 if (timer->state != HRTIMER_EXPIRED)
690 return ktime_sub(timer->expires, timer->base->get_time());
691 else
692 return (ktime_t) {.tv64 = 0 };
695 static inline ktime_t __sched
696 schedule_hrtimer_interruptible(struct hrtimer *timer,
697 const enum hrtimer_mode mode)
699 set_current_state(TASK_INTERRUPTIBLE);
701 return schedule_hrtimer(timer, mode);
704 static long __sched nanosleep_restart(struct restart_block *restart)
706 struct timespec __user *rmtp;
707 struct timespec tu;
708 void *rfn_save = restart->fn;
709 struct hrtimer timer;
710 ktime_t rem;
712 restart->fn = do_no_restart_syscall;
714 hrtimer_init(&timer, (clockid_t) restart->arg3, HRTIMER_ABS);
716 timer.expires.tv64 = ((u64)restart->arg1 << 32) | (u64) restart->arg0;
718 rem = schedule_hrtimer_interruptible(&timer, HRTIMER_ABS);
720 if (rem.tv64 <= 0)
721 return 0;
723 rmtp = (struct timespec __user *) restart->arg2;
724 tu = ktime_to_timespec(rem);
725 if (rmtp && copy_to_user(rmtp, &tu, sizeof(tu)))
726 return -EFAULT;
728 restart->fn = rfn_save;
730 /* The other values in restart are already filled in */
731 return -ERESTART_RESTARTBLOCK;
734 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
735 const enum hrtimer_mode mode, const clockid_t clockid)
737 struct restart_block *restart;
738 struct hrtimer timer;
739 struct timespec tu;
740 ktime_t rem;
742 hrtimer_init(&timer, clockid, mode);
744 timer.expires = timespec_to_ktime(*rqtp);
746 rem = schedule_hrtimer_interruptible(&timer, mode);
747 if (rem.tv64 <= 0)
748 return 0;
750 /* Absolute timers do not update the rmtp value and restart: */
751 if (mode == HRTIMER_ABS)
752 return -ERESTARTNOHAND;
754 tu = ktime_to_timespec(rem);
756 if (rmtp && copy_to_user(rmtp, &tu, sizeof(tu)))
757 return -EFAULT;
759 restart = &current_thread_info()->restart_block;
760 restart->fn = nanosleep_restart;
761 restart->arg0 = timer.expires.tv64 & 0xFFFFFFFF;
762 restart->arg1 = timer.expires.tv64 >> 32;
763 restart->arg2 = (unsigned long) rmtp;
764 restart->arg3 = (unsigned long) timer.base->index;
766 return -ERESTART_RESTARTBLOCK;
769 asmlinkage long
770 sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
772 struct timespec tu;
774 if (copy_from_user(&tu, rqtp, sizeof(tu)))
775 return -EFAULT;
777 if (!timespec_valid(&tu))
778 return -EINVAL;
780 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_REL, CLOCK_MONOTONIC);
784 * Functions related to boot-time initialization:
786 static void __devinit init_hrtimers_cpu(int cpu)
788 struct hrtimer_base *base = per_cpu(hrtimer_bases, cpu);
789 int i;
791 for (i = 0; i < MAX_HRTIMER_BASES; i++, base++)
792 spin_lock_init(&base->lock);
795 #ifdef CONFIG_HOTPLUG_CPU
797 static void migrate_hrtimer_list(struct hrtimer_base *old_base,
798 struct hrtimer_base *new_base)
800 struct hrtimer *timer;
801 struct rb_node *node;
803 while ((node = rb_first(&old_base->active))) {
804 timer = rb_entry(node, struct hrtimer, node);
805 __remove_hrtimer(timer, old_base);
806 timer->base = new_base;
807 enqueue_hrtimer(timer, new_base);
811 static void migrate_hrtimers(int cpu)
813 struct hrtimer_base *old_base, *new_base;
814 int i;
816 BUG_ON(cpu_online(cpu));
817 old_base = per_cpu(hrtimer_bases, cpu);
818 new_base = get_cpu_var(hrtimer_bases);
820 local_irq_disable();
822 for (i = 0; i < MAX_HRTIMER_BASES; i++) {
824 spin_lock(&new_base->lock);
825 spin_lock(&old_base->lock);
827 BUG_ON(old_base->curr_timer);
829 migrate_hrtimer_list(old_base, new_base);
831 spin_unlock(&old_base->lock);
832 spin_unlock(&new_base->lock);
833 old_base++;
834 new_base++;
837 local_irq_enable();
838 put_cpu_var(hrtimer_bases);
840 #endif /* CONFIG_HOTPLUG_CPU */
842 static int __devinit hrtimer_cpu_notify(struct notifier_block *self,
843 unsigned long action, void *hcpu)
845 long cpu = (long)hcpu;
847 switch (action) {
849 case CPU_UP_PREPARE:
850 init_hrtimers_cpu(cpu);
851 break;
853 #ifdef CONFIG_HOTPLUG_CPU
854 case CPU_DEAD:
855 migrate_hrtimers(cpu);
856 break;
857 #endif
859 default:
860 break;
863 return NOTIFY_OK;
866 static struct notifier_block __devinitdata hrtimers_nb = {
867 .notifier_call = hrtimer_cpu_notify,
870 void __init hrtimers_init(void)
872 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
873 (void *)(long)smp_processor_id());
874 register_cpu_notifier(&hrtimers_nb);