xref: /linux/kernel/time/tick-sched.c (revision 353a7e8a69058591c3ec40028063af798b698559)
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 
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  */
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  */
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 
184 static inline int tick_sched_flag_test(struct tick_sched *ts,
185 				       unsigned long flag)
186 {
187 	return !!(ts->flags & flag);
188 }
189 
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 
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  */
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 
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 
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  */
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 
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 
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(&current->tick_dep_mask))
397 		return false;
398 
399 	if (check_tick_dependency(&current->signal->tick_dep_mask))
400 		return false;
401 
402 	return true;
403 }
404 
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  */
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  */
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 
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  */
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 
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  */
516 void tick_nohz_dep_set(enum tick_dep_bits bit)
517 {
518 	tick_nohz_dep_set_all(&tick_dep_mask, bit);
519 }
520 
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  */
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 
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  */
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 
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  */
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 
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  */
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(&current->tick_dep_mask) ||
619 		    atomic_read(&current->signal->tick_dep_mask))
620 			tick_nohz_full_kick();
621 	}
622 }
623 
624 /* Get the boot-time nohz CPU list from the kernel parameters. */
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 
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 
644 static int tick_nohz_cpu_down(unsigned int cpu)
645 {
646 	return tick_nohz_cpu_hotpluggable(cpu) ? 0 : -EBUSY;
647 }
648 
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  */
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 
710 bool tick_nohz_is_active(void)
711 {
712 	return tick_nohz_active;
713 }
714 EXPORT_SYMBOL_GPL(tick_nohz_is_active);
715 
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 
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  */
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 
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 
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 
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  */
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  */
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 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
868 {
869 	hrtimer_cancel(&ts->sched_timer);
870 	hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
871 
872 	/* Forward the time to expire in the future */
873 	hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
874 
875 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
876 		hrtimer_start_expires(&ts->sched_timer,
877 				      HRTIMER_MODE_ABS_PINNED_HARD);
878 	} else {
879 		tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
880 	}
881 
882 	/*
883 	 * Reset to make sure the next tick stop doesn't get fooled by past
884 	 * cached clock deadline.
885 	 */
886 	ts->next_tick = 0;
887 }
888 
889 static inline bool local_timer_softirq_pending(void)
890 {
891 	return local_timers_pending() & BIT(TIMER_SOFTIRQ);
892 }
893 
894 /*
895  * Read jiffies and the time when jiffies were updated last
896  */
897 u64 get_jiffies_update(unsigned long *basej)
898 {
899 	unsigned long basejiff;
900 	unsigned int seq;
901 	u64 basemono;
902 
903 	do {
904 		seq = read_seqcount_begin(&jiffies_seq);
905 		basemono = last_jiffies_update;
906 		basejiff = jiffies;
907 	} while (read_seqcount_retry(&jiffies_seq, seq));
908 	*basej = basejiff;
909 	return basemono;
910 }
911 
912 /**
913  * tick_nohz_next_event() - return the clock monotonic based next event
914  * @ts:		pointer to tick_sched struct
915  * @cpu:	CPU number
916  *
917  * Return:
918  * *%0		- When the next event is a maximum of TICK_NSEC in the future
919  *		  and the tick is not stopped yet
920  * *%next_event	- Next event based on clock monotonic
921  */
922 static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
923 {
924 	u64 basemono, next_tick, delta, expires;
925 	unsigned long basejiff;
926 	int tick_cpu;
927 
928 	basemono = get_jiffies_update(&basejiff);
929 	ts->last_jiffies = basejiff;
930 	ts->timer_expires_base = basemono;
931 
932 	/*
933 	 * Keep the periodic tick, when RCU, architecture or irq_work
934 	 * requests it.
935 	 * Aside of that, check whether the local timer softirq is
936 	 * pending. If so, its a bad idea to call get_next_timer_interrupt(),
937 	 * because there is an already expired timer, so it will request
938 	 * immediate expiry, which rearms the hardware timer with a
939 	 * minimal delta, which brings us back to this place
940 	 * immediately. Lather, rinse and repeat...
941 	 */
942 	if (rcu_needs_cpu() || arch_needs_cpu() ||
943 	    irq_work_needs_cpu() || local_timer_softirq_pending()) {
944 		next_tick = basemono + TICK_NSEC;
945 	} else {
946 		/*
947 		 * Get the next pending timer. If high resolution
948 		 * timers are enabled this only takes the timer wheel
949 		 * timers into account. If high resolution timers are
950 		 * disabled this also looks at the next expiring
951 		 * hrtimer.
952 		 */
953 		next_tick = get_next_timer_interrupt(basejiff, basemono);
954 		ts->next_timer = next_tick;
955 	}
956 
957 	/* Make sure next_tick is never before basemono! */
958 	if (WARN_ON_ONCE(basemono > next_tick))
959 		next_tick = basemono;
960 
961 	/*
962 	 * If the tick is due in the next period, keep it ticking or
963 	 * force prod the timer.
964 	 */
965 	delta = next_tick - basemono;
966 	if (delta <= (u64)TICK_NSEC) {
967 		/*
968 		 * We've not stopped the tick yet, and there's a timer in the
969 		 * next period, so no point in stopping it either, bail.
970 		 */
971 		if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
972 			ts->timer_expires = 0;
973 			goto out;
974 		}
975 	}
976 
977 	/*
978 	 * If this CPU is the one which had the do_timer() duty last, we limit
979 	 * the sleep time to the timekeeping 'max_deferment' value.
980 	 * Otherwise we can sleep as long as we want.
981 	 */
982 	delta = timekeeping_max_deferment();
983 	tick_cpu = READ_ONCE(tick_do_timer_cpu);
984 	if (tick_cpu != cpu &&
985 	    (tick_cpu != TICK_DO_TIMER_NONE || !tick_sched_flag_test(ts, TS_FLAG_DO_TIMER_LAST)))
986 		delta = KTIME_MAX;
987 
988 	/* Calculate the next expiry time */
989 	if (delta < (KTIME_MAX - basemono))
990 		expires = basemono + delta;
991 	else
992 		expires = KTIME_MAX;
993 
994 	ts->timer_expires = min_t(u64, expires, next_tick);
995 
996 out:
997 	return ts->timer_expires;
998 }
999 
1000 static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
1001 {
1002 	struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1003 	unsigned long basejiff = ts->last_jiffies;
1004 	u64 basemono = ts->timer_expires_base;
1005 	bool timer_idle = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
1006 	int tick_cpu;
1007 	u64 expires;
1008 
1009 	/* Make sure we won't be trying to stop it twice in a row. */
1010 	ts->timer_expires_base = 0;
1011 
1012 	/*
1013 	 * Now the tick should be stopped definitely - so the timer base needs
1014 	 * to be marked idle as well to not miss a newly queued timer.
1015 	 */
1016 	expires = timer_base_try_to_set_idle(basejiff, basemono, &timer_idle);
1017 	if (expires > ts->timer_expires) {
1018 		/*
1019 		 * This path could only happen when the first timer was removed
1020 		 * between calculating the possible sleep length and now (when
1021 		 * high resolution mode is not active, timer could also be a
1022 		 * hrtimer).
1023 		 *
1024 		 * We have to stick to the original calculated expiry value to
1025 		 * not stop the tick for too long with a shallow C-state (which
1026 		 * was programmed by cpuidle because of an early next expiration
1027 		 * value).
1028 		 */
1029 		expires = ts->timer_expires;
1030 	}
1031 
1032 	/* If the timer base is not idle, retain the not yet stopped tick. */
1033 	if (!timer_idle)
1034 		return;
1035 
1036 	/*
1037 	 * If this CPU is the one which updates jiffies, then give up
1038 	 * the assignment and let it be taken by the CPU which runs
1039 	 * the tick timer next, which might be this CPU as well. If we
1040 	 * don't drop this here, the jiffies might be stale and
1041 	 * do_timer() never gets invoked. Keep track of the fact that it
1042 	 * was the one which had the do_timer() duty last.
1043 	 */
1044 	tick_cpu = READ_ONCE(tick_do_timer_cpu);
1045 	if (tick_cpu == cpu) {
1046 		WRITE_ONCE(tick_do_timer_cpu, TICK_DO_TIMER_NONE);
1047 		tick_sched_flag_set(ts, TS_FLAG_DO_TIMER_LAST);
1048 	} else if (tick_cpu != TICK_DO_TIMER_NONE) {
1049 		tick_sched_flag_clear(ts, TS_FLAG_DO_TIMER_LAST);
1050 	}
1051 
1052 	/* Skip reprogram of event if it's not changed */
1053 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED) && (expires == ts->next_tick)) {
1054 		/* Sanity check: make sure clockevent is actually programmed */
1055 		if (expires == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
1056 			return;
1057 
1058 		WARN_ONCE(1, "basemono: %llu ts->next_tick: %llu dev->next_event: %llu "
1059 			  "timer->active: %d timer->expires: %llu\n", basemono, ts->next_tick,
1060 			  dev->next_event, hrtimer_active(&ts->sched_timer),
1061 			  hrtimer_get_expires(&ts->sched_timer));
1062 	}
1063 
1064 	/*
1065 	 * tick_nohz_stop_tick() can be called several times before
1066 	 * tick_nohz_restart_sched_tick() is called. This happens when
1067 	 * interrupts arrive which do not cause a reschedule. In the first
1068 	 * call we save the current tick time, so we can restart the
1069 	 * scheduler tick in tick_nohz_restart_sched_tick().
1070 	 */
1071 	if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1072 		calc_load_nohz_start();
1073 		quiet_vmstat();
1074 
1075 		ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
1076 		tick_sched_flag_set(ts, TS_FLAG_STOPPED);
1077 		trace_tick_stop(1, TICK_DEP_MASK_NONE);
1078 	}
1079 
1080 	ts->next_tick = expires;
1081 
1082 	/*
1083 	 * If the expiration time == KTIME_MAX, then we simply stop
1084 	 * the tick timer.
1085 	 */
1086 	if (unlikely(expires == KTIME_MAX)) {
1087 		if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES))
1088 			hrtimer_cancel(&ts->sched_timer);
1089 		else
1090 			tick_program_event(KTIME_MAX, 1);
1091 		return;
1092 	}
1093 
1094 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
1095 		hrtimer_start(&ts->sched_timer, expires,
1096 			      HRTIMER_MODE_ABS_PINNED_HARD);
1097 	} else {
1098 		hrtimer_set_expires(&ts->sched_timer, expires);
1099 		tick_program_event(expires, 1);
1100 	}
1101 }
1102 
1103 static void tick_nohz_retain_tick(struct tick_sched *ts)
1104 {
1105 	ts->timer_expires_base = 0;
1106 }
1107 
1108 #ifdef CONFIG_NO_HZ_FULL
1109 static void tick_nohz_full_stop_tick(struct tick_sched *ts, int cpu)
1110 {
1111 	if (tick_nohz_next_event(ts, cpu))
1112 		tick_nohz_stop_tick(ts, cpu);
1113 	else
1114 		tick_nohz_retain_tick(ts);
1115 }
1116 #endif /* CONFIG_NO_HZ_FULL */
1117 
1118 static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
1119 {
1120 	/* Update jiffies first */
1121 	tick_do_update_jiffies64(now);
1122 
1123 	/*
1124 	 * Clear the timer idle flag, so we avoid IPIs on remote queueing and
1125 	 * the clock forward checks in the enqueue path:
1126 	 */
1127 	timer_clear_idle();
1128 
1129 	calc_load_nohz_stop();
1130 	touch_softlockup_watchdog_sched();
1131 
1132 	/* Cancel the scheduled timer and restore the tick: */
1133 	tick_sched_flag_clear(ts, TS_FLAG_STOPPED);
1134 	tick_nohz_restart(ts, now);
1135 }
1136 
1137 static void __tick_nohz_full_update_tick(struct tick_sched *ts,
1138 					 ktime_t now)
1139 {
1140 #ifdef CONFIG_NO_HZ_FULL
1141 	int cpu = smp_processor_id();
1142 
1143 	if (can_stop_full_tick(cpu, ts))
1144 		tick_nohz_full_stop_tick(ts, cpu);
1145 	else if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1146 		tick_nohz_restart_sched_tick(ts, now);
1147 #endif
1148 }
1149 
1150 static void tick_nohz_full_update_tick(struct tick_sched *ts)
1151 {
1152 	if (!tick_nohz_full_cpu(smp_processor_id()))
1153 		return;
1154 
1155 	if (!tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1156 		return;
1157 
1158 	__tick_nohz_full_update_tick(ts, ktime_get());
1159 }
1160 
1161 /*
1162  * A pending softirq outside an IRQ (or softirq disabled section) context
1163  * should be waiting for ksoftirqd to handle it. Therefore we shouldn't
1164  * reach this code due to the need_resched() early check in can_stop_idle_tick().
1165  *
1166  * However if we are between CPUHP_AP_SMPBOOT_THREADS and CPU_TEARDOWN_CPU on the
1167  * cpu_down() process, softirqs can still be raised while ksoftirqd is parked,
1168  * triggering the code below, since wakep_softirqd() is ignored.
1169  *
1170  */
1171 static bool report_idle_softirq(void)
1172 {
1173 	static int ratelimit;
1174 	unsigned int pending = local_softirq_pending();
1175 
1176 	if (likely(!pending))
1177 		return false;
1178 
1179 	/* Some softirqs claim to be safe against hotplug and ksoftirqd parking */
1180 	if (!cpu_active(smp_processor_id())) {
1181 		pending &= ~SOFTIRQ_HOTPLUG_SAFE_MASK;
1182 		if (!pending)
1183 			return false;
1184 	}
1185 
1186 	/* On RT, softirq handling may be waiting on some lock */
1187 	if (local_bh_blocked())
1188 		return false;
1189 
1190 	if (ratelimit < 10) {
1191 		pr_warn("NOHZ tick-stop error: local softirq work is pending, handler #%02x!!!\n",
1192 			pending);
1193 		ratelimit++;
1194 	}
1195 
1196 	return true;
1197 }
1198 
1199 static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
1200 {
1201 	WARN_ON_ONCE(cpu_is_offline(cpu));
1202 
1203 	if (unlikely(!tick_sched_flag_test(ts, TS_FLAG_NOHZ)))
1204 		return false;
1205 
1206 	if (need_resched())
1207 		return false;
1208 
1209 	if (unlikely(report_idle_softirq()))
1210 		return false;
1211 
1212 	if (tick_nohz_full_enabled()) {
1213 		int tick_cpu = READ_ONCE(tick_do_timer_cpu);
1214 
1215 		/*
1216 		 * Keep the tick alive to guarantee timekeeping progression
1217 		 * if there are full dynticks CPUs around
1218 		 */
1219 		if (tick_cpu == cpu)
1220 			return false;
1221 
1222 		/* Should not happen for nohz-full */
1223 		if (WARN_ON_ONCE(tick_cpu == TICK_DO_TIMER_NONE))
1224 			return false;
1225 	}
1226 
1227 	return true;
1228 }
1229 
1230 /**
1231  * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
1232  *
1233  * When the next event is more than a tick into the future, stop the idle tick
1234  */
1235 void tick_nohz_idle_stop_tick(void)
1236 {
1237 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1238 	int cpu = smp_processor_id();
1239 	ktime_t expires;
1240 
1241 	/*
1242 	 * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
1243 	 * tick timer expiration time is known already.
1244 	 */
1245 	if (ts->timer_expires_base)
1246 		expires = ts->timer_expires;
1247 	else if (can_stop_idle_tick(cpu, ts))
1248 		expires = tick_nohz_next_event(ts, cpu);
1249 	else
1250 		return;
1251 
1252 	ts->idle_calls++;
1253 
1254 	if (expires > 0LL) {
1255 		int was_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
1256 
1257 		tick_nohz_stop_tick(ts, cpu);
1258 
1259 		ts->idle_sleeps++;
1260 		ts->idle_expires = expires;
1261 
1262 		if (!was_stopped && tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1263 			ts->idle_jiffies = ts->last_jiffies;
1264 			nohz_balance_enter_idle(cpu);
1265 		}
1266 	} else {
1267 		tick_nohz_retain_tick(ts);
1268 	}
1269 }
1270 
1271 void tick_nohz_idle_retain_tick(void)
1272 {
1273 	tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
1274 }
1275 
1276 /**
1277  * tick_nohz_idle_enter - prepare for entering idle on the current CPU
1278  *
1279  * Called when we start the idle loop.
1280  */
1281 void tick_nohz_idle_enter(void)
1282 {
1283 	struct tick_sched *ts;
1284 
1285 	lockdep_assert_irqs_enabled();
1286 
1287 	local_irq_disable();
1288 
1289 	ts = this_cpu_ptr(&tick_cpu_sched);
1290 
1291 	WARN_ON_ONCE(ts->timer_expires_base);
1292 
1293 	tick_sched_flag_set(ts, TS_FLAG_INIDLE);
1294 	tick_nohz_start_idle(ts);
1295 
1296 	local_irq_enable();
1297 }
1298 
1299 /**
1300  * tick_nohz_irq_exit - Notify the tick about IRQ exit
1301  *
1302  * A timer may have been added/modified/deleted either by the current IRQ,
1303  * or by another place using this IRQ as a notification. This IRQ may have
1304  * also updated the RCU callback list. These events may require a
1305  * re-evaluation of the next tick. Depending on the context:
1306  *
1307  * 1) If the CPU is idle and no resched is pending, just proceed with idle
1308  *    time accounting. The next tick will be re-evaluated on the next idle
1309  *    loop iteration.
1310  *
1311  * 2) If the CPU is nohz_full:
1312  *
1313  *    2.1) If there is any tick dependency, restart the tick if stopped.
1314  *
1315  *    2.2) If there is no tick dependency, (re-)evaluate the next tick and
1316  *         stop/update it accordingly.
1317  */
1318 void tick_nohz_irq_exit(void)
1319 {
1320 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1321 
1322 	if (tick_sched_flag_test(ts, TS_FLAG_INIDLE))
1323 		tick_nohz_start_idle(ts);
1324 	else
1325 		tick_nohz_full_update_tick(ts);
1326 }
1327 
1328 /**
1329  * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
1330  *
1331  * Return: %true if the tick handler has run, otherwise %false
1332  */
1333 bool tick_nohz_idle_got_tick(void)
1334 {
1335 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1336 
1337 	if (ts->got_idle_tick) {
1338 		ts->got_idle_tick = 0;
1339 		return true;
1340 	}
1341 	return false;
1342 }
1343 
1344 /**
1345  * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
1346  * or the tick, whichever expires first. Note that, if the tick has been
1347  * stopped, it returns the next hrtimer.
1348  *
1349  * Called from power state control code with interrupts disabled
1350  *
1351  * Return: the next expiration time
1352  */
1353 ktime_t tick_nohz_get_next_hrtimer(void)
1354 {
1355 	return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
1356 }
1357 
1358 /**
1359  * tick_nohz_get_sleep_length - return the expected length of the current sleep
1360  * @delta_next: duration until the next event if the tick cannot be stopped
1361  *
1362  * Called from power state control code with interrupts disabled.
1363  *
1364  * The return value of this function and/or the value returned by it through the
1365  * @delta_next pointer can be negative which must be taken into account by its
1366  * callers.
1367  *
1368  * Return: the expected length of the current sleep
1369  */
1370 ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
1371 {
1372 	struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
1373 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1374 	int cpu = smp_processor_id();
1375 	/*
1376 	 * The idle entry time is expected to be a sufficient approximation of
1377 	 * the current time at this point.
1378 	 */
1379 	ktime_t now = ts->idle_entrytime;
1380 	ktime_t next_event;
1381 
1382 	WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
1383 
1384 	*delta_next = ktime_sub(dev->next_event, now);
1385 
1386 	if (!can_stop_idle_tick(cpu, ts))
1387 		return *delta_next;
1388 
1389 	next_event = tick_nohz_next_event(ts, cpu);
1390 	if (!next_event)
1391 		return *delta_next;
1392 
1393 	/*
1394 	 * If the next highres timer to expire is earlier than 'next_event', the
1395 	 * idle governor needs to know that.
1396 	 */
1397 	next_event = min_t(u64, next_event,
1398 			   hrtimer_next_event_without(&ts->sched_timer));
1399 
1400 	return ktime_sub(next_event, now);
1401 }
1402 
1403 /**
1404  * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
1405  * for a particular CPU.
1406  * @cpu: target CPU number
1407  *
1408  * Called from the schedutil frequency scaling governor in scheduler context.
1409  *
1410  * Return: the current idle calls counter value for @cpu
1411  */
1412 unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
1413 {
1414 	struct tick_sched *ts = tick_get_tick_sched(cpu);
1415 
1416 	return ts->idle_calls;
1417 }
1418 
1419 static void tick_nohz_account_idle_time(struct tick_sched *ts,
1420 					ktime_t now)
1421 {
1422 	unsigned long ticks;
1423 
1424 	ts->idle_exittime = now;
1425 
1426 	if (vtime_accounting_enabled_this_cpu())
1427 		return;
1428 	/*
1429 	 * We stopped the tick in idle. update_process_times() would miss the
1430 	 * time we slept, as it does only a 1 tick accounting.
1431 	 * Enforce that this is accounted to idle !
1432 	 */
1433 	ticks = jiffies - ts->idle_jiffies;
1434 	/*
1435 	 * We might be one off. Do not randomly account a huge number of ticks!
1436 	 */
1437 	if (ticks && ticks < LONG_MAX)
1438 		account_idle_ticks(ticks);
1439 }
1440 
1441 void tick_nohz_idle_restart_tick(void)
1442 {
1443 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1444 
1445 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
1446 		ktime_t now = ktime_get();
1447 		tick_nohz_restart_sched_tick(ts, now);
1448 		tick_nohz_account_idle_time(ts, now);
1449 	}
1450 }
1451 
1452 static void tick_nohz_idle_update_tick(struct tick_sched *ts, ktime_t now)
1453 {
1454 	if (tick_nohz_full_cpu(smp_processor_id()))
1455 		__tick_nohz_full_update_tick(ts, now);
1456 	else
1457 		tick_nohz_restart_sched_tick(ts, now);
1458 
1459 	tick_nohz_account_idle_time(ts, now);
1460 }
1461 
1462 /**
1463  * tick_nohz_idle_exit - Update the tick upon idle task exit
1464  *
1465  * When the idle task exits, update the tick depending on the
1466  * following situations:
1467  *
1468  * 1) If the CPU is not in nohz_full mode (most cases), then
1469  *    restart the tick.
1470  *
1471  * 2) If the CPU is in nohz_full mode (corner case):
1472  *   2.1) If the tick can be kept stopped (no tick dependencies)
1473  *        then re-evaluate the next tick and try to keep it stopped
1474  *        as long as possible.
1475  *   2.2) If the tick has dependencies, restart the tick.
1476  *
1477  */
1478 void tick_nohz_idle_exit(void)
1479 {
1480 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1481 	bool idle_active, tick_stopped;
1482 	ktime_t now;
1483 
1484 	local_irq_disable();
1485 
1486 	WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
1487 	WARN_ON_ONCE(ts->timer_expires_base);
1488 
1489 	tick_sched_flag_clear(ts, TS_FLAG_INIDLE);
1490 	idle_active = tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE);
1491 	tick_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
1492 
1493 	if (idle_active || tick_stopped)
1494 		now = ktime_get();
1495 
1496 	if (idle_active)
1497 		tick_nohz_stop_idle(ts, now);
1498 
1499 	if (tick_stopped)
1500 		tick_nohz_idle_update_tick(ts, now);
1501 
1502 	local_irq_enable();
1503 }
1504 
1505 /*
1506  * In low-resolution mode, the tick handler must be implemented directly
1507  * at the clockevent level. hrtimer can't be used instead, because its
1508  * infrastructure actually relies on the tick itself as a backend in
1509  * low-resolution mode (see hrtimer_run_queues()).
1510  */
1511 static void tick_nohz_lowres_handler(struct clock_event_device *dev)
1512 {
1513 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1514 
1515 	dev->next_event = KTIME_MAX;
1516 
1517 	if (likely(tick_nohz_handler(&ts->sched_timer) == HRTIMER_RESTART))
1518 		tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1519 }
1520 
1521 static inline void tick_nohz_activate(struct tick_sched *ts)
1522 {
1523 	if (!tick_nohz_enabled)
1524 		return;
1525 	tick_sched_flag_set(ts, TS_FLAG_NOHZ);
1526 	/* One update is enough */
1527 	if (!test_and_set_bit(0, &tick_nohz_active))
1528 		timers_update_nohz();
1529 }
1530 
1531 /**
1532  * tick_nohz_switch_to_nohz - switch to NOHZ mode
1533  */
1534 static void tick_nohz_switch_to_nohz(void)
1535 {
1536 	if (!tick_nohz_enabled)
1537 		return;
1538 
1539 	if (tick_switch_to_oneshot(tick_nohz_lowres_handler))
1540 		return;
1541 
1542 	/*
1543 	 * Recycle the hrtimer in 'ts', so we can share the
1544 	 * highres code.
1545 	 */
1546 	tick_setup_sched_timer(false);
1547 }
1548 
1549 static inline void tick_nohz_irq_enter(void)
1550 {
1551 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1552 	ktime_t now;
1553 
1554 	if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED | TS_FLAG_IDLE_ACTIVE))
1555 		return;
1556 	now = ktime_get();
1557 	if (tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE))
1558 		tick_nohz_stop_idle(ts, now);
1559 	/*
1560 	 * If all CPUs are idle we may need to update a stale jiffies value.
1561 	 * Note nohz_full is a special case: a timekeeper is guaranteed to stay
1562 	 * alive but it might be busy looping with interrupts disabled in some
1563 	 * rare case (typically stop machine). So we must make sure we have a
1564 	 * last resort.
1565 	 */
1566 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
1567 		tick_nohz_update_jiffies(now);
1568 }
1569 
1570 #else
1571 
1572 static inline void tick_nohz_switch_to_nohz(void) { }
1573 static inline void tick_nohz_irq_enter(void) { }
1574 static inline void tick_nohz_activate(struct tick_sched *ts) { }
1575 
1576 #endif /* CONFIG_NO_HZ_COMMON */
1577 
1578 /*
1579  * Called from irq_enter() to notify about the possible interruption of idle()
1580  */
1581 void tick_irq_enter(void)
1582 {
1583 	tick_check_oneshot_broadcast_this_cpu();
1584 	tick_nohz_irq_enter();
1585 }
1586 
1587 static int sched_skew_tick;
1588 
1589 static int __init skew_tick(char *str)
1590 {
1591 	get_option(&str, &sched_skew_tick);
1592 
1593 	return 0;
1594 }
1595 early_param("skew_tick", skew_tick);
1596 
1597 /**
1598  * tick_setup_sched_timer - setup the tick emulation timer
1599  * @hrtimer: whether to use the hrtimer or not
1600  */
1601 void tick_setup_sched_timer(bool hrtimer)
1602 {
1603 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1604 
1605 	/* Emulate tick processing via per-CPU hrtimers: */
1606 	hrtimer_setup(&ts->sched_timer, tick_nohz_handler, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
1607 
1608 	if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer)
1609 		tick_sched_flag_set(ts, TS_FLAG_HIGHRES);
1610 
1611 	/* Get the next period (per-CPU) */
1612 	hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
1613 
1614 	/* Offset the tick to avert 'jiffies_lock' contention. */
1615 	if (sched_skew_tick) {
1616 		u64 offset = TICK_NSEC >> 1;
1617 		do_div(offset, num_possible_cpus());
1618 		offset *= smp_processor_id();
1619 		hrtimer_add_expires_ns(&ts->sched_timer, offset);
1620 	}
1621 
1622 	hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
1623 	if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer)
1624 		hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
1625 	else
1626 		tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
1627 	tick_nohz_activate(ts);
1628 }
1629 
1630 /*
1631  * Shut down the tick and make sure the CPU won't try to retake the timekeeping
1632  * duty before disabling IRQs in idle for the last time.
1633  */
1634 void tick_sched_timer_dying(int cpu)
1635 {
1636 	struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
1637 	ktime_t idle_sleeptime, iowait_sleeptime;
1638 	unsigned long idle_calls, idle_sleeps;
1639 
1640 	/* This must happen before hrtimers are migrated! */
1641 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES))
1642 		hrtimer_cancel(&ts->sched_timer);
1643 
1644 	idle_sleeptime = ts->idle_sleeptime;
1645 	iowait_sleeptime = ts->iowait_sleeptime;
1646 	idle_calls = ts->idle_calls;
1647 	idle_sleeps = ts->idle_sleeps;
1648 	memset(ts, 0, sizeof(*ts));
1649 	ts->idle_sleeptime = idle_sleeptime;
1650 	ts->iowait_sleeptime = iowait_sleeptime;
1651 	ts->idle_calls = idle_calls;
1652 	ts->idle_sleeps = idle_sleeps;
1653 }
1654 
1655 /*
1656  * Async notification about clocksource changes
1657  */
1658 void tick_clock_notify(void)
1659 {
1660 	int cpu;
1661 
1662 	for_each_possible_cpu(cpu)
1663 		set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
1664 }
1665 
1666 /*
1667  * Async notification about clock event changes
1668  */
1669 void tick_oneshot_notify(void)
1670 {
1671 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1672 
1673 	set_bit(0, &ts->check_clocks);
1674 }
1675 
1676 /*
1677  * Check if a change happened, which makes oneshot possible.
1678  *
1679  * Called cyclically from the hrtimer softirq (driven by the timer
1680  * softirq). 'allow_nohz' signals that we can switch into low-res NOHZ
1681  * mode, because high resolution timers are disabled (either compile
1682  * or runtime). Called with interrupts disabled.
1683  */
1684 int tick_check_oneshot_change(int allow_nohz)
1685 {
1686 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
1687 
1688 	if (!test_and_clear_bit(0, &ts->check_clocks))
1689 		return 0;
1690 
1691 	if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
1692 		return 0;
1693 
1694 	if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
1695 		return 0;
1696 
1697 	if (!allow_nohz)
1698 		return 1;
1699 
1700 	tick_nohz_switch_to_nohz();
1701 	return 0;
1702 }
1703