2c6be169bdc75d04bc6054900121b55a2b738574
[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         /*
587          * CLOCK_REALTIME timer might be requested with an absolute
588          * expiry time which is less than base->offset. Nothing wrong
589          * about that, just avoid to call into the tick code, which
590          * has now objections against negative expiry values.
591          */
592         if (expires.tv64 < 0)
593                 return -ETIME;
594
595         if (expires.tv64 >= cpu_base->expires_next.tv64)
596                 return 0;
597
598         /*
599          * When the target cpu of the timer is currently executing
600          * hrtimer_interrupt(), then we do not touch the clock event
601          * device. hrtimer_interrupt() will reevaluate all clock bases
602          * before reprogramming the device.
603          */
604         if (cpu_base->in_hrtirq)
605                 return 0;
606
607         /*
608          * If a hang was detected in the last timer interrupt then we
609          * do not schedule a timer which is earlier than the expiry
610          * which we enforced in the hang detection. We want the system
611          * to make progress.
612          */
613         if (cpu_base->hang_detected)
614                 return 0;
615
616         /*
617          * Clockevents returns -ETIME, when the event was in the past.
618          */
619         res = tick_program_event(expires, 0);
620         if (!IS_ERR_VALUE(res))
621                 cpu_base->expires_next = expires;
622         return res;
623 }
624
625 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now);
626 static int hrtimer_rt_defer(struct hrtimer *timer);
627
628 /*
629  * Initialize the high resolution related parts of cpu_base
630  */
631 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
632 {
633         base->expires_next.tv64 = KTIME_MAX;
634         base->hres_active = 0;
635 }
636
637 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
638                                             struct hrtimer_clock_base *base,
639                                             int wakeup)
640 {
641         if (!hrtimer_reprogram(timer, base))
642                 return 0;
643         if (!wakeup)
644                 return -ETIME;
645 #ifdef CONFIG_PREEMPT_RT_BASE
646         if (!hrtimer_rt_defer(timer))
647                 return -ETIME;
648 #endif
649         return 1;
650 }
651
652 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
653 {
654         ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
655         ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
656         ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
657
658         return ktime_get_update_offsets_now(offs_real, offs_boot, offs_tai);
659 }
660
661 /*
662  * Retrigger next event is called after clock was set
663  *
664  * Called with interrupts disabled via on_each_cpu()
665  */
666 static void retrigger_next_event(void *arg)
667 {
668         struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
669
670         if (!hrtimer_hres_active())
671                 return;
672
673         raw_spin_lock(&base->lock);
674         hrtimer_update_base(base);
675         hrtimer_force_reprogram(base, 0);
676         raw_spin_unlock(&base->lock);
677 }
678
679 /*
680  * Switch to high resolution mode
681  */
682 static int hrtimer_switch_to_hres(void)
683 {
684         int i, cpu = smp_processor_id();
685         struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
686         unsigned long flags;
687
688         if (base->hres_active)
689                 return 1;
690
691         local_irq_save(flags);
692
693         if (tick_init_highres()) {
694                 local_irq_restore(flags);
695                 printk(KERN_WARNING "Could not switch to high resolution "
696                                     "mode on CPU %d\n", cpu);
697                 return 0;
698         }
699         base->hres_active = 1;
700         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
701                 base->clock_base[i].resolution = KTIME_HIGH_RES;
702
703         tick_setup_sched_timer();
704         /* "Retrigger" the interrupt to get things going */
705         retrigger_next_event(NULL);
706         local_irq_restore(flags);
707         return 1;
708 }
709
710 static void clock_was_set_work(struct work_struct *work)
711 {
712         clock_was_set();
713 }
714
715 static DECLARE_WORK(hrtimer_work, clock_was_set_work);
716
717 #ifdef CONFIG_PREEMPT_RT_FULL
718 /*
719  * RT can not call schedule_work from real interrupt context.
720  * Need to make a thread to do the real work.
721  */
722 static struct task_struct *clock_set_delay_thread;
723 static bool do_clock_set_delay;
724
725 static int run_clock_set_delay(void *ignore)
726 {
727         while (!kthread_should_stop()) {
728                 set_current_state(TASK_INTERRUPTIBLE);
729                 if (do_clock_set_delay) {
730                         do_clock_set_delay = false;
731                         schedule_work(&hrtimer_work);
732                 }
733                 schedule();
734         }
735         __set_current_state(TASK_RUNNING);
736         return 0;
737 }
738
739 void clock_was_set_delayed(void)
740 {
741         do_clock_set_delay = true;
742         /* Make visible before waking up process */
743         smp_wmb();
744         wake_up_process(clock_set_delay_thread);
745 }
746
747 static __init int create_clock_set_delay_thread(void)
748 {
749         clock_set_delay_thread = kthread_run(run_clock_set_delay, NULL, "kclksetdelayd");
750         BUG_ON(!clock_set_delay_thread);
751         return 0;
752 }
753 early_initcall(create_clock_set_delay_thread);
754 #else /* PREEMPT_RT_FULL */
755 /*
756  * Called from timekeeping and resume code to reprogramm the hrtimer
757  * interrupt device on all cpus.
758  */
759 void clock_was_set_delayed(void)
760 {
761         schedule_work(&hrtimer_work);
762 }
763 #endif
764
765 #else
766
767 static inline int hrtimer_hres_active(void) { return 0; }
768 static inline int hrtimer_is_hres_enabled(void) { return 0; }
769 static inline int hrtimer_switch_to_hres(void) { return 0; }
770 static inline void
771 hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
772 static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
773                                             struct hrtimer_clock_base *base,
774                                             int wakeup)
775 {
776         return 0;
777 }
778
779 static inline int hrtimer_reprogram(struct hrtimer *timer,
780                                     struct hrtimer_clock_base *base)
781 {
782         return 0;
783 }
784 static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
785 static inline void retrigger_next_event(void *arg) { }
786 #endif /* CONFIG_HIGH_RES_TIMERS */
787
788 /*
789  * Clock realtime was set
790  *
791  * Change the offset of the realtime clock vs. the monotonic
792  * clock.
793  *
794  * We might have to reprogram the high resolution timer interrupt. On
795  * SMP we call the architecture specific code to retrigger _all_ high
796  * resolution timer interrupts. On UP we just disable interrupts and
797  * call the high resolution interrupt code.
798  */
799 void clock_was_set(void)
800 {
801 #ifdef CONFIG_HIGH_RES_TIMERS
802         /* Retrigger the CPU local events everywhere */
803         on_each_cpu(retrigger_next_event, NULL, 1);
804 #endif
805         timerfd_clock_was_set();
806 }
807
808 /*
809  * During resume we might have to reprogram the high resolution timer
810  * interrupt on all online CPUs.  However, all other CPUs will be
811  * stopped with IRQs interrupts disabled so the clock_was_set() call
812  * must be deferred.
813  */
814 void hrtimers_resume(void)
815 {
816         WARN_ONCE(!irqs_disabled(),
817                   KERN_INFO "hrtimers_resume() called with IRQs enabled!");
818
819         /* Retrigger on the local CPU */
820         retrigger_next_event(NULL);
821         /* And schedule a retrigger for all others */
822         clock_was_set_delayed();
823 }
824
825 static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
826 {
827 #ifdef CONFIG_TIMER_STATS
828         if (timer->start_site)
829                 return;
830         timer->start_site = __builtin_return_address(0);
831         memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
832         timer->start_pid = current->pid;
833 #endif
834 }
835
836 static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
837 {
838 #ifdef CONFIG_TIMER_STATS
839         timer->start_site = NULL;
840 #endif
841 }
842
843 static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
844 {
845 #ifdef CONFIG_TIMER_STATS
846         if (likely(!timer_stats_active))
847                 return;
848         timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
849                                  timer->function, timer->start_comm, 0);
850 #endif
851 }
852
853 /*
854  * Counterpart to lock_hrtimer_base above:
855  */
856 static inline
857 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
858 {
859         raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
860 }
861
862 /**
863  * hrtimer_forward - forward the timer expiry
864  * @timer:      hrtimer to forward
865  * @now:        forward past this time
866  * @interval:   the interval to forward
867  *
868  * Forward the timer expiry so it will expire in the future.
869  * Returns the number of overruns.
870  */
871 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
872 {
873         u64 orun = 1;
874         ktime_t delta;
875
876         delta = ktime_sub(now, hrtimer_get_expires(timer));
877
878         if (delta.tv64 < 0)
879                 return 0;
880
881         if (interval.tv64 < timer->base->resolution.tv64)
882                 interval.tv64 = timer->base->resolution.tv64;
883
884         if (unlikely(delta.tv64 >= interval.tv64)) {
885                 s64 incr = ktime_to_ns(interval);
886
887                 orun = ktime_divns(delta, incr);
888                 hrtimer_add_expires_ns(timer, incr * orun);
889                 if (hrtimer_get_expires_tv64(timer) > now.tv64)
890                         return orun;
891                 /*
892                  * This (and the ktime_add() below) is the
893                  * correction for exact:
894                  */
895                 orun++;
896         }
897         hrtimer_add_expires(timer, interval);
898
899         return orun;
900 }
901 EXPORT_SYMBOL_GPL(hrtimer_forward);
902
903 #ifdef CONFIG_PREEMPT_RT_BASE
904 # define wake_up_timer_waiters(b)       wake_up(&(b)->wait)
905
906 /**
907  * hrtimer_wait_for_timer - Wait for a running timer
908  *
909  * @timer:      timer to wait for
910  *
911  * The function waits in case the timers callback function is
912  * currently executed on the waitqueue of the timer base. The
913  * waitqueue is woken up after the timer callback function has
914  * finished execution.
915  */
916 void hrtimer_wait_for_timer(const struct hrtimer *timer)
917 {
918         struct hrtimer_clock_base *base = timer->base;
919
920         if (base && base->cpu_base && !timer->irqsafe)
921                 wait_event(base->cpu_base->wait,
922                            !(timer->state & HRTIMER_STATE_CALLBACK));
923 }
924
925 #else
926 # define wake_up_timer_waiters(b)       do { } while (0)
927 #endif
928
929 /*
930  * enqueue_hrtimer - internal function to (re)start a timer
931  *
932  * The timer is inserted in expiry order. Insertion into the
933  * red black tree is O(log(n)). Must hold the base lock.
934  *
935  * Returns 1 when the new timer is the leftmost timer in the tree.
936  */
937 static int enqueue_hrtimer(struct hrtimer *timer,
938                            struct hrtimer_clock_base *base)
939 {
940         debug_activate(timer);
941
942         timerqueue_add(&base->active, &timer->node);
943         base->cpu_base->active_bases |= 1 << base->index;
944
945         /*
946          * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
947          * state of a possibly running callback.
948          */
949         timer->state |= HRTIMER_STATE_ENQUEUED;
950
951         return (&timer->node == base->active.next);
952 }
953
954 /*
955  * __remove_hrtimer - internal function to remove a timer
956  *
957  * Caller must hold the base lock.
958  *
959  * High resolution timer mode reprograms the clock event device when the
960  * timer is the one which expires next. The caller can disable this by setting
961  * reprogram to zero. This is useful, when the context does a reprogramming
962  * anyway (e.g. timer interrupt)
963  */
964 static void __remove_hrtimer(struct hrtimer *timer,
965                              struct hrtimer_clock_base *base,
966                              unsigned long newstate, int reprogram)
967 {
968         struct timerqueue_node *next_timer;
969         if (!(timer->state & HRTIMER_STATE_ENQUEUED))
970                 goto out;
971
972         if (unlikely(!list_empty(&timer->cb_entry))) {
973                 list_del_init(&timer->cb_entry);
974                 goto out;
975         }
976
977         next_timer = timerqueue_getnext(&base->active);
978         timerqueue_del(&base->active, &timer->node);
979         if (&timer->node == next_timer) {
980 #ifdef CONFIG_HIGH_RES_TIMERS
981                 /* Reprogram the clock event device. if enabled */
982                 if (reprogram && hrtimer_hres_active()) {
983                         ktime_t expires;
984
985                         expires = ktime_sub(hrtimer_get_expires(timer),
986                                             base->offset);
987                         if (base->cpu_base->expires_next.tv64 == expires.tv64)
988                                 hrtimer_force_reprogram(base->cpu_base, 1);
989                 }
990 #endif
991         }
992         if (!timerqueue_getnext(&base->active))
993                 base->cpu_base->active_bases &= ~(1 << base->index);
994 out:
995         timer->state = newstate;
996 }
997
998 /*
999  * remove hrtimer, called with base lock held
1000  */
1001 static inline int
1002 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
1003 {
1004         if (hrtimer_is_queued(timer)) {
1005                 unsigned long state;
1006                 int reprogram;
1007
1008                 /*
1009                  * Remove the timer and force reprogramming when high
1010                  * resolution mode is active and the timer is on the current
1011                  * CPU. If we remove a timer on another CPU, reprogramming is
1012                  * skipped. The interrupt event on this CPU is fired and
1013                  * reprogramming happens in the interrupt handler. This is a
1014                  * rare case and less expensive than a smp call.
1015                  */
1016                 debug_deactivate(timer);
1017                 timer_stats_hrtimer_clear_start_info(timer);
1018                 reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1019                 /*
1020                  * We must preserve the CALLBACK state flag here,
1021                  * otherwise we could move the timer base in
1022                  * switch_hrtimer_base.
1023                  */
1024                 state = timer->state & HRTIMER_STATE_CALLBACK;
1025                 __remove_hrtimer(timer, base, state, reprogram);
1026                 return 1;
1027         }
1028         return 0;
1029 }
1030
1031 int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1032                 unsigned long delta_ns, const enum hrtimer_mode mode,
1033                 int wakeup)
1034 {
1035         struct hrtimer_clock_base *base, *new_base;
1036         unsigned long flags;
1037         int ret, leftmost;
1038
1039         base = lock_hrtimer_base(timer, &flags);
1040
1041         /* Remove an active timer from the queue: */
1042         ret = remove_hrtimer(timer, base);
1043
1044         if (mode & HRTIMER_MODE_REL) {
1045                 tim = ktime_add_safe(tim, base->get_time());
1046                 /*
1047                  * CONFIG_TIME_LOW_RES is a temporary way for architectures
1048                  * to signal that they simply return xtime in
1049                  * do_gettimeoffset(). In this case we want to round up by
1050                  * resolution when starting a relative timer, to avoid short
1051                  * timeouts. This will go away with the GTOD framework.
1052                  */
1053 #ifdef CONFIG_TIME_LOW_RES
1054                 tim = ktime_add_safe(tim, base->resolution);
1055 #endif
1056         }
1057
1058         hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1059
1060         /* Switch the timer base, if necessary: */
1061         new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
1062
1063         timer_stats_hrtimer_set_start_info(timer);
1064 #ifdef CONFIG_MISSED_TIMER_OFFSETS_HIST
1065         {
1066                 ktime_t now = new_base->get_time();
1067
1068                 if (ktime_to_ns(tim) < ktime_to_ns(now))
1069                         timer->praecox = now;
1070                 else
1071                         timer->praecox = ktime_set(0, 0);
1072         }
1073 #endif
1074         leftmost = enqueue_hrtimer(timer, new_base);
1075
1076         if (!leftmost) {
1077                 unlock_hrtimer_base(timer, &flags);
1078                 return ret;
1079         }
1080
1081         if (!hrtimer_is_hres_active(timer)) {
1082                 /*
1083                  * Kick to reschedule the next tick to handle the new timer
1084                  * on dynticks target.
1085                  */
1086                 wake_up_nohz_cpu(new_base->cpu_base->cpu);
1087         } else if (new_base->cpu_base == this_cpu_ptr(&hrtimer_bases)) {
1088
1089                 ret = hrtimer_enqueue_reprogram(timer, new_base, wakeup);
1090                 if (ret < 0) {
1091                         /*
1092                          * In case we failed to reprogram the timer (mostly
1093                          * because out current timer is already elapsed),
1094                          * remove it again and report a failure. This avoids
1095                          * stale base->first entries.
1096                          */
1097                         debug_deactivate(timer);
1098                         __remove_hrtimer(timer, new_base,
1099                                 timer->state & HRTIMER_STATE_CALLBACK, 0);
1100                 } else if (ret > 0) {
1101                 /*
1102                  * Only allow reprogramming if the new base is on this CPU.
1103                  * (it might still be on another CPU if the timer was pending)
1104                  *
1105                  * XXX send_remote_softirq() ?
1106                  */
1107                         /*
1108                          * We need to drop cpu_base->lock to avoid a
1109                          * lock ordering issue vs. rq->lock.
1110                          */
1111                         raw_spin_unlock(&new_base->cpu_base->lock);
1112                         raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1113                         local_irq_restore(flags);
1114                         return 0;
1115                 }
1116         }
1117
1118         unlock_hrtimer_base(timer, &flags);
1119
1120         return ret;
1121 }
1122 EXPORT_SYMBOL_GPL(__hrtimer_start_range_ns);
1123
1124 /**
1125  * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1126  * @timer:      the timer to be added
1127  * @tim:        expiry time
1128  * @delta_ns:   "slack" range for the timer
1129  * @mode:       expiry mode: absolute (HRTIMER_MODE_ABS) or
1130  *              relative (HRTIMER_MODE_REL)
1131  *
1132  * Returns:
1133  *  0 on success
1134  *  1 when the timer was active
1135  */
1136 int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1137                 unsigned long delta_ns, const enum hrtimer_mode mode)
1138 {
1139         return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1140 }
1141 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1142
1143 /**
1144  * hrtimer_start - (re)start an hrtimer on the current CPU
1145  * @timer:      the timer to be added
1146  * @tim:        expiry time
1147  * @mode:       expiry mode: absolute (HRTIMER_MODE_ABS) or
1148  *              relative (HRTIMER_MODE_REL)
1149  *
1150  * Returns:
1151  *  0 on success
1152  *  1 when the timer was active
1153  */
1154 int
1155 hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1156 {
1157         return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1158 }
1159 EXPORT_SYMBOL_GPL(hrtimer_start);
1160
1161
1162 /**
1163  * hrtimer_try_to_cancel - try to deactivate a timer
1164  * @timer:      hrtimer to stop
1165  *
1166  * Returns:
1167  *  0 when the timer was not active
1168  *  1 when the timer was active
1169  * -1 when the timer is currently excuting the callback function and
1170  *    cannot be stopped
1171  */
1172 int hrtimer_try_to_cancel(struct hrtimer *timer)
1173 {
1174         struct hrtimer_clock_base *base;
1175         unsigned long flags;
1176         int ret = -1;
1177
1178         base = lock_hrtimer_base(timer, &flags);
1179
1180         if (!hrtimer_callback_running(timer))
1181                 ret = remove_hrtimer(timer, base);
1182
1183         unlock_hrtimer_base(timer, &flags);
1184
1185         return ret;
1186
1187 }
1188 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1189
1190 /**
1191  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1192  * @timer:      the timer to be cancelled
1193  *
1194  * Returns:
1195  *  0 when the timer was not active
1196  *  1 when the timer was active
1197  */
1198 int hrtimer_cancel(struct hrtimer *timer)
1199 {
1200         for (;;) {
1201                 int ret = hrtimer_try_to_cancel(timer);
1202
1203                 if (ret >= 0)
1204                         return ret;
1205                 hrtimer_wait_for_timer(timer);
1206         }
1207 }
1208 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1209
1210 /**
1211  * hrtimer_get_remaining - get remaining time for the timer
1212  * @timer:      the timer to read
1213  */
1214 ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1215 {
1216         unsigned long flags;
1217         ktime_t rem;
1218
1219         lock_hrtimer_base(timer, &flags);
1220         rem = hrtimer_expires_remaining(timer);
1221         unlock_hrtimer_base(timer, &flags);
1222
1223         return rem;
1224 }
1225 EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1226
1227 #ifdef CONFIG_NO_HZ_COMMON
1228 /**
1229  * hrtimer_get_next_event - get the time until next expiry event
1230  *
1231  * Returns the delta to the next expiry event or KTIME_MAX if no timer
1232  * is pending.
1233  */
1234 ktime_t hrtimer_get_next_event(void)
1235 {
1236         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1237         ktime_t mindelta = { .tv64 = KTIME_MAX };
1238         unsigned long flags;
1239
1240         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1241
1242         if (!hrtimer_hres_active())
1243                 mindelta = ktime_sub(__hrtimer_get_next_event(cpu_base),
1244                                      ktime_get());
1245
1246         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1247
1248         if (mindelta.tv64 < 0)
1249                 mindelta.tv64 = 0;
1250         return mindelta;
1251 }
1252 #endif
1253
1254 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1255                            enum hrtimer_mode mode)
1256 {
1257         struct hrtimer_cpu_base *cpu_base;
1258         int base;
1259
1260         memset(timer, 0, sizeof(struct hrtimer));
1261
1262         cpu_base = raw_cpu_ptr(&hrtimer_bases);
1263
1264         if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1265                 clock_id = CLOCK_MONOTONIC;
1266
1267         base = hrtimer_clockid_to_base(clock_id);
1268         timer->base = &cpu_base->clock_base[base];
1269         INIT_LIST_HEAD(&timer->cb_entry);
1270         timerqueue_init(&timer->node);
1271
1272 #ifdef CONFIG_TIMER_STATS
1273         timer->start_site = NULL;
1274         timer->start_pid = -1;
1275         memset(timer->start_comm, 0, TASK_COMM_LEN);
1276 #endif
1277 }
1278
1279 /**
1280  * hrtimer_init - initialize a timer to the given clock
1281  * @timer:      the timer to be initialized
1282  * @clock_id:   the clock to be used
1283  * @mode:       timer mode abs/rel
1284  */
1285 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1286                   enum hrtimer_mode mode)
1287 {
1288         debug_init(timer, clock_id, mode);
1289         __hrtimer_init(timer, clock_id, mode);
1290 }
1291 EXPORT_SYMBOL_GPL(hrtimer_init);
1292
1293 /**
1294  * hrtimer_get_res - get the timer resolution for a clock
1295  * @which_clock: which clock to query
1296  * @tp:          pointer to timespec variable to store the resolution
1297  *
1298  * Store the resolution of the clock selected by @which_clock in the
1299  * variable pointed to by @tp.
1300  */
1301 int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1302 {
1303         struct hrtimer_cpu_base *cpu_base;
1304         int base = hrtimer_clockid_to_base(which_clock);
1305
1306         cpu_base = raw_cpu_ptr(&hrtimer_bases);
1307         *tp = ktime_to_timespec(cpu_base->clock_base[base].resolution);
1308
1309         return 0;
1310 }
1311 EXPORT_SYMBOL_GPL(hrtimer_get_res);
1312
1313 static void __run_hrtimer(struct hrtimer *timer, ktime_t *now)
1314 {
1315         struct hrtimer_clock_base *base = timer->base;
1316         struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1317         enum hrtimer_restart (*fn)(struct hrtimer *);
1318         int restart;
1319
1320         WARN_ON(!irqs_disabled());
1321
1322         debug_deactivate(timer);
1323         __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1324         timer_stats_account_hrtimer(timer);
1325         fn = timer->function;
1326
1327         /*
1328          * Because we run timers from hardirq context, there is no chance
1329          * they get migrated to another cpu, therefore its safe to unlock
1330          * the timer base.
1331          */
1332         raw_spin_unlock(&cpu_base->lock);
1333         trace_hrtimer_expire_entry(timer, now);
1334         restart = fn(timer);
1335         trace_hrtimer_expire_exit(timer);
1336         raw_spin_lock(&cpu_base->lock);
1337
1338         /*
1339          * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1340          * we do not reprogramm the event hardware. Happens either in
1341          * hrtimer_start_range_ns() or in hrtimer_interrupt()
1342          */
1343         if (restart != HRTIMER_NORESTART) {
1344                 BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1345                 enqueue_hrtimer(timer, base);
1346         }
1347
1348         WARN_ON_ONCE(!(timer->state & HRTIMER_STATE_CALLBACK));
1349
1350         timer->state &= ~HRTIMER_STATE_CALLBACK;
1351 }
1352
1353 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer);
1354
1355 #ifdef CONFIG_PREEMPT_RT_BASE
1356 static void hrtimer_rt_reprogram(int restart, struct hrtimer *timer,
1357                                  struct hrtimer_clock_base *base)
1358 {
1359         /*
1360          * Note, we clear the callback flag before we requeue the
1361          * timer otherwise we trigger the callback_running() check
1362          * in hrtimer_reprogram().
1363          */
1364         timer->state &= ~HRTIMER_STATE_CALLBACK;
1365
1366         if (restart != HRTIMER_NORESTART) {
1367                 BUG_ON(hrtimer_active(timer));
1368                 /*
1369                  * Enqueue the timer, if it's the leftmost timer then
1370                  * we need to reprogram it.
1371                  */
1372                 if (!enqueue_hrtimer(timer, base))
1373                         return;
1374
1375 #ifndef CONFIG_HIGH_RES_TIMERS
1376         }
1377 #else
1378                 if (base->cpu_base->hres_active &&
1379                     hrtimer_reprogram(timer, base))
1380                         goto requeue;
1381
1382         } else if (hrtimer_active(timer)) {
1383                 /*
1384                  * If the timer was rearmed on another CPU, reprogram
1385                  * the event device.
1386                  */
1387                 if (&timer->node == base->active.next &&
1388                     base->cpu_base->hres_active &&
1389                     hrtimer_reprogram(timer, base))
1390                         goto requeue;
1391         }
1392         return;
1393
1394 requeue:
1395         /*
1396          * Timer is expired. Thus move it from tree to pending list
1397          * again.
1398          */
1399         __remove_hrtimer(timer, base, timer->state, 0);
1400         list_add_tail(&timer->cb_entry, &base->expired);
1401 #endif
1402 }
1403
1404 /*
1405  * The changes in mainline which removed the callback modes from
1406  * hrtimer are not yet working with -rt. The non wakeup_process()
1407  * based callbacks which involve sleeping locks need to be treated
1408  * seperately.
1409  */
1410 static void hrtimer_rt_run_pending(void)
1411 {
1412         enum hrtimer_restart (*fn)(struct hrtimer *);
1413         struct hrtimer_cpu_base *cpu_base;
1414         struct hrtimer_clock_base *base;
1415         struct hrtimer *timer;
1416         int index, restart;
1417
1418         local_irq_disable();
1419         cpu_base = &per_cpu(hrtimer_bases, smp_processor_id());
1420
1421         raw_spin_lock(&cpu_base->lock);
1422
1423         for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1424                 base = &cpu_base->clock_base[index];
1425
1426                 while (!list_empty(&base->expired)) {
1427                         timer = list_first_entry(&base->expired,
1428                                                  struct hrtimer, cb_entry);
1429
1430                         /*
1431                          * Same as the above __run_hrtimer function
1432                          * just we run with interrupts enabled.
1433                          */
1434                         debug_hrtimer_deactivate(timer);
1435                         __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1436                         timer_stats_account_hrtimer(timer);
1437                         fn = timer->function;
1438
1439                         raw_spin_unlock_irq(&cpu_base->lock);
1440                         restart = fn(timer);
1441                         raw_spin_lock_irq(&cpu_base->lock);
1442
1443                         hrtimer_rt_reprogram(restart, timer, base);
1444                 }
1445         }
1446
1447         raw_spin_unlock_irq(&cpu_base->lock);
1448
1449         wake_up_timer_waiters(cpu_base);
1450 }
1451
1452 static int hrtimer_rt_defer(struct hrtimer *timer)
1453 {
1454         if (timer->irqsafe)
1455                 return 0;
1456
1457         __remove_hrtimer(timer, timer->base, timer->state, 0);
1458         list_add_tail(&timer->cb_entry, &timer->base->expired);
1459         return 1;
1460 }
1461
1462 #else
1463
1464 static inline void hrtimer_rt_run_pending(void)
1465 {
1466         hrtimer_peek_ahead_timers();
1467 }
1468
1469 static inline int hrtimer_rt_defer(struct hrtimer *timer) { return 0; }
1470
1471 #endif
1472
1473 #ifdef CONFIG_HIGH_RES_TIMERS
1474
1475 /*
1476  * High resolution timer interrupt
1477  * Called with interrupts disabled
1478  */
1479 void hrtimer_interrupt(struct clock_event_device *dev)
1480 {
1481         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1482         ktime_t expires_next, now, entry_time, delta;
1483         int i, retries = 0, raise = 0;
1484
1485         BUG_ON(!cpu_base->hres_active);
1486         cpu_base->nr_events++;
1487         dev->next_event.tv64 = KTIME_MAX;
1488
1489         raw_spin_lock(&cpu_base->lock);
1490         entry_time = now = hrtimer_update_base(cpu_base);
1491 retry:
1492         cpu_base->in_hrtirq = 1;
1493         /*
1494          * We set expires_next to KTIME_MAX here with cpu_base->lock
1495          * held to prevent that a timer is enqueued in our queue via
1496          * the migration code. This does not affect enqueueing of
1497          * timers which run their callback and need to be requeued on
1498          * this CPU.
1499          */
1500         cpu_base->expires_next.tv64 = KTIME_MAX;
1501
1502         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1503                 struct hrtimer_clock_base *base;
1504                 struct timerqueue_node *node;
1505                 ktime_t basenow;
1506
1507                 if (!(cpu_base->active_bases & (1 << i)))
1508                         continue;
1509
1510                 base = cpu_base->clock_base + i;
1511                 basenow = ktime_add(now, base->offset);
1512
1513                 while ((node = timerqueue_getnext(&base->active))) {
1514                         struct hrtimer *timer;
1515
1516                         timer = container_of(node, struct hrtimer, node);
1517
1518                         trace_hrtimer_interrupt(raw_smp_processor_id(),
1519                             ktime_to_ns(ktime_sub(ktime_to_ns(timer->praecox) ?
1520                                 timer->praecox : hrtimer_get_expires(timer),
1521                                 basenow)),
1522                             current,
1523                             timer->function == hrtimer_wakeup ?
1524                             container_of(timer, struct hrtimer_sleeper,
1525                                 timer)->task : NULL);
1526
1527                         /*
1528                          * The immediate goal for using the softexpires is
1529                          * minimizing wakeups, not running timers at the
1530                          * earliest interrupt after their soft expiration.
1531                          * This allows us to avoid using a Priority Search
1532                          * Tree, which can answer a stabbing querry for
1533                          * overlapping intervals and instead use the simple
1534                          * BST we already have.
1535                          * We don't add extra wakeups by delaying timers that
1536                          * are right-of a not yet expired timer, because that
1537                          * timer will have to trigger a wakeup anyway.
1538                          */
1539                         if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer))
1540                                 break;
1541
1542                         if (!hrtimer_rt_defer(timer))
1543                                 __run_hrtimer(timer, &basenow);
1544                         else
1545                                 raise = 1;
1546                 }
1547         }
1548         /* Reevaluate the clock bases for the next expiry */
1549         expires_next = __hrtimer_get_next_event(cpu_base);
1550         /*
1551          * Store the new expiry value so the migration code can verify
1552          * against it.
1553          */
1554         cpu_base->expires_next = expires_next;
1555         cpu_base->in_hrtirq = 0;
1556         raw_spin_unlock(&cpu_base->lock);
1557
1558         /* Reprogramming necessary ? */
1559         if (expires_next.tv64 == KTIME_MAX ||
1560             !tick_program_event(expires_next, 0)) {
1561                 cpu_base->hang_detected = 0;
1562                 goto out;
1563         }
1564
1565         /*
1566          * The next timer was already expired due to:
1567          * - tracing
1568          * - long lasting callbacks
1569          * - being scheduled away when running in a VM
1570          *
1571          * We need to prevent that we loop forever in the hrtimer
1572          * interrupt routine. We give it 3 attempts to avoid
1573          * overreacting on some spurious event.
1574          *
1575          * Acquire base lock for updating the offsets and retrieving
1576          * the current time.
1577          */
1578         raw_spin_lock(&cpu_base->lock);
1579         now = hrtimer_update_base(cpu_base);
1580         cpu_base->nr_retries++;
1581         if (++retries < 3)
1582                 goto retry;
1583         /*
1584          * Give the system a chance to do something else than looping
1585          * here. We stored the entry time, so we know exactly how long
1586          * we spent here. We schedule the next event this amount of
1587          * time away.
1588          */
1589         cpu_base->nr_hangs++;
1590         cpu_base->hang_detected = 1;
1591         raw_spin_unlock(&cpu_base->lock);
1592         delta = ktime_sub(now, entry_time);
1593         if (delta.tv64 > cpu_base->max_hang_time.tv64)
1594                 cpu_base->max_hang_time = delta;
1595         /*
1596          * Limit it to a sensible value as we enforce a longer
1597          * delay. Give the CPU at least 100ms to catch up.
1598          */
1599         if (delta.tv64 > 100 * NSEC_PER_MSEC)
1600                 expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1601         else
1602                 expires_next = ktime_add(now, delta);
1603         tick_program_event(expires_next, 1);
1604         printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1605                     ktime_to_ns(delta));
1606 out:
1607         if (raise)
1608                 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1609 }
1610
1611 /*
1612  * local version of hrtimer_peek_ahead_timers() called with interrupts
1613  * disabled.
1614  */
1615 static void __hrtimer_peek_ahead_timers(void)
1616 {
1617         struct tick_device *td;
1618
1619         if (!hrtimer_hres_active())
1620                 return;
1621
1622         td = this_cpu_ptr(&tick_cpu_device);
1623         if (td && td->evtdev)
1624                 hrtimer_interrupt(td->evtdev);
1625 }
1626
1627 /**
1628  * hrtimer_peek_ahead_timers -- run soft-expired timers now
1629  *
1630  * hrtimer_peek_ahead_timers will peek at the timer queue of
1631  * the current cpu and check if there are any timers for which
1632  * the soft expires time has passed. If any such timers exist,
1633  * they are run immediately and then removed from the timer queue.
1634  *
1635  */
1636 void hrtimer_peek_ahead_timers(void)
1637 {
1638         unsigned long flags;
1639
1640         local_irq_save(flags);
1641         __hrtimer_peek_ahead_timers();
1642         local_irq_restore(flags);
1643 }
1644 #else /* CONFIG_HIGH_RES_TIMERS */
1645
1646 static inline void __hrtimer_peek_ahead_timers(void) { }
1647
1648 #endif  /* !CONFIG_HIGH_RES_TIMERS */
1649
1650
1651 static void run_hrtimer_softirq(struct softirq_action *h)
1652 {
1653         hrtimer_rt_run_pending();
1654 }
1655
1656 /*
1657  * Called from timer softirq every jiffy, expire hrtimers:
1658  *
1659  * For HRT its the fall back code to run the softirq in the timer
1660  * softirq context in case the hrtimer initialization failed or has
1661  * not been done yet.
1662  */
1663 void hrtimer_run_pending(void)
1664 {
1665         if (hrtimer_hres_active())
1666                 return;
1667
1668         /*
1669          * This _is_ ugly: We have to check in the softirq context,
1670          * whether we can switch to highres and / or nohz mode. The
1671          * clocksource switch happens in the timer interrupt with
1672          * xtime_lock held. Notification from there only sets the
1673          * check bit in the tick_oneshot code, otherwise we might
1674          * deadlock vs. xtime_lock.
1675          */
1676         if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1677                 hrtimer_switch_to_hres();
1678 }
1679
1680 /*
1681  * Called from hardirq context every jiffy
1682  */
1683 void hrtimer_run_queues(void)
1684 {
1685         struct timerqueue_node *node;
1686         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1687         struct hrtimer_clock_base *base;
1688         int index, gettime = 1, raise = 0;
1689
1690         if (hrtimer_hres_active())
1691                 return;
1692
1693         for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1694                 base = &cpu_base->clock_base[index];
1695                 if (!timerqueue_getnext(&base->active))
1696                         continue;
1697
1698                 if (gettime) {
1699                         hrtimer_get_softirq_time(cpu_base);
1700                         gettime = 0;
1701                 }
1702
1703                 raw_spin_lock(&cpu_base->lock);
1704
1705                 while ((node = timerqueue_getnext(&base->active))) {
1706                         struct hrtimer *timer;
1707
1708                         timer = container_of(node, struct hrtimer, node);
1709                         if (base->softirq_time.tv64 <=
1710                                         hrtimer_get_expires_tv64(timer))
1711                                 break;
1712
1713                         if (!hrtimer_rt_defer(timer))
1714                                 __run_hrtimer(timer, &base->softirq_time);
1715                         else
1716                                 raise = 1;
1717                 }
1718                 raw_spin_unlock(&cpu_base->lock);
1719         }
1720
1721         if (raise)
1722                 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1723 }
1724
1725 /*
1726  * Sleep related functions:
1727  */
1728 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1729 {
1730         struct hrtimer_sleeper *t =
1731                 container_of(timer, struct hrtimer_sleeper, timer);
1732         struct task_struct *task = t->task;
1733
1734         t->task = NULL;
1735         if (task)
1736                 wake_up_process(task);
1737
1738         return HRTIMER_NORESTART;
1739 }
1740
1741 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1742 {
1743         sl->timer.function = hrtimer_wakeup;
1744         sl->timer.irqsafe = 1;
1745         sl->task = task;
1746 }
1747 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1748
1749 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode,
1750                                 unsigned long state)
1751 {
1752         hrtimer_init_sleeper(t, current);
1753
1754         do {
1755                 set_current_state(state);
1756                 hrtimer_start_expires(&t->timer, mode);
1757                 if (!hrtimer_active(&t->timer))
1758                         t->task = NULL;
1759
1760                 if (likely(t->task))
1761                         freezable_schedule();
1762
1763                 hrtimer_cancel(&t->timer);
1764                 mode = HRTIMER_MODE_ABS;
1765
1766         } while (t->task && !signal_pending(current));
1767
1768         __set_current_state(TASK_RUNNING);
1769
1770         return t->task == NULL;
1771 }
1772
1773 static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1774 {
1775         struct timespec rmt;
1776         ktime_t rem;
1777
1778         rem = hrtimer_expires_remaining(timer);
1779         if (rem.tv64 <= 0)
1780                 return 0;
1781         rmt = ktime_to_timespec(rem);
1782
1783         if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1784                 return -EFAULT;
1785
1786         return 1;
1787 }
1788
1789 long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1790 {
1791         struct hrtimer_sleeper t;
1792         struct timespec __user  *rmtp;
1793         int ret = 0;
1794
1795         hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
1796                                 HRTIMER_MODE_ABS);
1797         hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1798
1799         /* cpu_chill() does not care about restart state. */
1800         if (do_nanosleep(&t, HRTIMER_MODE_ABS, TASK_INTERRUPTIBLE))
1801                 goto out;
1802
1803         rmtp = restart->nanosleep.rmtp;
1804         if (rmtp) {
1805                 ret = update_rmtp(&t.timer, rmtp);
1806                 if (ret <= 0)
1807                         goto out;
1808         }
1809
1810         /* The other values in restart are already filled in */
1811         ret = -ERESTART_RESTARTBLOCK;
1812 out:
1813         destroy_hrtimer_on_stack(&t.timer);
1814         return ret;
1815 }
1816
1817 static long
1818 __hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1819                     const enum hrtimer_mode mode, const clockid_t clockid,
1820                     unsigned long state)
1821 {
1822         struct restart_block *restart;
1823         struct hrtimer_sleeper t;
1824         int ret = 0;
1825         unsigned long slack;
1826
1827         slack = current->timer_slack_ns;
1828         if (dl_task(current) || rt_task(current))
1829                 slack = 0;
1830
1831         hrtimer_init_on_stack(&t.timer, clockid, mode);
1832         hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1833         if (do_nanosleep(&t, mode, state))
1834                 goto out;
1835
1836         /* Absolute timers do not update the rmtp value and restart: */
1837         if (mode == HRTIMER_MODE_ABS) {
1838                 ret = -ERESTARTNOHAND;
1839                 goto out;
1840         }
1841
1842         if (rmtp) {
1843                 ret = update_rmtp(&t.timer, rmtp);
1844                 if (ret <= 0)
1845                         goto out;
1846         }
1847
1848         restart = &current->restart_block;
1849         restart->fn = hrtimer_nanosleep_restart;
1850         restart->nanosleep.clockid = t.timer.base->clockid;
1851         restart->nanosleep.rmtp = rmtp;
1852         restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1853
1854         ret = -ERESTART_RESTARTBLOCK;
1855 out:
1856         destroy_hrtimer_on_stack(&t.timer);
1857         return ret;
1858 }
1859
1860 long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1861                        const enum hrtimer_mode mode, const clockid_t clockid)
1862 {
1863         return __hrtimer_nanosleep(rqtp, rmtp, mode, clockid, TASK_INTERRUPTIBLE);
1864 }
1865
1866 SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1867                 struct timespec __user *, rmtp)
1868 {
1869         struct timespec tu;
1870
1871         if (copy_from_user(&tu, rqtp, sizeof(tu)))
1872                 return -EFAULT;
1873
1874         if (!timespec_valid(&tu))
1875                 return -EINVAL;
1876
1877         return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1878 }
1879
1880 #ifdef CONFIG_PREEMPT_RT_FULL
1881 /*
1882  * Sleep for 1 ms in hope whoever holds what we want will let it go.
1883  */
1884 void cpu_chill(void)
1885 {
1886         struct timespec tu = {
1887                 .tv_nsec = NSEC_PER_MSEC,
1888         };
1889         unsigned int freeze_flag = current->flags & PF_NOFREEZE;
1890
1891         current->flags |= PF_NOFREEZE;
1892         __hrtimer_nanosleep(&tu, NULL, HRTIMER_MODE_REL, CLOCK_MONOTONIC,
1893                             TASK_UNINTERRUPTIBLE);
1894         if (!freeze_flag)
1895                 current->flags &= ~PF_NOFREEZE;
1896 }
1897 EXPORT_SYMBOL(cpu_chill);
1898 #endif
1899
1900 /*
1901  * Functions related to boot-time initialization:
1902  */
1903 static void init_hrtimers_cpu(int cpu)
1904 {
1905         struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1906         int i;
1907
1908         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1909                 cpu_base->clock_base[i].cpu_base = cpu_base;
1910                 timerqueue_init_head(&cpu_base->clock_base[i].active);
1911                 INIT_LIST_HEAD(&cpu_base->clock_base[i].expired);
1912         }
1913
1914         cpu_base->cpu = cpu;
1915         hrtimer_init_hres(cpu_base);
1916 #ifdef CONFIG_PREEMPT_RT_BASE
1917         init_waitqueue_head(&cpu_base->wait);
1918 #endif
1919 }
1920
1921 #ifdef CONFIG_HOTPLUG_CPU
1922
1923 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1924                                 struct hrtimer_clock_base *new_base)
1925 {
1926         struct hrtimer *timer;
1927         struct timerqueue_node *node;
1928
1929         while ((node = timerqueue_getnext(&old_base->active))) {
1930                 timer = container_of(node, struct hrtimer, node);
1931                 BUG_ON(hrtimer_callback_running(timer));
1932                 debug_deactivate(timer);
1933
1934                 /*
1935                  * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1936                  * timer could be seen as !active and just vanish away
1937                  * under us on another CPU
1938                  */
1939                 __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1940                 timer->base = new_base;
1941                 /*
1942                  * Enqueue the timers on the new cpu. This does not
1943                  * reprogram the event device in case the timer
1944                  * expires before the earliest on this CPU, but we run
1945                  * hrtimer_interrupt after we migrated everything to
1946                  * sort out already expired timers and reprogram the
1947                  * event device.
1948                  */
1949                 enqueue_hrtimer(timer, new_base);
1950
1951                 /* Clear the migration state bit */
1952                 timer->state &= ~HRTIMER_STATE_MIGRATE;
1953         }
1954 }
1955
1956 static void migrate_hrtimers(int scpu)
1957 {
1958         struct hrtimer_cpu_base *old_base, *new_base;
1959         int i;
1960
1961         BUG_ON(cpu_online(scpu));
1962         tick_cancel_sched_timer(scpu);
1963
1964         local_irq_disable();
1965         old_base = &per_cpu(hrtimer_bases, scpu);
1966         new_base = this_cpu_ptr(&hrtimer_bases);
1967         /*
1968          * The caller is globally serialized and nobody else
1969          * takes two locks at once, deadlock is not possible.
1970          */
1971         raw_spin_lock(&new_base->lock);
1972         raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1973
1974         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1975                 migrate_hrtimer_list(&old_base->clock_base[i],
1976                                      &new_base->clock_base[i]);
1977         }
1978
1979         raw_spin_unlock(&old_base->lock);
1980         raw_spin_unlock(&new_base->lock);
1981
1982         /* Check, if we got expired work to do */
1983         __hrtimer_peek_ahead_timers();
1984         local_irq_enable();
1985 }
1986
1987 #endif /* CONFIG_HOTPLUG_CPU */
1988
1989 static int hrtimer_cpu_notify(struct notifier_block *self,
1990                                         unsigned long action, void *hcpu)
1991 {
1992         int scpu = (long)hcpu;
1993
1994         switch (action) {
1995
1996         case CPU_UP_PREPARE:
1997         case CPU_UP_PREPARE_FROZEN:
1998                 init_hrtimers_cpu(scpu);
1999                 break;
2000
2001 #ifdef CONFIG_HOTPLUG_CPU
2002         case CPU_DEAD:
2003         case CPU_DEAD_FROZEN:
2004                 migrate_hrtimers(scpu);
2005                 break;
2006 #endif
2007
2008         default:
2009                 break;
2010         }
2011
2012         return NOTIFY_OK;
2013 }
2014
2015 static struct notifier_block hrtimers_nb = {
2016         .notifier_call = hrtimer_cpu_notify,
2017 };
2018
2019 void __init hrtimers_init(void)
2020 {
2021         hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
2022                           (void *)(long)smp_processor_id());
2023         register_cpu_notifier(&hrtimers_nb);
2024         open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
2025 }
2026
2027 /**
2028  * schedule_hrtimeout_range_clock - sleep until timeout
2029  * @expires:    timeout value (ktime_t)
2030  * @delta:      slack in expires timeout (ktime_t)
2031  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2032  * @clock:      timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
2033  */
2034 int __sched
2035 schedule_hrtimeout_range_clock(ktime_t *expires, unsigned long delta,
2036                                const enum hrtimer_mode mode, int clock)
2037 {
2038         struct hrtimer_sleeper t;
2039
2040         /*
2041          * Optimize when a zero timeout value is given. It does not
2042          * matter whether this is an absolute or a relative time.
2043          */
2044         if (expires && !expires->tv64) {
2045                 __set_current_state(TASK_RUNNING);
2046                 return 0;
2047         }
2048
2049         /*
2050          * A NULL parameter means "infinite"
2051          */
2052         if (!expires) {
2053                 schedule();
2054                 return -EINTR;
2055         }
2056
2057         hrtimer_init_on_stack(&t.timer, clock, mode);
2058         hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
2059
2060         hrtimer_init_sleeper(&t, current);
2061
2062         hrtimer_start_expires(&t.timer, mode);
2063         if (!hrtimer_active(&t.timer))
2064                 t.task = NULL;
2065
2066         if (likely(t.task))
2067                 schedule();
2068
2069         hrtimer_cancel(&t.timer);
2070         destroy_hrtimer_on_stack(&t.timer);
2071
2072         __set_current_state(TASK_RUNNING);
2073
2074         return !t.task ? 0 : -EINTR;
2075 }
2076
2077 /**
2078  * schedule_hrtimeout_range - sleep until timeout
2079  * @expires:    timeout value (ktime_t)
2080  * @delta:      slack in expires timeout (ktime_t)
2081  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2082  *
2083  * Make the current task sleep until the given expiry time has
2084  * elapsed. The routine will return immediately unless
2085  * the current task state has been set (see set_current_state()).
2086  *
2087  * The @delta argument gives the kernel the freedom to schedule the
2088  * actual wakeup to a time that is both power and performance friendly.
2089  * The kernel give the normal best effort behavior for "@expires+@delta",
2090  * but may decide to fire the timer earlier, but no earlier than @expires.
2091  *
2092  * You can set the task state as follows -
2093  *
2094  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2095  * pass before the routine returns.
2096  *
2097  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2098  * delivered to the current task.
2099  *
2100  * The current task state is guaranteed to be TASK_RUNNING when this
2101  * routine returns.
2102  *
2103  * Returns 0 when the timer has expired otherwise -EINTR
2104  */
2105 int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
2106                                      const enum hrtimer_mode mode)
2107 {
2108         return schedule_hrtimeout_range_clock(expires, delta, mode,
2109                                               CLOCK_MONOTONIC);
2110 }
2111 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
2112
2113 /**
2114  * schedule_hrtimeout - sleep until timeout
2115  * @expires:    timeout value (ktime_t)
2116  * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
2117  *
2118  * Make the current task sleep until the given expiry time has
2119  * elapsed. The routine will return immediately unless
2120  * the current task state has been set (see set_current_state()).
2121  *
2122  * You can set the task state as follows -
2123  *
2124  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2125  * pass before the routine returns.
2126  *
2127  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2128  * delivered to the current task.
2129  *
2130  * The current task state is guaranteed to be TASK_RUNNING when this
2131  * routine returns.
2132  *
2133  * Returns 0 when the timer has expired otherwise -EINTR
2134  */
2135 int __sched schedule_hrtimeout(ktime_t *expires,
2136                                const enum hrtimer_mode mode)
2137 {
2138         return schedule_hrtimeout_range(expires, 0, mode);
2139 }
2140 EXPORT_SYMBOL_GPL(schedule_hrtimeout);