hrtimer: Avoid more SMP function calls in clock_was_set()
[platform/kernel/linux-rpi.git] / kernel / time / hrtimer.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
4  *  Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
5  *  Copyright(C) 2006-2007  Timesys Corp., Thomas Gleixner
6  *
7  *  High-resolution kernel timers
8  *
9  *  In contrast to the low-resolution timeout API, aka timer wheel,
10  *  hrtimers provide finer resolution and accuracy depending on system
11  *  configuration and capabilities.
12  *
13  *  Started by: Thomas Gleixner and Ingo Molnar
14  *
15  *  Credits:
16  *      Based on the original timer wheel code
17  *
18  *      Help, testing, suggestions, bugfixes, improvements were
19  *      provided by:
20  *
21  *      George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
22  *      et. al.
23  */
24
25 #include <linux/cpu.h>
26 #include <linux/export.h>
27 #include <linux/percpu.h>
28 #include <linux/hrtimer.h>
29 #include <linux/notifier.h>
30 #include <linux/syscalls.h>
31 #include <linux/interrupt.h>
32 #include <linux/tick.h>
33 #include <linux/err.h>
34 #include <linux/debugobjects.h>
35 #include <linux/sched/signal.h>
36 #include <linux/sched/sysctl.h>
37 #include <linux/sched/rt.h>
38 #include <linux/sched/deadline.h>
39 #include <linux/sched/nohz.h>
40 #include <linux/sched/debug.h>
41 #include <linux/timer.h>
42 #include <linux/freezer.h>
43 #include <linux/compat.h>
44
45 #include <linux/uaccess.h>
46
47 #include <trace/events/timer.h>
48
49 #include "tick-internal.h"
50
51 /*
52  * Masks for selecting the soft and hard context timers from
53  * cpu_base->active
54  */
55 #define MASK_SHIFT              (HRTIMER_BASE_MONOTONIC_SOFT)
56 #define HRTIMER_ACTIVE_HARD     ((1U << MASK_SHIFT) - 1)
57 #define HRTIMER_ACTIVE_SOFT     (HRTIMER_ACTIVE_HARD << MASK_SHIFT)
58 #define HRTIMER_ACTIVE_ALL      (HRTIMER_ACTIVE_SOFT | HRTIMER_ACTIVE_HARD)
59
60 /*
61  * The timer bases:
62  *
63  * There are more clockids than hrtimer bases. Thus, we index
64  * into the timer bases by the hrtimer_base_type enum. When trying
65  * to reach a base using a clockid, hrtimer_clockid_to_base()
66  * is used to convert from clockid to the proper hrtimer_base_type.
67  */
68 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
69 {
70         .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
71         .clock_base =
72         {
73                 {
74                         .index = HRTIMER_BASE_MONOTONIC,
75                         .clockid = CLOCK_MONOTONIC,
76                         .get_time = &ktime_get,
77                 },
78                 {
79                         .index = HRTIMER_BASE_REALTIME,
80                         .clockid = CLOCK_REALTIME,
81                         .get_time = &ktime_get_real,
82                 },
83                 {
84                         .index = HRTIMER_BASE_BOOTTIME,
85                         .clockid = CLOCK_BOOTTIME,
86                         .get_time = &ktime_get_boottime,
87                 },
88                 {
89                         .index = HRTIMER_BASE_TAI,
90                         .clockid = CLOCK_TAI,
91                         .get_time = &ktime_get_clocktai,
92                 },
93                 {
94                         .index = HRTIMER_BASE_MONOTONIC_SOFT,
95                         .clockid = CLOCK_MONOTONIC,
96                         .get_time = &ktime_get,
97                 },
98                 {
99                         .index = HRTIMER_BASE_REALTIME_SOFT,
100                         .clockid = CLOCK_REALTIME,
101                         .get_time = &ktime_get_real,
102                 },
103                 {
104                         .index = HRTIMER_BASE_BOOTTIME_SOFT,
105                         .clockid = CLOCK_BOOTTIME,
106                         .get_time = &ktime_get_boottime,
107                 },
108                 {
109                         .index = HRTIMER_BASE_TAI_SOFT,
110                         .clockid = CLOCK_TAI,
111                         .get_time = &ktime_get_clocktai,
112                 },
113         }
114 };
115
116 static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
117         /* Make sure we catch unsupported clockids */
118         [0 ... MAX_CLOCKS - 1]  = HRTIMER_MAX_CLOCK_BASES,
119
120         [CLOCK_REALTIME]        = HRTIMER_BASE_REALTIME,
121         [CLOCK_MONOTONIC]       = HRTIMER_BASE_MONOTONIC,
122         [CLOCK_BOOTTIME]        = HRTIMER_BASE_BOOTTIME,
123         [CLOCK_TAI]             = HRTIMER_BASE_TAI,
124 };
125
126 /*
127  * Functions and macros which are different for UP/SMP systems are kept in a
128  * single place
129  */
130 #ifdef CONFIG_SMP
131
132 /*
133  * We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base()
134  * such that hrtimer_callback_running() can unconditionally dereference
135  * timer->base->cpu_base
136  */
137 static struct hrtimer_cpu_base migration_cpu_base = {
138         .clock_base = { {
139                 .cpu_base = &migration_cpu_base,
140                 .seq      = SEQCNT_RAW_SPINLOCK_ZERO(migration_cpu_base.seq,
141                                                      &migration_cpu_base.lock),
142         }, },
143 };
144
145 #define migration_base  migration_cpu_base.clock_base[0]
146
147 static inline bool is_migration_base(struct hrtimer_clock_base *base)
148 {
149         return base == &migration_base;
150 }
151
152 /*
153  * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
154  * means that all timers which are tied to this base via timer->base are
155  * locked, and the base itself is locked too.
156  *
157  * So __run_timers/migrate_timers can safely modify all timers which could
158  * be found on the lists/queues.
159  *
160  * When the timer's base is locked, and the timer removed from list, it is
161  * possible to set timer->base = &migration_base and drop the lock: the timer
162  * remains locked.
163  */
164 static
165 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
166                                              unsigned long *flags)
167 {
168         struct hrtimer_clock_base *base;
169
170         for (;;) {
171                 base = READ_ONCE(timer->base);
172                 if (likely(base != &migration_base)) {
173                         raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
174                         if (likely(base == timer->base))
175                                 return base;
176                         /* The timer has migrated to another CPU: */
177                         raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
178                 }
179                 cpu_relax();
180         }
181 }
182
183 /*
184  * We do not migrate the timer when it is expiring before the next
185  * event on the target cpu. When high resolution is enabled, we cannot
186  * reprogram the target cpu hardware and we would cause it to fire
187  * late. To keep it simple, we handle the high resolution enabled and
188  * disabled case similar.
189  *
190  * Called with cpu_base->lock of target cpu held.
191  */
192 static int
193 hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
194 {
195         ktime_t expires;
196
197         expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
198         return expires < new_base->cpu_base->expires_next;
199 }
200
201 static inline
202 struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base,
203                                          int pinned)
204 {
205 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
206         if (static_branch_likely(&timers_migration_enabled) && !pinned)
207                 return &per_cpu(hrtimer_bases, get_nohz_timer_target());
208 #endif
209         return base;
210 }
211
212 /*
213  * We switch the timer base to a power-optimized selected CPU target,
214  * if:
215  *      - NO_HZ_COMMON is enabled
216  *      - timer migration is enabled
217  *      - the timer callback is not running
218  *      - the timer is not the first expiring timer on the new target
219  *
220  * If one of the above requirements is not fulfilled we move the timer
221  * to the current CPU or leave it on the previously assigned CPU if
222  * the timer callback is currently running.
223  */
224 static inline struct hrtimer_clock_base *
225 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
226                     int pinned)
227 {
228         struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base;
229         struct hrtimer_clock_base *new_base;
230         int basenum = base->index;
231
232         this_cpu_base = this_cpu_ptr(&hrtimer_bases);
233         new_cpu_base = get_target_base(this_cpu_base, pinned);
234 again:
235         new_base = &new_cpu_base->clock_base[basenum];
236
237         if (base != new_base) {
238                 /*
239                  * We are trying to move timer to new_base.
240                  * However we can't change timer's base while it is running,
241                  * so we keep it on the same CPU. No hassle vs. reprogramming
242                  * the event source in the high resolution case. The softirq
243                  * code will take care of this when the timer function has
244                  * completed. There is no conflict as we hold the lock until
245                  * the timer is enqueued.
246                  */
247                 if (unlikely(hrtimer_callback_running(timer)))
248                         return base;
249
250                 /* See the comment in lock_hrtimer_base() */
251                 WRITE_ONCE(timer->base, &migration_base);
252                 raw_spin_unlock(&base->cpu_base->lock);
253                 raw_spin_lock(&new_base->cpu_base->lock);
254
255                 if (new_cpu_base != this_cpu_base &&
256                     hrtimer_check_target(timer, new_base)) {
257                         raw_spin_unlock(&new_base->cpu_base->lock);
258                         raw_spin_lock(&base->cpu_base->lock);
259                         new_cpu_base = this_cpu_base;
260                         WRITE_ONCE(timer->base, base);
261                         goto again;
262                 }
263                 WRITE_ONCE(timer->base, new_base);
264         } else {
265                 if (new_cpu_base != this_cpu_base &&
266                     hrtimer_check_target(timer, new_base)) {
267                         new_cpu_base = this_cpu_base;
268                         goto again;
269                 }
270         }
271         return new_base;
272 }
273
274 #else /* CONFIG_SMP */
275
276 static inline bool is_migration_base(struct hrtimer_clock_base *base)
277 {
278         return false;
279 }
280
281 static inline struct hrtimer_clock_base *
282 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
283 {
284         struct hrtimer_clock_base *base = timer->base;
285
286         raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
287
288         return base;
289 }
290
291 # define switch_hrtimer_base(t, b, p)   (b)
292
293 #endif  /* !CONFIG_SMP */
294
295 /*
296  * Functions for the union type storage format of ktime_t which are
297  * too large for inlining:
298  */
299 #if BITS_PER_LONG < 64
300 /*
301  * Divide a ktime value by a nanosecond value
302  */
303 s64 __ktime_divns(const ktime_t kt, s64 div)
304 {
305         int sft = 0;
306         s64 dclc;
307         u64 tmp;
308
309         dclc = ktime_to_ns(kt);
310         tmp = dclc < 0 ? -dclc : dclc;
311
312         /* Make sure the divisor is less than 2^32: */
313         while (div >> 32) {
314                 sft++;
315                 div >>= 1;
316         }
317         tmp >>= sft;
318         do_div(tmp, (u32) div);
319         return dclc < 0 ? -tmp : tmp;
320 }
321 EXPORT_SYMBOL_GPL(__ktime_divns);
322 #endif /* BITS_PER_LONG >= 64 */
323
324 /*
325  * Add two ktime values and do a safety check for overflow:
326  */
327 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
328 {
329         ktime_t res = ktime_add_unsafe(lhs, rhs);
330
331         /*
332          * We use KTIME_SEC_MAX here, the maximum timeout which we can
333          * return to user space in a timespec:
334          */
335         if (res < 0 || res < lhs || res < rhs)
336                 res = ktime_set(KTIME_SEC_MAX, 0);
337
338         return res;
339 }
340
341 EXPORT_SYMBOL_GPL(ktime_add_safe);
342
343 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
344
345 static const struct debug_obj_descr hrtimer_debug_descr;
346
347 static void *hrtimer_debug_hint(void *addr)
348 {
349         return ((struct hrtimer *) addr)->function;
350 }
351
352 /*
353  * fixup_init is called when:
354  * - an active object is initialized
355  */
356 static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state)
357 {
358         struct hrtimer *timer = addr;
359
360         switch (state) {
361         case ODEBUG_STATE_ACTIVE:
362                 hrtimer_cancel(timer);
363                 debug_object_init(timer, &hrtimer_debug_descr);
364                 return true;
365         default:
366                 return false;
367         }
368 }
369
370 /*
371  * fixup_activate is called when:
372  * - an active object is activated
373  * - an unknown non-static object is activated
374  */
375 static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
376 {
377         switch (state) {
378         case ODEBUG_STATE_ACTIVE:
379                 WARN_ON(1);
380                 fallthrough;
381         default:
382                 return false;
383         }
384 }
385
386 /*
387  * fixup_free is called when:
388  * - an active object is freed
389  */
390 static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state)
391 {
392         struct hrtimer *timer = addr;
393
394         switch (state) {
395         case ODEBUG_STATE_ACTIVE:
396                 hrtimer_cancel(timer);
397                 debug_object_free(timer, &hrtimer_debug_descr);
398                 return true;
399         default:
400                 return false;
401         }
402 }
403
404 static const struct debug_obj_descr hrtimer_debug_descr = {
405         .name           = "hrtimer",
406         .debug_hint     = hrtimer_debug_hint,
407         .fixup_init     = hrtimer_fixup_init,
408         .fixup_activate = hrtimer_fixup_activate,
409         .fixup_free     = hrtimer_fixup_free,
410 };
411
412 static inline void debug_hrtimer_init(struct hrtimer *timer)
413 {
414         debug_object_init(timer, &hrtimer_debug_descr);
415 }
416
417 static inline void debug_hrtimer_activate(struct hrtimer *timer,
418                                           enum hrtimer_mode mode)
419 {
420         debug_object_activate(timer, &hrtimer_debug_descr);
421 }
422
423 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
424 {
425         debug_object_deactivate(timer, &hrtimer_debug_descr);
426 }
427
428 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
429                            enum hrtimer_mode mode);
430
431 void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
432                            enum hrtimer_mode mode)
433 {
434         debug_object_init_on_stack(timer, &hrtimer_debug_descr);
435         __hrtimer_init(timer, clock_id, mode);
436 }
437 EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
438
439 static void __hrtimer_init_sleeper(struct hrtimer_sleeper *sl,
440                                    clockid_t clock_id, enum hrtimer_mode mode);
441
442 void hrtimer_init_sleeper_on_stack(struct hrtimer_sleeper *sl,
443                                    clockid_t clock_id, enum hrtimer_mode mode)
444 {
445         debug_object_init_on_stack(&sl->timer, &hrtimer_debug_descr);
446         __hrtimer_init_sleeper(sl, clock_id, mode);
447 }
448 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper_on_stack);
449
450 void destroy_hrtimer_on_stack(struct hrtimer *timer)
451 {
452         debug_object_free(timer, &hrtimer_debug_descr);
453 }
454 EXPORT_SYMBOL_GPL(destroy_hrtimer_on_stack);
455
456 #else
457
458 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
459 static inline void debug_hrtimer_activate(struct hrtimer *timer,
460                                           enum hrtimer_mode mode) { }
461 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
462 #endif
463
464 static inline void
465 debug_init(struct hrtimer *timer, clockid_t clockid,
466            enum hrtimer_mode mode)
467 {
468         debug_hrtimer_init(timer);
469         trace_hrtimer_init(timer, clockid, mode);
470 }
471
472 static inline void debug_activate(struct hrtimer *timer,
473                                   enum hrtimer_mode mode)
474 {
475         debug_hrtimer_activate(timer, mode);
476         trace_hrtimer_start(timer, mode);
477 }
478
479 static inline void debug_deactivate(struct hrtimer *timer)
480 {
481         debug_hrtimer_deactivate(timer);
482         trace_hrtimer_cancel(timer);
483 }
484
485 static struct hrtimer_clock_base *
486 __next_base(struct hrtimer_cpu_base *cpu_base, unsigned int *active)
487 {
488         unsigned int idx;
489
490         if (!*active)
491                 return NULL;
492
493         idx = __ffs(*active);
494         *active &= ~(1U << idx);
495
496         return &cpu_base->clock_base[idx];
497 }
498
499 #define for_each_active_base(base, cpu_base, active)    \
500         while ((base = __next_base((cpu_base), &(active))))
501
502 static ktime_t __hrtimer_next_event_base(struct hrtimer_cpu_base *cpu_base,
503                                          const struct hrtimer *exclude,
504                                          unsigned int active,
505                                          ktime_t expires_next)
506 {
507         struct hrtimer_clock_base *base;
508         ktime_t expires;
509
510         for_each_active_base(base, cpu_base, active) {
511                 struct timerqueue_node *next;
512                 struct hrtimer *timer;
513
514                 next = timerqueue_getnext(&base->active);
515                 timer = container_of(next, struct hrtimer, node);
516                 if (timer == exclude) {
517                         /* Get to the next timer in the queue. */
518                         next = timerqueue_iterate_next(next);
519                         if (!next)
520                                 continue;
521
522                         timer = container_of(next, struct hrtimer, node);
523                 }
524                 expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
525                 if (expires < expires_next) {
526                         expires_next = expires;
527
528                         /* Skip cpu_base update if a timer is being excluded. */
529                         if (exclude)
530                                 continue;
531
532                         if (timer->is_soft)
533                                 cpu_base->softirq_next_timer = timer;
534                         else
535                                 cpu_base->next_timer = timer;
536                 }
537         }
538         /*
539          * clock_was_set() might have changed base->offset of any of
540          * the clock bases so the result might be negative. Fix it up
541          * to prevent a false positive in clockevents_program_event().
542          */
543         if (expires_next < 0)
544                 expires_next = 0;
545         return expires_next;
546 }
547
548 /*
549  * Recomputes cpu_base::*next_timer and returns the earliest expires_next
550  * but does not set cpu_base::*expires_next, that is done by
551  * hrtimer[_force]_reprogram and hrtimer_interrupt only. When updating
552  * cpu_base::*expires_next right away, reprogramming logic would no longer
553  * work.
554  *
555  * When a softirq is pending, we can ignore the HRTIMER_ACTIVE_SOFT bases,
556  * those timers will get run whenever the softirq gets handled, at the end of
557  * hrtimer_run_softirq(), hrtimer_update_softirq_timer() will re-add these bases.
558  *
559  * Therefore softirq values are those from the HRTIMER_ACTIVE_SOFT clock bases.
560  * The !softirq values are the minima across HRTIMER_ACTIVE_ALL, unless an actual
561  * softirq is pending, in which case they're the minima of HRTIMER_ACTIVE_HARD.
562  *
563  * @active_mask must be one of:
564  *  - HRTIMER_ACTIVE_ALL,
565  *  - HRTIMER_ACTIVE_SOFT, or
566  *  - HRTIMER_ACTIVE_HARD.
567  */
568 static ktime_t
569 __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base, unsigned int active_mask)
570 {
571         unsigned int active;
572         struct hrtimer *next_timer = NULL;
573         ktime_t expires_next = KTIME_MAX;
574
575         if (!cpu_base->softirq_activated && (active_mask & HRTIMER_ACTIVE_SOFT)) {
576                 active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
577                 cpu_base->softirq_next_timer = NULL;
578                 expires_next = __hrtimer_next_event_base(cpu_base, NULL,
579                                                          active, KTIME_MAX);
580
581                 next_timer = cpu_base->softirq_next_timer;
582         }
583
584         if (active_mask & HRTIMER_ACTIVE_HARD) {
585                 active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
586                 cpu_base->next_timer = next_timer;
587                 expires_next = __hrtimer_next_event_base(cpu_base, NULL, active,
588                                                          expires_next);
589         }
590
591         return expires_next;
592 }
593
594 static ktime_t hrtimer_update_next_event(struct hrtimer_cpu_base *cpu_base)
595 {
596         ktime_t expires_next, soft = KTIME_MAX;
597
598         /*
599          * If the soft interrupt has already been activated, ignore the
600          * soft bases. They will be handled in the already raised soft
601          * interrupt.
602          */
603         if (!cpu_base->softirq_activated) {
604                 soft = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
605                 /*
606                  * Update the soft expiry time. clock_settime() might have
607                  * affected it.
608                  */
609                 cpu_base->softirq_expires_next = soft;
610         }
611
612         expires_next = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_HARD);
613         /*
614          * If a softirq timer is expiring first, update cpu_base->next_timer
615          * and program the hardware with the soft expiry time.
616          */
617         if (expires_next > soft) {
618                 cpu_base->next_timer = cpu_base->softirq_next_timer;
619                 expires_next = soft;
620         }
621
622         return expires_next;
623 }
624
625 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
626 {
627         ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
628         ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
629         ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
630
631         ktime_t now = ktime_get_update_offsets_now(&base->clock_was_set_seq,
632                                             offs_real, offs_boot, offs_tai);
633
634         base->clock_base[HRTIMER_BASE_REALTIME_SOFT].offset = *offs_real;
635         base->clock_base[HRTIMER_BASE_BOOTTIME_SOFT].offset = *offs_boot;
636         base->clock_base[HRTIMER_BASE_TAI_SOFT].offset = *offs_tai;
637
638         return now;
639 }
640
641 /*
642  * Is the high resolution mode active ?
643  */
644 static inline int __hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base)
645 {
646         return IS_ENABLED(CONFIG_HIGH_RES_TIMERS) ?
647                 cpu_base->hres_active : 0;
648 }
649
650 static inline int hrtimer_hres_active(void)
651 {
652         return __hrtimer_hres_active(this_cpu_ptr(&hrtimer_bases));
653 }
654
655 static void
656 __hrtimer_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal,
657                     struct hrtimer *next_timer, ktime_t expires_next)
658 {
659         /*
660          * If the hrtimer interrupt is running, then it will reevaluate the
661          * clock bases and reprogram the clock event device.
662          */
663         if (cpu_base->in_hrtirq)
664                 return;
665
666         if (expires_next > cpu_base->expires_next)
667                 return;
668
669         if (skip_equal && expires_next == cpu_base->expires_next)
670                 return;
671
672         cpu_base->next_timer = next_timer;
673         cpu_base->expires_next = expires_next;
674
675         /*
676          * If hres is not active, hardware does not have to be
677          * reprogrammed yet.
678          *
679          * If a hang was detected in the last timer interrupt then we
680          * leave the hang delay active in the hardware. We want the
681          * system to make progress. That also prevents the following
682          * scenario:
683          * T1 expires 50ms from now
684          * T2 expires 5s from now
685          *
686          * T1 is removed, so this code is called and would reprogram
687          * the hardware to 5s from now. Any hrtimer_start after that
688          * will not reprogram the hardware due to hang_detected being
689          * set. So we'd effectively block all timers until the T2 event
690          * fires.
691          */
692         if (!__hrtimer_hres_active(cpu_base) || cpu_base->hang_detected)
693                 return;
694
695         tick_program_event(expires_next, 1);
696 }
697
698 /*
699  * Reprogram the event source with checking both queues for the
700  * next event
701  * Called with interrupts disabled and base->lock held
702  */
703 static void
704 hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
705 {
706         ktime_t expires_next;
707
708         expires_next = hrtimer_update_next_event(cpu_base);
709
710         __hrtimer_reprogram(cpu_base, skip_equal, cpu_base->next_timer,
711                             expires_next);
712 }
713
714 /* High resolution timer related functions */
715 #ifdef CONFIG_HIGH_RES_TIMERS
716
717 /*
718  * High resolution timer enabled ?
719  */
720 static bool hrtimer_hres_enabled __read_mostly  = true;
721 unsigned int hrtimer_resolution __read_mostly = LOW_RES_NSEC;
722 EXPORT_SYMBOL_GPL(hrtimer_resolution);
723
724 /*
725  * Enable / Disable high resolution mode
726  */
727 static int __init setup_hrtimer_hres(char *str)
728 {
729         return (kstrtobool(str, &hrtimer_hres_enabled) == 0);
730 }
731
732 __setup("highres=", setup_hrtimer_hres);
733
734 /*
735  * hrtimer_high_res_enabled - query, if the highres mode is enabled
736  */
737 static inline int hrtimer_is_hres_enabled(void)
738 {
739         return hrtimer_hres_enabled;
740 }
741
742 static void retrigger_next_event(void *arg);
743
744 /*
745  * Switch to high resolution mode
746  */
747 static void hrtimer_switch_to_hres(void)
748 {
749         struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
750
751         if (tick_init_highres()) {
752                 pr_warn("Could not switch to high resolution mode on CPU %u\n",
753                         base->cpu);
754                 return;
755         }
756         base->hres_active = 1;
757         hrtimer_resolution = HIGH_RES_NSEC;
758
759         tick_setup_sched_timer();
760         /* "Retrigger" the interrupt to get things going */
761         retrigger_next_event(NULL);
762 }
763
764 #else
765
766 static inline int hrtimer_is_hres_enabled(void) { return 0; }
767 static inline void hrtimer_switch_to_hres(void) { }
768
769 #endif /* CONFIG_HIGH_RES_TIMERS */
770 /*
771  * Retrigger next event is called after clock was set with interrupts
772  * disabled through an SMP function call or directly from low level
773  * resume code.
774  *
775  * This is only invoked when:
776  *      - CONFIG_HIGH_RES_TIMERS is enabled.
777  *      - CONFIG_NOHZ_COMMON is enabled
778  *
779  * For the other cases this function is empty and because the call sites
780  * are optimized out it vanishes as well, i.e. no need for lots of
781  * #ifdeffery.
782  */
783 static void retrigger_next_event(void *arg)
784 {
785         struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
786
787         /*
788          * When high resolution mode or nohz is active, then the offsets of
789          * CLOCK_REALTIME/TAI/BOOTTIME have to be updated. Otherwise the
790          * next tick will take care of that.
791          *
792          * If high resolution mode is active then the next expiring timer
793          * must be reevaluated and the clock event device reprogrammed if
794          * necessary.
795          *
796          * In the NOHZ case the update of the offset and the reevaluation
797          * of the next expiring timer is enough. The return from the SMP
798          * function call will take care of the reprogramming in case the
799          * CPU was in a NOHZ idle sleep.
800          */
801         if (!__hrtimer_hres_active(base) && !tick_nohz_active)
802                 return;
803
804         raw_spin_lock(&base->lock);
805         hrtimer_update_base(base);
806         if (__hrtimer_hres_active(base))
807                 hrtimer_force_reprogram(base, 0);
808         else
809                 hrtimer_update_next_event(base);
810         raw_spin_unlock(&base->lock);
811 }
812
813 /*
814  * When a timer is enqueued and expires earlier than the already enqueued
815  * timers, we have to check, whether it expires earlier than the timer for
816  * which the clock event device was armed.
817  *
818  * Called with interrupts disabled and base->cpu_base.lock held
819  */
820 static void hrtimer_reprogram(struct hrtimer *timer, bool reprogram)
821 {
822         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
823         struct hrtimer_clock_base *base = timer->base;
824         ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
825
826         WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
827
828         /*
829          * CLOCK_REALTIME timer might be requested with an absolute
830          * expiry time which is less than base->offset. Set it to 0.
831          */
832         if (expires < 0)
833                 expires = 0;
834
835         if (timer->is_soft) {
836                 /*
837                  * soft hrtimer could be started on a remote CPU. In this
838                  * case softirq_expires_next needs to be updated on the
839                  * remote CPU. The soft hrtimer will not expire before the
840                  * first hard hrtimer on the remote CPU -
841                  * hrtimer_check_target() prevents this case.
842                  */
843                 struct hrtimer_cpu_base *timer_cpu_base = base->cpu_base;
844
845                 if (timer_cpu_base->softirq_activated)
846                         return;
847
848                 if (!ktime_before(expires, timer_cpu_base->softirq_expires_next))
849                         return;
850
851                 timer_cpu_base->softirq_next_timer = timer;
852                 timer_cpu_base->softirq_expires_next = expires;
853
854                 if (!ktime_before(expires, timer_cpu_base->expires_next) ||
855                     !reprogram)
856                         return;
857         }
858
859         /*
860          * If the timer is not on the current cpu, we cannot reprogram
861          * the other cpus clock event device.
862          */
863         if (base->cpu_base != cpu_base)
864                 return;
865
866         __hrtimer_reprogram(cpu_base, true, timer, expires);
867 }
868
869 static bool update_needs_ipi(struct hrtimer_cpu_base *cpu_base,
870                              unsigned int active)
871 {
872         struct hrtimer_clock_base *base;
873         unsigned int seq;
874         ktime_t expires;
875
876         /*
877          * Update the base offsets unconditionally so the following
878          * checks whether the SMP function call is required works.
879          *
880          * The update is safe even when the remote CPU is in the hrtimer
881          * interrupt or the hrtimer soft interrupt and expiring affected
882          * bases. Either it will see the update before handling a base or
883          * it will see it when it finishes the processing and reevaluates
884          * the next expiring timer.
885          */
886         seq = cpu_base->clock_was_set_seq;
887         hrtimer_update_base(cpu_base);
888
889         /*
890          * If the sequence did not change over the update then the
891          * remote CPU already handled it.
892          */
893         if (seq == cpu_base->clock_was_set_seq)
894                 return false;
895
896         /*
897          * If the remote CPU is currently handling an hrtimer interrupt, it
898          * will reevaluate the first expiring timer of all clock bases
899          * before reprogramming. Nothing to do here.
900          */
901         if (cpu_base->in_hrtirq)
902                 return false;
903
904         /*
905          * Walk the affected clock bases and check whether the first expiring
906          * timer in a clock base is moving ahead of the first expiring timer of
907          * @cpu_base. If so, the IPI must be invoked because per CPU clock
908          * event devices cannot be remotely reprogrammed.
909          */
910         active &= cpu_base->active_bases;
911
912         for_each_active_base(base, cpu_base, active) {
913                 struct timerqueue_node *next;
914
915                 next = timerqueue_getnext(&base->active);
916                 expires = ktime_sub(next->expires, base->offset);
917                 if (expires < cpu_base->expires_next)
918                         return true;
919
920                 /* Extra check for softirq clock bases */
921                 if (base->clockid < HRTIMER_BASE_MONOTONIC_SOFT)
922                         continue;
923                 if (cpu_base->softirq_activated)
924                         continue;
925                 if (expires < cpu_base->softirq_expires_next)
926                         return true;
927         }
928         return false;
929 }
930
931 /*
932  * Clock was set. This might affect CLOCK_REALTIME, CLOCK_TAI and
933  * CLOCK_BOOTTIME (for late sleep time injection).
934  *
935  * This requires to update the offsets for these clocks
936  * vs. CLOCK_MONOTONIC. When high resolution timers are enabled, then this
937  * also requires to eventually reprogram the per CPU clock event devices
938  * when the change moves an affected timer ahead of the first expiring
939  * timer on that CPU. Obviously remote per CPU clock event devices cannot
940  * be reprogrammed. The other reason why an IPI has to be sent is when the
941  * system is in !HIGH_RES and NOHZ mode. The NOHZ mode updates the offsets
942  * in the tick, which obviously might be stopped, so this has to bring out
943  * the remote CPU which might sleep in idle to get this sorted.
944  */
945 void clock_was_set(unsigned int bases)
946 {
947         cpumask_var_t mask;
948         int cpu;
949
950         if (!hrtimer_hres_active() && !tick_nohz_active)
951                 goto out_timerfd;
952
953         if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
954                 on_each_cpu(retrigger_next_event, NULL, 1);
955                 goto out_timerfd;
956         }
957
958         /* Avoid interrupting CPUs if possible */
959         cpus_read_lock();
960         for_each_online_cpu(cpu) {
961                 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
962                 unsigned long flags;
963
964                 raw_spin_lock_irqsave(&cpu_base->lock, flags);
965
966                 if (update_needs_ipi(cpu_base, bases))
967                         cpumask_set_cpu(cpu, mask);
968
969                 raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
970         }
971
972         preempt_disable();
973         smp_call_function_many(mask, retrigger_next_event, NULL, 1);
974         preempt_enable();
975         cpus_read_unlock();
976         free_cpumask_var(mask);
977
978 out_timerfd:
979         timerfd_clock_was_set();
980 }
981
982 static void clock_was_set_work(struct work_struct *work)
983 {
984         clock_was_set(CLOCK_SET_WALL);
985 }
986
987 static DECLARE_WORK(hrtimer_work, clock_was_set_work);
988
989 /*
990  * Called from timekeeping code to reprogram the hrtimer interrupt device
991  * on all cpus and to notify timerfd.
992  */
993 void clock_was_set_delayed(void)
994 {
995         schedule_work(&hrtimer_work);
996 }
997
998 /*
999  * Called during resume either directly from via timekeeping_resume()
1000  * or in the case of s2idle from tick_unfreeze() to ensure that the
1001  * hrtimers are up to date.
1002  */
1003 void hrtimers_resume_local(void)
1004 {
1005         lockdep_assert_irqs_disabled();
1006         /* Retrigger on the local CPU */
1007         retrigger_next_event(NULL);
1008 }
1009
1010 /*
1011  * Counterpart to lock_hrtimer_base above:
1012  */
1013 static inline
1014 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
1015 {
1016         raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
1017 }
1018
1019 /**
1020  * hrtimer_forward - forward the timer expiry
1021  * @timer:      hrtimer to forward
1022  * @now:        forward past this time
1023  * @interval:   the interval to forward
1024  *
1025  * Forward the timer expiry so it will expire in the future.
1026  * Returns the number of overruns.
1027  *
1028  * Can be safely called from the callback function of @timer. If
1029  * called from other contexts @timer must neither be enqueued nor
1030  * running the callback and the caller needs to take care of
1031  * serialization.
1032  *
1033  * Note: This only updates the timer expiry value and does not requeue
1034  * the timer.
1035  */
1036 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
1037 {
1038         u64 orun = 1;
1039         ktime_t delta;
1040
1041         delta = ktime_sub(now, hrtimer_get_expires(timer));
1042
1043         if (delta < 0)
1044                 return 0;
1045
1046         if (WARN_ON(timer->state & HRTIMER_STATE_ENQUEUED))
1047                 return 0;
1048
1049         if (interval < hrtimer_resolution)
1050                 interval = hrtimer_resolution;
1051
1052         if (unlikely(delta >= interval)) {
1053                 s64 incr = ktime_to_ns(interval);
1054
1055                 orun = ktime_divns(delta, incr);
1056                 hrtimer_add_expires_ns(timer, incr * orun);
1057                 if (hrtimer_get_expires_tv64(timer) > now)
1058                         return orun;
1059                 /*
1060                  * This (and the ktime_add() below) is the
1061                  * correction for exact:
1062                  */
1063                 orun++;
1064         }
1065         hrtimer_add_expires(timer, interval);
1066
1067         return orun;
1068 }
1069 EXPORT_SYMBOL_GPL(hrtimer_forward);
1070
1071 /*
1072  * enqueue_hrtimer - internal function to (re)start a timer
1073  *
1074  * The timer is inserted in expiry order. Insertion into the
1075  * red black tree is O(log(n)). Must hold the base lock.
1076  *
1077  * Returns 1 when the new timer is the leftmost timer in the tree.
1078  */
1079 static int enqueue_hrtimer(struct hrtimer *timer,
1080                            struct hrtimer_clock_base *base,
1081                            enum hrtimer_mode mode)
1082 {
1083         debug_activate(timer, mode);
1084
1085         base->cpu_base->active_bases |= 1 << base->index;
1086
1087         /* Pairs with the lockless read in hrtimer_is_queued() */
1088         WRITE_ONCE(timer->state, HRTIMER_STATE_ENQUEUED);
1089
1090         return timerqueue_add(&base->active, &timer->node);
1091 }
1092
1093 /*
1094  * __remove_hrtimer - internal function to remove a timer
1095  *
1096  * Caller must hold the base lock.
1097  *
1098  * High resolution timer mode reprograms the clock event device when the
1099  * timer is the one which expires next. The caller can disable this by setting
1100  * reprogram to zero. This is useful, when the context does a reprogramming
1101  * anyway (e.g. timer interrupt)
1102  */
1103 static void __remove_hrtimer(struct hrtimer *timer,
1104                              struct hrtimer_clock_base *base,
1105                              u8 newstate, int reprogram)
1106 {
1107         struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1108         u8 state = timer->state;
1109
1110         /* Pairs with the lockless read in hrtimer_is_queued() */
1111         WRITE_ONCE(timer->state, newstate);
1112         if (!(state & HRTIMER_STATE_ENQUEUED))
1113                 return;
1114
1115         if (!timerqueue_del(&base->active, &timer->node))
1116                 cpu_base->active_bases &= ~(1 << base->index);
1117
1118         /*
1119          * Note: If reprogram is false we do not update
1120          * cpu_base->next_timer. This happens when we remove the first
1121          * timer on a remote cpu. No harm as we never dereference
1122          * cpu_base->next_timer. So the worst thing what can happen is
1123          * an superfluous call to hrtimer_force_reprogram() on the
1124          * remote cpu later on if the same timer gets enqueued again.
1125          */
1126         if (reprogram && timer == cpu_base->next_timer)
1127                 hrtimer_force_reprogram(cpu_base, 1);
1128 }
1129
1130 /*
1131  * remove hrtimer, called with base lock held
1132  */
1133 static inline int
1134 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base,
1135                bool restart, bool keep_local)
1136 {
1137         u8 state = timer->state;
1138
1139         if (state & HRTIMER_STATE_ENQUEUED) {
1140                 bool reprogram;
1141
1142                 /*
1143                  * Remove the timer and force reprogramming when high
1144                  * resolution mode is active and the timer is on the current
1145                  * CPU. If we remove a timer on another CPU, reprogramming is
1146                  * skipped. The interrupt event on this CPU is fired and
1147                  * reprogramming happens in the interrupt handler. This is a
1148                  * rare case and less expensive than a smp call.
1149                  */
1150                 debug_deactivate(timer);
1151                 reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1152
1153                 /*
1154                  * If the timer is not restarted then reprogramming is
1155                  * required if the timer is local. If it is local and about
1156                  * to be restarted, avoid programming it twice (on removal
1157                  * and a moment later when it's requeued).
1158                  */
1159                 if (!restart)
1160                         state = HRTIMER_STATE_INACTIVE;
1161                 else
1162                         reprogram &= !keep_local;
1163
1164                 __remove_hrtimer(timer, base, state, reprogram);
1165                 return 1;
1166         }
1167         return 0;
1168 }
1169
1170 static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim,
1171                                             const enum hrtimer_mode mode)
1172 {
1173 #ifdef CONFIG_TIME_LOW_RES
1174         /*
1175          * CONFIG_TIME_LOW_RES indicates that the system has no way to return
1176          * granular time values. For relative timers we add hrtimer_resolution
1177          * (i.e. one jiffie) to prevent short timeouts.
1178          */
1179         timer->is_rel = mode & HRTIMER_MODE_REL;
1180         if (timer->is_rel)
1181                 tim = ktime_add_safe(tim, hrtimer_resolution);
1182 #endif
1183         return tim;
1184 }
1185
1186 static void
1187 hrtimer_update_softirq_timer(struct hrtimer_cpu_base *cpu_base, bool reprogram)
1188 {
1189         ktime_t expires;
1190
1191         /*
1192          * Find the next SOFT expiration.
1193          */
1194         expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
1195
1196         /*
1197          * reprogramming needs to be triggered, even if the next soft
1198          * hrtimer expires at the same time than the next hard
1199          * hrtimer. cpu_base->softirq_expires_next needs to be updated!
1200          */
1201         if (expires == KTIME_MAX)
1202                 return;
1203
1204         /*
1205          * cpu_base->*next_timer is recomputed by __hrtimer_get_next_event()
1206          * cpu_base->*expires_next is only set by hrtimer_reprogram()
1207          */
1208         hrtimer_reprogram(cpu_base->softirq_next_timer, reprogram);
1209 }
1210
1211 static int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1212                                     u64 delta_ns, const enum hrtimer_mode mode,
1213                                     struct hrtimer_clock_base *base)
1214 {
1215         struct hrtimer_clock_base *new_base;
1216         bool force_local, first;
1217
1218         /*
1219          * If the timer is on the local cpu base and is the first expiring
1220          * timer then this might end up reprogramming the hardware twice
1221          * (on removal and on enqueue). To avoid that by prevent the
1222          * reprogram on removal, keep the timer local to the current CPU
1223          * and enforce reprogramming after it is queued no matter whether
1224          * it is the new first expiring timer again or not.
1225          */
1226         force_local = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1227         force_local &= base->cpu_base->next_timer == timer;
1228
1229         /*
1230          * Remove an active timer from the queue. In case it is not queued
1231          * on the current CPU, make sure that remove_hrtimer() updates the
1232          * remote data correctly.
1233          *
1234          * If it's on the current CPU and the first expiring timer, then
1235          * skip reprogramming, keep the timer local and enforce
1236          * reprogramming later if it was the first expiring timer.  This
1237          * avoids programming the underlying clock event twice (once at
1238          * removal and once after enqueue).
1239          */
1240         remove_hrtimer(timer, base, true, force_local);
1241
1242         if (mode & HRTIMER_MODE_REL)
1243                 tim = ktime_add_safe(tim, base->get_time());
1244
1245         tim = hrtimer_update_lowres(timer, tim, mode);
1246
1247         hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1248
1249         /* Switch the timer base, if necessary: */
1250         if (!force_local) {
1251                 new_base = switch_hrtimer_base(timer, base,
1252                                                mode & HRTIMER_MODE_PINNED);
1253         } else {
1254                 new_base = base;
1255         }
1256
1257         first = enqueue_hrtimer(timer, new_base, mode);
1258         if (!force_local)
1259                 return first;
1260
1261         /*
1262          * Timer was forced to stay on the current CPU to avoid
1263          * reprogramming on removal and enqueue. Force reprogram the
1264          * hardware by evaluating the new first expiring timer.
1265          */
1266         hrtimer_force_reprogram(new_base->cpu_base, 1);
1267         return 0;
1268 }
1269
1270 /**
1271  * hrtimer_start_range_ns - (re)start an hrtimer
1272  * @timer:      the timer to be added
1273  * @tim:        expiry time
1274  * @delta_ns:   "slack" range for the timer
1275  * @mode:       timer mode: absolute (HRTIMER_MODE_ABS) or
1276  *              relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED);
1277  *              softirq based mode is considered for debug purpose only!
1278  */
1279 void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1280                             u64 delta_ns, const enum hrtimer_mode mode)
1281 {
1282         struct hrtimer_clock_base *base;
1283         unsigned long flags;
1284
1285         /*
1286          * Check whether the HRTIMER_MODE_SOFT bit and hrtimer.is_soft
1287          * match on CONFIG_PREEMPT_RT = n. With PREEMPT_RT check the hard
1288          * expiry mode because unmarked timers are moved to softirq expiry.
1289          */
1290         if (!IS_ENABLED(CONFIG_PREEMPT_RT))
1291                 WARN_ON_ONCE(!(mode & HRTIMER_MODE_SOFT) ^ !timer->is_soft);
1292         else
1293                 WARN_ON_ONCE(!(mode & HRTIMER_MODE_HARD) ^ !timer->is_hard);
1294
1295         base = lock_hrtimer_base(timer, &flags);
1296
1297         if (__hrtimer_start_range_ns(timer, tim, delta_ns, mode, base))
1298                 hrtimer_reprogram(timer, true);
1299
1300         unlock_hrtimer_base(timer, &flags);
1301 }
1302 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1303
1304 /**
1305  * hrtimer_try_to_cancel - try to deactivate a timer
1306  * @timer:      hrtimer to stop
1307  *
1308  * Returns:
1309  *
1310  *  *  0 when the timer was not active
1311  *  *  1 when the timer was active
1312  *  * -1 when the timer is currently executing the callback function and
1313  *    cannot be stopped
1314  */
1315 int hrtimer_try_to_cancel(struct hrtimer *timer)
1316 {
1317         struct hrtimer_clock_base *base;
1318         unsigned long flags;
1319         int ret = -1;
1320
1321         /*
1322          * Check lockless first. If the timer is not active (neither
1323          * enqueued nor running the callback, nothing to do here.  The
1324          * base lock does not serialize against a concurrent enqueue,
1325          * so we can avoid taking it.
1326          */
1327         if (!hrtimer_active(timer))
1328                 return 0;
1329
1330         base = lock_hrtimer_base(timer, &flags);
1331
1332         if (!hrtimer_callback_running(timer))
1333                 ret = remove_hrtimer(timer, base, false, false);
1334
1335         unlock_hrtimer_base(timer, &flags);
1336
1337         return ret;
1338
1339 }
1340 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1341
1342 #ifdef CONFIG_PREEMPT_RT
1343 static void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base)
1344 {
1345         spin_lock_init(&base->softirq_expiry_lock);
1346 }
1347
1348 static void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base)
1349 {
1350         spin_lock(&base->softirq_expiry_lock);
1351 }
1352
1353 static void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base)
1354 {
1355         spin_unlock(&base->softirq_expiry_lock);
1356 }
1357
1358 /*
1359  * The counterpart to hrtimer_cancel_wait_running().
1360  *
1361  * If there is a waiter for cpu_base->expiry_lock, then it was waiting for
1362  * the timer callback to finish. Drop expiry_lock and reacquire it. That
1363  * allows the waiter to acquire the lock and make progress.
1364  */
1365 static void hrtimer_sync_wait_running(struct hrtimer_cpu_base *cpu_base,
1366                                       unsigned long flags)
1367 {
1368         if (atomic_read(&cpu_base->timer_waiters)) {
1369                 raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1370                 spin_unlock(&cpu_base->softirq_expiry_lock);
1371                 spin_lock(&cpu_base->softirq_expiry_lock);
1372                 raw_spin_lock_irq(&cpu_base->lock);
1373         }
1374 }
1375
1376 /*
1377  * This function is called on PREEMPT_RT kernels when the fast path
1378  * deletion of a timer failed because the timer callback function was
1379  * running.
1380  *
1381  * This prevents priority inversion: if the soft irq thread is preempted
1382  * in the middle of a timer callback, then calling del_timer_sync() can
1383  * lead to two issues:
1384  *
1385  *  - If the caller is on a remote CPU then it has to spin wait for the timer
1386  *    handler to complete. This can result in unbound priority inversion.
1387  *
1388  *  - If the caller originates from the task which preempted the timer
1389  *    handler on the same CPU, then spin waiting for the timer handler to
1390  *    complete is never going to end.
1391  */
1392 void hrtimer_cancel_wait_running(const struct hrtimer *timer)
1393 {
1394         /* Lockless read. Prevent the compiler from reloading it below */
1395         struct hrtimer_clock_base *base = READ_ONCE(timer->base);
1396
1397         /*
1398          * Just relax if the timer expires in hard interrupt context or if
1399          * it is currently on the migration base.
1400          */
1401         if (!timer->is_soft || is_migration_base(base)) {
1402                 cpu_relax();
1403                 return;
1404         }
1405
1406         /*
1407          * Mark the base as contended and grab the expiry lock, which is
1408          * held by the softirq across the timer callback. Drop the lock
1409          * immediately so the softirq can expire the next timer. In theory
1410          * the timer could already be running again, but that's more than
1411          * unlikely and just causes another wait loop.
1412          */
1413         atomic_inc(&base->cpu_base->timer_waiters);
1414         spin_lock_bh(&base->cpu_base->softirq_expiry_lock);
1415         atomic_dec(&base->cpu_base->timer_waiters);
1416         spin_unlock_bh(&base->cpu_base->softirq_expiry_lock);
1417 }
1418 #else
1419 static inline void
1420 hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) { }
1421 static inline void
1422 hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) { }
1423 static inline void
1424 hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) { }
1425 static inline void hrtimer_sync_wait_running(struct hrtimer_cpu_base *base,
1426                                              unsigned long flags) { }
1427 #endif
1428
1429 /**
1430  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1431  * @timer:      the timer to be cancelled
1432  *
1433  * Returns:
1434  *  0 when the timer was not active
1435  *  1 when the timer was active
1436  */
1437 int hrtimer_cancel(struct hrtimer *timer)
1438 {
1439         int ret;
1440
1441         do {
1442                 ret = hrtimer_try_to_cancel(timer);
1443
1444                 if (ret < 0)
1445                         hrtimer_cancel_wait_running(timer);
1446         } while (ret < 0);
1447         return ret;
1448 }
1449 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1450
1451 /**
1452  * __hrtimer_get_remaining - get remaining time for the timer
1453  * @timer:      the timer to read
1454  * @adjust:     adjust relative timers when CONFIG_TIME_LOW_RES=y
1455  */
1456 ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
1457 {
1458         unsigned long flags;
1459         ktime_t rem;
1460
1461         lock_hrtimer_base(timer, &flags);
1462         if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
1463                 rem = hrtimer_expires_remaining_adjusted(timer);
1464         else
1465                 rem = hrtimer_expires_remaining(timer);
1466         unlock_hrtimer_base(timer, &flags);
1467
1468         return rem;
1469 }
1470 EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
1471
1472 #ifdef CONFIG_NO_HZ_COMMON
1473 /**
1474  * hrtimer_get_next_event - get the time until next expiry event
1475  *
1476  * Returns the next expiry time or KTIME_MAX if no timer is pending.
1477  */
1478 u64 hrtimer_get_next_event(void)
1479 {
1480         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1481         u64 expires = KTIME_MAX;
1482         unsigned long flags;
1483
1484         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1485
1486         if (!__hrtimer_hres_active(cpu_base))
1487                 expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
1488
1489         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1490
1491         return expires;
1492 }
1493
1494 /**
1495  * hrtimer_next_event_without - time until next expiry event w/o one timer
1496  * @exclude:    timer to exclude
1497  *
1498  * Returns the next expiry time over all timers except for the @exclude one or
1499  * KTIME_MAX if none of them is pending.
1500  */
1501 u64 hrtimer_next_event_without(const struct hrtimer *exclude)
1502 {
1503         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1504         u64 expires = KTIME_MAX;
1505         unsigned long flags;
1506
1507         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1508
1509         if (__hrtimer_hres_active(cpu_base)) {
1510                 unsigned int active;
1511
1512                 if (!cpu_base->softirq_activated) {
1513                         active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
1514                         expires = __hrtimer_next_event_base(cpu_base, exclude,
1515                                                             active, KTIME_MAX);
1516                 }
1517                 active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
1518                 expires = __hrtimer_next_event_base(cpu_base, exclude, active,
1519                                                     expires);
1520         }
1521
1522         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1523
1524         return expires;
1525 }
1526 #endif
1527
1528 static inline int hrtimer_clockid_to_base(clockid_t clock_id)
1529 {
1530         if (likely(clock_id < MAX_CLOCKS)) {
1531                 int base = hrtimer_clock_to_base_table[clock_id];
1532
1533                 if (likely(base != HRTIMER_MAX_CLOCK_BASES))
1534                         return base;
1535         }
1536         WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
1537         return HRTIMER_BASE_MONOTONIC;
1538 }
1539
1540 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1541                            enum hrtimer_mode mode)
1542 {
1543         bool softtimer = !!(mode & HRTIMER_MODE_SOFT);
1544         struct hrtimer_cpu_base *cpu_base;
1545         int base;
1546
1547         /*
1548          * On PREEMPT_RT enabled kernels hrtimers which are not explicitly
1549          * marked for hard interrupt expiry mode are moved into soft
1550          * interrupt context for latency reasons and because the callbacks
1551          * can invoke functions which might sleep on RT, e.g. spin_lock().
1552          */
1553         if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(mode & HRTIMER_MODE_HARD))
1554                 softtimer = true;
1555
1556         memset(timer, 0, sizeof(struct hrtimer));
1557
1558         cpu_base = raw_cpu_ptr(&hrtimer_bases);
1559
1560         /*
1561          * POSIX magic: Relative CLOCK_REALTIME timers are not affected by
1562          * clock modifications, so they needs to become CLOCK_MONOTONIC to
1563          * ensure POSIX compliance.
1564          */
1565         if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL)
1566                 clock_id = CLOCK_MONOTONIC;
1567
1568         base = softtimer ? HRTIMER_MAX_CLOCK_BASES / 2 : 0;
1569         base += hrtimer_clockid_to_base(clock_id);
1570         timer->is_soft = softtimer;
1571         timer->is_hard = !!(mode & HRTIMER_MODE_HARD);
1572         timer->base = &cpu_base->clock_base[base];
1573         timerqueue_init(&timer->node);
1574 }
1575
1576 /**
1577  * hrtimer_init - initialize a timer to the given clock
1578  * @timer:      the timer to be initialized
1579  * @clock_id:   the clock to be used
1580  * @mode:       The modes which are relevant for initialization:
1581  *              HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
1582  *              HRTIMER_MODE_REL_SOFT
1583  *
1584  *              The PINNED variants of the above can be handed in,
1585  *              but the PINNED bit is ignored as pinning happens
1586  *              when the hrtimer is started
1587  */
1588 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1589                   enum hrtimer_mode mode)
1590 {
1591         debug_init(timer, clock_id, mode);
1592         __hrtimer_init(timer, clock_id, mode);
1593 }
1594 EXPORT_SYMBOL_GPL(hrtimer_init);
1595
1596 /*
1597  * A timer is active, when it is enqueued into the rbtree or the
1598  * callback function is running or it's in the state of being migrated
1599  * to another cpu.
1600  *
1601  * It is important for this function to not return a false negative.
1602  */
1603 bool hrtimer_active(const struct hrtimer *timer)
1604 {
1605         struct hrtimer_clock_base *base;
1606         unsigned int seq;
1607
1608         do {
1609                 base = READ_ONCE(timer->base);
1610                 seq = raw_read_seqcount_begin(&base->seq);
1611
1612                 if (timer->state != HRTIMER_STATE_INACTIVE ||
1613                     base->running == timer)
1614                         return true;
1615
1616         } while (read_seqcount_retry(&base->seq, seq) ||
1617                  base != READ_ONCE(timer->base));
1618
1619         return false;
1620 }
1621 EXPORT_SYMBOL_GPL(hrtimer_active);
1622
1623 /*
1624  * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
1625  * distinct sections:
1626  *
1627  *  - queued:   the timer is queued
1628  *  - callback: the timer is being ran
1629  *  - post:     the timer is inactive or (re)queued
1630  *
1631  * On the read side we ensure we observe timer->state and cpu_base->running
1632  * from the same section, if anything changed while we looked at it, we retry.
1633  * This includes timer->base changing because sequence numbers alone are
1634  * insufficient for that.
1635  *
1636  * The sequence numbers are required because otherwise we could still observe
1637  * a false negative if the read side got smeared over multiple consecutive
1638  * __run_hrtimer() invocations.
1639  */
1640
1641 static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base,
1642                           struct hrtimer_clock_base *base,
1643                           struct hrtimer *timer, ktime_t *now,
1644                           unsigned long flags) __must_hold(&cpu_base->lock)
1645 {
1646         enum hrtimer_restart (*fn)(struct hrtimer *);
1647         bool expires_in_hardirq;
1648         int restart;
1649
1650         lockdep_assert_held(&cpu_base->lock);
1651
1652         debug_deactivate(timer);
1653         base->running = timer;
1654
1655         /*
1656          * Separate the ->running assignment from the ->state assignment.
1657          *
1658          * As with a regular write barrier, this ensures the read side in
1659          * hrtimer_active() cannot observe base->running == NULL &&
1660          * timer->state == INACTIVE.
1661          */
1662         raw_write_seqcount_barrier(&base->seq);
1663
1664         __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, 0);
1665         fn = timer->function;
1666
1667         /*
1668          * Clear the 'is relative' flag for the TIME_LOW_RES case. If the
1669          * timer is restarted with a period then it becomes an absolute
1670          * timer. If its not restarted it does not matter.
1671          */
1672         if (IS_ENABLED(CONFIG_TIME_LOW_RES))
1673                 timer->is_rel = false;
1674
1675         /*
1676          * The timer is marked as running in the CPU base, so it is
1677          * protected against migration to a different CPU even if the lock
1678          * is dropped.
1679          */
1680         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1681         trace_hrtimer_expire_entry(timer, now);
1682         expires_in_hardirq = lockdep_hrtimer_enter(timer);
1683
1684         restart = fn(timer);
1685
1686         lockdep_hrtimer_exit(expires_in_hardirq);
1687         trace_hrtimer_expire_exit(timer);
1688         raw_spin_lock_irq(&cpu_base->lock);
1689
1690         /*
1691          * Note: We clear the running state after enqueue_hrtimer and
1692          * we do not reprogram the event hardware. Happens either in
1693          * hrtimer_start_range_ns() or in hrtimer_interrupt()
1694          *
1695          * Note: Because we dropped the cpu_base->lock above,
1696          * hrtimer_start_range_ns() can have popped in and enqueued the timer
1697          * for us already.
1698          */
1699         if (restart != HRTIMER_NORESTART &&
1700             !(timer->state & HRTIMER_STATE_ENQUEUED))
1701                 enqueue_hrtimer(timer, base, HRTIMER_MODE_ABS);
1702
1703         /*
1704          * Separate the ->running assignment from the ->state assignment.
1705          *
1706          * As with a regular write barrier, this ensures the read side in
1707          * hrtimer_active() cannot observe base->running.timer == NULL &&
1708          * timer->state == INACTIVE.
1709          */
1710         raw_write_seqcount_barrier(&base->seq);
1711
1712         WARN_ON_ONCE(base->running != timer);
1713         base->running = NULL;
1714 }
1715
1716 static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now,
1717                                  unsigned long flags, unsigned int active_mask)
1718 {
1719         struct hrtimer_clock_base *base;
1720         unsigned int active = cpu_base->active_bases & active_mask;
1721
1722         for_each_active_base(base, cpu_base, active) {
1723                 struct timerqueue_node *node;
1724                 ktime_t basenow;
1725
1726                 basenow = ktime_add(now, base->offset);
1727
1728                 while ((node = timerqueue_getnext(&base->active))) {
1729                         struct hrtimer *timer;
1730
1731                         timer = container_of(node, struct hrtimer, node);
1732
1733                         /*
1734                          * The immediate goal for using the softexpires is
1735                          * minimizing wakeups, not running timers at the
1736                          * earliest interrupt after their soft expiration.
1737                          * This allows us to avoid using a Priority Search
1738                          * Tree, which can answer a stabbing query for
1739                          * overlapping intervals and instead use the simple
1740                          * BST we already have.
1741                          * We don't add extra wakeups by delaying timers that
1742                          * are right-of a not yet expired timer, because that
1743                          * timer will have to trigger a wakeup anyway.
1744                          */
1745                         if (basenow < hrtimer_get_softexpires_tv64(timer))
1746                                 break;
1747
1748                         __run_hrtimer(cpu_base, base, timer, &basenow, flags);
1749                         if (active_mask == HRTIMER_ACTIVE_SOFT)
1750                                 hrtimer_sync_wait_running(cpu_base, flags);
1751                 }
1752         }
1753 }
1754
1755 static __latent_entropy void hrtimer_run_softirq(struct softirq_action *h)
1756 {
1757         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1758         unsigned long flags;
1759         ktime_t now;
1760
1761         hrtimer_cpu_base_lock_expiry(cpu_base);
1762         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1763
1764         now = hrtimer_update_base(cpu_base);
1765         __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_SOFT);
1766
1767         cpu_base->softirq_activated = 0;
1768         hrtimer_update_softirq_timer(cpu_base, true);
1769
1770         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1771         hrtimer_cpu_base_unlock_expiry(cpu_base);
1772 }
1773
1774 #ifdef CONFIG_HIGH_RES_TIMERS
1775
1776 /*
1777  * High resolution timer interrupt
1778  * Called with interrupts disabled
1779  */
1780 void hrtimer_interrupt(struct clock_event_device *dev)
1781 {
1782         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1783         ktime_t expires_next, now, entry_time, delta;
1784         unsigned long flags;
1785         int retries = 0;
1786
1787         BUG_ON(!cpu_base->hres_active);
1788         cpu_base->nr_events++;
1789         dev->next_event = KTIME_MAX;
1790
1791         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1792         entry_time = now = hrtimer_update_base(cpu_base);
1793 retry:
1794         cpu_base->in_hrtirq = 1;
1795         /*
1796          * We set expires_next to KTIME_MAX here with cpu_base->lock
1797          * held to prevent that a timer is enqueued in our queue via
1798          * the migration code. This does not affect enqueueing of
1799          * timers which run their callback and need to be requeued on
1800          * this CPU.
1801          */
1802         cpu_base->expires_next = KTIME_MAX;
1803
1804         if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1805                 cpu_base->softirq_expires_next = KTIME_MAX;
1806                 cpu_base->softirq_activated = 1;
1807                 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1808         }
1809
1810         __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1811
1812         /* Reevaluate the clock bases for the [soft] next expiry */
1813         expires_next = hrtimer_update_next_event(cpu_base);
1814         /*
1815          * Store the new expiry value so the migration code can verify
1816          * against it.
1817          */
1818         cpu_base->expires_next = expires_next;
1819         cpu_base->in_hrtirq = 0;
1820         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1821
1822         /* Reprogramming necessary ? */
1823         if (!tick_program_event(expires_next, 0)) {
1824                 cpu_base->hang_detected = 0;
1825                 return;
1826         }
1827
1828         /*
1829          * The next timer was already expired due to:
1830          * - tracing
1831          * - long lasting callbacks
1832          * - being scheduled away when running in a VM
1833          *
1834          * We need to prevent that we loop forever in the hrtimer
1835          * interrupt routine. We give it 3 attempts to avoid
1836          * overreacting on some spurious event.
1837          *
1838          * Acquire base lock for updating the offsets and retrieving
1839          * the current time.
1840          */
1841         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1842         now = hrtimer_update_base(cpu_base);
1843         cpu_base->nr_retries++;
1844         if (++retries < 3)
1845                 goto retry;
1846         /*
1847          * Give the system a chance to do something else than looping
1848          * here. We stored the entry time, so we know exactly how long
1849          * we spent here. We schedule the next event this amount of
1850          * time away.
1851          */
1852         cpu_base->nr_hangs++;
1853         cpu_base->hang_detected = 1;
1854         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1855
1856         delta = ktime_sub(now, entry_time);
1857         if ((unsigned int)delta > cpu_base->max_hang_time)
1858                 cpu_base->max_hang_time = (unsigned int) delta;
1859         /*
1860          * Limit it to a sensible value as we enforce a longer
1861          * delay. Give the CPU at least 100ms to catch up.
1862          */
1863         if (delta > 100 * NSEC_PER_MSEC)
1864                 expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1865         else
1866                 expires_next = ktime_add(now, delta);
1867         tick_program_event(expires_next, 1);
1868         pr_warn_once("hrtimer: interrupt took %llu ns\n", ktime_to_ns(delta));
1869 }
1870
1871 /* called with interrupts disabled */
1872 static inline void __hrtimer_peek_ahead_timers(void)
1873 {
1874         struct tick_device *td;
1875
1876         if (!hrtimer_hres_active())
1877                 return;
1878
1879         td = this_cpu_ptr(&tick_cpu_device);
1880         if (td && td->evtdev)
1881                 hrtimer_interrupt(td->evtdev);
1882 }
1883
1884 #else /* CONFIG_HIGH_RES_TIMERS */
1885
1886 static inline void __hrtimer_peek_ahead_timers(void) { }
1887
1888 #endif  /* !CONFIG_HIGH_RES_TIMERS */
1889
1890 /*
1891  * Called from run_local_timers in hardirq context every jiffy
1892  */
1893 void hrtimer_run_queues(void)
1894 {
1895         struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1896         unsigned long flags;
1897         ktime_t now;
1898
1899         if (__hrtimer_hres_active(cpu_base))
1900                 return;
1901
1902         /*
1903          * This _is_ ugly: We have to check periodically, whether we
1904          * can switch to highres and / or nohz mode. The clocksource
1905          * switch happens with xtime_lock held. Notification from
1906          * there only sets the check bit in the tick_oneshot code,
1907          * otherwise we might deadlock vs. xtime_lock.
1908          */
1909         if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
1910                 hrtimer_switch_to_hres();
1911                 return;
1912         }
1913
1914         raw_spin_lock_irqsave(&cpu_base->lock, flags);
1915         now = hrtimer_update_base(cpu_base);
1916
1917         if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1918                 cpu_base->softirq_expires_next = KTIME_MAX;
1919                 cpu_base->softirq_activated = 1;
1920                 raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1921         }
1922
1923         __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1924         raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1925 }
1926
1927 /*
1928  * Sleep related functions:
1929  */
1930 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1931 {
1932         struct hrtimer_sleeper *t =
1933                 container_of(timer, struct hrtimer_sleeper, timer);
1934         struct task_struct *task = t->task;
1935
1936         t->task = NULL;
1937         if (task)
1938                 wake_up_process(task);
1939
1940         return HRTIMER_NORESTART;
1941 }
1942
1943 /**
1944  * hrtimer_sleeper_start_expires - Start a hrtimer sleeper timer
1945  * @sl:         sleeper to be started
1946  * @mode:       timer mode abs/rel
1947  *
1948  * Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers
1949  * to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)
1950  */
1951 void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl,
1952                                    enum hrtimer_mode mode)
1953 {
1954         /*
1955          * Make the enqueue delivery mode check work on RT. If the sleeper
1956          * was initialized for hard interrupt delivery, force the mode bit.
1957          * This is a special case for hrtimer_sleepers because
1958          * hrtimer_init_sleeper() determines the delivery mode on RT so the
1959          * fiddling with this decision is avoided at the call sites.
1960          */
1961         if (IS_ENABLED(CONFIG_PREEMPT_RT) && sl->timer.is_hard)
1962                 mode |= HRTIMER_MODE_HARD;
1963
1964         hrtimer_start_expires(&sl->timer, mode);
1965 }
1966 EXPORT_SYMBOL_GPL(hrtimer_sleeper_start_expires);
1967
1968 static void __hrtimer_init_sleeper(struct hrtimer_sleeper *sl,
1969                                    clockid_t clock_id, enum hrtimer_mode mode)
1970 {
1971         /*
1972          * On PREEMPT_RT enabled kernels hrtimers which are not explicitly
1973          * marked for hard interrupt expiry mode are moved into soft
1974          * interrupt context either for latency reasons or because the
1975          * hrtimer callback takes regular spinlocks or invokes other
1976          * functions which are not suitable for hard interrupt context on
1977          * PREEMPT_RT.
1978          *
1979          * The hrtimer_sleeper callback is RT compatible in hard interrupt
1980          * context, but there is a latency concern: Untrusted userspace can
1981          * spawn many threads which arm timers for the same expiry time on
1982          * the same CPU. That causes a latency spike due to the wakeup of
1983          * a gazillion threads.
1984          *
1985          * OTOH, privileged real-time user space applications rely on the
1986          * low latency of hard interrupt wakeups. If the current task is in
1987          * a real-time scheduling class, mark the mode for hard interrupt
1988          * expiry.
1989          */
1990         if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
1991                 if (task_is_realtime(current) && !(mode & HRTIMER_MODE_SOFT))
1992                         mode |= HRTIMER_MODE_HARD;
1993         }
1994
1995         __hrtimer_init(&sl->timer, clock_id, mode);
1996         sl->timer.function = hrtimer_wakeup;
1997         sl->task = current;
1998 }
1999
2000 /**
2001  * hrtimer_init_sleeper - initialize sleeper to the given clock
2002  * @sl:         sleeper to be initialized
2003  * @clock_id:   the clock to be used
2004  * @mode:       timer mode abs/rel
2005  */
2006 void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, clockid_t clock_id,
2007                           enum hrtimer_mode mode)
2008 {
2009         debug_init(&sl->timer, clock_id, mode);
2010         __hrtimer_init_sleeper(sl, clock_id, mode);
2011
2012 }
2013 EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
2014
2015 int nanosleep_copyout(struct restart_block *restart, struct timespec64 *ts)
2016 {
2017         switch(restart->nanosleep.type) {
2018 #ifdef CONFIG_COMPAT_32BIT_TIME
2019         case TT_COMPAT:
2020                 if (put_old_timespec32(ts, restart->nanosleep.compat_rmtp))
2021                         return -EFAULT;
2022                 break;
2023 #endif
2024         case TT_NATIVE:
2025                 if (put_timespec64(ts, restart->nanosleep.rmtp))
2026                         return -EFAULT;
2027                 break;
2028         default:
2029                 BUG();
2030         }
2031         return -ERESTART_RESTARTBLOCK;
2032 }
2033
2034 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
2035 {
2036         struct restart_block *restart;
2037
2038         do {
2039                 set_current_state(TASK_INTERRUPTIBLE);
2040                 hrtimer_sleeper_start_expires(t, mode);
2041
2042                 if (likely(t->task))
2043                         freezable_schedule();
2044
2045                 hrtimer_cancel(&t->timer);
2046                 mode = HRTIMER_MODE_ABS;
2047
2048         } while (t->task && !signal_pending(current));
2049
2050         __set_current_state(TASK_RUNNING);
2051
2052         if (!t->task)
2053                 return 0;
2054
2055         restart = &current->restart_block;
2056         if (restart->nanosleep.type != TT_NONE) {
2057                 ktime_t rem = hrtimer_expires_remaining(&t->timer);
2058                 struct timespec64 rmt;
2059
2060                 if (rem <= 0)
2061                         return 0;
2062                 rmt = ktime_to_timespec64(rem);
2063
2064                 return nanosleep_copyout(restart, &rmt);
2065         }
2066         return -ERESTART_RESTARTBLOCK;
2067 }
2068
2069 static long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
2070 {
2071         struct hrtimer_sleeper t;
2072         int ret;
2073
2074         hrtimer_init_sleeper_on_stack(&t, restart->nanosleep.clockid,
2075                                       HRTIMER_MODE_ABS);
2076         hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
2077         ret = do_nanosleep(&t, HRTIMER_MODE_ABS);
2078         destroy_hrtimer_on_stack(&t.timer);
2079         return ret;
2080 }
2081
2082 long hrtimer_nanosleep(ktime_t rqtp, const enum hrtimer_mode mode,
2083                        const clockid_t clockid)
2084 {
2085         struct restart_block *restart;
2086         struct hrtimer_sleeper t;
2087         int ret = 0;
2088         u64 slack;
2089
2090         slack = current->timer_slack_ns;
2091         if (dl_task(current) || rt_task(current))
2092                 slack = 0;
2093
2094         hrtimer_init_sleeper_on_stack(&t, clockid, mode);
2095         hrtimer_set_expires_range_ns(&t.timer, rqtp, slack);
2096         ret = do_nanosleep(&t, mode);
2097         if (ret != -ERESTART_RESTARTBLOCK)
2098                 goto out;
2099
2100         /* Absolute timers do not update the rmtp value and restart: */
2101         if (mode == HRTIMER_MODE_ABS) {
2102                 ret = -ERESTARTNOHAND;
2103                 goto out;
2104         }
2105
2106         restart = &current->restart_block;
2107         restart->nanosleep.clockid = t.timer.base->clockid;
2108         restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
2109         set_restart_fn(restart, hrtimer_nanosleep_restart);
2110 out:
2111         destroy_hrtimer_on_stack(&t.timer);
2112         return ret;
2113 }
2114
2115 #ifdef CONFIG_64BIT
2116
2117 SYSCALL_DEFINE2(nanosleep, struct __kernel_timespec __user *, rqtp,
2118                 struct __kernel_timespec __user *, rmtp)
2119 {
2120         struct timespec64 tu;
2121
2122         if (get_timespec64(&tu, rqtp))
2123                 return -EFAULT;
2124
2125         if (!timespec64_valid(&tu))
2126                 return -EINVAL;
2127
2128         current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
2129         current->restart_block.nanosleep.rmtp = rmtp;
2130         return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
2131                                  CLOCK_MONOTONIC);
2132 }
2133
2134 #endif
2135
2136 #ifdef CONFIG_COMPAT_32BIT_TIME
2137
2138 SYSCALL_DEFINE2(nanosleep_time32, struct old_timespec32 __user *, rqtp,
2139                        struct old_timespec32 __user *, rmtp)
2140 {
2141         struct timespec64 tu;
2142
2143         if (get_old_timespec32(&tu, rqtp))
2144                 return -EFAULT;
2145
2146         if (!timespec64_valid(&tu))
2147                 return -EINVAL;
2148
2149         current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
2150         current->restart_block.nanosleep.compat_rmtp = rmtp;
2151         return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
2152                                  CLOCK_MONOTONIC);
2153 }
2154 #endif
2155
2156 /*
2157  * Functions related to boot-time initialization:
2158  */
2159 int hrtimers_prepare_cpu(unsigned int cpu)
2160 {
2161         struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
2162         int i;
2163
2164         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2165                 struct hrtimer_clock_base *clock_b = &cpu_base->clock_base[i];
2166
2167                 clock_b->cpu_base = cpu_base;
2168                 seqcount_raw_spinlock_init(&clock_b->seq, &cpu_base->lock);
2169                 timerqueue_init_head(&clock_b->active);
2170         }
2171
2172         cpu_base->cpu = cpu;
2173         cpu_base->active_bases = 0;
2174         cpu_base->hres_active = 0;
2175         cpu_base->hang_detected = 0;
2176         cpu_base->next_timer = NULL;
2177         cpu_base->softirq_next_timer = NULL;
2178         cpu_base->expires_next = KTIME_MAX;
2179         cpu_base->softirq_expires_next = KTIME_MAX;
2180         hrtimer_cpu_base_init_expiry_lock(cpu_base);
2181         return 0;
2182 }
2183
2184 #ifdef CONFIG_HOTPLUG_CPU
2185
2186 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
2187                                 struct hrtimer_clock_base *new_base)
2188 {
2189         struct hrtimer *timer;
2190         struct timerqueue_node *node;
2191
2192         while ((node = timerqueue_getnext(&old_base->active))) {
2193                 timer = container_of(node, struct hrtimer, node);
2194                 BUG_ON(hrtimer_callback_running(timer));
2195                 debug_deactivate(timer);
2196
2197                 /*
2198                  * Mark it as ENQUEUED not INACTIVE otherwise the
2199                  * timer could be seen as !active and just vanish away
2200                  * under us on another CPU
2201                  */
2202                 __remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, 0);
2203                 timer->base = new_base;
2204                 /*
2205                  * Enqueue the timers on the new cpu. This does not
2206                  * reprogram the event device in case the timer
2207                  * expires before the earliest on this CPU, but we run
2208                  * hrtimer_interrupt after we migrated everything to
2209                  * sort out already expired timers and reprogram the
2210                  * event device.
2211                  */
2212                 enqueue_hrtimer(timer, new_base, HRTIMER_MODE_ABS);
2213         }
2214 }
2215
2216 int hrtimers_dead_cpu(unsigned int scpu)
2217 {
2218         struct hrtimer_cpu_base *old_base, *new_base;
2219         int i;
2220
2221         BUG_ON(cpu_online(scpu));
2222         tick_cancel_sched_timer(scpu);
2223
2224         /*
2225          * this BH disable ensures that raise_softirq_irqoff() does
2226          * not wakeup ksoftirqd (and acquire the pi-lock) while
2227          * holding the cpu_base lock
2228          */
2229         local_bh_disable();
2230         local_irq_disable();
2231         old_base = &per_cpu(hrtimer_bases, scpu);
2232         new_base = this_cpu_ptr(&hrtimer_bases);
2233         /*
2234          * The caller is globally serialized and nobody else
2235          * takes two locks at once, deadlock is not possible.
2236          */
2237         raw_spin_lock(&new_base->lock);
2238         raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
2239
2240         for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2241                 migrate_hrtimer_list(&old_base->clock_base[i],
2242                                      &new_base->clock_base[i]);
2243         }
2244
2245         /*
2246          * The migration might have changed the first expiring softirq
2247          * timer on this CPU. Update it.
2248          */
2249         hrtimer_update_softirq_timer(new_base, false);
2250
2251         raw_spin_unlock(&old_base->lock);
2252         raw_spin_unlock(&new_base->lock);
2253
2254         /* Check, if we got expired work to do */
2255         __hrtimer_peek_ahead_timers();
2256         local_irq_enable();
2257         local_bh_enable();
2258         return 0;
2259 }
2260
2261 #endif /* CONFIG_HOTPLUG_CPU */
2262
2263 void __init hrtimers_init(void)
2264 {
2265         hrtimers_prepare_cpu(smp_processor_id());
2266         open_softirq(HRTIMER_SOFTIRQ, hrtimer_run_softirq);
2267 }
2268
2269 /**
2270  * schedule_hrtimeout_range_clock - sleep until timeout
2271  * @expires:    timeout value (ktime_t)
2272  * @delta:      slack in expires timeout (ktime_t)
2273  * @mode:       timer mode
2274  * @clock_id:   timer clock to be used
2275  */
2276 int __sched
2277 schedule_hrtimeout_range_clock(ktime_t *expires, u64 delta,
2278                                const enum hrtimer_mode mode, clockid_t clock_id)
2279 {
2280         struct hrtimer_sleeper t;
2281
2282         /*
2283          * Optimize when a zero timeout value is given. It does not
2284          * matter whether this is an absolute or a relative time.
2285          */
2286         if (expires && *expires == 0) {
2287                 __set_current_state(TASK_RUNNING);
2288                 return 0;
2289         }
2290
2291         /*
2292          * A NULL parameter means "infinite"
2293          */
2294         if (!expires) {
2295                 schedule();
2296                 return -EINTR;
2297         }
2298
2299         hrtimer_init_sleeper_on_stack(&t, clock_id, mode);
2300         hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
2301         hrtimer_sleeper_start_expires(&t, mode);
2302
2303         if (likely(t.task))
2304                 schedule();
2305
2306         hrtimer_cancel(&t.timer);
2307         destroy_hrtimer_on_stack(&t.timer);
2308
2309         __set_current_state(TASK_RUNNING);
2310
2311         return !t.task ? 0 : -EINTR;
2312 }
2313
2314 /**
2315  * schedule_hrtimeout_range - sleep until timeout
2316  * @expires:    timeout value (ktime_t)
2317  * @delta:      slack in expires timeout (ktime_t)
2318  * @mode:       timer mode
2319  *
2320  * Make the current task sleep until the given expiry time has
2321  * elapsed. The routine will return immediately unless
2322  * the current task state has been set (see set_current_state()).
2323  *
2324  * The @delta argument gives the kernel the freedom to schedule the
2325  * actual wakeup to a time that is both power and performance friendly.
2326  * The kernel give the normal best effort behavior for "@expires+@delta",
2327  * but may decide to fire the timer earlier, but no earlier than @expires.
2328  *
2329  * You can set the task state as follows -
2330  *
2331  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2332  * pass before the routine returns unless the current task is explicitly
2333  * woken up, (e.g. by wake_up_process()).
2334  *
2335  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2336  * delivered to the current task or the current task is explicitly woken
2337  * up.
2338  *
2339  * The current task state is guaranteed to be TASK_RUNNING when this
2340  * routine returns.
2341  *
2342  * Returns 0 when the timer has expired. If the task was woken before the
2343  * timer expired by a signal (only possible in state TASK_INTERRUPTIBLE) or
2344  * by an explicit wakeup, it returns -EINTR.
2345  */
2346 int __sched schedule_hrtimeout_range(ktime_t *expires, u64 delta,
2347                                      const enum hrtimer_mode mode)
2348 {
2349         return schedule_hrtimeout_range_clock(expires, delta, mode,
2350                                               CLOCK_MONOTONIC);
2351 }
2352 EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
2353
2354 /**
2355  * schedule_hrtimeout - sleep until timeout
2356  * @expires:    timeout value (ktime_t)
2357  * @mode:       timer mode
2358  *
2359  * Make the current task sleep until the given expiry time has
2360  * elapsed. The routine will return immediately unless
2361  * the current task state has been set (see set_current_state()).
2362  *
2363  * You can set the task state as follows -
2364  *
2365  * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2366  * pass before the routine returns unless the current task is explicitly
2367  * woken up, (e.g. by wake_up_process()).
2368  *
2369  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2370  * delivered to the current task or the current task is explicitly woken
2371  * up.
2372  *
2373  * The current task state is guaranteed to be TASK_RUNNING when this
2374  * routine returns.
2375  *
2376  * Returns 0 when the timer has expired. If the task was woken before the
2377  * timer expired by a signal (only possible in state TASK_INTERRUPTIBLE) or
2378  * by an explicit wakeup, it returns -EINTR.
2379  */
2380 int __sched schedule_hrtimeout(ktime_t *expires,
2381                                const enum hrtimer_mode mode)
2382 {
2383         return schedule_hrtimeout_range(expires, 0, mode);
2384 }
2385 EXPORT_SYMBOL_GPL(schedule_hrtimeout);