hrtimer: migration: do not check expiry time on current CPU
[linux-2.6-block.git] / kernel / hrtimer.c
CommitLineData
c0a31329
TG
1/*
2 * linux/kernel/hrtimer.c
3 *
3c8aa39d 4 * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
79bf2bb3 5 * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
54cdfdb4 6 * Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner
c0a31329
TG
7 *
8 * High-resolution kernel timers
9 *
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.
13 *
14 * These timers are currently used for:
15 * - itimers
16 * - POSIX timers
17 * - nanosleep
18 * - precise in-kernel timing
19 *
20 * Started by: Thomas Gleixner and Ingo Molnar
21 *
22 * Credits:
23 * based on kernel/timer.c
24 *
66188fae
TG
25 * Help, testing, suggestions, bugfixes, improvements were
26 * provided by:
27 *
28 * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
29 * et. al.
30 *
c0a31329
TG
31 * For licencing details see kernel-base/COPYING
32 */
33
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>
54cdfdb4 40#include <linux/kallsyms.h>
c0a31329 41#include <linux/interrupt.h>
79bf2bb3 42#include <linux/tick.h>
54cdfdb4
TG
43#include <linux/seq_file.h>
44#include <linux/err.h>
237fc6e7 45#include <linux/debugobjects.h>
eea08f32
AB
46#include <linux/sched.h>
47#include <linux/timer.h>
c0a31329
TG
48
49#include <asm/uaccess.h>
50
51/**
52 * ktime_get - get the monotonic time in ktime_t format
53 *
54 * returns the time in ktime_t format
55 */
d316c57f 56ktime_t ktime_get(void)
c0a31329
TG
57{
58 struct timespec now;
59
60 ktime_get_ts(&now);
61
62 return timespec_to_ktime(now);
63}
641b9e0e 64EXPORT_SYMBOL_GPL(ktime_get);
c0a31329
TG
65
66/**
67 * ktime_get_real - get the real (wall-) time in ktime_t format
68 *
69 * returns the time in ktime_t format
70 */
d316c57f 71ktime_t ktime_get_real(void)
c0a31329
TG
72{
73 struct timespec now;
74
75 getnstimeofday(&now);
76
77 return timespec_to_ktime(now);
78}
79
80EXPORT_SYMBOL_GPL(ktime_get_real);
81
82/*
83 * The timer bases:
7978672c
GA
84 *
85 * Note: If we want to add new timer bases, we have to skip the two
86 * clock ids captured by the cpu-timers. We do this by holding empty
87 * entries rather than doing math adjustment of the clock ids.
88 * This ensures that we capture erroneous accesses to these clock ids
89 * rather than moving them into the range of valid clock id's.
c0a31329 90 */
54cdfdb4 91DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
c0a31329 92{
3c8aa39d
TG
93
94 .clock_base =
c0a31329 95 {
3c8aa39d
TG
96 {
97 .index = CLOCK_REALTIME,
98 .get_time = &ktime_get_real,
54cdfdb4 99 .resolution = KTIME_LOW_RES,
3c8aa39d
TG
100 },
101 {
102 .index = CLOCK_MONOTONIC,
103 .get_time = &ktime_get,
54cdfdb4 104 .resolution = KTIME_LOW_RES,
3c8aa39d
TG
105 },
106 }
c0a31329
TG
107};
108
109/**
110 * ktime_get_ts - get the monotonic clock in timespec format
c0a31329
TG
111 * @ts: pointer to timespec variable
112 *
113 * The function calculates the monotonic clock from the realtime
114 * clock and the wall_to_monotonic offset and stores the result
72fd4a35 115 * in normalized timespec format in the variable pointed to by @ts.
c0a31329
TG
116 */
117void ktime_get_ts(struct timespec *ts)
118{
119 struct timespec tomono;
120 unsigned long seq;
121
122 do {
123 seq = read_seqbegin(&xtime_lock);
124 getnstimeofday(ts);
125 tomono = wall_to_monotonic;
126
127 } while (read_seqretry(&xtime_lock, seq));
128
129 set_normalized_timespec(ts, ts->tv_sec + tomono.tv_sec,
130 ts->tv_nsec + tomono.tv_nsec);
131}
69778e32 132EXPORT_SYMBOL_GPL(ktime_get_ts);
c0a31329 133
92127c7a
TG
134/*
135 * Get the coarse grained time at the softirq based on xtime and
136 * wall_to_monotonic.
137 */
3c8aa39d 138static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
92127c7a
TG
139{
140 ktime_t xtim, tomono;
ad28d94a 141 struct timespec xts, tom;
92127c7a
TG
142 unsigned long seq;
143
144 do {
145 seq = read_seqbegin(&xtime_lock);
2c6b47de 146 xts = current_kernel_time();
ad28d94a 147 tom = wall_to_monotonic;
92127c7a
TG
148 } while (read_seqretry(&xtime_lock, seq));
149
f4304ab2 150 xtim = timespec_to_ktime(xts);
ad28d94a 151 tomono = timespec_to_ktime(tom);
3c8aa39d
TG
152 base->clock_base[CLOCK_REALTIME].softirq_time = xtim;
153 base->clock_base[CLOCK_MONOTONIC].softirq_time =
154 ktime_add(xtim, tomono);
92127c7a
TG
155}
156
c0a31329
TG
157/*
158 * Functions and macros which are different for UP/SMP systems are kept in a
159 * single place
160 */
161#ifdef CONFIG_SMP
162
c0a31329
TG
163/*
164 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
165 * means that all timers which are tied to this base via timer->base are
166 * locked, and the base itself is locked too.
167 *
168 * So __run_timers/migrate_timers can safely modify all timers which could
169 * be found on the lists/queues.
170 *
171 * When the timer's base is locked, and the timer removed from list, it is
172 * possible to set timer->base = NULL and drop the lock: the timer remains
173 * locked.
174 */
3c8aa39d
TG
175static
176struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
177 unsigned long *flags)
c0a31329 178{
3c8aa39d 179 struct hrtimer_clock_base *base;
c0a31329
TG
180
181 for (;;) {
182 base = timer->base;
183 if (likely(base != NULL)) {
3c8aa39d 184 spin_lock_irqsave(&base->cpu_base->lock, *flags);
c0a31329
TG
185 if (likely(base == timer->base))
186 return base;
187 /* The timer has migrated to another CPU: */
3c8aa39d 188 spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
c0a31329
TG
189 }
190 cpu_relax();
191 }
192}
193
194/*
195 * Switch the timer base to the current CPU when possible.
196 */
3c8aa39d 197static inline struct hrtimer_clock_base *
597d0275
AB
198switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
199 int pinned)
c0a31329 200{
3c8aa39d
TG
201 struct hrtimer_clock_base *new_base;
202 struct hrtimer_cpu_base *new_cpu_base;
eea08f32
AB
203 int cpu, preferred_cpu = -1;
204
205 cpu = smp_processor_id();
206#if defined(CONFIG_NO_HZ) && defined(CONFIG_SMP)
207 if (!pinned && get_sysctl_timer_migration() && idle_cpu(cpu)) {
208 preferred_cpu = get_nohz_load_balancer();
7e0c5086
TG
209 if (preferred_cpu >= 0) {
210 /*
211 * We must not check the expiry value when
212 * preferred_cpu is the current cpu. If base
213 * != new_base we would loop forever when the
214 * timer expires before the current programmed
215 * next timer event.
216 */
217 if (preferred_cpu != cpu)
218 cpu = preferred_cpu;
219 else
220 preferred_cpu = -1;
221 }
eea08f32
AB
222 }
223#endif
c0a31329 224
eea08f32
AB
225again:
226 new_cpu_base = &per_cpu(hrtimer_bases, cpu);
3c8aa39d 227 new_base = &new_cpu_base->clock_base[base->index];
c0a31329
TG
228
229 if (base != new_base) {
230 /*
231 * We are trying to schedule the timer on the local CPU.
232 * However we can't change timer's base while it is running,
233 * so we keep it on the same CPU. No hassle vs. reprogramming
234 * the event source in the high resolution case. The softirq
235 * code will take care of this when the timer function has
236 * completed. There is no conflict as we hold the lock until
237 * the timer is enqueued.
238 */
54cdfdb4 239 if (unlikely(hrtimer_callback_running(timer)))
c0a31329
TG
240 return base;
241
242 /* See the comment in lock_timer_base() */
243 timer->base = NULL;
3c8aa39d
TG
244 spin_unlock(&base->cpu_base->lock);
245 spin_lock(&new_base->cpu_base->lock);
eea08f32
AB
246
247 /* Optimized away for NOHZ=n SMP=n */
248 if (cpu == preferred_cpu) {
249 /* Calculate clock monotonic expiry time */
250#ifdef CONFIG_HIGH_RES_TIMERS
251 ktime_t expires = ktime_sub(hrtimer_get_expires(timer),
252 new_base->offset);
253#else
254 ktime_t expires = hrtimer_get_expires(timer);
255#endif
256
257 /*
258 * Get the next event on target cpu from the
259 * clock events layer.
260 * This covers the highres=off nohz=on case as well.
261 */
262 ktime_t next = clockevents_get_next_event(cpu);
263
264 ktime_t delta = ktime_sub(expires, next);
265
266 /*
267 * We do not migrate the timer when it is expiring
268 * before the next event on the target cpu because
269 * we cannot reprogram the target cpu hardware and
270 * we would cause it to fire late.
271 */
272 if (delta.tv64 < 0) {
273 cpu = smp_processor_id();
274 spin_unlock(&new_base->cpu_base->lock);
275 spin_lock(&base->cpu_base->lock);
276 timer->base = base;
277 goto again;
278 }
279 }
c0a31329
TG
280 timer->base = new_base;
281 }
282 return new_base;
283}
284
285#else /* CONFIG_SMP */
286
3c8aa39d 287static inline struct hrtimer_clock_base *
c0a31329
TG
288lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
289{
3c8aa39d 290 struct hrtimer_clock_base *base = timer->base;
c0a31329 291
3c8aa39d 292 spin_lock_irqsave(&base->cpu_base->lock, *flags);
c0a31329
TG
293
294 return base;
295}
296
eea08f32 297# define switch_hrtimer_base(t, b, p) (b)
c0a31329
TG
298
299#endif /* !CONFIG_SMP */
300
301/*
302 * Functions for the union type storage format of ktime_t which are
303 * too large for inlining:
304 */
305#if BITS_PER_LONG < 64
306# ifndef CONFIG_KTIME_SCALAR
307/**
308 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
c0a31329
TG
309 * @kt: addend
310 * @nsec: the scalar nsec value to add
311 *
312 * Returns the sum of kt and nsec in ktime_t format
313 */
314ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
315{
316 ktime_t tmp;
317
318 if (likely(nsec < NSEC_PER_SEC)) {
319 tmp.tv64 = nsec;
320 } else {
321 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
322
323 tmp = ktime_set((long)nsec, rem);
324 }
325
326 return ktime_add(kt, tmp);
327}
b8b8fd2d
DH
328
329EXPORT_SYMBOL_GPL(ktime_add_ns);
a272378d
ACM
330
331/**
332 * ktime_sub_ns - Subtract a scalar nanoseconds value from a ktime_t variable
333 * @kt: minuend
334 * @nsec: the scalar nsec value to subtract
335 *
336 * Returns the subtraction of @nsec from @kt in ktime_t format
337 */
338ktime_t ktime_sub_ns(const ktime_t kt, u64 nsec)
339{
340 ktime_t tmp;
341
342 if (likely(nsec < NSEC_PER_SEC)) {
343 tmp.tv64 = nsec;
344 } else {
345 unsigned long rem = do_div(nsec, NSEC_PER_SEC);
346
347 tmp = ktime_set((long)nsec, rem);
348 }
349
350 return ktime_sub(kt, tmp);
351}
352
353EXPORT_SYMBOL_GPL(ktime_sub_ns);
c0a31329
TG
354# endif /* !CONFIG_KTIME_SCALAR */
355
356/*
357 * Divide a ktime value by a nanosecond value
358 */
4d672e7a 359u64 ktime_divns(const ktime_t kt, s64 div)
c0a31329 360{
900cfa46 361 u64 dclc;
c0a31329
TG
362 int sft = 0;
363
900cfa46 364 dclc = ktime_to_ns(kt);
c0a31329
TG
365 /* Make sure the divisor is less than 2^32: */
366 while (div >> 32) {
367 sft++;
368 div >>= 1;
369 }
370 dclc >>= sft;
371 do_div(dclc, (unsigned long) div);
372
4d672e7a 373 return dclc;
c0a31329 374}
c0a31329
TG
375#endif /* BITS_PER_LONG >= 64 */
376
5a7780e7
TG
377/*
378 * Add two ktime values and do a safety check for overflow:
379 */
380ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
381{
382 ktime_t res = ktime_add(lhs, rhs);
383
384 /*
385 * We use KTIME_SEC_MAX here, the maximum timeout which we can
386 * return to user space in a timespec:
387 */
388 if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
389 res = ktime_set(KTIME_SEC_MAX, 0);
390
391 return res;
392}
393
8daa21e6
AB
394EXPORT_SYMBOL_GPL(ktime_add_safe);
395
237fc6e7
TG
396#ifdef CONFIG_DEBUG_OBJECTS_TIMERS
397
398static struct debug_obj_descr hrtimer_debug_descr;
399
400/*
401 * fixup_init is called when:
402 * - an active object is initialized
403 */
404static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
405{
406 struct hrtimer *timer = addr;
407
408 switch (state) {
409 case ODEBUG_STATE_ACTIVE:
410 hrtimer_cancel(timer);
411 debug_object_init(timer, &hrtimer_debug_descr);
412 return 1;
413 default:
414 return 0;
415 }
416}
417
418/*
419 * fixup_activate is called when:
420 * - an active object is activated
421 * - an unknown object is activated (might be a statically initialized object)
422 */
423static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
424{
425 switch (state) {
426
427 case ODEBUG_STATE_NOTAVAILABLE:
428 WARN_ON_ONCE(1);
429 return 0;
430
431 case ODEBUG_STATE_ACTIVE:
432 WARN_ON(1);
433
434 default:
435 return 0;
436 }
437}
438
439/*
440 * fixup_free is called when:
441 * - an active object is freed
442 */
443static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
444{
445 struct hrtimer *timer = addr;
446
447 switch (state) {
448 case ODEBUG_STATE_ACTIVE:
449 hrtimer_cancel(timer);
450 debug_object_free(timer, &hrtimer_debug_descr);
451 return 1;
452 default:
453 return 0;
454 }
455}
456
457static struct debug_obj_descr hrtimer_debug_descr = {
458 .name = "hrtimer",
459 .fixup_init = hrtimer_fixup_init,
460 .fixup_activate = hrtimer_fixup_activate,
461 .fixup_free = hrtimer_fixup_free,
462};
463
464static inline void debug_hrtimer_init(struct hrtimer *timer)
465{
466 debug_object_init(timer, &hrtimer_debug_descr);
467}
468
469static inline void debug_hrtimer_activate(struct hrtimer *timer)
470{
471 debug_object_activate(timer, &hrtimer_debug_descr);
472}
473
474static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
475{
476 debug_object_deactivate(timer, &hrtimer_debug_descr);
477}
478
479static inline void debug_hrtimer_free(struct hrtimer *timer)
480{
481 debug_object_free(timer, &hrtimer_debug_descr);
482}
483
484static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
485 enum hrtimer_mode mode);
486
487void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
488 enum hrtimer_mode mode)
489{
490 debug_object_init_on_stack(timer, &hrtimer_debug_descr);
491 __hrtimer_init(timer, clock_id, mode);
492}
493
494void destroy_hrtimer_on_stack(struct hrtimer *timer)
495{
496 debug_object_free(timer, &hrtimer_debug_descr);
497}
498
499#else
500static inline void debug_hrtimer_init(struct hrtimer *timer) { }
501static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
502static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
503#endif
504
54cdfdb4
TG
505/* High resolution timer related functions */
506#ifdef CONFIG_HIGH_RES_TIMERS
507
508/*
509 * High resolution timer enabled ?
510 */
511static int hrtimer_hres_enabled __read_mostly = 1;
512
513/*
514 * Enable / Disable high resolution mode
515 */
516static int __init setup_hrtimer_hres(char *str)
517{
518 if (!strcmp(str, "off"))
519 hrtimer_hres_enabled = 0;
520 else if (!strcmp(str, "on"))
521 hrtimer_hres_enabled = 1;
522 else
523 return 0;
524 return 1;
525}
526
527__setup("highres=", setup_hrtimer_hres);
528
529/*
530 * hrtimer_high_res_enabled - query, if the highres mode is enabled
531 */
532static inline int hrtimer_is_hres_enabled(void)
533{
534 return hrtimer_hres_enabled;
535}
536
537/*
538 * Is the high resolution mode active ?
539 */
540static inline int hrtimer_hres_active(void)
541{
542 return __get_cpu_var(hrtimer_bases).hres_active;
543}
544
545/*
546 * Reprogram the event source with checking both queues for the
547 * next event
548 * Called with interrupts disabled and base->lock held
549 */
550static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
551{
552 int i;
553 struct hrtimer_clock_base *base = cpu_base->clock_base;
554 ktime_t expires;
555
556 cpu_base->expires_next.tv64 = KTIME_MAX;
557
558 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
559 struct hrtimer *timer;
560
561 if (!base->first)
562 continue;
563 timer = rb_entry(base->first, struct hrtimer, node);
cc584b21 564 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
b0a9b511
TG
565 /*
566 * clock_was_set() has changed base->offset so the
567 * result might be negative. Fix it up to prevent a
568 * false positive in clockevents_program_event()
569 */
570 if (expires.tv64 < 0)
571 expires.tv64 = 0;
54cdfdb4
TG
572 if (expires.tv64 < cpu_base->expires_next.tv64)
573 cpu_base->expires_next = expires;
574 }
575
576 if (cpu_base->expires_next.tv64 != KTIME_MAX)
577 tick_program_event(cpu_base->expires_next, 1);
578}
579
580/*
581 * Shared reprogramming for clock_realtime and clock_monotonic
582 *
583 * When a timer is enqueued and expires earlier than the already enqueued
584 * timers, we have to check, whether it expires earlier than the timer for
585 * which the clock event device was armed.
586 *
587 * Called with interrupts disabled and base->cpu_base.lock held
588 */
589static int hrtimer_reprogram(struct hrtimer *timer,
590 struct hrtimer_clock_base *base)
591{
592 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
cc584b21 593 ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
54cdfdb4
TG
594 int res;
595
cc584b21 596 WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
63070a79 597
54cdfdb4
TG
598 /*
599 * When the callback is running, we do not reprogram the clock event
600 * device. The timer callback is either running on a different CPU or
3a4fa0a2 601 * the callback is executed in the hrtimer_interrupt context. The
54cdfdb4
TG
602 * reprogramming is handled either by the softirq, which called the
603 * callback or at the end of the hrtimer_interrupt.
604 */
605 if (hrtimer_callback_running(timer))
606 return 0;
607
63070a79
TG
608 /*
609 * CLOCK_REALTIME timer might be requested with an absolute
610 * expiry time which is less than base->offset. Nothing wrong
611 * about that, just avoid to call into the tick code, which
612 * has now objections against negative expiry values.
613 */
614 if (expires.tv64 < 0)
615 return -ETIME;
616
54cdfdb4
TG
617 if (expires.tv64 >= expires_next->tv64)
618 return 0;
619
620 /*
621 * Clockevents returns -ETIME, when the event was in the past.
622 */
623 res = tick_program_event(expires, 0);
624 if (!IS_ERR_VALUE(res))
625 *expires_next = expires;
626 return res;
627}
628
629
630/*
631 * Retrigger next event is called after clock was set
632 *
633 * Called with interrupts disabled via on_each_cpu()
634 */
635static void retrigger_next_event(void *arg)
636{
637 struct hrtimer_cpu_base *base;
638 struct timespec realtime_offset;
639 unsigned long seq;
640
641 if (!hrtimer_hres_active())
642 return;
643
644 do {
645 seq = read_seqbegin(&xtime_lock);
646 set_normalized_timespec(&realtime_offset,
647 -wall_to_monotonic.tv_sec,
648 -wall_to_monotonic.tv_nsec);
649 } while (read_seqretry(&xtime_lock, seq));
650
651 base = &__get_cpu_var(hrtimer_bases);
652
653 /* Adjust CLOCK_REALTIME offset */
654 spin_lock(&base->lock);
655 base->clock_base[CLOCK_REALTIME].offset =
656 timespec_to_ktime(realtime_offset);
657
658 hrtimer_force_reprogram(base);
659 spin_unlock(&base->lock);
660}
661
662/*
663 * Clock realtime was set
664 *
665 * Change the offset of the realtime clock vs. the monotonic
666 * clock.
667 *
668 * We might have to reprogram the high resolution timer interrupt. On
669 * SMP we call the architecture specific code to retrigger _all_ high
670 * resolution timer interrupts. On UP we just disable interrupts and
671 * call the high resolution interrupt code.
672 */
673void clock_was_set(void)
674{
675 /* Retrigger the CPU local events everywhere */
15c8b6c1 676 on_each_cpu(retrigger_next_event, NULL, 1);
54cdfdb4
TG
677}
678
995f054f
IM
679/*
680 * During resume we might have to reprogram the high resolution timer
681 * interrupt (on the local CPU):
682 */
683void hres_timers_resume(void)
684{
1d4a7f1c
PZ
685 WARN_ONCE(!irqs_disabled(),
686 KERN_INFO "hres_timers_resume() called with IRQs enabled!");
687
995f054f
IM
688 retrigger_next_event(NULL);
689}
690
54cdfdb4
TG
691/*
692 * Initialize the high resolution related parts of cpu_base
693 */
694static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
695{
696 base->expires_next.tv64 = KTIME_MAX;
697 base->hres_active = 0;
54cdfdb4
TG
698}
699
700/*
701 * Initialize the high resolution related parts of a hrtimer
702 */
703static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
704{
54cdfdb4
TG
705}
706
ca109491 707
54cdfdb4
TG
708/*
709 * When High resolution timers are active, try to reprogram. Note, that in case
710 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
711 * check happens. The timer gets enqueued into the rbtree. The reprogramming
712 * and expiry check is done in the hrtimer_interrupt or in the softirq.
713 */
714static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
7f1e2ca9
PZ
715 struct hrtimer_clock_base *base,
716 int wakeup)
54cdfdb4
TG
717{
718 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
7f1e2ca9
PZ
719 if (wakeup) {
720 spin_unlock(&base->cpu_base->lock);
721 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
722 spin_lock(&base->cpu_base->lock);
723 } else
724 __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
725
ca109491 726 return 1;
54cdfdb4 727 }
7f1e2ca9 728
54cdfdb4
TG
729 return 0;
730}
731
732/*
733 * Switch to high resolution mode
734 */
f8953856 735static int hrtimer_switch_to_hres(void)
54cdfdb4 736{
820de5c3
IM
737 int cpu = smp_processor_id();
738 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
54cdfdb4
TG
739 unsigned long flags;
740
741 if (base->hres_active)
f8953856 742 return 1;
54cdfdb4
TG
743
744 local_irq_save(flags);
745
746 if (tick_init_highres()) {
747 local_irq_restore(flags);
820de5c3
IM
748 printk(KERN_WARNING "Could not switch to high resolution "
749 "mode on CPU %d\n", cpu);
f8953856 750 return 0;
54cdfdb4
TG
751 }
752 base->hres_active = 1;
753 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
754 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
755
756 tick_setup_sched_timer();
757
758 /* "Retrigger" the interrupt to get things going */
759 retrigger_next_event(NULL);
760 local_irq_restore(flags);
edfed66e 761 printk(KERN_DEBUG "Switched to high resolution mode on CPU %d\n",
54cdfdb4 762 smp_processor_id());
f8953856 763 return 1;
54cdfdb4
TG
764}
765
766#else
767
768static inline int hrtimer_hres_active(void) { return 0; }
769static inline int hrtimer_is_hres_enabled(void) { return 0; }
f8953856 770static inline int hrtimer_switch_to_hres(void) { return 0; }
54cdfdb4
TG
771static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
772static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
7f1e2ca9
PZ
773 struct hrtimer_clock_base *base,
774 int wakeup)
54cdfdb4
TG
775{
776 return 0;
777}
54cdfdb4
TG
778static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
779static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
780
781#endif /* CONFIG_HIGH_RES_TIMERS */
782
82f67cd9
IM
783#ifdef CONFIG_TIMER_STATS
784void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
785{
786 if (timer->start_site)
787 return;
788
789 timer->start_site = addr;
790 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
791 timer->start_pid = current->pid;
792}
793#endif
794
c0a31329 795/*
6506f2aa 796 * Counterpart to lock_hrtimer_base above:
c0a31329
TG
797 */
798static inline
799void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
800{
3c8aa39d 801 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
c0a31329
TG
802}
803
804/**
805 * hrtimer_forward - forward the timer expiry
c0a31329 806 * @timer: hrtimer to forward
44f21475 807 * @now: forward past this time
c0a31329
TG
808 * @interval: the interval to forward
809 *
810 * Forward the timer expiry so it will expire in the future.
8dca6f33 811 * Returns the number of overruns.
c0a31329 812 */
4d672e7a 813u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
c0a31329 814{
4d672e7a 815 u64 orun = 1;
44f21475 816 ktime_t delta;
c0a31329 817
cc584b21 818 delta = ktime_sub(now, hrtimer_get_expires(timer));
c0a31329
TG
819
820 if (delta.tv64 < 0)
821 return 0;
822
c9db4fa1
TG
823 if (interval.tv64 < timer->base->resolution.tv64)
824 interval.tv64 = timer->base->resolution.tv64;
825
c0a31329 826 if (unlikely(delta.tv64 >= interval.tv64)) {
df869b63 827 s64 incr = ktime_to_ns(interval);
c0a31329
TG
828
829 orun = ktime_divns(delta, incr);
cc584b21
AV
830 hrtimer_add_expires_ns(timer, incr * orun);
831 if (hrtimer_get_expires_tv64(timer) > now.tv64)
c0a31329
TG
832 return orun;
833 /*
834 * This (and the ktime_add() below) is the
835 * correction for exact:
836 */
837 orun++;
838 }
cc584b21 839 hrtimer_add_expires(timer, interval);
c0a31329
TG
840
841 return orun;
842}
6bdb6b62 843EXPORT_SYMBOL_GPL(hrtimer_forward);
c0a31329
TG
844
845/*
846 * enqueue_hrtimer - internal function to (re)start a timer
847 *
848 * The timer is inserted in expiry order. Insertion into the
849 * red black tree is O(log(n)). Must hold the base lock.
a6037b61
PZ
850 *
851 * Returns 1 when the new timer is the leftmost timer in the tree.
c0a31329 852 */
a6037b61
PZ
853static int enqueue_hrtimer(struct hrtimer *timer,
854 struct hrtimer_clock_base *base)
c0a31329
TG
855{
856 struct rb_node **link = &base->active.rb_node;
c0a31329
TG
857 struct rb_node *parent = NULL;
858 struct hrtimer *entry;
99bc2fcb 859 int leftmost = 1;
c0a31329 860
237fc6e7
TG
861 debug_hrtimer_activate(timer);
862
c0a31329
TG
863 /*
864 * Find the right place in the rbtree:
865 */
866 while (*link) {
867 parent = *link;
868 entry = rb_entry(parent, struct hrtimer, node);
869 /*
870 * We dont care about collisions. Nodes with
871 * the same expiry time stay together.
872 */
cc584b21
AV
873 if (hrtimer_get_expires_tv64(timer) <
874 hrtimer_get_expires_tv64(entry)) {
c0a31329 875 link = &(*link)->rb_left;
99bc2fcb 876 } else {
c0a31329 877 link = &(*link)->rb_right;
99bc2fcb
IM
878 leftmost = 0;
879 }
c0a31329
TG
880 }
881
882 /*
288867ec
TG
883 * Insert the timer to the rbtree and check whether it
884 * replaces the first pending timer
c0a31329 885 */
a6037b61 886 if (leftmost)
54cdfdb4 887 base->first = &timer->node;
54cdfdb4 888
c0a31329
TG
889 rb_link_node(&timer->node, parent, link);
890 rb_insert_color(&timer->node, &base->active);
303e967f
TG
891 /*
892 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
893 * state of a possibly running callback.
894 */
895 timer->state |= HRTIMER_STATE_ENQUEUED;
a6037b61
PZ
896
897 return leftmost;
288867ec 898}
c0a31329
TG
899
900/*
901 * __remove_hrtimer - internal function to remove a timer
902 *
903 * Caller must hold the base lock.
54cdfdb4
TG
904 *
905 * High resolution timer mode reprograms the clock event device when the
906 * timer is the one which expires next. The caller can disable this by setting
907 * reprogram to zero. This is useful, when the context does a reprogramming
908 * anyway (e.g. timer interrupt)
c0a31329 909 */
3c8aa39d 910static void __remove_hrtimer(struct hrtimer *timer,
303e967f 911 struct hrtimer_clock_base *base,
54cdfdb4 912 unsigned long newstate, int reprogram)
c0a31329 913{
ca109491 914 if (timer->state & HRTIMER_STATE_ENQUEUED) {
54cdfdb4
TG
915 /*
916 * Remove the timer from the rbtree and replace the
917 * first entry pointer if necessary.
918 */
919 if (base->first == &timer->node) {
920 base->first = rb_next(&timer->node);
921 /* Reprogram the clock event device. if enabled */
922 if (reprogram && hrtimer_hres_active())
923 hrtimer_force_reprogram(base->cpu_base);
924 }
925 rb_erase(&timer->node, &base->active);
926 }
303e967f 927 timer->state = newstate;
c0a31329
TG
928}
929
930/*
931 * remove hrtimer, called with base lock held
932 */
933static inline int
3c8aa39d 934remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
c0a31329 935{
303e967f 936 if (hrtimer_is_queued(timer)) {
54cdfdb4
TG
937 int reprogram;
938
939 /*
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.
946 */
237fc6e7 947 debug_hrtimer_deactivate(timer);
82f67cd9 948 timer_stats_hrtimer_clear_start_info(timer);
54cdfdb4
TG
949 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
950 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
951 reprogram);
c0a31329
TG
952 return 1;
953 }
954 return 0;
955}
956
7f1e2ca9
PZ
957int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
958 unsigned long delta_ns, const enum hrtimer_mode mode,
959 int wakeup)
c0a31329 960{
3c8aa39d 961 struct hrtimer_clock_base *base, *new_base;
c0a31329 962 unsigned long flags;
a6037b61 963 int ret, leftmost;
c0a31329
TG
964
965 base = lock_hrtimer_base(timer, &flags);
966
967 /* Remove an active timer from the queue: */
968 ret = remove_hrtimer(timer, base);
969
970 /* Switch the timer base, if necessary: */
597d0275 971 new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
c0a31329 972
597d0275 973 if (mode & HRTIMER_MODE_REL) {
5a7780e7 974 tim = ktime_add_safe(tim, new_base->get_time());
06027bdd
IM
975 /*
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.
981 */
982#ifdef CONFIG_TIME_LOW_RES
5a7780e7 983 tim = ktime_add_safe(tim, base->resolution);
06027bdd
IM
984#endif
985 }
237fc6e7 986
da8f2e17 987 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
c0a31329 988
82f67cd9
IM
989 timer_stats_hrtimer_set_start_info(timer);
990
a6037b61
PZ
991 leftmost = enqueue_hrtimer(timer, new_base);
992
935c631d
IM
993 /*
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)
a6037b61
PZ
996 *
997 * XXX send_remote_softirq() ?
935c631d 998 */
a6037b61 999 if (leftmost && new_base->cpu_base == &__get_cpu_var(hrtimer_bases))
7f1e2ca9 1000 hrtimer_enqueue_reprogram(timer, new_base, wakeup);
c0a31329
TG
1001
1002 unlock_hrtimer_base(timer, &flags);
1003
1004 return ret;
1005}
7f1e2ca9
PZ
1006
1007/**
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)
1013 *
1014 * Returns:
1015 * 0 on success
1016 * 1 when the timer was active
1017 */
1018int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1019 unsigned long delta_ns, const enum hrtimer_mode mode)
1020{
1021 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1022}
da8f2e17
AV
1023EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1024
1025/**
e1dd7bc5 1026 * hrtimer_start - (re)start an hrtimer on the current CPU
da8f2e17
AV
1027 * @timer: the timer to be added
1028 * @tim: expiry time
1029 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1030 *
1031 * Returns:
1032 * 0 on success
1033 * 1 when the timer was active
1034 */
1035int
1036hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1037{
7f1e2ca9 1038 return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
da8f2e17 1039}
8d16b764 1040EXPORT_SYMBOL_GPL(hrtimer_start);
c0a31329 1041
da8f2e17 1042
c0a31329
TG
1043/**
1044 * hrtimer_try_to_cancel - try to deactivate a timer
c0a31329
TG
1045 * @timer: hrtimer to stop
1046 *
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
fa9799e3 1051 * cannot be stopped
c0a31329
TG
1052 */
1053int hrtimer_try_to_cancel(struct hrtimer *timer)
1054{
3c8aa39d 1055 struct hrtimer_clock_base *base;
c0a31329
TG
1056 unsigned long flags;
1057 int ret = -1;
1058
1059 base = lock_hrtimer_base(timer, &flags);
1060
303e967f 1061 if (!hrtimer_callback_running(timer))
c0a31329
TG
1062 ret = remove_hrtimer(timer, base);
1063
1064 unlock_hrtimer_base(timer, &flags);
1065
1066 return ret;
1067
1068}
8d16b764 1069EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
c0a31329
TG
1070
1071/**
1072 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
c0a31329
TG
1073 * @timer: the timer to be cancelled
1074 *
1075 * Returns:
1076 * 0 when the timer was not active
1077 * 1 when the timer was active
1078 */
1079int hrtimer_cancel(struct hrtimer *timer)
1080{
1081 for (;;) {
1082 int ret = hrtimer_try_to_cancel(timer);
1083
1084 if (ret >= 0)
1085 return ret;
5ef37b19 1086 cpu_relax();
c0a31329
TG
1087 }
1088}
8d16b764 1089EXPORT_SYMBOL_GPL(hrtimer_cancel);
c0a31329
TG
1090
1091/**
1092 * hrtimer_get_remaining - get remaining time for the timer
c0a31329
TG
1093 * @timer: the timer to read
1094 */
1095ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1096{
3c8aa39d 1097 struct hrtimer_clock_base *base;
c0a31329
TG
1098 unsigned long flags;
1099 ktime_t rem;
1100
1101 base = lock_hrtimer_base(timer, &flags);
cc584b21 1102 rem = hrtimer_expires_remaining(timer);
c0a31329
TG
1103 unlock_hrtimer_base(timer, &flags);
1104
1105 return rem;
1106}
8d16b764 1107EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
c0a31329 1108
ee9c5785 1109#ifdef CONFIG_NO_HZ
69239749
TL
1110/**
1111 * hrtimer_get_next_event - get the time until next expiry event
1112 *
1113 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1114 * is pending.
1115 */
1116ktime_t hrtimer_get_next_event(void)
1117{
3c8aa39d
TG
1118 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1119 struct hrtimer_clock_base *base = cpu_base->clock_base;
69239749
TL
1120 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1121 unsigned long flags;
1122 int i;
1123
3c8aa39d
TG
1124 spin_lock_irqsave(&cpu_base->lock, flags);
1125
54cdfdb4
TG
1126 if (!hrtimer_hres_active()) {
1127 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1128 struct hrtimer *timer;
69239749 1129
54cdfdb4
TG
1130 if (!base->first)
1131 continue;
3c8aa39d 1132
54cdfdb4 1133 timer = rb_entry(base->first, struct hrtimer, node);
cc584b21 1134 delta.tv64 = hrtimer_get_expires_tv64(timer);
54cdfdb4
TG
1135 delta = ktime_sub(delta, base->get_time());
1136 if (delta.tv64 < mindelta.tv64)
1137 mindelta.tv64 = delta.tv64;
1138 }
69239749 1139 }
3c8aa39d
TG
1140
1141 spin_unlock_irqrestore(&cpu_base->lock, flags);
1142
69239749
TL
1143 if (mindelta.tv64 < 0)
1144 mindelta.tv64 = 0;
1145 return mindelta;
1146}
1147#endif
1148
237fc6e7
TG
1149static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1150 enum hrtimer_mode mode)
c0a31329 1151{
3c8aa39d 1152 struct hrtimer_cpu_base *cpu_base;
c0a31329 1153
7978672c
GA
1154 memset(timer, 0, sizeof(struct hrtimer));
1155
3c8aa39d 1156 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
c0a31329 1157
c9cb2e3d 1158 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
7978672c
GA
1159 clock_id = CLOCK_MONOTONIC;
1160
3c8aa39d 1161 timer->base = &cpu_base->clock_base[clock_id];
d3d74453 1162 INIT_LIST_HEAD(&timer->cb_entry);
54cdfdb4 1163 hrtimer_init_timer_hres(timer);
82f67cd9
IM
1164
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
c0a31329 1170}
237fc6e7
TG
1171
1172/**
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
1177 */
1178void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1179 enum hrtimer_mode mode)
1180{
1181 debug_hrtimer_init(timer);
1182 __hrtimer_init(timer, clock_id, mode);
1183}
8d16b764 1184EXPORT_SYMBOL_GPL(hrtimer_init);
c0a31329
TG
1185
1186/**
1187 * hrtimer_get_res - get the timer resolution for a clock
c0a31329
TG
1188 * @which_clock: which clock to query
1189 * @tp: pointer to timespec variable to store the resolution
1190 *
72fd4a35
RD
1191 * Store the resolution of the clock selected by @which_clock in the
1192 * variable pointed to by @tp.
c0a31329
TG
1193 */
1194int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1195{
3c8aa39d 1196 struct hrtimer_cpu_base *cpu_base;
c0a31329 1197
3c8aa39d
TG
1198 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1199 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
c0a31329
TG
1200
1201 return 0;
1202}
8d16b764 1203EXPORT_SYMBOL_GPL(hrtimer_get_res);
c0a31329 1204
d3d74453
PZ
1205static void __run_hrtimer(struct hrtimer *timer)
1206{
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;
1211
ca109491
PZ
1212 WARN_ON(!irqs_disabled());
1213
237fc6e7 1214 debug_hrtimer_deactivate(timer);
d3d74453
PZ
1215 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1216 timer_stats_account_hrtimer(timer);
d3d74453 1217 fn = timer->function;
ca109491
PZ
1218
1219 /*
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.
1223 */
1224 spin_unlock(&cpu_base->lock);
1225 restart = fn(timer);
1226 spin_lock(&cpu_base->lock);
d3d74453
PZ
1227
1228 /*
e3f1d883
TG
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()
d3d74453
PZ
1232 */
1233 if (restart != HRTIMER_NORESTART) {
1234 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
a6037b61 1235 enqueue_hrtimer(timer, base);
d3d74453
PZ
1236 }
1237 timer->state &= ~HRTIMER_STATE_CALLBACK;
1238}
1239
54cdfdb4
TG
1240#ifdef CONFIG_HIGH_RES_TIMERS
1241
7f22391c
FW
1242static int force_clock_reprogram;
1243
1244/*
1245 * After 5 iteration's attempts, we consider that hrtimer_interrupt()
1246 * is hanging, which could happen with something that slows the interrupt
1247 * such as the tracing. Then we force the clock reprogramming for each future
1248 * hrtimer interrupts to avoid infinite loops and use the min_delta_ns
1249 * threshold that we will overwrite.
1250 * The next tick event will be scheduled to 3 times we currently spend on
1251 * hrtimer_interrupt(). This gives a good compromise, the cpus will spend
1252 * 1/4 of their time to process the hrtimer interrupts. This is enough to
1253 * let it running without serious starvation.
1254 */
1255
1256static inline void
1257hrtimer_interrupt_hanging(struct clock_event_device *dev,
1258 ktime_t try_time)
1259{
1260 force_clock_reprogram = 1;
1261 dev->min_delta_ns = (unsigned long)try_time.tv64 * 3;
1262 printk(KERN_WARNING "hrtimer: interrupt too slow, "
1263 "forcing clock min delta to %lu ns\n", dev->min_delta_ns);
1264}
54cdfdb4
TG
1265/*
1266 * High resolution timer interrupt
1267 * Called with interrupts disabled
1268 */
1269void hrtimer_interrupt(struct clock_event_device *dev)
1270{
1271 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1272 struct hrtimer_clock_base *base;
1273 ktime_t expires_next, now;
7f22391c 1274 int nr_retries = 0;
ca109491 1275 int i;
54cdfdb4
TG
1276
1277 BUG_ON(!cpu_base->hres_active);
1278 cpu_base->nr_events++;
1279 dev->next_event.tv64 = KTIME_MAX;
1280
1281 retry:
7f22391c
FW
1282 /* 5 retries is enough to notice a hang */
1283 if (!(++nr_retries % 5))
1284 hrtimer_interrupt_hanging(dev, ktime_sub(ktime_get(), now));
1285
54cdfdb4
TG
1286 now = ktime_get();
1287
1288 expires_next.tv64 = KTIME_MAX;
1289
1290 base = cpu_base->clock_base;
1291
1292 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1293 ktime_t basenow;
1294 struct rb_node *node;
1295
1296 spin_lock(&cpu_base->lock);
1297
1298 basenow = ktime_add(now, base->offset);
1299
1300 while ((node = base->first)) {
1301 struct hrtimer *timer;
1302
1303 timer = rb_entry(node, struct hrtimer, node);
1304
654c8e0b
AV
1305 /*
1306 * The immediate goal for using the softexpires is
1307 * minimizing wakeups, not running timers at the
1308 * earliest interrupt after their soft expiration.
1309 * This allows us to avoid using a Priority Search
1310 * Tree, which can answer a stabbing querry for
1311 * overlapping intervals and instead use the simple
1312 * BST we already have.
1313 * We don't add extra wakeups by delaying timers that
1314 * are right-of a not yet expired timer, because that
1315 * timer will have to trigger a wakeup anyway.
1316 */
1317
1318 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
54cdfdb4
TG
1319 ktime_t expires;
1320
cc584b21 1321 expires = ktime_sub(hrtimer_get_expires(timer),
54cdfdb4
TG
1322 base->offset);
1323 if (expires.tv64 < expires_next.tv64)
1324 expires_next = expires;
1325 break;
1326 }
1327
d3d74453 1328 __run_hrtimer(timer);
54cdfdb4
TG
1329 }
1330 spin_unlock(&cpu_base->lock);
1331 base++;
1332 }
1333
1334 cpu_base->expires_next = expires_next;
1335
1336 /* Reprogramming necessary ? */
1337 if (expires_next.tv64 != KTIME_MAX) {
7f22391c 1338 if (tick_program_event(expires_next, force_clock_reprogram))
54cdfdb4
TG
1339 goto retry;
1340 }
54cdfdb4
TG
1341}
1342
8bdec955
TG
1343/*
1344 * local version of hrtimer_peek_ahead_timers() called with interrupts
1345 * disabled.
1346 */
1347static void __hrtimer_peek_ahead_timers(void)
1348{
1349 struct tick_device *td;
1350
1351 if (!hrtimer_hres_active())
1352 return;
1353
1354 td = &__get_cpu_var(tick_cpu_device);
1355 if (td && td->evtdev)
1356 hrtimer_interrupt(td->evtdev);
1357}
1358
2e94d1f7
AV
1359/**
1360 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1361 *
1362 * hrtimer_peek_ahead_timers will peek at the timer queue of
1363 * the current cpu and check if there are any timers for which
1364 * the soft expires time has passed. If any such timers exist,
1365 * they are run immediately and then removed from the timer queue.
1366 *
1367 */
1368void hrtimer_peek_ahead_timers(void)
1369{
643bdf68 1370 unsigned long flags;
dc4304f7 1371
2e94d1f7 1372 local_irq_save(flags);
8bdec955 1373 __hrtimer_peek_ahead_timers();
2e94d1f7
AV
1374 local_irq_restore(flags);
1375}
1376
a6037b61
PZ
1377static void run_hrtimer_softirq(struct softirq_action *h)
1378{
1379 hrtimer_peek_ahead_timers();
1380}
1381
82c5b7b5
IM
1382#else /* CONFIG_HIGH_RES_TIMERS */
1383
1384static inline void __hrtimer_peek_ahead_timers(void) { }
1385
1386#endif /* !CONFIG_HIGH_RES_TIMERS */
82f67cd9 1387
d3d74453
PZ
1388/*
1389 * Called from timer softirq every jiffy, expire hrtimers:
1390 *
1391 * For HRT its the fall back code to run the softirq in the timer
1392 * softirq context in case the hrtimer initialization failed or has
1393 * not been done yet.
1394 */
1395void hrtimer_run_pending(void)
1396{
d3d74453
PZ
1397 if (hrtimer_hres_active())
1398 return;
54cdfdb4 1399
d3d74453
PZ
1400 /*
1401 * This _is_ ugly: We have to check in the softirq context,
1402 * whether we can switch to highres and / or nohz mode. The
1403 * clocksource switch happens in the timer interrupt with
1404 * xtime_lock held. Notification from there only sets the
1405 * check bit in the tick_oneshot code, otherwise we might
1406 * deadlock vs. xtime_lock.
1407 */
1408 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1409 hrtimer_switch_to_hres();
54cdfdb4
TG
1410}
1411
c0a31329 1412/*
d3d74453 1413 * Called from hardirq context every jiffy
c0a31329 1414 */
833883d9 1415void hrtimer_run_queues(void)
c0a31329 1416{
288867ec 1417 struct rb_node *node;
833883d9
DS
1418 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1419 struct hrtimer_clock_base *base;
1420 int index, gettime = 1;
c0a31329 1421
833883d9 1422 if (hrtimer_hres_active())
3055adda
DS
1423 return;
1424
833883d9
DS
1425 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1426 base = &cpu_base->clock_base[index];
c0a31329 1427
833883d9 1428 if (!base->first)
d3d74453 1429 continue;
833883d9 1430
d7cfb60c 1431 if (gettime) {
833883d9
DS
1432 hrtimer_get_softirq_time(cpu_base);
1433 gettime = 0;
b75f7a51 1434 }
d3d74453 1435
833883d9 1436 spin_lock(&cpu_base->lock);
c0a31329 1437
833883d9
DS
1438 while ((node = base->first)) {
1439 struct hrtimer *timer;
54cdfdb4 1440
833883d9 1441 timer = rb_entry(node, struct hrtimer, node);
cc584b21
AV
1442 if (base->softirq_time.tv64 <=
1443 hrtimer_get_expires_tv64(timer))
833883d9
DS
1444 break;
1445
833883d9
DS
1446 __run_hrtimer(timer);
1447 }
1448 spin_unlock(&cpu_base->lock);
1449 }
c0a31329
TG
1450}
1451
10c94ec1
TG
1452/*
1453 * Sleep related functions:
1454 */
c9cb2e3d 1455static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
00362e33
TG
1456{
1457 struct hrtimer_sleeper *t =
1458 container_of(timer, struct hrtimer_sleeper, timer);
1459 struct task_struct *task = t->task;
1460
1461 t->task = NULL;
1462 if (task)
1463 wake_up_process(task);
1464
1465 return HRTIMER_NORESTART;
1466}
1467
36c8b586 1468void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
00362e33
TG
1469{
1470 sl->timer.function = hrtimer_wakeup;
1471 sl->task = task;
1472}
1473
669d7868 1474static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
432569bb 1475{
669d7868 1476 hrtimer_init_sleeper(t, current);
10c94ec1 1477
432569bb
RZ
1478 do {
1479 set_current_state(TASK_INTERRUPTIBLE);
cc584b21 1480 hrtimer_start_expires(&t->timer, mode);
37bb6cb4
PZ
1481 if (!hrtimer_active(&t->timer))
1482 t->task = NULL;
432569bb 1483
54cdfdb4
TG
1484 if (likely(t->task))
1485 schedule();
432569bb 1486
669d7868 1487 hrtimer_cancel(&t->timer);
c9cb2e3d 1488 mode = HRTIMER_MODE_ABS;
669d7868
TG
1489
1490 } while (t->task && !signal_pending(current));
432569bb 1491
3588a085
PZ
1492 __set_current_state(TASK_RUNNING);
1493
669d7868 1494 return t->task == NULL;
10c94ec1
TG
1495}
1496
080344b9
ON
1497static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1498{
1499 struct timespec rmt;
1500 ktime_t rem;
1501
cc584b21 1502 rem = hrtimer_expires_remaining(timer);
080344b9
ON
1503 if (rem.tv64 <= 0)
1504 return 0;
1505 rmt = ktime_to_timespec(rem);
1506
1507 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1508 return -EFAULT;
1509
1510 return 1;
1511}
1512
1711ef38 1513long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
10c94ec1 1514{
669d7868 1515 struct hrtimer_sleeper t;
080344b9 1516 struct timespec __user *rmtp;
237fc6e7 1517 int ret = 0;
10c94ec1 1518
237fc6e7
TG
1519 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1520 HRTIMER_MODE_ABS);
cc584b21 1521 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
10c94ec1 1522
c9cb2e3d 1523 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
237fc6e7 1524 goto out;
10c94ec1 1525
029a07e0 1526 rmtp = restart->nanosleep.rmtp;
432569bb 1527 if (rmtp) {
237fc6e7 1528 ret = update_rmtp(&t.timer, rmtp);
080344b9 1529 if (ret <= 0)
237fc6e7 1530 goto out;
432569bb 1531 }
10c94ec1 1532
10c94ec1 1533 /* The other values in restart are already filled in */
237fc6e7
TG
1534 ret = -ERESTART_RESTARTBLOCK;
1535out:
1536 destroy_hrtimer_on_stack(&t.timer);
1537 return ret;
10c94ec1
TG
1538}
1539
080344b9 1540long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
10c94ec1
TG
1541 const enum hrtimer_mode mode, const clockid_t clockid)
1542{
1543 struct restart_block *restart;
669d7868 1544 struct hrtimer_sleeper t;
237fc6e7 1545 int ret = 0;
3bd01206
AV
1546 unsigned long slack;
1547
1548 slack = current->timer_slack_ns;
1549 if (rt_task(current))
1550 slack = 0;
10c94ec1 1551
237fc6e7 1552 hrtimer_init_on_stack(&t.timer, clockid, mode);
3bd01206 1553 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
432569bb 1554 if (do_nanosleep(&t, mode))
237fc6e7 1555 goto out;
10c94ec1 1556
7978672c 1557 /* Absolute timers do not update the rmtp value and restart: */
237fc6e7
TG
1558 if (mode == HRTIMER_MODE_ABS) {
1559 ret = -ERESTARTNOHAND;
1560 goto out;
1561 }
10c94ec1 1562
432569bb 1563 if (rmtp) {
237fc6e7 1564 ret = update_rmtp(&t.timer, rmtp);
080344b9 1565 if (ret <= 0)
237fc6e7 1566 goto out;
432569bb 1567 }
10c94ec1
TG
1568
1569 restart = &current_thread_info()->restart_block;
1711ef38 1570 restart->fn = hrtimer_nanosleep_restart;
029a07e0
TG
1571 restart->nanosleep.index = t.timer.base->index;
1572 restart->nanosleep.rmtp = rmtp;
cc584b21 1573 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
10c94ec1 1574
237fc6e7
TG
1575 ret = -ERESTART_RESTARTBLOCK;
1576out:
1577 destroy_hrtimer_on_stack(&t.timer);
1578 return ret;
10c94ec1
TG
1579}
1580
58fd3aa2
HC
1581SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1582 struct timespec __user *, rmtp)
6ba1b912 1583{
080344b9 1584 struct timespec tu;
6ba1b912
TG
1585
1586 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1587 return -EFAULT;
1588
1589 if (!timespec_valid(&tu))
1590 return -EINVAL;
1591
080344b9 1592 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
6ba1b912
TG
1593}
1594
c0a31329
TG
1595/*
1596 * Functions related to boot-time initialization:
1597 */
0ec160dd 1598static void __cpuinit init_hrtimers_cpu(int cpu)
c0a31329 1599{
3c8aa39d 1600 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
c0a31329
TG
1601 int i;
1602
3c8aa39d 1603 spin_lock_init(&cpu_base->lock);
3c8aa39d
TG
1604
1605 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1606 cpu_base->clock_base[i].cpu_base = cpu_base;
1607
54cdfdb4 1608 hrtimer_init_hres(cpu_base);
c0a31329
TG
1609}
1610
1611#ifdef CONFIG_HOTPLUG_CPU
1612
ca109491 1613static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
37810659 1614 struct hrtimer_clock_base *new_base)
c0a31329
TG
1615{
1616 struct hrtimer *timer;
1617 struct rb_node *node;
1618
1619 while ((node = rb_first(&old_base->active))) {
1620 timer = rb_entry(node, struct hrtimer, node);
54cdfdb4 1621 BUG_ON(hrtimer_callback_running(timer));
237fc6e7 1622 debug_hrtimer_deactivate(timer);
b00c1a99
TG
1623
1624 /*
1625 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1626 * timer could be seen as !active and just vanish away
1627 * under us on another CPU
1628 */
1629 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
c0a31329 1630 timer->base = new_base;
54cdfdb4 1631 /*
e3f1d883
TG
1632 * Enqueue the timers on the new cpu. This does not
1633 * reprogram the event device in case the timer
1634 * expires before the earliest on this CPU, but we run
1635 * hrtimer_interrupt after we migrated everything to
1636 * sort out already expired timers and reprogram the
1637 * event device.
54cdfdb4 1638 */
a6037b61 1639 enqueue_hrtimer(timer, new_base);
41e1022e 1640
b00c1a99
TG
1641 /* Clear the migration state bit */
1642 timer->state &= ~HRTIMER_STATE_MIGRATE;
c0a31329
TG
1643 }
1644}
1645
d5fd43c4 1646static void migrate_hrtimers(int scpu)
c0a31329 1647{
3c8aa39d 1648 struct hrtimer_cpu_base *old_base, *new_base;
731a55ba 1649 int i;
c0a31329 1650
37810659 1651 BUG_ON(cpu_online(scpu));
37810659 1652 tick_cancel_sched_timer(scpu);
731a55ba
TG
1653
1654 local_irq_disable();
1655 old_base = &per_cpu(hrtimer_bases, scpu);
1656 new_base = &__get_cpu_var(hrtimer_bases);
d82f0b0f
ON
1657 /*
1658 * The caller is globally serialized and nobody else
1659 * takes two locks at once, deadlock is not possible.
1660 */
731a55ba 1661 spin_lock(&new_base->lock);
8e60e05f 1662 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
c0a31329 1663
3c8aa39d 1664 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
ca109491 1665 migrate_hrtimer_list(&old_base->clock_base[i],
37810659 1666 &new_base->clock_base[i]);
c0a31329
TG
1667 }
1668
8e60e05f 1669 spin_unlock(&old_base->lock);
731a55ba 1670 spin_unlock(&new_base->lock);
37810659 1671
731a55ba
TG
1672 /* Check, if we got expired work to do */
1673 __hrtimer_peek_ahead_timers();
1674 local_irq_enable();
c0a31329 1675}
37810659 1676
c0a31329
TG
1677#endif /* CONFIG_HOTPLUG_CPU */
1678
8c78f307 1679static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
c0a31329
TG
1680 unsigned long action, void *hcpu)
1681{
b2e3c0ad 1682 int scpu = (long)hcpu;
c0a31329
TG
1683
1684 switch (action) {
1685
1686 case CPU_UP_PREPARE:
8bb78442 1687 case CPU_UP_PREPARE_FROZEN:
37810659 1688 init_hrtimers_cpu(scpu);
c0a31329
TG
1689 break;
1690
1691#ifdef CONFIG_HOTPLUG_CPU
94df7de0
SD
1692 case CPU_DYING:
1693 case CPU_DYING_FROZEN:
1694 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1695 break;
c0a31329 1696 case CPU_DEAD:
8bb78442 1697 case CPU_DEAD_FROZEN:
b2e3c0ad 1698 {
37810659 1699 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
d5fd43c4 1700 migrate_hrtimers(scpu);
c0a31329 1701 break;
b2e3c0ad 1702 }
c0a31329
TG
1703#endif
1704
1705 default:
1706 break;
1707 }
1708
1709 return NOTIFY_OK;
1710}
1711
8c78f307 1712static struct notifier_block __cpuinitdata hrtimers_nb = {
c0a31329
TG
1713 .notifier_call = hrtimer_cpu_notify,
1714};
1715
1716void __init hrtimers_init(void)
1717{
1718 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1719 (void *)(long)smp_processor_id());
1720 register_cpu_notifier(&hrtimers_nb);
a6037b61
PZ
1721#ifdef CONFIG_HIGH_RES_TIMERS
1722 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1723#endif
c0a31329
TG
1724}
1725
7bb67439 1726/**
654c8e0b 1727 * schedule_hrtimeout_range - sleep until timeout
7bb67439 1728 * @expires: timeout value (ktime_t)
654c8e0b 1729 * @delta: slack in expires timeout (ktime_t)
7bb67439
AV
1730 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1731 *
1732 * Make the current task sleep until the given expiry time has
1733 * elapsed. The routine will return immediately unless
1734 * the current task state has been set (see set_current_state()).
1735 *
654c8e0b
AV
1736 * The @delta argument gives the kernel the freedom to schedule the
1737 * actual wakeup to a time that is both power and performance friendly.
1738 * The kernel give the normal best effort behavior for "@expires+@delta",
1739 * but may decide to fire the timer earlier, but no earlier than @expires.
1740 *
7bb67439
AV
1741 * You can set the task state as follows -
1742 *
1743 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1744 * pass before the routine returns.
1745 *
1746 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1747 * delivered to the current task.
1748 *
1749 * The current task state is guaranteed to be TASK_RUNNING when this
1750 * routine returns.
1751 *
1752 * Returns 0 when the timer has expired otherwise -EINTR
1753 */
654c8e0b 1754int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
7bb67439
AV
1755 const enum hrtimer_mode mode)
1756{
1757 struct hrtimer_sleeper t;
1758
1759 /*
1760 * Optimize when a zero timeout value is given. It does not
1761 * matter whether this is an absolute or a relative time.
1762 */
1763 if (expires && !expires->tv64) {
1764 __set_current_state(TASK_RUNNING);
1765 return 0;
1766 }
1767
1768 /*
1769 * A NULL parameter means "inifinte"
1770 */
1771 if (!expires) {
1772 schedule();
1773 __set_current_state(TASK_RUNNING);
1774 return -EINTR;
1775 }
1776
1777 hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
654c8e0b 1778 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
7bb67439
AV
1779
1780 hrtimer_init_sleeper(&t, current);
1781
cc584b21 1782 hrtimer_start_expires(&t.timer, mode);
7bb67439
AV
1783 if (!hrtimer_active(&t.timer))
1784 t.task = NULL;
1785
1786 if (likely(t.task))
1787 schedule();
1788
1789 hrtimer_cancel(&t.timer);
1790 destroy_hrtimer_on_stack(&t.timer);
1791
1792 __set_current_state(TASK_RUNNING);
1793
1794 return !t.task ? 0 : -EINTR;
1795}
654c8e0b
AV
1796EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1797
1798/**
1799 * schedule_hrtimeout - sleep until timeout
1800 * @expires: timeout value (ktime_t)
1801 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1802 *
1803 * Make the current task sleep until the given expiry time has
1804 * elapsed. The routine will return immediately unless
1805 * the current task state has been set (see set_current_state()).
1806 *
1807 * You can set the task state as follows -
1808 *
1809 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1810 * pass before the routine returns.
1811 *
1812 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1813 * delivered to the current task.
1814 *
1815 * The current task state is guaranteed to be TASK_RUNNING when this
1816 * routine returns.
1817 *
1818 * Returns 0 when the timer has expired otherwise -EINTR
1819 */
1820int __sched schedule_hrtimeout(ktime_t *expires,
1821 const enum hrtimer_mode mode)
1822{
1823 return schedule_hrtimeout_range(expires, 0, mode);
1824}
7bb67439 1825EXPORT_SYMBOL_GPL(schedule_hrtimeout);