Force tick interrupt and get rid of softirq magic
[kvmfornfv.git] / kernel / kernel / time / 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/export.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 #include <linux/sched.h>
47 #include <linux/sched/sysctl.h>
48 #include <linux/sched/rt.h>
49 #include <linux/sched/deadline.h>
50 #include <linux/timer.h>
51 #include <linux/kthread.h>
52 #include <linux/freezer.h>
53
54 #include <asm/uaccess.h>
55
56 #include <trace/events/timer.h>
57 #include <trace/events/hist.h>
58
59 #include "tick-internal.h"
60
61 /*
62  * The timer bases:
63  *
64  * There are more clockids then hrtimer bases. Thus, we index
65  * into the timer bases by the hrtimer_base_type enum. When trying
66  * to reach a base using a clockid, hrtimer_clockid_to_base()
67  * is used to convert from clockid to the proper hrtimer_base_type.
68  */
69 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
70 {
71
72         .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
73         .clock_base =
74         {
75                 {
76                         .index = HRTIMER_BASE_MONOTONIC,
77                         .clockid = CLOCK_MONOTONIC,
78                         .get_time = &ktime_get,
79                         .resolution = KTIME_LOW_RES,
80                 },
81                 {
82                         .index = HRTIMER_BASE_REALTIME,
83                         .clockid = CLOCK_REALTIME,
84                         .get_time = &ktime_get_real,
85                         .resolution = KTIME_LOW_RES,
86                 },
87                 {
88                         .index = HRTIMER_BASE_BOOTTIME,
89                         .clockid = CLOCK_BOOTTIME,
90                         .get_time = &ktime_get_boottime,
91                         .resolution = KTIME_LOW_RES,
92                 },
93                 {
94                         .index = HRTIMER_BASE_TAI,
95                         .clockid = CLOCK_TAI,
96                         .get_time = &ktime_get_clocktai,
97                         .resolution = KTIME_LOW_RES,
98                 },
99         }
100 };
101
102 static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
103         [CLOCK_REALTIME]        = HRTIMER_BASE_REALTIME,
104         [CLOCK_MONOTONIC]       = HRTIMER_BASE_MONOTONIC,
105         [CLOCK_BOOTTIME]        = HRTIMER_BASE_BOOTTIME,
106         [CLOCK_TAI]             = HRTIMER_BASE_TAI,
107 };
108
109 static inline int hrtimer_clockid_to_base(clockid_t clock_id)
110 {
111         return hrtimer_clock_to_base_table[clock_id];
112 }
113
114
115 /*
116  * Get the coarse grained time at the softirq based on xtime and
117  * wall_to_monotonic.
118  */
119 static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
120 {
121         ktime_t xtim, mono, boot, tai;
122         ktime_t off_real, off_boot, off_tai;
123
124         mono = ktime_get_update_offsets_tick(&off_real, &off_boot, &off_tai);
125         boot = ktime_add(mono, off_boot);
126         xtim = ktime_add(mono, off_real);
127         tai = ktime_add(mono, off_tai);
128
129         base->clock_base[HRTIMER_BASE_REALTIME].softirq_time = xtim;
130         base->clock_base[HRTIMER_BASE_MONOTONIC].softirq_time = mono;
131         base->clock_base[HRTIMER_BASE_BOOTTIME].softirq_time = boot;
132         base->clock_base[HRTIMER_BASE_TAI].softirq_time = tai;
133 }
134
135 /*
136  * Functions and macros which are different for UP/SMP systems are kept in a
137  * single place
138  */
139 #ifdef CONFIG_SMP
140
141 /*
142  * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
143  * means that all timers which are tied to this base via timer->base are
144  * locked, and the base itself is locked too.
145  *
146  * So __run_timers/migrate_timers can safely modify all timers which could
147  * be found on the lists/queues.
148  *
149  * When the timer's base is locked, and the timer removed from list, it is
150  * possible to set timer->base = NULL and drop the lock: the timer remains
151  * locked.
152  */
153 static
154 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
155                                              unsigned long *flags)
156 {
157         struct hrtimer_clock_base *base;
158
159         for (;;) {
160                 base = timer->base;
161                 if (likely(base != NULL)) {
162                         raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
163                         if (likely(base == timer->base))
164                                 return base;
165                         /* The timer has migrated to another CPU: */
166                         raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
167                 }
168                 cpu_relax();
169         }
170 }
171
172 /*
173  * With HIGHRES=y we do not migrate the timer when it is expiring
174  * before the next event on the target cpu because we cannot reprogram
175  * the target cpu hardware and we would cause it to fire late.
176  *
177  * Called with cpu_base->lock of target cpu held.
178  */
179 static int
180 hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
181 {
182 #ifdef CONFIG_HIGH_RES_TIMERS
183         ktime_t expires;
184
185         if (!new_base->cpu_base->hres_active)
186                 return 0;
187
188         expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
189         return expires.tv64 <= new_base->cpu_base->expires_next.tv64;
190 #else
191         return 0;
192 #endif
193 }
194
195 /*
196  * Switch the timer base to the current CPU when possible.
197  */
198 static inline struct hrtimer_clock_base *
199 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
200                     int pinned)
201 {
202         struct hrtimer_clock_base *new_base;
203         struct hrtimer_cpu_base *new_cpu_base;
204         int this_cpu = smp_processor_id();
205         int cpu = get_nohz_timer_target(pinned);
206         int basenum = base->index;
207
208 again:
209         new_cpu_base = &per_cpu(hrtimer_bases, cpu);
210         new_base = &new_cpu_base->clock_base[basenum];
211
212         if (base != new_base) {
213                 /*
214                  * We are trying to move timer to new_base.
215                  * However we can't change timer's base while it is running,
216                  * so we keep it on the same CPU. No hassle vs. reprogramming
217                  * the event source in the high resolution case. The softirq
218                  * code will take care of this when the timer function has
219                  * completed. There is no conflict as we hold the lock until
220                  * the timer is enqueued.
221                  */
222                 if (unlikely(hrtimer_callback_running(timer)))
223                         return base;
224
225                 /* See the comment in lock_timer_base() */
226                 timer->base = NULL;
227                 raw_spin_unlock(&base->cpu_base->lock);
228                 raw_spin_lock(&new_base->cpu_base->lock);
229
230                 if (cpu != this_cpu && hrtimer_check_target(timer, new_base)) {
231                         cpu = this_cpu;
232                         raw_spin_unlock(&new_base->cpu_base->lock);
233                         raw_spin_lock(&base->cpu_base->lock);
234                         timer->base = base;
235                         goto again;
236                 }
237                 timer->base = new_base;
238         } else {
239                 if (cpu != this_cpu && hrtimer_check_target(timer, new_base)) {
240                         cpu = this_cpu;
241                         goto again;
242                 }
243         }
244         return new_base;
245 }
246
247 #else /* CONFIG_SMP */
248
249 static inline struct hrtimer_clock_base *
250 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
251 {
252         struct hrtimer_clock_base *base = timer->base;
253
254         raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
255
256         return base;
257 }
258
259 # define switch_hrtimer_base(t, b, p)   (b)
260
261 #endif  /* !CONFIG_SMP */
262
263 /*
264  * Functions for the union type storage format of ktime_t which are
265  * too large for inlining:
266  */
267 #if BITS_PER_LONG < 64
268 /*
269  * Divide a ktime value by a nanosecond value
270  */
271 s64 __ktime_divns(const ktime_t kt, s64 div)
272 {
273         int sft = 0;
274         s64 dclc;
275         u64 tmp;
276
277         dclc = ktime_to_ns(kt);
278         tmp = dclc < 0 ? -dclc : dclc;
279
280         /* Make sure the divisor is less than 2^32: */
281         while (div >> 32) {
282                 sft++;
283                 div >>= 1;
284         }
285         tmp >>= sft;
286         do_div(tmp, (unsigned long) div);
287         return dclc < 0 ? -tmp : tmp;
288 }
289 EXPORT_SYMBOL_GPL(__ktime_divns);
290 #endif /* BITS_PER_LONG >= 64 */
291
292 /*
293  * Add two ktime values and do a safety check for overflow:
294  */
295 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
296 {
297         ktime_t res = ktime_add(lhs, rhs);
298
299         /*
300          * We use KTIME_SEC_MAX here, the maximum timeout which we can
301          * return to user space in a timespec:
302          */
303         if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
304                 res = ktime_set(KTIME_SEC_MAX, 0);
305
306         return res;
307 }
308
309 EXPORT_SYMBOL_GPL(ktime_add_safe);
310
311 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
312
313 static struct debug_obj_descr hrtimer_debug_descr;
314
315 static void *hrtimer_debug_hint(void *addr)
316 {
317         return ((struct hrtimer *) addr)->function;
318 }
319
320 /*
321  * fixup_init is called when:
322  * - an active object is initialized
323  */
324 static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
325 {
326         struct hrtimer *timer = addr;
327
328         switch (state) {
329         case ODEBUG_STATE_ACTIVE:
330                 hrtimer_cancel(timer);
331                 debug_object_init(timer, &hrtimer_debug_descr);
332                 return 1;
333         default:
334                 return 0;
335         }
336 }
337
338 /*
339  * fixup_activate is called when:
340  * - an active object is activated
341  * - an unknown object is activated (might be a statically initialized object)
342  */
343 static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
344 {
345         switch (state) {
346
347         case ODEBUG_STATE_NOTAVAILABLE:
348                 WARN_ON_ONCE(1);
349                 return 0;
350
351         case ODEBUG_STATE_ACTIVE:
352                 WARN_ON(1);
353
354         default:
355                 return 0;
356         }
357 }
358
359 /*
360  * fixup_free is called when:
361  * - an active object is freed
362  */
363 static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
364 {
365         struct hrtimer *timer = addr;
366
367         switch (state) {
368         case ODEBUG_STATE_ACTIVE:
369                 hrtimer_cancel(timer);
370                 debug_object_free(timer, &hrtimer_debug_descr);
371                 return 1;
372         default:
373                 return 0;
374         }
375 }
376
377 static struct debug_obj_descr hrtimer_debug_descr = {
378         .name           = "hrtimer",
379         .debug_hint     = hrtimer_debug_hint,
380         .fixup_init     = hrtimer_fixup_init,
381         .fixup_activate = hrtimer_fixup_activate,
382         .fixup_free     = hrtimer_fixup_free,
383 };
384
385 static inline void debug_hrtimer_init(struct hrtimer *timer)
386 {
387         debug_object_init(timer, &hrtimer_debug_descr);
388 }
389
390 static inline void debug_hrtimer_activate(struct hrtimer *timer)
391 {
392         debug_object_activate(timer, &hrtimer_debug_descr);
393 }
394
395 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
396 {
397         debug_object_deactivate(timer, &hrtimer_debug_descr);
398 }
399
400 static inline void debug_hrtimer_free(struct hrtimer *timer)
401 {
402         debug_object_free(timer, &hrtimer_debug_descr);
403 }
404
405 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
406                            enum hrtimer_mode mode);
407
408 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
409                            enum hrtimer_mode mode)
410 {
411         debug_object_init_on_stack(timer, &hrtimer_debug_descr);
412         __hrtimer_init(timer, clock_id, mode);
413 }
414 EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
415
416 void destroy_hrtimer_on_stack(struct hrtimer *timer)
417 {
418         debug_object_free(timer, &hrtimer_debug_descr);
419 }
420
421 #else
422 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
423 static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
424 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
425 #endif
426
427 static inline void
428 debug_init(struct hrtimer *timer, clockid_t clockid,
429            enum hrtimer_mode mode)
430 {
431         debug_hrtimer_init(timer);
432         trace_hrtimer_init(timer, clockid, mode);
433 }
434
435 static inline void debug_activate(struct hrtimer *timer)
436 {
437         debug_hrtimer_activate(timer);
438         trace_hrtimer_start(timer);
439 }
440
441 static inline void debug_deactivate(struct hrtimer *timer)
442 {
443         debug_hrtimer_deactivate(timer);
444         trace_hrtimer_cancel(timer);
445 }
446
447 #if defined(CONFIG_NO_HZ_COMMON) || defined(CONFIG_HIGH_RES_TIMERS)
448 static ktime_t __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base)
449 {
450         struct hrtimer_clock_base *base = cpu_base->clock_base;
451         ktime_t expires, expires_next = { .tv64 = KTIME_MAX };
452         int i;
453
454         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
455                 struct timerqueue_node *next;
456                 struct hrtimer *timer;
457
458                 next = timerqueue_getnext(&base->active);
459                 if (!next)
460                         continue;
461
462                 timer = container_of(next, struct hrtimer, node);
463                 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
464                 if (expires.tv64 < expires_next.tv64)
465                         expires_next = expires;
466         }
467         /*
468          * clock_was_set() might have changed base->offset of any of
469          * the clock bases so the result might be negative. Fix it up
470          * to prevent a false positive in clockevents_program_event().
471          */
472         if (expires_next.tv64 < 0)
473                 expires_next.tv64 = 0;
474         return expires_next;
475 }
476 #endif
477
478 /* High resolution timer related functions */
479 #ifdef CONFIG_HIGH_RES_TIMERS
480
481 /*
482  * High resolution timer enabled ?
483  */
484 static int hrtimer_hres_enabled __read_mostly  = 1;
485
486 /*
487  * Enable / Disable high resolution mode
488  */
489 static int __init setup_hrtimer_hres(char *str)
490 {
491         if (!strcmp(str, "off"))
492                 hrtimer_hres_enabled = 0;
493         else if (!strcmp(str, "on"))
494                 hrtimer_hres_enabled = 1;
495         else
496                 return 0;
497         return 1;
498 }
499
500 __setup("highres=", setup_hrtimer_hres);
501
502 /*
503  * hrtimer_high_res_enabled - query, if the highres mode is enabled
504  */
505 static inline int hrtimer_is_hres_enabled(void)
506 {
507         return hrtimer_hres_enabled;
508 }
509
510 /*
511  * Is the high resolution mode active ?
512  */
513 static inline int hrtimer_hres_active(void)
514 {
515         return __this_cpu_read(hrtimer_bases.hres_active);
516 }
517
518 /*
519  * Reprogram the event source with checking both queues for the
520  * next event
521  * Called with interrupts disabled and base->lock held
522  */
523 static void
524 hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
525 {
526         ktime_t expires_next = __hrtimer_get_next_event(cpu_base);
527
528         if (skip_equal && expires_next.tv64 == cpu_base->expires_next.tv64)
529                 return;
530
531         cpu_base->expires_next.tv64 = expires_next.tv64;
532
533         /*
534          * If a hang was detected in the last timer interrupt then we
535          * leave the hang delay active in the hardware. We want the
536          * system to make progress. That also prevents the following
537          * scenario:
538          * T1 expires 50ms from now
539          * T2 expires 5s from now
540          *
541          * T1 is removed, so this code is called and would reprogram
542          * the hardware to 5s from now. Any hrtimer_start after that
543          * will not reprogram the hardware due to hang_detected being
544          * set. So we'd effectivly block all timers until the T2 event
545          * fires.
546          */
547         if (cpu_base->hang_detected)
548                 return;
549
550         if (cpu_base->expires_next.tv64 != KTIME_MAX)
551                 tick_program_event(cpu_base->expires_next, 1);
552 }
553
554 /*
555  * Shared reprogramming for clock_realtime and clock_monotonic
556  *
557  * When a timer is enqueued and expires earlier than the already enqueued
558  * timers, we have to check, whether it expires earlier than the timer for
559  * which the clock event device was armed.
560  *
561  * Note, that in case the state has HRTIMER_STATE_CALLBACK set, no reprogramming
562  * and no expiry check happens. The timer gets enqueued into the rbtree. The
563  * reprogramming and expiry check is done in the hrtimer_interrupt or in the
564  * softirq.
565  *
566  * Called with interrupts disabled and base->cpu_base.lock held
567  */
568 static int hrtimer_reprogram(struct hrtimer *timer,
569                              struct hrtimer_clock_base *base)
570 {
571         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
572         ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
573         int res;
574
575         WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
576
577         /*
578          * When the callback is running, we do not reprogram the clock event
579          * device. The timer callback is either running on a different CPU or
580          * the callback is executed in the hrtimer_interrupt context. The
581          * reprogramming is handled at the end of the hrtimer_interrupt.
582          */
583         if (hrtimer_callback_running(timer))
584                 return 0;
585
586         if (base->cpu_base != cpu_base)
587                 return 0;
588
589        if (cpu_base->in_hrtirq)
590                return 0;
591
592         /*
593          * CLOCK_REALTIME timer might be requested with an absolute
594          * expiry time which is less than base->offset. Nothing wrong
595          * about that, just avoid to call into the tick code, which
596          * has now objections against negative expiry values.
597          */
598         if (expires.tv64 < 0)
599                 return -ETIME;
600
601         if (expires.tv64 >= cpu_base->expires_next.tv64)
602                 return 0;
603
604         /*
605          * When the target cpu of the timer is currently executing
606          * hrtimer_interrupt(), then we do not touch the clock event
607          * device. hrtimer_interrupt() will reevaluate all clock bases
608          * before reprogramming the device.
609          */
610         if (cpu_base->in_hrtirq)
611                 return 0;
612
613         /*
614          * If a hang was detected in the last timer interrupt then we
615          * do not schedule a timer which is earlier than the expiry
616          * which we enforced in the hang detection. We want the system
617          * to make progress.
618          */
619         if (cpu_base->hang_detected)
620                 return 0;
621
622         cpu_base->expires_next = expires;
623         /*
624          * Clockevents returns -ETIME, when the event was in the past.
625          */
626         res = tick_program_event(expires, 1);
627         return res;
628 }
629
630 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now);
631 static int hrtimer_rt_defer(struct hrtimer *timer);
632
633 /*
634  * Initialize the high resolution related parts of cpu_base
635  */
636 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
637 {
638         base->expires_next.tv64 = KTIME_MAX;
639         base->hres_active = 0;
640 }
641
642 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
643                                             struct hrtimer_clock_base *base,
644                                             int wakeup)
645 {
646         if (!hrtimer_reprogram(timer, base))
647                 return 0;
648         if (!wakeup)
649                 return -ETIME;
650 #ifdef CONFIG_PREEMPT_RT_BASE
651         if (!hrtimer_rt_defer(timer))
652                 return -ETIME;
653 #endif
654         return 1;
655 }
656
657 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
658 {
659         ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
660         ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
661         ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
662
663         return ktime_get_update_offsets_now(offs_real, offs_boot, offs_tai);
664 }
665
666 /*
667  * Retrigger next event is called after clock was set
668  *
669  * Called with interrupts disabled via on_each_cpu()
670  */
671 static void retrigger_next_event(void *arg)
672 {
673         struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
674
675         if (!hrtimer_hres_active())
676                 return;
677
678         raw_spin_lock(&base->lock);
679         hrtimer_update_base(base);
680         hrtimer_force_reprogram(base, 0);
681         raw_spin_unlock(&base->lock);
682 }
683
684 /*
685  * Switch to high resolution mode
686  */
687 static int hrtimer_switch_to_hres(void)
688 {
689         int i, cpu = smp_processor_id();
690         struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
691         unsigned long flags;
692
693         if (base->hres_active)
694                 return 1;
695
696         local_irq_save(flags);
697
698         if (tick_init_highres()) {
699                 local_irq_restore(flags);
700                 printk(KERN_WARNING "Could not switch to high resolution "
701                                     "mode on CPU %d\n", cpu);
702                 return 0;
703         }
704         base->hres_active = 1;
705         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
706                 base->clock_base[i].resolution = KTIME_HIGH_RES;
707
708         tick_setup_sched_timer();
709         /* "Retrigger" the interrupt to get things going */
710         retrigger_next_event(NULL);
711         local_irq_restore(flags);
712         return 1;
713 }
714
715 static void clock_was_set_work(struct work_struct *work)
716 {
717         clock_was_set();
718 }
719
720 static DECLARE_WORK(hrtimer_work, clock_was_set_work);
721
722 #ifdef CONFIG_PREEMPT_RT_FULL
723 /*
724  * RT can not call schedule_work from real interrupt context.
725  * Need to make a thread to do the real work.
726  */
727 static struct task_struct *clock_set_delay_thread;
728 static bool do_clock_set_delay;
729
730 static int run_clock_set_delay(void *ignore)
731 {
732         while (!kthread_should_stop()) {
733                 set_current_state(TASK_INTERRUPTIBLE);
734                 if (do_clock_set_delay) {
735                         do_clock_set_delay = false;
736                         schedule_work(&hrtimer_work);
737                 }
738                 schedule();
739         }
740         __set_current_state(TASK_RUNNING);
741         return 0;
742 }
743
744 void clock_was_set_delayed(void)
745 {
746         do_clock_set_delay = true;
747         /* Make visible before waking up process */
748         smp_wmb();
749         wake_up_process(clock_set_delay_thread);
750 }
751
752 static __init int create_clock_set_delay_thread(void)
753 {
754         clock_set_delay_thread = kthread_run(run_clock_set_delay, NULL, "kclksetdelayd");
755         BUG_ON(!clock_set_delay_thread);
756         return 0;
757 }
758 early_initcall(create_clock_set_delay_thread);
759 #else /* PREEMPT_RT_FULL */
760 /*
761  * Called from timekeeping and resume code to reprogramm the hrtimer
762  * interrupt device on all cpus.
763  */
764 void clock_was_set_delayed(void)
765 {
766         schedule_work(&hrtimer_work);
767 }
768 #endif
769
770 #else
771
772 static inline int hrtimer_hres_active(void) { return 0; }
773 static inline int hrtimer_is_hres_enabled(void) { return 0; }
774 static inline int hrtimer_switch_to_hres(void) { return 0; }
775 static inline void
776 hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
777 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
778                                             struct hrtimer_clock_base *base,
779                                             int wakeup)
780 {
781         return 0;
782 }
783
784 static inline int hrtimer_reprogram(struct hrtimer *timer,
785                                     struct hrtimer_clock_base *base)
786 {
787         return 0;
788 }
789 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
790 static inline void retrigger_next_event(void *arg) { }
791 #endif /* CONFIG_HIGH_RES_TIMERS */
792
793 /*
794  * Clock realtime was set
795  *
796  * Change the offset of the realtime clock vs. the monotonic
797  * clock.
798  *
799  * We might have to reprogram the high resolution timer interrupt. On
800  * SMP we call the architecture specific code to retrigger _all_ high
801  * resolution timer interrupts. On UP we just disable interrupts and
802  * call the high resolution interrupt code.
803  */
804 void clock_was_set(void)
805 {
806 #ifdef CONFIG_HIGH_RES_TIMERS
807         /* Retrigger the CPU local events everywhere */
808         on_each_cpu(retrigger_next_event, NULL, 1);
809 #endif
810         timerfd_clock_was_set();
811 }
812
813 /*
814  * During resume we might have to reprogram the high resolution timer
815  * interrupt on all online CPUs.  However, all other CPUs will be
816  * stopped with IRQs interrupts disabled so the clock_was_set() call
817  * must be deferred.
818  */
819 void hrtimers_resume(void)
820 {
821         WARN_ONCE(!irqs_disabled(),
822                   KERN_INFO "hrtimers_resume() called with IRQs enabled!");
823
824         /* Retrigger on the local CPU */
825         retrigger_next_event(NULL);
826         /* And schedule a retrigger for all others */
827         clock_was_set_delayed();
828 }
829
830 static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
831 {
832 #ifdef CONFIG_TIMER_STATS
833         if (timer->start_site)
834                 return;
835         timer->start_site = __builtin_return_address(0);
836         memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
837         timer->start_pid = current->pid;
838 #endif
839 }
840
841 static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
842 {
843 #ifdef CONFIG_TIMER_STATS
844         timer->start_site = NULL;
845 #endif
846 }
847
848 static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
849 {
850 #ifdef CONFIG_TIMER_STATS
851         if (likely(!timer_stats_active))
852                 return;
853         timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
854                                  timer->function, timer->start_comm, 0);
855 #endif
856 }
857
858 /*
859  * Counterpart to lock_hrtimer_base above:
860  */
861 static inline
862 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
863 {
864         raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
865 }
866
867 /**
868  * hrtimer_forward - forward the timer expiry
869  * @timer:      hrtimer to forward
870  * @now:        forward past this time
871  * @interval:   the interval to forward
872  *
873  * Forward the timer expiry so it will expire in the future.
874  * Returns the number of overruns.
875  */
876 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
877 {
878         u64 orun = 1;
879         ktime_t delta;
880
881         delta = ktime_sub(now, hrtimer_get_expires(timer));
882
883         if (delta.tv64 < 0)
884                 return 0;
885
886         if (interval.tv64 < timer->base->resolution.tv64)
887                 interval.tv64 = timer->base->resolution.tv64;
888
889         if (unlikely(delta.tv64 >= interval.tv64)) {
890                 s64 incr = ktime_to_ns(interval);
891
892                 orun = ktime_divns(delta, incr);
893                 hrtimer_add_expires_ns(timer, incr * orun);
894                 if (hrtimer_get_expires_tv64(timer) > now.tv64)
895                         return orun;
896                 /*
897                  * This (and the ktime_add() below) is the
898                  * correction for exact:
899                  */
900                 orun++;
901         }
902         hrtimer_add_expires(timer, interval);
903
904         return orun;
905 }
906 EXPORT_SYMBOL_GPL(hrtimer_forward);
907
908 #ifdef CONFIG_PREEMPT_RT_BASE
909 # define wake_up_timer_waiters(b)       wake_up(&(b)->wait)
910
911 /**
912  * hrtimer_wait_for_timer - Wait for a running timer
913  *
914  * @timer:      timer to wait for
915  *
916  * The function waits in case the timers callback function is
917  * currently executed on the waitqueue of the timer base. The
918  * waitqueue is woken up after the timer callback function has
919  * finished execution.
920  */
921 void hrtimer_wait_for_timer(const struct hrtimer *timer)
922 {
923         struct hrtimer_clock_base *base = timer->base;
924
925         if (base && base->cpu_base && !timer->irqsafe)
926                 wait_event(base->cpu_base->wait,
927                            !(timer->state & HRTIMER_STATE_CALLBACK));
928 }
929
930 #else
931 # define wake_up_timer_waiters(b)       do { } while (0)
932 #endif
933
934 /*
935  * enqueue_hrtimer - internal function to (re)start a timer
936  *
937  * The timer is inserted in expiry order. Insertion into the
938  * red black tree is O(log(n)). Must hold the base lock.
939  *
940  * Returns 1 when the new timer is the leftmost timer in the tree.
941  */
942 static int enqueue_hrtimer(struct hrtimer *timer,
943                            struct hrtimer_clock_base *base)
944 {
945         debug_activate(timer);
946
947         timerqueue_add(&base->active, &timer->node);
948         base->cpu_base->active_bases |= 1 << base->index;
949
950         /*
951          * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
952          * state of a possibly running callback.
953          */
954         timer->state |= HRTIMER_STATE_ENQUEUED;
955
956         return (&timer->node == base->active.next);
957 }
958
959 /*
960  * __remove_hrtimer - internal function to remove a timer
961  *
962  * Caller must hold the base lock.
963  *
964  * High resolution timer mode reprograms the clock event device when the
965  * timer is the one which expires next. The caller can disable this by setting
966  * reprogram to zero. This is useful, when the context does a reprogramming
967  * anyway (e.g. timer interrupt)
968  */
969 static void __remove_hrtimer(struct hrtimer *timer,
970                              struct hrtimer_clock_base *base,
971                              unsigned long newstate, int reprogram)
972 {
973         struct timerqueue_node *next_timer;
974         if (!(timer->state & HRTIMER_STATE_ENQUEUED))
975                 goto out;
976
977         if (unlikely(!list_empty(&timer->cb_entry))) {
978                 list_del_init(&timer->cb_entry);
979                 goto out;
980         }
981
982         next_timer = timerqueue_getnext(&base->active);
983         timerqueue_del(&base->active, &timer->node);
984         if (&timer->node == next_timer) {
985 #ifdef CONFIG_HIGH_RES_TIMERS
986                 /* Reprogram the clock event device. if enabled */
987                 if (reprogram && hrtimer_hres_active()) {
988                         ktime_t expires;
989
990                         expires = ktime_sub(hrtimer_get_expires(timer),
991                                             base->offset);
992                         if (base->cpu_base->expires_next.tv64 == expires.tv64)
993                                 hrtimer_force_reprogram(base->cpu_base, 1);
994                 }
995 #endif
996         }
997         if (!timerqueue_getnext(&base->active))
998                 base->cpu_base->active_bases &= ~(1 << base->index);
999 out:
1000         timer->state = newstate;
1001 }
1002
1003 /*
1004  * remove hrtimer, called with base lock held
1005  */
1006 static inline int
1007 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
1008 {
1009         if (hrtimer_is_queued(timer)) {
1010                 unsigned long state;
1011                 int reprogram;
1012
1013                 /*
1014                  * Remove the timer and force reprogramming when high
1015                  * resolution mode is active and the timer is on the current
1016                  * CPU. If we remove a timer on another CPU, reprogramming is
1017                  * skipped. The interrupt event on this CPU is fired and
1018                  * reprogramming happens in the interrupt handler. This is a
1019                  * rare case and less expensive than a smp call.
1020                  */
1021                 debug_deactivate(timer);
1022                 timer_stats_hrtimer_clear_start_info(timer);
1023                 reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1024                 /*
1025                  * We must preserve the CALLBACK state flag here,
1026                  * otherwise we could move the timer base in
1027                  * switch_hrtimer_base.
1028                  */
1029                 state = timer->state & HRTIMER_STATE_CALLBACK;
1030                 __remove_hrtimer(timer, base, state, reprogram);
1031                 return 1;
1032         }
1033         return 0;
1034 }
1035
1036 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1037                 unsigned long delta_ns, const enum hrtimer_mode mode,
1038                 int wakeup)
1039 {
1040         struct hrtimer_clock_base *base, *new_base;
1041         unsigned long flags;
1042         int ret, leftmost;
1043
1044         base = lock_hrtimer_base(timer, &flags);
1045
1046         /* Remove an active timer from the queue: */
1047         ret = remove_hrtimer(timer, base);
1048
1049         if (mode & HRTIMER_MODE_REL) {
1050                 tim = ktime_add_safe(tim, base->get_time());
1051                 /*
1052                  * CONFIG_TIME_LOW_RES is a temporary way for architectures
1053                  * to signal that they simply return xtime in
1054                  * do_gettimeoffset(). In this case we want to round up by
1055                  * resolution when starting a relative timer, to avoid short
1056                  * timeouts. This will go away with the GTOD framework.
1057                  */
1058 #ifdef CONFIG_TIME_LOW_RES
1059                 tim = ktime_add_safe(tim, base->resolution);
1060 #endif
1061         }
1062
1063         hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1064
1065         /* Switch the timer base, if necessary: */
1066         new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
1067
1068         timer_stats_hrtimer_set_start_info(timer);
1069 #ifdef CONFIG_MISSED_TIMER_OFFSETS_HIST
1070         {
1071                 ktime_t now = new_base->get_time();
1072
1073                 if (ktime_to_ns(tim) < ktime_to_ns(now))
1074                         timer->praecox = now;
1075                 else
1076                         timer->praecox = ktime_set(0, 0);
1077         }
1078 #endif
1079         leftmost = enqueue_hrtimer(timer, new_base);
1080
1081         if (!leftmost) {
1082                 unlock_hrtimer_base(timer, &flags);
1083                 return ret;
1084         }
1085
1086         if (!hrtimer_is_hres_active(timer)) {
1087                 /*
1088                  * Kick to reschedule the next tick to handle the new timer
1089                  * on dynticks target.
1090                  */
1091                 wake_up_nohz_cpu(new_base->cpu_base->cpu);
1092         } else if (new_base->cpu_base == this_cpu_ptr(&hrtimer_bases)) {
1093
1094                 ret = hrtimer_enqueue_reprogram(timer, new_base, wakeup);
1095                 if (ret < 0) {
1096                         /*
1097                          * In case we failed to reprogram the timer (mostly
1098                          * because out current timer is already elapsed),
1099                          * remove it again and report a failure. This avoids
1100                          * stale base->first entries.
1101                          */
1102                         debug_deactivate(timer);
1103                         __remove_hrtimer(timer, new_base,
1104                                 timer->state & HRTIMER_STATE_CALLBACK, 0);
1105                 } else if (ret > 0) {
1106                 /*
1107                  * Only allow reprogramming if the new base is on this CPU.
1108                  * (it might still be on another CPU if the timer was pending)
1109                  *
1110                  * XXX send_remote_softirq() ?
1111                  */
1112                         /*
1113                          * We need to drop cpu_base->lock to avoid a
1114                          * lock ordering issue vs. rq->lock.
1115                          */
1116                         raw_spin_unlock(&new_base->cpu_base->lock);
1117                         raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1118                         local_irq_restore(flags);
1119                         return 0;
1120                 }
1121         }
1122
1123         unlock_hrtimer_base(timer, &flags);
1124
1125         return ret;
1126 }
1127 EXPORT_SYMBOL_GPL(__hrtimer_start_range_ns);
1128
1129 /**
1130  * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1131  * @timer:      the timer to be added
1132  * @tim:        expiry time
1133  * @delta_ns:   "slack" range for the timer
1134  * @mode:       expiry mode: absolute (HRTIMER_MODE_ABS) or
1135  *              relative (HRTIMER_MODE_REL)
1136  *
1137  * Returns:
1138  *  0 on success
1139  *  1 when the timer was active
1140  */
1141 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1142                 unsigned long delta_ns, const enum hrtimer_mode mode)
1143 {
1144         return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1145 }
1146 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1147
1148 /**
1149  * hrtimer_start - (re)start an hrtimer on the current CPU
1150  * @timer:      the timer to be added
1151  * @tim:        expiry time
1152  * @mode:       expiry mode: absolute (HRTIMER_MODE_ABS) or
1153  *              relative (HRTIMER_MODE_REL)
1154  *
1155  * Returns:
1156  *  0 on success
1157  *  1 when the timer was active
1158  */
1159 int
1160 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1161 {
1162         return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1163 }
1164 EXPORT_SYMBOL_GPL(hrtimer_start);
1165
1166
1167 /**
1168  * hrtimer_try_to_cancel - try to deactivate a timer
1169  * @timer:      hrtimer to stop
1170  *
1171  * Returns:
1172  *  0 when the timer was not active
1173  *  1 when the timer was active
1174  * -1 when the timer is currently excuting the callback function and
1175  *    cannot be stopped
1176  */
1177 int hrtimer_try_to_cancel(struct hrtimer *timer)
1178 {
1179         struct hrtimer_clock_base *base;
1180         unsigned long flags;
1181         int ret = -1;
1182
1183         base = lock_hrtimer_base(timer, &flags);
1184
1185         if (!hrtimer_callback_running(timer))
1186                 ret = remove_hrtimer(timer, base);
1187
1188         unlock_hrtimer_base(timer, &flags);
1189
1190         return ret;
1191
1192 }
1193 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1194
1195 /**
1196  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1197  * @timer:      the timer to be cancelled
1198  *
1199  * Returns:
1200  *  0 when the timer was not active
1201  *  1 when the timer was active
1202  */
1203 int hrtimer_cancel(struct hrtimer *timer)
1204 {
1205         for (;;) {
1206                 int ret = hrtimer_try_to_cancel(timer);
1207
1208                 if (ret >= 0)
1209                         return ret;
1210                 hrtimer_wait_for_timer(timer);
1211         }
1212 }
1213 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1214
1215 /**
1216  * hrtimer_get_remaining - get remaining time for the timer
1217  * @timer:      the timer to read
1218  */
1219 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1220 {
1221         unsigned long flags;
1222         ktime_t rem;
1223
1224         lock_hrtimer_base(timer, &flags);
1225         rem = hrtimer_expires_remaining(timer);
1226         unlock_hrtimer_base(timer, &flags);
1227
1228         return rem;
1229 }
1230 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1231
1232 #ifdef CONFIG_NO_HZ_COMMON
1233 /**
1234  * hrtimer_get_next_event - get the time until next expiry event
1235  *
1236  * Returns the delta to the next expiry event or KTIME_MAX if no timer
1237  * is pending.
1238  */
1239 ktime_t hrtimer_get_next_event(void)
1240 {
1241         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1242         ktime_t mindelta = { .tv64 = KTIME_MAX };
1243         unsigned long flags;
1244
1245         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1246
1247         if (!hrtimer_hres_active())
1248                 mindelta = ktime_sub(__hrtimer_get_next_event(cpu_base),
1249                                      ktime_get());
1250
1251         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1252
1253         if (mindelta.tv64 < 0)
1254                 mindelta.tv64 = 0;
1255         return mindelta;
1256 }
1257 #endif
1258
1259 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1260                            enum hrtimer_mode mode)
1261 {
1262         struct hrtimer_cpu_base *cpu_base;
1263         int base;
1264
1265         memset(timer, 0, sizeof(struct hrtimer));
1266
1267         cpu_base = raw_cpu_ptr(&hrtimer_bases);
1268
1269         if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1270                 clock_id = CLOCK_MONOTONIC;
1271
1272         base = hrtimer_clockid_to_base(clock_id);
1273         timer->base = &cpu_base->clock_base[base];
1274         INIT_LIST_HEAD(&timer->cb_entry);
1275         timerqueue_init(&timer->node);
1276
1277 #ifdef CONFIG_TIMER_STATS
1278         timer->start_site = NULL;
1279         timer->start_pid = -1;
1280         memset(timer->start_comm, 0, TASK_COMM_LEN);
1281 #endif
1282 }
1283
1284 /**
1285  * hrtimer_init - initialize a timer to the given clock
1286  * @timer:      the timer to be initialized
1287  * @clock_id:   the clock to be used
1288  * @mode:       timer mode abs/rel
1289  */
1290 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1291                   enum hrtimer_mode mode)
1292 {
1293         debug_init(timer, clock_id, mode);
1294         __hrtimer_init(timer, clock_id, mode);
1295 }
1296 EXPORT_SYMBOL_GPL(hrtimer_init);
1297
1298 /**
1299  * hrtimer_get_res - get the timer resolution for a clock
1300  * @which_clock: which clock to query
1301  * @tp:          pointer to timespec variable to store the resolution
1302  *
1303  * Store the resolution of the clock selected by @which_clock in the
1304  * variable pointed to by @tp.
1305  */
1306 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1307 {
1308         struct hrtimer_cpu_base *cpu_base;
1309         int base = hrtimer_clockid_to_base(which_clock);
1310
1311         cpu_base = raw_cpu_ptr(&hrtimer_bases);
1312         *tp = ktime_to_timespec(cpu_base->clock_base[base].resolution);
1313
1314         return 0;
1315 }
1316 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1317
1318 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now)
1319 {
1320         struct hrtimer_clock_base *base = timer->base;
1321         struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1322         enum hrtimer_restart (*fn)(struct hrtimer *);
1323         int restart;
1324
1325         WARN_ON(!irqs_disabled());
1326
1327         debug_deactivate(timer);
1328         __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1329         timer_stats_account_hrtimer(timer);
1330         fn = timer->function;
1331
1332         /*
1333          * Because we run timers from hardirq context, there is no chance
1334          * they get migrated to another cpu, therefore its safe to unlock
1335          * the timer base.
1336          */
1337         raw_spin_unlock(&cpu_base->lock);
1338         trace_hrtimer_expire_entry(timer, now);
1339         restart = fn(timer);
1340         trace_hrtimer_expire_exit(timer);
1341         raw_spin_lock(&cpu_base->lock);
1342
1343         /*
1344          * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1345          * we do not reprogramm the event hardware. Happens either in
1346          * hrtimer_start_range_ns() or in hrtimer_interrupt()
1347          */
1348         if (restart != HRTIMER_NORESTART) {
1349                 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1350                 enqueue_hrtimer(timer, base);
1351         }
1352
1353         WARN_ON_ONCE(!(timer->state & HRTIMER_STATE_CALLBACK));
1354
1355         timer->state &= ~HRTIMER_STATE_CALLBACK;
1356 }
1357
1358 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer);
1359
1360 #ifdef CONFIG_PREEMPT_RT_BASE
1361 static void hrtimer_rt_reprogram(int restart, struct hrtimer *timer,
1362                                  struct hrtimer_clock_base *base)
1363 {
1364         /*
1365          * Note, we clear the callback flag before we requeue the
1366          * timer otherwise we trigger the callback_running() check
1367          * in hrtimer_reprogram().
1368          */
1369         timer->state &= ~HRTIMER_STATE_CALLBACK;
1370
1371         if (restart != HRTIMER_NORESTART) {
1372                 BUG_ON(hrtimer_active(timer));
1373                 /*
1374                  * Enqueue the timer, if it's the leftmost timer then
1375                  * we need to reprogram it.
1376                  */
1377                 if (!enqueue_hrtimer(timer, base))
1378                         return;
1379
1380 #ifndef CONFIG_HIGH_RES_TIMERS
1381         }
1382 #else
1383                 if (base->cpu_base->hres_active &&
1384                     hrtimer_reprogram(timer, base))
1385                         goto requeue;
1386
1387         } else if (hrtimer_active(timer)) {
1388                 /*
1389                  * If the timer was rearmed on another CPU, reprogram
1390                  * the event device.
1391                  */
1392                 if (&timer->node == base->active.next &&
1393                     base->cpu_base->hres_active &&
1394                     hrtimer_reprogram(timer, base))
1395                         goto requeue;
1396         }
1397         return;
1398
1399 requeue:
1400         /*
1401          * Timer is expired. Thus move it from tree to pending list
1402          * again.
1403          */
1404         __remove_hrtimer(timer, base, timer->state, 0);
1405         list_add_tail(&timer->cb_entry, &base->expired);
1406 #endif
1407 }
1408
1409 /*
1410  * The changes in mainline which removed the callback modes from
1411  * hrtimer are not yet working with -rt. The non wakeup_process()
1412  * based callbacks which involve sleeping locks need to be treated
1413  * seperately.
1414  */
1415 static void hrtimer_rt_run_pending(void)
1416 {
1417         enum hrtimer_restart (*fn)(struct hrtimer *);
1418         struct hrtimer_cpu_base *cpu_base;
1419         struct hrtimer_clock_base *base;
1420         struct hrtimer *timer;
1421         int index, restart;
1422
1423         local_irq_disable();
1424         cpu_base = &per_cpu(hrtimer_bases, smp_processor_id());
1425
1426         raw_spin_lock(&cpu_base->lock);
1427
1428         for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1429                 base = &cpu_base->clock_base[index];
1430
1431                 while (!list_empty(&base->expired)) {
1432                         timer = list_first_entry(&base->expired,
1433                                                  struct hrtimer, cb_entry);
1434
1435                         /*
1436                          * Same as the above __run_hrtimer function
1437                          * just we run with interrupts enabled.
1438                          */
1439                         debug_hrtimer_deactivate(timer);
1440                         __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1441                         timer_stats_account_hrtimer(timer);
1442                         fn = timer->function;
1443
1444                         raw_spin_unlock_irq(&cpu_base->lock);
1445                         restart = fn(timer);
1446                         raw_spin_lock_irq(&cpu_base->lock);
1447
1448                         hrtimer_rt_reprogram(restart, timer, base);
1449                 }
1450         }
1451
1452         raw_spin_unlock_irq(&cpu_base->lock);
1453
1454         wake_up_timer_waiters(cpu_base);
1455 }
1456
1457 static int hrtimer_rt_defer(struct hrtimer *timer)
1458 {
1459         if (timer->irqsafe)
1460                 return 0;
1461
1462         __remove_hrtimer(timer, timer->base, timer->state, 0);
1463         list_add_tail(&timer->cb_entry, &timer->base->expired);
1464         return 1;
1465 }
1466
1467 #else
1468
1469 static inline void hrtimer_rt_run_pending(void)
1470 {
1471         hrtimer_peek_ahead_timers();
1472 }
1473
1474 static inline int hrtimer_rt_defer(struct hrtimer *timer) { return 0; }
1475
1476 #endif
1477
1478 #ifdef CONFIG_HIGH_RES_TIMERS
1479
1480 /*
1481  * High resolution timer interrupt
1482  * Called with interrupts disabled
1483  */
1484 void hrtimer_interrupt(struct clock_event_device *dev)
1485 {
1486         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1487         ktime_t expires_next, now, entry_time, delta;
1488         int i, retries = 0, raise = 0;
1489
1490         BUG_ON(!cpu_base->hres_active);
1491         cpu_base->nr_events++;
1492         dev->next_event.tv64 = KTIME_MAX;
1493
1494         raw_spin_lock(&cpu_base->lock);
1495         entry_time = now = hrtimer_update_base(cpu_base);
1496 retry:
1497         cpu_base->in_hrtirq = 1;
1498         /*
1499          * We set expires_next to KTIME_MAX here with cpu_base->lock
1500          * held to prevent that a timer is enqueued in our queue via
1501          * the migration code. This does not affect enqueueing of
1502          * timers which run their callback and need to be requeued on
1503          * this CPU.
1504          */
1505         cpu_base->expires_next.tv64 = KTIME_MAX;
1506
1507         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1508                 struct hrtimer_clock_base *base;
1509                 struct timerqueue_node *node;
1510                 ktime_t basenow;
1511
1512                 if (!(cpu_base->active_bases & (1 << i)))
1513                         continue;
1514
1515                 base = cpu_base->clock_base + i;
1516                 basenow = ktime_add(now, base->offset);
1517
1518                 while ((node = timerqueue_getnext(&base->active))) {
1519                         struct hrtimer *timer;
1520
1521                         timer = container_of(node, struct hrtimer, node);
1522
1523                         trace_hrtimer_interrupt(raw_smp_processor_id(),
1524                             ktime_to_ns(ktime_sub(ktime_to_ns(timer->praecox) ?
1525                                 timer->praecox : hrtimer_get_expires(timer),
1526                                 basenow)),
1527                             current,
1528                             timer->function == hrtimer_wakeup ?
1529                             container_of(timer, struct hrtimer_sleeper,
1530                                 timer)->task : NULL);
1531
1532                         /*
1533                          * The immediate goal for using the softexpires is
1534                          * minimizing wakeups, not running timers at the
1535                          * earliest interrupt after their soft expiration.
1536                          * This allows us to avoid using a Priority Search
1537                          * Tree, which can answer a stabbing querry for
1538                          * overlapping intervals and instead use the simple
1539                          * BST we already have.
1540                          * We don't add extra wakeups by delaying timers that
1541                          * are right-of a not yet expired timer, because that
1542                          * timer will have to trigger a wakeup anyway.
1543                          */
1544                         if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer))
1545                                 break;
1546
1547                         if (!hrtimer_rt_defer(timer))
1548                                 __run_hrtimer(timer, &basenow);
1549                         else
1550                                 raise = 1;
1551                 }
1552         }
1553         /* Reevaluate the clock bases for the next expiry */
1554         expires_next = __hrtimer_get_next_event(cpu_base);
1555         /*
1556          * Store the new expiry value so the migration code can verify
1557          * against it.
1558          */
1559         cpu_base->expires_next = expires_next;
1560         cpu_base->in_hrtirq = 0;
1561         raw_spin_unlock(&cpu_base->lock);
1562
1563         /* Reprogramming necessary ? */
1564         if (expires_next.tv64 == KTIME_MAX ||
1565             !tick_program_event(expires_next, 0)) {
1566                 cpu_base->hang_detected = 0;
1567                 goto out;
1568         }
1569
1570         /*
1571          * The next timer was already expired due to:
1572          * - tracing
1573          * - long lasting callbacks
1574          * - being scheduled away when running in a VM
1575          *
1576          * We need to prevent that we loop forever in the hrtimer
1577          * interrupt routine. We give it 3 attempts to avoid
1578          * overreacting on some spurious event.
1579          *
1580          * Acquire base lock for updating the offsets and retrieving
1581          * the current time.
1582          */
1583         raw_spin_lock(&cpu_base->lock);
1584         now = hrtimer_update_base(cpu_base);
1585         cpu_base->nr_retries++;
1586         if (++retries < 3)
1587                 goto retry;
1588         /*
1589          * Give the system a chance to do something else than looping
1590          * here. We stored the entry time, so we know exactly how long
1591          * we spent here. We schedule the next event this amount of
1592          * time away.
1593          */
1594         cpu_base->nr_hangs++;
1595         cpu_base->hang_detected = 1;
1596         raw_spin_unlock(&cpu_base->lock);
1597         delta = ktime_sub(now, entry_time);
1598         if (delta.tv64 > cpu_base->max_hang_time.tv64)
1599                 cpu_base->max_hang_time = delta;
1600         /*
1601          * Limit it to a sensible value as we enforce a longer
1602          * delay. Give the CPU at least 100ms to catch up.
1603          */
1604         if (delta.tv64 > 100 * NSEC_PER_MSEC)
1605                 expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1606         else
1607                 expires_next = ktime_add(now, delta);
1608         tick_program_event(expires_next, 1);
1609         printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1610                     ktime_to_ns(delta));
1611 out:
1612         if (raise)
1613                 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1614 }
1615
1616 /*
1617  * local version of hrtimer_peek_ahead_timers() called with interrupts
1618  * disabled.
1619  */
1620 static void __hrtimer_peek_ahead_timers(void)
1621 {
1622         struct tick_device *td;
1623
1624         if (!hrtimer_hres_active())
1625                 return;
1626
1627         td = this_cpu_ptr(&tick_cpu_device);
1628         if (td && td->evtdev)
1629                 hrtimer_interrupt(td->evtdev);
1630 }
1631
1632 /**
1633  * hrtimer_peek_ahead_timers -- run soft-expired timers now
1634  *
1635  * hrtimer_peek_ahead_timers will peek at the timer queue of
1636  * the current cpu and check if there are any timers for which
1637  * the soft expires time has passed. If any such timers exist,
1638  * they are run immediately and then removed from the timer queue.
1639  *
1640  */
1641 void hrtimer_peek_ahead_timers(void)
1642 {
1643         unsigned long flags;
1644
1645         local_irq_save(flags);
1646         __hrtimer_peek_ahead_timers();
1647         local_irq_restore(flags);
1648 }
1649 #else /* CONFIG_HIGH_RES_TIMERS */
1650
1651 static inline void __hrtimer_peek_ahead_timers(void) { }
1652
1653 #endif  /* !CONFIG_HIGH_RES_TIMERS */
1654
1655
1656 static void run_hrtimer_softirq(struct softirq_action *h)
1657 {
1658         hrtimer_rt_run_pending();
1659 }
1660
1661 /*
1662  * Called from timer softirq every jiffy, expire hrtimers:
1663  *
1664  * For HRT its the fall back code to run the softirq in the timer
1665  * softirq context in case the hrtimer initialization failed or has
1666  * not been done yet.
1667  */
1668 void hrtimer_run_pending(void)
1669 {
1670         if (hrtimer_hres_active())
1671                 return;
1672
1673         /*
1674          * This _is_ ugly: We have to check in the softirq context,
1675          * whether we can switch to highres and / or nohz mode. The
1676          * clocksource switch happens in the timer interrupt with
1677          * xtime_lock held. Notification from there only sets the
1678          * check bit in the tick_oneshot code, otherwise we might
1679          * deadlock vs. xtime_lock.
1680          */
1681         if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1682                 hrtimer_switch_to_hres();
1683 }
1684
1685 /*
1686  * Called from hardirq context every jiffy
1687  */
1688 void hrtimer_run_queues(void)
1689 {
1690         struct timerqueue_node *node;
1691         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1692         struct hrtimer_clock_base *base;
1693         int index, gettime = 1, raise = 0;
1694
1695         if (hrtimer_hres_active())
1696                 return;
1697
1698         for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1699                 base = &cpu_base->clock_base[index];
1700                 if (!timerqueue_getnext(&base->active))
1701                         continue;
1702
1703                 if (gettime) {
1704                         hrtimer_get_softirq_time(cpu_base);
1705                         gettime = 0;
1706                 }
1707
1708                 raw_spin_lock(&cpu_base->lock);
1709
1710                 while ((node = timerqueue_getnext(&base->active))) {
1711                         struct hrtimer *timer;
1712
1713                         timer = container_of(node, struct hrtimer, node);
1714                         if (base->softirq_time.tv64 <=
1715                                         hrtimer_get_expires_tv64(timer))
1716                                 break;
1717
1718                         if (!hrtimer_rt_defer(timer))
1719                                 __run_hrtimer(timer, &base->softirq_time);
1720                         else
1721                                 raise = 1;
1722                 }
1723                 raw_spin_unlock(&cpu_base->lock);
1724         }
1725
1726         if (raise)
1727                 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1728 }
1729
1730 /*
1731  * Sleep related functions:
1732  */
1733 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1734 {
1735         struct hrtimer_sleeper *t =
1736                 container_of(timer, struct hrtimer_sleeper, timer);
1737         struct task_struct *task = t->task;
1738
1739         t->task = NULL;
1740         if (task)
1741                 wake_up_process(task);
1742
1743         return HRTIMER_NORESTART;
1744 }
1745
1746 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1747 {
1748         sl->timer.function = hrtimer_wakeup;
1749         sl->timer.irqsafe = 1;
1750         sl->task = task;
1751 }
1752 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1753
1754 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode,
1755                                 unsigned long state)
1756 {
1757         hrtimer_init_sleeper(t, current);
1758
1759         do {
1760                 set_current_state(state);
1761                 hrtimer_start_expires(&t->timer, mode);
1762                 if (!hrtimer_active(&t->timer))
1763                         t->task = NULL;
1764
1765                 if (likely(t->task))
1766                         freezable_schedule();
1767
1768                 hrtimer_cancel(&t->timer);
1769                 mode = HRTIMER_MODE_ABS;
1770
1771         } while (t->task && !signal_pending(current));
1772
1773         __set_current_state(TASK_RUNNING);
1774
1775         return t->task == NULL;
1776 }
1777
1778 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1779 {
1780         struct timespec rmt;
1781         ktime_t rem;
1782
1783         rem = hrtimer_expires_remaining(timer);
1784         if (rem.tv64 <= 0)
1785                 return 0;
1786         rmt = ktime_to_timespec(rem);
1787
1788         if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1789                 return -EFAULT;
1790
1791         return 1;
1792 }
1793
1794 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1795 {
1796         struct hrtimer_sleeper t;
1797         struct timespec __user  *rmtp;
1798         int ret = 0;
1799
1800         hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
1801                                 HRTIMER_MODE_ABS);
1802         hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1803
1804         /* cpu_chill() does not care about restart state. */
1805         if (do_nanosleep(&t, HRTIMER_MODE_ABS, TASK_INTERRUPTIBLE))
1806                 goto out;
1807
1808         rmtp = restart->nanosleep.rmtp;
1809         if (rmtp) {
1810                 ret = update_rmtp(&t.timer, rmtp);
1811                 if (ret <= 0)
1812                         goto out;
1813         }
1814
1815         /* The other values in restart are already filled in */
1816         ret = -ERESTART_RESTARTBLOCK;
1817 out:
1818         destroy_hrtimer_on_stack(&t.timer);
1819         return ret;
1820 }
1821
1822 static long
1823 __hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1824                     const enum hrtimer_mode mode, const clockid_t clockid,
1825                     unsigned long state)
1826 {
1827         struct restart_block *restart;
1828         struct hrtimer_sleeper t;
1829         int ret = 0;
1830         unsigned long slack;
1831
1832         slack = current->timer_slack_ns;
1833         if (dl_task(current) || rt_task(current))
1834                 slack = 0;
1835
1836         hrtimer_init_on_stack(&t.timer, clockid, mode);
1837         hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1838         if (do_nanosleep(&t, mode, state))
1839                 goto out;
1840
1841         /* Absolute timers do not update the rmtp value and restart: */
1842         if (mode == HRTIMER_MODE_ABS) {
1843                 ret = -ERESTARTNOHAND;
1844                 goto out;
1845         }
1846
1847         if (rmtp) {
1848                 ret = update_rmtp(&t.timer, rmtp);
1849                 if (ret <= 0)
1850                         goto out;
1851         }
1852
1853         restart = &current->restart_block;
1854         restart->fn = hrtimer_nanosleep_restart;
1855         restart->nanosleep.clockid = t.timer.base->clockid;
1856         restart->nanosleep.rmtp = rmtp;
1857         restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1858
1859         ret = -ERESTART_RESTARTBLOCK;
1860 out:
1861         destroy_hrtimer_on_stack(&t.timer);
1862         return ret;
1863 }
1864
1865 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1866                        const enum hrtimer_mode mode, const clockid_t clockid)
1867 {
1868         return __hrtimer_nanosleep(rqtp, rmtp, mode, clockid, TASK_INTERRUPTIBLE);
1869 }
1870
1871 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1872                 struct timespec __user *, rmtp)
1873 {
1874         struct timespec tu;
1875
1876         if (copy_from_user(&tu, rqtp, sizeof(tu)))
1877                 return -EFAULT;
1878
1879         if (!timespec_valid(&tu))
1880                 return -EINVAL;
1881
1882         return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1883 }
1884
1885 #ifdef CONFIG_PREEMPT_RT_FULL
1886 /*
1887  * Sleep for 1 ms in hope whoever holds what we want will let it go.
1888  */
1889 void cpu_chill(void)
1890 {
1891         struct timespec tu = {
1892                 .tv_nsec = NSEC_PER_MSEC,
1893         };
1894         unsigned int freeze_flag = current->flags & PF_NOFREEZE;
1895
1896         current->flags |= PF_NOFREEZE;
1897         __hrtimer_nanosleep(&tu, NULL, HRTIMER_MODE_REL, CLOCK_MONOTONIC,
1898                             TASK_UNINTERRUPTIBLE);
1899         if (!freeze_flag)
1900                 current->flags &= ~PF_NOFREEZE;
1901 }
1902 EXPORT_SYMBOL(cpu_chill);
1903 #endif
1904
1905 /*
1906  * Functions related to boot-time initialization:
1907  */
1908 static void init_hrtimers_cpu(int cpu)
1909 {
1910         struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1911         int i;
1912
1913         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1914                 cpu_base->clock_base[i].cpu_base = cpu_base;
1915                 timerqueue_init_head(&cpu_base->clock_base[i].active);
1916                 INIT_LIST_HEAD(&cpu_base->clock_base[i].expired);
1917         }
1918
1919         cpu_base->cpu = cpu;
1920         hrtimer_init_hres(cpu_base);
1921 #ifdef CONFIG_PREEMPT_RT_BASE
1922         init_waitqueue_head(&cpu_base->wait);
1923 #endif
1924 }
1925
1926 #ifdef CONFIG_HOTPLUG_CPU
1927
1928 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1929                                 struct hrtimer_clock_base *new_base)
1930 {
1931         struct hrtimer *timer;
1932         struct timerqueue_node *node;
1933
1934         while ((node = timerqueue_getnext(&old_base->active))) {
1935                 timer = container_of(node, struct hrtimer, node);
1936                 BUG_ON(hrtimer_callback_running(timer));
1937                 debug_deactivate(timer);
1938
1939                 /*
1940                  * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1941                  * timer could be seen as !active and just vanish away
1942                  * under us on another CPU
1943                  */
1944                 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1945                 timer->base = new_base;
1946                 /*
1947                  * Enqueue the timers on the new cpu. This does not
1948                  * reprogram the event device in case the timer
1949                  * expires before the earliest on this CPU, but we run
1950                  * hrtimer_interrupt after we migrated everything to
1951                  * sort out already expired timers and reprogram the
1952                  * event device.
1953                  */
1954                 enqueue_hrtimer(timer, new_base);
1955
1956                 /* Clear the migration state bit */
1957                 timer->state &= ~HRTIMER_STATE_MIGRATE;
1958         }
1959 }
1960
1961 static void migrate_hrtimers(int scpu)
1962 {
1963         struct hrtimer_cpu_base *old_base, *new_base;
1964         int i;
1965
1966         BUG_ON(cpu_online(scpu));
1967         tick_cancel_sched_timer(scpu);
1968
1969         local_irq_disable();
1970         old_base = &per_cpu(hrtimer_bases, scpu);
1971         new_base = this_cpu_ptr(&hrtimer_bases);
1972         /*
1973          * The caller is globally serialized and nobody else
1974          * takes two locks at once, deadlock is not possible.
1975          */
1976         raw_spin_lock(&new_base->lock);
1977         raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1978
1979         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1980                 migrate_hrtimer_list(&old_base->clock_base[i],
1981                                      &new_base->clock_base[i]);
1982         }
1983
1984         raw_spin_unlock(&old_base->lock);
1985         raw_spin_unlock(&new_base->lock);
1986
1987         /* Check, if we got expired work to do */
1988         __hrtimer_peek_ahead_timers();
1989         local_irq_enable();
1990 }
1991
1992 #endif /* CONFIG_HOTPLUG_CPU */
1993
1994 static int hrtimer_cpu_notify(struct notifier_block *self,
1995                                         unsigned long action, void *hcpu)
1996 {
1997         int scpu = (long)hcpu;
1998
1999         switch (action) {
2000
2001         case CPU_UP_PREPARE:
2002         case CPU_UP_PREPARE_FROZEN:
2003                 init_hrtimers_cpu(scpu);
2004                 break;
2005
2006 #ifdef CONFIG_HOTPLUG_CPU
2007         case CPU_DEAD:
2008         case CPU_DEAD_FROZEN:
2009                 migrate_hrtimers(scpu);
2010                 break;
2011 #endif
2012
2013         default:
2014                 break;
2015         }
2016
2017         return NOTIFY_OK;
2018 }
2019
2020 static struct notifier_block hrtimers_nb = {
2021         .notifier_call = hrtimer_cpu_notify,
2022 };
2023
2024 void __init hrtimers_init(void)
2025 {
2026         hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
2027                           (void *)(long)smp_processor_id());
2028         register_cpu_notifier(&hrtimers_nb);
2029         open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
2030 }
2031
2032 /**
2033  * schedule_hrtimeout_range_clock - sleep until timeout
2034  * @expires:    timeout value (ktime_t)
2035  * @delta:      slack in expires timeout (ktime_t)
2036  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2037  * @clock:      timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
2038  */
2039 int __sched
2040 schedule_hrtimeout_range_clock(ktime_t *expires, unsigned long delta,
2041                                const enum hrtimer_mode mode, int clock)
2042 {
2043         struct hrtimer_sleeper t;
2044
2045         /*
2046          * Optimize when a zero timeout value is given. It does not
2047          * matter whether this is an absolute or a relative time.
2048          */
2049         if (expires && !expires->tv64) {
2050                 __set_current_state(TASK_RUNNING);
2051                 return 0;
2052         }
2053
2054         /*
2055          * A NULL parameter means "infinite"
2056          */
2057         if (!expires) {
2058                 schedule();
2059                 return -EINTR;
2060         }
2061
2062         hrtimer_init_on_stack(&t.timer, clock, mode);
2063         hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
2064
2065         hrtimer_init_sleeper(&t, current);
2066
2067         hrtimer_start_expires(&t.timer, mode);
2068         if (!hrtimer_active(&t.timer))
2069                 t.task = NULL;
2070
2071         if (likely(t.task))
2072                 schedule();
2073
2074         hrtimer_cancel(&t.timer);
2075         destroy_hrtimer_on_stack(&t.timer);
2076
2077         __set_current_state(TASK_RUNNING);
2078
2079         return !t.task ? 0 : -EINTR;
2080 }
2081
2082 /**
2083  * schedule_hrtimeout_range - sleep until timeout
2084  * @expires:    timeout value (ktime_t)
2085  * @delta:      slack in expires timeout (ktime_t)
2086  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2087  *
2088  * Make the current task sleep until the given expiry time has
2089  * elapsed. The routine will return immediately unless
2090  * the current task state has been set (see set_current_state()).
2091  *
2092  * The @delta argument gives the kernel the freedom to schedule the
2093  * actual wakeup to a time that is both power and performance friendly.
2094  * The kernel give the normal best effort behavior for "@expires+@delta",
2095  * but may decide to fire the timer earlier, but no earlier than @expires.
2096  *
2097  * You can set the task state as follows -
2098  *
2099  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2100  * pass before the routine returns.
2101  *
2102  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2103  * delivered to the current task.
2104  *
2105  * The current task state is guaranteed to be TASK_RUNNING when this
2106  * routine returns.
2107  *
2108  * Returns 0 when the timer has expired otherwise -EINTR
2109  */
2110 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
2111                                      const enum hrtimer_mode mode)
2112 {
2113         return schedule_hrtimeout_range_clock(expires, delta, mode,
2114                                               CLOCK_MONOTONIC);
2115 }
2116 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
2117
2118 /**
2119  * schedule_hrtimeout - sleep until timeout
2120  * @expires:    timeout value (ktime_t)
2121  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2122  *
2123  * Make the current task sleep until the given expiry time has
2124  * elapsed. The routine will return immediately unless
2125  * the current task state has been set (see set_current_state()).
2126  *
2127  * You can set the task state as follows -
2128  *
2129  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2130  * pass before the routine returns.
2131  *
2132  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2133  * delivered to the current task.
2134  *
2135  * The current task state is guaranteed to be TASK_RUNNING when this
2136  * routine returns.
2137  *
2138  * Returns 0 when the timer has expired otherwise -EINTR
2139  */
2140 int __sched schedule_hrtimeout(ktime_t *expires,
2141                                const enum hrtimer_mode mode)
2142 {
2143         return schedule_hrtimeout_range(expires, 0, mode);
2144 }
2145 EXPORT_SYMBOL_GPL(schedule_hrtimeout);