Linux 6.9-rc1
[linux-2.6-microblaze.git] / kernel / time / tick-sched.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  *  NOHZ implementation for low and high resolution timers
8  *
9  *  Started by: Thomas Gleixner and Ingo Molnar
10  */
11 #include <linux/cpu.h>
12 #include <linux/err.h>
13 #include <linux/hrtimer.h>
14 #include <linux/interrupt.h>
15 #include <linux/kernel_stat.h>
16 #include <linux/percpu.h>
17 #include <linux/nmi.h>
18 #include <linux/profile.h>
19 #include <linux/sched/signal.h>
20 #include <linux/sched/clock.h>
21 #include <linux/sched/stat.h>
22 #include <linux/sched/nohz.h>
23 #include <linux/sched/loadavg.h>
24 #include <linux/module.h>
25 #include <linux/irq_work.h>
26 #include <linux/posix-timers.h>
27 #include <linux/context_tracking.h>
28 #include <linux/mm.h>
29
30 #include <asm/irq_regs.h>
31
32 #include "tick-internal.h"
33
34 #include <trace/events/timer.h>
35
36 /*
37  * Per-CPU nohz control structure
38  */
39 static DEFINE_PER_CPU(struct tick_sched, tick_cpu_sched);
40
41 struct tick_sched *tick_get_tick_sched(int cpu)
42 {
43         return &per_cpu(tick_cpu_sched, cpu);
44 }
45
46 /*
47  * The time when the last jiffy update happened. Write access must hold
48  * jiffies_lock and jiffies_seq. tick_nohz_next_event() needs to get a
49  * consistent view of jiffies and last_jiffies_update.
50  */
51 static ktime_t last_jiffies_update;
52
53 /*
54  * Must be called with interrupts disabled !
55  */
56 static void tick_do_update_jiffies64(ktime_t now)
57 {
58         unsigned long ticks = 1;
59         ktime_t delta, nextp;
60
61         /*
62          * 64-bit can do a quick check without holding the jiffies lock and
63          * without looking at the sequence count. The smp_load_acquire()
64          * pairs with the update done later in this function.
65          *
66          * 32-bit cannot do that because the store of 'tick_next_period'
67          * consists of two 32-bit stores, and the first store could be
68          * moved by the CPU to a random point in the future.
69          */
70         if (IS_ENABLED(CONFIG_64BIT)) {
71                 if (ktime_before(now, smp_load_acquire(&tick_next_period)))
72                         return;
73         } else {
74                 unsigned int seq;
75
76                 /*
77                  * Avoid contention on 'jiffies_lock' and protect the quick
78                  * check with the sequence count.
79                  */
80                 do {
81                         seq = read_seqcount_begin(&jiffies_seq);
82                         nextp = tick_next_period;
83                 } while (read_seqcount_retry(&jiffies_seq, seq));
84
85                 if (ktime_before(now, nextp))
86                         return;
87         }
88
89         /* Quick check failed, i.e. update is required. */
90         raw_spin_lock(&jiffies_lock);
91         /*
92          * Re-evaluate with the lock held. Another CPU might have done the
93          * update already.
94          */
95         if (ktime_before(now, tick_next_period)) {
96                 raw_spin_unlock(&jiffies_lock);
97                 return;
98         }
99
100         write_seqcount_begin(&jiffies_seq);
101
102         delta = ktime_sub(now, tick_next_period);
103         if (unlikely(delta >= TICK_NSEC)) {
104                 /* Slow path for long idle sleep times */
105                 s64 incr = TICK_NSEC;
106
107                 ticks += ktime_divns(delta, incr);
108
109                 last_jiffies_update = ktime_add_ns(last_jiffies_update,
110                                                    incr * ticks);
111         } else {
112                 last_jiffies_update = ktime_add_ns(last_jiffies_update,
113                                                    TICK_NSEC);
114         }
115
116         /* Advance jiffies to complete the 'jiffies_seq' protected job */
117         jiffies_64 += ticks;
118
119         /* Keep the tick_next_period variable up to date */
120         nextp = ktime_add_ns(last_jiffies_update, TICK_NSEC);
121
122         if (IS_ENABLED(CONFIG_64BIT)) {
123                 /*
124                  * Pairs with smp_load_acquire() in the lockless quick
125                  * check above, and ensures that the update to 'jiffies_64' is
126                  * not reordered vs. the store to 'tick_next_period', neither
127                  * by the compiler nor by the CPU.
128                  */
129                 smp_store_release(&tick_next_period, nextp);
130         } else {
131                 /*
132                  * A plain store is good enough on 32-bit, as the quick check
133                  * above is protected by the sequence count.
134                  */
135                 tick_next_period = nextp;
136         }
137
138         /*
139          * Release the sequence count. calc_global_load() below is not
140          * protected by it, but 'jiffies_lock' needs to be held to prevent
141          * concurrent invocations.
142          */
143         write_seqcount_end(&jiffies_seq);
144
145         calc_global_load();
146
147         raw_spin_unlock(&jiffies_lock);
148         update_wall_time();
149 }
150
151 /*
152  * Initialize and return retrieve the jiffies update.
153  */
154 static ktime_t tick_init_jiffy_update(void)
155 {
156         ktime_t period;
157
158         raw_spin_lock(&jiffies_lock);
159         write_seqcount_begin(&jiffies_seq);
160
161         /* Have we started the jiffies update yet ? */
162         if (last_jiffies_update == 0) {
163                 u32 rem;
164
165                 /*
166                  * Ensure that the tick is aligned to a multiple of
167                  * TICK_NSEC.
168                  */
169                 div_u64_rem(tick_next_period, TICK_NSEC, &rem);
170                 if (rem)
171                         tick_next_period += TICK_NSEC - rem;
172
173                 last_jiffies_update = tick_next_period;
174         }
175         period = last_jiffies_update;
176
177         write_seqcount_end(&jiffies_seq);
178         raw_spin_unlock(&jiffies_lock);
179
180         return period;
181 }
182
183 static inline int tick_sched_flag_test(struct tick_sched *ts,
184                                        unsigned long flag)
185 {
186         return !!(ts->flags & flag);
187 }
188
189 static inline void tick_sched_flag_set(struct tick_sched *ts,
190                                        unsigned long flag)
191 {
192         lockdep_assert_irqs_disabled();
193         ts->flags |= flag;
194 }
195
196 static inline void tick_sched_flag_clear(struct tick_sched *ts,
197                                          unsigned long flag)
198 {
199         lockdep_assert_irqs_disabled();
200         ts->flags &= ~flag;
201 }
202
203 #define MAX_STALLED_JIFFIES 5
204
205 static void tick_sched_do_timer(struct tick_sched *ts, ktime_t now)
206 {
207         int cpu = smp_processor_id();
208
209         /*
210          * Check if the do_timer duty was dropped. We don't care about
211          * concurrency: This happens only when the CPU in charge went
212          * into a long sleep. If two CPUs happen to assign themselves to
213          * this duty, then the jiffies update is still serialized by
214          * 'jiffies_lock'.
215          *
216          * If nohz_full is enabled, this should not happen because the
217          * 'tick_do_timer_cpu' CPU never relinquishes.
218          */
219         if (IS_ENABLED(CONFIG_NO_HZ_COMMON) &&
220             unlikely(tick_do_timer_cpu == TICK_DO_TIMER_NONE)) {
221 #ifdef CONFIG_NO_HZ_FULL
222                 WARN_ON_ONCE(tick_nohz_full_running);
223 #endif
224                 tick_do_timer_cpu = cpu;
225         }
226
227         /* Check if jiffies need an update */
228         if (tick_do_timer_cpu == cpu)
229                 tick_do_update_jiffies64(now);
230
231         /*
232          * If the jiffies update stalled for too long (timekeeper in stop_machine()
233          * or VMEXIT'ed for several msecs), force an update.
234          */
235         if (ts->last_tick_jiffies != jiffies) {
236                 ts->stalled_jiffies = 0;
237                 ts->last_tick_jiffies = READ_ONCE(jiffies);
238         } else {
239                 if (++ts->stalled_jiffies == MAX_STALLED_JIFFIES) {
240                         tick_do_update_jiffies64(now);
241                         ts->stalled_jiffies = 0;
242                         ts->last_tick_jiffies = READ_ONCE(jiffies);
243                 }
244         }
245
246         if (tick_sched_flag_test(ts, TS_FLAG_INIDLE))
247                 ts->got_idle_tick = 1;
248 }
249
250 static void tick_sched_handle(struct tick_sched *ts, struct pt_regs *regs)
251 {
252         /*
253          * When we are idle and the tick is stopped, we have to touch
254          * the watchdog as we might not schedule for a really long
255          * time. This happens on completely idle SMP systems while
256          * waiting on the login prompt. We also increment the "start of
257          * idle" jiffy stamp so the idle accounting adjustment we do
258          * when we go busy again does not account too many ticks.
259          */
260         if (IS_ENABLED(CONFIG_NO_HZ_COMMON) &&
261             tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
262                 touch_softlockup_watchdog_sched();
263                 if (is_idle_task(current))
264                         ts->idle_jiffies++;
265                 /*
266                  * In case the current tick fired too early past its expected
267                  * expiration, make sure we don't bypass the next clock reprogramming
268                  * to the same deadline.
269                  */
270                 ts->next_tick = 0;
271         }
272
273         update_process_times(user_mode(regs));
274         profile_tick(CPU_PROFILING);
275 }
276
277 /*
278  * We rearm the timer until we get disabled by the idle code.
279  * Called with interrupts disabled.
280  */
281 static enum hrtimer_restart tick_nohz_handler(struct hrtimer *timer)
282 {
283         struct tick_sched *ts = container_of(timer, struct tick_sched, sched_timer);
284         struct pt_regs *regs = get_irq_regs();
285         ktime_t now = ktime_get();
286
287         tick_sched_do_timer(ts, now);
288
289         /*
290          * Do not call when we are not in IRQ context and have
291          * no valid 'regs' pointer
292          */
293         if (regs)
294                 tick_sched_handle(ts, regs);
295         else
296                 ts->next_tick = 0;
297
298         /*
299          * In dynticks mode, tick reprogram is deferred:
300          * - to the idle task if in dynticks-idle
301          * - to IRQ exit if in full-dynticks.
302          */
303         if (unlikely(tick_sched_flag_test(ts, TS_FLAG_STOPPED)))
304                 return HRTIMER_NORESTART;
305
306         hrtimer_forward(timer, now, TICK_NSEC);
307
308         return HRTIMER_RESTART;
309 }
310
311 static void tick_sched_timer_cancel(struct tick_sched *ts)
312 {
313         if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES))
314                 hrtimer_cancel(&ts->sched_timer);
315         else if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
316                 tick_program_event(KTIME_MAX, 1);
317 }
318
319 #ifdef CONFIG_NO_HZ_FULL
320 cpumask_var_t tick_nohz_full_mask;
321 EXPORT_SYMBOL_GPL(tick_nohz_full_mask);
322 bool tick_nohz_full_running;
323 EXPORT_SYMBOL_GPL(tick_nohz_full_running);
324 static atomic_t tick_dep_mask;
325
326 static bool check_tick_dependency(atomic_t *dep)
327 {
328         int val = atomic_read(dep);
329
330         if (val & TICK_DEP_MASK_POSIX_TIMER) {
331                 trace_tick_stop(0, TICK_DEP_MASK_POSIX_TIMER);
332                 return true;
333         }
334
335         if (val & TICK_DEP_MASK_PERF_EVENTS) {
336                 trace_tick_stop(0, TICK_DEP_MASK_PERF_EVENTS);
337                 return true;
338         }
339
340         if (val & TICK_DEP_MASK_SCHED) {
341                 trace_tick_stop(0, TICK_DEP_MASK_SCHED);
342                 return true;
343         }
344
345         if (val & TICK_DEP_MASK_CLOCK_UNSTABLE) {
346                 trace_tick_stop(0, TICK_DEP_MASK_CLOCK_UNSTABLE);
347                 return true;
348         }
349
350         if (val & TICK_DEP_MASK_RCU) {
351                 trace_tick_stop(0, TICK_DEP_MASK_RCU);
352                 return true;
353         }
354
355         if (val & TICK_DEP_MASK_RCU_EXP) {
356                 trace_tick_stop(0, TICK_DEP_MASK_RCU_EXP);
357                 return true;
358         }
359
360         return false;
361 }
362
363 static bool can_stop_full_tick(int cpu, struct tick_sched *ts)
364 {
365         lockdep_assert_irqs_disabled();
366
367         if (unlikely(!cpu_online(cpu)))
368                 return false;
369
370         if (check_tick_dependency(&tick_dep_mask))
371                 return false;
372
373         if (check_tick_dependency(&ts->tick_dep_mask))
374                 return false;
375
376         if (check_tick_dependency(&current->tick_dep_mask))
377                 return false;
378
379         if (check_tick_dependency(&current->signal->tick_dep_mask))
380                 return false;
381
382         return true;
383 }
384
385 static void nohz_full_kick_func(struct irq_work *work)
386 {
387         /* Empty, the tick restart happens on tick_nohz_irq_exit() */
388 }
389
390 static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) =
391         IRQ_WORK_INIT_HARD(nohz_full_kick_func);
392
393 /*
394  * Kick this CPU if it's full dynticks in order to force it to
395  * re-evaluate its dependency on the tick and restart it if necessary.
396  * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
397  * is NMI safe.
398  */
399 static void tick_nohz_full_kick(void)
400 {
401         if (!tick_nohz_full_cpu(smp_processor_id()))
402                 return;
403
404         irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
405 }
406
407 /*
408  * Kick the CPU if it's full dynticks in order to force it to
409  * re-evaluate its dependency on the tick and restart it if necessary.
410  */
411 void tick_nohz_full_kick_cpu(int cpu)
412 {
413         if (!tick_nohz_full_cpu(cpu))
414                 return;
415
416         irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
417 }
418
419 static void tick_nohz_kick_task(struct task_struct *tsk)
420 {
421         int cpu;
422
423         /*
424          * If the task is not running, run_posix_cpu_timers()
425          * has nothing to elapse, and an IPI can then be optimized out.
426          *
427          * activate_task()                      STORE p->tick_dep_mask
428          *   STORE p->on_rq
429          * __schedule() (switch to task 'p')    smp_mb() (atomic_fetch_or())
430          *   LOCK rq->lock                      LOAD p->on_rq
431          *   smp_mb__after_spin_lock()
432          *   tick_nohz_task_switch()
433          *     LOAD p->tick_dep_mask
434          */
435         if (!sched_task_on_rq(tsk))
436                 return;
437
438         /*
439          * If the task concurrently migrates to another CPU,
440          * we guarantee it sees the new tick dependency upon
441          * schedule.
442          *
443          * set_task_cpu(p, cpu);
444          *   STORE p->cpu = @cpu
445          * __schedule() (switch to task 'p')
446          *   LOCK rq->lock
447          *   smp_mb__after_spin_lock()          STORE p->tick_dep_mask
448          *   tick_nohz_task_switch()            smp_mb() (atomic_fetch_or())
449          *      LOAD p->tick_dep_mask           LOAD p->cpu
450          */
451         cpu = task_cpu(tsk);
452
453         preempt_disable();
454         if (cpu_online(cpu))
455                 tick_nohz_full_kick_cpu(cpu);
456         preempt_enable();
457 }
458
459 /*
460  * Kick all full dynticks CPUs in order to force these to re-evaluate
461  * their dependency on the tick and restart it if necessary.
462  */
463 static void tick_nohz_full_kick_all(void)
464 {
465         int cpu;
466
467         if (!tick_nohz_full_running)
468                 return;
469
470         preempt_disable();
471         for_each_cpu_and(cpu, tick_nohz_full_mask, cpu_online_mask)
472                 tick_nohz_full_kick_cpu(cpu);
473         preempt_enable();
474 }
475
476 static void tick_nohz_dep_set_all(atomic_t *dep,
477                                   enum tick_dep_bits bit)
478 {
479         int prev;
480
481         prev = atomic_fetch_or(BIT(bit), dep);
482         if (!prev)
483                 tick_nohz_full_kick_all();
484 }
485
486 /*
487  * Set a global tick dependency. Used by perf events that rely on freq and
488  * unstable clocks.
489  */
490 void tick_nohz_dep_set(enum tick_dep_bits bit)
491 {
492         tick_nohz_dep_set_all(&tick_dep_mask, bit);
493 }
494
495 void tick_nohz_dep_clear(enum tick_dep_bits bit)
496 {
497         atomic_andnot(BIT(bit), &tick_dep_mask);
498 }
499
500 /*
501  * Set per-CPU tick dependency. Used by scheduler and perf events in order to
502  * manage event-throttling.
503  */
504 void tick_nohz_dep_set_cpu(int cpu, enum tick_dep_bits bit)
505 {
506         int prev;
507         struct tick_sched *ts;
508
509         ts = per_cpu_ptr(&tick_cpu_sched, cpu);
510
511         prev = atomic_fetch_or(BIT(bit), &ts->tick_dep_mask);
512         if (!prev) {
513                 preempt_disable();
514                 /* Perf needs local kick that is NMI safe */
515                 if (cpu == smp_processor_id()) {
516                         tick_nohz_full_kick();
517                 } else {
518                         /* Remote IRQ work not NMI-safe */
519                         if (!WARN_ON_ONCE(in_nmi()))
520                                 tick_nohz_full_kick_cpu(cpu);
521                 }
522                 preempt_enable();
523         }
524 }
525 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_cpu);
526
527 void tick_nohz_dep_clear_cpu(int cpu, enum tick_dep_bits bit)
528 {
529         struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
530
531         atomic_andnot(BIT(bit), &ts->tick_dep_mask);
532 }
533 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_cpu);
534
535 /*
536  * Set a per-task tick dependency. RCU needs this. Also posix CPU timers
537  * in order to elapse per task timers.
538  */
539 void tick_nohz_dep_set_task(struct task_struct *tsk, enum tick_dep_bits bit)
540 {
541         if (!atomic_fetch_or(BIT(bit), &tsk->tick_dep_mask))
542                 tick_nohz_kick_task(tsk);
543 }
544 EXPORT_SYMBOL_GPL(tick_nohz_dep_set_task);
545
546 void tick_nohz_dep_clear_task(struct task_struct *tsk, enum tick_dep_bits bit)
547 {
548         atomic_andnot(BIT(bit), &tsk->tick_dep_mask);
549 }
550 EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_task);
551
552 /*
553  * Set a per-taskgroup tick dependency. Posix CPU timers need this in order to elapse
554  * per process timers.
555  */
556 void tick_nohz_dep_set_signal(struct task_struct *tsk,
557                               enum tick_dep_bits bit)
558 {
559         int prev;
560         struct signal_struct *sig = tsk->signal;
561
562         prev = atomic_fetch_or(BIT(bit), &sig->tick_dep_mask);
563         if (!prev) {
564                 struct task_struct *t;
565
566                 lockdep_assert_held(&tsk->sighand->siglock);
567                 __for_each_thread(sig, t)
568                         tick_nohz_kick_task(t);
569         }
570 }
571
572 void tick_nohz_dep_clear_signal(struct signal_struct *sig, enum tick_dep_bits bit)
573 {
574         atomic_andnot(BIT(bit), &sig->tick_dep_mask);
575 }
576
577 /*
578  * Re-evaluate the need for the tick as we switch the current task.
579  * It might need the tick due to per task/process properties:
580  * perf events, posix CPU timers, ...
581  */
582 void __tick_nohz_task_switch(void)
583 {
584         struct tick_sched *ts;
585
586         if (!tick_nohz_full_cpu(smp_processor_id()))
587                 return;
588
589         ts = this_cpu_ptr(&tick_cpu_sched);
590
591         if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
592                 if (atomic_read(&current->tick_dep_mask) ||
593                     atomic_read(&current->signal->tick_dep_mask))
594                         tick_nohz_full_kick();
595         }
596 }
597
598 /* Get the boot-time nohz CPU list from the kernel parameters. */
599 void __init tick_nohz_full_setup(cpumask_var_t cpumask)
600 {
601         alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
602         cpumask_copy(tick_nohz_full_mask, cpumask);
603         tick_nohz_full_running = true;
604 }
605
606 bool tick_nohz_cpu_hotpluggable(unsigned int cpu)
607 {
608         /*
609          * The 'tick_do_timer_cpu' CPU handles housekeeping duty (unbound
610          * timers, workqueues, timekeeping, ...) on behalf of full dynticks
611          * CPUs. It must remain online when nohz full is enabled.
612          */
613         if (tick_nohz_full_running && tick_do_timer_cpu == cpu)
614                 return false;
615         return true;
616 }
617
618 static int tick_nohz_cpu_down(unsigned int cpu)
619 {
620         return tick_nohz_cpu_hotpluggable(cpu) ? 0 : -EBUSY;
621 }
622
623 void __init tick_nohz_init(void)
624 {
625         int cpu, ret;
626
627         if (!tick_nohz_full_running)
628                 return;
629
630         /*
631          * Full dynticks uses IRQ work to drive the tick rescheduling on safe
632          * locking contexts. But then we need IRQ work to raise its own
633          * interrupts to avoid circular dependency on the tick.
634          */
635         if (!arch_irq_work_has_interrupt()) {
636                 pr_warn("NO_HZ: Can't run full dynticks because arch doesn't support IRQ work self-IPIs\n");
637                 cpumask_clear(tick_nohz_full_mask);
638                 tick_nohz_full_running = false;
639                 return;
640         }
641
642         if (IS_ENABLED(CONFIG_PM_SLEEP_SMP) &&
643                         !IS_ENABLED(CONFIG_PM_SLEEP_SMP_NONZERO_CPU)) {
644                 cpu = smp_processor_id();
645
646                 if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
647                         pr_warn("NO_HZ: Clearing %d from nohz_full range "
648                                 "for timekeeping\n", cpu);
649                         cpumask_clear_cpu(cpu, tick_nohz_full_mask);
650                 }
651         }
652
653         for_each_cpu(cpu, tick_nohz_full_mask)
654                 ct_cpu_track_user(cpu);
655
656         ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
657                                         "kernel/nohz:predown", NULL,
658                                         tick_nohz_cpu_down);
659         WARN_ON(ret < 0);
660         pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
661                 cpumask_pr_args(tick_nohz_full_mask));
662 }
663 #endif /* #ifdef CONFIG_NO_HZ_FULL */
664
665 /*
666  * NOHZ - aka dynamic tick functionality
667  */
668 #ifdef CONFIG_NO_HZ_COMMON
669 /*
670  * NO HZ enabled ?
671  */
672 bool tick_nohz_enabled __read_mostly  = true;
673 unsigned long tick_nohz_active  __read_mostly;
674 /*
675  * Enable / Disable tickless mode
676  */
677 static int __init setup_tick_nohz(char *str)
678 {
679         return (kstrtobool(str, &tick_nohz_enabled) == 0);
680 }
681
682 __setup("nohz=", setup_tick_nohz);
683
684 bool tick_nohz_tick_stopped(void)
685 {
686         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
687
688         return tick_sched_flag_test(ts, TS_FLAG_STOPPED);
689 }
690
691 bool tick_nohz_tick_stopped_cpu(int cpu)
692 {
693         struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
694
695         return tick_sched_flag_test(ts, TS_FLAG_STOPPED);
696 }
697
698 /**
699  * tick_nohz_update_jiffies - update jiffies when idle was interrupted
700  *
701  * Called from interrupt entry when the CPU was idle
702  *
703  * In case the sched_tick was stopped on this CPU, we have to check if jiffies
704  * must be updated. Otherwise an interrupt handler could use a stale jiffy
705  * value. We do this unconditionally on any CPU, as we don't know whether the
706  * CPU, which has the update task assigned, is in a long sleep.
707  */
708 static void tick_nohz_update_jiffies(ktime_t now)
709 {
710         unsigned long flags;
711
712         __this_cpu_write(tick_cpu_sched.idle_waketime, now);
713
714         local_irq_save(flags);
715         tick_do_update_jiffies64(now);
716         local_irq_restore(flags);
717
718         touch_softlockup_watchdog_sched();
719 }
720
721 static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
722 {
723         ktime_t delta;
724
725         if (WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE)))
726                 return;
727
728         delta = ktime_sub(now, ts->idle_entrytime);
729
730         write_seqcount_begin(&ts->idle_sleeptime_seq);
731         if (nr_iowait_cpu(smp_processor_id()) > 0)
732                 ts->iowait_sleeptime = ktime_add(ts->iowait_sleeptime, delta);
733         else
734                 ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
735
736         ts->idle_entrytime = now;
737         tick_sched_flag_clear(ts, TS_FLAG_IDLE_ACTIVE);
738         write_seqcount_end(&ts->idle_sleeptime_seq);
739
740         sched_clock_idle_wakeup_event();
741 }
742
743 static void tick_nohz_start_idle(struct tick_sched *ts)
744 {
745         write_seqcount_begin(&ts->idle_sleeptime_seq);
746         ts->idle_entrytime = ktime_get();
747         tick_sched_flag_set(ts, TS_FLAG_IDLE_ACTIVE);
748         write_seqcount_end(&ts->idle_sleeptime_seq);
749
750         sched_clock_idle_sleep_event();
751 }
752
753 static u64 get_cpu_sleep_time_us(struct tick_sched *ts, ktime_t *sleeptime,
754                                  bool compute_delta, u64 *last_update_time)
755 {
756         ktime_t now, idle;
757         unsigned int seq;
758
759         if (!tick_nohz_active)
760                 return -1;
761
762         now = ktime_get();
763         if (last_update_time)
764                 *last_update_time = ktime_to_us(now);
765
766         do {
767                 seq = read_seqcount_begin(&ts->idle_sleeptime_seq);
768
769                 if (tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE) && compute_delta) {
770                         ktime_t delta = ktime_sub(now, ts->idle_entrytime);
771
772                         idle = ktime_add(*sleeptime, delta);
773                 } else {
774                         idle = *sleeptime;
775                 }
776         } while (read_seqcount_retry(&ts->idle_sleeptime_seq, seq));
777
778         return ktime_to_us(idle);
779
780 }
781
782 /**
783  * get_cpu_idle_time_us - get the total idle time of a CPU
784  * @cpu: CPU number to query
785  * @last_update_time: variable to store update time in. Do not update
786  * counters if NULL.
787  *
788  * Return the cumulative idle time (since boot) for a given
789  * CPU, in microseconds. Note that this is partially broken due to
790  * the counter of iowait tasks that can be remotely updated without
791  * any synchronization. Therefore it is possible to observe backward
792  * values within two consecutive reads.
793  *
794  * This time is measured via accounting rather than sampling,
795  * and is as accurate as ktime_get() is.
796  *
797  * This function returns -1 if NOHZ is not enabled.
798  */
799 u64 get_cpu_idle_time_us(int cpu, u64 *last_update_time)
800 {
801         struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
802
803         return get_cpu_sleep_time_us(ts, &ts->idle_sleeptime,
804                                      !nr_iowait_cpu(cpu), last_update_time);
805 }
806 EXPORT_SYMBOL_GPL(get_cpu_idle_time_us);
807
808 /**
809  * get_cpu_iowait_time_us - get the total iowait time of a CPU
810  * @cpu: CPU number to query
811  * @last_update_time: variable to store update time in. Do not update
812  * counters if NULL.
813  *
814  * Return the cumulative iowait time (since boot) for a given
815  * CPU, in microseconds. Note this is partially broken due to
816  * the counter of iowait tasks that can be remotely updated without
817  * any synchronization. Therefore it is possible to observe backward
818  * values within two consecutive reads.
819  *
820  * This time is measured via accounting rather than sampling,
821  * and is as accurate as ktime_get() is.
822  *
823  * This function returns -1 if NOHZ is not enabled.
824  */
825 u64 get_cpu_iowait_time_us(int cpu, u64 *last_update_time)
826 {
827         struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
828
829         return get_cpu_sleep_time_us(ts, &ts->iowait_sleeptime,
830                                      nr_iowait_cpu(cpu), last_update_time);
831 }
832 EXPORT_SYMBOL_GPL(get_cpu_iowait_time_us);
833
834 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
835 {
836         hrtimer_cancel(&ts->sched_timer);
837         hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
838
839         /* Forward the time to expire in the future */
840         hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
841
842         if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
843                 hrtimer_start_expires(&ts->sched_timer,
844                                       HRTIMER_MODE_ABS_PINNED_HARD);
845         } else {
846                 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
847         }
848
849         /*
850          * Reset to make sure the next tick stop doesn't get fooled by past
851          * cached clock deadline.
852          */
853         ts->next_tick = 0;
854 }
855
856 static inline bool local_timer_softirq_pending(void)
857 {
858         return local_softirq_pending() & BIT(TIMER_SOFTIRQ);
859 }
860
861 /*
862  * Read jiffies and the time when jiffies were updated last
863  */
864 u64 get_jiffies_update(unsigned long *basej)
865 {
866         unsigned long basejiff;
867         unsigned int seq;
868         u64 basemono;
869
870         do {
871                 seq = read_seqcount_begin(&jiffies_seq);
872                 basemono = last_jiffies_update;
873                 basejiff = jiffies;
874         } while (read_seqcount_retry(&jiffies_seq, seq));
875         *basej = basejiff;
876         return basemono;
877 }
878
879 /**
880  * tick_nohz_next_event() - return the clock monotonic based next event
881  * @ts:         pointer to tick_sched struct
882  * @cpu:        CPU number
883  *
884  * Return:
885  * *%0          - When the next event is a maximum of TICK_NSEC in the future
886  *                and the tick is not stopped yet
887  * *%next_event - Next event based on clock monotonic
888  */
889 static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
890 {
891         u64 basemono, next_tick, delta, expires;
892         unsigned long basejiff;
893
894         basemono = get_jiffies_update(&basejiff);
895         ts->last_jiffies = basejiff;
896         ts->timer_expires_base = basemono;
897
898         /*
899          * Keep the periodic tick, when RCU, architecture or irq_work
900          * requests it.
901          * Aside of that, check whether the local timer softirq is
902          * pending. If so, its a bad idea to call get_next_timer_interrupt(),
903          * because there is an already expired timer, so it will request
904          * immediate expiry, which rearms the hardware timer with a
905          * minimal delta, which brings us back to this place
906          * immediately. Lather, rinse and repeat...
907          */
908         if (rcu_needs_cpu() || arch_needs_cpu() ||
909             irq_work_needs_cpu() || local_timer_softirq_pending()) {
910                 next_tick = basemono + TICK_NSEC;
911         } else {
912                 /*
913                  * Get the next pending timer. If high resolution
914                  * timers are enabled this only takes the timer wheel
915                  * timers into account. If high resolution timers are
916                  * disabled this also looks at the next expiring
917                  * hrtimer.
918                  */
919                 next_tick = get_next_timer_interrupt(basejiff, basemono);
920                 ts->next_timer = next_tick;
921         }
922
923         /* Make sure next_tick is never before basemono! */
924         if (WARN_ON_ONCE(basemono > next_tick))
925                 next_tick = basemono;
926
927         /*
928          * If the tick is due in the next period, keep it ticking or
929          * force prod the timer.
930          */
931         delta = next_tick - basemono;
932         if (delta <= (u64)TICK_NSEC) {
933                 /*
934                  * We've not stopped the tick yet, and there's a timer in the
935                  * next period, so no point in stopping it either, bail.
936                  */
937                 if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
938                         ts->timer_expires = 0;
939                         goto out;
940                 }
941         }
942
943         /*
944          * If this CPU is the one which had the do_timer() duty last, we limit
945          * the sleep time to the timekeeping 'max_deferment' value.
946          * Otherwise we can sleep as long as we want.
947          */
948         delta = timekeeping_max_deferment();
949         if (cpu != tick_do_timer_cpu &&
950             (tick_do_timer_cpu != TICK_DO_TIMER_NONE ||
951              !tick_sched_flag_test(ts, TS_FLAG_DO_TIMER_LAST)))
952                 delta = KTIME_MAX;
953
954         /* Calculate the next expiry time */
955         if (delta < (KTIME_MAX - basemono))
956                 expires = basemono + delta;
957         else
958                 expires = KTIME_MAX;
959
960         ts->timer_expires = min_t(u64, expires, next_tick);
961
962 out:
963         return ts->timer_expires;
964 }
965
966 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
967 {
968         struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
969         unsigned long basejiff = ts->last_jiffies;
970         u64 basemono = ts->timer_expires_base;
971         bool timer_idle = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
972         u64 expires;
973
974         /* Make sure we won't be trying to stop it twice in a row. */
975         ts->timer_expires_base = 0;
976
977         /*
978          * Now the tick should be stopped definitely - so the timer base needs
979          * to be marked idle as well to not miss a newly queued timer.
980          */
981         expires = timer_base_try_to_set_idle(basejiff, basemono, &timer_idle);
982         if (expires > ts->timer_expires) {
983                 /*
984                  * This path could only happen when the first timer was removed
985                  * between calculating the possible sleep length and now (when
986                  * high resolution mode is not active, timer could also be a
987                  * hrtimer).
988                  *
989                  * We have to stick to the original calculated expiry value to
990                  * not stop the tick for too long with a shallow C-state (which
991                  * was programmed by cpuidle because of an early next expiration
992                  * value).
993                  */
994                 expires = ts->timer_expires;
995         }
996
997         /* If the timer base is not idle, retain the not yet stopped tick. */
998         if (!timer_idle)
999                 return;
1000
1001         /*
1002          * If this CPU is the one which updates jiffies, then give up
1003          * the assignment and let it be taken by the CPU which runs
1004          * the tick timer next, which might be this CPU as well. If we
1005          * don't drop this here, the jiffies might be stale and
1006          * do_timer() never gets invoked. Keep track of the fact that it
1007          * was the one which had the do_timer() duty last.
1008          */
1009         if (cpu == tick_do_timer_cpu) {
1010                 tick_do_timer_cpu = TICK_DO_TIMER_NONE;
1011                 tick_sched_flag_set(ts, TS_FLAG_DO_TIMER_LAST);
1012         } else if (tick_do_timer_cpu != TICK_DO_TIMER_NONE) {
1013                 tick_sched_flag_clear(ts, TS_FLAG_DO_TIMER_LAST);
1014         }
1015
1016         /* Skip reprogram of event if it's not changed */
1017         if (tick_sched_flag_test(ts, TS_FLAG_STOPPED) && (expires == ts->next_tick)) {
1018                 /* Sanity check: make sure clockevent is actually programmed */
1019                 if (expires == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
1020                         return;
1021
1022                 WARN_ON_ONCE(1);
1023                 printk_once("basemono: %llu ts->next_tick: %llu dev->next_event: %llu timer->active: %d timer->expires: %llu\n",
1024                             basemono, ts->next_tick, dev->next_event,
1025                             hrtimer_active(&ts->sched_timer), hrtimer_get_expires(&ts->sched_timer));
1026         }
1027
1028         /*
1029          * tick_nohz_stop_tick() can be called several times before
1030          * tick_nohz_restart_sched_tick() is called. This happens when
1031          * interrupts arrive which do not cause a reschedule. In the first
1032          * call we save the current tick time, so we can restart the
1033          * scheduler tick in tick_nohz_restart_sched_tick().
1034          */
1035         if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1036                 calc_load_nohz_start();
1037                 quiet_vmstat();
1038
1039                 ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
1040                 tick_sched_flag_set(ts, TS_FLAG_STOPPED);
1041                 trace_tick_stop(1, TICK_DEP_MASK_NONE);
1042         }
1043
1044         ts->next_tick = expires;
1045
1046         /*
1047          * If the expiration time == KTIME_MAX, then we simply stop
1048          * the tick timer.
1049          */
1050         if (unlikely(expires == KTIME_MAX)) {
1051                 tick_sched_timer_cancel(ts);
1052                 return;
1053         }
1054
1055         if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
1056                 hrtimer_start(&ts->sched_timer, expires,
1057                               HRTIMER_MODE_ABS_PINNED_HARD);
1058         } else {
1059                 hrtimer_set_expires(&ts->sched_timer, expires);
1060                 tick_program_event(expires, 1);
1061         }
1062 }
1063
1064 static void tick_nohz_retain_tick(struct tick_sched *ts)
1065 {
1066         ts->timer_expires_base = 0;
1067 }
1068
1069 #ifdef CONFIG_NO_HZ_FULL
1070 static void tick_nohz_full_stop_tick(struct tick_sched *ts, int cpu)
1071 {
1072         if (tick_nohz_next_event(ts, cpu))
1073                 tick_nohz_stop_tick(ts, cpu);
1074         else
1075                 tick_nohz_retain_tick(ts);
1076 }
1077 #endif /* CONFIG_NO_HZ_FULL */
1078
1079 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
1080 {
1081         /* Update jiffies first */
1082         tick_do_update_jiffies64(now);
1083
1084         /*
1085          * Clear the timer idle flag, so we avoid IPIs on remote queueing and
1086          * the clock forward checks in the enqueue path:
1087          */
1088         timer_clear_idle();
1089
1090         calc_load_nohz_stop();
1091         touch_softlockup_watchdog_sched();
1092
1093         /* Cancel the scheduled timer and restore the tick: */
1094         tick_sched_flag_clear(ts, TS_FLAG_STOPPED);
1095         tick_nohz_restart(ts, now);
1096 }
1097
1098 static void __tick_nohz_full_update_tick(struct tick_sched *ts,
1099                                          ktime_t now)
1100 {
1101 #ifdef CONFIG_NO_HZ_FULL
1102         int cpu = smp_processor_id();
1103
1104         if (can_stop_full_tick(cpu, ts))
1105                 tick_nohz_full_stop_tick(ts, cpu);
1106         else if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1107                 tick_nohz_restart_sched_tick(ts, now);
1108 #endif
1109 }
1110
1111 static void tick_nohz_full_update_tick(struct tick_sched *ts)
1112 {
1113         if (!tick_nohz_full_cpu(smp_processor_id()))
1114                 return;
1115
1116         if (!tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1117                 return;
1118
1119         __tick_nohz_full_update_tick(ts, ktime_get());
1120 }
1121
1122 /*
1123  * A pending softirq outside an IRQ (or softirq disabled section) context
1124  * should be waiting for ksoftirqd to handle it. Therefore we shouldn't
1125  * reach this code due to the need_resched() early check in can_stop_idle_tick().
1126  *
1127  * However if we are between CPUHP_AP_SMPBOOT_THREADS and CPU_TEARDOWN_CPU on the
1128  * cpu_down() process, softirqs can still be raised while ksoftirqd is parked,
1129  * triggering the code below, since wakep_softirqd() is ignored.
1130  *
1131  */
1132 static bool report_idle_softirq(void)
1133 {
1134         static int ratelimit;
1135         unsigned int pending = local_softirq_pending();
1136
1137         if (likely(!pending))
1138                 return false;
1139
1140         /* Some softirqs claim to be safe against hotplug and ksoftirqd parking */
1141         if (!cpu_active(smp_processor_id())) {
1142                 pending &= ~SOFTIRQ_HOTPLUG_SAFE_MASK;
1143                 if (!pending)
1144                         return false;
1145         }
1146
1147         if (ratelimit >= 10)
1148                 return false;
1149
1150         /* On RT, softirq handling may be waiting on some lock */
1151         if (local_bh_blocked())
1152                 return false;
1153
1154         pr_warn("NOHZ tick-stop error: local softirq work is pending, handler #%02x!!!\n",
1155                 pending);
1156         ratelimit++;
1157
1158         return true;
1159 }
1160
1161 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
1162 {
1163         WARN_ON_ONCE(cpu_is_offline(cpu));
1164
1165         if (unlikely(!tick_sched_flag_test(ts, TS_FLAG_NOHZ)))
1166                 return false;
1167
1168         if (need_resched())
1169                 return false;
1170
1171         if (unlikely(report_idle_softirq()))
1172                 return false;
1173
1174         if (tick_nohz_full_enabled()) {
1175                 /*
1176                  * Keep the tick alive to guarantee timekeeping progression
1177                  * if there are full dynticks CPUs around
1178                  */
1179                 if (tick_do_timer_cpu == cpu)
1180                         return false;
1181
1182                 /* Should not happen for nohz-full */
1183                 if (WARN_ON_ONCE(tick_do_timer_cpu == TICK_DO_TIMER_NONE))
1184                         return false;
1185         }
1186
1187         return true;
1188 }
1189
1190 /**
1191  * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1192  *
1193  * When the next event is more than a tick into the future, stop the idle tick
1194  */
1195 void tick_nohz_idle_stop_tick(void)
1196 {
1197         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1198         int cpu = smp_processor_id();
1199         ktime_t expires;
1200
1201         /*
1202          * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
1203          * tick timer expiration time is known already.
1204          */
1205         if (ts->timer_expires_base)
1206                 expires = ts->timer_expires;
1207         else if (can_stop_idle_tick(cpu, ts))
1208                 expires = tick_nohz_next_event(ts, cpu);
1209         else
1210                 return;
1211
1212         ts->idle_calls++;
1213
1214         if (expires > 0LL) {
1215                 int was_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
1216
1217                 tick_nohz_stop_tick(ts, cpu);
1218
1219                 ts->idle_sleeps++;
1220                 ts->idle_expires = expires;
1221
1222                 if (!was_stopped && tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1223                         ts->idle_jiffies = ts->last_jiffies;
1224                         nohz_balance_enter_idle(cpu);
1225                 }
1226         } else {
1227                 tick_nohz_retain_tick(ts);
1228         }
1229 }
1230
1231 void tick_nohz_idle_retain_tick(void)
1232 {
1233         tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1234 }
1235
1236 /**
1237  * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1238  *
1239  * Called when we start the idle loop.
1240  */
1241 void tick_nohz_idle_enter(void)
1242 {
1243         struct tick_sched *ts;
1244
1245         lockdep_assert_irqs_enabled();
1246
1247         local_irq_disable();
1248
1249         ts = this_cpu_ptr(&tick_cpu_sched);
1250
1251         WARN_ON_ONCE(ts->timer_expires_base);
1252
1253         tick_sched_flag_set(ts, TS_FLAG_INIDLE);
1254         tick_nohz_start_idle(ts);
1255
1256         local_irq_enable();
1257 }
1258
1259 /**
1260  * tick_nohz_irq_exit - Notify the tick about IRQ exit
1261  *
1262  * A timer may have been added/modified/deleted either by the current IRQ,
1263  * or by another place using this IRQ as a notification. This IRQ may have
1264  * also updated the RCU callback list. These events may require a
1265  * re-evaluation of the next tick. Depending on the context:
1266  *
1267  * 1) If the CPU is idle and no resched is pending, just proceed with idle
1268  *    time accounting. The next tick will be re-evaluated on the next idle
1269  *    loop iteration.
1270  *
1271  * 2) If the CPU is nohz_full:
1272  *
1273  *    2.1) If there is any tick dependency, restart the tick if stopped.
1274  *
1275  *    2.2) If there is no tick dependency, (re-)evaluate the next tick and
1276  *         stop/update it accordingly.
1277  */
1278 void tick_nohz_irq_exit(void)
1279 {
1280         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1281
1282         if (tick_sched_flag_test(ts, TS_FLAG_INIDLE))
1283                 tick_nohz_start_idle(ts);
1284         else
1285                 tick_nohz_full_update_tick(ts);
1286 }
1287
1288 /**
1289  * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1290  */
1291 bool tick_nohz_idle_got_tick(void)
1292 {
1293         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1294
1295         if (ts->got_idle_tick) {
1296                 ts->got_idle_tick = 0;
1297                 return true;
1298         }
1299         return false;
1300 }
1301
1302 /**
1303  * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1304  * or the tick, whichever expires first. Note that, if the tick has been
1305  * stopped, it returns the next hrtimer.
1306  *
1307  * Called from power state control code with interrupts disabled
1308  */
1309 ktime_t tick_nohz_get_next_hrtimer(void)
1310 {
1311         return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1312 }
1313
1314 /**
1315  * tick_nohz_get_sleep_length - return the expected length of the current sleep
1316  * @delta_next: duration until the next event if the tick cannot be stopped
1317  *
1318  * Called from power state control code with interrupts disabled.
1319  *
1320  * The return value of this function and/or the value returned by it through the
1321  * @delta_next pointer can be negative which must be taken into account by its
1322  * callers.
1323  */
1324 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1325 {
1326         struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1327         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1328         int cpu = smp_processor_id();
1329         /*
1330          * The idle entry time is expected to be a sufficient approximation of
1331          * the current time at this point.
1332          */
1333         ktime_t now = ts->idle_entrytime;
1334         ktime_t next_event;
1335
1336         WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
1337
1338         *delta_next = ktime_sub(dev->next_event, now);
1339
1340         if (!can_stop_idle_tick(cpu, ts))
1341                 return *delta_next;
1342
1343         next_event = tick_nohz_next_event(ts, cpu);
1344         if (!next_event)
1345                 return *delta_next;
1346
1347         /*
1348          * If the next highres timer to expire is earlier than 'next_event', the
1349          * idle governor needs to know that.
1350          */
1351         next_event = min_t(u64, next_event,
1352                            hrtimer_next_event_without(&ts->sched_timer));
1353
1354         return ktime_sub(next_event, now);
1355 }
1356
1357 /**
1358  * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1359  * for a particular CPU.
1360  *
1361  * Called from the schedutil frequency scaling governor in scheduler context.
1362  */
1363 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1364 {
1365         struct tick_sched *ts = tick_get_tick_sched(cpu);
1366
1367         return ts->idle_calls;
1368 }
1369
1370 /**
1371  * tick_nohz_get_idle_calls - return the current idle calls counter value
1372  *
1373  * Called from the schedutil frequency scaling governor in scheduler context.
1374  */
1375 unsigned long tick_nohz_get_idle_calls(void)
1376 {
1377         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1378
1379         return ts->idle_calls;
1380 }
1381
1382 static void tick_nohz_account_idle_time(struct tick_sched *ts,
1383                                         ktime_t now)
1384 {
1385         unsigned long ticks;
1386
1387         ts->idle_exittime = now;
1388
1389         if (vtime_accounting_enabled_this_cpu())
1390                 return;
1391         /*
1392          * We stopped the tick in idle. update_process_times() would miss the
1393          * time we slept, as it does only a 1 tick accounting.
1394          * Enforce that this is accounted to idle !
1395          */
1396         ticks = jiffies - ts->idle_jiffies;
1397         /*
1398          * We might be one off. Do not randomly account a huge number of ticks!
1399          */
1400         if (ticks && ticks < LONG_MAX)
1401                 account_idle_ticks(ticks);
1402 }
1403
1404 void tick_nohz_idle_restart_tick(void)
1405 {
1406         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1407
1408         if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1409                 ktime_t now = ktime_get();
1410                 tick_nohz_restart_sched_tick(ts, now);
1411                 tick_nohz_account_idle_time(ts, now);
1412         }
1413 }
1414
1415 static void tick_nohz_idle_update_tick(struct tick_sched *ts, ktime_t now)
1416 {
1417         if (tick_nohz_full_cpu(smp_processor_id()))
1418                 __tick_nohz_full_update_tick(ts, now);
1419         else
1420                 tick_nohz_restart_sched_tick(ts, now);
1421
1422         tick_nohz_account_idle_time(ts, now);
1423 }
1424
1425 /**
1426  * tick_nohz_idle_exit - Update the tick upon idle task exit
1427  *
1428  * When the idle task exits, update the tick depending on the
1429  * following situations:
1430  *
1431  * 1) If the CPU is not in nohz_full mode (most cases), then
1432  *    restart the tick.
1433  *
1434  * 2) If the CPU is in nohz_full mode (corner case):
1435  *   2.1) If the tick can be kept stopped (no tick dependencies)
1436  *        then re-evaluate the next tick and try to keep it stopped
1437  *        as long as possible.
1438  *   2.2) If the tick has dependencies, restart the tick.
1439  *
1440  */
1441 void tick_nohz_idle_exit(void)
1442 {
1443         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1444         bool idle_active, tick_stopped;
1445         ktime_t now;
1446
1447         local_irq_disable();
1448
1449         WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
1450         WARN_ON_ONCE(ts->timer_expires_base);
1451
1452         tick_sched_flag_clear(ts, TS_FLAG_INIDLE);
1453         idle_active = tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE);
1454         tick_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
1455
1456         if (idle_active || tick_stopped)
1457                 now = ktime_get();
1458
1459         if (idle_active)
1460                 tick_nohz_stop_idle(ts, now);
1461
1462         if (tick_stopped)
1463                 tick_nohz_idle_update_tick(ts, now);
1464
1465         local_irq_enable();
1466 }
1467
1468 /*
1469  * In low-resolution mode, the tick handler must be implemented directly
1470  * at the clockevent level. hrtimer can't be used instead, because its
1471  * infrastructure actually relies on the tick itself as a backend in
1472  * low-resolution mode (see hrtimer_run_queues()).
1473  */
1474 static void tick_nohz_lowres_handler(struct clock_event_device *dev)
1475 {
1476         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1477
1478         dev->next_event = KTIME_MAX;
1479
1480         if (likely(tick_nohz_handler(&ts->sched_timer) == HRTIMER_RESTART))
1481                 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1482 }
1483
1484 static inline void tick_nohz_activate(struct tick_sched *ts)
1485 {
1486         if (!tick_nohz_enabled)
1487                 return;
1488         tick_sched_flag_set(ts, TS_FLAG_NOHZ);
1489         /* One update is enough */
1490         if (!test_and_set_bit(0, &tick_nohz_active))
1491                 timers_update_nohz();
1492 }
1493
1494 /**
1495  * tick_nohz_switch_to_nohz - switch to NOHZ mode
1496  */
1497 static void tick_nohz_switch_to_nohz(void)
1498 {
1499         if (!tick_nohz_enabled)
1500                 return;
1501
1502         if (tick_switch_to_oneshot(tick_nohz_lowres_handler))
1503                 return;
1504
1505         /*
1506          * Recycle the hrtimer in 'ts', so we can share the
1507          * highres code.
1508          */
1509         tick_setup_sched_timer(false);
1510 }
1511
1512 static inline void tick_nohz_irq_enter(void)
1513 {
1514         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1515         ktime_t now;
1516
1517         if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED | TS_FLAG_IDLE_ACTIVE))
1518                 return;
1519         now = ktime_get();
1520         if (tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE))
1521                 tick_nohz_stop_idle(ts, now);
1522         /*
1523          * If all CPUs are idle we may need to update a stale jiffies value.
1524          * Note nohz_full is a special case: a timekeeper is guaranteed to stay
1525          * alive but it might be busy looping with interrupts disabled in some
1526          * rare case (typically stop machine). So we must make sure we have a
1527          * last resort.
1528          */
1529         if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1530                 tick_nohz_update_jiffies(now);
1531 }
1532
1533 #else
1534
1535 static inline void tick_nohz_switch_to_nohz(void) { }
1536 static inline void tick_nohz_irq_enter(void) { }
1537 static inline void tick_nohz_activate(struct tick_sched *ts) { }
1538
1539 #endif /* CONFIG_NO_HZ_COMMON */
1540
1541 /*
1542  * Called from irq_enter() to notify about the possible interruption of idle()
1543  */
1544 void tick_irq_enter(void)
1545 {
1546         tick_check_oneshot_broadcast_this_cpu();
1547         tick_nohz_irq_enter();
1548 }
1549
1550 static int sched_skew_tick;
1551
1552 static int __init skew_tick(char *str)
1553 {
1554         get_option(&str, &sched_skew_tick);
1555
1556         return 0;
1557 }
1558 early_param("skew_tick", skew_tick);
1559
1560 /**
1561  * tick_setup_sched_timer - setup the tick emulation timer
1562  * @mode: tick_nohz_mode to setup for
1563  */
1564 void tick_setup_sched_timer(bool hrtimer)
1565 {
1566         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1567
1568         /* Emulate tick processing via per-CPU hrtimers: */
1569         hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1570
1571         if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer) {
1572                 tick_sched_flag_set(ts, TS_FLAG_HIGHRES);
1573                 ts->sched_timer.function = tick_nohz_handler;
1574         }
1575
1576         /* Get the next period (per-CPU) */
1577         hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1578
1579         /* Offset the tick to avert 'jiffies_lock' contention. */
1580         if (sched_skew_tick) {
1581                 u64 offset = TICK_NSEC >> 1;
1582                 do_div(offset, num_possible_cpus());
1583                 offset *= smp_processor_id();
1584                 hrtimer_add_expires_ns(&ts->sched_timer, offset);
1585         }
1586
1587         hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
1588         if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer)
1589                 hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1590         else
1591                 tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1592         tick_nohz_activate(ts);
1593 }
1594
1595 /*
1596  * Shut down the tick and make sure the CPU won't try to retake the timekeeping
1597  * duty before disabling IRQs in idle for the last time.
1598  */
1599 void tick_sched_timer_dying(int cpu)
1600 {
1601         struct tick_device *td = &per_cpu(tick_cpu_device, cpu);
1602         struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1603         struct clock_event_device *dev = td->evtdev;
1604         ktime_t idle_sleeptime, iowait_sleeptime;
1605         unsigned long idle_calls, idle_sleeps;
1606
1607         /* This must happen before hrtimers are migrated! */
1608         tick_sched_timer_cancel(ts);
1609
1610         /*
1611          * If the clockevents doesn't support CLOCK_EVT_STATE_ONESHOT_STOPPED,
1612          * make sure not to call low-res tick handler.
1613          */
1614         if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1615                 dev->event_handler = clockevents_handle_noop;
1616
1617         idle_sleeptime = ts->idle_sleeptime;
1618         iowait_sleeptime = ts->iowait_sleeptime;
1619         idle_calls = ts->idle_calls;
1620         idle_sleeps = ts->idle_sleeps;
1621         memset(ts, 0, sizeof(*ts));
1622         ts->idle_sleeptime = idle_sleeptime;
1623         ts->iowait_sleeptime = iowait_sleeptime;
1624         ts->idle_calls = idle_calls;
1625         ts->idle_sleeps = idle_sleeps;
1626 }
1627
1628 /*
1629  * Async notification about clocksource changes
1630  */
1631 void tick_clock_notify(void)
1632 {
1633         int cpu;
1634
1635         for_each_possible_cpu(cpu)
1636                 set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1637 }
1638
1639 /*
1640  * Async notification about clock event changes
1641  */
1642 void tick_oneshot_notify(void)
1643 {
1644         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1645
1646         set_bit(0, &ts->check_clocks);
1647 }
1648
1649 /*
1650  * Check if a change happened, which makes oneshot possible.
1651  *
1652  * Called cyclically from the hrtimer softirq (driven by the timer
1653  * softirq). 'allow_nohz' signals that we can switch into low-res NOHZ
1654  * mode, because high resolution timers are disabled (either compile
1655  * or runtime). Called with interrupts disabled.
1656  */
1657 int tick_check_oneshot_change(int allow_nohz)
1658 {
1659         struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1660
1661         if (!test_and_clear_bit(0, &ts->check_clocks))
1662                 return 0;
1663
1664         if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1665                 return 0;
1666
1667         if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1668                 return 0;
1669
1670         if (!allow_nohz)
1671                 return 1;
1672
1673         tick_nohz_switch_to_nohz();
1674         return 0;
1675 }