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