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:
17 * - precise in-kernel timing
19 * Started by: Thomas Gleixner and Ingo Molnar
22 * based on kernel/timer.c
24 * Help, testing, suggestions, bugfixes, improvements were
27 * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
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>
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)
54 return timespec_to_ktime(now
);
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)
68 return timespec_to_ktime(now
);
71 EXPORT_SYMBOL_GPL(ktime_get_real
);
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
,
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
;
114 seq
= read_seqbegin(&xtime_lock
);
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
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
145 static struct hrtimer_base
*lock_hrtimer_base(const struct hrtimer
*timer
,
146 unsigned long *flags
)
148 struct hrtimer_base
*base
;
152 if (likely(base
!= NULL
)) {
153 spin_lock_irqsave(&base
->lock
, *flags
);
154 if (likely(base
== timer
->base
))
156 /* The timer has migrated to another CPU: */
157 spin_unlock_irqrestore(&base
->lock
, *flags
);
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
))
186 /* See the comment in lock_timer_base() */
188 spin_unlock(&base
->lock
);
189 spin_lock(&new_base
->lock
);
190 timer
->base
= 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
);
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
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
)
231 if (likely(nsec
< NSEC_PER_SEC
)) {
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
)
254 dclc
= dns
= ktime_to_ns(kt
);
256 /* Make sure the divisor is less than 2^32: */
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:
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.
290 hrtimer_forward(struct hrtimer
*timer
, ktime_t interval
)
292 unsigned long orun
= 1;
295 now
= timer
->base
->get_time();
297 delta
= ktime_sub(now
, timer
->expires
);
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
)
313 * This (and the ktime_add() below) is the
314 * correction for exact:
318 timer
->expires
= ktime_add(timer
->expires
, interval
);
324 * enqueue_hrtimer - internal function to (re)start a timer
326 * The timer is inserted in expiry order. Insertion into the
327 * red black tree is O(log(n)). Must hold the base lock.
329 static void enqueue_hrtimer(struct hrtimer
*timer
, struct hrtimer_base
*base
)
331 struct rb_node
**link
= &base
->active
.rb_node
;
332 struct rb_node
*parent
= NULL
;
333 struct hrtimer
*entry
;
336 * Find the right place in the rbtree:
340 entry
= rb_entry(parent
, struct hrtimer
, node
);
342 * We dont care about collisions. Nodes with
343 * the same expiry time stay together.
345 if (timer
->expires
.tv64
< entry
->expires
.tv64
)
346 link
= &(*link
)->rb_left
;
348 link
= &(*link
)->rb_right
;
352 * Insert the timer to the rbtree and check whether it
353 * replaces the first pending timer
355 rb_link_node(&timer
->node
, parent
, link
);
356 rb_insert_color(&timer
->node
, &base
->active
);
358 timer
->state
= HRTIMER_PENDING
;
360 if (!base
->first
|| timer
->expires
.tv64
<
361 rb_entry(base
->first
, struct hrtimer
, node
)->expires
.tv64
)
362 base
->first
= &timer
->node
;
366 * __remove_hrtimer - internal function to remove a timer
368 * Caller must hold the base lock.
370 static void __remove_hrtimer(struct hrtimer
*timer
, struct hrtimer_base
*base
)
373 * Remove the timer from the rbtree and replace the
374 * first entry pointer if necessary.
376 if (base
->first
== &timer
->node
)
377 base
->first
= rb_next(&timer
->node
);
378 rb_erase(&timer
->node
, &base
->active
);
382 * remove hrtimer, called with base lock held
385 remove_hrtimer(struct hrtimer
*timer
, struct hrtimer_base
*base
)
387 if (hrtimer_active(timer
)) {
388 __remove_hrtimer(timer
, base
);
389 timer
->state
= HRTIMER_INACTIVE
;
396 * hrtimer_start - (re)start an relative timer on the current CPU
398 * @timer: the timer to be added
400 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
404 * 1 when the timer was active
407 hrtimer_start(struct hrtimer
*timer
, ktime_t tim
, const enum hrtimer_mode mode
)
409 struct hrtimer_base
*base
, *new_base
;
413 base
= lock_hrtimer_base(timer
, &flags
);
415 /* Remove an active timer from the queue: */
416 ret
= remove_hrtimer(timer
, base
);
418 /* Switch the timer base, if necessary: */
419 new_base
= switch_hrtimer_base(timer
, base
);
421 if (mode
== HRTIMER_REL
)
422 tim
= ktime_add(tim
, new_base
->get_time());
423 timer
->expires
= tim
;
425 enqueue_hrtimer(timer
, new_base
);
427 unlock_hrtimer_base(timer
, &flags
);
433 * hrtimer_try_to_cancel - try to deactivate a timer
435 * @timer: hrtimer to stop
438 * 0 when the timer was not active
439 * 1 when the timer was active
440 * -1 when the timer is currently excuting the callback function and
443 int hrtimer_try_to_cancel(struct hrtimer
*timer
)
445 struct hrtimer_base
*base
;
449 base
= lock_hrtimer_base(timer
, &flags
);
451 if (base
->curr_timer
!= timer
)
452 ret
= remove_hrtimer(timer
, base
);
454 unlock_hrtimer_base(timer
, &flags
);
461 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
463 * @timer: the timer to be cancelled
466 * 0 when the timer was not active
467 * 1 when the timer was active
469 int hrtimer_cancel(struct hrtimer
*timer
)
472 int ret
= hrtimer_try_to_cancel(timer
);
480 * hrtimer_get_remaining - get remaining time for the timer
482 * @timer: the timer to read
484 ktime_t
hrtimer_get_remaining(const struct hrtimer
*timer
)
486 struct hrtimer_base
*base
;
490 base
= lock_hrtimer_base(timer
, &flags
);
491 rem
= ktime_sub(timer
->expires
, timer
->base
->get_time());
492 unlock_hrtimer_base(timer
, &flags
);
498 * hrtimer_init - initialize a timer to the given clock
500 * @timer: the timer to be initialized
501 * @clock_id: the clock to be used
502 * @mode: timer mode abs/rel
504 void hrtimer_init(struct hrtimer
*timer
, clockid_t clock_id
,
505 enum hrtimer_mode mode
)
507 struct hrtimer_base
*bases
;
509 memset(timer
, 0, sizeof(struct hrtimer
));
511 bases
= per_cpu(hrtimer_bases
, raw_smp_processor_id());
513 if (clock_id
== CLOCK_REALTIME
&& mode
!= HRTIMER_ABS
)
514 clock_id
= CLOCK_MONOTONIC
;
516 timer
->base
= &bases
[clock_id
];
520 * hrtimer_get_res - get the timer resolution for a clock
522 * @which_clock: which clock to query
523 * @tp: pointer to timespec variable to store the resolution
525 * Store the resolution of the clock selected by which_clock in the
526 * variable pointed to by tp.
528 int hrtimer_get_res(const clockid_t which_clock
, struct timespec
*tp
)
530 struct hrtimer_base
*bases
;
532 bases
= per_cpu(hrtimer_bases
, raw_smp_processor_id());
533 *tp
= ktime_to_timespec(bases
[which_clock
].resolution
);
539 * Expire the per base hrtimer-queue:
541 static inline void run_hrtimer_queue(struct hrtimer_base
*base
)
543 ktime_t now
= base
->get_time();
544 struct rb_node
*node
;
546 spin_lock_irq(&base
->lock
);
548 while ((node
= base
->first
)) {
549 struct hrtimer
*timer
;
554 timer
= rb_entry(node
, struct hrtimer
, node
);
555 if (now
.tv64
<= timer
->expires
.tv64
)
558 fn
= timer
->function
;
560 set_curr_timer(base
, timer
);
561 timer
->state
= HRTIMER_RUNNING
;
562 __remove_hrtimer(timer
, base
);
563 spin_unlock_irq(&base
->lock
);
566 * fn == NULL is special case for the simplest timer
567 * variant - wake up process and do not restart:
570 wake_up_process(data
);
571 restart
= HRTIMER_NORESTART
;
575 spin_lock_irq(&base
->lock
);
577 /* Another CPU has added back the timer */
578 if (timer
->state
!= HRTIMER_RUNNING
)
581 if (restart
== HRTIMER_RESTART
)
582 enqueue_hrtimer(timer
, base
);
584 timer
->state
= HRTIMER_EXPIRED
;
586 set_curr_timer(base
, NULL
);
587 spin_unlock_irq(&base
->lock
);
591 * Called from timer softirq every jiffy, expire hrtimers:
593 void hrtimer_run_queues(void)
595 struct hrtimer_base
*base
= __get_cpu_var(hrtimer_bases
);
598 for (i
= 0; i
< MAX_HRTIMER_BASES
; i
++)
599 run_hrtimer_queue(&base
[i
]);
603 * Sleep related functions:
607 * schedule_hrtimer - sleep until timeout
609 * @timer: hrtimer variable initialized with the correct clock base
610 * @mode: timeout value is abs/rel
612 * Make the current task sleep until @timeout is
615 * You can set the task state as follows -
617 * %TASK_UNINTERRUPTIBLE - at least @timeout is guaranteed to
618 * pass before the routine returns. The routine will return 0
620 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
621 * delivered to the current task. In this case the remaining time
624 * The current task state is guaranteed to be TASK_RUNNING when this
627 static ktime_t __sched
628 schedule_hrtimer(struct hrtimer
*timer
, const enum hrtimer_mode mode
)
630 /* fn stays NULL, meaning single-shot wakeup: */
631 timer
->data
= current
;
633 hrtimer_start(timer
, timer
->expires
, mode
);
636 hrtimer_cancel(timer
);
638 /* Return the remaining time: */
639 if (timer
->state
!= HRTIMER_EXPIRED
)
640 return ktime_sub(timer
->expires
, timer
->base
->get_time());
642 return (ktime_t
) {.tv64
= 0 };
645 static inline ktime_t __sched
646 schedule_hrtimer_interruptible(struct hrtimer
*timer
,
647 const enum hrtimer_mode mode
)
649 set_current_state(TASK_INTERRUPTIBLE
);
651 return schedule_hrtimer(timer
, mode
);
654 static long __sched
nanosleep_restart(struct restart_block
*restart
)
656 struct timespec __user
*rmtp
;
658 void *rfn_save
= restart
->fn
;
659 struct hrtimer timer
;
662 restart
->fn
= do_no_restart_syscall
;
664 hrtimer_init(&timer
, (clockid_t
) restart
->arg3
, HRTIMER_ABS
);
666 timer
.expires
.tv64
= ((u64
)restart
->arg1
<< 32) | (u64
) restart
->arg0
;
668 rem
= schedule_hrtimer_interruptible(&timer
, HRTIMER_ABS
);
673 rmtp
= (struct timespec __user
*) restart
->arg2
;
674 tu
= ktime_to_timespec(rem
);
675 if (rmtp
&& copy_to_user(rmtp
, &tu
, sizeof(tu
)))
678 restart
->fn
= rfn_save
;
680 /* The other values in restart are already filled in */
681 return -ERESTART_RESTARTBLOCK
;
684 long hrtimer_nanosleep(struct timespec
*rqtp
, struct timespec __user
*rmtp
,
685 const enum hrtimer_mode mode
, const clockid_t clockid
)
687 struct restart_block
*restart
;
688 struct hrtimer timer
;
692 hrtimer_init(&timer
, clockid
, mode
);
694 timer
.expires
= timespec_to_ktime(*rqtp
);
696 rem
= schedule_hrtimer_interruptible(&timer
, mode
);
700 /* Absolute timers do not update the rmtp value and restart: */
701 if (mode
== HRTIMER_ABS
)
702 return -ERESTARTNOHAND
;
704 tu
= ktime_to_timespec(rem
);
706 if (rmtp
&& copy_to_user(rmtp
, &tu
, sizeof(tu
)))
709 restart
= ¤t_thread_info()->restart_block
;
710 restart
->fn
= nanosleep_restart
;
711 restart
->arg0
= timer
.expires
.tv64
& 0xFFFFFFFF;
712 restart
->arg1
= timer
.expires
.tv64
>> 32;
713 restart
->arg2
= (unsigned long) rmtp
;
714 restart
->arg3
= (unsigned long) timer
.base
->index
;
716 return -ERESTART_RESTARTBLOCK
;
720 sys_nanosleep(struct timespec __user
*rqtp
, struct timespec __user
*rmtp
)
724 if (copy_from_user(&tu
, rqtp
, sizeof(tu
)))
727 if (!timespec_valid(&tu
))
730 return hrtimer_nanosleep(&tu
, rmtp
, HRTIMER_REL
, CLOCK_MONOTONIC
);
734 * Functions related to boot-time initialization:
736 static void __devinit
init_hrtimers_cpu(int cpu
)
738 struct hrtimer_base
*base
= per_cpu(hrtimer_bases
, cpu
);
741 for (i
= 0; i
< MAX_HRTIMER_BASES
; i
++, base
++)
742 spin_lock_init(&base
->lock
);
745 #ifdef CONFIG_HOTPLUG_CPU
747 static void migrate_hrtimer_list(struct hrtimer_base
*old_base
,
748 struct hrtimer_base
*new_base
)
750 struct hrtimer
*timer
;
751 struct rb_node
*node
;
753 while ((node
= rb_first(&old_base
->active
))) {
754 timer
= rb_entry(node
, struct hrtimer
, node
);
755 __remove_hrtimer(timer
, old_base
);
756 timer
->base
= new_base
;
757 enqueue_hrtimer(timer
, new_base
);
761 static void migrate_hrtimers(int cpu
)
763 struct hrtimer_base
*old_base
, *new_base
;
766 BUG_ON(cpu_online(cpu
));
767 old_base
= per_cpu(hrtimer_bases
, cpu
);
768 new_base
= get_cpu_var(hrtimer_bases
);
772 for (i
= 0; i
< MAX_HRTIMER_BASES
; i
++) {
774 spin_lock(&new_base
->lock
);
775 spin_lock(&old_base
->lock
);
777 BUG_ON(old_base
->curr_timer
);
779 migrate_hrtimer_list(old_base
, new_base
);
781 spin_unlock(&old_base
->lock
);
782 spin_unlock(&new_base
->lock
);
788 put_cpu_var(hrtimer_bases
);
790 #endif /* CONFIG_HOTPLUG_CPU */
792 static int __devinit
hrtimer_cpu_notify(struct notifier_block
*self
,
793 unsigned long action
, void *hcpu
)
795 long cpu
= (long)hcpu
;
800 init_hrtimers_cpu(cpu
);
803 #ifdef CONFIG_HOTPLUG_CPU
805 migrate_hrtimers(cpu
);
816 static struct notifier_block __devinitdata hrtimers_nb
= {
817 .notifier_call
= hrtimer_cpu_notify
,
820 void __init
hrtimers_init(void)
822 hrtimer_cpu_notify(&hrtimers_nb
, (unsigned long)CPU_UP_PREPARE
,
823 (void *)(long)smp_processor_id());
824 register_cpu_notifier(&hrtimers_nb
);