]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - kernel/hrtimer.c
hrtimer: remove #include <linux/irq.h>
[mirror_ubuntu-bionic-kernel.git] / kernel / hrtimer.c
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 */
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 */
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 */
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 */
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
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 *
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 *
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 */
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 */
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 */
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 */
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 */
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 */
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 */
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
403 static inline void debug_hrtimer_init(struct hrtimer *timer)
404 {
405 debug_object_init(timer, &hrtimer_debug_descr);
406 }
407
408 static inline void debug_hrtimer_activate(struct hrtimer *timer)
409 {
410 debug_object_activate(timer, &hrtimer_debug_descr);
411 }
412
413 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
414 {
415 debug_object_deactivate(timer, &hrtimer_debug_descr);
416 }
417
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
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
433 void destroy_hrtimer_on_stack(struct hrtimer *timer)
434 {
435 debug_object_free(timer, &hrtimer_debug_descr);
436 }
437
438 #else
439 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
440 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
441 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
442 #endif
443
444 /*
445 * Check, whether the timer is on the callback pending list
446 */
447 static inline int hrtimer_cb_pending(const struct hrtimer *timer)
448 {
449 return timer->state & HRTIMER_STATE_PENDING;
450 }
451
452 /*
453 * Remove a timer from the callback pending list
454 */
455 static inline void hrtimer_remove_cb_pending(struct hrtimer *timer)
456 {
457 list_del_init(&timer->cb_entry);
458 }
459
460 /* High resolution timer related functions */
461 #ifdef CONFIG_HIGH_RES_TIMERS
462
463 /*
464 * High resolution timer enabled ?
465 */
466 static int hrtimer_hres_enabled __read_mostly = 1;
467
468 /*
469 * Enable / Disable high resolution mode
470 */
471 static int __init setup_hrtimer_hres(char *str)
472 {
473 if (!strcmp(str, "off"))
474 hrtimer_hres_enabled = 0;
475 else if (!strcmp(str, "on"))
476 hrtimer_hres_enabled = 1;
477 else
478 return 0;
479 return 1;
480 }
481
482 __setup("highres=", setup_hrtimer_hres);
483
484 /*
485 * hrtimer_high_res_enabled - query, if the highres mode is enabled
486 */
487 static inline int hrtimer_is_hres_enabled(void)
488 {
489 return hrtimer_hres_enabled;
490 }
491
492 /*
493 * Is the high resolution mode active ?
494 */
495 static inline int hrtimer_hres_active(void)
496 {
497 return __get_cpu_var(hrtimer_bases).hres_active;
498 }
499
500 /*
501 * Reprogram the event source with checking both queues for the
502 * next event
503 * Called with interrupts disabled and base->lock held
504 */
505 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base)
506 {
507 int i;
508 struct hrtimer_clock_base *base = cpu_base->clock_base;
509 ktime_t expires;
510
511 cpu_base->expires_next.tv64 = KTIME_MAX;
512
513 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
514 struct hrtimer *timer;
515
516 if (!base->first)
517 continue;
518 timer = rb_entry(base->first, struct hrtimer, node);
519 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
520 if (expires.tv64 < cpu_base->expires_next.tv64)
521 cpu_base->expires_next = expires;
522 }
523
524 if (cpu_base->expires_next.tv64 != KTIME_MAX)
525 tick_program_event(cpu_base->expires_next, 1);
526 }
527
528 /*
529 * Shared reprogramming for clock_realtime and clock_monotonic
530 *
531 * When a timer is enqueued and expires earlier than the already enqueued
532 * timers, we have to check, whether it expires earlier than the timer for
533 * which the clock event device was armed.
534 *
535 * Called with interrupts disabled and base->cpu_base.lock held
536 */
537 static int hrtimer_reprogram(struct hrtimer *timer,
538 struct hrtimer_clock_base *base)
539 {
540 ktime_t *expires_next = &__get_cpu_var(hrtimer_bases).expires_next;
541 ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
542 int res;
543
544 WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
545
546 /*
547 * When the callback is running, we do not reprogram the clock event
548 * device. The timer callback is either running on a different CPU or
549 * the callback is executed in the hrtimer_interrupt context. The
550 * reprogramming is handled either by the softirq, which called the
551 * callback or at the end of the hrtimer_interrupt.
552 */
553 if (hrtimer_callback_running(timer))
554 return 0;
555
556 /*
557 * CLOCK_REALTIME timer might be requested with an absolute
558 * expiry time which is less than base->offset. Nothing wrong
559 * about that, just avoid to call into the tick code, which
560 * has now objections against negative expiry values.
561 */
562 if (expires.tv64 < 0)
563 return -ETIME;
564
565 if (expires.tv64 >= expires_next->tv64)
566 return 0;
567
568 /*
569 * Clockevents returns -ETIME, when the event was in the past.
570 */
571 res = tick_program_event(expires, 0);
572 if (!IS_ERR_VALUE(res))
573 *expires_next = expires;
574 return res;
575 }
576
577
578 /*
579 * Retrigger next event is called after clock was set
580 *
581 * Called with interrupts disabled via on_each_cpu()
582 */
583 static void retrigger_next_event(void *arg)
584 {
585 struct hrtimer_cpu_base *base;
586 struct timespec realtime_offset;
587 unsigned long seq;
588
589 if (!hrtimer_hres_active())
590 return;
591
592 do {
593 seq = read_seqbegin(&xtime_lock);
594 set_normalized_timespec(&realtime_offset,
595 -wall_to_monotonic.tv_sec,
596 -wall_to_monotonic.tv_nsec);
597 } while (read_seqretry(&xtime_lock, seq));
598
599 base = &__get_cpu_var(hrtimer_bases);
600
601 /* Adjust CLOCK_REALTIME offset */
602 spin_lock(&base->lock);
603 base->clock_base[CLOCK_REALTIME].offset =
604 timespec_to_ktime(realtime_offset);
605
606 hrtimer_force_reprogram(base);
607 spin_unlock(&base->lock);
608 }
609
610 /*
611 * Clock realtime was set
612 *
613 * Change the offset of the realtime clock vs. the monotonic
614 * clock.
615 *
616 * We might have to reprogram the high resolution timer interrupt. On
617 * SMP we call the architecture specific code to retrigger _all_ high
618 * resolution timer interrupts. On UP we just disable interrupts and
619 * call the high resolution interrupt code.
620 */
621 void clock_was_set(void)
622 {
623 /* Retrigger the CPU local events everywhere */
624 on_each_cpu(retrigger_next_event, NULL, 1);
625 }
626
627 /*
628 * During resume we might have to reprogram the high resolution timer
629 * interrupt (on the local CPU):
630 */
631 void hres_timers_resume(void)
632 {
633 /* Retrigger the CPU local events: */
634 retrigger_next_event(NULL);
635 }
636
637 /*
638 * Initialize the high resolution related parts of cpu_base
639 */
640 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
641 {
642 base->expires_next.tv64 = KTIME_MAX;
643 base->hres_active = 0;
644 }
645
646 /*
647 * Initialize the high resolution related parts of a hrtimer
648 */
649 static inline void hrtimer_init_timer_hres(struct hrtimer *timer)
650 {
651 }
652
653 /*
654 * When High resolution timers are active, try to reprogram. Note, that in case
655 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
656 * check happens. The timer gets enqueued into the rbtree. The reprogramming
657 * and expiry check is done in the hrtimer_interrupt or in the softirq.
658 */
659 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
660 struct hrtimer_clock_base *base)
661 {
662 if (base->cpu_base->hres_active && hrtimer_reprogram(timer, base)) {
663
664 /* Timer is expired, act upon the callback mode */
665 switch(timer->cb_mode) {
666 case HRTIMER_CB_IRQSAFE_PERCPU:
667 case HRTIMER_CB_IRQSAFE_UNLOCKED:
668 /*
669 * This is solely for the sched tick emulation with
670 * dynamic tick support to ensure that we do not
671 * restart the tick right on the edge and end up with
672 * the tick timer in the softirq ! The calling site
673 * takes care of this. Also used for hrtimer sleeper !
674 */
675 debug_hrtimer_deactivate(timer);
676 return 1;
677 case HRTIMER_CB_SOFTIRQ:
678 /*
679 * Move everything else into the softirq pending list !
680 */
681 list_add_tail(&timer->cb_entry,
682 &base->cpu_base->cb_pending);
683 timer->state = HRTIMER_STATE_PENDING;
684 return 1;
685 default:
686 BUG();
687 }
688 }
689 return 0;
690 }
691
692 /*
693 * Switch to high resolution mode
694 */
695 static int hrtimer_switch_to_hres(void)
696 {
697 int cpu = smp_processor_id();
698 struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
699 unsigned long flags;
700
701 if (base->hres_active)
702 return 1;
703
704 local_irq_save(flags);
705
706 if (tick_init_highres()) {
707 local_irq_restore(flags);
708 printk(KERN_WARNING "Could not switch to high resolution "
709 "mode on CPU %d\n", cpu);
710 return 0;
711 }
712 base->hres_active = 1;
713 base->clock_base[CLOCK_REALTIME].resolution = KTIME_HIGH_RES;
714 base->clock_base[CLOCK_MONOTONIC].resolution = KTIME_HIGH_RES;
715
716 tick_setup_sched_timer();
717
718 /* "Retrigger" the interrupt to get things going */
719 retrigger_next_event(NULL);
720 local_irq_restore(flags);
721 printk(KERN_DEBUG "Switched to high resolution mode on CPU %d\n",
722 smp_processor_id());
723 return 1;
724 }
725
726 static inline void hrtimer_raise_softirq(void)
727 {
728 raise_softirq(HRTIMER_SOFTIRQ);
729 }
730
731 #else
732
733 static inline int hrtimer_hres_active(void) { return 0; }
734 static inline int hrtimer_is_hres_enabled(void) { return 0; }
735 static inline int hrtimer_switch_to_hres(void) { return 0; }
736 static inline void hrtimer_force_reprogram(struct hrtimer_cpu_base *base) { }
737 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
738 struct hrtimer_clock_base *base)
739 {
740 return 0;
741 }
742 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
743 static inline void hrtimer_init_timer_hres(struct hrtimer *timer) { }
744 static inline int hrtimer_reprogram(struct hrtimer *timer,
745 struct hrtimer_clock_base *base)
746 {
747 return 0;
748 }
749 static inline void hrtimer_raise_softirq(void) { }
750
751 #endif /* CONFIG_HIGH_RES_TIMERS */
752
753 #ifdef CONFIG_TIMER_STATS
754 void __timer_stats_hrtimer_set_start_info(struct hrtimer *timer, void *addr)
755 {
756 if (timer->start_site)
757 return;
758
759 timer->start_site = addr;
760 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
761 timer->start_pid = current->pid;
762 }
763 #endif
764
765 /*
766 * Counterpart to lock_hrtimer_base above:
767 */
768 static inline
769 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
770 {
771 spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
772 }
773
774 /**
775 * hrtimer_forward - forward the timer expiry
776 * @timer: hrtimer to forward
777 * @now: forward past this time
778 * @interval: the interval to forward
779 *
780 * Forward the timer expiry so it will expire in the future.
781 * Returns the number of overruns.
782 */
783 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
784 {
785 u64 orun = 1;
786 ktime_t delta;
787
788 delta = ktime_sub(now, hrtimer_get_expires(timer));
789
790 if (delta.tv64 < 0)
791 return 0;
792
793 if (interval.tv64 < timer->base->resolution.tv64)
794 interval.tv64 = timer->base->resolution.tv64;
795
796 if (unlikely(delta.tv64 >= interval.tv64)) {
797 s64 incr = ktime_to_ns(interval);
798
799 orun = ktime_divns(delta, incr);
800 hrtimer_add_expires_ns(timer, incr * orun);
801 if (hrtimer_get_expires_tv64(timer) > now.tv64)
802 return orun;
803 /*
804 * This (and the ktime_add() below) is the
805 * correction for exact:
806 */
807 orun++;
808 }
809 hrtimer_add_expires(timer, interval);
810
811 return orun;
812 }
813 EXPORT_SYMBOL_GPL(hrtimer_forward);
814
815 /*
816 * enqueue_hrtimer - internal function to (re)start a timer
817 *
818 * The timer is inserted in expiry order. Insertion into the
819 * red black tree is O(log(n)). Must hold the base lock.
820 */
821 static void enqueue_hrtimer(struct hrtimer *timer,
822 struct hrtimer_clock_base *base, int reprogram)
823 {
824 struct rb_node **link = &base->active.rb_node;
825 struct rb_node *parent = NULL;
826 struct hrtimer *entry;
827 int leftmost = 1;
828
829 debug_hrtimer_activate(timer);
830
831 /*
832 * Find the right place in the rbtree:
833 */
834 while (*link) {
835 parent = *link;
836 entry = rb_entry(parent, struct hrtimer, node);
837 /*
838 * We dont care about collisions. Nodes with
839 * the same expiry time stay together.
840 */
841 if (hrtimer_get_expires_tv64(timer) <
842 hrtimer_get_expires_tv64(entry)) {
843 link = &(*link)->rb_left;
844 } else {
845 link = &(*link)->rb_right;
846 leftmost = 0;
847 }
848 }
849
850 /*
851 * Insert the timer to the rbtree and check whether it
852 * replaces the first pending timer
853 */
854 if (leftmost) {
855 /*
856 * Reprogram the clock event device. When the timer is already
857 * expired hrtimer_enqueue_reprogram has either called the
858 * callback or added it to the pending list and raised the
859 * softirq.
860 *
861 * This is a NOP for !HIGHRES
862 */
863 if (reprogram && hrtimer_enqueue_reprogram(timer, base))
864 return;
865
866 base->first = &timer->node;
867 }
868
869 rb_link_node(&timer->node, parent, link);
870 rb_insert_color(&timer->node, &base->active);
871 /*
872 * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
873 * state of a possibly running callback.
874 */
875 timer->state |= HRTIMER_STATE_ENQUEUED;
876 }
877
878 /*
879 * __remove_hrtimer - internal function to remove a timer
880 *
881 * Caller must hold the base lock.
882 *
883 * High resolution timer mode reprograms the clock event device when the
884 * timer is the one which expires next. The caller can disable this by setting
885 * reprogram to zero. This is useful, when the context does a reprogramming
886 * anyway (e.g. timer interrupt)
887 */
888 static void __remove_hrtimer(struct hrtimer *timer,
889 struct hrtimer_clock_base *base,
890 unsigned long newstate, int reprogram)
891 {
892 /* High res. callback list. NOP for !HIGHRES */
893 if (hrtimer_cb_pending(timer))
894 hrtimer_remove_cb_pending(timer);
895 else {
896 /*
897 * Remove the timer from the rbtree and replace the
898 * first entry pointer if necessary.
899 */
900 if (base->first == &timer->node) {
901 base->first = rb_next(&timer->node);
902 /* Reprogram the clock event device. if enabled */
903 if (reprogram && hrtimer_hres_active())
904 hrtimer_force_reprogram(base->cpu_base);
905 }
906 rb_erase(&timer->node, &base->active);
907 }
908 timer->state = newstate;
909 }
910
911 /*
912 * remove hrtimer, called with base lock held
913 */
914 static inline int
915 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
916 {
917 if (hrtimer_is_queued(timer)) {
918 int reprogram;
919
920 /*
921 * Remove the timer and force reprogramming when high
922 * resolution mode is active and the timer is on the current
923 * CPU. If we remove a timer on another CPU, reprogramming is
924 * skipped. The interrupt event on this CPU is fired and
925 * reprogramming happens in the interrupt handler. This is a
926 * rare case and less expensive than a smp call.
927 */
928 debug_hrtimer_deactivate(timer);
929 timer_stats_hrtimer_clear_start_info(timer);
930 reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
931 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE,
932 reprogram);
933 return 1;
934 }
935 return 0;
936 }
937
938 /**
939 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
940 * @timer: the timer to be added
941 * @tim: expiry time
942 * @delta_ns: "slack" range for the timer
943 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
944 *
945 * Returns:
946 * 0 on success
947 * 1 when the timer was active
948 */
949 int
950 hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, unsigned long delta_ns,
951 const enum hrtimer_mode mode)
952 {
953 struct hrtimer_clock_base *base, *new_base;
954 unsigned long flags;
955 int ret, raise;
956
957 base = lock_hrtimer_base(timer, &flags);
958
959 /* Remove an active timer from the queue: */
960 ret = remove_hrtimer(timer, base);
961
962 /* Switch the timer base, if necessary: */
963 new_base = switch_hrtimer_base(timer, base);
964
965 if (mode == HRTIMER_MODE_REL) {
966 tim = ktime_add_safe(tim, new_base->get_time());
967 /*
968 * CONFIG_TIME_LOW_RES is a temporary way for architectures
969 * to signal that they simply return xtime in
970 * do_gettimeoffset(). In this case we want to round up by
971 * resolution when starting a relative timer, to avoid short
972 * timeouts. This will go away with the GTOD framework.
973 */
974 #ifdef CONFIG_TIME_LOW_RES
975 tim = ktime_add_safe(tim, base->resolution);
976 #endif
977 }
978
979 hrtimer_set_expires_range_ns(timer, tim, delta_ns);
980
981 timer_stats_hrtimer_set_start_info(timer);
982
983 /*
984 * Only allow reprogramming if the new base is on this CPU.
985 * (it might still be on another CPU if the timer was pending)
986 */
987 enqueue_hrtimer(timer, new_base,
988 new_base->cpu_base == &__get_cpu_var(hrtimer_bases));
989
990 /*
991 * The timer may be expired and moved to the cb_pending
992 * list. We can not raise the softirq with base lock held due
993 * to a possible deadlock with runqueue lock.
994 */
995 raise = timer->state == HRTIMER_STATE_PENDING;
996
997 /*
998 * We use preempt_disable to prevent this task from migrating after
999 * setting up the softirq and raising it. Otherwise, if me migrate
1000 * we will raise the softirq on the wrong CPU.
1001 */
1002 preempt_disable();
1003
1004 unlock_hrtimer_base(timer, &flags);
1005
1006 if (raise)
1007 hrtimer_raise_softirq();
1008 preempt_enable();
1009
1010 return ret;
1011 }
1012 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1013
1014 /**
1015 * hrtimer_start - (re)start an hrtimer on the current CPU
1016 * @timer: the timer to be added
1017 * @tim: expiry time
1018 * @mode: expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1019 *
1020 * Returns:
1021 * 0 on success
1022 * 1 when the timer was active
1023 */
1024 int
1025 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1026 {
1027 return hrtimer_start_range_ns(timer, tim, 0, mode);
1028 }
1029 EXPORT_SYMBOL_GPL(hrtimer_start);
1030
1031
1032 /**
1033 * hrtimer_try_to_cancel - try to deactivate a timer
1034 * @timer: hrtimer to stop
1035 *
1036 * Returns:
1037 * 0 when the timer was not active
1038 * 1 when the timer was active
1039 * -1 when the timer is currently excuting the callback function and
1040 * cannot be stopped
1041 */
1042 int hrtimer_try_to_cancel(struct hrtimer *timer)
1043 {
1044 struct hrtimer_clock_base *base;
1045 unsigned long flags;
1046 int ret = -1;
1047
1048 base = lock_hrtimer_base(timer, &flags);
1049
1050 if (!hrtimer_callback_running(timer))
1051 ret = remove_hrtimer(timer, base);
1052
1053 unlock_hrtimer_base(timer, &flags);
1054
1055 return ret;
1056
1057 }
1058 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1059
1060 /**
1061 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1062 * @timer: the timer to be cancelled
1063 *
1064 * Returns:
1065 * 0 when the timer was not active
1066 * 1 when the timer was active
1067 */
1068 int hrtimer_cancel(struct hrtimer *timer)
1069 {
1070 for (;;) {
1071 int ret = hrtimer_try_to_cancel(timer);
1072
1073 if (ret >= 0)
1074 return ret;
1075 cpu_relax();
1076 }
1077 }
1078 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1079
1080 /**
1081 * hrtimer_get_remaining - get remaining time for the timer
1082 * @timer: the timer to read
1083 */
1084 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1085 {
1086 struct hrtimer_clock_base *base;
1087 unsigned long flags;
1088 ktime_t rem;
1089
1090 base = lock_hrtimer_base(timer, &flags);
1091 rem = hrtimer_expires_remaining(timer);
1092 unlock_hrtimer_base(timer, &flags);
1093
1094 return rem;
1095 }
1096 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1097
1098 #ifdef CONFIG_NO_HZ
1099 /**
1100 * hrtimer_get_next_event - get the time until next expiry event
1101 *
1102 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1103 * is pending.
1104 */
1105 ktime_t hrtimer_get_next_event(void)
1106 {
1107 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1108 struct hrtimer_clock_base *base = cpu_base->clock_base;
1109 ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1110 unsigned long flags;
1111 int i;
1112
1113 spin_lock_irqsave(&cpu_base->lock, flags);
1114
1115 if (!hrtimer_hres_active()) {
1116 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1117 struct hrtimer *timer;
1118
1119 if (!base->first)
1120 continue;
1121
1122 timer = rb_entry(base->first, struct hrtimer, node);
1123 delta.tv64 = hrtimer_get_expires_tv64(timer);
1124 delta = ktime_sub(delta, base->get_time());
1125 if (delta.tv64 < mindelta.tv64)
1126 mindelta.tv64 = delta.tv64;
1127 }
1128 }
1129
1130 spin_unlock_irqrestore(&cpu_base->lock, flags);
1131
1132 if (mindelta.tv64 < 0)
1133 mindelta.tv64 = 0;
1134 return mindelta;
1135 }
1136 #endif
1137
1138 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1139 enum hrtimer_mode mode)
1140 {
1141 struct hrtimer_cpu_base *cpu_base;
1142
1143 memset(timer, 0, sizeof(struct hrtimer));
1144
1145 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1146
1147 if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1148 clock_id = CLOCK_MONOTONIC;
1149
1150 timer->base = &cpu_base->clock_base[clock_id];
1151 INIT_LIST_HEAD(&timer->cb_entry);
1152 hrtimer_init_timer_hres(timer);
1153
1154 #ifdef CONFIG_TIMER_STATS
1155 timer->start_site = NULL;
1156 timer->start_pid = -1;
1157 memset(timer->start_comm, 0, TASK_COMM_LEN);
1158 #endif
1159 }
1160
1161 /**
1162 * hrtimer_init - initialize a timer to the given clock
1163 * @timer: the timer to be initialized
1164 * @clock_id: the clock to be used
1165 * @mode: timer mode abs/rel
1166 */
1167 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1168 enum hrtimer_mode mode)
1169 {
1170 debug_hrtimer_init(timer);
1171 __hrtimer_init(timer, clock_id, mode);
1172 }
1173 EXPORT_SYMBOL_GPL(hrtimer_init);
1174
1175 /**
1176 * hrtimer_get_res - get the timer resolution for a clock
1177 * @which_clock: which clock to query
1178 * @tp: pointer to timespec variable to store the resolution
1179 *
1180 * Store the resolution of the clock selected by @which_clock in the
1181 * variable pointed to by @tp.
1182 */
1183 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1184 {
1185 struct hrtimer_cpu_base *cpu_base;
1186
1187 cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1188 *tp = ktime_to_timespec(cpu_base->clock_base[which_clock].resolution);
1189
1190 return 0;
1191 }
1192 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1193
1194 static void run_hrtimer_pending(struct hrtimer_cpu_base *cpu_base)
1195 {
1196 spin_lock_irq(&cpu_base->lock);
1197
1198 while (!list_empty(&cpu_base->cb_pending)) {
1199 enum hrtimer_restart (*fn)(struct hrtimer *);
1200 struct hrtimer *timer;
1201 int restart;
1202 int emulate_hardirq_ctx = 0;
1203
1204 timer = list_entry(cpu_base->cb_pending.next,
1205 struct hrtimer, cb_entry);
1206
1207 debug_hrtimer_deactivate(timer);
1208 timer_stats_account_hrtimer(timer);
1209
1210 fn = timer->function;
1211 /*
1212 * A timer might have been added to the cb_pending list
1213 * when it was migrated during a cpu-offline operation.
1214 * Emulate hardirq context for such timers.
1215 */
1216 if (timer->cb_mode == HRTIMER_CB_IRQSAFE_PERCPU ||
1217 timer->cb_mode == HRTIMER_CB_IRQSAFE_UNLOCKED)
1218 emulate_hardirq_ctx = 1;
1219
1220 __remove_hrtimer(timer, timer->base, HRTIMER_STATE_CALLBACK, 0);
1221 spin_unlock_irq(&cpu_base->lock);
1222
1223 if (unlikely(emulate_hardirq_ctx)) {
1224 local_irq_disable();
1225 restart = fn(timer);
1226 local_irq_enable();
1227 } else
1228 restart = fn(timer);
1229
1230 spin_lock_irq(&cpu_base->lock);
1231
1232 timer->state &= ~HRTIMER_STATE_CALLBACK;
1233 if (restart == HRTIMER_RESTART) {
1234 BUG_ON(hrtimer_active(timer));
1235 /*
1236 * Enqueue the timer, allow reprogramming of the event
1237 * device
1238 */
1239 enqueue_hrtimer(timer, timer->base, 1);
1240 } else if (hrtimer_active(timer)) {
1241 /*
1242 * If the timer was rearmed on another CPU, reprogram
1243 * the event device.
1244 */
1245 struct hrtimer_clock_base *base = timer->base;
1246
1247 if (base->first == &timer->node &&
1248 hrtimer_reprogram(timer, base)) {
1249 /*
1250 * Timer is expired. Thus move it from tree to
1251 * pending list again.
1252 */
1253 __remove_hrtimer(timer, base,
1254 HRTIMER_STATE_PENDING, 0);
1255 list_add_tail(&timer->cb_entry,
1256 &base->cpu_base->cb_pending);
1257 }
1258 }
1259 }
1260 spin_unlock_irq(&cpu_base->lock);
1261 }
1262
1263 static void __run_hrtimer(struct hrtimer *timer)
1264 {
1265 struct hrtimer_clock_base *base = timer->base;
1266 struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1267 enum hrtimer_restart (*fn)(struct hrtimer *);
1268 int restart;
1269
1270 debug_hrtimer_deactivate(timer);
1271 __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1272 timer_stats_account_hrtimer(timer);
1273
1274 fn = timer->function;
1275 if (timer->cb_mode == HRTIMER_CB_IRQSAFE_PERCPU ||
1276 timer->cb_mode == HRTIMER_CB_IRQSAFE_UNLOCKED) {
1277 /*
1278 * Used for scheduler timers, avoid lock inversion with
1279 * rq->lock and tasklist_lock.
1280 *
1281 * These timers are required to deal with enqueue expiry
1282 * themselves and are not allowed to migrate.
1283 */
1284 spin_unlock(&cpu_base->lock);
1285 restart = fn(timer);
1286 spin_lock(&cpu_base->lock);
1287 } else
1288 restart = fn(timer);
1289
1290 /*
1291 * Note: We clear the CALLBACK bit after enqueue_hrtimer to avoid
1292 * reprogramming of the event hardware. This happens at the end of this
1293 * function anyway.
1294 */
1295 if (restart != HRTIMER_NORESTART) {
1296 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1297 enqueue_hrtimer(timer, base, 0);
1298 }
1299 timer->state &= ~HRTIMER_STATE_CALLBACK;
1300 }
1301
1302 #ifdef CONFIG_HIGH_RES_TIMERS
1303
1304 /*
1305 * High resolution timer interrupt
1306 * Called with interrupts disabled
1307 */
1308 void hrtimer_interrupt(struct clock_event_device *dev)
1309 {
1310 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1311 struct hrtimer_clock_base *base;
1312 ktime_t expires_next, now;
1313 int i, raise = 0;
1314
1315 BUG_ON(!cpu_base->hres_active);
1316 cpu_base->nr_events++;
1317 dev->next_event.tv64 = KTIME_MAX;
1318
1319 retry:
1320 now = ktime_get();
1321
1322 expires_next.tv64 = KTIME_MAX;
1323
1324 base = cpu_base->clock_base;
1325
1326 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1327 ktime_t basenow;
1328 struct rb_node *node;
1329
1330 spin_lock(&cpu_base->lock);
1331
1332 basenow = ktime_add(now, base->offset);
1333
1334 while ((node = base->first)) {
1335 struct hrtimer *timer;
1336
1337 timer = rb_entry(node, struct hrtimer, node);
1338
1339 /*
1340 * The immediate goal for using the softexpires is
1341 * minimizing wakeups, not running timers at the
1342 * earliest interrupt after their soft expiration.
1343 * This allows us to avoid using a Priority Search
1344 * Tree, which can answer a stabbing querry for
1345 * overlapping intervals and instead use the simple
1346 * BST we already have.
1347 * We don't add extra wakeups by delaying timers that
1348 * are right-of a not yet expired timer, because that
1349 * timer will have to trigger a wakeup anyway.
1350 */
1351
1352 if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1353 ktime_t expires;
1354
1355 expires = ktime_sub(hrtimer_get_expires(timer),
1356 base->offset);
1357 if (expires.tv64 < expires_next.tv64)
1358 expires_next = expires;
1359 break;
1360 }
1361
1362 /* Move softirq callbacks to the pending list */
1363 if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1364 __remove_hrtimer(timer, base,
1365 HRTIMER_STATE_PENDING, 0);
1366 list_add_tail(&timer->cb_entry,
1367 &base->cpu_base->cb_pending);
1368 raise = 1;
1369 continue;
1370 }
1371
1372 __run_hrtimer(timer);
1373 }
1374 spin_unlock(&cpu_base->lock);
1375 base++;
1376 }
1377
1378 cpu_base->expires_next = expires_next;
1379
1380 /* Reprogramming necessary ? */
1381 if (expires_next.tv64 != KTIME_MAX) {
1382 if (tick_program_event(expires_next, 0))
1383 goto retry;
1384 }
1385
1386 /* Raise softirq ? */
1387 if (raise)
1388 raise_softirq(HRTIMER_SOFTIRQ);
1389 }
1390
1391 /**
1392 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1393 *
1394 * hrtimer_peek_ahead_timers will peek at the timer queue of
1395 * the current cpu and check if there are any timers for which
1396 * the soft expires time has passed. If any such timers exist,
1397 * they are run immediately and then removed from the timer queue.
1398 *
1399 */
1400 void hrtimer_peek_ahead_timers(void)
1401 {
1402 struct tick_device *td;
1403 unsigned long flags;
1404
1405 if (!hrtimer_hres_active())
1406 return;
1407
1408 local_irq_save(flags);
1409 td = &__get_cpu_var(tick_cpu_device);
1410 if (td && td->evtdev)
1411 hrtimer_interrupt(td->evtdev);
1412 local_irq_restore(flags);
1413 }
1414
1415 static void run_hrtimer_softirq(struct softirq_action *h)
1416 {
1417 run_hrtimer_pending(&__get_cpu_var(hrtimer_bases));
1418 }
1419
1420 #endif /* CONFIG_HIGH_RES_TIMERS */
1421
1422 /*
1423 * Called from timer softirq every jiffy, expire hrtimers:
1424 *
1425 * For HRT its the fall back code to run the softirq in the timer
1426 * softirq context in case the hrtimer initialization failed or has
1427 * not been done yet.
1428 */
1429 void hrtimer_run_pending(void)
1430 {
1431 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1432
1433 if (hrtimer_hres_active())
1434 return;
1435
1436 /*
1437 * This _is_ ugly: We have to check in the softirq context,
1438 * whether we can switch to highres and / or nohz mode. The
1439 * clocksource switch happens in the timer interrupt with
1440 * xtime_lock held. Notification from there only sets the
1441 * check bit in the tick_oneshot code, otherwise we might
1442 * deadlock vs. xtime_lock.
1443 */
1444 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1445 hrtimer_switch_to_hres();
1446
1447 run_hrtimer_pending(cpu_base);
1448 }
1449
1450 /*
1451 * Called from hardirq context every jiffy
1452 */
1453 void hrtimer_run_queues(void)
1454 {
1455 struct rb_node *node;
1456 struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1457 struct hrtimer_clock_base *base;
1458 int index, gettime = 1;
1459
1460 if (hrtimer_hres_active())
1461 return;
1462
1463 for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1464 base = &cpu_base->clock_base[index];
1465
1466 if (!base->first)
1467 continue;
1468
1469 if (gettime) {
1470 hrtimer_get_softirq_time(cpu_base);
1471 gettime = 0;
1472 }
1473
1474 spin_lock(&cpu_base->lock);
1475
1476 while ((node = base->first)) {
1477 struct hrtimer *timer;
1478
1479 timer = rb_entry(node, struct hrtimer, node);
1480 if (base->softirq_time.tv64 <=
1481 hrtimer_get_expires_tv64(timer))
1482 break;
1483
1484 if (timer->cb_mode == HRTIMER_CB_SOFTIRQ) {
1485 __remove_hrtimer(timer, base,
1486 HRTIMER_STATE_PENDING, 0);
1487 list_add_tail(&timer->cb_entry,
1488 &base->cpu_base->cb_pending);
1489 continue;
1490 }
1491
1492 __run_hrtimer(timer);
1493 }
1494 spin_unlock(&cpu_base->lock);
1495 }
1496 }
1497
1498 /*
1499 * Sleep related functions:
1500 */
1501 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1502 {
1503 struct hrtimer_sleeper *t =
1504 container_of(timer, struct hrtimer_sleeper, timer);
1505 struct task_struct *task = t->task;
1506
1507 t->task = NULL;
1508 if (task)
1509 wake_up_process(task);
1510
1511 return HRTIMER_NORESTART;
1512 }
1513
1514 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1515 {
1516 sl->timer.function = hrtimer_wakeup;
1517 sl->task = task;
1518 #ifdef CONFIG_HIGH_RES_TIMERS
1519 sl->timer.cb_mode = HRTIMER_CB_IRQSAFE_UNLOCKED;
1520 #endif
1521 }
1522
1523 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1524 {
1525 hrtimer_init_sleeper(t, current);
1526
1527 do {
1528 set_current_state(TASK_INTERRUPTIBLE);
1529 hrtimer_start_expires(&t->timer, mode);
1530 if (!hrtimer_active(&t->timer))
1531 t->task = NULL;
1532
1533 if (likely(t->task))
1534 schedule();
1535
1536 hrtimer_cancel(&t->timer);
1537 mode = HRTIMER_MODE_ABS;
1538
1539 } while (t->task && !signal_pending(current));
1540
1541 __set_current_state(TASK_RUNNING);
1542
1543 return t->task == NULL;
1544 }
1545
1546 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1547 {
1548 struct timespec rmt;
1549 ktime_t rem;
1550
1551 rem = hrtimer_expires_remaining(timer);
1552 if (rem.tv64 <= 0)
1553 return 0;
1554 rmt = ktime_to_timespec(rem);
1555
1556 if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1557 return -EFAULT;
1558
1559 return 1;
1560 }
1561
1562 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1563 {
1564 struct hrtimer_sleeper t;
1565 struct timespec __user *rmtp;
1566 int ret = 0;
1567
1568 hrtimer_init_on_stack(&t.timer, restart->nanosleep.index,
1569 HRTIMER_MODE_ABS);
1570 hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1571
1572 if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1573 goto out;
1574
1575 rmtp = restart->nanosleep.rmtp;
1576 if (rmtp) {
1577 ret = update_rmtp(&t.timer, rmtp);
1578 if (ret <= 0)
1579 goto out;
1580 }
1581
1582 /* The other values in restart are already filled in */
1583 ret = -ERESTART_RESTARTBLOCK;
1584 out:
1585 destroy_hrtimer_on_stack(&t.timer);
1586 return ret;
1587 }
1588
1589 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1590 const enum hrtimer_mode mode, const clockid_t clockid)
1591 {
1592 struct restart_block *restart;
1593 struct hrtimer_sleeper t;
1594 int ret = 0;
1595 unsigned long slack;
1596
1597 slack = current->timer_slack_ns;
1598 if (rt_task(current))
1599 slack = 0;
1600
1601 hrtimer_init_on_stack(&t.timer, clockid, mode);
1602 hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1603 if (do_nanosleep(&t, mode))
1604 goto out;
1605
1606 /* Absolute timers do not update the rmtp value and restart: */
1607 if (mode == HRTIMER_MODE_ABS) {
1608 ret = -ERESTARTNOHAND;
1609 goto out;
1610 }
1611
1612 if (rmtp) {
1613 ret = update_rmtp(&t.timer, rmtp);
1614 if (ret <= 0)
1615 goto out;
1616 }
1617
1618 restart = &current_thread_info()->restart_block;
1619 restart->fn = hrtimer_nanosleep_restart;
1620 restart->nanosleep.index = t.timer.base->index;
1621 restart->nanosleep.rmtp = rmtp;
1622 restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1623
1624 ret = -ERESTART_RESTARTBLOCK;
1625 out:
1626 destroy_hrtimer_on_stack(&t.timer);
1627 return ret;
1628 }
1629
1630 asmlinkage long
1631 sys_nanosleep(struct timespec __user *rqtp, struct timespec __user *rmtp)
1632 {
1633 struct timespec tu;
1634
1635 if (copy_from_user(&tu, rqtp, sizeof(tu)))
1636 return -EFAULT;
1637
1638 if (!timespec_valid(&tu))
1639 return -EINVAL;
1640
1641 return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1642 }
1643
1644 /*
1645 * Functions related to boot-time initialization:
1646 */
1647 static void __cpuinit init_hrtimers_cpu(int cpu)
1648 {
1649 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1650 int i;
1651
1652 spin_lock_init(&cpu_base->lock);
1653
1654 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
1655 cpu_base->clock_base[i].cpu_base = cpu_base;
1656
1657 INIT_LIST_HEAD(&cpu_base->cb_pending);
1658 hrtimer_init_hres(cpu_base);
1659 }
1660
1661 #ifdef CONFIG_HOTPLUG_CPU
1662
1663 static int migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1664 struct hrtimer_clock_base *new_base, int dcpu)
1665 {
1666 struct hrtimer *timer;
1667 struct rb_node *node;
1668 int raise = 0;
1669
1670 while ((node = rb_first(&old_base->active))) {
1671 timer = rb_entry(node, struct hrtimer, node);
1672 BUG_ON(hrtimer_callback_running(timer));
1673 debug_hrtimer_deactivate(timer);
1674
1675 /*
1676 * Should not happen. Per CPU timers should be
1677 * canceled _before_ the migration code is called
1678 */
1679 if (timer->cb_mode == HRTIMER_CB_IRQSAFE_PERCPU) {
1680 __remove_hrtimer(timer, old_base,
1681 HRTIMER_STATE_INACTIVE, 0);
1682 WARN(1, "hrtimer (%p %p)active but cpu %d dead\n",
1683 timer, timer->function, dcpu);
1684 continue;
1685 }
1686
1687 /*
1688 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1689 * timer could be seen as !active and just vanish away
1690 * under us on another CPU
1691 */
1692 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1693 timer->base = new_base;
1694 /*
1695 * Enqueue the timer. Allow reprogramming of the event device
1696 */
1697 enqueue_hrtimer(timer, new_base, 1);
1698
1699 #ifdef CONFIG_HIGH_RES_TIMERS
1700 /*
1701 * Happens with high res enabled when the timer was
1702 * already expired and the callback mode is
1703 * HRTIMER_CB_IRQSAFE_UNLOCKED (hrtimer_sleeper). The
1704 * enqueue code does not move them to the soft irq
1705 * pending list for performance/latency reasons, but
1706 * in the migration state, we need to do that
1707 * otherwise we end up with a stale timer.
1708 */
1709 if (timer->state == HRTIMER_STATE_MIGRATE) {
1710 timer->state = HRTIMER_STATE_PENDING;
1711 list_add_tail(&timer->cb_entry,
1712 &new_base->cpu_base->cb_pending);
1713 raise = 1;
1714 }
1715 #endif
1716 /* Clear the migration state bit */
1717 timer->state &= ~HRTIMER_STATE_MIGRATE;
1718 }
1719 return raise;
1720 }
1721
1722 #ifdef CONFIG_HIGH_RES_TIMERS
1723 static int migrate_hrtimer_pending(struct hrtimer_cpu_base *old_base,
1724 struct hrtimer_cpu_base *new_base)
1725 {
1726 struct hrtimer *timer;
1727 int raise = 0;
1728
1729 while (!list_empty(&old_base->cb_pending)) {
1730 timer = list_entry(old_base->cb_pending.next,
1731 struct hrtimer, cb_entry);
1732
1733 __remove_hrtimer(timer, timer->base, HRTIMER_STATE_PENDING, 0);
1734 timer->base = &new_base->clock_base[timer->base->index];
1735 list_add_tail(&timer->cb_entry, &new_base->cb_pending);
1736 raise = 1;
1737 }
1738 return raise;
1739 }
1740 #else
1741 static int migrate_hrtimer_pending(struct hrtimer_cpu_base *old_base,
1742 struct hrtimer_cpu_base *new_base)
1743 {
1744 return 0;
1745 }
1746 #endif
1747
1748 static void migrate_hrtimers(int cpu)
1749 {
1750 struct hrtimer_cpu_base *old_base, *new_base;
1751 int i, raise = 0;
1752
1753 BUG_ON(cpu_online(cpu));
1754 old_base = &per_cpu(hrtimer_bases, cpu);
1755 new_base = &get_cpu_var(hrtimer_bases);
1756
1757 tick_cancel_sched_timer(cpu);
1758 /*
1759 * The caller is globally serialized and nobody else
1760 * takes two locks at once, deadlock is not possible.
1761 */
1762 spin_lock_irq(&new_base->lock);
1763 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1764
1765 for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1766 if (migrate_hrtimer_list(&old_base->clock_base[i],
1767 &new_base->clock_base[i], cpu))
1768 raise = 1;
1769 }
1770
1771 if (migrate_hrtimer_pending(old_base, new_base))
1772 raise = 1;
1773
1774 spin_unlock(&old_base->lock);
1775 spin_unlock_irq(&new_base->lock);
1776 put_cpu_var(hrtimer_bases);
1777
1778 if (raise)
1779 hrtimer_raise_softirq();
1780 }
1781 #endif /* CONFIG_HOTPLUG_CPU */
1782
1783 static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1784 unsigned long action, void *hcpu)
1785 {
1786 unsigned int cpu = (long)hcpu;
1787
1788 switch (action) {
1789
1790 case CPU_UP_PREPARE:
1791 case CPU_UP_PREPARE_FROZEN:
1792 init_hrtimers_cpu(cpu);
1793 break;
1794
1795 #ifdef CONFIG_HOTPLUG_CPU
1796 case CPU_DEAD:
1797 case CPU_DEAD_FROZEN:
1798 clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &cpu);
1799 migrate_hrtimers(cpu);
1800 break;
1801 #endif
1802
1803 default:
1804 break;
1805 }
1806
1807 return NOTIFY_OK;
1808 }
1809
1810 static struct notifier_block __cpuinitdata hrtimers_nb = {
1811 .notifier_call = hrtimer_cpu_notify,
1812 };
1813
1814 void __init hrtimers_init(void)
1815 {
1816 hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1817 (void *)(long)smp_processor_id());
1818 register_cpu_notifier(&hrtimers_nb);
1819 #ifdef CONFIG_HIGH_RES_TIMERS
1820 open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1821 #endif
1822 }
1823
1824 /**
1825 * schedule_hrtimeout_range - sleep until timeout
1826 * @expires: timeout value (ktime_t)
1827 * @delta: slack in expires timeout (ktime_t)
1828 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1829 *
1830 * Make the current task sleep until the given expiry time has
1831 * elapsed. The routine will return immediately unless
1832 * the current task state has been set (see set_current_state()).
1833 *
1834 * The @delta argument gives the kernel the freedom to schedule the
1835 * actual wakeup to a time that is both power and performance friendly.
1836 * The kernel give the normal best effort behavior for "@expires+@delta",
1837 * but may decide to fire the timer earlier, but no earlier than @expires.
1838 *
1839 * You can set the task state as follows -
1840 *
1841 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1842 * pass before the routine returns.
1843 *
1844 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1845 * delivered to the current task.
1846 *
1847 * The current task state is guaranteed to be TASK_RUNNING when this
1848 * routine returns.
1849 *
1850 * Returns 0 when the timer has expired otherwise -EINTR
1851 */
1852 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1853 const enum hrtimer_mode mode)
1854 {
1855 struct hrtimer_sleeper t;
1856
1857 /*
1858 * Optimize when a zero timeout value is given. It does not
1859 * matter whether this is an absolute or a relative time.
1860 */
1861 if (expires && !expires->tv64) {
1862 __set_current_state(TASK_RUNNING);
1863 return 0;
1864 }
1865
1866 /*
1867 * A NULL parameter means "inifinte"
1868 */
1869 if (!expires) {
1870 schedule();
1871 __set_current_state(TASK_RUNNING);
1872 return -EINTR;
1873 }
1874
1875 hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, mode);
1876 hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1877
1878 hrtimer_init_sleeper(&t, current);
1879
1880 hrtimer_start_expires(&t.timer, mode);
1881 if (!hrtimer_active(&t.timer))
1882 t.task = NULL;
1883
1884 if (likely(t.task))
1885 schedule();
1886
1887 hrtimer_cancel(&t.timer);
1888 destroy_hrtimer_on_stack(&t.timer);
1889
1890 __set_current_state(TASK_RUNNING);
1891
1892 return !t.task ? 0 : -EINTR;
1893 }
1894 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1895
1896 /**
1897 * schedule_hrtimeout - sleep until timeout
1898 * @expires: timeout value (ktime_t)
1899 * @mode: timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1900 *
1901 * Make the current task sleep until the given expiry time has
1902 * elapsed. The routine will return immediately unless
1903 * the current task state has been set (see set_current_state()).
1904 *
1905 * You can set the task state as follows -
1906 *
1907 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1908 * pass before the routine returns.
1909 *
1910 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1911 * delivered to the current task.
1912 *
1913 * The current task state is guaranteed to be TASK_RUNNING when this
1914 * routine returns.
1915 *
1916 * Returns 0 when the timer has expired otherwise -EINTR
1917 */
1918 int __sched schedule_hrtimeout(ktime_t *expires,
1919 const enum hrtimer_mode mode)
1920 {
1921 return schedule_hrtimeout_range(expires, 0, mode);
1922 }
1923 EXPORT_SYMBOL_GPL(schedule_hrtimeout);