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