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 * For licencing details see kernel-base/COPYING
27 #include <linux/cpu.h>
28 #include <linux/module.h>
29 #include <linux/percpu.h>
30 #include <linux/hrtimer.h>
31 #include <linux/notifier.h>
32 #include <linux/syscalls.h>
33 #include <linux/interrupt.h>
35 #include <asm/uaccess.h>
38 * ktime_get - get the monotonic time in ktime_t format
40 * returns the time in ktime_t format
42 static ktime_t
ktime_get(void)
48 return timespec_to_ktime(now
);
52 * ktime_get_real - get the real (wall-) time in ktime_t format
54 * returns the time in ktime_t format
56 static ktime_t
ktime_get_real(void)
62 return timespec_to_ktime(now
);
65 EXPORT_SYMBOL_GPL(ktime_get_real
);
70 * Note: If we want to add new timer bases, we have to skip the two
71 * clock ids captured by the cpu-timers. We do this by holding empty
72 * entries rather than doing math adjustment of the clock ids.
73 * This ensures that we capture erroneous accesses to these clock ids
74 * rather than moving them into the range of valid clock id's.
77 #define MAX_HRTIMER_BASES 2
79 static DEFINE_PER_CPU(struct hrtimer_base
, hrtimer_bases
[MAX_HRTIMER_BASES
]) =
82 .index
= CLOCK_REALTIME
,
83 .get_time
= &ktime_get_real
,
84 .resolution
= KTIME_REALTIME_RES
,
87 .index
= CLOCK_MONOTONIC
,
88 .get_time
= &ktime_get
,
89 .resolution
= KTIME_MONOTONIC_RES
,
94 * ktime_get_ts - get the monotonic clock in timespec format
96 * @ts: pointer to timespec variable
98 * The function calculates the monotonic clock from the realtime
99 * clock and the wall_to_monotonic offset and stores the result
100 * in normalized timespec format in the variable pointed to by ts.
102 void ktime_get_ts(struct timespec
*ts
)
104 struct timespec tomono
;
108 seq
= read_seqbegin(&xtime_lock
);
110 tomono
= wall_to_monotonic
;
112 } while (read_seqretry(&xtime_lock
, seq
));
114 set_normalized_timespec(ts
, ts
->tv_sec
+ tomono
.tv_sec
,
115 ts
->tv_nsec
+ tomono
.tv_nsec
);
117 EXPORT_SYMBOL_GPL(ktime_get_ts
);
120 * Functions and macros which are different for UP/SMP systems are kept in a
125 #define set_curr_timer(b, t) do { (b)->curr_timer = (t); } while (0)
128 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
129 * means that all timers which are tied to this base via timer->base are
130 * locked, and the base itself is locked too.
132 * So __run_timers/migrate_timers can safely modify all timers which could
133 * be found on the lists/queues.
135 * When the timer's base is locked, and the timer removed from list, it is
136 * possible to set timer->base = NULL and drop the lock: the timer remains
139 static struct hrtimer_base
*lock_hrtimer_base(const struct hrtimer
*timer
,
140 unsigned long *flags
)
142 struct hrtimer_base
*base
;
146 if (likely(base
!= NULL
)) {
147 spin_lock_irqsave(&base
->lock
, *flags
);
148 if (likely(base
== timer
->base
))
150 /* The timer has migrated to another CPU: */
151 spin_unlock_irqrestore(&base
->lock
, *flags
);
158 * Switch the timer base to the current CPU when possible.
160 static inline struct hrtimer_base
*
161 switch_hrtimer_base(struct hrtimer
*timer
, struct hrtimer_base
*base
)
163 struct hrtimer_base
*new_base
;
165 new_base
= &__get_cpu_var(hrtimer_bases
[base
->index
]);
167 if (base
!= new_base
) {
169 * We are trying to schedule the timer on the local CPU.
170 * However we can't change timer's base while it is running,
171 * so we keep it on the same CPU. No hassle vs. reprogramming
172 * the event source in the high resolution case. The softirq
173 * code will take care of this when the timer function has
174 * completed. There is no conflict as we hold the lock until
175 * the timer is enqueued.
177 if (unlikely(base
->curr_timer
== timer
))
180 /* See the comment in lock_timer_base() */
182 spin_unlock(&base
->lock
);
183 spin_lock(&new_base
->lock
);
184 timer
->base
= new_base
;
189 #else /* CONFIG_SMP */
191 #define set_curr_timer(b, t) do { } while (0)
193 static inline struct hrtimer_base
*
194 lock_hrtimer_base(const struct hrtimer
*timer
, unsigned long *flags
)
196 struct hrtimer_base
*base
= timer
->base
;
198 spin_lock_irqsave(&base
->lock
, *flags
);
203 #define switch_hrtimer_base(t, b) (b)
205 #endif /* !CONFIG_SMP */
208 * Functions for the union type storage format of ktime_t which are
209 * too large for inlining:
211 #if BITS_PER_LONG < 64
212 # ifndef CONFIG_KTIME_SCALAR
214 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
217 * @nsec: the scalar nsec value to add
219 * Returns the sum of kt and nsec in ktime_t format
221 ktime_t
ktime_add_ns(const ktime_t kt
, u64 nsec
)
225 if (likely(nsec
< NSEC_PER_SEC
)) {
228 unsigned long rem
= do_div(nsec
, NSEC_PER_SEC
);
230 tmp
= ktime_set((long)nsec
, rem
);
233 return ktime_add(kt
, tmp
);
236 #else /* CONFIG_KTIME_SCALAR */
238 # endif /* !CONFIG_KTIME_SCALAR */
241 * Divide a ktime value by a nanosecond value
243 static unsigned long ktime_divns(const ktime_t kt
, nsec_t div
)
248 dclc
= dns
= ktime_to_ns(kt
);
250 /* Make sure the divisor is less than 2^32: */
256 do_div(dclc
, (unsigned long) div
);
258 return (unsigned long) dclc
;
261 #else /* BITS_PER_LONG < 64 */
262 # define ktime_divns(kt, div) (unsigned long)((kt).tv64 / (div))
263 #endif /* BITS_PER_LONG >= 64 */
266 * Counterpart to lock_timer_base above:
269 void unlock_hrtimer_base(const struct hrtimer
*timer
, unsigned long *flags
)
271 spin_unlock_irqrestore(&timer
->base
->lock
, *flags
);
275 * hrtimer_forward - forward the timer expiry
277 * @timer: hrtimer to forward
278 * @interval: the interval to forward
280 * Forward the timer expiry so it will expire in the future.
281 * Returns the number of overruns.
284 hrtimer_forward(struct hrtimer
*timer
, ktime_t interval
)
286 unsigned long orun
= 1;
289 now
= timer
->base
->get_time();
291 delta
= ktime_sub(now
, timer
->expires
);
296 if (interval
.tv64
< timer
->base
->resolution
.tv64
)
297 interval
.tv64
= timer
->base
->resolution
.tv64
;
299 if (unlikely(delta
.tv64
>= interval
.tv64
)) {
300 nsec_t incr
= ktime_to_ns(interval
);
302 orun
= ktime_divns(delta
, incr
);
303 timer
->expires
= ktime_add_ns(timer
->expires
, incr
* orun
);
304 if (timer
->expires
.tv64
> now
.tv64
)
307 * This (and the ktime_add() below) is the
308 * correction for exact:
312 timer
->expires
= ktime_add(timer
->expires
, interval
);
318 * enqueue_hrtimer - internal function to (re)start a timer
320 * The timer is inserted in expiry order. Insertion into the
321 * red black tree is O(log(n)). Must hold the base lock.
323 static void enqueue_hrtimer(struct hrtimer
*timer
, struct hrtimer_base
*base
)
325 struct rb_node
**link
= &base
->active
.rb_node
;
326 struct rb_node
*parent
= NULL
;
327 struct hrtimer
*entry
;
330 * Find the right place in the rbtree:
334 entry
= rb_entry(parent
, struct hrtimer
, node
);
336 * We dont care about collisions. Nodes with
337 * the same expiry time stay together.
339 if (timer
->expires
.tv64
< entry
->expires
.tv64
)
340 link
= &(*link
)->rb_left
;
342 link
= &(*link
)->rb_right
;
346 * Insert the timer to the rbtree and check whether it
347 * replaces the first pending timer
349 rb_link_node(&timer
->node
, parent
, link
);
350 rb_insert_color(&timer
->node
, &base
->active
);
352 timer
->state
= HRTIMER_PENDING
;
354 if (!base
->first
|| timer
->expires
.tv64
<
355 rb_entry(base
->first
, struct hrtimer
, node
)->expires
.tv64
)
356 base
->first
= &timer
->node
;
360 * __remove_hrtimer - internal function to remove a timer
362 * Caller must hold the base lock.
364 static void __remove_hrtimer(struct hrtimer
*timer
, struct hrtimer_base
*base
)
367 * Remove the timer from the rbtree and replace the
368 * first entry pointer if necessary.
370 if (base
->first
== &timer
->node
)
371 base
->first
= rb_next(&timer
->node
);
372 rb_erase(&timer
->node
, &base
->active
);
376 * remove hrtimer, called with base lock held
379 remove_hrtimer(struct hrtimer
*timer
, struct hrtimer_base
*base
)
381 if (hrtimer_active(timer
)) {
382 __remove_hrtimer(timer
, base
);
383 timer
->state
= HRTIMER_INACTIVE
;
390 * hrtimer_start - (re)start an relative timer on the current CPU
392 * @timer: the timer to be added
394 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
398 * 1 when the timer was active
401 hrtimer_start(struct hrtimer
*timer
, ktime_t tim
, const enum hrtimer_mode mode
)
403 struct hrtimer_base
*base
, *new_base
;
407 base
= lock_hrtimer_base(timer
, &flags
);
409 /* Remove an active timer from the queue: */
410 ret
= remove_hrtimer(timer
, base
);
412 /* Switch the timer base, if necessary: */
413 new_base
= switch_hrtimer_base(timer
, base
);
415 if (mode
== HRTIMER_REL
)
416 tim
= ktime_add(tim
, new_base
->get_time());
417 timer
->expires
= tim
;
419 enqueue_hrtimer(timer
, new_base
);
421 unlock_hrtimer_base(timer
, &flags
);
427 * hrtimer_try_to_cancel - try to deactivate a timer
429 * @timer: hrtimer to stop
432 * 0 when the timer was not active
433 * 1 when the timer was active
434 * -1 when the timer is currently excuting the callback function and
437 int hrtimer_try_to_cancel(struct hrtimer
*timer
)
439 struct hrtimer_base
*base
;
443 base
= lock_hrtimer_base(timer
, &flags
);
445 if (base
->curr_timer
!= timer
)
446 ret
= remove_hrtimer(timer
, base
);
448 unlock_hrtimer_base(timer
, &flags
);
455 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
457 * @timer: the timer to be cancelled
460 * 0 when the timer was not active
461 * 1 when the timer was active
463 int hrtimer_cancel(struct hrtimer
*timer
)
466 int ret
= hrtimer_try_to_cancel(timer
);
474 * hrtimer_get_remaining - get remaining time for the timer
476 * @timer: the timer to read
478 ktime_t
hrtimer_get_remaining(const struct hrtimer
*timer
)
480 struct hrtimer_base
*base
;
484 base
= lock_hrtimer_base(timer
, &flags
);
485 rem
= ktime_sub(timer
->expires
, timer
->base
->get_time());
486 unlock_hrtimer_base(timer
, &flags
);
492 * hrtimer_init - initialize a timer to the given clock
494 * @timer: the timer to be initialized
495 * @clock_id: the clock to be used
496 * @mode: timer mode abs/rel
498 void hrtimer_init(struct hrtimer
*timer
, clockid_t clock_id
,
499 enum hrtimer_mode mode
)
501 struct hrtimer_base
*bases
;
503 memset(timer
, 0, sizeof(struct hrtimer
));
505 bases
= per_cpu(hrtimer_bases
, raw_smp_processor_id());
507 if (clock_id
== CLOCK_REALTIME
&& mode
!= HRTIMER_ABS
)
508 clock_id
= CLOCK_MONOTONIC
;
510 timer
->base
= &bases
[clock_id
];
514 * hrtimer_get_res - get the timer resolution for a clock
516 * @which_clock: which clock to query
517 * @tp: pointer to timespec variable to store the resolution
519 * Store the resolution of the clock selected by which_clock in the
520 * variable pointed to by tp.
522 int hrtimer_get_res(const clockid_t which_clock
, struct timespec
*tp
)
524 struct hrtimer_base
*bases
;
526 bases
= per_cpu(hrtimer_bases
, raw_smp_processor_id());
527 *tp
= ktime_to_timespec(bases
[which_clock
].resolution
);
533 * Expire the per base hrtimer-queue:
535 static inline void run_hrtimer_queue(struct hrtimer_base
*base
)
537 ktime_t now
= base
->get_time();
538 struct rb_node
*node
;
540 spin_lock_irq(&base
->lock
);
542 while ((node
= base
->first
)) {
543 struct hrtimer
*timer
;
548 timer
= rb_entry(node
, struct hrtimer
, node
);
549 if (now
.tv64
<= timer
->expires
.tv64
)
552 fn
= timer
->function
;
554 set_curr_timer(base
, timer
);
555 timer
->state
= HRTIMER_RUNNING
;
556 __remove_hrtimer(timer
, base
);
557 spin_unlock_irq(&base
->lock
);
560 * fn == NULL is special case for the simplest timer
561 * variant - wake up process and do not restart:
564 wake_up_process(data
);
565 restart
= HRTIMER_NORESTART
;
569 spin_lock_irq(&base
->lock
);
571 /* Another CPU has added back the timer */
572 if (timer
->state
!= HRTIMER_RUNNING
)
575 if (restart
== HRTIMER_RESTART
)
576 enqueue_hrtimer(timer
, base
);
578 timer
->state
= HRTIMER_EXPIRED
;
580 set_curr_timer(base
, NULL
);
581 spin_unlock_irq(&base
->lock
);
585 * Called from timer softirq every jiffy, expire hrtimers:
587 void hrtimer_run_queues(void)
589 struct hrtimer_base
*base
= __get_cpu_var(hrtimer_bases
);
592 for (i
= 0; i
< MAX_HRTIMER_BASES
; i
++)
593 run_hrtimer_queue(&base
[i
]);
597 * Sleep related functions:
601 * schedule_hrtimer - sleep until timeout
603 * @timer: hrtimer variable initialized with the correct clock base
604 * @mode: timeout value is abs/rel
606 * Make the current task sleep until @timeout is
609 * You can set the task state as follows -
611 * %TASK_UNINTERRUPTIBLE - at least @timeout is guaranteed to
612 * pass before the routine returns. The routine will return 0
614 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
615 * delivered to the current task. In this case the remaining time
618 * The current task state is guaranteed to be TASK_RUNNING when this
621 static ktime_t __sched
622 schedule_hrtimer(struct hrtimer
*timer
, const enum hrtimer_mode mode
)
624 /* fn stays NULL, meaning single-shot wakeup: */
625 timer
->data
= current
;
627 hrtimer_start(timer
, timer
->expires
, mode
);
630 hrtimer_cancel(timer
);
632 /* Return the remaining time: */
633 if (timer
->state
!= HRTIMER_EXPIRED
)
634 return ktime_sub(timer
->expires
, timer
->base
->get_time());
636 return (ktime_t
) {.tv64
= 0 };
639 static inline ktime_t __sched
640 schedule_hrtimer_interruptible(struct hrtimer
*timer
,
641 const enum hrtimer_mode mode
)
643 set_current_state(TASK_INTERRUPTIBLE
);
645 return schedule_hrtimer(timer
, mode
);
648 static long __sched
nanosleep_restart(struct restart_block
*restart
)
650 struct timespec __user
*rmtp
;
652 void *rfn_save
= restart
->fn
;
653 struct hrtimer timer
;
656 restart
->fn
= do_no_restart_syscall
;
658 hrtimer_init(&timer
, (clockid_t
) restart
->arg3
, HRTIMER_ABS
);
660 timer
.expires
.tv64
= ((u64
)restart
->arg1
<< 32) | (u64
) restart
->arg0
;
662 rem
= schedule_hrtimer_interruptible(&timer
, HRTIMER_ABS
);
667 rmtp
= (struct timespec __user
*) restart
->arg2
;
668 tu
= ktime_to_timespec(rem
);
669 if (rmtp
&& copy_to_user(rmtp
, &tu
, sizeof(tu
)))
672 restart
->fn
= rfn_save
;
674 /* The other values in restart are already filled in */
675 return -ERESTART_RESTARTBLOCK
;
678 long hrtimer_nanosleep(struct timespec
*rqtp
, struct timespec __user
*rmtp
,
679 const enum hrtimer_mode mode
, const clockid_t clockid
)
681 struct restart_block
*restart
;
682 struct hrtimer timer
;
686 hrtimer_init(&timer
, clockid
, mode
);
688 timer
.expires
= timespec_to_ktime(*rqtp
);
690 rem
= schedule_hrtimer_interruptible(&timer
, mode
);
694 /* Absolute timers do not update the rmtp value and restart: */
695 if (mode
== HRTIMER_ABS
)
696 return -ERESTARTNOHAND
;
698 tu
= ktime_to_timespec(rem
);
700 if (rmtp
&& copy_to_user(rmtp
, &tu
, sizeof(tu
)))
703 restart
= ¤t_thread_info()->restart_block
;
704 restart
->fn
= nanosleep_restart
;
705 restart
->arg0
= timer
.expires
.tv64
& 0xFFFFFFFF;
706 restart
->arg1
= timer
.expires
.tv64
>> 32;
707 restart
->arg2
= (unsigned long) rmtp
;
708 restart
->arg3
= (unsigned long) timer
.base
->index
;
710 return -ERESTART_RESTARTBLOCK
;
714 sys_nanosleep(struct timespec __user
*rqtp
, struct timespec __user
*rmtp
)
718 if (copy_from_user(&tu
, rqtp
, sizeof(tu
)))
721 if (!timespec_valid(&tu
))
724 return hrtimer_nanosleep(&tu
, rmtp
, HRTIMER_REL
, CLOCK_MONOTONIC
);
728 * Functions related to boot-time initialization:
730 static void __devinit
init_hrtimers_cpu(int cpu
)
732 struct hrtimer_base
*base
= per_cpu(hrtimer_bases
, cpu
);
735 for (i
= 0; i
< MAX_HRTIMER_BASES
; i
++, base
++)
736 spin_lock_init(&base
->lock
);
739 #ifdef CONFIG_HOTPLUG_CPU
741 static void migrate_hrtimer_list(struct hrtimer_base
*old_base
,
742 struct hrtimer_base
*new_base
)
744 struct hrtimer
*timer
;
745 struct rb_node
*node
;
747 while ((node
= rb_first(&old_base
->active
))) {
748 timer
= rb_entry(node
, struct hrtimer
, node
);
749 __remove_hrtimer(timer
, old_base
);
750 timer
->base
= new_base
;
751 enqueue_hrtimer(timer
, new_base
);
755 static void migrate_hrtimers(int cpu
)
757 struct hrtimer_base
*old_base
, *new_base
;
760 BUG_ON(cpu_online(cpu
));
761 old_base
= per_cpu(hrtimer_bases
, cpu
);
762 new_base
= get_cpu_var(hrtimer_bases
);
766 for (i
= 0; i
< MAX_HRTIMER_BASES
; i
++) {
768 spin_lock(&new_base
->lock
);
769 spin_lock(&old_base
->lock
);
771 BUG_ON(old_base
->curr_timer
);
773 migrate_hrtimer_list(old_base
, new_base
);
775 spin_unlock(&old_base
->lock
);
776 spin_unlock(&new_base
->lock
);
782 put_cpu_var(hrtimer_bases
);
784 #endif /* CONFIG_HOTPLUG_CPU */
786 static int __devinit
hrtimer_cpu_notify(struct notifier_block
*self
,
787 unsigned long action
, void *hcpu
)
789 long cpu
= (long)hcpu
;
794 init_hrtimers_cpu(cpu
);
797 #ifdef CONFIG_HOTPLUG_CPU
799 migrate_hrtimers(cpu
);
810 static struct notifier_block __devinitdata hrtimers_nb
= {
811 .notifier_call
= hrtimer_cpu_notify
,
814 void __init
hrtimers_init(void)
816 hrtimer_cpu_notify(&hrtimers_nb
, (unsigned long)CPU_UP_PREPARE
,
817 (void *)(long)smp_processor_id());
818 register_cpu_notifier(&hrtimers_nb
);